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
92f827f7ba2abbdf8b371ebefe058e01
train_001.jsonl
1390231800
Iahub likes chess very much. He even invented a new chess piece named Coder. A Coder can move (and attack) one square horizontally or vertically. More precisely, if the Coder is located at position (x, y), he can move to (or attack) positions (x + 1, y), (x–1, y), (x, y + 1) and (x, y–1).Iahub wants to know how many Coders can be placed on an n × n chessboard, so that no Coder attacks any other Coder.
256 megabytes
import java.io.PrintWriter; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner input = new Scanner (System.in); PrintWriter output = new PrintWriter(System.out); int n = input.nextInt(); output.println((n*n+1)/2); for(int i = 0 ; i < n ; i++) { for(int j = 0 ; j < n ; j++) { if( (i+j) % 2 == 0) output.print("C"); else output.print("."); } output.println(); } output.flush(); } }
Java
["2"]
1 second
["2\nC.\n.C"]
null
Java 8
standard input
[ "implementation" ]
1aede54b41d6fad3e74f24a6592198eb
The first line contains an integer n (1 ≤ n ≤ 1000).
800
On the first line print an integer, the maximum number of Coders that can be placed on the chessboard. On each of the next n lines print n characters, describing the configuration of the Coders. For an empty cell print an '.', and for a Coder print a 'C'. If there are multiple correct answers, you can print any.
standard output
PASSED
6cc3acf7deb808feabc52e7ea76ed349
train_001.jsonl
1390231800
Iahub likes chess very much. He even invented a new chess piece named Coder. A Coder can move (and attack) one square horizontally or vertically. More precisely, if the Coder is located at position (x, y), he can move to (or attack) positions (x + 1, y), (x–1, y), (x, y + 1) and (x, y–1).Iahub wants to know how many Coders can be placed on an n × n chessboard, so that no Coder attacks any other Coder.
256 megabytes
import java.util.*; import java.io.*; public class Coder { public static void main(String args[]) throws Exception { BufferedReader f=new BufferedReader(new InputStreamReader(System.in)); int size=Integer.parseInt(f.readLine()); System.out.println(size*size/2+(size%2==1?1:0)); String[] arr=new String[2]; String one=""; for(int x=0;x<size;x++) one+=x%2==0?"C":"."; String two=""; for(int x=0;x<size;x++) two+=x%2==1?"C":"."; arr[0]=one; arr[1]=two; for(int y=0;y<size;y++) System.out.println(arr[y%2]); } }
Java
["2"]
1 second
["2\nC.\n.C"]
null
Java 8
standard input
[ "implementation" ]
1aede54b41d6fad3e74f24a6592198eb
The first line contains an integer n (1 ≤ n ≤ 1000).
800
On the first line print an integer, the maximum number of Coders that can be placed on the chessboard. On each of the next n lines print n characters, describing the configuration of the Coders. For an empty cell print an '.', and for a Coder print a 'C'. If there are multiple correct answers, you can print any.
standard output
PASSED
6c1f2aa797fbf343c94d01972cd07fa4
train_001.jsonl
1390231800
Iahub likes chess very much. He even invented a new chess piece named Coder. A Coder can move (and attack) one square horizontally or vertically. More precisely, if the Coder is located at position (x, y), he can move to (or attack) positions (x + 1, y), (x–1, y), (x, y + 1) and (x, y–1).Iahub wants to know how many Coders can be placed on an n × n chessboard, so that no Coder attacks any other Coder.
256 megabytes
import java.util.Scanner; public class Coder{ public static void main(String args[]){ Scanner scan = new Scanner(System.in); int n = scan.nextInt(); long numPieces = 0; //n is odd if(n%2 == 1){ //Odd rows numPieces += ((n+1)/2) * ((n+1)/2); //Even rows numPieces += (n/2)*(n/2); }else{ //n is even numPieces += n*(n/2); } System.out.println(numPieces); StringBuilder sb = new StringBuilder(); for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ if( (j+i)%2==0 ){ sb.append("C"); }else{ sb.append("."); } } sb.append("\n"); } System.out.println(sb.toString()); } }
Java
["2"]
1 second
["2\nC.\n.C"]
null
Java 8
standard input
[ "implementation" ]
1aede54b41d6fad3e74f24a6592198eb
The first line contains an integer n (1 ≤ n ≤ 1000).
800
On the first line print an integer, the maximum number of Coders that can be placed on the chessboard. On each of the next n lines print n characters, describing the configuration of the Coders. For an empty cell print an '.', and for a Coder print a 'C'. If there are multiple correct answers, you can print any.
standard output
PASSED
687fe28f013471e0d1f4aae4bcc4013b
train_001.jsonl
1443430800
Three companies decided to order a billboard with pictures of their logos. A billboard is a big square board. A logo of each company is a rectangle of a non-zero area. Advertisers will put up the ad only if it is possible to place all three logos on the billboard so that they do not overlap and the billboard has no empty space left. When you put a logo on the billboard, you should rotate it so that the sides were parallel to the sides of the billboard.Your task is to determine if it is possible to put the logos of all the three companies on some square billboard without breaking any of the described rules.
256 megabytes
import java.io.BufferedOutputStream; import java.io.Closeable; import java.io.DataInputStream; import java.io.Flushable; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Arrays; import java.util.InputMismatchException; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { static class TaskAdapter implements Runnable { @Override public void run() { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastReader in = new FastReader(inputStream); Output out = new Output(outputStream); DThreeLogos solver = new DThreeLogos(); solver.solve(1, in, out); out.close(); } } public static void main(String[] args) throws Exception { Thread thread = new Thread(null, new TaskAdapter(), "", 1<<29); thread.start(); thread.join(); } static class DThreeLogos { public DThreeLogos() { } public char[][] solve(int[] a, int[] b, int[] c, char[] arr) { char[][] ret = new char[a[1]][a[1]]; if(a[0]>ret.length) { return null; } for(int i = 0; i<a[0]; i++) { Arrays.fill(ret[i], arr[0]); } if(b[1]==c[1]&&b[1]==a[1]&&b[0]+c[0]+a[0]==ret.length) { for(int i = a[0]; i<a[0]+b[0]; i++) { Arrays.fill(ret[i], arr[1]); } for(int i = a[0]+b[0]; i<a[1]; i++) { Arrays.fill(ret[i], arr[2]); } return ret; } if(b[0]==c[0]&&b[1]+c[1]==a[1]&&b[0]+a[0]==ret.length) { for(int i = a[0]; i<a[1]; i++) { for(int j = 0; j<b[1]; j++) { ret[i][j] = arr[1]; } for(int j = b[1]; j<a[1]; j++) { ret[i][j] = arr[2]; } } return ret; } return null; } public void solve(int kase, InputReader in, Output pw) { int[] arr = new int[] {0, 1, 2}; int[] a = in.nextInt(2), b = in.nextInt(2), c = in.nextInt(2); do { int[] ac, bc, cc; if(arr[0]==0) { ac = a; }else if(arr[0]==1) { ac = b; }else { ac = c; } if(arr[1]==0) { bc = a; }else if(arr[1]==1) { bc = b; }else { bc = c; } if(arr[2]==0) { cc = a; }else if(arr[2]==1) { cc = b; }else { cc = c; } for(int i = 0; i<1<<3; i++) { int[] acc, bcc, ccc; acc = ac.clone(); bcc = bc.clone(); ccc = cc.clone(); if((i&1)==0) { Utilities.swap(acc, 0, 1); } if((i&2)==0) { Utilities.swap(bcc, 0, 1); } if((i&4)==0) { Utilities.swap(ccc, 0, 1); } char[][] cur = solve(acc, bcc, ccc, new char[] {(char) (arr[0]+'A'), (char) (arr[1]+'A'), (char) (arr[2]+'A')}); if(cur!=null) { pw.println(cur.length); for(int j = 0; j<cur.length; j++) { pw.println(cur[j]); } return; } } } while(Utilities.nextPermutation(arr)); pw.println(-1); } } static class Utilities { public static void swap(int[] arr, int i, int j) { if(i!=j) { arr[i] ^= arr[j]; arr[j] ^= arr[i]; arr[i] ^= arr[j]; } } public static void reverse(int[] arr, int i, int j) { while(i<j) { swap(arr, i++, j--); } } public static boolean nextPermutation(int[] data) { if(data.length<=1) { return false; } int last = data.length-2; while(last>=0) { if(data[last]<data[last+1]) { break; } last--; } if(last<0) return false; int nextGreater = data.length-1; for(int i = data.length-1; i>last; i--) { if(data[i]>data[last]) { nextGreater = i; break; } } swap(data, nextGreater, last); reverse(data, last+1, data.length-1); return true; } } static class Output implements Closeable, Flushable { public StringBuilder sb; public OutputStream os; public int BUFFER_SIZE; public boolean autoFlush; public String LineSeparator; public Output(OutputStream os) { this(os, 1<<16); } public Output(OutputStream os, int bs) { BUFFER_SIZE = bs; sb = new StringBuilder(BUFFER_SIZE); this.os = new BufferedOutputStream(os, 1<<17); autoFlush = false; LineSeparator = System.lineSeparator(); } public void println(int i) { println(String.valueOf(i)); } public void println(char[] c) { println(String.valueOf(c)); } public void println(String s) { sb.append(s); println(); if(autoFlush) { flush(); }else if(sb.length()>BUFFER_SIZE >> 1) { flushToBuffer(); } } public void println() { sb.append(LineSeparator); } private void flushToBuffer() { try { os.write(sb.toString().getBytes()); }catch(IOException e) { e.printStackTrace(); } sb = new StringBuilder(BUFFER_SIZE); } public void flush() { try { flushToBuffer(); os.flush(); }catch(IOException e) { e.printStackTrace(); } } public void close() { flush(); try { os.close(); }catch(IOException e) { e.printStackTrace(); } } } static interface InputReader { int nextInt(); default int[] nextInt(int n) { int[] ret = new int[n]; for(int i = 0; i<n; i++) { ret[i] = nextInt(); } return ret; } } static class FastReader implements InputReader { final private int BUFFER_SIZE = 1<<16; private DataInputStream din; private byte[] buffer; private int bufferPointer; private int bytesRead; public FastReader(InputStream is) { din = new DataInputStream(is); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public int nextInt() { int ret = 0; byte c = skipToDigit(); boolean neg = (c=='-'); if(neg) { c = read(); } do { ret = ret*10+c-'0'; } while((c = read())>='0'&&c<='9'); if(neg) { return -ret; } return ret; } private boolean isDigit(byte b) { return b>='0'&&b<='9'; } private byte skipToDigit() { byte ret; while(!isDigit(ret = read())&&ret!='-') ; return ret; } private void fillBuffer() { try { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); }catch(IOException e) { e.printStackTrace(); throw new InputMismatchException(); } if(bytesRead==-1) { buffer[0] = -1; } } private byte read() { if(bytesRead==-1) { throw new InputMismatchException(); }else if(bufferPointer==bytesRead) { fillBuffer(); } return buffer[bufferPointer++]; } } }
Java
["5 1 2 5 5 2", "4 4 2 6 4 2"]
1 second
["5\nAAAAA\nBBBBB\nBBBBB\nCCCCC\nCCCCC", "6\nBBBBBB\nBBBBBB\nAAAACC\nAAAACC\nAAAACC\nAAAACC"]
null
Java 11
standard input
[ "geometry", "constructive algorithms", "bitmasks", "math", "implementation", "brute force" ]
2befe5da2df57d23934601cbe4d4f151
The first line of the input contains six positive integers x1, y1, x2, y2, x3, y3 (1 ≤ x1, y1, x2, y2, x3, y3 ≤ 100), where xi and yi determine the length and width of the logo of the i-th company respectively.
1,700
If it is impossible to place all the three logos on a square shield, print a single integer "-1" (without the quotes). If it is possible, print in the first line the length of a side of square n, where you can place all the three logos. Each of the next n lines should contain n uppercase English letters "A", "B" or "C". The sets of the same letters should form solid rectangles, provided that: the sizes of the rectangle composed from letters "A" should be equal to the sizes of the logo of the first company, the sizes of the rectangle composed from letters "B" should be equal to the sizes of the logo of the second company, the sizes of the rectangle composed from letters "C" should be equal to the sizes of the logo of the third company, Note that the logos of the companies can be rotated for printing on the billboard. The billboard mustn't have any empty space. If a square billboard can be filled with the logos in multiple ways, you are allowed to print any of them. See the samples to better understand the statement.
standard output
PASSED
45e01a38ef33f73d1e0f7160676d101f
train_001.jsonl
1523370900
Polycarp has created his own training plan to prepare for the programming contests. He will train for $$$n$$$ days, all days are numbered from $$$1$$$ to $$$n$$$, beginning from the first.On the $$$i$$$-th day Polycarp will necessarily solve $$$a_i$$$ problems. One evening Polycarp plans to celebrate the equator. He will celebrate it on the first evening of such a day that from the beginning of the training and to this day inclusive he will solve half or more of all the problems.Determine the index of day when Polycarp will celebrate the equator.
256 megabytes
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner cin1 = new Scanner(System.in); while (cin1.hasNext()) { int n = cin1.nextInt(); int num = 0; int res = 0; int[] ary = new int[n]; for (int i = 0; i < n; i++) { int b = cin1.nextInt(); num += b; ary[i] = num; } int m = num / 2; if (num % 2 != 0) { m += 1; } for (int i = 0; i < n; i++) { if (ary[i] >= m) { res = i + 1; break; } } System.out.println(res); } } }
Java
["4\n1 3 2 1", "6\n2 2 2 2 2 2"]
2 seconds
["2", "3"]
NoteIn the first example Polycarp will celebrate the equator on the evening of the second day, because up to this day (inclusive) he will solve $$$4$$$ out of $$$7$$$ scheduled problems on four days of the training.In the second example Polycarp will celebrate the equator on the evening of the third day, because up to this day (inclusive) he will solve $$$6$$$ out of $$$12$$$ scheduled problems on six days of the training.
Java 8
standard input
[ "implementation" ]
241157c465fe5dd96acd514010904321
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 200\,000$$$) — the number of days to prepare for the programming contests. The second line contains a sequence $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10\,000$$$), where $$$a_i$$$ equals to the number of problems, which Polycarp will solve on the $$$i$$$-th day.
1,300
Print the index of the day when Polycarp will celebrate the equator.
standard output
PASSED
5a6e19cd586f5ccfeae41d62887c0aee
train_001.jsonl
1523370900
Polycarp has created his own training plan to prepare for the programming contests. He will train for $$$n$$$ days, all days are numbered from $$$1$$$ to $$$n$$$, beginning from the first.On the $$$i$$$-th day Polycarp will necessarily solve $$$a_i$$$ problems. One evening Polycarp plans to celebrate the equator. He will celebrate it on the first evening of such a day that from the beginning of the training and to this day inclusive he will solve half or more of all the problems.Determine the index of day when Polycarp will celebrate the equator.
256 megabytes
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); //inputs int n = in.nextInt(); int sum = 0 , cnt = 0; int [] a = new int [n]; for(int i=0 ; i<n ; i++){ int k = in.nextInt(); sum += k; a[i] = k; } for(int i=0 ; i<=n ; i++){ if(cnt >= (double)sum/2){ System.out.println(i); System.exit(0); } cnt += a[i]; } } }
Java
["4\n1 3 2 1", "6\n2 2 2 2 2 2"]
2 seconds
["2", "3"]
NoteIn the first example Polycarp will celebrate the equator on the evening of the second day, because up to this day (inclusive) he will solve $$$4$$$ out of $$$7$$$ scheduled problems on four days of the training.In the second example Polycarp will celebrate the equator on the evening of the third day, because up to this day (inclusive) he will solve $$$6$$$ out of $$$12$$$ scheduled problems on six days of the training.
Java 8
standard input
[ "implementation" ]
241157c465fe5dd96acd514010904321
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 200\,000$$$) — the number of days to prepare for the programming contests. The second line contains a sequence $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10\,000$$$), where $$$a_i$$$ equals to the number of problems, which Polycarp will solve on the $$$i$$$-th day.
1,300
Print the index of the day when Polycarp will celebrate the equator.
standard output
PASSED
ce941bed324b2ca09ecc8204831d26b4
train_001.jsonl
1523370900
Polycarp has created his own training plan to prepare for the programming contests. He will train for $$$n$$$ days, all days are numbered from $$$1$$$ to $$$n$$$, beginning from the first.On the $$$i$$$-th day Polycarp will necessarily solve $$$a_i$$$ problems. One evening Polycarp plans to celebrate the equator. He will celebrate it on the first evening of such a day that from the beginning of the training and to this day inclusive he will solve half or more of all the problems.Determine the index of day when Polycarp will celebrate the equator.
256 megabytes
import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class TestClass { public static void main(String[] args){ // TODO Auto-generated method stub FastScanner sc = new FastScanner(); int sum = 0 ; int currSum = 0; int n = sc.nextInt(); int[] arr = new int [n]; for(int i=0;i<n;i++){ arr[i] = sc.nextInt(); sum+=arr[i]; } for(int i=0;i<n;i++){ currSum+=arr[i]; if(currSum*2 >= sum){ System.out.println(i+1); break; } } } public static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(String s) { try { br = new BufferedReader(new FileReader(s)); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String nextToken() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(nextToken()); } long nextLong() { return Long.parseLong(nextToken()); } double nextDouble() { return Double.parseDouble(nextToken()); } } }
Java
["4\n1 3 2 1", "6\n2 2 2 2 2 2"]
2 seconds
["2", "3"]
NoteIn the first example Polycarp will celebrate the equator on the evening of the second day, because up to this day (inclusive) he will solve $$$4$$$ out of $$$7$$$ scheduled problems on four days of the training.In the second example Polycarp will celebrate the equator on the evening of the third day, because up to this day (inclusive) he will solve $$$6$$$ out of $$$12$$$ scheduled problems on six days of the training.
Java 8
standard input
[ "implementation" ]
241157c465fe5dd96acd514010904321
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 200\,000$$$) — the number of days to prepare for the programming contests. The second line contains a sequence $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10\,000$$$), where $$$a_i$$$ equals to the number of problems, which Polycarp will solve on the $$$i$$$-th day.
1,300
Print the index of the day when Polycarp will celebrate the equator.
standard output
PASSED
09788cf4b9b76027c94e778484a1cb60
train_001.jsonl
1523370900
Polycarp has created his own training plan to prepare for the programming contests. He will train for $$$n$$$ days, all days are numbered from $$$1$$$ to $$$n$$$, beginning from the first.On the $$$i$$$-th day Polycarp will necessarily solve $$$a_i$$$ problems. One evening Polycarp plans to celebrate the equator. He will celebrate it on the first evening of such a day that from the beginning of the training and to this day inclusive he will solve half or more of all the problems.Determine the index of day when Polycarp will celebrate the equator.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashMap; import java.util.StringTokenizer; public class dad { public static void main(String[] args) { InputReader in = new InputReader(System.in); int[] arr = new int[200002]; int n = in.nextInt(); long som = 0; for (int i = 0; i < n; i++) { arr[i] = in.nextInt(); som += arr[i]; } long tmpSom = 0; for (int i = 0; i < n; i++) { tmpSom += arr[i]; if (tmpSom >= (som / 2.0)) { System.out.println(i + 1); break; } } } } class InputReader { private BufferedReader reader; private 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 String readLine() { try { return reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public char nextChar() { return next().charAt(0); } }
Java
["4\n1 3 2 1", "6\n2 2 2 2 2 2"]
2 seconds
["2", "3"]
NoteIn the first example Polycarp will celebrate the equator on the evening of the second day, because up to this day (inclusive) he will solve $$$4$$$ out of $$$7$$$ scheduled problems on four days of the training.In the second example Polycarp will celebrate the equator on the evening of the third day, because up to this day (inclusive) he will solve $$$6$$$ out of $$$12$$$ scheduled problems on six days of the training.
Java 8
standard input
[ "implementation" ]
241157c465fe5dd96acd514010904321
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 200\,000$$$) — the number of days to prepare for the programming contests. The second line contains a sequence $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10\,000$$$), where $$$a_i$$$ equals to the number of problems, which Polycarp will solve on the $$$i$$$-th day.
1,300
Print the index of the day when Polycarp will celebrate the equator.
standard output
PASSED
8ac05e2176b946fb62780e7a78cce191
train_001.jsonl
1523370900
Polycarp has created his own training plan to prepare for the programming contests. He will train for $$$n$$$ days, all days are numbered from $$$1$$$ to $$$n$$$, beginning from the first.On the $$$i$$$-th day Polycarp will necessarily solve $$$a_i$$$ problems. One evening Polycarp plans to celebrate the equator. He will celebrate it on the first evening of such a day that from the beginning of the training and to this day inclusive he will solve half or more of all the problems.Determine the index of day when Polycarp will celebrate the equator.
256 megabytes
import java.util.Scanner; public class ProblemSet { private static Scanner reader; public static void main(String[] args) { // TODO Auto-generated method stub reader = new Scanner(System.in); int n = reader.nextInt(); double sum = 0; int arr[] = new int[n]; for(int i = 0; i < n; i++) { arr[i] = reader.nextInt(); sum += arr[i]; } if(n == 1) { System.out.println(1); return; } double result = 0; for(int i = 0; i < n; i++) { result += arr[i]; if (result >= sum / 2) { System.out.println(i + 1); return; } } } }
Java
["4\n1 3 2 1", "6\n2 2 2 2 2 2"]
2 seconds
["2", "3"]
NoteIn the first example Polycarp will celebrate the equator on the evening of the second day, because up to this day (inclusive) he will solve $$$4$$$ out of $$$7$$$ scheduled problems on four days of the training.In the second example Polycarp will celebrate the equator on the evening of the third day, because up to this day (inclusive) he will solve $$$6$$$ out of $$$12$$$ scheduled problems on six days of the training.
Java 8
standard input
[ "implementation" ]
241157c465fe5dd96acd514010904321
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 200\,000$$$) — the number of days to prepare for the programming contests. The second line contains a sequence $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10\,000$$$), where $$$a_i$$$ equals to the number of problems, which Polycarp will solve on the $$$i$$$-th day.
1,300
Print the index of the day when Polycarp will celebrate the equator.
standard output
PASSED
a446f0bd39a4251ecee648aaed85e30f
train_001.jsonl
1523370900
Polycarp has created his own training plan to prepare for the programming contests. He will train for $$$n$$$ days, all days are numbered from $$$1$$$ to $$$n$$$, beginning from the first.On the $$$i$$$-th day Polycarp will necessarily solve $$$a_i$$$ problems. One evening Polycarp plans to celebrate the equator. He will celebrate it on the first evening of such a day that from the beginning of the training and to this day inclusive he will solve half or more of all the problems.Determine the index of day when Polycarp will celebrate the equator.
256 megabytes
import java.util.Scanner; public class AEquator { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); int tot = 0; int[] a = new int[n]; for (int i=0;i<n;i++) { a[i] = scanner.nextInt(); tot += a[i]; } int over = 0; for (int i=0;i<n;i++) { over += a[i]; if (over >= (tot / 2 + (tot & 1)) ) { System.out.println(i+1); break; } } } }
Java
["4\n1 3 2 1", "6\n2 2 2 2 2 2"]
2 seconds
["2", "3"]
NoteIn the first example Polycarp will celebrate the equator on the evening of the second day, because up to this day (inclusive) he will solve $$$4$$$ out of $$$7$$$ scheduled problems on four days of the training.In the second example Polycarp will celebrate the equator on the evening of the third day, because up to this day (inclusive) he will solve $$$6$$$ out of $$$12$$$ scheduled problems on six days of the training.
Java 8
standard input
[ "implementation" ]
241157c465fe5dd96acd514010904321
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 200\,000$$$) — the number of days to prepare for the programming contests. The second line contains a sequence $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10\,000$$$), where $$$a_i$$$ equals to the number of problems, which Polycarp will solve on the $$$i$$$-th day.
1,300
Print the index of the day when Polycarp will celebrate the equator.
standard output
PASSED
955b7ddc86092d37db3a34d78e32f1c2
train_001.jsonl
1523370900
Polycarp has created his own training plan to prepare for the programming contests. He will train for $$$n$$$ days, all days are numbered from $$$1$$$ to $$$n$$$, beginning from the first.On the $$$i$$$-th day Polycarp will necessarily solve $$$a_i$$$ problems. One evening Polycarp plans to celebrate the equator. He will celebrate it on the first evening of such a day that from the beginning of the training and to this day inclusive he will solve half or more of all the problems.Determine the index of day when Polycarp will celebrate the equator.
256 megabytes
import java.util.*; public class atink { public static void main(String args[]) { Scanner in=new Scanner(System.in); int n=in.nextInt(); int arr[]=new int[n]; int sum=0; for(int i=0;i<n;i++) { arr[i]=in.nextInt(); sum+=arr[i]; } int temp=0; for(int i=0;i<n;i++) { temp+=arr[i]; if(temp>=(sum+1)/2) { System.out.print(i+1); return; } } } }
Java
["4\n1 3 2 1", "6\n2 2 2 2 2 2"]
2 seconds
["2", "3"]
NoteIn the first example Polycarp will celebrate the equator on the evening of the second day, because up to this day (inclusive) he will solve $$$4$$$ out of $$$7$$$ scheduled problems on four days of the training.In the second example Polycarp will celebrate the equator on the evening of the third day, because up to this day (inclusive) he will solve $$$6$$$ out of $$$12$$$ scheduled problems on six days of the training.
Java 8
standard input
[ "implementation" ]
241157c465fe5dd96acd514010904321
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 200\,000$$$) — the number of days to prepare for the programming contests. The second line contains a sequence $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10\,000$$$), where $$$a_i$$$ equals to the number of problems, which Polycarp will solve on the $$$i$$$-th day.
1,300
Print the index of the day when Polycarp will celebrate the equator.
standard output
PASSED
2c868ab3cddb2b03da3b05d54ae2e5a5
train_001.jsonl
1523370900
Polycarp has created his own training plan to prepare for the programming contests. He will train for $$$n$$$ days, all days are numbered from $$$1$$$ to $$$n$$$, beginning from the first.On the $$$i$$$-th day Polycarp will necessarily solve $$$a_i$$$ problems. One evening Polycarp plans to celebrate the equator. He will celebrate it on the first evening of such a day that from the beginning of the training and to this day inclusive he will solve half or more of all the problems.Determine the index of day when Polycarp will celebrate the equator.
256 megabytes
import java.util.Scanner; public class test { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int [] tab = new int[n]; double sum = 0; for (int i = 0; i < tab.length; i++) { tab[i] = in.nextInt(); sum += tab[i]; } int i = 0; double somme = 0; while (i < n && somme+tab[i] < (sum / 2)) { somme += tab[i]; i++; } System.out.println(i+1); } }
Java
["4\n1 3 2 1", "6\n2 2 2 2 2 2"]
2 seconds
["2", "3"]
NoteIn the first example Polycarp will celebrate the equator on the evening of the second day, because up to this day (inclusive) he will solve $$$4$$$ out of $$$7$$$ scheduled problems on four days of the training.In the second example Polycarp will celebrate the equator on the evening of the third day, because up to this day (inclusive) he will solve $$$6$$$ out of $$$12$$$ scheduled problems on six days of the training.
Java 8
standard input
[ "implementation" ]
241157c465fe5dd96acd514010904321
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 200\,000$$$) — the number of days to prepare for the programming contests. The second line contains a sequence $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10\,000$$$), where $$$a_i$$$ equals to the number of problems, which Polycarp will solve on the $$$i$$$-th day.
1,300
Print the index of the day when Polycarp will celebrate the equator.
standard output
PASSED
ad7838cea7d7f7fab15eccc3b37a0be3
train_001.jsonl
1523370900
Polycarp has created his own training plan to prepare for the programming contests. He will train for $$$n$$$ days, all days are numbered from $$$1$$$ to $$$n$$$, beginning from the first.On the $$$i$$$-th day Polycarp will necessarily solve $$$a_i$$$ problems. One evening Polycarp plans to celebrate the equator. He will celebrate it on the first evening of such a day that from the beginning of the training and to this day inclusive he will solve half or more of all the problems.Determine the index of day when Polycarp will celebrate the equator.
256 megabytes
import java.util.Scanner; public class Equator { public static void main (String [] args ){ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int sum=0; int [] arr = new int[n]; for(int i =0;i< n; i++){ arr[i]= sc.nextInt(); sum += arr[i]; } double mid = Math.ceil((double)sum/2); int sum2=0; int fl =-1; for( int i =0 ; i < n ; i++){ sum2=sum2+arr[i]; if( sum2 >= mid){ fl=i+1; break; } } System.out.println(fl); } }
Java
["4\n1 3 2 1", "6\n2 2 2 2 2 2"]
2 seconds
["2", "3"]
NoteIn the first example Polycarp will celebrate the equator on the evening of the second day, because up to this day (inclusive) he will solve $$$4$$$ out of $$$7$$$ scheduled problems on four days of the training.In the second example Polycarp will celebrate the equator on the evening of the third day, because up to this day (inclusive) he will solve $$$6$$$ out of $$$12$$$ scheduled problems on six days of the training.
Java 8
standard input
[ "implementation" ]
241157c465fe5dd96acd514010904321
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 200\,000$$$) — the number of days to prepare for the programming contests. The second line contains a sequence $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10\,000$$$), where $$$a_i$$$ equals to the number of problems, which Polycarp will solve on the $$$i$$$-th day.
1,300
Print the index of the day when Polycarp will celebrate the equator.
standard output
PASSED
61c2b2bc3e561fd67e55e05972f55af4
train_001.jsonl
1523370900
Polycarp has created his own training plan to prepare for the programming contests. He will train for $$$n$$$ days, all days are numbered from $$$1$$$ to $$$n$$$, beginning from the first.On the $$$i$$$-th day Polycarp will necessarily solve $$$a_i$$$ problems. One evening Polycarp plans to celebrate the equator. He will celebrate it on the first evening of such a day that from the beginning of the training and to this day inclusive he will solve half or more of all the problems.Determine the index of day when Polycarp will celebrate the equator.
256 megabytes
import java.util.Scanner; public class Polycarp { private int n; private int []a ; private Scanner sc; private int s=0; private int[] z; public Polycarp(){ sc=new Scanner(System.in); n=sc.nextInt(); a=new int[n]; z = new int[n]; for(int i=0; i<n; i++){ a[i]=sc.nextInt(); s+=a[i]; z[i]=s; } if(s%2!=0) s++; for(int i=0; i<n; i++){ if(z[i]>=s/2) { System.out.print(i + 1); return; } } } public static void main(String [] args) { Polycarp p =new Polycarp(); } }
Java
["4\n1 3 2 1", "6\n2 2 2 2 2 2"]
2 seconds
["2", "3"]
NoteIn the first example Polycarp will celebrate the equator on the evening of the second day, because up to this day (inclusive) he will solve $$$4$$$ out of $$$7$$$ scheduled problems on four days of the training.In the second example Polycarp will celebrate the equator on the evening of the third day, because up to this day (inclusive) he will solve $$$6$$$ out of $$$12$$$ scheduled problems on six days of the training.
Java 8
standard input
[ "implementation" ]
241157c465fe5dd96acd514010904321
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 200\,000$$$) — the number of days to prepare for the programming contests. The second line contains a sequence $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10\,000$$$), where $$$a_i$$$ equals to the number of problems, which Polycarp will solve on the $$$i$$$-th day.
1,300
Print the index of the day when Polycarp will celebrate the equator.
standard output
PASSED
b4b54d7e601388797e529b2e965a3602
train_001.jsonl
1523370900
Polycarp has created his own training plan to prepare for the programming contests. He will train for $$$n$$$ days, all days are numbered from $$$1$$$ to $$$n$$$, beginning from the first.On the $$$i$$$-th day Polycarp will necessarily solve $$$a_i$$$ problems. One evening Polycarp plans to celebrate the equator. He will celebrate it on the first evening of such a day that from the beginning of the training and to this day inclusive he will solve half or more of all the problems.Determine the index of day when Polycarp will celebrate the equator.
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; public class abcd { public static void main (String[] args) throws java.lang.Exception { Scanner s=new Scanner(System.in); int n=s.nextInt(); int a[]=new int[n]; int sum=0; for(int i=0;i<n;i++){ a[i]=s.nextInt(); sum=sum+a[i]; }int k=0; for(int i=0;i<n;i++){ k=k+a[i]; if((sum+1)/2<=k){ System.out.println(i+1); break; } } } }
Java
["4\n1 3 2 1", "6\n2 2 2 2 2 2"]
2 seconds
["2", "3"]
NoteIn the first example Polycarp will celebrate the equator on the evening of the second day, because up to this day (inclusive) he will solve $$$4$$$ out of $$$7$$$ scheduled problems on four days of the training.In the second example Polycarp will celebrate the equator on the evening of the third day, because up to this day (inclusive) he will solve $$$6$$$ out of $$$12$$$ scheduled problems on six days of the training.
Java 8
standard input
[ "implementation" ]
241157c465fe5dd96acd514010904321
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 200\,000$$$) — the number of days to prepare for the programming contests. The second line contains a sequence $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10\,000$$$), where $$$a_i$$$ equals to the number of problems, which Polycarp will solve on the $$$i$$$-th day.
1,300
Print the index of the day when Polycarp will celebrate the equator.
standard output
PASSED
29d0afd52a083587718ad34abd89a972
train_001.jsonl
1523370900
Polycarp has created his own training plan to prepare for the programming contests. He will train for $$$n$$$ days, all days are numbered from $$$1$$$ to $$$n$$$, beginning from the first.On the $$$i$$$-th day Polycarp will necessarily solve $$$a_i$$$ problems. One evening Polycarp plans to celebrate the equator. He will celebrate it on the first evening of such a day that from the beginning of the training and to this day inclusive he will solve half or more of all the problems.Determine the index of day when Polycarp will celebrate the equator.
256 megabytes
import java.util.Scanner; public class P962A { public static void main(String[] args) { Scanner s = new Scanner(System.in); int n = s.nextInt(); long[] arr = new long[n]; long sum = 0; for (int i = 0; i < n; i++) { arr[i] = s.nextLong(); sum += arr[i]; } long current = 0; for (int i = 0; i < n; i++) { current += arr[i]; if (2 * current >= sum) { System.out.println(i + 1); break; } } } }
Java
["4\n1 3 2 1", "6\n2 2 2 2 2 2"]
2 seconds
["2", "3"]
NoteIn the first example Polycarp will celebrate the equator on the evening of the second day, because up to this day (inclusive) he will solve $$$4$$$ out of $$$7$$$ scheduled problems on four days of the training.In the second example Polycarp will celebrate the equator on the evening of the third day, because up to this day (inclusive) he will solve $$$6$$$ out of $$$12$$$ scheduled problems on six days of the training.
Java 8
standard input
[ "implementation" ]
241157c465fe5dd96acd514010904321
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 200\,000$$$) — the number of days to prepare for the programming contests. The second line contains a sequence $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10\,000$$$), where $$$a_i$$$ equals to the number of problems, which Polycarp will solve on the $$$i$$$-th day.
1,300
Print the index of the day when Polycarp will celebrate the equator.
standard output
PASSED
4245901c48f24b7a0709999275901b4f
train_001.jsonl
1523370900
Polycarp has created his own training plan to prepare for the programming contests. He will train for $$$n$$$ days, all days are numbered from $$$1$$$ to $$$n$$$, beginning from the first.On the $$$i$$$-th day Polycarp will necessarily solve $$$a_i$$$ problems. One evening Polycarp plans to celebrate the equator. He will celebrate it on the first evening of such a day that from the beginning of the training and to this day inclusive he will solve half or more of all the problems.Determine the index of day when Polycarp will celebrate the equator.
256 megabytes
import java.util.Arrays; import java.util.LinkedList; import java.util.Scanner; /** * @author yazan */ public class JavaApplication1 { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); double [] arr = new double[n]; double sumall =0; for(int i=0; i< n; i++){ arr[i] = in.nextInt(); sumall+=arr[i]; } int i=0; double sum=0; double mid = sumall/2; while(sum < mid){ sum+=arr[i]; i++; } System.out.println(i); } }
Java
["4\n1 3 2 1", "6\n2 2 2 2 2 2"]
2 seconds
["2", "3"]
NoteIn the first example Polycarp will celebrate the equator on the evening of the second day, because up to this day (inclusive) he will solve $$$4$$$ out of $$$7$$$ scheduled problems on four days of the training.In the second example Polycarp will celebrate the equator on the evening of the third day, because up to this day (inclusive) he will solve $$$6$$$ out of $$$12$$$ scheduled problems on six days of the training.
Java 8
standard input
[ "implementation" ]
241157c465fe5dd96acd514010904321
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 200\,000$$$) — the number of days to prepare for the programming contests. The second line contains a sequence $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10\,000$$$), where $$$a_i$$$ equals to the number of problems, which Polycarp will solve on the $$$i$$$-th day.
1,300
Print the index of the day when Polycarp will celebrate the equator.
standard output
PASSED
e83c86d0072d8a43cc577d75fbb0bc1c
train_001.jsonl
1523370900
Polycarp has created his own training plan to prepare for the programming contests. He will train for $$$n$$$ days, all days are numbered from $$$1$$$ to $$$n$$$, beginning from the first.On the $$$i$$$-th day Polycarp will necessarily solve $$$a_i$$$ problems. One evening Polycarp plans to celebrate the equator. He will celebrate it on the first evening of such a day that from the beginning of the training and to this day inclusive he will solve half or more of all the problems.Determine the index of day when Polycarp will celebrate the equator.
256 megabytes
import java.util.Scanner; public class Equator { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String n = sc.nextLine(); int days = Integer.parseInt(n); String input_problems = sc.nextLine(); String[] problems_per_day = input_problems.split(" "); int[] problems_so_far = new int[days]; int count = 0; for (int i = 0; i < days; i++) { count += Integer.parseInt(problems_per_day[i]); problems_so_far[i] = count; } int half = (int) Math.ceil(count / 2.0); int res = 0; A: for (int i = 0; i < days; i++) { if (problems_so_far[i] >= half) { res = i + 1; break A; } } System.out.println(res); } }
Java
["4\n1 3 2 1", "6\n2 2 2 2 2 2"]
2 seconds
["2", "3"]
NoteIn the first example Polycarp will celebrate the equator on the evening of the second day, because up to this day (inclusive) he will solve $$$4$$$ out of $$$7$$$ scheduled problems on four days of the training.In the second example Polycarp will celebrate the equator on the evening of the third day, because up to this day (inclusive) he will solve $$$6$$$ out of $$$12$$$ scheduled problems on six days of the training.
Java 8
standard input
[ "implementation" ]
241157c465fe5dd96acd514010904321
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 200\,000$$$) — the number of days to prepare for the programming contests. The second line contains a sequence $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10\,000$$$), where $$$a_i$$$ equals to the number of problems, which Polycarp will solve on the $$$i$$$-th day.
1,300
Print the index of the day when Polycarp will celebrate the equator.
standard output
PASSED
b9327e5c460810f8c23f15d0b089ce70
train_001.jsonl
1523370900
Polycarp has created his own training plan to prepare for the programming contests. He will train for $$$n$$$ days, all days are numbered from $$$1$$$ to $$$n$$$, beginning from the first.On the $$$i$$$-th day Polycarp will necessarily solve $$$a_i$$$ problems. One evening Polycarp plans to celebrate the equator. He will celebrate it on the first evening of such a day that from the beginning of the training and to this day inclusive he will solve half or more of all the problems.Determine the index of day when Polycarp will celebrate the equator.
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; public class Ideone { public static void main (String[] args) throws java.lang.Exception { Scanner sc=new Scanner(System.in); ArrayList<Integer> a=new ArrayList<Integer> (); int n=sc.nextInt(); int i,sum=0,sum1=0,c=0; for(i=0;i<n;i++){ a.add(sc.nextInt()); sum+=a.get(i);} for(i=0;i<n;i++) { sum1+=a.get(i); if(sum1<(int)Math.ceil((double)sum/2)) ++c; else break; } System.out.println(c+1);}}
Java
["4\n1 3 2 1", "6\n2 2 2 2 2 2"]
2 seconds
["2", "3"]
NoteIn the first example Polycarp will celebrate the equator on the evening of the second day, because up to this day (inclusive) he will solve $$$4$$$ out of $$$7$$$ scheduled problems on four days of the training.In the second example Polycarp will celebrate the equator on the evening of the third day, because up to this day (inclusive) he will solve $$$6$$$ out of $$$12$$$ scheduled problems on six days of the training.
Java 8
standard input
[ "implementation" ]
241157c465fe5dd96acd514010904321
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 200\,000$$$) — the number of days to prepare for the programming contests. The second line contains a sequence $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10\,000$$$), where $$$a_i$$$ equals to the number of problems, which Polycarp will solve on the $$$i$$$-th day.
1,300
Print the index of the day when Polycarp will celebrate the equator.
standard output
PASSED
d2977abfbd787288b6c0f782644ebc4f
train_001.jsonl
1523370900
Polycarp has created his own training plan to prepare for the programming contests. He will train for $$$n$$$ days, all days are numbered from $$$1$$$ to $$$n$$$, beginning from the first.On the $$$i$$$-th day Polycarp will necessarily solve $$$a_i$$$ problems. One evening Polycarp plans to celebrate the equator. He will celebrate it on the first evening of such a day that from the beginning of the training and to this day inclusive he will solve half or more of all the problems.Determine the index of day when Polycarp will celebrate the equator.
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; public class Main { private void solve() { int days = nextInt(); int[] problemsInDay = new int[days]; int sumOfProblems = 0; for(int i = 0; i < days; i++) { int tmp = nextInt(); problemsInDay[i] = tmp; sumOfProblems += tmp; } double sumDivided = 0; if(sumOfProblems % 2 == 0) { sumDivided = sumOfProblems / 2; } else { sumDivided = (sumOfProblems / 2) + 0.5; } int tmpSum = 0; for(int i = 1; i <= days; i++) { tmpSum += problemsInDay[i - 1]; if(tmpSum >= sumDivided){ System.out.println(i); break; } } } public static void main(String[] args) { new Main().run(); } BufferedReader br; StringTokenizer st; PrintWriter out; private void run() { try { br = new BufferedReader(new InputStreamReader(System.in )); out = new PrintWriter(System.out); //br = new BufferedReader(new FileReader("birthday.in ")); //out = new PrintWriter(new FileWriter("birthday.out")); solve(); br.close(); out.close(); } catch (IOException e) { e.printStackTrace(); } } private int nextInt() { return Integer.parseInt(next()); } private String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); return "END_OF_FILE"; } } return st.nextToken(); } private int[] nextIntArr(int n) { int[] arr = new int[n]; for(int i = 0; i < n; i++) arr[i] = nextInt(); return arr; } private String[] nextArr(int n) { String[] arr = new String[n]; for(int i = 0; i < n; i++) arr[i] = next(); return arr; } }
Java
["4\n1 3 2 1", "6\n2 2 2 2 2 2"]
2 seconds
["2", "3"]
NoteIn the first example Polycarp will celebrate the equator on the evening of the second day, because up to this day (inclusive) he will solve $$$4$$$ out of $$$7$$$ scheduled problems on four days of the training.In the second example Polycarp will celebrate the equator on the evening of the third day, because up to this day (inclusive) he will solve $$$6$$$ out of $$$12$$$ scheduled problems on six days of the training.
Java 8
standard input
[ "implementation" ]
241157c465fe5dd96acd514010904321
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 200\,000$$$) — the number of days to prepare for the programming contests. The second line contains a sequence $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10\,000$$$), where $$$a_i$$$ equals to the number of problems, which Polycarp will solve on the $$$i$$$-th day.
1,300
Print the index of the day when Polycarp will celebrate the equator.
standard output
PASSED
31f90610eb21a31b895df704231dec51
train_001.jsonl
1523370900
Polycarp has created his own training plan to prepare for the programming contests. He will train for $$$n$$$ days, all days are numbered from $$$1$$$ to $$$n$$$, beginning from the first.On the $$$i$$$-th day Polycarp will necessarily solve $$$a_i$$$ problems. One evening Polycarp plans to celebrate the equator. He will celebrate it on the first evening of such a day that from the beginning of the training and to this day inclusive he will solve half or more of all the problems.Determine the index of day when Polycarp will celebrate the equator.
256 megabytes
import java.util.Scanner; /** * * @author Mostafa */ public class Equator { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here Scanner in = new Scanner ( System.in ) ; int n = in.nextInt() , i ; int x [] = new int [n]; x[0] = in.nextInt() ; for ( i = 1 ; i < n ; ++i ) { x[i] = in.nextInt() + x[ i - 1 ] ; } for ( i = 0 ; i < n ; ++i ) if ( (x[ i ] - x[ n - 1 ] % 2) >= x[ n - 1 ] / 2 ) { System.out.println( i + 1 ); break ; } } }
Java
["4\n1 3 2 1", "6\n2 2 2 2 2 2"]
2 seconds
["2", "3"]
NoteIn the first example Polycarp will celebrate the equator on the evening of the second day, because up to this day (inclusive) he will solve $$$4$$$ out of $$$7$$$ scheduled problems on four days of the training.In the second example Polycarp will celebrate the equator on the evening of the third day, because up to this day (inclusive) he will solve $$$6$$$ out of $$$12$$$ scheduled problems on six days of the training.
Java 8
standard input
[ "implementation" ]
241157c465fe5dd96acd514010904321
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 200\,000$$$) — the number of days to prepare for the programming contests. The second line contains a sequence $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10\,000$$$), where $$$a_i$$$ equals to the number of problems, which Polycarp will solve on the $$$i$$$-th day.
1,300
Print the index of the day when Polycarp will celebrate the equator.
standard output
PASSED
a4a6a5ec0b303b8d8fc45c11d67c25b9
train_001.jsonl
1523370900
Polycarp has created his own training plan to prepare for the programming contests. He will train for $$$n$$$ days, all days are numbered from $$$1$$$ to $$$n$$$, beginning from the first.On the $$$i$$$-th day Polycarp will necessarily solve $$$a_i$$$ problems. One evening Polycarp plans to celebrate the equator. He will celebrate it on the first evening of such a day that from the beginning of the training and to this day inclusive he will solve half or more of all the problems.Determine the index of day when Polycarp will celebrate the equator.
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 */ 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); TaskXXXXX solver = new TaskXXXXX(); solver.solve(1, in, out); out.close(); } static class TaskXXXXX { public void solve(int testNumber, Scanner in, PrintWriter out) { int n = in.nextInt(); long sum = 0; int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = in.nextInt(); sum += a[i]; } long cur = 0; for (int i = 0; i < n; i++) { cur += a[i]; if (cur * 2 >= sum) { out.print(i + 1); return; } } } } }
Java
["4\n1 3 2 1", "6\n2 2 2 2 2 2"]
2 seconds
["2", "3"]
NoteIn the first example Polycarp will celebrate the equator on the evening of the second day, because up to this day (inclusive) he will solve $$$4$$$ out of $$$7$$$ scheduled problems on four days of the training.In the second example Polycarp will celebrate the equator on the evening of the third day, because up to this day (inclusive) he will solve $$$6$$$ out of $$$12$$$ scheduled problems on six days of the training.
Java 8
standard input
[ "implementation" ]
241157c465fe5dd96acd514010904321
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 200\,000$$$) — the number of days to prepare for the programming contests. The second line contains a sequence $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10\,000$$$), where $$$a_i$$$ equals to the number of problems, which Polycarp will solve on the $$$i$$$-th day.
1,300
Print the index of the day when Polycarp will celebrate the equator.
standard output
PASSED
34f2e584398e4e1232dcb42dd9366ae4
train_001.jsonl
1523370900
Polycarp has created his own training plan to prepare for the programming contests. He will train for $$$n$$$ days, all days are numbered from $$$1$$$ to $$$n$$$, beginning from the first.On the $$$i$$$-th day Polycarp will necessarily solve $$$a_i$$$ problems. One evening Polycarp plans to celebrate the equator. He will celebrate it on the first evening of such a day that from the beginning of the training and to this day inclusive he will solve half or more of all the problems.Determine the index of day when Polycarp will celebrate the equator.
256 megabytes
import java.util.*; public class Equator { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int arr[] = new int[n]; long sum = 0; for(int i = 0; i<n; i++) { arr[i] = sc.nextInt(); sum += arr[i]; } long curr = 0; long half = sum/2; if((sum%2)==1) half++; for(int i = 0; i<n; i++) { curr += arr[i]; if(curr>=half) { System.out.println(""+(i+1)); break; } } } }
Java
["4\n1 3 2 1", "6\n2 2 2 2 2 2"]
2 seconds
["2", "3"]
NoteIn the first example Polycarp will celebrate the equator on the evening of the second day, because up to this day (inclusive) he will solve $$$4$$$ out of $$$7$$$ scheduled problems on four days of the training.In the second example Polycarp will celebrate the equator on the evening of the third day, because up to this day (inclusive) he will solve $$$6$$$ out of $$$12$$$ scheduled problems on six days of the training.
Java 8
standard input
[ "implementation" ]
241157c465fe5dd96acd514010904321
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 200\,000$$$) — the number of days to prepare for the programming contests. The second line contains a sequence $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10\,000$$$), where $$$a_i$$$ equals to the number of problems, which Polycarp will solve on the $$$i$$$-th day.
1,300
Print the index of the day when Polycarp will celebrate the equator.
standard output
PASSED
b0b1e9aa8255584dcce9e5e0792b674a
train_001.jsonl
1523370900
Polycarp has created his own training plan to prepare for the programming contests. He will train for $$$n$$$ days, all days are numbered from $$$1$$$ to $$$n$$$, beginning from the first.On the $$$i$$$-th day Polycarp will necessarily solve $$$a_i$$$ problems. One evening Polycarp plans to celebrate the equator. He will celebrate it on the first evening of such a day that from the beginning of the training and to this day inclusive he will solve half or more of all the problems.Determine the index of day when Polycarp will celebrate the equator.
256 megabytes
import java.util.*; import java.lang.Math; import java.io.*; public class Solution { public static void main(String[] args) throws IOException { FastReader in=new FastReader(System.in); int n=in.nextInt(); long[] sum=new long[n]; sum[0]=in.nextLong(); for(int i=1;i<n;i++) { sum[i]=sum[i-1]+in.nextLong(); } int ans=0; long x=sum[n-1]/2; if(sum[n-1]%2!=0) x++; ans=Arrays.binarySearch(sum,x); if(ans<0) { System.out.println(Math.abs(ans)); } else { ans++; System.out.println(ans); } } } class FastReader { static BufferedReader br; static StringTokenizer st; public FastReader(InputStream in) throws IOException { br=new BufferedReader(new InputStreamReader(in)); } static String next() throws IOException { if(st==null || !st.hasMoreElements()) { st=new StringTokenizer(br.readLine()); } return st.nextToken(); } static int nextInt() throws IOException { return Integer.parseInt(next()); } static long nextLong() throws IOException { return Long.parseLong(next()); } static double nextDouble() throws IOException { return Double.parseDouble(next()); } }
Java
["4\n1 3 2 1", "6\n2 2 2 2 2 2"]
2 seconds
["2", "3"]
NoteIn the first example Polycarp will celebrate the equator on the evening of the second day, because up to this day (inclusive) he will solve $$$4$$$ out of $$$7$$$ scheduled problems on four days of the training.In the second example Polycarp will celebrate the equator on the evening of the third day, because up to this day (inclusive) he will solve $$$6$$$ out of $$$12$$$ scheduled problems on six days of the training.
Java 8
standard input
[ "implementation" ]
241157c465fe5dd96acd514010904321
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 200\,000$$$) — the number of days to prepare for the programming contests. The second line contains a sequence $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10\,000$$$), where $$$a_i$$$ equals to the number of problems, which Polycarp will solve on the $$$i$$$-th day.
1,300
Print the index of the day when Polycarp will celebrate the equator.
standard output
PASSED
94e5e5c47644b725f78cfda7f7b932cc
train_001.jsonl
1523370900
Polycarp has created his own training plan to prepare for the programming contests. He will train for $$$n$$$ days, all days are numbered from $$$1$$$ to $$$n$$$, beginning from the first.On the $$$i$$$-th day Polycarp will necessarily solve $$$a_i$$$ problems. One evening Polycarp plans to celebrate the equator. He will celebrate it on the first evening of such a day that from the beginning of the training and to this day inclusive he will solve half or more of all the problems.Determine the index of day when Polycarp will celebrate the equator.
256 megabytes
import java.util.Scanner; public class EQUATOR { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int n=sc.nextInt(); int arr[]=new int[n]; long sum=0; for(int i=0;i<n;i++){ arr[i]=sc.nextInt(); sum=sum+arr[i]; } long sum2=0; for(int i=0;i<n;i++){ sum2=sum2+arr[i]; if((2*sum2)>=sum){System.out.println(i+1);break;} } } }
Java
["4\n1 3 2 1", "6\n2 2 2 2 2 2"]
2 seconds
["2", "3"]
NoteIn the first example Polycarp will celebrate the equator on the evening of the second day, because up to this day (inclusive) he will solve $$$4$$$ out of $$$7$$$ scheduled problems on four days of the training.In the second example Polycarp will celebrate the equator on the evening of the third day, because up to this day (inclusive) he will solve $$$6$$$ out of $$$12$$$ scheduled problems on six days of the training.
Java 8
standard input
[ "implementation" ]
241157c465fe5dd96acd514010904321
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 200\,000$$$) — the number of days to prepare for the programming contests. The second line contains a sequence $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10\,000$$$), where $$$a_i$$$ equals to the number of problems, which Polycarp will solve on the $$$i$$$-th day.
1,300
Print the index of the day when Polycarp will celebrate the equator.
standard output
PASSED
657c29e6698a10e966dbaec0cb72d068
train_001.jsonl
1523370900
Polycarp has created his own training plan to prepare for the programming contests. He will train for $$$n$$$ days, all days are numbered from $$$1$$$ to $$$n$$$, beginning from the first.On the $$$i$$$-th day Polycarp will necessarily solve $$$a_i$$$ problems. One evening Polycarp plans to celebrate the equator. He will celebrate it on the first evening of such a day that from the beginning of the training and to this day inclusive he will solve half or more of all the problems.Determine the index of day when Polycarp will celebrate the equator.
256 megabytes
import java.util.Scanner; public class EQUATOR { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int n=sc.nextInt(); double arr[]=new double[n]; double sum=0; for(int i=0;i<n;i++){ arr[i]=sc.nextInt(); sum=sum+arr[i]; } double half=0; if(sum>0){ half=sum/2.0; } double sum2=0; for(int i=0;i<n;i++){ sum2=sum2+arr[i]; if(sum2>=half){System.out.println(i+1);break;} } } }
Java
["4\n1 3 2 1", "6\n2 2 2 2 2 2"]
2 seconds
["2", "3"]
NoteIn the first example Polycarp will celebrate the equator on the evening of the second day, because up to this day (inclusive) he will solve $$$4$$$ out of $$$7$$$ scheduled problems on four days of the training.In the second example Polycarp will celebrate the equator on the evening of the third day, because up to this day (inclusive) he will solve $$$6$$$ out of $$$12$$$ scheduled problems on six days of the training.
Java 8
standard input
[ "implementation" ]
241157c465fe5dd96acd514010904321
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 200\,000$$$) — the number of days to prepare for the programming contests. The second line contains a sequence $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10\,000$$$), where $$$a_i$$$ equals to the number of problems, which Polycarp will solve on the $$$i$$$-th day.
1,300
Print the index of the day when Polycarp will celebrate the equator.
standard output
PASSED
accdddfc92f84ee33b6b507b83dd52f7
train_001.jsonl
1523370900
Polycarp has created his own training plan to prepare for the programming contests. He will train for $$$n$$$ days, all days are numbered from $$$1$$$ to $$$n$$$, beginning from the first.On the $$$i$$$-th day Polycarp will necessarily solve $$$a_i$$$ problems. One evening Polycarp plans to celebrate the equator. He will celebrate it on the first evening of such a day that from the beginning of the training and to this day inclusive he will solve half or more of all the problems.Determine the index of day when Polycarp will celebrate the equator.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.PrintStream; import java.util.InputMismatchException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Nirav */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; Scan in = new Scan(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, Scan in, PrintWriter out) { int N = in.scanInt(); long[] a = new long[N + 1]; for (int i = 1; i <= N; i++) { a[i] = in.scanLong(); a[i] += a[i - 1]; } long total = a[N]; int i = 1; while (a[i] < ((double) total / 2)) { i++; } out.println(i); } } static class Scan { private byte[] buf = new byte[1024]; private int index; private InputStream in; private int total; public Scan() { in = System.in; } public Scan(InputStream inputStream) { in = inputStream; } public int scan() { if (total < 0) { return 0; } if (index >= total) { index = 0; try { total = in.read(buf); } catch (Exception e) { System.out.println(e); } if (total <= 0) return -1; } return buf[index++]; } public int scanInt() { int integer = 0; int n = scan(); while (isWhiteSpace(n)) n = scan(); int neg = 1; if (n == '-') { neg = -1; n = scan(); } while (!isWhiteSpace(n)) { if (n >= '0' && n <= '9') { integer *= 10; integer += n - '0'; n = scan(); } else throw new InputMismatchException(); } return neg * integer; } public long scanLong() { long lng = 0; int n = scan(); while (isWhiteSpace(n)) n = scan(); int neg = 1; if (n == '-') { neg = -1; n = scan(); } while (!isWhiteSpace(n) && n != '.') { if (n >= '0' && n <= '9') { lng *= 10; lng += n - '0'; n = scan(); } else throw new InputMismatchException(); } if (n == '.') { n = scan(); long temp = 1; while (!isWhiteSpace(n)) { if (n >= '0' && n <= '9') { temp /= 10; lng += (n - '0') * temp; n = scan(); } else throw new InputMismatchException(); } } return neg * lng; } private boolean isWhiteSpace(int n) { if (n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1) return true; return false; } } }
Java
["4\n1 3 2 1", "6\n2 2 2 2 2 2"]
2 seconds
["2", "3"]
NoteIn the first example Polycarp will celebrate the equator on the evening of the second day, because up to this day (inclusive) he will solve $$$4$$$ out of $$$7$$$ scheduled problems on four days of the training.In the second example Polycarp will celebrate the equator on the evening of the third day, because up to this day (inclusive) he will solve $$$6$$$ out of $$$12$$$ scheduled problems on six days of the training.
Java 8
standard input
[ "implementation" ]
241157c465fe5dd96acd514010904321
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 200\,000$$$) — the number of days to prepare for the programming contests. The second line contains a sequence $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10\,000$$$), where $$$a_i$$$ equals to the number of problems, which Polycarp will solve on the $$$i$$$-th day.
1,300
Print the index of the day when Polycarp will celebrate the equator.
standard output
PASSED
a53a89d2fba5763bce1b97e7ea5b57cc
train_001.jsonl
1523370900
Polycarp has created his own training plan to prepare for the programming contests. He will train for $$$n$$$ days, all days are numbered from $$$1$$$ to $$$n$$$, beginning from the first.On the $$$i$$$-th day Polycarp will necessarily solve $$$a_i$$$ problems. One evening Polycarp plans to celebrate the equator. He will celebrate it on the first evening of such a day that from the beginning of the training and to this day inclusive he will solve half or more of all the problems.Determine the index of day when Polycarp will celebrate the equator.
256 megabytes
import java.util.Scanner; /** * * @author Ahmad */ public class JavaApplication1 { /** * @param args the command line arguments */ public static void main(String[] args) { Scanner console = new Scanner (System.in) ; int n = console.nextInt() ; int count = 0 ; int countt = 0 ; int ind = 0 ; int []x = new int [n] ; for (int i=0 ; i<x.length ; i++){ x[i]=console.nextInt() ; count += x[i] ; } int m = (int) Math.ceil(count/2.0) ; for (int i=0 ; i<x.length ; i++){ countt += x[i] ; if (countt>=m){ ind=i+1 ; break ; } } System.out.println(ind); } }
Java
["4\n1 3 2 1", "6\n2 2 2 2 2 2"]
2 seconds
["2", "3"]
NoteIn the first example Polycarp will celebrate the equator on the evening of the second day, because up to this day (inclusive) he will solve $$$4$$$ out of $$$7$$$ scheduled problems on four days of the training.In the second example Polycarp will celebrate the equator on the evening of the third day, because up to this day (inclusive) he will solve $$$6$$$ out of $$$12$$$ scheduled problems on six days of the training.
Java 8
standard input
[ "implementation" ]
241157c465fe5dd96acd514010904321
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 200\,000$$$) — the number of days to prepare for the programming contests. The second line contains a sequence $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10\,000$$$), where $$$a_i$$$ equals to the number of problems, which Polycarp will solve on the $$$i$$$-th day.
1,300
Print the index of the day when Polycarp will celebrate the equator.
standard output
PASSED
7fbbe7aa7b1c07ae45170f530b9bca8e
train_001.jsonl
1523370900
Polycarp has created his own training plan to prepare for the programming contests. He will train for $$$n$$$ days, all days are numbered from $$$1$$$ to $$$n$$$, beginning from the first.On the $$$i$$$-th day Polycarp will necessarily solve $$$a_i$$$ problems. One evening Polycarp plans to celebrate the equator. He will celebrate it on the first evening of such a day that from the beginning of the training and to this day inclusive he will solve half or more of all the problems.Determine the index of day when Polycarp will celebrate the equator.
256 megabytes
import java.io.*; public class Main { public static void main(String[] args) throws IOException { FastScanner in = new FastScanner(System.in); PrintWriter out = new PrintWriter(System.out); int n= in.nextInt(); int sum=0,sum1=0; int[] tabb = in.nextIntArray(n); for (int i=0;i<n;i++){ sum+=tabb[i]; } for (int i=0;i<n;i++){ sum1+=tabb[i]; if (sum1>=(((double)(sum)/2))){ sum1=i; break; } } out.print(sum1+1); out.close(); } static class FastScanner { private BufferedReader in; private String[] line; private int index; private int size; public FastScanner(InputStream in) throws IOException { this.in = new BufferedReader(new InputStreamReader(in)); init(); } public FastScanner(String file) throws FileNotFoundException { this.in = new BufferedReader(new FileReader(file)); } private void init() throws IOException { line = in.readLine().split(" "); index = 0; size = line.length; } public int nextInt() throws IOException { if (index == size) { init(); } return Integer.parseInt(line[index++]); } public long nextLong() throws IOException { if (index == size) { init(); } return Long.parseLong(line[index++]); } public float nextFloat() throws IOException { if (index == size) { init(); } return Float.parseFloat(line[index++]); } public double nextDouble() throws IOException { if (index == size) { init(); } return Double.parseDouble(line[index++]); } public String next() throws IOException { if (index == size) { init(); } return line[index++]; } public String nextLine() throws IOException { if (index == size) { init(); } StringBuilder sb = new StringBuilder(); for (int i = index; i < size; i++) { sb.append(line[i]).append(" "); } index=size; return sb.toString(); } private int[] nextIntArray(int n) throws IOException { int[] tab = new int[n]; for (int i = 0; i < tab.length; i++) { tab[i] = nextInt(); } return tab; } private double[] nextDoubleArray(int n) throws IOException { double[] tab = new double[n]; for (int i = 0; i < tab.length; i++) { tab[i] = nextDouble(); } return tab; } } }
Java
["4\n1 3 2 1", "6\n2 2 2 2 2 2"]
2 seconds
["2", "3"]
NoteIn the first example Polycarp will celebrate the equator on the evening of the second day, because up to this day (inclusive) he will solve $$$4$$$ out of $$$7$$$ scheduled problems on four days of the training.In the second example Polycarp will celebrate the equator on the evening of the third day, because up to this day (inclusive) he will solve $$$6$$$ out of $$$12$$$ scheduled problems on six days of the training.
Java 8
standard input
[ "implementation" ]
241157c465fe5dd96acd514010904321
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 200\,000$$$) — the number of days to prepare for the programming contests. The second line contains a sequence $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10\,000$$$), where $$$a_i$$$ equals to the number of problems, which Polycarp will solve on the $$$i$$$-th day.
1,300
Print the index of the day when Polycarp will celebrate the equator.
standard output
PASSED
1974d3b8d3d8e2de1c004b4918a103ff
train_001.jsonl
1523370900
Polycarp has created his own training plan to prepare for the programming contests. He will train for $$$n$$$ days, all days are numbered from $$$1$$$ to $$$n$$$, beginning from the first.On the $$$i$$$-th day Polycarp will necessarily solve $$$a_i$$$ problems. One evening Polycarp plans to celebrate the equator. He will celebrate it on the first evening of such a day that from the beginning of the training and to this day inclusive he will solve half or more of all the problems.Determine the index of day when Polycarp will celebrate the equator.
256 megabytes
import java.util.Scanner; import java.util.ArrayList; public class Equator{ static int run(int n, String[] a){ int[] an = new int[a.length]; int sum = 0; for(int i = 0; i < an.length; i ++){ sum += Integer.parseInt(a[i]); an[i] = sum; } for(int i = 0; i < an.length; i ++){ if(an[an.length-1] / (double) an[i] <= 2){ return i+1; } } return 0; } public static void main(String[] args){ Scanner s = new Scanner(System.in); int n = Integer.parseInt(s.nextLine()); String[] a = s.nextLine().split(" "); System.out.println(run(n, a)); } }
Java
["4\n1 3 2 1", "6\n2 2 2 2 2 2"]
2 seconds
["2", "3"]
NoteIn the first example Polycarp will celebrate the equator on the evening of the second day, because up to this day (inclusive) he will solve $$$4$$$ out of $$$7$$$ scheduled problems on four days of the training.In the second example Polycarp will celebrate the equator on the evening of the third day, because up to this day (inclusive) he will solve $$$6$$$ out of $$$12$$$ scheduled problems on six days of the training.
Java 8
standard input
[ "implementation" ]
241157c465fe5dd96acd514010904321
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 200\,000$$$) — the number of days to prepare for the programming contests. The second line contains a sequence $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10\,000$$$), where $$$a_i$$$ equals to the number of problems, which Polycarp will solve on the $$$i$$$-th day.
1,300
Print the index of the day when Polycarp will celebrate the equator.
standard output
PASSED
94f84d163e4ff362a88be7ff02b96790
train_001.jsonl
1523370900
Polycarp has created his own training plan to prepare for the programming contests. He will train for $$$n$$$ days, all days are numbered from $$$1$$$ to $$$n$$$, beginning from the first.On the $$$i$$$-th day Polycarp will necessarily solve $$$a_i$$$ problems. One evening Polycarp plans to celebrate the equator. He will celebrate it on the first evening of such a day that from the beginning of the training and to this day inclusive he will solve half or more of all the problems.Determine the index of day when Polycarp will celebrate the equator.
256 megabytes
import java.util.*; public class contestA { public static void main(String[]args){ double answer=0;int sum=0; 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();sum+=arr[i]; } for(int i=0;i<n;i++){ answer+=arr[i];if(answer>=sum/2.0){System.out.println(i+1);return;} } } }
Java
["4\n1 3 2 1", "6\n2 2 2 2 2 2"]
2 seconds
["2", "3"]
NoteIn the first example Polycarp will celebrate the equator on the evening of the second day, because up to this day (inclusive) he will solve $$$4$$$ out of $$$7$$$ scheduled problems on four days of the training.In the second example Polycarp will celebrate the equator on the evening of the third day, because up to this day (inclusive) he will solve $$$6$$$ out of $$$12$$$ scheduled problems on six days of the training.
Java 8
standard input
[ "implementation" ]
241157c465fe5dd96acd514010904321
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 200\,000$$$) — the number of days to prepare for the programming contests. The second line contains a sequence $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10\,000$$$), where $$$a_i$$$ equals to the number of problems, which Polycarp will solve on the $$$i$$$-th day.
1,300
Print the index of the day when Polycarp will celebrate the equator.
standard output
PASSED
581a29e7e66c5799d793085ecc3cb1ff
train_001.jsonl
1523370900
Polycarp has created his own training plan to prepare for the programming contests. He will train for $$$n$$$ days, all days are numbered from $$$1$$$ to $$$n$$$, beginning from the first.On the $$$i$$$-th day Polycarp will necessarily solve $$$a_i$$$ problems. One evening Polycarp plans to celebrate the equator. He will celebrate it on the first evening of such a day that from the beginning of the training and to this day inclusive he will solve half or more of all the problems.Determine the index of day when Polycarp will celebrate the equator.
256 megabytes
import java.lang.*; import java.io.*; import java.util.*; public class MyClass { public static void main(String args[]) { Scanner sc=new Scanner(System.in); int n=sc.nextInt(); int a[]=new int[n]; int p[]=new int[n+1]; int sum=0; for(int i=0;i<n;i++) { a[i]=sc.nextInt(); sum=sum+a[i]; } p[1]=a[0]; for(int i=2;i<=n;i++) { p[i]=p[i-1]+a[i-1]; } int k=(int)Math.ceil((double)sum/2); for(int i=1;i<=n;i++) {//System.out.println(p[i]); if(p[i]>=k) { System.out.println(i); break; } }//System.out.print(k); } }
Java
["4\n1 3 2 1", "6\n2 2 2 2 2 2"]
2 seconds
["2", "3"]
NoteIn the first example Polycarp will celebrate the equator on the evening of the second day, because up to this day (inclusive) he will solve $$$4$$$ out of $$$7$$$ scheduled problems on four days of the training.In the second example Polycarp will celebrate the equator on the evening of the third day, because up to this day (inclusive) he will solve $$$6$$$ out of $$$12$$$ scheduled problems on six days of the training.
Java 8
standard input
[ "implementation" ]
241157c465fe5dd96acd514010904321
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 200\,000$$$) — the number of days to prepare for the programming contests. The second line contains a sequence $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10\,000$$$), where $$$a_i$$$ equals to the number of problems, which Polycarp will solve on the $$$i$$$-th day.
1,300
Print the index of the day when Polycarp will celebrate the equator.
standard output
PASSED
cdc3cb32d560722311063341988a6d14
train_001.jsonl
1403191800
When Adam gets a rooted tree (connected non-directed graph without cycles), he immediately starts coloring it. More formally, he assigns a color to each edge of the tree so that it meets the following two conditions: There is no vertex that has more than two incident edges painted the same color. For any two vertexes that have incident edges painted the same color (say, c), the path between them consists of the edges of the color c. Not all tree paintings are equally good for Adam. Let's consider the path from some vertex to the root. Let's call the number of distinct colors on this path the cost of the vertex. The cost of the tree's coloring will be the maximum cost among all the vertexes. Help Adam determine the minimum possible cost of painting the tree. Initially, Adam's tree consists of a single vertex that has number one and is the root. In one move Adam adds a new vertex to the already existing one, the new vertex gets the number equal to the minimum positive available integer. After each operation you need to calculate the minimum cost of coloring the resulting tree.
256 megabytes
import java.io.InputStreamReader; import java.io.IOException; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.math.BigInteger; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ 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); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } } class TaskD { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int[] parent = new int[n + 2]; int[] value = new int[n + 2]; int[] max = new int[n + 2]; for (int i = 2; i <= n+1; ++i) { parent[i] = in.nextInt(); value[i] = 0; int up = 1; int cur = i; while (cur != 1) { int next = parent[cur]; if (value[next] < up) { value[next] = up; max[next] = cur; } else if (value[next] == up && cur != max[next]) { ++up; } else { break; } cur = next; } out.print(value[1] + " "); } out.println(); } } class InputReader { private BufferedReader reader; private StringTokenizer stt; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); } public String nextLine() { try { return reader.readLine().trim(); } catch (IOException e) { return null; } } public String nextString() { while (stt == null || !stt.hasMoreTokens()) { stt = new StringTokenizer(nextLine()); } return stt.nextToken(); } public int nextInt() { return Integer.parseInt(nextString()); } }
Java
["11\n1 1 1 3 4 4 7 3 7 6 6"]
2 seconds
["1 1 1 1 1 2 2 2 2 2 3"]
NoteThe figure below shows one of the possible variants to paint a tree from the sample at the last moment. The cost of the vertexes with numbers 11 and 12 equals 3.
Java 8
standard input
[ "data structures", "trees" ]
dd47f47922a5457f89391beea749242b
The first line contains integer n (1 ≤ n ≤ 106) — the number of times a new vertex is added. The second line contains n numbers pi (1 ≤ pi ≤ i) — the numbers of the vertexes to which we add another vertex.
2,600
Print n integers — the minimum costs of the tree painting after each addition.
standard output
PASSED
6c1f3cdd50d14f996a606debcea7bc33
train_001.jsonl
1403191800
When Adam gets a rooted tree (connected non-directed graph without cycles), he immediately starts coloring it. More formally, he assigns a color to each edge of the tree so that it meets the following two conditions: There is no vertex that has more than two incident edges painted the same color. For any two vertexes that have incident edges painted the same color (say, c), the path between them consists of the edges of the color c. Not all tree paintings are equally good for Adam. Let's consider the path from some vertex to the root. Let's call the number of distinct colors on this path the cost of the vertex. The cost of the tree's coloring will be the maximum cost among all the vertexes. Help Adam determine the minimum possible cost of painting the tree. Initially, Adam's tree consists of a single vertex that has number one and is the root. In one move Adam adds a new vertex to the already existing one, the new vertex gets the number equal to the minimum positive available integer. After each operation you need to calculate the minimum cost of coloring the resulting tree.
256 megabytes
import java.io.*; import java.lang.reflect.Array; import java.util.*; import java.math.BigInteger; import java.util.Collections.*; import java.util.function.Consumer; import static java.lang.Math.*; import static java.lang.Math.min; import static java.util.Arrays.*; import static java.math.BigInteger.*; public class Main{ void run(){ Locale.setDefault(Locale.US); boolean my; try { my = System.getProperty("MY_LOCAL") != null; } catch (Exception e) { my = false; } try{ err = System.err; if( my ){ sc = new FastScanner(new BufferedReader(new FileReader("input.txt"))); // sc = new FastScanner(new BufferedReader(new FileReader("C:\\myTest.txt"))); out = new PrintWriter (new FileWriter("output.txt")); } else { sc = new FastScanner(new BufferedReader(new InputStreamReader(System.in))); out = new PrintWriter(new OutputStreamWriter(System.out)); } // out = new PrintWriter(new OutputStreamWriter(System.out)); }catch(Exception e){ MLE(); } if( my ) tBeg = System.currentTimeMillis(); solve(); if( my ) err.println( "TIME: " + (System.currentTimeMillis() - tBeg ) / 1e3 ); exit(0); } void exit( int val ){ err.flush(); out.flush(); System.exit(val); } double tBeg; FastScanner sc; PrintWriter out; PrintStream err; class FastScanner{ StringTokenizer st; BufferedReader br; FastScanner( BufferedReader _br ){ br = _br; } String readLine(){ try { return br.readLine(); } catch (IOException e) { return null; } } String next(){ while( st==null || !st.hasMoreElements() ) st = new StringTokenizer(readLine()); return st.nextToken(); } int nextInt(){ return Integer.parseInt(next()); } long nextLong(){ return Long.parseLong(next()); } double nextDouble(){ return Double.parseDouble(next()); } } void MLE(){ int[][] arr = new int[1024*1024][]; for( int i = 0; i < 1024*1024; ++i ) arr[i] = new int[1024*1024]; } void MLE( boolean doNotMLE ){ if( !doNotMLE ) MLE(); } void TLE(){ for(;;); } public static void main(String[] args) { new Main().run(); // new Thread( null, new Runnable() { // @Override // public void run() { // new Main().run(); // } // }, "Lolka", 256_000_000L ).run(); } //////////////////////////////////////////////////////////////// int n; int[] dp; int[] pr; ArrayList<Integer>[] val; void trim( ArrayList<Integer> arr ){ Collections.sort( arr ); while( 3 <= arr.size() ){ arr.remove( 0 ); } } void upd( int v ){ if( v == 1 ){ dp[v] = 1 + val[v].get( val[v].size() - 1 ); } else{ int newDp = 0; if ( val[v].size() == 1 ) newDp = val[v].get(0); else if( val[v].size() == 2 ) newDp = max(val[v].get(0)+1, val[v].get(1)); else MLE(); if( newDp < dp[v] ) MLE(); if( newDp > dp[v] ){ int p = pr[v]; val[p].remove( (Integer) dp[v] ); dp[v] = newDp; val[p].add( dp[v] ); trim( val[p] ); upd(p); } } } void solve(){ n = sc.nextInt(); dp = new int[n+2]; pr = new int[n+2]; fill( pr, -1 ); val = new ArrayList[n+2]; for (int v = 1; v < val.length; v++) { val[v] = new ArrayList<>(3); } for (int i = 0, v = 2; i < n; i++, ++v) { pr[v] = sc.nextInt(); val[pr[v]].add( 0 ); trim( val[pr[v]] ); upd(pr[v]); out.print( " " + (dp[1]) ); } } }
Java
["11\n1 1 1 3 4 4 7 3 7 6 6"]
2 seconds
["1 1 1 1 1 2 2 2 2 2 3"]
NoteThe figure below shows one of the possible variants to paint a tree from the sample at the last moment. The cost of the vertexes with numbers 11 and 12 equals 3.
Java 8
standard input
[ "data structures", "trees" ]
dd47f47922a5457f89391beea749242b
The first line contains integer n (1 ≤ n ≤ 106) — the number of times a new vertex is added. The second line contains n numbers pi (1 ≤ pi ≤ i) — the numbers of the vertexes to which we add another vertex.
2,600
Print n integers — the minimum costs of the tree painting after each addition.
standard output
PASSED
c16ed0c5916bc48422c514f6ce09c5c4
train_001.jsonl
1432053000
Little Susie listens to fairy tales before bed every day. Today's fairy tale was about wood cutters and the little girl immediately started imagining the choppers cutting wood. She imagined the situation that is described below.There are n trees located along the road at points with coordinates x1, x2, ..., xn. Each tree has its height hi. Woodcutters can cut down a tree and fell it to the left or to the right. After that it occupies one of the segments [xi - hi, xi] or [xi;xi + hi]. The tree that is not cut down occupies a single point with coordinate xi. Woodcutters can fell a tree if the segment to be occupied by the fallen tree doesn't contain any occupied point. The woodcutters want to process as many trees as possible, so Susie wonders, what is the maximum number of trees to fell.
256 megabytes
import java.util.Scanner; public class woodcutter { public static void main(String[] arg){ Scanner scan = new Scanner(System.in); int len = scan.nextInt(); if(len<2){System.out.println(len); return;} int[][] nums = new int[len][2]; boolean[] v = new boolean[len+1]; for(int i = 0;i<len;i++){ String s = scan.nextLine(); if(s.length()==0){ i--; continue; } String[] num = s.split("\\s+"); if(num[0].length()>0){ // System.out.println("here"); nums[i][0] = Integer.parseInt(num[0]); nums[i][1] = Integer.parseInt(num[1]); } } scan.close(); int res = 2; for(int i = 1;i<len-1;i++){ int idx = nums[i][0]; int l = nums[i][1]; if((idx-l>nums[i-1][0] && !v[i-1]) || (idx-l>(nums[i-1][0]+nums[i-1][1]))){ res++; } else if(idx+l<nums[i+1][0]){ res++; v[i] = true; } } System.out.println(res); } }
Java
["5\n1 2\n2 1\n5 10\n10 9\n19 1", "5\n1 2\n2 1\n5 10\n10 9\n20 1"]
1 second
["3", "4"]
NoteIn the first sample you can fell the trees like that: fell the 1-st tree to the left — now it occupies segment [ - 1;1] fell the 2-nd tree to the right — now it occupies segment [2;3] leave the 3-rd tree — it occupies point 5 leave the 4-th tree — it occupies point 10 fell the 5-th tree to the right — now it occupies segment [19;20] In the second sample you can also fell 4-th tree to the right, after that it will occupy segment [10;19].
Java 8
standard input
[ "dp", "greedy" ]
a850dd88a67a6295823e70e2c5c857c9
The first line contains integer n (1 ≤ n ≤ 105) — the number of trees. Next n lines contain pairs of integers xi, hi (1 ≤ xi, hi ≤ 109) — the coordinate and the height of the і-th tree. The pairs are given in the order of ascending xi. No two trees are located at the point with the same coordinate.
1,500
Print a single number — the maximum number of trees that you can cut down by the given rules.
standard output
PASSED
399bb9ba43fd8f9b8265fc9cec3139f9
train_001.jsonl
1432053000
Little Susie listens to fairy tales before bed every day. Today's fairy tale was about wood cutters and the little girl immediately started imagining the choppers cutting wood. She imagined the situation that is described below.There are n trees located along the road at points with coordinates x1, x2, ..., xn. Each tree has its height hi. Woodcutters can cut down a tree and fell it to the left or to the right. After that it occupies one of the segments [xi - hi, xi] or [xi;xi + hi]. The tree that is not cut down occupies a single point with coordinate xi. Woodcutters can fell a tree if the segment to be occupied by the fallen tree doesn't contain any occupied point. The woodcutters want to process as many trees as possible, so Susie wonders, what is the maximum number of trees to fell.
256 megabytes
import java.util.*; import java.io.*; public class Main implements Runnable { public void solve() throws IOException { int n = nextInt(); int[] x = new int[n]; int[] h = new int[n]; for(int i = 0; i < n; i++){ x[i] = nextInt(); h[i] = nextInt(); } int answer = 0; int last = Integer.MIN_VALUE; for(int i = 0; i < n; i++){ if(last < x[i] - h[i]){ answer++; last = x[i]; } else if(i+1 == n || x[i] + h[i] < x[i+1]){ answer++; last = x[i] + h[i]; } else last = x[i]; } out.println(answer); } //----------------------------------------------------------- public static void main(String[] args) { new Main().run(); } public void debug(Object... arr){ System.out.println(Arrays.deepToString(arr)); } public void print1Int(int[] a){ for(int i = 0; i < a.length; i++) System.out.print(a[i] + " "); System.out.println(); } public void print2Int(int[][] a){ for(int i = 0; i < a.length; i++){ for(int j = 0; j < a[0].length; j++){ System.out.print(a[i][j] + " "); } System.out.println(); } } public void run() { try { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); tok = null; solve(); in.close(); out.close(); } catch (IOException e) { System.exit(0); } } public String nextToken() throws IOException { while (tok == null || !tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); } return tok.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(nextToken()); } public long nextLong() throws IOException { return Long.parseLong(nextToken()); } public double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } PrintWriter out; BufferedReader in; StringTokenizer tok; }
Java
["5\n1 2\n2 1\n5 10\n10 9\n19 1", "5\n1 2\n2 1\n5 10\n10 9\n20 1"]
1 second
["3", "4"]
NoteIn the first sample you can fell the trees like that: fell the 1-st tree to the left — now it occupies segment [ - 1;1] fell the 2-nd tree to the right — now it occupies segment [2;3] leave the 3-rd tree — it occupies point 5 leave the 4-th tree — it occupies point 10 fell the 5-th tree to the right — now it occupies segment [19;20] In the second sample you can also fell 4-th tree to the right, after that it will occupy segment [10;19].
Java 8
standard input
[ "dp", "greedy" ]
a850dd88a67a6295823e70e2c5c857c9
The first line contains integer n (1 ≤ n ≤ 105) — the number of trees. Next n lines contain pairs of integers xi, hi (1 ≤ xi, hi ≤ 109) — the coordinate and the height of the і-th tree. The pairs are given in the order of ascending xi. No two trees are located at the point with the same coordinate.
1,500
Print a single number — the maximum number of trees that you can cut down by the given rules.
standard output
PASSED
73b40f850d47b95046e8615609735c68
train_001.jsonl
1432053000
Little Susie listens to fairy tales before bed every day. Today's fairy tale was about wood cutters and the little girl immediately started imagining the choppers cutting wood. She imagined the situation that is described below.There are n trees located along the road at points with coordinates x1, x2, ..., xn. Each tree has its height hi. Woodcutters can cut down a tree and fell it to the left or to the right. After that it occupies one of the segments [xi - hi, xi] or [xi;xi + hi]. The tree that is not cut down occupies a single point with coordinate xi. Woodcutters can fell a tree if the segment to be occupied by the fallen tree doesn't contain any occupied point. The woodcutters want to process as many trees as possible, so Susie wonders, what is the maximum number of trees to fell.
256 megabytes
import java.util.*; import java.io.*; public class Main implements Runnable { int[][] a; int[][] b; int[][] ret; boolean[][] was; int n; public void solve() throws IOException { n = nextInt(); a = new int[n][3]; b = new int[n][3]; ret = new int[n][3]; was = new boolean[n][3]; for(int i = 0; i < n; i++){ int x = nextInt(); int y = nextInt(); a[i][0] = x - y; b[i][0] = x; a[i][1] = x; b[i][1] = x; a[i][2] = x; b[i][2] = x + y; } out.println(doitDP(1, 0) + 1); } private boolean good(int i, int last, int now, int cur){ return b[i][last] < a[now][cur]; } private int doitDP(int i, int last){ if(i == n) return 0; if(was[i][last]) return ret[i][last]; was[i][last] = true; int now = 0; for(int cur = 0; cur < 3; cur++){ if(good(i-1, last, i, cur)){ int n = doitDP(i + 1, cur); if(cur != 1) n++; now = Math.max(now, n); } } ret[i][last] = now; return ret[i][last]; } //----------------------------------------------------------- public static void main(String[] args) { new Main().run(); } public void debug(Object... arr){ System.out.println(Arrays.deepToString(arr)); } public void print1Int(int[] a){ for(int i = 0; i < a.length; i++) System.out.print(a[i] + " "); System.out.println(); } public void print2Int(int[][] a){ for(int i = 0; i < a.length; i++){ for(int j = 0; j < a[0].length; j++){ System.out.print(a[i][j] + " "); } System.out.println(); } } public void run() { try { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); tok = null; solve(); in.close(); out.close(); } catch (IOException e) { System.exit(0); } } public String nextToken() throws IOException { while (tok == null || !tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); } return tok.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(nextToken()); } public long nextLong() throws IOException { return Long.parseLong(nextToken()); } public double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } PrintWriter out; BufferedReader in; StringTokenizer tok; }
Java
["5\n1 2\n2 1\n5 10\n10 9\n19 1", "5\n1 2\n2 1\n5 10\n10 9\n20 1"]
1 second
["3", "4"]
NoteIn the first sample you can fell the trees like that: fell the 1-st tree to the left — now it occupies segment [ - 1;1] fell the 2-nd tree to the right — now it occupies segment [2;3] leave the 3-rd tree — it occupies point 5 leave the 4-th tree — it occupies point 10 fell the 5-th tree to the right — now it occupies segment [19;20] In the second sample you can also fell 4-th tree to the right, after that it will occupy segment [10;19].
Java 8
standard input
[ "dp", "greedy" ]
a850dd88a67a6295823e70e2c5c857c9
The first line contains integer n (1 ≤ n ≤ 105) — the number of trees. Next n lines contain pairs of integers xi, hi (1 ≤ xi, hi ≤ 109) — the coordinate and the height of the і-th tree. The pairs are given in the order of ascending xi. No two trees are located at the point with the same coordinate.
1,500
Print a single number — the maximum number of trees that you can cut down by the given rules.
standard output
PASSED
360fbc628f673002c4c222524bf40b6e
train_001.jsonl
1432053000
Little Susie listens to fairy tales before bed every day. Today's fairy tale was about wood cutters and the little girl immediately started imagining the choppers cutting wood. She imagined the situation that is described below.There are n trees located along the road at points with coordinates x1, x2, ..., xn. Each tree has its height hi. Woodcutters can cut down a tree and fell it to the left or to the right. After that it occupies one of the segments [xi - hi, xi] or [xi;xi + hi]. The tree that is not cut down occupies a single point with coordinate xi. Woodcutters can fell a tree if the segment to be occupied by the fallen tree doesn't contain any occupied point. The woodcutters want to process as many trees as possible, so Susie wonders, what is the maximum number of trees to fell.
256 megabytes
import java.util.Scanner; public class CF545_C_Woodcutters { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); int[] x = new int[n]; int[] h = new int[n]; for (int i = 0; i < n; i++) { x[i] = scanner.nextInt(); h[i] = scanner.nextInt(); } if (n == 1) { System.out.println("1"); return; } int ans = 1; int left = x[0]; for (int i = 1; i < n-1; i++) { if (x[i]-h[i] > left) { ans++; left = x[i]; } else if (x[i]+h[i] < x[i+1]) { ans++; left = x[i]+h[i]; } else { left = x[i]; } } System.out.println(++ans); } }
Java
["5\n1 2\n2 1\n5 10\n10 9\n19 1", "5\n1 2\n2 1\n5 10\n10 9\n20 1"]
1 second
["3", "4"]
NoteIn the first sample you can fell the trees like that: fell the 1-st tree to the left — now it occupies segment [ - 1;1] fell the 2-nd tree to the right — now it occupies segment [2;3] leave the 3-rd tree — it occupies point 5 leave the 4-th tree — it occupies point 10 fell the 5-th tree to the right — now it occupies segment [19;20] In the second sample you can also fell 4-th tree to the right, after that it will occupy segment [10;19].
Java 8
standard input
[ "dp", "greedy" ]
a850dd88a67a6295823e70e2c5c857c9
The first line contains integer n (1 ≤ n ≤ 105) — the number of trees. Next n lines contain pairs of integers xi, hi (1 ≤ xi, hi ≤ 109) — the coordinate and the height of the і-th tree. The pairs are given in the order of ascending xi. No two trees are located at the point with the same coordinate.
1,500
Print a single number — the maximum number of trees that you can cut down by the given rules.
standard output
PASSED
15d09f43c53ae25214cca9f98f6639b7
train_001.jsonl
1432053000
Little Susie listens to fairy tales before bed every day. Today's fairy tale was about wood cutters and the little girl immediately started imagining the choppers cutting wood. She imagined the situation that is described below.There are n trees located along the road at points with coordinates x1, x2, ..., xn. Each tree has its height hi. Woodcutters can cut down a tree and fell it to the left or to the right. After that it occupies one of the segments [xi - hi, xi] or [xi;xi + hi]. The tree that is not cut down occupies a single point with coordinate xi. Woodcutters can fell a tree if the segment to be occupied by the fallen tree doesn't contain any occupied point. The woodcutters want to process as many trees as possible, so Susie wonders, what is the maximum number of trees to fell.
256 megabytes
import java.util.* ; import java.io.BufferedReader ; import java.io.InputStreamReader ; public class WoodCutters { private static final boolean debug = true ; public static void main(String args[]) throws Exception { BufferedReader bro = new BufferedReader(new InputStreamReader(System.in)) ; int N = Integer.parseInt(bro.readLine()) ; int[] pos = new int[N] ; int[] h = new int[N] ; for(int i=0;i<N;i++) { String[] S = bro.readLine().split(" ") ; pos[i] = Integer.parseInt(S[0]) ; h[i] = Integer.parseInt(S[1]) ; } System.out.println(solve(pos,h)) ; } static int solve(int[] pos,int[] h) { int ways = 1,n = pos.length ; // boolean right = false ;//The first tree falls to it's left int last = pos[0] ; for(int i=1;i<n-1;i++) { if(pos[i]-h[i]>last) { ways++ ; last = pos[i] ; // System.out.println("Selected :("+pos[i]+ } else if(pos[i+1]-pos[i]>h[i]) { ways++ ; last = pos[i]+h[i] ; } else last = pos[i] ; } return n==1?ways:ways+1 ; } }
Java
["5\n1 2\n2 1\n5 10\n10 9\n19 1", "5\n1 2\n2 1\n5 10\n10 9\n20 1"]
1 second
["3", "4"]
NoteIn the first sample you can fell the trees like that: fell the 1-st tree to the left — now it occupies segment [ - 1;1] fell the 2-nd tree to the right — now it occupies segment [2;3] leave the 3-rd tree — it occupies point 5 leave the 4-th tree — it occupies point 10 fell the 5-th tree to the right — now it occupies segment [19;20] In the second sample you can also fell 4-th tree to the right, after that it will occupy segment [10;19].
Java 8
standard input
[ "dp", "greedy" ]
a850dd88a67a6295823e70e2c5c857c9
The first line contains integer n (1 ≤ n ≤ 105) — the number of trees. Next n lines contain pairs of integers xi, hi (1 ≤ xi, hi ≤ 109) — the coordinate and the height of the і-th tree. The pairs are given in the order of ascending xi. No two trees are located at the point with the same coordinate.
1,500
Print a single number — the maximum number of trees that you can cut down by the given rules.
standard output
PASSED
1a125ddafdb68bf941b231a9b653c0a9
train_001.jsonl
1432053000
Little Susie listens to fairy tales before bed every day. Today's fairy tale was about wood cutters and the little girl immediately started imagining the choppers cutting wood. She imagined the situation that is described below.There are n trees located along the road at points with coordinates x1, x2, ..., xn. Each tree has its height hi. Woodcutters can cut down a tree and fell it to the left or to the right. After that it occupies one of the segments [xi - hi, xi] or [xi;xi + hi]. The tree that is not cut down occupies a single point with coordinate xi. Woodcutters can fell a tree if the segment to be occupied by the fallen tree doesn't contain any occupied point. The woodcutters want to process as many trees as possible, so Susie wonders, what is the maximum number of trees to fell.
256 megabytes
import java.util.*; public class Test { public static void main(String args[]) { Scanner scn = new Scanner(System.in); int n = scn.nextInt(); int x[] = new int[n]; int h[] = new int[n]; for(int i=0;i<n;i++) { x[i] = scn.nextInt(); h[i] = scn.nextInt(); } if(n<3) System.out.println(n); else { int cnt=2,lf=1; for(int i=1;i<n-1;i++) { if((lf==1 && x[i]-h[i]>x[i-1]) || (lf==0 && x[i]-h[i]>x[i-1]+h[i-1])) { cnt++; lf=1; } else if(x[i]+h[i]<x[i+1]) { cnt++; lf=0; } else lf=1; } System.out.println(cnt); } } }
Java
["5\n1 2\n2 1\n5 10\n10 9\n19 1", "5\n1 2\n2 1\n5 10\n10 9\n20 1"]
1 second
["3", "4"]
NoteIn the first sample you can fell the trees like that: fell the 1-st tree to the left — now it occupies segment [ - 1;1] fell the 2-nd tree to the right — now it occupies segment [2;3] leave the 3-rd tree — it occupies point 5 leave the 4-th tree — it occupies point 10 fell the 5-th tree to the right — now it occupies segment [19;20] In the second sample you can also fell 4-th tree to the right, after that it will occupy segment [10;19].
Java 8
standard input
[ "dp", "greedy" ]
a850dd88a67a6295823e70e2c5c857c9
The first line contains integer n (1 ≤ n ≤ 105) — the number of trees. Next n lines contain pairs of integers xi, hi (1 ≤ xi, hi ≤ 109) — the coordinate and the height of the і-th tree. The pairs are given in the order of ascending xi. No two trees are located at the point with the same coordinate.
1,500
Print a single number — the maximum number of trees that you can cut down by the given rules.
standard output
PASSED
2743cd0c10aaa7ad86c8c31c2a46154e
train_001.jsonl
1432053000
Little Susie listens to fairy tales before bed every day. Today's fairy tale was about wood cutters and the little girl immediately started imagining the choppers cutting wood. She imagined the situation that is described below.There are n trees located along the road at points with coordinates x1, x2, ..., xn. Each tree has its height hi. Woodcutters can cut down a tree and fell it to the left or to the right. After that it occupies one of the segments [xi - hi, xi] or [xi;xi + hi]. The tree that is not cut down occupies a single point with coordinate xi. Woodcutters can fell a tree if the segment to be occupied by the fallen tree doesn't contain any occupied point. The woodcutters want to process as many trees as possible, so Susie wonders, what is the maximum number of trees to fell.
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 o_panda_o([email protected]) */ public class Code_545C_Woodcutters{ public static void main(String[] args){ InputStream inputStream=System.in; OutputStream outputStream=System.out; InputReader in=new InputReader(inputStream); OutputWriter out=new OutputWriter(outputStream); Task545C solver=new Task545C(); solver.solve(1,in,out); out.close(); } static class Task545C{ public void solve(int testNumber,InputReader in,OutputWriter out){ int n=in.nextInt(); int[] x=new int[n]; int[] h=new int[n]; for(int i=0;i<n;++i){ x[i]=in.nextInt(); h[i]=in.nextInt(); } int[] left=new int[n]; int[] right=new int[n]; left[0]=1; for(int i=1;i<n;++i){ left[i]=Math.max(left[i-1],right[i-1]);//The case when the tree could not be cut //The case where both the tree and the tree left adjacent to it could be cut if(x[i]-h[i]>x[i-1]+h[i-1]) left[i]=Math.max(left[i-1],right[i-1])+1; //The case when only it could be cut down to left if(x[i]-h[i]>x[i-1]) left[i]=Math.max(left[i],left[i-1]+1); //The case when the tree could be cut down to the right if(i==n-1 || (x[i]+h[i]<x[i+1])) right[i]=Math.max(left[i-1],right[i-1])+1; } //Print the best case out.print(Math.max(left[n-1],right[n-1])); } } 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 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 print(int i){ writer.print(i); } } }
Java
["5\n1 2\n2 1\n5 10\n10 9\n19 1", "5\n1 2\n2 1\n5 10\n10 9\n20 1"]
1 second
["3", "4"]
NoteIn the first sample you can fell the trees like that: fell the 1-st tree to the left — now it occupies segment [ - 1;1] fell the 2-nd tree to the right — now it occupies segment [2;3] leave the 3-rd tree — it occupies point 5 leave the 4-th tree — it occupies point 10 fell the 5-th tree to the right — now it occupies segment [19;20] In the second sample you can also fell 4-th tree to the right, after that it will occupy segment [10;19].
Java 8
standard input
[ "dp", "greedy" ]
a850dd88a67a6295823e70e2c5c857c9
The first line contains integer n (1 ≤ n ≤ 105) — the number of trees. Next n lines contain pairs of integers xi, hi (1 ≤ xi, hi ≤ 109) — the coordinate and the height of the і-th tree. The pairs are given in the order of ascending xi. No two trees are located at the point with the same coordinate.
1,500
Print a single number — the maximum number of trees that you can cut down by the given rules.
standard output
PASSED
eec4542c7c3eed1045770f0a027aae8a
train_001.jsonl
1432053000
Little Susie listens to fairy tales before bed every day. Today's fairy tale was about wood cutters and the little girl immediately started imagining the choppers cutting wood. She imagined the situation that is described below.There are n trees located along the road at points with coordinates x1, x2, ..., xn. Each tree has its height hi. Woodcutters can cut down a tree and fell it to the left or to the right. After that it occupies one of the segments [xi - hi, xi] or [xi;xi + hi]. The tree that is not cut down occupies a single point with coordinate xi. Woodcutters can fell a tree if the segment to be occupied by the fallen tree doesn't contain any occupied point. The woodcutters want to process as many trees as possible, so Susie wonders, what is the maximum number of trees to fell.
256 megabytes
import java.util.Scanner; public class Woodcutters { public static int n; public static int[] coordinates; public static int[] heights; public static int[][] memo = new int[100002][3]; static { for (int i = 0; i < 100002; i++) { for (int j = 0; j < 3; j++) { memo[i][j] = -1; } } } public static void main(String[] args) { Scanner s = new Scanner(System.in); n = s.nextInt(); coordinates = new int[n+2]; heights = new int[n+1]; for (int i = 1; i <= n; i++) { coordinates[i] = s.nextInt(); heights[i] = s.nextInt(); } coordinates[0] = Integer.MIN_VALUE; coordinates[coordinates.length - 1] = Integer.MAX_VALUE; System.out.println(maxCut(1, 0)); } public static int maxCut(int i, int fallDirection) { // base case if(i == n + 1) return 0; if (memo[i][fallDirection] != -1) return memo[i][fallDirection]; int maxCutTrees = Integer.MIN_VALUE; // we have three choices if(fallDirection == 0) { // no fall maxCutTrees = Math.max(maxCutTrees, maxCut(i+1, 0)); //fall left if(coordinates[i-1] < coordinates[i] - heights[i]) { maxCutTrees = Math.max(maxCutTrees, 1 + maxCut(i+1,1)); } // fall right if (coordinates[i] + heights[i] < coordinates[i+1]) { maxCutTrees = Math.max(maxCutTrees, 1 + maxCut(i+1, 2)); } } else if(fallDirection == 1) { // no fall maxCutTrees = Math.max(maxCutTrees, maxCut(i+1, 0)); //fall left if(coordinates[i-1] < coordinates[i] - heights[i]) { maxCutTrees = Math.max(maxCutTrees, 1 + maxCut(i+1,1)); } // fall right if (coordinates[i] + heights[i] < coordinates[i+1]) { maxCutTrees = Math.max(maxCutTrees, 1 + maxCut(i+1, 2)); } } else { // no fall maxCutTrees = Math.max(maxCutTrees, maxCut(i+1, 0)); //fall left if(coordinates[i-1] + heights[i-1] < coordinates[i] - heights[i]) { maxCutTrees = Math.max(maxCutTrees, 1 + maxCut(i+1,1)); } // fall right if (coordinates[i] + heights[i] < coordinates[i+1]) { maxCutTrees = Math.max(maxCutTrees, 1 + maxCut(i+1, 2)); } } return memo[i][fallDirection] = maxCutTrees; } }
Java
["5\n1 2\n2 1\n5 10\n10 9\n19 1", "5\n1 2\n2 1\n5 10\n10 9\n20 1"]
1 second
["3", "4"]
NoteIn the first sample you can fell the trees like that: fell the 1-st tree to the left — now it occupies segment [ - 1;1] fell the 2-nd tree to the right — now it occupies segment [2;3] leave the 3-rd tree — it occupies point 5 leave the 4-th tree — it occupies point 10 fell the 5-th tree to the right — now it occupies segment [19;20] In the second sample you can also fell 4-th tree to the right, after that it will occupy segment [10;19].
Java 8
standard input
[ "dp", "greedy" ]
a850dd88a67a6295823e70e2c5c857c9
The first line contains integer n (1 ≤ n ≤ 105) — the number of trees. Next n lines contain pairs of integers xi, hi (1 ≤ xi, hi ≤ 109) — the coordinate and the height of the і-th tree. The pairs are given in the order of ascending xi. No two trees are located at the point with the same coordinate.
1,500
Print a single number — the maximum number of trees that you can cut down by the given rules.
standard output
PASSED
b37dddd38a56035a5d73cdfc2ec74ce4
train_001.jsonl
1432053000
Little Susie listens to fairy tales before bed every day. Today's fairy tale was about wood cutters and the little girl immediately started imagining the choppers cutting wood. She imagined the situation that is described below.There are n trees located along the road at points with coordinates x1, x2, ..., xn. Each tree has its height hi. Woodcutters can cut down a tree and fell it to the left or to the right. After that it occupies one of the segments [xi - hi, xi] or [xi;xi + hi]. The tree that is not cut down occupies a single point with coordinate xi. Woodcutters can fell a tree if the segment to be occupied by the fallen tree doesn't contain any occupied point. The woodcutters want to process as many trees as possible, so Susie wonders, what is the maximum number of trees to fell.
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; public class Temp { public static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader() { reader = new BufferedReader(new InputStreamReader(System.in), 32768); tokenizer = null; } public InputReader(InputStream stream) { 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 char nextChar() { return next().charAt(0); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public int[] nextIntArr(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = this.nextInt(); } return arr; } public Integer[] nextIntegerArr(int n) { Integer[] arr = new Integer[n]; for (int i = 0; i < n; i++) { arr[i] = new Integer(this.nextInt()); } return arr; } public int[][] next2DIntArr(int n, int m) { int[][] arr = new int[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { arr[i][j] = this.nextInt(); } } return arr; } public int[] nextSortedIntArr(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = this.nextInt(); } Arrays.sort(arr); return arr; } public long[] nextLongArr(int n) { long[] arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = this.nextLong(); } return arr; } public char[] nextCharArr(int n) { char[] arr = new char[n]; for (int i = 0; i < n; i++) { arr[i] = this.nextChar(); } return arr; } } public static InputReader scn = new InputReader(); public static PrintWriter out = new PrintWriter(System.out); public static void main(String[] args) { // InputStream inputStream = System.in; // Useful when taking input other than // console eg file handling // check ctor of inputReader int n = scn.nextInt(); int[] arr = new int[n], hgt = new int[n]; for (int i = 0; i < n; i++) { arr[i] = scn.nextInt(); hgt[i] = scn.nextInt(); } if(n == 1) { System.out.println(1); return; } int ans = 0; for (int i = 1; i < n - 1; i++) { if (arr[i] - arr[i - 1] > hgt[i]) { ans++; } else if (arr[i + 1] - arr[i] > hgt[i]) { ans++; arr[i] += hgt[i]; } } System.out.println(ans + 2); } }
Java
["5\n1 2\n2 1\n5 10\n10 9\n19 1", "5\n1 2\n2 1\n5 10\n10 9\n20 1"]
1 second
["3", "4"]
NoteIn the first sample you can fell the trees like that: fell the 1-st tree to the left — now it occupies segment [ - 1;1] fell the 2-nd tree to the right — now it occupies segment [2;3] leave the 3-rd tree — it occupies point 5 leave the 4-th tree — it occupies point 10 fell the 5-th tree to the right — now it occupies segment [19;20] In the second sample you can also fell 4-th tree to the right, after that it will occupy segment [10;19].
Java 8
standard input
[ "dp", "greedy" ]
a850dd88a67a6295823e70e2c5c857c9
The first line contains integer n (1 ≤ n ≤ 105) — the number of trees. Next n lines contain pairs of integers xi, hi (1 ≤ xi, hi ≤ 109) — the coordinate and the height of the і-th tree. The pairs are given in the order of ascending xi. No two trees are located at the point with the same coordinate.
1,500
Print a single number — the maximum number of trees that you can cut down by the given rules.
standard output
PASSED
e33e1e1932fca622753a60d0b4cfd679
train_001.jsonl
1432053000
Little Susie listens to fairy tales before bed every day. Today's fairy tale was about wood cutters and the little girl immediately started imagining the choppers cutting wood. She imagined the situation that is described below.There are n trees located along the road at points with coordinates x1, x2, ..., xn. Each tree has its height hi. Woodcutters can cut down a tree and fell it to the left or to the right. After that it occupies one of the segments [xi - hi, xi] or [xi;xi + hi]. The tree that is not cut down occupies a single point with coordinate xi. Woodcutters can fell a tree if the segment to be occupied by the fallen tree doesn't contain any occupied point. The woodcutters want to process as many trees as possible, so Susie wonders, what is the maximum number of trees to fell.
256 megabytes
import java.util.Scanner; /** * * @author ADNAN */ public class Woodcutters { public static int dp[]; public static void main(String args[]) { int x[]; int h[]; int n; Scanner scanner = new Scanner(System.in); n = scanner.nextInt(); scanner.nextLine(); x = new int[n]; h = new int[n]; dp = new int[n]; while (n != 0) { x[x.length - n] = scanner.nextInt(); h[x.length - n] = scanner.nextInt(); scanner.nextLine(); n--; } int count = x.length == 1? 1: 2; for(int i = 1 ;i< x.length - 1;i++ ){ if(x[i] - h[i] > x[i-1] ) count++; else if(x[i] + h[i] < x[i +1]){ count++; x[i] = x[i] +h[i]; } } System.out.println(count); } }
Java
["5\n1 2\n2 1\n5 10\n10 9\n19 1", "5\n1 2\n2 1\n5 10\n10 9\n20 1"]
1 second
["3", "4"]
NoteIn the first sample you can fell the trees like that: fell the 1-st tree to the left — now it occupies segment [ - 1;1] fell the 2-nd tree to the right — now it occupies segment [2;3] leave the 3-rd tree — it occupies point 5 leave the 4-th tree — it occupies point 10 fell the 5-th tree to the right — now it occupies segment [19;20] In the second sample you can also fell 4-th tree to the right, after that it will occupy segment [10;19].
Java 8
standard input
[ "dp", "greedy" ]
a850dd88a67a6295823e70e2c5c857c9
The first line contains integer n (1 ≤ n ≤ 105) — the number of trees. Next n lines contain pairs of integers xi, hi (1 ≤ xi, hi ≤ 109) — the coordinate and the height of the і-th tree. The pairs are given in the order of ascending xi. No two trees are located at the point with the same coordinate.
1,500
Print a single number — the maximum number of trees that you can cut down by the given rules.
standard output
PASSED
56fad37e9926d4cfdfcf670ee608c301
train_001.jsonl
1432053000
Little Susie listens to fairy tales before bed every day. Today's fairy tale was about wood cutters and the little girl immediately started imagining the choppers cutting wood. She imagined the situation that is described below.There are n trees located along the road at points with coordinates x1, x2, ..., xn. Each tree has its height hi. Woodcutters can cut down a tree and fell it to the left or to the right. After that it occupies one of the segments [xi - hi, xi] or [xi;xi + hi]. The tree that is not cut down occupies a single point with coordinate xi. Woodcutters can fell a tree if the segment to be occupied by the fallen tree doesn't contain any occupied point. The woodcutters want to process as many trees as possible, so Susie wonders, what is the maximum number of trees to fell.
256 megabytes
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); if (n == 1) { System.out.println(1); return; } int[] x = new int[n]; int[] h = new int[n]; for (int i = 0; i < n; i++) { x[i] = sc.nextInt(); h[i] = sc.nextInt(); } int k = 2; int rightest = x[0]; for (int i = 1; i < n - 1; i++) { if (x[i] - h[i] > rightest) { k++; rightest = x[i]; } else if (x[i] + h[i] < x[i + 1]) { k++; rightest = x[i] + h[i]; } else { rightest = x[i]; } } System.out.println(k); } }
Java
["5\n1 2\n2 1\n5 10\n10 9\n19 1", "5\n1 2\n2 1\n5 10\n10 9\n20 1"]
1 second
["3", "4"]
NoteIn the first sample you can fell the trees like that: fell the 1-st tree to the left — now it occupies segment [ - 1;1] fell the 2-nd tree to the right — now it occupies segment [2;3] leave the 3-rd tree — it occupies point 5 leave the 4-th tree — it occupies point 10 fell the 5-th tree to the right — now it occupies segment [19;20] In the second sample you can also fell 4-th tree to the right, after that it will occupy segment [10;19].
Java 8
standard input
[ "dp", "greedy" ]
a850dd88a67a6295823e70e2c5c857c9
The first line contains integer n (1 ≤ n ≤ 105) — the number of trees. Next n lines contain pairs of integers xi, hi (1 ≤ xi, hi ≤ 109) — the coordinate and the height of the і-th tree. The pairs are given in the order of ascending xi. No two trees are located at the point with the same coordinate.
1,500
Print a single number — the maximum number of trees that you can cut down by the given rules.
standard output
PASSED
9ddb3cdf22a3499ddfbee5292fc310b9
train_001.jsonl
1432053000
Little Susie listens to fairy tales before bed every day. Today's fairy tale was about wood cutters and the little girl immediately started imagining the choppers cutting wood. She imagined the situation that is described below.There are n trees located along the road at points with coordinates x1, x2, ..., xn. Each tree has its height hi. Woodcutters can cut down a tree and fell it to the left or to the right. After that it occupies one of the segments [xi - hi, xi] or [xi;xi + hi]. The tree that is not cut down occupies a single point with coordinate xi. Woodcutters can fell a tree if the segment to be occupied by the fallen tree doesn't contain any occupied point. The woodcutters want to process as many trees as possible, so Susie wonders, what is the maximum number of trees to fell.
256 megabytes
import java.util.*; public class WoodCutters { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int tree = sc.nextInt(); int[] X = new int[tree]; int[] H = new int[tree]; for (int i = 0; i < tree; i++) { int first = sc.nextInt(); int second = sc.nextInt(); X[i] = first; H[i] = second; } H[0] = H[tree-1] = 0; for (int i = 1; i < X.length - 1; i++) { if (H[i] < X[i] - X[i - 1]) { H[i] = 0; } else if (H[i] < X[i + 1] - X[i]) { X[i] += H[i]; H[i] = 0; } } int sum = 0; for (int i = 0; i < X.length; i++) { if (H[i] == 0) { sum++; } } System.out.println(sum); sc.close(); } }
Java
["5\n1 2\n2 1\n5 10\n10 9\n19 1", "5\n1 2\n2 1\n5 10\n10 9\n20 1"]
1 second
["3", "4"]
NoteIn the first sample you can fell the trees like that: fell the 1-st tree to the left — now it occupies segment [ - 1;1] fell the 2-nd tree to the right — now it occupies segment [2;3] leave the 3-rd tree — it occupies point 5 leave the 4-th tree — it occupies point 10 fell the 5-th tree to the right — now it occupies segment [19;20] In the second sample you can also fell 4-th tree to the right, after that it will occupy segment [10;19].
Java 8
standard input
[ "dp", "greedy" ]
a850dd88a67a6295823e70e2c5c857c9
The first line contains integer n (1 ≤ n ≤ 105) — the number of trees. Next n lines contain pairs of integers xi, hi (1 ≤ xi, hi ≤ 109) — the coordinate and the height of the і-th tree. The pairs are given in the order of ascending xi. No two trees are located at the point with the same coordinate.
1,500
Print a single number — the maximum number of trees that you can cut down by the given rules.
standard output
PASSED
56230c20ba67a29ad207f3c0ab304b92
train_001.jsonl
1432053000
Little Susie listens to fairy tales before bed every day. Today's fairy tale was about wood cutters and the little girl immediately started imagining the choppers cutting wood. She imagined the situation that is described below.There are n trees located along the road at points with coordinates x1, x2, ..., xn. Each tree has its height hi. Woodcutters can cut down a tree and fell it to the left or to the right. After that it occupies one of the segments [xi - hi, xi] or [xi;xi + hi]. The tree that is not cut down occupies a single point with coordinate xi. Woodcutters can fell a tree if the segment to be occupied by the fallen tree doesn't contain any occupied point. The woodcutters want to process as many trees as possible, so Susie wonders, what is the maximum number of trees to fell.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ 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); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); if (n <= 2) { out.println(n); return; } long[] x = new long[n]; long[] h = new long[n]; for (int i = 0; i < n; i++) { x[i] = in.nextInt(); h[i] = in.nextInt(); } long delta = 0; int cnt = 2; for (int i = 1; i < n - 1; i++) { if (x[i] - x[i - 1] - delta > h[i]) { delta = 0; cnt++; } else if (x[i + 1] - x[i] > h[i]) { delta = h[i]; cnt++; } else { delta = 0; } } out.println(cnt); } } static class InputReader { final InputStream is; final byte[] buffer = new byte[1024]; int curCharIdx; int nChars; public InputReader(InputStream is) { this.is = is; } public int read() { if (curCharIdx >= nChars) { try { curCharIdx = 0; nChars = is.read(buffer); if (nChars == -1) return -1; } catch (IOException e) { throw new RuntimeException(e); } } return buffer[curCharIdx++]; } public int nextInt() { int sign = 1; int c = skipDelims(); if (c == '-') { sign = -1; c = read(); if (isDelim(c)) throw new RuntimeException("Incorrect format"); } int val = 0; while (c != -1 && !isDelim(c)) { if (!isDigit(c)) throw new RuntimeException("Incorrect format"); val = 10 * val + (c - '0'); c = read(); } return val * sign; } private final int skipDelims() { int c = read(); while (isDelim(c)) { c = read(); } return c; } private static boolean isDelim(final int c) { return c == ' ' || c == '\n' || c == '\t' || c == '\r' || c == '\f'; } private static boolean isDigit(final int c) { return '0' <= c && c <= '9'; } } }
Java
["5\n1 2\n2 1\n5 10\n10 9\n19 1", "5\n1 2\n2 1\n5 10\n10 9\n20 1"]
1 second
["3", "4"]
NoteIn the first sample you can fell the trees like that: fell the 1-st tree to the left — now it occupies segment [ - 1;1] fell the 2-nd tree to the right — now it occupies segment [2;3] leave the 3-rd tree — it occupies point 5 leave the 4-th tree — it occupies point 10 fell the 5-th tree to the right — now it occupies segment [19;20] In the second sample you can also fell 4-th tree to the right, after that it will occupy segment [10;19].
Java 8
standard input
[ "dp", "greedy" ]
a850dd88a67a6295823e70e2c5c857c9
The first line contains integer n (1 ≤ n ≤ 105) — the number of trees. Next n lines contain pairs of integers xi, hi (1 ≤ xi, hi ≤ 109) — the coordinate and the height of the і-th tree. The pairs are given in the order of ascending xi. No two trees are located at the point with the same coordinate.
1,500
Print a single number — the maximum number of trees that you can cut down by the given rules.
standard output
PASSED
334cccdb9918d8ef48727ca77e6a57e0
train_001.jsonl
1432053000
Little Susie listens to fairy tales before bed every day. Today's fairy tale was about wood cutters and the little girl immediately started imagining the choppers cutting wood. She imagined the situation that is described below.There are n trees located along the road at points with coordinates x1, x2, ..., xn. Each tree has its height hi. Woodcutters can cut down a tree and fell it to the left or to the right. After that it occupies one of the segments [xi - hi, xi] or [xi;xi + hi]. The tree that is not cut down occupies a single point with coordinate xi. Woodcutters can fell a tree if the segment to be occupied by the fallen tree doesn't contain any occupied point. The woodcutters want to process as many trees as possible, so Susie wonders, what is the maximum number of trees to fell.
256 megabytes
import java.util.ArrayList; import java.util.List; import java.util.Scanner; import java.util.Stack; /* tutorial solution much better*/ public class Main { public static int dirr[][] = {{1,0},{0,1},{0,-1},{-1,0}}; public static boolean possible; public static void main(String[] args) { // write your code here // q1365D(); // q1354D(); // q1363C(); q545C(); } public static void q545C(){ Scanner sc = new Scanner(System.in); List<Corrd> arr = new ArrayList<>(); int n = sc.nextInt(); int ans=n-2<=0?n:2; for(int j=0;j<n;j++){ arr.add(new Corrd(sc.nextInt(),sc.nextInt())); } int closest = arr.get(0).x; for(int j=1;j<arr.size()-1;j++){ Corrd tree = arr.get(j); int farthest = arr.get(j+1).x; if(closest<tree.x-tree.y){ ans++; closest=tree.x; } else if(farthest>tree.x+tree.y){ ans++; closest=tree.x+tree.y; } else{ closest= tree.x; } } System.out.println(ans); } public static void q1363C(){ Scanner sc = new Scanner(System.in); int t = sc.nextInt(); for(int i=0;i<t;i++){ int deg =0; int n = sc.nextInt(); int x = sc.nextInt(); for(int j=0;j<n-1;j++){ int p = sc.nextInt(); int q = sc.nextInt(); if(p==x || q==x){ deg++; } } if(deg<=1){ System.out.println("Ayush"); } else{ if(n%2==0){ System.out.println("Ayush"); } else{ System.out.println("Ashish"); } } } } public static void q1354D(){ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int q = sc.nextInt(); int[] cnt= new int[n+1]; for(int i=0;i<n;i++){ cnt[sc.nextInt()]++; } for(int i=0;i<q;i++){ int k = sc.nextInt(); if(k>0){ cnt[k]++; } else{ k=k*(-1); } } } public static void q1365D(){ Scanner sc = new Scanner(System.in); int t = sc.nextInt(); for(int i=0;i<t;i++){ possible = true; int n = sc.nextInt(); int m = sc.nextInt(); Integer[][] graph = new Integer[n+1][m+1]; Corrd[][] corrds = new Corrd[n+1][m+1]; for(int j=0;j<n;j++){ String str = sc.next(); for(int k=0;k<m;k++){ graph[j][k] = (int)str.charAt(k); // System.out.println(graph[j][k]); corrds[j][k] = new Corrd(j,k); } } dfs(n-1,m-1,n,m,graph,corrds); if(!possible){ System.out.println("NO"); continue; } dfs2(n-1,m-1,n,m,graph,corrds); for(int j=0;j<n;j++){ for(int k=0;k<m;k++){ // System.out.print((char)((int)graph[j][k])); if(graph[j][k]=='G'){ // System.out.print(corrds[j][k].color); if(corrds[j][k].color<2){ // System.out.print("Mee"+corrds[j][k].color); possible = false; break; } } } // System.out.println(); } System.out.println(possible?"YES":"NO"); } } public static void dfs(int x,int y,int maxx,int maxy,Integer[][] graph,Corrd[][] corrds) { Stack<Corrd> st = new Stack<Corrd>(); if (graph[x][y] == '#') { return; } st.push(corrds[x][y]); corrds[x][y].color++; while (!st.empty()) { Corrd p = st.pop(); // System.out.println(p.x + " " + p.y); for (int i = 0; i < 4; i++) { int nx = p.x + dirr[i][0]; int ny = p.y + dirr[i][1]; if (nx >= 0 && nx < maxx && ny >= 0 && ny < maxy && corrds[nx][ny].color == 0) { // System.out.println("x" + nx + " " + ny); if (!(graph[nx][ny] == '#')) { if (graph[nx][ny] == 'B' && (graph[p.x][p.y] == '.')) { graph[p.x][p.y] = (int) '#'; break; } else { if (graph[nx][ny] == 'B' && graph[p.x][p.y] == 'G') { possible = false; break; } else { corrds[nx][ny].color++; st.push(corrds[nx][ny]); } } } } } } } public static void dfs2(int x,int y,int maxx,int maxy,Integer[][] graph,Corrd[][] corrds){ Stack<Corrd> st = new Stack<Corrd>(); if(graph[x][y]=='#'){ return; } st.push(corrds[x][y]); corrds[x][y].color++; while(!st.empty()){ Corrd p = st.pop(); // System.out.println(p.x+" "+p.y); for(int i=0;i<4;i++){ int nx = p.x+dirr[i][0]; int ny = p.y+dirr[i][1]; if(nx>=0 && nx<maxx && ny>=0 && ny<maxy && corrds[nx][ny].color==1){ if(!(graph[nx][ny]=='#')){ corrds[nx][ny].color++; st.push(corrds[nx][ny]); } } } } } public static class Corrd{ int x; int y; int color; Corrd(int x,int y){ this.x = x; this.y = y; this.color =0; } } }
Java
["5\n1 2\n2 1\n5 10\n10 9\n19 1", "5\n1 2\n2 1\n5 10\n10 9\n20 1"]
1 second
["3", "4"]
NoteIn the first sample you can fell the trees like that: fell the 1-st tree to the left — now it occupies segment [ - 1;1] fell the 2-nd tree to the right — now it occupies segment [2;3] leave the 3-rd tree — it occupies point 5 leave the 4-th tree — it occupies point 10 fell the 5-th tree to the right — now it occupies segment [19;20] In the second sample you can also fell 4-th tree to the right, after that it will occupy segment [10;19].
Java 8
standard input
[ "dp", "greedy" ]
a850dd88a67a6295823e70e2c5c857c9
The first line contains integer n (1 ≤ n ≤ 105) — the number of trees. Next n lines contain pairs of integers xi, hi (1 ≤ xi, hi ≤ 109) — the coordinate and the height of the і-th tree. The pairs are given in the order of ascending xi. No two trees are located at the point with the same coordinate.
1,500
Print a single number — the maximum number of trees that you can cut down by the given rules.
standard output
PASSED
0b9cd9c64b9149fe55e57a8ad0d6d470
train_001.jsonl
1432053000
Little Susie listens to fairy tales before bed every day. Today's fairy tale was about wood cutters and the little girl immediately started imagining the choppers cutting wood. She imagined the situation that is described below.There are n trees located along the road at points with coordinates x1, x2, ..., xn. Each tree has its height hi. Woodcutters can cut down a tree and fell it to the left or to the right. After that it occupies one of the segments [xi - hi, xi] or [xi;xi + hi]. The tree that is not cut down occupies a single point with coordinate xi. Woodcutters can fell a tree if the segment to be occupied by the fallen tree doesn't contain any occupied point. The woodcutters want to process as many trees as possible, so Susie wonders, what is the maximum number of trees to fell.
256 megabytes
import java.util.Scanner; public class Woodcutters { public static void main(String[] args) { // TODO Auto-generated method stub Scanner scan = new Scanner(System.in); // number of trees int num = scan.nextInt(); int [] xi = new int [num]; int [] height = new int [num]; for(int i = 0; i < num; i++){ xi[i] = scan.nextInt(); height[i] = scan.nextInt(); } long counter = 0; int pointer = xi[0]; if(num < 2){ counter = num; } else { counter = 2; } for(int i = 1; i < num - 1; i++){ if(pointer < (xi[i] - height[i]) || (xi[i] + height[i]) < xi[i + 1]){ counter++; } if((xi[i] + height[i]) >= xi[i + 1] || pointer < (xi[i] - height[i])){ pointer = xi[i]; } else{ pointer = xi[i] + height[i]; } } System.out.println(counter); } }
Java
["5\n1 2\n2 1\n5 10\n10 9\n19 1", "5\n1 2\n2 1\n5 10\n10 9\n20 1"]
1 second
["3", "4"]
NoteIn the first sample you can fell the trees like that: fell the 1-st tree to the left — now it occupies segment [ - 1;1] fell the 2-nd tree to the right — now it occupies segment [2;3] leave the 3-rd tree — it occupies point 5 leave the 4-th tree — it occupies point 10 fell the 5-th tree to the right — now it occupies segment [19;20] In the second sample you can also fell 4-th tree to the right, after that it will occupy segment [10;19].
Java 8
standard input
[ "dp", "greedy" ]
a850dd88a67a6295823e70e2c5c857c9
The first line contains integer n (1 ≤ n ≤ 105) — the number of trees. Next n lines contain pairs of integers xi, hi (1 ≤ xi, hi ≤ 109) — the coordinate and the height of the і-th tree. The pairs are given in the order of ascending xi. No two trees are located at the point with the same coordinate.
1,500
Print a single number — the maximum number of trees that you can cut down by the given rules.
standard output
PASSED
3cada42aec438ff583acd5e677035715
train_001.jsonl
1432053000
Little Susie listens to fairy tales before bed every day. Today's fairy tale was about wood cutters and the little girl immediately started imagining the choppers cutting wood. She imagined the situation that is described below.There are n trees located along the road at points with coordinates x1, x2, ..., xn. Each tree has its height hi. Woodcutters can cut down a tree and fell it to the left or to the right. After that it occupies one of the segments [xi - hi, xi] or [xi;xi + hi]. The tree that is not cut down occupies a single point with coordinate xi. Woodcutters can fell a tree if the segment to be occupied by the fallen tree doesn't contain any occupied point. The woodcutters want to process as many trees as possible, so Susie wonders, what is the maximum number of trees to fell.
256 megabytes
import java.io.*; import java.util.*; public class Solution { public void run() throws IOException{ Scanner s = new Scanner(System.in); int n = s.nextInt(); int [] x = new int[n]; int [] h = new int[n]; int [] rocc = new int[n]; int [][] dp = new int[n][3]; for(int i=0;i<n;i++){ x[i] = s.nextInt();h[i] = s.nextInt(); Arrays.fill(dp[i],0); } Arrays.fill(rocc,Integer.MAX_VALUE); if(n==1 || n==2){ System.out.println(n); return; } int res = 2; if(x[1] - h[1] > x[0]){ dp[1][0] = 1; } if(x[1]+h[1] < x[2]){ dp[1][1] = 1; rocc[1] = x[1]+h[1]; } dp[1][2] = 0; //System.out.println(dp[1][1]); for(int i=2;i<n-1;i++){ for(int j=0;j<3;j++){ for(int k=0;k<3;k++){ if(j==0){ if(k==1){ if(rocc[i-1]!=Integer.MAX_VALUE && rocc[i-1]<x[i]-h[i]){ dp[i][j] = Math.max(dp[i][j],dp[i-1][k]+1); } } else{ if(x[i-1]<x[i]-h[i]){ dp[i][j] = Math.max(dp[i][j],dp[i-1][k]+1); } } } else if(j==1 && (x[i]+h[i]<x[i+1])){ dp[i][j] = Math.max(dp[i][j],dp[i-1][k]+1); rocc[i] = x[i]+h[i]; } else{ dp[i][j] = Math.max(dp[i][j],dp[i-1][k]); } } } } int max1 = Math.max(dp[n-2][0],dp[n-2][1]); max1 = Math.max(max1,dp[n-2][2]); for(int i=0;i<n;i++) Arrays.fill(dp[i],0); Arrays.fill(rocc,Integer.MAX_VALUE); if(x[n-2] - h[n-2] > x[n-3]){ dp[n-2][0] = 1; rocc[n-2] = x[n-2]-h[n-2]; } if(x[n-2]+h[n-2] < x[n-1]){ dp[n-2][1] = 1; } // System.out.println(dp[n-2][0] + " " + dp[n-2][1]); for(int i=n-3;i>0;i--){ for(int j=0;j<3;j++){ for(int k=0;k<3;k++){ if(j==1){ if(k==0){ if(rocc[i+1]!=Integer.MAX_VALUE && rocc[i+1]>x[i]+h[i]){ dp[i][j] = Math.max(dp[i][j],dp[i+1][k]+1); } } else{ if(x[i+1]>x[i]+h[i]){ dp[i][j] = Math.max(dp[i][j],dp[i+1][k]+1); } } } else if(j==0 && (x[i]-h[i]>x[i-1])){ dp[i][j] = Math.max(dp[i][j],dp[i+1][k]+1); rocc[i] = x[i]-h[i]; } else{ dp[i][j] = Math.max(dp[i][j],dp[i+1][k]); } } } } // System.out.println(dp[3][0] + " " + dp[3][1] + " " + dp[3][2]); //System.out.println(dp[2][0] + " " + dp[2][1] + " " + dp[2][2]); int max2 = Math.max(dp[1][0],dp[1][1]); max2 = Math.max(max2,dp[1][2]); int max = Math.max(max1,max2); System.out.println(res+max); } public static void main(String [] args) throws IOException{ new Solution().run(); } }
Java
["5\n1 2\n2 1\n5 10\n10 9\n19 1", "5\n1 2\n2 1\n5 10\n10 9\n20 1"]
1 second
["3", "4"]
NoteIn the first sample you can fell the trees like that: fell the 1-st tree to the left — now it occupies segment [ - 1;1] fell the 2-nd tree to the right — now it occupies segment [2;3] leave the 3-rd tree — it occupies point 5 leave the 4-th tree — it occupies point 10 fell the 5-th tree to the right — now it occupies segment [19;20] In the second sample you can also fell 4-th tree to the right, after that it will occupy segment [10;19].
Java 8
standard input
[ "dp", "greedy" ]
a850dd88a67a6295823e70e2c5c857c9
The first line contains integer n (1 ≤ n ≤ 105) — the number of trees. Next n lines contain pairs of integers xi, hi (1 ≤ xi, hi ≤ 109) — the coordinate and the height of the і-th tree. The pairs are given in the order of ascending xi. No two trees are located at the point with the same coordinate.
1,500
Print a single number — the maximum number of trees that you can cut down by the given rules.
standard output
PASSED
7b2ac7cdc6b64ae4624fb13e9c4a8cb1
train_001.jsonl
1432053000
Little Susie listens to fairy tales before bed every day. Today's fairy tale was about wood cutters and the little girl immediately started imagining the choppers cutting wood. She imagined the situation that is described below.There are n trees located along the road at points with coordinates x1, x2, ..., xn. Each tree has its height hi. Woodcutters can cut down a tree and fell it to the left or to the right. After that it occupies one of the segments [xi - hi, xi] or [xi;xi + hi]. The tree that is not cut down occupies a single point with coordinate xi. Woodcutters can fell a tree if the segment to be occupied by the fallen tree doesn't contain any occupied point. The woodcutters want to process as many trees as possible, so Susie wonders, what is the maximum number of trees to fell.
256 megabytes
/* `\-. ` \ `. ` \ \ | __.._ | \. S O N - G O K U ..---~~ ~ . | Y ~-. `| | `. `~~--. \ ~. \ \__. . -- - . .-~~~~~ , , ~~~~~~---...._ .-~___ ,'/ ,'/ ,'\ __...---~~~ ~-. /._\_( ,(/_. 7,-. ~~---...__ _...>- P""6=`_/"6"~ 6) ___...--~~~ ~~--._ \`--') `---' 9' _..--~~~ ~\ ~~/_ ~~~ /`-.--~~ `. --- .' \_ `. " _.-' | ~-.,-------._ ..._../~~ ./ .-' .-~~~-. ,--~~~ ,'...\` _./.----~~.'/ /' `- _.-( |\ `/~ _____..-' / / _.-~~`. / | /. ^---~~~~ ' / / ,' ~. \ ( / ( . _ ' /' / ,/ \ ) (`. | `\ - - - - ~ /' ( / . | \.\| \ /' \ |`. / /.'\\ `\ /' ~-\ . /\ /, ( `\ /' `.___..- \ | | \ `\_/' // \. | | | | _Seal_ /' | | | */ import java.io.*; import java.util.*; public class C303C { static PrintWriter out = new PrintWriter((System.out)); public static void main(String args[]) throws IOException { Reader sc = new Reader(); int n=sc.nextInt(); long pos[]=new long[n]; long height[]=new long[n]; for(int x=0;x<n;x++) { pos[x]=sc.nextLong(); height[x]=sc.nextLong(); } int ans=n>=2?2:1; long d=pos[0]; for(int x=1;x<n-1;x++) { if(pos[x]-height[x]>d) { d=pos[x]; ans++; } else { if(pos[x]+height[x]<pos[x+1]) { ans++; d=pos[x]+height[x]; } } d=Math.max(d,pos[x]); } out.println(ans); out.close(); } static class Reader { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); public String next() { while (!st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { e.printStackTrace(); } } return st.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 br.readLine(); } catch (Exception e) { e.printStackTrace(); } return null; } public boolean hasNext() { String next = null; try { next = br.readLine(); } catch (Exception e) { } if (next == null) { return false; } st = new StringTokenizer(next); return true; } } }
Java
["5\n1 2\n2 1\n5 10\n10 9\n19 1", "5\n1 2\n2 1\n5 10\n10 9\n20 1"]
1 second
["3", "4"]
NoteIn the first sample you can fell the trees like that: fell the 1-st tree to the left — now it occupies segment [ - 1;1] fell the 2-nd tree to the right — now it occupies segment [2;3] leave the 3-rd tree — it occupies point 5 leave the 4-th tree — it occupies point 10 fell the 5-th tree to the right — now it occupies segment [19;20] In the second sample you can also fell 4-th tree to the right, after that it will occupy segment [10;19].
Java 8
standard input
[ "dp", "greedy" ]
a850dd88a67a6295823e70e2c5c857c9
The first line contains integer n (1 ≤ n ≤ 105) — the number of trees. Next n lines contain pairs of integers xi, hi (1 ≤ xi, hi ≤ 109) — the coordinate and the height of the і-th tree. The pairs are given in the order of ascending xi. No two trees are located at the point with the same coordinate.
1,500
Print a single number — the maximum number of trees that you can cut down by the given rules.
standard output
PASSED
f361f4220d43536418876bc756a2f911
train_001.jsonl
1432053000
Little Susie listens to fairy tales before bed every day. Today's fairy tale was about wood cutters and the little girl immediately started imagining the choppers cutting wood. She imagined the situation that is described below.There are n trees located along the road at points with coordinates x1, x2, ..., xn. Each tree has its height hi. Woodcutters can cut down a tree and fell it to the left or to the right. After that it occupies one of the segments [xi - hi, xi] or [xi;xi + hi]. The tree that is not cut down occupies a single point with coordinate xi. Woodcutters can fell a tree if the segment to be occupied by the fallen tree doesn't contain any occupied point. The woodcutters want to process as many trees as possible, so Susie wonders, what is the maximum number of trees to fell.
256 megabytes
/* `\-. ` \ `. ` \ \ | __.._ | \. S O N - G O K U ..---~~ ~ . | Y ~-. `| | `. `~~--. \ ~. \ \__. . -- - . .-~~~~~ , , ~~~~~~---...._ .-~___ ,'/ ,'/ ,'\ __...---~~~ ~-. /._\_( ,(/_. 7,-. ~~---...__ _...>- P""6=`_/"6"~ 6) ___...--~~~ ~~--._ \`--') `---' 9' _..--~~~ ~\ ~~/_ ~~~ /`-.--~~ `. --- .' \_ `. " _.-' | ~-.,-------._ ..._../~~ ./ .-' .-~~~-. ,--~~~ ,'...\` _./.----~~.'/ /' `- _.-( |\ `/~ _____..-' / / _.-~~`. / | /. ^---~~~~ ' / / ,' ~. \ ( / ( . _ ' /' / ,/ \ ) (`. | `\ - - - - ~ /' ( / . | \.\| \ /' \ |`. / /.'\\ `\ /' ~-\ . /\ /, ( `\ /' `.___..- \ | | \ `\_/' // \. | | | | _Seal_ /' | | | */ import java.io.*; import java.util.*; public class C303C { static PrintWriter out = new PrintWriter((System.out)); public static void main(String args[]) throws IOException { Reader sc = new Reader(); int n=sc.nextInt(); long pos[]=new long[n]; long height[]=new long[n]; for(int x=0;x<n;x++) { pos[x]=sc.nextLong(); height[x]=sc.nextLong(); } int ans=n>=2?2:1; long d=pos[0]; for(int x=1;x<n-1;x++) { if(pos[x]-height[x]>d) { d=pos[x]; ans++; } else { if(pos[x]+height[x]<pos[x+1]) { ans++; d=pos[x]+height[x]; } } d=Math.max(d,pos[x]); } out.println(ans); out.close(); } static class Reader { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); public String next() { while (!st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { e.printStackTrace(); } } return st.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 br.readLine(); } catch (Exception e) { e.printStackTrace(); } return null; } public boolean hasNext() { String next = null; try { next = br.readLine(); } catch (Exception e) { } if (next == null) { return false; } st = new StringTokenizer(next); return true; } } }
Java
["5\n1 2\n2 1\n5 10\n10 9\n19 1", "5\n1 2\n2 1\n5 10\n10 9\n20 1"]
1 second
["3", "4"]
NoteIn the first sample you can fell the trees like that: fell the 1-st tree to the left — now it occupies segment [ - 1;1] fell the 2-nd tree to the right — now it occupies segment [2;3] leave the 3-rd tree — it occupies point 5 leave the 4-th tree — it occupies point 10 fell the 5-th tree to the right — now it occupies segment [19;20] In the second sample you can also fell 4-th tree to the right, after that it will occupy segment [10;19].
Java 8
standard input
[ "dp", "greedy" ]
a850dd88a67a6295823e70e2c5c857c9
The first line contains integer n (1 ≤ n ≤ 105) — the number of trees. Next n lines contain pairs of integers xi, hi (1 ≤ xi, hi ≤ 109) — the coordinate and the height of the і-th tree. The pairs are given in the order of ascending xi. No two trees are located at the point with the same coordinate.
1,500
Print a single number — the maximum number of trees that you can cut down by the given rules.
standard output
PASSED
3a97625f26fb69c04dabd71e6aa59c73
train_001.jsonl
1432053000
Little Susie listens to fairy tales before bed every day. Today's fairy tale was about wood cutters and the little girl immediately started imagining the choppers cutting wood. She imagined the situation that is described below.There are n trees located along the road at points with coordinates x1, x2, ..., xn. Each tree has its height hi. Woodcutters can cut down a tree and fell it to the left or to the right. After that it occupies one of the segments [xi - hi, xi] or [xi;xi + hi]. The tree that is not cut down occupies a single point with coordinate xi. Woodcutters can fell a tree if the segment to be occupied by the fallen tree doesn't contain any occupied point. The woodcutters want to process as many trees as possible, so Susie wonders, what is the maximum number of trees to fell.
256 megabytes
import java.util.Scanner; public class TaskC { public static int max(int a,int b) { if(a>b) return a; else return b; } public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc=new Scanner(System.in); int n=sc.nextInt(); if(n==1) { System.out.println(1); return; } if(n==2) { System.out.println(2); return; } int x[]=new int[n]; int h[]=new int[n]; int last; for(int i=0;i<n;i++) { x[i]=sc.nextInt(); h[i]=sc.nextInt(); } int res[][]=new int[n][3]; //0- left 1 -stay 2-right res[0][0]=1; res[0][1]=0; if(x[0]+h[0]<x[1]) res[0][2]=1; else res[0][2]=0; for(int i=1;i<n-1;i++) { //1 res[i][1]=0; for(int j=0;j<3;j++) if(res[i][1]<res[i-1][j]) res[i][1]=res[i-1][j]; //0 if(x[i]-h[i]<=x[i-1]) res[i][0]=res[i][1]; if(x[i]-h[i]>x[i-1]) res[i][0]=res[i-1][0]+1; if(x[i]-h[i]>x[i-1]+h[i-1]) res[i][0]=max(res[i-1][2],res[i-1][0])+1; //2 if(x[i]+h[i]<x[i+1]) res[i][2]=res[i][1]+1; else res[i][2]=res[i][1]; //System.out.println(res[i][0]+" "+res[i][1]+" "+res[i][2]); } System.out.println(max(max(res[n-2][0],res[n-2][1]),res[n-2][2])+1); } } //int am=2; //last=x[0]; //for(int i=1;i<n-1;i++) //{ // if(x[i]-last>h[i]) // { // am++; // last=x[i]; // } // else // { // if(x[i+1]-x[i]>h[i]) // { // am++; // last=x[i]+h[i]; // } // } //} //System.out.println(am);
Java
["5\n1 2\n2 1\n5 10\n10 9\n19 1", "5\n1 2\n2 1\n5 10\n10 9\n20 1"]
1 second
["3", "4"]
NoteIn the first sample you can fell the trees like that: fell the 1-st tree to the left — now it occupies segment [ - 1;1] fell the 2-nd tree to the right — now it occupies segment [2;3] leave the 3-rd tree — it occupies point 5 leave the 4-th tree — it occupies point 10 fell the 5-th tree to the right — now it occupies segment [19;20] In the second sample you can also fell 4-th tree to the right, after that it will occupy segment [10;19].
Java 8
standard input
[ "dp", "greedy" ]
a850dd88a67a6295823e70e2c5c857c9
The first line contains integer n (1 ≤ n ≤ 105) — the number of trees. Next n lines contain pairs of integers xi, hi (1 ≤ xi, hi ≤ 109) — the coordinate and the height of the і-th tree. The pairs are given in the order of ascending xi. No two trees are located at the point with the same coordinate.
1,500
Print a single number — the maximum number of trees that you can cut down by the given rules.
standard output
PASSED
4d9af81ae01558c076e5a78738507363
train_001.jsonl
1432053000
Little Susie listens to fairy tales before bed every day. Today's fairy tale was about wood cutters and the little girl immediately started imagining the choppers cutting wood. She imagined the situation that is described below.There are n trees located along the road at points with coordinates x1, x2, ..., xn. Each tree has its height hi. Woodcutters can cut down a tree and fell it to the left or to the right. After that it occupies one of the segments [xi - hi, xi] or [xi;xi + hi]. The tree that is not cut down occupies a single point with coordinate xi. Woodcutters can fell a tree if the segment to be occupied by the fallen tree doesn't contain any occupied point. The woodcutters want to process as many trees as possible, so Susie wonders, what is the maximum number of trees to fell.
256 megabytes
import java.util.Scanner; public class Program { public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc = new Scanner (System.in); int n = Integer.parseInt(sc.nextLine()); int [] x = new int [n]; int [] h = new int [n]; for (int i = 0; i < n; i ++) { String [] temp = sc.nextLine().split(" "); x[i] = Integer.parseInt(temp[0]); h[i] = Integer.parseInt(temp[1]); } if (n == 1) System.out.println(1); else { int ans = 1; int right_pos = x[0]; for (int i = 1; i < n; i++) { if (x[i] - h[i] > right_pos) { ans++; right_pos = x[i]; } else{ if (i + 1 == n || x[i] + h[i] < x[i + 1]) { ans++; right_pos = x[i] + h[i]; } else { right_pos = x[i]; } } } System.out.println(ans); } } }
Java
["5\n1 2\n2 1\n5 10\n10 9\n19 1", "5\n1 2\n2 1\n5 10\n10 9\n20 1"]
1 second
["3", "4"]
NoteIn the first sample you can fell the trees like that: fell the 1-st tree to the left — now it occupies segment [ - 1;1] fell the 2-nd tree to the right — now it occupies segment [2;3] leave the 3-rd tree — it occupies point 5 leave the 4-th tree — it occupies point 10 fell the 5-th tree to the right — now it occupies segment [19;20] In the second sample you can also fell 4-th tree to the right, after that it will occupy segment [10;19].
Java 8
standard input
[ "dp", "greedy" ]
a850dd88a67a6295823e70e2c5c857c9
The first line contains integer n (1 ≤ n ≤ 105) — the number of trees. Next n lines contain pairs of integers xi, hi (1 ≤ xi, hi ≤ 109) — the coordinate and the height of the і-th tree. The pairs are given in the order of ascending xi. No two trees are located at the point with the same coordinate.
1,500
Print a single number — the maximum number of trees that you can cut down by the given rules.
standard output
PASSED
4020b231b628732667e5bdce6f46f74c
train_001.jsonl
1432053000
Little Susie listens to fairy tales before bed every day. Today's fairy tale was about wood cutters and the little girl immediately started imagining the choppers cutting wood. She imagined the situation that is described below.There are n trees located along the road at points with coordinates x1, x2, ..., xn. Each tree has its height hi. Woodcutters can cut down a tree and fell it to the left or to the right. After that it occupies one of the segments [xi - hi, xi] or [xi;xi + hi]. The tree that is not cut down occupies a single point with coordinate xi. Woodcutters can fell a tree if the segment to be occupied by the fallen tree doesn't contain any occupied point. The woodcutters want to process as many trees as possible, so Susie wonders, what is the maximum number of trees to fell.
256 megabytes
import java.util.Scanner; public class Program { public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc = new Scanner (System.in); int n = Integer.parseInt(sc.nextLine()); int [] x = new int [n]; int [] h = new int [n]; for (int i = 0; i < n; i ++) { String [] temp = sc.nextLine().split(" "); x[i] = Integer.parseInt(temp[0]); h[i] = Integer.parseInt(temp[1]); } if (n == 1) System.out.println(1); else { int Max = 1; int BiChiem = x[0]; for (int i = 1; i < n; i++) { if (x[i] - h[i] > BiChiem) { Max++; BiChiem = x[i]; } else { if (i + 1 == n || x[i] + h[i] < x[i + 1]) { Max++; BiChiem = x[i] + h[i]; } else { BiChiem = x[i]; } } } System.out.println(Max); } } }
Java
["5\n1 2\n2 1\n5 10\n10 9\n19 1", "5\n1 2\n2 1\n5 10\n10 9\n20 1"]
1 second
["3", "4"]
NoteIn the first sample you can fell the trees like that: fell the 1-st tree to the left — now it occupies segment [ - 1;1] fell the 2-nd tree to the right — now it occupies segment [2;3] leave the 3-rd tree — it occupies point 5 leave the 4-th tree — it occupies point 10 fell the 5-th tree to the right — now it occupies segment [19;20] In the second sample you can also fell 4-th tree to the right, after that it will occupy segment [10;19].
Java 8
standard input
[ "dp", "greedy" ]
a850dd88a67a6295823e70e2c5c857c9
The first line contains integer n (1 ≤ n ≤ 105) — the number of trees. Next n lines contain pairs of integers xi, hi (1 ≤ xi, hi ≤ 109) — the coordinate and the height of the і-th tree. The pairs are given in the order of ascending xi. No two trees are located at the point with the same coordinate.
1,500
Print a single number — the maximum number of trees that you can cut down by the given rules.
standard output
PASSED
e736729aff279c4812096bbb8479fc47
train_001.jsonl
1432658100
Mike and some bears are playing a game just for fun. Mike is the judge. All bears except Mike are standing in an n × m grid, there's exactly one bear in each cell. We denote the bear standing in column number j of row number i by (i, j). Mike's hands are on his ears (since he's the judge) and each bear standing in the grid has hands either on his mouth or his eyes. They play for q rounds. In each round, Mike chooses a bear (i, j) and tells him to change his state i. e. if his hands are on his mouth, then he'll put his hands on his eyes or he'll put his hands on his mouth otherwise. After that, Mike wants to know the score of the bears.Score of the bears is the maximum over all rows of number of consecutive bears with hands on their eyes in that row.Since bears are lazy, Mike asked you for help. For each round, tell him the score of these bears after changing the state of a bear selected in that round.
256 megabytes
/* Harish Anumula */ import java.util.*; //import java.awt.Point; import java.io.*; //import java.math.BigInteger; public class MAXEINSTLE { public static void main (String[] args) throws java.lang.Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw = new PrintWriter(new BufferedOutputStream(System.out)); FastScanner scan = new FastScanner(br); Task solver = new Task(); solver.solve(scan,pw); pw.close(); } } class Task{ //long MOD = (long)1e9+7L; public void solve(FastScanner scan , PrintWriter pw) throws java.lang.Exception{ int n = scan.nextInt(); int m = scan.nextInt(); int q = scan.nextInt(); int[][] arr = new int[n][m]; for(int i = 0;i<n;i++){ for(int j = 0;j<m;j++){ arr[i][j] = scan.nextInt(); } } ArrayList<Integer> arrs = new ArrayList<Integer>(); for(int i = 0;i<n;i++){ arrs.add(calc(arr,i,m)); } for(int i = 0;i<q;i++){ int x = scan.nextInt()-1; int y = scan.nextInt()-1; arr[x][y] = arr[x][y]==1?0:1; int update = calc(arr,x,m); arrs.set(x, update); pw.println(Collections.max(arrs)); } } int calc(int[][] arr , int i , int m){ int ans = 0; // String ch = ""; // int local = 0; // for(int j = 0;j<m;j++){ // ch += arr[i][j]; // } // String c = "1"; // while(ch.contains(c)){ // local = c.length(); // c += '1'; // } // if(ans<local){ // ans = local; // } int local = 0; for(int j = 0;j<m;j++){ if(arr[i][j]==1){ local++; } else{ local = 0; } ans = Math.max(ans, local); } return ans; } } class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(BufferedReader br) { this.br = br; } public String nextToken() throws Exception { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(br.readLine()); } return st.nextToken(); } public int nextInt() throws Exception { return Integer.parseInt(nextToken()); } public long nextLong() throws Exception { return Long.parseLong(nextToken()); } public double nextDouble() throws Exception { return Double.parseDouble(nextToken()); } public String nextLine() throws Exception { return br.readLine(); } }
Java
["5 4 5\n0 1 1 0\n1 0 0 1\n0 1 1 0\n1 0 0 1\n0 0 0 0\n1 1\n1 4\n1 1\n4 2\n4 3"]
2 seconds
["3\n4\n3\n3\n4"]
null
Java 8
standard input
[ "dp", "implementation", "greedy", "brute force" ]
337b6d2a11a25ef917809e6409f8edef
The first line of input contains three integers n, m and q (1 ≤ n, m ≤ 500 and 1 ≤ q ≤ 5000). The next n lines contain the grid description. There are m integers separated by spaces in each line. Each of these numbers is either 0 (for mouth) or 1 (for eyes). The next q lines contain the information about the rounds. Each of them contains two integers i and j (1 ≤ i ≤ n and 1 ≤ j ≤ m), the row number and the column number of the bear changing his state.
1,400
After each round, print the current score of the bears.
standard output
PASSED
d1f5fe8f2cdfbb9c4ce9b4e661afb24b
train_001.jsonl
1432658100
Mike and some bears are playing a game just for fun. Mike is the judge. All bears except Mike are standing in an n × m grid, there's exactly one bear in each cell. We denote the bear standing in column number j of row number i by (i, j). Mike's hands are on his ears (since he's the judge) and each bear standing in the grid has hands either on his mouth or his eyes. They play for q rounds. In each round, Mike chooses a bear (i, j) and tells him to change his state i. e. if his hands are on his mouth, then he'll put his hands on his eyes or he'll put his hands on his mouth otherwise. After that, Mike wants to know the score of the bears.Score of the bears is the maximum over all rows of number of consecutive bears with hands on their eyes in that row.Since bears are lazy, Mike asked you for help. For each round, tell him the score of these bears after changing the state of a bear selected in that round.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class B { public static void main(String[] args) throws IOException { FastScanner scan = new FastScanner(); PrintWriter out = new PrintWriter(System.out); int n = scan.nextInt(), m = scan.nextInt(), q = scan.nextInt(); boolean[][] a = new boolean[n][m]; int[] max = new int[n]; for(int i = 0; i < n; i++){ int res = 0, c = 0;; for(int j = 0; j < m; j++) { a[i][j] = scan.nextInt()==1; if(a[i][j]) c++; else c = 0; res = Math.max(c, res); } max[i] = res; } for(int k = 0; k < q; k++){ int x = scan.nextInt()-1, y = scan.nextInt()-1; a[x][y] = !a[x][y]; int next = 0, c = 0; for(int i = 0; i < m; i++){ if(a[x][i]) c++; else c = 0; next = Math.max(next, c); } max[x] = next; int res = 0; for(int i = 0; i < n; i++) res = Math.max(res, max[i]); out.println(res); } out.close(); } static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner() { try { br = new BufferedReader(new InputStreamReader(System.in)); st = new StringTokenizer(br.readLine()); } catch (Exception e){e.printStackTrace();} } public String next() { if (st.hasMoreTokens()) return st.nextToken(); try {st = new StringTokenizer(br.readLine());} catch (Exception e) {e.printStackTrace();} return st.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() { String line = ""; try {line = br.readLine();} catch (Exception e) {e.printStackTrace();} return line; } public int[] nextIntArray(int n) { int[] a = new int[n]; for(int i = 0; i < n; i++) a[i] = nextInt(); return a; } public long[] nextLongArray(int n){ long[] a = new long[n]; for(int i = 0; i < n; i++) a[i] = nextLong(); return a; } public double[] nextDoubleArray(int n){ double[] a = new double[n]; for(int i = 0; i < n; i++) a[i] = nextDouble(); return a; } public char[][] nextGrid(int n, int m){ char[][] grid = new char[n][m]; for(int i = 0; i < n; i++) grid[i] = next().toCharArray(); return grid; } } }
Java
["5 4 5\n0 1 1 0\n1 0 0 1\n0 1 1 0\n1 0 0 1\n0 0 0 0\n1 1\n1 4\n1 1\n4 2\n4 3"]
2 seconds
["3\n4\n3\n3\n4"]
null
Java 8
standard input
[ "dp", "implementation", "greedy", "brute force" ]
337b6d2a11a25ef917809e6409f8edef
The first line of input contains three integers n, m and q (1 ≤ n, m ≤ 500 and 1 ≤ q ≤ 5000). The next n lines contain the grid description. There are m integers separated by spaces in each line. Each of these numbers is either 0 (for mouth) or 1 (for eyes). The next q lines contain the information about the rounds. Each of them contains two integers i and j (1 ≤ i ≤ n and 1 ≤ j ≤ m), the row number and the column number of the bear changing his state.
1,400
After each round, print the current score of the bears.
standard output
PASSED
ee3e8bdd6b21379d141dccc78e1478c7
train_001.jsonl
1432658100
Mike and some bears are playing a game just for fun. Mike is the judge. All bears except Mike are standing in an n × m grid, there's exactly one bear in each cell. We denote the bear standing in column number j of row number i by (i, j). Mike's hands are on his ears (since he's the judge) and each bear standing in the grid has hands either on his mouth or his eyes. They play for q rounds. In each round, Mike chooses a bear (i, j) and tells him to change his state i. e. if his hands are on his mouth, then he'll put his hands on his eyes or he'll put his hands on his mouth otherwise. After that, Mike wants to know the score of the bears.Score of the bears is the maximum over all rows of number of consecutive bears with hands on their eyes in that row.Since bears are lazy, Mike asked you for help. For each round, tell him the score of these bears after changing the state of a bear selected in that round.
256 megabytes
import java.util.ArrayList; import java.util.Collections; import java.util.Scanner; public class B548 { public static void main(String[] args) { // TODO Auto-generated method stub. Scanner scan = new Scanner(System.in); int n = scan.nextInt(); int m = scan.nextInt(); int q = scan.nextInt(); int[][] bearMap = new int[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { bearMap[i][j] = scan.nextInt(); } } ArrayList<Integer> maxValues = new ArrayList<Integer>(); for (int row = 0; row < n; row++) { int max = 0; int tempMax = 0; for (int col = 0; col < m; col++) { if (bearMap[row][col] == 1) { tempMax++; } else { if (tempMax > max) { max = tempMax; } tempMax = 0; } } if (tempMax > max) { max = tempMax; } maxValues.add(max); } for (int i = 0; i < q; i++) { int r = scan.nextInt(); int c = scan.nextInt(); bearMap[r - 1][c - 1] = (bearMap[r - 1][c - 1] + 1) % 2; int max = 0; int tempMax = 0; for (int col = 0; col < m; col++) { if (bearMap[r - 1][col] == 1) { tempMax++; } else { if (tempMax > max) { max = tempMax; } tempMax = 0; } } if (tempMax > max) { max = tempMax; } maxValues.set(r - 1, max); System.out.println(Collections.max(maxValues)); } } }
Java
["5 4 5\n0 1 1 0\n1 0 0 1\n0 1 1 0\n1 0 0 1\n0 0 0 0\n1 1\n1 4\n1 1\n4 2\n4 3"]
2 seconds
["3\n4\n3\n3\n4"]
null
Java 8
standard input
[ "dp", "implementation", "greedy", "brute force" ]
337b6d2a11a25ef917809e6409f8edef
The first line of input contains three integers n, m and q (1 ≤ n, m ≤ 500 and 1 ≤ q ≤ 5000). The next n lines contain the grid description. There are m integers separated by spaces in each line. Each of these numbers is either 0 (for mouth) or 1 (for eyes). The next q lines contain the information about the rounds. Each of them contains two integers i and j (1 ≤ i ≤ n and 1 ≤ j ≤ m), the row number and the column number of the bear changing his state.
1,400
After each round, print the current score of the bears.
standard output
PASSED
14afe2e1b34170f25017d2eed14347f0
train_001.jsonl
1432658100
Mike and some bears are playing a game just for fun. Mike is the judge. All bears except Mike are standing in an n × m grid, there's exactly one bear in each cell. We denote the bear standing in column number j of row number i by (i, j). Mike's hands are on his ears (since he's the judge) and each bear standing in the grid has hands either on his mouth or his eyes. They play for q rounds. In each round, Mike chooses a bear (i, j) and tells him to change his state i. e. if his hands are on his mouth, then he'll put his hands on his eyes or he'll put his hands on his mouth otherwise. After that, Mike wants to know the score of the bears.Score of the bears is the maximum over all rows of number of consecutive bears with hands on their eyes in that row.Since bears are lazy, Mike asked you for help. For each round, tell him the score of these bears after changing the state of a bear selected in that round.
256 megabytes
import java.util.Scanner; import java.util.Arrays; import java.util.Collections; public class Main { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int n=sc.nextInt(); int m=sc.nextInt(); int q=sc.nextInt(); int[][] table=new int[n+1][m+1]; int [] store=new int[n+1]; for(int i=1;i<n+1;i++) {int ct=0; for(int j=1;j<m+1;j++) { table[i][j]=sc.nextInt(); if(table[i][j]==1) ct++; else {store[i]=Math.max(store[i], ct); ct=0; } } store[i]=Math.max(store[i], ct); } for(int i=1;i<q+1;i++) { int r=sc.nextInt(); int c=sc.nextInt(); if(table[r][c]==0) { table[r][c]=1; } else { table[r][c]=0; } int count=0; store[r]=0; for(int l=1;l<m+1;l++) { if(table[r][l]==1) {count++; } else { store[r]=Math.max(store[r], count); count=0; } } store[r]=Math.max(store[r], count); int max=store[0]; for(int j=1;j<n+1;j++){ if(max<store[j]) max=store[j]; } System.out.println(max); } } }
Java
["5 4 5\n0 1 1 0\n1 0 0 1\n0 1 1 0\n1 0 0 1\n0 0 0 0\n1 1\n1 4\n1 1\n4 2\n4 3"]
2 seconds
["3\n4\n3\n3\n4"]
null
Java 8
standard input
[ "dp", "implementation", "greedy", "brute force" ]
337b6d2a11a25ef917809e6409f8edef
The first line of input contains three integers n, m and q (1 ≤ n, m ≤ 500 and 1 ≤ q ≤ 5000). The next n lines contain the grid description. There are m integers separated by spaces in each line. Each of these numbers is either 0 (for mouth) or 1 (for eyes). The next q lines contain the information about the rounds. Each of them contains two integers i and j (1 ≤ i ≤ n and 1 ≤ j ≤ m), the row number and the column number of the bear changing his state.
1,400
After each round, print the current score of the bears.
standard output
PASSED
c6114391912ca772911779aa02b0a863
train_001.jsonl
1432658100
Mike and some bears are playing a game just for fun. Mike is the judge. All bears except Mike are standing in an n × m grid, there's exactly one bear in each cell. We denote the bear standing in column number j of row number i by (i, j). Mike's hands are on his ears (since he's the judge) and each bear standing in the grid has hands either on his mouth or his eyes. They play for q rounds. In each round, Mike chooses a bear (i, j) and tells him to change his state i. e. if his hands are on his mouth, then he'll put his hands on his eyes or he'll put his hands on his mouth otherwise. After that, Mike wants to know the score of the bears.Score of the bears is the maximum over all rows of number of consecutive bears with hands on their eyes in that row.Since bears are lazy, Mike asked you for help. For each round, tell him the score of these bears after changing the state of a bear selected in that round.
256 megabytes
import java.util.*; public class cf_02 { static int[][] map=new int[501][501]; public static int check(int s[]){ int max=0; int cur=0; for(int a:s){ if (a==1){ cur++; } else{ max=Math.max(max,cur); cur=0; } } return Math.max(max,cur); } public static int mx(int s[]){ int max=s[0]; for(int a:s){ max=Math.max(max, a); } return max; } public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc=new Scanner(System.in); int n=sc.nextInt(); int m=sc.nextInt(); int q=sc.nextInt(); int[] ans=new int[n+1]; for(int i=1;i<=n;i++){ for(int j=1;j<=m;j++){ map[i][j]=sc.nextInt(); } ans[i]=check(map[i]); } while(q>0){ int i=sc.nextInt(); int j=sc.nextInt(); map[i][j]=(map[i][j]==0?1:0); ans[i]=check(map[i]); System.out.println(mx(ans)); q--; } } }
Java
["5 4 5\n0 1 1 0\n1 0 0 1\n0 1 1 0\n1 0 0 1\n0 0 0 0\n1 1\n1 4\n1 1\n4 2\n4 3"]
2 seconds
["3\n4\n3\n3\n4"]
null
Java 8
standard input
[ "dp", "implementation", "greedy", "brute force" ]
337b6d2a11a25ef917809e6409f8edef
The first line of input contains three integers n, m and q (1 ≤ n, m ≤ 500 and 1 ≤ q ≤ 5000). The next n lines contain the grid description. There are m integers separated by spaces in each line. Each of these numbers is either 0 (for mouth) or 1 (for eyes). The next q lines contain the information about the rounds. Each of them contains two integers i and j (1 ≤ i ≤ n and 1 ≤ j ≤ m), the row number and the column number of the bear changing his state.
1,400
After each round, print the current score of the bears.
standard output
PASSED
56652198829107125f5f5843ddae5b15
train_001.jsonl
1432658100
Mike and some bears are playing a game just for fun. Mike is the judge. All bears except Mike are standing in an n × m grid, there's exactly one bear in each cell. We denote the bear standing in column number j of row number i by (i, j). Mike's hands are on his ears (since he's the judge) and each bear standing in the grid has hands either on his mouth or his eyes. They play for q rounds. In each round, Mike chooses a bear (i, j) and tells him to change his state i. e. if his hands are on his mouth, then he'll put his hands on his eyes or he'll put his hands on his mouth otherwise. After that, Mike wants to know the score of the bears.Score of the bears is the maximum over all rows of number of consecutive bears with hands on their eyes in that row.Since bears are lazy, Mike asked you for help. For each round, tell him the score of these bears after changing the state of a bear selected in that round.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Q305B2 { static int n, m, q; static int[][] arr; public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String[] line = br.readLine().split(" "); n = Integer.parseInt(line[0]); m = Integer.parseInt(line[1]); q = Integer.parseInt(line[2]); arr = new int[n][m]; int[] max = new int[n]; for (int i = 0; i < n; i++) { line = br.readLine().split(" "); for (int j = 0; j < m; j++) { arr[i][j] = Integer.parseInt(line[j]); } max[i] = calculateMaxRow(i); } for (int i = 0; i < q; i++) { line = br.readLine().split(" "); int a = Integer.parseInt(line[0]); int b = Integer.parseInt(line[1]); if(arr[a-1][b-1] == 0){ arr[a-1][b-1] = 1; } else if(arr[a-1][b-1] == 1){ arr[a-1][b-1] = 0; } int currentMax = calculateMaxRow(a-1); max[a-1] = currentMax; int answer = 0; for (int j = 0; j < n; j++) { if(max[j] > answer){ answer = max[j]; } } System.out.println(answer); } } private static int calculateMaxRow(int i) { int rollSum = 0; int maxSum = 0; for (int j = 0; j < m; j++) { if(arr[i][j] == 0){ rollSum = 0; } else if(arr[i][j] == 1){ rollSum++; maxSum = Math.max(rollSum, maxSum); } } return maxSum; } }
Java
["5 4 5\n0 1 1 0\n1 0 0 1\n0 1 1 0\n1 0 0 1\n0 0 0 0\n1 1\n1 4\n1 1\n4 2\n4 3"]
2 seconds
["3\n4\n3\n3\n4"]
null
Java 8
standard input
[ "dp", "implementation", "greedy", "brute force" ]
337b6d2a11a25ef917809e6409f8edef
The first line of input contains three integers n, m and q (1 ≤ n, m ≤ 500 and 1 ≤ q ≤ 5000). The next n lines contain the grid description. There are m integers separated by spaces in each line. Each of these numbers is either 0 (for mouth) or 1 (for eyes). The next q lines contain the information about the rounds. Each of them contains two integers i and j (1 ≤ i ≤ n and 1 ≤ j ≤ m), the row number and the column number of the bear changing his state.
1,400
After each round, print the current score of the bears.
standard output
PASSED
5febde78e248e3e581ae9b60fcebc981
train_001.jsonl
1432658100
Mike and some bears are playing a game just for fun. Mike is the judge. All bears except Mike are standing in an n × m grid, there's exactly one bear in each cell. We denote the bear standing in column number j of row number i by (i, j). Mike's hands are on his ears (since he's the judge) and each bear standing in the grid has hands either on his mouth or his eyes. They play for q rounds. In each round, Mike chooses a bear (i, j) and tells him to change his state i. e. if his hands are on his mouth, then he'll put his hands on his eyes or he'll put his hands on his mouth otherwise. After that, Mike wants to know the score of the bears.Score of the bears is the maximum over all rows of number of consecutive bears with hands on their eyes in that row.Since bears are lazy, Mike asked you for help. For each round, tell him the score of these bears after changing the state of a bear selected in that round.
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.io.*; /** * * @author Alex */ public class B { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); int t = sc.nextInt(); int j = sc.nextInt(); int[][] grid = new int[t][j]; int[] sum = new int[t]; int max = 0; int test = sc.nextInt(); for(int i=0;i<t;i++){ for(int k=0;k<j;k++){ grid[i][k] = sc.nextInt(); } int temp = 0; int localMax=0; for(int k=0;k<j;k++){ if(grid[i][k]==1){ temp++; } else{ temp=0; } if(temp>localMax){ localMax = temp; } } sum[i]=localMax; } for(int i=0;i<test;i++){ int first = sc.nextInt()-1; int second = sc.nextInt()-1; grid[first][second]= grid[first][second]^1; int temp = 0; int localMax=0; for(int k=0;k<j;k++){ if(grid[first][k]==1){ temp++; } else{ temp=0; } if(temp>localMax){ localMax = temp; } } sum[first]=localMax; max = 0; for(int k=0;k<t;k++){ if(sum[k]>max){ max = sum[k]; } } out.println(max); } sc.close(); out.close(); } }
Java
["5 4 5\n0 1 1 0\n1 0 0 1\n0 1 1 0\n1 0 0 1\n0 0 0 0\n1 1\n1 4\n1 1\n4 2\n4 3"]
2 seconds
["3\n4\n3\n3\n4"]
null
Java 8
standard input
[ "dp", "implementation", "greedy", "brute force" ]
337b6d2a11a25ef917809e6409f8edef
The first line of input contains three integers n, m and q (1 ≤ n, m ≤ 500 and 1 ≤ q ≤ 5000). The next n lines contain the grid description. There are m integers separated by spaces in each line. Each of these numbers is either 0 (for mouth) or 1 (for eyes). The next q lines contain the information about the rounds. Each of them contains two integers i and j (1 ≤ i ≤ n and 1 ≤ j ≤ m), the row number and the column number of the bear changing his state.
1,400
After each round, print the current score of the bears.
standard output
PASSED
e86844ff25b5b5ca9ad26eca3ed70e9e
train_001.jsonl
1432658100
Mike and some bears are playing a game just for fun. Mike is the judge. All bears except Mike are standing in an n × m grid, there's exactly one bear in each cell. We denote the bear standing in column number j of row number i by (i, j). Mike's hands are on his ears (since he's the judge) and each bear standing in the grid has hands either on his mouth or his eyes. They play for q rounds. In each round, Mike chooses a bear (i, j) and tells him to change his state i. e. if his hands are on his mouth, then he'll put his hands on his eyes or he'll put his hands on his mouth otherwise. After that, Mike wants to know the score of the bears.Score of the bears is the maximum over all rows of number of consecutive bears with hands on their eyes in that row.Since bears are lazy, Mike asked you for help. For each round, tell him the score of these bears after changing the state of a bear selected in that round.
256 megabytes
import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.math.BigInteger; import java.util.StringTokenizer; public class Solution{ /////////////////////////////////////////////////////////////////////////// static class FastScanner{ BufferedReader s; StringTokenizer st; public FastScanner(InputStream InputStream){ st = new StringTokenizer(""); s = new BufferedReader(new InputStreamReader(InputStream)); } public FastScanner(File f) throws FileNotFoundException{ st = new StringTokenizer(""); s = new BufferedReader (new FileReader(f)); } public int nextInt() throws IOException{ if(st.hasMoreTokens()) return Integer.parseInt(st.nextToken()); else{ st = new StringTokenizer(s.readLine()); return nextInt(); } } public BigInteger big() throws IOException{ if(st.hasMoreTokens()) return new BigInteger(st.nextToken()); else{ st = new StringTokenizer(s.readLine()); return big(); } } public double nextDouble() throws IOException{ if(st.hasMoreTokens()) return Double.parseDouble(st.nextToken()); else{ st = new StringTokenizer(s.readLine()); return nextDouble(); } } public long nextLong() throws IOException{ if(st.hasMoreTokens()) return Long.parseLong(st.nextToken()); else{ st = new StringTokenizer(s.readLine()); return nextLong(); } } public String nextString() throws IOException{ if(st.hasMoreTokens()) return st.nextToken(); else{ st = new StringTokenizer(s.readLine()); return nextString(); } } public String readLine() throws IOException{ return s.readLine(); } public void close() throws IOException{ s.close(); } } //////////////////////////////////////////////////////////////////// // Number Theory long pow(long a,long b,long mod){ long x = 1; long y = a; while(b > 0){ if(b % 2 == 1){ x = (x*y); x %= mod; } y = (y*y); y %= mod; b /= 2; } return x; } int divisor(long x,long[] a){ long limit = x; int numberOfDivisors = 0; for (int i=1; i < limit; ++i) { if (x % i == 0) { limit = x / i; if (limit != i) { numberOfDivisors++; } numberOfDivisors++; } } return numberOfDivisors; } void findSubsets(int array[]){ long numOfSubsets = 1 << array.length; for(int i = 0; i < numOfSubsets; i++){ @SuppressWarnings("unused") int pos = array.length - 1; int bitmask = i; while(bitmask > 0){ if((bitmask & 1) == 1) // ww.print(array[pos]+" "); bitmask >>= 1; pos--; } // ww.println(); } } public static long gcd(long a, long b){ return b == 0 ? a : gcd(b,a%b); } public static long lcm(int a,int b, int c){ return lcm(lcm(a,b),c); } public static long lcm(long a, long b){ return (a*b/gcd(a,b)); } public static long invl(long a, long mod) { long b = mod; long p = 1, q = 0; while (b > 0) { long c = a / b; long d; d = a; a = b; b = d % b; d = p; p = q; q = d - c * q; } return p < 0 ? p + mod : p; } //////////////////////////////////////////////////////////////////// // FastScanner s = new FastScanner(new File("a.pdf")); // PrintWriter ww = new PrintWriter(new FileWriter("output.txt")); static InputStream inputStream = System.in; static FastScanner s = new FastScanner(inputStream); static OutputStream outputStream = System.out; static PrintWriter ww = new PrintWriter(new OutputStreamWriter(outputStream)); // private static Scanner s = new Scanner(System.in); @SuppressWarnings("unused") private static int[][] states = { {-1,0} , {1,0} , {0,-1} , {0,1} }; //////////////////////////////////////////////////////////////////// public static void main(String[] args) throws Exception{ new Solution().solve(); s.close(); ww.close(); } //////////////////////////////////////////////////////////////////// int[][] a; int[] pre; void query(){ for(int i=0;i<a.length;i++){ int count = 1; int max = 0; boolean two = false; boolean one = false; if(a[i][0] == 1) one = true; for(int j=1;j<a[0].length;j++){ if(a[i][0] == 1 || a[i][j] == 1) one = true; if((a[i][j] == a[i][j-1]) && ((a[i][j]+a[i][j-1]) == 2)){ count++; two = true; } else{ max = Math.max(count, max); count = 1; } } if(!two && one) max = 1; else if(!two && !one) max = 0; else max = Math.max(count, max); pre[i] = max; } } void ch(int i){ int count = 1; int max = 0; boolean two = false; boolean one = false; if(a[i][0] == 1) one = true; for(int j=1;j<a[0].length;j++){ if(a[i][0] == 1 || a[i][j] == 1) one = true; if(a[i][j] == a[i][j-1] && (a[i][j]+a[i][j-1] == 2)){ count++; two = true; } else{ max = Math.max(count, max); count = 1; } } if(!two && one) max = 1; else if(!two && !one) max = 0; else max = Math.max(count, max); pre[i] = max; } void solve() throws IOException{ int n = s.nextInt(); int m = s.nextInt(); int q = s.nextInt(); a = new int[n][m]; pre = new int[n]; for(int i=0;i<n;i++) for(int j=0;j<m;j++) a[i][j] = s.nextInt(); query(); // for(int i=0;i<pre.length;i++) ww.println(pre[i]); while(q -- > 0){ int x = s.nextInt()-1; int y = s.nextInt()-1; if(a[x][y] == 1) a[x][y] = 0; else a[x][y] = 1; ch(x); int maxi = 0; for(int i=0;i<pre.length;i++) maxi = Math.max(maxi, pre[i]); ww.println(maxi); } } }
Java
["5 4 5\n0 1 1 0\n1 0 0 1\n0 1 1 0\n1 0 0 1\n0 0 0 0\n1 1\n1 4\n1 1\n4 2\n4 3"]
2 seconds
["3\n4\n3\n3\n4"]
null
Java 8
standard input
[ "dp", "implementation", "greedy", "brute force" ]
337b6d2a11a25ef917809e6409f8edef
The first line of input contains three integers n, m and q (1 ≤ n, m ≤ 500 and 1 ≤ q ≤ 5000). The next n lines contain the grid description. There are m integers separated by spaces in each line. Each of these numbers is either 0 (for mouth) or 1 (for eyes). The next q lines contain the information about the rounds. Each of them contains two integers i and j (1 ≤ i ≤ n and 1 ≤ j ≤ m), the row number and the column number of the bear changing his state.
1,400
After each round, print the current score of the bears.
standard output
PASSED
f3265f4b11ec2d116195ff873e45c2ee
train_001.jsonl
1432658100
Mike and some bears are playing a game just for fun. Mike is the judge. All bears except Mike are standing in an n × m grid, there's exactly one bear in each cell. We denote the bear standing in column number j of row number i by (i, j). Mike's hands are on his ears (since he's the judge) and each bear standing in the grid has hands either on his mouth or his eyes. They play for q rounds. In each round, Mike chooses a bear (i, j) and tells him to change his state i. e. if his hands are on his mouth, then he'll put his hands on his eyes or he'll put his hands on his mouth otherwise. After that, Mike wants to know the score of the bears.Score of the bears is the maximum over all rows of number of consecutive bears with hands on their eyes in that row.Since bears are lazy, Mike asked you for help. For each round, tell him the score of these bears after changing the state of a bear selected in that round.
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; public class CP { public static void main(String[] args) { InputStreamReader ir = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(ir); String line; String[] arr; try { line = br.readLine(); arr = line.split(" "); int n = Integer.parseInt(arr[0]); int m = Integer.parseInt(arr[1]); int q = Integer.parseInt(arr[2]); int[][] ar = new int[n][m]; for (int i = 0; i < n; i++) { line = br.readLine(); arr = line.split(" "); for (int j = 0; j < m; j++) { ar[i][j] = Integer.parseInt(arr[j]); } } int[] max = new int[n]; for (int i = 0; i < n; i++) { max[i] = countOnes(ar[i], m); } while (q > 0) { line = br.readLine(); arr = line.split(" "); int a = Integer.parseInt(arr[0]) - 1; int b = Integer.parseInt(arr[1]) - 1; if (ar[a][b] == 0) { ar[a][b] = 1; } else { ar[a][b] = 0; } max[a] = countOnes(ar[a], m); System.out.println(maximum(max, n)); q--; } } catch (Exception ex) { ex.printStackTrace(); } } public static int countOnes(int[] a, int m) { ArrayList<Integer> mm = new ArrayList<Integer>(); mm.add(0); boolean b = false; int count = 0; for (int j = 0; j < m; j++) { if (!b) { if (a[j] == 1) { b = true; count = 1; } } else if (a[j] == 1) { count++; } else { b = false; mm.add(count); count = 0; } mm.add(count); } return Collections.max(mm); } public static int maximum(int[] a, int n) { int max = a[0]; for (int i = 1; i < n; i++) if (a[i] > max) max = a[i]; return max; } }
Java
["5 4 5\n0 1 1 0\n1 0 0 1\n0 1 1 0\n1 0 0 1\n0 0 0 0\n1 1\n1 4\n1 1\n4 2\n4 3"]
2 seconds
["3\n4\n3\n3\n4"]
null
Java 8
standard input
[ "dp", "implementation", "greedy", "brute force" ]
337b6d2a11a25ef917809e6409f8edef
The first line of input contains three integers n, m and q (1 ≤ n, m ≤ 500 and 1 ≤ q ≤ 5000). The next n lines contain the grid description. There are m integers separated by spaces in each line. Each of these numbers is either 0 (for mouth) or 1 (for eyes). The next q lines contain the information about the rounds. Each of them contains two integers i and j (1 ≤ i ≤ n and 1 ≤ j ≤ m), the row number and the column number of the bear changing his state.
1,400
After each round, print the current score of the bears.
standard output
PASSED
d60882b3ff4a2b60fcd22e55439f1ef4
train_001.jsonl
1432658100
Mike and some bears are playing a game just for fun. Mike is the judge. All bears except Mike are standing in an n × m grid, there's exactly one bear in each cell. We denote the bear standing in column number j of row number i by (i, j). Mike's hands are on his ears (since he's the judge) and each bear standing in the grid has hands either on his mouth or his eyes. They play for q rounds. In each round, Mike chooses a bear (i, j) and tells him to change his state i. e. if his hands are on his mouth, then he'll put his hands on his eyes or he'll put his hands on his mouth otherwise. After that, Mike wants to know the score of the bears.Score of the bears is the maximum over all rows of number of consecutive bears with hands on their eyes in that row.Since bears are lazy, Mike asked you for help. For each round, tell him the score of these bears after changing the state of a bear selected in that round.
256 megabytes
import java.io.*; import java.math.*; import java.util.*; /** * * @author Saju * */ public class Main { private static int dx[] = { 1, 0, -1, 0 }; private static int dy[] = { 0, -1, 0, 1 }; private static final long INF = Long.MAX_VALUE; private static final int INT_INF = Integer.MAX_VALUE; private static final long NEG_INF = Long.MIN_VALUE; private static final int NEG_INT_INF = Integer.MIN_VALUE; private static final double EPSILON = 1e-10; private static final int MAX = 1007; private static final long MOD = 1000000007; private static final int MAXN = 10000007; private static final int MAXA = 10000009; private static final int MAXLOG = 22; public static void main(String[] args) throws IOException { InputReader in = new InputReader(System.in); PrintWriter out = new PrintWriter(System.out); // InputReader in = new InputReader(new FileInputStream("src/test.in")); // PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("src/test.out"))); /* */ int n = in.nextInt(); int m = in.nextInt(); int q = in.nextInt(); int[][] grid = new int[n][m]; for(int i = 0; i < n; i++) { for(int j = 0; j < m; j++) { grid[i][j] = in.nextInt(); } } int cnt[] = new int[n]; for(int i = 0; i < n; i++) { int c = 0; int mx = 0; for(int j = 0; j < m; j++) { if(grid[i][j] == 1) { c++; if(j == m - 1) { mx = max(mx, c); } } else if(grid[i][j] == 0) { mx = max(mx, c); c = 0; } } cnt[i] = mx; } // System.out.println(Arrays.toString(cnt)); for(int qq = 0; qq < q; qq++) { int a = in.nextInt() - 1; int b = in.nextInt() - 1; grid[a][b] = abs(grid[a][b] - 1); int c = 0; int mx = 0; for(int j = 0; j < m; j++) { if(grid[a][j] == 1) { c++; if(j == m - 1) { mx = max(mx, c); } } else if(grid[a][j] == 0) { mx = max(mx, c); c = 0; } } cnt[a] = mx; int max = 0; for(int i = 0; i < n; i++) { max = max(max, cnt[i]); } out.println(max); } out.flush(); out.close(); System.exit(0); } private static long bigMod(long n, long k, long m) { long ans = 1; while (k > 0) { if ((k & 1) == 1) { ans = (ans * n) % m; } n = (n * n) % m; k >>= 1; } return ans; } private static int ceil(int n, int x) { int div = n / x; if(div * x != n) { div++; } return div; } private static class Point { double x; double y; Point(double x, double y) { this.x = x; this.y = y; } double getDistance(Point p2) { Point p1 = this; double dx = p1.x - p2.x; double dy = p1.y - p2.y; return Math.sqrt((dx * dx) + (dy * dy)); } } private static int abs(int x) { if (x < 0) { return -x; } return x; } private static long abs(long x) { if(x < 0) { return -x; } return x; } private static int lcm(int a, int b) { return (a * b) / gcd(a, b); } private static int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a); } private static int log(long x, int base) { return (int) (Math.log(x) / Math.log(base)); } private static long min(long a, long b) { if (a < b) { return a; } return b; } private static int min(int a, int b) { if (a < b) { return a; } return b; } private static long max(long a, long b) { if (a < b) { return b; } return a; } private static int max(int a, int b) { if (a < b) { return b; } return a; } private static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); tokenizer = null; } public String next() { try { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } } catch (IOException e) { return null; } return tokenizer.nextToken(); } public String nextLine() { String line = null; try { tokenizer = null; line = reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } return line; } public int nextInt() { return Integer.parseInt(next()); } public double nextDouble() { return Double.parseDouble(next()); } public long nextLong() { return Long.parseLong(next()); } public boolean hasNext() { try { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } } catch (Exception e) { return false; } return true; } } }
Java
["5 4 5\n0 1 1 0\n1 0 0 1\n0 1 1 0\n1 0 0 1\n0 0 0 0\n1 1\n1 4\n1 1\n4 2\n4 3"]
2 seconds
["3\n4\n3\n3\n4"]
null
Java 8
standard input
[ "dp", "implementation", "greedy", "brute force" ]
337b6d2a11a25ef917809e6409f8edef
The first line of input contains three integers n, m and q (1 ≤ n, m ≤ 500 and 1 ≤ q ≤ 5000). The next n lines contain the grid description. There are m integers separated by spaces in each line. Each of these numbers is either 0 (for mouth) or 1 (for eyes). The next q lines contain the information about the rounds. Each of them contains two integers i and j (1 ≤ i ≤ n and 1 ≤ j ≤ m), the row number and the column number of the bear changing his state.
1,400
After each round, print the current score of the bears.
standard output
PASSED
8d86c79dec12fc5fd18064a59f80da0b
train_001.jsonl
1432658100
Mike and some bears are playing a game just for fun. Mike is the judge. All bears except Mike are standing in an n × m grid, there's exactly one bear in each cell. We denote the bear standing in column number j of row number i by (i, j). Mike's hands are on his ears (since he's the judge) and each bear standing in the grid has hands either on his mouth or his eyes. They play for q rounds. In each round, Mike chooses a bear (i, j) and tells him to change his state i. e. if his hands are on his mouth, then he'll put his hands on his eyes or he'll put his hands on his mouth otherwise. After that, Mike wants to know the score of the bears.Score of the bears is the maximum over all rows of number of consecutive bears with hands on their eyes in that row.Since bears are lazy, Mike asked you for help. For each round, tell him the score of these bears after changing the state of a bear selected in that round.
256 megabytes
import java.util.*; public final class MikeAndFun {static int a[][], res[],n,m,b[]; public static void main(String arg[]) { Scanner br=new Scanner(System.in); n=br.nextInt(); m=br.nextInt(); int q=br.nextInt(); res=new int [q]; a=new int[n][m]; b=new int[n]; for(int i=0;i<n;i++) {int c=0; for(int j=0;j<m;j++) { int f=br.nextInt(); a[i][j]=f; if(f==1) c++; else { if(c>b[i]) b[i]=c; c=0; } } if(c>b[i]) b[i]=c; } for(int i=0;i<q;i++) { int r,c; r=br.nextInt()-1; //row of bear c=br.nextInt()-1; //column of bear if(a[r][c]==0) { a[r][c]=1; getMax(i,r); } else { a[r][c]=0; getMax(i,r); } } print(); } public static void getMax(int t,int i) { int max=0,c=0; c=0; for(int j=0;j<m;j++) { if(a[i][j]==1) c++; else { if(c>max) max=c; c=0; } } if(c>max) max=c; b[i]=max; for(int l=0;l<b.length;l++) if(b[l]>max) max=b[l]; res[t]=max; } public static void print() { for(int i=0;i<res.length;i++) System.out.println(res[i]); } }
Java
["5 4 5\n0 1 1 0\n1 0 0 1\n0 1 1 0\n1 0 0 1\n0 0 0 0\n1 1\n1 4\n1 1\n4 2\n4 3"]
2 seconds
["3\n4\n3\n3\n4"]
null
Java 8
standard input
[ "dp", "implementation", "greedy", "brute force" ]
337b6d2a11a25ef917809e6409f8edef
The first line of input contains three integers n, m and q (1 ≤ n, m ≤ 500 and 1 ≤ q ≤ 5000). The next n lines contain the grid description. There are m integers separated by spaces in each line. Each of these numbers is either 0 (for mouth) or 1 (for eyes). The next q lines contain the information about the rounds. Each of them contains two integers i and j (1 ≤ i ≤ n and 1 ≤ j ≤ m), the row number and the column number of the bear changing his state.
1,400
After each round, print the current score of the bears.
standard output
PASSED
57a7978bb44058e9476cd0fe508940bc
train_001.jsonl
1432658100
Mike and some bears are playing a game just for fun. Mike is the judge. All bears except Mike are standing in an n × m grid, there's exactly one bear in each cell. We denote the bear standing in column number j of row number i by (i, j). Mike's hands are on his ears (since he's the judge) and each bear standing in the grid has hands either on his mouth or his eyes. They play for q rounds. In each round, Mike chooses a bear (i, j) and tells him to change his state i. e. if his hands are on his mouth, then he'll put his hands on his eyes or he'll put his hands on his mouth otherwise. After that, Mike wants to know the score of the bears.Score of the bears is the maximum over all rows of number of consecutive bears with hands on their eyes in that row.Since bears are lazy, Mike asked you for help. For each round, tell him the score of these bears after changing the state of a bear selected in that round.
256 megabytes
import java.util.Scanner; import java.util.Arrays; /** * * @author win7 */ public class Lifecodechef{ /** * @param args the command line arguments */ public static void main(String[] args) throws java.lang.Exception{ // TODO code application logic here Scanner input = new Scanner(System.in); int n = input.nextInt(); int m = input.nextInt(); int q = input.nextInt(); int[][] a = new int[n][m]; int[] score = new int[n]; for(int i=0;i<n;i++){ for(int j=0;j<m;j++){ a[i][j]= input.nextInt(); } } int count =0,x=0; for(int i=0;i<n;i++){ x=0;count =0; for(int j=0;j<m;j++){ if(a[i][j] == 1) count++; else{ x = Math.max(x, count); count =0; } } x = Math.max(x, count); score[i] = x; } for(int i =0;i<q;i++){ int e = input.nextInt() -1; int f = input.nextInt() -1; a[e][f] = Math.abs(a[e][f]-1); x=count=0; for(int j=0;j<m;j++){ if(a[e][j] == 1) count++; else{ x = Math.max(x, count); count =0; } } x = Math.max(x, count); score[e] = x; int max =0; for(int k=0;k<n;k++){ if(score[k] > max) max = score[k]; } System.out.printf("%d\n",max); } } }
Java
["5 4 5\n0 1 1 0\n1 0 0 1\n0 1 1 0\n1 0 0 1\n0 0 0 0\n1 1\n1 4\n1 1\n4 2\n4 3"]
2 seconds
["3\n4\n3\n3\n4"]
null
Java 8
standard input
[ "dp", "implementation", "greedy", "brute force" ]
337b6d2a11a25ef917809e6409f8edef
The first line of input contains three integers n, m and q (1 ≤ n, m ≤ 500 and 1 ≤ q ≤ 5000). The next n lines contain the grid description. There are m integers separated by spaces in each line. Each of these numbers is either 0 (for mouth) or 1 (for eyes). The next q lines contain the information about the rounds. Each of them contains two integers i and j (1 ≤ i ≤ n and 1 ≤ j ≤ m), the row number and the column number of the bear changing his state.
1,400
After each round, print the current score of the bears.
standard output
PASSED
8ad6ecd4082ba191a05cfe2fb5ecdd09
train_001.jsonl
1414170000
Permutation p is an ordered set of integers p1,   p2,   ...,   pn, consisting of n distinct positive integers not larger than n. We'll denote as n the length of permutation p1,   p2,   ...,   pn.Your task is to find such permutation p of length n, that the group of numbers |p1 - p2|, |p2 - p3|, ..., |pn - 1 - pn| has exactly k distinct elements.
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; import java.awt.Point; // SHIVAM GUPTA : //NSIT //decoder_1671 // STOP NOT TILL IT IS DONE OR U DIE . // U KNOW THAT IF THIS DAY WILL BE URS THEN NO ONE CAN DEFEAT U HERE................ // ASCII = 48 + i ;// 2^28 = 268,435,456 > 2* 10^8 // log 10 base 2 = 3.3219 // odd:: (x^2+1)/2 , (x^2-1)/2 ; x>=3// even:: (x^2/4)+1 ,(x^2/4)-1 x >=4 // FOR ANY ODD NO N : N,N-1,N-2 //ALL ARE PAIRWISE COPRIME //THEIR COMBINED LCM IS PRODUCT OF ALL THESE NOS // two consecutive odds are always coprime to each other // two consecutive even have always gcd = 2 ; public class Main { // static int[] arr = new int[100002] ; // static int[] dp = new int[100002] ; static PrintWriter out; static class FastReader{ BufferedReader br; StringTokenizer st; public FastReader(){ br=new BufferedReader(new InputStreamReader(System.in)); out=new PrintWriter(System.out); } 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; } } //////////////////////////////////////////////////////////////////////////////////// public static int countDigit(long n) { return (int)Math.floor(Math.log10(n) + 1); } ///////////////////////////////////////////////////////////////////////////////////////// public static int sumOfDigits(long n) { if( n< 0)return -1 ; int sum = 0; while( n > 0) { sum = sum + (int)( n %10) ; n /= 10 ; } return sum ; } ////////////////////////////////////////////////////////////////////////////////////////////////// public static long arraySum(int[] arr , int start , int end) { long ans = 0 ; for(int i = start ; i <= end ; i++)ans += arr[i] ; return ans ; } ///////////////////////////////////////////////////////////////////////////////// public static int mod(int x) { if(x <0)return -1*x ; else return x ; } public static long mod(long x) { if(x <0)return -1*x ; else return x ; } //////////////////////////////////////////////////////////////////////////////// public static void swapArray(int[] arr , int start , int end) { while(start < end) { int temp = arr[start] ; arr[start] = arr[end]; arr[end] = temp; start++ ;end-- ; } } ////////////////////////////////////////////////////////////////////////////////// public static int[][] rotate(int[][] input){ int n =input.length; int m = input[0].length ; int[][] output = new int [m][n]; for (int i=0; i<n; i++) for (int j=0;j<m; j++) output [j][n-1-i] = input[i][j]; return output; } /////////////////////////////////////////////////////////////////////////////////////////////////////// public static int countBits(long n) { int count = 0; while (n != 0) { count++; n = (n) >> (1L) ; } return count; } /////////////////////////////////////////// //////////////////////////////////////////////// public static boolean isPowerOfTwo(long n) { if(n==0) return false; if(((n ) & (n-1)) == 0 ) return true ; else return false ; } ///////////////////////////////////////////////////////////////////////////////////// public static int min(int a ,int b , int c, int d) { int[] arr = new int[4] ; arr[0] = a;arr[1] = b ;arr[2] = c;arr[3] = d;Arrays.sort(arr) ; return arr[0]; } ///////////////////////////////////////////////////////////////////////////// public static int max(int a ,int b , int c, int d) { int[] arr = new int[4] ; arr[0] = a;arr[1] = b ;arr[2] = c;arr[3] = d;Arrays.sort(arr) ; return arr[3]; } /////////////////////////////////////////////////////////////////////////////////// public static String reverse(String input) { StringBuilder str = new StringBuilder("") ; for(int i =input.length()-1 ; i >= 0 ; i-- ) { str.append(input.charAt(i)); } return str.toString() ; } /////////////////////////////////////////////////////////////////////////////////////////// public static boolean sameParity(long a ,long b ) { long x = a% 2L; long y = b%2L ; if(x==y)return true ; else return false ; } //////////////////////////////////////////////////////////////////////////////////////////////////// public static boolean isPossibleTriangle(int a ,int b , int c) { if( a + b > c && c+b > a && a +c > b)return true ; else return false ; } //////////////////////////////////////////////////////////////////////////////////////////// static long xnor(long num1, long num2) { if (num1 < num2) { long temp = num1; num1 = num2; num2 = temp; } num1 = togglebit(num1); return num1 ^ num2; } static long togglebit(long n) { if (n == 0) return 1; long i = n; n |= n >> 1; n |= n >> 2; n |= n >> 4; n |= n >> 8; n |= n >> 16; return i ^ n; } /////////////////////////////////////////////////////////////////////////////////////////////// public static int xorOfFirstN(int n) { if( n % 4 ==0)return n ; else if( n % 4 == 1)return 1 ; else if( n % 4 == 2)return n+1 ; else return 0 ; } ////////////////////////////////////////////////////////////////////////////////////////////// public static int gcd(int a, int b ) { if(b==0)return a ; else return gcd(b,a%b) ; } public static long gcd(long a, long b ) { if(b==0)return a ; else return gcd(b,a%b) ; } //////////////////////////////////////////////////////////////////////////////////// public static int lcm(int a, int b ,int c , int d ) { int temp = lcm(a,b , c) ; int ans = lcm(temp ,d ) ; return ans ; } /////////////////////////////////////////////////////////////////////////////////////////// public static int lcm(int a, int b ,int c ) { int temp = lcm(a,b) ; int ans = lcm(temp ,c) ; return ans ; } //////////////////////////////////////////////////////////////////////////////////////// public static int lcm(int a , int b ) { int gc = gcd(a,b); return (a*b)/gc ; } public static long lcm(long a , long b ) { long gc = gcd(a,b); return (a*b)/gc ; } /////////////////////////////////////////////////////////////////////////////////////////// static boolean isPrime(long n) { if(n==1) { return false ; } boolean ans = true ; for(long i = 2L; i*i <= n ;i++) { if(n% i ==0) { ans = false ;break ; } } return ans ; } /////////////////////////////////////////////////////////////////////////// static int sieve = 1000000 ; static boolean[] prime = new boolean[sieve + 1] ; public static void sieveOfEratosthenes() { // FALSE == prime // TRUE == COMPOSITE // FALSE== 1 // time complexity = 0(NlogLogN)== o(N) // gives prime nos bw 1 to N for(int i = 4; i<= sieve ; i++) { prime[i] = true ; i++ ; } for(int p = 3; p*p <= sieve; p++) { if(prime[p] == false) { for(int i = p*p; i <= sieve; i += p) prime[i] = true; } p++ ; } } /////////////////////////////////////////////////////////////////////////////////// public static void sortD(int[] arr , int s , int e) { sort(arr ,s , e) ; int i =s ; int j = e ; while( i < j) { int temp = arr[i] ; arr[i] =arr[j] ; arr[j] = temp ; i++ ; j-- ; } return ; } public static void sortD(long[] arr , int s , int e) { sort(arr ,s , e) ; int i =s ; int j = e ; while( i < j) { long temp = arr[i] ; arr[i] =arr[j] ; arr[j] = temp ; i++ ; j-- ; } return ; } ///////////////////////////////////////////////////////////////////////////////////////// public static long countSubarraysSumToK(long[] arr ,long sum ) { HashMap<Long,Long> map = new HashMap<>() ; int n = arr.length ; long prefixsum = 0 ; long count = 0L ; for(int i = 0; i < n ; i++) { prefixsum = prefixsum + arr[i] ; if(sum == prefixsum)count = count+1 ; if(map.containsKey(prefixsum -sum)) { count = count + map.get(prefixsum -sum) ; } if(map.containsKey(prefixsum )) { map.put(prefixsum , map.get(prefixsum) +1 ); } else{ map.put(prefixsum , 1L ); } } return count ; } /////////////////////////////////////////////////////////////////////////////////////////////// // KMP ALGORITHM : TIME COMPL:O(N+M) // FINDS THE OCCURENCES OF PATTERN AS A SUBSTRING IN STRING //RETURN THE ARRAYLIST OF INDEXES // IF SIZE OF LIST IS ZERO MEANS PATTERN IS NOT PRESENT IN STRING public static ArrayList<Integer> kmpAlgorithm(String str , String pat) { ArrayList<Integer> list =new ArrayList<>(); int n = str.length() ; int m = pat.length() ; String q = pat + "#" + str ; int[] lps =new int[n+m+1] ; longestPefixSuffix(lps, q,(n+m+1)) ; for(int i =m+1 ; i < (n+m+1) ; i++ ) { if(lps[i] == m) { list.add(i-2*m) ; } } return list ; } public static void longestPefixSuffix(int[] lps ,String str , int n) { lps[0] = 0 ; for(int i = 1 ; i<= n-1; i++) { int l = lps[i-1] ; while( l > 0 && str.charAt(i) != str.charAt(l)) { l = lps[l-1] ; } if(str.charAt(i) == str.charAt(l)) { l++ ; } lps[i] = l ; } } /////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////// // CALCULATE TOTIENT Fn FOR ALL VALUES FROM 1 TO n // TOTIENT(N) = count of nos less than n and grater than 1 whose gcd with n is 1 // or n and the no will be coprime in nature //time : O(n*(log(logn))) public static void eulerTotientFunction(int[] arr ,int n ) { for(int i = 1; i <= n ;i++)arr[i] =i ; for(int i= 2 ; i<= n ;i++) { if(arr[i] == i) { arr[i] =i-1 ; for(int j =2*i ; j<= n ; j+= i ) { arr[j] = (arr[j]*(i-1))/i ; } } } return ; } ///////////////////////////////////////////////////////////////////////////////////////////// public static long nCr(int n,int k) { long ans=1L; k=k>n-k?n-k:k; int j=1; for(;j<=k;j++,n--) { if(n%j==0) { ans*=n/j; }else if(ans%j==0) { ans=ans/j*n; }else { ans=(ans*n)/j; } } return ans; } /////////////////////////////////////////////////////////////////////////////////////////// public static ArrayList<Integer> allFactors(int n) { ArrayList<Integer> list = new ArrayList<>() ; for(int i = 1; i*i <= n ;i++) { if( n % i == 0) { if(i*i == n) { list.add(i) ; } else{ list.add(i) ; list.add(n/i) ; } } } return list ; } public static ArrayList<Long> allFactors(long n) { ArrayList<Long> list = new ArrayList<>() ; for(long i = 1L; i*i <= n ;i++) { if( n % i == 0) { if(i*i == n) { list.add(i) ; } else{ list.add(i) ; list.add(n/i) ; } } } return list ; } //////////////////////////////////////////////////////////////////////////////////////////////////// static final int MAXN = 10000001; static int spf[] = new int[MAXN]; static void sieve() { spf[1] = 1; for (int i=2; i<MAXN; i++) spf[i] = i; for (int i=4; i<MAXN; i+=2) spf[i] = 2; for (int i=3; i*i<MAXN; i++) { if (spf[i] == i) { for (int j=i*i; j<MAXN; j+=i) if (spf[j]==j) spf[j] = i; } } } // The above code works well for n upto the order of 10^7. // Beyond this we will face memory issues. // Time Complexity: The precomputation for smallest prime factor is done in O(n log log n) // using sieve. // Where as in the calculation step we are dividing the number every time by // the smallest prime number till it becomes 1. // So, let’s consider a worst case in which every time the SPF is 2 . // Therefore will have log n division steps. // Hence, We can say that our Time Complexity will be O(log n) in worst case. static Vector<Integer> getFactorization(int x) { Vector<Integer> ret = new Vector<>(); while (x != 1) { ret.add(spf[x]); x = x / spf[x]; } return ret; } ////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////// public static void merge(int arr[], int l, int m, int r) { // Find sizes of two subarrays to be merged int n1 = m - l + 1; int n2 = r - m; /* Create temp arrays */ int L[] = new int[n1]; int R[] = new int[n2]; //Copy data to temp arrays for (int i=0; i<n1; ++i) L[i] = arr[l + i]; for (int j=0; j<n2; ++j) R[j] = arr[m + 1+ j]; /* Merge the temp arrays */ // Initial indexes of first and second subarrays int i = 0, j = 0; // Initial index of merged subarry array int k = l; while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } /* Copy remaining elements of L[] if any */ while (i < n1) { arr[k] = L[i]; i++; k++; } /* Copy remaining elements of R[] if any */ while (j < n2) { arr[k] = R[j]; j++; k++; } } // Main function that sorts arr[l..r] using // merge() public static void sort(int arr[], int l, int r) { if (l < r) { // Find the middle point int m = (l+r)/2; // Sort first and second halves sort(arr, l, m); sort(arr , m+1, r); // Merge the sorted halves merge(arr, l, m, r); } } public static void sort(long arr[], int l, int r) { if (l < r) { // Find the middle point int m = (l+r)/2; // Sort first and second halves sort(arr, l, m); sort(arr , m+1, r); // Merge the sorted halves merge(arr, l, m, r); } } public static void merge(long arr[], int l, int m, int r) { // Find sizes of two subarrays to be merged int n1 = m - l + 1; int n2 = r - m; /* Create temp arrays */ long L[] = new long[n1]; long R[] = new long[n2]; //Copy data to temp arrays for (int i=0; i<n1; ++i) L[i] = arr[l + i]; for (int j=0; j<n2; ++j) R[j] = arr[m + 1+ j]; /* Merge the temp arrays */ // Initial indexes of first and second subarrays int i = 0, j = 0; // Initial index of merged subarry array int k = l; while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } /* Copy remaining elements of L[] if any */ while (i < n1) { arr[k] = L[i]; i++; k++; } /* Copy remaining elements of R[] if any */ while (j < n2) { arr[k] = R[j]; j++; k++; } } ///////////////////////////////////////////////////////////////////////////////////////// public static long knapsack(int[] weight,long value[],int maxWeight){ int n= value.length ; //dp[i] stores the profit with KnapSack capacity "i" long []dp = new long[maxWeight+1]; //initially profit with 0 to W KnapSack capacity is 0 Arrays.fill(dp, 0); // iterate through all items for(int i=0; i < n; i++) //traverse dp array from right to left for(int j = maxWeight; j >= weight[i]; j--) dp[j] = Math.max(dp[j] , value[i] + dp[j - weight[i]]); /*above line finds out maximum of dp[j](excluding ith element value) and val[i] + dp[j-wt[i]] (including ith element value and the profit with "KnapSack capacity - ith element weight") */ return dp[maxWeight]; } /////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////// // to return max sum of any subarray in given array public static long kadanesAlgorithm(long[] arr) { long[] dp = new long[arr.length] ; dp[0] = arr[0] ; long max = dp[0] ; for(int i = 1; i < arr.length ; i++) { if(dp[i-1] > 0) { dp[i] = dp[i-1] + arr[i] ; } else{ dp[i] = arr[i] ; } if(dp[i] > max)max = dp[i] ; } return max ; } ///////////////////////////////////////////////////////////////////////////////////////////// public static long kadanesAlgorithm(int[] arr) { long[] dp = new long[arr.length] ; dp[0] = arr[0] ; long max = dp[0] ; for(int i = 1; i < arr.length ; i++) { if(dp[i-1] > 0) { dp[i] = dp[i-1] + arr[i] ; } else{ dp[i] = arr[i] ; } if(dp[i] > max)max = dp[i] ; } return max ; } /////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////// public static long binarySerachGreater(int[] arr , int start , int end , int val) { // fing total no of elements strictly grater than val in sorted array arr if(start > end)return 0 ; //Base case int mid = (start + end)/2 ; if(arr[mid] <=val) { return binarySerachGreater(arr,mid+1, end ,val) ; } else{ return binarySerachGreater(arr,start , mid -1,val) + end-mid+1 ; } } ////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////// //TO GENERATE ALL(DUPLICATE ALSO EXIST) PERMUTATIONS OF A STRING // JUST CALL generatePermutation( str, start, end) start :inclusive ,end : exclusive //Function for swapping the characters at position I with character at position j public static String swapString(String a, int i, int j) { char[] b =a.toCharArray(); char ch; ch = b[i]; b[i] = b[j]; b[j] = ch; return String.valueOf(b); } //Function for generating different permutations of the string public static void generatePermutation(String str, int start, int end) { //Prints the permutations if (start == end-1) System.out.println(str); else { for (int i = start; i < end; i++) { //Swapping the string by fixing a character str = swapString(str,start,i); //Recursively calling function generatePermutation() for rest of the characters generatePermutation(str,start+1,end); //Backtracking and swapping the characters again. str = swapString(str,start,i); } } } //////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////// public static long factMod(long n, long mod) { if (n <= 1) return 1; long ans = 1; for (int i = 1; i <= n; i++) { ans = (ans * i) % mod; } return ans; } ///////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////// public static long power(long x ,long n) { //time comp : o(logn) if(n==0)return 1L ; if(n==1)return x; long ans =1L ; while(n>0) { if(n % 2 ==1) { ans = ans *x ; } n /= 2 ; x = x*x ; } return ans ; } //////////////////////////////////////////////////////////////////////////////////////////////////// public static long powerMod(long x, long n, long mod) { //time comp : o(logn) if(n==0)return 1L ; if(n==1)return x; long ans = 1; while (n > 0) { if (n % 2 == 1) ans = (ans * x) % mod; x = (x * x) % mod; n /= 2; } return ans; } ////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////// /* lowerBound - finds largest element equal or less than value paased upperBound - finds smallest element equal or more than value passed if not present return -1; */ public static long lowerBound(long[] arr,long k) { long ans=-1; int start=0; int end=arr.length-1; while(start<=end) { int mid=(start+end)/2; if(arr[mid]<=k) { ans=arr[mid]; start=mid+1; } else { end=mid-1; } } return ans; } public static int lowerBound(int[] arr,int k) { int ans=-1; int start=0; int end=arr.length-1; while(start<=end) { int mid=(start+end)/2; if(arr[mid]<=k) { ans=arr[mid]; start=mid+1; } else { end=mid-1; } } return ans; } public static long upperBound(long[] arr,long k) { long ans=-1; int start=0; int end=arr.length-1; while(start<=end) { int mid=(start+end)/2; if(arr[mid]>=k) { ans=arr[mid]; end=mid-1; } else { start=mid+1; } } return ans; } public static int upperBound(int[] arr,int k) { int ans=-1; int start=0; int end=arr.length-1; while(start<=end) { int mid=(start+end)/2; if(arr[mid]>=k) { ans=arr[mid]; end=mid-1; } else { start=mid+1; } } return ans; } ////////////////////////////////////////////////////////////////////////////////////////// public static void printArray(int[] arr , int si ,int ei) { for(int i = si ; i <= ei ; i++) { out.print(arr[i] +" ") ; } } public static void printArrayln(int[] arr , int si ,int ei) { for(int i = si ; i <= ei ; i++) { out.print(arr[i] +" ") ; } out.println() ; } public static void printLArray(long[] arr , int si , int ei) { for(int i = si ; i <= ei ; i++) { out.print(arr[i] +" ") ; } } public static void printLArrayln(long[] arr , int si , int ei) { for(int i = si ; i <= ei ; i++) { out.print(arr[i] +" ") ; } out.println() ; } public static void printtwodArray(int[][] ans) { for(int i = 0; i< ans.length ; i++) { for(int j = 0 ; j < ans[0].length ; j++)out.print(ans[i][j] +" "); out.println() ; } out.println() ; } static long modPow(long a, long x, long p) { //calculates a^x mod p in logarithmic time. long res = 1; while(x > 0) { if( x % 2 != 0) { res = (res * a) % p; } a = (a * a) % p; x /= 2; } return res; } static long modInverse(long a, long p) { //calculates the modular multiplicative of a mod m. //(assuming p is prime). return modPow(a, p-2, p); } static long modBinomial(long n, long k, long p) { // calculates C(n,k) mod p (assuming p is prime). long numerator = 1; // n * (n-1) * ... * (n-k+1) for (int i=0; i<k; i++) { numerator = (numerator * (n-i) ) % p; } long denominator = 1; // k! for (int i=1; i<=k; i++) { denominator = (denominator * i) % p; } // numerator / denominator mod p. return ( numerator* modInverse(denominator,p) ) % p; } ///////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////// static ArrayList<Integer>[] tree ; // static long[] child; // static int mod= 1000000007 ; // static int[][] pre = new int[3001][3001]; // static int[][] suf = new int[3001][3001] ; //program to calculate noof nodes in subtree for every vertex including itself public static void countNoOfNodesInsubtree(int child ,int par , int[] dp) { int count = 1 ; for(int x : tree[child]) { if(x== par)continue ; countNoOfNodesInsubtree(x,child,dp) ; count= count + dp[x] ; } dp[child] = count ; } public static void depth(int child ,int par , int[] dp , int d ) { dp[child] =d ; for(int x : tree[child]) { if(x== par)continue ; depth(x,child,dp,d+1) ; } } public static void dfs(int sv , boolean[] vis) { vis[sv] = true ; for(int x : tree[sv]) { if( !vis[x]) { dfs(x ,vis) ; } } } ////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////// public static void solve() { FastReader scn = new FastReader() ; //Scanner scn = new Scanner(System.in); //int[] store = {2 ,3, 5 , 7 ,11 , 13 , 17 , 19 , 23 , 29 , 31 , 37 } ; // product of first 11 prime nos is greater than 10 ^ 12; //ArrayList<Integer> arr[] = new ArrayList[n] ; ArrayList<Integer> list = new ArrayList<>() ; ArrayList<Long> listl = new ArrayList<>() ; ArrayList<Integer> lista = new ArrayList<>() ; ArrayList<Integer> listb = new ArrayList<>() ; //ArrayList<String> lists = new ArrayList<>() ; HashMap<Integer,Integer> map = new HashMap<>() ; //HashMap<Long,Long> map = new HashMap<>() ; HashMap<Integer,Integer> map1 = new HashMap<>() ; HashMap<Integer,Integer> map2 = new HashMap<>() ; //HashMap<String,Integer> maps = new HashMap<>() ; //HashMap<Integer,Boolean> mapb = new HashMap<>() ; //HashMap<Point,Integer> point = new HashMap<>() ; // Set<Long> set = new HashSet<>() ; Set<Integer> set = new HashSet<>() ; Set<Integer> setx = new HashSet<>() ; Set<Integer> sety = new HashSet<>() ; StringBuilder sb =new StringBuilder("") ; //Collections.sort(list); //if(map.containsKey(arr[i]))map.put(arr[i] , map.get(arr[i]) +1 ) ; //else map.put(arr[i],1) ; // if(map.containsKey(temp))map.put(temp , map.get(temp) +1 ) ; // else map.put(temp,1) ; //int bit =Integer.bitCount(n); // gives total no of set bits in n; // Arrays.sort(arr, new Comparator<Pair>() { // @Override // public int compare(Pair a, Pair b) { // if (a.first != b.first) { // return a.first - b.first; // for increasing order of first // } // return a.second - b.second ; //if first is same then sort on second basis // } // }); int testcases = 1; //testcases = scn.nextInt() ; for(int testcase =1 ; testcase <= testcases ;testcase++) { //if(map.containsKey(arr[i]))map.put(arr[i],map.get(arr[i])+1) ;else map.put(arr[i],1) ; //if(map.containsKey(temp))map.put(temp,map.get(temp)+1) ;else map.put(temp,1) ; // int n = scn.nextInt() ;int m = scn.nextInt() ; // tree = new ArrayList[n] ; // for(int i = 0; i< n; i++) // { // tree[i] = new ArrayList<Integer>(); // } // for(int i = 0 ; i <= m-1 ; i++) // { // int fv = scn.nextInt()-1 ; int sv = scn.nextInt()-1 ; // tree[fv].add(sv) ; // tree[sv].add(fv) ; // } // boolean[] visited = new boolean[n] ; // int ans = 0 ; // for(int i = 0 ; i < n ; i++) // { // if(!visited[i]) // { // dfs(i , visited ) ; // ans++ ; // } // } int n = scn.nextInt() ;int k = scn.nextInt() ; int[] arr = new int[n] ; int i = 0 ; int s =1 ; int e = n ; int f = 0 ; // f-0 -s while(i < n) { if(f== 0) { arr[i] =s ; s++ ;i++ ; } else{ arr[i] = e ;e-- ; i++ ; } f =1-f ; } if( k % 2== 1) { sort(arr,k ,n-1) ; } else{ sortD(arr,k ,n-1) ; } printArrayln(arr,0,n-1) ; sb.delete(0 , sb.length()) ; list.clear() ;listb.clear() ; map.clear() ; map1.clear() ; map2.clear() ; set.clear() ;sety.clear() ; } // test case end loop out.flush() ; } // solve fn ends public static void main (String[] args) throws java.lang.Exception { solve() ; } } class Pair { int first ; int second ; @Override public String toString() { String ans = "" ; ans += this.first ; ans += " "; ans += this.second ; return ans ; } }
Java
["3 2", "3 1", "5 2"]
1 second
["1 3 2", "1 2 3", "1 3 2 4 5"]
NoteBy |x| we denote the absolute value of number x.
Java 11
standard input
[ "constructive algorithms", "implementation" ]
18b3d8f57ecc2b392c7b1708f75a477e
The single line of the input contains two space-separated positive integers n, k (1 ≤ k &lt; n ≤ 105).
1,200
Print n integers forming the permutation. If there are multiple answers, print any of them.
standard output
PASSED
9e0c5d8b8ab77b94bdf781b8e07e6dbc
train_001.jsonl
1414170000
Permutation p is an ordered set of integers p1,   p2,   ...,   pn, consisting of n distinct positive integers not larger than n. We'll denote as n the length of permutation p1,   p2,   ...,   pn.Your task is to find such permutation p of length n, that the group of numbers |p1 - p2|, |p2 - p3|, ..., |pn - 1 - pn| has exactly k distinct elements.
256 megabytes
//import com.sun.org.apache.xpath.internal.operations.String; import java.io.*; import java.util.*; public class scratch_25 { //static long count=0; static class Reader { static BufferedReader reader; static StringTokenizer tokenizer; /** * call this method to initialize reader for InputStream */ static void init(InputStream input) { reader = new BufferedReader( new InputStreamReader(input)); tokenizer = new StringTokenizer(""); } /** * get next word */ static String next() throws IOException { while (!tokenizer.hasMoreTokens()) { //TODO add check for eof if necessary tokenizer = new StringTokenizer( reader.readLine()); } return tokenizer.nextToken(); } static int nextInt() throws IOException { return Integer.parseInt(next()); } static double nextDouble() throws IOException { return Double.parseDouble(next()); } static long nextLong() throws IOException { return Long.parseLong(next()); } } public static class Graph{ public static class Vertex{ HashMap<Integer,Integer> nb= new HashMap<>(); // for neighbours of each vertex } public static HashMap<Integer,Vertex> vt; // for vertices(all) public Graph(){ vt= new HashMap<>(); } public static int numVer(){ return vt.size(); } public static boolean contVer(int ver){ return vt.containsKey(ver); } public static void addVer(int ver){ Vertex v= new Vertex(); vt.put(ver,v); } public static int numEdg(){ int count=0; ArrayList<Integer> vrtc= new ArrayList<>(vt.keySet()); for (int i = 0; i <vrtc.size() ; i++) { count+=(vt.get(vrtc.get(i))).nb.size(); } return count/2; } public static boolean contEdg(int ver1, int ver2){ if(vt.get(ver1)==null || vt.get(ver2)==null){ return false; } Vertex v= vt.get(ver1); if(v.nb.containsKey(ver2)){ return true; } return false; } public static void addEdge(int ver1, int ver2, int weight){ if(!vt.containsKey(ver1) || !vt.containsKey(ver2)){ return; } Vertex v1= vt.get(ver1); Vertex v2= vt.get(ver2); v1.nb.put(ver2,weight); // if previously there is an edge, then this replaces that edge v2.nb.put(ver1,weight); } public static void delEdge(int ver1, int ver2){ if(!vt.containsKey(ver1) || !vt.containsKey(ver2)){ return; } vt.get(ver1).nb.remove(ver2); vt.get(ver2).nb.remove(ver1); } public static void delVer(int ver){ if(!vt.containsKey(ver)){ return; } Vertex v1= vt.get(ver); ArrayList<Integer> arr= new ArrayList<>(v1.nb.keySet()); for (int i = 0; i <arr.size() ; i++) { int s= arr.get(i); vt.get(s).nb.remove(ver); } vt.remove(ver); } public class Pair{ int vname; ArrayList<Integer> psf= new ArrayList<>(); // path so far int dis; int col; } public HashMap<Integer,Integer> bfs(int src){ HashMap<Integer, Boolean> prcd= new HashMap<>(); // jo jo ho chuke hain unke liye HashMap<Integer, Integer> ans= new HashMap<>(); LinkedList<Pair> queue= new LinkedList<>(); // for bfs queue Pair strtp= new Pair(); strtp.vname= src; ArrayList<Integer> ar= new ArrayList<>(); ar.add(src); strtp.psf= ar; strtp.dis=0; queue.addLast(strtp); while(!queue.isEmpty()){ Pair rp = queue.removeFirst(); if(prcd.containsKey(rp.vname)){ continue; } prcd.put(rp.vname,true); ans.put(rp.vname,rp.dis); // if(contEdg(rp.vname,dst)){ // return true; // } Vertex a= vt.get(rp.vname); ArrayList<Integer> arr= new ArrayList<>(a.nb.keySet()); for (int i = 0; i <arr.size() ; i++) { int s= arr.get(i); if(!prcd.containsKey(s)){ Pair np = new Pair(); np.vname= s; np.dis+=rp.dis+a.nb.get(s); np.psf.addAll(rp.psf); np.psf.add(s); // np.psf.add(s); // np.psf= rp.psf+" "+s; queue.addLast(np); } } } return ans; // return false; } public HashMap<Integer,Integer> dfs(int src){ HashMap<Integer, Boolean> prcd= new HashMap<>(); // jo jo ho chuke hain unke liye HashMap<Integer, Integer> ans= new HashMap<>(); LinkedList<Pair> stack= new LinkedList<>(); // for bfs queue Pair strtp= new Pair(); strtp.vname= src; ArrayList<Integer> ar= new ArrayList<>(); ar.add(src); strtp.psf= ar; strtp.dis=0; stack.addFirst(strtp); while(!stack.isEmpty()){ Pair rp = stack.removeFirst(); if(prcd.containsKey(rp.vname)){ continue; } prcd.put(rp.vname,true); ans.put(rp.vname,rp.dis); // if(contEdg(rp.vname,dst)){ // return true; // } Vertex a= vt.get(rp.vname); ArrayList<Integer> arr= new ArrayList<>(a.nb.keySet()); for (int i = 0; i <arr.size() ; i++) { int s= arr.get(i); if(!prcd.containsKey(s)){ Pair np = new Pair(); np.vname= s; np.dis+=rp.dis+a.nb.get(s); np.psf.addAll(rp.psf); np.psf.add(s); // np.psf.add(s); // np.psf= rp.psf+" "+s; stack.addFirst(np); } } } return ans; // return false; } public boolean isCycle(){ HashMap<Integer, Boolean> prcd= new HashMap<>(); // jo jo ho chuke hain unke liye // HashMap<Integer, Integer> ans= new HashMap<>(); LinkedList<Pair> queue= new LinkedList<>(); // for bfs queue ArrayList<Integer> keys = new ArrayList<>(vt.keySet()); for (int i = 0; i <keys.size(); i++) { int cur= keys.get(i); if(prcd.containsKey(cur)){ continue; } Pair sp = new Pair(); sp.vname= cur; ArrayList<Integer> as= new ArrayList<>(); as.add(cur); sp.psf= as; queue.addLast(sp); while(!queue.isEmpty()){ Pair rp= queue.removeFirst(); if(prcd.containsKey(rp.vname)){ return true; } prcd.put(rp.vname,true); Vertex v1= vt.get(rp.vname); ArrayList<Integer> nbrs= new ArrayList<>(v1.nb.keySet()); for (int j = 0; j <nbrs.size() ; j++) { int u= nbrs.get(j); Pair np= new Pair(); np.vname= u; queue.addLast(np); } } } return false; } public ArrayList<ArrayList<Integer>> genConnctdComp(){ HashMap<Integer, Boolean> prcd= new HashMap<>(); // jo jo ho chuke hain unke liye ArrayList<ArrayList<Integer>> ans= new ArrayList<>(); // HashMap<Integer, Integer> ans= new HashMap<>(); LinkedList<Pair> queue= new LinkedList<>(); // for bfs queue // int con=-1; ArrayList<Integer> keys = new ArrayList<>(vt.keySet()); for (int i = 0; i <keys.size(); i++) { int cur= keys.get(i); if(prcd.containsKey(cur)){ //return true; continue; } ArrayList<Integer> fu= new ArrayList<>(); fu.add(cur); Pair sp = new Pair(); sp.vname= cur; ArrayList<Integer> as= new ArrayList<>(); as.add(cur); sp.psf= as; queue.addLast(sp); while(!queue.isEmpty()){ Pair rp= queue.removeFirst(); if(prcd.containsKey(rp.vname)){ //return true; continue; } prcd.put(rp.vname,true); fu.add(cur); Vertex v1= vt.get(rp.vname); ArrayList<Integer> nbrs= new ArrayList<>(); for (int j = 0; j <nbrs.size() ; j++) { int u= nbrs.get(j); Pair np= new Pair(); np.vname= u; queue.addLast(np); } } ans.add(fu); } //return false; return ans; } public boolean isBip(int src){ // only for connected graph HashMap<Integer,Integer> clr= new HashMap<>(); // colors are 1 and -1 LinkedList<Integer>q = new LinkedList<Integer>(); clr.put(src,1); q.add(src); while(!q.isEmpty()){ int u = q.getFirst(); q.pop(); ArrayList<Integer> arr= new ArrayList<>(vt.keySet()); for (int i = 0; i <arr.size() ; ++i) { int x= arr.get(i); if(vt.get(u).nb.containsKey(x) && !clr.containsKey(x)){ if(clr.get(u)==1){ clr.put(x,-1); } else{ clr.put(x,1); } q.push(x); } else if(vt.get(u).nb.containsKey(x) && (clr.get(x)==clr.get(u))){ return false; } } } return true; } public static void printGr() { ArrayList<Integer> arr= new ArrayList<>(vt.keySet()); for (int i = 0; i <arr.size() ; i++) { int ver= arr.get(i); Vertex v1= vt.get(ver); ArrayList<Integer> arr1= new ArrayList<>(v1.nb.keySet()); for (int j = 0; j <arr1.size() ; j++) { System.out.println(ver+"-"+arr1.get(j)+":"+v1.nb.get(arr1.get(j))); } } } } static class Cus implements Comparable<Cus>{ int size; int mon; int num; public Cus(int size,int mon,int num){ this.size=size; this.mon=mon; this.num=num; } @Override public int compareTo(Cus o){ if(this.mon!=o.mon){ return this.mon-o.mon;} else{ return o.size-this.size; } } } static class Table implements Comparable<Table>{ int go; int cum; int cost; public Table(int go,int cum,int cost){ this.go=go; this.cum=cum; this.cost=cost; } @Override public int compareTo(Table o){ if(this.go==o.go){ return this.cum-o.cum; } return this.go-o.go; } } static class Table1 implements Comparable<Table1>{ int go; int cum; int cost; public Table1(int go,int cum,int cost){ this.go=go; this.cum=cum; this.cost=cost; } @Override public int compareTo(Table1 o){ return this.cost-o.cost; }} public static void main(String[] args) throws IOException { Reader.init(System.in); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out)); // System.out.println(arr); int n= Reader.nextInt(); int k= Reader.nextInt(); int arr[]= new int[n]; arr[0]=1; int a[]= new int[n+1]; int p=1; int mul=1; a[1]=1; while(k>=1){ arr[p]=arr[p-1]+k*mul; a[arr[p]]=1; k--; mul=-1*mul; p++; } int ptr=arr[p-1]; for (int i = p; i <n ; i++) { for (int j = ptr; j <n+1 ; j++) { if(a[j]==0){ a[j]=1; ptr=j; break; } } arr[i]=ptr; } // System.out.println(Arrays.toString(arr)); for (int i = 0; i <n ; i++) { out.append(arr[i]+" "); } out.flush(); out.close(); } static long gcd(long a, long b) { if (a == 0) return b; return gcd(b % a, a); } static long gcd1(long a, long b) { // Everything divides 0 if (a == 0) return b; if (b == 0) return a; // base case if (a == b) return a; // a is greater //count++; if (a > b){ return gcd(a-b, b); } return gcd(a, b-a); } // method to return LCM of two numbers static long lcm(long a, long b) { return (a*b)/gcd(a, b); } // Driver method static int partition(long arr[],long arr1[], int low, int high) { long pivot = arr[high]; int i = (low-1); // index of smaller element for (int j=low; j<high; j++) { // If current element is smaller than the pivot if (arr[j] < pivot) { i++; // swap arr[i] and arr[j] long temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; long temp1=arr1[i]; arr1[i]=arr1[j]; arr1[j]=temp1; } } // swap arr[i+1] and arr[high] (or pivot) long temp = arr[i+1]; arr[i+1] = arr[high]; arr[high] = temp; long temp1= arr1[i+1]; arr1[i+1]=arr1[high]; arr1[high]= temp1; return i+1; } /* The main function that implements QuickSort() arr[] --> Array to be sorted, low --> Starting index, high --> Ending index */ static void sort(long arr[],long arr1[], int low, int high) { if (low < high) { /* pi is partitioning index, arr[pi] is now at right place */ int pi = partition(arr,arr1, low, high); // Recursively sort elements before // partition and after partition sort(arr,arr1, low, pi-1); sort(arr,arr1, pi+1, high); } } public static ArrayList<Integer> Sieve(int n) { boolean arr[]= new boolean [n+1]; Arrays.fill(arr,true); arr[0]=false; arr[1]=false; for (int i = 2; i*i <=n ; i++) { if(arr[i]==true){ for (int j = 2; j <=n/i ; j++) { int u= i*j; arr[u]=false; }} } ArrayList<Integer> ans= new ArrayList<>(); for (int i = 0; i <n+1 ; i++) { if(arr[i]){ ans.add(i); } } return ans; } }
Java
["3 2", "3 1", "5 2"]
1 second
["1 3 2", "1 2 3", "1 3 2 4 5"]
NoteBy |x| we denote the absolute value of number x.
Java 11
standard input
[ "constructive algorithms", "implementation" ]
18b3d8f57ecc2b392c7b1708f75a477e
The single line of the input contains two space-separated positive integers n, k (1 ≤ k &lt; n ≤ 105).
1,200
Print n integers forming the permutation. If there are multiple answers, print any of them.
standard output
PASSED
e51c5895bdf8c85774f8c6180ff705b4
train_001.jsonl
1414170000
Permutation p is an ordered set of integers p1,   p2,   ...,   pn, consisting of n distinct positive integers not larger than n. We'll denote as n the length of permutation p1,   p2,   ...,   pn.Your task is to find such permutation p of length n, that the group of numbers |p1 - p2|, |p2 - p3|, ..., |pn - 1 - pn| has exactly k distinct elements.
256 megabytes
import java.util.Arrays; import java.util.Scanner; public class Test { public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int k = sc.nextInt(); int a[] = new int[n+1]; for (int i = 0, j = 1; i < n - 1; i += 2, j++) { a[i] = j; a[i + 1] = n - j + 1; } if(n % 2 != 0) a[n - 1] = n/2 + 1; // for(int i = 0;i < n;i++) { // if(i > 0) // System.out.print(" "); // System.out.print(a[i]); // } // System.out.println(); a[n] = n/2 + 1; int l = Math.min(a[k], a[k+1]); int m = Math.max(a[k], a[k+1]); // System.out.println(a[k - 1]); if(a[k-1] - 1 != m) for(int i = l, id = k;i <= m;i++, id++) { a[id] = i; } else for(int i = m, id = k;i >= l;i--, id++) { a[id] = i; } for(int i = 0;i < n;i++) { if(i > 0) System.out.print(" "); System.out.print(a[i]); } } }
Java
["3 2", "3 1", "5 2"]
1 second
["1 3 2", "1 2 3", "1 3 2 4 5"]
NoteBy |x| we denote the absolute value of number x.
Java 11
standard input
[ "constructive algorithms", "implementation" ]
18b3d8f57ecc2b392c7b1708f75a477e
The single line of the input contains two space-separated positive integers n, k (1 ≤ k &lt; n ≤ 105).
1,200
Print n integers forming the permutation. If there are multiple answers, print any of them.
standard output
PASSED
d626362e8ea556ffa21bcbf07d6e74a9
train_001.jsonl
1266580800
In the popular spreadsheets systems (for example, in Excel) the following numeration of columns is used. The first column has number A, the second — number B, etc. till column 26 that is marked by Z. Then there are two-letter numbers: column 27 has number AA, 28 — AB, column 52 is marked by AZ. After ZZ there follow three-letter numbers, etc.The rows are marked by integer numbers starting with 1. The cell name is the concatenation of the column and the row numbers. For example, BC23 is the name for the cell that is in column 55, row 23. Sometimes another numeration system is used: RXCY, where X and Y are integer numbers, showing the column and the row numbers respectfully. For instance, R23C55 is the cell from the previous example.Your task is to write a program that reads the given sequence of cell coordinates and produce each item written according to the rules of another numeration system.
64 megabytes
import java.util.Scanner; public class Forces1B { public static void main(String[] args) { Scanner input = new Scanner(System.in); int numCycles = Integer.parseInt(input.nextLine()); for(int i = 0; i < numCycles; i++){ String line = input.nextLine(); if(line.charAt(1) > 48 && line.charAt(1) < 58 && line.length() != 2 && line.charAt(0) == 82 && line.contains("C")){ System.out.println(convertNormalToNew(line)); }else{ System.out.println(convertNewToNormal(line)); } } } public static String convertNormalToNew(String line){ String converse = ""; String[] coordinates = line.split("[^0-9]"); int col = Integer.parseInt(coordinates[2]); String row = coordinates[1]; String colString = ""; int num = 0; while(col > 0){ int colRemainder = col % 26; colString = numToLetterZ(colRemainder) + colString; if(col % 26 == 0){ col -= 1; col /= 26; }else{ col /= 26; } num++; } converse = colString + row; return converse; } public static String numToLetter(int num){ if(num == 0){ return "A"; } return String.valueOf((char)(num + 64)); } public static String numToLetterZ(int num){ if(num == 0){ return "Z"; } return String.valueOf((char)(num + 64)); } public static String convertNewToNormal(String line){ String converse = ""; String colStr = line.replaceAll("[0-9]", ""); String rowStr = line.replaceAll("[A-Z]", ""); converse += "R" + rowStr; int col = 0; for(int i = colStr.length(); i >= 0; i--){ int numForThisCol = line.charAt(i) - 64; col += numForThisCol * Math.pow(26, colStr.length() - i - 1); } converse += "C" + col; return converse; } }
Java
["2\nR23C55\nBC23"]
10 seconds
["BC23\nR23C55"]
null
Java 11
standard input
[ "implementation", "math" ]
910c0e650d48af22fa51ab05e8123709
The first line of the input contains integer number n (1 ≤ n ≤ 105), the number of coordinates in the test. Then there follow n lines, each of them contains coordinates. All the coordinates are correct, there are no cells with the column and/or the row numbers larger than 106 .
1,600
Write n lines, each line should contain a cell coordinates in the other numeration system.
standard output
PASSED
234733a0ad4b612800d1e3b9a823064b
train_001.jsonl
1266580800
In the popular spreadsheets systems (for example, in Excel) the following numeration of columns is used. The first column has number A, the second — number B, etc. till column 26 that is marked by Z. Then there are two-letter numbers: column 27 has number AA, 28 — AB, column 52 is marked by AZ. After ZZ there follow three-letter numbers, etc.The rows are marked by integer numbers starting with 1. The cell name is the concatenation of the column and the row numbers. For example, BC23 is the name for the cell that is in column 55, row 23. Sometimes another numeration system is used: RXCY, where X and Y are integer numbers, showing the column and the row numbers respectfully. For instance, R23C55 is the cell from the previous example.Your task is to write a program that reads the given sequence of cell coordinates and produce each item written according to the rules of another numeration system.
64 megabytes
import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class QuickSort { public static void main(String[] args) { Pattern pattern1 = Pattern.compile("^R(\\d+)C(\\d+)"); Pattern pattern2 = Pattern.compile("(^[A-Z]+)(\\d+)"); Scanner scanner = new Scanner(System.in); int number = scanner.nextInt(); scanner.nextLine(); String result = ""; for (int i = 0; i < number; ++i){ String checkLine = scanner.nextLine(); Matcher matcher1 = pattern1.matcher(checkLine); Matcher matcher2 = pattern2.matcher(checkLine); if (matcher1.find()){ result = match1(matcher1.group(1), matcher1.group(2)); } else if (matcher2.find()) { result = match2(matcher2.group(1), matcher2.group(2)); } System.out.println(result); } } public static String match1(String row, String col){ int column = Integer.parseInt(col); return toAlphabet(column) + row; } public static String match2(String col, String row){ return "R" + row + "C" + toDigits(col); } public static String toAlphabet(int number){ StringBuilder result = new StringBuilder(); char[] alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray(); do { number--; result.append(alphabet[number % 26]); number /= 26; } while (number > 0); return result.reverse().toString(); } public static int toDigits(String letters){ int result = 0; String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; int length = letters.length(); for (int i = 0; i < length; i++){ char c = letters.charAt(i); int d = alphabet.indexOf(c) + 1; result = result * 26 + d; } return result; } }
Java
["2\nR23C55\nBC23"]
10 seconds
["BC23\nR23C55"]
null
Java 11
standard input
[ "implementation", "math" ]
910c0e650d48af22fa51ab05e8123709
The first line of the input contains integer number n (1 ≤ n ≤ 105), the number of coordinates in the test. Then there follow n lines, each of them contains coordinates. All the coordinates are correct, there are no cells with the column and/or the row numbers larger than 106 .
1,600
Write n lines, each line should contain a cell coordinates in the other numeration system.
standard output
PASSED
ac623925cdd81a73a77347ff6b3aa8cb
train_001.jsonl
1266580800
In the popular spreadsheets systems (for example, in Excel) the following numeration of columns is used. The first column has number A, the second — number B, etc. till column 26 that is marked by Z. Then there are two-letter numbers: column 27 has number AA, 28 — AB, column 52 is marked by AZ. After ZZ there follow three-letter numbers, etc.The rows are marked by integer numbers starting with 1. The cell name is the concatenation of the column and the row numbers. For example, BC23 is the name for the cell that is in column 55, row 23. Sometimes another numeration system is used: RXCY, where X and Y are integer numbers, showing the column and the row numbers respectfully. For instance, R23C55 is the cell from the previous example.Your task is to write a program that reads the given sequence of cell coordinates and produce each item written according to the rules of another numeration system.
64 megabytes
import java.util.Scanner; public class Spreadsheets { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int n = scan.nextInt(); while (--n >= 0) { String coord = scan.next(); int cIndex = coord.indexOf('C'); if (coord.startsWith("R") && Character.isDigit(coord.charAt(1)) && cIndex != -1) { int row = Integer.parseInt(coord.substring(1, cIndex)); int col = Integer.parseInt(coord.substring(cIndex + 1)); StringBuilder colStr = new StringBuilder(); while (col > 0) { colStr.insert(0, (char)((col - 1) % 26 + 'A')); col = (col - 1) / 26; } System.out.println(colStr.toString() + row); } else { int split = 1; while (!Character.isDigit(coord.charAt(split))) split++; String colStr = coord.substring(0, split); int row = Integer.parseInt(coord.substring(split)); int col = 0; for (int i = 0; i < colStr.length(); i++) { col *= 26; col += colStr.charAt(i) - 'A' + 1; } System.out.println("R" + row + "C" + col); } } } }
Java
["2\nR23C55\nBC23"]
10 seconds
["BC23\nR23C55"]
null
Java 11
standard input
[ "implementation", "math" ]
910c0e650d48af22fa51ab05e8123709
The first line of the input contains integer number n (1 ≤ n ≤ 105), the number of coordinates in the test. Then there follow n lines, each of them contains coordinates. All the coordinates are correct, there are no cells with the column and/or the row numbers larger than 106 .
1,600
Write n lines, each line should contain a cell coordinates in the other numeration system.
standard output
PASSED
ce17bf08d7b407be5cfc603eea20fdd2
train_001.jsonl
1266580800
In the popular spreadsheets systems (for example, in Excel) the following numeration of columns is used. The first column has number A, the second — number B, etc. till column 26 that is marked by Z. Then there are two-letter numbers: column 27 has number AA, 28 — AB, column 52 is marked by AZ. After ZZ there follow three-letter numbers, etc.The rows are marked by integer numbers starting with 1. The cell name is the concatenation of the column and the row numbers. For example, BC23 is the name for the cell that is in column 55, row 23. Sometimes another numeration system is used: RXCY, where X and Y are integer numbers, showing the column and the row numbers respectfully. For instance, R23C55 is the cell from the previous example.Your task is to write a program that reads the given sequence of cell coordinates and produce each item written according to the rules of another numeration system.
64 megabytes
import java.util.Scanner; public class Spreadsheet{ public static void main(String[] args) { Scanner scan = new Scanner(System.in); int n = scan.nextInt(); while (--n >= 0) { String coord = scan.next(); int cIndex = coord.indexOf('C'); if (coord.startsWith("R") && Character.isDigit(coord.charAt(1)) && cIndex != -1) { int row = Integer.parseInt(coord.substring(1, cIndex)); int col = Integer.parseInt(coord.substring(cIndex + 1)); StringBuilder colStr = new StringBuilder(); while (col > 0) { colStr.insert(0, (char)((col - 1) % 26 + 'A')); col = (col - 1) / 26; } System.out.println(colStr.toString() + row); } else { int split = 1; while (!Character.isDigit(coord.charAt(split))) split++; String colStr = coord.substring(0, split); int row = Integer.parseInt(coord.substring(split)); int col = 0; for (int i = 0; i < colStr.length(); i++) { col *= 26; col += colStr.charAt(i) - 'A' + 1; } System.out.println("R" + row + "C" + col); } } } }
Java
["2\nR23C55\nBC23"]
10 seconds
["BC23\nR23C55"]
null
Java 11
standard input
[ "implementation", "math" ]
910c0e650d48af22fa51ab05e8123709
The first line of the input contains integer number n (1 ≤ n ≤ 105), the number of coordinates in the test. Then there follow n lines, each of them contains coordinates. All the coordinates are correct, there are no cells with the column and/or the row numbers larger than 106 .
1,600
Write n lines, each line should contain a cell coordinates in the other numeration system.
standard output
PASSED
33c0bc9a0ef55ba2cc377072445fd301
train_001.jsonl
1266580800
In the popular spreadsheets systems (for example, in Excel) the following numeration of columns is used. The first column has number A, the second — number B, etc. till column 26 that is marked by Z. Then there are two-letter numbers: column 27 has number AA, 28 — AB, column 52 is marked by AZ. After ZZ there follow three-letter numbers, etc.The rows are marked by integer numbers starting with 1. The cell name is the concatenation of the column and the row numbers. For example, BC23 is the name for the cell that is in column 55, row 23. Sometimes another numeration system is used: RXCY, where X and Y are integer numbers, showing the column and the row numbers respectfully. For instance, R23C55 is the cell from the previous example.Your task is to write a program that reads the given sequence of cell coordinates and produce each item written according to the rules of another numeration system.
64 megabytes
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); for(int i=0; i<t; i++) { String s = sc.next(); int indexOfC = s.indexOf('C'); if(s.charAt(0)=='R' && s.charAt(1)-'0'<=9 && indexOfC>0) { int row, col; row = Integer.parseInt(s.substring(1, indexOfC)); col = Integer.parseInt(s.substring(indexOfC+1)); StringBuilder colStr = new StringBuilder(); while (col > 0) { colStr.insert(0, (char)((col - 1) % 26 + 'A')); col = (col - 1) / 26; } System.out.println(colStr.toString()+""+row); } else { int k,row,col = 0; for(k=0; s.charAt(k)-'A'>=0; k++) { col *= 26; col += s.charAt(k) - 'A' + 1; } row = Integer.parseInt(s.substring(k)); System.out.println("R"+row+"C"+col); } } } }
Java
["2\nR23C55\nBC23"]
10 seconds
["BC23\nR23C55"]
null
Java 11
standard input
[ "implementation", "math" ]
910c0e650d48af22fa51ab05e8123709
The first line of the input contains integer number n (1 ≤ n ≤ 105), the number of coordinates in the test. Then there follow n lines, each of them contains coordinates. All the coordinates are correct, there are no cells with the column and/or the row numbers larger than 106 .
1,600
Write n lines, each line should contain a cell coordinates in the other numeration system.
standard output
PASSED
552962128fd382d97c364b48d9420fdf
train_001.jsonl
1266580800
In the popular spreadsheets systems (for example, in Excel) the following numeration of columns is used. The first column has number A, the second — number B, etc. till column 26 that is marked by Z. Then there are two-letter numbers: column 27 has number AA, 28 — AB, column 52 is marked by AZ. After ZZ there follow three-letter numbers, etc.The rows are marked by integer numbers starting with 1. The cell name is the concatenation of the column and the row numbers. For example, BC23 is the name for the cell that is in column 55, row 23. Sometimes another numeration system is used: RXCY, where X and Y are integer numbers, showing the column and the row numbers respectfully. For instance, R23C55 is the cell from the previous example.Your task is to write a program that reads the given sequence of cell coordinates and produce each item written according to the rules of another numeration system.
64 megabytes
import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Solution { public static Pattern numbersPattern = Pattern.compile("^R(\\d+)C(\\d+)$"); public static Pattern lettersPattern = Pattern.compile("^([A-Z]+)(\\d+)$"); public static int[] numbersBase = {1, 26, 676, 17576, 456976}; public static void main(String[] args) { Scanner s = new Scanner(System.in); int t = s.nextInt(); String testCase; Matcher numbersMatcher, lettersMatcher; while (t-- > 0) { testCase = s.next(); numbersMatcher = numbersPattern.matcher(testCase); lettersMatcher = lettersPattern.matcher(testCase); if (numbersMatcher.find()) System.out.println(numbersToLetters(numbersMatcher.group(1), numbersMatcher.group(2))); else if (lettersMatcher.find()) System.out.println(lettersToNumbers(lettersMatcher.group(2), lettersMatcher.group(1))); } } public static String numbersToLetters(String row, String cols) { int colValue = Integer.parseInt(cols); String resultCol = ""; int remainder = 0; while (colValue > 0){ remainder = (colValue -1) % 26; colValue = (colValue -1) / 26; resultCol = (char)(65 +remainder) +resultCol; } return resultCol + row; } public static String lettersToNumbers(String row, String cols) { int resultCols = 0; int j = 0; for (int i = cols.length() - 1; i >= 0; i--) { resultCols += ((cols.charAt(i) - 'A') + 1) * numbersBase[j++]; } return "R" + row + "C" + resultCols; } }
Java
["2\nR23C55\nBC23"]
10 seconds
["BC23\nR23C55"]
null
Java 11
standard input
[ "implementation", "math" ]
910c0e650d48af22fa51ab05e8123709
The first line of the input contains integer number n (1 ≤ n ≤ 105), the number of coordinates in the test. Then there follow n lines, each of them contains coordinates. All the coordinates are correct, there are no cells with the column and/or the row numbers larger than 106 .
1,600
Write n lines, each line should contain a cell coordinates in the other numeration system.
standard output
PASSED
ab61961ad6989d7036c75573959d3f87
train_001.jsonl
1266580800
In the popular spreadsheets systems (for example, in Excel) the following numeration of columns is used. The first column has number A, the second — number B, etc. till column 26 that is marked by Z. Then there are two-letter numbers: column 27 has number AA, 28 — AB, column 52 is marked by AZ. After ZZ there follow three-letter numbers, etc.The rows are marked by integer numbers starting with 1. The cell name is the concatenation of the column and the row numbers. For example, BC23 is the name for the cell that is in column 55, row 23. Sometimes another numeration system is used: RXCY, where X and Y are integer numbers, showing the column and the row numbers respectfully. For instance, R23C55 is the cell from the previous example.Your task is to write a program that reads the given sequence of cell coordinates and produce each item written according to the rules of another numeration system.
64 megabytes
import java.util.Scanner; public class spreadsheets { public static void main(String[] args){ Scanner scan = new Scanner(System.in); int n = scan.nextInt(); String str2 = scan.nextLine(); while(n-->0){ String str = scan.nextLine(); int i=0; int flag = 1; int dig = 0; int rb = 1; /*if(str.charAt(0)=='R' && i<str.length()){ while(i<str.length() && str.charAt(i)>=48 && str.charAt(i)<=57){ i++; } }*/ if(str.charAt(0)=='R' && str.charAt(1)=='C'){ flag = 1; } else if(str.charAt(0)=='R' && i<str.length()){ while(i<str.length()){ if(i<str.length() && str.charAt(i)>=48 && str.charAt(i)<=57 && rb==1) dig++; if(str.charAt(i)=='C' && dig>0 && rb==1){ flag = 0; rb = 0; } else if(rb==1) flag = 1; i++; } } if(str.charAt(0)=='R' && flag==0){ i=1; int row = 0; int col = 0; while(i<str.length() && str.charAt(i)>=48 && str.charAt(i)<=57){ row = row*10+(str.charAt(i)-48); i++; } i++; while(i<str.length() && str.charAt(i)>=48 && str.charAt(i)<=57){ col = col*10+(str.charAt(i)-48); i++; } String strCol = ""; while(col/26 != 0){ int rem = col%26; if(rem==0){ rem = 26; col = (col/26)-1; } else{ col = col/26; } char ch = (char)(rem+64); strCol += ch; } if(col!=0){ char ch = (char)(col+64); strCol += ch; } int length = strCol.length(); String reverse = ""; for (i = length - 1 ; i >= 0 ; i--) reverse = reverse + strCol.charAt(i); System.out.println(reverse+Integer.toString(row)); } else if(flag==1){ i=0; int col = 0; int row = 0; while(str.charAt(i)>=65 && str.charAt(i)<=90){ col = col*26+(str.charAt(i)-64); i++; } while(i<str.length() && str.charAt(i)>=48 && str.charAt(i)<=57){ row = row*10+(str.charAt(i)-48); i++; } System.out.println("R"+Integer.toString(row)+"C"+Integer.toString(col)); } } } }
Java
["2\nR23C55\nBC23"]
10 seconds
["BC23\nR23C55"]
null
Java 11
standard input
[ "implementation", "math" ]
910c0e650d48af22fa51ab05e8123709
The first line of the input contains integer number n (1 ≤ n ≤ 105), the number of coordinates in the test. Then there follow n lines, each of them contains coordinates. All the coordinates are correct, there are no cells with the column and/or the row numbers larger than 106 .
1,600
Write n lines, each line should contain a cell coordinates in the other numeration system.
standard output
PASSED
79243f6429ab800ea52460f863b6ecc4
train_001.jsonl
1266580800
In the popular spreadsheets systems (for example, in Excel) the following numeration of columns is used. The first column has number A, the second — number B, etc. till column 26 that is marked by Z. Then there are two-letter numbers: column 27 has number AA, 28 — AB, column 52 is marked by AZ. After ZZ there follow three-letter numbers, etc.The rows are marked by integer numbers starting with 1. The cell name is the concatenation of the column and the row numbers. For example, BC23 is the name for the cell that is in column 55, row 23. Sometimes another numeration system is used: RXCY, where X and Y are integer numbers, showing the column and the row numbers respectfully. For instance, R23C55 is the cell from the previous example.Your task is to write a program that reads the given sequence of cell coordinates and produce each item written according to the rules of another numeration system.
64 megabytes
import java.io.*; import java.util.StringTokenizer; public class B { static class Task { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); while ((n--) > 0) { String str = in.next(); char[] arr = str.toCharArray(); int type = 0; for (int i = 2; i < arr.length; i++) { if (Character.isDigit(arr[1]) && Character.isLetter(arr[i])) { type = 1; break; } } if (type == 0) { // 如BC23, 输出R23C55 int colNum = 0; int rowNum = 0; for (int i = 0; i < arr.length; i++) { if (Character.isDigit(arr[i])) { rowNum = Integer.parseInt(str.substring(i)); break; } colNum *= 26; colNum += arr[i] - 'A' + 1; } out.println("R" + rowNum + "C" + colNum); } else { // 如R23C55, 输出BC23 int rowNum = 0; int i; for (i = 1; i < arr.length; i++) { if (Character.isLetter(arr[i])) { break; } rowNum *= 10; rowNum += arr[i] - '0'; } int colNum = Integer.parseInt(str.substring(i + 1)); StringBuilder sb = new StringBuilder(); while (colNum > 0) { colNum--; sb.append((char)(colNum % 26 + 'A')); colNum /= 26; } out.println(sb.reverse().toString() + rowNum); } } } } private static void solve() { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); Task task = new Task(); task.solve(1, in, out); out.close(); } public static void main(String[] args) { new Thread(null, () -> solve(), "1", 1 << 26).start(); } static 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 int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } } }
Java
["2\nR23C55\nBC23"]
10 seconds
["BC23\nR23C55"]
null
Java 11
standard input
[ "implementation", "math" ]
910c0e650d48af22fa51ab05e8123709
The first line of the input contains integer number n (1 ≤ n ≤ 105), the number of coordinates in the test. Then there follow n lines, each of them contains coordinates. All the coordinates are correct, there are no cells with the column and/or the row numbers larger than 106 .
1,600
Write n lines, each line should contain a cell coordinates in the other numeration system.
standard output
PASSED
e3a39153dcaaca884d6660aadeb0a347
train_001.jsonl
1266580800
In the popular spreadsheets systems (for example, in Excel) the following numeration of columns is used. The first column has number A, the second — number B, etc. till column 26 that is marked by Z. Then there are two-letter numbers: column 27 has number AA, 28 — AB, column 52 is marked by AZ. After ZZ there follow three-letter numbers, etc.The rows are marked by integer numbers starting with 1. The cell name is the concatenation of the column and the row numbers. For example, BC23 is the name for the cell that is in column 55, row 23. Sometimes another numeration system is used: RXCY, where X and Y are integer numbers, showing the column and the row numbers respectfully. For instance, R23C55 is the cell from the previous example.Your task is to write a program that reads the given sequence of cell coordinates and produce each item written according to the rules of another numeration system.
64 megabytes
/*package whatever //do not write package name here */ import java.io.*; import java.util.*; public class GFG { public static void main (String[] args) { Scanner sc=new Scanner(System.in); long _a=sc.nextLong(); while(_a-->0) { String s=sc.next(); if(s.charAt(0)=='R' && Character.isDigit(s.charAt(1))&& s.indexOf("C")>-1) { String[] ss=s.split("C"); ss[0]=ss[0].trim(); String temp=""; long l=Long.parseLong(ss[1].trim()); while(l>26) { char c; if(l%26!=0){ c=(char)((l%26)+(int)64);l/=26;} else {c='Z';l-=1;l/=26;} temp=c+temp; } if(l!=0) { temp=((char)(l+64))+temp; } System.out.println(temp+ss[0].substring(1,ss[0].length())); } else { String ss=""; String ss1=""; for(int i=0;i<s.length();i++) { if(Character.isDigit(s.charAt(i))) { ss1+=s.charAt(i); } else ss+=s.charAt(i); } long c=0; int z=0; for(int i=ss.length()-1;i>=0;i--) { c+=Math.pow(26,z++)*(ss.charAt(i)-64); } System.out.println("R"+ss1+"C"+c); } } } }
Java
["2\nR23C55\nBC23"]
10 seconds
["BC23\nR23C55"]
null
Java 11
standard input
[ "implementation", "math" ]
910c0e650d48af22fa51ab05e8123709
The first line of the input contains integer number n (1 ≤ n ≤ 105), the number of coordinates in the test. Then there follow n lines, each of them contains coordinates. All the coordinates are correct, there are no cells with the column and/or the row numbers larger than 106 .
1,600
Write n lines, each line should contain a cell coordinates in the other numeration system.
standard output
PASSED
4fa988ec18477eaf25f844f97d185cdd
train_001.jsonl
1266580800
In the popular spreadsheets systems (for example, in Excel) the following numeration of columns is used. The first column has number A, the second — number B, etc. till column 26 that is marked by Z. Then there are two-letter numbers: column 27 has number AA, 28 — AB, column 52 is marked by AZ. After ZZ there follow three-letter numbers, etc.The rows are marked by integer numbers starting with 1. The cell name is the concatenation of the column and the row numbers. For example, BC23 is the name for the cell that is in column 55, row 23. Sometimes another numeration system is used: RXCY, where X and Y are integer numbers, showing the column and the row numbers respectfully. For instance, R23C55 is the cell from the previous example.Your task is to write a program that reads the given sequence of cell coordinates and produce each item written according to the rules of another numeration system.
64 megabytes
import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Spreadsheets { public static void main(String[] args) { int n; String regex1 = "R(?<row>[0-9]+)C(?<column>[0-9]+)"; String regex2 = "(?<column>[A-Z]+)(?<row>[0-9]+)"; Pattern pattern1 = Pattern.compile(regex1); Pattern pattern2 = Pattern.compile(regex2); Scanner scanner = new Scanner(System.in); n = Integer.parseInt(scanner.nextLine()); String[] lines = new String[n]; int indx = 0; while((n--)>0) { lines[indx++] = scanner.nextLine(); } for(int i=0; i<lines.length; i++) { Matcher m1 = pattern1.matcher(lines[i]); if(m1.matches()) { System.out.println(toBase26(Integer.parseInt(m1.group("column"))) + m1.group("row")); } else { Matcher m2 = pattern2.matcher(lines[i]); if(m2.matches()) { System.out.println("R" + m2.group("row") + "C" + toDecimal(m2.group("column"))); } else { System.out.println("Format not valid"); } } } } public static int toDecimal(String base26) { int res = 0; int base = 1; for(int i=base26.length()-1; i>=0; i--) { res += ((int)(base26.charAt(i)) - 64) * base; base *= 26; } return res; } public static String toBase26(int decimal) { StringBuilder res = new StringBuilder(); while(decimal != 0) { int k = decimal % 26; if(k == 0) { decimal = decimal / 26 - 1; res.insert(0, "Z"); } else { decimal /= 26; res.insert(0, (char)(k + 64)); } } return res.toString(); } }
Java
["2\nR23C55\nBC23"]
10 seconds
["BC23\nR23C55"]
null
Java 11
standard input
[ "implementation", "math" ]
910c0e650d48af22fa51ab05e8123709
The first line of the input contains integer number n (1 ≤ n ≤ 105), the number of coordinates in the test. Then there follow n lines, each of them contains coordinates. All the coordinates are correct, there are no cells with the column and/or the row numbers larger than 106 .
1,600
Write n lines, each line should contain a cell coordinates in the other numeration system.
standard output
PASSED
50d4d0dd8a018fbcf994097d9c05450b
train_001.jsonl
1266580800
In the popular spreadsheets systems (for example, in Excel) the following numeration of columns is used. The first column has number A, the second — number B, etc. till column 26 that is marked by Z. Then there are two-letter numbers: column 27 has number AA, 28 — AB, column 52 is marked by AZ. After ZZ there follow three-letter numbers, etc.The rows are marked by integer numbers starting with 1. The cell name is the concatenation of the column and the row numbers. For example, BC23 is the name for the cell that is in column 55, row 23. Sometimes another numeration system is used: RXCY, where X and Y are integer numbers, showing the column and the row numbers respectfully. For instance, R23C55 is the cell from the previous example.Your task is to write a program that reads the given sequence of cell coordinates and produce each item written according to the rules of another numeration system.
64 megabytes
import java.util.Scanner; import java.util.regex.*; import java.lang.Object; public class cf_1B{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); int t = sc.nextInt(); String dummy = sc.nextLine(); while(t>0) { int i = 0, len = 0; String imu = ""; String ara[] = new String[3]; int arr[] = new int[3]; String ss = sc.nextLine(); Pattern p = Pattern.compile("\\d+"); Matcher m = p.matcher(ss); while(m.find()) { ara[i] = m.group(); arr[i] = Integer.parseInt(ara[i]); i++; } if(i>1) nToA(arr[0],arr[1]); else { Pattern pp = Pattern.compile("^([A-Za-z]+)[^A-Za-z]"); Matcher matcher = pp.matcher(ss); if (matcher.find()) { imu = matcher.group(1); len = imu.length(); } aToN(imu, len, arr[0]); } t--; } } public static void aToN(String dsp,int len, int c){ System.out.print("R"); System.out.print(c); System.out.print("C"); int i = 0, sum = 0; len--; while(len >= 0) { double power = Math.pow(26d,len); char ch = dsp.charAt(i); sum += (ch-64) * power; len--; i++; } System.out.println(sum); } public static void nToA(int r, int c){ int digit[] = new int[1000]; int i = 0; while(c>0) { int rem = c % 26; if(rem == 0) { rem = rem+26; digit[i] = rem; c = c/26 - 1; i++; } else { digit[i] = rem; c = c/26; i++; } } for(int j = i-1; j >= 0; j--) { System.out.print((char)(digit[j]+64) ); } System.out.println(r); } }
Java
["2\nR23C55\nBC23"]
10 seconds
["BC23\nR23C55"]
null
Java 11
standard input
[ "implementation", "math" ]
910c0e650d48af22fa51ab05e8123709
The first line of the input contains integer number n (1 ≤ n ≤ 105), the number of coordinates in the test. Then there follow n lines, each of them contains coordinates. All the coordinates are correct, there are no cells with the column and/or the row numbers larger than 106 .
1,600
Write n lines, each line should contain a cell coordinates in the other numeration system.
standard output
PASSED
d3c535a1be147d09e939260446ba4a6e
train_001.jsonl
1266580800
In the popular spreadsheets systems (for example, in Excel) the following numeration of columns is used. The first column has number A, the second — number B, etc. till column 26 that is marked by Z. Then there are two-letter numbers: column 27 has number AA, 28 — AB, column 52 is marked by AZ. After ZZ there follow three-letter numbers, etc.The rows are marked by integer numbers starting with 1. The cell name is the concatenation of the column and the row numbers. For example, BC23 is the name for the cell that is in column 55, row 23. Sometimes another numeration system is used: RXCY, where X and Y are integer numbers, showing the column and the row numbers respectfully. For instance, R23C55 is the cell from the previous example.Your task is to write a program that reads the given sequence of cell coordinates and produce each item written according to the rules of another numeration system.
64 megabytes
import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Spreadsheets { private static final int BASE = 26; private static final String PATTERN_NUMBERS = "^R(\\d+)C(\\d*)$"; private static final String PATTERN_LETTERS = "^([A-Z]*)(\\d*)$"; private static final Pattern P1 = Pattern.compile(PATTERN_NUMBERS); private static final Pattern P2 = Pattern.compile(PATTERN_LETTERS); public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); sc.nextLine(); final String[] input = new String[n]; for (int i = 0; i < n; i++) input[i] = sc.nextLine(); for (String s : input) { Matcher matcher = P1.matcher(s); if (matcher.matches()) System.out.println(toLetters(matcher)); else { matcher = P2.matcher(s); matcher.matches(); System.out.println(toNumbers(matcher)); } } } private static String toLetters(Matcher matcher) { final StringBuilder result = new StringBuilder(); int col = Integer.parseInt(matcher.group(2)); while (col > 0) { result.insert(0, (char) ((col - 1) % 26 + 'A')); col = (col - 1) / 26; } return result.append(matcher.group(1)).toString(); } private static String toNumbers(Matcher matcher) { final StringBuilder result = new StringBuilder(); String letters = matcher.group(1); int col = 0; for (int i = 0; i < letters.length(); i++) { col *= BASE; col += letters.charAt(i) - 'A' + 1; } return result.append('R').append(matcher.group(2)).append('C').append(col).toString(); } } /* import java.util.Scanner; public class Spreadsheets { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int n = scan.nextInt(); while (--n >= 0) { String coord = scan.next(); int cIndex = coord.indexOf('C'); if (coord.startsWith("R") && Character.isDigit(coord.charAt(1)) && cIndex != -1) { int row = Integer.parseInt(coord.substring(1, cIndex)); int col = Integer.parseInt(coord.substring(cIndex + 1)); StringBuilder colStr = new StringBuilder(); while (col > 0) { colStr.insert(0, (char)((col - 1) % 26 + 'A')); col = (col - 1) / 26; } System.out.println(colStr.toString() + row); } else { int split = 1; while (!Character.isDigit(coord.charAt(split))) split++; String colStr = coord.substring(0, split); int row = Integer.parseInt(coord.substring(split)); int col = 0; for (int i = 0; i < colStr.length(); i++) { col *= 26; col += colStr.charAt(i) - 'A' + 1; } System.out.println("R" + row + "C" + col); } } } } */
Java
["2\nR23C55\nBC23"]
10 seconds
["BC23\nR23C55"]
null
Java 11
standard input
[ "implementation", "math" ]
910c0e650d48af22fa51ab05e8123709
The first line of the input contains integer number n (1 ≤ n ≤ 105), the number of coordinates in the test. Then there follow n lines, each of them contains coordinates. All the coordinates are correct, there are no cells with the column and/or the row numbers larger than 106 .
1,600
Write n lines, each line should contain a cell coordinates in the other numeration system.
standard output
PASSED
2bca180348ef3bbdd777cd71dfc5688b
train_001.jsonl
1266580800
In the popular spreadsheets systems (for example, in Excel) the following numeration of columns is used. The first column has number A, the second — number B, etc. till column 26 that is marked by Z. Then there are two-letter numbers: column 27 has number AA, 28 — AB, column 52 is marked by AZ. After ZZ there follow three-letter numbers, etc.The rows are marked by integer numbers starting with 1. The cell name is the concatenation of the column and the row numbers. For example, BC23 is the name for the cell that is in column 55, row 23. Sometimes another numeration system is used: RXCY, where X and Y are integer numbers, showing the column and the row numbers respectfully. For instance, R23C55 is the cell from the previous example.Your task is to write a program that reads the given sequence of cell coordinates and produce each item written according to the rules of another numeration system.
64 megabytes
import java.util.Scanner; public class Spreadsheets { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int n = scan.nextInt(); while (--n >= 0) { String coord = scan.next(); int cIndex = coord.indexOf('C'); if (coord.startsWith("R") && Character.isDigit(coord.charAt(1)) && cIndex != -1) { int row = Integer.parseInt(coord.substring(1, cIndex)); int col = Integer.parseInt(coord.substring(cIndex + 1)); StringBuilder colStr = new StringBuilder(); while (col > 0) { colStr.insert(0, (char)((col - 1) % 26 + 'A')); col = (col - 1) / 26; } System.out.println(colStr.toString() + row); } else { int split = 1; while (!Character.isDigit(coord.charAt(split))) split++; String colStr = coord.substring(0, split); int row = Integer.parseInt(coord.substring(split)); int col = 0; for (int i = 0; i < colStr.length(); i++) { col *= 26; col += colStr.charAt(i) - 'A' + 1; } System.out.println("R" + row + "C" + col); } } } }
Java
["2\nR23C55\nBC23"]
10 seconds
["BC23\nR23C55"]
null
Java 11
standard input
[ "implementation", "math" ]
910c0e650d48af22fa51ab05e8123709
The first line of the input contains integer number n (1 ≤ n ≤ 105), the number of coordinates in the test. Then there follow n lines, each of them contains coordinates. All the coordinates are correct, there are no cells with the column and/or the row numbers larger than 106 .
1,600
Write n lines, each line should contain a cell coordinates in the other numeration system.
standard output
PASSED
ba6f20233c1b493ba75e8a23df0bc747
train_001.jsonl
1266580800
In the popular spreadsheets systems (for example, in Excel) the following numeration of columns is used. The first column has number A, the second — number B, etc. till column 26 that is marked by Z. Then there are two-letter numbers: column 27 has number AA, 28 — AB, column 52 is marked by AZ. After ZZ there follow three-letter numbers, etc.The rows are marked by integer numbers starting with 1. The cell name is the concatenation of the column and the row numbers. For example, BC23 is the name for the cell that is in column 55, row 23. Sometimes another numeration system is used: RXCY, where X and Y are integer numbers, showing the column and the row numbers respectfully. For instance, R23C55 is the cell from the previous example.Your task is to write a program that reads the given sequence of cell coordinates and produce each item written according to the rules of another numeration system.
64 megabytes
//package code.package_import.baitap; import java.util.Scanner; import java.util.*; public class main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int soTest = sc.nextInt(); String chuoi = sc.nextLine(); while(soTest > 0) { chuoi = sc.nextLine(); int id_R = chuoi.indexOf('R'); int id_C = chuoi.lastIndexOf('C'); if(id_R != -1 && id_C != -1 && chuoi.charAt(id_R + 1) >= '0' && chuoi.charAt(id_R + 1) <= '9' && id_R < id_C) { String row = new String(); for(int i = id_R + 1;i<id_C;i++) row += chuoi.charAt(i); String column = chuoi.substring(id_C + 1); long columnLong = Long.parseLong(column), du; column = ""; char temp; while(columnLong > 0) { du = columnLong % 26; if(du == 0) temp = 'Z'; else temp = (char)('A' + du - 1); column = temp + column; columnLong /= 26; if(du == 0) columnLong--; } System.out.println(column + row); } else { int i, col = 0, mu = 0; for(i = chuoi.length() - 1;i >= 0;i--) { if(chuoi.charAt(i) >= 'A' && chuoi.charAt(i) <= 'Z') { col += Math.pow(26, mu) * (chuoi.charAt(i) - 'A' + 1); mu++; } } int row = 0; for(i = 0;i < chuoi.length();i++) { if(chuoi.charAt(i) >= '0' && chuoi.charAt(i) <= '9') { row = row * 10 + (chuoi.charAt(i) - '0'); } } System.out.println("R" + row + "C" + col); } soTest--; } } }
Java
["2\nR23C55\nBC23"]
10 seconds
["BC23\nR23C55"]
null
Java 11
standard input
[ "implementation", "math" ]
910c0e650d48af22fa51ab05e8123709
The first line of the input contains integer number n (1 ≤ n ≤ 105), the number of coordinates in the test. Then there follow n lines, each of them contains coordinates. All the coordinates are correct, there are no cells with the column and/or the row numbers larger than 106 .
1,600
Write n lines, each line should contain a cell coordinates in the other numeration system.
standard output
PASSED
9ffab7eaacb7de4b762feac4d098d620
train_001.jsonl
1266580800
In the popular spreadsheets systems (for example, in Excel) the following numeration of columns is used. The first column has number A, the second — number B, etc. till column 26 that is marked by Z. Then there are two-letter numbers: column 27 has number AA, 28 — AB, column 52 is marked by AZ. After ZZ there follow three-letter numbers, etc.The rows are marked by integer numbers starting with 1. The cell name is the concatenation of the column and the row numbers. For example, BC23 is the name for the cell that is in column 55, row 23. Sometimes another numeration system is used: RXCY, where X and Y are integer numbers, showing the column and the row numbers respectfully. For instance, R23C55 is the cell from the previous example.Your task is to write a program that reads the given sequence of cell coordinates and produce each item written according to the rules of another numeration system.
64 megabytes
import java.util.*; public class Main { public static void main(String[] args) { Scanner console = new Scanner(System.in); int t = console.nextInt(); String alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; while (t-- > 0) { String word = console.next(); if (word.substring(0, 1).equals("R") && alpha.indexOf(word.substring(1, 2)) == -1 && word.contains("C")) { int i = word.indexOf("C"); int row = Integer.valueOf(word.substring(1, i)); int col = Integer.valueOf(word.substring(i+1)); String letters = ""; int col2 = col; int len = 0; while (col2 > 0) { int total = (int) Math.pow(26, len); if (total != 0 && (col2-1) / total > 0) { len++; } else if (col2 == 1) { len++; break; } else { break; } } while (len > 0) { if (col <= 26) { int index = (col-1) % 26; letters = alpha.substring(index, index+1) + letters; break; } int index = (col-1) % 26; letters = alpha.substring(index, index+1) + letters; col = (col-1) / 26; len--; } System.out.println(letters + row); } else { String word2 = word.replaceAll("[0-9]", ""); int i = word2.length(); int col = 0; int row = Integer.valueOf(word.substring(i)); int j = 0; while (alpha.indexOf(word.substring(j, j +1)) != -1) { int index = alpha.indexOf(word.substring(j, j+1)) + 1; col += index * Math.pow(26, i-1); j++; i--; } System.out.println("R" + row + "C" + col); } } } }
Java
["2\nR23C55\nBC23"]
10 seconds
["BC23\nR23C55"]
null
Java 11
standard input
[ "implementation", "math" ]
910c0e650d48af22fa51ab05e8123709
The first line of the input contains integer number n (1 ≤ n ≤ 105), the number of coordinates in the test. Then there follow n lines, each of them contains coordinates. All the coordinates are correct, there are no cells with the column and/or the row numbers larger than 106 .
1,600
Write n lines, each line should contain a cell coordinates in the other numeration system.
standard output
PASSED
551787afed1709c7456abb5443472533
train_001.jsonl
1266580800
In the popular spreadsheets systems (for example, in Excel) the following numeration of columns is used. The first column has number A, the second — number B, etc. till column 26 that is marked by Z. Then there are two-letter numbers: column 27 has number AA, 28 — AB, column 52 is marked by AZ. After ZZ there follow three-letter numbers, etc.The rows are marked by integer numbers starting with 1. The cell name is the concatenation of the column and the row numbers. For example, BC23 is the name for the cell that is in column 55, row 23. Sometimes another numeration system is used: RXCY, where X and Y are integer numbers, showing the column and the row numbers respectfully. For instance, R23C55 is the cell from the previous example.Your task is to write a program that reads the given sequence of cell coordinates and produce each item written according to the rules of another numeration system.
64 megabytes
import java.util.*; public class Main { public static void main(String[] args) { Scanner console = new Scanner(System.in); int t = console.nextInt(); String alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; while (t-- > 0) { String word = console.next(); if (word.matches("^R[0-9]+C[0-9]+")) { int i = word.indexOf("C"); int row = Integer.valueOf(word.substring(1, i)); int col = Integer.valueOf(word.substring(i+1)); String letters = ""; int col2 = col; int len = 0; while (col2 > 0) { int total = (int) Math.pow(26, len); if (total != 0 && (col2-1) / total > 0) { len++; } else if (col2 == 1) { len++; break; } else { break; } } while (len > 0) { if (col <= 26) { int index = (col-1) % 26; letters = alpha.substring(index, index+1) + letters; break; } int index = (col-1) % 26; letters = alpha.substring(index, index+1) + letters; col = (col-1) / 26; len--; } System.out.println(letters + row); } else { String word2 = word.replaceAll("[0-9]", ""); int i = word2.length(); int col = 0; int row = Integer.valueOf(word.substring(i)); int j = 0; while (alpha.indexOf(word.substring(j, j +1)) != -1) { int index = alpha.indexOf(word.substring(j, j+1)) + 1; col += index * Math.pow(26, i-1); j++; i--; } System.out.println("R" + row + "C" + col); } } } }
Java
["2\nR23C55\nBC23"]
10 seconds
["BC23\nR23C55"]
null
Java 11
standard input
[ "implementation", "math" ]
910c0e650d48af22fa51ab05e8123709
The first line of the input contains integer number n (1 ≤ n ≤ 105), the number of coordinates in the test. Then there follow n lines, each of them contains coordinates. All the coordinates are correct, there are no cells with the column and/or the row numbers larger than 106 .
1,600
Write n lines, each line should contain a cell coordinates in the other numeration system.
standard output
PASSED
83c0660fbe6dba0b8eca3c67f055f5f5
train_001.jsonl
1266580800
In the popular spreadsheets systems (for example, in Excel) the following numeration of columns is used. The first column has number A, the second — number B, etc. till column 26 that is marked by Z. Then there are two-letter numbers: column 27 has number AA, 28 — AB, column 52 is marked by AZ. After ZZ there follow three-letter numbers, etc.The rows are marked by integer numbers starting with 1. The cell name is the concatenation of the column and the row numbers. For example, BC23 is the name for the cell that is in column 55, row 23. Sometimes another numeration system is used: RXCY, where X and Y are integer numbers, showing the column and the row numbers respectfully. For instance, R23C55 is the cell from the previous example.Your task is to write a program that reads the given sequence of cell coordinates and produce each item written according to the rules of another numeration system.
64 megabytes
import java.io.*; import java.util.*; public class A { public static void main (String[] args) { new A(); } public A() { FastScanner fs = new FastScanner(); PrintWriter out = new PrintWriter(System.out); System.err.println(""); String[] all = new String[1000001]; all[1] = "A"; for(int i = 2; i < all.length; i++) { String prev = all[i-1]; char[] s = prev.toCharArray(); boolean fnd = false; for(int j = s.length-1; j >= 0; j--) { if(s[j] == 'Z') { s[j]='A'; } else { s[j]++; fnd = true; break; } } if(!fnd) { String x = new String(s); x = "A"+x; all[i] = x; } else { all[i] = new String(s); } } int T = fs.nextInt(); while(T-->0) { String str = fs.next(); int charFirst = 1; boolean not1 = false; for(int i = 0; i < str.length(); i++) { char now = str.charAt(i); if(Character.isAlphabetic(now)) { if(charFirst == 0) { not1 = true; break; } } else { charFirst = 0; } } if(not1) { String it1 = "", it2 = ""; boolean swap = false; for(int i = 1; i < str.length(); i++) { char now = str.charAt(i); if(Character.isAlphabetic(now)) { swap = true; continue; } if(!swap) it1 += now; else it2 += now; } String col = all[Integer.parseInt(it2)]; out.printf("%s%d\n", col, Integer.parseInt(it1)); } else { String it = "", it2 = ""; for(int i = 0; i < str.length(); i++) { char now = str.charAt(i); if(Character.isAlphabetic(now)) it += now; else { it2 += now; } } int row = Integer.parseInt(it2); int col = getVal(it); out.printf("R%dC%d\n", row, col); } } out.close(); } int getVal(String str) { int pow = 1, res = 0; for(int i = str.length()-1; i >= 0; i--) { char now = str.charAt(i); int idx = now-'A'+1; res += idx*pow; pow *= 26; } return res; } class FastScanner { public int BS = 1<<16; public char NC = (char)0; byte[] buf = new byte[BS]; int bId = 0, size = 0; char c = NC; double num = 1; BufferedInputStream in; public FastScanner() { in = new BufferedInputStream(System.in, BS); } public FastScanner(String s) { try { in = new BufferedInputStream(new FileInputStream(new File(s)), BS); } catch (Exception e) { in = new BufferedInputStream(System.in, BS); } } public char nextChar(){ while(bId==size) { try { size = in.read(buf); }catch(Exception e) { return NC; } if(size==-1)return NC; bId=0; } return (char)buf[bId++]; } public int nextInt() { return (int)nextLong(); } public long nextLong() { num=1; boolean neg = false; if(c==NC)c=nextChar(); for(;(c<'0' || c>'9'); c = nextChar()) { if(c=='-')neg=true; } long res = 0; for(; c>='0' && c <='9'; c=nextChar()) { res = (res<<3)+(res<<1)+c-'0'; num*=10; } return neg?-res:res; } public double nextDouble() { double cur = nextLong(); return c!='.' ? cur:cur+nextLong()/num; } public String next() { StringBuilder res = new StringBuilder(); while(c<=32)c=nextChar(); while(c>32) { res.append(c); c=nextChar(); } return res.toString(); } public String nextLine() { StringBuilder res = new StringBuilder(); while(c<=32)c=nextChar(); while(c!='\n') { res.append(c); c=nextChar(); } return res.toString(); } public boolean hasNext() { if(c>32)return true; while(true) { c=nextChar(); if(c==NC)return false; else if(c>32)return true; } } public int[] nextIntArray(int n) { int[] res = new int[n]; for(int i = 0; i < n; i++) res[i] = nextInt(); return res; } } }
Java
["2\nR23C55\nBC23"]
10 seconds
["BC23\nR23C55"]
null
Java 11
standard input
[ "implementation", "math" ]
910c0e650d48af22fa51ab05e8123709
The first line of the input contains integer number n (1 ≤ n ≤ 105), the number of coordinates in the test. Then there follow n lines, each of them contains coordinates. All the coordinates are correct, there are no cells with the column and/or the row numbers larger than 106 .
1,600
Write n lines, each line should contain a cell coordinates in the other numeration system.
standard output
PASSED
8eb8194b18b4e20bd39889a46ccb41ff
train_001.jsonl
1266580800
In the popular spreadsheets systems (for example, in Excel) the following numeration of columns is used. The first column has number A, the second — number B, etc. till column 26 that is marked by Z. Then there are two-letter numbers: column 27 has number AA, 28 — AB, column 52 is marked by AZ. After ZZ there follow three-letter numbers, etc.The rows are marked by integer numbers starting with 1. The cell name is the concatenation of the column and the row numbers. For example, BC23 is the name for the cell that is in column 55, row 23. Sometimes another numeration system is used: RXCY, where X and Y are integer numbers, showing the column and the row numbers respectfully. For instance, R23C55 is the cell from the previous example.Your task is to write a program that reads the given sequence of cell coordinates and produce each item written according to the rules of another numeration system.
64 megabytes
import java.util.Scanner; public class Spreadsheets { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int n = scan.nextInt(); while (--n >= 0) { String coord = scan.next(); int cIndex = coord.indexOf('C'); if (coord.startsWith("R") && Character.isDigit(coord.charAt(1)) && cIndex != -1) { int row = Integer.parseInt(coord.substring(1, cIndex)); int col = Integer.parseInt(coord.substring(cIndex + 1)); StringBuilder colStr = new StringBuilder(); while (col > 0) { colStr.insert(0, (char)((col - 1) % 26 + 'A')); col = (col - 1) / 26; } System.out.println(colStr.toString() + row); } else { int split = 1; while (!Character.isDigit(coord.charAt(split))) split++; String colStr = coord.substring(0, split); int row = Integer.parseInt(coord.substring(split)); int col = 0; for (int i = 0; i < colStr.length(); i++) { col *= 26; col += colStr.charAt(i) - 'A' + 1; } System.out.println("R" + row + "C" + col); } } } }
Java
["2\nR23C55\nBC23"]
10 seconds
["BC23\nR23C55"]
null
Java 11
standard input
[ "implementation", "math" ]
910c0e650d48af22fa51ab05e8123709
The first line of the input contains integer number n (1 ≤ n ≤ 105), the number of coordinates in the test. Then there follow n lines, each of them contains coordinates. All the coordinates are correct, there are no cells with the column and/or the row numbers larger than 106 .
1,600
Write n lines, each line should contain a cell coordinates in the other numeration system.
standard output
PASSED
7966a68b9778e838a70a7d9721d66d42
train_001.jsonl
1266580800
In the popular spreadsheets systems (for example, in Excel) the following numeration of columns is used. The first column has number A, the second — number B, etc. till column 26 that is marked by Z. Then there are two-letter numbers: column 27 has number AA, 28 — AB, column 52 is marked by AZ. After ZZ there follow three-letter numbers, etc.The rows are marked by integer numbers starting with 1. The cell name is the concatenation of the column and the row numbers. For example, BC23 is the name for the cell that is in column 55, row 23. Sometimes another numeration system is used: RXCY, where X and Y are integer numbers, showing the column and the row numbers respectfully. For instance, R23C55 is the cell from the previous example.Your task is to write a program that reads the given sequence of cell coordinates and produce each item written according to the rules of another numeration system.
64 megabytes
import java.util.regex.Pattern; import java.util.regex.Matcher; import java.util.Scanner; public class Spreadsheets { public static void main(String[] args) { /*Splits n1 = new Splits("R32C45"); n1.printNum(); n1.printStr();*/ /*String s = "abcd0123m1".replaceAll("\\d+", ""); String n = "abcd0123m1".replaceAll("\\D+", ""); System.out.println(s); System.out.println(n);*/ /*// 按指定模式在字符串查找 String line = "as45"; String pattern = "(\\D*)(\\d+)(\\D*)(\\d+)(.*)"; // 创建 Pattern 对象 Pattern r = Pattern.compile(pattern); // 现在创建 matcher 对象 Matcher m = r.matcher(line); if (m.find( )) { System.out.println("Found value: " + m.group(1) ); System.out.println("Found value: " + m.group(2) ); System.out.println("Found value: " + m.group(3) ); System.out.println("Found value: " + m.group(4) ); } else { System.out.println("NO MATCH"); } if(m.group(3) == null || m.group(3).length() == 0) System.out.println("第三段为空");*/ Scanner s = new Scanner(System.in); int i = s.nextInt(); String stringInput = ""; for(; i > 0; i--){ stringInput = s.next(); converse(stringInput); } } //将字符串转换为另一种形式 public static void converse(String s){ //分解字符串 String pattern = "(\\D*)(\\d+)(.*)"; // 创建 Pattern 对象 Pattern r = Pattern.compile(pattern); // 现在创建 matcher 对象 Matcher m = r.matcher(s); if (m.find()) { /*System.out.println("Found value: " + m.group(1) ); System.out.println("Found value: " + m.group(2) ); System.out.println("Found value: " + m.group(3) );*/ } else { System.out.println("NO MATCH"); } //判断输入的字符串是哪种形式 //字母+数字—>R数字C数字 if(m.group(3) == null || m.group(3).length() == 0){ //System.out.println("第三段为空"); String a = m.group(1); int l = a.length(); int c = 0; int count = 0; //System.out.println(l); for(; l > 0; l--){ String b = a.substring(l - 1, l); a = a.substring(0, l - 1); c = c + letterToNumber(b) * (int)Math.pow(26,count); //System.out.println(c); count++; } System.out.println("R" + m.group(2) + "C" + c); } //R数字C数字—>字母+数字 else{ //System.out.println("第三段不为空"); String pattern1 = "(\\D*)(\\d+)"; // 创建 Pattern 对象 Pattern r1 = Pattern.compile(pattern1); // 现在创建 matcher 对象 Matcher m1 = r1.matcher(m.group(3)); if (m1.find()) { /*System.out.println("Found value: " + m1.group(1) ); System.out.println("Found value: " + m1.group(2) );*/ } else { System.out.println("NO MATCH"); } int a = Integer.valueOf(m1.group(2)).intValue(); String c = ""; while (a > 26 ) { int b = a % 26; a = a / 26; //System.out.println(b); //System.out.println(a); if(b > 0){ c = numberToLetter(b) + c; } else { c = "Z" + c; a--; } } if(a > 0) c = numberToLetter(a) + c; System.out.println(c + m.group(2)); } } //字母转化为数字 public static String numberToLetter(int num) { if (num <= 0) { return null; } String letter = ""; num--; do { if (letter.length() > 0) { num--; } letter = ((char) (num % 26 + (int) 'A')) + letter; num = (int) ((num - num % 26) / 26); } while (num > 0); return letter; } //数字转化为字母 public static int letterToNumber(String letter) { int length = letter.length(); int num = 0; int number = 0; for (int i = 0; i < length; i++) { char ch = letter.charAt(length - i - 1); num = (int) (ch - 'A' + 1); num *= Math.pow(26, i); number += num; } return number; } }
Java
["2\nR23C55\nBC23"]
10 seconds
["BC23\nR23C55"]
null
Java 11
standard input
[ "implementation", "math" ]
910c0e650d48af22fa51ab05e8123709
The first line of the input contains integer number n (1 ≤ n ≤ 105), the number of coordinates in the test. Then there follow n lines, each of them contains coordinates. All the coordinates are correct, there are no cells with the column and/or the row numbers larger than 106 .
1,600
Write n lines, each line should contain a cell coordinates in the other numeration system.
standard output
PASSED
7e4fc97c12b3ac76d071facbe8bdea38
train_001.jsonl
1266580800
In the popular spreadsheets systems (for example, in Excel) the following numeration of columns is used. The first column has number A, the second — number B, etc. till column 26 that is marked by Z. Then there are two-letter numbers: column 27 has number AA, 28 — AB, column 52 is marked by AZ. After ZZ there follow three-letter numbers, etc.The rows are marked by integer numbers starting with 1. The cell name is the concatenation of the column and the row numbers. For example, BC23 is the name for the cell that is in column 55, row 23. Sometimes another numeration system is used: RXCY, where X and Y are integer numbers, showing the column and the row numbers respectfully. For instance, R23C55 is the cell from the previous example.Your task is to write a program that reads the given sequence of cell coordinates and produce each item written according to the rules of another numeration system.
64 megabytes
// #pragma GCC optimize("Ofast") // #pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native") import java.io.*; import java.util.*; import static java.lang.Math.*; public class Main { static int infi = Integer.MAX_VALUE / 2, mod = (int) (1e9 + 7), maxn = (int) 1e5; static long infl = Long.MAX_VALUE / 2; static boolean let(char x) { return x >= 'A' && x <= 'Z'; } static boolean dig(char x) { return x >= '0' && x <= '9'; } public static void main(String[] args) throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); int t = nextInt(); for (int t123 = 0; t123 < t; t123++) { char[] x = next().toCharArray(); int flag1 = 0, flag2 = 0; int len = x.length; int r = 0, c = 0; String cc = ""; for (int i = 1; i < len; i++) { if (dig(x[i]) && let(x[i - 1])) { flag1 = i; break; } } for (int i = flag1 + 1; i < len; i++) { if (dig(x[i - 1]) && let(x[i])) { flag2 = i; break; } } if (flag2 != 0) { for (int i = flag1; i < flag2; i++) { r = r * 10 + (x[i] - '0'); } for (int i = flag2 + 1; i < len; i++) c = c * 10 + (x[i] - '0'); while (c != 0) { int temp = c % 26; if (temp != 0) { cc += (char) (temp - 1 + 'A'); c /= 26; } else { cc += 'Z'; c = c / 26 - 1; } } for (int i = cc.length() - 1; i >= 0; i--) out.print(cc.charAt(i)); out.println(r); } else { for (int i = 0; i < flag1; i++) c = c * 26 + (x[i] - 'A' + 1); for (int i = flag1; i < len; i++) r = r * 10 + x[i] - '0'; out.println("R" + r + "C" + c); } } out.close(); } static BufferedReader br; static StringTokenizer st = new StringTokenizer(""); static PrintWriter out; static String next() throws IOException { while (!st.hasMoreTokens()) { st = new StringTokenizer(br.readLine()); } return st.nextToken(); } static int nextInt() throws IOException { return Integer.parseInt(next()); } static long nextLong() throws IOException { return Long.parseLong(next()); } } class f { int x, y; public f(int x, int y) { this.x = x; this.y = y; } }
Java
["2\nR23C55\nBC23"]
10 seconds
["BC23\nR23C55"]
null
Java 11
standard input
[ "implementation", "math" ]
910c0e650d48af22fa51ab05e8123709
The first line of the input contains integer number n (1 ≤ n ≤ 105), the number of coordinates in the test. Then there follow n lines, each of them contains coordinates. All the coordinates are correct, there are no cells with the column and/or the row numbers larger than 106 .
1,600
Write n lines, each line should contain a cell coordinates in the other numeration system.
standard output
PASSED
d28cfdb9182b6af554f70c426df81eba
train_001.jsonl
1266580800
In the popular spreadsheets systems (for example, in Excel) the following numeration of columns is used. The first column has number A, the second — number B, etc. till column 26 that is marked by Z. Then there are two-letter numbers: column 27 has number AA, 28 — AB, column 52 is marked by AZ. After ZZ there follow three-letter numbers, etc.The rows are marked by integer numbers starting with 1. The cell name is the concatenation of the column and the row numbers. For example, BC23 is the name for the cell that is in column 55, row 23. Sometimes another numeration system is used: RXCY, where X and Y are integer numbers, showing the column and the row numbers respectfully. For instance, R23C55 is the cell from the previous example.Your task is to write a program that reads the given sequence of cell coordinates and produce each item written according to the rules of another numeration system.
64 megabytes
import java.util.Scanner; public class solution { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); for(int i=0; i<t; i++) { String s = sc.next(); int indexOfC = s.indexOf('C'); if(s.charAt(0)=='R' && s.charAt(1)-'0'<=9 && indexOfC>0) { int row, col; row = Integer.parseInt(s.substring(1, indexOfC)); col = Integer.parseInt(s.substring(indexOfC+1)); StringBuilder colStr = new StringBuilder(); while (col > 0) { colStr.insert(0, (char)((col - 1) % 26 + 'A')); col = (col - 1) / 26; } System.out.println(colStr.toString()+""+row); } else { int k,row,col = 0; for(k=0; s.charAt(k)-'A'>=0; k++) { col *= 26; col += s.charAt(k) - 'A' + 1; } row = Integer.parseInt(s.substring(k)); System.out.println("R"+row+"C"+col); } } } }
Java
["2\nR23C55\nBC23"]
10 seconds
["BC23\nR23C55"]
null
Java 11
standard input
[ "implementation", "math" ]
910c0e650d48af22fa51ab05e8123709
The first line of the input contains integer number n (1 ≤ n ≤ 105), the number of coordinates in the test. Then there follow n lines, each of them contains coordinates. All the coordinates are correct, there are no cells with the column and/or the row numbers larger than 106 .
1,600
Write n lines, each line should contain a cell coordinates in the other numeration system.
standard output
PASSED
beebf791f8d9269df1387d1540951f4d
train_001.jsonl
1266580800
In the popular spreadsheets systems (for example, in Excel) the following numeration of columns is used. The first column has number A, the second — number B, etc. till column 26 that is marked by Z. Then there are two-letter numbers: column 27 has number AA, 28 — AB, column 52 is marked by AZ. After ZZ there follow three-letter numbers, etc.The rows are marked by integer numbers starting with 1. The cell name is the concatenation of the column and the row numbers. For example, BC23 is the name for the cell that is in column 55, row 23. Sometimes another numeration system is used: RXCY, where X and Y are integer numbers, showing the column and the row numbers respectfully. For instance, R23C55 is the cell from the previous example.Your task is to write a program that reads the given sequence of cell coordinates and produce each item written according to the rules of another numeration system.
64 megabytes
import java.util.*; // 1700 - implementation, math public class Problem1B_Spreadsheets { public static void main (String[] args) { Scanner s = new Scanner(System.in); int n = s.nextInt(); while (--n >= 0) { String str = s.next(); int cIndex = str.indexOf('C'); // if string is in RXCY format if (str.charAt(0) == 'R' && cIndex > 1 && str.charAt(1) >= '0' && str.charAt(1) <= '9') { int rowNum = 0; int colNum = 0; for (int i = 1; i < cIndex; i++) { int a = str.charAt(i); rowNum = rowNum * 10 + (a - '0'); } for (int j = cIndex + 1; j < str.length(); j++) { int b = str.charAt(j); colNum = colNum * 10 + (b - '0'); } String colAlp = toAlphabetic(colNum - 1); String rowString = Integer.toString(rowNum); System.out.println(colAlp + rowString); } else { // if string is in CX format int colNum = 0; int rowNum = 0; for (int i = 0; i < str.length(); i++) { char c = str.charAt(i); if (c < '0' || c > '9') { int num = c - 'A' + 1; colNum = colNum * 26 + num; } else { rowNum = rowNum * 10 + (c - '0'); } } String row = Integer.toString(rowNum); String col = Integer.toString(colNum); System.out.println("R" + row + "C" + col); } } } public static String toAlphabetic(int i) { int quot = i / 26; int rem = i % 26; char letter = (char) ((int)'A' + rem); if (quot == 0) { return "" + letter; } else { return toAlphabetic(quot - 1) + letter; } } }
Java
["2\nR23C55\nBC23"]
10 seconds
["BC23\nR23C55"]
null
Java 11
standard input
[ "implementation", "math" ]
910c0e650d48af22fa51ab05e8123709
The first line of the input contains integer number n (1 ≤ n ≤ 105), the number of coordinates in the test. Then there follow n lines, each of them contains coordinates. All the coordinates are correct, there are no cells with the column and/or the row numbers larger than 106 .
1,600
Write n lines, each line should contain a cell coordinates in the other numeration system.
standard output
PASSED
460792ca95dd1305f795221547409be0
train_001.jsonl
1266580800
In the popular spreadsheets systems (for example, in Excel) the following numeration of columns is used. The first column has number A, the second — number B, etc. till column 26 that is marked by Z. Then there are two-letter numbers: column 27 has number AA, 28 — AB, column 52 is marked by AZ. After ZZ there follow three-letter numbers, etc.The rows are marked by integer numbers starting with 1. The cell name is the concatenation of the column and the row numbers. For example, BC23 is the name for the cell that is in column 55, row 23. Sometimes another numeration system is used: RXCY, where X and Y are integer numbers, showing the column and the row numbers respectfully. For instance, R23C55 is the cell from the previous example.Your task is to write a program that reads the given sequence of cell coordinates and produce each item written according to the rules of another numeration system.
64 megabytes
import java.util.ArrayList; import java.util.List; import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; //R228C494 //wrong answer 56th words differ - expected: 'RZ228', found: 'S@228' public class B_Spreadsheets { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); sc.nextLine(); List<String> numerations = new ArrayList<>(); while(n > 0) { numerations.add(sc.nextLine()); n--; } sc.close(); outputAlternateNumerationSystem(numerations); } private static void outputAlternateNumerationSystem(List<String> numerations) { for(String numeration : numerations) { if(numeration.matches("^[R]([0-9]+)[C]([0-9]+)$")) { Pattern pattern = Pattern.compile("^[R]([0-9]+)[C]([0-9]+)$"); Matcher matcher = pattern.matcher(numeration); if (matcher.matches()) { int rows = Integer.parseInt(matcher.group(1)); int columns = Integer.parseInt(matcher.group(2)); StringBuilder sb = new StringBuilder(); while(columns > 0) { if(columns % 26 == 0) { sb.append('Z'); columns -= 26; } else sb.append((char) ('A' + (columns % 26) - 1)); columns = columns / 26; } System.out.println(sb.reverse().toString() + rows); } } else { Pattern pattern = Pattern.compile("^([A-Z]+)([0-9]+)$"); Matcher matcher = pattern.matcher(numeration); if (matcher.matches()) { String columns = matcher.group(1); char[] charsOfColumn = columns.toCharArray(); int noOfColumns = 0; for (final char c : charsOfColumn) { noOfColumns = 26 * noOfColumns + (c - 'A' + 1); } System.out.println("R" + matcher.group(2) + "C" + noOfColumns); } } } } }
Java
["2\nR23C55\nBC23"]
10 seconds
["BC23\nR23C55"]
null
Java 11
standard input
[ "implementation", "math" ]
910c0e650d48af22fa51ab05e8123709
The first line of the input contains integer number n (1 ≤ n ≤ 105), the number of coordinates in the test. Then there follow n lines, each of them contains coordinates. All the coordinates are correct, there are no cells with the column and/or the row numbers larger than 106 .
1,600
Write n lines, each line should contain a cell coordinates in the other numeration system.
standard output
PASSED
02825b7e9089438b72eeb9a0218fec85
train_001.jsonl
1365694200
Greg has a weighed directed graph, consisting of n vertices. In this graph any pair of distinct vertices has an edge between them in both directions. Greg loves playing with the graph and now he has invented a new game: The game consists of n steps. On the i-th step Greg removes vertex number xi from the graph. As Greg removes a vertex, he also removes all the edges that go in and out of this vertex. Before executing each step, Greg wants to know the sum of lengths of the shortest paths between all pairs of the remaining vertices. The shortest path can go through any remaining vertex. In other words, if we assume that d(i, v, u) is the shortest path between vertices v and u in the graph that formed before deleting vertex xi, then Greg wants to know the value of the following sum: . Help Greg, print the value of the required sum before each step.
256 megabytes
import java.io.*; import java.util.*; public class Main { Scanner in; PrintWriter out; static class Scanner { StreamTokenizer in; Scanner(InputStream is) { in = new StreamTokenizer(new BufferedReader(new InputStreamReader(is))); } int nextInt() { try { in.nextToken(); return (int)in.nval; } catch (IOException e) { throw new Error(); } } } static class Op { int left; int right; long amount; Op(Scanner in) { left = in.nextInt() - 1; right = in.nextInt() - 1; amount = in.nextInt(); } } long getSum2(int appOrder[], int number, int[][] dist) { if (number == 0) { return 0; } for (int i = 0; i <= number; i++) { int m1 = appOrder[i]; for (int j = 0; j <= number; j++) { int m2 = appOrder[j]; for (int k = 0; k <= number; k++) { int mk = appOrder[k]; int anotherDist = dist[m2][m1] + dist[m1][mk]; if (dist[m2][mk] > anotherDist) { dist[m2][mk] = anotherDist; } } } } long ans = 0; for (int i = 0; i <= number; i++) { for (int j = 0; j <= number; j++) { ans = ans + dist[appOrder[i]][appOrder[j]]; } } return ans; } long getSum(int appOrder[], int number, int[][] dist) { if (number == 0) { return 0; } for (int i = 0; i <= number; i++) { int m1 = appOrder[i]; int mk = appOrder[number]; for (int j = 0; j <= number; j++) { int m2 = appOrder[j]; int anotherDist = dist[m1][m2] + dist[m2][mk]; if (dist[m1][mk] > anotherDist) { dist[m1][mk] = anotherDist; } } } for (int i = 0; i <= number; i++) { int m1 = appOrder[i]; int mk = appOrder[number]; for (int j = 0; j <= number; j++) { int m2 = appOrder[j]; int anotherDist = dist[mk][m1] + dist[m1][m2]; if (dist[mk][m2] > anotherDist) { dist[mk][m2] = anotherDist; } } } for (int i = 0; i <= number; i++) { int m1 = appOrder[i]; int mk = appOrder[number]; for (int j = 0; j <= number; j++) { int m2 = appOrder[j]; int anotherDist = dist[m1][mk] + dist[mk][m2]; if (dist[m1][m2] > anotherDist) { dist[m1][m2] = anotherDist; } } } /* for (int i = 0; i <= number; i++) { int m1 = appOrder[i]; int mk = appOrder[number]; for (int j = 0; j <= number; j++) { int m2 = appOrder[j]; int anotherDist = dist[m1][m2] + dist[m2][mk]; if (dist[m1][mk] > anotherDist) { dist[m1][mk] = anotherDist; } } } for (int i = 0; i <= number; i++) { int m1 = appOrder[i]; int mk = appOrder[number]; for (int j = 0; j <= number; j++) { int m2 = appOrder[j]; int anotherDist = dist[mk][m1] + dist[m1][m2]; if (dist[mk][m2] > anotherDist) { dist[mk][m2] = anotherDist; } } } */ long ans = 0; for (int i = 0; i <= number; i++) { for (int j = 0; j <= number; j++) { ans = ans + dist[appOrder[i]][appOrder[j]]; } } return ans; } void solve() { int n = in.nextInt(); int dist[][] = new int[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { dist[i][j] = in.nextInt(); } } int order[] = new int[n]; for (int i = 0; i < n; i++) { order[n - 1 - i] = in.nextInt() - 1; } Stack<Long> ans = new Stack<Long>(); for (int i = 0; i < n; i++) { ans.push(getSum(order, i, dist)); } while (!ans.isEmpty()) { out.print(ans.pop()); out.print(" "); } out.println(); } static void check(boolean e) { if (!e) { throw new Error(); } } public void run() { in = new Scanner(System.in); out = new PrintWriter(System.out); try { solve(); } finally { out.close(); } } public static void main(String[] args) { new Main().run(); } }
Java
["1\n0\n1", "2\n0 5\n4 0\n1 2", "4\n0 3 1 1\n6 0 400 1\n2 4 0 1\n1 1 1 0\n4 1 2 3"]
3 seconds
["0", "9 0", "17 23 404 0"]
null
Java 7
standard input
[ "dp", "graphs", "shortest paths" ]
46920a192a8f5fca0f2aad665ba2c22d
The first line contains integer n (1 ≤ n ≤ 500) — the number of vertices in the graph. Next n lines contain n integers each — the graph adjacency matrix: the j-th number in the i-th line aij (1 ≤ aij ≤ 105, aii = 0) represents the weight of the edge that goes from vertex i to vertex j. The next line contains n distinct integers: x1, x2, ..., xn (1 ≤ xi ≤ n) — the vertices that Greg deletes.
1,700
Print n integers — the i-th number equals the required sum before the i-th step. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams of the %I64d specifier.
standard output
PASSED
43f215250adb356a779c50bc06b310a5
train_001.jsonl
1365694200
Greg has a weighed directed graph, consisting of n vertices. In this graph any pair of distinct vertices has an edge between them in both directions. Greg loves playing with the graph and now he has invented a new game: The game consists of n steps. On the i-th step Greg removes vertex number xi from the graph. As Greg removes a vertex, he also removes all the edges that go in and out of this vertex. Before executing each step, Greg wants to know the sum of lengths of the shortest paths between all pairs of the remaining vertices. The shortest path can go through any remaining vertex. In other words, if we assume that d(i, v, u) is the shortest path between vertices v and u in the graph that formed before deleting vertex xi, then Greg wants to know the value of the following sum: . Help Greg, print the value of the required sum before each step.
256 megabytes
import static java.util.Arrays.deepToString; import java.io.*; import java.math.*; import java.util.*; public class B { static void solve() { int n = nextInt(); int[][] d = new int[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { d[i][j] = nextInt(); } } int[] x = new int[n]; for (int i = 0; i < n; i++) { x[i] = nextInt() - 1; } boolean[] have = new boolean[n]; long[] total = new long[n]; for (int t = 0; t < n; t++) { int use = x[n - 1 - t]; have[use] = true; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (d[i][use] + d[use][j] < d[i][j]) { d[i][j] = d[i][use] + d[use][j]; } } } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (have[i] && have[j]) { total[n - 1 - t] += d[i][j]; } } } } for (long v : total) { writer.print(v + " "); } } public static void main(String[] args) throws Exception { reader = new BufferedReader(new InputStreamReader(System.in)); writer = new PrintWriter(System.out); setTime(); solve(); printTime(); printMemory(); writer.close(); } static BufferedReader reader; static PrintWriter writer; static StringTokenizer tok = new StringTokenizer(""); static long systemTime; static void debug(Object... o) { System.err.println(deepToString(o)); } static void setTime() { systemTime = System.currentTimeMillis(); } static void printTime() { System.err.println("Time consumed: " + (System.currentTimeMillis() - systemTime)); } static void printMemory() { System.err.println("Memory consumed: " + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / 1000 + "kb"); } static String next() { while (!tok.hasMoreTokens()) { String w = null; try { w = reader.readLine(); } catch (Exception e) { e.printStackTrace(); } if (w == null) return null; tok = new StringTokenizer(w); } return tok.nextToken(); } static int nextInt() { return Integer.parseInt(next()); } static long nextLong() { return Long.parseLong(next()); } static double nextDouble() { return Double.parseDouble(next()); } static BigInteger nextBigInteger() { return new BigInteger(next()); } }
Java
["1\n0\n1", "2\n0 5\n4 0\n1 2", "4\n0 3 1 1\n6 0 400 1\n2 4 0 1\n1 1 1 0\n4 1 2 3"]
3 seconds
["0", "9 0", "17 23 404 0"]
null
Java 7
standard input
[ "dp", "graphs", "shortest paths" ]
46920a192a8f5fca0f2aad665ba2c22d
The first line contains integer n (1 ≤ n ≤ 500) — the number of vertices in the graph. Next n lines contain n integers each — the graph adjacency matrix: the j-th number in the i-th line aij (1 ≤ aij ≤ 105, aii = 0) represents the weight of the edge that goes from vertex i to vertex j. The next line contains n distinct integers: x1, x2, ..., xn (1 ≤ xi ≤ n) — the vertices that Greg deletes.
1,700
Print n integers — the i-th number equals the required sum before the i-th step. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams of the %I64d specifier.
standard output
PASSED
4d7e7fb1825b8c1130d6a295763dd6a7
train_001.jsonl
1365694200
Greg has a weighed directed graph, consisting of n vertices. In this graph any pair of distinct vertices has an edge between them in both directions. Greg loves playing with the graph and now he has invented a new game: The game consists of n steps. On the i-th step Greg removes vertex number xi from the graph. As Greg removes a vertex, he also removes all the edges that go in and out of this vertex. Before executing each step, Greg wants to know the sum of lengths of the shortest paths between all pairs of the remaining vertices. The shortest path can go through any remaining vertex. In other words, if we assume that d(i, v, u) is the shortest path between vertices v and u in the graph that formed before deleting vertex xi, then Greg wants to know the value of the following sum: . Help Greg, print the value of the required sum before each step.
256 megabytes
import static java.util.Arrays.deepToString; import java.io.*; import java.math.*; import java.util.*; public class Main { static void solve() { int n = nextInt(); int[][] a = new int[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { a[i][j] = nextInt(); } } int[] b = new int[n]; boolean[] v = new boolean[n]; long[] ans = new long[n]; for (int t = 0; t < b.length; t++) { b[t] = nextInt() - 1; } for (int k = n - 1; k >= 0; k--) { v[b[k]] = true; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { a[i][j] = Math.min(a[i][j], a[i][b[k]] + a[b[k]][j]); if (v[i] && v[j]) { ans[k] += (long) a[i][j]; } } } } for (int i = 0; i < ans.length; i++) { System.out.print(ans[i] + " "); } System.out.println(); } public static void main(String[] args) throws Exception { reader = new BufferedReader(new InputStreamReader(System.in)); writer = new PrintWriter(System.out); setTime(); solve(); printTime(); printMemory(); writer.close(); } static BufferedReader reader; static PrintWriter writer; static StringTokenizer tok = new StringTokenizer(""); static long systemTime; static void debug(Object... o) { System.err.println(deepToString(o)); } static void setTime() { systemTime = System.currentTimeMillis(); } static void printTime() { System.err.println("Time consumed: " + (System.currentTimeMillis() - systemTime)); } static void printMemory() { System.err.println("Memory consumed: " + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime() .freeMemory()) / 1000 + "kb"); } static String next() { while (!tok.hasMoreTokens()) { String w = null; try { w = reader.readLine(); } catch (Exception e) { e.printStackTrace(); } if (w == null) return null; tok = new StringTokenizer(w); } return tok.nextToken(); } static int nextInt() { return Integer.parseInt(next()); } static long nextLong() { return Long.parseLong(next()); } static double nextDouble() { return Double.parseDouble(next()); } static BigInteger nextBigInteger() { return new BigInteger(next()); } }
Java
["1\n0\n1", "2\n0 5\n4 0\n1 2", "4\n0 3 1 1\n6 0 400 1\n2 4 0 1\n1 1 1 0\n4 1 2 3"]
3 seconds
["0", "9 0", "17 23 404 0"]
null
Java 7
standard input
[ "dp", "graphs", "shortest paths" ]
46920a192a8f5fca0f2aad665ba2c22d
The first line contains integer n (1 ≤ n ≤ 500) — the number of vertices in the graph. Next n lines contain n integers each — the graph adjacency matrix: the j-th number in the i-th line aij (1 ≤ aij ≤ 105, aii = 0) represents the weight of the edge that goes from vertex i to vertex j. The next line contains n distinct integers: x1, x2, ..., xn (1 ≤ xi ≤ n) — the vertices that Greg deletes.
1,700
Print n integers — the i-th number equals the required sum before the i-th step. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams of the %I64d specifier.
standard output
PASSED
db40ef6247c1e8612600a7616b04ca54
train_001.jsonl
1365694200
Greg has a weighed directed graph, consisting of n vertices. In this graph any pair of distinct vertices has an edge between them in both directions. Greg loves playing with the graph and now he has invented a new game: The game consists of n steps. On the i-th step Greg removes vertex number xi from the graph. As Greg removes a vertex, he also removes all the edges that go in and out of this vertex. Before executing each step, Greg wants to know the sum of lengths of the shortest paths between all pairs of the remaining vertices. The shortest path can go through any remaining vertex. In other words, if we assume that d(i, v, u) is the shortest path between vertices v and u in the graph that formed before deleting vertex xi, then Greg wants to know the value of the following sum: . Help Greg, print the value of the required sum before each step.
256 megabytes
import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Hashtable; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.PriorityQueue; import java.util.Queue; import java.util.Set; import java.util.StringTokenizer; import java.util.Scanner; import java.util.TreeMap; public class Solution{ /////////////////////////////////////////////////////////////////////////// static class FastScanner{ BufferedReader s; StringTokenizer st; public FastScanner(){ st = new StringTokenizer(""); s = new BufferedReader(new InputStreamReader(System.in)); } public FastScanner(File f) throws FileNotFoundException{ st = new StringTokenizer(""); s = new BufferedReader (new FileReader(f)); } public int nextInt() throws IOException{ if(st.hasMoreTokens()) return Integer.parseInt(st.nextToken()); else{ st = new StringTokenizer(s.readLine()); return nextInt(); } } public double nextDouble() throws IOException{ if(st.hasMoreTokens()) return Double.parseDouble(st.nextToken()); else{ st = new StringTokenizer(s.readLine()); return nextDouble(); } } public long nextLong() throws IOException{ if(st.hasMoreTokens()) return Long.parseLong(st.nextToken()); else{ st = new StringTokenizer(s.readLine()); return nextLong(); } } public String nextString() throws IOException{ if(st.hasMoreTokens()) return st.nextToken(); else{ st = new StringTokenizer(s.readLine()); return nextString(); } } public String readLine() throws IOException{ return s.readLine(); } public void close() throws IOException{ s.close(); } } //////////////////////////////////////////////////////////////////// // Number Theory public static int divisor(int x){ int limit = x; int numberOfDivisors = 0; for (int i=1; i < limit; ++i) { if (x % i == 0) { limit = x / i; if (limit != i) { numberOfDivisors++; } numberOfDivisors++; } } return numberOfDivisors; } public static long gcd(long a, long b){ return b == 0 ? a : gcd(b,a%b); } public static long lcm(long a,long b, long c){ return lcm(lcm(a,b),c); } public static long lcm(long a, long b){ return a*b/gcd(a,b); } //////////////////////////////////////////////////////////////////// // private static FastScanner s = new FastScanner(new File("input.txt")); // private static PrintWriter ww = new PrintWriter(new FileWriter("output.txt")); private static FastScanner s = new FastScanner(); private static PrintWriter ww = new PrintWriter(new OutputStreamWriter(System.out)); // private static Scanner s = new Scanner(System.in); @SuppressWarnings("unused") private static Map<Integer,Integer> mm = new HashMap<Integer,Integer>(); @SuppressWarnings("unused") private static Map<Integer,node> mn = new HashMap<Integer,node>(); @SuppressWarnings("unused") private static int[][] states = { {-1,0} , {1,0} , {0,-1} , {0,1} }; //////////////////////////////////////////////////////////////////// static class node implements Comparable<node>{ int to; long cost; public node(int x, long y){ this.to = x; this.cost = y; } @Override public int compareTo(node arg0) { // TODO Auto-generated method stub return Long.compare(cost, arg0.cost); } } public static void main(String[] args) throws IOException{ Solution so = new Solution(); so.solve(); } //////////////////////////////////////////////////////////////////// void solve() throws IOException{ int n = s.nextInt(); int[][] Graph = new int[n][n]; boolean[] vis = new boolean[n]; int[] rem = new int[n]; long[] ans = new long[n]; for(int i=0;i<n;i++) for(int j=0;j<n;j++) Graph[i][j] = s.nextInt(); for(int i=0;i<n;i++) rem[i] = s.nextInt()-1; for(int k=0;k<n;k++){ int m = rem[n-k-1]; vis[m] = true; for(int i=0;i<n;i++) for(int j=0;j<n;j++) Graph[i][j] = Math.min(Graph[i][j],Graph[i][m] + Graph[m][j]); /* ww.println(); for(int i=0;i<n;i++){ for(int j=0;j<n;j++) ww.print(Graph[i][j]+" "); ww.println(); } */ long an = 0; for (int i=0; i<n; i++) if (vis[i]) for (int j=0; j<n; j++) if (vis[j]) an += Graph[i][j]; ans[n-k-1] = an; } for(int i=0;i<n;i++) ww.print(ans[i]+" "); s.close(); ww.close(); } }
Java
["1\n0\n1", "2\n0 5\n4 0\n1 2", "4\n0 3 1 1\n6 0 400 1\n2 4 0 1\n1 1 1 0\n4 1 2 3"]
3 seconds
["0", "9 0", "17 23 404 0"]
null
Java 7
standard input
[ "dp", "graphs", "shortest paths" ]
46920a192a8f5fca0f2aad665ba2c22d
The first line contains integer n (1 ≤ n ≤ 500) — the number of vertices in the graph. Next n lines contain n integers each — the graph adjacency matrix: the j-th number in the i-th line aij (1 ≤ aij ≤ 105, aii = 0) represents the weight of the edge that goes from vertex i to vertex j. The next line contains n distinct integers: x1, x2, ..., xn (1 ≤ xi ≤ n) — the vertices that Greg deletes.
1,700
Print n integers — the i-th number equals the required sum before the i-th step. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams of the %I64d specifier.
standard output
PASSED
05b284d776675428081f6813b71fa8b8
train_001.jsonl
1365694200
Greg has a weighed directed graph, consisting of n vertices. In this graph any pair of distinct vertices has an edge between them in both directions. Greg loves playing with the graph and now he has invented a new game: The game consists of n steps. On the i-th step Greg removes vertex number xi from the graph. As Greg removes a vertex, he also removes all the edges that go in and out of this vertex. Before executing each step, Greg wants to know the sum of lengths of the shortest paths between all pairs of the remaining vertices. The shortest path can go through any remaining vertex. In other words, if we assume that d(i, v, u) is the shortest path between vertices v and u in the graph that formed before deleting vertex xi, then Greg wants to know the value of the following sum: . Help Greg, print the value of the required sum before each step.
256 megabytes
import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Hashtable; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.PriorityQueue; import java.util.Queue; import java.util.Set; import java.util.StringTokenizer; import java.util.Scanner; import java.util.TreeMap; public class Solution{ /////////////////////////////////////////////////////////////////////////// static class FastScanner{ BufferedReader s; StringTokenizer st; public FastScanner(){ st = new StringTokenizer(""); s = new BufferedReader(new InputStreamReader(System.in)); } public FastScanner(File f) throws FileNotFoundException{ st = new StringTokenizer(""); s = new BufferedReader (new FileReader(f)); } public int nextInt() throws IOException{ if(st.hasMoreTokens()) return Integer.parseInt(st.nextToken()); else{ st = new StringTokenizer(s.readLine()); return nextInt(); } } public double nextDouble() throws IOException{ if(st.hasMoreTokens()) return Double.parseDouble(st.nextToken()); else{ st = new StringTokenizer(s.readLine()); return nextDouble(); } } public long nextLong() throws IOException{ if(st.hasMoreTokens()) return Long.parseLong(st.nextToken()); else{ st = new StringTokenizer(s.readLine()); return nextLong(); } } public String nextString() throws IOException{ if(st.hasMoreTokens()) return st.nextToken(); else{ st = new StringTokenizer(s.readLine()); return nextString(); } } public String readLine() throws IOException{ return s.readLine(); } public void close() throws IOException{ s.close(); } } //////////////////////////////////////////////////////////////////// // Number Theory public static int divisor(int x){ int limit = x; int numberOfDivisors = 0; for (int i=1; i < limit; ++i) { if (x % i == 0) { limit = x / i; if (limit != i) { numberOfDivisors++; } numberOfDivisors++; } } return numberOfDivisors; } public static long gcd(long a, long b){ return b == 0 ? a : gcd(b,a%b); } public static long lcm(long a,long b, long c){ return lcm(lcm(a,b),c); } public static long lcm(long a, long b){ return a*b/gcd(a,b); } //////////////////////////////////////////////////////////////////// // private static FastScanner s = new FastScanner(new File("input.txt")); // private static PrintWriter ww = new PrintWriter(new FileWriter("output.txt")); private static FastScanner s = new FastScanner(); private static PrintWriter ww = new PrintWriter(new OutputStreamWriter(System.out)); // private static Scanner s = new Scanner(System.in); @SuppressWarnings("unused") private static Map<Integer,Integer> mm = new HashMap<Integer,Integer>(); @SuppressWarnings("unused") private static Map<Integer,node> mn = new HashMap<Integer,node>(); @SuppressWarnings("unused") private static int[][] states = { {-1,0} , {1,0} , {0,-1} , {0,1} }; //////////////////////////////////////////////////////////////////// static class node implements Comparable<node>{ int to; long cost; public node(int x, long y){ this.to = x; this.cost = y; } @Override public int compareTo(node arg0) { // TODO Auto-generated method stub return Long.compare(cost, arg0.cost); } } public static void main(String[] args) throws IOException{ Solution so = new Solution(); so.solve(); } //////////////////////////////////////////////////////////////////// void solve() throws IOException{ int n = s.nextInt(); int[][] Graph = new int[n][n]; boolean[] vis = new boolean[n]; int[] rem = new int[n]; long[] ans = new long[n]; for(int i=0;i<n;i++) for(int j=0;j<n;j++) Graph[i][j] = s.nextInt(); for(int i=0;i<n;i++) rem[i] = s.nextInt()-1; for(int k=0;k<n;k++){ int m = rem[n-k-1]; vis[m] = true; for(int i=0;i<n;i++) for(int j=0;j<n;j++) Graph[i][j] = Math.min(Graph[i][j],Graph[i][m] + Graph[m][j]); long an = 0; for (int i=0; i<n; i++) if (vis[i]) for (int j=0; j<n; j++) if (vis[j]) an+=Graph[i][j]; ans[n-k-1] = an; } for(int i=0;i<n;i++) ww.print(ans[i]+" "); s.close(); ww.close(); } }
Java
["1\n0\n1", "2\n0 5\n4 0\n1 2", "4\n0 3 1 1\n6 0 400 1\n2 4 0 1\n1 1 1 0\n4 1 2 3"]
3 seconds
["0", "9 0", "17 23 404 0"]
null
Java 7
standard input
[ "dp", "graphs", "shortest paths" ]
46920a192a8f5fca0f2aad665ba2c22d
The first line contains integer n (1 ≤ n ≤ 500) — the number of vertices in the graph. Next n lines contain n integers each — the graph adjacency matrix: the j-th number in the i-th line aij (1 ≤ aij ≤ 105, aii = 0) represents the weight of the edge that goes from vertex i to vertex j. The next line contains n distinct integers: x1, x2, ..., xn (1 ≤ xi ≤ n) — the vertices that Greg deletes.
1,700
Print n integers — the i-th number equals the required sum before the i-th step. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams of the %I64d specifier.
standard output
PASSED
e29e95cad7916b1ae8ec56268120bb8a
train_001.jsonl
1365694200
Greg has a weighed directed graph, consisting of n vertices. In this graph any pair of distinct vertices has an edge between them in both directions. Greg loves playing with the graph and now he has invented a new game: The game consists of n steps. On the i-th step Greg removes vertex number xi from the graph. As Greg removes a vertex, he also removes all the edges that go in and out of this vertex. Before executing each step, Greg wants to know the sum of lengths of the shortest paths between all pairs of the remaining vertices. The shortest path can go through any remaining vertex. In other words, if we assume that d(i, v, u) is the shortest path between vertices v and u in the graph that formed before deleting vertex xi, then Greg wants to know the value of the following sum: . Help Greg, print the value of the required sum before each step.
256 megabytes
import static java.lang.Math.*; import static java.util.Arrays.*; import java.util.*; //@SuppressWarnings("unused") public class B { private final static boolean autoflush = false; public B () { int N = sc.nextInt(); Long [][] A = sc.nextLongs(N); Integer [] X = sc.nextInts(); int [] Y = new int [N]; for (int i = 0; i < N; ++i) Y[i] = X[N-1-i] - 1; long [][] G = new long [N][N]; for (int i = 0; i < N; ++i) for (int j = 0; j < N; ++j) G[i][j] = A[Y[i]][Y[j]]; long [] R = new long [N]; for (int i = 1; i < N; ++i) { Long [] H = new Long [i], V = new Long [i]; for (int j = 0; j < i; ++j) { H[j] = G[i][j]; V[j] = G[j][i]; } Integer [] J = si(H), K = si(V); R[i] = R[i-1]; for (int j = 0; j < i; ++j) { for (int k = 0; k < j; ++k) { int r, s; r = J[j]; s = J[k]; G[i][r] = min(G[i][r], G[i][s] + G[s][r]); r = K[j]; s = K[k]; G[r][i] = min(G[r][i], G[r][s] + G[s][i]); } R[i] += G[i][J[j]] + G[K[j]][i]; } for (int j = 0; j < i; ++j) for (int k = 0; k < i; ++k) { long L = G[j][i] + G[i][k]; if (L < G[j][k]) { R[i] -= (G[j][k] - L); G[j][k] = L; } } } long [] res = new long [N]; for (int i = 0; i < N; ++i) res[i] = R[N-1-i]; exit(res); } <T extends Comparable<T>> Integer [] si(final T [] X) { return si(X, new Comparator<T> () { @Override public int compare (T x, T y) { return x.compareTo(y); } }); } <T> Integer [] si(final T [] X, final Comparator<T> C) { int N = X.length; Integer [] J = new Integer [N]; for (int i = 0; i < N; ++i) J[i] = i; sort(J, new Comparator<Integer>() { @Override public int compare(Integer i, Integer j) { int res = C.compare(X[i], X[j]); return res != 0 ? res : i.compareTo(j); } }); return J; } //////////////////////////////////////////////////////////////////////////////////// private static int [] rep(int N) { return rep(0, N); } private static int [] rep(int S, int T) { int [] res = new int [max(T-S, 0)]; for (int i = S; i < T; ++i) res[i-S] = i; return res; } private static <T extends Comparable<T>> T max(T x, T y) { return x.compareTo(y) > 0 ? x : y; } //////////////////////////////////////////////////////////////////////////////////// private final static MyScanner sc = new MyScanner(); private static class MyScanner { private String next() { newLine(); return line[index++]; } private int nextInt() { return Integer.parseInt(next()); } private String [] nextStrings() { line = null; return readLine().split(" "); } private Integer [] nextInts() { String [] L = nextStrings(); Integer [] res = new Integer [L.length]; for (int i : rep(L.length)) res[i] = Integer.parseInt(L[i]); return res; } private Long [] nextLongs() { String [] L = nextStrings(); Long [] res = new Long [L.length]; for (int i : rep(L.length)) res[i] = Long.parseLong(L[i]); return res; } private Long [][] nextLongs (int N) { Long [][] res = new Long [N][]; for (int i : rep(N)) res[i] = nextLongs(); return res; } ////////////////////////////////////////////// private boolean eol() { return index == line.length; } private String readLine() { try { return r.readLine(); } catch (Exception e) { throw new Error (e); } } private final java.io.BufferedReader r; private MyScanner () { this(new java.io.BufferedReader(new java.io.InputStreamReader(System.in))); } private MyScanner (java.io.BufferedReader r) { try { this.r = r; while (!r.ready()) Thread.sleep(1); start(); } catch (Exception e) { throw new Error(e); } } private String [] line; private int index; private void newLine() { if (line == null || eol()) { line = readLine().split(" "); index = 0; } } } private static void print (Object o, Object... a) { printDelim(" ", o, a); } private static void printDelim (String delim, Object o, Object... a) { pw.println(build(delim, o, a)); } private static void exit (Object o, Object... a) { print(o, a); exit(); } private static void exit() { pw.close(); System.out.flush(); System.err.println("------------------"); System.err.println("Time: " + ((millis() - t) / 1000.0)); System.exit(0); } //////////////////////////////////////////////////////////////////////////////////// private static String build (String delim, Object o, Object... a) { StringBuilder b = new StringBuilder(); append(b, o, delim); for (Object p : a) append(b, p, delim); return b.toString().trim(); } private static void append(StringBuilder b, Object o, String delim) { if (o.getClass().isArray()) { int L = java.lang.reflect.Array.getLength(o); for (int i : rep(L)) append(b, java.lang.reflect.Array.get(o, i), delim); } else if (o instanceof Iterable<?>) for (Object p : (Iterable<?>)o) append(b, p, delim); else b.append(delim).append(o); } //////////////////////////////////////////////////////////////////////////////////// private static void start() { t = millis(); } private static java.io.PrintWriter pw = new java.io.PrintWriter(System.out, autoflush); private static long t; private static long millis() { return System.currentTimeMillis(); } public static void main (String[] args) { new B(); exit(); } }
Java
["1\n0\n1", "2\n0 5\n4 0\n1 2", "4\n0 3 1 1\n6 0 400 1\n2 4 0 1\n1 1 1 0\n4 1 2 3"]
3 seconds
["0", "9 0", "17 23 404 0"]
null
Java 7
standard input
[ "dp", "graphs", "shortest paths" ]
46920a192a8f5fca0f2aad665ba2c22d
The first line contains integer n (1 ≤ n ≤ 500) — the number of vertices in the graph. Next n lines contain n integers each — the graph adjacency matrix: the j-th number in the i-th line aij (1 ≤ aij ≤ 105, aii = 0) represents the weight of the edge that goes from vertex i to vertex j. The next line contains n distinct integers: x1, x2, ..., xn (1 ≤ xi ≤ n) — the vertices that Greg deletes.
1,700
Print n integers — the i-th number equals the required sum before the i-th step. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams of the %I64d specifier.
standard output
PASSED
17600c15bfcb35959a79a58d6b448cd2
train_001.jsonl
1365694200
Greg has a weighed directed graph, consisting of n vertices. In this graph any pair of distinct vertices has an edge between them in both directions. Greg loves playing with the graph and now he has invented a new game: The game consists of n steps. On the i-th step Greg removes vertex number xi from the graph. As Greg removes a vertex, he also removes all the edges that go in and out of this vertex. Before executing each step, Greg wants to know the sum of lengths of the shortest paths between all pairs of the remaining vertices. The shortest path can go through any remaining vertex. In other words, if we assume that d(i, v, u) is the shortest path between vertices v and u in the graph that formed before deleting vertex xi, then Greg wants to know the value of the following sum: . Help Greg, print the value of the required sum before each step.
256 megabytes
// @author Sanzhar import java.io.*; import java.util.*; import java.awt.Point; public class Template { BufferedReader in; PrintWriter out; StringTokenizer st; String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(in.readLine()); } catch (Exception e) { } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } public void run() throws Exception { //in = new BufferedReader(new FileReader("input.txt")); //out = new PrintWriter(new FileWriter("output.txt")); in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); out.flush(); out.close(); in.close(); } public void solve() throws Exception { int n = nextInt(); int[][] a = new int[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { a[i][j] = nextInt(); } } int[] num = new int[n]; for (int i = 0; i < n; i++) { int x = nextInt() - 1; num[x] = n - i - 1; } int[][] d = new int[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { d[num[i]][num[j]] = a[i][j]; } } long[] ans = new long[n]; for (int k = 0; k < n; k++) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { d[i][j] = Math.min(d[i][j], d[i][k] + d[k][j]); } } long cur = 0; for (int i = 0; i <= k; i++) { for (int j = 0; j <= k; j++) { cur += d[i][j]; } } ans[n - k - 1] = cur; } for (int i = 0; i < n; i++) { out.print(ans[i] + " "); } out.println(); } public static void main(String[] args) throws Exception { new Template().run(); } }
Java
["1\n0\n1", "2\n0 5\n4 0\n1 2", "4\n0 3 1 1\n6 0 400 1\n2 4 0 1\n1 1 1 0\n4 1 2 3"]
3 seconds
["0", "9 0", "17 23 404 0"]
null
Java 7
standard input
[ "dp", "graphs", "shortest paths" ]
46920a192a8f5fca0f2aad665ba2c22d
The first line contains integer n (1 ≤ n ≤ 500) — the number of vertices in the graph. Next n lines contain n integers each — the graph adjacency matrix: the j-th number in the i-th line aij (1 ≤ aij ≤ 105, aii = 0) represents the weight of the edge that goes from vertex i to vertex j. The next line contains n distinct integers: x1, x2, ..., xn (1 ≤ xi ≤ n) — the vertices that Greg deletes.
1,700
Print n integers — the i-th number equals the required sum before the i-th step. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams of the %I64d specifier.
standard output