exec_outcome stringclasses 1 value | code_uid stringlengths 32 32 | file_name stringclasses 111 values | prob_desc_created_at stringlengths 10 10 | prob_desc_description stringlengths 63 3.8k | prob_desc_memory_limit stringclasses 18 values | source_code stringlengths 117 65.5k | lang_cluster stringclasses 1 value | prob_desc_sample_inputs stringlengths 2 802 | prob_desc_time_limit stringclasses 27 values | prob_desc_sample_outputs stringlengths 2 796 | prob_desc_notes stringlengths 4 3k β | lang stringclasses 5 values | prob_desc_input_from stringclasses 3 values | tags listlengths 0 11 | src_uid stringlengths 32 32 | prob_desc_input_spec stringlengths 28 2.37k β | difficulty int64 -1 3.5k β | prob_desc_output_spec stringlengths 17 1.47k β | prob_desc_output_to stringclasses 3 values | hidden_unit_tests stringclasses 1 value |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
PASSED | 5ec7c43382ea778dc44b9482b3c1cb3e | train_003.jsonl | 1362065400 | The circle line of the Berland subway has n stations. We know the distances between all pairs of neighboring stations: d1 is the distance between the 1-st and the 2-nd station; d2 is the distance between the 2-nd and the 3-rd station;... dnβ-β1 is the distance between the nβ-β1-th and the n-th station; dn is the distance between the n-th and the 1-st station.The trains go along the circle line in both directions. Find the shortest distance between stations with numbers s and t. | 256 megabytes | import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.StringTokenizer;
public class A implements CodeforcesSolver {
private int n;
private int[] as;
public void solve(InputStream is) {
FastScanner in = new FastScanner(is);
n = in.nextInt();
as = new int[n];
for(int i : ZeroTo.get(n))
as[i] = in.nextInt();
int p1 = in.nextInt()-1;
int p2 = in.nextInt()-1;
System.out.println(Math.min(toright(p2,p1), toright(p1, p2)));
}
private int toright(int p1, int p2) {
int r = 0;
for(int i : ZeroTo.get((p2-p1+n) % n))
r += as[(p1 + i)%n];
return r;
}
public static void main(String[] args) throws Exception {
CodeforcesSolverLauncher.launch(new CodeforcesSolverFactory() {
public CodeforcesSolver create() {
return new A();
}
}, "A1.txt", "A2.txt");
}
}
interface CodeforcesSolver {
void solve(InputStream is);
}
interface CodeforcesSolverFactory {
CodeforcesSolver create();
}
class CodeforcesSolverLauncher {
public static void launch(CodeforcesSolverFactory factory, String... inputFilePath) throws FileNotFoundException, IOException {
if(System.getProperty("ONLINE_JUDGE", "false").equals("true")) {
factory.create().solve(System.in);
} else {
for(String path : inputFilePath) {
FileInputStream is = new FileInputStream(new File(path));
factory.create().solve(is);
is.close();
System.out.println();
}
}
}
}
class FastScanner {
private StringTokenizer tokenizer;
public FastScanner(InputStream is) {
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream(1024*1024);
byte[] buf = new byte[1024*1024];
while(true) {
int read = is.read(buf);
if(read == -1)
break;
bos.write(buf, 0, read);
}
tokenizer = new StringTokenizer(new String(bos.toByteArray()));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public int nextInt() {
return Integer.parseInt(tokenizer.nextToken());
}
public long nextLong() {
return Long.parseLong(tokenizer.nextToken());
}
public double nextDouble() {
return Double.parseDouble(tokenizer.nextToken());
}
public String next() {
return tokenizer.nextToken();
}
}
class ZeroTo {
public static Iterable<Integer> get(int end) {
return IntSequenceIterable.create(0, 1, end);
}
}
class IntSequenceIterable {
public static Iterable<Integer> create(final int from, final int step, final int size) {
return new Iterable<Integer>() {
public Iterator<Integer> iterator() {
return new ReadOnlyIterator<Integer>() {
int nextIndex = 0;
public boolean hasNext() {
return nextIndex < size;
}
public Integer next() {
return from + step * (nextIndex++);
}
};
}
};
}
private IntSequenceIterable() {
}
}
abstract class ReadOnlyIterator<T> implements Iterator<T> {
public final void remove() {
throw new UnsupportedOperationException();
}
}
| Java | ["4\n2 3 4 9\n1 3", "4\n5 8 2 100\n4 1", "3\n1 1 1\n3 1", "3\n31 41 59\n1 1"] | 2 seconds | ["5", "15", "1", "0"] | NoteIn the first sample the length of path 1βββ2βββ3 equals 5, the length of path 1βββ4βββ3 equals 13.In the second sample the length of path 4βββ1 is 100, the length of path 4βββ3βββ2βββ1 is 15.In the third sample the length of path 3βββ1 is 1, the length of path 3βββ2βββ1 is 2.In the fourth sample the numbers of stations are the same, so the shortest distance equals 0. | Java 7 | standard input | [
"implementation"
] | 22ef37041ebbd8266f62ab932f188b31 | The first line contains integer n (3ββ€βnββ€β100) β the number of stations on the circle line. The second line contains n integers d1,βd2,β...,βdn (1ββ€βdiββ€β100) β the distances between pairs of neighboring stations. The third line contains two integers s and t (1ββ€βs,βtββ€βn) β the numbers of stations, between which you need to find the shortest distance. These numbers can be the same. The numbers in the lines are separated by single spaces. | 800 | Print a single number β the length of the shortest path between stations number s and t. | standard output | |
PASSED | 3c1917138c926208f0a74a34cdbe7ae7 | train_003.jsonl | 1362065400 | The circle line of the Berland subway has n stations. We know the distances between all pairs of neighboring stations: d1 is the distance between the 1-st and the 2-nd station; d2 is the distance between the 2-nd and the 3-rd station;... dnβ-β1 is the distance between the nβ-β1-th and the n-th station; dn is the distance between the n-th and the 1-st station.The trains go along the circle line in both directions. Find the shortest distance between stations with numbers s and t. | 256 megabytes | import java.io.IOException;
import java.util.Scanner;
/**
*
* @author Oreste
*/
public class Main{
static int[][] arr;
public static int Distancia(int N1,int N2,int NA){
return Math.min(arr[N1][N2], arr[N1][NA]+arr[NA][N2]);
}
public static void main(String[] args) throws IOException {
Scanner entrada=new Scanner(System.in);
int Nodos=entrada.nextInt();
arr=new int[Nodos][Nodos];
for(int i=0;i<Nodos;i++){
for(int j=0;j<Nodos;j++){
if(j!=i)arr[i][j]=100000;
}
}
for(int i=0;i<Nodos;i++){
int p=entrada.nextInt();
int x=i,y=i+1;
if(y==Nodos)y=0;
arr[x][y]=arr[y][x]=p;
}
int NI=entrada.nextInt()-1;
int NF=entrada.nextInt()-1;
for(int k=0;k<Nodos;k++)
for(int i=0;i<Nodos;i++){
for(int j=0;j<Nodos;j++){
int p=Distancia(i, j, k);
arr[i][j]=p;
}
}
System.out.println(arr[NI][NF]);
}
}
| Java | ["4\n2 3 4 9\n1 3", "4\n5 8 2 100\n4 1", "3\n1 1 1\n3 1", "3\n31 41 59\n1 1"] | 2 seconds | ["5", "15", "1", "0"] | NoteIn the first sample the length of path 1βββ2βββ3 equals 5, the length of path 1βββ4βββ3 equals 13.In the second sample the length of path 4βββ1 is 100, the length of path 4βββ3βββ2βββ1 is 15.In the third sample the length of path 3βββ1 is 1, the length of path 3βββ2βββ1 is 2.In the fourth sample the numbers of stations are the same, so the shortest distance equals 0. | Java 7 | standard input | [
"implementation"
] | 22ef37041ebbd8266f62ab932f188b31 | The first line contains integer n (3ββ€βnββ€β100) β the number of stations on the circle line. The second line contains n integers d1,βd2,β...,βdn (1ββ€βdiββ€β100) β the distances between pairs of neighboring stations. The third line contains two integers s and t (1ββ€βs,βtββ€βn) β the numbers of stations, between which you need to find the shortest distance. These numbers can be the same. The numbers in the lines are separated by single spaces. | 800 | Print a single number β the length of the shortest path between stations number s and t. | standard output | |
PASSED | 77e36b8dcce15c3f706ff32e6ec60534 | train_003.jsonl | 1362065400 | The circle line of the Berland subway has n stations. We know the distances between all pairs of neighboring stations: d1 is the distance between the 1-st and the 2-nd station; d2 is the distance between the 2-nd and the 3-rd station;... dnβ-β1 is the distance between the nβ-β1-th and the n-th station; dn is the distance between the n-th and the 1-st station.The trains go along the circle line in both directions. Find the shortest distance between stations with numbers s and t. | 256 megabytes | import java.util.Scanner;
public class cf278a {
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int d[] = new int[2 * n + 1];
for (int i = 1; i <= n; i++) {
d[i] = in.nextInt();
}
for (int i = n + 1; i <= (2 * n); i++) {
d[i] = d[i - n];
}
int s = in.nextInt();
int t = in.nextInt();
int dis1 = 0;
int dis2 = 0;
int dis3 = 0;
if (s < t) {
for (int i = s; i < t; i++) {
dis1 += d[i];
}
for (int j = t; j <= n + s - 1; j++) {
dis2 += d[j];
}
if (dis1 < dis2)
dis3 = dis1;
else
dis3 = dis2;
}
else if (s > t) {
for (int i = s - 1; i >= t; i--)
dis1 += d[i];
for (int i = s; i <= n + t - 1; i++)
dis2 += d[i];
if (dis1 < dis2)
dis3 = dis1;
else
dis3 = dis2;
}
System.out.println(dis3);
}
}
| Java | ["4\n2 3 4 9\n1 3", "4\n5 8 2 100\n4 1", "3\n1 1 1\n3 1", "3\n31 41 59\n1 1"] | 2 seconds | ["5", "15", "1", "0"] | NoteIn the first sample the length of path 1βββ2βββ3 equals 5, the length of path 1βββ4βββ3 equals 13.In the second sample the length of path 4βββ1 is 100, the length of path 4βββ3βββ2βββ1 is 15.In the third sample the length of path 3βββ1 is 1, the length of path 3βββ2βββ1 is 2.In the fourth sample the numbers of stations are the same, so the shortest distance equals 0. | Java 7 | standard input | [
"implementation"
] | 22ef37041ebbd8266f62ab932f188b31 | The first line contains integer n (3ββ€βnββ€β100) β the number of stations on the circle line. The second line contains n integers d1,βd2,β...,βdn (1ββ€βdiββ€β100) β the distances between pairs of neighboring stations. The third line contains two integers s and t (1ββ€βs,βtββ€βn) β the numbers of stations, between which you need to find the shortest distance. These numbers can be the same. The numbers in the lines are separated by single spaces. | 800 | Print a single number β the length of the shortest path between stations number s and t. | standard output | |
PASSED | d01252005de33261ca7bd78f8983f628 | train_003.jsonl | 1362065400 | The circle line of the Berland subway has n stations. We know the distances between all pairs of neighboring stations: d1 is the distance between the 1-st and the 2-nd station; d2 is the distance between the 2-nd and the 3-rd station;... dnβ-β1 is the distance between the nβ-β1-th and the n-th station; dn is the distance between the n-th and the 1-st station.The trains go along the circle line in both directions. Find the shortest distance between stations with numbers s and t. | 256 megabytes | import java.util.Scanner;
public class azin
{
public static void main (String [] args)
{
Scanner scan = new Scanner (System.in);
int res = 0,s,t ;
int n1 = scan.nextInt();
int [] table = new int [n1];
for (int i=0;i<n1;i++)
table[i]=scan.nextInt();
s=scan.nextInt();
t=scan.nextInt();
int m=0,tmp=0;
for (int j=s;j<t;j++)
m +=table[j-1];
for (int j=t;j<s;j++)
m +=table[j-1];
for (int i=0;i<n1;i++)
tmp+=table[i];
if (tmp-m<=m)
res=tmp-m;
else
res=m;
System.out.println(res);
}
}
| Java | ["4\n2 3 4 9\n1 3", "4\n5 8 2 100\n4 1", "3\n1 1 1\n3 1", "3\n31 41 59\n1 1"] | 2 seconds | ["5", "15", "1", "0"] | NoteIn the first sample the length of path 1βββ2βββ3 equals 5, the length of path 1βββ4βββ3 equals 13.In the second sample the length of path 4βββ1 is 100, the length of path 4βββ3βββ2βββ1 is 15.In the third sample the length of path 3βββ1 is 1, the length of path 3βββ2βββ1 is 2.In the fourth sample the numbers of stations are the same, so the shortest distance equals 0. | Java 7 | standard input | [
"implementation"
] | 22ef37041ebbd8266f62ab932f188b31 | The first line contains integer n (3ββ€βnββ€β100) β the number of stations on the circle line. The second line contains n integers d1,βd2,β...,βdn (1ββ€βdiββ€β100) β the distances between pairs of neighboring stations. The third line contains two integers s and t (1ββ€βs,βtββ€βn) β the numbers of stations, between which you need to find the shortest distance. These numbers can be the same. The numbers in the lines are separated by single spaces. | 800 | Print a single number β the length of the shortest path between stations number s and t. | standard output | |
PASSED | b9f530e8fa4624827cc742de6f1223a4 | train_003.jsonl | 1362065400 | The circle line of the Berland subway has n stations. We know the distances between all pairs of neighboring stations: d1 is the distance between the 1-st and the 2-nd station; d2 is the distance between the 2-nd and the 3-rd station;... dnβ-β1 is the distance between the nβ-β1-th and the n-th station; dn is the distance between the n-th and the 1-st station.The trains go along the circle line in both directions. Find the shortest distance between stations with numbers s and t. | 256 megabytes | import java.util.*;
public class Main {
public static void main(String... args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] t = new int[n+1];
for (int i=1; i<=n; i++){
t[i]=sc.nextInt();
}
int a = sc.nextInt();
int b = sc.nextInt();
if (a>b){int c = a; a=b; b=c;}
int t0 = 0;
int t1 = 0;
for (int i=0; i<=n; i++){
if (i>=a && i<b){t0+=t[i];}else{t1+=t[i];}
}
System.out.println(Math.min(t0,t1));
}
} | Java | ["4\n2 3 4 9\n1 3", "4\n5 8 2 100\n4 1", "3\n1 1 1\n3 1", "3\n31 41 59\n1 1"] | 2 seconds | ["5", "15", "1", "0"] | NoteIn the first sample the length of path 1βββ2βββ3 equals 5, the length of path 1βββ4βββ3 equals 13.In the second sample the length of path 4βββ1 is 100, the length of path 4βββ3βββ2βββ1 is 15.In the third sample the length of path 3βββ1 is 1, the length of path 3βββ2βββ1 is 2.In the fourth sample the numbers of stations are the same, so the shortest distance equals 0. | Java 7 | standard input | [
"implementation"
] | 22ef37041ebbd8266f62ab932f188b31 | The first line contains integer n (3ββ€βnββ€β100) β the number of stations on the circle line. The second line contains n integers d1,βd2,β...,βdn (1ββ€βdiββ€β100) β the distances between pairs of neighboring stations. The third line contains two integers s and t (1ββ€βs,βtββ€βn) β the numbers of stations, between which you need to find the shortest distance. These numbers can be the same. The numbers in the lines are separated by single spaces. | 800 | Print a single number β the length of the shortest path between stations number s and t. | standard output | |
PASSED | 8dcf0d550e953fb324603d6f1e7c07e3 | train_003.jsonl | 1362065400 | The circle line of the Berland subway has n stations. We know the distances between all pairs of neighboring stations: d1 is the distance between the 1-st and the 2-nd station; d2 is the distance between the 2-nd and the 3-rd station;... dnβ-β1 is the distance between the nβ-β1-th and the n-th station; dn is the distance between the n-th and the 1-st station.The trains go along the circle line in both directions. Find the shortest distance between stations with numbers s and t. | 256 megabytes | import java.util.Random;
import java.util.*;
import java.util.Scanner;
public class Main {
public static String binary = "";
//System.out.println(ans);
public static int gcd(int a,int b){
if(a == 0)
return b;
return gcd(b % a, a);
}
private static void Binaryform(int number) {
int remainder;
if (number <= 1) {
binary += number;
return;
}
remainder = number %2;
Binaryform(number >> 1);
binary += remainder +"";
}
public static void print(Object o){
System.out.print(o +" ");
}
public static void println(Object o){
System.out.println(o);
}
public static class Point{
public int x = 0;
public int y = 0;
Point (int x , int y){
this.x = x;
this.y = y;
}
}
public static int isSquare(Point p1, Point p2,Point p3,Point p4){
double dx = 0, dy = 0;
double dd [] = new double [6];
Point [] pp = new Point[4];
pp[0]=p1; pp[1]=p2; pp[2]=p3; pp[3]=p4;
int ii = 0; int jj = 0; int kk = 0; int nn = 0;
for(ii = 0; ii < 3; ii++){
for(jj = ii + 1; jj < 4; jj++){
dx = pp[ii].x - pp[jj].x;
dy = pp[ii].y - pp[jj].y;
dd[kk] = dx*dx + dy*dy;
if(dd[kk] == 0) return 0;
if(kk > 1){
for(nn = 0; nn < kk - 1; nn++){
if (!( (2*dd[nn] == dd[kk] ) || (dd[nn] == dd[kk]) || (2*dd[kk] == dd[nn] )) )
return 0;
}
}
kk += 1;
}
}
return 1;
}
/*
4
2 3 4 9
1 3
*/
public static void main(String arg[]){
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int v [] = new int [n];
for(int i = 0; i < n; i++){
v[i] = scan.nextInt();
}
int s = scan.nextInt();
int t = scan.nextInt();
s -= 1; t -= 1;
int ans = 1<<30; int suma = 0;
//System.out.println(s +" "+t);
for(int i = s; i%n != t; i++){
suma += v[i%n];
}
//System.out.println("suma:"+suma);
ans = Math.min(ans,suma);
suma = 0;
for(int i = t; Math.abs(i%n)!= s; i++){
suma += v[i%n];
}
//System.out.println("suma:"+suma);
ans = Math.min(ans,suma);
System.out.println(ans);
}
}
| Java | ["4\n2 3 4 9\n1 3", "4\n5 8 2 100\n4 1", "3\n1 1 1\n3 1", "3\n31 41 59\n1 1"] | 2 seconds | ["5", "15", "1", "0"] | NoteIn the first sample the length of path 1βββ2βββ3 equals 5, the length of path 1βββ4βββ3 equals 13.In the second sample the length of path 4βββ1 is 100, the length of path 4βββ3βββ2βββ1 is 15.In the third sample the length of path 3βββ1 is 1, the length of path 3βββ2βββ1 is 2.In the fourth sample the numbers of stations are the same, so the shortest distance equals 0. | Java 7 | standard input | [
"implementation"
] | 22ef37041ebbd8266f62ab932f188b31 | The first line contains integer n (3ββ€βnββ€β100) β the number of stations on the circle line. The second line contains n integers d1,βd2,β...,βdn (1ββ€βdiββ€β100) β the distances between pairs of neighboring stations. The third line contains two integers s and t (1ββ€βs,βtββ€βn) β the numbers of stations, between which you need to find the shortest distance. These numbers can be the same. The numbers in the lines are separated by single spaces. | 800 | Print a single number β the length of the shortest path between stations number s and t. | standard output | |
PASSED | cc0d842049f7133692d7a4539b9b83ff | train_003.jsonl | 1362065400 | The circle line of the Berland subway has n stations. We know the distances between all pairs of neighboring stations: d1 is the distance between the 1-st and the 2-nd station; d2 is the distance between the 2-nd and the 3-rd station;... dnβ-β1 is the distance between the nβ-β1-th and the n-th station; dn is the distance between the n-th and the 1-st station.The trains go along the circle line in both directions. Find the shortest distance between stations with numbers s and t. | 256 megabytes |
import java.util.Scanner;
public class A278 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int N = input.nextInt();
int[] A = new int[2*N];
for (int n=0; n<N; n++) {
int value = input.nextInt();
A[n] = value;
A[n+N] = value;
}
int s = input.nextInt()-1;
int t = input.nextInt()-1;
if (s > t) {
int temp = t;
t = s;
s = temp;
}
int dist1 = 0;
for (int n=s; n<t; n++) {
dist1 += A[n];
}
int dist2 = 0;
for (int n=t; n<N+s; n++) {
dist2 += A[n];
}
System.out.println(Math.min(dist1, dist2));
}
}
| Java | ["4\n2 3 4 9\n1 3", "4\n5 8 2 100\n4 1", "3\n1 1 1\n3 1", "3\n31 41 59\n1 1"] | 2 seconds | ["5", "15", "1", "0"] | NoteIn the first sample the length of path 1βββ2βββ3 equals 5, the length of path 1βββ4βββ3 equals 13.In the second sample the length of path 4βββ1 is 100, the length of path 4βββ3βββ2βββ1 is 15.In the third sample the length of path 3βββ1 is 1, the length of path 3βββ2βββ1 is 2.In the fourth sample the numbers of stations are the same, so the shortest distance equals 0. | Java 7 | standard input | [
"implementation"
] | 22ef37041ebbd8266f62ab932f188b31 | The first line contains integer n (3ββ€βnββ€β100) β the number of stations on the circle line. The second line contains n integers d1,βd2,β...,βdn (1ββ€βdiββ€β100) β the distances between pairs of neighboring stations. The third line contains two integers s and t (1ββ€βs,βtββ€βn) β the numbers of stations, between which you need to find the shortest distance. These numbers can be the same. The numbers in the lines are separated by single spaces. | 800 | Print a single number β the length of the shortest path between stations number s and t. | standard output | |
PASSED | 30ccd04084b9d748d433828d6cfdef4b | train_003.jsonl | 1362065400 | The circle line of the Berland subway has n stations. We know the distances between all pairs of neighboring stations: d1 is the distance between the 1-st and the 2-nd station; d2 is the distance between the 2-nd and the 3-rd station;... dnβ-β1 is the distance between the nβ-β1-th and the n-th station; dn is the distance between the n-th and the 1-st station.The trains go along the circle line in both directions. Find the shortest distance between stations with numbers s and t. | 256 megabytes | /**
*
* @author Faruk
*/
import java.util.Arrays;
import java.util.Scanner;
import java.util.HashSet;
import java.util.HashMap;
import java.util.ArrayList;
public class tmp {
public static void main(String [] args){
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int [] d = new int[n+2];
int tot = 0;
for(int i=1; i<=n; i++)
d[i+1] = scan.nextInt() +d[i];
tot = d[n+1];
int s = scan.nextInt();
int t = scan.nextInt();
int small = Math.min(s, t);
int big = Math.max(s, t);
int max = d[big] - d[small];
if(tot > 2*max)
System.out.println(max);
else
System.out.println(tot-max);
}
}
| Java | ["4\n2 3 4 9\n1 3", "4\n5 8 2 100\n4 1", "3\n1 1 1\n3 1", "3\n31 41 59\n1 1"] | 2 seconds | ["5", "15", "1", "0"] | NoteIn the first sample the length of path 1βββ2βββ3 equals 5, the length of path 1βββ4βββ3 equals 13.In the second sample the length of path 4βββ1 is 100, the length of path 4βββ3βββ2βββ1 is 15.In the third sample the length of path 3βββ1 is 1, the length of path 3βββ2βββ1 is 2.In the fourth sample the numbers of stations are the same, so the shortest distance equals 0. | Java 7 | standard input | [
"implementation"
] | 22ef37041ebbd8266f62ab932f188b31 | The first line contains integer n (3ββ€βnββ€β100) β the number of stations on the circle line. The second line contains n integers d1,βd2,β...,βdn (1ββ€βdiββ€β100) β the distances between pairs of neighboring stations. The third line contains two integers s and t (1ββ€βs,βtββ€βn) β the numbers of stations, between which you need to find the shortest distance. These numbers can be the same. The numbers in the lines are separated by single spaces. | 800 | Print a single number β the length of the shortest path between stations number s and t. | standard output | |
PASSED | 55249e213774f53028b8030932a1fe0a | train_003.jsonl | 1362065400 | The circle line of the Berland subway has n stations. We know the distances between all pairs of neighboring stations: d1 is the distance between the 1-st and the 2-nd station; d2 is the distance between the 2-nd and the 3-rd station;... dnβ-β1 is the distance between the nβ-β1-th and the n-th station; dn is the distance between the n-th and the 1-st station.The trains go along the circle line in both directions. Find the shortest distance between stations with numbers s and t. | 256 megabytes |
import java.util.Scanner;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author mehrdad
*/
public class Main {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int[] d=new int[n+1];
d[0]=0;
int sum1=0;
int sum2=0;
for(int i=1;i<=n;i++)
{
d[i]=sc.nextInt();
}
int s=sc.nextInt();
int e=sc.nextInt();
boolean noMove=false;
if(e==s)noMove=true;
else if(s<e)
{
for(int i=s;i<e;i++)
{
sum1+=d[i];
}
for(int i=1;i<s;i++)
{
sum2+=d[i];
}
for(int i=e;i<=n;i++)
{
sum2+=d[i];
}
}
else {
for(int i=e;i<s;i++)
{
sum1+=d[i];
}
for(int i=1;i<e;i++)
{
sum2+=d[i];
}
for(int i=s;i<=n;i++)
{
sum2+=d[i];
}
}
if(noMove)
System.out.print("0");
else if(sum1==sum2)
System.out.print(sum1);
else if(sum1<sum2)
System.out.print(sum1);
else if(sum1>sum2)
System.out.print(sum2);
}
}
| Java | ["4\n2 3 4 9\n1 3", "4\n5 8 2 100\n4 1", "3\n1 1 1\n3 1", "3\n31 41 59\n1 1"] | 2 seconds | ["5", "15", "1", "0"] | NoteIn the first sample the length of path 1βββ2βββ3 equals 5, the length of path 1βββ4βββ3 equals 13.In the second sample the length of path 4βββ1 is 100, the length of path 4βββ3βββ2βββ1 is 15.In the third sample the length of path 3βββ1 is 1, the length of path 3βββ2βββ1 is 2.In the fourth sample the numbers of stations are the same, so the shortest distance equals 0. | Java 7 | standard input | [
"implementation"
] | 22ef37041ebbd8266f62ab932f188b31 | The first line contains integer n (3ββ€βnββ€β100) β the number of stations on the circle line. The second line contains n integers d1,βd2,β...,βdn (1ββ€βdiββ€β100) β the distances between pairs of neighboring stations. The third line contains two integers s and t (1ββ€βs,βtββ€βn) β the numbers of stations, between which you need to find the shortest distance. These numbers can be the same. The numbers in the lines are separated by single spaces. | 800 | Print a single number β the length of the shortest path between stations number s and t. | standard output | |
PASSED | e93fade413717d12e1f5f177eac527c7 | train_003.jsonl | 1362065400 | The circle line of the Berland subway has n stations. We know the distances between all pairs of neighboring stations: d1 is the distance between the 1-st and the 2-nd station; d2 is the distance between the 2-nd and the 3-rd station;... dnβ-β1 is the distance between the nβ-β1-th and the n-th station; dn is the distance between the n-th and the 1-st station.The trains go along the circle line in both directions. Find the shortest distance between stations with numbers s and t. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOError;
import java.io.IOException;
import java.io.InputStreamReader;
public class CircleLine {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(
System.in));
int n = Integer.valueOf(reader.readLine());
int[] is = new int[n];
int index = 0;
for (String string : reader.readLine().split(" ")) {
is[index++] = Integer.valueOf(string);
}
String[] strings = reader.readLine().split(" ");
int x = Integer.valueOf(strings[0]);
int y = Integer.valueOf(strings[1]);
int sum1 = 0;
for (int i = Math.min(x, y); i < Math.max(x, y); i++) {
sum1 += is[i - 1];
}
int sum2 = 0;
if (y > x) {
for (int i = Math.min(x, y)-1; i > 0; i--) {
sum2 += is[i - 1];
}
for (int i = is.length - 1; i >= Math.max(x, y) - 1; i--) {
sum2 += is[i];
}
}
if (x > y) {
for (int i = Math.max(x, y); i <= is.length; i++) {
sum2 += is[i - 1];
}
for (int i = 0; i < Math.min(x, y) - 1; i++) {
sum2 += is[i];
}
}
System.out.println(Math.min(sum1, sum2));
}
} | Java | ["4\n2 3 4 9\n1 3", "4\n5 8 2 100\n4 1", "3\n1 1 1\n3 1", "3\n31 41 59\n1 1"] | 2 seconds | ["5", "15", "1", "0"] | NoteIn the first sample the length of path 1βββ2βββ3 equals 5, the length of path 1βββ4βββ3 equals 13.In the second sample the length of path 4βββ1 is 100, the length of path 4βββ3βββ2βββ1 is 15.In the third sample the length of path 3βββ1 is 1, the length of path 3βββ2βββ1 is 2.In the fourth sample the numbers of stations are the same, so the shortest distance equals 0. | Java 7 | standard input | [
"implementation"
] | 22ef37041ebbd8266f62ab932f188b31 | The first line contains integer n (3ββ€βnββ€β100) β the number of stations on the circle line. The second line contains n integers d1,βd2,β...,βdn (1ββ€βdiββ€β100) β the distances between pairs of neighboring stations. The third line contains two integers s and t (1ββ€βs,βtββ€βn) β the numbers of stations, between which you need to find the shortest distance. These numbers can be the same. The numbers in the lines are separated by single spaces. | 800 | Print a single number β the length of the shortest path between stations number s and t. | standard output | |
PASSED | 61db1ef09f8a5210e61d48c79c65e559 | train_003.jsonl | 1362065400 | The circle line of the Berland subway has n stations. We know the distances between all pairs of neighboring stations: d1 is the distance between the 1-st and the 2-nd station; d2 is the distance between the 2-nd and the 3-rd station;... dnβ-β1 is the distance between the nβ-β1-th and the n-th station; dn is the distance between the n-th and the 1-st station.The trains go along the circle line in both directions. Find the shortest distance between stations with numbers s and t. | 256 megabytes | import java.io.IOException;
import java.util.InputMismatchException;
public class CircleLine {
public static void main(String[] args) {
FasterScanner sc = new FasterScanner();
int N = sc.nextInt();
int[] D = sc.nextIntArray(N);
int S = sc.nextInt() - 1;
int T = sc.nextInt() - 1;
int d1 = 0;
for (int i = S; i != T; i = (i + 1) % N) {
d1 += D[i];
}
int d2 = 0;
for (int i = (S + N - 1) % N; i != (T + N - 1) % N; i = (i + N - 1) % N) {
d2 += D[i];
}
System.out.println(Math.min(d1, d2));
}
public static class FasterScanner {
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = System.in.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public String nextString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public long nextLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int nextInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n) {
return nextIntArray(n, 0);
}
public int[] nextIntArray(int n, int off) {
int[] arr = new int[n + off];
for (int i = 0; i < n; i++) {
arr[i + off] = nextInt();
}
return arr;
}
public long[] nextLongArray(int n) {
return nextLongArray(n, 0);
}
public long[] nextLongArray(int n, int off) {
long[] arr = new long[n + off];
for (int i = 0; i < n; i++) {
arr[i + off] = nextLong();
}
return arr;
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
}
} | Java | ["4\n2 3 4 9\n1 3", "4\n5 8 2 100\n4 1", "3\n1 1 1\n3 1", "3\n31 41 59\n1 1"] | 2 seconds | ["5", "15", "1", "0"] | NoteIn the first sample the length of path 1βββ2βββ3 equals 5, the length of path 1βββ4βββ3 equals 13.In the second sample the length of path 4βββ1 is 100, the length of path 4βββ3βββ2βββ1 is 15.In the third sample the length of path 3βββ1 is 1, the length of path 3βββ2βββ1 is 2.In the fourth sample the numbers of stations are the same, so the shortest distance equals 0. | Java 7 | standard input | [
"implementation"
] | 22ef37041ebbd8266f62ab932f188b31 | The first line contains integer n (3ββ€βnββ€β100) β the number of stations on the circle line. The second line contains n integers d1,βd2,β...,βdn (1ββ€βdiββ€β100) β the distances between pairs of neighboring stations. The third line contains two integers s and t (1ββ€βs,βtββ€βn) β the numbers of stations, between which you need to find the shortest distance. These numbers can be the same. The numbers in the lines are separated by single spaces. | 800 | Print a single number β the length of the shortest path between stations number s and t. | standard output | |
PASSED | f6e8bbda8be3e1bc65ad273282e6e4d0 | train_003.jsonl | 1362065400 | The circle line of the Berland subway has n stations. We know the distances between all pairs of neighboring stations: d1 is the distance between the 1-st and the 2-nd station; d2 is the distance between the 2-nd and the 3-rd station;... dnβ-β1 is the distance between the nβ-β1-th and the n-th station; dn is the distance between the n-th and the 1-st station.The trains go along the circle line in both directions. Find the shortest distance between stations with numbers s and t. | 256 megabytes | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
import java.util.*;
//import java.text.DecimalFormat;
/**
*
* @author emaK
*/
public class Main {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Scanner next;
next = new Scanner(System.in);
int x;
x=next.nextInt();
ArrayList<Integer> a=new ArrayList<Integer>();
for(int i=0;i<x;i++)
{
int y;
y=next.nextInt();
a.add(y);
}
int g,h;
g=next.nextInt();
h=next.nextInt();
g--;
h--;
if(g>h)
{
int s=0,w=0;
for(int i=h;i<g;i++)
{
s+=a.get(i);
}
for(int i=g;i<x;i++)
{
w+=a.get(i);
}
for(int i=0;i<h;i++)
{
w+=a.get(i);
}
if(s>=w)
System.out.println(w);
else
System.out.println(s);
}
else if(g<h)
{
int s=0,w=0;
for(int i=g;i<h;i++)
{
s+=a.get(i);
}
for(int i=h;i<x;i++)
{
w+=a.get(i);
}
for(int i=0;i<g;i++)
{
w+=a.get(i);
}
if(s>=w)
System.out.println(w);
else
System.out.println(s);
}
else
System.out.println("0");
}
}
/* for(float i=0;i<=2.1;i+=.2)
{
for(float j=1+i;j<=3+i;j++)
{
Scanner next;
next = new Scanner(System.in);
DecimalFormat df = new DecimalFormat("#.0");
float x=j+i;
System.out.println("I="+df.format(i)+" "+"J="+df.format(j));
}
}
*/
// TODO code application logic here
| Java | ["4\n2 3 4 9\n1 3", "4\n5 8 2 100\n4 1", "3\n1 1 1\n3 1", "3\n31 41 59\n1 1"] | 2 seconds | ["5", "15", "1", "0"] | NoteIn the first sample the length of path 1βββ2βββ3 equals 5, the length of path 1βββ4βββ3 equals 13.In the second sample the length of path 4βββ1 is 100, the length of path 4βββ3βββ2βββ1 is 15.In the third sample the length of path 3βββ1 is 1, the length of path 3βββ2βββ1 is 2.In the fourth sample the numbers of stations are the same, so the shortest distance equals 0. | Java 7 | standard input | [
"implementation"
] | 22ef37041ebbd8266f62ab932f188b31 | The first line contains integer n (3ββ€βnββ€β100) β the number of stations on the circle line. The second line contains n integers d1,βd2,β...,βdn (1ββ€βdiββ€β100) β the distances between pairs of neighboring stations. The third line contains two integers s and t (1ββ€βs,βtββ€βn) β the numbers of stations, between which you need to find the shortest distance. These numbers can be the same. The numbers in the lines are separated by single spaces. | 800 | Print a single number β the length of the shortest path between stations number s and t. | standard output | |
PASSED | 3d6a51d8542c93f3aeeb2844c8795fda | train_003.jsonl | 1362065400 | The circle line of the Berland subway has n stations. We know the distances between all pairs of neighboring stations: d1 is the distance between the 1-st and the 2-nd station; d2 is the distance between the 2-nd and the 3-rd station;... dnβ-β1 is the distance between the nβ-β1-th and the n-th station; dn is the distance between the n-th and the 1-st station.The trains go along the circle line in both directions. Find the shortest distance between stations with numbers s and t. | 256 megabytes |
import java.util.Scanner;
public class Practica_1 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int array[] = new int[n * 2];
for (int i = 0; i < n; i++) {
int d = in.nextInt();
array[i] = d;
array[i + n] = d;
}
int s = in.nextInt();
int t = in.nextInt();
int minimo = Math.min(s, t);
int maximo = Math.max(s, t);
int count_1 = 0;
for (int i = maximo - 1; i < n + minimo - 1; i++) {
count_1 += array[i];
}
int count_2 = 0;
for (int i = minimo - 1; i < maximo - 1; i++) {
count_2 += array[i];
}
System.out.println(Math.min(count_1, count_2));
}
}
| Java | ["4\n2 3 4 9\n1 3", "4\n5 8 2 100\n4 1", "3\n1 1 1\n3 1", "3\n31 41 59\n1 1"] | 2 seconds | ["5", "15", "1", "0"] | NoteIn the first sample the length of path 1βββ2βββ3 equals 5, the length of path 1βββ4βββ3 equals 13.In the second sample the length of path 4βββ1 is 100, the length of path 4βββ3βββ2βββ1 is 15.In the third sample the length of path 3βββ1 is 1, the length of path 3βββ2βββ1 is 2.In the fourth sample the numbers of stations are the same, so the shortest distance equals 0. | Java 7 | standard input | [
"implementation"
] | 22ef37041ebbd8266f62ab932f188b31 | The first line contains integer n (3ββ€βnββ€β100) β the number of stations on the circle line. The second line contains n integers d1,βd2,β...,βdn (1ββ€βdiββ€β100) β the distances between pairs of neighboring stations. The third line contains two integers s and t (1ββ€βs,βtββ€βn) β the numbers of stations, between which you need to find the shortest distance. These numbers can be the same. The numbers in the lines are separated by single spaces. | 800 | Print a single number β the length of the shortest path between stations number s and t. | standard output | |
PASSED | 878d6764a8830173163d7551de177958 | train_003.jsonl | 1362065400 | The circle line of the Berland subway has n stations. We know the distances between all pairs of neighboring stations: d1 is the distance between the 1-st and the 2-nd station; d2 is the distance between the 2-nd and the 3-rd station;... dnβ-β1 is the distance between the nβ-β1-th and the n-th station; dn is the distance between the n-th and the 1-st station.The trains go along the circle line in both directions. Find the shortest distance between stations with numbers s and t. | 256 megabytes | import java.util.*;
import java.io.*;
public class A {
static long[] room;
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = sc.nextInt();
int[] d = new int[n];
for(int i=0;i<n;i++) d[i] = sc.nextInt();
int s = sc.nextInt()-1;
int t = sc.nextInt()-1;
sc.close();
int cnt1=0,cnt2=0;
int max = Math.max(s,t);
int min = Math.min(s,t);
for(int i=min;i<max;i++){
cnt1+=d[i];
}
for(int i=max;i<d.length+min;i++){
cnt2+=d[i%d.length];
}
int res = Math.min(cnt1,cnt2);
out.println(res);
out.flush();
out.close();
}
} | Java | ["4\n2 3 4 9\n1 3", "4\n5 8 2 100\n4 1", "3\n1 1 1\n3 1", "3\n31 41 59\n1 1"] | 2 seconds | ["5", "15", "1", "0"] | NoteIn the first sample the length of path 1βββ2βββ3 equals 5, the length of path 1βββ4βββ3 equals 13.In the second sample the length of path 4βββ1 is 100, the length of path 4βββ3βββ2βββ1 is 15.In the third sample the length of path 3βββ1 is 1, the length of path 3βββ2βββ1 is 2.In the fourth sample the numbers of stations are the same, so the shortest distance equals 0. | Java 7 | standard input | [
"implementation"
] | 22ef37041ebbd8266f62ab932f188b31 | The first line contains integer n (3ββ€βnββ€β100) β the number of stations on the circle line. The second line contains n integers d1,βd2,β...,βdn (1ββ€βdiββ€β100) β the distances between pairs of neighboring stations. The third line contains two integers s and t (1ββ€βs,βtββ€βn) β the numbers of stations, between which you need to find the shortest distance. These numbers can be the same. The numbers in the lines are separated by single spaces. | 800 | Print a single number β the length of the shortest path between stations number s and t. | standard output | |
PASSED | 668641db51dde013e3cabfe1a5358f4d | train_003.jsonl | 1362065400 | The circle line of the Berland subway has n stations. We know the distances between all pairs of neighboring stations: d1 is the distance between the 1-st and the 2-nd station; d2 is the distance between the 2-nd and the 3-rd station;... dnβ-β1 is the distance between the nβ-β1-th and the n-th station; dn is the distance between the n-th and the 1-st station.The trains go along the circle line in both directions. Find the shortest distance between stations with numbers s and t. | 256 megabytes | import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int cost[] = new int[n];
for (int i = 0; i < n; i++) {
cost[i] = in.nextInt();
}
int s = in.nextInt();
int t = in.nextInt();
int start = Math.min(s, t);
int end = Math.max(s, t);
System.out.println(minDistance(cost, start, end));
in.close();
}
private static int minDistance(int[] cost, int start, int end) {
if (start == end)
return 0;
int way1 = 0;
int way2 = 0;
for (int i = start - 1; i < end - 1; i++) {
way1 += cost[i];
}
for (int i = end - 1; i < cost.length; i++) {
way2 += cost[i];
}
for (int i = 0; i < start - 1; i++) {
way2 += cost[i];
}
return Math.min(way1, way2);
}
}
| Java | ["4\n2 3 4 9\n1 3", "4\n5 8 2 100\n4 1", "3\n1 1 1\n3 1", "3\n31 41 59\n1 1"] | 2 seconds | ["5", "15", "1", "0"] | NoteIn the first sample the length of path 1βββ2βββ3 equals 5, the length of path 1βββ4βββ3 equals 13.In the second sample the length of path 4βββ1 is 100, the length of path 4βββ3βββ2βββ1 is 15.In the third sample the length of path 3βββ1 is 1, the length of path 3βββ2βββ1 is 2.In the fourth sample the numbers of stations are the same, so the shortest distance equals 0. | Java 7 | standard input | [
"implementation"
] | 22ef37041ebbd8266f62ab932f188b31 | The first line contains integer n (3ββ€βnββ€β100) β the number of stations on the circle line. The second line contains n integers d1,βd2,β...,βdn (1ββ€βdiββ€β100) β the distances between pairs of neighboring stations. The third line contains two integers s and t (1ββ€βs,βtββ€βn) β the numbers of stations, between which you need to find the shortest distance. These numbers can be the same. The numbers in the lines are separated by single spaces. | 800 | Print a single number β the length of the shortest path between stations number s and t. | standard output | |
PASSED | 3d0fcc73d5f4483d53bf62e6b8bc5f7b | train_003.jsonl | 1362065400 | The circle line of the Berland subway has n stations. We know the distances between all pairs of neighboring stations: d1 is the distance between the 1-st and the 2-nd station; d2 is the distance between the 2-nd and the 3-rd station;... dnβ-β1 is the distance between the nβ-β1-th and the n-th station; dn is the distance between the n-th and the 1-st station.The trains go along the circle line in both directions. Find the shortest distance between stations with numbers s and t. | 256 megabytes | import java.util.Scanner;
public class A {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int n = s.nextInt();
int[] d = new int[n];
int total = 0;
for (int i = 0; i < n; i++) {
d[i] = s.nextInt();
total += d[i];
}
int ss = s.nextInt();
int tt = s.nextInt();
int dist = calc(ss, tt, d);
System.out.println(Math.min(dist, total - dist));
}
static int calc(int s, int t, int[] d) {
if (s > t) {
return calc(t, s, d);
}
int ans = 0;
for (; s < t; s++) {
ans += d[s - 1];
}
return ans;
}
}
| Java | ["4\n2 3 4 9\n1 3", "4\n5 8 2 100\n4 1", "3\n1 1 1\n3 1", "3\n31 41 59\n1 1"] | 2 seconds | ["5", "15", "1", "0"] | NoteIn the first sample the length of path 1βββ2βββ3 equals 5, the length of path 1βββ4βββ3 equals 13.In the second sample the length of path 4βββ1 is 100, the length of path 4βββ3βββ2βββ1 is 15.In the third sample the length of path 3βββ1 is 1, the length of path 3βββ2βββ1 is 2.In the fourth sample the numbers of stations are the same, so the shortest distance equals 0. | Java 7 | standard input | [
"implementation"
] | 22ef37041ebbd8266f62ab932f188b31 | The first line contains integer n (3ββ€βnββ€β100) β the number of stations on the circle line. The second line contains n integers d1,βd2,β...,βdn (1ββ€βdiββ€β100) β the distances between pairs of neighboring stations. The third line contains two integers s and t (1ββ€βs,βtββ€βn) β the numbers of stations, between which you need to find the shortest distance. These numbers can be the same. The numbers in the lines are separated by single spaces. | 800 | Print a single number β the length of the shortest path between stations number s and t. | standard output | |
PASSED | 5b2adb1c84f0068e48cbe0052d67754a | train_003.jsonl | 1362065400 | The circle line of the Berland subway has n stations. We know the distances between all pairs of neighboring stations: d1 is the distance between the 1-st and the 2-nd station; d2 is the distance between the 2-nd and the 3-rd station;... dnβ-β1 is the distance between the nβ-β1-th and the n-th station; dn is the distance between the n-th and the 1-st station.The trains go along the circle line in both directions. Find the shortest distance between stations with numbers s and t. | 256 megabytes | import java.util.Scanner;
public class A {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int n = s.nextInt();
int[] d = new int[n + 1];
for (int i = 1; i <= n; i++) {
d[i] = d[i - 1] + s.nextInt();
}
int dist = Math.abs(d[s.nextInt() - 1] - d[s.nextInt() - 1]);
System.out.println(Math.min(dist, d[n] - dist));
}
}
| Java | ["4\n2 3 4 9\n1 3", "4\n5 8 2 100\n4 1", "3\n1 1 1\n3 1", "3\n31 41 59\n1 1"] | 2 seconds | ["5", "15", "1", "0"] | NoteIn the first sample the length of path 1βββ2βββ3 equals 5, the length of path 1βββ4βββ3 equals 13.In the second sample the length of path 4βββ1 is 100, the length of path 4βββ3βββ2βββ1 is 15.In the third sample the length of path 3βββ1 is 1, the length of path 3βββ2βββ1 is 2.In the fourth sample the numbers of stations are the same, so the shortest distance equals 0. | Java 7 | standard input | [
"implementation"
] | 22ef37041ebbd8266f62ab932f188b31 | The first line contains integer n (3ββ€βnββ€β100) β the number of stations on the circle line. The second line contains n integers d1,βd2,β...,βdn (1ββ€βdiββ€β100) β the distances between pairs of neighboring stations. The third line contains two integers s and t (1ββ€βs,βtββ€βn) β the numbers of stations, between which you need to find the shortest distance. These numbers can be the same. The numbers in the lines are separated by single spaces. | 800 | Print a single number β the length of the shortest path between stations number s and t. | standard output | |
PASSED | 27d686ffa2213461b3c1986ace81c0ef | train_003.jsonl | 1362065400 | The circle line of the Berland subway has n stations. We know the distances between all pairs of neighboring stations: d1 is the distance between the 1-st and the 2-nd station; d2 is the distance between the 2-nd and the 3-rd station;... dnβ-β1 is the distance between the nβ-β1-th and the n-th station; dn is the distance between the n-th and the 1-st station.The trains go along the circle line in both directions. Find the shortest distance between stations with numbers s and t. | 256 megabytes | import java.util.Scanner;
public class Line {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[] a = new int[n + 1];
a[0] = 0;
for (int i = 1; i <= n; i++) {
a[i] = a[i - 1] + in.nextInt();
}
int s = in.nextInt();
int t = in.nextInt();
int d = a[Math.max(s, t) - 1] - a[Math.min(s, t) - 1];
System.out.println(Math.min(d, a[n] - d));
}
}
| Java | ["4\n2 3 4 9\n1 3", "4\n5 8 2 100\n4 1", "3\n1 1 1\n3 1", "3\n31 41 59\n1 1"] | 2 seconds | ["5", "15", "1", "0"] | NoteIn the first sample the length of path 1βββ2βββ3 equals 5, the length of path 1βββ4βββ3 equals 13.In the second sample the length of path 4βββ1 is 100, the length of path 4βββ3βββ2βββ1 is 15.In the third sample the length of path 3βββ1 is 1, the length of path 3βββ2βββ1 is 2.In the fourth sample the numbers of stations are the same, so the shortest distance equals 0. | Java 7 | standard input | [
"implementation"
] | 22ef37041ebbd8266f62ab932f188b31 | The first line contains integer n (3ββ€βnββ€β100) β the number of stations on the circle line. The second line contains n integers d1,βd2,β...,βdn (1ββ€βdiββ€β100) β the distances between pairs of neighboring stations. The third line contains two integers s and t (1ββ€βs,βtββ€βn) β the numbers of stations, between which you need to find the shortest distance. These numbers can be the same. The numbers in the lines are separated by single spaces. | 800 | Print a single number β the length of the shortest path between stations number s and t. | standard output | |
PASSED | 82e3db4dad6eb4de884bd042b0514835 | train_003.jsonl | 1362065400 | The circle line of the Berland subway has n stations. We know the distances between all pairs of neighboring stations: d1 is the distance between the 1-st and the 2-nd station; d2 is the distance between the 2-nd and the 3-rd station;... dnβ-β1 is the distance between the nβ-β1-th and the n-th station; dn is the distance between the n-th and the 1-st station.The trains go along the circle line in both directions. Find the shortest distance between stations with numbers s and t. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main{
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader sc = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(sc.readLine());
int [] arr = new int[2 * n];
int i = 0;
for (String s : sc.readLine().split(" ") ) {
arr[i] = Integer.parseInt(s);
arr[n + i] = arr[i++];
}
String [] temp = sc.readLine().split(" ");
int s = Integer.parseInt(temp[0]) - 1, t = Integer.parseInt(temp[1]) - 1;
int fs = Math.min(s,t);
int ft = Math.max(s,t);
s = 0;
for (int r = fs; r < ft; ++r)
s += arr[r];
t = 0;
for (int r = ft; r < ft + n - (ft - fs); ++r)
t += arr[r];
System.out.println(Math.min(s,t));
}
} | Java | ["4\n2 3 4 9\n1 3", "4\n5 8 2 100\n4 1", "3\n1 1 1\n3 1", "3\n31 41 59\n1 1"] | 2 seconds | ["5", "15", "1", "0"] | NoteIn the first sample the length of path 1βββ2βββ3 equals 5, the length of path 1βββ4βββ3 equals 13.In the second sample the length of path 4βββ1 is 100, the length of path 4βββ3βββ2βββ1 is 15.In the third sample the length of path 3βββ1 is 1, the length of path 3βββ2βββ1 is 2.In the fourth sample the numbers of stations are the same, so the shortest distance equals 0. | Java 7 | standard input | [
"implementation"
] | 22ef37041ebbd8266f62ab932f188b31 | The first line contains integer n (3ββ€βnββ€β100) β the number of stations on the circle line. The second line contains n integers d1,βd2,β...,βdn (1ββ€βdiββ€β100) β the distances between pairs of neighboring stations. The third line contains two integers s and t (1ββ€βs,βtββ€βn) β the numbers of stations, between which you need to find the shortest distance. These numbers can be the same. The numbers in the lines are separated by single spaces. | 800 | Print a single number β the length of the shortest path between stations number s and t. | standard output | |
PASSED | db8c8bebaf1f78aa5259a9e52351a4f3 | train_003.jsonl | 1362065400 | The circle line of the Berland subway has n stations. We know the distances between all pairs of neighboring stations: d1 is the distance between the 1-st and the 2-nd station; d2 is the distance between the 2-nd and the 3-rd station;... dnβ-β1 is the distance between the nβ-β1-th and the n-th station; dn is the distance between the n-th and the 1-st station.The trains go along the circle line in both directions. Find the shortest distance between stations with numbers s and t. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main{
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader sc = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(sc.readLine());
int [] arr = new int[n];
int i = 0;
for (String s : sc.readLine().split(" ") )
arr[i++] = Integer.parseInt(s);
String [] temp = sc.readLine().split(" ");
int s = Integer.parseInt(temp[0]) - 1, t = Integer.parseInt(temp[1]) - 1;
int fs = Math.min(s,t);
int ft = Math.max(s,t);
s = 0;
for (int r = fs; r < ft; ++r)
s += arr[r];
t = 0;
for (int r = ft; r < n + fs; ++r)
t += arr[r % n];
System.out.println(Math.min(s,t));
}
} | Java | ["4\n2 3 4 9\n1 3", "4\n5 8 2 100\n4 1", "3\n1 1 1\n3 1", "3\n31 41 59\n1 1"] | 2 seconds | ["5", "15", "1", "0"] | NoteIn the first sample the length of path 1βββ2βββ3 equals 5, the length of path 1βββ4βββ3 equals 13.In the second sample the length of path 4βββ1 is 100, the length of path 4βββ3βββ2βββ1 is 15.In the third sample the length of path 3βββ1 is 1, the length of path 3βββ2βββ1 is 2.In the fourth sample the numbers of stations are the same, so the shortest distance equals 0. | Java 7 | standard input | [
"implementation"
] | 22ef37041ebbd8266f62ab932f188b31 | The first line contains integer n (3ββ€βnββ€β100) β the number of stations on the circle line. The second line contains n integers d1,βd2,β...,βdn (1ββ€βdiββ€β100) β the distances between pairs of neighboring stations. The third line contains two integers s and t (1ββ€βs,βtββ€βn) β the numbers of stations, between which you need to find the shortest distance. These numbers can be the same. The numbers in the lines are separated by single spaces. | 800 | Print a single number β the length of the shortest path between stations number s and t. | standard output | |
PASSED | 23213d63a61f71268c4e4ca92ead5537 | train_003.jsonl | 1362065400 | The circle line of the Berland subway has n stations. We know the distances between all pairs of neighboring stations: d1 is the distance between the 1-st and the 2-nd station; d2 is the distance between the 2-nd and the 3-rd station;... dnβ-β1 is the distance between the nβ-β1-th and the n-th station; dn is the distance between the n-th and the 1-st station.The trains go along the circle line in both directions. Find the shortest distance between stations with numbers s and t. | 256 megabytes | /**
* Created by Dima on 28.07.2014.
*/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class RingRing {
private static BufferedReader reader;
private static PrintWriter writer;
private static StringTokenizer st;
private static int[][] graph;
public static void main(String[] args) throws IOException {
reader = new BufferedReader(new InputStreamReader(System.in));
writer = new PrintWriter(System.out, true);
solve();
}
private static void solve() throws IOException {
int n = nextInt();
graph = new int[n][n];
for(int i = 0; i < n; ++i) {
for(int j = 0; j < n; ++j) {
if(i == j) graph[i][j] = 0;
else graph[i][j] = Integer.MAX_VALUE;
}
}
for(int i = 0; i < n; ++i) {
int tmp = nextInt();
if(i != n-1) {
graph[i][i+1] = tmp;
graph[i+1][i] = tmp;
}
else {
graph[i][0] = tmp;
graph[0][i] = tmp;
}
}
int s = nextInt();
int t = nextInt();
int[] dist = dijkstra(s-1, n);
writer.println(dist[t-1]);
}
private static int[] dijkstra(int start , int n) {
boolean[] visited = new boolean[n];
int[] dist = new int[n];
for(int i = 0; i < n; ++i) dist[i] = Integer.MAX_VALUE;
dist[start] = 0;
for (;;) {
int v = -1;
for (int nv = 0; nv < n; nv++)
if (!visited[nv] && dist[nv] < Integer.MAX_VALUE && (v == -1 || dist[v] > dist[nv]))
v = nv;
if (v == -1) break;
visited[v] = true;
for (int nv = 0; nv < n; nv++)
if (!visited[nv] && graph[v][nv] < Integer.MAX_VALUE)
dist[nv] = Math.min(dist[nv], dist[v] + graph[v][nv]); // ΡΠ»ΡΡΡΠ°Π΅ΠΌ ΠΎΡΠ΅Π½ΠΊΡ ΡΠ°ΡΡΡΠΎΡΠ½ΠΈΡ (ΡΠ΅Π»Π°ΠΊΡΠ°ΡΠΈΡ)
}
return dist;
}
private static int nextInt() throws IOException {
return Integer.parseInt(readToken());
}
private static String readToken() throws IOException {
while (st == null || !st.hasMoreElements()) st = new StringTokenizer(reader.readLine(), " ");
return st.nextToken();
}
}
| Java | ["4\n2 3 4 9\n1 3", "4\n5 8 2 100\n4 1", "3\n1 1 1\n3 1", "3\n31 41 59\n1 1"] | 2 seconds | ["5", "15", "1", "0"] | NoteIn the first sample the length of path 1βββ2βββ3 equals 5, the length of path 1βββ4βββ3 equals 13.In the second sample the length of path 4βββ1 is 100, the length of path 4βββ3βββ2βββ1 is 15.In the third sample the length of path 3βββ1 is 1, the length of path 3βββ2βββ1 is 2.In the fourth sample the numbers of stations are the same, so the shortest distance equals 0. | Java 7 | standard input | [
"implementation"
] | 22ef37041ebbd8266f62ab932f188b31 | The first line contains integer n (3ββ€βnββ€β100) β the number of stations on the circle line. The second line contains n integers d1,βd2,β...,βdn (1ββ€βdiββ€β100) β the distances between pairs of neighboring stations. The third line contains two integers s and t (1ββ€βs,βtββ€βn) β the numbers of stations, between which you need to find the shortest distance. These numbers can be the same. The numbers in the lines are separated by single spaces. | 800 | Print a single number β the length of the shortest path between stations number s and t. | standard output | |
PASSED | 6cef9af6f9004815954c6fac54337500 | train_003.jsonl | 1362065400 | The circle line of the Berland subway has n stations. We know the distances between all pairs of neighboring stations: d1 is the distance between the 1-st and the 2-nd station; d2 is the distance between the 2-nd and the 3-rd station;... dnβ-β1 is the distance between the nβ-β1-th and the n-th station; dn is the distance between the n-th and the 1-st station.The trains go along the circle line in both directions. Find the shortest distance between stations with numbers s and t. | 256 megabytes |
import java.util.Scanner;
public class A {
public static void run() {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] d = new int[n];
for(int i = 0; i < n; i++) d[i] = sc.nextInt();
int s = sc.nextInt();
int t = sc.nextInt();
task(n, d, s, t);
}
public static void test() {
task(4, new int[]{2, 3, 4, 9}, 1, 3);
task(4, new int[]{5, 8, 2, 100}, 4, 1);
task(3, new int[]{1, 1, 1}, 3, 1);
task(3, new int[]{31, 41, 59}, 1, 1);
}
public static void task(int n, int[] d, int s, int t) {
if(s > t) {
task(n, d, t, s);
return;
} else if (s == t) {
System.out.println(0);
return;
} else {
int is = s - 1, it = t - 1;
int s1 = 0;
//System.out.println(">>");
for(int i = is; i != it; i = i == n-1 ? 0: i + 1) {
//System.out.println(i);
s1 += d[i];
}
//System.out.println("<<");
int s2 = 0;
for(int i = is == 0 ? n - 1: is - 1; i != it - 1 && i != -1; i = i == 0 ? n - 1: i - 1) {
//System.out.println(i);
s2 += d[i];
}
System.out.println(s1 < s2? s1 : s2);
}
}
public static void main(String[] args) {
run();
}
}
| Java | ["4\n2 3 4 9\n1 3", "4\n5 8 2 100\n4 1", "3\n1 1 1\n3 1", "3\n31 41 59\n1 1"] | 2 seconds | ["5", "15", "1", "0"] | NoteIn the first sample the length of path 1βββ2βββ3 equals 5, the length of path 1βββ4βββ3 equals 13.In the second sample the length of path 4βββ1 is 100, the length of path 4βββ3βββ2βββ1 is 15.In the third sample the length of path 3βββ1 is 1, the length of path 3βββ2βββ1 is 2.In the fourth sample the numbers of stations are the same, so the shortest distance equals 0. | Java 7 | standard input | [
"implementation"
] | 22ef37041ebbd8266f62ab932f188b31 | The first line contains integer n (3ββ€βnββ€β100) β the number of stations on the circle line. The second line contains n integers d1,βd2,β...,βdn (1ββ€βdiββ€β100) β the distances between pairs of neighboring stations. The third line contains two integers s and t (1ββ€βs,βtββ€βn) β the numbers of stations, between which you need to find the shortest distance. These numbers can be the same. The numbers in the lines are separated by single spaces. | 800 | Print a single number β the length of the shortest path between stations number s and t. | standard output | |
PASSED | ef705b2ac97c08d8f94d91ee63101ac2 | train_003.jsonl | 1362065400 | The circle line of the Berland subway has n stations. We know the distances between all pairs of neighboring stations: d1 is the distance between the 1-st and the 2-nd station; d2 is the distance between the 2-nd and the 3-rd station;... dnβ-β1 is the distance between the nβ-β1-th and the n-th station; dn is the distance between the n-th and the 1-st station.The trains go along the circle line in both directions. Find the shortest distance between stations with numbers s and t. | 256 megabytes | import java.util.Scanner;
public class circleine {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] arr = new int[sc.nextInt()];
for (int i = 0; i < arr.length; i++)
arr[i] = sc.nextInt();
int sum1 = 0;
int sum2 = 0;
int stop1 = sc.nextInt()-1;
int stop2 = sc.nextInt()-1;
if(stop1 > stop2)
{
int temp = stop1;
stop1 = stop2;
stop2 = temp;
}
for(int i = stop1; i<stop2; i++)
sum1 += arr[i];
int index = stop2;
while(index != stop1)
{
if(index == stop1)
break;
else if(index == arr.length-1) {
sum2 += arr[index];
index = 0;
}
else {
sum2 += arr[index];
index++;
}
}
if(sum1<sum2)
System.out.println(sum1);
else
System.out.println(sum2);
}
}
| Java | ["4\n2 3 4 9\n1 3", "4\n5 8 2 100\n4 1", "3\n1 1 1\n3 1", "3\n31 41 59\n1 1"] | 2 seconds | ["5", "15", "1", "0"] | NoteIn the first sample the length of path 1βββ2βββ3 equals 5, the length of path 1βββ4βββ3 equals 13.In the second sample the length of path 4βββ1 is 100, the length of path 4βββ3βββ2βββ1 is 15.In the third sample the length of path 3βββ1 is 1, the length of path 3βββ2βββ1 is 2.In the fourth sample the numbers of stations are the same, so the shortest distance equals 0. | Java 7 | standard input | [
"implementation"
] | 22ef37041ebbd8266f62ab932f188b31 | The first line contains integer n (3ββ€βnββ€β100) β the number of stations on the circle line. The second line contains n integers d1,βd2,β...,βdn (1ββ€βdiββ€β100) β the distances between pairs of neighboring stations. The third line contains two integers s and t (1ββ€βs,βtββ€βn) β the numbers of stations, between which you need to find the shortest distance. These numbers can be the same. The numbers in the lines are separated by single spaces. | 800 | Print a single number β the length of the shortest path between stations number s and t. | standard output | |
PASSED | 10f239076cf1613fe579999e09ae2dd1 | train_003.jsonl | 1362065400 | The circle line of the Berland subway has n stations. We know the distances between all pairs of neighboring stations: d1 is the distance between the 1-st and the 2-nd station; d2 is the distance between the 2-nd and the 3-rd station;... dnβ-β1 is the distance between the nβ-β1-th and the n-th station; dn is the distance between the n-th and the 1-st station.The trains go along the circle line in both directions. Find the shortest distance between stations with numbers s and t. | 256 megabytes | import java.util.Scanner;
public class circleine {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] arr = new int[n];
for (int i = 0; i < arr.length; i++)
arr[i] = sc.nextInt();
int sum1 = 0;
int sum2 = 0;
int stop1 = sc.nextInt()-1;
int stop2 = sc.nextInt()-1;
for(int i = stop1; i!=stop2; i = (i+1) % n)
sum1+=arr[i];
for(int i = stop2; i!=stop1; i= (i+1)%n)
sum2 += arr[i];
System.out.println(Math.min(sum1, sum2));
}
}
| Java | ["4\n2 3 4 9\n1 3", "4\n5 8 2 100\n4 1", "3\n1 1 1\n3 1", "3\n31 41 59\n1 1"] | 2 seconds | ["5", "15", "1", "0"] | NoteIn the first sample the length of path 1βββ2βββ3 equals 5, the length of path 1βββ4βββ3 equals 13.In the second sample the length of path 4βββ1 is 100, the length of path 4βββ3βββ2βββ1 is 15.In the third sample the length of path 3βββ1 is 1, the length of path 3βββ2βββ1 is 2.In the fourth sample the numbers of stations are the same, so the shortest distance equals 0. | Java 7 | standard input | [
"implementation"
] | 22ef37041ebbd8266f62ab932f188b31 | The first line contains integer n (3ββ€βnββ€β100) β the number of stations on the circle line. The second line contains n integers d1,βd2,β...,βdn (1ββ€βdiββ€β100) β the distances between pairs of neighboring stations. The third line contains two integers s and t (1ββ€βs,βtββ€βn) β the numbers of stations, between which you need to find the shortest distance. These numbers can be the same. The numbers in the lines are separated by single spaces. | 800 | Print a single number β the length of the shortest path between stations number s and t. | standard output | |
PASSED | d0b074d7e657b17be3ab7c71565164be | train_003.jsonl | 1362065400 | The circle line of the Berland subway has n stations. We know the distances between all pairs of neighboring stations: d1 is the distance between the 1-st and the 2-nd station; d2 is the distance between the 2-nd and the 3-rd station;... dnβ-β1 is the distance between the nβ-β1-th and the n-th station; dn is the distance between the n-th and the 1-st station.The trains go along the circle line in both directions. Find the shortest distance between stations with numbers s and t. | 256 megabytes | import java.io.*;
import java.math.*;
import java.util.*;
/**
* @author Togrul Gasimov (ttogrul30@gmail.com)
*/
public class Main {
public static void main(String[] args) /*throws FileNotFoundException*/ {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastScanner in = new FastScanner(inputStream);
FastPrinter out = new FastPrinter(outputStream);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
}
class TaskA{
public void solve(int testNumber, FastScanner scan, FastPrinter out) /*throws FileNotFoundException*/ {
//Scanner sscan = new Scanner(new File("input.txt"));
//PrintStream oout = new PrintStream(new File("output.txt"));
int[] a = new int[100];
int s, t;
int n = scan.nextInt();
for(int i = 0; i < n; i++){
a[i] = scan.nextInt();
}
s = scan.nextInt(); t = scan.nextInt();
s--; t--;
int x1 = s, d1 = 0;
while(x1 != t) {
d1 += a[x1]; x1++; if(x1 == n)x1 = 0;
}
int x2 = s, d2 = 0;
while(x2 != t) {
d2 += a[x2];
x2--; if(x2 == -1)x2 = n - 1;
}
d2 = d2 + a[t] - a[s];
out.println(d1 < d2 ? d1 : d2);
//sscan.close();
//oout.close();
}
}
class FastScanner extends BufferedReader {
public FastScanner(InputStream is) {
super(new InputStreamReader(is));
}
public int read() {
try{
int ret = super.read();
return ret;
}catch(Exception e){
throw new InputMismatchException();
}
}
public String next() {
StringBuilder sb = new StringBuilder();
int c = read();
while (isWhiteSpace(c)) {
c = read();
}
if (c < 0) {
return null;
}
while (c >= 0 && !isWhiteSpace(c)) {
sb.appendCodePoint(c);
c = read();
}
return sb.toString();
}
static boolean isWhiteSpace(int c) {
return c >= 0 && c <= 32;
}
public int nextInt() {
int c = read();
while (isWhiteSpace(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int ret = 0;
while (c >= 0 && !isWhiteSpace(c)) {
if (c < '0' || c > '9') {
throw new NumberFormatException("digit expected " + (char) c
+ " found");
}
ret = ret * 10 + c - '0';
c = read();
}
return ret * sgn;
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public BigInteger nextBigInteger() {
return new BigInteger(next());
}
public BigDecimal nextBigDecimal(){
return new BigDecimal(next());
}
public String readLine(){
try{
return super.readLine();
}catch(IOException e){
return null;
}
}
}
class FastPrinter extends PrintWriter {
public FastPrinter(OutputStream out) {
super(out);
}
public FastPrinter(Writer out) {
super(out);
}
} | Java | ["4\n2 3 4 9\n1 3", "4\n5 8 2 100\n4 1", "3\n1 1 1\n3 1", "3\n31 41 59\n1 1"] | 2 seconds | ["5", "15", "1", "0"] | NoteIn the first sample the length of path 1βββ2βββ3 equals 5, the length of path 1βββ4βββ3 equals 13.In the second sample the length of path 4βββ1 is 100, the length of path 4βββ3βββ2βββ1 is 15.In the third sample the length of path 3βββ1 is 1, the length of path 3βββ2βββ1 is 2.In the fourth sample the numbers of stations are the same, so the shortest distance equals 0. | Java 7 | standard input | [
"implementation"
] | 22ef37041ebbd8266f62ab932f188b31 | The first line contains integer n (3ββ€βnββ€β100) β the number of stations on the circle line. The second line contains n integers d1,βd2,β...,βdn (1ββ€βdiββ€β100) β the distances between pairs of neighboring stations. The third line contains two integers s and t (1ββ€βs,βtββ€βn) β the numbers of stations, between which you need to find the shortest distance. These numbers can be the same. The numbers in the lines are separated by single spaces. | 800 | Print a single number β the length of the shortest path between stations number s and t. | standard output | |
PASSED | db29bb896973413d9c5f2048e31dea64 | train_003.jsonl | 1362065400 | The circle line of the Berland subway has n stations. We know the distances between all pairs of neighboring stations: d1 is the distance between the 1-st and the 2-nd station; d2 is the distance between the 2-nd and the 3-rd station;... dnβ-β1 is the distance between the nβ-β1-th and the n-th station; dn is the distance between the n-th and the 1-st station.The trains go along the circle line in both directions. Find the shortest distance between stations with numbers s and t. | 256 megabytes | import java.io.*;
import java.math.*;
import java.util.*;
/**
* @author Togrul Gasimov (ttogrul30@gmail.com)
*/
public class Main {
public static void main(String[] args) /*throws FileNotFoundException*/ {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastScanner in = new FastScanner(inputStream);
FastPrinter out = new FastPrinter(outputStream);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
}
class TaskA{
public void solve(int testNumber, FastScanner scan, FastPrinter out) /*throws FileNotFoundException*/ {
//Scanner sscan = new Scanner(new File("input.txt"));
//PrintStream oout = new PrintStream(new File("output.txt"));
int[] a = new int[100];
int s, t, sum = 0;
int n = scan.nextInt();
for(int i = 0; i < n; i++){
a[i] = scan.nextInt(); sum += a[i];
}
s = scan.nextInt(); t = scan.nextInt();
s--; t--;
int x1 = s, d1 = 0;
while(x1 != t) {
d1 += a[x1]; x1++; if(x1 == n)x1 = 0;
}
out.println(d1 < sum - d1 ? d1 : sum - d1);
//sscan.close();
//oout.close();
}
}
class FastScanner extends BufferedReader {
public FastScanner(InputStream is) {
super(new InputStreamReader(is));
}
public int read() {
try{
int ret = super.read();
return ret;
}catch(Exception e){
throw new InputMismatchException();
}
}
public String next() {
StringBuilder sb = new StringBuilder();
int c = read();
while (isWhiteSpace(c)) {
c = read();
}
if (c < 0) {
return null;
}
while (c >= 0 && !isWhiteSpace(c)) {
sb.appendCodePoint(c);
c = read();
}
return sb.toString();
}
static boolean isWhiteSpace(int c) {
return c >= 0 && c <= 32;
}
public int nextInt() {
int c = read();
while (isWhiteSpace(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int ret = 0;
while (c >= 0 && !isWhiteSpace(c)) {
if (c < '0' || c > '9') {
throw new NumberFormatException("digit expected " + (char) c
+ " found");
}
ret = ret * 10 + c - '0';
c = read();
}
return ret * sgn;
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public BigInteger nextBigInteger() {
return new BigInteger(next());
}
public BigDecimal nextBigDecimal(){
return new BigDecimal(next());
}
public String readLine(){
try{
return super.readLine();
}catch(IOException e){
return null;
}
}
}
class FastPrinter extends PrintWriter {
public FastPrinter(OutputStream out) {
super(out);
}
public FastPrinter(Writer out) {
super(out);
}
} | Java | ["4\n2 3 4 9\n1 3", "4\n5 8 2 100\n4 1", "3\n1 1 1\n3 1", "3\n31 41 59\n1 1"] | 2 seconds | ["5", "15", "1", "0"] | NoteIn the first sample the length of path 1βββ2βββ3 equals 5, the length of path 1βββ4βββ3 equals 13.In the second sample the length of path 4βββ1 is 100, the length of path 4βββ3βββ2βββ1 is 15.In the third sample the length of path 3βββ1 is 1, the length of path 3βββ2βββ1 is 2.In the fourth sample the numbers of stations are the same, so the shortest distance equals 0. | Java 7 | standard input | [
"implementation"
] | 22ef37041ebbd8266f62ab932f188b31 | The first line contains integer n (3ββ€βnββ€β100) β the number of stations on the circle line. The second line contains n integers d1,βd2,β...,βdn (1ββ€βdiββ€β100) β the distances between pairs of neighboring stations. The third line contains two integers s and t (1ββ€βs,βtββ€βn) β the numbers of stations, between which you need to find the shortest distance. These numbers can be the same. The numbers in the lines are separated by single spaces. | 800 | Print a single number β the length of the shortest path between stations number s and t. | standard output | |
PASSED | 8742849beab7a2aab0ef505e346e85d8 | train_003.jsonl | 1362065400 | The circle line of the Berland subway has n stations. We know the distances between all pairs of neighboring stations: d1 is the distance between the 1-st and the 2-nd station; d2 is the distance between the 2-nd and the 3-rd station;... dnβ-β1 is the distance between the nβ-β1-th and the n-th station; dn is the distance between the n-th and the 1-st station.The trains go along the circle line in both directions. Find the shortest distance between stations with numbers s and t. | 256 megabytes | import java.util.*;
public class A278
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int a[] = new int[n];
for(int i = 0; i<n; i++)
{
a[i] = in.nextInt();
}
int s = in.nextInt()-1;
int t = in.nextInt()-1;
int minDist1 = 0;
for (int i = s; i != t; i = (i + 1) % n)
minDist1 += a[i];
int minDist2 = 0;
for (int i = t; i != s; i = (i + 1) % n)
minDist2 += a[i];
System.out.println(Math.min(minDist1, minDist2));
}
} | Java | ["4\n2 3 4 9\n1 3", "4\n5 8 2 100\n4 1", "3\n1 1 1\n3 1", "3\n31 41 59\n1 1"] | 2 seconds | ["5", "15", "1", "0"] | NoteIn the first sample the length of path 1βββ2βββ3 equals 5, the length of path 1βββ4βββ3 equals 13.In the second sample the length of path 4βββ1 is 100, the length of path 4βββ3βββ2βββ1 is 15.In the third sample the length of path 3βββ1 is 1, the length of path 3βββ2βββ1 is 2.In the fourth sample the numbers of stations are the same, so the shortest distance equals 0. | Java 7 | standard input | [
"implementation"
] | 22ef37041ebbd8266f62ab932f188b31 | The first line contains integer n (3ββ€βnββ€β100) β the number of stations on the circle line. The second line contains n integers d1,βd2,β...,βdn (1ββ€βdiββ€β100) β the distances between pairs of neighboring stations. The third line contains two integers s and t (1ββ€βs,βtββ€βn) β the numbers of stations, between which you need to find the shortest distance. These numbers can be the same. The numbers in the lines are separated by single spaces. | 800 | Print a single number β the length of the shortest path between stations number s and t. | standard output | |
PASSED | 766c749cde574bd36cb990162e871f9d | train_003.jsonl | 1362065400 | The circle line of the Berland subway has n stations. We know the distances between all pairs of neighboring stations: d1 is the distance between the 1-st and the 2-nd station; d2 is the distance between the 2-nd and the 3-rd station;... dnβ-β1 is the distance between the nβ-β1-th and the n-th station; dn is the distance between the n-th and the 1-st station.The trains go along the circle line in both directions. Find the shortest distance between stations with numbers s and t. | 256 megabytes | import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
public class Main {
public static void main(String[] args) {
Task task = new Task();
task.getData();
task.solve();
task.printAnswer();
}
}
class Task {
int[] d;
int s, t;
String answer = "";
public void getData() {
Scanner console = new Scanner(System.in);
d = new int[console.nextInt()];
for (int i = 0; i < d.length; ++i) {
d[i] = console.nextInt();
}
s = console.nextInt();
t = console.nextInt();
console.close();
}
public void solve() {
int sNew = Math.min(s, t) - 1;
int tNew = Math.max(s, t) - 1;
int lengthFirst = 0;
for (int i = sNew; i < tNew; ++i) {
lengthFirst += d[i];
}
int totalLength = 0;
for (int number : d) {
totalLength += number;
}
answer = Integer
.toString(lengthFirst < totalLength - lengthFirst ? lengthFirst
: totalLength - lengthFirst);
}
public void printAnswer() {
System.out.print(answer);
}
} | Java | ["4\n2 3 4 9\n1 3", "4\n5 8 2 100\n4 1", "3\n1 1 1\n3 1", "3\n31 41 59\n1 1"] | 2 seconds | ["5", "15", "1", "0"] | NoteIn the first sample the length of path 1βββ2βββ3 equals 5, the length of path 1βββ4βββ3 equals 13.In the second sample the length of path 4βββ1 is 100, the length of path 4βββ3βββ2βββ1 is 15.In the third sample the length of path 3βββ1 is 1, the length of path 3βββ2βββ1 is 2.In the fourth sample the numbers of stations are the same, so the shortest distance equals 0. | Java 7 | standard input | [
"implementation"
] | 22ef37041ebbd8266f62ab932f188b31 | The first line contains integer n (3ββ€βnββ€β100) β the number of stations on the circle line. The second line contains n integers d1,βd2,β...,βdn (1ββ€βdiββ€β100) β the distances between pairs of neighboring stations. The third line contains two integers s and t (1ββ€βs,βtββ€βn) β the numbers of stations, between which you need to find the shortest distance. These numbers can be the same. The numbers in the lines are separated by single spaces. | 800 | Print a single number β the length of the shortest path between stations number s and t. | standard output | |
PASSED | 3a89314bb99eae054f637d987c8b4a80 | train_003.jsonl | 1362065400 | The circle line of the Berland subway has n stations. We know the distances between all pairs of neighboring stations: d1 is the distance between the 1-st and the 2-nd station; d2 is the distance between the 2-nd and the 3-rd station;... dnβ-β1 is the distance between the nβ-β1-th and the n-th station; dn is the distance between the n-th and the 1-st station.The trains go along the circle line in both directions. Find the shortest distance between stations with numbers s and t. | 256 megabytes | import java.io.*;
public class CircleLine{
static int[] m;
static int n;
public static void main(String[] args) throws IOException{
BufferedReader r=new BufferedReader(new InputStreamReader(System.in));
n=Integer.parseInt(r.readLine());
String[] str=(r.readLine()).split(" ");
m=new int[n];
for(int i=0;i<n;i++)
m[i]=Integer.parseInt(str[i]);
String[] s=(r.readLine()).split(" ");
int a=Integer.parseInt(s[0]);
int b=Integer.parseInt(s[1]);
System.out.println(Math.min(find(a,b),findrev(a,b)));
}
static int find(int a,int b){
int sum=0;
if(a==b) return 0;
if(a < b){
for(int i=a-1;i<(b-1);i++)
sum += m[i];
return sum;
}
else
return find(a,n)+m[n-1]+find(1,b);
}
static int findrev(int a,int b){
if(a >= b) return find(b,a);
else
return find(1,a)+ m[n-1]+ find(b,n);
}
} | Java | ["4\n2 3 4 9\n1 3", "4\n5 8 2 100\n4 1", "3\n1 1 1\n3 1", "3\n31 41 59\n1 1"] | 2 seconds | ["5", "15", "1", "0"] | NoteIn the first sample the length of path 1βββ2βββ3 equals 5, the length of path 1βββ4βββ3 equals 13.In the second sample the length of path 4βββ1 is 100, the length of path 4βββ3βββ2βββ1 is 15.In the third sample the length of path 3βββ1 is 1, the length of path 3βββ2βββ1 is 2.In the fourth sample the numbers of stations are the same, so the shortest distance equals 0. | Java 7 | standard input | [
"implementation"
] | 22ef37041ebbd8266f62ab932f188b31 | The first line contains integer n (3ββ€βnββ€β100) β the number of stations on the circle line. The second line contains n integers d1,βd2,β...,βdn (1ββ€βdiββ€β100) β the distances between pairs of neighboring stations. The third line contains two integers s and t (1ββ€βs,βtββ€βn) β the numbers of stations, between which you need to find the shortest distance. These numbers can be the same. The numbers in the lines are separated by single spaces. | 800 | Print a single number β the length of the shortest path between stations number s and t. | standard output | |
PASSED | 6f29b7e4b4bf07060e98b6d32f806cb0 | train_003.jsonl | 1362065400 | The circle line of the Berland subway has n stations. We know the distances between all pairs of neighboring stations: d1 is the distance between the 1-st and the 2-nd station; d2 is the distance between the 2-nd and the 3-rd station;... dnβ-β1 is the distance between the nβ-β1-th and the n-th station; dn is the distance between the n-th and the 1-st station.The trains go along the circle line in both directions. Find the shortest distance between stations with numbers s and t. | 256 megabytes | import java.util.Scanner;
import java.util.Arrays;
public class Cakeminator {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] data = new int[n];
int summa=0;
for(int i=0;i<n;i++){
data[i]=sc.nextInt();
summa+=data[i];
}
int s=sc.nextInt(),t=sc.nextInt();
int temp;
if(s>t){
temp=s;s=t;t=temp;
}
int answer=0;
for(int i=s-1;i<t-1;i++){
answer+=data[i];
}
System.out.println(summa-answer>answer?answer:summa-answer);
}
} | Java | ["4\n2 3 4 9\n1 3", "4\n5 8 2 100\n4 1", "3\n1 1 1\n3 1", "3\n31 41 59\n1 1"] | 2 seconds | ["5", "15", "1", "0"] | NoteIn the first sample the length of path 1βββ2βββ3 equals 5, the length of path 1βββ4βββ3 equals 13.In the second sample the length of path 4βββ1 is 100, the length of path 4βββ3βββ2βββ1 is 15.In the third sample the length of path 3βββ1 is 1, the length of path 3βββ2βββ1 is 2.In the fourth sample the numbers of stations are the same, so the shortest distance equals 0. | Java 7 | standard input | [
"implementation"
] | 22ef37041ebbd8266f62ab932f188b31 | The first line contains integer n (3ββ€βnββ€β100) β the number of stations on the circle line. The second line contains n integers d1,βd2,β...,βdn (1ββ€βdiββ€β100) β the distances between pairs of neighboring stations. The third line contains two integers s and t (1ββ€βs,βtββ€βn) β the numbers of stations, between which you need to find the shortest distance. These numbers can be the same. The numbers in the lines are separated by single spaces. | 800 | Print a single number β the length of the shortest path between stations number s and t. | standard output | |
PASSED | 003d1ee786429808cf0b4f9966614668 | train_003.jsonl | 1362065400 | The circle line of the Berland subway has n stations. We know the distances between all pairs of neighboring stations: d1 is the distance between the 1-st and the 2-nd station; d2 is the distance between the 2-nd and the 3-rd station;... dnβ-β1 is the distance between the nβ-β1-th and the n-th station; dn is the distance between the n-th and the 1-st station.The trains go along the circle line in both directions. Find the shortest distance between stations with numbers s and t. | 256 megabytes | /**
*
* @author Yesha Shah
*/
import java.util.Scanner;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] arr = new int[n+1];
int sum = 0;
for(int i=1; i<=n; i++) {
arr[i] = sc.nextInt();
sum+=arr[i];
}
int s = sc.nextInt();
int t = sc.nextInt();
int dist = 0;
if(s<t) {
for(int i=s; i<t; i++) dist+=arr[i];
}
else {
for(int i=t; i<s; i++) dist+=arr[i];
}
if(dist<sum-dist) System.out.println(dist);
else System.out.println(sum-dist);
}
} | Java | ["4\n2 3 4 9\n1 3", "4\n5 8 2 100\n4 1", "3\n1 1 1\n3 1", "3\n31 41 59\n1 1"] | 2 seconds | ["5", "15", "1", "0"] | NoteIn the first sample the length of path 1βββ2βββ3 equals 5, the length of path 1βββ4βββ3 equals 13.In the second sample the length of path 4βββ1 is 100, the length of path 4βββ3βββ2βββ1 is 15.In the third sample the length of path 3βββ1 is 1, the length of path 3βββ2βββ1 is 2.In the fourth sample the numbers of stations are the same, so the shortest distance equals 0. | Java 7 | standard input | [
"implementation"
] | 22ef37041ebbd8266f62ab932f188b31 | The first line contains integer n (3ββ€βnββ€β100) β the number of stations on the circle line. The second line contains n integers d1,βd2,β...,βdn (1ββ€βdiββ€β100) β the distances between pairs of neighboring stations. The third line contains two integers s and t (1ββ€βs,βtββ€βn) β the numbers of stations, between which you need to find the shortest distance. These numbers can be the same. The numbers in the lines are separated by single spaces. | 800 | Print a single number β the length of the shortest path between stations number s and t. | standard output | |
PASSED | 1e15098ecd02efcd32bc4b1d6ba7b5fa | train_003.jsonl | 1362065400 | The circle line of the Berland subway has n stations. We know the distances between all pairs of neighboring stations: d1 is the distance between the 1-st and the 2-nd station; d2 is the distance between the 2-nd and the 3-rd station;... dnβ-β1 is the distance between the nβ-β1-th and the n-th station; dn is the distance between the n-th and the 1-st station.The trains go along the circle line in both directions. Find the shortest distance between stations with numbers s and t. | 256 megabytes | import java.io.*;
import java.util.*;
import static java.lang.Math.*;
public class B {
static PrintStream ps = new PrintStream(
new BufferedOutputStream(System.out));
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
int n = sc.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = sc.nextInt();
int s = sc.nextInt() - 1;
int t = sc.nextInt() - 1;
int b = 0;
for (int i = s; i != t; i = (i + 1) % n) {
b += a[i];
}
int x = 0;
for (int i = t; i != s; i = ((i + 1) % n)) {
x += a[i];
}
ps.println(min(x, b));
sc.close();
ps.flush();
ps.close();
}
}
| Java | ["4\n2 3 4 9\n1 3", "4\n5 8 2 100\n4 1", "3\n1 1 1\n3 1", "3\n31 41 59\n1 1"] | 2 seconds | ["5", "15", "1", "0"] | NoteIn the first sample the length of path 1βββ2βββ3 equals 5, the length of path 1βββ4βββ3 equals 13.In the second sample the length of path 4βββ1 is 100, the length of path 4βββ3βββ2βββ1 is 15.In the third sample the length of path 3βββ1 is 1, the length of path 3βββ2βββ1 is 2.In the fourth sample the numbers of stations are the same, so the shortest distance equals 0. | Java 7 | standard input | [
"implementation"
] | 22ef37041ebbd8266f62ab932f188b31 | The first line contains integer n (3ββ€βnββ€β100) β the number of stations on the circle line. The second line contains n integers d1,βd2,β...,βdn (1ββ€βdiββ€β100) β the distances between pairs of neighboring stations. The third line contains two integers s and t (1ββ€βs,βtββ€βn) β the numbers of stations, between which you need to find the shortest distance. These numbers can be the same. The numbers in the lines are separated by single spaces. | 800 | Print a single number β the length of the shortest path between stations number s and t. | standard output | |
PASSED | c47200fe3125dd728d627b3a95b39da8 | train_003.jsonl | 1362065400 | The circle line of the Berland subway has n stations. We know the distances between all pairs of neighboring stations: d1 is the distance between the 1-st and the 2-nd station; d2 is the distance between the 2-nd and the 3-rd station;... dnβ-β1 is the distance between the nβ-β1-th and the n-th station; dn is the distance between the n-th and the 1-st station.The trains go along the circle line in both directions. Find the shortest distance between stations with numbers s and t. | 256 megabytes | import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
public class A {
/* Write your custom/own functions here */
public static void main(String[] ar) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++)
arr[i] = sc.nextInt();
int a = sc.nextInt() - 1;
int b = sc.nextInt() - 1;
if (a == b) {
System.out.println("0");
} else {
int one = 0;
for (int k = a;; k++) {
k = k % n;
if (k == b)
break;
// System.out.println("je");
one += arr[k];
}
int two = 0;
for (int k = b;; k++) {
// System.out.println("ne");
k = k % n;
if (k == a)
break;
two += arr[k];
}
System.out.println(Math.min(one, two));
}
}
}
| Java | ["4\n2 3 4 9\n1 3", "4\n5 8 2 100\n4 1", "3\n1 1 1\n3 1", "3\n31 41 59\n1 1"] | 2 seconds | ["5", "15", "1", "0"] | NoteIn the first sample the length of path 1βββ2βββ3 equals 5, the length of path 1βββ4βββ3 equals 13.In the second sample the length of path 4βββ1 is 100, the length of path 4βββ3βββ2βββ1 is 15.In the third sample the length of path 3βββ1 is 1, the length of path 3βββ2βββ1 is 2.In the fourth sample the numbers of stations are the same, so the shortest distance equals 0. | Java 7 | standard input | [
"implementation"
] | 22ef37041ebbd8266f62ab932f188b31 | The first line contains integer n (3ββ€βnββ€β100) β the number of stations on the circle line. The second line contains n integers d1,βd2,β...,βdn (1ββ€βdiββ€β100) β the distances between pairs of neighboring stations. The third line contains two integers s and t (1ββ€βs,βtββ€βn) β the numbers of stations, between which you need to find the shortest distance. These numbers can be the same. The numbers in the lines are separated by single spaces. | 800 | Print a single number β the length of the shortest path between stations number s and t. | standard output | |
PASSED | 97671abc98509f3bf1fa2078745f6677 | train_003.jsonl | 1362065400 | The circle line of the Berland subway has n stations. We know the distances between all pairs of neighboring stations: d1 is the distance between the 1-st and the 2-nd station; d2 is the distance between the 2-nd and the 3-rd station;... dnβ-β1 is the distance between the nβ-β1-th and the n-th station; dn is the distance between the n-th and the 1-st station.The trains go along the circle line in both directions. Find the shortest distance between stations with numbers s and t. | 256 megabytes | import java.util.Scanner;
public class A {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int cantidadEstaciones = sc.nextInt();
int[] distancias = new int[cantidadEstaciones];
for (int i = 0; i < distancias.length; i++) {
distancias[i] = sc.nextInt();
}
int estacionInicio = sc.nextInt() - 1;
int estacionFin = sc.nextInt() - 1;
sc.close();
int distancia1 = 0;
for (int i = estacionInicio; i != estacionFin; i = (i + 1) % cantidadEstaciones) {
distancia1 += distancias[i];
}
int distancia2 = 0;
for (int i = estacionFin; i != estacionInicio; i = (i + 1) % cantidadEstaciones) {
distancia2 += distancias[i];
}
System.out.println(Math.min(distancia1, distancia2));
}
}
| Java | ["4\n2 3 4 9\n1 3", "4\n5 8 2 100\n4 1", "3\n1 1 1\n3 1", "3\n31 41 59\n1 1"] | 2 seconds | ["5", "15", "1", "0"] | NoteIn the first sample the length of path 1βββ2βββ3 equals 5, the length of path 1βββ4βββ3 equals 13.In the second sample the length of path 4βββ1 is 100, the length of path 4βββ3βββ2βββ1 is 15.In the third sample the length of path 3βββ1 is 1, the length of path 3βββ2βββ1 is 2.In the fourth sample the numbers of stations are the same, so the shortest distance equals 0. | Java 7 | standard input | [
"implementation"
] | 22ef37041ebbd8266f62ab932f188b31 | The first line contains integer n (3ββ€βnββ€β100) β the number of stations on the circle line. The second line contains n integers d1,βd2,β...,βdn (1ββ€βdiββ€β100) β the distances between pairs of neighboring stations. The third line contains two integers s and t (1ββ€βs,βtββ€βn) β the numbers of stations, between which you need to find the shortest distance. These numbers can be the same. The numbers in the lines are separated by single spaces. | 800 | Print a single number β the length of the shortest path between stations number s and t. | standard output | |
PASSED | a82e9193d58aa157b4adcf8234241759 | train_003.jsonl | 1362065400 | The circle line of the Berland subway has n stations. We know the distances between all pairs of neighboring stations: d1 is the distance between the 1-st and the 2-nd station; d2 is the distance between the 2-nd and the 3-rd station;... dnβ-β1 is the distance between the nβ-β1-th and the n-th station; dn is the distance between the n-th and the 1-st station.The trains go along the circle line in both directions. Find the shortest distance between stations with numbers s and t. | 256 megabytes | import java.util.Scanner;
public class A {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int cantidadEstaciones = sc.nextInt();
int[] distancias = new int[cantidadEstaciones];
for (int i = 0; i < distancias.length; i++) {
distancias[i] = sc.nextInt();
}
int estacionInicio = sc.nextInt() - 1;
int estacionFin = sc.nextInt() - 1;
sc.close();
int distanciaDer =
distanciaADerecha(estacionInicio, estacionFin, distancias);
int distanciaIzq =
distanciaADerecha(estacionFin, estacionInicio, distancias);
System.out.println(Math.min(distanciaDer, distanciaIzq));
}
private static int distanciaADerecha(int estacionInicio, int estacionFin,
int[] distancias) {
int res = 0;
for (int i = estacionInicio; i != estacionFin; i =
(i + 1) % distancias.length) {
res += distancias[i];
}
return res;
}
}
| Java | ["4\n2 3 4 9\n1 3", "4\n5 8 2 100\n4 1", "3\n1 1 1\n3 1", "3\n31 41 59\n1 1"] | 2 seconds | ["5", "15", "1", "0"] | NoteIn the first sample the length of path 1βββ2βββ3 equals 5, the length of path 1βββ4βββ3 equals 13.In the second sample the length of path 4βββ1 is 100, the length of path 4βββ3βββ2βββ1 is 15.In the third sample the length of path 3βββ1 is 1, the length of path 3βββ2βββ1 is 2.In the fourth sample the numbers of stations are the same, so the shortest distance equals 0. | Java 7 | standard input | [
"implementation"
] | 22ef37041ebbd8266f62ab932f188b31 | The first line contains integer n (3ββ€βnββ€β100) β the number of stations on the circle line. The second line contains n integers d1,βd2,β...,βdn (1ββ€βdiββ€β100) β the distances between pairs of neighboring stations. The third line contains two integers s and t (1ββ€βs,βtββ€βn) β the numbers of stations, between which you need to find the shortest distance. These numbers can be the same. The numbers in the lines are separated by single spaces. | 800 | Print a single number β the length of the shortest path between stations number s and t. | standard output | |
PASSED | be02b9cb280914e62f3e02b0ecc21063 | train_003.jsonl | 1362065400 | The circle line of the Berland subway has n stations. We know the distances between all pairs of neighboring stations: d1 is the distance between the 1-st and the 2-nd station; d2 is the distance between the 2-nd and the 3-rd station;... dnβ-β1 is the distance between the nβ-β1-th and the n-th station; dn is the distance between the n-th and the 1-st station.The trains go along the circle line in both directions. Find the shortest distance between stations with numbers s and t. | 256 megabytes | import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class A {
private static BufferedReader in;
private static StringTokenizer st;
private static PrintWriter out;
public static void main(String[] args) throws NumberFormatException, IOException {
in = new BufferedReader(new InputStreamReader(System.in));
st = new StringTokenizer("");
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
int n = nextInt();
int a[] = new int[2 * n];
for (int i = 0; i < n; i++) {
a[i] = nextInt();
a[n+i] = a[i];
}
int t = nextInt();
int s = nextInt();
if(t>s){
int tmp = t;
t = s;
s = tmp;
}
t--;
s--;
if(s==t){
System.out.println(0);
return;
}
int sum [] = new int [2*n];
sum[0] = 0;
for (int i = 1; i < 2*n-1; i++) {
sum[i] = sum[i] + sum[i-1]+a[i-1];
}
int ans = Math.min(sum[s] - sum[t], sum[n+t]-sum[s]);
System.out.println(ans);
}
static String next() throws IOException{
while(!st.hasMoreTokens()){
st = new StringTokenizer(in.readLine());
}
return st.nextToken();
}
static int nextInt() throws NumberFormatException, IOException{
return Integer.parseInt(next());
}
static long nextLong() throws NumberFormatException, IOException{
return Long.parseLong(next());
}
static double nextDouble() throws NumberFormatException, IOException{
return Double.parseDouble(next());
}
}
| Java | ["4\n2 3 4 9\n1 3", "4\n5 8 2 100\n4 1", "3\n1 1 1\n3 1", "3\n31 41 59\n1 1"] | 2 seconds | ["5", "15", "1", "0"] | NoteIn the first sample the length of path 1βββ2βββ3 equals 5, the length of path 1βββ4βββ3 equals 13.In the second sample the length of path 4βββ1 is 100, the length of path 4βββ3βββ2βββ1 is 15.In the third sample the length of path 3βββ1 is 1, the length of path 3βββ2βββ1 is 2.In the fourth sample the numbers of stations are the same, so the shortest distance equals 0. | Java 7 | standard input | [
"implementation"
] | 22ef37041ebbd8266f62ab932f188b31 | The first line contains integer n (3ββ€βnββ€β100) β the number of stations on the circle line. The second line contains n integers d1,βd2,β...,βdn (1ββ€βdiββ€β100) β the distances between pairs of neighboring stations. The third line contains two integers s and t (1ββ€βs,βtββ€βn) β the numbers of stations, between which you need to find the shortest distance. These numbers can be the same. The numbers in the lines are separated by single spaces. | 800 | Print a single number β the length of the shortest path between stations number s and t. | standard output | |
PASSED | 7f62b19e7399f0dd8dc035eb3c91139c | train_003.jsonl | 1362065400 | The circle line of the Berland subway has n stations. We know the distances between all pairs of neighboring stations: d1 is the distance between the 1-st and the 2-nd station; d2 is the distance between the 2-nd and the 3-rd station;... dnβ-β1 is the distance between the nβ-β1-th and the n-th station; dn is the distance between the n-th and the 1-st station.The trains go along the circle line in both directions. Find the shortest distance between stations with numbers s and t. | 256 megabytes | import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.InputMismatchException;
import java.util.LinkedList;
import java.util.Map.Entry;
import java.util.Queue;
import java.util.Random;
import java.util.Set;
import java.util.SortedSet;
import java.util.Stack;
import java.util.TreeMap;
import java.util.TreeSet;
public class Main
{
/********************************************** a list of common variables **********************************************/
private MyScanner scan = new MyScanner();
private PrintWriter out = new PrintWriter(System.out);
private final int MOD = (int)(1e9 + 7);
public void foo()
{
int n = scan.nextInt();
int sum = 0;
int[] d = new int[n];
for(int i = 0;i < n;++i)
{
d[i] = scan.nextInt();
sum += d[i];
}
int s = scan.nextInt();
int t = scan.nextInt();
if(s > t)
{
int tmp = s;
s = t;
t = tmp;
}
int ans = 0;
for(int i = s - 1;i < t - 1;++i)
{
ans += d[i];
}
out.println(Math.min(ans, sum - ans));
}
public static void main(String[] args)
{
Main m = new Main();
m.foo();
m.out.close();
}
/********************************************** a list of common algorithms **********************************************/
/**
* KMP match, i.e. kmpMatch("abcd", "bcd") = 1, kmpMatch("abcd", "bfcd") = -1.
*
* @param t: String to match.
* @param p: String to be matched.
* @return if can match, first index; otherwise -1.
*/
public int kmpMatch(char[] t, char[] p)
{
int n = t.length;
int m = p.length;
int[] next = new int[m + 1];
next[0] = -1;
int j = -1;
for(int i = 1;i < m;++i)
{
while(j >= 0 && p[i] != p[j + 1])
{
j = next[j];
}
if(p[i] == p[j + 1])
{
++j;
}
next[i] = j;
}
j = -1;
for(int i = 0;i < n;++i)
{
while(j >= 0 && t[i] != p[j + 1])
{
j = next[j];
}
if(t[i] == p[j + 1])
{
++j;
}
if(j == m - 1)
{
return i - m + 1;
}
}
return -1;
}
class MyScanner
{
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
BufferedInputStream bis = new BufferedInputStream(System.in);
public int read()
{
if (-1 == numChars)
{
throw new InputMismatchException();
}
if (curChar >= numChars)
{
curChar = 0;
try
{
numChars = bis.read(buf);
}
catch (IOException e)
{
throw new InputMismatchException();
}
if (numChars <= 0)
{
return -1;
}
}
return buf[curChar++];
}
public int nextInt()
{
int c = read();
while (isSpaceChar(c))
{
c = read();
}
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
int res = 0;
do
{
if (c < '0' || c > '9')
{
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong()
{
int c = read();
while (isSpaceChar(c))
{
c = read();
}
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
long res = 0;
do
{
if (c < '0' || c > '9')
{
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public double nextDouble()
{
int c = read();
while (isSpaceChar(c))
{
c = read();
}
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.')
{
if (c == 'e' || c == 'E')
{
return res * Math.pow(10, nextInt());
}
if (c < '0' || c > '9')
{
throw new InputMismatchException();
}
res *= 10;
res += c & 15;
c = read();
}
if (c == '.')
{
c = read();
double m = 1;
while (!isSpaceChar(c))
{
if (c == 'e' || c == 'E')
{
return res * Math.pow(10, nextInt());
}
if (c < '0' || c > '9')
{
throw new InputMismatchException();
}
m /= 10;
res += (c & 15) * m;
c = read();
}
}
return res * sgn;
}
public String next()
{
int c = read();
while (isSpaceChar(c))
{
c = read();
}
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
private boolean isSpaceChar(int c)
{
return ' ' == c || '\n' == c || '\r' == c || '\t' == c || -1 == c;
}
}
} | Java | ["4\n2 3 4 9\n1 3", "4\n5 8 2 100\n4 1", "3\n1 1 1\n3 1", "3\n31 41 59\n1 1"] | 2 seconds | ["5", "15", "1", "0"] | NoteIn the first sample the length of path 1βββ2βββ3 equals 5, the length of path 1βββ4βββ3 equals 13.In the second sample the length of path 4βββ1 is 100, the length of path 4βββ3βββ2βββ1 is 15.In the third sample the length of path 3βββ1 is 1, the length of path 3βββ2βββ1 is 2.In the fourth sample the numbers of stations are the same, so the shortest distance equals 0. | Java 7 | standard input | [
"implementation"
] | 22ef37041ebbd8266f62ab932f188b31 | The first line contains integer n (3ββ€βnββ€β100) β the number of stations on the circle line. The second line contains n integers d1,βd2,β...,βdn (1ββ€βdiββ€β100) β the distances between pairs of neighboring stations. The third line contains two integers s and t (1ββ€βs,βtββ€βn) β the numbers of stations, between which you need to find the shortest distance. These numbers can be the same. The numbers in the lines are separated by single spaces. | 800 | Print a single number β the length of the shortest path between stations number s and t. | standard output | |
PASSED | cb349017ebf3b85ade23ce99bf98545d | train_004.jsonl | 1448636400 | You are given string s. Let's call word any largest sequence of consecutive symbols without symbols ',' (comma) and ';' (semicolon). For example, there are four words in string "aba,123;1a;0": "aba", "123", "1a", "0". A word can be empty: for example, the string s=";;" contains three empty words separated by ';'.You should find all words in the given string that are nonnegative INTEGER numbers without leading zeroes and build by them new string a. String a should contain all words that are numbers separating them by ',' (the order of numbers should remain the same as in the string s). By all other words you should build string b in the same way (the order of numbers should remain the same as in the string s).Here strings "101", "0" are INTEGER numbers, but "01" and "1.0" are not.For example, for the string aba,123;1a;0 the string a would be equal to "123,0" and string b would be equal to "aba,1a". | 256 megabytes | import java.io.*;
import java.util.*;
import java.math.*;
public class Main{
static boolean isNumeric(String s){
if(s.length()==0)
return false;
for(int i=0; i<s.length(); i++)
if(s.charAt(i)<'0' || s.charAt(i)>'9')
return false;
return s.length()==1?true:s.charAt(0)!='0';
}
public static void main(String[] args)throws Throwable{
Escanner sc = new Escanner( );
out = new PrintWriter(System.out);
//////////
String s1 = sc.in.readLine();
StringBuilder sIn = new StringBuilder();
for(int i=0; i<s1.length(); i++)
if(s1.charAt(i)==',' || s1.charAt(i)==';')
sIn.append(" "+s1.charAt(i)+" ");
else
sIn.append(s1.charAt(i));
sc.set(sIn.toString());
StringBuilder a = new StringBuilder("\""), b = new StringBuilder("\"");
boolean ea = true, eb = true;
do{
String s = sc.nextStr();
if(isNumeric(s.trim())){
a.append((ea?"":",")+s.trim());
ea = false;
}else{
b.append((eb?"":",")+s.trim());
eb = false;
}
}while(!sc.EOL());
a.append("\"");
b.append("\"");
out.println(ea?"-":a);
out.println(eb?"-":b);
//////////
out.close();
}
static class Escanner {
BufferedReader in;
StringTokenizer st;
Escanner() throws Throwable {
in = new BufferedReader(new InputStreamReader(System.in),32768);
st = new StringTokenizer("");
}
Escanner(String fileName) throws Throwable {
in = new BufferedReader(new FileReader(fileName),32768);
st = new StringTokenizer("");
}
void set(String s){
st = new StringTokenizer(s);
}
boolean isBlank() throws Throwable{
String l = in.readLine();
st = new StringTokenizer(l==null?"":l);
return !st.hasMoreTokens();
}
boolean EOL(){
return !st.hasMoreTokens();
}
String nextStr() throws Throwable {
while(!st.hasMoreTokens())
st = new StringTokenizer(in.readLine());
return st.nextToken(";,");
}
int nextInt() throws Throwable {
return Integer.parseInt(nextStr());
}
long nextLong() throws Throwable {
return Long.parseLong(nextStr());
}
BigInteger nextBigInt() throws Throwable {
return new BigInteger(nextStr());
}
double nextDouble() throws Throwable {
return Double.parseDouble(nextStr());
}
}
static PrintWriter out;
} | Java | ["aba,123;1a;0", "1;;01,a0,", "1", "a"] | 2 seconds | ["\"123,0\"\n\"aba,1a\"", "\"1\"\n\",01,a0,\"", "\"1\"\n-", "-\n\"a\""] | NoteIn the second example the string s contains five words: "1", "", "01", "a0", "". | Java 7 | standard input | [
"implementation",
"strings"
] | ad02cead427d0765eb642203d13d3b99 | The only line of input contains the string s (1ββ€β|s|ββ€β105). The string contains only symbols '.' (ASCII 46), ',' (ASCII 44), ';' (ASCII 59), digits, lowercase and uppercase latin letters. | 1,600 | Print the string a to the first line and string b to the second line. Each string should be surrounded by quotes (ASCII 34). If there are no words that are numbers print dash (ASCII 45) on the first line. If all words are numbers print dash on the second line. | standard output | |
PASSED | 05fd99f8ab03e1d816abd4cc47ced72e | train_004.jsonl | 1448636400 | You are given string s. Let's call word any largest sequence of consecutive symbols without symbols ',' (comma) and ';' (semicolon). For example, there are four words in string "aba,123;1a;0": "aba", "123", "1a", "0". A word can be empty: for example, the string s=";;" contains three empty words separated by ';'.You should find all words in the given string that are nonnegative INTEGER numbers without leading zeroes and build by them new string a. String a should contain all words that are numbers separating them by ',' (the order of numbers should remain the same as in the string s). By all other words you should build string b in the same way (the order of numbers should remain the same as in the string s).Here strings "101", "0" are INTEGER numbers, but "01" and "1.0" are not.For example, for the string aba,123;1a;0 the string a would be equal to "123,0" and string b would be equal to "aba,1a". | 256 megabytes | import java.util.*;
import java.io.*;
import java.math.*;
public class Parse {
public static void solve(String s) {
ArrayList<String> words = new ArrayList<>();
ArrayList<String> nums = new ArrayList<>();
StringBuffer cur = new StringBuffer();
for (int i = 0; i <= s.length(); i++) {
char c = (i < s.length()) ? s.charAt(i) : '`';
if (c == ';' || c == ',' || c == '`') {
String add = cur.toString();
try {
if (add.charAt(0) != '0' || add.length() == 1) {
BigInteger v = new BigInteger(add);
nums.add(add);
} else {
words.add(add);
}
} catch (Exception e) {
words.add(add);
}
cur = new StringBuffer();
} else {
cur.append(c);
}
}
print(nums);
print(words);
}
public static void print(ArrayList<String> vals) {
if (vals.size() == 0) {
System.out.println("-");
return;
}
StringBuffer out = new StringBuffer();
out.append("\"");
for (int i = 0; i < vals.size() - 1; i++) out.append(vals.get(i) + ",");
out.append(vals.get(vals.size() - 1));
out.append("\"");
System.out.println(out.toString());
}
public static void main(String[] args) {
try {
InputStreamReader is = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(is);
solve(br.readLine());
} catch (Exception e) {e.printStackTrace();}
}
}
| Java | ["aba,123;1a;0", "1;;01,a0,", "1", "a"] | 2 seconds | ["\"123,0\"\n\"aba,1a\"", "\"1\"\n\",01,a0,\"", "\"1\"\n-", "-\n\"a\""] | NoteIn the second example the string s contains five words: "1", "", "01", "a0", "". | Java 7 | standard input | [
"implementation",
"strings"
] | ad02cead427d0765eb642203d13d3b99 | The only line of input contains the string s (1ββ€β|s|ββ€β105). The string contains only symbols '.' (ASCII 46), ',' (ASCII 44), ';' (ASCII 59), digits, lowercase and uppercase latin letters. | 1,600 | Print the string a to the first line and string b to the second line. Each string should be surrounded by quotes (ASCII 34). If there are no words that are numbers print dash (ASCII 45) on the first line. If all words are numbers print dash on the second line. | standard output | |
PASSED | 6a38935f8c5cbe4fc5c821f7eb0cc15c | train_004.jsonl | 1448636400 | You are given string s. Let's call word any largest sequence of consecutive symbols without symbols ',' (comma) and ';' (semicolon). For example, there are four words in string "aba,123;1a;0": "aba", "123", "1a", "0". A word can be empty: for example, the string s=";;" contains three empty words separated by ';'.You should find all words in the given string that are nonnegative INTEGER numbers without leading zeroes and build by them new string a. String a should contain all words that are numbers separating them by ',' (the order of numbers should remain the same as in the string s). By all other words you should build string b in the same way (the order of numbers should remain the same as in the string s).Here strings "101", "0" are INTEGER numbers, but "01" and "1.0" are not.For example, for the string aba,123;1a;0 the string a would be equal to "123,0" and string b would be equal to "aba,1a". | 256 megabytes |
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
String s;
Scanner in = new Scanner(System.in);
s = in.nextLine();
if (s.charAt(s.length() - 1) == ',' || s.charAt(s.length() - 1) == ';')
s += '@';
String[] arr = s.split("[,;]");
StringBuilder s1 = new StringBuilder();
StringBuilder s2 = new StringBuilder();
for (String str : arr) {
if(str.matches("([1-9][0-9]*)|([0-9])")) {
s1.append(",");
s1.append(str);
} else {
s2.append(",");
str = str.replace("@", "");
s2.append(str);
}
}
if (s1.length() == 0)
System.out.println("-");
else{
s1.deleteCharAt(0);
System.out.println("\"" + s1.toString() + "\"");
}
if (s2.length() == 0)
System.out.println("-");
else {
s2.deleteCharAt(0);
System.out.println("\"" + s2.toString() + "\"");
}
in.close();
}
} | Java | ["aba,123;1a;0", "1;;01,a0,", "1", "a"] | 2 seconds | ["\"123,0\"\n\"aba,1a\"", "\"1\"\n\",01,a0,\"", "\"1\"\n-", "-\n\"a\""] | NoteIn the second example the string s contains five words: "1", "", "01", "a0", "". | Java 7 | standard input | [
"implementation",
"strings"
] | ad02cead427d0765eb642203d13d3b99 | The only line of input contains the string s (1ββ€β|s|ββ€β105). The string contains only symbols '.' (ASCII 46), ',' (ASCII 44), ';' (ASCII 59), digits, lowercase and uppercase latin letters. | 1,600 | Print the string a to the first line and string b to the second line. Each string should be surrounded by quotes (ASCII 34). If there are no words that are numbers print dash (ASCII 45) on the first line. If all words are numbers print dash on the second line. | standard output | |
PASSED | 46e82a0f1add65eaa45bebef0b82a7c0 | train_004.jsonl | 1448636400 | You are given string s. Let's call word any largest sequence of consecutive symbols without symbols ',' (comma) and ';' (semicolon). For example, there are four words in string "aba,123;1a;0": "aba", "123", "1a", "0". A word can be empty: for example, the string s=";;" contains three empty words separated by ';'.You should find all words in the given string that are nonnegative INTEGER numbers without leading zeroes and build by them new string a. String a should contain all words that are numbers separating them by ',' (the order of numbers should remain the same as in the string s). By all other words you should build string b in the same way (the order of numbers should remain the same as in the string s).Here strings "101", "0" are INTEGER numbers, but "01" and "1.0" are not.For example, for the string aba,123;1a;0 the string a would be equal to "123,0" and string b would be equal to "aba,1a". | 256 megabytes |
import java.math.BigInteger;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
String s;
Scanner in = new Scanner(System.in);
s = in.nextLine();
if (s.charAt(s.length() - 1) == ',' || s.charAt(s.length() - 1) == ';')
s += '@';
String[] arr = s.split("[,;]");
StringBuilder s1 = new StringBuilder();
StringBuilder s2 = new StringBuilder();
for (String str : arr) {
try {
BigInteger bi = new BigInteger(str);
if (str.charAt(0) == '0' && str.length() > 1)
throw new RuntimeException();
s1.append(",");
s1.append(str);
} catch (Exception e) {
s2.append(",");
str = str.replace("@", "");
s2.append(str);
}
}
if (s1.length() == 0)
System.out.println("-");
else{
s1.deleteCharAt(0);
System.out.println("\"" + s1.toString() + "\"");
}
if (s2.length() == 0)
System.out.println("-");
else {
s2.deleteCharAt(0);
System.out.println("\"" + s2.toString() + "\"");
}
in.close();
}
}
| Java | ["aba,123;1a;0", "1;;01,a0,", "1", "a"] | 2 seconds | ["\"123,0\"\n\"aba,1a\"", "\"1\"\n\",01,a0,\"", "\"1\"\n-", "-\n\"a\""] | NoteIn the second example the string s contains five words: "1", "", "01", "a0", "". | Java 7 | standard input | [
"implementation",
"strings"
] | ad02cead427d0765eb642203d13d3b99 | The only line of input contains the string s (1ββ€β|s|ββ€β105). The string contains only symbols '.' (ASCII 46), ',' (ASCII 44), ';' (ASCII 59), digits, lowercase and uppercase latin letters. | 1,600 | Print the string a to the first line and string b to the second line. Each string should be surrounded by quotes (ASCII 34). If there are no words that are numbers print dash (ASCII 45) on the first line. If all words are numbers print dash on the second line. | standard output | |
PASSED | 812a452bb5f57f423cd728de05757be4 | train_004.jsonl | 1448636400 | You are given string s. Let's call word any largest sequence of consecutive symbols without symbols ',' (comma) and ';' (semicolon). For example, there are four words in string "aba,123;1a;0": "aba", "123", "1a", "0". A word can be empty: for example, the string s=";;" contains three empty words separated by ';'.You should find all words in the given string that are nonnegative INTEGER numbers without leading zeroes and build by them new string a. String a should contain all words that are numbers separating them by ',' (the order of numbers should remain the same as in the string s). By all other words you should build string b in the same way (the order of numbers should remain the same as in the string s).Here strings "101", "0" are INTEGER numbers, but "01" and "1.0" are not.For example, for the string aba,123;1a;0 the string a would be equal to "123,0" and string b would be equal to "aba,1a". | 256 megabytes | import java.util.*;
import java.io.*;
import java.text.DecimalFormat;
public class CodeForces {
public static void main(String[] args) throws IOException {
Reader.init(System.in);
char s[] = Reader.next().toCharArray();
ArrayList<StringBuilder> a = new ArrayList();
ArrayList<StringBuilder> b = new ArrayList();
StringBuilder se = new StringBuilder();
boolean isN = true;
for(char ch : s){
if(ch == ',' || ch == ';'){
if(isN && se.length() > 0 && ( se.charAt(0) != '0' || se.length() == 1))
a.add(se.append(','));
else
b.add(se.append(','));
se = new StringBuilder();
isN = true;
continue;
}
se.append(ch);
if(!Character.isDigit(ch))
isN = false;
}
if(isN && se.length() > 0 && ( se.charAt(0) != '0' || se.length() == 1))
a.add(se.append(','));
else
b.add(se.append(','));
if(a.isEmpty())
System.out.println("-");
else {
System.out.print("\"");
for(int i = 0; i < a.size(); i++){
if(i == a.size() -1)
a.get(i).deleteCharAt(a.get(i).length()-1);
System.out.print(a.get(i));
}
System.out.println("\"");
}
if(b.isEmpty())
System.out.println("-");
else{
System.out.print("\"");
for(int i = 0; i < b.size(); i++){
if(i == b.size() -1)
b.get(i).deleteCharAt(b.get(i).length()-1);
System.out.print(b.get(i));
}
System.out.println("\"");
}
}
}
class Edge implements Comparable<Edge>{
int to;
int from;
int cost;
Edge(int a, int b, int c){
from = a;
to = b;
cost = c;
}
@Override
public int compareTo(Edge t) {
return t.cost - cost;
}
}
class NN implements Comparable<NN>{
int mony;
int f;
NN(int a, int b){
mony = a;
f = b;
}
@Override
public int compareTo(NN t) {
return mony - t.mony;
}
}
class Reader {
static BufferedReader reader;
static StringTokenizer tokenizer;
public static int pars(String x) {
int num = 0;
int i = 0;
if (x.charAt(0) == '-') {
i = 1;
}
for (; i < x.length(); i++) {
num = num * 10 + (x.charAt(i) - '0');
}
if (x.charAt(0) == '-') {
return -num;
}
return num;
}
static void init(InputStream input) {
reader = new BufferedReader(
new InputStreamReader(input));
tokenizer = new StringTokenizer("");
}
static void init(FileReader input) {
reader = new BufferedReader(input);
tokenizer = new StringTokenizer("");
}
static String next() throws IOException {
while (!tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(
reader.readLine());
}
return tokenizer.nextToken();
}
static int nextInt() throws IOException {
return pars(next());
}
static long nextLong() throws IOException {
return Long.parseLong(next());
}
static double nextDouble() throws IOException {
return Double.parseDouble(next());
}
} | Java | ["aba,123;1a;0", "1;;01,a0,", "1", "a"] | 2 seconds | ["\"123,0\"\n\"aba,1a\"", "\"1\"\n\",01,a0,\"", "\"1\"\n-", "-\n\"a\""] | NoteIn the second example the string s contains five words: "1", "", "01", "a0", "". | Java 7 | standard input | [
"implementation",
"strings"
] | ad02cead427d0765eb642203d13d3b99 | The only line of input contains the string s (1ββ€β|s|ββ€β105). The string contains only symbols '.' (ASCII 46), ',' (ASCII 44), ';' (ASCII 59), digits, lowercase and uppercase latin letters. | 1,600 | Print the string a to the first line and string b to the second line. Each string should be surrounded by quotes (ASCII 34). If there are no words that are numbers print dash (ASCII 45) on the first line. If all words are numbers print dash on the second line. | standard output | |
PASSED | 2eec1eabf1ef204f7c4c43fa952745de | train_004.jsonl | 1448636400 | You are given string s. Let's call word any largest sequence of consecutive symbols without symbols ',' (comma) and ';' (semicolon). For example, there are four words in string "aba,123;1a;0": "aba", "123", "1a", "0". A word can be empty: for example, the string s=";;" contains three empty words separated by ';'.You should find all words in the given string that are nonnegative INTEGER numbers without leading zeroes and build by them new string a. String a should contain all words that are numbers separating them by ',' (the order of numbers should remain the same as in the string s). By all other words you should build string b in the same way (the order of numbers should remain the same as in the string s).Here strings "101", "0" are INTEGER numbers, but "01" and "1.0" are not.For example, for the string aba,123;1a;0 the string a would be equal to "123,0" and string b would be equal to "aba,1a". | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
/**
* @author shakhawat.hossain
* @since 11/29/2015 6:57 PM
*/
public class A600 {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String input = br.readLine();
List<String> words = tokenize(input);
StringBuilder aStr = new StringBuilder();
StringBuilder bStr = new StringBuilder();
for (String word : words) {
if (isInteger(word)) {
bStr.append(",").append(word);
} else {
aStr.append(",").append(word);
}
}
System.out.println(bStr.length() == 0 ? "-" : "\"" + bStr.substring(1) + "\"");
System.out.println(aStr.length() == 0 ? "-" : "\"" + aStr.substring(1) + "\"");
}
private static List<String> tokenize(String input) {
List<String> words = new ArrayList<>();
int p = 0;
for (int i = 0; i < input.length(); i++) {
if (input.charAt(i) == ',' || input.charAt(i) == ';') {
words.add(input.substring(p, i));
p = i + 1;
}
}
words.add(input.substring(p));
return words;
}
private static boolean isInteger(String word) {
if (word.length() == 0 || (word.length() > 1 && word.startsWith("0"))) {
return false;
}
for (int i = 0; i < word.length(); i++) {
if (!Character.isDigit(word.charAt(i))) {
return false;
}
}
return true;
}
}
| Java | ["aba,123;1a;0", "1;;01,a0,", "1", "a"] | 2 seconds | ["\"123,0\"\n\"aba,1a\"", "\"1\"\n\",01,a0,\"", "\"1\"\n-", "-\n\"a\""] | NoteIn the second example the string s contains five words: "1", "", "01", "a0", "". | Java 7 | standard input | [
"implementation",
"strings"
] | ad02cead427d0765eb642203d13d3b99 | The only line of input contains the string s (1ββ€β|s|ββ€β105). The string contains only symbols '.' (ASCII 46), ',' (ASCII 44), ';' (ASCII 59), digits, lowercase and uppercase latin letters. | 1,600 | Print the string a to the first line and string b to the second line. Each string should be surrounded by quotes (ASCII 34). If there are no words that are numbers print dash (ASCII 45) on the first line. If all words are numbers print dash on the second line. | standard output | |
PASSED | b5e21ee21156c51d76f8c8be00de0936 | train_004.jsonl | 1448636400 | You are given string s. Let's call word any largest sequence of consecutive symbols without symbols ',' (comma) and ';' (semicolon). For example, there are four words in string "aba,123;1a;0": "aba", "123", "1a", "0". A word can be empty: for example, the string s=";;" contains three empty words separated by ';'.You should find all words in the given string that are nonnegative INTEGER numbers without leading zeroes and build by them new string a. String a should contain all words that are numbers separating them by ',' (the order of numbers should remain the same as in the string s). By all other words you should build string b in the same way (the order of numbers should remain the same as in the string s).Here strings "101", "0" are INTEGER numbers, but "01" and "1.0" are not.For example, for the string aba,123;1a;0 the string a would be equal to "123,0" and string b would be equal to "aba,1a". | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
/**
* @author shakhawat.hossain
* @since 11/29/2015 6:57 PM
*/
public class A600 {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String input = br.readLine();
List<String> words = tokenize(input);
StringBuilder aStr = new StringBuilder();
StringBuilder bStr = new StringBuilder();
for (String word : words) {
try {
Integer tmp = Integer.parseInt(word);
if (word.length() == (tmp + "").length() && !word.startsWith("-")) {
bStr.append(",").append(word);
} else {
throw new NumberFormatException();
}
} catch (Exception exp) {
boolean bigInt = true;
if (word.length() == 0 || word.startsWith("0")) {
bigInt = false;
} else {
for (int i = 0; i < word.length(); i++) {
if (!Character.isDigit(word.charAt(i))) {
bigInt = false;
break;
}
}
}
if (bigInt) {
bStr.append(",").append(word);
} else {
aStr.append(",").append(word);
}
}
}
System.out.println(bStr.length() == 0 ? "-" : "\"" + bStr.substring(1) + "\"");
System.out.println(aStr.length() == 0 ? "-" : "\"" + aStr.substring(1) + "\"");
}
private static List<String> tokenize(String input) {
List<String> words = new ArrayList<>();
int p = 0;
for (int i = 0; i < input.length(); i++) {
if (input.charAt(i) == ',' || input.charAt(i) == ';') {
words.add(input.substring(p, i));
p = i + 1;
}
}
words.add(input.substring(p));
return words;
}
}
| Java | ["aba,123;1a;0", "1;;01,a0,", "1", "a"] | 2 seconds | ["\"123,0\"\n\"aba,1a\"", "\"1\"\n\",01,a0,\"", "\"1\"\n-", "-\n\"a\""] | NoteIn the second example the string s contains five words: "1", "", "01", "a0", "". | Java 7 | standard input | [
"implementation",
"strings"
] | ad02cead427d0765eb642203d13d3b99 | The only line of input contains the string s (1ββ€β|s|ββ€β105). The string contains only symbols '.' (ASCII 46), ',' (ASCII 44), ';' (ASCII 59), digits, lowercase and uppercase latin letters. | 1,600 | Print the string a to the first line and string b to the second line. Each string should be surrounded by quotes (ASCII 34). If there are no words that are numbers print dash (ASCII 45) on the first line. If all words are numbers print dash on the second line. | standard output | |
PASSED | ea0077733ddbad8d1b1ef2bd8881e9f5 | train_004.jsonl | 1448636400 | You are given string s. Let's call word any largest sequence of consecutive symbols without symbols ',' (comma) and ';' (semicolon). For example, there are four words in string "aba,123;1a;0": "aba", "123", "1a", "0". A word can be empty: for example, the string s=";;" contains three empty words separated by ';'.You should find all words in the given string that are nonnegative INTEGER numbers without leading zeroes and build by them new string a. String a should contain all words that are numbers separating them by ',' (the order of numbers should remain the same as in the string s). By all other words you should build string b in the same way (the order of numbers should remain the same as in the string s).Here strings "101", "0" are INTEGER numbers, but "01" and "1.0" are not.For example, for the string aba,123;1a;0 the string a would be equal to "123,0" and string b would be equal to "aba,1a". | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class ProblemA {
private static final String digits = "0123456789";
public static void main(String[] args) {
InputReader in = new InputReader();
PrintWriter out = new PrintWriter(System.out);
new ProblemA().solve(in, out);
out.close();
}
public void solve(InputReader in, PrintWriter out) {
String s = in.nextLine();
s += ";";
StringBuilder a = new StringBuilder();
StringBuilder b = new StringBuilder();
StringBuilder word = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == ',' || s.charAt(i) == ';') {
if (isInteger(word.toString())) {
a.append(word);
a.append(",");
} else {
b.append(word);
b.append(",");
}
word = new StringBuilder();
} else {
word.append(s.charAt(i));
}
}
if (a.length() > 0) {
a.deleteCharAt(a.length() - 1);
out.println("\"" + a.toString() + "\"");
} else {
out.println("-");
}
if (b.length() > 0) {
b.deleteCharAt(b.length() - 1);
out.println("\"" + b.toString() + "\"");
} else {
out.println("-");
}
}
private static boolean isInteger(String s) {
int n = s.length();
if (n == 0) {
return false;
}
if (s.startsWith("0")) {
if (s.length() == 1) {
return true;
} else {
return false;
}
}
for (int i = 0; i < n; i++) {
if (digits.indexOf(s.charAt(i)) < 0) {
return false;
}
}
return true;
}
static class InputReader {
public BufferedReader br;
public StringTokenizer st;
public InputReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
| Java | ["aba,123;1a;0", "1;;01,a0,", "1", "a"] | 2 seconds | ["\"123,0\"\n\"aba,1a\"", "\"1\"\n\",01,a0,\"", "\"1\"\n-", "-\n\"a\""] | NoteIn the second example the string s contains five words: "1", "", "01", "a0", "". | Java 7 | standard input | [
"implementation",
"strings"
] | ad02cead427d0765eb642203d13d3b99 | The only line of input contains the string s (1ββ€β|s|ββ€β105). The string contains only symbols '.' (ASCII 46), ',' (ASCII 44), ';' (ASCII 59), digits, lowercase and uppercase latin letters. | 1,600 | Print the string a to the first line and string b to the second line. Each string should be surrounded by quotes (ASCII 34). If there are no words that are numbers print dash (ASCII 45) on the first line. If all words are numbers print dash on the second line. | standard output | |
PASSED | d515fa2f7b705ad6a1c5da857d118737 | train_004.jsonl | 1448636400 | You are given string s. Let's call word any largest sequence of consecutive symbols without symbols ',' (comma) and ';' (semicolon). For example, there are four words in string "aba,123;1a;0": "aba", "123", "1a", "0". A word can be empty: for example, the string s=";;" contains three empty words separated by ';'.You should find all words in the given string that are nonnegative INTEGER numbers without leading zeroes and build by them new string a. String a should contain all words that are numbers separating them by ',' (the order of numbers should remain the same as in the string s). By all other words you should build string b in the same way (the order of numbers should remain the same as in the string s).Here strings "101", "0" are INTEGER numbers, but "01" and "1.0" are not.For example, for the string aba,123;1a;0 the string a would be equal to "123,0" and string b would be equal to "aba,1a". | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.ArrayList;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author George Marcus
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
static class TaskA {
public void solve(int testNumber, InputReader in, PrintWriter out) {
String S = in.readString();
String[] tokens = S.split("[,;]", -1);
ArrayList<String> A = new ArrayList<>();
ArrayList<String> B = new ArrayList<>();
for (String token : tokens) {
if (isNumber(token)) {
A.add(token);
} else {
B.add(token);
}
}
printList(A, out);
printList(B, out);
}
private boolean isNumber(String s) {
if (s.length() == 0) {
return false;
}
if (s.charAt(0) == '0' && s.length() > 1) {
return false;
}
for (int i = 0; i < s.length(); i++) {
if (!Character.isDigit(s.charAt(i))) {
return false;
}
}
return true;
}
private void printList(ArrayList<String> A, PrintWriter out) {
if (A.size() == 0) {
out.println("-");
return;
}
StringBuilder sb = new StringBuilder();
sb.append("\"");
boolean first = true;
for (String s : A) {
if (!first) {
sb.append(',');
}
first = false;
sb.append(s);
}
sb.append("\"");
out.println(sb.toString());
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public String readString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
if (Character.isValidCodePoint(c))
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
| Java | ["aba,123;1a;0", "1;;01,a0,", "1", "a"] | 2 seconds | ["\"123,0\"\n\"aba,1a\"", "\"1\"\n\",01,a0,\"", "\"1\"\n-", "-\n\"a\""] | NoteIn the second example the string s contains five words: "1", "", "01", "a0", "". | Java 7 | standard input | [
"implementation",
"strings"
] | ad02cead427d0765eb642203d13d3b99 | The only line of input contains the string s (1ββ€β|s|ββ€β105). The string contains only symbols '.' (ASCII 46), ',' (ASCII 44), ';' (ASCII 59), digits, lowercase and uppercase latin letters. | 1,600 | Print the string a to the first line and string b to the second line. Each string should be surrounded by quotes (ASCII 34). If there are no words that are numbers print dash (ASCII 45) on the first line. If all words are numbers print dash on the second line. | standard output | |
PASSED | 50550f4c11df196356c4297439369f5e | train_004.jsonl | 1448636400 | You are given string s. Let's call word any largest sequence of consecutive symbols without symbols ',' (comma) and ';' (semicolon). For example, there are four words in string "aba,123;1a;0": "aba", "123", "1a", "0". A word can be empty: for example, the string s=";;" contains three empty words separated by ';'.You should find all words in the given string that are nonnegative INTEGER numbers without leading zeroes and build by them new string a. String a should contain all words that are numbers separating them by ',' (the order of numbers should remain the same as in the string s). By all other words you should build string b in the same way (the order of numbers should remain the same as in the string s).Here strings "101", "0" are INTEGER numbers, but "01" and "1.0" are not.For example, for the string aba,123;1a;0 the string a would be equal to "123,0" and string b would be equal to "aba,1a". | 256 megabytes | import java.util.*;
import java.io.*;
public class ExtractNumbers600A
{
public static class MyFasterScanner
{
BufferedReader br;
StringTokenizer st;
public MyFasterScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine(){
String str="";
try {
str = br.readLine().toString();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
public static int findCommaOrSemi(int currentstart, String s)
{
int i = currentstart;
while (i < s.length())
{
if (s.charAt(i) == ',' || s.charAt(i) == ';')
{
return i;
}
else
{
i++;
}
}
return -1;
}
public static void main(String[] args)
{
// Set up scanner
MyFasterScanner sc = new MyFasterScanner();
// System.out.println("Enter the string");
String s = sc.next();
StringBuilder lineone = new StringBuilder();
StringBuilder linetwo = new StringBuilder();
lineone.append("\"");
linetwo.append("\"");
int currentstart = 0;
// int comma = s.indexOf(',', currentstart);
// int semi = s.indexOf(';', currentstart);
int nextdivide = findCommaOrSemi(currentstart, s);
while (nextdivide >= 0)
{
String nextstring = s.substring(currentstart, nextdivide);
currentstart = nextdivide+1;
nextdivide = findCommaOrSemi(currentstart, s);
boolean isNumber = true;
for (int i=0; i<nextstring.length(); i++)
{
char next = nextstring.charAt(i);
if (i == 0)
{
if (next < '1' || next > '9')
{
isNumber = false;
break;
}
}
else
{
if (next < '0' || next > '9')
{
isNumber = false;
break;
}
}
}
if ((isNumber && nextstring.length() > 0) || nextstring.equals("0"))
{
lineone.append(nextstring + ",");
}
else
{
linetwo.append(nextstring + ",");
}
}
// Process the last one, after all separators
boolean isNumber = true;
s = s.substring(currentstart);
for (int i=0; i<s.length(); i++)
{
char next = s.charAt(i);
if (i == 0)
{
if (next < '1' || next > '9')
{
isNumber = false;
break;
}
}
else
{
if (next < '0' || next > '9')
{
isNumber = false;
break;
}
}
}
if ((isNumber && s.length() > 0) || s.equals("0"))
{
lineone.append(s + ",");
}
else
{
linetwo.append(s + ",");
}
String answerone = "";
String answertwo = "";
if (lineone.length() == 1 && lineone.charAt(0) == '"')
{
answerone = "-";
}
else
{
lineone.deleteCharAt(lineone.length() - 1);
lineone.append("\"");
answerone = lineone.toString();
// answerone = answerone.substring(0, answerone.length() -1) + "\"";
}
if (linetwo.length() == 1 && linetwo.charAt(0) == '"')
{
answertwo = "-";
}
else
{
linetwo.deleteCharAt(linetwo.length() - 1);
linetwo.append("\"");
answertwo = linetwo.toString();
// answertwo = answertwo.substring(0, answertwo.length() -1) + "\"";
}
System.out.println(answerone);
System.out.println(answertwo);
}
}
| Java | ["aba,123;1a;0", "1;;01,a0,", "1", "a"] | 2 seconds | ["\"123,0\"\n\"aba,1a\"", "\"1\"\n\",01,a0,\"", "\"1\"\n-", "-\n\"a\""] | NoteIn the second example the string s contains five words: "1", "", "01", "a0", "". | Java 7 | standard input | [
"implementation",
"strings"
] | ad02cead427d0765eb642203d13d3b99 | The only line of input contains the string s (1ββ€β|s|ββ€β105). The string contains only symbols '.' (ASCII 46), ',' (ASCII 44), ';' (ASCII 59), digits, lowercase and uppercase latin letters. | 1,600 | Print the string a to the first line and string b to the second line. Each string should be surrounded by quotes (ASCII 34). If there are no words that are numbers print dash (ASCII 45) on the first line. If all words are numbers print dash on the second line. | standard output | |
PASSED | 54faee20c79b499aa7449c357640ea4f | train_004.jsonl | 1448636400 | You are given string s. Let's call word any largest sequence of consecutive symbols without symbols ',' (comma) and ';' (semicolon). For example, there are four words in string "aba,123;1a;0": "aba", "123", "1a", "0". A word can be empty: for example, the string s=";;" contains three empty words separated by ';'.You should find all words in the given string that are nonnegative INTEGER numbers without leading zeroes and build by them new string a. String a should contain all words that are numbers separating them by ',' (the order of numbers should remain the same as in the string s). By all other words you should build string b in the same way (the order of numbers should remain the same as in the string s).Here strings "101", "0" are INTEGER numbers, but "01" and "1.0" are not.For example, for the string aba,123;1a;0 the string a would be equal to "123,0" and string b would be equal to "aba,1a". | 256 megabytes | //package educationalRound2;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class ExtractNumbers {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = br.readLine();
StringBuilder a = new StringBuilder();
StringBuilder b = new StringBuilder();
StringBuilder sb = new StringBuilder();
for (int i =0 ;i<line.length();i++) {
if (line.charAt(i)==';'|| line.charAt(i)==','){
String p = sb.toString();
boolean allDigits = true;
for (int j = 0; j < p.length(); j++) {
if (!Character.isDigit(p.charAt(j))) {
allDigits = false;
break;
}
}
if (allDigits && p.length()>0 && (p.charAt(0)!='0' || p.length()==1)) {
a.append(p + ",");
} else {
b.append(p + ",");
}
sb = new StringBuilder();
}
else{
sb.append(line.charAt(i));
}
}
String p = sb.toString();
boolean allDigits = true;
for (int j = 0; j < p.length(); j++) {
if (!Character.isDigit(p.charAt(j))) {
allDigits = false;
break;
}
}
if (allDigits && p.length()>0 && (p.charAt(0)!='0' || p.length()==1)) {
a.append(p + ",");
} else {
b.append(p + ",");
}
if (a.length() > 0) {
System.out.println("\""+a.substring(0, a.length() - 1).toString()+"\"");
}
else{
System.out.println("-");
}
if (b.length() > 0){
System.out.println("\""+b.substring(0, b.length() - 1).toString()+"\"");
}
else{
System.out.println("-");
}
}
}
| Java | ["aba,123;1a;0", "1;;01,a0,", "1", "a"] | 2 seconds | ["\"123,0\"\n\"aba,1a\"", "\"1\"\n\",01,a0,\"", "\"1\"\n-", "-\n\"a\""] | NoteIn the second example the string s contains five words: "1", "", "01", "a0", "". | Java 7 | standard input | [
"implementation",
"strings"
] | ad02cead427d0765eb642203d13d3b99 | The only line of input contains the string s (1ββ€β|s|ββ€β105). The string contains only symbols '.' (ASCII 46), ',' (ASCII 44), ';' (ASCII 59), digits, lowercase and uppercase latin letters. | 1,600 | Print the string a to the first line and string b to the second line. Each string should be surrounded by quotes (ASCII 34). If there are no words that are numbers print dash (ASCII 45) on the first line. If all words are numbers print dash on the second line. | standard output | |
PASSED | 381fac14d37df6c8e31383e75085493f | train_004.jsonl | 1448636400 | You are given string s. Let's call word any largest sequence of consecutive symbols without symbols ',' (comma) and ';' (semicolon). For example, there are four words in string "aba,123;1a;0": "aba", "123", "1a", "0". A word can be empty: for example, the string s=";;" contains three empty words separated by ';'.You should find all words in the given string that are nonnegative INTEGER numbers without leading zeroes and build by them new string a. String a should contain all words that are numbers separating them by ',' (the order of numbers should remain the same as in the string s). By all other words you should build string b in the same way (the order of numbers should remain the same as in the string s).Here strings "101", "0" are INTEGER numbers, but "01" and "1.0" are not.For example, for the string aba,123;1a;0 the string a would be equal to "123,0" and string b would be equal to "aba,1a". | 256 megabytes | import java.util.List;
import java.io.BufferedReader;
import java.util.ArrayList;
import java.io.IOException;
import java.io.InputStreamReader;
public class A {
public static List<String> getWords(String str) {
List<String> arr = new ArrayList<String>();
StringBuilder currWord = new StringBuilder();
for(int i=0; i<str.length(); i++) {
if(str.charAt(i) == ',' || str.charAt(i) == ';') {
arr.add(currWord.toString());
currWord = new StringBuilder();
} else {
currWord.append(str.charAt(i));
}
}
arr.add(currWord.toString());
return arr;
}
public static boolean isNumber(String word) {
if(word.length() == 0) return false;
if(word.length() > 1 && word.charAt(0) == '0') return false;
for(int i=0; i<word.length(); i++) {
if( '0' <= word.charAt(i) && word.charAt(i) <= '9') continue;
return false;
}
return true;
}
public static void solve(String str) {
List<String> words = getWords(str);
List<String> numbers = new ArrayList<String>();
List<String> others = new ArrayList<String>();
for(int i=0; i<words.size(); i++) {
if(isNumber(words.get(i))) {
numbers.add(words.get(i));
} else {
others.add(words.get(i));
}
}
StringBuilder sb1 = new StringBuilder();
StringBuilder sb2 = new StringBuilder();
boolean hasOne = false;
boolean hasTwo = false;
for(int i=0; i<numbers.size(); i++) {
hasOne = true;
sb1.append(numbers.get(i));
if(i < numbers.size() - 1) sb1.append(',');
}
for(int i=0; i<others.size(); i++) {
hasTwo = true;
sb2.append(others.get(i));
if(i < others.size() - 1) sb2.append(',');
}
if(hasOne)
System.out.println("\"" + sb1.toString() + "\"");
else
System.out.println("-");
if(hasTwo)
System.out.println("\"" + sb2.toString() + "\"");
else
System.out.println("-");
}
public static void main(String [] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str = br.readLine();
solve(str);
}
} | Java | ["aba,123;1a;0", "1;;01,a0,", "1", "a"] | 2 seconds | ["\"123,0\"\n\"aba,1a\"", "\"1\"\n\",01,a0,\"", "\"1\"\n-", "-\n\"a\""] | NoteIn the second example the string s contains five words: "1", "", "01", "a0", "". | Java 7 | standard input | [
"implementation",
"strings"
] | ad02cead427d0765eb642203d13d3b99 | The only line of input contains the string s (1ββ€β|s|ββ€β105). The string contains only symbols '.' (ASCII 46), ',' (ASCII 44), ';' (ASCII 59), digits, lowercase and uppercase latin letters. | 1,600 | Print the string a to the first line and string b to the second line. Each string should be surrounded by quotes (ASCII 34). If there are no words that are numbers print dash (ASCII 45) on the first line. If all words are numbers print dash on the second line. | standard output | |
PASSED | 9e93f092e782b4430e178a1faf43b777 | train_004.jsonl | 1587479700 | Recall that the sequence $$$b$$$ is a a subsequence of the sequence $$$a$$$ if $$$b$$$ can be derived from $$$a$$$ by removing zero or more elements without changing the order of the remaining elements. For example, if $$$a=[1, 2, 1, 3, 1, 2, 1]$$$, then possible subsequences are: $$$[1, 1, 1, 1]$$$, $$$[3]$$$ and $$$[1, 2, 1, 3, 1, 2, 1]$$$, but not $$$[3, 2, 3]$$$ and $$$[1, 1, 1, 1, 2]$$$.You are given a sequence $$$a$$$ consisting of $$$n$$$ positive and negative elements (there is no zeros in the sequence).Your task is to choose maximum by size (length) alternating subsequence of the given sequence (i.e. the sign of each next element is the opposite from the sign of the current element, like positive-negative-positive and so on or negative-positive-negative and so on). Among all such subsequences, you have to choose one which has the maximum sum of elements.In other words, if the maximum length of alternating subsequence is $$$k$$$ then your task is to find the maximum sum of elements of some alternating subsequence of length $$$k$$$.You have to answer $$$t$$$ independent test cases. | 256 megabytes | import java.util.*;
import java.lang.*;
public class Main
{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t= sc.nextInt();
while(t-->0){
int n = sc.nextInt();
long sum = 0;
int max = 0;
int min = 0;
int a[] = new int[n];
for(int i=0;i<n;i++){
a[i]=sc.nextInt();
}
int j = 0;
while(j<n){
while(a[j]>0&&j<n){
max = Math.max(max,a[j]);
j++;
if(j==n) break;
}
sum = sum + max;
max =-1000000007;
if(j==n) break;
while(a[j]<0&&j<n){
max = Math.max(max,a[j]);
j++;
if(j==n) break;
}
sum = sum + max;
max =0;
}
System.out.println(sum);
}
}
}
| Java | ["4\n5\n1 2 3 -1 -2\n4\n-1 -2 -1 -3\n10\n-2 8 3 8 -4 -15 5 -2 -3 1\n6\n1 -1000000000 1 -1000000000 1 -1000000000"] | 1 second | ["2\n-1\n6\n-2999999997"] | NoteIn the first test case of the example, one of the possible answers is $$$[1, 2, \underline{3}, \underline{-1}, -2]$$$.In the second test case of the example, one of the possible answers is $$$[-1, -2, \underline{-1}, -3]$$$.In the third test case of the example, one of the possible answers is $$$[\underline{-2}, 8, 3, \underline{8}, \underline{-4}, -15, \underline{5}, \underline{-2}, -3, \underline{1}]$$$.In the fourth test case of the example, one of the possible answers is $$$[\underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}]$$$. | Java 11 | standard input | [
"dp",
"two pointers",
"greedy"
] | 39480cdf697fc9743dc9665f989077d7 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) β the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β the number of elements in $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \le a_i \le 10^9, a_i \ne 0$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$). | 1,200 | For each test case, print the answer β the maximum sum of the maximum by size (length) alternating subsequence of $$$a$$$. | standard output | |
PASSED | dd51451640d0afe9407130c4a70a0f4e | train_004.jsonl | 1587479700 | Recall that the sequence $$$b$$$ is a a subsequence of the sequence $$$a$$$ if $$$b$$$ can be derived from $$$a$$$ by removing zero or more elements without changing the order of the remaining elements. For example, if $$$a=[1, 2, 1, 3, 1, 2, 1]$$$, then possible subsequences are: $$$[1, 1, 1, 1]$$$, $$$[3]$$$ and $$$[1, 2, 1, 3, 1, 2, 1]$$$, but not $$$[3, 2, 3]$$$ and $$$[1, 1, 1, 1, 2]$$$.You are given a sequence $$$a$$$ consisting of $$$n$$$ positive and negative elements (there is no zeros in the sequence).Your task is to choose maximum by size (length) alternating subsequence of the given sequence (i.e. the sign of each next element is the opposite from the sign of the current element, like positive-negative-positive and so on or negative-positive-negative and so on). Among all such subsequences, you have to choose one which has the maximum sum of elements.In other words, if the maximum length of alternating subsequence is $$$k$$$ then your task is to find the maximum sum of elements of some alternating subsequence of length $$$k$$$.You have to answer $$$t$$$ independent test cases. | 256 megabytes | import java.util.Scanner;
public class Codeforces{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
int t = Integer.parseInt(in.nextLine());
for(int j=0; j<t; j++){
int n = Integer.parseInt(in.nextLine());
String[] x = in.nextLine().split(" ");
long[] num = new long[n];
boolean neg = false, p = false;
long altMax = Integer.MIN_VALUE;
for(int i=0; i<n; i++){
num[i] = Integer.parseInt(x[i]);
if(num[i]>altMax) altMax = num[i];
if(num[i]>0) p=true;
else if(num[i]<0) neg = true;
}
if(!p || !neg) {
System.out.println(altMax);
continue;
}
long max = num[0];
long sum=0;
for(int i=1; i<n; i++){
if(num[i-1]*num[i]>0) max = num[i]>max?num[i]:max;
else{
sum+=max;
max=num[i];
}
}
System.out.println(sum+max);
}
}
} | Java | ["4\n5\n1 2 3 -1 -2\n4\n-1 -2 -1 -3\n10\n-2 8 3 8 -4 -15 5 -2 -3 1\n6\n1 -1000000000 1 -1000000000 1 -1000000000"] | 1 second | ["2\n-1\n6\n-2999999997"] | NoteIn the first test case of the example, one of the possible answers is $$$[1, 2, \underline{3}, \underline{-1}, -2]$$$.In the second test case of the example, one of the possible answers is $$$[-1, -2, \underline{-1}, -3]$$$.In the third test case of the example, one of the possible answers is $$$[\underline{-2}, 8, 3, \underline{8}, \underline{-4}, -15, \underline{5}, \underline{-2}, -3, \underline{1}]$$$.In the fourth test case of the example, one of the possible answers is $$$[\underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}]$$$. | Java 11 | standard input | [
"dp",
"two pointers",
"greedy"
] | 39480cdf697fc9743dc9665f989077d7 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) β the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β the number of elements in $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \le a_i \le 10^9, a_i \ne 0$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$). | 1,200 | For each test case, print the answer β the maximum sum of the maximum by size (length) alternating subsequence of $$$a$$$. | standard output | |
PASSED | 5f377546c77f91cb610df20df70dd3b3 | train_004.jsonl | 1587479700 | Recall that the sequence $$$b$$$ is a a subsequence of the sequence $$$a$$$ if $$$b$$$ can be derived from $$$a$$$ by removing zero or more elements without changing the order of the remaining elements. For example, if $$$a=[1, 2, 1, 3, 1, 2, 1]$$$, then possible subsequences are: $$$[1, 1, 1, 1]$$$, $$$[3]$$$ and $$$[1, 2, 1, 3, 1, 2, 1]$$$, but not $$$[3, 2, 3]$$$ and $$$[1, 1, 1, 1, 2]$$$.You are given a sequence $$$a$$$ consisting of $$$n$$$ positive and negative elements (there is no zeros in the sequence).Your task is to choose maximum by size (length) alternating subsequence of the given sequence (i.e. the sign of each next element is the opposite from the sign of the current element, like positive-negative-positive and so on or negative-positive-negative and so on). Among all such subsequences, you have to choose one which has the maximum sum of elements.In other words, if the maximum length of alternating subsequence is $$$k$$$ then your task is to find the maximum sum of elements of some alternating subsequence of length $$$k$$$.You have to answer $$$t$$$ independent test cases. | 256 megabytes | //package div3.c1343;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.StringTokenizer;
import java.util.stream.Collectors;
public class ProbC {
public static void main(String[] args) {
MyScanner sc = new MyScanner();
out = new PrintWriter(new BufferedOutputStream(System.out));
var t = sc.nextInt();
for (int i = 0; i < t; i++) {
var n = sc.nextInt();
var arr = new ArrayList<Integer>(n);
for (int j = 0; j < n; j++) {
arr.add(sc.nextInt());
}
process(arr);
}
out.close();
}
private static void process(ArrayList<Integer> arr) {
int localOptima = Integer.MIN_VALUE;
var subsequence = new ArrayList<Integer>();
int runningFlag = getFlag(arr.get(0));
for (int i = 0; i < arr.size(); i++) {
if(getFlag(arr.get(i)) == runningFlag) {
localOptima = getNewLocalOptima(arr.get(i), localOptima);
}
else {
subsequence.add(localOptima);
localOptima = arr.get(i);
runningFlag = getFlag(arr.get(i));
}
}
subsequence.add(localOptima);
//out.println(subsequence.stream().map(String::valueOf).collect(Collectors.joining(" ")));
out.println(subsequence.stream().map(i -> (long)i).reduce(0L, Long::sum));
}
private static int getNewLocalOptima(Integer x, int localOptima) {
return x>localOptima ? x : localOptima;
}
private static int getFlag(int x) {
return x > 0 ? 1 : -1;
}
//-----------PrintWriter for faster output---------------------------------
public static PrintWriter out;
//-----------MyScanner class for faster input----------
public static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine(){
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
//--------------------------------------------------------
}
| Java | ["4\n5\n1 2 3 -1 -2\n4\n-1 -2 -1 -3\n10\n-2 8 3 8 -4 -15 5 -2 -3 1\n6\n1 -1000000000 1 -1000000000 1 -1000000000"] | 1 second | ["2\n-1\n6\n-2999999997"] | NoteIn the first test case of the example, one of the possible answers is $$$[1, 2, \underline{3}, \underline{-1}, -2]$$$.In the second test case of the example, one of the possible answers is $$$[-1, -2, \underline{-1}, -3]$$$.In the third test case of the example, one of the possible answers is $$$[\underline{-2}, 8, 3, \underline{8}, \underline{-4}, -15, \underline{5}, \underline{-2}, -3, \underline{1}]$$$.In the fourth test case of the example, one of the possible answers is $$$[\underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}]$$$. | Java 11 | standard input | [
"dp",
"two pointers",
"greedy"
] | 39480cdf697fc9743dc9665f989077d7 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) β the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β the number of elements in $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \le a_i \le 10^9, a_i \ne 0$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$). | 1,200 | For each test case, print the answer β the maximum sum of the maximum by size (length) alternating subsequence of $$$a$$$. | standard output | |
PASSED | 80fd29540d0944e8fabfe9447ffed2a8 | train_004.jsonl | 1587479700 | Recall that the sequence $$$b$$$ is a a subsequence of the sequence $$$a$$$ if $$$b$$$ can be derived from $$$a$$$ by removing zero or more elements without changing the order of the remaining elements. For example, if $$$a=[1, 2, 1, 3, 1, 2, 1]$$$, then possible subsequences are: $$$[1, 1, 1, 1]$$$, $$$[3]$$$ and $$$[1, 2, 1, 3, 1, 2, 1]$$$, but not $$$[3, 2, 3]$$$ and $$$[1, 1, 1, 1, 2]$$$.You are given a sequence $$$a$$$ consisting of $$$n$$$ positive and negative elements (there is no zeros in the sequence).Your task is to choose maximum by size (length) alternating subsequence of the given sequence (i.e. the sign of each next element is the opposite from the sign of the current element, like positive-negative-positive and so on or negative-positive-negative and so on). Among all such subsequences, you have to choose one which has the maximum sum of elements.In other words, if the maximum length of alternating subsequence is $$$k$$$ then your task is to find the maximum sum of elements of some alternating subsequence of length $$$k$$$.You have to answer $$$t$$$ independent test cases. | 256 megabytes | import java.io.*;
import java.lang.reflect.Array;
import java.util.*;
public class Main {
static Long max = (long) (2 * 10E5);
private static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
private static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
static Long[] readLongArray() throws IOException {
return Arrays.stream(br.readLine().split("\\s+")).map(Long::parseLong).toArray(Long[]::new);
}
static Integer[] readIntArray() throws IOException {
return Arrays.stream(br.readLine().split("\\s+")).map(Integer::parseInt).toArray(Integer[]::new);
}
static int readInt() throws IOException {
return Integer.parseInt(br.readLine());
}
static long readLong() throws IOException {
return Long.parseLong(br.readLine());
}
static boolean oppositeSigns(long x, long y) {
return ((x ^ y) < 0);
}
public static void main(String[] args) throws IOException {
Scanner scanner = new Scanner(System.in);
int _t = scanner.nextInt();
for (int t = 0; t < _t; t++) {
int n = scanner.nextInt();
long[] a = new long[n];
int pos = -1, neg = -1;
for (int i = 0; i < n && i >= 0; i++) {
a[i] = scanner.nextLong();
if (pos < 0 && a[i] >= 0)
pos = i;
if (neg < 0 && a[i] < 0)
neg = i;
}
long sumPos = 0;
long lenPos = 1;
long currentMaxPos = a[0];
for (int i = pos; i < n && i >= 0; i++) {
if (i > pos && oppositeSigns(a[i - 1], a[i])){
sumPos += currentMaxPos;
currentMaxPos = a[i];
lenPos += 1;
} else {
currentMaxPos = Math.max(currentMaxPos, a[i]);
}
}
sumPos += currentMaxPos;
long sumNeg = 0;
long lenNeg = 1;
long currentMaxNeg = a[0];
for (int i = neg; i < n && i >= 0; i++) {
if (i > neg && (oppositeSigns(a[i - 1], a[i]))){
sumNeg += currentMaxNeg;
currentMaxNeg = a[i];
lenNeg += 1;
} else {
currentMaxNeg = Math.max(currentMaxNeg, a[i]);
}
}
sumNeg += currentMaxNeg;
if (neg < 0){
lenNeg = 0;
}
if (pos < 0){
lenPos = 0;
}
if (lenPos == lenNeg){
System.out.println(Math.max(sumNeg, sumPos));
} else if (lenPos > lenNeg){
System.out.println(sumPos);
} else {
System.out.println(sumNeg);
}
}
}
}
| Java | ["4\n5\n1 2 3 -1 -2\n4\n-1 -2 -1 -3\n10\n-2 8 3 8 -4 -15 5 -2 -3 1\n6\n1 -1000000000 1 -1000000000 1 -1000000000"] | 1 second | ["2\n-1\n6\n-2999999997"] | NoteIn the first test case of the example, one of the possible answers is $$$[1, 2, \underline{3}, \underline{-1}, -2]$$$.In the second test case of the example, one of the possible answers is $$$[-1, -2, \underline{-1}, -3]$$$.In the third test case of the example, one of the possible answers is $$$[\underline{-2}, 8, 3, \underline{8}, \underline{-4}, -15, \underline{5}, \underline{-2}, -3, \underline{1}]$$$.In the fourth test case of the example, one of the possible answers is $$$[\underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}]$$$. | Java 11 | standard input | [
"dp",
"two pointers",
"greedy"
] | 39480cdf697fc9743dc9665f989077d7 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) β the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β the number of elements in $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \le a_i \le 10^9, a_i \ne 0$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$). | 1,200 | For each test case, print the answer β the maximum sum of the maximum by size (length) alternating subsequence of $$$a$$$. | standard output | |
PASSED | 0159b7c2e8ea49b2f727b36e465996ba | train_004.jsonl | 1587479700 | Recall that the sequence $$$b$$$ is a a subsequence of the sequence $$$a$$$ if $$$b$$$ can be derived from $$$a$$$ by removing zero or more elements without changing the order of the remaining elements. For example, if $$$a=[1, 2, 1, 3, 1, 2, 1]$$$, then possible subsequences are: $$$[1, 1, 1, 1]$$$, $$$[3]$$$ and $$$[1, 2, 1, 3, 1, 2, 1]$$$, but not $$$[3, 2, 3]$$$ and $$$[1, 1, 1, 1, 2]$$$.You are given a sequence $$$a$$$ consisting of $$$n$$$ positive and negative elements (there is no zeros in the sequence).Your task is to choose maximum by size (length) alternating subsequence of the given sequence (i.e. the sign of each next element is the opposite from the sign of the current element, like positive-negative-positive and so on or negative-positive-negative and so on). Among all such subsequences, you have to choose one which has the maximum sum of elements.In other words, if the maximum length of alternating subsequence is $$$k$$$ then your task is to find the maximum sum of elements of some alternating subsequence of length $$$k$$$.You have to answer $$$t$$$ independent test cases. | 256 megabytes | import java.io.*;
import java.lang.reflect.Array;
import java.util.*;
public class Main {
static Long max = (long) (2 * 10E5);
private static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
private static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
static Long[] readLongArray() throws IOException {
return Arrays.stream(br.readLine().split("\\s+")).map(Long::parseLong).toArray(Long[]::new);
}
static Integer[] readIntArray() throws IOException {
return Arrays.stream(br.readLine().split("\\s+")).map(Integer::parseInt).toArray(Integer[]::new);
}
static int readInt() throws IOException {
return Integer.parseInt(br.readLine());
}
static long readLong() throws IOException {
return Long.parseLong(br.readLine());
}
static boolean oppositeSigns(long x, long y) {
return ((x ^ y) < 0);
}
static long[] count(long[] a, int i) {
long sum = 0, currentMax = Long.MIN_VALUE, len = (i >= 0) ? 1 : 0;
for (int j = i; j < a.length && j >= 0; j++) {
if (j > i && oppositeSigns(a[j - 1], a[j])) {
sum += currentMax;
currentMax = a[j];
len += 1;
} else
currentMax = Math.max(currentMax, a[j]);
}
sum += currentMax;
return new long[]{len, sum};
}
public static void main(String[] args) throws IOException {
Scanner scanner = new Scanner(System.in);
int _t = scanner.nextInt();
for (int t = 0; t < _t; t++) {
int n = scanner.nextInt();
long[] a = new long[n];
int pos = -1, neg = -1;
for (int i = 0; i < n && i >= 0; i++) {
a[i] = scanner.nextLong();
if (pos < 0 && a[i] >= 0)
pos = i;
if (neg < 0 && a[i] < 0)
neg = i;
}
long[] resNeg = count(a, neg);
long[] resPos = count(a, pos);
if (resPos[0] == resNeg[0]) {
System.out.println(Math.max(resPos[1], resNeg[1]));
} else if (resPos[0] > resNeg[0]) {
System.out.println(resPos[1]);
} else {
System.out.println(resNeg[1]);
}
}
}
}
| Java | ["4\n5\n1 2 3 -1 -2\n4\n-1 -2 -1 -3\n10\n-2 8 3 8 -4 -15 5 -2 -3 1\n6\n1 -1000000000 1 -1000000000 1 -1000000000"] | 1 second | ["2\n-1\n6\n-2999999997"] | NoteIn the first test case of the example, one of the possible answers is $$$[1, 2, \underline{3}, \underline{-1}, -2]$$$.In the second test case of the example, one of the possible answers is $$$[-1, -2, \underline{-1}, -3]$$$.In the third test case of the example, one of the possible answers is $$$[\underline{-2}, 8, 3, \underline{8}, \underline{-4}, -15, \underline{5}, \underline{-2}, -3, \underline{1}]$$$.In the fourth test case of the example, one of the possible answers is $$$[\underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}]$$$. | Java 11 | standard input | [
"dp",
"two pointers",
"greedy"
] | 39480cdf697fc9743dc9665f989077d7 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) β the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β the number of elements in $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \le a_i \le 10^9, a_i \ne 0$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$). | 1,200 | For each test case, print the answer β the maximum sum of the maximum by size (length) alternating subsequence of $$$a$$$. | standard output | |
PASSED | 602906d230b36d891c4c1ce68bcd840a | train_004.jsonl | 1587479700 | Recall that the sequence $$$b$$$ is a a subsequence of the sequence $$$a$$$ if $$$b$$$ can be derived from $$$a$$$ by removing zero or more elements without changing the order of the remaining elements. For example, if $$$a=[1, 2, 1, 3, 1, 2, 1]$$$, then possible subsequences are: $$$[1, 1, 1, 1]$$$, $$$[3]$$$ and $$$[1, 2, 1, 3, 1, 2, 1]$$$, but not $$$[3, 2, 3]$$$ and $$$[1, 1, 1, 1, 2]$$$.You are given a sequence $$$a$$$ consisting of $$$n$$$ positive and negative elements (there is no zeros in the sequence).Your task is to choose maximum by size (length) alternating subsequence of the given sequence (i.e. the sign of each next element is the opposite from the sign of the current element, like positive-negative-positive and so on or negative-positive-negative and so on). Among all such subsequences, you have to choose one which has the maximum sum of elements.In other words, if the maximum length of alternating subsequence is $$$k$$$ then your task is to find the maximum sum of elements of some alternating subsequence of length $$$k$$$.You have to answer $$$t$$$ independent test cases. | 256 megabytes |
import java.util.* ;
public class Subsequences {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in) ;
int t = sc.nextInt();
for(int i = 0 ; i < t ; i++) {
int p = sc.nextInt();
long sum = 0;
ArrayList<Long> num = new ArrayList<Long>();
long x ;
for(int j = 0; j< p ; j++) {
x = sc.nextLong() ;
if( num.isEmpty()) {
num.add(x);
}
else if( x*(num.get(num.size() - 1)) > 0 ) {
num.set(num.size()-1, (long) Math.max(x, num.get(num.size() - 1))) ;
}
else { num.add(x) ;}
}
for(long k: num) {
sum = sum + k ;
}
System.out.println(sum);
}
}
}
| Java | ["4\n5\n1 2 3 -1 -2\n4\n-1 -2 -1 -3\n10\n-2 8 3 8 -4 -15 5 -2 -3 1\n6\n1 -1000000000 1 -1000000000 1 -1000000000"] | 1 second | ["2\n-1\n6\n-2999999997"] | NoteIn the first test case of the example, one of the possible answers is $$$[1, 2, \underline{3}, \underline{-1}, -2]$$$.In the second test case of the example, one of the possible answers is $$$[-1, -2, \underline{-1}, -3]$$$.In the third test case of the example, one of the possible answers is $$$[\underline{-2}, 8, 3, \underline{8}, \underline{-4}, -15, \underline{5}, \underline{-2}, -3, \underline{1}]$$$.In the fourth test case of the example, one of the possible answers is $$$[\underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}]$$$. | Java 11 | standard input | [
"dp",
"two pointers",
"greedy"
] | 39480cdf697fc9743dc9665f989077d7 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) β the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β the number of elements in $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \le a_i \le 10^9, a_i \ne 0$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$). | 1,200 | For each test case, print the answer β the maximum sum of the maximum by size (length) alternating subsequence of $$$a$$$. | standard output | |
PASSED | 5f9dd6b8a49c88551e0cd781bfabafd2 | train_004.jsonl | 1587479700 | Recall that the sequence $$$b$$$ is a a subsequence of the sequence $$$a$$$ if $$$b$$$ can be derived from $$$a$$$ by removing zero or more elements without changing the order of the remaining elements. For example, if $$$a=[1, 2, 1, 3, 1, 2, 1]$$$, then possible subsequences are: $$$[1, 1, 1, 1]$$$, $$$[3]$$$ and $$$[1, 2, 1, 3, 1, 2, 1]$$$, but not $$$[3, 2, 3]$$$ and $$$[1, 1, 1, 1, 2]$$$.You are given a sequence $$$a$$$ consisting of $$$n$$$ positive and negative elements (there is no zeros in the sequence).Your task is to choose maximum by size (length) alternating subsequence of the given sequence (i.e. the sign of each next element is the opposite from the sign of the current element, like positive-negative-positive and so on or negative-positive-negative and so on). Among all such subsequences, you have to choose one which has the maximum sum of elements.In other words, if the maximum length of alternating subsequence is $$$k$$$ then your task is to find the maximum sum of elements of some alternating subsequence of length $$$k$$$.You have to answer $$$t$$$ independent test cases. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Scanner;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Kumar Ayush
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
Scanner in = new Scanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
CAlternatingSubsequence solver = new CAlternatingSubsequence();
solver.solve(1, in, out);
out.close();
}
static class CAlternatingSubsequence {
public void solve(int testNumber, Scanner in, PrintWriter out) {
int t = in.nextInt();
while (t-- > 0) {
int n = in.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = in.nextInt();
long ans = 0;
int i = 0;
while (i < n) {
long curr = a[i];
boolean pos = true;
if (a[i] < 0) pos = false;
int j = i + 1;
while (j < n) {
if (pos && a[j] < 0) break;
if (!pos && a[j] > 0) break;
curr = Math.max(curr, a[j]);
j++;
}
ans += curr;
i = j;
}
out.println(ans);
}
}
}
}
| Java | ["4\n5\n1 2 3 -1 -2\n4\n-1 -2 -1 -3\n10\n-2 8 3 8 -4 -15 5 -2 -3 1\n6\n1 -1000000000 1 -1000000000 1 -1000000000"] | 1 second | ["2\n-1\n6\n-2999999997"] | NoteIn the first test case of the example, one of the possible answers is $$$[1, 2, \underline{3}, \underline{-1}, -2]$$$.In the second test case of the example, one of the possible answers is $$$[-1, -2, \underline{-1}, -3]$$$.In the third test case of the example, one of the possible answers is $$$[\underline{-2}, 8, 3, \underline{8}, \underline{-4}, -15, \underline{5}, \underline{-2}, -3, \underline{1}]$$$.In the fourth test case of the example, one of the possible answers is $$$[\underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}]$$$. | Java 11 | standard input | [
"dp",
"two pointers",
"greedy"
] | 39480cdf697fc9743dc9665f989077d7 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) β the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β the number of elements in $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \le a_i \le 10^9, a_i \ne 0$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$). | 1,200 | For each test case, print the answer β the maximum sum of the maximum by size (length) alternating subsequence of $$$a$$$. | standard output | |
PASSED | 064a87a9bbce56d74d8f4c17c8e798b7 | train_004.jsonl | 1587479700 | Recall that the sequence $$$b$$$ is a a subsequence of the sequence $$$a$$$ if $$$b$$$ can be derived from $$$a$$$ by removing zero or more elements without changing the order of the remaining elements. For example, if $$$a=[1, 2, 1, 3, 1, 2, 1]$$$, then possible subsequences are: $$$[1, 1, 1, 1]$$$, $$$[3]$$$ and $$$[1, 2, 1, 3, 1, 2, 1]$$$, but not $$$[3, 2, 3]$$$ and $$$[1, 1, 1, 1, 2]$$$.You are given a sequence $$$a$$$ consisting of $$$n$$$ positive and negative elements (there is no zeros in the sequence).Your task is to choose maximum by size (length) alternating subsequence of the given sequence (i.e. the sign of each next element is the opposite from the sign of the current element, like positive-negative-positive and so on or negative-positive-negative and so on). Among all such subsequences, you have to choose one which has the maximum sum of elements.In other words, if the maximum length of alternating subsequence is $$$k$$$ then your task is to find the maximum sum of elements of some alternating subsequence of length $$$k$$$.You have to answer $$$t$$$ independent test cases. | 256 megabytes | import java.util.*;
import java.io.*;
public class problemC {
public static void main(String[] args) throws Exception {
Scanner in = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
// Scanner in = new Scanner(new File("input.in"));
// PrintWriter out = new PrintWriter(new File("output.out"));
int t = in.nextInt();
for (int i = 0; i < t; i++) {
int n = in.nextInt();
long[] sequence = new long[n];
for (int j = 0; j < n; j++) {
sequence[j] = in.nextLong();
}
long[] subMaxes = new long[n];
int subMaxCounter = 0;
subMaxes[0] = sequence[0];
for (int j = 0; j < n - 1; j++) {
if (sequence[j + 1] > 0 && sequence[j] > 0 && sequence[j + 1] > subMaxes[subMaxCounter]) {
subMaxes[subMaxCounter] = sequence[j + 1];
} else if (sequence[j + 1] < 0 && sequence[j] < 0 && sequence[j + 1] > subMaxes[subMaxCounter]) {
subMaxes[subMaxCounter] = sequence[j + 1];
} else if (sequence[j + 1] < 0 && sequence[j] > 0) {
subMaxCounter = subMaxCounter + 1;
subMaxes[subMaxCounter] = sequence[j + 1];
} else if (sequence[j + 1] > 0 && sequence[j] < 0) {
subMaxCounter = subMaxCounter + 1;
subMaxes[subMaxCounter] = sequence[j + 1];
}
}
long maxSum = 0;
for (int j = 0; j <= subMaxCounter && j < n; j++) {
maxSum = maxSum + subMaxes[j];
}
System.out.println(maxSum);
}
in.close();
// out.close();
}
} | Java | ["4\n5\n1 2 3 -1 -2\n4\n-1 -2 -1 -3\n10\n-2 8 3 8 -4 -15 5 -2 -3 1\n6\n1 -1000000000 1 -1000000000 1 -1000000000"] | 1 second | ["2\n-1\n6\n-2999999997"] | NoteIn the first test case of the example, one of the possible answers is $$$[1, 2, \underline{3}, \underline{-1}, -2]$$$.In the second test case of the example, one of the possible answers is $$$[-1, -2, \underline{-1}, -3]$$$.In the third test case of the example, one of the possible answers is $$$[\underline{-2}, 8, 3, \underline{8}, \underline{-4}, -15, \underline{5}, \underline{-2}, -3, \underline{1}]$$$.In the fourth test case of the example, one of the possible answers is $$$[\underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}]$$$. | Java 11 | standard input | [
"dp",
"two pointers",
"greedy"
] | 39480cdf697fc9743dc9665f989077d7 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) β the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β the number of elements in $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \le a_i \le 10^9, a_i \ne 0$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$). | 1,200 | For each test case, print the answer β the maximum sum of the maximum by size (length) alternating subsequence of $$$a$$$. | standard output | |
PASSED | 4f6f21c859d99fa6a7e5f4dbe08c5c0d | train_004.jsonl | 1587479700 | Recall that the sequence $$$b$$$ is a a subsequence of the sequence $$$a$$$ if $$$b$$$ can be derived from $$$a$$$ by removing zero or more elements without changing the order of the remaining elements. For example, if $$$a=[1, 2, 1, 3, 1, 2, 1]$$$, then possible subsequences are: $$$[1, 1, 1, 1]$$$, $$$[3]$$$ and $$$[1, 2, 1, 3, 1, 2, 1]$$$, but not $$$[3, 2, 3]$$$ and $$$[1, 1, 1, 1, 2]$$$.You are given a sequence $$$a$$$ consisting of $$$n$$$ positive and negative elements (there is no zeros in the sequence).Your task is to choose maximum by size (length) alternating subsequence of the given sequence (i.e. the sign of each next element is the opposite from the sign of the current element, like positive-negative-positive and so on or negative-positive-negative and so on). Among all such subsequences, you have to choose one which has the maximum sum of elements.In other words, if the maximum length of alternating subsequence is $$$k$$$ then your task is to find the maximum sum of elements of some alternating subsequence of length $$$k$$$.You have to answer $$$t$$$ independent test cases. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author unknown
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
CAlternatingSubsequence solver = new CAlternatingSubsequence();
solver.solve(1, in, out);
out.close();
}
static class CAlternatingSubsequence {
long LINF = (long) 1e18 + 33331;
public void solve(int testNumber, InputReader in, OutputWriter out) {
int ntc = in.nextInt();
while ((ntc--) > 0) {
int n = in.nextInt();
int[] arr = in.nextIntArray(n);
long maxP = -LINF;
long minN = -LINF;
long sum = 0;
int i = 0;
while (i < n) {
while (i < n && arr[i] > 0) {
maxP = Math.max(arr[i], maxP);
++i;
}
if (maxP != -LINF) {
sum += maxP;
maxP = -LINF;
}
while (i < n && arr[i] < 0) {
maxP = Math.max(arr[i], maxP);
++i;
}
if (maxP != -LINF) {
sum += maxP;
maxP = -LINF;
}
}
out.println(sum);
}
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public int[] nextIntArray(int n) {
int[] array = new int[n];
for (int i = 0; i < n; ++i) array[i] = nextInt();
return array;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void close() {
writer.close();
}
public void println(long i) {
writer.println(i);
}
}
}
| Java | ["4\n5\n1 2 3 -1 -2\n4\n-1 -2 -1 -3\n10\n-2 8 3 8 -4 -15 5 -2 -3 1\n6\n1 -1000000000 1 -1000000000 1 -1000000000"] | 1 second | ["2\n-1\n6\n-2999999997"] | NoteIn the first test case of the example, one of the possible answers is $$$[1, 2, \underline{3}, \underline{-1}, -2]$$$.In the second test case of the example, one of the possible answers is $$$[-1, -2, \underline{-1}, -3]$$$.In the third test case of the example, one of the possible answers is $$$[\underline{-2}, 8, 3, \underline{8}, \underline{-4}, -15, \underline{5}, \underline{-2}, -3, \underline{1}]$$$.In the fourth test case of the example, one of the possible answers is $$$[\underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}]$$$. | Java 11 | standard input | [
"dp",
"two pointers",
"greedy"
] | 39480cdf697fc9743dc9665f989077d7 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) β the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β the number of elements in $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \le a_i \le 10^9, a_i \ne 0$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$). | 1,200 | For each test case, print the answer β the maximum sum of the maximum by size (length) alternating subsequence of $$$a$$$. | standard output | |
PASSED | b0005c339008180697622f68722be294 | train_004.jsonl | 1587479700 | Recall that the sequence $$$b$$$ is a a subsequence of the sequence $$$a$$$ if $$$b$$$ can be derived from $$$a$$$ by removing zero or more elements without changing the order of the remaining elements. For example, if $$$a=[1, 2, 1, 3, 1, 2, 1]$$$, then possible subsequences are: $$$[1, 1, 1, 1]$$$, $$$[3]$$$ and $$$[1, 2, 1, 3, 1, 2, 1]$$$, but not $$$[3, 2, 3]$$$ and $$$[1, 1, 1, 1, 2]$$$.You are given a sequence $$$a$$$ consisting of $$$n$$$ positive and negative elements (there is no zeros in the sequence).Your task is to choose maximum by size (length) alternating subsequence of the given sequence (i.e. the sign of each next element is the opposite from the sign of the current element, like positive-negative-positive and so on or negative-positive-negative and so on). Among all such subsequences, you have to choose one which has the maximum sum of elements.In other words, if the maximum length of alternating subsequence is $$$k$$$ then your task is to find the maximum sum of elements of some alternating subsequence of length $$$k$$$.You have to answer $$$t$$$ independent test cases. | 256 megabytes | import java.util.*;
import java.lang.Math;
import java.lang.*;
public class Main{
public static void main(String args[])
{
Scanner in=new Scanner(System.in);
int t,n;
t=in.nextInt();
for(int i=0;i<t;i++)
{
n=in.nextInt();
long a[]=new long[n];
long sign=0,sum=0,max=-1000000009;
for(int j=0;j<n;j++)
{
a[j]=in.nextLong();
if((j>0&&sign*a[j]<0)||(j==n-1))
{
if(j==n-1&&sign*a[j]<0)
{
sum=sum+a[j];
}
if(sign*a[j]>0&&j==n-1&&a[j]>max)
{
max=a[j];
}
sum=sum+max;
max=-1000000009;
}
if(a[j]>max)
{
max=a[j];
}
if(a[j]>0)
{
sign=1;
}
if(a[j]<0)
{
sign=-1;
}
if(n==1)
{
sum=a[0];
break;
}
}
System.out.println(sum);
}
}
} | Java | ["4\n5\n1 2 3 -1 -2\n4\n-1 -2 -1 -3\n10\n-2 8 3 8 -4 -15 5 -2 -3 1\n6\n1 -1000000000 1 -1000000000 1 -1000000000"] | 1 second | ["2\n-1\n6\n-2999999997"] | NoteIn the first test case of the example, one of the possible answers is $$$[1, 2, \underline{3}, \underline{-1}, -2]$$$.In the second test case of the example, one of the possible answers is $$$[-1, -2, \underline{-1}, -3]$$$.In the third test case of the example, one of the possible answers is $$$[\underline{-2}, 8, 3, \underline{8}, \underline{-4}, -15, \underline{5}, \underline{-2}, -3, \underline{1}]$$$.In the fourth test case of the example, one of the possible answers is $$$[\underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}]$$$. | Java 11 | standard input | [
"dp",
"two pointers",
"greedy"
] | 39480cdf697fc9743dc9665f989077d7 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) β the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β the number of elements in $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \le a_i \le 10^9, a_i \ne 0$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$). | 1,200 | For each test case, print the answer β the maximum sum of the maximum by size (length) alternating subsequence of $$$a$$$. | standard output | |
PASSED | d18069e54e08edcf9d539fdcf8b4c278 | train_004.jsonl | 1587479700 | Recall that the sequence $$$b$$$ is a a subsequence of the sequence $$$a$$$ if $$$b$$$ can be derived from $$$a$$$ by removing zero or more elements without changing the order of the remaining elements. For example, if $$$a=[1, 2, 1, 3, 1, 2, 1]$$$, then possible subsequences are: $$$[1, 1, 1, 1]$$$, $$$[3]$$$ and $$$[1, 2, 1, 3, 1, 2, 1]$$$, but not $$$[3, 2, 3]$$$ and $$$[1, 1, 1, 1, 2]$$$.You are given a sequence $$$a$$$ consisting of $$$n$$$ positive and negative elements (there is no zeros in the sequence).Your task is to choose maximum by size (length) alternating subsequence of the given sequence (i.e. the sign of each next element is the opposite from the sign of the current element, like positive-negative-positive and so on or negative-positive-negative and so on). Among all such subsequences, you have to choose one which has the maximum sum of elements.In other words, if the maximum length of alternating subsequence is $$$k$$$ then your task is to find the maximum sum of elements of some alternating subsequence of length $$$k$$$.You have to answer $$$t$$$ independent test cases. | 256 megabytes | import java.util.*;
public class C1343C {
public static boolean checkSign(int a, int b) {
if (a > 0 && b > 0) {
return true;
} else if (a < 0 && b < 0) {
return true;
} else {
return false;
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
for (int i = 0; i < t; i++) {
int n = sc.nextInt();
int array[] = new int[n];
int alternate = 1;
for (int k = 0; k < n; k++) {
array[k] = sc.nextInt();
if (k >= 1) {
if ((array[k] > 0 && array[k - 1] < 0) || (array[k] < 0 && array[k - 1] > 0)) {
alternate++;
}
}
}
long[] dp = new long[alternate];
dp[0] = array[0];
int x = 0;
// System.out.println(alternate);
for (int k = 1; k < n; k++) {
if (x == 0) {
if (checkSign(array[k], array[k - 1])) {
dp[x] = Math.max(dp[x], Math.max(array[k], array[k - 1]));
continue;
} else if (!checkSign(array[k], array[k - 1])) {
x++;
dp[x] = dp[x - 1] + array[k];
continue;
}
} else if (x > 0) {
if (!checkSign(array[k], array[k - 1])) {
x++;
dp[x] = dp[x - 1] + array[k];
} else if (checkSign(array[k], array[k - 1])) {
dp[x] =Math.max(dp[x], dp[x-1]+array[k]);
}
}
}
System.out.println(dp[alternate-1]);
}
}
}
| Java | ["4\n5\n1 2 3 -1 -2\n4\n-1 -2 -1 -3\n10\n-2 8 3 8 -4 -15 5 -2 -3 1\n6\n1 -1000000000 1 -1000000000 1 -1000000000"] | 1 second | ["2\n-1\n6\n-2999999997"] | NoteIn the first test case of the example, one of the possible answers is $$$[1, 2, \underline{3}, \underline{-1}, -2]$$$.In the second test case of the example, one of the possible answers is $$$[-1, -2, \underline{-1}, -3]$$$.In the third test case of the example, one of the possible answers is $$$[\underline{-2}, 8, 3, \underline{8}, \underline{-4}, -15, \underline{5}, \underline{-2}, -3, \underline{1}]$$$.In the fourth test case of the example, one of the possible answers is $$$[\underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}]$$$. | Java 11 | standard input | [
"dp",
"two pointers",
"greedy"
] | 39480cdf697fc9743dc9665f989077d7 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) β the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β the number of elements in $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \le a_i \le 10^9, a_i \ne 0$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$). | 1,200 | For each test case, print the answer β the maximum sum of the maximum by size (length) alternating subsequence of $$$a$$$. | standard output | |
PASSED | 23d98b3bb42ccd7497d14049d48e46c8 | train_004.jsonl | 1587479700 | Recall that the sequence $$$b$$$ is a a subsequence of the sequence $$$a$$$ if $$$b$$$ can be derived from $$$a$$$ by removing zero or more elements without changing the order of the remaining elements. For example, if $$$a=[1, 2, 1, 3, 1, 2, 1]$$$, then possible subsequences are: $$$[1, 1, 1, 1]$$$, $$$[3]$$$ and $$$[1, 2, 1, 3, 1, 2, 1]$$$, but not $$$[3, 2, 3]$$$ and $$$[1, 1, 1, 1, 2]$$$.You are given a sequence $$$a$$$ consisting of $$$n$$$ positive and negative elements (there is no zeros in the sequence).Your task is to choose maximum by size (length) alternating subsequence of the given sequence (i.e. the sign of each next element is the opposite from the sign of the current element, like positive-negative-positive and so on or negative-positive-negative and so on). Among all such subsequences, you have to choose one which has the maximum sum of elements.In other words, if the maximum length of alternating subsequence is $$$k$$$ then your task is to find the maximum sum of elements of some alternating subsequence of length $$$k$$$.You have to answer $$$t$$$ independent test cases. | 256 megabytes | import java.util.Scanner;
public class codefcf {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int t = s.nextInt();
while (t-- > 0) {
int n = s.nextInt();
long[] a = new long[n];
for (int i = 0; i < n; i++) {
a[i] = s.nextLong();
}
long sumTillnow = 0;
long minN = Long.MIN_VALUE;
long maxp = Long.MIN_VALUE;
for (int i = 0; i < a.length; i++) {
if (a[i] > 0) {
if (a[i] > maxp) {
if (maxp != Long.MIN_VALUE) {
sumTillnow -= maxp;
}
maxp = a[i];
sumTillnow += maxp;
}
minN = Long.MIN_VALUE;
} else {
if (a[i] > minN) {
if (minN != Long.MIN_VALUE) {
sumTillnow -= minN;
}
minN = a[i];
sumTillnow += minN;
}
maxp = Long.MIN_VALUE;
}
}
System.out.println(sumTillnow);
}
}
}
| Java | ["4\n5\n1 2 3 -1 -2\n4\n-1 -2 -1 -3\n10\n-2 8 3 8 -4 -15 5 -2 -3 1\n6\n1 -1000000000 1 -1000000000 1 -1000000000"] | 1 second | ["2\n-1\n6\n-2999999997"] | NoteIn the first test case of the example, one of the possible answers is $$$[1, 2, \underline{3}, \underline{-1}, -2]$$$.In the second test case of the example, one of the possible answers is $$$[-1, -2, \underline{-1}, -3]$$$.In the third test case of the example, one of the possible answers is $$$[\underline{-2}, 8, 3, \underline{8}, \underline{-4}, -15, \underline{5}, \underline{-2}, -3, \underline{1}]$$$.In the fourth test case of the example, one of the possible answers is $$$[\underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}]$$$. | Java 11 | standard input | [
"dp",
"two pointers",
"greedy"
] | 39480cdf697fc9743dc9665f989077d7 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) β the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β the number of elements in $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \le a_i \le 10^9, a_i \ne 0$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$). | 1,200 | For each test case, print the answer β the maximum sum of the maximum by size (length) alternating subsequence of $$$a$$$. | standard output | |
PASSED | 16b0e221d99e8e79337ac6539c8d0d92 | train_004.jsonl | 1587479700 | Recall that the sequence $$$b$$$ is a a subsequence of the sequence $$$a$$$ if $$$b$$$ can be derived from $$$a$$$ by removing zero or more elements without changing the order of the remaining elements. For example, if $$$a=[1, 2, 1, 3, 1, 2, 1]$$$, then possible subsequences are: $$$[1, 1, 1, 1]$$$, $$$[3]$$$ and $$$[1, 2, 1, 3, 1, 2, 1]$$$, but not $$$[3, 2, 3]$$$ and $$$[1, 1, 1, 1, 2]$$$.You are given a sequence $$$a$$$ consisting of $$$n$$$ positive and negative elements (there is no zeros in the sequence).Your task is to choose maximum by size (length) alternating subsequence of the given sequence (i.e. the sign of each next element is the opposite from the sign of the current element, like positive-negative-positive and so on or negative-positive-negative and so on). Among all such subsequences, you have to choose one which has the maximum sum of elements.In other words, if the maximum length of alternating subsequence is $$$k$$$ then your task is to find the maximum sum of elements of some alternating subsequence of length $$$k$$$.You have to answer $$$t$$$ independent test cases. | 256 megabytes | import java.util.*;
public class test
{
public static void main(String[]args)
{
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
for(int l=1;l<=t;l++)
{
int n=sc.nextInt();
int arr[]=new int[n];
//int signflip=false;
arr[0]=sc.nextInt();
int max=arr[0];
long sum=0;
if(n==1)
{
sum=max;
}
for(int i=1;i<n;i++)
{
arr[i]=sc.nextInt();
if((arr[i]>0&&arr[i-1]<0)||(arr[i-1]>0&&arr[i]<0))
{
//signflip=true;
sum+=max;
//System.out.println(max);
max=arr[i];
if(i==n-1)
sum+=max;
}
else
{
if(arr[i]>max)
{
max=arr[i];
}
if(i==n-1)
sum+=max;
}
}
//System.out.println(Arrays.toString(arr));
System.out.println(sum);
}
}
} | Java | ["4\n5\n1 2 3 -1 -2\n4\n-1 -2 -1 -3\n10\n-2 8 3 8 -4 -15 5 -2 -3 1\n6\n1 -1000000000 1 -1000000000 1 -1000000000"] | 1 second | ["2\n-1\n6\n-2999999997"] | NoteIn the first test case of the example, one of the possible answers is $$$[1, 2, \underline{3}, \underline{-1}, -2]$$$.In the second test case of the example, one of the possible answers is $$$[-1, -2, \underline{-1}, -3]$$$.In the third test case of the example, one of the possible answers is $$$[\underline{-2}, 8, 3, \underline{8}, \underline{-4}, -15, \underline{5}, \underline{-2}, -3, \underline{1}]$$$.In the fourth test case of the example, one of the possible answers is $$$[\underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}]$$$. | Java 11 | standard input | [
"dp",
"two pointers",
"greedy"
] | 39480cdf697fc9743dc9665f989077d7 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) β the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β the number of elements in $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \le a_i \le 10^9, a_i \ne 0$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$). | 1,200 | For each test case, print the answer β the maximum sum of the maximum by size (length) alternating subsequence of $$$a$$$. | standard output | |
PASSED | 7ad6428b45eb61a642f40215dafa75b9 | train_004.jsonl | 1587479700 | Recall that the sequence $$$b$$$ is a a subsequence of the sequence $$$a$$$ if $$$b$$$ can be derived from $$$a$$$ by removing zero or more elements without changing the order of the remaining elements. For example, if $$$a=[1, 2, 1, 3, 1, 2, 1]$$$, then possible subsequences are: $$$[1, 1, 1, 1]$$$, $$$[3]$$$ and $$$[1, 2, 1, 3, 1, 2, 1]$$$, but not $$$[3, 2, 3]$$$ and $$$[1, 1, 1, 1, 2]$$$.You are given a sequence $$$a$$$ consisting of $$$n$$$ positive and negative elements (there is no zeros in the sequence).Your task is to choose maximum by size (length) alternating subsequence of the given sequence (i.e. the sign of each next element is the opposite from the sign of the current element, like positive-negative-positive and so on or negative-positive-negative and so on). Among all such subsequences, you have to choose one which has the maximum sum of elements.In other words, if the maximum length of alternating subsequence is $$$k$$$ then your task is to find the maximum sum of elements of some alternating subsequence of length $$$k$$$.You have to answer $$$t$$$ independent test cases. | 256 megabytes | // Codeforces 1343C
import java.util.Scanner;
import java.util.Vector;
public class CF1343C {
static final Scanner SC = new Scanner(System.in);
public static void main(String[] args) {
int tests = SC.nextInt();
for (int t = 0; t < tests; ++t) {
int arrLen = SC.nextInt();
int[] arr = new int[arrLen];
for (int i = 0; i < arrLen; ++i)
arr[i] = SC.nextInt();
long solutionSum = getSolutionSum(arr);
System.out.println(solutionSum);
}
}
// Computes and returns sum of longest alternating sequence with maximum sum
static long getSolutionSum(int[] arr) {
Vector<Integer> solution = new Vector<>();
boolean prevPos = arr[0] > 0;
int appendSolution = arr[0]; // Candidate number to be appended to solution vector
for (int i = 0; i < arr.length; ++i) {
boolean isPos = arr[i] > 0;
if (prevPos) {
if (isPos) {
appendSolution = Math.max(arr[i], appendSolution);
}
else {
solution.add(appendSolution);
appendSolution = arr[i];
prevPos = false;
}
}
else {
if (isPos) {
solution.add(appendSolution);
appendSolution = arr[i];
prevPos = true;
}
else {
appendSolution = Math.max(appendSolution, arr[i]);
}
}
}
//Adding last element
solution.add(appendSolution);
return vectorSum(solution);
}
// Returns sum of elements of vector
static long vectorSum(Vector<Integer> v) {
long sum = 0;
for (int num : v)
sum += num;
return sum;
}
} | Java | ["4\n5\n1 2 3 -1 -2\n4\n-1 -2 -1 -3\n10\n-2 8 3 8 -4 -15 5 -2 -3 1\n6\n1 -1000000000 1 -1000000000 1 -1000000000"] | 1 second | ["2\n-1\n6\n-2999999997"] | NoteIn the first test case of the example, one of the possible answers is $$$[1, 2, \underline{3}, \underline{-1}, -2]$$$.In the second test case of the example, one of the possible answers is $$$[-1, -2, \underline{-1}, -3]$$$.In the third test case of the example, one of the possible answers is $$$[\underline{-2}, 8, 3, \underline{8}, \underline{-4}, -15, \underline{5}, \underline{-2}, -3, \underline{1}]$$$.In the fourth test case of the example, one of the possible answers is $$$[\underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}]$$$. | Java 11 | standard input | [
"dp",
"two pointers",
"greedy"
] | 39480cdf697fc9743dc9665f989077d7 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) β the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β the number of elements in $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \le a_i \le 10^9, a_i \ne 0$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$). | 1,200 | For each test case, print the answer β the maximum sum of the maximum by size (length) alternating subsequence of $$$a$$$. | standard output | |
PASSED | a0cd3cbe002d35b2b6de4c64288c467a | train_004.jsonl | 1587479700 | Recall that the sequence $$$b$$$ is a a subsequence of the sequence $$$a$$$ if $$$b$$$ can be derived from $$$a$$$ by removing zero or more elements without changing the order of the remaining elements. For example, if $$$a=[1, 2, 1, 3, 1, 2, 1]$$$, then possible subsequences are: $$$[1, 1, 1, 1]$$$, $$$[3]$$$ and $$$[1, 2, 1, 3, 1, 2, 1]$$$, but not $$$[3, 2, 3]$$$ and $$$[1, 1, 1, 1, 2]$$$.You are given a sequence $$$a$$$ consisting of $$$n$$$ positive and negative elements (there is no zeros in the sequence).Your task is to choose maximum by size (length) alternating subsequence of the given sequence (i.e. the sign of each next element is the opposite from the sign of the current element, like positive-negative-positive and so on or negative-positive-negative and so on). Among all such subsequences, you have to choose one which has the maximum sum of elements.In other words, if the maximum length of alternating subsequence is $$$k$$$ then your task is to find the maximum sum of elements of some alternating subsequence of length $$$k$$$.You have to answer $$$t$$$ independent test cases. | 256 megabytes | // Codeforces 1343C
import java.util.Scanner;
import java.util.Vector;
public class CF1343C {
static final Scanner SC = new Scanner(System.in);
public static void main(String[] args) {
int tests = SC.nextInt();
for (int t = 0; t < tests; ++t) {
int arrLen = SC.nextInt();
int[] arr = new int[arrLen];
for (int i = 0; i < arrLen; ++i)
arr[i] = SC.nextInt();
long solutionSum = getSolutionSum(arr);
System.out.println(solutionSum);
}
}
// Computes and returns sum of longest alternating sequence with maximum sum
static long getSolutionSum(int[] arr) {
Vector<Integer> negFirst = new Vector<>();
Vector<Integer> posFirst = new Vector<>();
boolean prevPosNF = false; // Notes whether the last addition to negFirst was posititve or not
boolean prevPosPF = true; // Notes whether the last addition to posFirst was positive or not
int addToNF = Integer.MIN_VALUE; // This won't be added
int addToPF = Integer.MIN_VALUE; // This won't be added
for (int i = 0; i < arr.length; ++i) {
boolean isPos = arr[i] > 0;
// Working on negFirst vector
if (prevPosNF) {
if (isPos) {
addToNF = Math.max(arr[i], addToNF);
}
else {
negFirst.add(addToNF);
addToNF = arr[i];
prevPosNF = false;
}
}
else {
if (isPos) {
if (addToNF != Integer.MIN_VALUE) // Initial value
negFirst.add(addToNF);
addToNF = arr[i];
prevPosNF = true;
}
else {
addToNF = Math.max(arr[i], addToNF);
}
}
// Working on posFirst vector
if (prevPosPF) {
if (isPos) {
addToPF = Math.max(arr[i], addToPF);
}
else {
if (addToPF != Integer.MIN_VALUE)
posFirst.add(addToPF);
addToPF = arr[i];
prevPosPF = false;
}
}
else {
if (isPos) {
posFirst.add(addToPF);
addToPF = arr[i];
prevPosPF = true;
}
else {
addToPF = Math.max(arr[i], addToPF);
}
}
}
// Adding last element if not added already
if (negFirst.size() == 0 && addToNF != Integer.MIN_VALUE)
negFirst.add(addToNF);
else {
int lastAddedNF = negFirst.get(negFirst.size()-1);
if (lastAddedNF != addToNF)
negFirst.add(addToNF);
}
if (posFirst.size() == 0 && addToPF != Integer.MIN_VALUE)
posFirst.add(addToPF);
else {
int lastAddedPF = posFirst.get(posFirst.size()-1);
if (lastAddedPF != addToPF)
posFirst.add(addToPF);
}
if (negFirst.size() > posFirst.size())
return vectorSum(negFirst);
else if (posFirst.size() > negFirst.size())
return vectorSum(posFirst);
else // Same size
return Math.max(vectorSum(negFirst), vectorSum(posFirst));
}
// Returns sum of elements of vector
static long vectorSum(Vector<Integer> v) {
long sum = 0;
for (int num : v)
sum += num;
return sum;
}
} | Java | ["4\n5\n1 2 3 -1 -2\n4\n-1 -2 -1 -3\n10\n-2 8 3 8 -4 -15 5 -2 -3 1\n6\n1 -1000000000 1 -1000000000 1 -1000000000"] | 1 second | ["2\n-1\n6\n-2999999997"] | NoteIn the first test case of the example, one of the possible answers is $$$[1, 2, \underline{3}, \underline{-1}, -2]$$$.In the second test case of the example, one of the possible answers is $$$[-1, -2, \underline{-1}, -3]$$$.In the third test case of the example, one of the possible answers is $$$[\underline{-2}, 8, 3, \underline{8}, \underline{-4}, -15, \underline{5}, \underline{-2}, -3, \underline{1}]$$$.In the fourth test case of the example, one of the possible answers is $$$[\underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}]$$$. | Java 11 | standard input | [
"dp",
"two pointers",
"greedy"
] | 39480cdf697fc9743dc9665f989077d7 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) β the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β the number of elements in $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \le a_i \le 10^9, a_i \ne 0$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$). | 1,200 | For each test case, print the answer β the maximum sum of the maximum by size (length) alternating subsequence of $$$a$$$. | standard output | |
PASSED | eb410709068736eac4bc26d654054882 | train_004.jsonl | 1587479700 | Recall that the sequence $$$b$$$ is a a subsequence of the sequence $$$a$$$ if $$$b$$$ can be derived from $$$a$$$ by removing zero or more elements without changing the order of the remaining elements. For example, if $$$a=[1, 2, 1, 3, 1, 2, 1]$$$, then possible subsequences are: $$$[1, 1, 1, 1]$$$, $$$[3]$$$ and $$$[1, 2, 1, 3, 1, 2, 1]$$$, but not $$$[3, 2, 3]$$$ and $$$[1, 1, 1, 1, 2]$$$.You are given a sequence $$$a$$$ consisting of $$$n$$$ positive and negative elements (there is no zeros in the sequence).Your task is to choose maximum by size (length) alternating subsequence of the given sequence (i.e. the sign of each next element is the opposite from the sign of the current element, like positive-negative-positive and so on or negative-positive-negative and so on). Among all such subsequences, you have to choose one which has the maximum sum of elements.In other words, if the maximum length of alternating subsequence is $$$k$$$ then your task is to find the maximum sum of elements of some alternating subsequence of length $$$k$$$.You have to answer $$$t$$$ independent test cases. | 256 megabytes | import java.util.*;
public class cf1343c {
public static void main(String args[])
{Scanner sc=new Scanner(System.in);
long k=sc.nextLong();
for(int j=1;j<=k;j++)
{int n=sc.nextInt();
long arr[]=new long[n];
arr[0]=sc.nextLong();
long max=arr[0];
long sum=0,g=0;
if(arr[0]>0)
g=1;int f=0;
for(int i=1;i<n;i++)
{arr[i]=sc.nextLong();
if(arr[i]>0)
f=1;
else
f=0;
if(f==g)
{if(arr[i]>max)
max=arr[i];}
else
{sum=sum+max;
max=arr[i];
g=f;}}
sum=sum+max;
System.out.println(sum);
}sc.close();}} | Java | ["4\n5\n1 2 3 -1 -2\n4\n-1 -2 -1 -3\n10\n-2 8 3 8 -4 -15 5 -2 -3 1\n6\n1 -1000000000 1 -1000000000 1 -1000000000"] | 1 second | ["2\n-1\n6\n-2999999997"] | NoteIn the first test case of the example, one of the possible answers is $$$[1, 2, \underline{3}, \underline{-1}, -2]$$$.In the second test case of the example, one of the possible answers is $$$[-1, -2, \underline{-1}, -3]$$$.In the third test case of the example, one of the possible answers is $$$[\underline{-2}, 8, 3, \underline{8}, \underline{-4}, -15, \underline{5}, \underline{-2}, -3, \underline{1}]$$$.In the fourth test case of the example, one of the possible answers is $$$[\underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}]$$$. | Java 11 | standard input | [
"dp",
"two pointers",
"greedy"
] | 39480cdf697fc9743dc9665f989077d7 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) β the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β the number of elements in $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \le a_i \le 10^9, a_i \ne 0$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$). | 1,200 | For each test case, print the answer β the maximum sum of the maximum by size (length) alternating subsequence of $$$a$$$. | standard output | |
PASSED | 037b562e050049b38a1f05740bb041a6 | train_004.jsonl | 1587479700 | Recall that the sequence $$$b$$$ is a a subsequence of the sequence $$$a$$$ if $$$b$$$ can be derived from $$$a$$$ by removing zero or more elements without changing the order of the remaining elements. For example, if $$$a=[1, 2, 1, 3, 1, 2, 1]$$$, then possible subsequences are: $$$[1, 1, 1, 1]$$$, $$$[3]$$$ and $$$[1, 2, 1, 3, 1, 2, 1]$$$, but not $$$[3, 2, 3]$$$ and $$$[1, 1, 1, 1, 2]$$$.You are given a sequence $$$a$$$ consisting of $$$n$$$ positive and negative elements (there is no zeros in the sequence).Your task is to choose maximum by size (length) alternating subsequence of the given sequence (i.e. the sign of each next element is the opposite from the sign of the current element, like positive-negative-positive and so on or negative-positive-negative and so on). Among all such subsequences, you have to choose one which has the maximum sum of elements.In other words, if the maximum length of alternating subsequence is $$$k$$$ then your task is to find the maximum sum of elements of some alternating subsequence of length $$$k$$$.You have to answer $$$t$$$ independent test cases. | 256 megabytes | import java.util.*;
public class xyz
{
public static long max(long[] arr, int start , int end)
{
long max = Long.MIN_VALUE;
for( int i = start ; i<= end ; i++)
{
if(arr[i] > max)
{
max = arr[i];
}
}
return max;
}
public static void main(String[] args)
{
Scanner scn = new Scanner(System.in);
int t = scn.nextInt();
for( int j = 1; j<= t ; j++ )
{
int n = scn.nextInt() ;
long[] arr = new long[n];
for(int i= 0; i < n ; i++)
{
arr[i] = scn.nextLong();
}
int start = 0 ;
int end ;
long sum = 0 ;
for( int i = 1 ; i < n ; i++)
{
long x = arr[start]*arr[i] ;
if( x < 0)
{
end = i-1 ;
sum = sum + max(arr,start ,end) ;
start = i ;
}
}
end = n-1 ;
sum = sum + max(arr,start ,end) ;
System.out.println(sum) ;
}
}
}
| Java | ["4\n5\n1 2 3 -1 -2\n4\n-1 -2 -1 -3\n10\n-2 8 3 8 -4 -15 5 -2 -3 1\n6\n1 -1000000000 1 -1000000000 1 -1000000000"] | 1 second | ["2\n-1\n6\n-2999999997"] | NoteIn the first test case of the example, one of the possible answers is $$$[1, 2, \underline{3}, \underline{-1}, -2]$$$.In the second test case of the example, one of the possible answers is $$$[-1, -2, \underline{-1}, -3]$$$.In the third test case of the example, one of the possible answers is $$$[\underline{-2}, 8, 3, \underline{8}, \underline{-4}, -15, \underline{5}, \underline{-2}, -3, \underline{1}]$$$.In the fourth test case of the example, one of the possible answers is $$$[\underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}]$$$. | Java 11 | standard input | [
"dp",
"two pointers",
"greedy"
] | 39480cdf697fc9743dc9665f989077d7 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) β the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β the number of elements in $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \le a_i \le 10^9, a_i \ne 0$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$). | 1,200 | For each test case, print the answer β the maximum sum of the maximum by size (length) alternating subsequence of $$$a$$$. | standard output | |
PASSED | 46d3e3cc3127b4f50fc866f5f2b30a8c | train_004.jsonl | 1587479700 | Recall that the sequence $$$b$$$ is a a subsequence of the sequence $$$a$$$ if $$$b$$$ can be derived from $$$a$$$ by removing zero or more elements without changing the order of the remaining elements. For example, if $$$a=[1, 2, 1, 3, 1, 2, 1]$$$, then possible subsequences are: $$$[1, 1, 1, 1]$$$, $$$[3]$$$ and $$$[1, 2, 1, 3, 1, 2, 1]$$$, but not $$$[3, 2, 3]$$$ and $$$[1, 1, 1, 1, 2]$$$.You are given a sequence $$$a$$$ consisting of $$$n$$$ positive and negative elements (there is no zeros in the sequence).Your task is to choose maximum by size (length) alternating subsequence of the given sequence (i.e. the sign of each next element is the opposite from the sign of the current element, like positive-negative-positive and so on or negative-positive-negative and so on). Among all such subsequences, you have to choose one which has the maximum sum of elements.In other words, if the maximum length of alternating subsequence is $$$k$$$ then your task is to find the maximum sum of elements of some alternating subsequence of length $$$k$$$.You have to answer $$$t$$$ independent test cases. | 256 megabytes | /*
Ο
/ \
/ \
/ \
/-------\
/ \
__/ \__
*/
//import java.util.Arrays;
import java.util.Scanner;
//import java.util.Stack;
public class CodeForces
{
/*static int BinarySearch(int a[],int q)
{
int i=0,swap=0,n=a.length;
int low=0,high=n-1;
while(low<=high)
{
int mid=(low+high)/2;
if(a[mid]==q)
{
return mid;
}
else if(q>a[mid])
{
low = mid+1;
}
else if(q<a[mid])
{
high = mid-1;
}
}
return 0;
}
static class stack
{
int top = -1;
char items[] = new char[1000000000];
void push(char x)
{
if(top<1000000000)
{
items[top++]=x;
}
}
void pop()
{
if(top!=-1)
{
top--;
}
}
boolean isEmpty()
{
return (top==-1) ? true : false;
}
}*/
/*public static long findexp(long dr)
{
int count = 0;
while(dr/2>=1&&dr%2==0)
{
dr/=2;
count++;
}
return count;
} */
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
for(int i=0;i<t;i++)
{
int n = sc.nextInt();
int a[] = new int[n];
for(int j=0;j<n;j++)
{
a[j] = sc.nextInt();
}
boolean b[] = new boolean[n];
long sum =0;
for(int j=0;j<n;j++)
{
if(a[j]>0)
{
b[j]=true;
}
}
int count = 0;
int max = a[0];
boolean is = b[0];
for(int j=1;j<n;j++)
{
if(b[j]==is)
{
max = Math.max(max,a[j]);
}
if(b[j]!=is||j==n-1)
{
sum+=max;
max = a[j];
is = b[j];
}
}
if(n==1)
{
System.out.println(a[0]);
}
else
{
if(b[n-1]!=b[n-2])
{
sum+=a[n-1];
}
System.out.println(sum);
}
}
}
} | Java | ["4\n5\n1 2 3 -1 -2\n4\n-1 -2 -1 -3\n10\n-2 8 3 8 -4 -15 5 -2 -3 1\n6\n1 -1000000000 1 -1000000000 1 -1000000000"] | 1 second | ["2\n-1\n6\n-2999999997"] | NoteIn the first test case of the example, one of the possible answers is $$$[1, 2, \underline{3}, \underline{-1}, -2]$$$.In the second test case of the example, one of the possible answers is $$$[-1, -2, \underline{-1}, -3]$$$.In the third test case of the example, one of the possible answers is $$$[\underline{-2}, 8, 3, \underline{8}, \underline{-4}, -15, \underline{5}, \underline{-2}, -3, \underline{1}]$$$.In the fourth test case of the example, one of the possible answers is $$$[\underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}]$$$. | Java 11 | standard input | [
"dp",
"two pointers",
"greedy"
] | 39480cdf697fc9743dc9665f989077d7 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) β the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β the number of elements in $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \le a_i \le 10^9, a_i \ne 0$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$). | 1,200 | For each test case, print the answer β the maximum sum of the maximum by size (length) alternating subsequence of $$$a$$$. | standard output | |
PASSED | f3d99a7508ad8e08426289a08eb822eb | train_004.jsonl | 1587479700 | Recall that the sequence $$$b$$$ is a a subsequence of the sequence $$$a$$$ if $$$b$$$ can be derived from $$$a$$$ by removing zero or more elements without changing the order of the remaining elements. For example, if $$$a=[1, 2, 1, 3, 1, 2, 1]$$$, then possible subsequences are: $$$[1, 1, 1, 1]$$$, $$$[3]$$$ and $$$[1, 2, 1, 3, 1, 2, 1]$$$, but not $$$[3, 2, 3]$$$ and $$$[1, 1, 1, 1, 2]$$$.You are given a sequence $$$a$$$ consisting of $$$n$$$ positive and negative elements (there is no zeros in the sequence).Your task is to choose maximum by size (length) alternating subsequence of the given sequence (i.e. the sign of each next element is the opposite from the sign of the current element, like positive-negative-positive and so on or negative-positive-negative and so on). Among all such subsequences, you have to choose one which has the maximum sum of elements.In other words, if the maximum length of alternating subsequence is $$$k$$$ then your task is to find the maximum sum of elements of some alternating subsequence of length $$$k$$$.You have to answer $$$t$$$ independent test cases. | 256 megabytes | /* package codechef; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
public class Main
{
static Scanner in = new Scanner(System.in);
public static void solve()
{
int n=in.nextInt();
int[] a = new int[n];
int[] dp = new int[n];
for(int i=0;i<n;i++)
{
a[i]=in.nextInt();
}
long max=0;
for(int i=0;i<n;i++)
{
int x=a[i];
int j=i+1;
int curr=x;
while(j<n && ((x>0 && a[j]>0) || (x<0 && a[j]<0)))
{
curr=(int)Math.max(curr,a[j]);
j++;
}
i=j-1;
max=max+curr;
}
System.out.println(max);
}
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
int t=in.nextInt();
//in.nextLine();
while(t>0)
{
solve();
t--;
}
// System.out.println(x);
}
}
| Java | ["4\n5\n1 2 3 -1 -2\n4\n-1 -2 -1 -3\n10\n-2 8 3 8 -4 -15 5 -2 -3 1\n6\n1 -1000000000 1 -1000000000 1 -1000000000"] | 1 second | ["2\n-1\n6\n-2999999997"] | NoteIn the first test case of the example, one of the possible answers is $$$[1, 2, \underline{3}, \underline{-1}, -2]$$$.In the second test case of the example, one of the possible answers is $$$[-1, -2, \underline{-1}, -3]$$$.In the third test case of the example, one of the possible answers is $$$[\underline{-2}, 8, 3, \underline{8}, \underline{-4}, -15, \underline{5}, \underline{-2}, -3, \underline{1}]$$$.In the fourth test case of the example, one of the possible answers is $$$[\underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}]$$$. | Java 11 | standard input | [
"dp",
"two pointers",
"greedy"
] | 39480cdf697fc9743dc9665f989077d7 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) β the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β the number of elements in $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \le a_i \le 10^9, a_i \ne 0$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$). | 1,200 | For each test case, print the answer β the maximum sum of the maximum by size (length) alternating subsequence of $$$a$$$. | standard output | |
PASSED | 145e852e093f017c24d1954e1dedd8bc | train_004.jsonl | 1587479700 | Recall that the sequence $$$b$$$ is a a subsequence of the sequence $$$a$$$ if $$$b$$$ can be derived from $$$a$$$ by removing zero or more elements without changing the order of the remaining elements. For example, if $$$a=[1, 2, 1, 3, 1, 2, 1]$$$, then possible subsequences are: $$$[1, 1, 1, 1]$$$, $$$[3]$$$ and $$$[1, 2, 1, 3, 1, 2, 1]$$$, but not $$$[3, 2, 3]$$$ and $$$[1, 1, 1, 1, 2]$$$.You are given a sequence $$$a$$$ consisting of $$$n$$$ positive and negative elements (there is no zeros in the sequence).Your task is to choose maximum by size (length) alternating subsequence of the given sequence (i.e. the sign of each next element is the opposite from the sign of the current element, like positive-negative-positive and so on or negative-positive-negative and so on). Among all such subsequences, you have to choose one which has the maximum sum of elements.In other words, if the maximum length of alternating subsequence is $$$k$$$ then your task is to find the maximum sum of elements of some alternating subsequence of length $$$k$$$.You have to answer $$$t$$$ independent test cases. | 256 megabytes | import java.util.*;
import java.io.*;
public class Main {
public static void main (String[] args) {
FastScanner scanner = new FastScanner();
int t = scanner.nextInt();
while(t-- > 0) {
int n = scanner.nextInt();
int[] a = new int[n];
int sumArr[] = new int[n];
int max = Integer.MIN_VALUE, currentIndex = 0;
for (int i = 0; i < n; i++) {
a[i] = scanner.nextInt();
if (i > 0 && Math.signum(a[i]) != Math.signum(a[i - 1])) {
currentIndex++;
max = Integer.MIN_VALUE;
}
max = Math.max(max, a[i]);
sumArr[currentIndex] = max;
}
long res = 0;
for (int val :sumArr){
res += val;
}
System.out.println(res);
}
}
}
class FastScanner {
public BufferedReader reader;
public StringTokenizer tokenizer;
public FastScanner() {
reader = new BufferedReader(new InputStreamReader(System.in), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public String nextLine() {
try {
return reader.readLine();
} catch(IOException e) {
throw new RuntimeException(e);
}
}
}
| Java | ["4\n5\n1 2 3 -1 -2\n4\n-1 -2 -1 -3\n10\n-2 8 3 8 -4 -15 5 -2 -3 1\n6\n1 -1000000000 1 -1000000000 1 -1000000000"] | 1 second | ["2\n-1\n6\n-2999999997"] | NoteIn the first test case of the example, one of the possible answers is $$$[1, 2, \underline{3}, \underline{-1}, -2]$$$.In the second test case of the example, one of the possible answers is $$$[-1, -2, \underline{-1}, -3]$$$.In the third test case of the example, one of the possible answers is $$$[\underline{-2}, 8, 3, \underline{8}, \underline{-4}, -15, \underline{5}, \underline{-2}, -3, \underline{1}]$$$.In the fourth test case of the example, one of the possible answers is $$$[\underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}]$$$. | Java 11 | standard input | [
"dp",
"two pointers",
"greedy"
] | 39480cdf697fc9743dc9665f989077d7 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) β the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β the number of elements in $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \le a_i \le 10^9, a_i \ne 0$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$). | 1,200 | For each test case, print the answer β the maximum sum of the maximum by size (length) alternating subsequence of $$$a$$$. | standard output | |
PASSED | a1a44318ecf03535861dc105763727c2 | train_004.jsonl | 1587479700 | Recall that the sequence $$$b$$$ is a a subsequence of the sequence $$$a$$$ if $$$b$$$ can be derived from $$$a$$$ by removing zero or more elements without changing the order of the remaining elements. For example, if $$$a=[1, 2, 1, 3, 1, 2, 1]$$$, then possible subsequences are: $$$[1, 1, 1, 1]$$$, $$$[3]$$$ and $$$[1, 2, 1, 3, 1, 2, 1]$$$, but not $$$[3, 2, 3]$$$ and $$$[1, 1, 1, 1, 2]$$$.You are given a sequence $$$a$$$ consisting of $$$n$$$ positive and negative elements (there is no zeros in the sequence).Your task is to choose maximum by size (length) alternating subsequence of the given sequence (i.e. the sign of each next element is the opposite from the sign of the current element, like positive-negative-positive and so on or negative-positive-negative and so on). Among all such subsequences, you have to choose one which has the maximum sum of elements.In other words, if the maximum length of alternating subsequence is $$$k$$$ then your task is to find the maximum sum of elements of some alternating subsequence of length $$$k$$$.You have to answer $$$t$$$ independent test cases. | 256 megabytes |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.util.*;
public class Test2 {
public static void main(String[] args) throws IOException {
BufferedReader bf=new BufferedReader(new InputStreamReader(System.in));
String test_numS=bf.readLine();
int test_num=Integer.parseInt(test_numS);
while(test_num>0){
String N=bf.readLine();
int n=Integer.parseInt(N);
String aS=bf.readLine();
String a[]=aS.split(" ");
long arr[]=new long[n];
for (int i = 0; i <n ; i++) {
arr[i]=Integer.parseInt(a[i]);
}
solve(n,arr);
test_num--;
}
bf.close();
}
public static void solve(int n,long a[]){
Map<Integer,Long> pos=new TreeMap<>();
Map<Integer,Long> neg=new TreeMap<>();
for (int i = 0; i <n ; i++) {
if (a[i]>0){
pos.put(i,a[i]);
}else {
neg.put(i,a[i]);
}
}
int ai=0;ArrayList<Long> arr=new ArrayList<>();
while(ai<n){
if (ai==0){
if (pos.containsKey(ai)){
arr.add(pos.get(ai));
}else arr.add(neg.get(ai));
}else {
if (pos.containsKey(ai)&&arr.get(arr.size()-1)*pos.get(ai)<0){
arr.add(pos.get(ai));
}else if (pos.containsKey(ai)&&arr.get(arr.size()-1)*pos.get(ai)>0){
if (pos.get(ai)>arr.get(arr.size()-1)){
arr.remove(arr.size()-1);
arr.add(arr.size(),pos.get(ai));
}
}else if (neg.containsKey(ai)&&arr.get(arr.size()-1)*(-1)<0){
arr.add(neg.get(ai));
}else if (neg.containsKey(ai)&&arr.get(arr.size()-1)*(-1)>0){
if (neg.get(ai)>arr.get(arr.size()-1)){
arr.remove(arr.size()-1);
arr.add(arr.size(),neg.get(ai));
}
}
}
ai++;
}
long sum=0;
for (long l:arr) {
sum+=l;
}
System.out.println(sum);
}
} | Java | ["4\n5\n1 2 3 -1 -2\n4\n-1 -2 -1 -3\n10\n-2 8 3 8 -4 -15 5 -2 -3 1\n6\n1 -1000000000 1 -1000000000 1 -1000000000"] | 1 second | ["2\n-1\n6\n-2999999997"] | NoteIn the first test case of the example, one of the possible answers is $$$[1, 2, \underline{3}, \underline{-1}, -2]$$$.In the second test case of the example, one of the possible answers is $$$[-1, -2, \underline{-1}, -3]$$$.In the third test case of the example, one of the possible answers is $$$[\underline{-2}, 8, 3, \underline{8}, \underline{-4}, -15, \underline{5}, \underline{-2}, -3, \underline{1}]$$$.In the fourth test case of the example, one of the possible answers is $$$[\underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}]$$$. | Java 11 | standard input | [
"dp",
"two pointers",
"greedy"
] | 39480cdf697fc9743dc9665f989077d7 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) β the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β the number of elements in $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \le a_i \le 10^9, a_i \ne 0$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$). | 1,200 | For each test case, print the answer β the maximum sum of the maximum by size (length) alternating subsequence of $$$a$$$. | standard output | |
PASSED | 38164988a11c83c9b7b57da5bc45607d | train_004.jsonl | 1587479700 | Recall that the sequence $$$b$$$ is a a subsequence of the sequence $$$a$$$ if $$$b$$$ can be derived from $$$a$$$ by removing zero or more elements without changing the order of the remaining elements. For example, if $$$a=[1, 2, 1, 3, 1, 2, 1]$$$, then possible subsequences are: $$$[1, 1, 1, 1]$$$, $$$[3]$$$ and $$$[1, 2, 1, 3, 1, 2, 1]$$$, but not $$$[3, 2, 3]$$$ and $$$[1, 1, 1, 1, 2]$$$.You are given a sequence $$$a$$$ consisting of $$$n$$$ positive and negative elements (there is no zeros in the sequence).Your task is to choose maximum by size (length) alternating subsequence of the given sequence (i.e. the sign of each next element is the opposite from the sign of the current element, like positive-negative-positive and so on or negative-positive-negative and so on). Among all such subsequences, you have to choose one which has the maximum sum of elements.In other words, if the maximum length of alternating subsequence is $$$k$$$ then your task is to find the maximum sum of elements of some alternating subsequence of length $$$k$$$.You have to answer $$$t$$$ independent test cases. | 256 megabytes | import java.io.*;
import java.util.*;
public class Solution {
public static void main (String[] args) throws java.lang.Exception
{
FastReader fr = new FastReader();
int test_case = fr.nextInt();
while(test_case--!=0){
int n = fr.nextInt();
long arr[] = new long[n];
for(int i=0;i<n;i++){
arr[i] = fr.nextInt();
}
long sum = 0;
long num = arr[0];
for(int i=1;i<n;i++){
if(arr[i-1]*arr[i]<0){
sum+=num;
num = Long.MIN_VALUE;
}
num = Math.max(num, arr[i]);
}
sum+=num;
System.out.println(sum);
}
}
static int gcd(int a, int b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
static int lcm(int a, int b){
int g = gcd(a,b);
return a*(b/g);
}
static int exponentMod(int A, int B, int C) {
if (A == 0)
return 0;
if (B == 0)
return 1;
long y;
if (B % 2 == 0)
{
y = exponentMod(A, B / 2, C);
y = (y * y) % C;
}
else
{
y = A % C;
y = (y * exponentMod(A, B - 1, C) % C) % C;
}
return (int)((y + C) % C);
}
static class FastReader{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
} | Java | ["4\n5\n1 2 3 -1 -2\n4\n-1 -2 -1 -3\n10\n-2 8 3 8 -4 -15 5 -2 -3 1\n6\n1 -1000000000 1 -1000000000 1 -1000000000"] | 1 second | ["2\n-1\n6\n-2999999997"] | NoteIn the first test case of the example, one of the possible answers is $$$[1, 2, \underline{3}, \underline{-1}, -2]$$$.In the second test case of the example, one of the possible answers is $$$[-1, -2, \underline{-1}, -3]$$$.In the third test case of the example, one of the possible answers is $$$[\underline{-2}, 8, 3, \underline{8}, \underline{-4}, -15, \underline{5}, \underline{-2}, -3, \underline{1}]$$$.In the fourth test case of the example, one of the possible answers is $$$[\underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}]$$$. | Java 11 | standard input | [
"dp",
"two pointers",
"greedy"
] | 39480cdf697fc9743dc9665f989077d7 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) β the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β the number of elements in $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \le a_i \le 10^9, a_i \ne 0$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$). | 1,200 | For each test case, print the answer β the maximum sum of the maximum by size (length) alternating subsequence of $$$a$$$. | standard output | |
PASSED | 6c4e01014a7e4a883669263cce6ea323 | train_004.jsonl | 1587479700 | Recall that the sequence $$$b$$$ is a a subsequence of the sequence $$$a$$$ if $$$b$$$ can be derived from $$$a$$$ by removing zero or more elements without changing the order of the remaining elements. For example, if $$$a=[1, 2, 1, 3, 1, 2, 1]$$$, then possible subsequences are: $$$[1, 1, 1, 1]$$$, $$$[3]$$$ and $$$[1, 2, 1, 3, 1, 2, 1]$$$, but not $$$[3, 2, 3]$$$ and $$$[1, 1, 1, 1, 2]$$$.You are given a sequence $$$a$$$ consisting of $$$n$$$ positive and negative elements (there is no zeros in the sequence).Your task is to choose maximum by size (length) alternating subsequence of the given sequence (i.e. the sign of each next element is the opposite from the sign of the current element, like positive-negative-positive and so on or negative-positive-negative and so on). Among all such subsequences, you have to choose one which has the maximum sum of elements.In other words, if the maximum length of alternating subsequence is $$$k$$$ then your task is to find the maximum sum of elements of some alternating subsequence of length $$$k$$$.You have to answer $$$t$$$ independent test cases. | 256 megabytes | import java.util.*;
import java.math.*;
public final class AlternatingSequence {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while(t-- != 0) {
int n = sc.nextInt();
long[] a = new long[n];
for (int i = 0; i < n; i++) {
a[i] = sc.nextLong();
}
long sum = 0, max = a[0];
for (int i = 0; i < n; i++) {
max = Math.max(a[i], max);
if(i < n - 1) {
if(diffSign(a[i], a[i + 1])) {
sum += max;
max = a[i + 1];
}
}
else if (i > 0) {
if(diffSign(a[i], a[i - 1]))
sum += a[i];
else
sum += max;
}
else {
sum += max;
}
}
System.out.println(sum);
}
}
static boolean diffSign(long x, long y) {
if(x >= 0 && y < 0)
return true;
else if(x < 0 && y >= 0)
return true;
return false;
}
} | Java | ["4\n5\n1 2 3 -1 -2\n4\n-1 -2 -1 -3\n10\n-2 8 3 8 -4 -15 5 -2 -3 1\n6\n1 -1000000000 1 -1000000000 1 -1000000000"] | 1 second | ["2\n-1\n6\n-2999999997"] | NoteIn the first test case of the example, one of the possible answers is $$$[1, 2, \underline{3}, \underline{-1}, -2]$$$.In the second test case of the example, one of the possible answers is $$$[-1, -2, \underline{-1}, -3]$$$.In the third test case of the example, one of the possible answers is $$$[\underline{-2}, 8, 3, \underline{8}, \underline{-4}, -15, \underline{5}, \underline{-2}, -3, \underline{1}]$$$.In the fourth test case of the example, one of the possible answers is $$$[\underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}]$$$. | Java 11 | standard input | [
"dp",
"two pointers",
"greedy"
] | 39480cdf697fc9743dc9665f989077d7 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) β the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β the number of elements in $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \le a_i \le 10^9, a_i \ne 0$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$). | 1,200 | For each test case, print the answer β the maximum sum of the maximum by size (length) alternating subsequence of $$$a$$$. | standard output | |
PASSED | 021bcfa4c12f5d8fe0876fad1c94bd7a | train_004.jsonl | 1587479700 | Recall that the sequence $$$b$$$ is a a subsequence of the sequence $$$a$$$ if $$$b$$$ can be derived from $$$a$$$ by removing zero or more elements without changing the order of the remaining elements. For example, if $$$a=[1, 2, 1, 3, 1, 2, 1]$$$, then possible subsequences are: $$$[1, 1, 1, 1]$$$, $$$[3]$$$ and $$$[1, 2, 1, 3, 1, 2, 1]$$$, but not $$$[3, 2, 3]$$$ and $$$[1, 1, 1, 1, 2]$$$.You are given a sequence $$$a$$$ consisting of $$$n$$$ positive and negative elements (there is no zeros in the sequence).Your task is to choose maximum by size (length) alternating subsequence of the given sequence (i.e. the sign of each next element is the opposite from the sign of the current element, like positive-negative-positive and so on or negative-positive-negative and so on). Among all such subsequences, you have to choose one which has the maximum sum of elements.In other words, if the maximum length of alternating subsequence is $$$k$$$ then your task is to find the maximum sum of elements of some alternating subsequence of length $$$k$$$.You have to answer $$$t$$$ independent test cases. | 256 megabytes | import java.util.*;
public class solution
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int t = sc.nextInt(),k=0;
int n;
ArrayList<Long> tab = new ArrayList<Long>();
for(int j=0;j<t;j++)
{
n = sc.nextInt();
if(n==0)
System.out.println(0);
else if(n==1)
System.out.println(sc.nextLong());
else
{
tab.add(sc.nextLong());
Long maxsum=tab.get(0),sum = tab.get(0)-tab.get(0);
for(int i = 1;i<n;i++)
{
tab.add(sc.nextLong());
if(tab.get(i)*tab.get(i-1)<0)
{
sum+=maxsum;
maxsum=tab.get(i);
}
else
if(tab.get(i)>maxsum)
maxsum=tab.get(i);
}
if(tab.get(n-1)*tab.get(n-2)<0)
sum+=tab.get(n-1);
else
if(tab.get(n-1)>maxsum)
sum+=tab.get(n-1);
else
sum+=maxsum;
tab.clear();
System.out.println(sum);
}
}
}
} | Java | ["4\n5\n1 2 3 -1 -2\n4\n-1 -2 -1 -3\n10\n-2 8 3 8 -4 -15 5 -2 -3 1\n6\n1 -1000000000 1 -1000000000 1 -1000000000"] | 1 second | ["2\n-1\n6\n-2999999997"] | NoteIn the first test case of the example, one of the possible answers is $$$[1, 2, \underline{3}, \underline{-1}, -2]$$$.In the second test case of the example, one of the possible answers is $$$[-1, -2, \underline{-1}, -3]$$$.In the third test case of the example, one of the possible answers is $$$[\underline{-2}, 8, 3, \underline{8}, \underline{-4}, -15, \underline{5}, \underline{-2}, -3, \underline{1}]$$$.In the fourth test case of the example, one of the possible answers is $$$[\underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}]$$$. | Java 11 | standard input | [
"dp",
"two pointers",
"greedy"
] | 39480cdf697fc9743dc9665f989077d7 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) β the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β the number of elements in $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \le a_i \le 10^9, a_i \ne 0$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$). | 1,200 | For each test case, print the answer β the maximum sum of the maximum by size (length) alternating subsequence of $$$a$$$. | standard output | |
PASSED | 38bb46b4278f2df7e03e683ffc6722f2 | train_004.jsonl | 1587479700 | Recall that the sequence $$$b$$$ is a a subsequence of the sequence $$$a$$$ if $$$b$$$ can be derived from $$$a$$$ by removing zero or more elements without changing the order of the remaining elements. For example, if $$$a=[1, 2, 1, 3, 1, 2, 1]$$$, then possible subsequences are: $$$[1, 1, 1, 1]$$$, $$$[3]$$$ and $$$[1, 2, 1, 3, 1, 2, 1]$$$, but not $$$[3, 2, 3]$$$ and $$$[1, 1, 1, 1, 2]$$$.You are given a sequence $$$a$$$ consisting of $$$n$$$ positive and negative elements (there is no zeros in the sequence).Your task is to choose maximum by size (length) alternating subsequence of the given sequence (i.e. the sign of each next element is the opposite from the sign of the current element, like positive-negative-positive and so on or negative-positive-negative and so on). Among all such subsequences, you have to choose one which has the maximum sum of elements.In other words, if the maximum length of alternating subsequence is $$$k$$$ then your task is to find the maximum sum of elements of some alternating subsequence of length $$$k$$$.You have to answer $$$t$$$ independent test cases. | 256 megabytes | import java.io.*;
import java.util.*;
public class MyProgram{
public static void main(String[] args) {
MyScanner sc = new MyScanner();
out = new PrintWriter(new BufferedOutputStream(System.out));
int n = sc.nextInt();
for(int i = 0; i < n; i++){
int inputs = sc.nextInt();
int[] arr = new int[inputs];
for(int j = 0; j < inputs; j++){
arr[j] = sc.nextInt();
}
//solution
int a = 0;
int b = 0;
int counter = 0;
long maxSum = 0;
if(arr[0] > 0){
while(a+b < inputs){
if(counter % 2 == 0){
if(arr[a+b] < 0){
maxSum+=max(arr, a, a+b-1);
counter++;
a+=b;
b=0;
}
else{
b++;
}
}
else{
if(arr[a+b] > 0){
maxSum += max(arr, a, a+b-1);
counter++;
a+=b;
b=1;
}
else{
b++;
}
}
}
if(a+b == inputs){
maxSum += max(arr, a, a+b-1);
}
}
else{
while(a+b < inputs){
if(counter % 2 == 0){
if(arr[a+b] > 0){
maxSum += max(arr,a, a+b-1);
counter++;
a+=b;
b=0;
}
else{
b++;
}
}
else{
if(arr[a+b] < 0){
maxSum += max(arr, a, a+b-1);
counter++;
a+=b;
b=0;
}
else{
b++;
}
}
}
if(a+b == inputs){
maxSum += max(arr, a, a+b-1);
}
}
System.out.println(maxSum);
}
out.close();
}
public static int max(int[] arr, int start, int end){
int max = Integer.MIN_VALUE;
for(int i = start; i <= end; i++){
max = Math.max(arr[i], max);
}
return max;
}
//-----------PrintWriter for faster output---------------------------------
public static PrintWriter out;
//-----------MyScanner class for faster input----------
public static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine(){
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
//--------------------------------------------------------
} | Java | ["4\n5\n1 2 3 -1 -2\n4\n-1 -2 -1 -3\n10\n-2 8 3 8 -4 -15 5 -2 -3 1\n6\n1 -1000000000 1 -1000000000 1 -1000000000"] | 1 second | ["2\n-1\n6\n-2999999997"] | NoteIn the first test case of the example, one of the possible answers is $$$[1, 2, \underline{3}, \underline{-1}, -2]$$$.In the second test case of the example, one of the possible answers is $$$[-1, -2, \underline{-1}, -3]$$$.In the third test case of the example, one of the possible answers is $$$[\underline{-2}, 8, 3, \underline{8}, \underline{-4}, -15, \underline{5}, \underline{-2}, -3, \underline{1}]$$$.In the fourth test case of the example, one of the possible answers is $$$[\underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}]$$$. | Java 11 | standard input | [
"dp",
"two pointers",
"greedy"
] | 39480cdf697fc9743dc9665f989077d7 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) β the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β the number of elements in $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \le a_i \le 10^9, a_i \ne 0$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$). | 1,200 | For each test case, print the answer β the maximum sum of the maximum by size (length) alternating subsequence of $$$a$$$. | standard output | |
PASSED | 84983d096f44092b1ba09faeaae6cc30 | train_004.jsonl | 1587479700 | Recall that the sequence $$$b$$$ is a a subsequence of the sequence $$$a$$$ if $$$b$$$ can be derived from $$$a$$$ by removing zero or more elements without changing the order of the remaining elements. For example, if $$$a=[1, 2, 1, 3, 1, 2, 1]$$$, then possible subsequences are: $$$[1, 1, 1, 1]$$$, $$$[3]$$$ and $$$[1, 2, 1, 3, 1, 2, 1]$$$, but not $$$[3, 2, 3]$$$ and $$$[1, 1, 1, 1, 2]$$$.You are given a sequence $$$a$$$ consisting of $$$n$$$ positive and negative elements (there is no zeros in the sequence).Your task is to choose maximum by size (length) alternating subsequence of the given sequence (i.e. the sign of each next element is the opposite from the sign of the current element, like positive-negative-positive and so on or negative-positive-negative and so on). Among all such subsequences, you have to choose one which has the maximum sum of elements.In other words, if the maximum length of alternating subsequence is $$$k$$$ then your task is to find the maximum sum of elements of some alternating subsequence of length $$$k$$$.You have to answer $$$t$$$ independent test cases. | 256 megabytes | import java.util.*;
import java.util.Map.Entry;
import java.io.*;
public class b_prblm {
private static class p {
int x;
int idx;
p(int x, int idx) {
this.x = x;
this.idx = idx;
}
}
static long gcd(long a, long b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
StringBuilder res = new StringBuilder();
int T = scn.nextInt(), tmcs = 0;
C: while (tmcs++ < T) {
int n = scn.nextInt();
int[] mrf = new int[n];
ArrayList<p> myl1a = new ArrayList<>(), l2 = new ArrayList<>();
for (int i = 0; i < n; i++) {
int mtm = scn.nextInt();
mrf[i] = mtm;
p p = new p(mtm, i);
if (mtm < 0)
l2.add(p);
else
myl1a.add(p);
}
long rr=gcd(2,3);
int s = pn(myl1a, l2), e = np(myl1a, l2);
if (s < e)
res.append(myfntwo(mrf, false) + "\n");
else if (e < s)
res.append(myfntwo(mrf, true) + "\n");
else
res.append(Math.max(myfntwo(mrf, true), myfntwo(mrf, false)) + "\n");
}
System.out.print(res);
}
public static int sol(int n){
int arr[]=new int[n];
for(int i=0;i<n;i++){
arr[i]=i;
}
return 3+n;
}
private static long myfntwo(int[] mar, boolean b) {
long res = 0;
int res2=sol(5);
for (int i = 0; i < mar.length;) {
if (b) {
int max = 0;
while (i < mar.length) {
max = Math.max(max, mar[i]);
if (mar[i] < 0 && max != 0) {
break;
}
i++;
}
res += max;
} else {
int max = Integer.MIN_VALUE;
while (i < mar.length) {
max = Math.max(max, mar[i]);
i++;
if (i < mar.length && mar[i] > 0) {
break;
}
}
if (max != Integer.MIN_VALUE) {
res += max;
}
}
b = !b;
}
return res;
}
private static int np(ArrayList<p> a, ArrayList<p> mbal) {
int l = 0;
int r = 0;
long rr=gcd(2,3);
int size = mbal.size() > 0 ? 1 : 0;
while (l < a.size() && r < mbal.size()) {
p temp = mbal.get(r);
while (l < a.size()) {
p temp1 = a.get(l);
if (temp1.idx < temp.idx) {
l++;
} else {
size++;
break;
}
}
int raa=sol(34);
if (l >= a.size()) {
break;
}
for(int ll=0;ll<2;ll++){
long ra=gcd(3,4);
}
temp = a.get(l);
while (r < mbal.size()) {
p temp1 = mbal.get(r);
if (temp1.idx < temp.idx) {
r++;
} else {
size++;
break;
}
}
}
return size;
}
private static int pn(ArrayList<p> a, ArrayList<p> b) {
int l = 0;
int r = 0;
int size = a.size() > 0 ? 1 : 0;
while (l < a.size() && r < b.size()) {
p temp = a.get(l);
while (r < b.size()) {
p temp1 = b.get(r);
if (temp1.idx < temp.idx) {
r++;
} else {
size++;
break;
}
}
int res2=sol(7);
if (r >= b.size()) {
break;
}
temp = b.get(r);
while (l < a.size()) {
p temp1 = a.get(l);
if (temp1.idx < temp.idx) {
l++;
} else {
size++;
break;
}
}
}
return size;
}
}
| Java | ["4\n5\n1 2 3 -1 -2\n4\n-1 -2 -1 -3\n10\n-2 8 3 8 -4 -15 5 -2 -3 1\n6\n1 -1000000000 1 -1000000000 1 -1000000000"] | 1 second | ["2\n-1\n6\n-2999999997"] | NoteIn the first test case of the example, one of the possible answers is $$$[1, 2, \underline{3}, \underline{-1}, -2]$$$.In the second test case of the example, one of the possible answers is $$$[-1, -2, \underline{-1}, -3]$$$.In the third test case of the example, one of the possible answers is $$$[\underline{-2}, 8, 3, \underline{8}, \underline{-4}, -15, \underline{5}, \underline{-2}, -3, \underline{1}]$$$.In the fourth test case of the example, one of the possible answers is $$$[\underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}]$$$. | Java 11 | standard input | [
"dp",
"two pointers",
"greedy"
] | 39480cdf697fc9743dc9665f989077d7 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) β the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β the number of elements in $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \le a_i \le 10^9, a_i \ne 0$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$). | 1,200 | For each test case, print the answer β the maximum sum of the maximum by size (length) alternating subsequence of $$$a$$$. | standard output | |
PASSED | 02ecd7876a45a73b32648e340689a8f2 | train_004.jsonl | 1587479700 | Recall that the sequence $$$b$$$ is a a subsequence of the sequence $$$a$$$ if $$$b$$$ can be derived from $$$a$$$ by removing zero or more elements without changing the order of the remaining elements. For example, if $$$a=[1, 2, 1, 3, 1, 2, 1]$$$, then possible subsequences are: $$$[1, 1, 1, 1]$$$, $$$[3]$$$ and $$$[1, 2, 1, 3, 1, 2, 1]$$$, but not $$$[3, 2, 3]$$$ and $$$[1, 1, 1, 1, 2]$$$.You are given a sequence $$$a$$$ consisting of $$$n$$$ positive and negative elements (there is no zeros in the sequence).Your task is to choose maximum by size (length) alternating subsequence of the given sequence (i.e. the sign of each next element is the opposite from the sign of the current element, like positive-negative-positive and so on or negative-positive-negative and so on). Among all such subsequences, you have to choose one which has the maximum sum of elements.In other words, if the maximum length of alternating subsequence is $$$k$$$ then your task is to find the maximum sum of elements of some alternating subsequence of length $$$k$$$.You have to answer $$$t$$$ independent test cases. | 256 megabytes | import java.util.*;
import java.util.concurrent.SynchronousQueue;
import java.io.*;
public class given_len_sum_of_dig {
// 1
// -79
// 1
// 75
// 2
// -75 -56
// 2
// 72 -20
// 2
// -54 29
// 2
// 97 2
// 3
// -26 -76 -19
// 3
// 84 -84 -45
// 3
// -69 2 -73
// 3
// 37 57 -62
// 3
// -83 -90 79
// 3
// 6 -61 68
// 3
// -33 16 40
// 3
// 63 93 49
// 4
// -10 -91 -46 -33
// 4
// 31 -21 -44 -83
// 4
// -67 28 -25 -46
// 4
// 21 80 -79 -56
// 4
// -90 -34 67 -27
// 4
// 91 -97 35 -67
// 4
// -36 80 21 -6
// 4
// 1 52 25 -70
// 4
// -99 -48 -5 22
// 4
// 89 -2 -94 66
// 4
// -69 2 -33 33
// 4
// 75 92 -17 10
// 4
// -7 -73 54 12
// 4
// 9 -21 43 21
// 4
// -50 92 20 97
// 4
// 7 25 67 17
public static void main(String[] args) throws IOException {
Scanner scn = new Scanner(System.in);
int t=scn.nextInt();
while(t-->0){
int n=scn.nextInt();
long arr[]=new long[n];
for(int i=0;i<n;i++){
arr[i]=scn.nextLong();
}
int i=1;
long sum=0;
ArrayList<Long> al=new ArrayList<>();
long max=Integer.MIN_VALUE;
long min=Integer.MIN_VALUE;
boolean f=(arr[0]>0)?true:false;
if(f)
max=arr[0];
else
min=arr[0];
while(i<arr.length){
if(f){
if(arr[i]>0){
max=Math.max(max, arr[i]);
}else{
f=!f;
al.add(max);
sum+=max;
min=Math.max(min, arr[i]);
max=Integer.MIN_VALUE;
}
}else{
if(arr[i]<0){
min=Math.max(min, arr[i]);
}else{
f=!f;
al.add(min);
sum+=min;
max=Math.max(max, arr[i]);
min=Integer.MIN_VALUE;
}
// -79
// 75
// -56
// 52
// -25
// 97
// -19
// 39
// -140
// -5
// -4
// 13
// 7
// 93
// -10
// 10
// -64
// 24
// 6
// -38
// 38
// -18
// 17
// 153
// -67
// 85
// 47
// 31
// 47
// 67
// -1
// 0
// -85
// 42
// 51
// 48
// 29
// 50
// -41
// -3
// -123
// 84
// -37
// -17
// 15
// 62
// 41
// 86
// -13
// 121
// 57
// -24
// -17
// 144
// 50
// 61
// 0
// 10
// 45
// 88
// 77
// 94
// -3
// 19
// 22
// -11
// -86
// 91
// -25
// 85
// -39
// 41
// -23
// 92
// 1
// 81
// 31
// 4
// -9
// 91
// -154
// -39
// 57
// -84
// -37
// -20
// -15
// 28
// -8
// 6
// -28
// 71
// -22
// -4
// 52
// 123
// 85
// 131
// 61
// 94
// 75
// 122
// 7
// -24
// 15
// 139
// 87
// -33
// -40
// 73
// 44
// 56
// -58
// -22
// 48
// 133
// -9
// 118
// ...
//
}
i++;
}
if(al.size()==0){
if(!f && min!=Integer.MIN_VALUE){
al.add(min);
sum+=min;
}
if(f && max!=Integer.MIN_VALUE){
al.add(max);
sum+=max;
}
}else{
if(al.size()>0 && f&& al.get(al.size()-1)!=max && max!=Integer.MIN_VALUE){
al.add(max);
sum+=max;
}
if(al.size()>0 && !f &&al.get(al.size()-1)!=min && min!=Integer.MIN_VALUE){
al.add(min);
sum+=min;
}
}
// System.out.println(al);
// if(al.size()>1 && al.get(0)>0 && al.get(al.size()-1)>0){
// System.out.println(Math.max(sum-al.get(al.size()-1), sum-al.get(0)));
// }else if(al.size()>1 && al.get(0)<0 && al.get(al.size()-1)<0)
// {
// System.out.println(Math.max(sum-al.get(al.size()-1), sum-al.get(0)));
// }else{
System.out.println(sum);
// }
}
}
} | Java | ["4\n5\n1 2 3 -1 -2\n4\n-1 -2 -1 -3\n10\n-2 8 3 8 -4 -15 5 -2 -3 1\n6\n1 -1000000000 1 -1000000000 1 -1000000000"] | 1 second | ["2\n-1\n6\n-2999999997"] | NoteIn the first test case of the example, one of the possible answers is $$$[1, 2, \underline{3}, \underline{-1}, -2]$$$.In the second test case of the example, one of the possible answers is $$$[-1, -2, \underline{-1}, -3]$$$.In the third test case of the example, one of the possible answers is $$$[\underline{-2}, 8, 3, \underline{8}, \underline{-4}, -15, \underline{5}, \underline{-2}, -3, \underline{1}]$$$.In the fourth test case of the example, one of the possible answers is $$$[\underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}]$$$. | Java 11 | standard input | [
"dp",
"two pointers",
"greedy"
] | 39480cdf697fc9743dc9665f989077d7 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) β the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β the number of elements in $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \le a_i \le 10^9, a_i \ne 0$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$). | 1,200 | For each test case, print the answer β the maximum sum of the maximum by size (length) alternating subsequence of $$$a$$$. | standard output | |
PASSED | 1001c67022ba3308ee035de956700036 | train_004.jsonl | 1587479700 | Recall that the sequence $$$b$$$ is a a subsequence of the sequence $$$a$$$ if $$$b$$$ can be derived from $$$a$$$ by removing zero or more elements without changing the order of the remaining elements. For example, if $$$a=[1, 2, 1, 3, 1, 2, 1]$$$, then possible subsequences are: $$$[1, 1, 1, 1]$$$, $$$[3]$$$ and $$$[1, 2, 1, 3, 1, 2, 1]$$$, but not $$$[3, 2, 3]$$$ and $$$[1, 1, 1, 1, 2]$$$.You are given a sequence $$$a$$$ consisting of $$$n$$$ positive and negative elements (there is no zeros in the sequence).Your task is to choose maximum by size (length) alternating subsequence of the given sequence (i.e. the sign of each next element is the opposite from the sign of the current element, like positive-negative-positive and so on or negative-positive-negative and so on). Among all such subsequences, you have to choose one which has the maximum sum of elements.In other words, if the maximum length of alternating subsequence is $$$k$$$ then your task is to find the maximum sum of elements of some alternating subsequence of length $$$k$$$.You have to answer $$$t$$$ independent test cases. | 256 megabytes | import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int cases = scanner.nextInt();
for (int c = 1; c <= cases; c++) {
int n = scanner.nextInt();
int el = scanner.nextInt();
boolean positive = el > 0;
int max = el;
long sum = 0;
for (int i = 1; i < n; i++) {
el = scanner.nextInt();
if (el > 0) {
if (positive) {
max = Math.max(el, max);
} else {
sum += max;
max = el;
positive = true;
}
} else {
if (positive) {
sum += max;
max = el;
positive = false;
} else {
max = Math.max(el, max);
}
}
}
sum += max;
System.out.println(sum);
}
}
} | Java | ["4\n5\n1 2 3 -1 -2\n4\n-1 -2 -1 -3\n10\n-2 8 3 8 -4 -15 5 -2 -3 1\n6\n1 -1000000000 1 -1000000000 1 -1000000000"] | 1 second | ["2\n-1\n6\n-2999999997"] | NoteIn the first test case of the example, one of the possible answers is $$$[1, 2, \underline{3}, \underline{-1}, -2]$$$.In the second test case of the example, one of the possible answers is $$$[-1, -2, \underline{-1}, -3]$$$.In the third test case of the example, one of the possible answers is $$$[\underline{-2}, 8, 3, \underline{8}, \underline{-4}, -15, \underline{5}, \underline{-2}, -3, \underline{1}]$$$.In the fourth test case of the example, one of the possible answers is $$$[\underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}]$$$. | Java 11 | standard input | [
"dp",
"two pointers",
"greedy"
] | 39480cdf697fc9743dc9665f989077d7 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) β the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β the number of elements in $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \le a_i \le 10^9, a_i \ne 0$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$). | 1,200 | For each test case, print the answer β the maximum sum of the maximum by size (length) alternating subsequence of $$$a$$$. | standard output | |
PASSED | 94466ec26f35ef605f3dc2c8a9acfe24 | train_004.jsonl | 1587479700 | Recall that the sequence $$$b$$$ is a a subsequence of the sequence $$$a$$$ if $$$b$$$ can be derived from $$$a$$$ by removing zero or more elements without changing the order of the remaining elements. For example, if $$$a=[1, 2, 1, 3, 1, 2, 1]$$$, then possible subsequences are: $$$[1, 1, 1, 1]$$$, $$$[3]$$$ and $$$[1, 2, 1, 3, 1, 2, 1]$$$, but not $$$[3, 2, 3]$$$ and $$$[1, 1, 1, 1, 2]$$$.You are given a sequence $$$a$$$ consisting of $$$n$$$ positive and negative elements (there is no zeros in the sequence).Your task is to choose maximum by size (length) alternating subsequence of the given sequence (i.e. the sign of each next element is the opposite from the sign of the current element, like positive-negative-positive and so on or negative-positive-negative and so on). Among all such subsequences, you have to choose one which has the maximum sum of elements.In other words, if the maximum length of alternating subsequence is $$$k$$$ then your task is to find the maximum sum of elements of some alternating subsequence of length $$$k$$$.You have to answer $$$t$$$ independent test cases. | 256 megabytes | import java.util.Scanner;
public class P3 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int cases = scanner.nextInt();
for (int c = 1; c <= cases; c++) {
int n = scanner.nextInt();
int el = scanner.nextInt();
boolean positive = el > 0;
int max = el;
long sum = 0;
for (int i = 1; i < n; i++) {
el = scanner.nextInt();
if (el > 0) {
if (positive) {
max = Math.max(el, max);
} else {
sum += max;
max = el;
positive = true;
}
} else {
if (positive) {
sum += max;
max = el;
positive = false;
} else {
max = Math.max(el, max);
}
}
}
sum += max;
System.out.println(sum);
}
}
} | Java | ["4\n5\n1 2 3 -1 -2\n4\n-1 -2 -1 -3\n10\n-2 8 3 8 -4 -15 5 -2 -3 1\n6\n1 -1000000000 1 -1000000000 1 -1000000000"] | 1 second | ["2\n-1\n6\n-2999999997"] | NoteIn the first test case of the example, one of the possible answers is $$$[1, 2, \underline{3}, \underline{-1}, -2]$$$.In the second test case of the example, one of the possible answers is $$$[-1, -2, \underline{-1}, -3]$$$.In the third test case of the example, one of the possible answers is $$$[\underline{-2}, 8, 3, \underline{8}, \underline{-4}, -15, \underline{5}, \underline{-2}, -3, \underline{1}]$$$.In the fourth test case of the example, one of the possible answers is $$$[\underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}]$$$. | Java 11 | standard input | [
"dp",
"two pointers",
"greedy"
] | 39480cdf697fc9743dc9665f989077d7 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) β the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β the number of elements in $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \le a_i \le 10^9, a_i \ne 0$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$). | 1,200 | For each test case, print the answer β the maximum sum of the maximum by size (length) alternating subsequence of $$$a$$$. | standard output | |
PASSED | 1bb14b638af18ed8fc0bb1d92f261f11 | train_004.jsonl | 1587479700 | Recall that the sequence $$$b$$$ is a a subsequence of the sequence $$$a$$$ if $$$b$$$ can be derived from $$$a$$$ by removing zero or more elements without changing the order of the remaining elements. For example, if $$$a=[1, 2, 1, 3, 1, 2, 1]$$$, then possible subsequences are: $$$[1, 1, 1, 1]$$$, $$$[3]$$$ and $$$[1, 2, 1, 3, 1, 2, 1]$$$, but not $$$[3, 2, 3]$$$ and $$$[1, 1, 1, 1, 2]$$$.You are given a sequence $$$a$$$ consisting of $$$n$$$ positive and negative elements (there is no zeros in the sequence).Your task is to choose maximum by size (length) alternating subsequence of the given sequence (i.e. the sign of each next element is the opposite from the sign of the current element, like positive-negative-positive and so on or negative-positive-negative and so on). Among all such subsequences, you have to choose one which has the maximum sum of elements.In other words, if the maximum length of alternating subsequence is $$$k$$$ then your task is to find the maximum sum of elements of some alternating subsequence of length $$$k$$$.You have to answer $$$t$$$ independent test cases. | 256 megabytes | import java.util.Scanner;
public class alternatingSubsequence {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
StringBuilder ans = new StringBuilder();
int T = sc.nextInt();
while (--T >= 0) {
int n = sc.nextInt(), a[] = new int[n];
for (int i = 0; i < n; i++) {
a[i] = sc.nextInt();
}
boolean pos = false;
if (a[0] > 0)
pos = true;
int max = Integer.MIN_VALUE;
long sum = 0;
for (int j = 0; j < n;) {
if ((!pos && a[j] < 0) || (pos && a[j] > 0)) {
max = Integer.max(max, a[j]);
j++;
} else {
pos = !pos;
sum += max;
max = Integer.MIN_VALUE;
}
}
if (max != Integer.MAX_VALUE)
sum += max;
ans.append(sum + "\n");
}
System.out.println(ans);
sc.close();
}
}
| Java | ["4\n5\n1 2 3 -1 -2\n4\n-1 -2 -1 -3\n10\n-2 8 3 8 -4 -15 5 -2 -3 1\n6\n1 -1000000000 1 -1000000000 1 -1000000000"] | 1 second | ["2\n-1\n6\n-2999999997"] | NoteIn the first test case of the example, one of the possible answers is $$$[1, 2, \underline{3}, \underline{-1}, -2]$$$.In the second test case of the example, one of the possible answers is $$$[-1, -2, \underline{-1}, -3]$$$.In the third test case of the example, one of the possible answers is $$$[\underline{-2}, 8, 3, \underline{8}, \underline{-4}, -15, \underline{5}, \underline{-2}, -3, \underline{1}]$$$.In the fourth test case of the example, one of the possible answers is $$$[\underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}]$$$. | Java 11 | standard input | [
"dp",
"two pointers",
"greedy"
] | 39480cdf697fc9743dc9665f989077d7 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) β the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β the number of elements in $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \le a_i \le 10^9, a_i \ne 0$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$). | 1,200 | For each test case, print the answer β the maximum sum of the maximum by size (length) alternating subsequence of $$$a$$$. | standard output | |
PASSED | 6cc71b4941498447768287c6a2ceefe3 | train_004.jsonl | 1587479700 | Recall that the sequence $$$b$$$ is a a subsequence of the sequence $$$a$$$ if $$$b$$$ can be derived from $$$a$$$ by removing zero or more elements without changing the order of the remaining elements. For example, if $$$a=[1, 2, 1, 3, 1, 2, 1]$$$, then possible subsequences are: $$$[1, 1, 1, 1]$$$, $$$[3]$$$ and $$$[1, 2, 1, 3, 1, 2, 1]$$$, but not $$$[3, 2, 3]$$$ and $$$[1, 1, 1, 1, 2]$$$.You are given a sequence $$$a$$$ consisting of $$$n$$$ positive and negative elements (there is no zeros in the sequence).Your task is to choose maximum by size (length) alternating subsequence of the given sequence (i.e. the sign of each next element is the opposite from the sign of the current element, like positive-negative-positive and so on or negative-positive-negative and so on). Among all such subsequences, you have to choose one which has the maximum sum of elements.In other words, if the maximum length of alternating subsequence is $$$k$$$ then your task is to find the maximum sum of elements of some alternating subsequence of length $$$k$$$.You have to answer $$$t$$$ independent test cases. | 256 megabytes | import java.util.Scanner;
public class alternatingSubsequence {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
StringBuilder ans = new StringBuilder();
int T = sc.nextInt();
while (--T >= 0) {
int n = sc.nextInt(), a[] = new int[n];
for (int i = 0; i < n; i++) {
a[i] = sc.nextInt();
}
boolean pos = false;
if (a[0] > 0)
pos = true;
int max = Integer.MIN_VALUE;
long sum = 0;
for (int j = 0; j < n;) {
if ((!pos && a[j] < 0) || (pos && a[j] > 0)) {
max = Integer.max(max, a[j]);
j++;
} else {
pos = !pos;
sum += max;
max = Integer.MIN_VALUE;
}
}
sum += max;
ans.append(sum + "\n");
}
System.out.println(ans);
sc.close();
}
}
| Java | ["4\n5\n1 2 3 -1 -2\n4\n-1 -2 -1 -3\n10\n-2 8 3 8 -4 -15 5 -2 -3 1\n6\n1 -1000000000 1 -1000000000 1 -1000000000"] | 1 second | ["2\n-1\n6\n-2999999997"] | NoteIn the first test case of the example, one of the possible answers is $$$[1, 2, \underline{3}, \underline{-1}, -2]$$$.In the second test case of the example, one of the possible answers is $$$[-1, -2, \underline{-1}, -3]$$$.In the third test case of the example, one of the possible answers is $$$[\underline{-2}, 8, 3, \underline{8}, \underline{-4}, -15, \underline{5}, \underline{-2}, -3, \underline{1}]$$$.In the fourth test case of the example, one of the possible answers is $$$[\underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}]$$$. | Java 11 | standard input | [
"dp",
"two pointers",
"greedy"
] | 39480cdf697fc9743dc9665f989077d7 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) β the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β the number of elements in $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \le a_i \le 10^9, a_i \ne 0$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$). | 1,200 | For each test case, print the answer β the maximum sum of the maximum by size (length) alternating subsequence of $$$a$$$. | standard output | |
PASSED | 83845037edb36e330440837b0b18019e | train_004.jsonl | 1587479700 | Recall that the sequence $$$b$$$ is a a subsequence of the sequence $$$a$$$ if $$$b$$$ can be derived from $$$a$$$ by removing zero or more elements without changing the order of the remaining elements. For example, if $$$a=[1, 2, 1, 3, 1, 2, 1]$$$, then possible subsequences are: $$$[1, 1, 1, 1]$$$, $$$[3]$$$ and $$$[1, 2, 1, 3, 1, 2, 1]$$$, but not $$$[3, 2, 3]$$$ and $$$[1, 1, 1, 1, 2]$$$.You are given a sequence $$$a$$$ consisting of $$$n$$$ positive and negative elements (there is no zeros in the sequence).Your task is to choose maximum by size (length) alternating subsequence of the given sequence (i.e. the sign of each next element is the opposite from the sign of the current element, like positive-negative-positive and so on or negative-positive-negative and so on). Among all such subsequences, you have to choose one which has the maximum sum of elements.In other words, if the maximum length of alternating subsequence is $$$k$$$ then your task is to find the maximum sum of elements of some alternating subsequence of length $$$k$$$.You have to answer $$$t$$$ independent test cases. | 256 megabytes | import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int t = in.nextInt();
for(int i = 0; i < t; ++i) {
int n = in.nextInt();
long sum = 0;
int s = 0;
for(int j = 0; j < n; ++j) {
int a = in.nextInt();
if((s==0) || ((s>0) != (a>0))) {
sum += s;
s = a;
}
else if(a > s) {
s = a;
}
if(j == n - 1) {
sum += s;
}
}
System.out.println(sum);
}
}
}
| Java | ["4\n5\n1 2 3 -1 -2\n4\n-1 -2 -1 -3\n10\n-2 8 3 8 -4 -15 5 -2 -3 1\n6\n1 -1000000000 1 -1000000000 1 -1000000000"] | 1 second | ["2\n-1\n6\n-2999999997"] | NoteIn the first test case of the example, one of the possible answers is $$$[1, 2, \underline{3}, \underline{-1}, -2]$$$.In the second test case of the example, one of the possible answers is $$$[-1, -2, \underline{-1}, -3]$$$.In the third test case of the example, one of the possible answers is $$$[\underline{-2}, 8, 3, \underline{8}, \underline{-4}, -15, \underline{5}, \underline{-2}, -3, \underline{1}]$$$.In the fourth test case of the example, one of the possible answers is $$$[\underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}]$$$. | Java 11 | standard input | [
"dp",
"two pointers",
"greedy"
] | 39480cdf697fc9743dc9665f989077d7 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) β the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β the number of elements in $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \le a_i \le 10^9, a_i \ne 0$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$). | 1,200 | For each test case, print the answer β the maximum sum of the maximum by size (length) alternating subsequence of $$$a$$$. | standard output | |
PASSED | d37c20742786e0ff7e43a02baa133c7c | train_004.jsonl | 1598798100 | Let's call a list of positive integers $$$a_0, a_1, ..., a_{n-1}$$$ a power sequence if there is a positive integer $$$c$$$, so that for every $$$0 \le i \le n-1$$$ then $$$a_i = c^i$$$.Given a list of $$$n$$$ positive integers $$$a_0, a_1, ..., a_{n-1}$$$, you are allowed to: Reorder the list (i.e. pick a permutation $$$p$$$ of $$$\{0,1,...,n - 1\}$$$ and change $$$a_i$$$ to $$$a_{p_i}$$$), then Do the following operation any number of times: pick an index $$$i$$$ and change $$$a_i$$$ to $$$a_i - 1$$$ or $$$a_i + 1$$$ (i.e. increment or decrement $$$a_i$$$ by $$$1$$$) with a cost of $$$1$$$. Find the minimum cost to transform $$$a_0, a_1, ..., a_{n-1}$$$ into a power sequence. | 256 megabytes | import java.util.*;
public class b {
static Scanner in = new Scanner(System.in);
public static void main(String[] args) {
int n = in.nextInt();
Long[] tab = new Long[n];
for(int i = 0; i < n; i++) {
tab[i] = in.nextLong();
}
Arrays.sort(tab);
long a = (long) Math.floor(Math.pow((double)tab[n-1],(double)1/(double)(n-1)));
long b = (long) Math.ceil(Math.pow((double)tab[n-1],(double)1/(double)(n-1)));
long x = 0;
long y = 0;
for(int i = 0; i < n; i++) {
x += Math.abs(tab[i] - Math.pow(a, i));
}
for(int i = 0; i < n; i++) {
y += Math.abs(tab[i] - Math.pow(b, i));
}
System.out.println(Math.min(x, y));
}
} | Java | ["3\n1 3 2", "3\n1000000000 1000000000 1000000000"] | 1 second | ["1", "1999982505"] | NoteIn the first example, we first reorder $$$\{1, 3, 2\}$$$ into $$$\{1, 2, 3\}$$$, then increment $$$a_2$$$ to $$$4$$$ with cost $$$1$$$ to get a power sequence $$$\{1, 2, 4\}$$$. | Java 11 | standard input | [
"number theory",
"sortings",
"brute force",
"math"
] | 54e9c6f24c430c5124d840b5a65a1bc4 | The first line contains an integer $$$n$$$ ($$$3 \le n \le 10^5$$$). The second line contains $$$n$$$ integers $$$a_0, a_1, ..., a_{n-1}$$$ ($$$1 \le a_i \le 10^9$$$). | 1,500 | Print the minimum cost to transform $$$a_0, a_1, ..., a_{n-1}$$$ into a power sequence. | standard output | |
PASSED | b5b9e52608e874bcdb250d6e85ceba77 | train_004.jsonl | 1598798100 | Let's call a list of positive integers $$$a_0, a_1, ..., a_{n-1}$$$ a power sequence if there is a positive integer $$$c$$$, so that for every $$$0 \le i \le n-1$$$ then $$$a_i = c^i$$$.Given a list of $$$n$$$ positive integers $$$a_0, a_1, ..., a_{n-1}$$$, you are allowed to: Reorder the list (i.e. pick a permutation $$$p$$$ of $$$\{0,1,...,n - 1\}$$$ and change $$$a_i$$$ to $$$a_{p_i}$$$), then Do the following operation any number of times: pick an index $$$i$$$ and change $$$a_i$$$ to $$$a_i - 1$$$ or $$$a_i + 1$$$ (i.e. increment or decrement $$$a_i$$$ by $$$1$$$) with a cost of $$$1$$$. Find the minimum cost to transform $$$a_0, a_1, ..., a_{n-1}$$$ into a power sequence. | 256 megabytes | import java.util.*;
public class cf666_2_2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
Long a[] = new Long[n];
for(int i=0;i<n;i++) {
a[i] = sc.nextLong();
}
Arrays.sort(a);
long s1=0,s2=0,x1,x2;
x1 = (long) Math.floor(Math.pow(a[n-1],(double)1/(n-1)));
x2 = (long) Math.ceil(Math.pow(a[n-1],(double)1/(n-1)));
for(int i=0;i<n;i++) {
s1 += Math.abs(a[i]-Math.pow(x1,i));
}
for(int i=0;i<n;i++) {
s2 += Math.abs(a[i]-Math.pow(x2,i));
}
System.out.println(Math.min(s1, s2));
sc.close();
}
} | Java | ["3\n1 3 2", "3\n1000000000 1000000000 1000000000"] | 1 second | ["1", "1999982505"] | NoteIn the first example, we first reorder $$$\{1, 3, 2\}$$$ into $$$\{1, 2, 3\}$$$, then increment $$$a_2$$$ to $$$4$$$ with cost $$$1$$$ to get a power sequence $$$\{1, 2, 4\}$$$. | Java 11 | standard input | [
"number theory",
"sortings",
"brute force",
"math"
] | 54e9c6f24c430c5124d840b5a65a1bc4 | The first line contains an integer $$$n$$$ ($$$3 \le n \le 10^5$$$). The second line contains $$$n$$$ integers $$$a_0, a_1, ..., a_{n-1}$$$ ($$$1 \le a_i \le 10^9$$$). | 1,500 | Print the minimum cost to transform $$$a_0, a_1, ..., a_{n-1}$$$ into a power sequence. | standard output | |
PASSED | 6a4d064d0b8a99544238523836915de2 | train_004.jsonl | 1421053200 | Let's define the sum of two permutations p and q of numbers 0,β1,β...,β(nβ-β1) as permutation , where Perm(x) is the x-th lexicographically permutation of numbers 0,β1,β...,β(nβ-β1) (counting from zero), and Ord(p) is the number of permutation p in the lexicographical order.For example, Perm(0)β=β(0,β1,β...,βnβ-β2,βnβ-β1), Perm(n!β-β1)β=β(nβ-β1,βnβ-β2,β...,β1,β0)Misha has two permutations, p and q. Your task is to find their sum.Permutation aβ=β(a0,βa1,β...,βanβ-β1) is called to be lexicographically smaller than permutation bβ=β(b0,βb1,β...,βbnβ-β1), if for some k following conditions hold: a0β=βb0,βa1β=βb1,β...,βakβ-β1β=βbkβ-β1,βakβ<βbk. | 256 megabytes | import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;
public class B {
static StringTokenizer st;
static BufferedReader br;
static PrintWriter pw;
static int[]t;
static int n;
public static void main(String[] args) throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
n = nextInt();
int[]p = new int[n], q = new int[n];
for (int i = 0; i < n; i++) {
p[i] = nextInt();
}
for (int i = 0; i < n; i++) {
q[i] = nextInt();
}
t = new int[n+1];
int[]x = get_number(p, n);
int[]y = get_number(q, n);
int[]z = new int[n];
for (int i = n-1; i >= 0; i--) {
z[i] += x[i]+y[i];
if (z[i] > n-i-1) {
int r = (n-1-i);
if (i-1 >= 0)
z[i-1] += z[i] / (r+1);
z[i] %= (r+1);
}
}
Arrays.fill(t, 0);
int[]ans = new int[n];
for (int i = 0; i < n; i++) {
z[i]++;
int left = 0, right = n;
while (right-left > 1) {
int middle = (left+right) >> 1;
int zeros = middle-sum(middle);
if (zeros >= z[i])
right = middle;
else
left = middle;
}
ans[i] = right-1;
inc(right);
}
for (int i = 0; i < n; i++) {
pw.print(ans[i]+" ");
}
pw.close();
}
private static int[] get_number(int[] p, int n) {
int[]x = new int[n];
Arrays.fill(t, 0);
for (int i = 0; i < n; i++) {
x[i] = p[i]-sum(p[i]+1);
inc(p[i]+1);
}
return x;
}
private static void inc(int ind) {
for (int i = ind; i <= n; i = (i | (i-1))+1) {
t[i]++;
}
}
private static int sum(int ind) {
int sum = 0;
for (int i = ind; i >= 1; i = (i & (i-1))) {
sum += t[i];
}
return sum;
}
private static int nextInt() throws IOException {
return Integer.parseInt(next());
}
private static long nextLong() throws IOException {
return Long.parseLong(next());
}
private static double nextDouble() throws IOException {
return Double.parseDouble(next());
}
private static String next() throws IOException {
while (st==null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
}
| Java | ["2\n0 1\n0 1", "2\n0 1\n1 0", "3\n1 2 0\n2 1 0"] | 2 seconds | ["0 1", "1 0", "1 0 2"] | NotePermutations of numbers from 0 to 1 in the lexicographical order: (0,β1),β(1,β0).In the first sample Ord(p)β=β0 and Ord(q)β=β0, so the answer is .In the second sample Ord(p)β=β0 and Ord(q)β=β1, so the answer is .Permutations of numbers from 0 to 2 in the lexicographical order: (0,β1,β2),β(0,β2,β1),β(1,β0,β2),β(1,β2,β0),β(2,β0,β1),β(2,β1,β0).In the third sample Ord(p)β=β3 and Ord(q)β=β5, so the answer is . | Java 7 | standard input | [
"data structures",
"binary search",
"math"
] | ade941d5869b9a0cb18dad1e6d52218b | The first line contains an integer n (1ββ€βnββ€β200β000). The second line contains n distinct integers from 0 to nβ-β1, separated by a space, forming permutation p. The third line contains n distinct integers from 0 to nβ-β1, separated by spaces, forming permutation q. | 2,000 | Print n distinct integers from 0 to nβ-β1, forming the sum of the given permutations. Separate the numbers by spaces. | standard output | |
PASSED | 8cc22fadc1cab9ddc4d68ce406dfa681 | train_004.jsonl | 1421053200 | Let's define the sum of two permutations p and q of numbers 0,β1,β...,β(nβ-β1) as permutation , where Perm(x) is the x-th lexicographically permutation of numbers 0,β1,β...,β(nβ-β1) (counting from zero), and Ord(p) is the number of permutation p in the lexicographical order.For example, Perm(0)β=β(0,β1,β...,βnβ-β2,βnβ-β1), Perm(n!β-β1)β=β(nβ-β1,βnβ-β2,β...,β1,β0)Misha has two permutations, p and q. Your task is to find their sum.Permutation aβ=β(a0,βa1,β...,βanβ-β1) is called to be lexicographically smaller than permutation bβ=β(b0,βb1,β...,βbnβ-β1), if for some k following conditions hold: a0β=βb0,βa1β=βb1,β...,βakβ-β1β=βbkβ-β1,βakβ<βbk. | 256 megabytes | import java.util.*;
import java.io.*;
public class B {
public static PrintStream out = System.out;
public static InputReader in = new InputReader(System.in);
public static int[] encode(int[] perm) {
BinaryIndexedTree bit = new BinaryIndexedTree(perm.length);
int[] encoded = new int[perm.length];
for (int i = 0; i < perm.length; i++) {
encoded[i] = perm[i] - bit.sum(perm[i]);
bit.insert(perm[i] + 1);
}
return encoded;
}
public static int[] decode(int[] encoded) {
BinaryIndexedTree bit = new BinaryIndexedTree(encoded.length);
int[] perm = new int[encoded.length];
for (int i = 0; i < encoded.length; i++) {
bit.insert(i + 1);
}
for (int i = 0; i < encoded.length; i++) {
perm[i] = bit.select(encoded[i] + 1) - 1;
bit.remove(perm[i] + 1);
}
return perm;
}
public static void main(String args[]) {
int N = in.nextInt();
int[] perm1 = new int[N];
for (int i = 0; i < N; i++) {
perm1[i] = in.nextInt();
}
int[] perm2 = new int[N];
for (int i = 0; i < N; i++) {
perm2[i] = in.nextInt();
}
int[] a = encode(perm1);
int[] b = encode(perm2);;
int[] c = new int[N];
for (int i = N - 1; i >= 0 ; i--) {
int base = N - i;
c[i] += a[i] + b[i];
if (i > 0) c[i - 1] = c[i] / base;
c[i] %= base;
}
// out.println(Arrays.toString(c));
int[] ret = decode(c);
for (int i = 0; i < N; i++) {
if (i != 0) out.print(" ");
out.print(ret[i]);
}
out.println();
}
static class BinaryIndexedTree {
int length;
int logLength;
int[] c;
BinaryIndexedTree(int n) {
logLength = Integer.SIZE - Integer.numberOfLeadingZeros(n);
length = 1 << logLength;
c = new int[length + 1];
}
void add(int x, int num) {
if (!(x >= 1 && x <= length)) throw new AssertionError();
for (; x <= length; x += Integer.lowestOneBit(x)) {
c[x] += num;
}
}
void insert(int x) {
add(x, 1);
}
void remove(int x) {
add(x, -1);
}
int sum(int x) {
if (!(x >= 0 && x <= length)) throw new AssertionError();
int sum = 0;
for (; x > 0; x -= Integer.lowestOneBit(x)) {
sum += c[x];
}
return sum;
}
int sum(int l, int r) {
return sum(r) - sum(l - 1);
}
int rank(int x) {
return sum(x - 1) + 1;
}
int select(int k) {
int ans = 0;
for (int i = logLength; i >= 0; i--) {
ans += (1 << i);
if (c[ans] < k) {
k -= c[ans];
} else {
ans -= (1 << i);
}
}
return ans + 1;
}
}
}
class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public double nextDouble() {
return Double.parseDouble(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public int nextInt() {
return Integer.parseInt(next());
}
}
| Java | ["2\n0 1\n0 1", "2\n0 1\n1 0", "3\n1 2 0\n2 1 0"] | 2 seconds | ["0 1", "1 0", "1 0 2"] | NotePermutations of numbers from 0 to 1 in the lexicographical order: (0,β1),β(1,β0).In the first sample Ord(p)β=β0 and Ord(q)β=β0, so the answer is .In the second sample Ord(p)β=β0 and Ord(q)β=β1, so the answer is .Permutations of numbers from 0 to 2 in the lexicographical order: (0,β1,β2),β(0,β2,β1),β(1,β0,β2),β(1,β2,β0),β(2,β0,β1),β(2,β1,β0).In the third sample Ord(p)β=β3 and Ord(q)β=β5, so the answer is . | Java 7 | standard input | [
"data structures",
"binary search",
"math"
] | ade941d5869b9a0cb18dad1e6d52218b | The first line contains an integer n (1ββ€βnββ€β200β000). The second line contains n distinct integers from 0 to nβ-β1, separated by a space, forming permutation p. The third line contains n distinct integers from 0 to nβ-β1, separated by spaces, forming permutation q. | 2,000 | Print n distinct integers from 0 to nβ-β1, forming the sum of the given permutations. Separate the numbers by spaces. | standard output | |
PASSED | 442a9664db27e01d1bb462622a97152a | train_004.jsonl | 1421053200 | Let's define the sum of two permutations p and q of numbers 0,β1,β...,β(nβ-β1) as permutation , where Perm(x) is the x-th lexicographically permutation of numbers 0,β1,β...,β(nβ-β1) (counting from zero), and Ord(p) is the number of permutation p in the lexicographical order.For example, Perm(0)β=β(0,β1,β...,βnβ-β2,βnβ-β1), Perm(n!β-β1)β=β(nβ-β1,βnβ-β2,β...,β1,β0)Misha has two permutations, p and q. Your task is to find their sum.Permutation aβ=β(a0,βa1,β...,βanβ-β1) is called to be lexicographically smaller than permutation bβ=β(b0,βb1,β...,βbnβ-β1), if for some k following conditions hold: a0β=βb0,βa1β=βb1,β...,βakβ-β1β=βbkβ-β1,βakβ<βbk. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;
public class B {
BufferedReader reader;
StringTokenizer tokenizer;
PrintWriter out;
int N;
long[] F;
int MOD;
public void solve() throws IOException {
N = nextInt();
int[] P1 = new int[N];
int[] P2 = new int[N];
for (int i = 0; i < N; i++) {
P1[i] = nextInt();
}
for (int i = 0; i < N; i++) {
P2[i] = nextInt();
}
int[] cum1 = new int[N];
int[] cum2 = new int[N];
int[] smaller = new int[N];
for (int i = 0; i < N; i++) {
int smaller1 = P1[i] - sum(cum1, P1[i]);
int smaller2 = P2[i] - sum(cum2, P2[i]);
smaller[i] = smaller1 + smaller2;
add(cum1, P1[i], 1);
add(cum2, P2[i], 1);
// out.println(i + ", " + smaller1 + ", " + smaller2 + ", " + smaller[i]);
}
int[] smaller3 = new int[N];
int carry = 0;
for (int i = N - 1; i >= 0; i--) {
int index = N - i;
int a = smaller[i] + carry;
// out.println(i + ": " + carry + ", " + a);
carry = a / index;
a %= index;
smaller3[i] = a;
}
// for (int i = 0; i < N; i++) {
// System.out.println("smaller3 " + i + ": " + smaller3[i]);
// }
int[] ans = new int[N];
int[] cum3 = new int[N];
for (int i = 1; i < N; i++) {
add(cum3, i, 1);
}
for (int i = 0; i < N; i++) {
int l = 0;
int r = N-1;
while (l < r) {
int m = (l + r + 1) / 2;
int beforeRemain = sum(cum3, m);
if (beforeRemain > smaller3[i]) {
r = m - 1;
} else {
l = m;
}
}
ans[i] = l;
add(cum3, l+1, -1);
}
for (int i = 0; i < N; i++) {
out.print(ans[i] + " ");
}
out.println();
}
// T[i] += value
public static void add(int[] t, int i, int value) {
for (; i < t.length; i |= i + 1)
t[i] += value;
}
// sum[0..i]
public static int sum(int[] t, int i) {
int res = 0;
for (; i >= 0; i = (i & (i + 1)) - 1)
res += t[i];
return res;
}
/**
* @param args
*/
public static void main(String[] args) {
new B().run();
}
public void run() {
try {
reader = new BufferedReader(new InputStreamReader(System.in));
tokenizer = null;
out = new PrintWriter(System.out);
solve();
reader.close();
out.close();
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
String nextToken() throws IOException {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
return tokenizer.nextToken();
}
}
| Java | ["2\n0 1\n0 1", "2\n0 1\n1 0", "3\n1 2 0\n2 1 0"] | 2 seconds | ["0 1", "1 0", "1 0 2"] | NotePermutations of numbers from 0 to 1 in the lexicographical order: (0,β1),β(1,β0).In the first sample Ord(p)β=β0 and Ord(q)β=β0, so the answer is .In the second sample Ord(p)β=β0 and Ord(q)β=β1, so the answer is .Permutations of numbers from 0 to 2 in the lexicographical order: (0,β1,β2),β(0,β2,β1),β(1,β0,β2),β(1,β2,β0),β(2,β0,β1),β(2,β1,β0).In the third sample Ord(p)β=β3 and Ord(q)β=β5, so the answer is . | Java 7 | standard input | [
"data structures",
"binary search",
"math"
] | ade941d5869b9a0cb18dad1e6d52218b | The first line contains an integer n (1ββ€βnββ€β200β000). The second line contains n distinct integers from 0 to nβ-β1, separated by a space, forming permutation p. The third line contains n distinct integers from 0 to nβ-β1, separated by spaces, forming permutation q. | 2,000 | Print n distinct integers from 0 to nβ-β1, forming the sum of the given permutations. Separate the numbers by spaces. | standard output | |
PASSED | 783e25c84473f8f59cf14d8f2125cfba | train_004.jsonl | 1421053200 | Let's define the sum of two permutations p and q of numbers 0,β1,β...,β(nβ-β1) as permutation , where Perm(x) is the x-th lexicographically permutation of numbers 0,β1,β...,β(nβ-β1) (counting from zero), and Ord(p) is the number of permutation p in the lexicographical order.For example, Perm(0)β=β(0,β1,β...,βnβ-β2,βnβ-β1), Perm(n!β-β1)β=β(nβ-β1,βnβ-β2,β...,β1,β0)Misha has two permutations, p and q. Your task is to find their sum.Permutation aβ=β(a0,βa1,β...,βanβ-β1) is called to be lexicographically smaller than permutation bβ=β(b0,βb1,β...,βbnβ-β1), if for some k following conditions hold: a0β=βb0,βa1β=βb1,β...,βakβ-β1β=βbkβ-β1,βakβ<βbk. | 256 megabytes | import java.util.NavigableSet;
import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.util.ArrayList;
import java.util.NoSuchElementException;
import java.util.List;
import java.math.BigInteger;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.Iterator;
import java.util.Collections;
import java.io.IOException;
import java.io.InputStream;
import java.util.Random;
import java.util.Collection;
import java.io.OutputStreamWriter;
import java.util.Comparator;
import java.util.SortedSet;
import java.util.Set;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author Nguyen Trung Hieu - vuondenthanhcong11@gmail.com
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
TaskB solver = new TaskB();
solver.solve(1, in, out);
out.close();
}
}
class TaskB {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int count = in.readInt();
int[] p = IOUtils.readIntArray(in, count);
int[] q = IOUtils.readIntArray(in, count);
SumIntervalTree pTree = new SumIntervalTree(count);
pTree.update(0, count - 1, 1);
for (int i = 0; i < count; i++) {
pTree.update(p[i], p[i], -1);
p[i] = (int) pTree.query(0, p[i]);
}
SumIntervalTree qTree = new SumIntervalTree(count);
qTree.update(0, count - 1, 1);
for (int i = 0; i < count; i++) {
qTree.update(q[i], q[i], -1);
q[i] = (int) qTree.query(0, q[i]);
}
int[] result = new int[count];
for (int i = count - 1; i >= 0; i--) {
result[i] += p[i] + q[i];
if (result[i] >= count - i) {
result[i] -= count - i;
if (i > 0) result[i - 1]++;
}
}
TreapSet<Integer> treapSet = new TreapSet<Integer>();
for (int i = 0; i < count; i++) {
treapSet.add(i);
}
for (int i = 0; i < count; i++) {
result[i] = treapSet.get(result[i]);
treapSet.remove(result[i]);
}
out.printLine(result);
}
}
class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int readInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public void print(int[] array) {
for (int i = 0; i < array.length; i++) {
if (i != 0)
writer.print(' ');
writer.print(array[i]);
}
}
public void printLine(int[] array) {
print(array);
writer.println();
}
public void close() {
writer.close();
}
}
class IOUtils {
public static int[] readIntArray(InputReader in, int size) {
int[] array = new int[size];
for (int i = 0; i < size; i++)
array[i] = in.readInt();
return array;
}
}
class SumIntervalTree extends LongIntervalTree {
public SumIntervalTree(int size) {
super(size);
}
protected long joinValue(long left, long right) {
return left + right;
}
protected long joinDelta(long was, long delta) {
return was + delta;
}
protected long accumulate(long value, long delta, int length) {
return value + delta * length;
}
protected long neutralValue() {
return 0;
}
protected long neutralDelta() {
return 0;
}
}
abstract class IntervalTree {
protected int size;
public IntervalTree(int size, boolean shouldInit) {
this.size = size;
int nodeCount = Math.max(1, Integer.highestOneBit(size) << 2);
initData(size, nodeCount);
if (shouldInit)
init();
}
protected abstract void initData(int size, int nodeCount);
protected abstract void initAfter(int root, int left, int right, int middle);
protected abstract void initBefore(int root, int left, int right, int middle);
protected abstract void initLeaf(int root, int index);
protected abstract void updatePostProcess(int root, int left, int right, int from, int to, long delta, int middle);
protected abstract void updatePreProcess(int root, int left, int right, int from, int to, long delta, int middle);
protected abstract void updateFull(int root, int left, int right, int from, int to, long delta);
protected abstract long queryPostProcess(int root, int left, int right, int from, int to, int middle, long leftResult, long rightResult);
protected abstract void queryPreProcess(int root, int left, int right, int from, int to, int middle);
protected abstract long queryFull(int root, int left, int right, int from, int to);
protected abstract long emptySegmentResult();
public void init() {
if (size == 0)
return;
init(0, 0, size - 1);
}
private void init(int root, int left, int right) {
if (left == right) {
initLeaf(root, left);
} else {
int middle = (left + right) >> 1;
initBefore(root, left, right, middle);
init(2 * root + 1, left, middle);
init(2 * root + 2, middle + 1, right);
initAfter(root, left, right, middle);
}
}
public void update(int from, int to, long delta) {
update(0, 0, size - 1, from, to, delta);
}
protected void update(int root, int left, int right, int from, int to, long delta) {
if (left > to || right < from)
return;
if (left >= from && right <= to) {
updateFull(root, left, right, from, to, delta);
return;
}
int middle = (left + right) >> 1;
updatePreProcess(root, left, right, from, to, delta, middle);
update(2 * root + 1, left, middle, from, to, delta);
update(2 * root + 2, middle + 1, right, from, to, delta);
updatePostProcess(root, left, right, from, to, delta, middle);
}
public long query(int from, int to) {
return query(0, 0, size - 1, from, to);
}
protected long query(int root, int left, int right, int from, int to) {
if (left > to || right < from)
return emptySegmentResult();
if (left >= from && right <= to)
return queryFull(root, left, right, from, to);
int middle = (left + right) >> 1;
queryPreProcess(root, left, right, from, to, middle);
long leftResult = query(2 * root + 1, left, middle, from, to);
long rightResult = query(2 * root + 2, middle + 1, right, from, to);
return queryPostProcess(root, left, right, from, to, middle, leftResult, rightResult);
}
}
class TreapSet<K> implements NavigableSet<K> {
protected static final Random rnd = new Random(239);
protected final Node nullNode;
protected final Comparator<? super K> comparator;
protected Node root;
private final K from;
private final K to;
private final boolean fromInclusive;
private final boolean toInclusive;
public TreapSet() {
this((Comparator<? super K>)null);
}
public TreapSet(Comparator<? super K> comparator) {
this(null, null, false, false, comparator, null, null);
}
protected TreapSet(K from, K to, boolean fromInclusive, boolean toInclusive, Comparator<? super K> comparator, Node root, Node nullNode) {
this.comparator = comparator;
this.from = from;
this.to = to;
this.fromInclusive = fromInclusive;
this.toInclusive = toInclusive;
if (nullNode == null)
nullNode = new NullNode();
if (root == null)
root = nullNode;
this.root = root;
this.nullNode = nullNode;
}
public boolean addAll(Iterable<? extends K> collection) {
boolean result = false;
for (K element : collection)
result |= add(element);
return result;
}
public K lower(K k) {
Node target = root.lower(k);
if (target == nullNode)
return null;
if (belongs(target.key))
return target.key;
return null;
}
private boolean belongs(K key) {
int valueFrom = compare(from, key);
int valueTo = compare(key, to);
return (valueFrom < 0 || valueFrom == 0 && fromInclusive) && (valueTo < 0 || valueTo == 0 && toInclusive);
}
public K floor(K k) {
Node target = root.floor(k);
if (target == nullNode)
return null;
if (belongs(target.key))
return target.key;
return null;
}
public K ceiling(K k) {
Node target = root.ceil(k);
if (target == nullNode)
return null;
if (belongs(target.key))
return target.key;
return null;
}
public K higher(K k) {
Node target = root.higher(k);
if (target == nullNode)
return null;
if (belongs(target.key))
return target.key;
return null;
}
public K pollFirst() {
K first = first();
if (first == null)
throw new NoSuchElementException();
root.erase(first);
return first;
}
public K pollLast() {
K last = last();
if (last == null)
throw new NoSuchElementException();
root.erase(last);
return last;
}
public int size() {
if (from == null && to == null)
return root.size;
if (from == null) {
Node to = toInclusive ? root.floor(this.to) : root.lower(this.to);
if (to == nullNode)
return 0;
return root.indexOf(to) + 1;
}
if (to == null) {
Node from = fromInclusive ? root.ceil(this.from) : root.higher(this.from);
if (from == nullNode)
return 0;
return root.size - root.indexOf(from);
}
Node from = fromInclusive ? root.ceil(this.from) : root.higher(this.from);
if (from == nullNode || !belongs(from.key))
return 0;
Node to = toInclusive ? root.floor(this.to) : root.lower(this.to);
return root.indexOf(to) - root.indexOf(from) + 1;
}
public boolean isEmpty() {
return size() == 0;
}
public boolean contains(Object o) {
return belongs((K) o) && root.search((K) o) != nullNode;
}
public Iterator<K> iterator() {
return new Iterator<K>() {
private K current = first();
public boolean hasNext() {
return current != null;
}
public K next() {
K result = current;
current = higher(current);
return result;
}
public void remove() {
TreapSet.this.remove(current);
}
};
}
public Object[] toArray() {
Object[] array = new Object[size()];
int index = 0;
for (K key : this)
array[index++] = key;
return array;
}
public <T> T[] toArray(T[] a) {
if (a.length < size())
throw new IllegalArgumentException();
int index = 0;
for (K key : this)
a[index++] = (T) key;
return a;
}
public boolean add(K k) {
if (k == null)
throw new NullPointerException();
if (contains(k))
return false;
root = root.insert(createNode(k));
return true;
}
protected Node createNode(K k) {
return new Node(k, rnd.nextLong());
}
public boolean remove(Object o) {
if (!contains(o))
return false;
//noinspection unchecked
root = root.erase((K) o);
return true;
}
public boolean containsAll(Collection<?> c) {
for (Object o : c) {
if (!contains(o))
return false;
}
return true;
}
public boolean addAll(Collection<? extends K> c) {
return addAll((Iterable<? extends K>)c);
}
public boolean retainAll(Collection<?> c) {
List<K> toRemove = new ArrayList<K>();
for (K key : this) {
if (!c.contains(key))
toRemove.add(key);
}
return removeAll(toRemove);
}
public boolean removeAll(Collection<?> c) {
boolean result = false;
for (Object o : c)
result |= remove(o);
return result;
}
public void clear() {
retainAll(Collections.<Object>emptySet());
}
public NavigableSet<K> descendingSet() {
throw new UnsupportedOperationException();
}
public Iterator<K> descendingIterator() {
return new Iterator<K>() {
private K current = last();
public boolean hasNext() {
return current != null;
}
public K next() {
K result = current;
current = lower(current);
return result;
}
public void remove() {
TreapSet.this.remove(current);
}
};
}
public NavigableSet<K> subSet(K fromElement, boolean fromInclusive, K toElement, boolean toInclusive) {
return new TreapSet<K>(fromElement, toElement, fromInclusive, toInclusive, comparator, root, nullNode);
}
public NavigableSet<K> headSet(K toElement, boolean inclusive) {
return subSet(null, false, toElement, inclusive);
}
public NavigableSet<K> tailSet(K fromElement, boolean inclusive) {
return subSet(fromElement, inclusive, null, false);
}
public Comparator<? super K> comparator() {
return comparator;
}
public SortedSet<K> subSet(K fromElement, K toElement) {
return subSet(fromElement, true, toElement, false);
}
public SortedSet<K> headSet(K toElement) {
return subSet(null, false, toElement, false);
}
public SortedSet<K> tailSet(K fromElement) {
return tailSet(fromElement, true);
}
public K first() {
if (isEmpty())
return null;
if (from == null)
return root.first().key;
if (fromInclusive)
return ceiling(from);
return higher(from);
}
public K last() {
if (isEmpty())
return null;
if (to == null)
return root.last().key;
if (toInclusive)
return floor(to);
return lower(to);
}
public K get(int index) {
if (index >= size() || index < 0)
throw new IndexOutOfBoundsException(Integer.toString(index));
if (from != null)
index += headSet(from, !fromInclusive).size();
return root.get(index);
}
protected int compare(K first, K second) {
if (first == null || second == null)
return -1;
if (comparator != null)
return comparator.compare(first, second);
//noinspection unchecked
return ((Comparable<? super K>)first).compareTo(second);
}
protected class Node {
protected final K key;
protected final long priority;
protected Node left;
protected Node right;
protected int size;
protected Node(K key, long priority) {
this.key = key;
this.priority = priority;
left = nullNode;
right = nullNode;
size = 1;
}
protected Object[] split(K key) {
if (compare(key, this.key) < 0) {
Object[] result = left.split(key);
left = (Node) result[1];
result[1] = this;
updateSize();
return result;
}
Object[] result = right.split(key);
right = (Node) result[0];
result[0] = this;
updateSize();
return result;
}
protected void updateSize() {
size = left.size + right.size + 1;
}
protected Node insert(Node node) {
if (node.priority > priority) {
Object[] result = split(node.key);
node.left = (Node) result[0];
node.right = (Node) result[1];
node.updateSize();
return node;
}
if (compare(node.key, this.key) < 0) {
left = left.insert(node);
updateSize();
return this;
}
right = right.insert(node);
updateSize();
return this;
}
protected Node merge(Node left, Node right) {
if (left == nullNode)
return right;
if (right == nullNode)
return left;
if (left.priority > right.priority) {
left.right = left.right.merge(left.right, right);
left.updateSize();
return left;
}
right.left = right.left.merge(left, right.left);
right.updateSize();
return right;
}
protected Node erase(K key) {
int value = compare(key, this.key);
if (value == 0)
return merge(left, right);
if (value < 0) {
left = left.erase(key);
updateSize();
return this;
}
right = right.erase(key);
updateSize();
return this;
}
protected Node lower(K key) {
if (compare(key, this.key) <= 0)
return left.lower(key);
Node result = right.lower(key);
if (result == nullNode)
return this;
return result;
}
protected Node floor(K key) {
if (compare(key, this.key) < 0)
return left.floor(key);
Node result = right.floor(key);
if (result == nullNode)
return this;
return result;
}
protected Node higher(K key) {
if (compare(key, this.key) >= 0)
return right.higher(key);
Node result = left.higher(key);
if (result == nullNode)
return this;
return result;
}
protected Node ceil(K key) {
if (compare(key, this.key) > 0)
return right.ceil(key);
Node result = left.ceil(key);
if (result == nullNode)
return this;
return result;
}
protected Node first() {
if (left == nullNode)
return this;
return left.first();
}
protected Node last() {
if (right == nullNode)
return this;
return right.last();
}
protected Node search(K key) {
int value = compare(key, this.key);
if (value == 0)
return this;
if (value < 0)
return left.search(key);
return right.search(key);
}
public int indexOf(Node node) {
if (this == node)
return left.size;
if (compare(node.key, this.key) > 0)
return left.size + 1 + right.indexOf(node);
return left.indexOf(node);
}
public K get(int index) {
if (index < left.size)
return left.get(index);
else if (index == left.size)
return key;
else
return right.get(index - left.size - 1);
}
}
private class NullNode extends Node {
private NullNode() {
super(null, Long.MIN_VALUE);
left = this;
right = this;
size = 0;
}
protected Object[] split(K key) {
return new Object[]{this, this};
}
protected Node insert(Node node) {
return node;
}
protected Node erase(K key) {
return this;
}
protected Node lower(K key) {
return this;
}
protected Node floor(K key) {
return this;
}
protected Node higher(K key) {
return this;
}
protected Node ceil(K key) {
return this;
}
protected Node first() {
throw new NoSuchElementException();
}
protected Node last() {
throw new NoSuchElementException();
}
protected void updateSize() {
}
protected Node search(K key) {
return this;
}
}
}
abstract class LongIntervalTree extends IntervalTree {
protected long[] value;
protected long[] delta;
protected LongIntervalTree(int size) {
this(size, true);
}
public LongIntervalTree(int size, boolean shouldInit) {
super(size, shouldInit);
}
protected void initData(int size, int nodeCount) {
value = new long[nodeCount];
delta = new long[nodeCount];
}
protected abstract long joinValue(long left, long right);
protected abstract long joinDelta(long was, long delta);
protected abstract long accumulate(long value, long delta, int length);
protected abstract long neutralValue();
protected abstract long neutralDelta();
protected long initValue(int index) {
return neutralValue();
}
protected void initAfter(int root, int left, int right, int middle) {
value[root] = joinValue(value[2 * root + 1], value[2 * root + 2]);
delta[root] = neutralDelta();
}
protected void initBefore(int root, int left, int right, int middle) {
}
protected void initLeaf(int root, int index) {
value[root] = initValue(index);
delta[root] = neutralDelta();
}
protected void updatePostProcess(int root, int left, int right, int from, int to, long delta, int middle) {
value[root] = joinValue(value[2 * root + 1], value[2 * root + 2]);
}
protected void updatePreProcess(int root, int left, int right, int from, int to, long delta, int middle) {
pushDown(root, left, middle, right);
}
protected void pushDown(int root, int left, int middle, int right) {
value[2 * root + 1] = accumulate(value[2 * root + 1], delta[root], middle - left + 1);
value[2 * root + 2] = accumulate(value[2 * root + 2], delta[root], right - middle);
delta[2 * root + 1] = joinDelta(delta[2 * root + 1], delta[root]);
delta[2 * root + 2] = joinDelta(delta[2 * root + 2], delta[root]);
delta[root] = neutralDelta();
}
protected void updateFull(int root, int left, int right, int from, int to, long delta) {
value[root] = accumulate(value[root], delta, right - left + 1);
this.delta[root] = joinDelta(this.delta[root], delta);
}
protected long queryPostProcess(int root, int left, int right, int from, int to, int middle, long leftResult, long rightResult) {
return joinValue(leftResult, rightResult);
}
protected void queryPreProcess(int root, int left, int right, int from, int to, int middle) {
pushDown(root, left, middle, right);
}
protected long queryFull(int root, int left, int right, int from, int to) {
return value[root];
}
protected long emptySegmentResult() {
return neutralValue();
}
}
| Java | ["2\n0 1\n0 1", "2\n0 1\n1 0", "3\n1 2 0\n2 1 0"] | 2 seconds | ["0 1", "1 0", "1 0 2"] | NotePermutations of numbers from 0 to 1 in the lexicographical order: (0,β1),β(1,β0).In the first sample Ord(p)β=β0 and Ord(q)β=β0, so the answer is .In the second sample Ord(p)β=β0 and Ord(q)β=β1, so the answer is .Permutations of numbers from 0 to 2 in the lexicographical order: (0,β1,β2),β(0,β2,β1),β(1,β0,β2),β(1,β2,β0),β(2,β0,β1),β(2,β1,β0).In the third sample Ord(p)β=β3 and Ord(q)β=β5, so the answer is . | Java 7 | standard input | [
"data structures",
"binary search",
"math"
] | ade941d5869b9a0cb18dad1e6d52218b | The first line contains an integer n (1ββ€βnββ€β200β000). The second line contains n distinct integers from 0 to nβ-β1, separated by a space, forming permutation p. The third line contains n distinct integers from 0 to nβ-β1, separated by spaces, forming permutation q. | 2,000 | Print n distinct integers from 0 to nβ-β1, forming the sum of the given permutations. Separate the numbers by spaces. | standard output | |
PASSED | 1e583f74edf496d7d736feec171768c0 | train_004.jsonl | 1421053200 | Let's define the sum of two permutations p and q of numbers 0,β1,β...,β(nβ-β1) as permutation , where Perm(x) is the x-th lexicographically permutation of numbers 0,β1,β...,β(nβ-β1) (counting from zero), and Ord(p) is the number of permutation p in the lexicographical order.For example, Perm(0)β=β(0,β1,β...,βnβ-β2,βnβ-β1), Perm(n!β-β1)β=β(nβ-β1,βnβ-β2,β...,β1,β0)Misha has two permutations, p and q. Your task is to find their sum.Permutation aβ=β(a0,βa1,β...,βanβ-β1) is called to be lexicographically smaller than permutation bβ=β(b0,βb1,β...,βbnβ-β1), if for some k following conditions hold: a0β=βb0,βa1β=βb1,β...,βakβ-β1β=βbkβ-β1,βakβ<βbk. | 256 megabytes | //Author: net12k44
import java.io.*;
import java.util.*;
//public
class Main{//}
static class Data{
int[] data;
Data(int n){
data = new int[n];
}
void update(int i){
while (i < data.length){
data[i]++;
i |= (i+1);
}
}
int get(int i){
int t = 0;
while (i>=0){
t += data[i];
i = (i & (i+1)) - 1;
}
return t;
}
}
private int[] cal(int n){
int[] p = new int[n];
for(int i = 0; i < n; ++i) p[i] = in.nextInt();
Data T = new Data(n);
int[] res = new int[n];
for(int i = 0; i < n; ++i){
res[i] = p[i] - T.get(p[i]);
T.update(p[i]);
}
return res;
}
private void solve() {
int n = in.nextInt();
int[] ord = cal(n), ord2 = cal(n);
for(int i = n-1, k = 1; i>=0; --i, k++){
ord[i] += ord2[i];
if (i > 0) ord[i-1] += ord[i] / k;
ord[i] %= k;
}
Data T = new Data(n);
for(int i = 0; i < n; ++i){
int dau = 0, cuoi = n-1;
while (dau <= cuoi){
int k = (dau + cuoi)/2;
if (k - T.get(k) >= ord[i])
cuoi = k-1;
else
dau = k+1;
}
out.print(dau+" ");
T.update(dau);
}
}
public static void main (String[] args) throws java.lang.Exception {
long startTime = System.currentTimeMillis();
out = new PrintWriter(System.out);
new Main().solve();
//out.println((String.format("%.2f",(double)(System.currentTimeMillis()-startTime)/1000)));
out.close();
}
static PrintWriter out;
static void println(int[] a){
for(int i = 0; i < a.length; ++i){
if (i != 0) out.print(' ');
out.print(a[i]);
}
out.println();
}
static class in {
static BufferedReader reader = new BufferedReader( new InputStreamReader(System.in) ) ;
static StringTokenizer tokenizer = new StringTokenizer("");
static String next() {
while ( !tokenizer.hasMoreTokens() )
try { tokenizer = new StringTokenizer( reader.readLine() ); }
catch (IOException e){
throw new RuntimeException(e);
}
return tokenizer.nextToken();
}
static int nextInt() { return Integer.parseInt( next() ); }
}
//////////////////////////////////////////////////
}// | Java | ["2\n0 1\n0 1", "2\n0 1\n1 0", "3\n1 2 0\n2 1 0"] | 2 seconds | ["0 1", "1 0", "1 0 2"] | NotePermutations of numbers from 0 to 1 in the lexicographical order: (0,β1),β(1,β0).In the first sample Ord(p)β=β0 and Ord(q)β=β0, so the answer is .In the second sample Ord(p)β=β0 and Ord(q)β=β1, so the answer is .Permutations of numbers from 0 to 2 in the lexicographical order: (0,β1,β2),β(0,β2,β1),β(1,β0,β2),β(1,β2,β0),β(2,β0,β1),β(2,β1,β0).In the third sample Ord(p)β=β3 and Ord(q)β=β5, so the answer is . | Java 7 | standard input | [
"data structures",
"binary search",
"math"
] | ade941d5869b9a0cb18dad1e6d52218b | The first line contains an integer n (1ββ€βnββ€β200β000). The second line contains n distinct integers from 0 to nβ-β1, separated by a space, forming permutation p. The third line contains n distinct integers from 0 to nβ-β1, separated by spaces, forming permutation q. | 2,000 | Print n distinct integers from 0 to nβ-β1, forming the sum of the given permutations. Separate the numbers by spaces. | standard output | |
PASSED | 2e3d766c3ee4ab747b8a033a81723665 | train_004.jsonl | 1421053200 | Let's define the sum of two permutations p and q of numbers 0,β1,β...,β(nβ-β1) as permutation , where Perm(x) is the x-th lexicographically permutation of numbers 0,β1,β...,β(nβ-β1) (counting from zero), and Ord(p) is the number of permutation p in the lexicographical order.For example, Perm(0)β=β(0,β1,β...,βnβ-β2,βnβ-β1), Perm(n!β-β1)β=β(nβ-β1,βnβ-β2,β...,β1,β0)Misha has two permutations, p and q. Your task is to find their sum.Permutation aβ=β(a0,βa1,β...,βanβ-β1) is called to be lexicographically smaller than permutation bβ=β(b0,βb1,β...,βbnβ-β1), if for some k following conditions hold: a0β=βb0,βa1β=βb1,β...,βakβ-β1β=βbkβ-β1,βakβ<βbk. | 256 megabytes | import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StreamTokenizer;
import java.util.Scanner;
public class B {
static boolean solve() throws IOException {
int n = nextInt();
if ( n < 0 ) {
return false;
}
int[][] ord = new int[2][];
for ( int num = 0; num < 2; num ++ ) {
int[] p = new int[n];
for (int i = 0; i < n; i++) {
p[i] = nextInt();
}
ord[num] = ord( p );
}
for ( int i = 0; i < n; i ++ ) {
ord[0][i] += ord[1][i];
if ( ord[0][i] >= i + 1 ) {
ord[0][i] -= i + 1;
if ( i + 1 < n ) {
ord[0][i + 1] ++;
}
}
}
int[] p = perm( ord[0] );
for ( int i = 0; i < n; i ++ ) {
out.print( p[i] + " " );
}
out.println();
return true;
}
private static int[] perm(int[] ord) {
int n = ord.length;
FTree f = new FTree( n );
int[] p = new int[n];
for ( int i = n - 1; i >= 0; i -- ) {
p[n - 1 - i] = findLast(f, ord[i]);
f.inc( p[n - 1 - i] );
}
return p;
}
private static int[] ord(int[] p) {
int n = p.length;
FTree f = new FTree( n );
int[] r = new int[n];
for ( int i = n - 1; i >= 0; i -- ) {
r[n - 1 - i] = f.sum( p[i] );
f.inc( p[i] );
}
return r;
}
static int findLast(FTree f, int pos) {
int l = 0;
int r = f.size - 1;
while ( l < r ) {
int m = ( l + r ) / 2;
if ( m - f.sum(m) < pos ) {
l = m + 1;
} else {
r = m;
}
}
return l;
}
private static class FTree {
int size;
int[] s;
FTree( int n ) {
size = n;
s = new int[n + 1];
}
void inc( int pos ) {
pos ++;
while ( pos < s.length ) {
s[pos] ++;
pos = ( pos | ( pos - 1 ) ) + 1;
}
}
int sum( int pos ) {
int r = 0;
pos ++;
while ( pos > 0 ) {
r += s[pos];
pos &= pos - 1;
}
return r;
}
}
static StreamTokenizer in;
static PrintWriter out;
static int nextInt() throws IOException {
if ( in.nextToken() != StreamTokenizer.TT_NUMBER )
return -1;
return ( int ) in.nval;
}
public static void main( String[] args ) throws IOException {
in = new StreamTokenizer( new InputStreamReader( System.in ) );
out = new PrintWriter( System.out );
while ( solve() );
out.close();
}
}
| Java | ["2\n0 1\n0 1", "2\n0 1\n1 0", "3\n1 2 0\n2 1 0"] | 2 seconds | ["0 1", "1 0", "1 0 2"] | NotePermutations of numbers from 0 to 1 in the lexicographical order: (0,β1),β(1,β0).In the first sample Ord(p)β=β0 and Ord(q)β=β0, so the answer is .In the second sample Ord(p)β=β0 and Ord(q)β=β1, so the answer is .Permutations of numbers from 0 to 2 in the lexicographical order: (0,β1,β2),β(0,β2,β1),β(1,β0,β2),β(1,β2,β0),β(2,β0,β1),β(2,β1,β0).In the third sample Ord(p)β=β3 and Ord(q)β=β5, so the answer is . | Java 7 | standard input | [
"data structures",
"binary search",
"math"
] | ade941d5869b9a0cb18dad1e6d52218b | The first line contains an integer n (1ββ€βnββ€β200β000). The second line contains n distinct integers from 0 to nβ-β1, separated by a space, forming permutation p. The third line contains n distinct integers from 0 to nβ-β1, separated by spaces, forming permutation q. | 2,000 | Print n distinct integers from 0 to nβ-β1, forming the sum of the given permutations. Separate the numbers by spaces. | standard output | |
PASSED | 120ccbfc705c1b4acd55456ee2b02ef7 | train_004.jsonl | 1421053200 | Let's define the sum of two permutations p and q of numbers 0,β1,β...,β(nβ-β1) as permutation , where Perm(x) is the x-th lexicographically permutation of numbers 0,β1,β...,β(nβ-β1) (counting from zero), and Ord(p) is the number of permutation p in the lexicographical order.For example, Perm(0)β=β(0,β1,β...,βnβ-β2,βnβ-β1), Perm(n!β-β1)β=β(nβ-β1,βnβ-β2,β...,β1,β0)Misha has two permutations, p and q. Your task is to find their sum.Permutation aβ=β(a0,βa1,β...,βanβ-β1) is called to be lexicographically smaller than permutation bβ=β(b0,βb1,β...,βbnβ-β1), if for some k following conditions hold: a0β=βb0,βa1β=βb1,β...,βakβ-β1β=βbkβ-β1,βakβ<βbk. | 256 megabytes | import java.io.*;
import java.util.*;
public class BMain {
String noResultMessage = "NoResult";
Parser in = new Parser();
PrintWriter out;
int n = in.nextInteger();
int[] p = in.nextIntegers(n);
int[] q = in.nextIntegers(n);
boolean[] done = new boolean[n];
int[] calc(int[] p){
int[] pos = new int[n];
Counts counts = new Counts(n);
for(int i = 0; i < n; ++i){
int v = p[i];
counts.add(v, 1);
pos[i] = v - counts.pos(v);
}
return pos;
}
public void solve() {
int[] posP = calc(p);
int[] posQ = calc(q);
int[] pos = new int[n];
int delta = 0;
for(int i = 0; i < n; ++i){
int p = n - i - 1;
int val = posP[p] + posQ[p] + delta;
delta = val / (i + 1);
pos[p] = val % (i + 1);
}
Counts counts = new Counts(n);
for(int i = 0; i < n; ++i){
counts.add(i, 1);
}
for(int p : pos){
int val = counts.at(p);
counts.add(val, -1);
out.print(" " + val);
}
}
static class Counts {
int N;
int[] counts;
int up;
Counts(int n) {
N = n;
up = n;
while((up & (up-1)) != 0) up &= up-1;
up = up * 2 - 1;
counts = new int[up + N];
}
void add(int n, int d){
n += up;
while(n > 0){
counts[n] += d;
n = (n - 1) / 2;
}
}
int pos(int n){
n += up;
int count = 0;
while(n > 0){
if((n&1) == 0){
count += counts[n-1];
}
n = (n - 1) / 2;
}
return count;
}
int at(int pos){
pos += 1;
int n = 1;
while(n < up){
if(counts[n] < pos) {
pos -= counts[n];
++n;
}
n = n*2 + 1;
}
if(counts[n] < pos) ++n;
return n - up;
}
}
static public class Parser{
Scanner scanner;
public Parser() {
scanner = new Scanner(System.in).useLocale(Locale.ENGLISH);
}
public Parser(String str) {
scanner = new Scanner(str).useLocale(Locale.ENGLISH);
}
long nextLong(){
return scanner.nextLong();
}
int nextInteger(){
return scanner.nextInt();
}
double nextDouble(){
return scanner.nextDouble();
}
String nextLine(){
return scanner.nextLine();
}
String next(){
return scanner.next();
}
int[] nextIntegers(int count){
int[] result = new int[count];
for(int i = 0; i < count; ++i){
result[i] = nextInteger();
}
return result;
}
long[] nextLongs(int count){
long[] result = new long[count];
for(int i = 0; i < count; ++i){
result[i] = nextLong();
}
return result;
}
int[][] nextIntegers(int fields, int count){
int[][] result = new int[fields][count];
for(int c = 0; c < count; ++c){
for(int i = 0; i < fields; ++i){
result[i][c] = nextInteger();
}
}
return result;
}
}
void noResult(){
throw new NoResultException();
}
void noResult(String str){
throw new NoResultException(str);
}
void run(){
try{
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
out = new PrintWriter(System.out);
solve();
out.close();
System.out.print(outStream.toString());
} catch (NoResultException exc){
System.out.print(null == exc.response ? noResultMessage : exc.response);
}
}
public static void main(String[] args) {
new BMain().run();
}
public static class NoResultException extends RuntimeException{
private String response;
public NoResultException(String response) {
this.response = response;
}
public NoResultException() {
}
}
}
| Java | ["2\n0 1\n0 1", "2\n0 1\n1 0", "3\n1 2 0\n2 1 0"] | 2 seconds | ["0 1", "1 0", "1 0 2"] | NotePermutations of numbers from 0 to 1 in the lexicographical order: (0,β1),β(1,β0).In the first sample Ord(p)β=β0 and Ord(q)β=β0, so the answer is .In the second sample Ord(p)β=β0 and Ord(q)β=β1, so the answer is .Permutations of numbers from 0 to 2 in the lexicographical order: (0,β1,β2),β(0,β2,β1),β(1,β0,β2),β(1,β2,β0),β(2,β0,β1),β(2,β1,β0).In the third sample Ord(p)β=β3 and Ord(q)β=β5, so the answer is . | Java 7 | standard input | [
"data structures",
"binary search",
"math"
] | ade941d5869b9a0cb18dad1e6d52218b | The first line contains an integer n (1ββ€βnββ€β200β000). The second line contains n distinct integers from 0 to nβ-β1, separated by a space, forming permutation p. The third line contains n distinct integers from 0 to nβ-β1, separated by spaces, forming permutation q. | 2,000 | Print n distinct integers from 0 to nβ-β1, forming the sum of the given permutations. Separate the numbers by spaces. | standard output | |
PASSED | 650d022e530a1b8d8efb1f3e5c1ef219 | train_004.jsonl | 1421053200 | Let's define the sum of two permutations p and q of numbers 0,β1,β...,β(nβ-β1) as permutation , where Perm(x) is the x-th lexicographically permutation of numbers 0,β1,β...,β(nβ-β1) (counting from zero), and Ord(p) is the number of permutation p in the lexicographical order.For example, Perm(0)β=β(0,β1,β...,βnβ-β2,βnβ-β1), Perm(n!β-β1)β=β(nβ-β1,βnβ-β2,β...,β1,β0)Misha has two permutations, p and q. Your task is to find their sum.Permutation aβ=β(a0,βa1,β...,βanβ-β1) is called to be lexicographically smaller than permutation bβ=β(b0,βb1,β...,βbnβ-β1), if for some k following conditions hold: a0β=βb0,βa1β=βb1,β...,βakβ-β1β=βbkβ-β1,βakβ<βbk. | 256 megabytes |
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.HashSet;
import java.util.InputMismatchException;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Set;
import java.util.TreeSet;
// *******************εΎ©ηΏγγγ***********************
public class D {
FastScanner in = new FastScanner(System.in);
PrintWriter out = new PrintWriter(System.out);
class BIT {
int bitA;
int[] bit;
public BIT(int maxa) {
bitA = maxa;
bit = new int[bitA + 1];
}
public void update(int a, int val) {
for (int i = a; i <= bitA; i = i | (i + 1)) {
bit[i] += val;
}
}
public int calc(int max, int min) {
return calc(max) - calc(min - 1);
}
public int calc(int a) {
int res = 0;
for (int i = a; i >= 0; i = (i & (i + 1)) - 1) {
res += bit[i];
}
return res;
}
}
int[] getId(int[] perm) {
int n = perm.length;
int[] res = new int[n - 1];
BIT bit = new BIT(n);
for (int i = 0; i < n - 1; i++) {
res[i] = perm[i] - bit.calc(perm[i]);
bit.update(perm[i], 1);
}
return res;
}
int[] genPerm(int[] id) {
int n = id.length + 1;
BIT bit = new BIT(n);
int[] res = new int[n];
for (int i = 0; i < n; i++) {
int l = -1, r = n;
int myid = i == n - 1 ? 0 : id[i];
myid++;
while (r - l > 1) {
int mid = (l + r) >>> 1;
if (mid + 1 - bit.calc(mid) >= myid) r = mid;
else l = mid;
}
res[i] = r;
bit.update(res[i], 1);
}
return res;
}
public void run() {
int n = in.nextInt();
int[] p = in.nextIntArray(n), q = in.nextIntArray(n);
int[] id1 = getId(p);
int[] id2 = getId(q);
int[] myId = new int[n - 1];
int mod = 2, add = 0;
for (int i = n - 2; i >= 0; i--) {
myId[i] = (id1[i] + id2[i] + add) % mod;
add = (id1[i] + id2[i] + add) / mod;
mod++;
}
int[] ans = genPerm(myId);
// System.out.println(Arrays.toString(p) + " " + Arrays.toString(id1));
// System.out.println(Arrays.toString(q) + " " + Arrays.toString(id2));
// System.out.println(Arrays.toString(ans) + " " + Arrays.toString(myId));
for (int x : ans) out.print(x + " ");
out.println();
out.close();
}
public static void main(String[] args) {
new D().run();
}
public void mapDebug(int[][] a) {
System.out.println("--------map display---------");
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[i].length; j++) {
System.out.printf("%3d ", a[i][j]);
}
System.out.println();
}
System.out.println("----------------------------");
System.out.println();
}
public void debug(Object... obj) {
System.out.println(Arrays.deepToString(obj));
}
class FastScanner {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public FastScanner(InputStream stream) {
this.stream = stream;
//stream = new FileInputStream(new File("dec.in"));
}
int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
boolean isEndline(int c) {
return c == '\n' || c == '\r' || c == -1;
}
int nextInt() {
return Integer.parseInt(next());
}
int[] nextIntArray(int n) {
int[] array = new int[n];
for (int i = 0; i < n; i++)
array[i] = nextInt();
return array;
}
int[][] nextIntMap(int n, int m) {
int[][] map = new int[n][m];
for (int i = 0; i < n; i++) {
map[i] = in.nextIntArray(m);
}
return map;
}
long nextLong() {
return Long.parseLong(next());
}
long[] nextLongArray(int n) {
long[] array = new long[n];
for (int i = 0; i < n; i++)
array[i] = nextLong();
return array;
}
long[][] nextLongMap(int n, int m) {
long[][] map = new long[n][m];
for (int i = 0; i < n; i++) {
map[i] = in.nextLongArray(m);
}
return map;
}
double nextDouble() {
return Double.parseDouble(next());
}
double[] nextDoubleArray(int n) {
double[] array = new double[n];
for (int i = 0; i < n; i++)
array[i] = nextDouble();
return array;
}
double[][] nextDoubleMap(int n, int m) {
double[][] map = new double[n][m];
for (int i = 0; i < n; i++) {
map[i] = in.nextDoubleArray(m);
}
return map;
}
String next() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
String[] nextStringArray(int n) {
String[] array = new String[n];
for (int i = 0; i < n; i++)
array[i] = next();
return array;
}
String nextLine() {
int c = read();
while (isEndline(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndline(c));
return res.toString();
}
}
}
| Java | ["2\n0 1\n0 1", "2\n0 1\n1 0", "3\n1 2 0\n2 1 0"] | 2 seconds | ["0 1", "1 0", "1 0 2"] | NotePermutations of numbers from 0 to 1 in the lexicographical order: (0,β1),β(1,β0).In the first sample Ord(p)β=β0 and Ord(q)β=β0, so the answer is .In the second sample Ord(p)β=β0 and Ord(q)β=β1, so the answer is .Permutations of numbers from 0 to 2 in the lexicographical order: (0,β1,β2),β(0,β2,β1),β(1,β0,β2),β(1,β2,β0),β(2,β0,β1),β(2,β1,β0).In the third sample Ord(p)β=β3 and Ord(q)β=β5, so the answer is . | Java 7 | standard input | [
"data structures",
"binary search",
"math"
] | ade941d5869b9a0cb18dad1e6d52218b | The first line contains an integer n (1ββ€βnββ€β200β000). The second line contains n distinct integers from 0 to nβ-β1, separated by a space, forming permutation p. The third line contains n distinct integers from 0 to nβ-β1, separated by spaces, forming permutation q. | 2,000 | Print n distinct integers from 0 to nβ-β1, forming the sum of the given permutations. Separate the numbers by spaces. | standard output | |
PASSED | e0b52019b61afbad0ac230eae42dd76c | train_004.jsonl | 1355047200 | Petya has got 2n cards, each card contains some integer. The numbers on the cards can be the same. Let's index all cards by consecutive integers from 1 to 2n. We'll denote the number that is written on a card with number i, as ai. In order to play one entertaining game with his friends, Petya needs to split the cards into pairs so that each pair had equal numbers on the cards. Help Petya do that. | 256 megabytes |
import java.util.*;
import java.io.*;
import java.math.*;
import java.util.regex.*;
public class Main {
static InputReader in;
static class Pair implements Comparable<Pair> {
int a, b;
public Pair(int a, int b){
this.a = a;
this.b = b;
}
public int compareTo( Pair p ){
return a-p.a;
}
}
public static void main(String[] args) throws IOException{
File file = new File("input.txt");
if(file.exists())in = new InputReader( new FileInputStream(file) );
else in = new InputReader( System.in );
PrintWriter out=new PrintWriter("output.txt");
int n=2*in.nextInt();
Pair a[]=new Pair[n];
for( int i=0; i<n; i++ ) a[i]= new Pair( in.nextInt(), i+1) ;
Arrays.sort(a);
boolean can=true;
for( int i=0; can && i<n; i+=2 ) if( a[i].a!=a[i+1].a ) can=false;
if( can )
for(int i=0; i<n; i+=2)
out.println( a[i].b + " " + a[i+1].b );
else out.println("-1");
out.close();
}
// IO utilities:
static void out(Object ...o){
System.out.println(Arrays.deepToString(o));
}
static class InputReader {
private BufferedInputStream inp;
private int offset;
private final int size=5120000;
private byte buff[];
InputReader( InputStream in ) throws IOException {
inp = new BufferedInputStream( in );
buff=new byte[size];
offset=0;
inp.read( buff, 0, size );
}
int nextInt() throws IOException {
int parsedInt=0;
int i=offset;
if( buff[i]==0 ) throw new IOException(); //EOF
// skip any non digits
while ( i<size && ( buff[i]<'0' || buff[i]>'9' ) ) i++;
// read digits and parse number
while( i<size && buff[i]>='0' && buff[i]<='9') {
parsedInt*=10;
parsedInt+=buff[i]-'0';
i++;
}
// check if we reached end of buffer
if ( i==size ) {
// copy leftovers to buffer start
int j = 0;
for ( ; offset<buff.length; j++, offset++ )
buff[j] = buff[offset];
// and now fill the buffer
inp.read( buff, j, size - j );
// and attempt to parse int again
offset = 0;
parsedInt = nextInt();
} else offset=i;
return parsedInt;
}
long nextLong() throws IOException{
long parsedLong=0;
int i=offset;
if( buff[i]==0 ) throw new IOException(); //EOF
// skip any non digits
while( i<size && ( buff[i]<'0' || buff[i]>'9' ) ) i++;
// read digits and parse number
while( i<size && buff[i]>='0' && buff[i]<='9') {
parsedLong*=10L;
parsedLong+=buff[i]-'0';
i++;
}
// check if we reached end of buffer
if ( i==size ) {
// copy leftovers to buffer start
int j = 0;
for ( ; offset<buff.length; j++, offset++ )
buff[j] = buff[offset];
// and now fill the buffer
inp.read( buff, j, size - j );
// and attempt to parse int again
offset = 0;
parsedLong = nextLong();
} else offset=i;
return parsedLong;
}
String next() throws IOException {
StringBuilder token=new StringBuilder();
int i=offset;
if( buff[i]==0 ) throw new IOException(); //EOF
// skip any non chars
while( i<size && ( buff[i]=='\n' || buff[i]==' ' || buff[i]=='\r' ||
buff[i]=='\t' ) ) i++;
// read chars
while( i<size && buff[i]!='\n' && buff[i]!=' ' && buff[i]!='\r' &&
buff[i]!='\t' && buff[i]!=0 ) {
token.append( (char)buff[i] );
i++;
}
// check if we reached end of buffer
if ( i==size ) {
// copy leftovers to buffer start
int j = 0;
for ( ; offset<buff.length; j++, offset++ )
buff[j] = buff[offset];
// and now fill the buffer
inp.read( buff, j, size - j );
// and attempt to parse int again
offset = 0;
return next();
} else offset=i;
return token.toString();
}
String nextLine() throws IOException {
StringBuilder line=new StringBuilder();
int i=offset;
if( buff[i]==0 ) throw new IOException(); //EOF
// read chars
while( i<size && buff[i]!='\n' && buff[i]!=0 ) {
line.append( (char)buff[i] );
i++;
}
if( i<size && buff[i]=='\n' ) i++;
// check if we reached end of buffer
if ( i==size ) {
// copy leftovers to buffer start
int j = 0;
for ( ; offset<buff.length; j++, offset++ )
buff[j] = buff[offset];
// and now fill the buffer
inp.read( buff, j, size - j );
// and attempt to parse int again
offset = 0;
return nextLine();
} else offset=i;
line.deleteCharAt( line.length()-1 );
return line.toString();
}
}
} | Java | ["3\n20 30 10 30 20 10", "1\n1 2"] | 1 second | ["4 2\n1 5\n6 3", "-1"] | null | Java 7 | input.txt | [
"constructive algorithms",
"sortings"
] | 0352429425782d7fe44818594eb0660c | The first line contains integer n (1ββ€βnββ€β3Β·105). The second line contains the sequence of 2n positive integers a1,βa2,β...,βa2n (1ββ€βaiββ€β5000) β the numbers that are written on the cards. The numbers on the line are separated by single spaces. | 1,200 | If it is impossible to divide the cards into pairs so that cards in each pair had the same numbers, print on a single line integer -1. But if the required partition exists, then print n pairs of integers, a pair per line β the indices of the cards that form the pairs. Separate the numbers on the lines by spaces. You can print the pairs and the numbers in the pairs in any order. If there are multiple solutions, print any of them. | output.txt | |
PASSED | 5ce853da8b7ee5284eb9d5e4283234c2 | train_004.jsonl | 1355047200 | Petya has got 2n cards, each card contains some integer. The numbers on the cards can be the same. Let's index all cards by consecutive integers from 1 to 2n. We'll denote the number that is written on a card with number i, as ai. In order to play one entertaining game with his friends, Petya needs to split the cards into pairs so that each pair had equal numbers on the cards. Help Petya do that. | 256 megabytes | import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.InputMismatchException;
public class CardsWithNumbers {
public static void main(String[] args) throws FileNotFoundException {
FasterScanner sc = new FasterScanner();
PrintWriter out = new PrintWriter("output.txt");
int N = sc.nextInt();
StringBuilder sb = new StringBuilder();
int[] pos = new int[5001];
for (int i = 1; i <= 2 * N; i++) {
int A = sc.nextInt();
if (pos[A] > 0) {
sb.append(i + " " + pos[A] + "\n");
pos[A] = 0;
} else {
pos[A] = i;
}
}
for (int p : pos) {
if (p > 0) {
out.println(-1);
out.close();
return;
}
}
out.print(sb.toString());
out.close();
}
public static class FasterScanner {
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputStream stream;
public FasterScanner() throws FileNotFoundException {
stream = new FileInputStream("input.txt");
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public String nextString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public long nextLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int nextInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n) {
return nextIntArray(n, 0);
}
public int[] nextIntArray(int n, int off) {
int[] arr = new int[n + off];
for (int i = 0; i < n; i++) {
arr[i + off] = nextInt();
}
return arr;
}
public long[] nextLongArray(int n) {
return nextLongArray(n, 0);
}
public long[] nextLongArray(int n, int off) {
long[] arr = new long[n + off];
for (int i = 0; i < n; i++) {
arr[i + off] = nextLong();
}
return arr;
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
public void close() throws IOException {
stream.close();
}
}
} | Java | ["3\n20 30 10 30 20 10", "1\n1 2"] | 1 second | ["4 2\n1 5\n6 3", "-1"] | null | Java 7 | input.txt | [
"constructive algorithms",
"sortings"
] | 0352429425782d7fe44818594eb0660c | The first line contains integer n (1ββ€βnββ€β3Β·105). The second line contains the sequence of 2n positive integers a1,βa2,β...,βa2n (1ββ€βaiββ€β5000) β the numbers that are written on the cards. The numbers on the line are separated by single spaces. | 1,200 | If it is impossible to divide the cards into pairs so that cards in each pair had the same numbers, print on a single line integer -1. But if the required partition exists, then print n pairs of integers, a pair per line β the indices of the cards that form the pairs. Separate the numbers on the lines by spaces. You can print the pairs and the numbers in the pairs in any order. If there are multiple solutions, print any of them. | output.txt | |
PASSED | b26744b5df0a3e2fc4a51500c78fdbb6 | train_004.jsonl | 1355047200 | Petya has got 2n cards, each card contains some integer. The numbers on the cards can be the same. Let's index all cards by consecutive integers from 1 to 2n. We'll denote the number that is written on a card with number i, as ai. In order to play one entertaining game with his friends, Petya needs to split the cards into pairs so that each pair had equal numbers on the cards. Help Petya do that. | 256 megabytes | import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Arrays;
public class Game_Cards {
static int numOutputs;
public static void main (String[] args) throws IOException {
BufferedReader br;
br = new BufferedReader(new FileReader("input.txt"));
String line;
line = br.readLine();
numOutputs = Integer.parseInt(line);
line = br.readLine();
String results[] = line.split(" ");
solve(results);
}
public static void solve (String[] results) throws IOException {
BufferedWriter bw = new BufferedWriter(new FileWriter("output.txt"));
if ((results.length % 2) != 0) {
bw.write(-1+"");
}
else {
int[] numResults = new int[results.length];
MyNode[] myNodes = new MyNode[results.length];
for (int i = 0; i < results.length; i++) {
numResults[i] = Integer.parseInt(results[i]);
myNodes[i] = new MyNode(i+1, numResults[i]);
}
Arrays.sort(numResults);
Arrays.sort(myNodes);
boolean valid = true;
for (int i = 0; i < myNodes.length; i+=2) {
if (numResults[i] != numResults[i+1]) {
valid = false;
break;
}
}
if (valid) {
int count = 0;
for (int i = 0; i < numOutputs; i++) {
bw.write(myNodes[count++].getIndex() + " " + myNodes[count++].getIndex());
bw.newLine();
}
}
else bw.write(-1+"");
}
bw.close();
}
}
class MyNode implements Comparable<MyNode> {
private int index;
private int value;
public MyNode(int index, int value) {
this.index = index;
this.value = value;
}
public int compareTo(MyNode node) {
if (value > node.getValue()) {
return 1;
}
else if (value < node.getValue()) {
return -1;
}
return 0;
}
public int getIndex() {
return index;
}
public int getValue() {
return value;
}
} | Java | ["3\n20 30 10 30 20 10", "1\n1 2"] | 1 second | ["4 2\n1 5\n6 3", "-1"] | null | Java 7 | input.txt | [
"constructive algorithms",
"sortings"
] | 0352429425782d7fe44818594eb0660c | The first line contains integer n (1ββ€βnββ€β3Β·105). The second line contains the sequence of 2n positive integers a1,βa2,β...,βa2n (1ββ€βaiββ€β5000) β the numbers that are written on the cards. The numbers on the line are separated by single spaces. | 1,200 | If it is impossible to divide the cards into pairs so that cards in each pair had the same numbers, print on a single line integer -1. But if the required partition exists, then print n pairs of integers, a pair per line β the indices of the cards that form the pairs. Separate the numbers on the lines by spaces. You can print the pairs and the numbers in the pairs in any order. If there are multiple solutions, print any of them. | output.txt | |
PASSED | 47430b00ae7a828e317012136a571b3c | train_004.jsonl | 1355047200 | Petya has got 2n cards, each card contains some integer. The numbers on the cards can be the same. Let's index all cards by consecutive integers from 1 to 2n. We'll denote the number that is written on a card with number i, as ai. In order to play one entertaining game with his friends, Petya needs to split the cards into pairs so that each pair had equal numbers on the cards. Help Petya do that. | 256 megabytes | import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class Cards {
public static void main(String a[])throws IOException{
BufferedReader b = new BufferedReader(new FileReader("input.txt"));
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(
"output.txt")));
int i = 0, n = 0, m = 0, k = 0;
String s;
n = Integer.parseInt(b.readLine());
int e[][] = new int[n][2];
int f[] = new int[5001];
s = b.readLine();
StringTokenizer z = new StringTokenizer(s);
for (i = 1; i <= 2 * n; i++) {
m = Integer.parseInt(z.nextToken());
if (f[m] == 0)
f[m] = i;
else {
e[k][0] = f[m];
e[k++][1] = i;
f[m] = 0;
}
}
if (k != n)
out.print("-1");
else {
for (i = 0; i < n; i++)
out.println(e[i][0] + " " + e[i][1]);
}
out.close();
}
} | Java | ["3\n20 30 10 30 20 10", "1\n1 2"] | 1 second | ["4 2\n1 5\n6 3", "-1"] | null | Java 7 | input.txt | [
"constructive algorithms",
"sortings"
] | 0352429425782d7fe44818594eb0660c | The first line contains integer n (1ββ€βnββ€β3Β·105). The second line contains the sequence of 2n positive integers a1,βa2,β...,βa2n (1ββ€βaiββ€β5000) β the numbers that are written on the cards. The numbers on the line are separated by single spaces. | 1,200 | If it is impossible to divide the cards into pairs so that cards in each pair had the same numbers, print on a single line integer -1. But if the required partition exists, then print n pairs of integers, a pair per line β the indices of the cards that form the pairs. Separate the numbers on the lines by spaces. You can print the pairs and the numbers in the pairs in any order. If there are multiple solutions, print any of them. | output.txt | |
PASSED | fb630c3cd0be1fda538cc234a60a7127 | train_004.jsonl | 1355047200 | Petya has got 2n cards, each card contains some integer. The numbers on the cards can be the same. Let's index all cards by consecutive integers from 1 to 2n. We'll denote the number that is written on a card with number i, as ai. In order to play one entertaining game with his friends, Petya needs to split the cards into pairs so that each pair had equal numbers on the cards. Help Petya do that. | 256 megabytes | import java.util.*;
import java.io.*;
import java.awt.Point;
import java.math.BigDecimal;
import java.math.BigInteger;
import static java.lang.Math.*;
// Solution is at the bottom of code
public class A implements Runnable{
final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null;
BufferedReader in;
OutputWriter out;
StringTokenizer tok = new StringTokenizer("");
public static void main(String[] args){
new Thread(null, new A(), "", 128 * (1L << 20)).start();
}
/////////////////////////////////////////////////////////////////////
void init() throws FileNotFoundException{
Locale.setDefault(Locale.US);
in = new BufferedReader(new FileReader("input.txt"));
out = new OutputWriter("output.txt");
}
////////////////////////////////////////////////////////////////
long timeBegin, timeEnd;
void time(){
timeEnd = System.currentTimeMillis();
System.err.println("Time = " + (timeEnd - timeBegin));
}
void debug(Object... objects){
if (ONLINE_JUDGE){
for (Object o: objects){
System.err.println(o.toString());
}
}
}
/////////////////////////////////////////////////////////////////////
public void run(){
try{
timeBegin = System.currentTimeMillis();
Locale.setDefault(Locale.US);
init();
solve();
out.close();
time();
}catch (Exception e){
e.printStackTrace(System.err);
System.exit(-1);
}
}
/////////////////////////////////////////////////////////////////////
String delim = " ";
String readString() throws IOException{
while(!tok.hasMoreTokens()){
try{
tok = new StringTokenizer(in.readLine());
}catch (Exception e){
return null;
}
}
return tok.nextToken(delim);
}
String readLine() throws IOException{
return in.readLine();
}
/////////////////////////////////////////////////////////////////
final char NOT_A_SYMBOL = '\0';
char readChar() throws IOException{
int intValue = in.read();
if (intValue == -1){
return NOT_A_SYMBOL;
}
return (char) intValue;
}
char[] readCharArray() throws IOException{
return readLine().toCharArray();
}
/////////////////////////////////////////////////////////////////
int readInt() throws IOException{
return Integer.parseInt(readString());
}
int[] readIntArray(int size) throws IOException{
int[] array = new int[size];
for (int index = 0; index < size; ++index){
array[index] = readInt();
}
return array;
}
///////////////////////////////////////////////////////////////////
long readLong() throws IOException{
return Long.parseLong(readString());
}
long[] readLongArray(int size) throws IOException{
long[] array = new long[size];
for (int index = 0; index < size; ++index){
array[index] = readLong();
}
return array;
}
////////////////////////////////////////////////////////////////////
double readDouble() throws IOException{
return Double.parseDouble(readString());
}
double[] readDoubleArray(int size) throws IOException{
double[] array = new double[size];
for (int index = 0; index < size; ++index){
array[index] = readDouble();
}
return array;
}
////////////////////////////////////////////////////////////////////
BigInteger readBigInteger() throws IOException {
return new BigInteger(readString());
}
BigDecimal readBigDecimal() throws IOException {
return new BigDecimal(readString());
}
/////////////////////////////////////////////////////////////////////
Point readPoint() throws IOException{
int x = readInt();
int y = readInt();
return new Point(x, y);
}
Point[] readPointArray(int size) throws IOException{
Point[] array = new Point[size];
for (int index = 0; index < size; ++index){
array[index] = readPoint();
}
return array;
}
/////////////////////////////////////////////////////////////////////
List<Integer>[] readGraph(int vertexNumber, int edgeNumber)
throws IOException{
@SuppressWarnings("unchecked")
List<Integer>[] graph = new List[vertexNumber];
for (int index = 0; index < vertexNumber; ++index){
graph[index] = new ArrayList<Integer>();
}
while (edgeNumber-- > 0){
int from = readInt() - 1;
int to = readInt() - 1;
graph[from].add(to);
graph[to].add(from);
}
return graph;
}
/////////////////////////////////////////////////////////////////////
static class IntIndexPair {
static Comparator<IntIndexPair> increaseComparator = new Comparator<A.IntIndexPair>() {
@Override
public int compare(IntIndexPair indexPair1, IntIndexPair indexPair2) {
int value1 = indexPair1.value;
int value2 = indexPair2.value;
if (value1 != value2) return value1 - value2;
int index1 = indexPair1.index;
int index2 = indexPair2.index;
return index1 - index2;
}
};
static Comparator<IntIndexPair> decreaseComparator = new Comparator<A.IntIndexPair>() {
@Override
public int compare(IntIndexPair indexPair1, IntIndexPair indexPair2) {
int value1 = indexPair1.value;
int value2 = indexPair2.value;
if (value1 != value2) return -(value1 - value2);
int index1 = indexPair1.index;
int index2 = indexPair2.index;
return index1 - index2;
}
};
int value, index;
public IntIndexPair(int value, int index) {
super();
this.value = value;
this.index = index;
}
}
IntIndexPair[] readIntIndexArray(int size) throws IOException {
IntIndexPair[] array = new IntIndexPair[size];
for (int index = 0; index < size; ++index) {
array[index] = new IntIndexPair(readInt(), index);
}
return array;
}
/////////////////////////////////////////////////////////////////////
static class OutputWriter extends PrintWriter{
final int DEFAULT_PRECISION = 12;
int precision;
String format, formatWithSpace;
{
precision = DEFAULT_PRECISION;
format = createFormat(precision);
formatWithSpace = format + " ";
}
public OutputWriter(OutputStream out) {
super(out);
}
public OutputWriter(String fileName) throws FileNotFoundException {
super(fileName);
}
public int getPrecision() {
return precision;
}
public void setPrecision(int precision) {
precision = max(0, precision);
this.precision = precision;
format = createFormat(precision);
formatWithSpace = format + " ";
}
private String createFormat(int precision){
return "%." + precision + "f";
}
@Override
public void print(double d){
printf(format, d);
}
public void printWithSpace(double d){
printf(formatWithSpace, d);
}
public void printAll(double...d){
for (int i = 0; i < d.length - 1; ++i){
printWithSpace(d[i]);
}
print(d[d.length - 1]);
}
@Override
public void println(double d){
printlnAll(d);
}
public void printlnAll(double... d){
printAll(d);
println();
}
}
/////////////////////////////////////////////////////////////////////
int[][] steps = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
int[][] steps8 = {
{-1, 0}, {1, 0}, {0, -1}, {0, 1},
{-1, -1}, {1, 1}, {1, -1}, {-1, 1}
};
boolean check(int index, int lim){
return (0 <= index && index < lim);
}
/////////////////////////////////////////////////////////////////////
boolean checkBit(int mask, int bitNumber){
return (mask & (1 << bitNumber)) != 0;
}
/////////////////////////////////////////////////////////////////////
void solve() throws IOException {
int n = (readInt() << 1);
IntIndexPair[] array = readIntIndexArray(n);
List<Point> answer = getAnswer(n, array);
if (answer == null) {
out.println(-1);
} else {
for (Point pair: answer) {
out.println(pair.x + " " + pair.y);
}
}
}
private List<Point> getAnswer(int n, IntIndexPair[] array) {
List<Point> result = new ArrayList<Point>();
Arrays.sort(array, IntIndexPair.increaseComparator);
for (int i = 0; i < n; i++) {
IntIndexPair first = array[i++];
IntIndexPair second = array[i];
if (first.value == second.value) {
result.add(new Point(first.index + 1, second.index + 1));
} else {
return null;
}
}
return result;
}
}
| Java | ["3\n20 30 10 30 20 10", "1\n1 2"] | 1 second | ["4 2\n1 5\n6 3", "-1"] | null | Java 7 | input.txt | [
"constructive algorithms",
"sortings"
] | 0352429425782d7fe44818594eb0660c | The first line contains integer n (1ββ€βnββ€β3Β·105). The second line contains the sequence of 2n positive integers a1,βa2,β...,βa2n (1ββ€βaiββ€β5000) β the numbers that are written on the cards. The numbers on the line are separated by single spaces. | 1,200 | If it is impossible to divide the cards into pairs so that cards in each pair had the same numbers, print on a single line integer -1. But if the required partition exists, then print n pairs of integers, a pair per line β the indices of the cards that form the pairs. Separate the numbers on the lines by spaces. You can print the pairs and the numbers in the pairs in any order. If there are multiple solutions, print any of them. | output.txt | |
PASSED | fe528583ffab3f7372a6b10d5e44a077 | train_004.jsonl | 1355047200 | Petya has got 2n cards, each card contains some integer. The numbers on the cards can be the same. Let's index all cards by consecutive integers from 1 to 2n. We'll denote the number that is written on a card with number i, as ai. In order to play one entertaining game with his friends, Petya needs to split the cards into pairs so that each pair had equal numbers on the cards. Help Petya do that. | 256 megabytes | import java.awt.Point;
import java.io.*;
import java.util.*;
public class A {
private static BufferedReader reader;
private static PrintWriter writer;
private static StringTokenizer tokenizer;
private static void println() {
writer.println();
}
private static void print(Object obj) {
writer.print(obj);
}
private static void println(Object obj) {
writer.println(obj);
}
private static void printf(String f, Object... obj) {
writer.printf(f, obj);
}
private static int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
private long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
private double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
private static String nextToken() throws IOException {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
return tokenizer.nextToken();
}
public static void main(String[] args) throws IOException{
begin();
int n = nextInt();
ArrayList<Point> ans = new ArrayList<Point>();
Map<Integer, Integer> mp = new HashMap<Integer, Integer>();
for (int i = 0; i < 2*n; i++) {
int x = nextInt();
if (mp.get(x) == null){
mp.put(x, i);
}else{
ans.add(new Point(i+1,mp.get(x)+1));
mp.remove(x);
}
}
if (ans.size() != n) println(-1);
else{
for (int i = 0; i < ans.size(); i++) {
println(ans.get(i).x+" "+ans.get(i).y);
}
}
end();
}
private static void end() {
writer.close();
}
private static void begin() throws IOException{
reader = new BufferedReader(new FileReader("input.txt"));
writer = new PrintWriter(new FileWriter("output.txt")) ;
}
}
| Java | ["3\n20 30 10 30 20 10", "1\n1 2"] | 1 second | ["4 2\n1 5\n6 3", "-1"] | null | Java 7 | input.txt | [
"constructive algorithms",
"sortings"
] | 0352429425782d7fe44818594eb0660c | The first line contains integer n (1ββ€βnββ€β3Β·105). The second line contains the sequence of 2n positive integers a1,βa2,β...,βa2n (1ββ€βaiββ€β5000) β the numbers that are written on the cards. The numbers on the line are separated by single spaces. | 1,200 | If it is impossible to divide the cards into pairs so that cards in each pair had the same numbers, print on a single line integer -1. But if the required partition exists, then print n pairs of integers, a pair per line β the indices of the cards that form the pairs. Separate the numbers on the lines by spaces. You can print the pairs and the numbers in the pairs in any order. If there are multiple solutions, print any of them. | output.txt | |
PASSED | c9176b37f6074ab6793c5b66836115a0 | train_004.jsonl | 1355047200 | Petya has got 2n cards, each card contains some integer. The numbers on the cards can be the same. Let's index all cards by consecutive integers from 1 to 2n. We'll denote the number that is written on a card with number i, as ai. In order to play one entertaining game with his friends, Petya needs to split the cards into pairs so that each pair had equal numbers on the cards. Help Petya do that. | 256 megabytes | /**
* Created with IntelliJ IDEA.
* User: Venky
*/
import java.io.*;
import java.lang.reflect.Array;
import java.math.BigInteger;
import java.util.*;
public class Main {
static void solve() throws IOException {
class Elem
{
int val;
int ind;
}
int n = nextInt();
int c = 0;
Elem[] arr = new Elem[2*n];
for(int i=0;i<arr.length;i++)
{
arr[i] = new Elem();
arr[i].val = nextInt();
arr[i].ind = i+1;
}
Arrays.sort(arr, new Comparator<Elem>() {
@Override
public int compare(Elem o1, Elem o2) {
return o1.val-o2.val;
}
});
int countCheck = 0;
for(int i=0;i<arr.length-1;i++)
{
if(arr[i].val == arr[i+1].val)
countCheck++;
else
{
countCheck++;
if(countCheck % 2 != 0)
{
out.println("-1");
return;
}
countCheck = 0;
}
}
if(arr[arr.length-1].val != arr[arr.length-2].val)
{
out.println("-1");
return;
}
else
{
countCheck++;
if(countCheck % 2 != 0)
{
out.println("-1");
return;
}
}
for(int i=0;i<arr.length;i+=2)
{
out.println(arr[i].ind + " " + arr[i+1].ind);
}
}
static BufferedReader br;
static StringTokenizer st;
static PrintWriter out;
public static void main(String[] args) throws IOException {
InputStream input = new FileInputStream("input.txt");
/*
File fileIn = new File("input.txt");
File fileOut = new File("output.txt");
if (fileIn.exists() && fileIn.canRead()) {
input = new FileInputStream(fileIn);
}
if (fileOut.exists()) {
output = new PrintStream(new FileOutputStream(fileOut));
}
*/
br = new BufferedReader(new InputStreamReader(input));
out = new PrintWriter(new FileOutputStream("output.txt"));
solve();
out.close();
}
static long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
static double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
static int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
static String nextToken() throws IOException {
while (st == null || !st.hasMoreTokens()) {
String line = br.readLine();
if (line == null) {
return null;
}
st = new StringTokenizer(line);
}
return st.nextToken();
}
}
| Java | ["3\n20 30 10 30 20 10", "1\n1 2"] | 1 second | ["4 2\n1 5\n6 3", "-1"] | null | Java 7 | input.txt | [
"constructive algorithms",
"sortings"
] | 0352429425782d7fe44818594eb0660c | The first line contains integer n (1ββ€βnββ€β3Β·105). The second line contains the sequence of 2n positive integers a1,βa2,β...,βa2n (1ββ€βaiββ€β5000) β the numbers that are written on the cards. The numbers on the line are separated by single spaces. | 1,200 | If it is impossible to divide the cards into pairs so that cards in each pair had the same numbers, print on a single line integer -1. But if the required partition exists, then print n pairs of integers, a pair per line β the indices of the cards that form the pairs. Separate the numbers on the lines by spaces. You can print the pairs and the numbers in the pairs in any order. If there are multiple solutions, print any of them. | output.txt | |
PASSED | f8e885882f224390ce9a7d016597ec42 | train_004.jsonl | 1355047200 | Petya has got 2n cards, each card contains some integer. The numbers on the cards can be the same. Let's index all cards by consecutive integers from 1 to 2n. We'll denote the number that is written on a card with number i, as ai. In order to play one entertaining game with his friends, Petya needs to split the cards into pairs so that each pair had equal numbers on the cards. Help Petya do that. | 256 megabytes | import java.io.IOException;
import java.util.InputMismatchException;
import java.util.ArrayList;
import java.io.OutputStream;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.io.FileInputStream;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author George Marcus
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream;
try {
inputStream = new FileInputStream("input.txt");
} catch (IOException e) {
throw new RuntimeException(e);
}
OutputStream outputStream;
try {
outputStream = new FileOutputStream("output.txt");
} catch (IOException e) {
throw new RuntimeException(e);
}
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
}
class TaskA {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int N = in.nextInt();
ArrayList<Integer>[] vals = new ArrayList[5001];
for(int i = 0; i < 5001; i++)
vals[i] = new ArrayList<Integer>();
int x = -1;
for(int i = 0; i < 2 * N; i++) {
x = in.nextInt();
vals[x].add(i + 1);
}
boolean ok = true;
for(int i = 0; i < 5001; i++)
if(vals[i].size() % 2 > 0)
ok = false;
if(!ok) {
out.println(-1);
return;
}
for(int i = 0; i < 5001; i++) {
for(int j = 0; j < vals[i].size(); j += 2)
out.println(vals[i].get(j) + " " + vals[i].get(j + 1));
}
}
}
class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt() {
return Integer.parseInt(nextString());
}
public String nextString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuffer res = new StringBuffer();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
}
| Java | ["3\n20 30 10 30 20 10", "1\n1 2"] | 1 second | ["4 2\n1 5\n6 3", "-1"] | null | Java 7 | input.txt | [
"constructive algorithms",
"sortings"
] | 0352429425782d7fe44818594eb0660c | The first line contains integer n (1ββ€βnββ€β3Β·105). The second line contains the sequence of 2n positive integers a1,βa2,β...,βa2n (1ββ€βaiββ€β5000) β the numbers that are written on the cards. The numbers on the line are separated by single spaces. | 1,200 | If it is impossible to divide the cards into pairs so that cards in each pair had the same numbers, print on a single line integer -1. But if the required partition exists, then print n pairs of integers, a pair per line β the indices of the cards that form the pairs. Separate the numbers on the lines by spaces. You can print the pairs and the numbers in the pairs in any order. If there are multiple solutions, print any of them. | output.txt | |
PASSED | 1af3cfc98edd25e37dce923a1e65fbf6 | train_004.jsonl | 1355047200 | Petya has got 2n cards, each card contains some integer. The numbers on the cards can be the same. Let's index all cards by consecutive integers from 1 to 2n. We'll denote the number that is written on a card with number i, as ai. In order to play one entertaining game with his friends, Petya needs to split the cards into pairs so that each pair had equal numbers on the cards. Help Petya do that. | 256 megabytes | import java.io.*;
import java.util.*;
/**
* @author artyom
*/
public class CardsWithNumbers implements Runnable {
private BufferedReader in;
private PrintWriter out;
private StringTokenizer tok;
private void solve() throws IOException {
int n = nextInt();
short[] a = readArray(2 * n);
Iterable<Set<Integer>> g = groupWithIndices(a);
Collection<int[]> pairs = splitGroupsInPairs(g);
write(pairs);
}
private short[] readArray(int lim) throws IOException {
short[] res = new short[lim];
for (int i = 0; i < lim; i++) {
res[i] = nextShort();
}
return res;
}
private Collection<Set<Integer>> groupWithIndices(short[] cards) {
Map<Short, Set<Integer>> groups = new HashMap<>();
for (int i = 0, n = cards.length; i < n; i++) {
if (!groups.containsKey(cards[i])) {
groups.put(cards[i], new HashSet<Integer>());
}
groups.get(cards[i]).add(i + 1);
}
return groups.values();
}
private Collection<int[]> splitGroupsInPairs(Iterable<Set<Integer>> groups) {
Collection<int[]> res = new LinkedList<>();
for (Set<Integer> group : groups) {
if (group.size() % 2 == 1) {
return Collections.emptyList();
}
for (Iterator<Integer> it = group.iterator(); it.hasNext(); ) {
res.add(new int[]{it.next(), it.next()});
}
}
return res;
}
private void write(Collection<int[]> pairs) {
if (pairs.isEmpty()) {
out.println(-1);
return;
}
for (int[] pair : pairs) {
out.println(pair[0] + " " + pair[1]);
}
}
//--------------------------------------------------------------
public static void main(String[] args) {
new CardsWithNumbers().run();
}
@Override
public void run() {
try {
in = new BufferedReader(new FileReader("input.txt"));
out = new PrintWriter(new FileWriter("output.txt"));
tok = null;
solve();
in.close();
out.close();
} catch (IOException e) {
System.exit(0);
}
}
private String nextToken() throws IOException {
while (tok == null || !tok.hasMoreTokens()) {
tok = new StringTokenizer(in.readLine());
}
return tok.nextToken();
}
private short nextShort() throws IOException {
return Short.parseShort(nextToken());
}
private int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
} | Java | ["3\n20 30 10 30 20 10", "1\n1 2"] | 1 second | ["4 2\n1 5\n6 3", "-1"] | null | Java 7 | input.txt | [
"constructive algorithms",
"sortings"
] | 0352429425782d7fe44818594eb0660c | The first line contains integer n (1ββ€βnββ€β3Β·105). The second line contains the sequence of 2n positive integers a1,βa2,β...,βa2n (1ββ€βaiββ€β5000) β the numbers that are written on the cards. The numbers on the line are separated by single spaces. | 1,200 | If it is impossible to divide the cards into pairs so that cards in each pair had the same numbers, print on a single line integer -1. But if the required partition exists, then print n pairs of integers, a pair per line β the indices of the cards that form the pairs. Separate the numbers on the lines by spaces. You can print the pairs and the numbers in the pairs in any order. If there are multiple solutions, print any of them. | output.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.