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
c5c4d41c9fb0ef7363fc122e7167132e
train_003.jsonl
1454835900
A long time ago, in a galaxy far far away two giant IT-corporations Pineapple and Gogol continue their fierce competition. Crucial moment is just around the corner: Gogol is ready to release it's new tablet Lastus 3000.This new device is equipped with specially designed artificial intelligence (AI). Employees of Pineapple did their best to postpone the release of Lastus 3000 as long as possible. Finally, they found out, that the name of the new artificial intelligence is similar to the name of the phone, that Pineapple released 200 years ago. As all rights on its name belong to Pineapple, they stand on changing the name of Gogol's artificial intelligence.Pineapple insists, that the name of their phone occurs in the name of AI as a substring. Because the name of technology was already printed on all devices, the Gogol's director decided to replace some characters in AI name with "#". As this operation is pretty expensive, you should find the minimum number of characters to replace with "#", such that the name of AI doesn't contain the name of the phone as a substring.Substring is a continuous subsequence of a string.
256 megabytes
import java.util.*; public class intro{ public static void main(String[] args){ Scanner in=new Scanner(System.in); String a=in.next(); String b=in.next(); int x=a.length(); a=a.replaceAll(b,""); System.out.println((x-a.length())/b.length()); } }
Java
["intellect\ntell", "google\napple", "sirisiri\nsir"]
1 second
["1", "0", "2"]
NoteIn the first sample AI's name may be replaced with "int#llect".In the second sample Gogol can just keep things as they are.In the third sample one of the new possible names of AI may be "s#ris#ri".
Java 7
standard input
[ "constructive algorithms", "greedy", "strings" ]
62a672fcaee8be282700176803c623a7
The first line of the input contains the name of AI designed by Gogol, its length doesn't exceed 100 000 characters. Second line contains the name of the phone released by Pineapple 200 years ago, its length doesn't exceed 30. Both string are non-empty and consist of only small English letters.
1,200
Print the minimum number of characters that must be replaced with "#" in order to obtain that the name of the phone doesn't occur in the name of AI as a substring.
standard output
PASSED
28b57c73a2899c8493909d46d3d8a5cd
train_003.jsonl
1454835900
A long time ago, in a galaxy far far away two giant IT-corporations Pineapple and Gogol continue their fierce competition. Crucial moment is just around the corner: Gogol is ready to release it's new tablet Lastus 3000.This new device is equipped with specially designed artificial intelligence (AI). Employees of Pineapple did their best to postpone the release of Lastus 3000 as long as possible. Finally, they found out, that the name of the new artificial intelligence is similar to the name of the phone, that Pineapple released 200 years ago. As all rights on its name belong to Pineapple, they stand on changing the name of Gogol's artificial intelligence.Pineapple insists, that the name of their phone occurs in the name of AI as a substring. Because the name of technology was already printed on all devices, the Gogol's director decided to replace some characters in AI name with "#". As this operation is pretty expensive, you should find the minimum number of characters to replace with "#", such that the name of AI doesn't contain the name of the phone as a substring.Substring is a continuous subsequence of a string.
256 megabytes
import java.util.Scanner; public class B625 { public static void main(String[] args) { Scanner scan = new Scanner(System.in); String gog = scan.nextLine(); String pin = scan.nextLine(); int hash = 0, start = 0; while (true) { int mIndex = gog.indexOf(pin, start); if (mIndex == -1) break; hash++; start = mIndex + pin.length(); } System.out.println(hash); } }
Java
["intellect\ntell", "google\napple", "sirisiri\nsir"]
1 second
["1", "0", "2"]
NoteIn the first sample AI's name may be replaced with "int#llect".In the second sample Gogol can just keep things as they are.In the third sample one of the new possible names of AI may be "s#ris#ri".
Java 7
standard input
[ "constructive algorithms", "greedy", "strings" ]
62a672fcaee8be282700176803c623a7
The first line of the input contains the name of AI designed by Gogol, its length doesn't exceed 100 000 characters. Second line contains the name of the phone released by Pineapple 200 years ago, its length doesn't exceed 30. Both string are non-empty and consist of only small English letters.
1,200
Print the minimum number of characters that must be replaced with "#" in order to obtain that the name of the phone doesn't occur in the name of AI as a substring.
standard output
PASSED
4628a6a425fff4dcfd073f515eb7f090
train_003.jsonl
1454835900
A long time ago, in a galaxy far far away two giant IT-corporations Pineapple and Gogol continue their fierce competition. Crucial moment is just around the corner: Gogol is ready to release it's new tablet Lastus 3000.This new device is equipped with specially designed artificial intelligence (AI). Employees of Pineapple did their best to postpone the release of Lastus 3000 as long as possible. Finally, they found out, that the name of the new artificial intelligence is similar to the name of the phone, that Pineapple released 200 years ago. As all rights on its name belong to Pineapple, they stand on changing the name of Gogol's artificial intelligence.Pineapple insists, that the name of their phone occurs in the name of AI as a substring. Because the name of technology was already printed on all devices, the Gogol's director decided to replace some characters in AI name with "#". As this operation is pretty expensive, you should find the minimum number of characters to replace with "#", such that the name of AI doesn't contain the name of the phone as a substring.Substring is a continuous subsequence of a string.
256 megabytes
import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.Buffer; import java.nio.charset.Charset; import java.util.Arrays; import java.util.Scanner; public class PUTOVANJE { public static void main(String[] args) throws IOException { Scanner sc=new Scanner(System.in); String s=sc.next(); String s2=sc.next(); int i=0; long count=0; while((i=s.indexOf(s2, i))!=-1) { count++; i+=s2.length(); } System.out.println(count); } }
Java
["intellect\ntell", "google\napple", "sirisiri\nsir"]
1 second
["1", "0", "2"]
NoteIn the first sample AI's name may be replaced with "int#llect".In the second sample Gogol can just keep things as they are.In the third sample one of the new possible names of AI may be "s#ris#ri".
Java 7
standard input
[ "constructive algorithms", "greedy", "strings" ]
62a672fcaee8be282700176803c623a7
The first line of the input contains the name of AI designed by Gogol, its length doesn't exceed 100 000 characters. Second line contains the name of the phone released by Pineapple 200 years ago, its length doesn't exceed 30. Both string are non-empty and consist of only small English letters.
1,200
Print the minimum number of characters that must be replaced with "#" in order to obtain that the name of the phone doesn't occur in the name of AI as a substring.
standard output
PASSED
5da161a2c17d6e3fba1f7783b3307ffb
train_003.jsonl
1454835900
A long time ago, in a galaxy far far away two giant IT-corporations Pineapple and Gogol continue their fierce competition. Crucial moment is just around the corner: Gogol is ready to release it's new tablet Lastus 3000.This new device is equipped with specially designed artificial intelligence (AI). Employees of Pineapple did their best to postpone the release of Lastus 3000 as long as possible. Finally, they found out, that the name of the new artificial intelligence is similar to the name of the phone, that Pineapple released 200 years ago. As all rights on its name belong to Pineapple, they stand on changing the name of Gogol's artificial intelligence.Pineapple insists, that the name of their phone occurs in the name of AI as a substring. Because the name of technology was already printed on all devices, the Gogol's director decided to replace some characters in AI name with "#". As this operation is pretty expensive, you should find the minimum number of characters to replace with "#", such that the name of AI doesn't contain the name of the phone as a substring.Substring is a continuous subsequence of a string.
256 megabytes
import java.io.FileInputStream; import java.io.FileNotFoundException; import java.util.Scanner; public class WarCorporations { public static void main(String[] args) throws FileNotFoundException { Scanner sc = new Scanner(System.in); // Scanner sc = new Scanner(new FileInputStream("input.txt")); String s1 = sc.nextLine(); String s2 = sc.nextLine(); int lengS1 = s1.length(); int lengS2 = s2.length(); int dem = 0; for(int i =0; i <= s1.length() - s2.length();){ String sub1 = s1.substring(i, i+s2.length()); if(sub1.equals(s2)){ dem++; i = i+ s2.length(); }else { i++; } } System.out.println(dem); } }
Java
["intellect\ntell", "google\napple", "sirisiri\nsir"]
1 second
["1", "0", "2"]
NoteIn the first sample AI's name may be replaced with "int#llect".In the second sample Gogol can just keep things as they are.In the third sample one of the new possible names of AI may be "s#ris#ri".
Java 7
standard input
[ "constructive algorithms", "greedy", "strings" ]
62a672fcaee8be282700176803c623a7
The first line of the input contains the name of AI designed by Gogol, its length doesn't exceed 100 000 characters. Second line contains the name of the phone released by Pineapple 200 years ago, its length doesn't exceed 30. Both string are non-empty and consist of only small English letters.
1,200
Print the minimum number of characters that must be replaced with "#" in order to obtain that the name of the phone doesn't occur in the name of AI as a substring.
standard output
PASSED
a5bb2d40b84e3f2865decafa050e5e49
train_003.jsonl
1454835900
A long time ago, in a galaxy far far away two giant IT-corporations Pineapple and Gogol continue their fierce competition. Crucial moment is just around the corner: Gogol is ready to release it's new tablet Lastus 3000.This new device is equipped with specially designed artificial intelligence (AI). Employees of Pineapple did their best to postpone the release of Lastus 3000 as long as possible. Finally, they found out, that the name of the new artificial intelligence is similar to the name of the phone, that Pineapple released 200 years ago. As all rights on its name belong to Pineapple, they stand on changing the name of Gogol's artificial intelligence.Pineapple insists, that the name of their phone occurs in the name of AI as a substring. Because the name of technology was already printed on all devices, the Gogol's director decided to replace some characters in AI name with "#". As this operation is pretty expensive, you should find the minimum number of characters to replace with "#", such that the name of AI doesn't contain the name of the phone as a substring.Substring is a continuous subsequence of a string.
256 megabytes
import java.util.*; import java.util.regex.Pattern; import java.util.regex.Matcher; public class WarOfTheCorporations { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String lastusName = sc.nextLine(); String pineapplePhone = sc.nextLine(); int count = 0; //Java Regex : Boyer-Moore algorithm. Worst case still O(nm) Pattern p = Pattern.compile(pineapplePhone); Matcher m = p.matcher(lastusName); while (m.find()){ count +=1; } System.out.println(count); sc.close(); } }
Java
["intellect\ntell", "google\napple", "sirisiri\nsir"]
1 second
["1", "0", "2"]
NoteIn the first sample AI's name may be replaced with "int#llect".In the second sample Gogol can just keep things as they are.In the third sample one of the new possible names of AI may be "s#ris#ri".
Java 7
standard input
[ "constructive algorithms", "greedy", "strings" ]
62a672fcaee8be282700176803c623a7
The first line of the input contains the name of AI designed by Gogol, its length doesn't exceed 100 000 characters. Second line contains the name of the phone released by Pineapple 200 years ago, its length doesn't exceed 30. Both string are non-empty and consist of only small English letters.
1,200
Print the minimum number of characters that must be replaced with "#" in order to obtain that the name of the phone doesn't occur in the name of AI as a substring.
standard output
PASSED
685f0b43b0193d685c2227da17ed6b4a
train_003.jsonl
1603011900
Pink Floyd are pulling a prank on Roger Waters. They know he doesn't like walls, he wants to be able to walk freely, so they are blocking him from exiting his room which can be seen as a grid.Roger Waters has a square grid of size $$$n\times n$$$ and he wants to traverse his grid from the upper left ($$$1,1$$$) corner to the lower right corner ($$$n,n$$$). Waters can move from a square to any other square adjacent by a side, as long as he is still in the grid. Also except for the cells ($$$1,1$$$) and ($$$n,n$$$) every cell has a value $$$0$$$ or $$$1$$$ in it.Before starting his traversal he will pick either a $$$0$$$ or a $$$1$$$ and will be able to only go to cells values in which are equal to the digit he chose. The starting and finishing cells ($$$1,1$$$) and ($$$n,n$$$) are exempt from this rule, he may go through them regardless of picked digit. Because of this the cell ($$$1,1$$$) takes value the letter 'S' and the cell ($$$n,n$$$) takes value the letter 'F'.For example, in the first example test case, he can go from ($$$1, 1$$$) to ($$$n, n$$$) by using the zeroes on this path: ($$$1, 1$$$), ($$$2, 1$$$), ($$$2, 2$$$), ($$$2, 3$$$), ($$$3, 3$$$), ($$$3, 4$$$), ($$$4, 4$$$)The rest of the band (Pink Floyd) wants Waters to not be able to do his traversal, so while he is not looking they will invert at most two cells in the grid (from $$$0$$$ to $$$1$$$ or vice versa). They are afraid they will not be quick enough and asked for your help in choosing the cells. Note that you cannot invert cells $$$(1, 1)$$$ and $$$(n, n)$$$.We can show that there always exists a solution for the given constraints.Also note that Waters will pick his digit of the traversal after the band has changed his grid, so he must not be able to reach ($$$n,n$$$) no matter what digit he picks.
256 megabytes
import java.util.*; import java.io.*; public class B{ static class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar, snumChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int snext() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } public String readString() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isSpaceChar(c)); return res.toString(); } public String nextLine() { int c = snext(); while (isSpaceChar(c)) c = snext(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isEndOfLine(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || 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 print(Object...objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.print(objects[i]); } } public void printLine(Object...objects) { print(objects); writer.println(); } public void close() { writer.close(); } public void flush() { writer.flush(); } } static int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a); } static int mod = (int)(1e9+7); public static long pow(long a,long b) { long ans = 1; while(b> 0) { if((b & 1)==1){ ans = (ans*a) % mod; } a = (a*a) % mod; b = b>>1; } return ans; } static void sort(int[] a) { ArrayList<Integer> l=new ArrayList<>(); for (int i:a) l.add(i); Collections.sort(l); for (int i=0; i<a.length; i++) a[i]=l.get(i); } public static void main(String[] args) { InputReader in = new InputReader(System.in); OutputWriter out = new OutputWriter(System.out); int t = in.nextInt(); while(t-- >0) { int n = in.nextInt(); char[][] grid = new char[n][n]; for(int i=0;i<n;i++) grid[i] = in.nextLine().toCharArray(); char x = grid[0][1],y = grid[1][0]; char u = grid[n-1][n-2],v = grid[n-2][n-1]; if(x=='0' && y=='0') { if(u=='0' && v=='0') { out.printLine(2); out.printLine((n) + " " + (n-1)); out.printLine((n-1) + " " + (n)); } else if(u=='0' && v=='1') { out.printLine(1); out.printLine((n) + " " + (n-1)); } else if(u=='1' && v=='0') { out.printLine(1); out.printLine((n-1) + " " + (n)); } else { out.printLine(0); } } else if(x=='0' && y=='1') { if(u=='0' && v=='0') { out.printLine(1); out.printLine(1 + " " + 2); } else if(u=='0' && v=='1') { out.printLine(2); out.printLine((n) + " " + (n-1)); out.printLine(2 + " " + 1 ); } else if(u=='1' && v=='0') { out.printLine(2); out.printLine((n-1) + " " + (n)); out.printLine(2 + " " + 1 ); } else { out.printLine(1); out.printLine(2 + " " + 1 ); } } else if(x=='1' && y=='0') { if(u=='0' && v=='0') { out.printLine(1); out.printLine(2 + " " + 1); } else if(u=='0' && v=='1') { out.printLine(2); out.printLine((n) + " " + (n-1)); out.printLine(1 + " " + 2); } else if(u=='1' && v=='0') { out.printLine(2); out.printLine((n-1) + " " + (n)); out.printLine(1 + " " + 2 ); } else { out.printLine(1); out.printLine(1 + " " + 2 ); } } else{ if(u=='0' && v=='0') { out.printLine(0); } else if(u=='0' && v=='1') { out.printLine(1); out.printLine((n-1) + " " + (n)); } else if(u=='1' && v=='0') { out.printLine(1); out.printLine((n) + " " + (n-1)); // out.printLine(1 + " " + 2 ); } else { out.printLine(2); out.printLine((n-1) + " " + (n)); out.printLine((n) + " " + (n-1)); } } } out.flush(); out.close(); } }
Java
["3\n4\nS010\n0001\n1000\n111F\n3\nS10\n101\n01F\n5\nS0101\n00000\n01111\n11111\n0001F"]
1 second
["1\n3 4\n2\n1 2\n2 1\n0"]
NoteFor the first test case, after inverting the cell, we get the following grid:S01000011001111F
Java 11
standard input
[ "constructive algorithms", "implementation" ]
be60cca56505e4b04d24c9b4990553c7
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 50$$$). Description of the test cases follows. The first line of each test case contains one integers $$$n$$$ ($$$3 \le n \le 200$$$). The following $$$n$$$ lines of each test case contain the binary grid, square ($$$1, 1$$$) being colored in 'S' and square ($$$n, n$$$) being colored in 'F'. The sum of values of $$$n$$$ doesn't exceed $$$200$$$.
1,100
For each test case output on the first line an integer $$$c$$$ ($$$0 \le c \le 2$$$)  — the number of inverted cells. In $$$i$$$-th of the following $$$c$$$ lines, print the coordinates of the $$$i$$$-th cell you inverted. You may not invert the same cell twice. Note that you cannot invert cells $$$(1, 1)$$$ and $$$(n, n)$$$.
standard output
PASSED
b6f31c7da1bd4ad50c442378336c434d
train_003.jsonl
1603011900
Pink Floyd are pulling a prank on Roger Waters. They know he doesn't like walls, he wants to be able to walk freely, so they are blocking him from exiting his room which can be seen as a grid.Roger Waters has a square grid of size $$$n\times n$$$ and he wants to traverse his grid from the upper left ($$$1,1$$$) corner to the lower right corner ($$$n,n$$$). Waters can move from a square to any other square adjacent by a side, as long as he is still in the grid. Also except for the cells ($$$1,1$$$) and ($$$n,n$$$) every cell has a value $$$0$$$ or $$$1$$$ in it.Before starting his traversal he will pick either a $$$0$$$ or a $$$1$$$ and will be able to only go to cells values in which are equal to the digit he chose. The starting and finishing cells ($$$1,1$$$) and ($$$n,n$$$) are exempt from this rule, he may go through them regardless of picked digit. Because of this the cell ($$$1,1$$$) takes value the letter 'S' and the cell ($$$n,n$$$) takes value the letter 'F'.For example, in the first example test case, he can go from ($$$1, 1$$$) to ($$$n, n$$$) by using the zeroes on this path: ($$$1, 1$$$), ($$$2, 1$$$), ($$$2, 2$$$), ($$$2, 3$$$), ($$$3, 3$$$), ($$$3, 4$$$), ($$$4, 4$$$)The rest of the band (Pink Floyd) wants Waters to not be able to do his traversal, so while he is not looking they will invert at most two cells in the grid (from $$$0$$$ to $$$1$$$ or vice versa). They are afraid they will not be quick enough and asked for your help in choosing the cells. Note that you cannot invert cells $$$(1, 1)$$$ and $$$(n, n)$$$.We can show that there always exists a solution for the given constraints.Also note that Waters will pick his digit of the traversal after the band has changed his grid, so he must not be able to reach ($$$n,n$$$) no matter what digit he picks.
256 megabytes
import java.util.*; import java.io.*; import java.math.*; public class B { static FastReader sc=new FastReader(); public static void main(String[] args) { int ttt =i(); outer :while (ttt-- > 0) { StringBuffer sb=new StringBuffer(""); int n=i(); String A[]=inputS(n); int c=0; if(A[n-1].charAt(n-2)==A[n-2].charAt(n-1) && A[n-1].charAt(n-2)=='0') { char a=A[0].charAt(1); char b=A[1].charAt(0); if(a!='1') { c++; sb.append("1 2"+"\n"); } if(b!='1') { c++; sb.append("2 1"+"\n"); } System.out.println(c); System.out.println(sb.toString()); continue outer; } else if(A[n-1].charAt(n-2)==A[n-2].charAt(n-1) && A[n-1].charAt(n-2)=='1') { char a=A[0].charAt(1); char b=A[1].charAt(0); if(a!='0') { c++; sb.append("1 2"+"\n"); } if(b!='0') { c++; sb.append("2 1"+"\n"); } System.out.println(c); System.out.println(sb.toString()); continue outer; } char a=A[0].charAt(1); char b=A[1].charAt(0); if(a==b && a=='0') { if(A[n-1].charAt(n-2)!='1') { c++; sb.append(n+" "+(n-1)+"\n"); } if(A[n-2].charAt(n-1)!='1') { c++; sb.append((n-1)+" "+(n)+"\n"); } System.out.println(c); System.out.println(sb.toString()); continue outer; } else if(a==b && a=='1') { if(A[n-1].charAt(n-2)!='0') { c++; sb.append(n+" "+(n-1)+"\n"); } if(A[n-2].charAt(n-1)!='0') { c++; sb.append((n-1)+" "+(n)+"\n"); } System.out.println(c); System.out.println(sb.toString()); continue outer; } char aaa=A[0].charAt(1); char bbb=A[1].charAt(0); char aa=A[n-1].charAt(n-2); char bb=A[n-2].charAt(n-1); c=2; sb.append("1 2"+"\n"); if(aaa=='0') { if(aa!='0') { sb.append(n+" "+(n-1)+"\n"); } if(bb!='0') { sb.append((n-1)+" "+(n)+"\n"); } System.out.println(c); System.out.println(sb.toString()); } else { if(aa!='1') { sb.append(n+" "+(n-1)+"\n"); } if(bb!='1') { sb.append((n-1)+" "+(n)+"\n"); } System.out.println(c); System.out.println(sb.toString()); } } // System.out.println(sb.toString()); } static int[] input(int n) { int A[]=new int[n]; for(int i=0;i<n;i++) { A[i]=sc.nextInt(); } return A; } static long[] inputL(int n) { long A[]=new long[n]; for(int i=0;i<n;i++) { A[i]=sc.nextLong(); } return A; } static String[] inputS(int n) { String A[]=new String[n]; for(int i=0;i<n;i++) { A[i]=sc.next(); } return A; } static void input(int A[],int B[]) { for(int i=0;i<A.length;i++) { A[i]=sc.nextInt(); B[i]=sc.nextInt(); } } static int max(int A[]) { int max=Integer.MIN_VALUE; for(int i=0;i<A.length;i++) { max=Math.max(max, A[i]); } return max; } static int min(int A[]) { int min=Integer.MAX_VALUE; for(int i=0;i<A.length;i++) { min=Math.min(min, A[i]); } return min; } static long max(long A[]) { long max=Long.MIN_VALUE; for(int i=0;i<A.length;i++) { max=Math.max(max, A[i]); } return max; } static long min(long A[]) { long min=Long.MAX_VALUE; for(int i=0;i<A.length;i++) { min=Math.min(min, A[i]); } return min; } static long mod(long x) { int mod=1000000007; return ((x%mod + mod)%mod); } static int i() { return sc.nextInt(); } static String s() { return sc.next(); } static long l() { return sc.nextLong(); } static void sort(int[] A){ int n = A.length; Random rnd = new Random(); for(int i=0; i<n; ++i){ int tmp = A[i]; int randomPos = i + rnd.nextInt(n-i); A[i] = A[randomPos]; A[randomPos] = tmp; } Arrays.sort(A); } static boolean prime(int n) { if (n <= 1) return false; if (n <= 3) return true; if (n % 2 == 0 || n % 3 == 0) return false; double sq=Math.sqrt(n); for (int i = 5; i <= sq; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } static int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a); } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["3\n4\nS010\n0001\n1000\n111F\n3\nS10\n101\n01F\n5\nS0101\n00000\n01111\n11111\n0001F"]
1 second
["1\n3 4\n2\n1 2\n2 1\n0"]
NoteFor the first test case, after inverting the cell, we get the following grid:S01000011001111F
Java 11
standard input
[ "constructive algorithms", "implementation" ]
be60cca56505e4b04d24c9b4990553c7
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 50$$$). Description of the test cases follows. The first line of each test case contains one integers $$$n$$$ ($$$3 \le n \le 200$$$). The following $$$n$$$ lines of each test case contain the binary grid, square ($$$1, 1$$$) being colored in 'S' and square ($$$n, n$$$) being colored in 'F'. The sum of values of $$$n$$$ doesn't exceed $$$200$$$.
1,100
For each test case output on the first line an integer $$$c$$$ ($$$0 \le c \le 2$$$)  — the number of inverted cells. In $$$i$$$-th of the following $$$c$$$ lines, print the coordinates of the $$$i$$$-th cell you inverted. You may not invert the same cell twice. Note that you cannot invert cells $$$(1, 1)$$$ and $$$(n, n)$$$.
standard output
PASSED
88129d87f3345988927af8a664605c54
train_003.jsonl
1603011900
Pink Floyd are pulling a prank on Roger Waters. They know he doesn't like walls, he wants to be able to walk freely, so they are blocking him from exiting his room which can be seen as a grid.Roger Waters has a square grid of size $$$n\times n$$$ and he wants to traverse his grid from the upper left ($$$1,1$$$) corner to the lower right corner ($$$n,n$$$). Waters can move from a square to any other square adjacent by a side, as long as he is still in the grid. Also except for the cells ($$$1,1$$$) and ($$$n,n$$$) every cell has a value $$$0$$$ or $$$1$$$ in it.Before starting his traversal he will pick either a $$$0$$$ or a $$$1$$$ and will be able to only go to cells values in which are equal to the digit he chose. The starting and finishing cells ($$$1,1$$$) and ($$$n,n$$$) are exempt from this rule, he may go through them regardless of picked digit. Because of this the cell ($$$1,1$$$) takes value the letter 'S' and the cell ($$$n,n$$$) takes value the letter 'F'.For example, in the first example test case, he can go from ($$$1, 1$$$) to ($$$n, n$$$) by using the zeroes on this path: ($$$1, 1$$$), ($$$2, 1$$$), ($$$2, 2$$$), ($$$2, 3$$$), ($$$3, 3$$$), ($$$3, 4$$$), ($$$4, 4$$$)The rest of the band (Pink Floyd) wants Waters to not be able to do his traversal, so while he is not looking they will invert at most two cells in the grid (from $$$0$$$ to $$$1$$$ or vice versa). They are afraid they will not be quick enough and asked for your help in choosing the cells. Note that you cannot invert cells $$$(1, 1)$$$ and $$$(n, n)$$$.We can show that there always exists a solution for the given constraints.Also note that Waters will pick his digit of the traversal after the band has changed his grid, so he must not be able to reach ($$$n,n$$$) no matter what digit he picks.
256 megabytes
import java.util.Scanner; public class B { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int anInt = sc.nextInt(); for (int zzz = 0; zzz < anInt; zzz++) { int len = sc.nextInt(); char[][]chars = new char[len][len]; for (int i = 0; i < len; i++) { chars[i] = sc.next().toCharArray(); } int invert; if(chars[0][1] == chars[1][0]){ invert = 0; if(chars[len - 1][len - 2] == chars[0][1]) invert++; if(chars[len - 2][len - 1] == chars[0][1]) invert++; System.out.println(invert); if(chars[len - 1][len - 2] == chars[0][1]){ System.out.println(len + " " + (len - 1)); } if(chars[len - 2][len - 1] == chars[0][1]){ System.out.println((len - 1) + " " + len); } }else if(chars[len - 1][len - 2] == chars[len - 2][len - 1]){ invert = 0; if(chars[len - 1][len - 2] == chars[0][1]) invert++; if(chars[len - 2][len - 1] == chars[1][0]) invert++; System.out.println(invert); if(chars[0][1] == chars[len - 1][len - 2]){ System.out.println("1 2"); }else if(chars[1][0] == chars[len - 1][len - 2]){ System.out.println("2 1"); } }else{ System.out.println(2); System.out.println(1 + " " + 2); if(chars[len - 1][len - 2] == chars[1][0]){ System.out.println(len + " " + (len - 1)); }else{ System.out.println((len - 1) + " " + len); } /* if(chars[0][1] == chars[len - 1][len - 2]){ System.out.println("1 2"); System.out.println(len + " " + (len - 1)); }else{ System.out.println("1 2"); System.out.println((len - 1) + " " + len); }*/ } } } } // 1 0 1 0
Java
["3\n4\nS010\n0001\n1000\n111F\n3\nS10\n101\n01F\n5\nS0101\n00000\n01111\n11111\n0001F"]
1 second
["1\n3 4\n2\n1 2\n2 1\n0"]
NoteFor the first test case, after inverting the cell, we get the following grid:S01000011001111F
Java 11
standard input
[ "constructive algorithms", "implementation" ]
be60cca56505e4b04d24c9b4990553c7
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 50$$$). Description of the test cases follows. The first line of each test case contains one integers $$$n$$$ ($$$3 \le n \le 200$$$). The following $$$n$$$ lines of each test case contain the binary grid, square ($$$1, 1$$$) being colored in 'S' and square ($$$n, n$$$) being colored in 'F'. The sum of values of $$$n$$$ doesn't exceed $$$200$$$.
1,100
For each test case output on the first line an integer $$$c$$$ ($$$0 \le c \le 2$$$)  — the number of inverted cells. In $$$i$$$-th of the following $$$c$$$ lines, print the coordinates of the $$$i$$$-th cell you inverted. You may not invert the same cell twice. Note that you cannot invert cells $$$(1, 1)$$$ and $$$(n, n)$$$.
standard output
PASSED
c93f56e8146eb6bc62c3b5b5872f1406
train_003.jsonl
1603011900
Pink Floyd are pulling a prank on Roger Waters. They know he doesn't like walls, he wants to be able to walk freely, so they are blocking him from exiting his room which can be seen as a grid.Roger Waters has a square grid of size $$$n\times n$$$ and he wants to traverse his grid from the upper left ($$$1,1$$$) corner to the lower right corner ($$$n,n$$$). Waters can move from a square to any other square adjacent by a side, as long as he is still in the grid. Also except for the cells ($$$1,1$$$) and ($$$n,n$$$) every cell has a value $$$0$$$ or $$$1$$$ in it.Before starting his traversal he will pick either a $$$0$$$ or a $$$1$$$ and will be able to only go to cells values in which are equal to the digit he chose. The starting and finishing cells ($$$1,1$$$) and ($$$n,n$$$) are exempt from this rule, he may go through them regardless of picked digit. Because of this the cell ($$$1,1$$$) takes value the letter 'S' and the cell ($$$n,n$$$) takes value the letter 'F'.For example, in the first example test case, he can go from ($$$1, 1$$$) to ($$$n, n$$$) by using the zeroes on this path: ($$$1, 1$$$), ($$$2, 1$$$), ($$$2, 2$$$), ($$$2, 3$$$), ($$$3, 3$$$), ($$$3, 4$$$), ($$$4, 4$$$)The rest of the band (Pink Floyd) wants Waters to not be able to do his traversal, so while he is not looking they will invert at most two cells in the grid (from $$$0$$$ to $$$1$$$ or vice versa). They are afraid they will not be quick enough and asked for your help in choosing the cells. Note that you cannot invert cells $$$(1, 1)$$$ and $$$(n, n)$$$.We can show that there always exists a solution for the given constraints.Also note that Waters will pick his digit of the traversal after the band has changed his grid, so he must not be able to reach ($$$n,n$$$) no matter what digit he picks.
256 megabytes
import java.util.Scanner; public class B { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int anInt = sc.nextInt(); for (int zzz = 0; zzz < anInt; zzz++) { int len = sc.nextInt(); char[][]chars = new char[len][len]; for (int i = 0; i < len; i++) { chars[i] = sc.next().toCharArray(); } int invert; if(chars[0][1] == chars[1][0]){ invert = 0; if(chars[len - 1][len - 2] == chars[0][1]) invert++; if(chars[len - 2][len - 1] == chars[0][1]) invert++; System.out.println(invert); if(chars[len - 1][len - 2] == chars[0][1]){ System.out.println(len + " " + (len - 1)); } if(chars[len - 2][len - 1] == chars[0][1]){ System.out.println((len - 1) + " " + len); } }else if(chars[len - 1][len - 2] == chars[len - 2][len - 1]){ invert = 0; if(chars[len - 1][len - 2] == chars[0][1]) invert++; if(chars[len - 2][len - 1] == chars[1][0]) invert++; System.out.println(invert); if(chars[0][1] == chars[len - 1][len - 2]){ System.out.println("1 2"); }else if(chars[1][0] == chars[len - 1][len - 2]){ System.out.println("2 1"); } }else{ System.out.println(2); if(chars[0][1] == chars[len - 1][len - 2]){ System.out.println("1 2"); System.out.println((len - 1) + " " + len); }else{ System.out.println("1 2"); System.out.println(len + " " + (len - 1)); } } } } } // 1 0 1 0
Java
["3\n4\nS010\n0001\n1000\n111F\n3\nS10\n101\n01F\n5\nS0101\n00000\n01111\n11111\n0001F"]
1 second
["1\n3 4\n2\n1 2\n2 1\n0"]
NoteFor the first test case, after inverting the cell, we get the following grid:S01000011001111F
Java 11
standard input
[ "constructive algorithms", "implementation" ]
be60cca56505e4b04d24c9b4990553c7
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 50$$$). Description of the test cases follows. The first line of each test case contains one integers $$$n$$$ ($$$3 \le n \le 200$$$). The following $$$n$$$ lines of each test case contain the binary grid, square ($$$1, 1$$$) being colored in 'S' and square ($$$n, n$$$) being colored in 'F'. The sum of values of $$$n$$$ doesn't exceed $$$200$$$.
1,100
For each test case output on the first line an integer $$$c$$$ ($$$0 \le c \le 2$$$)  — the number of inverted cells. In $$$i$$$-th of the following $$$c$$$ lines, print the coordinates of the $$$i$$$-th cell you inverted. You may not invert the same cell twice. Note that you cannot invert cells $$$(1, 1)$$$ and $$$(n, n)$$$.
standard output
PASSED
5b93a6dc76442b874f9161971c4a4c90
train_003.jsonl
1603011900
Pink Floyd are pulling a prank on Roger Waters. They know he doesn't like walls, he wants to be able to walk freely, so they are blocking him from exiting his room which can be seen as a grid.Roger Waters has a square grid of size $$$n\times n$$$ and he wants to traverse his grid from the upper left ($$$1,1$$$) corner to the lower right corner ($$$n,n$$$). Waters can move from a square to any other square adjacent by a side, as long as he is still in the grid. Also except for the cells ($$$1,1$$$) and ($$$n,n$$$) every cell has a value $$$0$$$ or $$$1$$$ in it.Before starting his traversal he will pick either a $$$0$$$ or a $$$1$$$ and will be able to only go to cells values in which are equal to the digit he chose. The starting and finishing cells ($$$1,1$$$) and ($$$n,n$$$) are exempt from this rule, he may go through them regardless of picked digit. Because of this the cell ($$$1,1$$$) takes value the letter 'S' and the cell ($$$n,n$$$) takes value the letter 'F'.For example, in the first example test case, he can go from ($$$1, 1$$$) to ($$$n, n$$$) by using the zeroes on this path: ($$$1, 1$$$), ($$$2, 1$$$), ($$$2, 2$$$), ($$$2, 3$$$), ($$$3, 3$$$), ($$$3, 4$$$), ($$$4, 4$$$)The rest of the band (Pink Floyd) wants Waters to not be able to do his traversal, so while he is not looking they will invert at most two cells in the grid (from $$$0$$$ to $$$1$$$ or vice versa). They are afraid they will not be quick enough and asked for your help in choosing the cells. Note that you cannot invert cells $$$(1, 1)$$$ and $$$(n, n)$$$.We can show that there always exists a solution for the given constraints.Also note that Waters will pick his digit of the traversal after the band has changed his grid, so he must not be able to reach ($$$n,n$$$) no matter what digit he picks.
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; public class Main { public static void main (String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw = new PrintWriter(System.out); int t = Integer.parseInt(br.readLine()); while(t-- > 0){ int n = Integer.parseInt(br.readLine()); int arr[][] = new int[n][n]; for(int i = 0; i<n; i++){ String num[] = br.readLine().split(""); for(int j = 0; j<n; j++){ if((i==0 && j==0) || (i==n-1 && j==n-1)) continue; arr[i][j] = Integer.parseInt(num[j]); } } int startRight = arr[0][1]; int startBottom = arr[1][0]; int destLeft = arr[n-1][n-2]; int destTop = arr[n-2][n-1]; if(startBottom==startRight){ if(startRight==destLeft && startRight==destTop){ pw.println(2); pw.println(1+" "+2); pw.println(2+" "+1); } else if(startRight==destLeft && startRight!=destTop){ pw.println(1); pw.print(n+" "); pw.println(n-1); } else if(startRight!=destLeft && startRight==destTop){ pw.println(1); pw.println(n-1+" "+n); } else{ pw.println("0"); } } else if(destLeft==destTop) { if(startRight==destLeft && startBottom!=destTop){ pw.println(1); pw.println(1+" "+2); } else if(startRight!=destLeft && startBottom==destTop){ pw.println(1); pw.println(2+" "+1); } else{ pw.println("0"); } } else { if(startBottom==destLeft){ pw.println(2); pw.println(2+" "+1); pw.println(n-1+" "+n); } else if(startBottom==destTop){ pw.println(2); pw.println(2+" "+1); pw.print(n+" "); pw.println(n-1); } else{ pw.println("0"); } } } pw.flush(); } }
Java
["3\n4\nS010\n0001\n1000\n111F\n3\nS10\n101\n01F\n5\nS0101\n00000\n01111\n11111\n0001F"]
1 second
["1\n3 4\n2\n1 2\n2 1\n0"]
NoteFor the first test case, after inverting the cell, we get the following grid:S01000011001111F
Java 11
standard input
[ "constructive algorithms", "implementation" ]
be60cca56505e4b04d24c9b4990553c7
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 50$$$). Description of the test cases follows. The first line of each test case contains one integers $$$n$$$ ($$$3 \le n \le 200$$$). The following $$$n$$$ lines of each test case contain the binary grid, square ($$$1, 1$$$) being colored in 'S' and square ($$$n, n$$$) being colored in 'F'. The sum of values of $$$n$$$ doesn't exceed $$$200$$$.
1,100
For each test case output on the first line an integer $$$c$$$ ($$$0 \le c \le 2$$$)  — the number of inverted cells. In $$$i$$$-th of the following $$$c$$$ lines, print the coordinates of the $$$i$$$-th cell you inverted. You may not invert the same cell twice. Note that you cannot invert cells $$$(1, 1)$$$ and $$$(n, n)$$$.
standard output
PASSED
8bda95e31f39d1d2603c6eb9bc3ed743
train_003.jsonl
1603011900
Pink Floyd are pulling a prank on Roger Waters. They know he doesn't like walls, he wants to be able to walk freely, so they are blocking him from exiting his room which can be seen as a grid.Roger Waters has a square grid of size $$$n\times n$$$ and he wants to traverse his grid from the upper left ($$$1,1$$$) corner to the lower right corner ($$$n,n$$$). Waters can move from a square to any other square adjacent by a side, as long as he is still in the grid. Also except for the cells ($$$1,1$$$) and ($$$n,n$$$) every cell has a value $$$0$$$ or $$$1$$$ in it.Before starting his traversal he will pick either a $$$0$$$ or a $$$1$$$ and will be able to only go to cells values in which are equal to the digit he chose. The starting and finishing cells ($$$1,1$$$) and ($$$n,n$$$) are exempt from this rule, he may go through them regardless of picked digit. Because of this the cell ($$$1,1$$$) takes value the letter 'S' and the cell ($$$n,n$$$) takes value the letter 'F'.For example, in the first example test case, he can go from ($$$1, 1$$$) to ($$$n, n$$$) by using the zeroes on this path: ($$$1, 1$$$), ($$$2, 1$$$), ($$$2, 2$$$), ($$$2, 3$$$), ($$$3, 3$$$), ($$$3, 4$$$), ($$$4, 4$$$)The rest of the band (Pink Floyd) wants Waters to not be able to do his traversal, so while he is not looking they will invert at most two cells in the grid (from $$$0$$$ to $$$1$$$ or vice versa). They are afraid they will not be quick enough and asked for your help in choosing the cells. Note that you cannot invert cells $$$(1, 1)$$$ and $$$(n, n)$$$.We can show that there always exists a solution for the given constraints.Also note that Waters will pick his digit of the traversal after the band has changed his grid, so he must not be able to reach ($$$n,n$$$) no matter what digit he picks.
256 megabytes
import java.io.*; import java.util.*; public class B { public static void main(String[] args) throws IOException{ FastScanner sc = new FastScanner(); int yo = sc.nextInt(); while(yo-->0) { int n = sc.nextInt(); char[][] arr = new char[n][n]; for(int i = 0; i < n; i++) { String s = sc.next(); for(int j = 0; j < n; j++) { arr[i][j] = s.charAt(j); } } int startRight = arr[0][1]-'0'; int startDown = arr[1][0]-'0'; int endLeft = arr[n-1][n-2]-'0'; int endTop = arr[n-2][n-1]-'0'; // System.out.println(startRight + " " +startDown + " " + endLeft + " " + endTop); int count = 0; if(startRight == 0 && startDown == 0) { if(endLeft == 0) { count++; } if(endTop == 0) { count++; } System.out.println(count); if(endLeft == 0) { System.out.println((n-1+1) + " " + (n-2+1)); } if(endTop == 0) { System.out.println((n-2+1) + " " + (n-1+1)); } } else if(startRight == 1 && startDown == 1) { if(endLeft == 1) { count++; } if(endTop == 1) { count++; } System.out.println(count); if(endLeft == 1) { count++; System.out.println((n-1+1) + " " + (n-2+1)); } if(endTop == 1) { count++; System.out.println((n-2+1) + " " + (n-1+1)); } } else { count = 0; if((startRight == 0 && startDown == 1)) { if((endLeft == 1 && endTop == 0)) { System.out.println(2); System.out.println(1 + " " + 2); System.out.println((n) + " " + (n-1)); } else if((endLeft == 0 && endTop == 1)) { System.out.println(2); System.out.println(1 + " " + 2); System.out.println((n-1) + " " + (n)); } else if((endLeft == 0 && endTop == 0)) { System.out.println(1); System.out.println(1 + " " + 2); } else if((endLeft == 1 && endTop == 1)) { System.out.println(1); System.out.println(2 + " " + 1); } } else if((startRight == 1 && startDown == 0)) { if((endLeft == 1 && endTop == 0)) { System.out.println(2); System.out.println(1 + " " + 2); System.out.println((n-1) + " " + (n)); } else if((endLeft == 0 && endTop == 1)) { System.out.println(2); System.out.println(1 + " " + 2); System.out.println((n) + " " + (n-1)); } else if((endLeft == 0 && endTop == 0)) { System.out.println(1); System.out.println(2 + " " + 1); } else if((endLeft == 1 && endTop == 1)) { System.out.println(1); System.out.println(1 + " " + 2); } } } } //S010 //1001 //1000 //111F } static int mod = 1000000007; static long pow(int a, int b) { if(b == 0) { return 1; } if(b == 1) { return a; } if(b%2 == 0) { long ans = pow(a,b/2); return ans*ans; } else { long ans = pow(a,(b-1)/2); return a * ans * ans; } } static class FastScanner { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readArray(int n) { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } long nextLong() { return Long.parseLong(next()); } } static int gcd(int a, int b) { return a%b == 0 ? b : gcd(b,a%b); } static boolean[] sieve(int n) { boolean isPrime[] = new boolean[n+1]; for(int i = 2; i <= n; i++) { if(isPrime[i]) continue; for(int j = 2*i; j <= n; j+=i) { isPrime[j] = true; } } return isPrime; } // For Input.txt and Output.txt // FileInputStream in = new FileInputStream("input.txt"); // FileOutputStream out = new FileOutputStream("output.txt"); // PrintWriter pw = new PrintWriter(out); // Scanner sc = new Scanner(in); // sc.nextLine() }
Java
["3\n4\nS010\n0001\n1000\n111F\n3\nS10\n101\n01F\n5\nS0101\n00000\n01111\n11111\n0001F"]
1 second
["1\n3 4\n2\n1 2\n2 1\n0"]
NoteFor the first test case, after inverting the cell, we get the following grid:S01000011001111F
Java 11
standard input
[ "constructive algorithms", "implementation" ]
be60cca56505e4b04d24c9b4990553c7
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 50$$$). Description of the test cases follows. The first line of each test case contains one integers $$$n$$$ ($$$3 \le n \le 200$$$). The following $$$n$$$ lines of each test case contain the binary grid, square ($$$1, 1$$$) being colored in 'S' and square ($$$n, n$$$) being colored in 'F'. The sum of values of $$$n$$$ doesn't exceed $$$200$$$.
1,100
For each test case output on the first line an integer $$$c$$$ ($$$0 \le c \le 2$$$)  — the number of inverted cells. In $$$i$$$-th of the following $$$c$$$ lines, print the coordinates of the $$$i$$$-th cell you inverted. You may not invert the same cell twice. Note that you cannot invert cells $$$(1, 1)$$$ and $$$(n, n)$$$.
standard output
PASSED
2cd944b9be38c181f2870b803f3e2e8a
train_003.jsonl
1603011900
Pink Floyd are pulling a prank on Roger Waters. They know he doesn't like walls, he wants to be able to walk freely, so they are blocking him from exiting his room which can be seen as a grid.Roger Waters has a square grid of size $$$n\times n$$$ and he wants to traverse his grid from the upper left ($$$1,1$$$) corner to the lower right corner ($$$n,n$$$). Waters can move from a square to any other square adjacent by a side, as long as he is still in the grid. Also except for the cells ($$$1,1$$$) and ($$$n,n$$$) every cell has a value $$$0$$$ or $$$1$$$ in it.Before starting his traversal he will pick either a $$$0$$$ or a $$$1$$$ and will be able to only go to cells values in which are equal to the digit he chose. The starting and finishing cells ($$$1,1$$$) and ($$$n,n$$$) are exempt from this rule, he may go through them regardless of picked digit. Because of this the cell ($$$1,1$$$) takes value the letter 'S' and the cell ($$$n,n$$$) takes value the letter 'F'.For example, in the first example test case, he can go from ($$$1, 1$$$) to ($$$n, n$$$) by using the zeroes on this path: ($$$1, 1$$$), ($$$2, 1$$$), ($$$2, 2$$$), ($$$2, 3$$$), ($$$3, 3$$$), ($$$3, 4$$$), ($$$4, 4$$$)The rest of the band (Pink Floyd) wants Waters to not be able to do his traversal, so while he is not looking they will invert at most two cells in the grid (from $$$0$$$ to $$$1$$$ or vice versa). They are afraid they will not be quick enough and asked for your help in choosing the cells. Note that you cannot invert cells $$$(1, 1)$$$ and $$$(n, n)$$$.We can show that there always exists a solution for the given constraints.Also note that Waters will pick his digit of the traversal after the band has changed his grid, so he must not be able to reach ($$$n,n$$$) no matter what digit he picks.
256 megabytes
import java.io.*; import java.util.*; import static java.lang.Math.*; public class Main { public static void main(String[] args) throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw = new PrintWriter(System.out); int t = nextInt(); for (int q = 0; q < t; q++) { int n = nextInt(); char[][] m = new char[n][n]; for (int i = 0; i < n; i++) { m[i] = next().toCharArray(); } int firstLevelZeroCnt = 0; int firstLevelOneCnt = 0; int secondLevelZeroCnt = 0; int secondLevelOneCnt = 0; if (m[0][1] == '0') firstLevelZeroCnt++; else firstLevelOneCnt++; if (m[1][0] == '0') firstLevelZeroCnt++; else firstLevelOneCnt++; if (m[0][2] == '0') secondLevelZeroCnt++; else secondLevelOneCnt++; if (m[1][1] == '0') secondLevelZeroCnt++; else secondLevelOneCnt++; if (m[2][0] == '0') secondLevelZeroCnt++; else secondLevelOneCnt++; int cnt = 0; if (secondLevelOneCnt == 3) { if (m[0][1] == '1') cnt++; if (m[1][0] == '1') cnt++; pw.println(cnt); if (m[0][1] == '1') pw.println(1 + " " + 2); if (m[1][0] == '1') pw.println(2 + " " + 1); } else if (secondLevelZeroCnt == 3) { if (m[0][1] == '0') cnt++; if (m[1][0] == '0') cnt++; pw.println(cnt); if (m[0][1] == '0') pw.println(1 + " " + 2); if (m[1][0] == '0') pw.println(2 + " " + 1); } else if (firstLevelZeroCnt == 2) { for (int i = 0; i < 3; i++) if (m[i][2 - i] == '0') cnt++; pw.println(cnt); for (int i = 0; i < 3; i++) if (m[i][2 - i] == '0') pw.println((i + 1) + " " + (3 - i)); } else if (firstLevelOneCnt == 2) { for (int i = 0; i < 3; i++) if (m[i][2 - i] == '1') cnt++; pw.println(cnt); for (int i = 0; i < 3; i++) if (m[i][2 - i] == '1') pw.println((i + 1) + " " + (3 - i)); } else { if (secondLevelOneCnt > secondLevelZeroCnt) { for (int i = 0; i < 3; i++) if (m[i][2 - i] == '0') cnt++; if (m[0][1] == '1') cnt++; if (m[1][0] == '1') cnt++; pw.println(cnt); if (m[0][1] == '1') pw.println(1 + " " + 2); if (m[1][0] == '1') pw.println(2 + " " + 1); for (int i = 0; i < 3; i++) if (m[i][2 - i] == '0') pw.println((i + 1) + " " + (3 - i)); } else { for (int i = 0; i < 3; i++) if (m[i][2 - i] == '1') cnt++; if (m[0][1] == '0') cnt++; if (m[1][0] == '0') cnt++; pw.println(cnt); if (m[0][1] == '0') pw.println(1 + " " + 2); if (m[1][0] == '0') pw.println(2 + " " + 1); for (int i = 0; i < 3; i++) if (m[i][2 - i] == '1') pw.println((i + 1) + " " + (3 - i)); } } } pw.close(); } static long mod = 1_000_000_007; static StringTokenizer st = new StringTokenizer(""); static BufferedReader br; static String next() throws IOException { while (st == null || !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()); } static double nextDouble() throws IOException { return Double.parseDouble(next()); } }
Java
["3\n4\nS010\n0001\n1000\n111F\n3\nS10\n101\n01F\n5\nS0101\n00000\n01111\n11111\n0001F"]
1 second
["1\n3 4\n2\n1 2\n2 1\n0"]
NoteFor the first test case, after inverting the cell, we get the following grid:S01000011001111F
Java 11
standard input
[ "constructive algorithms", "implementation" ]
be60cca56505e4b04d24c9b4990553c7
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 50$$$). Description of the test cases follows. The first line of each test case contains one integers $$$n$$$ ($$$3 \le n \le 200$$$). The following $$$n$$$ lines of each test case contain the binary grid, square ($$$1, 1$$$) being colored in 'S' and square ($$$n, n$$$) being colored in 'F'. The sum of values of $$$n$$$ doesn't exceed $$$200$$$.
1,100
For each test case output on the first line an integer $$$c$$$ ($$$0 \le c \le 2$$$)  — the number of inverted cells. In $$$i$$$-th of the following $$$c$$$ lines, print the coordinates of the $$$i$$$-th cell you inverted. You may not invert the same cell twice. Note that you cannot invert cells $$$(1, 1)$$$ and $$$(n, n)$$$.
standard output
PASSED
6c2a957454380fffaf6a34806425f303
train_003.jsonl
1603011900
Pink Floyd are pulling a prank on Roger Waters. They know he doesn't like walls, he wants to be able to walk freely, so they are blocking him from exiting his room which can be seen as a grid.Roger Waters has a square grid of size $$$n\times n$$$ and he wants to traverse his grid from the upper left ($$$1,1$$$) corner to the lower right corner ($$$n,n$$$). Waters can move from a square to any other square adjacent by a side, as long as he is still in the grid. Also except for the cells ($$$1,1$$$) and ($$$n,n$$$) every cell has a value $$$0$$$ or $$$1$$$ in it.Before starting his traversal he will pick either a $$$0$$$ or a $$$1$$$ and will be able to only go to cells values in which are equal to the digit he chose. The starting and finishing cells ($$$1,1$$$) and ($$$n,n$$$) are exempt from this rule, he may go through them regardless of picked digit. Because of this the cell ($$$1,1$$$) takes value the letter 'S' and the cell ($$$n,n$$$) takes value the letter 'F'.For example, in the first example test case, he can go from ($$$1, 1$$$) to ($$$n, n$$$) by using the zeroes on this path: ($$$1, 1$$$), ($$$2, 1$$$), ($$$2, 2$$$), ($$$2, 3$$$), ($$$3, 3$$$), ($$$3, 4$$$), ($$$4, 4$$$)The rest of the band (Pink Floyd) wants Waters to not be able to do his traversal, so while he is not looking they will invert at most two cells in the grid (from $$$0$$$ to $$$1$$$ or vice versa). They are afraid they will not be quick enough and asked for your help in choosing the cells. Note that you cannot invert cells $$$(1, 1)$$$ and $$$(n, n)$$$.We can show that there always exists a solution for the given constraints.Also note that Waters will pick his digit of the traversal after the band has changed his grid, so he must not be able to reach ($$$n,n$$$) no matter what digit he picks.
256 megabytes
import java.util.*; public class ks { public static void main(String[] args) { Scanner no=new Scanner(System.in); int t=no.nextInt(); for(int i=0;i<t;i++){ int n=no.nextInt(); char arr[][]=new char[n][n]; int ans=0; for(int j=0;j<n;j++){ String s=no.next(); arr[j]=s.toCharArray(); } if(arr[n-2][n-1]=='0'&&arr[n-1][n-2]=='0'){ if(arr[0][1]=='0'){ ans++; } if(arr[1][0]=='0'){ ans++; } } else if(arr[n-2][n-1]=='1'&&arr[n-1][n-2]=='1'){ if(arr[0][1]=='1'){ ans++; } if(arr[1][0]=='1'){ ans++; } } else if(arr[n-2][n-1]=='1'&&arr[n-1][n-2]=='0'){ ans++; if(arr[0][1]=='1'&&arr[1][0]=='1'){ //ans++; } else if(arr[0][1]=='1'&&arr[1][0]=='0'){ ans++; } else if(arr[0][1]=='0'&&arr[1][0]=='0'){ //ans++; } else if(arr[0][1]=='0'&&arr[1][0]=='1'){ ans++; } } else if(arr[n-2][n-1]=='0'&&arr[n-1][n-2]=='1'){ ans++; if(arr[0][1]=='1'&&arr[1][0]=='1'){ // ans++; } else if(arr[0][1]=='1'&&arr[1][0]=='0'){ ans++; } else if(arr[0][1]=='0'&&arr[1][0]=='0'){ // ans++; } else if(arr[0][1]=='0'&&arr[1][0]=='1'){ ans++; } } if(arr[n-2][n-1]=='0'&&arr[n-1][n-2]=='0'){ System.out.println(ans); if(arr[0][1]=='0'){ System.out.println(1+" "+2); } if(arr[1][0]=='0'){ System.out.println(2+" "+1); } } else if(arr[n-2][n-1]=='1'&&arr[n-1][n-2]=='1'){ System.out.println(ans); if(arr[0][1]=='1'){ System.out.println(1+" "+2); } if(arr[1][0]=='1'){ System.out.println(2+" "+1); } } else if(arr[n-2][n-1]=='1'&&arr[n-1][n-2]=='0'){ // arr[n-1][n-2]='1'; // ans++; System.out.println(ans); if(arr[0][1]=='1'&&arr[1][0]=='1'){ System.out.println((n-1)+" "+n); } else if(arr[0][1]=='1'&&arr[1][0]=='0'){ System.out.println((n-1)+" "+n); System.out.println(2+" "+1); } else if(arr[0][1]=='0'&&arr[1][0]=='0'){ System.out.println(n+" "+(n-1)); } else if(arr[0][1]=='0'&&arr[1][0]=='1'){ System.out.println((n-1)+" "+n); System.out.println(1+" "+2); } } else if(arr[n-2][n-1]=='0'&&arr[n-1][n-2]=='1'){ System.out.println(ans); if(arr[0][1]=='1'&&arr[1][0]=='1'){ System.out.println((n)+" "+(n-1)); } else if(arr[0][1]=='1'&&arr[1][0]=='0'){ System.out.println((n-1)+" "+n); System.out.println(1+" "+2); } else if(arr[0][1]=='0'&&arr[1][0]=='0'){ System.out.println((n-1)+" "+(n)); } else if(arr[0][1]=='0'&&arr[1][0]=='1'){ System.out.println((n-1)+" "+n); System.out.println(2+" "+1); } } } } }
Java
["3\n4\nS010\n0001\n1000\n111F\n3\nS10\n101\n01F\n5\nS0101\n00000\n01111\n11111\n0001F"]
1 second
["1\n3 4\n2\n1 2\n2 1\n0"]
NoteFor the first test case, after inverting the cell, we get the following grid:S01000011001111F
Java 11
standard input
[ "constructive algorithms", "implementation" ]
be60cca56505e4b04d24c9b4990553c7
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 50$$$). Description of the test cases follows. The first line of each test case contains one integers $$$n$$$ ($$$3 \le n \le 200$$$). The following $$$n$$$ lines of each test case contain the binary grid, square ($$$1, 1$$$) being colored in 'S' and square ($$$n, n$$$) being colored in 'F'. The sum of values of $$$n$$$ doesn't exceed $$$200$$$.
1,100
For each test case output on the first line an integer $$$c$$$ ($$$0 \le c \le 2$$$)  — the number of inverted cells. In $$$i$$$-th of the following $$$c$$$ lines, print the coordinates of the $$$i$$$-th cell you inverted. You may not invert the same cell twice. Note that you cannot invert cells $$$(1, 1)$$$ and $$$(n, n)$$$.
standard output
PASSED
b2f9f2710586ff7663a3aa3a0cfd7ade
train_003.jsonl
1603011900
Pink Floyd are pulling a prank on Roger Waters. They know he doesn't like walls, he wants to be able to walk freely, so they are blocking him from exiting his room which can be seen as a grid.Roger Waters has a square grid of size $$$n\times n$$$ and he wants to traverse his grid from the upper left ($$$1,1$$$) corner to the lower right corner ($$$n,n$$$). Waters can move from a square to any other square adjacent by a side, as long as he is still in the grid. Also except for the cells ($$$1,1$$$) and ($$$n,n$$$) every cell has a value $$$0$$$ or $$$1$$$ in it.Before starting his traversal he will pick either a $$$0$$$ or a $$$1$$$ and will be able to only go to cells values in which are equal to the digit he chose. The starting and finishing cells ($$$1,1$$$) and ($$$n,n$$$) are exempt from this rule, he may go through them regardless of picked digit. Because of this the cell ($$$1,1$$$) takes value the letter 'S' and the cell ($$$n,n$$$) takes value the letter 'F'.For example, in the first example test case, he can go from ($$$1, 1$$$) to ($$$n, n$$$) by using the zeroes on this path: ($$$1, 1$$$), ($$$2, 1$$$), ($$$2, 2$$$), ($$$2, 3$$$), ($$$3, 3$$$), ($$$3, 4$$$), ($$$4, 4$$$)The rest of the band (Pink Floyd) wants Waters to not be able to do his traversal, so while he is not looking they will invert at most two cells in the grid (from $$$0$$$ to $$$1$$$ or vice versa). They are afraid they will not be quick enough and asked for your help in choosing the cells. Note that you cannot invert cells $$$(1, 1)$$$ and $$$(n, n)$$$.We can show that there always exists a solution for the given constraints.Also note that Waters will pick his digit of the traversal after the band has changed his grid, so he must not be able to reach ($$$n,n$$$) no matter what digit he picks.
256 megabytes
import java.io.*; import java.util.*; public class B { static FastReader reader = new FastReader(); //static OutputWriter out = new OutputWriter(System.out); static void solve(char[][] arr) { int n = arr.length - 1; int up = Character.getNumericValue(arr[n-1][n]); int left = Character.getNumericValue(arr[n][n-1]); int g1 = Character.getNumericValue(arr[n][n-2]); int g2 = Character.getNumericValue(arr[n-1][n-1]); int g3 = Character.getNumericValue(arr[n-2][n]); List<int[]> res = new LinkedList<>(); if(g1 == g2 && g2 == g3) { if(up == g1) { res.add(new int[] {n -1 + 1, n + 1}); } if(left == g1) { res.add(new int[] {n + 1, n -1 + 1}); } } else if(left == up) { if(g1 == left) { res.add(new int[] {n+1, n-2+1}); } if(g2 == left) { res.add(new int[] {n-1 + 1, n-1 + 1}); } if(g3 == left) { res.add(new int[] {n - 2 + 1, n + 1}); } } else if(g1 + g2 + g3 == 2) { if(g1 == 0) { res.add(new int[] {n+1, n-2+1}); } if(g2 == 0) { res.add(new int[] {n-1 + 1, n-1 + 1}); } if(g3 == 0) { res.add(new int[] {n - 2 + 1, n + 1}); } if(up == 1) { res.add(new int[] {n-1 + 1, n + 1});//[n-1][n] } if(left == 1) { res.add(new int[] {n + 1, n -1 + 1});//[n][n-1] } } else { if(g1 == 1) { res.add(new int[] {n+1, n-2+1}); } if(g2 == 1) { res.add(new int[] {n-1 + 1, n-1 + 1}); } if(g3 == 1) { res.add(new int[] {n - 2 + 1, n + 1}); } if(up == 0) { res.add(new int[] {n-1 + 1, n + 1});//[n-1][n] } if(left == 0) { res.add(new int[] {n + 1, n -1 + 1});//[n][n-1] } } System.out.println(res.size()); for(int[] a : res) { System.out.println(a[0] + " " + a[1]); } } public static void main(String[] args) { int tests = reader.nextInt(); for(int test = 1; test <= tests; test++) { int n = reader.nextInt(); char[][] arr = new char[n][n]; for(int i = 0; i < n; i++) { arr[i] = reader.next().toCharArray(); } solve(arr); } } static final Random random = new Random(); static void shuffleSort(int[] a) { int n = a.length;//shuffle, then sort for (int i = 0; i < n; i++) { int oi = random.nextInt(n), temp = a[oi]; a[oi] = a[i]; a[i] = temp; } Arrays.sort(a); } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } public 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 print(char[] array) { writer.print(array); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) { writer.print(' '); } writer.print(objects[i]); } } public void print(int[] array) { for (int i = 0; i < array.length; i++) { if (i != 0) { writer.print(' '); } writer.print(array[i]); } } public void print(double[] array) { for (int i = 0; i < array.length; i++) { if (i != 0) { writer.print(' '); } writer.print(array[i]); } } public void print(long[] array) { for (int i = 0; i < array.length; i++) { if (i != 0) { writer.print(' '); } writer.print(array[i]); } } public void println(int[] array) { print(array); writer.println(); } public void println(double[] array) { print(array); writer.println(); } public void println(long[] array) { print(array); writer.println(); } public void println() { writer.println(); } public void println(Object... objects) { print(objects); writer.println(); } public void print(char i) { writer.print(i); } public void println(char i) { writer.println(i); } public void println(char[] array) { writer.println(array); } public void printf(String format, Object... objects) { writer.printf(format, objects); } public void close() { writer.close(); } public void flush() { writer.flush(); } public void print(long i) { writer.print(i); } public void println(long i) { writer.println(i); } public void print(int i) { writer.print(i); } public void println(int i) { writer.println(i); } public void separateLines(int[] array) { for (int i : array) { println(i); } } } }
Java
["3\n4\nS010\n0001\n1000\n111F\n3\nS10\n101\n01F\n5\nS0101\n00000\n01111\n11111\n0001F"]
1 second
["1\n3 4\n2\n1 2\n2 1\n0"]
NoteFor the first test case, after inverting the cell, we get the following grid:S01000011001111F
Java 11
standard input
[ "constructive algorithms", "implementation" ]
be60cca56505e4b04d24c9b4990553c7
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 50$$$). Description of the test cases follows. The first line of each test case contains one integers $$$n$$$ ($$$3 \le n \le 200$$$). The following $$$n$$$ lines of each test case contain the binary grid, square ($$$1, 1$$$) being colored in 'S' and square ($$$n, n$$$) being colored in 'F'. The sum of values of $$$n$$$ doesn't exceed $$$200$$$.
1,100
For each test case output on the first line an integer $$$c$$$ ($$$0 \le c \le 2$$$)  — the number of inverted cells. In $$$i$$$-th of the following $$$c$$$ lines, print the coordinates of the $$$i$$$-th cell you inverted. You may not invert the same cell twice. Note that you cannot invert cells $$$(1, 1)$$$ and $$$(n, n)$$$.
standard output
PASSED
ebcce1f739df9590abe41226caa57cae
train_003.jsonl
1603011900
Pink Floyd are pulling a prank on Roger Waters. They know he doesn't like walls, he wants to be able to walk freely, so they are blocking him from exiting his room which can be seen as a grid.Roger Waters has a square grid of size $$$n\times n$$$ and he wants to traverse his grid from the upper left ($$$1,1$$$) corner to the lower right corner ($$$n,n$$$). Waters can move from a square to any other square adjacent by a side, as long as he is still in the grid. Also except for the cells ($$$1,1$$$) and ($$$n,n$$$) every cell has a value $$$0$$$ or $$$1$$$ in it.Before starting his traversal he will pick either a $$$0$$$ or a $$$1$$$ and will be able to only go to cells values in which are equal to the digit he chose. The starting and finishing cells ($$$1,1$$$) and ($$$n,n$$$) are exempt from this rule, he may go through them regardless of picked digit. Because of this the cell ($$$1,1$$$) takes value the letter 'S' and the cell ($$$n,n$$$) takes value the letter 'F'.For example, in the first example test case, he can go from ($$$1, 1$$$) to ($$$n, n$$$) by using the zeroes on this path: ($$$1, 1$$$), ($$$2, 1$$$), ($$$2, 2$$$), ($$$2, 3$$$), ($$$3, 3$$$), ($$$3, 4$$$), ($$$4, 4$$$)The rest of the band (Pink Floyd) wants Waters to not be able to do his traversal, so while he is not looking they will invert at most two cells in the grid (from $$$0$$$ to $$$1$$$ or vice versa). They are afraid they will not be quick enough and asked for your help in choosing the cells. Note that you cannot invert cells $$$(1, 1)$$$ and $$$(n, n)$$$.We can show that there always exists a solution for the given constraints.Also note that Waters will pick his digit of the traversal after the band has changed his grid, so he must not be able to reach ($$$n,n$$$) no matter what digit he picks.
256 megabytes
import java.io.*; import java.util.*; import static java.lang.Math.*; import static java.util.Arrays.*; public class cf1421b { public static void main(String[] args) throws IOException { int t = ri(); while (t --> 0) { int n = ri(), m[][] = new int[n][n]; for (int i = 0; i < n; ++i) { char[] row = rcha(); for (int j = 0; j < n; ++j) { m[i][j] = row[j] - '0'; } } List<int[]> ans = new ArrayList<>(); if (m[0][1] == m[1][0]) { if (m[n - 1][n - 2] == m[0][1]) { ans.add(new int[] {n, n - 1}); } if (m[n - 2][n - 1] == m[0][1]) { ans.add(new int[] {n - 1, n}); } } else { if (m[n - 1][n - 2] == m[n - 2][n - 1]) { if (m[0][1] == m[n - 1][n - 2]) { ans.add(new int[] {1, 2}); } else { ans.add(new int[] {2, 1}); } } else if (m[n - 1][n - 2] == m[0][1]) { ans.add(new int[] {1, 2}); ans.add(new int[] {n - 1, n}); } else { ans.add(new int[] {2, 1}); ans.add(new int[] {n - 1, n}); } } prln(ans.size()); for (int[] e : ans) { prln(e); } } close(); } static BufferedReader __in = new BufferedReader(new InputStreamReader(System.in)); static PrintWriter __out = new PrintWriter(new OutputStreamWriter(System.out)); static StringTokenizer input; static Random __rand = new Random(); // references // IBIG = 1e9 + 7 // IMAX ~= 2e9 // LMAX ~= 9e18 // constants static final int IBIG = 1000000007; static final int IMAX = 2147483647; static final int IMIN = -2147483648; static final long LMAX = 9223372036854775807L; static final long LMIN = -9223372036854775808L; // math util static int minof(int a, int b, int c) {return min(a, min(b, c));} static int minof(int... x) {if (x.length == 1) return x[0]; if (x.length == 2) return min(x[0], x[1]); if (x.length == 3) return min(x[0], min(x[1], x[2])); int min = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] < min) min = x[i]; return min;} static long minof(long a, long b, long c) {return min(a, min(b, c));} static long minof(long... x) {if (x.length == 1) return x[0]; if (x.length == 2) return min(x[0], x[1]); if (x.length == 3) return min(x[0], min(x[1], x[2])); long min = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] < min) min = x[i]; return min;} static int maxof(int a, int b, int c) {return max(a, max(b, c));} static int maxof(int... x) {if (x.length == 1) return x[0]; if (x.length == 2) return max(x[0], x[1]); if (x.length == 3) return max(x[0], max(x[1], x[2])); int max = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] > max) max = x[i]; return max;} static long maxof(long a, long b, long c) {return max(a, max(b, c));} static long maxof(long... x) {if (x.length == 1) return x[0]; if (x.length == 2) return max(x[0], x[1]); if (x.length == 3) return max(x[0], max(x[1], x[2])); long max = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] > max) max = x[i]; return max;} static int powi(int a, int b) {if (a == 0) return 0; int ans = 1; while (b > 0) {if ((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;} static long powl(long a, int b) {if (a == 0) return 0; long ans = 1; while (b > 0) {if ((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;} static int fli(double d) {return (int) d;} static int cei(double d) {return (int) ceil(d);} static long fll(double d) {return (long) d;} static long cel(double d) {return (long) ceil(d);} static int gcf(int a, int b) {return b == 0 ? a : gcf(b, a % b);} static long gcf(long a, long b) {return b == 0 ? a : gcf(b, a % b);} static int lcm(int a, int b) {return a * b / gcf(a, b);} static long lcm(long a, long b) {return a * b / gcf(a, b);} static int randInt(int min, int max) {return __rand.nextInt(max - min + 1) + min;} static long mix(long x) {x += 0x9e3779b97f4a7c15L; x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9L; x = (x ^ (x >> 27)) * 0x94d049bb133111ebL; return x ^ (x >> 31);} // array util static void reverse(int[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {int swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}} static void reverse(long[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {long swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}} static void reverse(double[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {double swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}} static void reverse(char[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {char swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}} static void shuffle(int[] a) {int n = a.length - 1; for (int i = 0; i < n; ++i) {int ind = randInt(i, n); int swap = a[i]; a[i] = a[ind]; a[ind] = swap;}} static void shuffle(long[] a) {int n = a.length - 1; for (int i = 0; i < n; ++i) {int ind = randInt(i, n); long swap = a[i]; a[i] = a[ind]; a[ind] = swap;}} static void shuffle(double[] a) {int n = a.length - 1; for (int i = 0; i < n; ++i) {int ind = randInt(i, n); double swap = a[i]; a[i] = a[ind]; a[ind] = swap;}} static void rsort(int[] a) {shuffle(a); sort(a);} static void rsort(long[] a) {shuffle(a); sort(a);} static void rsort(double[] a) {shuffle(a); sort(a);} static int[] copy(int[] a) {int[] ans = new int[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;} static long[] copy(long[] a) {long[] ans = new long[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;} static double[] copy(double[] a) {double[] ans = new double[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;} static char[] copy(char[] a) {char[] ans = new char[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;} // input static void r() throws IOException {input = new StringTokenizer(rline());} static int ri() throws IOException {return Integer.parseInt(rline());} static long rl() throws IOException {return Long.parseLong(rline());} static double rd() throws IOException {return Double.parseDouble(rline());} static int[] ria(int n) throws IOException {int[] a = new int[n]; r(); for (int i = 0; i < n; ++i) a[i] = ni(); return a;} static int[] riam1(int n) throws IOException {int[] a = new int[n]; r(); for (int i = 0; i < n; ++i) a[i] = ni() - 1; return a;} static long[] rla(int n) throws IOException {long[] a = new long[n]; r(); for (int i = 0; i < n; ++i) a[i] = nl(); return a;} static double[] rda(int n) throws IOException {double[] a = new double[n]; r(); for (int i = 0; i < n; ++i) a[i] = nd(); return a;} static char[] rcha() throws IOException {return rline().toCharArray();} static String rline() throws IOException {return __in.readLine();} static String n() {return input.nextToken();} static int rni() throws IOException {r(); return ni();} static int ni() {return Integer.parseInt(n());} static long rnl() throws IOException {r(); return nl();} static long nl() {return Long.parseLong(n());} static double rnd() throws IOException {r(); return nd();} static double nd() {return Double.parseDouble(n());} // output static void pr(int i) {__out.print(i);} static void prln(int i) {__out.println(i);} static void pr(long l) {__out.print(l);} static void prln(long l) {__out.println(l);} static void pr(double d) {__out.print(d);} static void prln(double d) {__out.println(d);} static void pr(char c) {__out.print(c);} static void prln(char c) {__out.println(c);} static void pr(char[] s) {__out.print(new String(s));} static void prln(char[] s) {__out.println(new String(s));} static void pr(String s) {__out.print(s);} static void prln(String s) {__out.println(s);} static void pr(Object o) {__out.print(o);} static void prln(Object o) {__out.println(o);} static void prln() {__out.println();} static void pryes() {prln("yes");} static void pry() {prln("Yes");} static void prY() {prln("YES");} static void prno() {prln("no");} static void prn() {prln("No");} static void prN() {prln("NO");} static boolean pryesno(boolean b) {prln(b ? "yes" : "no"); return b;}; static boolean pryn(boolean b) {prln(b ? "Yes" : "No"); return b;} static boolean prYN(boolean b) {prln(b ? "YES" : "NO"); return b;} static void prln(int... a) {for (int i = 0, len = a.length - 1; i < len; pr(a[i]), pr(' '), ++i); if (a.length > 0) prln(a[a.length - 1]); else prln();} static void prln(long... a) {for (int i = 0, len = a.length - 1; i < len; pr(a[i]), pr(' '), ++i); if (a.length > 0) prln(a[a.length - 1]); else prln();} static void prln(double... a) {for (int i = 0, len = a.length - 1; i < len; pr(a[i]), pr(' '), ++i); if (a.length > 0) prln(a[a.length - 1]); else prln();} static <T> void prln(Collection<T> c) {int n = c.size() - 1; Iterator<T> iter = c.iterator(); for (int i = 0; i < n; pr(iter.next()), pr(' '), ++i); if (n >= 0) prln(iter.next()); else prln();} static void h() {prln("hlfd"); flush();} static void flush() {__out.flush();} static void close() {__out.close();} }
Java
["3\n4\nS010\n0001\n1000\n111F\n3\nS10\n101\n01F\n5\nS0101\n00000\n01111\n11111\n0001F"]
1 second
["1\n3 4\n2\n1 2\n2 1\n0"]
NoteFor the first test case, after inverting the cell, we get the following grid:S01000011001111F
Java 11
standard input
[ "constructive algorithms", "implementation" ]
be60cca56505e4b04d24c9b4990553c7
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 50$$$). Description of the test cases follows. The first line of each test case contains one integers $$$n$$$ ($$$3 \le n \le 200$$$). The following $$$n$$$ lines of each test case contain the binary grid, square ($$$1, 1$$$) being colored in 'S' and square ($$$n, n$$$) being colored in 'F'. The sum of values of $$$n$$$ doesn't exceed $$$200$$$.
1,100
For each test case output on the first line an integer $$$c$$$ ($$$0 \le c \le 2$$$)  — the number of inverted cells. In $$$i$$$-th of the following $$$c$$$ lines, print the coordinates of the $$$i$$$-th cell you inverted. You may not invert the same cell twice. Note that you cannot invert cells $$$(1, 1)$$$ and $$$(n, n)$$$.
standard output
PASSED
7a428ee0aaab9cae009d557b64b1c070
train_003.jsonl
1603011900
Pink Floyd are pulling a prank on Roger Waters. They know he doesn't like walls, he wants to be able to walk freely, so they are blocking him from exiting his room which can be seen as a grid.Roger Waters has a square grid of size $$$n\times n$$$ and he wants to traverse his grid from the upper left ($$$1,1$$$) corner to the lower right corner ($$$n,n$$$). Waters can move from a square to any other square adjacent by a side, as long as he is still in the grid. Also except for the cells ($$$1,1$$$) and ($$$n,n$$$) every cell has a value $$$0$$$ or $$$1$$$ in it.Before starting his traversal he will pick either a $$$0$$$ or a $$$1$$$ and will be able to only go to cells values in which are equal to the digit he chose. The starting and finishing cells ($$$1,1$$$) and ($$$n,n$$$) are exempt from this rule, he may go through them regardless of picked digit. Because of this the cell ($$$1,1$$$) takes value the letter 'S' and the cell ($$$n,n$$$) takes value the letter 'F'.For example, in the first example test case, he can go from ($$$1, 1$$$) to ($$$n, n$$$) by using the zeroes on this path: ($$$1, 1$$$), ($$$2, 1$$$), ($$$2, 2$$$), ($$$2, 3$$$), ($$$3, 3$$$), ($$$3, 4$$$), ($$$4, 4$$$)The rest of the band (Pink Floyd) wants Waters to not be able to do his traversal, so while he is not looking they will invert at most two cells in the grid (from $$$0$$$ to $$$1$$$ or vice versa). They are afraid they will not be quick enough and asked for your help in choosing the cells. Note that you cannot invert cells $$$(1, 1)$$$ and $$$(n, n)$$$.We can show that there always exists a solution for the given constraints.Also note that Waters will pick his digit of the traversal after the band has changed his grid, so he must not be able to reach ($$$n,n$$$) no matter what digit he picks.
256 megabytes
import java.io.*; import java.util.*; import static java.lang.Math.*; public class B extends Object { public static final String ANSI_RED = "\u001B[31m"; public static final String ANSI_RESET = "\u001B[0m"; static long startTime; static long endTime; static boolean [] prime ; static int M=(int)1e9+7; static long MM=M*M; static int MAX=Integer.MAX_VALUE; static int MIN=Integer.MIN_VALUE; static int SIZE = (int)1e9*2; static class FastReader{ BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } public static void revArray(int [] arr){ int n =arr.length; for (int i = 0; i < n/2; i++) { int temp=arr[i]; arr[i]=arr[n-i-1]; arr[n-i-1]=temp; } } public static void revArray(long [] arr){ int n =arr.length; for (int i = 0; i < n/2; i++) { long temp=arr[i]; arr[i]=arr[n-i-1]; arr[n-i-1]=temp; } } public static void revArray(Long [] arr){ int n =arr.length; for (int i = 0; i < n/2; i++) { Long temp=arr[i]; arr[i]=arr[n-i-1]; arr[n-i-1]=temp; } } public static void revArray(Integer [] arr){ int n =arr.length; for (int i = 0; i < n/2; i++) { Integer temp=arr[i]; arr[i]=arr[n-i-1]; arr[n-i-1]=temp; } } static void printArray(int[] arr) { int n = arr.length; for (int i = 0; i < n; ++i) System.out.print(arr[i] + " "); System.out.println(); } static void printArray(long[] arr) { int n = arr.length; for (int i = 0; i < n; ++i) System.out.print(arr[i] + " "); System.out.println(); } static void printArray(Integer[] arr) { int n = arr.length; for (int i = 0; i < n; ++i) System.out.print(arr[i] + " "); System.out.println(); } static void printArray(Long[] arr) { int n = arr.length; for (int i = 0; i < n; ++i) System.out.print(arr[i] + " "); System.out.println(); } static void yes(){ System.out.println("YES"); } static void no(){System.out.println("NO");} public static int lowerBound (Integer[] array, int length, int value) { // Returns the index of the value or // if there is no value, returns the closest to the left. int low=-1; // arr[low]<=tar int hi=length;//arr[hi]>tar while (low+1<hi){ // while pointers are not neighboring(low+1!=hi) int mid=(low+hi)/2; if(array[mid]<=value){ low=mid; } else { hi=mid; } } return low;// if no such element, returns -1. } public static int upperBound(Integer[] array, int length, int value){ // returns the index of the value or // if the value does not exist, returns the closest to the right int low=-1; // arr[low]<tar int hi=length;// arr[hi]>=tar while (low+1<hi){// Eventually, pointers should be adjacent. int mid=(low+hi)>>1; if(array[mid]>=value){ hi=mid; } else low=mid; } return hi; } public static int binarySearch(Integer [] arr, int length, int value){ // returns the index of the targeted value or -1 if there is no value. int low=0; int hi=length-1; int ans=-1; while (low<=hi){ int mid=(low+hi)>>1; if(arr[mid]>value){ hi=mid-1; } else if(arr[mid]<value){ low=mid+1; } else { ans=mid; break; } } return ans; } public static int gcd(int a, int b){ if (b == 0) return a; else return gcd(b, a % b); } public static long lcm(int a , int b){ return a/gcd(a,b)*b; } public static int countDivs(int n ){ int cn=0; int sqr = (int)Math.sqrt(n); for (int i = 1; i<=sqr ; ++i) { if(n%i==0){ ++cn; } } cn*=2; if(sqr*sqr==n) cn--; return cn; } static void prime(int x) { //sieve algorithm. nlog(log(n)). prime=new boolean[ (x+1)]; Arrays.fill(prime,true); prime[0] = prime[1] = false; for (int i = 2; i * i <= x ; i++) if (prime[i]) for (int j = i * i; j <= x; j += i) prime[j] = false; } static int[] sum; static void cumulitiveSum( int [] arr){ sum = new int[arr.length]; sum[0]=arr[0]; for (int i = 1; i <arr.length; i++) { sum[i]=arr[i]+sum[i-1]; } } static boolean isEven(long x ){ return x % 2 == 0; } static boolean isPrime(long x ){ boolean flag = true; int sqr = (int)Math.sqrt(x); if(x<2) return false; for (int i = 2; i <=sqr; i++) { if(x%i==0){ flag=false; break; } } return flag; } static long factorial( long x) { long total = 1; for (int i = 2; i <= x; i++) total = (total*i)%M; return total; } static long power(long x, long n) { if (n == 0) { return 1; } long pow = power(x, n / 2L); if ((n & 1) == 1) { return (x * (pow) * (pow)); } return (pow * pow); } static void decimalToRadix(){ int num= sc.nextInt(),radix= sc.nextInt(); StringBuilder s = new StringBuilder(); while (num>0){ int x=num%radix; if(x>9){ s.append((char)('A'+x-10)); } else s.append(x); num/=radix; } System.out.println(s.reverse()); } static void radixToDecimal(){ String num= sc.next(); int radix= sc.nextInt(); int n =num.length(); long ans=0; for (int i = 0; i < n; i++) { int number =num.charAt(i)-'0'; if(!(number>=0 && number<=9)){ number+='0'+10-'A'; } ans+=number*power(radix,n-1-i); } System.out.println(ans); } static void remAndNumber(){ int number= sc.nextInt(),radix= sc.nextInt(); while (number>0) { System.out.println("Remainder: " + number%radix +" Number: " + number ); number /= radix; } } static void dg (String ss){ System.out.println(ANSI_RED + ss + ANSI_RESET); } public static void main(String [] args) throws FileNotFoundException { startTime = System.currentTimeMillis(); int T = sc.nextInt();while (T--!=0) { solve(); } endTime = System.currentTimeMillis(); long duration= endTime-startTime; // System.out.println(duration); } // static Scanner sc = new Scanner(System.in); static FastReader sc = new FastReader(); // dg(String.valueOf()); public static int swap(int... args) { return args[0]; } public static void solve() throws FileNotFoundException { ////////////////////////////////////////////////////////////////////// int n =sc.nextInt(); char [] [] g = new char [n][n]; for (int i = 0; i < n; i++) { String row = sc.next(); for (int j = 0; j < n; j++) { g[i][j]=row.charAt(j); } } // System.out.println("2\n1 2\n" + (n-1)+" " + (n)); if(g[0][1]=='0'&&g[1][0]=='0'&&g[n-1][n-2]=='0'&&g[n-2][n-1]=='0'){//3 System.out.println("2\n1 2\n2 1"); return; } if(g[0][1]=='0'&&g[1][0]=='0'&&g[n-1][n-2]=='0'&&g[n-2][n-1]=='1'){//10 System.out.println("1\n"+(n)+" " + (n-1)); return; } if(g[0][1]=='0'&&g[1][0]=='0'&&g[n-1][n-2]=='1'&&g[n-2][n-1]=='1'){//1 System.out.println(0); return; } if(g[0][1]=='0'&&g[1][0]=='0'&&g[n-1][n-2]=='1'&&g[n-2][n-1]=='0'){//9 System.out.println("1\n"+(n-1)+" " + (n)); return; } if(g[0][1]=='1'&&g[1][0]=='1'&&g[n-1][n-2]=='0'&&g[n-2][n-1]=='0'){//2 System.out.println(0); return; } if(g[0][1]=='1'&&g[1][0]=='1'&&g[n-1][n-2]=='1'&&g[n-2][n-1]=='1'){//4 System.out.println("2\n1 2\n2 1"); return; } if(g[0][1]=='0'&&g[1][0]=='1'&&g[n-1][n-2]=='0'&&g[n-2][n-1]=='1'){//5 System.out.println("2\n1 2\n" + (n-1)+" " + (n));/////////// return; } if(g[0][1]=='0'&&g[1][0]=='1'&&g[n-1][n-2]=='1'&&g[n-2][n-1]=='0'){//6 System.out.println("2\n1 2\n" + (n)+" " + (n-1)); return; } if(g[0][1]=='1'&&g[1][0]=='0'&&g[n-1][n-2]=='0'&&g[n-2][n-1]=='1'){//7 System.out.println("2\n2 1\n" + (n-1)+" " + (n)); return; } if(g[0][1]=='1'&&g[1][0]=='0'&&g[n-1][n-2]=='1'&&g[n-2][n-1]=='0'){//8 System.out.println("2\n2 1\n" + (n)+" " + (n-1)); return; } if(g[0][1]=='1'&&g[1][0]=='0'&&g[n-1][n-2]=='0'&&g[n-2][n-1]=='0'){//11 System.out.println("1\n2 1"); return; } if(g[0][1]=='0'&&g[1][0]=='1'&&g[n-1][n-2]=='0'&&g[n-2][n-1]=='0'){//12 System.out.println("1\n1 2"); return; } if(g[0][1]=='0'&&g[1][0]=='1'&&g[n-1][n-2]=='1'&&g[n-2][n-1]=='1'){//13 System.out.println("1\n2 1"); return; } if(g[0][1]=='1'&&g[1][0]=='0'&&g[n-1][n-2]=='1'&&g[n-2][n-1]=='1'){//14 System.out.println("1\n1 2"); return; } if(g[0][1]=='1'&&g[1][0]=='1'&&g[n-1][n-2]=='0'&&g[n-2][n-1]=='1'){//15 System.out.println("1\n" + (n-1) +" "+(n)); return; } if(g[0][1]=='1'&&g[1][0]=='1'&&g[n-1][n-2]=='1'&&g[n-2][n-1]=='0'){//16 System.out.println("1\n" + (n) +" "+(n-1)); return; } /////////////////////////////////////////////////////////////////////// } }
Java
["3\n4\nS010\n0001\n1000\n111F\n3\nS10\n101\n01F\n5\nS0101\n00000\n01111\n11111\n0001F"]
1 second
["1\n3 4\n2\n1 2\n2 1\n0"]
NoteFor the first test case, after inverting the cell, we get the following grid:S01000011001111F
Java 11
standard input
[ "constructive algorithms", "implementation" ]
be60cca56505e4b04d24c9b4990553c7
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 50$$$). Description of the test cases follows. The first line of each test case contains one integers $$$n$$$ ($$$3 \le n \le 200$$$). The following $$$n$$$ lines of each test case contain the binary grid, square ($$$1, 1$$$) being colored in 'S' and square ($$$n, n$$$) being colored in 'F'. The sum of values of $$$n$$$ doesn't exceed $$$200$$$.
1,100
For each test case output on the first line an integer $$$c$$$ ($$$0 \le c \le 2$$$)  — the number of inverted cells. In $$$i$$$-th of the following $$$c$$$ lines, print the coordinates of the $$$i$$$-th cell you inverted. You may not invert the same cell twice. Note that you cannot invert cells $$$(1, 1)$$$ and $$$(n, n)$$$.
standard output
PASSED
b2516d08d910fa145591e2e45e1f0b22
train_003.jsonl
1603011900
Pink Floyd are pulling a prank on Roger Waters. They know he doesn't like walls, he wants to be able to walk freely, so they are blocking him from exiting his room which can be seen as a grid.Roger Waters has a square grid of size $$$n\times n$$$ and he wants to traverse his grid from the upper left ($$$1,1$$$) corner to the lower right corner ($$$n,n$$$). Waters can move from a square to any other square adjacent by a side, as long as he is still in the grid. Also except for the cells ($$$1,1$$$) and ($$$n,n$$$) every cell has a value $$$0$$$ or $$$1$$$ in it.Before starting his traversal he will pick either a $$$0$$$ or a $$$1$$$ and will be able to only go to cells values in which are equal to the digit he chose. The starting and finishing cells ($$$1,1$$$) and ($$$n,n$$$) are exempt from this rule, he may go through them regardless of picked digit. Because of this the cell ($$$1,1$$$) takes value the letter 'S' and the cell ($$$n,n$$$) takes value the letter 'F'.For example, in the first example test case, he can go from ($$$1, 1$$$) to ($$$n, n$$$) by using the zeroes on this path: ($$$1, 1$$$), ($$$2, 1$$$), ($$$2, 2$$$), ($$$2, 3$$$), ($$$3, 3$$$), ($$$3, 4$$$), ($$$4, 4$$$)The rest of the band (Pink Floyd) wants Waters to not be able to do his traversal, so while he is not looking they will invert at most two cells in the grid (from $$$0$$$ to $$$1$$$ or vice versa). They are afraid they will not be quick enough and asked for your help in choosing the cells. Note that you cannot invert cells $$$(1, 1)$$$ and $$$(n, n)$$$.We can show that there always exists a solution for the given constraints.Also note that Waters will pick his digit of the traversal after the band has changed his grid, so he must not be able to reach ($$$n,n$$$) no matter what digit he picks.
256 megabytes
import java.util.Scanner; public class CodeForces1810 { public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc = new Scanner(System.in); int t = sc.nextInt(); for(int i = 0; i<t; i++) { System.out.println(algo(sc)); } } public static String algo(Scanner sc) { int n = sc.nextInt(); char[][] m = new char[n][n]; for(int i = 0; i<n; i++) { String s = sc.next(); for(int j = 0; j<n; j++) { m[i][j] = s.charAt(j); } } StringBuilder a = new StringBuilder(""); a.append(m[0][1]); a.append(m[1][0]); a.append(m[n-2][n-1]); a.append(m[n-1][n-2]); StringBuilder r = new StringBuilder(""); int[] a1 = transform(a, "1100"); int[] a2 = transform(a, "0011"); int[] q = a1[0]<=a2[0]?a1:a2; if(q[0]==0) return "0 "; else r.append(q[0] + " "); for(int i = 1; i<1+q[0]; i++) { if(q[i]==0) r.append("1 2 "); else if(q[i]==1) r.append("2 1 "); else if(q[i]==2) r.append((n-1) + " " + (n) + " "); else if(q[i]==3) r.append((n) + " " + (n-1) + " "); } r.append("\n"); return r.toString(); } public static int[] transform(StringBuilder a, String o) { int[] r = new int[8]; int g = 1; for(int i = 0; i<4; i++) { if(a.charAt(i)!=o.charAt(i)) { r[0]++; r[g++]=i; } } return r; } }
Java
["3\n4\nS010\n0001\n1000\n111F\n3\nS10\n101\n01F\n5\nS0101\n00000\n01111\n11111\n0001F"]
1 second
["1\n3 4\n2\n1 2\n2 1\n0"]
NoteFor the first test case, after inverting the cell, we get the following grid:S01000011001111F
Java 11
standard input
[ "constructive algorithms", "implementation" ]
be60cca56505e4b04d24c9b4990553c7
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 50$$$). Description of the test cases follows. The first line of each test case contains one integers $$$n$$$ ($$$3 \le n \le 200$$$). The following $$$n$$$ lines of each test case contain the binary grid, square ($$$1, 1$$$) being colored in 'S' and square ($$$n, n$$$) being colored in 'F'. The sum of values of $$$n$$$ doesn't exceed $$$200$$$.
1,100
For each test case output on the first line an integer $$$c$$$ ($$$0 \le c \le 2$$$)  — the number of inverted cells. In $$$i$$$-th of the following $$$c$$$ lines, print the coordinates of the $$$i$$$-th cell you inverted. You may not invert the same cell twice. Note that you cannot invert cells $$$(1, 1)$$$ and $$$(n, n)$$$.
standard output
PASSED
d0738ad151bd241218a77ccc9016c85d
train_003.jsonl
1603011900
Pink Floyd are pulling a prank on Roger Waters. They know he doesn't like walls, he wants to be able to walk freely, so they are blocking him from exiting his room which can be seen as a grid.Roger Waters has a square grid of size $$$n\times n$$$ and he wants to traverse his grid from the upper left ($$$1,1$$$) corner to the lower right corner ($$$n,n$$$). Waters can move from a square to any other square adjacent by a side, as long as he is still in the grid. Also except for the cells ($$$1,1$$$) and ($$$n,n$$$) every cell has a value $$$0$$$ or $$$1$$$ in it.Before starting his traversal he will pick either a $$$0$$$ or a $$$1$$$ and will be able to only go to cells values in which are equal to the digit he chose. The starting and finishing cells ($$$1,1$$$) and ($$$n,n$$$) are exempt from this rule, he may go through them regardless of picked digit. Because of this the cell ($$$1,1$$$) takes value the letter 'S' and the cell ($$$n,n$$$) takes value the letter 'F'.For example, in the first example test case, he can go from ($$$1, 1$$$) to ($$$n, n$$$) by using the zeroes on this path: ($$$1, 1$$$), ($$$2, 1$$$), ($$$2, 2$$$), ($$$2, 3$$$), ($$$3, 3$$$), ($$$3, 4$$$), ($$$4, 4$$$)The rest of the band (Pink Floyd) wants Waters to not be able to do his traversal, so while he is not looking they will invert at most two cells in the grid (from $$$0$$$ to $$$1$$$ or vice versa). They are afraid they will not be quick enough and asked for your help in choosing the cells. Note that you cannot invert cells $$$(1, 1)$$$ and $$$(n, n)$$$.We can show that there always exists a solution for the given constraints.Also note that Waters will pick his digit of the traversal after the band has changed his grid, so he must not be able to reach ($$$n,n$$$) no matter what digit he picks.
256 megabytes
import java.util.Scanner; public class B { public static void main(String[] args) { Scanner sc = new Scanner(System.in); for (int t = sc.nextInt(); t-- > 0;) { int n = sc.nextInt(), c = 0; char a[][] = new char[n][n]; for(int i=0;i<n;i++) a[i]=sc.next().toCharArray(); String s = "", s2 = ""; int x[] = {a[0][1]-'0', a[1][0]-'0', a[n - 2][n - 1]-'0', a[n - 1][n - 2]-'0'}; if(x[0]==x[1]&&x[1]==x[2]&&x[2]==x[3]) {c=2; s="1 2"; s2="2 1";} else if(x[0]+x[1]==x[2]+x[3]) {c=2; s="2 1"; if(x[1]==x[2]) s2= n+" "+(n-1); else s2=(n-1)+" "+n;} else if(x[0]!=x[1]) {c=1; if(x[0]==x[3]) s="1 2"; else s="2 1";} else if(x[2]!=x[3]) {c=1; if(x[2]==x[0]) s=(n-1)+" "+n; else s=n+" "+(n-1);} System.out.println(s!=""?c+"\n"+s+(s2!=""?"\n"+s2:""):c); } } }
Java
["3\n4\nS010\n0001\n1000\n111F\n3\nS10\n101\n01F\n5\nS0101\n00000\n01111\n11111\n0001F"]
1 second
["1\n3 4\n2\n1 2\n2 1\n0"]
NoteFor the first test case, after inverting the cell, we get the following grid:S01000011001111F
Java 11
standard input
[ "constructive algorithms", "implementation" ]
be60cca56505e4b04d24c9b4990553c7
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 50$$$). Description of the test cases follows. The first line of each test case contains one integers $$$n$$$ ($$$3 \le n \le 200$$$). The following $$$n$$$ lines of each test case contain the binary grid, square ($$$1, 1$$$) being colored in 'S' and square ($$$n, n$$$) being colored in 'F'. The sum of values of $$$n$$$ doesn't exceed $$$200$$$.
1,100
For each test case output on the first line an integer $$$c$$$ ($$$0 \le c \le 2$$$)  — the number of inverted cells. In $$$i$$$-th of the following $$$c$$$ lines, print the coordinates of the $$$i$$$-th cell you inverted. You may not invert the same cell twice. Note that you cannot invert cells $$$(1, 1)$$$ and $$$(n, n)$$$.
standard output
PASSED
2bbae638eee0336d145980705e8b9e5b
train_003.jsonl
1603011900
Pink Floyd are pulling a prank on Roger Waters. They know he doesn't like walls, he wants to be able to walk freely, so they are blocking him from exiting his room which can be seen as a grid.Roger Waters has a square grid of size $$$n\times n$$$ and he wants to traverse his grid from the upper left ($$$1,1$$$) corner to the lower right corner ($$$n,n$$$). Waters can move from a square to any other square adjacent by a side, as long as he is still in the grid. Also except for the cells ($$$1,1$$$) and ($$$n,n$$$) every cell has a value $$$0$$$ or $$$1$$$ in it.Before starting his traversal he will pick either a $$$0$$$ or a $$$1$$$ and will be able to only go to cells values in which are equal to the digit he chose. The starting and finishing cells ($$$1,1$$$) and ($$$n,n$$$) are exempt from this rule, he may go through them regardless of picked digit. Because of this the cell ($$$1,1$$$) takes value the letter 'S' and the cell ($$$n,n$$$) takes value the letter 'F'.For example, in the first example test case, he can go from ($$$1, 1$$$) to ($$$n, n$$$) by using the zeroes on this path: ($$$1, 1$$$), ($$$2, 1$$$), ($$$2, 2$$$), ($$$2, 3$$$), ($$$3, 3$$$), ($$$3, 4$$$), ($$$4, 4$$$)The rest of the band (Pink Floyd) wants Waters to not be able to do his traversal, so while he is not looking they will invert at most two cells in the grid (from $$$0$$$ to $$$1$$$ or vice versa). They are afraid they will not be quick enough and asked for your help in choosing the cells. Note that you cannot invert cells $$$(1, 1)$$$ and $$$(n, n)$$$.We can show that there always exists a solution for the given constraints.Also note that Waters will pick his digit of the traversal after the band has changed his grid, so he must not be able to reach ($$$n,n$$$) no matter what digit he picks.
256 megabytes
//package div2_676; import java.util.ArrayList; import java.util.Scanner; public class PuttingBricksInWall { public static void main(String[] args) { Scanner in=new Scanner(System.in); int t=in.nextInt(); while(t>0) { int n=in.nextInt(); in.nextLine(); String[] s=new String[n]; for(int i=0;i<n;i++) { s[i]=in.nextLine(); } char[][] c=new char[n][n]; for(int i=0;i<n;i++) { c[i]=s[i].toCharArray(); } int ans=0; String[] an=new String[2]; if(c[0][1]==c[1][0]) { if(c[0][2]==c[1][1] && c[1][1]==c[2][0]) { if(c[0][1]==c[0][2]) { ans=2; an[0]="1 2"; an[1]="2 1"; } } else { if(c[0][2]==c[0][1]) { ans++; an[ans-1]="1 3"; } if(c[1][1]==c[0][1]) { ans++; an[ans-1]="2 2"; } if(c[2][0]==c[0][1]) { ans++; an[ans-1]="3 1"; } } } else { if(c[0][2]==c[1][1] && c[1][1]==c[2][0]) { ans++; if(c[0][1]==c[1][1]) { an[ans-1]="1 2"; } else { an[ans-1]="2 1"; } } else { if(c[0][2]==c[1][1]) { ans=2; an[0]="3 1"; if(c[0][1]==c[1][1]) { an[1]="1 2"; } else { an[1]="2 1"; } } else if(c[0][2]==c[2][0]) { ans=2; an[0]="2 2"; if(c[0][1]==c[2][0]) { an[1]="1 2"; } else { an[1]="2 1"; } } else { ans=2; an[0]="1 3"; if(c[0][1]==c[1][1]) { an[1]="1 2"; } else { an[1]="2 1"; } } } } System.out.println(ans); for(int i=0;i<ans;i++) { System.out.println(an[i]); } t--; } } }
Java
["3\n4\nS010\n0001\n1000\n111F\n3\nS10\n101\n01F\n5\nS0101\n00000\n01111\n11111\n0001F"]
1 second
["1\n3 4\n2\n1 2\n2 1\n0"]
NoteFor the first test case, after inverting the cell, we get the following grid:S01000011001111F
Java 11
standard input
[ "constructive algorithms", "implementation" ]
be60cca56505e4b04d24c9b4990553c7
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 50$$$). Description of the test cases follows. The first line of each test case contains one integers $$$n$$$ ($$$3 \le n \le 200$$$). The following $$$n$$$ lines of each test case contain the binary grid, square ($$$1, 1$$$) being colored in 'S' and square ($$$n, n$$$) being colored in 'F'. The sum of values of $$$n$$$ doesn't exceed $$$200$$$.
1,100
For each test case output on the first line an integer $$$c$$$ ($$$0 \le c \le 2$$$)  — the number of inverted cells. In $$$i$$$-th of the following $$$c$$$ lines, print the coordinates of the $$$i$$$-th cell you inverted. You may not invert the same cell twice. Note that you cannot invert cells $$$(1, 1)$$$ and $$$(n, n)$$$.
standard output
PASSED
46cf28c325b9325b4503811af195e4ab
train_003.jsonl
1603011900
Pink Floyd are pulling a prank on Roger Waters. They know he doesn't like walls, he wants to be able to walk freely, so they are blocking him from exiting his room which can be seen as a grid.Roger Waters has a square grid of size $$$n\times n$$$ and he wants to traverse his grid from the upper left ($$$1,1$$$) corner to the lower right corner ($$$n,n$$$). Waters can move from a square to any other square adjacent by a side, as long as he is still in the grid. Also except for the cells ($$$1,1$$$) and ($$$n,n$$$) every cell has a value $$$0$$$ or $$$1$$$ in it.Before starting his traversal he will pick either a $$$0$$$ or a $$$1$$$ and will be able to only go to cells values in which are equal to the digit he chose. The starting and finishing cells ($$$1,1$$$) and ($$$n,n$$$) are exempt from this rule, he may go through them regardless of picked digit. Because of this the cell ($$$1,1$$$) takes value the letter 'S' and the cell ($$$n,n$$$) takes value the letter 'F'.For example, in the first example test case, he can go from ($$$1, 1$$$) to ($$$n, n$$$) by using the zeroes on this path: ($$$1, 1$$$), ($$$2, 1$$$), ($$$2, 2$$$), ($$$2, 3$$$), ($$$3, 3$$$), ($$$3, 4$$$), ($$$4, 4$$$)The rest of the band (Pink Floyd) wants Waters to not be able to do his traversal, so while he is not looking they will invert at most two cells in the grid (from $$$0$$$ to $$$1$$$ or vice versa). They are afraid they will not be quick enough and asked for your help in choosing the cells. Note that you cannot invert cells $$$(1, 1)$$$ and $$$(n, n)$$$.We can show that there always exists a solution for the given constraints.Also note that Waters will pick his digit of the traversal after the band has changed his grid, so he must not be able to reach ($$$n,n$$$) no matter what digit he picks.
256 megabytes
import java.util.*; import javax.swing.plaf.basic.BasicScrollPaneUI.HSBChangeListener; import java.io.*; public class A { static BufferedReader br; static PrintWriter pw; static int inf = (int) 1e9; static long mod = (long) 1e9 + 7; static ArrayList<Integer>[] graph; static int n; static char[][] a; static boolean[][] vis; public static void main(String[] args) throws NumberFormatException, IOException, InterruptedException { // br = new BufferedReader(new FileReader(new File("chief.in"))); // br = new BufferedReader(new InputStreamReader(System.in)); Scanner sc = new Scanner(System.in); pw = new PrintWriter(System.out); int t = sc.nextInt(); while (t-- > 0) { n = sc.nextInt(); a = new char[n][n]; for (int i = 0; i < a.length; i++) { a[i] = sc.nextLine().toCharArray(); } int c = 0; ArrayList<pair> ans = new ArrayList<>(); if (a[n - 1][n - 2] == '0') { ans.add(new pair(n, n - 1)); c++; } if (a[n - 2][n - 1] == '0') { ans.add(new pair(n - 1, n)); c++; } if (a[1][0] == '1') { ans.add(new pair(2, 1)); c++; } if (a[0][1] == '1') { ans.add(new pair(1, 2)); c++; } if(c<3) { pw.println(c); for (pair x : ans) pw.println(x.x + " " + x.y); } else { c=0; ans=new ArrayList<>(); if (a[n - 1][n - 2] == '1') { ans.add(new pair(n, n - 1)); c++; } if (a[n - 2][n - 1] == '1') { ans.add(new pair(n - 1, n)); c++; } if (a[1][0] == '0') { ans.add(new pair(2, 1)); c++; } if (a[0][1] == '0') { ans.add(new pair(1, 2)); c++; } pw.println(c); for (pair x : ans) pw.println(x.x + " " + x.y); } // vis = new boolean[n][n]; // boolean f = find('0', 0, 0); // vis = new boolean[n][n]; // boolean g = find('1', 0, 0); //// System.out.println(f+" "+g); // if (!f && !g) // c = 0; // else if (f && g) { // c = 2; // if (a[n - 1][n - 2] == '0') { // ans.add(new pair(n, n - 1)); // } // if (a[n - 2][n - 1] == '0') { // ans.add(new pair(n - 1, n)); // } // if (a[1][0] == '1') { // ans.add(new pair(2, 1)); // } // if (a[0][1] == '1') { // ans.add(new pair(1, 2)); // } // } else if (f) { // if (a[0][1] == '0' && a[1][0] == '0') { // if (a[n - 1][n - 2] == '0') { // c++; // ans.add(new pair(n, n - 1)); // } // if (a[n - 2][n - 1] == '0') { // c++; // ans.add(new pair(n - 1, n)); // } // } else { // // } // } else { // if (a[0][1] == '1' && a[1][0] == '1') { // if (a[n - 1][n - 2] == '1') { // c++; // ans.add(new pair(n, n - 1)); // } // if (a[n - 2][n - 1] == '1') { // c++; // ans.add(new pair(n - 1, n)); // } // } // } } pw.flush(); pw.close(); } static boolean find(int s, int x, int y) { vis[x][y] = true; if (valid(x, y)) { if (x == n - 1 && y == n - 1) return true; boolean f = false; if (valid(x - 1, y) && !vis[x - 1][y] && (a[x - 1][y] == s || a[x - 1][y] == 'F')) f |= find(s, x - 1, y); if (valid(x + 1, y) && !vis[x + 1][y] && (a[x + 1][y] == s || a[x + 1][y] == 'F')) f |= find(s, x + 1, y); if (valid(x, y + 1) && !vis[x][y + 1] && (a[x][y + 1] == s || a[x][y + 1] == 'F')) f |= find(s, x, y + 1); if (valid(x, y - 1) && !vis[x][y - 1] && (a[x][y - 1] == s || a[x][y - 1] == 'F')) f |= find(s, x, y - 1); return f; } return false; } static boolean valid(int x, int y) { return x > -1 && x < n && y > -1 && y < n; } static long ans; static long[][] dp; static boolean[] color, down, total; static int dfs(int u, int pa) { int sum = down[u] ? 1 : 0; for (int v : graph[u]) { if (v == pa) continue; int s = dfs(v, u); ans += Math.min((2 * k - s), s); sum += s; } return sum; } // static int dfs2(int u, int pa, long l) { // int sum = 0; // for (pair v : graph[u]) { // if (v.x == pa) // continue; // if (l + v.y > down[v.x]) { // sum += total[v.x]; // } else { // sum += dfs2(v.x, u, Math.max(0, l + v.y)); // } // } // return sum; // } // static long[] f, g; // // static void numOfSubtrees(int u, int pa) { // f[u] = 1; // for (int v : graph[u]) { // if (v == pa) // continue; // numOfSubtrees(v, u); // f[u] *= (1 + f[v]); // g[u] += f[v] + g[v]; // } // } static ArrayList<Integer> primes; // generated by sieve /* * 1. Generating a list of prime factors of N */ static ArrayList<Long> primeFactors(Long N) // O(sqrt(N) / ln sqrt(N)) { ArrayList<Long> factors = new ArrayList<Long>(); // take abs(N) in case of -ve integers int idx = 0, p = primes.get(idx); while (p * p <= N) { if (N % p == 0) factors.add((long) p); while (N % p == 0) { N /= p; } if (idx + 1 == primes.size()) break; p = primes.get(++idx); } if (N != 1) // last prime factor may be > sqrt(N) factors.add(N); // for integers whose largest prime factor has a power of 1 return factors; } static int[] isComposite; static void sieve(int N) // O(N log log N) { isComposite = new int[N + 1]; isComposite[0] = isComposite[1] = 1; // 0 indicates a prime number primes = new ArrayList<Integer>(); for (int i = 2; i <= N; ++i) // can loop till i*i <= N if primes array is not needed O(N log log sqrt(N)) if (isComposite[i] == 0) // can loop in 2 and odd integers for slightly better performance { primes.add(i); if (1l * i * i <= N) for (int j = i * i; j <= N; j += i) // j = i * 2 will not affect performance too much, may alter in // modified sieve isComposite[j] = 1; } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public boolean ready() throws IOException { return br.ready(); } } static int m, k; static double[] memo; static ArrayList<Integer>[] adj; static long gcd(long a, long b) { if (a == 0) return b; return gcd(b % a, a); } // method to return LCM of two numbers static long lcm(long a, long b) { return (a * b) / gcd(a, b); } static double dis(int x, int y, int z, int w) { return Math.sqrt((x - z) * (x - z) + (y - w) * (y - w)); } static int[] nxtarr() throws IOException { StringTokenizer st = new StringTokenizer(br.readLine()); int[] a = new int[st.countTokens()]; for (int i = 0; i < a.length; i++) { a[i] = Integer.parseInt(st.nextToken()); } return a; } static long[] nxtarrLong() throws IOException { StringTokenizer st = new StringTokenizer(br.readLine()); long[] a = new long[st.countTokens()]; for (int i = 0; i < a.length; i++) { a[i] = Long.parseLong(st.nextToken()); } return a; } static class pair implements Comparable<pair> { int x; int y; public pair(int d, int u) { x = d; y = u; } @Override public int compareTo(pair o) { // TODO Auto-generated method stub if (y == o.y) return x - o.x; return y - o.y; } } static class triple implements Comparable<triple> { int x; int y; int z; public triple(int a, int b, int c) { x = a; y = b; z = c; } @Override public int compareTo(triple o) { // TODO Auto-generated method stub return x - o.x; } } }
Java
["3\n4\nS010\n0001\n1000\n111F\n3\nS10\n101\n01F\n5\nS0101\n00000\n01111\n11111\n0001F"]
1 second
["1\n3 4\n2\n1 2\n2 1\n0"]
NoteFor the first test case, after inverting the cell, we get the following grid:S01000011001111F
Java 11
standard input
[ "constructive algorithms", "implementation" ]
be60cca56505e4b04d24c9b4990553c7
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 50$$$). Description of the test cases follows. The first line of each test case contains one integers $$$n$$$ ($$$3 \le n \le 200$$$). The following $$$n$$$ lines of each test case contain the binary grid, square ($$$1, 1$$$) being colored in 'S' and square ($$$n, n$$$) being colored in 'F'. The sum of values of $$$n$$$ doesn't exceed $$$200$$$.
1,100
For each test case output on the first line an integer $$$c$$$ ($$$0 \le c \le 2$$$)  — the number of inverted cells. In $$$i$$$-th of the following $$$c$$$ lines, print the coordinates of the $$$i$$$-th cell you inverted. You may not invert the same cell twice. Note that you cannot invert cells $$$(1, 1)$$$ and $$$(n, n)$$$.
standard output
PASSED
56a3800708f028691004214dc0e4d5a5
train_003.jsonl
1603011900
Pink Floyd are pulling a prank on Roger Waters. They know he doesn't like walls, he wants to be able to walk freely, so they are blocking him from exiting his room which can be seen as a grid.Roger Waters has a square grid of size $$$n\times n$$$ and he wants to traverse his grid from the upper left ($$$1,1$$$) corner to the lower right corner ($$$n,n$$$). Waters can move from a square to any other square adjacent by a side, as long as he is still in the grid. Also except for the cells ($$$1,1$$$) and ($$$n,n$$$) every cell has a value $$$0$$$ or $$$1$$$ in it.Before starting his traversal he will pick either a $$$0$$$ or a $$$1$$$ and will be able to only go to cells values in which are equal to the digit he chose. The starting and finishing cells ($$$1,1$$$) and ($$$n,n$$$) are exempt from this rule, he may go through them regardless of picked digit. Because of this the cell ($$$1,1$$$) takes value the letter 'S' and the cell ($$$n,n$$$) takes value the letter 'F'.For example, in the first example test case, he can go from ($$$1, 1$$$) to ($$$n, n$$$) by using the zeroes on this path: ($$$1, 1$$$), ($$$2, 1$$$), ($$$2, 2$$$), ($$$2, 3$$$), ($$$3, 3$$$), ($$$3, 4$$$), ($$$4, 4$$$)The rest of the band (Pink Floyd) wants Waters to not be able to do his traversal, so while he is not looking they will invert at most two cells in the grid (from $$$0$$$ to $$$1$$$ or vice versa). They are afraid they will not be quick enough and asked for your help in choosing the cells. Note that you cannot invert cells $$$(1, 1)$$$ and $$$(n, n)$$$.We can show that there always exists a solution for the given constraints.Also note that Waters will pick his digit of the traversal after the band has changed his grid, so he must not be able to reach ($$$n,n$$$) no matter what digit he picks.
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; public class First { public static void main(String[] args) throws Exception { // BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); // int t = Integer.parseInt(br.readLine()); // StringBuilder sb = new StringBuilder(); // while (t-- > 0) { // int n = Integer.parseInt(br.readLine()); // String[] str = (br.readLine()).trim().split(" "); // int[] arr = new int[n]; // for (int i = 0; i < n; i++) { // arr[i] = Integer.parseInt(str[i]); // } // } // return; // first(); sec(); // third(); // four(); // fif(); // six(); } private static void first() throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(br.readLine()); StringBuilder sb = new StringBuilder(); while (t-- > 0) { String[] str = (br.readLine()).trim().split(" "); int n = Integer.parseInt(str[0]); int m = Integer.parseInt(str[1]); System.out.println(n ^ m); } return; } private static void sec() throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(br.readLine()); while (t-- > 0) { int n = Integer.parseInt(br.readLine()); int[][] arr = new int[n][n]; for (int i = 0; i < n; i++) { String[] str = (br.readLine()).trim().split(""); for (int j = 0; j < n; j++) { if ((i == 0 && j == 0) || (i == n - 1 && j == n - 1)) { continue; } arr[i][j] = Integer.parseInt(str[j]); } } int a = arr[1][0], b = arr[0][1]; int x = arr[n - 2][n - 1], y = arr[n - 1][n - 2]; if (a == b && x == y) { if (a != x) { System.out.println("0"); } else { System.out.println("2"); System.out.println("1 2"); System.out.println("2 1"); } } else if (a != b && x == y) { if (x == a) { System.out.println("1"); System.out.println("2 1"); } else { System.out.println("1"); System.out.println("1 2"); } } else if (a == b && x != y) { if (x == a) { System.out.println("1"); System.out.println(n - 1 + " " + n); } else { System.out.println("1"); System.out.println(n + " " + (n - 1)); } } else { if (x == a) { System.out.println("2"); System.out.println("2 1"); System.out.println(n + " " + (n - 1)); } else if (x == b) { System.out.println("2"); System.out.println("1 2"); System.out.println(n + " " + (n-1)); } else if (y == a) { System.out.println("2"); System.out.println("2 1"); System.out.println(n - 1 + " " + (n)); } else if (y == b) { System.out.println("2"); System.out.println("1 2"); System.out.println(n -1+ " " + (n)); } } } return; } private static void third() throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(br.readLine()); StringBuilder sb = new StringBuilder(); while (t-- > 0) { int n = Integer.parseInt(br.readLine()); String[] str = (br.readLine()).trim().split(" "); int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = Integer.parseInt(str[i]); } } return; } private static void four() throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(br.readLine()); StringBuilder sb = new StringBuilder(); while (t-- > 0) { int n = Integer.parseInt(br.readLine()); String[] str = (br.readLine()).trim().split(" "); int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = Integer.parseInt(str[i]); } } return; } private static void fif() throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(br.readLine()); StringBuilder sb = new StringBuilder(); while (t-- > 0) { int n = Integer.parseInt(br.readLine()); String[] str = (br.readLine()).trim().split(" "); int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = Integer.parseInt(str[i]); } } return; } private static void six() throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(br.readLine()); StringBuilder sb = new StringBuilder(); while (t-- > 0) { int n = Integer.parseInt(br.readLine()); String[] str = (br.readLine()).trim().split(" "); int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = Integer.parseInt(str[i]); } } return; } }
Java
["3\n4\nS010\n0001\n1000\n111F\n3\nS10\n101\n01F\n5\nS0101\n00000\n01111\n11111\n0001F"]
1 second
["1\n3 4\n2\n1 2\n2 1\n0"]
NoteFor the first test case, after inverting the cell, we get the following grid:S01000011001111F
Java 11
standard input
[ "constructive algorithms", "implementation" ]
be60cca56505e4b04d24c9b4990553c7
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 50$$$). Description of the test cases follows. The first line of each test case contains one integers $$$n$$$ ($$$3 \le n \le 200$$$). The following $$$n$$$ lines of each test case contain the binary grid, square ($$$1, 1$$$) being colored in 'S' and square ($$$n, n$$$) being colored in 'F'. The sum of values of $$$n$$$ doesn't exceed $$$200$$$.
1,100
For each test case output on the first line an integer $$$c$$$ ($$$0 \le c \le 2$$$)  — the number of inverted cells. In $$$i$$$-th of the following $$$c$$$ lines, print the coordinates of the $$$i$$$-th cell you inverted. You may not invert the same cell twice. Note that you cannot invert cells $$$(1, 1)$$$ and $$$(n, n)$$$.
standard output
PASSED
e0b7e211cae17650ac9ba9f03910be7a
train_003.jsonl
1603011900
Pink Floyd are pulling a prank on Roger Waters. They know he doesn't like walls, he wants to be able to walk freely, so they are blocking him from exiting his room which can be seen as a grid.Roger Waters has a square grid of size $$$n\times n$$$ and he wants to traverse his grid from the upper left ($$$1,1$$$) corner to the lower right corner ($$$n,n$$$). Waters can move from a square to any other square adjacent by a side, as long as he is still in the grid. Also except for the cells ($$$1,1$$$) and ($$$n,n$$$) every cell has a value $$$0$$$ or $$$1$$$ in it.Before starting his traversal he will pick either a $$$0$$$ or a $$$1$$$ and will be able to only go to cells values in which are equal to the digit he chose. The starting and finishing cells ($$$1,1$$$) and ($$$n,n$$$) are exempt from this rule, he may go through them regardless of picked digit. Because of this the cell ($$$1,1$$$) takes value the letter 'S' and the cell ($$$n,n$$$) takes value the letter 'F'.For example, in the first example test case, he can go from ($$$1, 1$$$) to ($$$n, n$$$) by using the zeroes on this path: ($$$1, 1$$$), ($$$2, 1$$$), ($$$2, 2$$$), ($$$2, 3$$$), ($$$3, 3$$$), ($$$3, 4$$$), ($$$4, 4$$$)The rest of the band (Pink Floyd) wants Waters to not be able to do his traversal, so while he is not looking they will invert at most two cells in the grid (from $$$0$$$ to $$$1$$$ or vice versa). They are afraid they will not be quick enough and asked for your help in choosing the cells. Note that you cannot invert cells $$$(1, 1)$$$ and $$$(n, n)$$$.We can show that there always exists a solution for the given constraints.Also note that Waters will pick his digit of the traversal after the band has changed his grid, so he must not be able to reach ($$$n,n$$$) no matter what digit he picks.
256 megabytes
import java.util.Scanner; import java.awt.image.BandedSampleModel; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.lang.reflect.Array; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.Scanner; public class B { public static void main(String args[]) { Scanner sc=new Scanner(System.in); int cases = sc.nextInt(); for(int i=0;i<cases;i++) { int n = sc.nextInt(); int grid[][]=new int[n][n]; // long arr[] = new long[n]; for(int j=0;j<n;j++) { String s=sc.next(); for(int k=0;k<s.length();k++) { grid[j][k]=s.charAt(k)-'0'; } } int l1=grid[1][0]; int l2=grid[0][1]; int r1=grid[n-1][n-2]; int r2=grid[n-2][n-1]; //String ans=""; if(l1==0&&l2==0) { if(r1==0&&r2==0) { System.out.println(2); System.out.println(n+" "+(n-1)); System.out.println((n-1)+" "+(n)); } else if(r1==0&&r2==1) { System.out.println(1); System.out.println(n+" "+(n-1)); //System.out.println((n-1)+" "+(n)); } else if(r1==1&&r2==0) { System.out.println(1); //System.out.println(n+" "+(n-1)); System.out.println((n-1)+" "+(n)); } else { System.out.println(0); } } else if(l1==1&&l2==0) { if(r1==0&&r2==0) { System.out.println(1); //System.out.println(n+" "+(n-1)); System.out.println(1+" "+2); } else if(r1==0&&r2==1) { System.out.println(2); System.out.println((n-1)+" "+(n)); System.out.println(1+" "+2); //System.out.println((n-1)+" "+(n)); } else if(r1==1&&r2==0) { System.out.println(2); System.out.println(1+" "+2); //System.out.println(n+" "+(n-1)); System.out.println((n)+" "+(n-1)); } else if(r1==1&&r2==1) { System.out.println(1); System.out.println(2+" "+1); //System.out.println(n+" "+(n-1)); //System.out.println((n)+" "+(n-1)); } } else if(l1==0&&l2==1) { if(r1==0&&r2==0) { System.out.println(1); //System.out.println(n+" "+(n-1)); System.out.println(2+" "+1); } else if(r1==0&&r2==1) { System.out.println(2); System.out.println((n-1)+" "+(n)); System.out.println(2+" "+1); //System.out.println((n-1)+" "+(n)); } else if(r1==1&&r2==0) { System.out.println(2); System.out.println(1+" "+2); //System.out.println(n+" "+(n-1)); System.out.println((n-1)+" "+(n)); } else if(r1==1&&r2==1) { System.out.println(1); System.out.println(1+" "+2); //System.out.println(n+" "+(n-1)); //System.out.println((n)+" "+(n-1)); } } else { if(r1==1&&r2==1) { System.out.println(2); System.out.println(n+" "+(n-1)); System.out.println((n-1)+" "+(n)); } else if(r1==0&&r2==1) { System.out.println(1); System.out.println((n-1)+" "+(n)); //System.out.println((n-1)+" "+(n)); } else if(r1==1&&r2==0) { System.out.println(1); //System.out.println(n+" "+(n-1)); System.out.println((n)+" "+(n-1)); } else { System.out.println(0); } } } } }
Java
["3\n4\nS010\n0001\n1000\n111F\n3\nS10\n101\n01F\n5\nS0101\n00000\n01111\n11111\n0001F"]
1 second
["1\n3 4\n2\n1 2\n2 1\n0"]
NoteFor the first test case, after inverting the cell, we get the following grid:S01000011001111F
Java 11
standard input
[ "constructive algorithms", "implementation" ]
be60cca56505e4b04d24c9b4990553c7
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 50$$$). Description of the test cases follows. The first line of each test case contains one integers $$$n$$$ ($$$3 \le n \le 200$$$). The following $$$n$$$ lines of each test case contain the binary grid, square ($$$1, 1$$$) being colored in 'S' and square ($$$n, n$$$) being colored in 'F'. The sum of values of $$$n$$$ doesn't exceed $$$200$$$.
1,100
For each test case output on the first line an integer $$$c$$$ ($$$0 \le c \le 2$$$)  — the number of inverted cells. In $$$i$$$-th of the following $$$c$$$ lines, print the coordinates of the $$$i$$$-th cell you inverted. You may not invert the same cell twice. Note that you cannot invert cells $$$(1, 1)$$$ and $$$(n, n)$$$.
standard output
PASSED
f3c01f7f465c20045781d836c4f11024
train_003.jsonl
1603011900
Pink Floyd are pulling a prank on Roger Waters. They know he doesn't like walls, he wants to be able to walk freely, so they are blocking him from exiting his room which can be seen as a grid.Roger Waters has a square grid of size $$$n\times n$$$ and he wants to traverse his grid from the upper left ($$$1,1$$$) corner to the lower right corner ($$$n,n$$$). Waters can move from a square to any other square adjacent by a side, as long as he is still in the grid. Also except for the cells ($$$1,1$$$) and ($$$n,n$$$) every cell has a value $$$0$$$ or $$$1$$$ in it.Before starting his traversal he will pick either a $$$0$$$ or a $$$1$$$ and will be able to only go to cells values in which are equal to the digit he chose. The starting and finishing cells ($$$1,1$$$) and ($$$n,n$$$) are exempt from this rule, he may go through them regardless of picked digit. Because of this the cell ($$$1,1$$$) takes value the letter 'S' and the cell ($$$n,n$$$) takes value the letter 'F'.For example, in the first example test case, he can go from ($$$1, 1$$$) to ($$$n, n$$$) by using the zeroes on this path: ($$$1, 1$$$), ($$$2, 1$$$), ($$$2, 2$$$), ($$$2, 3$$$), ($$$3, 3$$$), ($$$3, 4$$$), ($$$4, 4$$$)The rest of the band (Pink Floyd) wants Waters to not be able to do his traversal, so while he is not looking they will invert at most two cells in the grid (from $$$0$$$ to $$$1$$$ or vice versa). They are afraid they will not be quick enough and asked for your help in choosing the cells. Note that you cannot invert cells $$$(1, 1)$$$ and $$$(n, n)$$$.We can show that there always exists a solution for the given constraints.Also note that Waters will pick his digit of the traversal after the band has changed his grid, so he must not be able to reach ($$$n,n$$$) no matter what digit he picks.
256 megabytes
import java.io.*; import java.util.*; import java.lang.*; public class Rextester{ public static void main(String[] args)throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(br.readLine()); StringBuffer sb = new StringBuffer(); while(t-->0){ int n = Integer.parseInt(br.readLine()); int a=0,b=0,c=0,d=0; for(int i=0;i<n;i++){ String s = br.readLine(); if(i==0){ a = s.charAt(1)-'0'; } if(i==1){ b = s.charAt(0)-'0'; } if(i==n-2){ c = s.charAt(n-1)-'0'; } if(i==n-1){ d = s.charAt(n-2)-'0'; } } //System.out.println(a +" "+b+" "+c+" "+d); if((a^b)==0 && (c^d)==0){ if((a==1 && c==0)||(a==0 && c==1)){ sb.append("0\n"); continue; } else{ sb.append("2\n"); sb.append("1 2\n"); sb.append("2 1\n"); } } else if((a^b)==1 && (c^d)==1){ if(a==c && b==d){ sb.append("2\n1 2\n"+(n)+" "+(n-1)+"\n"); } else { sb.append("2\n2 1\n"+(n)+" "+(n-1)+"\n"); } } else if((a^b)==1 && (c^d)==0){ if(a==c){ sb.append("1\n1 2\n"); } else if(b==c){ sb.append("1\n2 1\n"); } } else if((a^b)==0 && (c^d)==1){ if(a==c){ sb.append("1\n"+(n-1)+" "+n+"\n"); } else if(a==d){ sb.append("1\n"+(n)+" "+(n-1)+"\n"); } } } br.close(); System.out.println(sb); } }
Java
["3\n4\nS010\n0001\n1000\n111F\n3\nS10\n101\n01F\n5\nS0101\n00000\n01111\n11111\n0001F"]
1 second
["1\n3 4\n2\n1 2\n2 1\n0"]
NoteFor the first test case, after inverting the cell, we get the following grid:S01000011001111F
Java 11
standard input
[ "constructive algorithms", "implementation" ]
be60cca56505e4b04d24c9b4990553c7
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 50$$$). Description of the test cases follows. The first line of each test case contains one integers $$$n$$$ ($$$3 \le n \le 200$$$). The following $$$n$$$ lines of each test case contain the binary grid, square ($$$1, 1$$$) being colored in 'S' and square ($$$n, n$$$) being colored in 'F'. The sum of values of $$$n$$$ doesn't exceed $$$200$$$.
1,100
For each test case output on the first line an integer $$$c$$$ ($$$0 \le c \le 2$$$)  — the number of inverted cells. In $$$i$$$-th of the following $$$c$$$ lines, print the coordinates of the $$$i$$$-th cell you inverted. You may not invert the same cell twice. Note that you cannot invert cells $$$(1, 1)$$$ and $$$(n, n)$$$.
standard output
PASSED
6f400a7c76120dbde8a5d09a3cc55cda
train_003.jsonl
1603011900
Pink Floyd are pulling a prank on Roger Waters. They know he doesn't like walls, he wants to be able to walk freely, so they are blocking him from exiting his room which can be seen as a grid.Roger Waters has a square grid of size $$$n\times n$$$ and he wants to traverse his grid from the upper left ($$$1,1$$$) corner to the lower right corner ($$$n,n$$$). Waters can move from a square to any other square adjacent by a side, as long as he is still in the grid. Also except for the cells ($$$1,1$$$) and ($$$n,n$$$) every cell has a value $$$0$$$ or $$$1$$$ in it.Before starting his traversal he will pick either a $$$0$$$ or a $$$1$$$ and will be able to only go to cells values in which are equal to the digit he chose. The starting and finishing cells ($$$1,1$$$) and ($$$n,n$$$) are exempt from this rule, he may go through them regardless of picked digit. Because of this the cell ($$$1,1$$$) takes value the letter 'S' and the cell ($$$n,n$$$) takes value the letter 'F'.For example, in the first example test case, he can go from ($$$1, 1$$$) to ($$$n, n$$$) by using the zeroes on this path: ($$$1, 1$$$), ($$$2, 1$$$), ($$$2, 2$$$), ($$$2, 3$$$), ($$$3, 3$$$), ($$$3, 4$$$), ($$$4, 4$$$)The rest of the band (Pink Floyd) wants Waters to not be able to do his traversal, so while he is not looking they will invert at most two cells in the grid (from $$$0$$$ to $$$1$$$ or vice versa). They are afraid they will not be quick enough and asked for your help in choosing the cells. Note that you cannot invert cells $$$(1, 1)$$$ and $$$(n, n)$$$.We can show that there always exists a solution for the given constraints.Also note that Waters will pick his digit of the traversal after the band has changed his grid, so he must not be able to reach ($$$n,n$$$) no matter what digit he picks.
256 megabytes
import java.util.*; import java.io.*; public class A{ static int[] a; public static void main(String[] args) throws IOException,NumberFormatException{ try { FastScanner sc=new FastScanner(); int t=sc.nextInt(); while(t-->0) { int n=sc.nextInt(); char a[][]=new char[n][n]; for(int i=0;i<n;i++) { char s[]=sc.next().toCharArray(); for(int j=0;j<n;j++) { a[i][j]=s[j]; } } int x1=0,y1=0,x2=0,y2=0; int moves=0; if(a[0][1]==a[1][0]&&a[1][0]==a[n-2][n-1]&&a[n-2][n-1]==a[n-1][n-2]) { moves+=2; x1=1; y1=0; x2=0; y2=1; } else if(a[0][1]==a[1][0]&&a[n-2][n-1]==a[n-1][n-2]) { moves=0; } else { if(a[0][1]==a[1][0]) { moves+=1; if(a[0][1]==a[n-1][n-2]) { x1=n-1; y1=n-2; } else { x1=n-2; y1=n-1; } } else if(a[n-2][n-1]==a[n-1][n-2]) { moves+=1; if(a[0][1]==a[n-1][n-2]) { x1=0; y1=1; } else { x1=1; y1=0; } } else { moves+=2; if(a[0][1]==a[n-2][n-1]) { x1=0;y1=1; x2=n-1;y2=n-2; } else if(a[0][1]==a[n-1][n-2]) { x1=0;y1=1; x2=n-2;y2=n-1; } } } System.out.println(moves); if(moves==0)continue; if(moves==1) { System.out.println((x1+1)+" "+(y1+1)); } else { System.out.println((x1+1)+" "+(y1+1)); System.out.println((x2+1)+" "+(y2+1)); } } } catch(Exception e) { return ; } } public static void insertionSort(int a[]) { int n=a.length; for(int i=1;i<n;i++) { int j=i-1; int x=a[i]; while(j>=0&&a[j]>x) { a[j+1]=a[j]; j--; } a[j+1]=x; } } static final Random random=new Random(); static void ruffleSort(int[] a) { int n=a.length; for(int i=0;i<n;i++) { int oi=random.nextInt(n),temp=a[oi]; a[oi]=a[i]; a[i]=temp; } Arrays.sort(a); } public static class FastScanner { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) {} return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } int[] readArray(int n) { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } long[] readLongArray(int n) { long[] a=new long[n]; for(int i=0; i<n ; i++) a[i]=nextLong(); return a; } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["3\n4\nS010\n0001\n1000\n111F\n3\nS10\n101\n01F\n5\nS0101\n00000\n01111\n11111\n0001F"]
1 second
["1\n3 4\n2\n1 2\n2 1\n0"]
NoteFor the first test case, after inverting the cell, we get the following grid:S01000011001111F
Java 11
standard input
[ "constructive algorithms", "implementation" ]
be60cca56505e4b04d24c9b4990553c7
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 50$$$). Description of the test cases follows. The first line of each test case contains one integers $$$n$$$ ($$$3 \le n \le 200$$$). The following $$$n$$$ lines of each test case contain the binary grid, square ($$$1, 1$$$) being colored in 'S' and square ($$$n, n$$$) being colored in 'F'. The sum of values of $$$n$$$ doesn't exceed $$$200$$$.
1,100
For each test case output on the first line an integer $$$c$$$ ($$$0 \le c \le 2$$$)  — the number of inverted cells. In $$$i$$$-th of the following $$$c$$$ lines, print the coordinates of the $$$i$$$-th cell you inverted. You may not invert the same cell twice. Note that you cannot invert cells $$$(1, 1)$$$ and $$$(n, n)$$$.
standard output
PASSED
72424154e41bc20d60fb965039f40412
train_003.jsonl
1603011900
Pink Floyd are pulling a prank on Roger Waters. They know he doesn't like walls, he wants to be able to walk freely, so they are blocking him from exiting his room which can be seen as a grid.Roger Waters has a square grid of size $$$n\times n$$$ and he wants to traverse his grid from the upper left ($$$1,1$$$) corner to the lower right corner ($$$n,n$$$). Waters can move from a square to any other square adjacent by a side, as long as he is still in the grid. Also except for the cells ($$$1,1$$$) and ($$$n,n$$$) every cell has a value $$$0$$$ or $$$1$$$ in it.Before starting his traversal he will pick either a $$$0$$$ or a $$$1$$$ and will be able to only go to cells values in which are equal to the digit he chose. The starting and finishing cells ($$$1,1$$$) and ($$$n,n$$$) are exempt from this rule, he may go through them regardless of picked digit. Because of this the cell ($$$1,1$$$) takes value the letter 'S' and the cell ($$$n,n$$$) takes value the letter 'F'.For example, in the first example test case, he can go from ($$$1, 1$$$) to ($$$n, n$$$) by using the zeroes on this path: ($$$1, 1$$$), ($$$2, 1$$$), ($$$2, 2$$$), ($$$2, 3$$$), ($$$3, 3$$$), ($$$3, 4$$$), ($$$4, 4$$$)The rest of the band (Pink Floyd) wants Waters to not be able to do his traversal, so while he is not looking they will invert at most two cells in the grid (from $$$0$$$ to $$$1$$$ or vice versa). They are afraid they will not be quick enough and asked for your help in choosing the cells. Note that you cannot invert cells $$$(1, 1)$$$ and $$$(n, n)$$$.We can show that there always exists a solution for the given constraints.Also note that Waters will pick his digit of the traversal after the band has changed his grid, so he must not be able to reach ($$$n,n$$$) no matter what digit he picks.
256 megabytes
/** * Date: 18 Oct, 2020 * Link: https://codeforces.com/contest/1421/problem/B * * @author: Prasad Chaudhari * @linkedIn: https://www.linkedin.com/in/prasad-chaudhari-841655a6/ * @git: https://github.com/Prasad-Chaudhari */ import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.Arrays; import java.util.LinkedList; public class B_1421 { public static void main(String[] args) throws IOException { FastIO in = new FastIO(args); int t = in.ni(); outer: while (t-- > 0) { int n = in.ni(); char[][] c = new char[n][n]; for (int i = 0; i < n; i++) c[i] = in.next().toCharArray(); int[][] indices = new int[][] { new int[] { 0, 1 }, new int[] { 1, 0 }, new int[] { n - 1, n - 2 }, new int[] { n - 2, n - 1 } }; for (int i = 0; i < 1 << 4; i++) { if (Integer.bitCount(i) <= 2) { int temp = i; for (int j = 0; j < 4; j++) { if (temp % 2 == 1) { if (c[indices[j][0]][indices[j][1]] == '0') { c[indices[j][0]][indices[j][1]] = '1'; } else { c[indices[j][0]][indices[j][1]] = '0'; } } temp /= 2; } if (!reachable(c)) { System.out.println(Integer.bitCount(i)); temp = i; for (int j = 0; j < 4; j++) { if (temp % 2 == 1) { System.out.println((indices[j][0] + 1) + " " + (indices[j][1] + 1)); } temp /= 2; } continue outer; } temp = i; for (int j = 0; j < 4; j++) { if (temp % 2 == 1) { if (c[indices[j][0]][indices[j][1]] == '0') { c[indices[j][0]][indices[j][1]] = '1'; } else { c[indices[j][0]][indices[j][1]] = '0'; } } temp /= 2; } } } } in.bw.flush(); } private static boolean reachable(char c[][]) { int n = c.length; boolean reach[][] = new boolean[n][n]; boolean traversed[][] = new boolean[n][n]; reach[0][0] = true; traverse(0, 0, n, '0', c, reach, traversed); if (reach[n - 1][n - 1]) { return true; } reach = new boolean[n][n]; traversed = new boolean[n][n]; reach[0][0] = true; traverse(0, 0, n, '1', c, reach, traversed); return reach[n - 1][n - 1]; } private static void traverse(int x, int y, int n, char match, char c[][], boolean reach[][], boolean traversed[][]) { if (x < 0 || x >= n) return; if (y < 0 || y >= n) return; if (!traversed[x][y]) { traversed[x][y] = true; if (c[x][y] == match || c[x][y] == 'F') { reach[x][y] = true; } if (reach[x][y]) { traverse(x - 1, y, n, match, c, reach, traversed); traverse(x, y - 1, n, match, c, reach, traversed); traverse(x + 1, y, n, match, c, reach, traversed); traverse(x, y + 1, n, match, c, reach, traversed); } } } static class Data implements Comparable<Data> { int a, b; public Data(int a, int b) { this.a = a; this.b = b; } @Override public int compareTo(Data o) { if (a == o.a) { return Integer.compare(b, o.b); } return Integer.compare(a, o.a); } public static void sort(int a[]) { Data d[] = new Data[a.length]; for (int i = 0; i < a.length; i++) { d[i] = new Data(a[i], 0); } Arrays.sort(d); for (int i = 0; i < a.length; i++) { a[i] = d[i].a; } } } static class FastIO { private final BufferedReader br; private final BufferedWriter bw; private String s[]; private int index; public FastIO(String[] args) throws IOException { if (args.length > 1) { br = new BufferedReader(new InputStreamReader(new FileInputStream(new File(args[0])))); bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(args[1])))); } else { br = new BufferedReader(new InputStreamReader(System.in)); bw = new BufferedWriter(new OutputStreamWriter(System.out, "UTF-8")); } s = br.readLine().split(" "); index = 0; } public int ni() throws IOException { return Integer.parseInt(nextToken()); } public double nd() throws IOException { return Double.parseDouble(nextToken()); } public long nl() throws IOException { return Long.parseLong(nextToken()); } public String next() throws IOException { return nextToken(); } public String nli() throws IOException { try { return br.readLine(); } catch (IOException ex) { } return null; } public int[] gia(int n) throws IOException { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = ni(); } return a; } public int[] gia(int n, int start, int end) throws IOException { validate(n, start, end); int a[] = new int[n]; for (int i = start; i < end; i++) { a[i] = ni(); } return a; } public double[] gda(int n) throws IOException { double a[] = new double[n]; for (int i = 0; i < n; i++) { a[i] = nd(); } return a; } public double[] gda(int n, int start, int end) throws IOException { validate(n, start, end); double a[] = new double[n]; for (int i = start; i < end; i++) { a[i] = nd(); } return a; } public long[] gla(int n) throws IOException { long a[] = new long[n]; for (int i = 0; i < n; i++) { a[i] = nl(); } return a; } public long[] gla(int n, int start, int end) throws IOException { validate(n, start, end); long a[] = new long[n]; for (int i = start; i < end; i++) { a[i] = nl(); } return a; } public void print(String s) throws IOException { bw.write(s); } public void println(String s) throws IOException { bw.write(s); bw.newLine(); } public void print(int s) throws IOException { bw.write(s + ""); } public void println(int s) throws IOException { bw.write(s + ""); bw.newLine(); } public void print(long s) throws IOException { bw.write(s + ""); } public void println(long s) throws IOException { bw.write(s + ""); bw.newLine(); } public void print(double s) throws IOException { bw.write(s + ""); } public void println(double s) throws IOException { bw.write(s + ""); bw.newLine(); } private String nextToken() throws IndexOutOfBoundsException, IOException { if (index == s.length) { s = br.readLine().split(" "); index = 0; } return s[index++]; } private void validate(int n, int start, int end) { if (start < 0 || end >= n) { throw new IllegalArgumentException(); } } } }
Java
["3\n4\nS010\n0001\n1000\n111F\n3\nS10\n101\n01F\n5\nS0101\n00000\n01111\n11111\n0001F"]
1 second
["1\n3 4\n2\n1 2\n2 1\n0"]
NoteFor the first test case, after inverting the cell, we get the following grid:S01000011001111F
Java 11
standard input
[ "constructive algorithms", "implementation" ]
be60cca56505e4b04d24c9b4990553c7
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 50$$$). Description of the test cases follows. The first line of each test case contains one integers $$$n$$$ ($$$3 \le n \le 200$$$). The following $$$n$$$ lines of each test case contain the binary grid, square ($$$1, 1$$$) being colored in 'S' and square ($$$n, n$$$) being colored in 'F'. The sum of values of $$$n$$$ doesn't exceed $$$200$$$.
1,100
For each test case output on the first line an integer $$$c$$$ ($$$0 \le c \le 2$$$)  — the number of inverted cells. In $$$i$$$-th of the following $$$c$$$ lines, print the coordinates of the $$$i$$$-th cell you inverted. You may not invert the same cell twice. Note that you cannot invert cells $$$(1, 1)$$$ and $$$(n, n)$$$.
standard output
PASSED
1e67a81c781c72e48bf0ed738be91682
train_003.jsonl
1603011900
Pink Floyd are pulling a prank on Roger Waters. They know he doesn't like walls, he wants to be able to walk freely, so they are blocking him from exiting his room which can be seen as a grid.Roger Waters has a square grid of size $$$n\times n$$$ and he wants to traverse his grid from the upper left ($$$1,1$$$) corner to the lower right corner ($$$n,n$$$). Waters can move from a square to any other square adjacent by a side, as long as he is still in the grid. Also except for the cells ($$$1,1$$$) and ($$$n,n$$$) every cell has a value $$$0$$$ or $$$1$$$ in it.Before starting his traversal he will pick either a $$$0$$$ or a $$$1$$$ and will be able to only go to cells values in which are equal to the digit he chose. The starting and finishing cells ($$$1,1$$$) and ($$$n,n$$$) are exempt from this rule, he may go through them regardless of picked digit. Because of this the cell ($$$1,1$$$) takes value the letter 'S' and the cell ($$$n,n$$$) takes value the letter 'F'.For example, in the first example test case, he can go from ($$$1, 1$$$) to ($$$n, n$$$) by using the zeroes on this path: ($$$1, 1$$$), ($$$2, 1$$$), ($$$2, 2$$$), ($$$2, 3$$$), ($$$3, 3$$$), ($$$3, 4$$$), ($$$4, 4$$$)The rest of the band (Pink Floyd) wants Waters to not be able to do his traversal, so while he is not looking they will invert at most two cells in the grid (from $$$0$$$ to $$$1$$$ or vice versa). They are afraid they will not be quick enough and asked for your help in choosing the cells. Note that you cannot invert cells $$$(1, 1)$$$ and $$$(n, n)$$$.We can show that there always exists a solution for the given constraints.Also note that Waters will pick his digit of the traversal after the band has changed his grid, so he must not be able to reach ($$$n,n$$$) no matter what digit he picks.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; public class PuttingBricksInWall { public static void main(String[] args) throws IOException{ BufferedReader r=new BufferedReader(new InputStreamReader(System.in)); int t=Integer.parseInt(r.readLine()); while(t-->0){ int n=Integer.parseInt(r.readLine()); String[]array=new String[n]; for(int i=0;i<n;i++){ array[i]=r.readLine(); } ArrayList<String>list=new ArrayList<>(); if(array[0].charAt(1)!='0') list.add("1 2"); if(array[1].charAt(0)!='0') list.add("2 1"); if(array[n-2].charAt(n-1)!='1') list.add((n-1)+" "+n); if(array[n-1].charAt(n-2)!='1') list.add((n)+" "+(n-1)); ArrayList<String>list1=new ArrayList<>(); if(array[0].charAt(1)!='1') list1.add("1 2"); if(array[1].charAt(0)!='1') list1.add("2 1"); if(array[n-2].charAt(n-1)!='0') list1.add((n-1)+" "+n); if(array[n-1].charAt(n-2)!='0') list1.add((n)+" "+(n-1)); if(list.size()<list1.size()){ System.out.println(list.size()); for(String s:list) System.out.println(s); } else{ System.out.println(list1.size()); for(String s:list1) System.out.println(s); } } } }
Java
["3\n4\nS010\n0001\n1000\n111F\n3\nS10\n101\n01F\n5\nS0101\n00000\n01111\n11111\n0001F"]
1 second
["1\n3 4\n2\n1 2\n2 1\n0"]
NoteFor the first test case, after inverting the cell, we get the following grid:S01000011001111F
Java 11
standard input
[ "constructive algorithms", "implementation" ]
be60cca56505e4b04d24c9b4990553c7
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 50$$$). Description of the test cases follows. The first line of each test case contains one integers $$$n$$$ ($$$3 \le n \le 200$$$). The following $$$n$$$ lines of each test case contain the binary grid, square ($$$1, 1$$$) being colored in 'S' and square ($$$n, n$$$) being colored in 'F'. The sum of values of $$$n$$$ doesn't exceed $$$200$$$.
1,100
For each test case output on the first line an integer $$$c$$$ ($$$0 \le c \le 2$$$)  — the number of inverted cells. In $$$i$$$-th of the following $$$c$$$ lines, print the coordinates of the $$$i$$$-th cell you inverted. You may not invert the same cell twice. Note that you cannot invert cells $$$(1, 1)$$$ and $$$(n, n)$$$.
standard output
PASSED
05cdb9c1638b3a07baf9a482b71fc635
train_003.jsonl
1603011900
Pink Floyd are pulling a prank on Roger Waters. They know he doesn't like walls, he wants to be able to walk freely, so they are blocking him from exiting his room which can be seen as a grid.Roger Waters has a square grid of size $$$n\times n$$$ and he wants to traverse his grid from the upper left ($$$1,1$$$) corner to the lower right corner ($$$n,n$$$). Waters can move from a square to any other square adjacent by a side, as long as he is still in the grid. Also except for the cells ($$$1,1$$$) and ($$$n,n$$$) every cell has a value $$$0$$$ or $$$1$$$ in it.Before starting his traversal he will pick either a $$$0$$$ or a $$$1$$$ and will be able to only go to cells values in which are equal to the digit he chose. The starting and finishing cells ($$$1,1$$$) and ($$$n,n$$$) are exempt from this rule, he may go through them regardless of picked digit. Because of this the cell ($$$1,1$$$) takes value the letter 'S' and the cell ($$$n,n$$$) takes value the letter 'F'.For example, in the first example test case, he can go from ($$$1, 1$$$) to ($$$n, n$$$) by using the zeroes on this path: ($$$1, 1$$$), ($$$2, 1$$$), ($$$2, 2$$$), ($$$2, 3$$$), ($$$3, 3$$$), ($$$3, 4$$$), ($$$4, 4$$$)The rest of the band (Pink Floyd) wants Waters to not be able to do his traversal, so while he is not looking they will invert at most two cells in the grid (from $$$0$$$ to $$$1$$$ or vice versa). They are afraid they will not be quick enough and asked for your help in choosing the cells. Note that you cannot invert cells $$$(1, 1)$$$ and $$$(n, n)$$$.We can show that there always exists a solution for the given constraints.Also note that Waters will pick his digit of the traversal after the band has changed his grid, so he must not be able to reach ($$$n,n$$$) no matter what digit he picks.
256 megabytes
import java.util.*; public class Main { public static void main(String[] args){ Scanner sc = new Scanner(System.in); int t = sc.nextInt(); for ( int j=0; j<t; j++ ) { int n = sc.nextInt(); String[][] m = new String[n][n]; for ( int i=0; i<n; i++ ) { String x = sc.next(); m[i] = x.split(""); } int c = 0; int[][] p = new int[2][2]; if ( m[0][1].equals(m[1][0]) ) { if ( m[n-2][n-1].equals(m[0][1]) ) { p[c][0] = n-1; p[c][1] = n; c++; } if ( m[n-1][n-2].equals(m[0][1]) ) { p[c][0] = n; p[c][1] = n-1; c++; } } else if ( m[n-2][n-1].equals(m[n-1][n-2]) ) { if ( m[0][1].equals(m[n-2][n-1]) ) { p[c][0] = 1; p[c][1] = 2; c++; } if ( m[1][0].equals(m[n-2][n-1]) ) { p[c][0] = 2; p[c][1] = 1; c++; } } else if ( m[0][1].equals(m[n-2][n-1]) ) { p[c][0] = 1; p[c][1] = 2; c++; p[c][0] = n; p[c][1] = n-1; c++; } else { p[c][0] = 1; p[c][1] = 2; c++; p[c][0] = n-1; p[c][1] = n; c++; } System.out.println(c); for ( int i=0; i<c; i++ ) { System.out.println(p[i][0] + " " + p[i][1]); } } } }
Java
["3\n4\nS010\n0001\n1000\n111F\n3\nS10\n101\n01F\n5\nS0101\n00000\n01111\n11111\n0001F"]
1 second
["1\n3 4\n2\n1 2\n2 1\n0"]
NoteFor the first test case, after inverting the cell, we get the following grid:S01000011001111F
Java 11
standard input
[ "constructive algorithms", "implementation" ]
be60cca56505e4b04d24c9b4990553c7
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 50$$$). Description of the test cases follows. The first line of each test case contains one integers $$$n$$$ ($$$3 \le n \le 200$$$). The following $$$n$$$ lines of each test case contain the binary grid, square ($$$1, 1$$$) being colored in 'S' and square ($$$n, n$$$) being colored in 'F'. The sum of values of $$$n$$$ doesn't exceed $$$200$$$.
1,100
For each test case output on the first line an integer $$$c$$$ ($$$0 \le c \le 2$$$)  — the number of inverted cells. In $$$i$$$-th of the following $$$c$$$ lines, print the coordinates of the $$$i$$$-th cell you inverted. You may not invert the same cell twice. Note that you cannot invert cells $$$(1, 1)$$$ and $$$(n, n)$$$.
standard output
PASSED
41c85674e7c27aed9b87aa3fff28fc4c
train_003.jsonl
1603011900
Pink Floyd are pulling a prank on Roger Waters. They know he doesn't like walls, he wants to be able to walk freely, so they are blocking him from exiting his room which can be seen as a grid.Roger Waters has a square grid of size $$$n\times n$$$ and he wants to traverse his grid from the upper left ($$$1,1$$$) corner to the lower right corner ($$$n,n$$$). Waters can move from a square to any other square adjacent by a side, as long as he is still in the grid. Also except for the cells ($$$1,1$$$) and ($$$n,n$$$) every cell has a value $$$0$$$ or $$$1$$$ in it.Before starting his traversal he will pick either a $$$0$$$ or a $$$1$$$ and will be able to only go to cells values in which are equal to the digit he chose. The starting and finishing cells ($$$1,1$$$) and ($$$n,n$$$) are exempt from this rule, he may go through them regardless of picked digit. Because of this the cell ($$$1,1$$$) takes value the letter 'S' and the cell ($$$n,n$$$) takes value the letter 'F'.For example, in the first example test case, he can go from ($$$1, 1$$$) to ($$$n, n$$$) by using the zeroes on this path: ($$$1, 1$$$), ($$$2, 1$$$), ($$$2, 2$$$), ($$$2, 3$$$), ($$$3, 3$$$), ($$$3, 4$$$), ($$$4, 4$$$)The rest of the band (Pink Floyd) wants Waters to not be able to do his traversal, so while he is not looking they will invert at most two cells in the grid (from $$$0$$$ to $$$1$$$ or vice versa). They are afraid they will not be quick enough and asked for your help in choosing the cells. Note that you cannot invert cells $$$(1, 1)$$$ and $$$(n, n)$$$.We can show that there always exists a solution for the given constraints.Also note that Waters will pick his digit of the traversal after the band has changed his grid, so he must not be able to reach ($$$n,n$$$) no matter what digit he picks.
256 megabytes
import java.io.*; import java.util.*; public class B181020 { public static void main(String[] args) throws IOException { // TODO Auto-generated method stub BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(br.readLine()); while(t-->0) { int n = Integer.parseInt(br.readLine()); String s[] = new String[n]; for(int i = 0; i<n; i++) { s[i] = br.readLine(); } int a = Integer.parseInt(String.valueOf(s[0].charAt(1))); int b = Integer.parseInt(String.valueOf(s[1].charAt(0))); int x = Integer.parseInt(String.valueOf(s[n-2].charAt(n-1))); int y = Integer.parseInt(String.valueOf(s[n-1].charAt(n-2))); if(a+b == 0 && x+y == 0) { System.out.println(2); System.out.println(1+" "+2); System.out.println(2+" "+1); } if(a+b==2 && x+y==2) { System.out.println(2); System.out.println(1+" "+2); System.out.println(2+" "+1); } if(a+b == 1 && x+y==1) { System.out.println(2); if(a==1 && b==0) { System.out.println(1+" "+2); } else { System.out.println(2+" "+1); } if(x==0 && y==1) { System.out.println((n-1)+" "+(n)); } else { System.out.println((n)+" "+(n-1)); } } if(a+b == 1 && x+y==0) { System.out.println(1); if(a==1) { System.out.println(2+" "+1); } else { System.out.println(1+" "+2); } } if(a+b==0 && x+y==1) { System.out.println(1); if(x==1) { System.out.println((n)+" "+(n-1)); } else { System.out.println((n-1)+" "+(n)); } } if(a+b==0 && x+y==2) { System.out.println(0); } if(a+b==2 && x+y==0) { System.out.println(0); } if(a+b==2 && x+y==1) { System.out.println(1); if(x==1) { System.out.println((n-1)+" "+n); } else { System.out.println(n+" "+(n-1)); } } if(a+b==1 && x+y==2) { System.out.println(1); if(a==1) { System.out.println(1+" "+2); } else { System.out.println(2+" "+1); } } } } }
Java
["3\n4\nS010\n0001\n1000\n111F\n3\nS10\n101\n01F\n5\nS0101\n00000\n01111\n11111\n0001F"]
1 second
["1\n3 4\n2\n1 2\n2 1\n0"]
NoteFor the first test case, after inverting the cell, we get the following grid:S01000011001111F
Java 11
standard input
[ "constructive algorithms", "implementation" ]
be60cca56505e4b04d24c9b4990553c7
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 50$$$). Description of the test cases follows. The first line of each test case contains one integers $$$n$$$ ($$$3 \le n \le 200$$$). The following $$$n$$$ lines of each test case contain the binary grid, square ($$$1, 1$$$) being colored in 'S' and square ($$$n, n$$$) being colored in 'F'. The sum of values of $$$n$$$ doesn't exceed $$$200$$$.
1,100
For each test case output on the first line an integer $$$c$$$ ($$$0 \le c \le 2$$$)  — the number of inverted cells. In $$$i$$$-th of the following $$$c$$$ lines, print the coordinates of the $$$i$$$-th cell you inverted. You may not invert the same cell twice. Note that you cannot invert cells $$$(1, 1)$$$ and $$$(n, n)$$$.
standard output
PASSED
a50493e061e175ad444632c32901d4f6
train_003.jsonl
1603011900
Pink Floyd are pulling a prank on Roger Waters. They know he doesn't like walls, he wants to be able to walk freely, so they are blocking him from exiting his room which can be seen as a grid.Roger Waters has a square grid of size $$$n\times n$$$ and he wants to traverse his grid from the upper left ($$$1,1$$$) corner to the lower right corner ($$$n,n$$$). Waters can move from a square to any other square adjacent by a side, as long as he is still in the grid. Also except for the cells ($$$1,1$$$) and ($$$n,n$$$) every cell has a value $$$0$$$ or $$$1$$$ in it.Before starting his traversal he will pick either a $$$0$$$ or a $$$1$$$ and will be able to only go to cells values in which are equal to the digit he chose. The starting and finishing cells ($$$1,1$$$) and ($$$n,n$$$) are exempt from this rule, he may go through them regardless of picked digit. Because of this the cell ($$$1,1$$$) takes value the letter 'S' and the cell ($$$n,n$$$) takes value the letter 'F'.For example, in the first example test case, he can go from ($$$1, 1$$$) to ($$$n, n$$$) by using the zeroes on this path: ($$$1, 1$$$), ($$$2, 1$$$), ($$$2, 2$$$), ($$$2, 3$$$), ($$$3, 3$$$), ($$$3, 4$$$), ($$$4, 4$$$)The rest of the band (Pink Floyd) wants Waters to not be able to do his traversal, so while he is not looking they will invert at most two cells in the grid (from $$$0$$$ to $$$1$$$ or vice versa). They are afraid they will not be quick enough and asked for your help in choosing the cells. Note that you cannot invert cells $$$(1, 1)$$$ and $$$(n, n)$$$.We can show that there always exists a solution for the given constraints.Also note that Waters will pick his digit of the traversal after the band has changed his grid, so he must not be able to reach ($$$n,n$$$) no matter what digit he picks.
256 megabytes
import java.util.*; public class S { static void print1() { System.out.println(1+" "+2); return; } static void print2() { System.out.println(2+" "+1); return; } static void print3(int n) { System.out.println((n)+" "+(n-1)); return; } static void print4(int n) { System.out.println((n-1)+" "+(n)); return; } public static void main(String [] args) { Scanner obj = new Scanner(System.in); int t = obj.nextInt(); while(t-->0) { int n = obj.nextInt(); ArrayList<String> arr = new ArrayList<String>(); for(int i=0;i<n;i++) { String s = obj.next(); arr.add(s); } char a1=arr.get(0).charAt(1); char a2=arr.get(1).charAt(0); char b1=arr.get(n-1).charAt(n-2); char b2=arr.get(n-2).charAt(n-1); if(a1==a2&&a1=='0') { if(b1!=b2) { System.out.println("1"); if(b1=='0') print3(n); else print4(n); } else if(b1==b2&&b1=='0') { System.out.println(2); print3(n); print4(n); } else { System.out.println(0); } } else if(a1==a2&&a1=='1') { if(b1!=b2) { System.out.println("1"); if(b1=='1') print3(n); else print4(n); } else if(b1==b2&&b1=='1') { System.out.println(2); print3(n); print4(n); } else { System.out.println(0); } } else if(a1!=a2) { if(b1==b2&&b1=='0') { System.out.println(1); if(a1=='0') print1(); else print2(); } else if(b1==b2&&b1=='1') { System.out.println(1); if(a1=='1') print1(); else print2(); } else if(b1!=b2) { System.out.println(2); if(a1!='0') print1(); if(a2!='0') print2(); if(b1!='1') print3(n); if(b2!='1') print4(n); } } } } }
Java
["3\n4\nS010\n0001\n1000\n111F\n3\nS10\n101\n01F\n5\nS0101\n00000\n01111\n11111\n0001F"]
1 second
["1\n3 4\n2\n1 2\n2 1\n0"]
NoteFor the first test case, after inverting the cell, we get the following grid:S01000011001111F
Java 11
standard input
[ "constructive algorithms", "implementation" ]
be60cca56505e4b04d24c9b4990553c7
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 50$$$). Description of the test cases follows. The first line of each test case contains one integers $$$n$$$ ($$$3 \le n \le 200$$$). The following $$$n$$$ lines of each test case contain the binary grid, square ($$$1, 1$$$) being colored in 'S' and square ($$$n, n$$$) being colored in 'F'. The sum of values of $$$n$$$ doesn't exceed $$$200$$$.
1,100
For each test case output on the first line an integer $$$c$$$ ($$$0 \le c \le 2$$$)  — the number of inverted cells. In $$$i$$$-th of the following $$$c$$$ lines, print the coordinates of the $$$i$$$-th cell you inverted. You may not invert the same cell twice. Note that you cannot invert cells $$$(1, 1)$$$ and $$$(n, n)$$$.
standard output
PASSED
e4ac064484d8c4287c4d05ccfe0618d4
train_003.jsonl
1603011900
Pink Floyd are pulling a prank on Roger Waters. They know he doesn't like walls, he wants to be able to walk freely, so they are blocking him from exiting his room which can be seen as a grid.Roger Waters has a square grid of size $$$n\times n$$$ and he wants to traverse his grid from the upper left ($$$1,1$$$) corner to the lower right corner ($$$n,n$$$). Waters can move from a square to any other square adjacent by a side, as long as he is still in the grid. Also except for the cells ($$$1,1$$$) and ($$$n,n$$$) every cell has a value $$$0$$$ or $$$1$$$ in it.Before starting his traversal he will pick either a $$$0$$$ or a $$$1$$$ and will be able to only go to cells values in which are equal to the digit he chose. The starting and finishing cells ($$$1,1$$$) and ($$$n,n$$$) are exempt from this rule, he may go through them regardless of picked digit. Because of this the cell ($$$1,1$$$) takes value the letter 'S' and the cell ($$$n,n$$$) takes value the letter 'F'.For example, in the first example test case, he can go from ($$$1, 1$$$) to ($$$n, n$$$) by using the zeroes on this path: ($$$1, 1$$$), ($$$2, 1$$$), ($$$2, 2$$$), ($$$2, 3$$$), ($$$3, 3$$$), ($$$3, 4$$$), ($$$4, 4$$$)The rest of the band (Pink Floyd) wants Waters to not be able to do his traversal, so while he is not looking they will invert at most two cells in the grid (from $$$0$$$ to $$$1$$$ or vice versa). They are afraid they will not be quick enough and asked for your help in choosing the cells. Note that you cannot invert cells $$$(1, 1)$$$ and $$$(n, n)$$$.We can show that there always exists a solution for the given constraints.Also note that Waters will pick his digit of the traversal after the band has changed his grid, so he must not be able to reach ($$$n,n$$$) no matter what digit he picks.
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; public class Main { public static void main (String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw = new PrintWriter(System.out); int t = Integer.parseInt(br.readLine()); while(t-- > 0){ int n = Integer.parseInt(br.readLine()); int arr[][] = new int[n][n]; for(int i = 0; i<n; i++){ String num[] = br.readLine().split(""); for(int j = 0; j<n; j++){ if((i==0 && j==0) || (i==n-1 && j==n-1)) continue; arr[i][j] = Integer.parseInt(num[j]); } } int startRight = arr[0][1]; int startBottom = arr[1][0]; int destLeft = arr[n-1][n-2]; int destTop = arr[n-2][n-1]; if(startBottom==startRight){ if(startRight==destLeft && startRight==destTop){ pw.println(2); pw.println(1+" "+2); pw.println(2+" "+1); } else if(startRight==destLeft && startRight!=destTop){ pw.println(1); pw.print(n+" "); pw.println(n-1); } else if(startRight!=destLeft && startRight==destTop){ pw.println(1); pw.println(n-1+" "+n); } else{ pw.println("0"); } } else if(destLeft==destTop) { if(startRight==destLeft && startBottom!=destTop){ pw.println(1); pw.println(1+" "+2); } else if(startRight!=destLeft && startBottom==destTop){ pw.println(1); pw.println(2+" "+1); } else{ pw.print("0"); pw.println(); } } else { if(startBottom==destLeft){ pw.println(2); pw.println(2+" "+1); pw.println(n-1+" "+n); } else if(startBottom==destTop){ pw.println(2); pw.println(2+" "+1); pw.print(n+" "); pw.println(n-1); } else{ pw.println("0"); } } } pw.flush(); } }
Java
["3\n4\nS010\n0001\n1000\n111F\n3\nS10\n101\n01F\n5\nS0101\n00000\n01111\n11111\n0001F"]
1 second
["1\n3 4\n2\n1 2\n2 1\n0"]
NoteFor the first test case, after inverting the cell, we get the following grid:S01000011001111F
Java 11
standard input
[ "constructive algorithms", "implementation" ]
be60cca56505e4b04d24c9b4990553c7
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 50$$$). Description of the test cases follows. The first line of each test case contains one integers $$$n$$$ ($$$3 \le n \le 200$$$). The following $$$n$$$ lines of each test case contain the binary grid, square ($$$1, 1$$$) being colored in 'S' and square ($$$n, n$$$) being colored in 'F'. The sum of values of $$$n$$$ doesn't exceed $$$200$$$.
1,100
For each test case output on the first line an integer $$$c$$$ ($$$0 \le c \le 2$$$)  — the number of inverted cells. In $$$i$$$-th of the following $$$c$$$ lines, print the coordinates of the $$$i$$$-th cell you inverted. You may not invert the same cell twice. Note that you cannot invert cells $$$(1, 1)$$$ and $$$(n, n)$$$.
standard output
PASSED
0638f8365167c6b8a2ac7b5561d261f0
train_003.jsonl
1603011900
Pink Floyd are pulling a prank on Roger Waters. They know he doesn't like walls, he wants to be able to walk freely, so they are blocking him from exiting his room which can be seen as a grid.Roger Waters has a square grid of size $$$n\times n$$$ and he wants to traverse his grid from the upper left ($$$1,1$$$) corner to the lower right corner ($$$n,n$$$). Waters can move from a square to any other square adjacent by a side, as long as he is still in the grid. Also except for the cells ($$$1,1$$$) and ($$$n,n$$$) every cell has a value $$$0$$$ or $$$1$$$ in it.Before starting his traversal he will pick either a $$$0$$$ or a $$$1$$$ and will be able to only go to cells values in which are equal to the digit he chose. The starting and finishing cells ($$$1,1$$$) and ($$$n,n$$$) are exempt from this rule, he may go through them regardless of picked digit. Because of this the cell ($$$1,1$$$) takes value the letter 'S' and the cell ($$$n,n$$$) takes value the letter 'F'.For example, in the first example test case, he can go from ($$$1, 1$$$) to ($$$n, n$$$) by using the zeroes on this path: ($$$1, 1$$$), ($$$2, 1$$$), ($$$2, 2$$$), ($$$2, 3$$$), ($$$3, 3$$$), ($$$3, 4$$$), ($$$4, 4$$$)The rest of the band (Pink Floyd) wants Waters to not be able to do his traversal, so while he is not looking they will invert at most two cells in the grid (from $$$0$$$ to $$$1$$$ or vice versa). They are afraid they will not be quick enough and asked for your help in choosing the cells. Note that you cannot invert cells $$$(1, 1)$$$ and $$$(n, n)$$$.We can show that there always exists a solution for the given constraints.Also note that Waters will pick his digit of the traversal after the band has changed his grid, so he must not be able to reach ($$$n,n$$$) no matter what digit he picks.
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; public class Main { public static void main (String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw = new PrintWriter(System.out); int t = Integer.parseInt(br.readLine()); while(t-- > 0){ int n = Integer.parseInt(br.readLine()); int arr[][] = new int[n][n]; for(int i = 0; i<n; i++){ String num[] = br.readLine().split(""); for(int j = 0; j<n; j++){ if((i==0 && j==0) || (i==n-1 && j==n-1)) continue; arr[i][j] = Integer.parseInt(num[j]); } } int startRight = arr[0][1]; int startBottom = arr[1][0]; int destLeft = arr[n-1][n-2]; int destTop = arr[n-2][n-1]; if(startBottom==startRight){ if(startRight==destLeft && startRight==destTop){ pw.println(2); pw.println(1+" "+2); pw.println(2+" "+1); } else if(startRight==destLeft && startRight!=destTop){ pw.println(1); pw.print(n+" "); pw.println(n-1); } else if(startRight!=destLeft && startRight==destTop){ pw.println(1); pw.println(n-1+" "+n); } else{ pw.println("0"); } } else if(destLeft==destTop) { if(startRight==destLeft && startBottom!=destTop){ pw.println(1); pw.println(1+" "+2); } else if(startRight!=destLeft && startBottom==destTop){ pw.println(1); pw.println(2+" "+1); } else{ pw.println("0"); } } else { if(startBottom==destLeft){ pw.println(2); pw.println(2+" "+1); pw.println(n-1+" "+n); } else if(startBottom==destTop){ pw.println(2); pw.println(2+" "+1); pw.print(n+" "); pw.println(n-1); } else{ pw.println("0"); } } } pw.flush(); } }
Java
["3\n4\nS010\n0001\n1000\n111F\n3\nS10\n101\n01F\n5\nS0101\n00000\n01111\n11111\n0001F"]
1 second
["1\n3 4\n2\n1 2\n2 1\n0"]
NoteFor the first test case, after inverting the cell, we get the following grid:S01000011001111F
Java 11
standard input
[ "constructive algorithms", "implementation" ]
be60cca56505e4b04d24c9b4990553c7
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 50$$$). Description of the test cases follows. The first line of each test case contains one integers $$$n$$$ ($$$3 \le n \le 200$$$). The following $$$n$$$ lines of each test case contain the binary grid, square ($$$1, 1$$$) being colored in 'S' and square ($$$n, n$$$) being colored in 'F'. The sum of values of $$$n$$$ doesn't exceed $$$200$$$.
1,100
For each test case output on the first line an integer $$$c$$$ ($$$0 \le c \le 2$$$)  — the number of inverted cells. In $$$i$$$-th of the following $$$c$$$ lines, print the coordinates of the $$$i$$$-th cell you inverted. You may not invert the same cell twice. Note that you cannot invert cells $$$(1, 1)$$$ and $$$(n, n)$$$.
standard output
PASSED
702427bc6e9b3fbeca68ac428e2f8d89
train_003.jsonl
1603011900
Pink Floyd are pulling a prank on Roger Waters. They know he doesn't like walls, he wants to be able to walk freely, so they are blocking him from exiting his room which can be seen as a grid.Roger Waters has a square grid of size $$$n\times n$$$ and he wants to traverse his grid from the upper left ($$$1,1$$$) corner to the lower right corner ($$$n,n$$$). Waters can move from a square to any other square adjacent by a side, as long as he is still in the grid. Also except for the cells ($$$1,1$$$) and ($$$n,n$$$) every cell has a value $$$0$$$ or $$$1$$$ in it.Before starting his traversal he will pick either a $$$0$$$ or a $$$1$$$ and will be able to only go to cells values in which are equal to the digit he chose. The starting and finishing cells ($$$1,1$$$) and ($$$n,n$$$) are exempt from this rule, he may go through them regardless of picked digit. Because of this the cell ($$$1,1$$$) takes value the letter 'S' and the cell ($$$n,n$$$) takes value the letter 'F'.For example, in the first example test case, he can go from ($$$1, 1$$$) to ($$$n, n$$$) by using the zeroes on this path: ($$$1, 1$$$), ($$$2, 1$$$), ($$$2, 2$$$), ($$$2, 3$$$), ($$$3, 3$$$), ($$$3, 4$$$), ($$$4, 4$$$)The rest of the band (Pink Floyd) wants Waters to not be able to do his traversal, so while he is not looking they will invert at most two cells in the grid (from $$$0$$$ to $$$1$$$ or vice versa). They are afraid they will not be quick enough and asked for your help in choosing the cells. Note that you cannot invert cells $$$(1, 1)$$$ and $$$(n, n)$$$.We can show that there always exists a solution for the given constraints.Also note that Waters will pick his digit of the traversal after the band has changed his grid, so he must not be able to reach ($$$n,n$$$) no matter what digit he picks.
256 megabytes
import java.io.*; import java.util.*; public class Hackerrank { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t=sc.nextInt(); for(int i=0;i<t;i++) { int n=sc.nextInt(); String[] grid= new String[n]; sc.nextLine(); for(int j=0;j<n;j++) { grid[j]=sc.nextLine(); } int start1=0; int start0=0; int end1=0; int end0=0; if(String.valueOf(grid[0].charAt(1)).equals("0")) start0+=1; else start1+=1; if(String.valueOf(grid[1].charAt(0)).equals("0")) start0+=1; else start1+=1; if(String.valueOf(grid[n-1].charAt(n-2)).equals("0")) end0+=1; else end1+=1; if(String.valueOf(grid[n-2].charAt(n-1)).equals("0")) end0+=1; else end1+=1; if((start0==2 && end0==2) || (end1==2 && start1==2)) { System.out.println("2"); System.out.println("1 2"); System.out.println("2 1"); } else if(start1==1 && end1==1) { System.out.println("2"); if(String.valueOf(grid[0].charAt(1)).equals("1")) System.out.println("1 2"); else System.out.println("2 1"); if(String.valueOf(grid[n-2].charAt(n-1)).equals("0")) System.out.println(String.valueOf(n-1)+" "+String.valueOf(n)); else System.out.println(String.valueOf(n)+" "+String.valueOf(n-1)); } else if(start1==2 && end1==1) { System.out.println("1"); if(String.valueOf(grid[n-2].charAt(n-1)).equals("1")) System.out.println(String.valueOf(n-1)+" "+String.valueOf(n)); else System.out.println(String.valueOf(n)+" "+String.valueOf(n-1)); } else if(start0==2 && end0==1) { System.out.println("1"); if(String.valueOf(grid[n-2].charAt(n-1)).equals("0")) System.out.println(String.valueOf(n-1)+" "+String.valueOf(n)); else System.out.println(String.valueOf(n)+" "+String.valueOf(n-1)); } else if(start1==1 && end1==2) { System.out.println("1"); if(String.valueOf(grid[0].charAt(1)).equals("1")) System.out.println("1 2"); else System.out.println("2 1"); } else if(start0==1 && end0==2) { System.out.println("1"); if(String.valueOf(grid[0].charAt(1)).equals("0")) System.out.println("1 2"); else System.out.println("2 1"); } else { System.out.println("0"); } } } }
Java
["3\n4\nS010\n0001\n1000\n111F\n3\nS10\n101\n01F\n5\nS0101\n00000\n01111\n11111\n0001F"]
1 second
["1\n3 4\n2\n1 2\n2 1\n0"]
NoteFor the first test case, after inverting the cell, we get the following grid:S01000011001111F
Java 11
standard input
[ "constructive algorithms", "implementation" ]
be60cca56505e4b04d24c9b4990553c7
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 50$$$). Description of the test cases follows. The first line of each test case contains one integers $$$n$$$ ($$$3 \le n \le 200$$$). The following $$$n$$$ lines of each test case contain the binary grid, square ($$$1, 1$$$) being colored in 'S' and square ($$$n, n$$$) being colored in 'F'. The sum of values of $$$n$$$ doesn't exceed $$$200$$$.
1,100
For each test case output on the first line an integer $$$c$$$ ($$$0 \le c \le 2$$$)  — the number of inverted cells. In $$$i$$$-th of the following $$$c$$$ lines, print the coordinates of the $$$i$$$-th cell you inverted. You may not invert the same cell twice. Note that you cannot invert cells $$$(1, 1)$$$ and $$$(n, n)$$$.
standard output
PASSED
6214cc7b8896631ab7656ad5a92bf65a
train_003.jsonl
1603011900
Pink Floyd are pulling a prank on Roger Waters. They know he doesn't like walls, he wants to be able to walk freely, so they are blocking him from exiting his room which can be seen as a grid.Roger Waters has a square grid of size $$$n\times n$$$ and he wants to traverse his grid from the upper left ($$$1,1$$$) corner to the lower right corner ($$$n,n$$$). Waters can move from a square to any other square adjacent by a side, as long as he is still in the grid. Also except for the cells ($$$1,1$$$) and ($$$n,n$$$) every cell has a value $$$0$$$ or $$$1$$$ in it.Before starting his traversal he will pick either a $$$0$$$ or a $$$1$$$ and will be able to only go to cells values in which are equal to the digit he chose. The starting and finishing cells ($$$1,1$$$) and ($$$n,n$$$) are exempt from this rule, he may go through them regardless of picked digit. Because of this the cell ($$$1,1$$$) takes value the letter 'S' and the cell ($$$n,n$$$) takes value the letter 'F'.For example, in the first example test case, he can go from ($$$1, 1$$$) to ($$$n, n$$$) by using the zeroes on this path: ($$$1, 1$$$), ($$$2, 1$$$), ($$$2, 2$$$), ($$$2, 3$$$), ($$$3, 3$$$), ($$$3, 4$$$), ($$$4, 4$$$)The rest of the band (Pink Floyd) wants Waters to not be able to do his traversal, so while he is not looking they will invert at most two cells in the grid (from $$$0$$$ to $$$1$$$ or vice versa). They are afraid they will not be quick enough and asked for your help in choosing the cells. Note that you cannot invert cells $$$(1, 1)$$$ and $$$(n, n)$$$.We can show that there always exists a solution for the given constraints.Also note that Waters will pick his digit of the traversal after the band has changed his grid, so he must not be able to reach ($$$n,n$$$) no matter what digit he picks.
256 megabytes
import java.util.ArrayList; import javax.management.RuntimeErrorException; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; import java.util.Arrays; import java.util.Random; import java.io.FileWriter; import java.io.PrintWriter; /* Solution Created: 13:02:19 18/10/2020 Custom Competitive programming helper. */ public class Main { static int n; static char[][] g; static boolean vis[][]; static boolean can = false; public static void solve(Reader in, Writer out) { int t = in.nextInt(); outer: while(t-->0) { n = in.nextInt(); g = new char[n][n]; for(int i = 0; i<n; i++) g[i] = in.nca(); char[][] gC = new char[n][n]; for(int i = 0; i<n; i++) for(int j = 0; j<n; j++) gC[i][j] = g[i][j]; int[] dx = {0,1,n-1,n-2}; int[] dy = {1,0,n-2,n-1}; for(int msk = 0; msk<(1<<4); msk++) { int totalOn = 0; for(int i = 0; i<4; i++) { if(isOn(msk, i)) { g[dx[i]][dy[i]] = sp(gC[dx[i]][dy[i]]); totalOn++; } else { g[dx[i]][dy[i]] = gC[dx[i]][dy[i]]; } } if(totalOn>2) continue; boolean c1 = canReach('1'); boolean c2 = canReach('0'); if(!c1 && !c2) { ArrayList<Integer> ans = new ArrayList<Integer>(); for(int i = 0; i<n; i++) for(int j = 0; j<n; j++) if(g[i][j]!=gC[i][j]) { ans.add(i+1); ans.add(j+1); } out.println(ans.size()/2); for(int i = 0; i<ans.size(); i+=2) { out.println(ans.get(i)+" "+ans.get(i+1)); } continue outer; } } throw new RuntimeErrorException(null,"dab"); } } public static char sp(char c) { if(c=='1') return '0'; return '1'; } public static boolean isOn(int v, int b) { return ((v&1<<b) != 0); } public static boolean canReach(char v) { can = false; vis = new boolean[n][n]; dfs(0, 0, v); return can; } public static void dfs(int i, int j, char v) { if(!(i>=0 && j>=0 && i<n && j<n)) return; if(vis[i][j]) return; if(i==n-1 && j==n-1) { can = true; return; } if(g[i][j]!=v && g[i][j]!='S') return; vis[i][j] = true; dfs(i+1, j,v); dfs(i-1, j,v); dfs(i, j+1,v); dfs(i, j-1,v); } public static void main(String[] args) { Reader in = new Reader(); Writer out = new Writer(); solve(in, out); out.exit(); } static class Reader { static BufferedReader br; static StringTokenizer st; private int charIdx = 0; private String s; public Reader() { this.br = new BufferedReader(new InputStreamReader(System.in)); } public Reader(String f){ try { this.br = new BufferedReader(new FileReader(f)); } catch (IOException e) { e.printStackTrace(); } } public int[] na(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public double[] nd(int n) { double[] a = new double[n]; for (int i = 0; i < n; i++) a[i] = nextDouble(); return a; } public char nextChar() { if (s == null || charIdx >= s.length()) { if (st == null || !st.hasMoreTokens()) try { readLine(); } catch (Exception e) { } s = st.nextToken(); charIdx = 0; } return s.charAt(charIdx++); } public long[] nl(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } public char[] nca() { return next().toCharArray(); } public String[] nS(int n) { String[] a = new String[n]; for (int i = 0; i < n; i++) a[i] = next(); return a; } public int nextInt() { if (st == null || !st.hasMoreTokens()) try { readLine(); } catch (Exception e) { } return Integer.parseInt(st.nextToken()); } public double nextDouble() { if (st == null || !st.hasMoreTokens()) try { readLine(); } catch (Exception e) { } return Double.parseDouble(st.nextToken()); } public Long nextLong() { if (st == null || !st.hasMoreTokens()) try { readLine(); } catch (Exception e) { } return Long.parseLong(st.nextToken()); } public String next() { if (st == null || !st.hasMoreTokens()) try { readLine(); } catch (Exception e) { } return st.nextToken(); } public static void readLine() { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { } } } static class Util{ private static Random random = new Random(); static long[] fact; public static void initFactorial(int n, long mod) { fact = new long[n+1]; fact[0] = 1; for (int i = 1; i < n+1; i++) fact[i] = (fact[i - 1] * i) % mod; } public static long modInverse(long a, long MOD) { long[] gcdE = gcdExtended(a, MOD); if (gcdE[0] != 1) return -1; // Inverted doesn't exist long x = gcdE[1]; return (x % MOD + MOD) % MOD; } public static long[] gcdExtended(long p, long q) { if (q == 0) return new long[] { p, 1, 0 }; long[] vals = gcdExtended(q, p % q); long tmp = vals[2]; vals[2] = vals[1] - (p / q) * vals[2]; vals[1] = tmp; return vals; } public static long nCr(int n, int r, long MOD) { if (r == 0) return 1; return (fact[n] * modInverse(fact[r], MOD) % MOD * modInverse(fact[n - r], MOD) % MOD) % MOD; } public static long nCr(int n, int r) { return (fact[n]/fact[r])/fact[n-r]; } public static long nPr(int n, int r, long MOD) { if (r == 0) return 1; return (fact[n] * modInverse(fact[n - r], MOD) % MOD) % MOD; } public static long nPr(int n, int r) { return fact[n]/fact[n-r]; } public static boolean isPrime(int n) { if (n <= 1) return false; if (n <= 3) return true; if (n % 2 == 0 || n % 3 == 0) return false; for (int i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } public static int lowerBound(int[] a, int v) { int l = 0, h = a.length; while(l<h) { int mid = (l+h)/2; if(v<=a[mid]) h = mid; else l = mid+1; } return l; } public static int lowerBound(long[] a, long v) { int l = 0, h = a.length; while(l<h) { int mid = (l+h)/2; if(v<=a[mid]) h = mid; else l = mid+1; } return l; } public static int upperBound(int[] a, int v) { int l = 0, h = a.length; while(l<h) { int mid = (l+h)/2; if(a[mid]<=v) l = mid+1; else h = mid; } return l; } public static int upperBound(long[] a, long v) { int l = 0, h = a.length; while(l<h) { int mid = (l+h)/2; if(a[mid]<=v) l = mid+1; else h = mid; } return l; } public static boolean[] getSieve(int n) { boolean[] isPrime = new boolean[n+1]; for (int i = 2; i <= n; i++) isPrime[i] = true; for (int i = 2; i*i <= n; i++) if (isPrime[i]) for (int j = i; i*j <= n; j++) isPrime[i*j] = false; return isPrime; } public static int gcd(int a, int b) { int tmp = 0; while(b != 0) { tmp = b; b = a%b; a = tmp; } return a; } public static long gcd(long a, long b) { long tmp = 0; while(b != 0) { tmp = b; b = a%b; a = tmp; } return a; } public static int random(int min, int max) { return random.nextInt(max-min+1)+min; } public static void dbg(Object... o) { System.out.println(Arrays.deepToString(o)); } public static void reverse(int[] s, int l , int r) { for(int i = l; i<=(l+r)/2; i++) { int tmp = s[i]; s[i] = s[r+l-i]; s[r+l-i] = tmp; } } public static void reverse(int[] s) { reverse(s, 0, s.length-1); } public static void reverse(long[] s, int l , int r) { for(int i = l; i<=(l+r)/2; i++) { long tmp = s[i]; s[i] = s[r+l-i]; s[r+l-i] = tmp; } } public static void reverse(long[] s) { reverse(s, 0, s.length-1); } public static void reverse(float[] s, int l , int r) { for(int i = l; i<=(l+r)/2; i++) { float tmp = s[i]; s[i] = s[r+l-i]; s[r+l-i] = tmp; } } public static void reverse(float[] s) { reverse(s, 0, s.length-1); } public static void reverse(double[] s, int l , int r) { for(int i = l; i<=(l+r)/2; i++) { double tmp = s[i]; s[i] = s[r+l-i]; s[r+l-i] = tmp; } } public static void reverse(double[] s) { reverse(s, 0, s.length-1); } public static void reverse(char[] s, int l , int r) { for(int i = l; i<=(l+r)/2; i++) { char tmp = s[i]; s[i] = s[r+l-i]; s[r+l-i] = tmp; } } public static void reverse(char[] s) { reverse(s, 0, s.length-1); } public static <T> void reverse(T[] s, int l , int r) { for(int i = l; i<=(l+r)/2; i++) { T tmp = s[i]; s[i] = s[r+l-i]; s[r+l-i] = tmp; } } public static <T> void reverse(T[] s) { reverse(s, 0, s.length-1); } public static void shuffle(int[] s) { for (int i = 0; i < s.length; ++i) { int j = random.nextInt(i + 1); int t = s[i]; s[i] = s[j]; s[j] = t; } } public static void shuffle(long[] s) { for (int i = 0; i < s.length; ++i) { int j = random.nextInt(i + 1); long t = s[i]; s[i] = s[j]; s[j] = t; } } public static void shuffle(float[] s) { for (int i = 0; i < s.length; ++i) { int j = random.nextInt(i + 1); float t = s[i]; s[i] = s[j]; s[j] = t; } } public static void shuffle(double[] s) { for (int i = 0; i < s.length; ++i) { int j = random.nextInt(i + 1); double t = s[i]; s[i] = s[j]; s[j] = t; } } public static void shuffle(char[] s) { for (int i = 0; i < s.length; ++i) { int j = random.nextInt(i + 1); char t = s[i]; s[i] = s[j]; s[j] = t; } } public static <T> void shuffle(T[] s) { for (int i = 0; i < s.length; ++i) { int j = random.nextInt(i + 1); T t = s[i]; s[i] = s[j]; s[j] = t; } } public static void sortArray(int[] a) { shuffle(a); Arrays.sort(a); } public static void sortArray(long[] a) { shuffle(a); Arrays.sort(a); } public static void sortArray(float[] a) { shuffle(a); Arrays.sort(a); } public static void sortArray(double[] a) { shuffle(a); Arrays.sort(a); } public static void sortArray(char[] a) { shuffle(a); Arrays.sort(a); } public static <T extends Comparable<T>> void sortArray(T[] a) { Arrays.sort(a); } } static class Writer { private PrintWriter pw; public Writer(){ pw = new PrintWriter(System.out); } public Writer(String f){ try { pw = new PrintWriter(new FileWriter(f)); } catch (IOException e) { e.printStackTrace(); } } public void printArray(int[] a) { for(int i = 0; i<a.length; i++) print(a[i]+" "); } public void printlnArray(int[] a) { for(int i = 0; i<a.length; i++) print(a[i]+" "); pw.println(); } public void printArray(long[] a) { for(int i = 0; i<a.length; i++) print(a[i]+" "); } public void printlnArray(long[] a) { for(int i = 0; i<a.length; i++) print(a[i]+" "); pw.println(); } public void print(Object o) { pw.print(o.toString()); } public void println(Object o) { pw.println(o.toString()); } public void println() { pw.println(); } public void flush() { pw.flush(); } public void exit() { pw.close(); } } }
Java
["3\n4\nS010\n0001\n1000\n111F\n3\nS10\n101\n01F\n5\nS0101\n00000\n01111\n11111\n0001F"]
1 second
["1\n3 4\n2\n1 2\n2 1\n0"]
NoteFor the first test case, after inverting the cell, we get the following grid:S01000011001111F
Java 11
standard input
[ "constructive algorithms", "implementation" ]
be60cca56505e4b04d24c9b4990553c7
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 50$$$). Description of the test cases follows. The first line of each test case contains one integers $$$n$$$ ($$$3 \le n \le 200$$$). The following $$$n$$$ lines of each test case contain the binary grid, square ($$$1, 1$$$) being colored in 'S' and square ($$$n, n$$$) being colored in 'F'. The sum of values of $$$n$$$ doesn't exceed $$$200$$$.
1,100
For each test case output on the first line an integer $$$c$$$ ($$$0 \le c \le 2$$$)  — the number of inverted cells. In $$$i$$$-th of the following $$$c$$$ lines, print the coordinates of the $$$i$$$-th cell you inverted. You may not invert the same cell twice. Note that you cannot invert cells $$$(1, 1)$$$ and $$$(n, n)$$$.
standard output
PASSED
cb89ef0bbcaf983a319506e6de2be3df
train_003.jsonl
1603011900
Pink Floyd are pulling a prank on Roger Waters. They know he doesn't like walls, he wants to be able to walk freely, so they are blocking him from exiting his room which can be seen as a grid.Roger Waters has a square grid of size $$$n\times n$$$ and he wants to traverse his grid from the upper left ($$$1,1$$$) corner to the lower right corner ($$$n,n$$$). Waters can move from a square to any other square adjacent by a side, as long as he is still in the grid. Also except for the cells ($$$1,1$$$) and ($$$n,n$$$) every cell has a value $$$0$$$ or $$$1$$$ in it.Before starting his traversal he will pick either a $$$0$$$ or a $$$1$$$ and will be able to only go to cells values in which are equal to the digit he chose. The starting and finishing cells ($$$1,1$$$) and ($$$n,n$$$) are exempt from this rule, he may go through them regardless of picked digit. Because of this the cell ($$$1,1$$$) takes value the letter 'S' and the cell ($$$n,n$$$) takes value the letter 'F'.For example, in the first example test case, he can go from ($$$1, 1$$$) to ($$$n, n$$$) by using the zeroes on this path: ($$$1, 1$$$), ($$$2, 1$$$), ($$$2, 2$$$), ($$$2, 3$$$), ($$$3, 3$$$), ($$$3, 4$$$), ($$$4, 4$$$)The rest of the band (Pink Floyd) wants Waters to not be able to do his traversal, so while he is not looking they will invert at most two cells in the grid (from $$$0$$$ to $$$1$$$ or vice versa). They are afraid they will not be quick enough and asked for your help in choosing the cells. Note that you cannot invert cells $$$(1, 1)$$$ and $$$(n, n)$$$.We can show that there always exists a solution for the given constraints.Also note that Waters will pick his digit of the traversal after the band has changed his grid, so he must not be able to reach ($$$n,n$$$) no matter what digit he picks.
256 megabytes
import java.lang.*; import java.util.*; import java.io.*; // import java.io.BufferedReader; // import java.io.IOException; // import java.io.InputStreamReader; public class Main { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } public static void main(String[] args)throws java.lang.Exception { FastReader sc = new FastReader(); StringBuffer sb = new StringBuffer(); // ArrayList<Integer> al=new ArrayList<>(); // ArrayList<Integer> b=new ArrayList<>(); // Set<Integer> x=new HashSet<>(); // Set<Integer> y=new HashSet<>(); int t=sc.nextInt(); while(t-->0) { int n=sc.nextInt(); String[] s=new String[n]; for(int i=0;i<n;i++) s[i]=sc.next(); if((s[0].charAt(1)=='1') && (s[1].charAt(0)=='1')) { if((s[n-1].charAt(s[n-1].length()-2)=='1') && (s[n-2].charAt(s[n-1].length()-1)=='1')) { System.out.println(2); System.out.println(1+" "+2); System.out.println(2+" "+1); continue; } else if((s[n-1].charAt(s[n-1].length()-2)=='0') && (s[n-2].charAt(s[n-1].length()-1)=='0')) { System.out.println(0); continue; } else if((s[n-1].charAt(s[n-1].length()-2)=='1') && (s[n-2].charAt(s[n-1].length()-1)=='0')) { System.out.println(1); System.out.println(n+" "+(n-1)); continue; } else { System.out.println(1); System.out.println((n-1)+" "+(n)); continue; } } if((s[0].charAt(1)=='0') && (s[1].charAt(0)=='0')) { if((s[n-1].charAt(s[n-1].length()-2)=='1') && (s[n-2].charAt(s[n-1].length()-1)=='1')) { System.out.println(0); continue; } else if((s[n-1].charAt(s[n-1].length()-2)=='0') && (s[n-2].charAt(s[n-1].length()-1)=='0')) { System.out.println(2); System.out.println(1+" "+2); System.out.println(2+" "+1); continue; } else if((s[n-1].charAt(s[n-1].length()-2)=='1') && (s[n-2].charAt(s[n-1].length()-1)=='0')) { System.out.println(1); System.out.println((n-1)+" "+(n)); continue; } else { System.out.println(1); System.out.println(n+" "+(n-1)); continue; } } if((s[1].charAt(0)=='1') && (s[0].charAt(1)=='0')) { if((s[n-1].charAt(s[n-1].length()-2)=='1') && (s[n-2].charAt(s[n-1].length()-1)=='1')) { System.out.println(1); System.out.println(2+" "+1); continue; } else if((s[n-1].charAt(s[n-1].length()-2)=='0') && (s[n-2].charAt(s[n-1].length()-1)=='0')) { System.out.println(1); System.out.println(1+" "+2); continue; } else if((s[n-1].charAt(s[n-1].length()-2)=='1') && (s[n-2].charAt(s[n-1].length()-1)=='0')) { System.out.println(2); System.out.println(2+" "+1); System.out.println((n-1)+" "+(n)); continue; } else { System.out.println(2); System.out.println(2+" "+1); System.out.println((n)+" "+(n-1)); continue; } } else { if((s[n-1].charAt(s[n-1].length()-2)=='1') && (s[n-2].charAt(s[n-1].length()-1)=='1')) { System.out.println(1); System.out.println(1+" "+2); continue; } else if((s[n-1].charAt(s[n-1].length()-2)=='0') && (s[n-2].charAt(s[n-1].length()-1)=='0')) { System.out.println(1); System.out.println(2+" "+1); continue; } else if((s[n-1].charAt(s[n-1].length()-2)=='1') && (s[n-2].charAt(s[n-1].length()-1)=='0')) { System.out.println(2); System.out.println(2+" "+1); System.out.println((n)+" "+(n-1)); continue; } else { System.out.println(2); System.out.println(2+" "+1); System.out.println((n-1)+" "+(n)); continue; } } } } }
Java
["3\n4\nS010\n0001\n1000\n111F\n3\nS10\n101\n01F\n5\nS0101\n00000\n01111\n11111\n0001F"]
1 second
["1\n3 4\n2\n1 2\n2 1\n0"]
NoteFor the first test case, after inverting the cell, we get the following grid:S01000011001111F
Java 11
standard input
[ "constructive algorithms", "implementation" ]
be60cca56505e4b04d24c9b4990553c7
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 50$$$). Description of the test cases follows. The first line of each test case contains one integers $$$n$$$ ($$$3 \le n \le 200$$$). The following $$$n$$$ lines of each test case contain the binary grid, square ($$$1, 1$$$) being colored in 'S' and square ($$$n, n$$$) being colored in 'F'. The sum of values of $$$n$$$ doesn't exceed $$$200$$$.
1,100
For each test case output on the first line an integer $$$c$$$ ($$$0 \le c \le 2$$$)  — the number of inverted cells. In $$$i$$$-th of the following $$$c$$$ lines, print the coordinates of the $$$i$$$-th cell you inverted. You may not invert the same cell twice. Note that you cannot invert cells $$$(1, 1)$$$ and $$$(n, n)$$$.
standard output
PASSED
a8e06c9cb1db8222efefd136be645d0e
train_003.jsonl
1603011900
Pink Floyd are pulling a prank on Roger Waters. They know he doesn't like walls, he wants to be able to walk freely, so they are blocking him from exiting his room which can be seen as a grid.Roger Waters has a square grid of size $$$n\times n$$$ and he wants to traverse his grid from the upper left ($$$1,1$$$) corner to the lower right corner ($$$n,n$$$). Waters can move from a square to any other square adjacent by a side, as long as he is still in the grid. Also except for the cells ($$$1,1$$$) and ($$$n,n$$$) every cell has a value $$$0$$$ or $$$1$$$ in it.Before starting his traversal he will pick either a $$$0$$$ or a $$$1$$$ and will be able to only go to cells values in which are equal to the digit he chose. The starting and finishing cells ($$$1,1$$$) and ($$$n,n$$$) are exempt from this rule, he may go through them regardless of picked digit. Because of this the cell ($$$1,1$$$) takes value the letter 'S' and the cell ($$$n,n$$$) takes value the letter 'F'.For example, in the first example test case, he can go from ($$$1, 1$$$) to ($$$n, n$$$) by using the zeroes on this path: ($$$1, 1$$$), ($$$2, 1$$$), ($$$2, 2$$$), ($$$2, 3$$$), ($$$3, 3$$$), ($$$3, 4$$$), ($$$4, 4$$$)The rest of the band (Pink Floyd) wants Waters to not be able to do his traversal, so while he is not looking they will invert at most two cells in the grid (from $$$0$$$ to $$$1$$$ or vice versa). They are afraid they will not be quick enough and asked for your help in choosing the cells. Note that you cannot invert cells $$$(1, 1)$$$ and $$$(n, n)$$$.We can show that there always exists a solution for the given constraints.Also note that Waters will pick his digit of the traversal after the band has changed his grid, so he must not be able to reach ($$$n,n$$$) no matter what digit he picks.
256 megabytes
import java.util.*; import java.io.*; import java.math.*; public class B { static class Coord{ int x, y; public Coord(int x, int y){ this.x = x; this.y = y; } } static boolean isValid(int x, int y, int n, boolean visited[][], char arr[][], char req){ return (x <= n && y <= n && x >= 1 && y >= 1 && !visited[x][y] && arr[x][y] == req); } static boolean bfs1(char arr[][], int n){ boolean visited[][] = new boolean[n + 1][n + 1]; Coord c = new Coord(1, 1); visited[1][1] = true; Queue<Coord> q = new LinkedList<>(); q.add(c); while(!q.isEmpty()){ c = q.poll(); int x = c.x, y = c.y, nx = 0, ny = 0; for(int i = 0; i < 4; i++){ nx = x + dx[i]; ny = y + dy[i]; if(nx == n && ny == n) return true; if(isValid(nx, ny, n, visited, arr, '1')){ Coord nc = new Coord(nx, ny); q.add(nc); visited[nx][ny] = true; } } } return false; } static boolean bfs0(char arr[][], int n){ boolean visited[][] = new boolean[n + 1][n + 1]; Coord c = new Coord(1, 1); visited[1][1] = true; Queue<Coord> q = new LinkedList<>(); q.add(c); while(!q.isEmpty()){ c = q.poll(); int x = c.x, y = c.y, nx = 0, ny = 0; for(int i = 0; i < 4; i++){ nx = x + dx[i]; ny = y + dy[i]; if(nx == n && ny == n) return true; if(isValid(nx, ny, n, visited, arr, '0')){ q.add(new Coord(nx, ny)); visited[nx][ny] = true; } } } return false; } static void print_res(char a[][], char b[][], int n){ String res = ""; int cnt = 0; for(int i = 1; i <= n; i++){ for(int j = 1; j <= n; j++){ if(a[i][j] != b[i][j]){ cnt++; res += i + " " + j + "\n"; } } } p(cnt + "\n" + res); } public static void process(int test_number)throws IOException { int n = ni(); char grid[][] = new char[n + 1][], aux[][] = new char[n + 1][n + 1]; for(int i = 1; i <= n; i++){ grid[i] = ("#"+nln()).toCharArray(); for(int j = 1; j <= n; j++) aux[i][j] = grid[i][j]; } grid[n - 1][n] = '0'; grid[n][n - 1] = '0'; if(!bfs1(grid, n) && !bfs0(grid, n)){ print_res(grid, aux,n); return ; } for(int i = 0; i <= 3; i++){ int mask = i; char bit1 = Integer.toString((int)(mask & 1)).charAt(0); mask /= 2; char bit2 = Integer.toString((int)(mask & 1)).charAt(0); //trace(bit1, bit2); grid[1][2] = bit1; grid[2][1] = bit2; if(!bfs1(grid, n) && !bfs0(grid, n)){ print_res(grid, aux, n); return ; } grid[1][2] = aux[1][2]; grid[2][1] = aux[2][1]; grid[1][2] = bit1; grid[n][n - 1] = bit2; if(!bfs1(grid, n) && !bfs0(grid, n)){ print_res(grid, aux, n); return ; } grid[1][2] = aux[1][2]; grid[n][n - 1] = aux[n][n - 1]; grid[1][2] = bit1; grid[n - 1][n] = bit2; if(!bfs1(grid, n) && !bfs0(grid, n)){ print_res(grid, aux, n); return ; } grid[1][2] = aux[1][2]; grid[n - 1][n] = aux[n - 1][n]; grid[2][1] = bit1; grid[n][n - 1] = bit2; if(!bfs1(grid, n) && !bfs0(grid, n)){ print_res(grid, aux, n); return ; } grid[2][1] = aux[2][1]; grid[n][n - 1] = aux[n][n - 1]; grid[2][1] = bit1; grid[n - 1][n] = bit2; if(!bfs1(grid, n) && !bfs0(grid, n)){ print_res(grid, aux, n); return ; } grid[2][1] = aux[2][1]; grid[n - 1][n] = aux[n - 1][n]; grid[n][n - 1] = bit1; grid[n - 1][n] = bit2; if(!bfs1(grid, n) && !bfs0(grid, n)){ print_res(grid, aux, n); return ; } grid[n][n - 1] = aux[n][n - 1]; grid[n - 1][n] = aux[n - 1][n]; } } static int dx[] = {1, 0, -1 , 0}, dy[] = {0, 1, 0, -1}; static final long mod = (long)1e9+7l; static FastReader sc; static PrintWriter out; public static void main(String[]args)throws IOException { out = new PrintWriter(System.out); sc = new FastReader(); long s = System.currentTimeMillis(); int t = 1; t = ni(); for(int i = 1; i <= t; i++) process(i); out.flush(); System.err.println(System.currentTimeMillis()-s+"ms"); } static void trace(Object... o){ System.err.println(Arrays.deepToString(o)); }; static void pn(Object o){ out.println(o); } static void p(Object o){ out.print(o); } static int ni()throws IOException{ return Integer.parseInt(sc.next()); } static long nl()throws IOException{ return Long.parseLong(sc.next()); } static double nd()throws IOException{ return Double.parseDouble(sc.next()); } static String nln()throws IOException{ return sc.nextLine(); } static long gcd(long a, long b)throws IOException{ return (b==0)?a:gcd(b,a%b);} static int gcd(int a, int b)throws IOException{ return (b==0)?a:gcd(b,a%b); } static int bit(long n)throws IOException{ return (n==0)?0:(1+bit(n&(n-1))); } static class FastReader{ BufferedReader br; StringTokenizer st; public FastReader(){ br = new BufferedReader(new InputStreamReader(System.in)); } String next(){ while (st == null || !st.hasMoreElements()){ try{ st = new StringTokenizer(br.readLine()); } catch (IOException e){ e.printStackTrace(); } } return st.nextToken(); } String nextLine(){ String str = ""; try{ str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["3\n4\nS010\n0001\n1000\n111F\n3\nS10\n101\n01F\n5\nS0101\n00000\n01111\n11111\n0001F"]
1 second
["1\n3 4\n2\n1 2\n2 1\n0"]
NoteFor the first test case, after inverting the cell, we get the following grid:S01000011001111F
Java 11
standard input
[ "constructive algorithms", "implementation" ]
be60cca56505e4b04d24c9b4990553c7
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 50$$$). Description of the test cases follows. The first line of each test case contains one integers $$$n$$$ ($$$3 \le n \le 200$$$). The following $$$n$$$ lines of each test case contain the binary grid, square ($$$1, 1$$$) being colored in 'S' and square ($$$n, n$$$) being colored in 'F'. The sum of values of $$$n$$$ doesn't exceed $$$200$$$.
1,100
For each test case output on the first line an integer $$$c$$$ ($$$0 \le c \le 2$$$)  — the number of inverted cells. In $$$i$$$-th of the following $$$c$$$ lines, print the coordinates of the $$$i$$$-th cell you inverted. You may not invert the same cell twice. Note that you cannot invert cells $$$(1, 1)$$$ and $$$(n, n)$$$.
standard output
PASSED
bf5f08fc63253858feca7cf8cbe0ba3c
train_003.jsonl
1603011900
Pink Floyd are pulling a prank on Roger Waters. They know he doesn't like walls, he wants to be able to walk freely, so they are blocking him from exiting his room which can be seen as a grid.Roger Waters has a square grid of size $$$n\times n$$$ and he wants to traverse his grid from the upper left ($$$1,1$$$) corner to the lower right corner ($$$n,n$$$). Waters can move from a square to any other square adjacent by a side, as long as he is still in the grid. Also except for the cells ($$$1,1$$$) and ($$$n,n$$$) every cell has a value $$$0$$$ or $$$1$$$ in it.Before starting his traversal he will pick either a $$$0$$$ or a $$$1$$$ and will be able to only go to cells values in which are equal to the digit he chose. The starting and finishing cells ($$$1,1$$$) and ($$$n,n$$$) are exempt from this rule, he may go through them regardless of picked digit. Because of this the cell ($$$1,1$$$) takes value the letter 'S' and the cell ($$$n,n$$$) takes value the letter 'F'.For example, in the first example test case, he can go from ($$$1, 1$$$) to ($$$n, n$$$) by using the zeroes on this path: ($$$1, 1$$$), ($$$2, 1$$$), ($$$2, 2$$$), ($$$2, 3$$$), ($$$3, 3$$$), ($$$3, 4$$$), ($$$4, 4$$$)The rest of the band (Pink Floyd) wants Waters to not be able to do his traversal, so while he is not looking they will invert at most two cells in the grid (from $$$0$$$ to $$$1$$$ or vice versa). They are afraid they will not be quick enough and asked for your help in choosing the cells. Note that you cannot invert cells $$$(1, 1)$$$ and $$$(n, n)$$$.We can show that there always exists a solution for the given constraints.Also note that Waters will pick his digit of the traversal after the band has changed his grid, so he must not be able to reach ($$$n,n$$$) no matter what digit he picks.
256 megabytes
import java.util.*; import java.util.Scanner; import java.io.*; import javax.lang.model.util.ElementScanner6; import static java.lang.System.out; public class B1421 { public static void main(String args[]) { FastReader in=new FastReader(); PrintWriter pr = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); int tc=1; tc=in.nextInt(); while(tc-->0) { int n=in.nextInt(); char arr[][]=new char[n][n]; for(int i=0;i<+n;i++) { String S=in.nextLine(); arr[i]=S.toCharArray(); } int xtop=((arr[1][0]-'0')^(arr[0][1]-'0')); int xbot=((arr[n-2][n-1]-'0')^(arr[n-1][n-2]-'0')); if(xtop==xbot) { if(xtop==0) { if(arr[1][0]==arr[n-1][n-2]) { pr.println(2); pr.println(1+" "+2); pr.println(2+" "+1); } else pr.println(0); } else { pr.println(2); if(arr[1][0]=='1') { pr.println(2+" "+1); } else pr.println(1+" "+2); if(arr[n-1][n-2]=='0') { pr.println(n+" "+(n-1)); } else pr.println(n-1+" "+n); } } else { pr.println(1); if(xtop==1) { if(((arr[1][0]-'0')^(arr[n-2][n-1]-'0'))==0) { pr.println(2+" "+1); } else pr.println(1+" "+2); } else { if(((arr[1][0]-'0')^(arr[n-2][n-1]-'0'))==0) { pr.println((n-1)+" "+(n)); } else pr.println(n+" "+(n-1)); } } } pr.flush(); } static void sort(long[] a) { ArrayList<Long> l = new ArrayList<>(); for (long i : a) l.add(i); Collections.sort(l); for (int i = 0; i < a.length; i++) a[i] = l.get(i); } static void sort(int[] a) { ArrayList<Integer> l = new ArrayList<>(); for (int i : a) l.add(i); Collections.sort(l); for (int i = 0; i < a.length; i++) a[i] = l.get(i); } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["3\n4\nS010\n0001\n1000\n111F\n3\nS10\n101\n01F\n5\nS0101\n00000\n01111\n11111\n0001F"]
1 second
["1\n3 4\n2\n1 2\n2 1\n0"]
NoteFor the first test case, after inverting the cell, we get the following grid:S01000011001111F
Java 11
standard input
[ "constructive algorithms", "implementation" ]
be60cca56505e4b04d24c9b4990553c7
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 50$$$). Description of the test cases follows. The first line of each test case contains one integers $$$n$$$ ($$$3 \le n \le 200$$$). The following $$$n$$$ lines of each test case contain the binary grid, square ($$$1, 1$$$) being colored in 'S' and square ($$$n, n$$$) being colored in 'F'. The sum of values of $$$n$$$ doesn't exceed $$$200$$$.
1,100
For each test case output on the first line an integer $$$c$$$ ($$$0 \le c \le 2$$$)  — the number of inverted cells. In $$$i$$$-th of the following $$$c$$$ lines, print the coordinates of the $$$i$$$-th cell you inverted. You may not invert the same cell twice. Note that you cannot invert cells $$$(1, 1)$$$ and $$$(n, n)$$$.
standard output
PASSED
1ac41fa02eb7504f88823ae19a9ccb92
train_003.jsonl
1603011900
Pink Floyd are pulling a prank on Roger Waters. They know he doesn't like walls, he wants to be able to walk freely, so they are blocking him from exiting his room which can be seen as a grid.Roger Waters has a square grid of size $$$n\times n$$$ and he wants to traverse his grid from the upper left ($$$1,1$$$) corner to the lower right corner ($$$n,n$$$). Waters can move from a square to any other square adjacent by a side, as long as he is still in the grid. Also except for the cells ($$$1,1$$$) and ($$$n,n$$$) every cell has a value $$$0$$$ or $$$1$$$ in it.Before starting his traversal he will pick either a $$$0$$$ or a $$$1$$$ and will be able to only go to cells values in which are equal to the digit he chose. The starting and finishing cells ($$$1,1$$$) and ($$$n,n$$$) are exempt from this rule, he may go through them regardless of picked digit. Because of this the cell ($$$1,1$$$) takes value the letter 'S' and the cell ($$$n,n$$$) takes value the letter 'F'.For example, in the first example test case, he can go from ($$$1, 1$$$) to ($$$n, n$$$) by using the zeroes on this path: ($$$1, 1$$$), ($$$2, 1$$$), ($$$2, 2$$$), ($$$2, 3$$$), ($$$3, 3$$$), ($$$3, 4$$$), ($$$4, 4$$$)The rest of the band (Pink Floyd) wants Waters to not be able to do his traversal, so while he is not looking they will invert at most two cells in the grid (from $$$0$$$ to $$$1$$$ or vice versa). They are afraid they will not be quick enough and asked for your help in choosing the cells. Note that you cannot invert cells $$$(1, 1)$$$ and $$$(n, n)$$$.We can show that there always exists a solution for the given constraints.Also note that Waters will pick his digit of the traversal after the band has changed his grid, so he must not be able to reach ($$$n,n$$$) no matter what digit he picks.
256 megabytes
import java.util.Scanner; public class solution { public static void main(String[] args) { int testNum, gridSize; String temp; char[][] grid = new char[200][200]; Scanner scanner = new Scanner(System.in); testNum = scanner.nextInt(); for (int i = 0; i < testNum; i++) { int[][] store = new int[4][30]; int count = 0, recount = 0; gridSize = scanner.nextInt(); for (int j = 0; j < gridSize; j++) { temp = scanner.next(); for (int k = 0; k < gridSize; k++) { grid[j][k] = temp.charAt(k); } } if (grid[1][0] == '0') { store[0][count] = 1; store[1][count] = 0; count++; } else { store[2][recount] = 1; store[3][recount] = 0; recount++; } if (grid[0][1] == '0') { store[0][count] = 0; store[1][count] = 1; count++; } else { store[2][recount] = 0; store[3][recount] = 1; recount++; } if (grid[0][2] == '1') { store[0][count] = 0; store[1][count] = 2; count++; } else { store[2][recount] = 0; store[3][recount] = 2; recount++; } if (grid[1][1] == '1') { store[0][count] = 1; store[1][count] = 1; count++; } else { store[2][recount] = 1; store[3][recount] = 1; recount++; } if (grid[2][0] == '1') { store[0][count] = 2; store[1][count] = 0; count++; } else { store[2][recount] = 2; store[3][recount] = 0; recount++; } if (count > 2) { System.out.println(recount); for (int j = 0; j < recount; j++) { System.out.println((store[2][j] + 1) + " " + (store[3][j] + 1)); } } else { System.out.println(count); for (int j = 0; j < count; j++) { System.out.println((store[0][j] + 1) + " " + (store[1][j] + 1)); } } //System.out.println(); } } }
Java
["3\n4\nS010\n0001\n1000\n111F\n3\nS10\n101\n01F\n5\nS0101\n00000\n01111\n11111\n0001F"]
1 second
["1\n3 4\n2\n1 2\n2 1\n0"]
NoteFor the first test case, after inverting the cell, we get the following grid:S01000011001111F
Java 11
standard input
[ "constructive algorithms", "implementation" ]
be60cca56505e4b04d24c9b4990553c7
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 50$$$). Description of the test cases follows. The first line of each test case contains one integers $$$n$$$ ($$$3 \le n \le 200$$$). The following $$$n$$$ lines of each test case contain the binary grid, square ($$$1, 1$$$) being colored in 'S' and square ($$$n, n$$$) being colored in 'F'. The sum of values of $$$n$$$ doesn't exceed $$$200$$$.
1,100
For each test case output on the first line an integer $$$c$$$ ($$$0 \le c \le 2$$$)  — the number of inverted cells. In $$$i$$$-th of the following $$$c$$$ lines, print the coordinates of the $$$i$$$-th cell you inverted. You may not invert the same cell twice. Note that you cannot invert cells $$$(1, 1)$$$ and $$$(n, n)$$$.
standard output
PASSED
0cd6e57aa42f7004888262b9249d99e7
train_003.jsonl
1603011900
Pink Floyd are pulling a prank on Roger Waters. They know he doesn't like walls, he wants to be able to walk freely, so they are blocking him from exiting his room which can be seen as a grid.Roger Waters has a square grid of size $$$n\times n$$$ and he wants to traverse his grid from the upper left ($$$1,1$$$) corner to the lower right corner ($$$n,n$$$). Waters can move from a square to any other square adjacent by a side, as long as he is still in the grid. Also except for the cells ($$$1,1$$$) and ($$$n,n$$$) every cell has a value $$$0$$$ or $$$1$$$ in it.Before starting his traversal he will pick either a $$$0$$$ or a $$$1$$$ and will be able to only go to cells values in which are equal to the digit he chose. The starting and finishing cells ($$$1,1$$$) and ($$$n,n$$$) are exempt from this rule, he may go through them regardless of picked digit. Because of this the cell ($$$1,1$$$) takes value the letter 'S' and the cell ($$$n,n$$$) takes value the letter 'F'.For example, in the first example test case, he can go from ($$$1, 1$$$) to ($$$n, n$$$) by using the zeroes on this path: ($$$1, 1$$$), ($$$2, 1$$$), ($$$2, 2$$$), ($$$2, 3$$$), ($$$3, 3$$$), ($$$3, 4$$$), ($$$4, 4$$$)The rest of the band (Pink Floyd) wants Waters to not be able to do his traversal, so while he is not looking they will invert at most two cells in the grid (from $$$0$$$ to $$$1$$$ or vice versa). They are afraid they will not be quick enough and asked for your help in choosing the cells. Note that you cannot invert cells $$$(1, 1)$$$ and $$$(n, n)$$$.We can show that there always exists a solution for the given constraints.Also note that Waters will pick his digit of the traversal after the band has changed his grid, so he must not be able to reach ($$$n,n$$$) no matter what digit he picks.
256 megabytes
//"We have two lives, and the second begins when we realize we only have one." — Confucius import java.io.BufferedReader; import java.util.*; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.Random; import java.util.StringTokenizer; public class C{ public static void main(String[] args) { FastScanner fs = new FastScanner(); int t = fs.nextInt(); for(int tt=0;tt<t;tt++) { int n= fs.nextInt(); char[][] arr = new char[n][n]; for(int i=0;i<n;i++) { String str = fs.next(); int index = 0; for(int j=0;j<n;j++) { arr[i][j]=str.charAt(index++); } } /*for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { System.out.print(arr[i][j]+" "); } System.out.println(); }*/ int ans =0; if(arr[0][1]!=arr[1][0] && arr[n-1][n-2]!=arr[n-2][n-1]) { System.out.println(2); if(arr[0][1]=='1') { System.out.println(1+" "+2); if(arr[n-2][n-1]=='0') { System.out.println(n-1 +" "+n); } else { System.out.println(n+" "+(n-1)); } } else { System.out.println(2+" "+1); if(arr[n-2][n-1]=='0') { System.out.println(n-1 +" "+n); } else { System.out.println(n+" "+(n-1)); } } } else if(arr[0][1]==arr[1][0]) { int res=0; boolean flag1 =false; boolean flag2=false; char c=arr[0][1]; if(arr[n-1][n-2]==c) { flag1=true; res++; } if(arr[n-2][n-1]==c) { flag2=true; res++; } System.out.println(res); if(flag1==true) { System.out.println(n+" "+(n-1)); } if(flag2==true) { System.out.println(n-1+" "+n); } } else { int res=0; boolean flag1 =false; boolean flag2=false; char c=arr[n-1][n-2]; if(arr[0][1]==c) { flag1=true; res++; } if(arr[1][0]==c) { flag2=true; res++; } System.out.println(res); if(flag1==true) { System.out.println(1+" "+2); } if(flag2==true) { System.out.println(2+" "+1); } } } } static class FastScanner { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readArray(int n) { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } long nextLong() { return Long.parseLong(next()); } } }
Java
["3\n4\nS010\n0001\n1000\n111F\n3\nS10\n101\n01F\n5\nS0101\n00000\n01111\n11111\n0001F"]
1 second
["1\n3 4\n2\n1 2\n2 1\n0"]
NoteFor the first test case, after inverting the cell, we get the following grid:S01000011001111F
Java 11
standard input
[ "constructive algorithms", "implementation" ]
be60cca56505e4b04d24c9b4990553c7
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 50$$$). Description of the test cases follows. The first line of each test case contains one integers $$$n$$$ ($$$3 \le n \le 200$$$). The following $$$n$$$ lines of each test case contain the binary grid, square ($$$1, 1$$$) being colored in 'S' and square ($$$n, n$$$) being colored in 'F'. The sum of values of $$$n$$$ doesn't exceed $$$200$$$.
1,100
For each test case output on the first line an integer $$$c$$$ ($$$0 \le c \le 2$$$)  — the number of inverted cells. In $$$i$$$-th of the following $$$c$$$ lines, print the coordinates of the $$$i$$$-th cell you inverted. You may not invert the same cell twice. Note that you cannot invert cells $$$(1, 1)$$$ and $$$(n, n)$$$.
standard output
PASSED
08196a2d6c44b1b6e6e7557382fff9e9
train_003.jsonl
1603011900
Pink Floyd are pulling a prank on Roger Waters. They know he doesn't like walls, he wants to be able to walk freely, so they are blocking him from exiting his room which can be seen as a grid.Roger Waters has a square grid of size $$$n\times n$$$ and he wants to traverse his grid from the upper left ($$$1,1$$$) corner to the lower right corner ($$$n,n$$$). Waters can move from a square to any other square adjacent by a side, as long as he is still in the grid. Also except for the cells ($$$1,1$$$) and ($$$n,n$$$) every cell has a value $$$0$$$ or $$$1$$$ in it.Before starting his traversal he will pick either a $$$0$$$ or a $$$1$$$ and will be able to only go to cells values in which are equal to the digit he chose. The starting and finishing cells ($$$1,1$$$) and ($$$n,n$$$) are exempt from this rule, he may go through them regardless of picked digit. Because of this the cell ($$$1,1$$$) takes value the letter 'S' and the cell ($$$n,n$$$) takes value the letter 'F'.For example, in the first example test case, he can go from ($$$1, 1$$$) to ($$$n, n$$$) by using the zeroes on this path: ($$$1, 1$$$), ($$$2, 1$$$), ($$$2, 2$$$), ($$$2, 3$$$), ($$$3, 3$$$), ($$$3, 4$$$), ($$$4, 4$$$)The rest of the band (Pink Floyd) wants Waters to not be able to do his traversal, so while he is not looking they will invert at most two cells in the grid (from $$$0$$$ to $$$1$$$ or vice versa). They are afraid they will not be quick enough and asked for your help in choosing the cells. Note that you cannot invert cells $$$(1, 1)$$$ and $$$(n, n)$$$.We can show that there always exists a solution for the given constraints.Also note that Waters will pick his digit of the traversal after the band has changed his grid, so he must not be able to reach ($$$n,n$$$) no matter what digit he picks.
256 megabytes
import java.lang.reflect.Array; import java.util.*; public class Solution { public static boolean check(String x,String y,String[][] s){ int n=s.length-1; int a=s[0][1].equals(y)?1:0; int b=s[1][0].equals(y)?1:0; int c=s[n][n-1].equals(x)?1:0; int d=s[n-1][n].equals(x)?1:0; int res=a+b+c+d; if(res<=2) { System.out.println(res); if(a==1) System.out.println("1 2"); if(b==1) System.out.println("2 1"); if(c==1) System.out.println((n+1)+" "+n); if(d==1) System.out.println(n+" "+(n+1)); return true; } return false; } public static void main(String args[]){ Scanner sc= new Scanner(System.in); int t = sc.nextInt(); while(t-->0) { int n = sc.nextInt(); String[][] array = new String[n][n]; sc.nextLine(); for (int i = 0; i < n; i++) { array[i] = sc.nextLine().split(""); } if(! check("0","1",array)) check("1","0",array); } } }
Java
["3\n4\nS010\n0001\n1000\n111F\n3\nS10\n101\n01F\n5\nS0101\n00000\n01111\n11111\n0001F"]
1 second
["1\n3 4\n2\n1 2\n2 1\n0"]
NoteFor the first test case, after inverting the cell, we get the following grid:S01000011001111F
Java 11
standard input
[ "constructive algorithms", "implementation" ]
be60cca56505e4b04d24c9b4990553c7
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 50$$$). Description of the test cases follows. The first line of each test case contains one integers $$$n$$$ ($$$3 \le n \le 200$$$). The following $$$n$$$ lines of each test case contain the binary grid, square ($$$1, 1$$$) being colored in 'S' and square ($$$n, n$$$) being colored in 'F'. The sum of values of $$$n$$$ doesn't exceed $$$200$$$.
1,100
For each test case output on the first line an integer $$$c$$$ ($$$0 \le c \le 2$$$)  — the number of inverted cells. In $$$i$$$-th of the following $$$c$$$ lines, print the coordinates of the $$$i$$$-th cell you inverted. You may not invert the same cell twice. Note that you cannot invert cells $$$(1, 1)$$$ and $$$(n, n)$$$.
standard output
PASSED
1b1481e1f08c29337061afe7ee71f2e7
train_003.jsonl
1379172600
Mad scientist Mike entertains himself by arranging rows of dominoes. He doesn't need dominoes, though: he uses rectangular magnets instead. Each magnet has two poles, positive (a "plus") and negative (a "minus"). If two magnets are put together at a close distance, then the like poles will repel each other and the opposite poles will attract each other.Mike starts by laying one magnet horizontally on the table. During each following step Mike adds one more magnet horizontally to the right end of the row. Depending on how Mike puts the magnet on the table, it is either attracted to the previous one (forming a group of multiple magnets linked together) or repelled by it (then Mike lays this magnet at some distance to the right from the previous one). We assume that a sole magnet not linked to others forms a group of its own. Mike arranged multiple magnets in a row. Determine the number of groups that the magnets formed.
256 megabytes
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner in=new Scanner(System.in); int n=in.nextInt(); int a,b=0,c=0; for(int i=0;i<n;i++) { a=in.nextInt(); if(a!=b)c++; b=a; } System.out.println(c); } }
Java
["6\n10\n10\n10\n01\n10\n10", "4\n01\n01\n10\n10"]
1 second
["3", "2"]
NoteThe first testcase corresponds to the figure. The testcase has three groups consisting of three, one and two magnets.The second testcase has two groups, each consisting of two magnets.
Java 11
standard input
[ "implementation" ]
6c52df7ea24671102e4c0eee19dc6bba
The first line of the input contains an integer n (1 ≤ n ≤ 100000) — the number of magnets. Then n lines follow. The i-th line (1 ≤ i ≤ n) contains either characters "01", if Mike put the i-th magnet in the "plus-minus" position, or characters "10", if Mike put the magnet in the "minus-plus" position.
800
On the single line of the output print the number of groups of magnets.
standard output
PASSED
df4c14a7a6425ec55b0e5dfd41a26c6c
train_003.jsonl
1379172600
Mad scientist Mike entertains himself by arranging rows of dominoes. He doesn't need dominoes, though: he uses rectangular magnets instead. Each magnet has two poles, positive (a "plus") and negative (a "minus"). If two magnets are put together at a close distance, then the like poles will repel each other and the opposite poles will attract each other.Mike starts by laying one magnet horizontally on the table. During each following step Mike adds one more magnet horizontally to the right end of the row. Depending on how Mike puts the magnet on the table, it is either attracted to the previous one (forming a group of multiple magnets linked together) or repelled by it (then Mike lays this magnet at some distance to the right from the previous one). We assume that a sole magnet not linked to others forms a group of its own. Mike arranged multiple magnets in a row. Determine the number of groups that the magnets formed.
256 megabytes
import java.util.*; public class magnet{ public static void main(String args[]){ Scanner sc=new Scanner(System.in); int n=sc.nextInt(); int c=1,i=0; int a[]=new int[10000000]; for( i=0;i<n;i++){ a[i]=sc.nextInt(); } for( i=0;i<n-1;i++){ if(a[i]!=a[i+1]){ c++; } } System.out.println(c); }}
Java
["6\n10\n10\n10\n01\n10\n10", "4\n01\n01\n10\n10"]
1 second
["3", "2"]
NoteThe first testcase corresponds to the figure. The testcase has three groups consisting of three, one and two magnets.The second testcase has two groups, each consisting of two magnets.
Java 11
standard input
[ "implementation" ]
6c52df7ea24671102e4c0eee19dc6bba
The first line of the input contains an integer n (1 ≤ n ≤ 100000) — the number of magnets. Then n lines follow. The i-th line (1 ≤ i ≤ n) contains either characters "01", if Mike put the i-th magnet in the "plus-minus" position, or characters "10", if Mike put the magnet in the "minus-plus" position.
800
On the single line of the output print the number of groups of magnets.
standard output
PASSED
2875392a1643b1434bf464222673e462
train_003.jsonl
1379172600
Mad scientist Mike entertains himself by arranging rows of dominoes. He doesn't need dominoes, though: he uses rectangular magnets instead. Each magnet has two poles, positive (a "plus") and negative (a "minus"). If two magnets are put together at a close distance, then the like poles will repel each other and the opposite poles will attract each other.Mike starts by laying one magnet horizontally on the table. During each following step Mike adds one more magnet horizontally to the right end of the row. Depending on how Mike puts the magnet on the table, it is either attracted to the previous one (forming a group of multiple magnets linked together) or repelled by it (then Mike lays this magnet at some distance to the right from the previous one). We assume that a sole magnet not linked to others forms a group of its own. Mike arranged multiple magnets in a row. Determine the number of groups that the magnets formed.
256 megabytes
import java.util.Scanner; public class Abhi { public static void main(String[] args) { Scanner s = new Scanner(System.in); int n = s.nextInt(); int a[] = new int[n]; int group = 1; for(int i=0; i<n; i++) { a[i] = s.nextInt(); } for(int i=0; i<n-1; i++) { if(a[i] != a[i+1]) { group++; } } System.out.println(group); } }
Java
["6\n10\n10\n10\n01\n10\n10", "4\n01\n01\n10\n10"]
1 second
["3", "2"]
NoteThe first testcase corresponds to the figure. The testcase has three groups consisting of three, one and two magnets.The second testcase has two groups, each consisting of two magnets.
Java 11
standard input
[ "implementation" ]
6c52df7ea24671102e4c0eee19dc6bba
The first line of the input contains an integer n (1 ≤ n ≤ 100000) — the number of magnets. Then n lines follow. The i-th line (1 ≤ i ≤ n) contains either characters "01", if Mike put the i-th magnet in the "plus-minus" position, or characters "10", if Mike put the magnet in the "minus-plus" position.
800
On the single line of the output print the number of groups of magnets.
standard output
PASSED
52b4145f9cee273d157cf0be4552f65d
train_003.jsonl
1379172600
Mad scientist Mike entertains himself by arranging rows of dominoes. He doesn't need dominoes, though: he uses rectangular magnets instead. Each magnet has two poles, positive (a "plus") and negative (a "minus"). If two magnets are put together at a close distance, then the like poles will repel each other and the opposite poles will attract each other.Mike starts by laying one magnet horizontally on the table. During each following step Mike adds one more magnet horizontally to the right end of the row. Depending on how Mike puts the magnet on the table, it is either attracted to the previous one (forming a group of multiple magnets linked together) or repelled by it (then Mike lays this magnet at some distance to the right from the previous one). We assume that a sole magnet not linked to others forms a group of its own. Mike arranged multiple magnets in a row. Determine the number of groups that the magnets formed.
256 megabytes
import java.util.Scanner; public class Magnets { public static void main (String []args){ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); String [] arr = new String [n]; int c =0; boolean changed = true; for (int i=0;i<n;i++) arr[i]=sc.next(); for (int i=0;i<n;i++){ if (arr[i].compareTo("01")==0&&((!changed)||i==0)){ c++; changed = true; } if(changed&&!arr[i].equals("01") ){ c++; changed = false; } } System.out.println(c); } } /* * * boolean changed = true; * int c =0; * * * * */
Java
["6\n10\n10\n10\n01\n10\n10", "4\n01\n01\n10\n10"]
1 second
["3", "2"]
NoteThe first testcase corresponds to the figure. The testcase has three groups consisting of three, one and two magnets.The second testcase has two groups, each consisting of two magnets.
Java 11
standard input
[ "implementation" ]
6c52df7ea24671102e4c0eee19dc6bba
The first line of the input contains an integer n (1 ≤ n ≤ 100000) — the number of magnets. Then n lines follow. The i-th line (1 ≤ i ≤ n) contains either characters "01", if Mike put the i-th magnet in the "plus-minus" position, or characters "10", if Mike put the magnet in the "minus-plus" position.
800
On the single line of the output print the number of groups of magnets.
standard output
PASSED
650e1c7481c12a50ec85e1af618d3929
train_003.jsonl
1379172600
Mad scientist Mike entertains himself by arranging rows of dominoes. He doesn't need dominoes, though: he uses rectangular magnets instead. Each magnet has two poles, positive (a "plus") and negative (a "minus"). If two magnets are put together at a close distance, then the like poles will repel each other and the opposite poles will attract each other.Mike starts by laying one magnet horizontally on the table. During each following step Mike adds one more magnet horizontally to the right end of the row. Depending on how Mike puts the magnet on the table, it is either attracted to the previous one (forming a group of multiple magnets linked together) or repelled by it (then Mike lays this magnet at some distance to the right from the previous one). We assume that a sole magnet not linked to others forms a group of its own. Mike arranged multiple magnets in a row. Determine the number of groups that the magnets formed.
256 megabytes
import java.util.Scanner; public class Main { public static void main(String[] args) { int n,result = 1; Scanner scanner = new Scanner(System.in); n = scanner.nextInt(); char m[] = new char[n]; for (int i = 0; i < m.length; i++) { m[i] = (char)scanner.nextInt(); } for (int i = 0; i < m.length - 1; i++) { if(m[i+1] != m[i]) result += 1; } System.out.println(result); } }
Java
["6\n10\n10\n10\n01\n10\n10", "4\n01\n01\n10\n10"]
1 second
["3", "2"]
NoteThe first testcase corresponds to the figure. The testcase has three groups consisting of three, one and two magnets.The second testcase has two groups, each consisting of two magnets.
Java 11
standard input
[ "implementation" ]
6c52df7ea24671102e4c0eee19dc6bba
The first line of the input contains an integer n (1 ≤ n ≤ 100000) — the number of magnets. Then n lines follow. The i-th line (1 ≤ i ≤ n) contains either characters "01", if Mike put the i-th magnet in the "plus-minus" position, or characters "10", if Mike put the magnet in the "minus-plus" position.
800
On the single line of the output print the number of groups of magnets.
standard output
PASSED
3457df61dff1caaf9f1dca639c12b628
train_003.jsonl
1379172600
Mad scientist Mike entertains himself by arranging rows of dominoes. He doesn't need dominoes, though: he uses rectangular magnets instead. Each magnet has two poles, positive (a "plus") and negative (a "minus"). If two magnets are put together at a close distance, then the like poles will repel each other and the opposite poles will attract each other.Mike starts by laying one magnet horizontally on the table. During each following step Mike adds one more magnet horizontally to the right end of the row. Depending on how Mike puts the magnet on the table, it is either attracted to the previous one (forming a group of multiple magnets linked together) or repelled by it (then Mike lays this magnet at some distance to the right from the previous one). We assume that a sole magnet not linked to others forms a group of its own. Mike arranged multiple magnets in a row. Determine the number of groups that the magnets formed.
256 megabytes
import java.util.Scanner; public class Main { public static void main(String[] args) { int n,result = 1; Scanner scanner = new Scanner(System.in); n = scanner.nextInt(); char m[] = new char[n]; for (int i = 0; i < m.length; i++) { m[i] = (char)scanner.nextInt(); } for (int i = 0; i < m.length - 1; i++) { if(m[i+1] != m[i]) result += 1; } System.out.println(result); } }
Java
["6\n10\n10\n10\n01\n10\n10", "4\n01\n01\n10\n10"]
1 second
["3", "2"]
NoteThe first testcase corresponds to the figure. The testcase has three groups consisting of three, one and two magnets.The second testcase has two groups, each consisting of two magnets.
Java 11
standard input
[ "implementation" ]
6c52df7ea24671102e4c0eee19dc6bba
The first line of the input contains an integer n (1 ≤ n ≤ 100000) — the number of magnets. Then n lines follow. The i-th line (1 ≤ i ≤ n) contains either characters "01", if Mike put the i-th magnet in the "plus-minus" position, or characters "10", if Mike put the magnet in the "minus-plus" position.
800
On the single line of the output print the number of groups of magnets.
standard output
PASSED
0a3a3e14823c97eae2b1bf8a8ce6d88f
train_003.jsonl
1379172600
Mad scientist Mike entertains himself by arranging rows of dominoes. He doesn't need dominoes, though: he uses rectangular magnets instead. Each magnet has two poles, positive (a "plus") and negative (a "minus"). If two magnets are put together at a close distance, then the like poles will repel each other and the opposite poles will attract each other.Mike starts by laying one magnet horizontally on the table. During each following step Mike adds one more magnet horizontally to the right end of the row. Depending on how Mike puts the magnet on the table, it is either attracted to the previous one (forming a group of multiple magnets linked together) or repelled by it (then Mike lays this magnet at some distance to the right from the previous one). We assume that a sole magnet not linked to others forms a group of its own. Mike arranged multiple magnets in a row. Determine the number of groups that the magnets formed.
256 megabytes
import java.util.*; public class ClassA { public static void main(String args[]){ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int count = 0; int b = 0; for(int i=0; i<n; i++){ int a = sc.nextInt(); if(a != b) count++; b = a; } System.out.println(count); } }
Java
["6\n10\n10\n10\n01\n10\n10", "4\n01\n01\n10\n10"]
1 second
["3", "2"]
NoteThe first testcase corresponds to the figure. The testcase has three groups consisting of three, one and two magnets.The second testcase has two groups, each consisting of two magnets.
Java 11
standard input
[ "implementation" ]
6c52df7ea24671102e4c0eee19dc6bba
The first line of the input contains an integer n (1 ≤ n ≤ 100000) — the number of magnets. Then n lines follow. The i-th line (1 ≤ i ≤ n) contains either characters "01", if Mike put the i-th magnet in the "plus-minus" position, or characters "10", if Mike put the magnet in the "minus-plus" position.
800
On the single line of the output print the number of groups of magnets.
standard output
PASSED
60b26ba3fe137b10cbd5cd53589509c0
train_003.jsonl
1379172600
Mad scientist Mike entertains himself by arranging rows of dominoes. He doesn't need dominoes, though: he uses rectangular magnets instead. Each magnet has two poles, positive (a "plus") and negative (a "minus"). If two magnets are put together at a close distance, then the like poles will repel each other and the opposite poles will attract each other.Mike starts by laying one magnet horizontally on the table. During each following step Mike adds one more magnet horizontally to the right end of the row. Depending on how Mike puts the magnet on the table, it is either attracted to the previous one (forming a group of multiple magnets linked together) or repelled by it (then Mike lays this magnet at some distance to the right from the previous one). We assume that a sole magnet not linked to others forms a group of its own. Mike arranged multiple magnets in a row. Determine the number of groups that the magnets formed.
256 megabytes
import java.util.Scanner; public class cau344A { public static void main(String[] args) { int n; int temp[] = new int[2]; int result = 1; Scanner scanner = new Scanner(System.in); n = scanner.nextInt(); for (int i = 0; i < n ; i++) { temp[1] = scanner.nextInt(); if (i > 0) { if (temp[1] != temp[0]) { result++; } } temp[0] = temp[1]; } System.out.println(result); } }
Java
["6\n10\n10\n10\n01\n10\n10", "4\n01\n01\n10\n10"]
1 second
["3", "2"]
NoteThe first testcase corresponds to the figure. The testcase has three groups consisting of three, one and two magnets.The second testcase has two groups, each consisting of two magnets.
Java 11
standard input
[ "implementation" ]
6c52df7ea24671102e4c0eee19dc6bba
The first line of the input contains an integer n (1 ≤ n ≤ 100000) — the number of magnets. Then n lines follow. The i-th line (1 ≤ i ≤ n) contains either characters "01", if Mike put the i-th magnet in the "plus-minus" position, or characters "10", if Mike put the magnet in the "minus-plus" position.
800
On the single line of the output print the number of groups of magnets.
standard output
PASSED
5f985a5bd0577bfd19c9e8b550a07ef4
train_003.jsonl
1379172600
Mad scientist Mike entertains himself by arranging rows of dominoes. He doesn't need dominoes, though: he uses rectangular magnets instead. Each magnet has two poles, positive (a "plus") and negative (a "minus"). If two magnets are put together at a close distance, then the like poles will repel each other and the opposite poles will attract each other.Mike starts by laying one magnet horizontally on the table. During each following step Mike adds one more magnet horizontally to the right end of the row. Depending on how Mike puts the magnet on the table, it is either attracted to the previous one (forming a group of multiple magnets linked together) or repelled by it (then Mike lays this magnet at some distance to the right from the previous one). We assume that a sole magnet not linked to others forms a group of its own. Mike arranged multiple magnets in a row. Determine the number of groups that the magnets formed.
256 megabytes
import java.util.Scanner; public class Problem_344A{ public static void main(String[] args) { Scanner S = new Scanner(System.in); int n = S.nextInt(); int groups = 0; String Magnet; char P0 = '3'; char[] Poles; for(int i = 0; i < n; i++){ Magnet = S.next(); groups++; Poles = Magnet.toCharArray(); if(i == 0){ P0 = Poles[1]; continue; } if(Poles[0] != P0) groups--; P0 = Poles[1]; } System.out.print(groups); } }
Java
["6\n10\n10\n10\n01\n10\n10", "4\n01\n01\n10\n10"]
1 second
["3", "2"]
NoteThe first testcase corresponds to the figure. The testcase has three groups consisting of three, one and two magnets.The second testcase has two groups, each consisting of two magnets.
Java 11
standard input
[ "implementation" ]
6c52df7ea24671102e4c0eee19dc6bba
The first line of the input contains an integer n (1 ≤ n ≤ 100000) — the number of magnets. Then n lines follow. The i-th line (1 ≤ i ≤ n) contains either characters "01", if Mike put the i-th magnet in the "plus-minus" position, or characters "10", if Mike put the magnet in the "minus-plus" position.
800
On the single line of the output print the number of groups of magnets.
standard output
PASSED
1801231d661d7efdf536f1552483f944
train_003.jsonl
1379172600
Mad scientist Mike entertains himself by arranging rows of dominoes. He doesn't need dominoes, though: he uses rectangular magnets instead. Each magnet has two poles, positive (a "plus") and negative (a "minus"). If two magnets are put together at a close distance, then the like poles will repel each other and the opposite poles will attract each other.Mike starts by laying one magnet horizontally on the table. During each following step Mike adds one more magnet horizontally to the right end of the row. Depending on how Mike puts the magnet on the table, it is either attracted to the previous one (forming a group of multiple magnets linked together) or repelled by it (then Mike lays this magnet at some distance to the right from the previous one). We assume that a sole magnet not linked to others forms a group of its own. Mike arranged multiple magnets in a row. Determine the number of groups that the magnets formed.
256 megabytes
import java.util.Scanner; public class cau344A { public static void main(String[] args) { int n; int temp[] = new int[2]; int result = 1; Scanner scanner = new Scanner(System.in); do { n = scanner.nextInt(); } while (n<1 || n> 100000); for (int i = 0; i < n ; i++) { temp[1] = scanner.nextInt(); if (i > 0) { if (temp[1] != temp[0]) { result++; } } temp[0] = temp[1]; } System.out.println(result); } }
Java
["6\n10\n10\n10\n01\n10\n10", "4\n01\n01\n10\n10"]
1 second
["3", "2"]
NoteThe first testcase corresponds to the figure. The testcase has three groups consisting of three, one and two magnets.The second testcase has two groups, each consisting of two magnets.
Java 11
standard input
[ "implementation" ]
6c52df7ea24671102e4c0eee19dc6bba
The first line of the input contains an integer n (1 ≤ n ≤ 100000) — the number of magnets. Then n lines follow. The i-th line (1 ≤ i ≤ n) contains either characters "01", if Mike put the i-th magnet in the "plus-minus" position, or characters "10", if Mike put the magnet in the "minus-plus" position.
800
On the single line of the output print the number of groups of magnets.
standard output
PASSED
62553f87e9ac0b5e53c48d1023e3cc93
train_003.jsonl
1379172600
Mad scientist Mike entertains himself by arranging rows of dominoes. He doesn't need dominoes, though: he uses rectangular magnets instead. Each magnet has two poles, positive (a "plus") and negative (a "minus"). If two magnets are put together at a close distance, then the like poles will repel each other and the opposite poles will attract each other.Mike starts by laying one magnet horizontally on the table. During each following step Mike adds one more magnet horizontally to the right end of the row. Depending on how Mike puts the magnet on the table, it is either attracted to the previous one (forming a group of multiple magnets linked together) or repelled by it (then Mike lays this magnet at some distance to the right from the previous one). We assume that a sole magnet not linked to others forms a group of its own. Mike arranged multiple magnets in a row. Determine the number of groups that the magnets formed.
256 megabytes
import java.util.Scanner; public class cau344A { public static void main(String[] args) { int n; int temp[] = new int[2]; int result = 1; Scanner scanner = new Scanner(System.in); do { n = scanner.nextInt(); } while (n<1 || n> 100000); for (int i = 0; i < n ; i++) { temp[1] = scanner.nextInt(); if (i > 0) { if (temp[1] != temp[0]) { result++; } } temp[0] = temp[1]; } System.out.println(result); } }
Java
["6\n10\n10\n10\n01\n10\n10", "4\n01\n01\n10\n10"]
1 second
["3", "2"]
NoteThe first testcase corresponds to the figure. The testcase has three groups consisting of three, one and two magnets.The second testcase has two groups, each consisting of two magnets.
Java 11
standard input
[ "implementation" ]
6c52df7ea24671102e4c0eee19dc6bba
The first line of the input contains an integer n (1 ≤ n ≤ 100000) — the number of magnets. Then n lines follow. The i-th line (1 ≤ i ≤ n) contains either characters "01", if Mike put the i-th magnet in the "plus-minus" position, or characters "10", if Mike put the magnet in the "minus-plus" position.
800
On the single line of the output print the number of groups of magnets.
standard output
PASSED
e059d35a4750813f7735776d4449d584
train_003.jsonl
1379172600
Mad scientist Mike entertains himself by arranging rows of dominoes. He doesn't need dominoes, though: he uses rectangular magnets instead. Each magnet has two poles, positive (a "plus") and negative (a "minus"). If two magnets are put together at a close distance, then the like poles will repel each other and the opposite poles will attract each other.Mike starts by laying one magnet horizontally on the table. During each following step Mike adds one more magnet horizontally to the right end of the row. Depending on how Mike puts the magnet on the table, it is either attracted to the previous one (forming a group of multiple magnets linked together) or repelled by it (then Mike lays this magnet at some distance to the right from the previous one). We assume that a sole magnet not linked to others forms a group of its own. Mike arranged multiple magnets in a row. Determine the number of groups that the magnets formed.
256 megabytes
import java.util.Scanner; public class cau344A { public static void main(String[] args) { int n; int temp[] = new int[2]; boolean flag = true; int result = 1; Scanner scanner = new Scanner(System.in); do { n = scanner.nextInt(); } while (n<1 || n > 100000); for (int i = 0; i < n ; i++) { temp[1] = scanner.nextInt(); if (i > 0) { if (temp[1] != temp[0]) { result++; } } temp[0] = temp[1]; } System.out.println(result); } }
Java
["6\n10\n10\n10\n01\n10\n10", "4\n01\n01\n10\n10"]
1 second
["3", "2"]
NoteThe first testcase corresponds to the figure. The testcase has three groups consisting of three, one and two magnets.The second testcase has two groups, each consisting of two magnets.
Java 11
standard input
[ "implementation" ]
6c52df7ea24671102e4c0eee19dc6bba
The first line of the input contains an integer n (1 ≤ n ≤ 100000) — the number of magnets. Then n lines follow. The i-th line (1 ≤ i ≤ n) contains either characters "01", if Mike put the i-th magnet in the "plus-minus" position, or characters "10", if Mike put the magnet in the "minus-plus" position.
800
On the single line of the output print the number of groups of magnets.
standard output
PASSED
9d3d6ac9d3dc92677358658a359ee7ac
train_003.jsonl
1379172600
Mad scientist Mike entertains himself by arranging rows of dominoes. He doesn't need dominoes, though: he uses rectangular magnets instead. Each magnet has two poles, positive (a "plus") and negative (a "minus"). If two magnets are put together at a close distance, then the like poles will repel each other and the opposite poles will attract each other.Mike starts by laying one magnet horizontally on the table. During each following step Mike adds one more magnet horizontally to the right end of the row. Depending on how Mike puts the magnet on the table, it is either attracted to the previous one (forming a group of multiple magnets linked together) or repelled by it (then Mike lays this magnet at some distance to the right from the previous one). We assume that a sole magnet not linked to others forms a group of its own. Mike arranged multiple magnets in a row. Determine the number of groups that the magnets formed.
256 megabytes
import java.util.Scanner; public class Magnets { static Scanner scanner = new Scanner(System.in); public static void main(String[] args) { int n = scanner.nextInt(); scanner.nextLine(); int output = 1; String s = scanner.nextLine(); for(int i = 1; i < n; i++){ String c = scanner.nextLine(); if(c.charAt(0) == s.charAt(1)){ output++; s = c; }else{ s = c; } } System.out.println(output); } }
Java
["6\n10\n10\n10\n01\n10\n10", "4\n01\n01\n10\n10"]
1 second
["3", "2"]
NoteThe first testcase corresponds to the figure. The testcase has three groups consisting of three, one and two magnets.The second testcase has two groups, each consisting of two magnets.
Java 11
standard input
[ "implementation" ]
6c52df7ea24671102e4c0eee19dc6bba
The first line of the input contains an integer n (1 ≤ n ≤ 100000) — the number of magnets. Then n lines follow. The i-th line (1 ≤ i ≤ n) contains either characters "01", if Mike put the i-th magnet in the "plus-minus" position, or characters "10", if Mike put the magnet in the "minus-plus" position.
800
On the single line of the output print the number of groups of magnets.
standard output
PASSED
6660b04d51089ae3d88ca9e77b0b1338
train_003.jsonl
1379172600
Mad scientist Mike entertains himself by arranging rows of dominoes. He doesn't need dominoes, though: he uses rectangular magnets instead. Each magnet has two poles, positive (a "plus") and negative (a "minus"). If two magnets are put together at a close distance, then the like poles will repel each other and the opposite poles will attract each other.Mike starts by laying one magnet horizontally on the table. During each following step Mike adds one more magnet horizontally to the right end of the row. Depending on how Mike puts the magnet on the table, it is either attracted to the previous one (forming a group of multiple magnets linked together) or repelled by it (then Mike lays this magnet at some distance to the right from the previous one). We assume that a sole magnet not linked to others forms a group of its own. Mike arranged multiple magnets in a row. Determine the number of groups that the magnets formed.
256 megabytes
import java.util.Scanner; public class Magnets { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); scanner.nextLine(); int output = 1; String s = scanner.nextLine(); for(int i = 1; i < n; i++){ String c = scanner.nextLine(); if(c.charAt(0) == s.charAt(1)){ output++; s = c; }else{ s = c; } } System.out.println(output); } }
Java
["6\n10\n10\n10\n01\n10\n10", "4\n01\n01\n10\n10"]
1 second
["3", "2"]
NoteThe first testcase corresponds to the figure. The testcase has three groups consisting of three, one and two magnets.The second testcase has two groups, each consisting of two magnets.
Java 11
standard input
[ "implementation" ]
6c52df7ea24671102e4c0eee19dc6bba
The first line of the input contains an integer n (1 ≤ n ≤ 100000) — the number of magnets. Then n lines follow. The i-th line (1 ≤ i ≤ n) contains either characters "01", if Mike put the i-th magnet in the "plus-minus" position, or characters "10", if Mike put the magnet in the "minus-plus" position.
800
On the single line of the output print the number of groups of magnets.
standard output
PASSED
ae0110d9de90577b925c9d5f68931c19
train_003.jsonl
1379172600
Mad scientist Mike entertains himself by arranging rows of dominoes. He doesn't need dominoes, though: he uses rectangular magnets instead. Each magnet has two poles, positive (a "plus") and negative (a "minus"). If two magnets are put together at a close distance, then the like poles will repel each other and the opposite poles will attract each other.Mike starts by laying one magnet horizontally on the table. During each following step Mike adds one more magnet horizontally to the right end of the row. Depending on how Mike puts the magnet on the table, it is either attracted to the previous one (forming a group of multiple magnets linked together) or repelled by it (then Mike lays this magnet at some distance to the right from the previous one). We assume that a sole magnet not linked to others forms a group of its own. Mike arranged multiple magnets in a row. Determine the number of groups that the magnets formed.
256 megabytes
import java .util.Scanner; public class HelloWorld{ public static void main(String[] args) { Scanner sc =new Scanner(System.in); int n=sc.nextInt(); int []arr=new int[n]; for(int i=0;i<n;i++){ arr[i]=sc.nextInt(); } int count=1; for(int i=0;i<arr.length-1;i++){ if(arr[i]!=arr[i+1]){ count++; } } System.out.println(count); } }
Java
["6\n10\n10\n10\n01\n10\n10", "4\n01\n01\n10\n10"]
1 second
["3", "2"]
NoteThe first testcase corresponds to the figure. The testcase has three groups consisting of three, one and two magnets.The second testcase has two groups, each consisting of two magnets.
Java 11
standard input
[ "implementation" ]
6c52df7ea24671102e4c0eee19dc6bba
The first line of the input contains an integer n (1 ≤ n ≤ 100000) — the number of magnets. Then n lines follow. The i-th line (1 ≤ i ≤ n) contains either characters "01", if Mike put the i-th magnet in the "plus-minus" position, or characters "10", if Mike put the magnet in the "minus-plus" position.
800
On the single line of the output print the number of groups of magnets.
standard output
PASSED
2bda379dec369c69f7d9a3bb7fdf7af5
train_003.jsonl
1379172600
Mad scientist Mike entertains himself by arranging rows of dominoes. He doesn't need dominoes, though: he uses rectangular magnets instead. Each magnet has two poles, positive (a "plus") and negative (a "minus"). If two magnets are put together at a close distance, then the like poles will repel each other and the opposite poles will attract each other.Mike starts by laying one magnet horizontally on the table. During each following step Mike adds one more magnet horizontally to the right end of the row. Depending on how Mike puts the magnet on the table, it is either attracted to the previous one (forming a group of multiple magnets linked together) or repelled by it (then Mike lays this magnet at some distance to the right from the previous one). We assume that a sole magnet not linked to others forms a group of its own. Mike arranged multiple magnets in a row. Determine the number of groups that the magnets formed.
256 megabytes
import java.util.Scanner; public class Main { public static void main(String[] args) { int n,i=0,j=0,a,b,ln,my=0,ck=0; Scanner input = new Scanner(System.in); n = input.nextInt(); int arr[] = new int [100001]; for(i =0; i<n; i++){ arr[i] = input.nextInt(); } for(i=0; i<n; i++){ if(arr[i]!=arr[i+1]) ck++; } System.out.print(ck); } }
Java
["6\n10\n10\n10\n01\n10\n10", "4\n01\n01\n10\n10"]
1 second
["3", "2"]
NoteThe first testcase corresponds to the figure. The testcase has three groups consisting of three, one and two magnets.The second testcase has two groups, each consisting of two magnets.
Java 11
standard input
[ "implementation" ]
6c52df7ea24671102e4c0eee19dc6bba
The first line of the input contains an integer n (1 ≤ n ≤ 100000) — the number of magnets. Then n lines follow. The i-th line (1 ≤ i ≤ n) contains either characters "01", if Mike put the i-th magnet in the "plus-minus" position, or characters "10", if Mike put the magnet in the "minus-plus" position.
800
On the single line of the output print the number of groups of magnets.
standard output
PASSED
a5cdb856c5923bb9aa8934e7c33fa1d6
train_003.jsonl
1379172600
Mad scientist Mike entertains himself by arranging rows of dominoes. He doesn't need dominoes, though: he uses rectangular magnets instead. Each magnet has two poles, positive (a "plus") and negative (a "minus"). If two magnets are put together at a close distance, then the like poles will repel each other and the opposite poles will attract each other.Mike starts by laying one magnet horizontally on the table. During each following step Mike adds one more magnet horizontally to the right end of the row. Depending on how Mike puts the magnet on the table, it is either attracted to the previous one (forming a group of multiple magnets linked together) or repelled by it (then Mike lays this magnet at some distance to the right from the previous one). We assume that a sole magnet not linked to others forms a group of its own. Mike arranged multiple magnets in a row. Determine the number of groups that the magnets formed.
256 megabytes
import java.io.DataInputStream; import java.io.FileInputStream; import java.io.IOException; public class Main { static long MOD = (long) (1e9) + 7; static class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); 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; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); 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; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } public static void main(String[] args) throws java.lang.Exception { Reader in = new Reader(); int n = in.nextInt(); in.readLine(); String[] arr = new String[n]; int count = 0; for (int i = 0; i < n; i++) { arr[i] = in.readLine(); } for (int i = 1; i < n; i++) { if (!arr[i].equals(arr[i - 1])) { count++; } } System.out.println(count + 1); } }
Java
["6\n10\n10\n10\n01\n10\n10", "4\n01\n01\n10\n10"]
1 second
["3", "2"]
NoteThe first testcase corresponds to the figure. The testcase has three groups consisting of three, one and two magnets.The second testcase has two groups, each consisting of two magnets.
Java 11
standard input
[ "implementation" ]
6c52df7ea24671102e4c0eee19dc6bba
The first line of the input contains an integer n (1 ≤ n ≤ 100000) — the number of magnets. Then n lines follow. The i-th line (1 ≤ i ≤ n) contains either characters "01", if Mike put the i-th magnet in the "plus-minus" position, or characters "10", if Mike put the magnet in the "minus-plus" position.
800
On the single line of the output print the number of groups of magnets.
standard output
PASSED
0ef33e9f99b2177f86365eaec55992c0
train_003.jsonl
1379172600
Mad scientist Mike entertains himself by arranging rows of dominoes. He doesn't need dominoes, though: he uses rectangular magnets instead. Each magnet has two poles, positive (a "plus") and negative (a "minus"). If two magnets are put together at a close distance, then the like poles will repel each other and the opposite poles will attract each other.Mike starts by laying one magnet horizontally on the table. During each following step Mike adds one more magnet horizontally to the right end of the row. Depending on how Mike puts the magnet on the table, it is either attracted to the previous one (forming a group of multiple magnets linked together) or repelled by it (then Mike lays this magnet at some distance to the right from the previous one). We assume that a sole magnet not linked to others forms a group of its own. Mike arranged multiple magnets in a row. Determine the number of groups that the magnets formed.
256 megabytes
import java.util.Scanner; public class Magnet { public static void main(String[] args) { Scanner input=new Scanner(System.in); int n=input.nextInt(); int j[]=new int[n]; int count=j.length; for (int i=0;i<n;i++){ j[i]=input.nextInt();} for(int x=0;x<j.length; x++){ if((x+1)<j.length){ if(j[x]==j[x+1]){ count--;}} } System.out.println(count); }}
Java
["6\n10\n10\n10\n01\n10\n10", "4\n01\n01\n10\n10"]
1 second
["3", "2"]
NoteThe first testcase corresponds to the figure. The testcase has three groups consisting of three, one and two magnets.The second testcase has two groups, each consisting of two magnets.
Java 11
standard input
[ "implementation" ]
6c52df7ea24671102e4c0eee19dc6bba
The first line of the input contains an integer n (1 ≤ n ≤ 100000) — the number of magnets. Then n lines follow. The i-th line (1 ≤ i ≤ n) contains either characters "01", if Mike put the i-th magnet in the "plus-minus" position, or characters "10", if Mike put the magnet in the "minus-plus" position.
800
On the single line of the output print the number of groups of magnets.
standard output
PASSED
d40d571ed1a4bed44560c14e16f37be4
train_003.jsonl
1379172600
Mad scientist Mike entertains himself by arranging rows of dominoes. He doesn't need dominoes, though: he uses rectangular magnets instead. Each magnet has two poles, positive (a "plus") and negative (a "minus"). If two magnets are put together at a close distance, then the like poles will repel each other and the opposite poles will attract each other.Mike starts by laying one magnet horizontally on the table. During each following step Mike adds one more magnet horizontally to the right end of the row. Depending on how Mike puts the magnet on the table, it is either attracted to the previous one (forming a group of multiple magnets linked together) or repelled by it (then Mike lays this magnet at some distance to the right from the previous one). We assume that a sole magnet not linked to others forms a group of its own. Mike arranged multiple magnets in a row. Determine the number of groups that the magnets formed.
256 megabytes
/****************************************************************************** Online Java Compiler. Code, Compile, Run and Debug java program online. Write your code in this editor and press "Run" button to execute it. *******************************************************************************/ import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int n=sc.nextInt(); long c=1; int arr[]=new int[n]; for(int i=0; i<n; i++) { arr[i] = sc.nextInt(); } int stonk = arr[0]; for(int i=0; i<n;i++) { if(arr[i] != stonk) { c++; stonk = arr[i]; } } System.out.println(c); } }
Java
["6\n10\n10\n10\n01\n10\n10", "4\n01\n01\n10\n10"]
1 second
["3", "2"]
NoteThe first testcase corresponds to the figure. The testcase has three groups consisting of three, one and two magnets.The second testcase has two groups, each consisting of two magnets.
Java 11
standard input
[ "implementation" ]
6c52df7ea24671102e4c0eee19dc6bba
The first line of the input contains an integer n (1 ≤ n ≤ 100000) — the number of magnets. Then n lines follow. The i-th line (1 ≤ i ≤ n) contains either characters "01", if Mike put the i-th magnet in the "plus-minus" position, or characters "10", if Mike put the magnet in the "minus-plus" position.
800
On the single line of the output print the number of groups of magnets.
standard output
PASSED
3665beb684570c6b8deaea157f027c21
train_003.jsonl
1379172600
Mad scientist Mike entertains himself by arranging rows of dominoes. He doesn't need dominoes, though: he uses rectangular magnets instead. Each magnet has two poles, positive (a "plus") and negative (a "minus"). If two magnets are put together at a close distance, then the like poles will repel each other and the opposite poles will attract each other.Mike starts by laying one magnet horizontally on the table. During each following step Mike adds one more magnet horizontally to the right end of the row. Depending on how Mike puts the magnet on the table, it is either attracted to the previous one (forming a group of multiple magnets linked together) or repelled by it (then Mike lays this magnet at some distance to the right from the previous one). We assume that a sole magnet not linked to others forms a group of its own. Mike arranged multiple magnets in a row. Determine the number of groups that the magnets formed.
256 megabytes
import java.util.*; import java.lang.Math; public class Main{ public static void main(String [] args){ Scanner input = new Scanner(System.in); int n = input.nextInt(); int pos = 0; int neg = 0; int count = 0; for(int i=0;i<n;i++){ pos = input.nextInt(); if(pos != neg){ count++; neg = pos; } } System.out.println(count); } }
Java
["6\n10\n10\n10\n01\n10\n10", "4\n01\n01\n10\n10"]
1 second
["3", "2"]
NoteThe first testcase corresponds to the figure. The testcase has three groups consisting of three, one and two magnets.The second testcase has two groups, each consisting of two magnets.
Java 11
standard input
[ "implementation" ]
6c52df7ea24671102e4c0eee19dc6bba
The first line of the input contains an integer n (1 ≤ n ≤ 100000) — the number of magnets. Then n lines follow. The i-th line (1 ≤ i ≤ n) contains either characters "01", if Mike put the i-th magnet in the "plus-minus" position, or characters "10", if Mike put the magnet in the "minus-plus" position.
800
On the single line of the output print the number of groups of magnets.
standard output
PASSED
e6d5af9c784b9890fd726827fce2bf37
train_003.jsonl
1379172600
Mad scientist Mike entertains himself by arranging rows of dominoes. He doesn't need dominoes, though: he uses rectangular magnets instead. Each magnet has two poles, positive (a "plus") and negative (a "minus"). If two magnets are put together at a close distance, then the like poles will repel each other and the opposite poles will attract each other.Mike starts by laying one magnet horizontally on the table. During each following step Mike adds one more magnet horizontally to the right end of the row. Depending on how Mike puts the magnet on the table, it is either attracted to the previous one (forming a group of multiple magnets linked together) or repelled by it (then Mike lays this magnet at some distance to the right from the previous one). We assume that a sole magnet not linked to others forms a group of its own. Mike arranged multiple magnets in a row. Determine the number of groups that the magnets formed.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Magnets { public static void main (String[] args) throws IOException { //code BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n=Integer.parseInt(br.readLine()); String m=br.readLine(); // System.out.println("m="+m); int o=Integer.parseInt(String.valueOf(m.charAt(1))); int t=Integer.parseInt(String.valueOf(m.charAt(0))); int count=0; int newo=o; if(n>1) { for (int i = 0; i < n - 1; i++) { String s = br.readLine(); // System.out.println("s=" + s); int so = Integer.parseInt(String.valueOf(s.charAt(1))); int st = Integer.parseInt(String.valueOf(s.charAt(0))); int newt = st; if (newt == newo) { count++; // System.out.println("count=" + count); } newo = so; } System.out.println(count+1); } else { System.out.println("1"); } } }
Java
["6\n10\n10\n10\n01\n10\n10", "4\n01\n01\n10\n10"]
1 second
["3", "2"]
NoteThe first testcase corresponds to the figure. The testcase has three groups consisting of three, one and two magnets.The second testcase has two groups, each consisting of two magnets.
Java 11
standard input
[ "implementation" ]
6c52df7ea24671102e4c0eee19dc6bba
The first line of the input contains an integer n (1 ≤ n ≤ 100000) — the number of magnets. Then n lines follow. The i-th line (1 ≤ i ≤ n) contains either characters "01", if Mike put the i-th magnet in the "plus-minus" position, or characters "10", if Mike put the magnet in the "minus-plus" position.
800
On the single line of the output print the number of groups of magnets.
standard output
PASSED
3b1dcea031faeddaab527d9927d8287b
train_003.jsonl
1379172600
Mad scientist Mike entertains himself by arranging rows of dominoes. He doesn't need dominoes, though: he uses rectangular magnets instead. Each magnet has two poles, positive (a "plus") and negative (a "minus"). If two magnets are put together at a close distance, then the like poles will repel each other and the opposite poles will attract each other.Mike starts by laying one magnet horizontally on the table. During each following step Mike adds one more magnet horizontally to the right end of the row. Depending on how Mike puts the magnet on the table, it is either attracted to the previous one (forming a group of multiple magnets linked together) or repelled by it (then Mike lays this magnet at some distance to the right from the previous one). We assume that a sole magnet not linked to others forms a group of its own. Mike arranged multiple magnets in a row. Determine the number of groups that the magnets formed.
256 megabytes
import java.util.*; public class Main { public static void main(String[] args) { int count=1; Scanner sc=new Scanner(System.in); int n=sc.nextInt(); int a[]=new int[n]; for(int i=0;i<n;i++) { a[i]=sc.nextInt(); } for(int i=0;i<n-1;i++) { if(a[i]!=a[i+1]) count++; } System.out.println(count); } }
Java
["6\n10\n10\n10\n01\n10\n10", "4\n01\n01\n10\n10"]
1 second
["3", "2"]
NoteThe first testcase corresponds to the figure. The testcase has three groups consisting of three, one and two magnets.The second testcase has two groups, each consisting of two magnets.
Java 11
standard input
[ "implementation" ]
6c52df7ea24671102e4c0eee19dc6bba
The first line of the input contains an integer n (1 ≤ n ≤ 100000) — the number of magnets. Then n lines follow. The i-th line (1 ≤ i ≤ n) contains either characters "01", if Mike put the i-th magnet in the "plus-minus" position, or characters "10", if Mike put the magnet in the "minus-plus" position.
800
On the single line of the output print the number of groups of magnets.
standard output
PASSED
090a075d76bb55407fb60cd03a1f600b
train_003.jsonl
1379172600
Mad scientist Mike entertains himself by arranging rows of dominoes. He doesn't need dominoes, though: he uses rectangular magnets instead. Each magnet has two poles, positive (a "plus") and negative (a "minus"). If two magnets are put together at a close distance, then the like poles will repel each other and the opposite poles will attract each other.Mike starts by laying one magnet horizontally on the table. During each following step Mike adds one more magnet horizontally to the right end of the row. Depending on how Mike puts the magnet on the table, it is either attracted to the previous one (forming a group of multiple magnets linked together) or repelled by it (then Mike lays this magnet at some distance to the right from the previous one). We assume that a sole magnet not linked to others forms a group of its own. Mike arranged multiple magnets in a row. Determine the number of groups that the magnets formed.
256 megabytes
import java.util.Scanner; public class _344A_Magnets { public static void main(String[] args) { Scanner input = new Scanner(System.in); int n = input.nextInt(); int k=1; if (n==1){ System.out.println("1"); return; } int m1 = input.nextInt(); for (int i = 1; i < n; i++) { int m2 = input.nextInt(); if (m1%10 == m2/10) { k++; } m1=m2; } System.out.println(k); } }
Java
["6\n10\n10\n10\n01\n10\n10", "4\n01\n01\n10\n10"]
1 second
["3", "2"]
NoteThe first testcase corresponds to the figure. The testcase has three groups consisting of three, one and two magnets.The second testcase has two groups, each consisting of two magnets.
Java 11
standard input
[ "implementation" ]
6c52df7ea24671102e4c0eee19dc6bba
The first line of the input contains an integer n (1 ≤ n ≤ 100000) — the number of magnets. Then n lines follow. The i-th line (1 ≤ i ≤ n) contains either characters "01", if Mike put the i-th magnet in the "plus-minus" position, or characters "10", if Mike put the magnet in the "minus-plus" position.
800
On the single line of the output print the number of groups of magnets.
standard output
PASSED
09d19a49c93531772ea89620f7dc06a1
train_003.jsonl
1379172600
Mad scientist Mike entertains himself by arranging rows of dominoes. He doesn't need dominoes, though: he uses rectangular magnets instead. Each magnet has two poles, positive (a "plus") and negative (a "minus"). If two magnets are put together at a close distance, then the like poles will repel each other and the opposite poles will attract each other.Mike starts by laying one magnet horizontally on the table. During each following step Mike adds one more magnet horizontally to the right end of the row. Depending on how Mike puts the magnet on the table, it is either attracted to the previous one (forming a group of multiple magnets linked together) or repelled by it (then Mike lays this magnet at some distance to the right from the previous one). We assume that a sole magnet not linked to others forms a group of its own. Mike arranged multiple magnets in a row. Determine the number of groups that the magnets formed.
256 megabytes
import java.util.Scanner; public class magnets { public static void main(String args[]) { Scanner sc=new Scanner(System.in); int n=sc.nextInt(); int ar[]=new int[n]; for(int x=0;x<n;x++) ar[x]=sc.nextInt(); int check,change; if(ar[0]==1) { check=1; change=10; } else { check=10; change=1; } int count=1; for(int x=0;x<n;x++) { if(ar[x]==check) continue; else { count++; int temp=check; check=change; change=temp; } } System.out.println(count); } }
Java
["6\n10\n10\n10\n01\n10\n10", "4\n01\n01\n10\n10"]
1 second
["3", "2"]
NoteThe first testcase corresponds to the figure. The testcase has three groups consisting of three, one and two magnets.The second testcase has two groups, each consisting of two magnets.
Java 11
standard input
[ "implementation" ]
6c52df7ea24671102e4c0eee19dc6bba
The first line of the input contains an integer n (1 ≤ n ≤ 100000) — the number of magnets. Then n lines follow. The i-th line (1 ≤ i ≤ n) contains either characters "01", if Mike put the i-th magnet in the "plus-minus" position, or characters "10", if Mike put the magnet in the "minus-plus" position.
800
On the single line of the output print the number of groups of magnets.
standard output
PASSED
97b59ba8d81c5dd6c45d522aee3469ae
train_003.jsonl
1379172600
Mad scientist Mike entertains himself by arranging rows of dominoes. He doesn't need dominoes, though: he uses rectangular magnets instead. Each magnet has two poles, positive (a "plus") and negative (a "minus"). If two magnets are put together at a close distance, then the like poles will repel each other and the opposite poles will attract each other.Mike starts by laying one magnet horizontally on the table. During each following step Mike adds one more magnet horizontally to the right end of the row. Depending on how Mike puts the magnet on the table, it is either attracted to the previous one (forming a group of multiple magnets linked together) or repelled by it (then Mike lays this magnet at some distance to the right from the previous one). We assume that a sole magnet not linked to others forms a group of its own. Mike arranged multiple magnets in a row. Determine the number of groups that the magnets formed.
256 megabytes
import java.util.Scanner; public class P344A { public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc = new Scanner(System.in); int n=sc.nextInt(); sc.nextLine(); int start=0; int grps=0; String current_str=""; String previous_str=""; for (int i=0;i<n;i++) { if(start==0) { current_str=sc.nextLine(); start+=1; grps+=1; previous_str=current_str; continue; } else { current_str=sc.nextLine(); if (!current_str.equals(previous_str)) { grps+=1; } previous_str=current_str; } } System.out.println(grps); sc.close(); } }
Java
["6\n10\n10\n10\n01\n10\n10", "4\n01\n01\n10\n10"]
1 second
["3", "2"]
NoteThe first testcase corresponds to the figure. The testcase has three groups consisting of three, one and two magnets.The second testcase has two groups, each consisting of two magnets.
Java 11
standard input
[ "implementation" ]
6c52df7ea24671102e4c0eee19dc6bba
The first line of the input contains an integer n (1 ≤ n ≤ 100000) — the number of magnets. Then n lines follow. The i-th line (1 ≤ i ≤ n) contains either characters "01", if Mike put the i-th magnet in the "plus-minus" position, or characters "10", if Mike put the magnet in the "minus-plus" position.
800
On the single line of the output print the number of groups of magnets.
standard output
PASSED
249c0e9e3d24b363f4be35694c2ef8bf
train_003.jsonl
1379172600
Mad scientist Mike entertains himself by arranging rows of dominoes. He doesn't need dominoes, though: he uses rectangular magnets instead. Each magnet has two poles, positive (a "plus") and negative (a "minus"). If two magnets are put together at a close distance, then the like poles will repel each other and the opposite poles will attract each other.Mike starts by laying one magnet horizontally on the table. During each following step Mike adds one more magnet horizontally to the right end of the row. Depending on how Mike puts the magnet on the table, it is either attracted to the previous one (forming a group of multiple magnets linked together) or repelled by it (then Mike lays this magnet at some distance to the right from the previous one). We assume that a sole magnet not linked to others forms a group of its own. Mike arranged multiple magnets in a row. Determine the number of groups that the magnets formed.
256 megabytes
import java.util.*; public class hulk { public static void main(String[] args) { Scanner console = new Scanner(System.in); int num = console.nextInt(); int groups = 1; String start = console.next(); for (int i = 0; i < num - 1; i++) { String temp = console.next(); if (!(start.equals(temp))) { groups++; } start = temp; } System.out.println(groups); } }
Java
["6\n10\n10\n10\n01\n10\n10", "4\n01\n01\n10\n10"]
1 second
["3", "2"]
NoteThe first testcase corresponds to the figure. The testcase has three groups consisting of three, one and two magnets.The second testcase has two groups, each consisting of two magnets.
Java 11
standard input
[ "implementation" ]
6c52df7ea24671102e4c0eee19dc6bba
The first line of the input contains an integer n (1 ≤ n ≤ 100000) — the number of magnets. Then n lines follow. The i-th line (1 ≤ i ≤ n) contains either characters "01", if Mike put the i-th magnet in the "plus-minus" position, or characters "10", if Mike put the magnet in the "minus-plus" position.
800
On the single line of the output print the number of groups of magnets.
standard output
PASSED
8704a19961f33ea4c6fc74bf12bc19b0
train_003.jsonl
1582473900
VK news recommendation system daily selects interesting publications of one of $$$n$$$ disjoint categories for each user. Each publication belongs to exactly one category. For each category $$$i$$$ batch algorithm selects $$$a_i$$$ publications.The latest A/B test suggests that users are reading recommended publications more actively if each category has a different number of publications within daily recommendations. The targeted algorithm can find a single interesting publication of $$$i$$$-th category within $$$t_i$$$ seconds. What is the minimum total time necessary to add publications to the result of batch algorithm execution, so all categories have a different number of publications? You can't remove publications recommended by the batch algorithm.
512 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; public class Main { static long sx = 0, sy = 0, mod = (long) (1e9 + 7); static ArrayList<Integer>[] a; static long[][][] dp; static long[] fa; static long[] farr; public static PrintWriter out; static ArrayList<pair> pa = new ArrayList<>(); static long[] fact = new long[(int) 1e6]; static StringBuilder sb = new StringBuilder(); static boolean cycle = false; static long m = 998244353; static long[] no, col; // static String s; static long k = 0, n = 0; static int[] c; static long ans = 0; static int[] down; static int[] score; static HashMap<Integer, ArrayList<Integer>> hm; public static void main(String[] args) throws IOException { // Scanner scn = new Scanner(new BufferedReader(new // InputStreamReader(System.in))); out = new PrintWriter(System.out); Reader scn = new Reader(); int n = scn.nextInt(); ArrayList<pair> p = new ArrayList<>(); for (int i = 0; i < n; i++) p.add(new pair(scn.nextInt(), -1)); for (int i = 0; i < n; i++) p.get(i).t = scn.nextInt(); Collections.sort(p); PriorityQueue<Long> pq = new PriorityQueue<>(Collections.reverseOrder()); long sum = 0, ans = 0; int i = 0; while (i < n) { if (i > 0 && p.get(i).val != p.get(i - 1).val) { sum -= pq.remove(); ans += sum; long d = p.get(i).val - p.get(i-1).val - 1; while(pq.size()!=0 && d--!=0){ sum -= pq.remove(); ans += sum; } sum += p.get(i).t; pq.add(p.get(i).t); } else { pq.add(p.get(i).t); sum += p.get(i).t; } i++; } pq.remove(); int size = pq.size(); for( i=1; i<=size; i++){ ans+=i*pq.remove(); } System.out.println(ans); } // _________________________TEMPLATE_____________________________________________________________ // public static long lcm(long x, long y) { // // return (x * y) / gcd(x, y); // } // // private static long gcd(long x, long y) { // if (x == 0) // return y; // // return gcd(y % x, x); // } // // static class comp implements Comparator<Integer> { // // @Override // public int compare(Integer p1, Integer p2) { // // return p2 - p1; // // } // } // // } // // public static long pow(long a, long b) { // // if (b < 0) // return 0; // if (b == 0 || b == 1) // return (long) Math.pow(a, b); // // if (b % 2 == 0) { // // long ret = pow(a, b / 2); // ret = (ret % mod * ret % mod) % mod; // return ret; // } // // else { // return ((pow(a, b - 1) % mod) * a % mod) % mod; // } // } private static class pair implements Comparable<pair> { long val; long t; pair(long a, long b) { val = a; t = b; } @Override public int compareTo(pair o) { return (int)(this.val - o.val); } // @Override // // public int hashCode() { // return i; // } // // @Override // // public boolean equals(Object o) { // // pair p = (pair) o; // return this.i == p.i; // } } private static String reverse(String s) { return new StringBuilder(s).reverse().toString(); } public static class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[1000000 + 1]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); 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; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); 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; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } public int[] nextIntArray(int n) throws IOException { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = nextInt(); } return arr; } public long[] nextLongArray(int n) throws IOException { long[] arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = nextLong(); } return arr; } public int[][] nextInt2DArray(int m, int n) throws IOException { int[][] arr = new int[m][n]; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) arr[i][j] = nextInt(); } return arr; } public long[][] nextInt2DArrayL(int m, int n) throws IOException { long[][] arr = new long[m][n]; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) arr[i][j] = nextInt(); } return arr; } // kickstart - Solution // atcoder - Main } }
Java
["5\n3 7 9 7 8\n5 2 5 7 5", "5\n1 2 3 4 5\n1 1 1 1 1"]
2 seconds
["6", "0"]
NoteIn the first example, it is possible to find three publications of the second type, which will take 6 seconds.In the second example, all news categories contain a different number of publications.
Java 11
standard input
[ "data structures", "sortings", "greedy" ]
6bceaf308c38d234ba931c13e4f70929
The first line of input consists of single integer $$$n$$$ — the number of news categories ($$$1 \le n \le 200\,000$$$). The second line of input consists of $$$n$$$ integers $$$a_i$$$ — the number of publications of $$$i$$$-th category selected by the batch algorithm ($$$1 \le a_i \le 10^9$$$). The third line of input consists of $$$n$$$ integers $$$t_i$$$ — time it takes for targeted algorithm to find one new publication of category $$$i$$$ ($$$1 \le t_i \le 10^5)$$$.
1,700
Print one integer — the minimal required time for the targeted algorithm to get rid of categories with the same size.
standard output
PASSED
562bd65fc0e8d3098c090b22dd2d780a
train_003.jsonl
1582473900
VK news recommendation system daily selects interesting publications of one of $$$n$$$ disjoint categories for each user. Each publication belongs to exactly one category. For each category $$$i$$$ batch algorithm selects $$$a_i$$$ publications.The latest A/B test suggests that users are reading recommended publications more actively if each category has a different number of publications within daily recommendations. The targeted algorithm can find a single interesting publication of $$$i$$$-th category within $$$t_i$$$ seconds. What is the minimum total time necessary to add publications to the result of batch algorithm execution, so all categories have a different number of publications? You can't remove publications recommended by the batch algorithm.
512 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Objects; import java.util.Arrays; import java.util.Scanner; import java.util.Comparator; import java.util.TreeSet; /** * 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); TaskA solver = new TaskA(); solver.solve(1, in, out); out.close(); } static class TaskA { public void solve(int testNumber, Scanner in, PrintWriter out) { int n = in.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = in.nextInt(); } TaskA.Node[] nodes = new TaskA.Node[n]; for (int i = 0; i < n; i++) { int t = in.nextInt(); nodes[i] = new TaskA.Node(a[i], t, i); } Arrays.sort(nodes, Comparator.comparingInt(e -> e.a)); long sum = 0; int category = -1; TreeSet<TaskA.Node> active = new TreeSet<>(); for (TaskA.Node e : nodes) { while (!active.isEmpty() && category < e.a) { TaskA.Node eo = active.pollFirst(); sum += (long) (category - eo.a) * eo.t; ++category; } if (category < e.a) { category = e.a; } active.add(e); } while (!active.isEmpty()) { TaskA.Node eo = active.pollFirst(); sum += (long) (category - eo.a) * eo.t; ++category; } out.println(sum); } static class Node implements Comparable<TaskA.Node> { int a; int t; int index; public Node(int a, int t, int index) { this.a = a; this.t = t; this.index = index; } public int compareTo(TaskA.Node o) { if (t != o.t) { return -Integer.compare(t, o.t); } return Integer.compare(index, o.index); } public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; TaskA.Node node = (TaskA.Node) o; return a == node.a && t == node.t && index == node.index; } public int hashCode() { return Objects.hash(a, t, index); } } } }
Java
["5\n3 7 9 7 8\n5 2 5 7 5", "5\n1 2 3 4 5\n1 1 1 1 1"]
2 seconds
["6", "0"]
NoteIn the first example, it is possible to find three publications of the second type, which will take 6 seconds.In the second example, all news categories contain a different number of publications.
Java 11
standard input
[ "data structures", "sortings", "greedy" ]
6bceaf308c38d234ba931c13e4f70929
The first line of input consists of single integer $$$n$$$ — the number of news categories ($$$1 \le n \le 200\,000$$$). The second line of input consists of $$$n$$$ integers $$$a_i$$$ — the number of publications of $$$i$$$-th category selected by the batch algorithm ($$$1 \le a_i \le 10^9$$$). The third line of input consists of $$$n$$$ integers $$$t_i$$$ — time it takes for targeted algorithm to find one new publication of category $$$i$$$ ($$$1 \le t_i \le 10^5)$$$.
1,700
Print one integer — the minimal required time for the targeted algorithm to get rid of categories with the same size.
standard output
PASSED
8c4af12694217fb7f3c334b71955e971
train_003.jsonl
1582473900
VK news recommendation system daily selects interesting publications of one of $$$n$$$ disjoint categories for each user. Each publication belongs to exactly one category. For each category $$$i$$$ batch algorithm selects $$$a_i$$$ publications.The latest A/B test suggests that users are reading recommended publications more actively if each category has a different number of publications within daily recommendations. The targeted algorithm can find a single interesting publication of $$$i$$$-th category within $$$t_i$$$ seconds. What is the minimum total time necessary to add publications to the result of batch algorithm execution, so all categories have a different number of publications? You can't remove publications recommended by the batch algorithm.
512 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Objects; import java.util.Arrays; import java.util.Scanner; import java.util.Comparator; import java.util.TreeSet; /** * 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); TaskA solver = new TaskA(); solver.solve(1, in, out); out.close(); } static class TaskA { public void solve(int testNumber, Scanner in, PrintWriter out) { int n = in.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = in.nextInt(); } TaskA.Node[] nodes = new TaskA.Node[n]; for (int i = 0; i < n; i++) { int t = in.nextInt(); nodes[i] = new TaskA.Node(a[i], t, i); } Arrays.sort(nodes, Comparator.comparingInt(e -> e.a)); long sum = 0; int category = -1; TreeSet<TaskA.Node> active = new TreeSet<>(); for (TaskA.Node e : nodes) { while (!active.isEmpty() && category < e.a) { TaskA.Node eo = active.pollFirst(); sum += (category - eo.a) * 1L * eo.t; ++category; } if (category < e.a) { category = e.a; } active.add(e); } while (!active.isEmpty()) { TaskA.Node eo = active.pollFirst(); sum += (category - eo.a) * 1L * eo.t; ++category; } out.println(sum); } static class Node implements Comparable<TaskA.Node> { int a; int t; int index; public Node(int a, int t, int index) { this.a = a; this.t = t; this.index = index; } public int compareTo(TaskA.Node o) { if (t != o.t) { return -Integer.compare(t, o.t); } return Integer.compare(index, o.index); } public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; TaskA.Node node = (TaskA.Node) o; return a == node.a && t == node.t && index == node.index; } public int hashCode() { return Objects.hash(a, t, index); } } } }
Java
["5\n3 7 9 7 8\n5 2 5 7 5", "5\n1 2 3 4 5\n1 1 1 1 1"]
2 seconds
["6", "0"]
NoteIn the first example, it is possible to find three publications of the second type, which will take 6 seconds.In the second example, all news categories contain a different number of publications.
Java 11
standard input
[ "data structures", "sortings", "greedy" ]
6bceaf308c38d234ba931c13e4f70929
The first line of input consists of single integer $$$n$$$ — the number of news categories ($$$1 \le n \le 200\,000$$$). The second line of input consists of $$$n$$$ integers $$$a_i$$$ — the number of publications of $$$i$$$-th category selected by the batch algorithm ($$$1 \le a_i \le 10^9$$$). The third line of input consists of $$$n$$$ integers $$$t_i$$$ — time it takes for targeted algorithm to find one new publication of category $$$i$$$ ($$$1 \le t_i \le 10^5)$$$.
1,700
Print one integer — the minimal required time for the targeted algorithm to get rid of categories with the same size.
standard output
PASSED
66400b7ae882f25015e8164b206f124c
train_003.jsonl
1582473900
VK news recommendation system daily selects interesting publications of one of $$$n$$$ disjoint categories for each user. Each publication belongs to exactly one category. For each category $$$i$$$ batch algorithm selects $$$a_i$$$ publications.The latest A/B test suggests that users are reading recommended publications more actively if each category has a different number of publications within daily recommendations. The targeted algorithm can find a single interesting publication of $$$i$$$-th category within $$$t_i$$$ seconds. What is the minimum total time necessary to add publications to the result of batch algorithm execution, so all categories have a different number of publications? You can't remove publications recommended by the batch algorithm.
512 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Arrays; import java.io.BufferedWriter; import java.util.InputMismatchException; import java.io.IOException; import java.util.TreeSet; import java.util.Objects; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.Comparator; import java.io.InputStream; /** * Built using CHelper plug-in Actual solution is at the top * * @author ilyakor */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskA solver = new TaskA(); solver.solve(1, in, out); out.close(); } static class TaskA { public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; ++i) { a[i] = in.nextInt(); } int[] T = new int[n]; for (int i = 0; i < n; ++i) { T[i] = in.nextInt(); } TaskA.Entry[] entries = new TaskA.Entry[n]; for (int i = 0; i < n; ++i) { entries[i] = new TaskA.Entry(a[i], T[i], i); } Arrays.sort(entries, new Comparator<TaskA.Entry>() { public int compare(TaskA.Entry o1, TaskA.Entry o2) { return Integer.compare(o1.x, o2.x); } }); long res = 0; int pos = -1; TreeSet<TaskA.Entry> active = new TreeSet<>(); for (TaskA.Entry e : entries) { while (!active.isEmpty() && pos < e.x) { TaskA.Entry oe = active.pollFirst(); res += (pos - oe.x) * (long) oe.t; ++pos; } if (pos < e.x) { pos = e.x; } active.add(e); } while (!active.isEmpty()) { TaskA.Entry oe = active.pollFirst(); res += (pos - oe.x) * (long) oe.t; ++pos; } out.printLine(res); } static class Entry implements Comparable<TaskA.Entry> { int x; int t; int id; public Entry(int x, int t, int id) { this.x = x; this.t = t; this.id = id; } public int compareTo(TaskA.Entry o) { if (t != o.t) { return -Integer.compare(t, o.t); } return Integer.compare(id, o.id); } public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof TaskA.Entry)) { return false; } TaskA.Entry entry = (TaskA.Entry) o; return x == entry.x && t == entry.t && id == entry.id; } public int hashCode() { return Objects.hash(x, t, id); } } } 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 print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) { writer.print(' '); } writer.print(objects[i]); } } public void printLine(Object... objects) { print(objects); writer.println(); } public void close() { writer.close(); } } static class InputReader { private InputStream stream; private byte[] buffer = new byte[10000]; private int cur; private int count; public InputReader(InputStream stream) { this.stream = stream; } public static boolean isSpace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public int read() { if (count == -1) { throw new InputMismatchException(); } try { if (cur >= count) { cur = 0; count = stream.read(buffer); if (count <= 0) { return -1; } } } catch (IOException e) { throw new InputMismatchException(); } return buffer[cur++]; } public int readSkipSpace() { int c; do { c = read(); } while (isSpace(c)); return c; } public int nextInt() { int sgn = 1; int c = readSkipSpace(); if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res = res * 10 + c - '0'; c = read(); } while (!isSpace(c)); res *= sgn; return res; } } }
Java
["5\n3 7 9 7 8\n5 2 5 7 5", "5\n1 2 3 4 5\n1 1 1 1 1"]
2 seconds
["6", "0"]
NoteIn the first example, it is possible to find three publications of the second type, which will take 6 seconds.In the second example, all news categories contain a different number of publications.
Java 11
standard input
[ "data structures", "sortings", "greedy" ]
6bceaf308c38d234ba931c13e4f70929
The first line of input consists of single integer $$$n$$$ — the number of news categories ($$$1 \le n \le 200\,000$$$). The second line of input consists of $$$n$$$ integers $$$a_i$$$ — the number of publications of $$$i$$$-th category selected by the batch algorithm ($$$1 \le a_i \le 10^9$$$). The third line of input consists of $$$n$$$ integers $$$t_i$$$ — time it takes for targeted algorithm to find one new publication of category $$$i$$$ ($$$1 \le t_i \le 10^5)$$$.
1,700
Print one integer — the minimal required time for the targeted algorithm to get rid of categories with the same size.
standard output
PASSED
078fef2cf40a05c9b568015e30c0fc15
train_003.jsonl
1582473900
VK news recommendation system daily selects interesting publications of one of $$$n$$$ disjoint categories for each user. Each publication belongs to exactly one category. For each category $$$i$$$ batch algorithm selects $$$a_i$$$ publications.The latest A/B test suggests that users are reading recommended publications more actively if each category has a different number of publications within daily recommendations. The targeted algorithm can find a single interesting publication of $$$i$$$-th category within $$$t_i$$$ seconds. What is the minimum total time necessary to add publications to the result of batch algorithm execution, so all categories have a different number of publications? You can't remove publications recommended by the batch algorithm.
512 megabytes
import java.io.*; import java.util.*; public class Recommendations { public static void main(String[] args) throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(br.readLine()); int[][] a = new int[n][2]; for (int i = 0; i < 2; i++) { StringTokenizer st = new StringTokenizer(br.readLine()); for (int j = 0; j < n; j++) { a[j][i] = Integer.parseInt(st.nextToken()); } } br.close(); System.out.println(adjust(a)); } static long adjust(int[][] arr) { Arrays.sort(arr, (a, b) -> a[0] == b[0] ? a[1] - b[1] : a[0] - b[0]); long cost = 0; int val = -1; long addVal = 0; Queue<Integer> todo = new PriorityQueue<>((a, b) -> b - a); for (int[] e: arr) { // System.out.println(i); // System.out.println(cost + " " + addVal); // System.out.println(todo); while (!todo.isEmpty() && val < e[0]) { // System.out.println("emptying"); // System.out.println(val + " < " + arr[i][0]); // System.out.println(todo.peek()); // System.out.println("cost: " + cost); addVal -= todo.poll(); cost += addVal; val++; } val = e[0]; todo.add(e[1]); addVal += e[1]; } // System.out.println(todo); while (!todo.isEmpty()) { // System.out.println("emptying"); // System.out.println(todo.peek()); // System.out.println("cost: " + cost); addVal -= todo.poll(); cost += addVal; } return cost; } }
Java
["5\n3 7 9 7 8\n5 2 5 7 5", "5\n1 2 3 4 5\n1 1 1 1 1"]
2 seconds
["6", "0"]
NoteIn the first example, it is possible to find three publications of the second type, which will take 6 seconds.In the second example, all news categories contain a different number of publications.
Java 11
standard input
[ "data structures", "sortings", "greedy" ]
6bceaf308c38d234ba931c13e4f70929
The first line of input consists of single integer $$$n$$$ — the number of news categories ($$$1 \le n \le 200\,000$$$). The second line of input consists of $$$n$$$ integers $$$a_i$$$ — the number of publications of $$$i$$$-th category selected by the batch algorithm ($$$1 \le a_i \le 10^9$$$). The third line of input consists of $$$n$$$ integers $$$t_i$$$ — time it takes for targeted algorithm to find one new publication of category $$$i$$$ ($$$1 \le t_i \le 10^5)$$$.
1,700
Print one integer — the minimal required time for the targeted algorithm to get rid of categories with the same size.
standard output
PASSED
e4b8f85cde4e8d2e85ac5543fd3b61e3
train_003.jsonl
1582473900
VK news recommendation system daily selects interesting publications of one of $$$n$$$ disjoint categories for each user. Each publication belongs to exactly one category. For each category $$$i$$$ batch algorithm selects $$$a_i$$$ publications.The latest A/B test suggests that users are reading recommended publications more actively if each category has a different number of publications within daily recommendations. The targeted algorithm can find a single interesting publication of $$$i$$$-th category within $$$t_i$$$ seconds. What is the minimum total time necessary to add publications to the result of batch algorithm execution, so all categories have a different number of publications? You can't remove publications recommended by the batch algorithm.
512 megabytes
import java.io.*; import java.util.*; import java.util.stream.Collectors; import java.util.stream.IntStream; /** * @author Nikita Gorokhov <wackloner@yandex-team.ru> */ public class A1310 { // 420 remainder: use long everywhere private final static boolean MULTIPLE_TESTS = false; private FastReader reader; private FastWriter writer; private void solve() { int n = reader.readInt(); int[] a = reader.readIntArray(n); int[] t = reader.readIntArray(n); var sorted = IntStream.range(0, n) .mapToObj(i -> Tuple.Tuple2.of(a[i], t[i])) .sorted() .collect(Collectors.toList()); TreeMap<Integer, Integer> multiset = new TreeMap<>(); long sumInSet = 0; long ans = 0; int last = -1; for (int i = 0; i < n; i++) { var cur = sorted.get(i); if (cur.first != last) { while (!multiset.isEmpty() && last < cur.first) { var max = multiset.lastEntry(); var newVal = max.getValue() - 1; sumInSet -= max.getKey(); if (newVal == 0) { multiset.remove(max.getKey()); } else { multiset.put(max.getKey(), max.getValue() - 1); } ans += sumInSet; last++; } last = cur.first; } multiset.put(cur.second, multiset.getOrDefault(cur.second, 0) + 1); sumInSet += cur.second; } while (!multiset.isEmpty()) { var max = multiset.lastEntry(); var newVal = max.getValue() - 1; sumInSet -= max.getKey(); if (newVal == 0) { multiset.remove(max.getKey()); } else { multiset.put(max.getKey(), max.getValue() - 1); } ans += sumInSet; last++; } writer.print(ans); } private void run() throws Exception { reader = new FastReader(); writer = new FastWriter(); int t = MULTIPLE_TESTS ? reader.readInt() : 1; for (int testNum = 0; testNum < t; testNum++) { solve(); } writer.close(); reader.close(); } public static void main(String[] args) throws Exception { new A1310().run(); } private final static boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null; private static class FastWriter implements AutoCloseable { @SuppressWarnings(value="all") private final static Optional<String> OUTPUT_FILENAME = Optional.empty(); private final PrintWriter out; public FastWriter() throws FileNotFoundException { this.out = OUTPUT_FILENAME.isEmpty() ? new PrintWriter(System.out) : new PrintWriter(new File(OUTPUT_FILENAME.get())); } public void print(int value) { out.print(value); } public void print(long value) { out.print(value); } public void print(double value) { out.print(value); } public <T> void print(T value) { out.print(value); } public void println(int value) { out.println(value); } public void println(long value) { out.println(value); } public void println(double value) { out.println(value); } public <T> void println(T value) { out.println(value); } public <T> void printArray(T[] array) { for (int i = 0; i < array.length; i++) { out.print(array[i]); if (i + 1 < array.length) { out.print(' '); } } out.println(); } public void printArray(int[] array) { for (int i = 0; i < array.length; i++) { out.print(array[i]); if (i + 1 < array.length) { out.print(' '); } } out.println(); } public void printArray(long[] array) { for (int i = 0; i < array.length; i++) { out.print(array[i]); if (i + 1 < array.length) { out.print(' '); } } out.println(); } public void printArray(double[] array) { for (int i = 0; i < array.length; i++) { out.print(array[i]); if (i + 1 < array.length) { out.print(' '); } } out.println(); } @Override public void close() { out.close(); } } private static class FastReader implements AutoCloseable { private final static String INPUT_FILENAME = "input.txt"; private final InputStream inputStream; private final byte[] buffer = new byte[1024]; private int bufferLen = 0; private int bufferPtr = 0; public FastReader() throws FileNotFoundException { this.inputStream = ONLINE_JUDGE ? System.in : new FileInputStream(INPUT_FILENAME); } public int[] readIntArray(int size) { int[] array = new int[size]; for (int i = 0; i < size; i++) { array[i] = readInt(); } return array; } public long[] readLongArray(int size) { long[] array = new long[size]; for (int i = 0; i < size; i++) { array[i] = readLong(); } return array; } public double[] readDoubleArray(int size) { double[] array = new double[size]; for (int i = 0; i < size; i++) { array[i] = readLong(); } return array; } public double readDouble() { return Double.parseDouble(readToken()); } public String readToken() { int b = skip(); StringBuilder sb = new StringBuilder(); while (!(isSpaceChar(b))) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } public int readInt() { int num = 0, b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } public long readLong() { long num = 0; int b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } public int readByte() { if (bufferLen == -1) { throw new InputMismatchException(); } if (bufferPtr >= bufferLen) { bufferPtr = 0; try { bufferLen = inputStream.read(buffer); } catch (IOException e) { throw new InputMismatchException(); } if (bufferLen <= 0) { return -1; } } return buffer[bufferPtr++]; } public char readChar() { return (char) skip(); } private int skip() { int b; while ((b = readByte()) != -1 && isSpaceChar(b)); return b; } private static boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } @Override public void close() throws Exception { inputStream.close(); bufferPtr = bufferLen; } } private static class Tuple { public static <A, B> Tuple2<A, B> of(A first, B second) { return new Tuple2<>(first, second); } public static <A extends Comparable<A>, B extends Comparable<B>> Tuple2<A, B> of(A first, B second) { return new ComparableTuple2<>(first, second); } public static <A, B, C> Tuple3<A, B, C> of(A first, B second, C third) { return new Tuple3<>(first, second, third); } public static <A extends Comparable<A>, B extends Comparable<B>, C extends Comparable<C>> Tuple3<A, B, C> of(A first, B second, C third) { return new ComparableTuple3<>(first, second, third); } private static class Tuple2<A, B> extends Tuple { public final A first; public final B second; private Tuple2(A first, B second) { this.first = first; this.second = second; } @Override public String toString() { return "(" + first + ", " + second + ")"; } } private static class Tuple3<A, B, C> extends Tuple2<A, B> { public final C third; private Tuple3(A first, B second, C third) { super(first, second); this.third = third; } @Override public String toString() { return "(" + first + ", " + second + ", " + third + ")"; } } private static class ComparableTuple2<A extends Comparable<A>, B extends Comparable<B>> extends Tuple2<A, B> implements Comparable<ComparableTuple2<A, B>> { private ComparableTuple2(A first, B second) { super(first, second); } @Override @SuppressWarnings("unchecked") public int compareTo(ComparableTuple2 that) { var res = first.compareTo((A) that.first); return res == 0 ? second.compareTo((B) that.second) : res; } } private static class ComparableTuple3<A extends Comparable<A>, B extends Comparable<B>, C extends Comparable<C>> extends Tuple3<A, B, C> implements Comparable<ComparableTuple3<A, B, C>> { private ComparableTuple3(A first, B second, C third) { super(first, second, third); } @Override @SuppressWarnings("unchecked") public int compareTo(ComparableTuple3 that) { var firstR = first.compareTo((A) that.first); if (firstR == 0) { var secondR = second.compareTo((B) that.second); if (secondR == 0) { return third.compareTo((C) that.third); } return secondR; } return firstR; } } } private static class Utils { private static final Random random = new Random(System.nanoTime()); public static <T extends Comparable<T>> void sort(T[] array) { shuffle(array); Arrays.sort(array); } public static void sort(int[] array) { shuffle(array); Arrays.sort(array); } public static void sort(long[] array) { shuffle(array); Arrays.sort(array); } public static void sort(double[] array) { shuffle(array); Arrays.sort(array); } public static <T> void sort(T[] array, Comparator<T> comparator) { shuffle(array); Arrays.sort(array, comparator); } public static <T> void shuffle(T[] array) { for (int i = array.length - 1; i > 0; i--) { int index = random.nextInt(i + 1); T a = array[index]; array[index] = array[i]; array[i] = a; } } public static void shuffle(int[] array) { for (int i = array.length - 1; i > 0; i--) { int index = random.nextInt(i + 1); int a = array[index]; array[index] = array[i]; array[i] = a; } } public static void shuffle(long[] array) { for (int i = array.length - 1; i > 0; i--) { int index = random.nextInt(i + 1); long a = array[index]; array[index] = array[i]; array[i] = a; } } public static void shuffle(double[] array) { for (int i = array.length - 1; i > 0; i--) { int index = random.nextInt(i + 1); double a = array[index]; array[index] = array[i]; array[i] = a; } } public static <T extends Comparable<T>> void sort(List<T> list) { Collections.shuffle(list); Collections.sort(list); } public static <T> void sort(List<T> list, Comparator<T> comparator) { Collections.shuffle(list); list.sort(comparator); } public static int randomInt(int fromIncluded, int toExcluded) { return fromIncluded + random.nextInt(toExcluded - fromIncluded); } } }
Java
["5\n3 7 9 7 8\n5 2 5 7 5", "5\n1 2 3 4 5\n1 1 1 1 1"]
2 seconds
["6", "0"]
NoteIn the first example, it is possible to find three publications of the second type, which will take 6 seconds.In the second example, all news categories contain a different number of publications.
Java 11
standard input
[ "data structures", "sortings", "greedy" ]
6bceaf308c38d234ba931c13e4f70929
The first line of input consists of single integer $$$n$$$ — the number of news categories ($$$1 \le n \le 200\,000$$$). The second line of input consists of $$$n$$$ integers $$$a_i$$$ — the number of publications of $$$i$$$-th category selected by the batch algorithm ($$$1 \le a_i \le 10^9$$$). The third line of input consists of $$$n$$$ integers $$$t_i$$$ — time it takes for targeted algorithm to find one new publication of category $$$i$$$ ($$$1 \le t_i \le 10^5)$$$.
1,700
Print one integer — the minimal required time for the targeted algorithm to get rid of categories with the same size.
standard output
PASSED
6077b2bcaf27df63b86a8c92d00a6069
train_003.jsonl
1582473900
VK news recommendation system daily selects interesting publications of one of $$$n$$$ disjoint categories for each user. Each publication belongs to exactly one category. For each category $$$i$$$ batch algorithm selects $$$a_i$$$ publications.The latest A/B test suggests that users are reading recommended publications more actively if each category has a different number of publications within daily recommendations. The targeted algorithm can find a single interesting publication of $$$i$$$-th category within $$$t_i$$$ seconds. What is the minimum total time necessary to add publications to the result of batch algorithm execution, so all categories have a different number of publications? You can't remove publications recommended by the batch algorithm.
512 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.PriorityQueue; import java.io.IOException; import java.io.InputStreamReader; import java.util.AbstractCollection; import java.util.StringTokenizer; import java.io.BufferedReader; import java.io.FileReader; import java.util.Collections; 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; Scanner in = new Scanner(inputStream); PrintWriter out = new PrintWriter(outputStream); ARecommendations solver = new ARecommendations(); solver.solve(1, in, out); out.close(); } static class ARecommendations { public void solve(int testNumber, Scanner sc, PrintWriter pw) { int n = sc.nextInt(); int[] arr = new int[n]; int[] time = new int[n]; for (int i = 0; i < n; i++) arr[i] = sc.nextInt(); for (int i = 0; i < n; i++) time[i] = sc.nextInt(); Integer[] sort = new Integer[n]; for (int i = 0; i < n; i++) sort[i] = i; Arrays.sort(sort, (a, b) -> arr[a] - arr[b]); PriorityQueue<Integer> pq = new PriorityQueue<>(Collections.reverseOrder()); int last = arr[sort[0]]; long ans = 0; long cur = 0; for (int i = 0; i < n; i++) { if (last != arr[sort[i]]) { while (last < arr[sort[i]] && !pq.isEmpty()) { cur -= pq.poll(); ans += cur; last++; } } pq.add(time[sort[i]]); cur += time[sort[i]]; last = arr[sort[i]]; } while (!pq.isEmpty()) { cur -= pq.poll(); ans += cur; } pw.println(ans); } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(FileReader r) { br = new BufferedReader(r); } public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["5\n3 7 9 7 8\n5 2 5 7 5", "5\n1 2 3 4 5\n1 1 1 1 1"]
2 seconds
["6", "0"]
NoteIn the first example, it is possible to find three publications of the second type, which will take 6 seconds.In the second example, all news categories contain a different number of publications.
Java 11
standard input
[ "data structures", "sortings", "greedy" ]
6bceaf308c38d234ba931c13e4f70929
The first line of input consists of single integer $$$n$$$ — the number of news categories ($$$1 \le n \le 200\,000$$$). The second line of input consists of $$$n$$$ integers $$$a_i$$$ — the number of publications of $$$i$$$-th category selected by the batch algorithm ($$$1 \le a_i \le 10^9$$$). The third line of input consists of $$$n$$$ integers $$$t_i$$$ — time it takes for targeted algorithm to find one new publication of category $$$i$$$ ($$$1 \le t_i \le 10^5)$$$.
1,700
Print one integer — the minimal required time for the targeted algorithm to get rid of categories with the same size.
standard output
PASSED
edb47d5653ff6b4f0a5081053849d91e
train_003.jsonl
1582473900
VK news recommendation system daily selects interesting publications of one of $$$n$$$ disjoint categories for each user. Each publication belongs to exactly one category. For each category $$$i$$$ batch algorithm selects $$$a_i$$$ publications.The latest A/B test suggests that users are reading recommended publications more actively if each category has a different number of publications within daily recommendations. The targeted algorithm can find a single interesting publication of $$$i$$$-th category within $$$t_i$$$ seconds. What is the minimum total time necessary to add publications to the result of batch algorithm execution, so all categories have a different number of publications? You can't remove publications recommended by the batch algorithm.
512 megabytes
import java.io.*; import java.util.*; import static java.lang.Math.*; import static java.util.Arrays.*; public class cf1310a_2 { public static void main(String[] args) throws IOException { int n = ri(), at[][] = new int[n][2]; r(); for(int i = 0; i < n; ++i) { at[i][0] = ni(); } r(); for(int i = 0; i < n; ++i) { at[i][1] = ni(); } sort(at, (p, q) -> p[0] - q[0]); PriorityQueue<Integer> pq = new PriorityQueue<>((p, q) -> q - p); int ind = 0, cur = -1; long sum = 0, ans = 0; while(ind < n || !pq.isEmpty()) { if(pq.isEmpty()) { cur = at[ind][0]; } while(ind < n && at[ind][0] == cur) { sum += at[ind][1]; pq.offer(at[ind][1]); ++ind; } sum -= pq.poll(); ans += sum; ++cur; } prln(ans); close(); } static BufferedReader __in = new BufferedReader(new InputStreamReader(System.in)); static PrintWriter __out = new PrintWriter(new OutputStreamWriter(System.out)); static StringTokenizer input; static Random __rand = new Random(); // references // IBIG = 1e9 + 7 // IMAX ~= 2e10 // LMAX ~= 9e18 // constants static final int IBIG = 1000000007; static final int IMAX = 2147483647; static final int IMIN = -2147483648; static final long LMAX = 9223372036854775807L; static final long LMIN = -9223372036854775808L; // math util static int minof(int a, int b, int c) {return min(a, min(b, c));} static int minof(int... x) {if(x.length == 1) return x[0]; if(x.length == 2) return min(x[0], x[1]); if(x.length == 3) return min(x[0], min(x[1], x[2])); int min = x[0]; for(int i = 1; i < x.length; ++i) if(x[i] < min) min = x[i]; return min;} static long minof(long a, long b, long c) {return min(a, min(b, c));} static long minof(long... x) {if(x.length == 1) return x[0]; if(x.length == 2) return min(x[0], x[1]); if(x.length == 3) return min(x[0], min(x[1], x[2])); long min = x[0]; for(int i = 1; i < x.length; ++i) if(x[i] < min) min = x[i]; return min;} static int maxof(int a, int b, int c) {return max(a, max(b, c));} static int maxof(int... x) {if(x.length == 1) return x[0]; if(x.length == 2) return max(x[0], x[1]); if(x.length == 3) return max(x[0], max(x[1], x[2])); int max = x[0]; for(int i = 1; i < x.length; ++i) if(x[i] > max) max = x[i]; return max;} static long maxof(long a, long b, long c) {return max(a, max(b, c));} static long maxof(long... x) {if(x.length == 1) return x[0]; if(x.length == 2) return max(x[0], x[1]); if(x.length == 3) return max(x[0], max(x[1], x[2])); long max = x[0]; for(int i = 1; i < x.length; ++i) if(x[i] > max) max = x[i]; return max;} static int powi(int a, int b) {if(a == 0) return 0; int ans = 1; while(b > 0) {if((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;} static long powl(long a, int b) {if(a == 0) return 0; long ans = 1; while(b > 0) {if((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;} static int fli(double d) {return (int)d;} static int cei(double d) {return (int)ceil(d);} static long fll(double d) {return (long)d;} static long cel(double d) {return (long)ceil(d);} static int gcf(int a, int b) {return b == 0 ? a : gcf(b, a % b);} static long gcf(long a, long b) {return b == 0 ? a : gcf(b, a % b);} static int randInt(int min, int max) {return __rand.nextInt(max - min + 1) + min;} static long hash(long x) {x += 0x9e3779b97f4a7c15L; x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9L; x = (x ^ (x >> 27)) * 0x94d049bb133111ebL; return x ^ (x >> 31);} // array util static void reverse(int[] a) {for(int i = 0, n = a.length, half = n / 2; i < half; ++i) {int swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}} static void reverse(long[] a) {for(int i = 0, n = a.length, half = n / 2; i < half; ++i) {long swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}} static void reverse(char[] a) {for(int i = 0, n = a.length, half = n / 2; i < half; ++i) {char swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}} static void shuffle(int[] a) {int n = a.length - 1; for(int i = 0; i < n; ++i) {int ind = randInt(i, n); int swap = a[i]; a[i] = a[ind]; a[ind] = swap;}} static void shuffle(long[] a) {int n = a.length - 1; for(int i = 0; i < n; ++i) {int ind = randInt(i, n); long swap = a[i]; a[i] = a[ind]; a[ind] = swap;}} static void rsort(int[] a) {shuffle(a); sort(a);} static void rsort(long[] a) {shuffle(a); sort(a);} static int[] copy(int[] a) {int[] ans = new int[a.length]; for(int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;} static long[] copy(long[] a) {long[] ans = new long[a.length]; for(int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;} static char[] copy(char[] a) {char[] ans = new char[a.length]; for(int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;} static int[] sorted(int[] a) {int[] ans = copy(a); sort(ans); return ans;} static long[] sorted(long[] a) {long[] ans = copy(a); sort(ans); return ans;} static int[] rsorted(int[] a) {int[] ans = copy(a); rsort(ans); return ans;} static long[] rsorted(long[] a) {long[] ans = copy(a); rsort(ans); return ans;} // graph util static List<List<Integer>> graph(int n) {List<List<Integer>> g = new ArrayList<>(); for(int i = 0; i < n; ++i) g.add(new ArrayList<>()); return g;} static List<List<Integer>> graph(List<List<Integer>> g, int m) throws IOException {for(int i = 0; i < m; ++i) connect(g, rni() - 1, ni() - 1); return g;} static List<List<Integer>> graph(int n, int m) throws IOException {return graph(graph(n), m);} static List<List<Integer>> dgraph(List<List<Integer>> g, int m) throws IOException {for(int i = 0; i < m; ++i) connecto(g, rni() - 1, ni() - 1); return g;} static List<List<Integer>> dgraph(List<List<Integer>> g, int n, int m) throws IOException {return dgraph(graph(n), m);} static List<Set<Integer>> sgraph(int n) {List<Set<Integer>> g = new ArrayList<>(); for(int i = 0; i < n; ++i) g.add(new HashSet<>()); return g;} static List<Set<Integer>> sgraph(List<Set<Integer>> g, int m) throws IOException {for(int i = 0; i < m; ++i) connect(g, rni() - 1, ni() - 1); return g;} static List<Set<Integer>> sgraph(int n, int m) throws IOException {return sgraph(sgraph(n), m);} static List<Set<Integer>> dsgraph(List<Set<Integer>> g, int m) throws IOException {for(int i = 0; i < m; ++i) connecto(g, rni() - 1, ni() - 1); return g;} static List<Set<Integer>> dsgraph(List<Set<Integer>> g, int n, int m) throws IOException {return dsgraph(sgraph(n), m);} static void connect(List<? extends Collection<Integer>> g, int u, int v) {g.get(u).add(v); g.get(v).add(u);} static void connecto(List<? extends Collection<Integer>> g, int u, int v) {g.get(u).add(v);} static void dconnect(List<? extends Collection<Integer>> g, int u, int v) {g.get(u).remove(v); g.get(v).remove(u);} static void dconnecto(List<? extends Collection<Integer>> g, int u, int v) {g.get(u).remove(v);} // input static void r() throws IOException {input = new StringTokenizer(__in.readLine());} static int ri() throws IOException {return Integer.parseInt(__in.readLine());} static long rl() throws IOException {return Long.parseLong(__in.readLine());} static int[] ria(int n) throws IOException {int[] a = new int[n]; input = new StringTokenizer(__in.readLine()); for(int i = 0; i < n; ++i) a[i] = Integer.parseInt(input.nextToken()); return a;} static int[] riam1(int n) throws IOException {int[] a = new int[n]; input = new StringTokenizer(__in.readLine()); for(int i = 0; i < n; ++i) a[i] = Integer.parseInt(input.nextToken()) - 1; return a;} static long[] rla(int n) throws IOException {long[] a = new long[n]; input = new StringTokenizer(__in.readLine()); for(int i = 0; i < n; ++i) a[i] = Long.parseLong(input.nextToken()); return a;} static char[] rcha() throws IOException {return __in.readLine().toCharArray();} static String rline() throws IOException {return __in.readLine();} static int rni() throws IOException {input = new StringTokenizer(__in.readLine()); return Integer.parseInt(input.nextToken());} static int ni() {return Integer.parseInt(input.nextToken());} static long rnl() throws IOException {input = new StringTokenizer(__in.readLine()); return Long.parseLong(input.nextToken());} static long nl() {return Long.parseLong(input.nextToken());} // output static void pr(int i) {__out.print(i);} static void prln(int i) {__out.println(i);} static void pr(long l) {__out.print(l);} static void prln(long l) {__out.println(l);} static void pr(double d) {__out.print(d);} static void prln(double d) {__out.println(d);} static void pr(char c) {__out.print(c);} static void prln(char c) {__out.println(c);} static void pr(char[] s) {__out.print(new String(s));} static void prln(char[] s) {__out.println(new String(s));} static void pr(String s) {__out.print(s);} static void prln(String s) {__out.println(s);} static void pr(Object o) {__out.print(o);} static void prln(Object o) {__out.println(o);} static void prln() {__out.println();} static void pryes() {__out.println("yes");} static void pry() {__out.println("Yes");} static void prY() {__out.println("YES");} static void prno() {__out.println("no");} static void prn() {__out.println("No");} static void prN() {__out.println("NO");} static void pryesno(boolean b) {__out.println(b ? "yes" : "no");}; static void pryn(boolean b) {__out.println(b ? "Yes" : "No");} static void prYN(boolean b) {__out.println(b ? "YES" : "NO");} static void prln(int... a) {for(int i = 0, len = a.length - 1; i < len; __out.print(a[i]), __out.print(' '), ++i); __out.println(a[a.length - 1]);} static void prln(long... a) {for(int i = 0, len = a.length - 1; i < len; __out.print(a[i]), __out.print(' '), ++i); __out.println(a[a.length - 1]);} static <T> void prln(Collection<T> c) {int n = c.size() - 1; Iterator<T> iter = c.iterator(); for(int i = 0; i < n; __out.print(iter.next()), __out.print(' '), ++i); if(n >= 0) __out.println(iter.next()); else __out.println();} static void h() {__out.println("hlfd");} static void flush() {__out.flush();} static void close() {__out.close();} }
Java
["5\n3 7 9 7 8\n5 2 5 7 5", "5\n1 2 3 4 5\n1 1 1 1 1"]
2 seconds
["6", "0"]
NoteIn the first example, it is possible to find three publications of the second type, which will take 6 seconds.In the second example, all news categories contain a different number of publications.
Java 11
standard input
[ "data structures", "sortings", "greedy" ]
6bceaf308c38d234ba931c13e4f70929
The first line of input consists of single integer $$$n$$$ — the number of news categories ($$$1 \le n \le 200\,000$$$). The second line of input consists of $$$n$$$ integers $$$a_i$$$ — the number of publications of $$$i$$$-th category selected by the batch algorithm ($$$1 \le a_i \le 10^9$$$). The third line of input consists of $$$n$$$ integers $$$t_i$$$ — time it takes for targeted algorithm to find one new publication of category $$$i$$$ ($$$1 \le t_i \le 10^5)$$$.
1,700
Print one integer — the minimal required time for the targeted algorithm to get rid of categories with the same size.
standard output
PASSED
4eba09fbbfe0426b2acd5e6dcdad0f80
train_003.jsonl
1582473900
VK news recommendation system daily selects interesting publications of one of $$$n$$$ disjoint categories for each user. Each publication belongs to exactly one category. For each category $$$i$$$ batch algorithm selects $$$a_i$$$ publications.The latest A/B test suggests that users are reading recommended publications more actively if each category has a different number of publications within daily recommendations. The targeted algorithm can find a single interesting publication of $$$i$$$-th category within $$$t_i$$$ seconds. What is the minimum total time necessary to add publications to the result of batch algorithm execution, so all categories have a different number of publications? You can't remove publications recommended by the batch algorithm.
512 megabytes
import static java.lang.Integer.parseInt; import static java.lang.Long.parseLong; import static java.lang.System.exit; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.PriorityQueue; import java.util.StringTokenizer; public class A { static void sortBy(int a[], int n, int v[]) { if (n == 0) { return; } for (int i = 1; i < n; i++) { int j = i; int ca = a[i]; int cv = v[ca]; do { int nj = (j - 1) >> 1; int na = a[nj]; if (cv <= v[na]) { break; } a[j] = na; j = nj; } while (j != 0); a[j] = ca; } int ca = a[0]; for (int i = n - 1; i > 0; i--) { int j = 0; while ((j << 1) + 2 + Integer.MIN_VALUE < i + Integer.MIN_VALUE) { j <<= 1; j += (v[a[j + 2]] > v[a[j + 1]]) ? 2 : 1; } if ((j << 1) + 2 == i) { j = (j << 1) + 1; } int na = a[i]; a[i] = ca; ca = na; int cv = v[ca]; while (j != 0 && v[a[j]] < cv) { j = (j - 1) >> 1; } while (j != 0) { na = a[j]; a[j] = ca; ca = na; j = (j - 1) >> 1; } } a[0] = ca; } static void solve() throws Exception { int n = scanInt(); int a[] = new int[n], t[] = new int[n], idx[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = scanInt(); idx[i] = i; } for (int i = 0; i < n; i++) { t[i] = scanInt(); } sortBy(idx, n, a); PriorityQueue<Integer> ts = new PriorityQueue<>(); long tsum = 0; int ca = 0; long ans = 0; for (int i: idx) { while (ca < a[i] && !ts.isEmpty()) { int v = ts.remove(); tsum += v; ans += tsum; ++ca; } ca = a[i]; ts.add(-t[i]); tsum += t[i]; } while (!ts.isEmpty()) { int v = ts.remove(); tsum += v; ans += tsum; } out.print(ans); } static int scanInt() throws IOException { return parseInt(scanString()); } static long scanLong() throws IOException { return parseLong(scanString()); } static String scanString() throws IOException { while (tok == null || !tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); } return tok.nextToken(); } static BufferedReader in; static PrintWriter out; static StringTokenizer tok; public static void main(String[] args) { try { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); in.close(); out.close(); } catch (Throwable e) { e.printStackTrace(); exit(1); } } }
Java
["5\n3 7 9 7 8\n5 2 5 7 5", "5\n1 2 3 4 5\n1 1 1 1 1"]
2 seconds
["6", "0"]
NoteIn the first example, it is possible to find three publications of the second type, which will take 6 seconds.In the second example, all news categories contain a different number of publications.
Java 11
standard input
[ "data structures", "sortings", "greedy" ]
6bceaf308c38d234ba931c13e4f70929
The first line of input consists of single integer $$$n$$$ — the number of news categories ($$$1 \le n \le 200\,000$$$). The second line of input consists of $$$n$$$ integers $$$a_i$$$ — the number of publications of $$$i$$$-th category selected by the batch algorithm ($$$1 \le a_i \le 10^9$$$). The third line of input consists of $$$n$$$ integers $$$t_i$$$ — time it takes for targeted algorithm to find one new publication of category $$$i$$$ ($$$1 \le t_i \le 10^5)$$$.
1,700
Print one integer — the minimal required time for the targeted algorithm to get rid of categories with the same size.
standard output
PASSED
e6e8c522ff8cae12bff43a14e780d6da
train_003.jsonl
1582473900
VK news recommendation system daily selects interesting publications of one of $$$n$$$ disjoint categories for each user. Each publication belongs to exactly one category. For each category $$$i$$$ batch algorithm selects $$$a_i$$$ publications.The latest A/B test suggests that users are reading recommended publications more actively if each category has a different number of publications within daily recommendations. The targeted algorithm can find a single interesting publication of $$$i$$$-th category within $$$t_i$$$ seconds. What is the minimum total time necessary to add publications to the result of batch algorithm execution, so all categories have a different number of publications? You can't remove publications recommended by the batch algorithm.
512 megabytes
import java.util.*; public class Recoomendations { public static void main(String[] args) { Scanner s = new Scanner(System.in); int n = s.nextInt(); Topic[] topics = new Topic[n+1]; //Topic[] topics2 = new Topic[n+1]; int[] temp1 = new int[n]; int[] temp2 = new int[n]; for (int i = 0; i < n; i++) { temp1[i] = s.nextInt(); } for (int i = 0; i < n; i++) { temp2[i] = s.nextInt(); } for (int i = 0; i < n; i++) { topics[i] = new Topic(temp1[i], temp2[i], i); } topics[n] = new Topic(2000000000, 10,n+10); Arrays.sort(topics, Topic::compareTo2); //Arrays.sort(topics); long minCost = 0L; long curCost = 0L; SortedSet<Topic> ss = new TreeSet<>(); int curVal = 0; //ss.add(topics[0]); for (int i = 0; i <= n; i++) { if (ss.size() != 0 && topics[i].topics != curVal) { while (ss.size() > 0 && curVal < topics[i].topics) { curCost -= ss.last().cost; minCost += curCost; ss.remove(ss.last()); curVal++; } } ss.add(topics[i]); curVal = topics[i].topics; curCost += topics[i].cost; } System.out.println(minCost); } public static class Topic implements Comparable<Topic> { public int topics; public int cost; private int id; public Topic(int t, int c, int id) { this.topics = t; this.cost = c; this.id = id; } @Override public int compareTo(Topic t) { if (this.cost - t.cost != 0) { return this.cost - t.cost; } else { return this.id- t.id; } } public int compareTo2(Topic t) { int e = this.topics - t.topics; if (e == 0) { if (this.cost - t.cost != 0) { return this.cost - t.cost; } else { return this.id- t.id; } } else { return e; } } } }
Java
["5\n3 7 9 7 8\n5 2 5 7 5", "5\n1 2 3 4 5\n1 1 1 1 1"]
2 seconds
["6", "0"]
NoteIn the first example, it is possible to find three publications of the second type, which will take 6 seconds.In the second example, all news categories contain a different number of publications.
Java 11
standard input
[ "data structures", "sortings", "greedy" ]
6bceaf308c38d234ba931c13e4f70929
The first line of input consists of single integer $$$n$$$ — the number of news categories ($$$1 \le n \le 200\,000$$$). The second line of input consists of $$$n$$$ integers $$$a_i$$$ — the number of publications of $$$i$$$-th category selected by the batch algorithm ($$$1 \le a_i \le 10^9$$$). The third line of input consists of $$$n$$$ integers $$$t_i$$$ — time it takes for targeted algorithm to find one new publication of category $$$i$$$ ($$$1 \le t_i \le 10^5)$$$.
1,700
Print one integer — the minimal required time for the targeted algorithm to get rid of categories with the same size.
standard output
PASSED
0b75f4408ad14ba0a1a0b58704ef9f4f
train_003.jsonl
1582473900
VK news recommendation system daily selects interesting publications of one of $$$n$$$ disjoint categories for each user. Each publication belongs to exactly one category. For each category $$$i$$$ batch algorithm selects $$$a_i$$$ publications.The latest A/B test suggests that users are reading recommended publications more actively if each category has a different number of publications within daily recommendations. The targeted algorithm can find a single interesting publication of $$$i$$$-th category within $$$t_i$$$ seconds. What is the minimum total time necessary to add publications to the result of batch algorithm execution, so all categories have a different number of publications? You can't remove publications recommended by the batch algorithm.
512 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.AbstractMap; import java.util.Arrays; import java.util.Comparator; import java.util.InputMismatchException; import java.util.Map; import java.util.TreeMap; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { static class TaskAdapter implements Runnable { @Override public void run() { long startTime = System.currentTimeMillis(); InputStream inputStream = System.in; OutputStream outputStream = System.out; FastReader in = new FastReader(inputStream); Output out = new Output(outputStream); ARecommendations solver = new ARecommendations(); solver.solve(1, in, out); out.close(); System.err.println(System.currentTimeMillis()-startTime+"ms"); } } public static void main(String[] args) throws Exception { Thread thread = new Thread(null, new TaskAdapter(), "", 1<<28); thread.start(); thread.join(); } static class ARecommendations { public ARecommendations() { } public void solve(int kase, InputReader in, Output pw) { int n = in.nextInt(); int[][] arr = new int[n][2]; for(int j = 0; j<2; j++) { for(int i = 0; i<n; i++) { arr[i][j] = in.nextInt(); } } Arrays.sort(arr, Comparator.comparingInt(o -> o[0])); TreeMap<Integer, Integer> tm = new TreeMap<>(); long ans = 0, sum = 0, cnt = 0; int i = 0, cur = -1; while(i<n||!tm.isEmpty()) { if(tm.isEmpty()) { cur = arr[i][0]; } for(; i<n&&arr[i][0]==cur; i++) { Utilities.add(tm, arr[i][1]); sum += arr[i][1]; } sum -= tm.lastKey(); Utilities.remove(tm, tm.lastKey()); ans += sum; cur++; } ; pw.println(ans); } } static class Utilities { public static <K, V> V getOrDefault(Map<? extends K, ? extends V> map, K key, V value) { V ret = map.get(key); if(ret==null) { return value; } return ret; } public static <T> void add(Map<? super T, Integer> map, T key) { map.put(key, getOrDefault(map, key, 0)+1); } public static <T> void remove(Map<? super T, Integer> map, T key) { int cnt = getOrDefault(map, key, 1)-1; if(cnt>0) { map.put(key, cnt); }else { map.remove(key); } } } static class Output implements Closeable, Flushable { public StringBuilder sb; public OutputStream os; public int BUFFER_SIZE; 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); lineSeparator = System.lineSeparator(); } public void println(long l) { println(String.valueOf(l)); } public void println(String s) { sb.append(s); println(); } 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 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++]; } } static interface InputReader { int nextInt(); } }
Java
["5\n3 7 9 7 8\n5 2 5 7 5", "5\n1 2 3 4 5\n1 1 1 1 1"]
2 seconds
["6", "0"]
NoteIn the first example, it is possible to find three publications of the second type, which will take 6 seconds.In the second example, all news categories contain a different number of publications.
Java 11
standard input
[ "data structures", "sortings", "greedy" ]
6bceaf308c38d234ba931c13e4f70929
The first line of input consists of single integer $$$n$$$ — the number of news categories ($$$1 \le n \le 200\,000$$$). The second line of input consists of $$$n$$$ integers $$$a_i$$$ — the number of publications of $$$i$$$-th category selected by the batch algorithm ($$$1 \le a_i \le 10^9$$$). The third line of input consists of $$$n$$$ integers $$$t_i$$$ — time it takes for targeted algorithm to find one new publication of category $$$i$$$ ($$$1 \le t_i \le 10^5)$$$.
1,700
Print one integer — the minimal required time for the targeted algorithm to get rid of categories with the same size.
standard output
PASSED
2f361d0b0933ef8d02b9da47a6e08207
train_003.jsonl
1582473900
VK news recommendation system daily selects interesting publications of one of $$$n$$$ disjoint categories for each user. Each publication belongs to exactly one category. For each category $$$i$$$ batch algorithm selects $$$a_i$$$ publications.The latest A/B test suggests that users are reading recommended publications more actively if each category has a different number of publications within daily recommendations. The targeted algorithm can find a single interesting publication of $$$i$$$-th category within $$$t_i$$$ seconds. What is the minimum total time necessary to add publications to the result of batch algorithm execution, so all categories have a different number of publications? You can't remove publications recommended by the batch algorithm.
512 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.util.InputMismatchException; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.AbstractMap; import java.util.TreeMap; import java.util.Map; import java.io.Writer; import java.io.OutputStreamWriter; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Rustam Musin (t.me/musin_acm) */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); ARekomendatsii solver = new ARekomendatsii(); solver.solve(1, in, out); out.close(); } static class ARekomendatsii { public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.readInt(); int[] a = in.readIntArray(n); int[] t = in.readIntArray(n); long ans = 0; TreeMap<Integer, List<Integer>> byCount = new TreeMap<>(); for (int i = 0; i < n; i++) { if (!byCount.containsKey(a[i])) byCount.put(a[i], new ArrayList<>()); byCount.get(a[i]).add(i); } TreeMap<Integer, Integer> costToCount = new TreeMap<>(); long activeCost = 0; for (int curCount = byCount.firstKey(); ; curCount++) { if (byCount.containsKey(curCount)) { for (int at : byCount.get(curCount)) { int cost = t[at]; add(costToCount, cost); activeCost += cost; } byCount.remove(curCount); } if (costToCount.isEmpty()) { if (byCount.isEmpty()) break; curCount = byCount.firstKey() - 1; continue; } int maxCost = costToCount.lastKey(); activeCost -= maxCost; rem(costToCount, maxCost); ans += activeCost; } out.print(ans); } void add(Map<Integer, Integer> m, int k) { int was = m.containsKey(k) ? m.get(k) : 0; m.put(k, was + 1); } void rem(Map<Integer, Integer> m, int k) { if (m.get(k) == 1) m.remove(k); else m.put(k, m.get(k) - 1); } } 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(long i) { writer.print(i); } } 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[] readIntArray(int size) { int[] array = new int[size]; for (int i = 0; i < size; i++) { array[i] = readInt(); } return array; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["5\n3 7 9 7 8\n5 2 5 7 5", "5\n1 2 3 4 5\n1 1 1 1 1"]
2 seconds
["6", "0"]
NoteIn the first example, it is possible to find three publications of the second type, which will take 6 seconds.In the second example, all news categories contain a different number of publications.
Java 11
standard input
[ "data structures", "sortings", "greedy" ]
6bceaf308c38d234ba931c13e4f70929
The first line of input consists of single integer $$$n$$$ — the number of news categories ($$$1 \le n \le 200\,000$$$). The second line of input consists of $$$n$$$ integers $$$a_i$$$ — the number of publications of $$$i$$$-th category selected by the batch algorithm ($$$1 \le a_i \le 10^9$$$). The third line of input consists of $$$n$$$ integers $$$t_i$$$ — time it takes for targeted algorithm to find one new publication of category $$$i$$$ ($$$1 \le t_i \le 10^5)$$$.
1,700
Print one integer — the minimal required time for the targeted algorithm to get rid of categories with the same size.
standard output
PASSED
37ca54f93769dbd274ffd959310bf2d2
train_003.jsonl
1582473900
VK news recommendation system daily selects interesting publications of one of $$$n$$$ disjoint categories for each user. Each publication belongs to exactly one category. For each category $$$i$$$ batch algorithm selects $$$a_i$$$ publications.The latest A/B test suggests that users are reading recommended publications more actively if each category has a different number of publications within daily recommendations. The targeted algorithm can find a single interesting publication of $$$i$$$-th category within $$$t_i$$$ seconds. What is the minimum total time necessary to add publications to the result of batch algorithm execution, so all categories have a different number of publications? You can't remove publications recommended by the batch algorithm.
512 megabytes
import java.util.*; import java.io.*; public class Main { static FastReader in=new FastReader(); static StringBuilder Sd=new StringBuilder(); static List<Integer>Gr[]; static long Mod=998244353; static Map<Integer,Integer>map=new HashMap<>(); public static void main(String [] args) { //Dir by MohammedElkady int n=in.nextInt(); int a[]=fillint(n); node[]node=new node[n]; long ans=0L; for(int i=0;i<n;i++){ int t=in.nextInt(); node[i]=(new node(a[i],t)); } Sorting.bucketSort((node),n); for(int i=n-1;i>=0;i--) { int x=node[(i)].x,t=node[i].t; if(!map.containsKey(x)) {map.put(x, x+1);} else { int z=MakeHash(x); int lol=z-1-x; ans+=((long)lol*(long)t); } } Soutln(ans+""); Sclose(); } static int MakeHash(int z) { if(map.containsKey(z)) { int w=map.get(z); w=MakeHash(w); map.put(z, w); return w; } else { map.put(z, z+1); return z+1; } } static long power(long x, long y, long p) { // Initialize result long res = 1; // Update x if it is more than or // equal to p x = x % p; while (y > 0) { // If y is odd, multiply x // with result if (y % 2 == 1) res = (res * x) % p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return res; } // Returns n^(-1) mod p static long modInverse(long n, long p) { return power(n, p-2, p); } // Returns nCr % p using Fermat's // little theorem. static long nCrModPFermat(int n, int r, long p) { // Base case if (r == 0) return 1; // Fill factorial array so that we // can find all factorial of r, n // and n-r long[] fac = new long[n+1]; fac[0] = 1; for (int i = 1 ;i <= n; i++) fac[i] = fac[i-1] * i % p; return (fac[n]* modInverse(fac[r], p) % p * modInverse(fac[n-r], p) % p) % p; } static long fac(int n , int m,int l) { long res=1; for(int i=l,u=1;i<=n||u<=m;i++,u++) { if(i<=n) {res*=i;} if(u<=m) {res/=u;} while(res>Mod) res-=Mod; } return res; } static long posation(int n) { long res=1; for(int i=0;i<n-3;i++) {res*=2L; while(res>Mod) res-=Mod; while(res<=0)res+=Mod;} return res; } static long gcd(long g,long x){ if(x<1)return g; else return gcd(x,g%x); } //array fill static long[]filllong(int n){long a[]=new long[n];for(int i=0;i<n;i++)a[i]=in.nextLong();return a;} static int[]fillint(int n){int a[]=new int[n];for(int i=0;i<n;i++)a[i]=in.nextInt();return a;} //OutPut Line static void Sout(String S) {Sd.append(S);} static void Soutln(String S) {Sd.append(S+"\n");} static void Soutf(String S) {Sd.insert(0, S);} static void Sclose() {System.out.println(Sd);} static void Sclean() {Sd=new StringBuilder();} } class node implements Comparable<node>{ int x,t; node(int x,int p){ this.x=x; this.t=p; } @Override public int compareTo(node o) { return (t-o.t); } } class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } class Sorting{ public static node[] bucketSort(node[] array, int bucketCount) { if (bucketCount <= 0) throw new IllegalArgumentException("Invalid bucket count"); if (array.length <= 1) return array; //trivially sorted int high = array[0].t; int low = array[0].t; for (int i = 1; i < array.length; i++) { //find the range of input elements if (array[i].t > high) high = array[i].t; if (array[i].t < low) low = array[i].t; } double interval = ((double)(high - low + 1))/bucketCount; //range of one bucket ArrayList<node> buckets[] = new ArrayList[bucketCount]; for (int i = 0; i < bucketCount; i++) { //initialize buckets buckets[i] = new ArrayList(); } for (int i = 0; i < array.length; i++) { //partition the input array buckets[(int)((array[i].t - low)/interval)].add(array[i]); } int pointer = 0; for (int i = 0; i < buckets.length; i++) { Collections.sort(buckets[i]); //mergeSort for (int j = 0; j < buckets[i].size(); j++) { //merge the buckets array[pointer] = buckets[i].get(j); pointer++; } } return array; } }
Java
["5\n3 7 9 7 8\n5 2 5 7 5", "5\n1 2 3 4 5\n1 1 1 1 1"]
2 seconds
["6", "0"]
NoteIn the first example, it is possible to find three publications of the second type, which will take 6 seconds.In the second example, all news categories contain a different number of publications.
Java 11
standard input
[ "data structures", "sortings", "greedy" ]
6bceaf308c38d234ba931c13e4f70929
The first line of input consists of single integer $$$n$$$ — the number of news categories ($$$1 \le n \le 200\,000$$$). The second line of input consists of $$$n$$$ integers $$$a_i$$$ — the number of publications of $$$i$$$-th category selected by the batch algorithm ($$$1 \le a_i \le 10^9$$$). The third line of input consists of $$$n$$$ integers $$$t_i$$$ — time it takes for targeted algorithm to find one new publication of category $$$i$$$ ($$$1 \le t_i \le 10^5)$$$.
1,700
Print one integer — the minimal required time for the targeted algorithm to get rid of categories with the same size.
standard output
PASSED
b69a7876a85edc1ff55db2555bb09fec
train_003.jsonl
1582473900
VK news recommendation system daily selects interesting publications of one of $$$n$$$ disjoint categories for each user. Each publication belongs to exactly one category. For each category $$$i$$$ batch algorithm selects $$$a_i$$$ publications.The latest A/B test suggests that users are reading recommended publications more actively if each category has a different number of publications within daily recommendations. The targeted algorithm can find a single interesting publication of $$$i$$$-th category within $$$t_i$$$ seconds. What is the minimum total time necessary to add publications to the result of batch algorithm execution, so all categories have a different number of publications? You can't remove publications recommended by the batch algorithm.
512 megabytes
import java.util.*; /** * Created by Acesine on 3/27/20. */ public class A { Scanner in = new Scanner(System.in); void solve() { int n = in.nextInt(); int[][] c = new int[n][2]; for (int i=0;i<n;i++) c[i][0] = in.nextInt(); for (int i=0;i<n;i++) c[i][1] = in.nextInt(); TreeMap<Integer, List<Integer>> m = new TreeMap<>(); for (int i=0;i<n;i++) { m.computeIfAbsent(c[i][0], k -> new ArrayList<>()).add(c[i][1]); } long sum = 0; PriorityQueue<Integer> t = new PriorityQueue<>(Comparator.reverseOrder()); long ret = 0; final List<Integer> keys = new ArrayList<>(m.keySet()); for (int i = 0; i < keys.size(); i++) { int curr = keys.get(i); // System.out.println(curr + ": " + sum + " : " + ret); for (int a : m.get(curr)) { sum += a; t.add(a); } sum -= t.poll(); if (!t.isEmpty()) { int next = i + 1 < keys.size() ? keys.get(i + 1) : Integer.MAX_VALUE; int tt = Math.min(t.size(), next - curr - 1); for (int x=0;x<tt;x++) { ret += sum; int v = t.poll(); sum -= v; } ret += sum; } } System.out.println(ret); } public static void main(String[] args) { new A().solve(); } }
Java
["5\n3 7 9 7 8\n5 2 5 7 5", "5\n1 2 3 4 5\n1 1 1 1 1"]
2 seconds
["6", "0"]
NoteIn the first example, it is possible to find three publications of the second type, which will take 6 seconds.In the second example, all news categories contain a different number of publications.
Java 11
standard input
[ "data structures", "sortings", "greedy" ]
6bceaf308c38d234ba931c13e4f70929
The first line of input consists of single integer $$$n$$$ — the number of news categories ($$$1 \le n \le 200\,000$$$). The second line of input consists of $$$n$$$ integers $$$a_i$$$ — the number of publications of $$$i$$$-th category selected by the batch algorithm ($$$1 \le a_i \le 10^9$$$). The third line of input consists of $$$n$$$ integers $$$t_i$$$ — time it takes for targeted algorithm to find one new publication of category $$$i$$$ ($$$1 \le t_i \le 10^5)$$$.
1,700
Print one integer — the minimal required time for the targeted algorithm to get rid of categories with the same size.
standard output
PASSED
743fbf5398536d96a4a481d46f0a1532
train_003.jsonl
1582473900
VK news recommendation system daily selects interesting publications of one of $$$n$$$ disjoint categories for each user. Each publication belongs to exactly one category. For each category $$$i$$$ batch algorithm selects $$$a_i$$$ publications.The latest A/B test suggests that users are reading recommended publications more actively if each category has a different number of publications within daily recommendations. The targeted algorithm can find a single interesting publication of $$$i$$$-th category within $$$t_i$$$ seconds. What is the minimum total time necessary to add publications to the result of batch algorithm execution, so all categories have a different number of publications? You can't remove publications recommended by the batch algorithm.
512 megabytes
import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.Reader; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.PriorityQueue; import java.util.StringTokenizer; public class C1310A { public static void main(String[] args) { var scanner = new BufferedScanner(); var writer = new PrintWriter(new BufferedOutputStream(System.out)); var n = scanner.nextInt(); var a = new int[n]; for (int i = 0; i < n; i++) { a[i] = scanner.nextInt(); // a[i] = (int) (Math.random() * n / 2 + 1); // System.out.print(a[i] + " "); } // System.out.println(); var t = new int[n]; for (int i = 0; i < n; i++) { t[i] = scanner.nextInt(); // t[i] = (int) (Math.random() * n / 2 + 1); // System.out.print(t[i] + " "); } // System.out.println(); // var ans = wrongSolve(n, a, t); // var ans1 = wrongSolve1(n, a, t); // var ansBf = bf(n, a, t); // var ans2 = solve2(n, a, t); // if (ans != ans1 || ans != ansBf || ans != ans2) { // throw new RuntimeException("diff: " + ans + " " + ans1 + " " + ansBf + " " + ans2); // } writer.println(solve2(n, a, t)); scanner.close(); writer.flush(); writer.close(); } private static long wrongSolve(int n, int[] a, int[] t) { var order = new ArrayList<Integer>(); for (int i = 0; i < n; i++) { order.add(i); } order.sort(Comparator.comparingInt(o -> a[(int) o]).thenComparingInt(o -> t[(int) o])); var backlog = new PriorityQueue<Integer>(Comparator.comparingInt(o -> t[(int) o]).reversed()); var x = a[order.get(0)]; var oIndex = 0; var ans = 0L; while (oIndex < order.size() || backlog.size() > 0) { // System.out.println(x); var nextA = oIndex < order.size() ? a[order.get(oIndex)] : Integer.MAX_VALUE; if (x == nextA) { while (oIndex + 1 < order.size() && a[order.get(oIndex + 1)] == x) { backlog.add(order.get(oIndex)); oIndex++; } x++; oIndex++; } else { // x < nextA while (x < nextA && backlog.size() > 0) { var i = backlog.poll(); ans += (long) t[i] * (x - a[i]); x++; } x = nextA; // backlog可能先空了还没到nextA } } return ans; } private static long wrongSolve1(int n, int[] a, int[] t) { var byA = new HashMap<Integer, List<Integer>>(); for (int i = 0; i < n; i++) { byA.putIfAbsent(a[i], new ArrayList<>()); byA.get(a[i]).add(i); } // if (n == 200000) { // for (Map.Entry<Integer, List<Integer>> entry : byA.entrySet()) { // System.out.println(entry.getKey() + " " + entry.getValue().size()); // } // } var toChange = new ArrayList<Integer>(); var ans = 0L; for (var value : byA.values()) { value.sort(Comparator.comparingInt(o -> t[o])); for (int i = 0; i + 1 < value.size(); i++) { toChange.add(value.get(i)); ans -= (long) t[value.get(i)] * a[value.get(i)]; } } toChange.sort(Comparator.comparingInt(o -> a[o])); // x递增,找需要改变的a[i]<x中t[i]最大的。 var xs = new ArrayList<>(byA.keySet()); xs.add(Integer.MAX_VALUE); xs.sort(Integer::compareTo); var backlog = new PriorityQueue<Integer>(Comparator.comparingInt(o -> t[(int) o]).reversed()); var toChangeIndex = 0; var move = new HashMap<Integer, Integer>(); for (int i = 0; i + 1 < xs.size(); i++) { var gapFrom = xs.get(i) + 1; var gapTo = xs.get(i + 1) - 1; for (int x = gapFrom; x <= gapTo; x++) { while (toChangeIndex < toChange.size() && a[toChange.get(toChangeIndex)] < x) { backlog.add(toChange.get(toChangeIndex)); toChangeIndex++; } // System.out.println("backlog: " + backlog.size()); if (backlog.isEmpty()) { break; } var j = backlog.poll(); move.put(j, x); ans += (long) t[j] * x; // System.out.println("x: " + x); } } if (!backlog.isEmpty()) { throw new RuntimeException("backlog is not empty!!!"); } // if (!swapCheck(n, a, t, move)) { // throw new RuntimeException("swap check failed!!"); // } return ans; } private static long solve2(int n, int[] a, int[] t) { var order = new ArrayList<Integer>(); for (int i = 0; i < n; i++) { order.add(i); } order.sort(Comparator.comparingInt(o -> a[o])); var ans = 0L; var xs = Arrays.stream(a).distinct().sorted().toArray(); var backlog = new PriorityQueue<Integer>( Comparator.comparingInt(o -> t[(int) o]).reversed().thenComparingInt(o -> a[(int) o])); var orderIndex = 0; var move = new HashMap<Integer, Integer>(); for (int i = 0; i < xs.length; i++) { // 先把a[j]==xs[i]的都加到backlog里面一起选 while (orderIndex < order.size() && a[order.get(orderIndex)] <= xs[i]) { backlog.add(order.get(orderIndex++)); } var from = xs[i]; var to = i + 1 < xs.length ? xs[i + 1] - 1 : Integer.MAX_VALUE; for (int x = from; x <= to; x++) { if (backlog.isEmpty()) { break; } var j = backlog.poll(); move.put(j, x); ans += (long) t[j] * (x - a[j]); } } if (!backlog.isEmpty()) { throw new RuntimeException("backlog is not empty!!!"); } // if (!swapCheck(n, a, t, move)) { // throw new RuntimeException("swap check failed!!"); // } return ans; } private static long bf(int n, int[] a, int[] t) { var work = new int[n]; System.arraycopy(a, 0, work, 0, n); var left = new HashSet<Integer>(); for (int i = 0; i < n; i++) { left.add(i); } var ans = 0L; while (left.size() > 0) { var it = left.iterator(); var minAWithMaxT = (int) it.next(); while (it.hasNext()) { var i = it.next(); if (work[i] < work[minAWithMaxT] || work[i] == work[minAWithMaxT] && t[i] > t[minAWithMaxT]) { minAWithMaxT = i; } } for (var each : left) { if (each != minAWithMaxT && work[each] == work[minAWithMaxT]) { work[each]++; ans += t[each]; } } left.remove(minAWithMaxT); } return ans; } private static boolean swapCheck(int n, int[] a, int[] t, Map<Integer, Integer> move) { for (int i = 0; i < n; i++) { if (!move.containsKey(i)) { move.put(i, i); } for (int j = i + 1; j < n; j++) { if (!move.containsKey(j)) { move.put(j, j); } if (a[j] < move.get(i) && a[i] < move.get(j) && (move.get(i) < move.get(j) && t[i] < t[j] || move.get(i) > move.get(j) && t[i] > t[j])) { return false; } } } return true; } public static class BufferedScanner { BufferedReader br; StringTokenizer st; public BufferedScanner(Reader reader) { br = new BufferedReader(reader); } public BufferedScanner() { this(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } void close() { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } } static long gcd(long a, long b) { if (a < b) { return gcd(b, a); } while (b > 0) { long tmp = b; b = a % b; a = tmp; } return a; } static long inverse(long a, long m) { long[] ans = extgcd(a, m); return ans[0] == 1 ? (ans[1] + m) % m : -1; } private static long[] extgcd(long a, long m) { if (m == 0) { return new long[]{a, 1, 0}; } else { long[] ans = extgcd(m, a % m); long tmp = ans[1]; ans[1] = ans[2]; ans[2] = tmp; ans[2] -= ans[1] * (a / m); return ans; } } private static List<Integer> primes(double upperBound) { var limit = (int) Math.sqrt(upperBound); var isComposite = new boolean[limit + 1]; var primes = new ArrayList<Integer>(); for (int i = 2; i <= limit; i++) { if (isComposite[i]) { continue; } primes.add(i); int j = i + i; while (j <= limit) { isComposite[j] = true; j += i; } } return primes; } }
Java
["5\n3 7 9 7 8\n5 2 5 7 5", "5\n1 2 3 4 5\n1 1 1 1 1"]
2 seconds
["6", "0"]
NoteIn the first example, it is possible to find three publications of the second type, which will take 6 seconds.In the second example, all news categories contain a different number of publications.
Java 11
standard input
[ "data structures", "sortings", "greedy" ]
6bceaf308c38d234ba931c13e4f70929
The first line of input consists of single integer $$$n$$$ — the number of news categories ($$$1 \le n \le 200\,000$$$). The second line of input consists of $$$n$$$ integers $$$a_i$$$ — the number of publications of $$$i$$$-th category selected by the batch algorithm ($$$1 \le a_i \le 10^9$$$). The third line of input consists of $$$n$$$ integers $$$t_i$$$ — time it takes for targeted algorithm to find one new publication of category $$$i$$$ ($$$1 \le t_i \le 10^5)$$$.
1,700
Print one integer — the minimal required time for the targeted algorithm to get rid of categories with the same size.
standard output
PASSED
7acc6e9db4c194ae4104df3f85bd820c
train_003.jsonl
1513091100
Vova is again playing some computer game, now an RPG. In the game Vova's character received a quest: to slay the fearsome monster called Modcrab.After two hours of playing the game Vova has tracked the monster and analyzed its tactics. The Modcrab has h2 health points and an attack power of a2. Knowing that, Vova has decided to buy a lot of strong healing potions and to prepare for battle.Vova's character has h1 health points and an attack power of a1. Also he has a large supply of healing potions, each of which increases his current amount of health points by c1 when Vova drinks a potion. All potions are identical to each other. It is guaranteed that c1 &gt; a2.The battle consists of multiple phases. In the beginning of each phase, Vova can either attack the monster (thus reducing its health by a1) or drink a healing potion (it increases Vova's health by c1; Vova's health can exceed h1). Then, if the battle is not over yet, the Modcrab attacks Vova, reducing his health by a2. The battle ends when Vova's (or Modcrab's) health drops to 0 or lower. It is possible that the battle ends in a middle of a phase after Vova's attack.Of course, Vova wants to win the fight. But also he wants to do it as fast as possible. So he wants to make up a strategy that will allow him to win the fight after the minimum possible number of phases.Help Vova to make up a strategy! You may assume that Vova never runs out of healing potions, and that he can always win.
256 megabytes
import java.util.*; import java.io.*; import java.math.*; public class Main { public static void process()throws IOException { int h1=ni(),a1=ni(),c1=ni(),cnt=0; int h2=ni(),a2=ni(); StringBuilder res=new StringBuilder(); while(h2>0){ if(h2-a1<=0){ res.append("STRIKE\n"); h2-=a1; h1-=a2; } else if(h1-a2<=0){ res.append("HEAL\n"); h1+=c1; h1-=a2; } else{ res.append("STRIKE\n"); h2-=a1; h1-=a2; } cnt++; } pn(cnt+"\n"+res); } static FastReader sc; static PrintWriter out; public static void main(String[]args)throws IOException { out = new PrintWriter(System.out); sc=new FastReader(); long s = System.currentTimeMillis(); int t=1; //t=ni(); while(t-->0) process(); out.flush(); //System.err.println(System.currentTimeMillis()-s+"ms"); } static void pn(Object o){out.println(o);} static void p(Object o){out.print(o);} static int ni()throws IOException{return Integer.parseInt(sc.next());} static long nl()throws IOException{return Long.parseLong(sc.next());} static double nd()throws IOException{return Double.parseDouble(sc.next());} static String nln()throws IOException{return sc.nextLine();} static long gcd(long a, long b)throws IOException{return (b==0)?a:gcd(b,a%b);} static int gcd(int a, int b)throws IOException{return (b==0)?a:gcd(b,a%b);} static int bit(long n)throws IOException{return (n==0)?0:(1+bit(n&(n-1)));} static long mod=(long)1e9+7l; static<T> void r_sort(T arr[],int n){ Random r = new Random(); for (int i = n-1; i > 0; i--){ int j = r.nextInt(i+1); T temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } Arrays.sort(arr); } ///////////////////////////////////////////////////////////////////////////////////////////////////////// static class FastReader{ BufferedReader br; StringTokenizer st; public FastReader(){ br = new BufferedReader(new InputStreamReader(System.in)); } String next(){ while (st == null || !st.hasMoreElements()){ try{ st = new StringTokenizer(br.readLine()); } catch (IOException e){ e.printStackTrace(); } } return st.nextToken(); } String nextLine(){ String str = ""; try{ str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } ///////////////////////////////////////////////////////////////////////////////////////////////////////////// }
Java
["10 6 100\n17 5", "11 6 100\n12 5"]
1 second
["4\nSTRIKE\nHEAL\nSTRIKE\nSTRIKE", "2\nSTRIKE\nSTRIKE"]
NoteIn the first example Vova's character must heal before or after his first attack. Otherwise his health will drop to zero in 2 phases while he needs 3 strikes to win.In the second example no healing needed, two strikes are enough to get monster to zero health and win with 6 health left.
Java 11
standard input
[ "implementation", "greedy" ]
d497431eb37fafdf211309da8740ece6
The first line contains three integers h1, a1, c1 (1 ≤ h1, a1 ≤ 100, 2 ≤ c1 ≤ 100) — Vova's health, Vova's attack power and the healing power of a potion. The second line contains two integers h2, a2 (1 ≤ h2 ≤ 100, 1 ≤ a2 &lt; c1) — the Modcrab's health and his attack power.
1,200
In the first line print one integer n denoting the minimum number of phases required to win the battle. Then print n lines. i-th line must be equal to HEAL if Vova drinks a potion in i-th phase, or STRIKE if he attacks the Modcrab. The strategy must be valid: Vova's character must not be defeated before slaying the Modcrab, and the monster's health must be 0 or lower after Vova's last action. If there are multiple optimal solutions, print any of them.
standard output
PASSED
fda9abb303755d6a20cc8246a85af5b2
train_003.jsonl
1513091100
Vova is again playing some computer game, now an RPG. In the game Vova's character received a quest: to slay the fearsome monster called Modcrab.After two hours of playing the game Vova has tracked the monster and analyzed its tactics. The Modcrab has h2 health points and an attack power of a2. Knowing that, Vova has decided to buy a lot of strong healing potions and to prepare for battle.Vova's character has h1 health points and an attack power of a1. Also he has a large supply of healing potions, each of which increases his current amount of health points by c1 when Vova drinks a potion. All potions are identical to each other. It is guaranteed that c1 &gt; a2.The battle consists of multiple phases. In the beginning of each phase, Vova can either attack the monster (thus reducing its health by a1) or drink a healing potion (it increases Vova's health by c1; Vova's health can exceed h1). Then, if the battle is not over yet, the Modcrab attacks Vova, reducing his health by a2. The battle ends when Vova's (or Modcrab's) health drops to 0 or lower. It is possible that the battle ends in a middle of a phase after Vova's attack.Of course, Vova wants to win the fight. But also he wants to do it as fast as possible. So he wants to make up a strategy that will allow him to win the fight after the minimum possible number of phases.Help Vova to make up a strategy! You may assume that Vova never runs out of healing potions, and that he can always win.
256 megabytes
import java.util.Iterator; import java.util.Scanner; import java.util.Vector; /* * 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. */ /** * * @author MDTus */ public class CF_903B { public static void main(String[] args) { Scanner input = new Scanner(System.in); int h1=input.nextInt(); int a1=input.nextInt(); int c1=input.nextInt(); int h2=input.nextInt(); int a2=input.nextInt(); Vector v = new Vector(); while(true) { if(h1-a2<=0 && h2-a1>0){ v.add("HEAL"); h1+=c1; h1-=a2; }else{ v.add("STRIKE"); h2-=a1; h1-=a2; } if(h2<=0) break; } System.out.println(v.size()); Iterator it = v.iterator(); while(it.hasNext()){ System.out.println(it.next()); } } }
Java
["10 6 100\n17 5", "11 6 100\n12 5"]
1 second
["4\nSTRIKE\nHEAL\nSTRIKE\nSTRIKE", "2\nSTRIKE\nSTRIKE"]
NoteIn the first example Vova's character must heal before or after his first attack. Otherwise his health will drop to zero in 2 phases while he needs 3 strikes to win.In the second example no healing needed, two strikes are enough to get monster to zero health and win with 6 health left.
Java 11
standard input
[ "implementation", "greedy" ]
d497431eb37fafdf211309da8740ece6
The first line contains three integers h1, a1, c1 (1 ≤ h1, a1 ≤ 100, 2 ≤ c1 ≤ 100) — Vova's health, Vova's attack power and the healing power of a potion. The second line contains two integers h2, a2 (1 ≤ h2 ≤ 100, 1 ≤ a2 &lt; c1) — the Modcrab's health and his attack power.
1,200
In the first line print one integer n denoting the minimum number of phases required to win the battle. Then print n lines. i-th line must be equal to HEAL if Vova drinks a potion in i-th phase, or STRIKE if he attacks the Modcrab. The strategy must be valid: Vova's character must not be defeated before slaying the Modcrab, and the monster's health must be 0 or lower after Vova's last action. If there are multiple optimal solutions, print any of them.
standard output
PASSED
277eb301fae6203e5e2f0e838c19a907
train_003.jsonl
1513091100
Vova is again playing some computer game, now an RPG. In the game Vova's character received a quest: to slay the fearsome monster called Modcrab.After two hours of playing the game Vova has tracked the monster and analyzed its tactics. The Modcrab has h2 health points and an attack power of a2. Knowing that, Vova has decided to buy a lot of strong healing potions and to prepare for battle.Vova's character has h1 health points and an attack power of a1. Also he has a large supply of healing potions, each of which increases his current amount of health points by c1 when Vova drinks a potion. All potions are identical to each other. It is guaranteed that c1 &gt; a2.The battle consists of multiple phases. In the beginning of each phase, Vova can either attack the monster (thus reducing its health by a1) or drink a healing potion (it increases Vova's health by c1; Vova's health can exceed h1). Then, if the battle is not over yet, the Modcrab attacks Vova, reducing his health by a2. The battle ends when Vova's (or Modcrab's) health drops to 0 or lower. It is possible that the battle ends in a middle of a phase after Vova's attack.Of course, Vova wants to win the fight. But also he wants to do it as fast as possible. So he wants to make up a strategy that will allow him to win the fight after the minimum possible number of phases.Help Vova to make up a strategy! You may assume that Vova never runs out of healing potions, and that he can always win.
256 megabytes
import java.util.*; import java.io.*; import java.math.*; public class Main { static PrintWriter out = new PrintWriter(System.out); static Reader in = new Reader(); public static void main(String[] args) throws IOException { Main solver = new Main(); solver.solve(); out.flush(); out.close(); } static int INF = (int)1e9; static int maxn = (int)1e5+5; static int mod = 998244353; static int n,m,q,k,t; void solve() throws IOException{ int h1 = in.nextInt(), a1 = in.nextInt(), c1 = in.nextInt(), h2 = in.nextInt(), a2 = in.nextInt(); StringBuilder ans = new StringBuilder(""); int cnt = 0; while (h2 > 0) { if (h2 <= a1) { ans.append("STRIKE\n"); cnt++; break; } if (h1 <= a2) { ans.append("HEAL\n"); h1 += c1-a2; } else { ans.append("STRIKE\n"); h2 -= a1; h1 -= a2; } cnt++; } out.println(cnt); out.println(ans); } //<> static class Reader { private InputStream mIs; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public Reader() { this(System.in); } public Reader(InputStream is) { mIs = is; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = mIs.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public String nextLine() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public String next() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } double nextDouble() { return Double.parseDouble(next()); } public long nextLong() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } } }
Java
["10 6 100\n17 5", "11 6 100\n12 5"]
1 second
["4\nSTRIKE\nHEAL\nSTRIKE\nSTRIKE", "2\nSTRIKE\nSTRIKE"]
NoteIn the first example Vova's character must heal before or after his first attack. Otherwise his health will drop to zero in 2 phases while he needs 3 strikes to win.In the second example no healing needed, two strikes are enough to get monster to zero health and win with 6 health left.
Java 11
standard input
[ "implementation", "greedy" ]
d497431eb37fafdf211309da8740ece6
The first line contains three integers h1, a1, c1 (1 ≤ h1, a1 ≤ 100, 2 ≤ c1 ≤ 100) — Vova's health, Vova's attack power and the healing power of a potion. The second line contains two integers h2, a2 (1 ≤ h2 ≤ 100, 1 ≤ a2 &lt; c1) — the Modcrab's health and his attack power.
1,200
In the first line print one integer n denoting the minimum number of phases required to win the battle. Then print n lines. i-th line must be equal to HEAL if Vova drinks a potion in i-th phase, or STRIKE if he attacks the Modcrab. The strategy must be valid: Vova's character must not be defeated before slaying the Modcrab, and the monster's health must be 0 or lower after Vova's last action. If there are multiple optimal solutions, print any of them.
standard output
PASSED
a6492f741d22e8e07039a3a13015e8bf
train_003.jsonl
1513091100
Vova is again playing some computer game, now an RPG. In the game Vova's character received a quest: to slay the fearsome monster called Modcrab.After two hours of playing the game Vova has tracked the monster and analyzed its tactics. The Modcrab has h2 health points and an attack power of a2. Knowing that, Vova has decided to buy a lot of strong healing potions and to prepare for battle.Vova's character has h1 health points and an attack power of a1. Also he has a large supply of healing potions, each of which increases his current amount of health points by c1 when Vova drinks a potion. All potions are identical to each other. It is guaranteed that c1 &gt; a2.The battle consists of multiple phases. In the beginning of each phase, Vova can either attack the monster (thus reducing its health by a1) or drink a healing potion (it increases Vova's health by c1; Vova's health can exceed h1). Then, if the battle is not over yet, the Modcrab attacks Vova, reducing his health by a2. The battle ends when Vova's (or Modcrab's) health drops to 0 or lower. It is possible that the battle ends in a middle of a phase after Vova's attack.Of course, Vova wants to win the fight. But also he wants to do it as fast as possible. So he wants to make up a strategy that will allow him to win the fight after the minimum possible number of phases.Help Vova to make up a strategy! You may assume that Vova never runs out of healing potions, and that he can always win.
256 megabytes
import java.math.BigInteger; import java.util.*; import java.io.*; public class solution { 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 long gcd(long a, long b) { if (b == 0) { return a; } else return gcd(b, a % b); } static class pair { int x; int y; public pair(int x, int y) { this.x = x; this.y = y; } } public static long lcm(long a, long b) { long v = a * b; long u = gcd(a, b); return v / u; } public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); int h1 = Integer.parseInt(st.nextToken()); int a1 = Integer.parseInt(st.nextToken()); int c1 = Integer.parseInt(st.nextToken()); st = new StringTokenizer(br.readLine()); int h2 = Integer.parseInt(st.nextToken()); int a2 = Integer.parseInt(st.nextToken()); ArrayList<String>A = new ArrayList<>(); while(true){ if(a1>=h2){ A.add("STRIKE"); break; } else if(h1<=a2){ A.add("HEAL"); h1+=c1; h1-=a2; } else{ A.add("STRIKE"); h2-=a1; h1-=a2; } } System.out.println(A.size());{ for(int i=0;i<A.size();i++){ System.out.println(A.get(i)); } } } static class sort implements Comparator<ArrayList<Integer>> { @Override public int compare(ArrayList<Integer> o1, ArrayList<Integer> o2) { int c = o1.get(0).compareTo(o2.get(0)); return c; } } }
Java
["10 6 100\n17 5", "11 6 100\n12 5"]
1 second
["4\nSTRIKE\nHEAL\nSTRIKE\nSTRIKE", "2\nSTRIKE\nSTRIKE"]
NoteIn the first example Vova's character must heal before or after his first attack. Otherwise his health will drop to zero in 2 phases while he needs 3 strikes to win.In the second example no healing needed, two strikes are enough to get monster to zero health and win with 6 health left.
Java 11
standard input
[ "implementation", "greedy" ]
d497431eb37fafdf211309da8740ece6
The first line contains three integers h1, a1, c1 (1 ≤ h1, a1 ≤ 100, 2 ≤ c1 ≤ 100) — Vova's health, Vova's attack power and the healing power of a potion. The second line contains two integers h2, a2 (1 ≤ h2 ≤ 100, 1 ≤ a2 &lt; c1) — the Modcrab's health and his attack power.
1,200
In the first line print one integer n denoting the minimum number of phases required to win the battle. Then print n lines. i-th line must be equal to HEAL if Vova drinks a potion in i-th phase, or STRIKE if he attacks the Modcrab. The strategy must be valid: Vova's character must not be defeated before slaying the Modcrab, and the monster's health must be 0 or lower after Vova's last action. If there are multiple optimal solutions, print any of them.
standard output
PASSED
8d03c896067f4226df7432d16976ef14
train_003.jsonl
1513091100
Vova is again playing some computer game, now an RPG. In the game Vova's character received a quest: to slay the fearsome monster called Modcrab.After two hours of playing the game Vova has tracked the monster and analyzed its tactics. The Modcrab has h2 health points and an attack power of a2. Knowing that, Vova has decided to buy a lot of strong healing potions and to prepare for battle.Vova's character has h1 health points and an attack power of a1. Also he has a large supply of healing potions, each of which increases his current amount of health points by c1 when Vova drinks a potion. All potions are identical to each other. It is guaranteed that c1 &gt; a2.The battle consists of multiple phases. In the beginning of each phase, Vova can either attack the monster (thus reducing its health by a1) or drink a healing potion (it increases Vova's health by c1; Vova's health can exceed h1). Then, if the battle is not over yet, the Modcrab attacks Vova, reducing his health by a2. The battle ends when Vova's (or Modcrab's) health drops to 0 or lower. It is possible that the battle ends in a middle of a phase after Vova's attack.Of course, Vova wants to win the fight. But also he wants to do it as fast as possible. So he wants to make up a strategy that will allow him to win the fight after the minimum possible number of phases.Help Vova to make up a strategy! You may assume that Vova never runs out of healing potions, and that he can always win.
256 megabytes
import java.util.*; public class Solution{ static int count = 0; static void solve(int ah,int aat,int apo,int bh,int ba) { while(bh>0) { if(aat>=bh) { count++; break; } if(ah<=ba) { ah+=apo; count++; ah-=ba; }else{ bh-=aat; ah-=ba; count++; } } } static void solv(int ah,int aat,int apo,int bh,int ba) { while(bh>0) { if(aat>=bh) { System.out.println("STRIKE"); break; } if(ah<=ba) { ah+=apo; ah-=ba; System.out.println("HEAL"); }else{ bh-=aat; ah-=ba; System.out.println("STRIKE"); } } } public static void main(String[] args) { Scanner sc = new Scanner(System.in); int hl = sc.nextInt(); int at = sc.nextInt(); int po = sc.nextInt(); int h = sc.nextInt(); int a = sc.nextInt(); solve(hl,at,po,h,a); System.out.println(count); solv(hl,at,po,h,a); } }
Java
["10 6 100\n17 5", "11 6 100\n12 5"]
1 second
["4\nSTRIKE\nHEAL\nSTRIKE\nSTRIKE", "2\nSTRIKE\nSTRIKE"]
NoteIn the first example Vova's character must heal before or after his first attack. Otherwise his health will drop to zero in 2 phases while he needs 3 strikes to win.In the second example no healing needed, two strikes are enough to get monster to zero health and win with 6 health left.
Java 11
standard input
[ "implementation", "greedy" ]
d497431eb37fafdf211309da8740ece6
The first line contains three integers h1, a1, c1 (1 ≤ h1, a1 ≤ 100, 2 ≤ c1 ≤ 100) — Vova's health, Vova's attack power and the healing power of a potion. The second line contains two integers h2, a2 (1 ≤ h2 ≤ 100, 1 ≤ a2 &lt; c1) — the Modcrab's health and his attack power.
1,200
In the first line print one integer n denoting the minimum number of phases required to win the battle. Then print n lines. i-th line must be equal to HEAL if Vova drinks a potion in i-th phase, or STRIKE if he attacks the Modcrab. The strategy must be valid: Vova's character must not be defeated before slaying the Modcrab, and the monster's health must be 0 or lower after Vova's last action. If there are multiple optimal solutions, print any of them.
standard output
PASSED
006f3f148f15e73583c85b5f84bd4ed0
train_003.jsonl
1513091100
Vova is again playing some computer game, now an RPG. In the game Vova's character received a quest: to slay the fearsome monster called Modcrab.After two hours of playing the game Vova has tracked the monster and analyzed its tactics. The Modcrab has h2 health points and an attack power of a2. Knowing that, Vova has decided to buy a lot of strong healing potions and to prepare for battle.Vova's character has h1 health points and an attack power of a1. Also he has a large supply of healing potions, each of which increases his current amount of health points by c1 when Vova drinks a potion. All potions are identical to each other. It is guaranteed that c1 &gt; a2.The battle consists of multiple phases. In the beginning of each phase, Vova can either attack the monster (thus reducing its health by a1) or drink a healing potion (it increases Vova's health by c1; Vova's health can exceed h1). Then, if the battle is not over yet, the Modcrab attacks Vova, reducing his health by a2. The battle ends when Vova's (or Modcrab's) health drops to 0 or lower. It is possible that the battle ends in a middle of a phase after Vova's attack.Of course, Vova wants to win the fight. But also he wants to do it as fast as possible. So he wants to make up a strategy that will allow him to win the fight after the minimum possible number of phases.Help Vova to make up a strategy! You may assume that Vova never runs out of healing potions, and that he can always win.
256 megabytes
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.PriorityQueue; import java.util.Scanner; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.TreeSet; import java.util.concurrent.ConcurrentHashMap; public class Main { static ArrayList<Integer> adj[]; static PrintWriter out = new PrintWriter(System.out); public static long mod; static int [][]notmemo; static int k; static long[] a; static long b[]; static int m; static char c[]; static class Pair implements Comparable<Pair>{ long a; int b; int node; public Pair(long level,int b1,int n) { a=level; b=b1; node=n; } @Override public int compareTo(Pair o) { if(this.a==o.a) return b-o.b; return Long.compare(o.a,a); } } static Pair s1[]; static long s[]; static ArrayList<Pair> adjlist[]; static int n1; static int n2; static int k1; static int k2; static int skip=0; public static void main(String args[]) throws IOException { Scanner sc = new Scanner(System.in); int h1=sc.nextInt(); int a1=sc.nextInt(); int c1=sc.nextInt(); int h2=sc.nextInt(); int a2=sc.nextInt(); boolean f=true; StringBuilder sb=new StringBuilder(); int turns=0; while(true) { if(f) { turns++; if(h1-a2<=0&&h2-a1>0) { sb.append("HEAL"); sb.append("\n"); h1+=c1; } else { sb.append("STRIKE"); sb.append("\n"); h2-=a1; } } else { h1-=a2; } if(h2<=0) { break; } f=!f; } System.out.println(turns); System.out.println(sb); } private static long lcm(long a2, long b2) { return (a2*b2)/gcd(a2,b2); } static Boolean zero[][]; static int small[]; static void dfs(int s, int e) { small[s] = 1; for(int u: adj[s]) { if(u == e) continue; dfs(u ,s); small[s] +=small[u]; } } static int idx=0; static long dpdp[][][][]; static int modd=(int) 1e8; static class Edge implements Comparable<Edge> { int node;long cost; Edge(int a, long b) { node = a; cost = b; } public int compareTo(Edge e){ return Long.compare(cost,e.cost); } } static void sieve(int N) // O(N log log N) { isComposite = new int[N+1]; isComposite[0] = isComposite[1] = 1; // 0 indicates a prime number primes = new ArrayList<Integer>(); for (int i = 2; i <= N; ++i) //can loop till i*i <= N if primes array is not needed O(N log log sqrt(N)) if (isComposite[i] == 0) //can loop in 2 and odd integers for slightly better performance { primes.add(i); if(1l * i * i <= N) for (int j = i * i; j <= N; j += i) // j = i * 2 will not affect performance too much, may alter in modified sieve isComposite[j] = 1; } } static TreeSet<Integer> factors; static ArrayList<Integer> primeFactors(int N) // O(sqrt(N) / ln sqrt(N)) { ArrayList<Integer> factors = new ArrayList<Integer>(); //take abs(N) in case of -ve integers int idx = 0, p = primes.get(idx); while(1l*p * p <= N) { while(N % p == 0) { factors.add(p); N /= p; } p = primes.get(++idx); } if(N != 1) // last prime factor may be > sqrt(N) factors.add(N); // for integers whose largest prime factor has a power of 1 return factors; } static String y; static int nomnom[]; static long fac[]; static class book implements Comparable<book> { int idx; long score; public book(int i, long s) { idx = i; score = s; } public int compareTo(book o) { return (int) (o.score - score); } } static class library implements Comparable<library> { int numofbooks; int signup; int shiprate; int idx; public library(int a, int b, int c, int idx) { numofbooks = a; signup = b; shiprate = c; this.idx = idx; } @Override public int compareTo(library o) { if(signup==o.signup) { return o.numofbooks-numofbooks; } return signup - o.signup; } } static boolean isOn(int S, int j) { return (S & 1 << j) != 0; } static boolean f = true; static class SegmentTree { // 1-based DS, OOP int N; // the number of elements in the array as a power of 2 (i.e. after padding) int[] array, sTree, lazy; SegmentTree(int[] in) { array = in; N = in.length - 1; sTree = new int[N << 1]; // no. of nodes = 2*N - 1, we add one to cross out index zero lazy = new int[N << 1]; //build(1, 1, N); } void build(int node, int b, int e) // O(n) { if (b == e) sTree[node] = array[b]; else { int mid = b + e >> 1; build(node << 1, b, mid); build(node << 1 | 1, mid + 1, e); sTree[node] = sTree[node << 1] + sTree[node << 1 | 1]; } } void update_point(int index, int val) // O(log n) { index += N - 1; sTree[index] = val; while(index>1) { index >>= 1; sTree[index] = Math.max(sTree[index<<1] ,sTree[index<<1|1]); } } void update_range(int i, int j, int val) // O(log n) { update_range(1, 1, N, i, j, val); } void update_range(int node, int b, int e, int i, int j, int val) { if (i > e || j < b) return; if (b >= i && e <= j) { sTree[node] += (e - b + 1) * val; lazy[node] += val; } else { int mid = b + e >> 1; propagate(node, b, mid, e); update_range(node << 1, b, mid, i, j, val); update_range(node << 1 | 1, mid + 1, e, i, j, val); sTree[node] = sTree[node << 1] + sTree[node << 1 | 1]; } } void propagate(int node, int b, int mid, int e) { lazy[node << 1] += lazy[node]; lazy[node << 1 | 1] += lazy[node]; sTree[node << 1] += (mid - b + 1) * lazy[node]; sTree[node << 1 | 1] += (e - mid) * lazy[node]; lazy[node] = 0; } int query(int i, int j) { return query(1, 1, N, i, j); } int query(int node, int b, int e, int i, int j) // O(log n) { if (i > e || j < b) return 0; if (b >= i && e <= j) return sTree[node]; int mid = b + e >> 1; // propagate(node, b, mid, e); int q1 = query(node << 1, b, mid, i, j); int q2 = query(node << 1 | 1, mid + 1, e, i, j); return Math.max(q1,q2); } } static long[][] memo; static class UnionFind { int[] p, rank, setSize; int numSets; int max[]; public UnionFind(int N) { p = new int[numSets = N]; rank = new int[N]; setSize = new int[N]; for (int i = 0; i < N; i++) { p[i] = i; setSize[i] = 1; } } public int findSet(int i) { return p[i] == i ? i : (p[i] = findSet(p[i])); } public boolean isSameSet(int i, int j) { return findSet(i) == findSet(j); } public int chunion(int i,int j, int x2) { if (isSameSet(i, j)) return 0; numSets--; int x = findSet(i), y = findSet(j); int z=findSet(x2); p[x]=z;; p[y]=z; return x; } public void unionSet(int i, int j) { if (isSameSet(i, j)) return; numSets--; int x = findSet(i), y = findSet(j); if (rank[x] > rank[y]) { p[y] = x; setSize[x] += setSize[y]; } else { p[x] = y; setSize[y] += setSize[x]; if (rank[x] == rank[y]) rank[y]++; } } public int numDisjointSets() { return numSets; } public int sizeOfSet(int i) { return setSize[findSet(i)]; } } /** * private static void trace(int i, int time) { if(i==n) return; * * * long ans=dp(i,time); * if(time+a[i].t<a[i].burn&&(ans==dp(i+1,time+a[i].t)+a[i].cost)) { * * trace(i+1, time+a[i].t); * * l1.add(a[i].idx); return; } trace(i+1,time); * * } **/ static class incpair implements Comparable<incpair> { int a; long b; int idx; incpair(int a, long dirg, int i) { this.a = a; b = dirg; idx = i; } public int compareTo(incpair e) { return (int) (b - e.b); } } static class decpair implements Comparable<decpair> { int a; long b; int idx; decpair(int a, long dirg, int i) { this.a = a; b = dirg; idx = i; } public int compareTo(decpair e) { return (int) (e.b - b); } } static long allpowers[]; static class Quad implements Comparable<Quad> { int u; int v; char state; int turns; public Quad(int i, int j, char c, int k) { u = i; v = j; state = c; turns = k; } public int compareTo(Quad e) { return (int) (turns - e.turns); } } static long dirg[][]; static Edge[] driver; static int n; static long manhatandistance(long x, long x2, long y, long y2) { return Math.abs(x - x2) + Math.abs(y - y2); } static long fib[]; static long fib(int n) { if (n == 1 || n == 0) { return 1; } if (fib[n] != -1) { return fib[n]; } else return fib[n] = ((fib(n - 2) % mod + fib(n - 1) % mod) % mod); } static class Point implements Comparable<Point>{ long x, y; Point(long counth, long counts) { x = counth; y = counts; } @Override public int compareTo(Point p ) { return Long.compare(p.y*1l*x, p.x*1l*y); } } static long[][] comb; static class Triple implements Comparable<Triple> { int l; int r; long cost; int idx; public Triple(int a, int b, long l1, int l2) { l = a; r = b; cost = l1; idx = l2; } public int compareTo(Triple x) { if (l != x.l || idx == x.idx) return l - x.l; return -idx; } } static TreeSet<Long> primeFactors(long N) // O(sqrt(N) / ln sqrt(N)) { TreeSet<Long> factors = new TreeSet<Long>(); // take abs(N) in case of -ve integers int idx = 0, p = primes.get(idx); while (p * p <= N) { while (N % p == 0) { factors.add((long) p); N /= p; } if (primes.size() > idx + 1) p = primes.get(++idx); else break; } if (N != 1) // last prime factor may be > sqrt(N) factors.add(N); // for integers whose largest prime factor has a power of 1 return factors; } static boolean visited[]; /** * static int bfs(int s) { Queue<Integer> q = new LinkedList<Integer>(); * q.add(s); int count=0; int maxcost=0; int dist[]=new int[n]; dist[s]=0; * while(!q.isEmpty()) { * * int u = q.remove(); if(dist[u]==k) { break; } for(Pair v: adj[u]) { * maxcost=Math.max(maxcost, v.cost); * * * * if(!visited[v.v]) { * * visited[v.v]=true; q.add(v.v); dist[v.v]=dist[u]+1; maxcost=Math.max(maxcost, * v.cost); } } * * } return maxcost; } **/ public static boolean FindAllElements(int n, int k) { int sum = k; int[] A = new int[k]; Arrays.fill(A, 0, k, 1); for (int i = k - 1; i >= 0; --i) { while (sum + A[i] <= n) { sum += A[i]; A[i] *= 2; } } if (sum == n) { return true; } else return false; } static boolean[] vis2; static boolean f2 = false; static long[][] matMul(long[][] a2, long[][] b, int p, int q, int r) // C(p x r) = A(p x q) x (q x r) -- O(p x q x // r) { long[][] C = new long[p][r]; for (int i = 0; i < p; ++i) { for (int j = 0; j < r; ++j) { for (int k = 0; k < q; ++k) { C[i][j] = (C[i][j] + (a2[i][k] % mod * b[k][j] % mod)) % mod; C[i][j] %= mod; } } } return C; } public static int[] schuffle(int[] a2) { for (int i = 0; i < a2.length; i++) { int x = (int) (Math.random() * a2.length); int temp = a2[x]; a2[x] = a2[i]; a2[i] = temp; } return a2; } static int memo1[]; static boolean vis[]; static TreeSet<Integer> set = new TreeSet<Integer>(); static long modPow(long ways, long count, long mod) // O(log e) { ways %= mod; long res = 1; while (count > 0) { if ((count & 1) == 1) res = (res * ways) % mod; ways = (ways * ways) % mod; count >>= 1; } return res % mod; } static long gcd(long ans, long b) { if (b == 0) { return ans; } return gcd(b, ans % b); } static int[] isComposite; static int[] valid; static ArrayList<Integer> primes; static ArrayList<Integer> l1; static TreeSet<Integer> primus = new TreeSet<Integer>(); static void sieveLinear(int N) { int[] lp = new int[N + 1]; //lp[i] = least prime divisor of i for(int i = 2; i <= N; ++i) { if(lp[i] == 0) { primus.add(i); lp[i] = i; } int curLP = lp[i]; for(int p: primus) if(p > curLP || p * i > N) break; else lp[p * i] = i; } } public static long[] schuffle(long[] a2) { for (int i = 0; i < a2.length; i++) { int x = (int) (Math.random() * a2.length); long temp = a2[x]; a2[x] = a2[i]; a2[i] = temp; } return a2; } static int V; static long INF = (long) 1E16; static class Edge2 { int node; long cost; long next; Edge2(int a, int c, Long long1) { node = a; cost = long1; next = c; } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream system) { br = new BufferedReader(new InputStreamReader(system)); } public Scanner(String file) throws Exception { br = new BufferedReader(new FileReader(file)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public String nextLine() throws IOException { return br.readLine(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public char nextChar() throws IOException { return next().charAt(0); } public Long nextLong() throws IOException { return Long.parseLong(next()); } public boolean ready() throws IOException { return br.ready(); } public void waitForInput() throws InterruptedException { Thread.sleep(3000); } public int[] nxtArr(int n) throws IOException { int[] ans = new int[n]; for (int i = 0; i < n; i++) ans[i] = nextInt(); return ans; } } public static int[] sortarray(int a[]) { schuffle(a); Arrays.sort(a); return a; } public static long[] sortarray(long a[]) { schuffle(a); Arrays.sort(a); return a; } }
Java
["10 6 100\n17 5", "11 6 100\n12 5"]
1 second
["4\nSTRIKE\nHEAL\nSTRIKE\nSTRIKE", "2\nSTRIKE\nSTRIKE"]
NoteIn the first example Vova's character must heal before or after his first attack. Otherwise his health will drop to zero in 2 phases while he needs 3 strikes to win.In the second example no healing needed, two strikes are enough to get monster to zero health and win with 6 health left.
Java 11
standard input
[ "implementation", "greedy" ]
d497431eb37fafdf211309da8740ece6
The first line contains three integers h1, a1, c1 (1 ≤ h1, a1 ≤ 100, 2 ≤ c1 ≤ 100) — Vova's health, Vova's attack power and the healing power of a potion. The second line contains two integers h2, a2 (1 ≤ h2 ≤ 100, 1 ≤ a2 &lt; c1) — the Modcrab's health and his attack power.
1,200
In the first line print one integer n denoting the minimum number of phases required to win the battle. Then print n lines. i-th line must be equal to HEAL if Vova drinks a potion in i-th phase, or STRIKE if he attacks the Modcrab. The strategy must be valid: Vova's character must not be defeated before slaying the Modcrab, and the monster's health must be 0 or lower after Vova's last action. If there are multiple optimal solutions, print any of them.
standard output
PASSED
d39715ef0df526b073e0d041d597e0a5
train_003.jsonl
1543163700
Arkady's morning seemed to be straight of his nightmare. He overslept through the whole morning and, still half-asleep, got into the tram that arrived the first. Some time after, leaving the tram, he realized that he was not sure about the line number of the tram he was in.During his ride, Arkady woke up several times and each time he saw the tram stopping at some stop. For each stop he knows which lines of tram stop there. Given this information, can you help Arkady determine what are the possible lines of the tram he was in?
256 megabytes
import java.io.*; import java.util.*; import java.text.*; import java.math.*; import java.util.regex.*; import java.awt.Point; public class TryB { static class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar, snumChars; public InputReader(InputStream st) { this.stream = st; } public int read() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int ni() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long nl() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nia(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = ni(); } return a; } public String rs() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public String nextLine() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } } static PrintWriter w = new PrintWriter(System.out); static char [][]sol; public static void main(String[] args) { InputReader sc = new InputReader(System.in); //PrintWriter w = new PrintWriter(System.out); /* prime = new boolean[n + 1]; sieve(); prime[1] = false; */ /* as = new ArrayList<>(); for(int i=2;i<=1000000;i++) { if(prime[i]) as.add(i); } */ /* long a = sc.nl(); BigInteger ans = new BigInteger("1"); for (long i = 1; i < Math.sqrt(a); i++) { if (a % i == 0) { if (a / i == i) { ans = ans.multiply(BigInteger.valueOf(phi(i))); } else { ans = ans.multiply(BigInteger.valueOf(phi(i))); ans = ans.multiply(BigInteger.valueOf(phi(a / i))); } } } w.println(ans.mod(bigInteger)); */ // MergeSort ob = new MergeSort(); // ob.sort(arr, 0, arr.length-1); // Student []st = new Student[x]; // st[i] = new Student(i,d[i]); //Arrays.sort(st,(p,q)->p.diff-q.diff); int x = sc.ni(); int r = x; int []a = new int[101]; while(x-- > 0) { int t = sc.ni(); while(t-- > 0) { a[sc.ni()]++; } } for(int i=1;i<=100;i++) { if(a[i] == r) w.print(i + " "); } w.close(); } /* static void dfs(List<Integer>[] graph, int u,int []p1,List<Integer> res) { //res = new ArrayList<>(); vis[u] = true; for (int v : graph[u]) if (!vis[v]) dfs(graph, v,p1,res); res.add(u); ts.add(p1[u-1]); } */ static int log(long base,long sum) { long temp = sum; int i = 0; while(sum > 0) { sum /= base; i++; } return i; } static boolean checkT(int a,int b, int c) { int f = 0; if(a+b <= c || b+c <=a||a+c <= b) return false; else return true; } static double costheta(int a,int b,int c) { double pos = ((double)b*(double)b + (double)c*(double)c-(double)a*(double)a) / (2*(double)b*(double)c); return pos; } public static int ip(String s){ return Integer.parseInt(s); } public static String ips(int s){ return Integer.toString(s); } static long area(int ax,int ay,int bx,int by,int cx,int cy) { long ar = ((long)ax*((long)by-(long)cy)) + ((long)bx*((long)cy-(long)ay)) + ((long)cx*((long)ay-(long)by)); return Math.abs(ar); } public static int lowerBound(Student[] array, int length, int value) { int low = 0; int high = length-1; while (low < high) { final int mid = (low + high) / 2; if (value <= array[mid].val) { high = mid; } else { low = mid + 1; } } return low; } public static int upperBound(int[] array, int length, int value) { int low = 0; int high = length-1; while (low < high) { final int mid = (low + high) / 2; if (value >= array[mid]) { low = mid + 1; } else { high = mid; } } return low; } static class Student { int val; int index; Student(int val,int index) { this.val = val; this.index = index; } } }
Java
["3\n3 1 4 6\n2 1 4\n5 10 5 6 4 1", "5\n1 1\n10 10 9 8 7 100 5 4 3 99 1\n5 1 2 3 4 5\n5 4 1 3 2 5\n4 10 1 5 3"]
1 second
["1 4", "1"]
NoteConsider the first example. Arkady woke up three times. The first time he saw a stop with lines $$$1$$$, $$$4$$$, $$$6$$$. The second time he saw a stop with lines $$$1$$$, $$$4$$$. The third time he saw a stop with lines $$$10$$$, $$$5$$$, $$$6$$$, $$$4$$$ and $$$1$$$. He can be in a tram of one of two lines: $$$1$$$ or $$$4$$$.
Java 8
standard input
[ "implementation" ]
16c54cf7d8b484b5e22a7d391fdc5cd3
The first line contains a single integer $$$n$$$ ($$$2 \le n \le 100$$$) — the number of stops Arkady saw. The next $$$n$$$ lines describe the stops. Each of them starts with a single integer $$$r$$$ ($$$1 \le r \le 100$$$) — the number of tram lines that stop there. $$$r$$$ distinct integers follow, each one between $$$1$$$ and $$$100$$$, inclusive, — the line numbers. They can be in arbitrary order. It is guaranteed that Arkady's information is consistent, i.e. there is at least one tram line that Arkady could take.
800
Print all tram lines that Arkady could be in, in arbitrary order.
standard output
PASSED
3023773f9d6bc01fbea18aba15077e0b
train_003.jsonl
1543163700
Arkady's morning seemed to be straight of his nightmare. He overslept through the whole morning and, still half-asleep, got into the tram that arrived the first. Some time after, leaving the tram, he realized that he was not sure about the line number of the tram he was in.During his ride, Arkady woke up several times and each time he saw the tram stopping at some stop. For each stop he knows which lines of tram stop there. Given this information, can you help Arkady determine what are the possible lines of the tram he was in?
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashSet; import java.util.Scanner; /** * * @author Jakub */ public class ProblemA { /** * @param args the command line arguments */ public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringBuilder sb = new StringBuilder(1000); int stops = Integer.parseInt(br.readLine()); String[] line = br.readLine().split(" "); HashSet<Integer> first = new HashSet<>(); for (int i = 1; i < line.length; i++) { first.add(Integer.parseInt(line[i])); } for (int i = 1; i < stops; i++) { HashSet<Integer> other = new HashSet<>(); line = br.readLine().split(" "); for (int j = 1; j < line.length; j++) { int num = (Integer.parseInt(line[j])); if (first.contains(num)){ other.add(num); } } first = other; } for (Integer integer : first) { sb.append(integer).append(' '); } sb.replace(sb.length()-1, sb.length(), "\n"); System.out.print(sb); } }
Java
["3\n3 1 4 6\n2 1 4\n5 10 5 6 4 1", "5\n1 1\n10 10 9 8 7 100 5 4 3 99 1\n5 1 2 3 4 5\n5 4 1 3 2 5\n4 10 1 5 3"]
1 second
["1 4", "1"]
NoteConsider the first example. Arkady woke up three times. The first time he saw a stop with lines $$$1$$$, $$$4$$$, $$$6$$$. The second time he saw a stop with lines $$$1$$$, $$$4$$$. The third time he saw a stop with lines $$$10$$$, $$$5$$$, $$$6$$$, $$$4$$$ and $$$1$$$. He can be in a tram of one of two lines: $$$1$$$ or $$$4$$$.
Java 8
standard input
[ "implementation" ]
16c54cf7d8b484b5e22a7d391fdc5cd3
The first line contains a single integer $$$n$$$ ($$$2 \le n \le 100$$$) — the number of stops Arkady saw. The next $$$n$$$ lines describe the stops. Each of them starts with a single integer $$$r$$$ ($$$1 \le r \le 100$$$) — the number of tram lines that stop there. $$$r$$$ distinct integers follow, each one between $$$1$$$ and $$$100$$$, inclusive, — the line numbers. They can be in arbitrary order. It is guaranteed that Arkady's information is consistent, i.e. there is at least one tram line that Arkady could take.
800
Print all tram lines that Arkady could be in, in arbitrary order.
standard output
PASSED
57a000c46075c6df663199c134c536f4
train_003.jsonl
1543163700
Arkady's morning seemed to be straight of his nightmare. He overslept through the whole morning and, still half-asleep, got into the tram that arrived the first. Some time after, leaving the tram, he realized that he was not sure about the line number of the tram he was in.During his ride, Arkady woke up several times and each time he saw the tram stopping at some stop. For each stop he knows which lines of tram stop there. Given this information, can you help Arkady determine what are the possible lines of the tram he was in?
256 megabytes
import java.io.*; import java.util.*; public class Main { public static void main(String[] args) throws Exception { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(in.readLine()); HashSet<Integer>[] sets = new HashSet[t]; for (int i = 0; i < t; i++) { sets[i] = new HashSet<>(); StringTokenizer st = new StringTokenizer(in.readLine()); int r = Integer.parseInt(st.nextToken()); for (int j = 0; j < r; j++) { sets[i].add(Integer.parseInt(st.nextToken())); } } for (int i = 1; i <= 100; i++) { boolean flag = true; for (int j = 0; j < t; j++) { if (!sets[j].contains(i)) { flag = false; break; } } if (flag) { System.out.print(i + " "); } } System.out.print("\n"); } } /* */
Java
["3\n3 1 4 6\n2 1 4\n5 10 5 6 4 1", "5\n1 1\n10 10 9 8 7 100 5 4 3 99 1\n5 1 2 3 4 5\n5 4 1 3 2 5\n4 10 1 5 3"]
1 second
["1 4", "1"]
NoteConsider the first example. Arkady woke up three times. The first time he saw a stop with lines $$$1$$$, $$$4$$$, $$$6$$$. The second time he saw a stop with lines $$$1$$$, $$$4$$$. The third time he saw a stop with lines $$$10$$$, $$$5$$$, $$$6$$$, $$$4$$$ and $$$1$$$. He can be in a tram of one of two lines: $$$1$$$ or $$$4$$$.
Java 8
standard input
[ "implementation" ]
16c54cf7d8b484b5e22a7d391fdc5cd3
The first line contains a single integer $$$n$$$ ($$$2 \le n \le 100$$$) — the number of stops Arkady saw. The next $$$n$$$ lines describe the stops. Each of them starts with a single integer $$$r$$$ ($$$1 \le r \le 100$$$) — the number of tram lines that stop there. $$$r$$$ distinct integers follow, each one between $$$1$$$ and $$$100$$$, inclusive, — the line numbers. They can be in arbitrary order. It is guaranteed that Arkady's information is consistent, i.e. there is at least one tram line that Arkady could take.
800
Print all tram lines that Arkady could be in, in arbitrary order.
standard output
PASSED
851055f795ccf8123bcf9c3f6920b6a9
train_003.jsonl
1543163700
Arkady's morning seemed to be straight of his nightmare. He overslept through the whole morning and, still half-asleep, got into the tram that arrived the first. Some time after, leaving the tram, he realized that he was not sure about the line number of the tram he was in.During his ride, Arkady woke up several times and each time he saw the tram stopping at some stop. For each stop he knows which lines of tram stop there. Given this information, can you help Arkady determine what are the possible lines of the tram he was in?
256 megabytes
//Author: Mo Abjal, MJP Rohilkhand University Bareilly, UP, India 2018. /////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////********************////////////////////////////////////////////// /////////////////////////////////////////* S0LUT10N *////////////////////////////////////////////// /////////////////////////////////////////********************////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////// import java.util.*; import java.io.*; import java.text.*; import java.math.*; public class Main{ public static StringTokenizer token = new StringTokenizer(""); public static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); public static PrintWriter output = new PrintWriter(System.out); public static void main(String[] afzal) throws Exception { int N = ni(); int min=Integer.MAX_VALUE; ArrayList<Integer> list = new ArrayList<Integer>(); int A[] = new int[105]; for(int i=0;i<N;i++){ int r = ni(); if(min>r){ list.clear(); for(int j=0;j<r;j++){ int x = ni(); list.add(x); A[x]++; } min = r; } else{ for(int j=0;j<r;j++){ A[ni()]++; } } } ArrayList<Integer> ans = new ArrayList<Integer>(); for(int i=0;i<list.size();i++){ int x = (int)list.get(i); if(A[x]==N){ ans.add(x); } } for(int i=0;i<ans.size();i++){ output.print(ans.get(i)+" "); } output.close(); /*int N = ni(); int D = ni(); https://www.udemy.com/spring-hibernate-tutorial/learn/v4/t/lecture/10689826?start=0 int x1 = 0, y1 = D, x2 = D, y2 = 0, x3 = N, y3 = N-D, x4 = N-D, y4 = N; int M = ni(); while(M-->0){ int x = ni(); int y = ni(); double A = area(x1,y1,x2,y2,x3,y3); double B = area(x2,y2,x3,y3,x4,y4); double A1 = area(x,y,x1,y1,x2,y2); double A2 = area(x,y,x1,y1,x3,y3); double A3 = area(x,y,x3,y3,x4,y4); double A4 = area(x,y,x2,y2,x4,y4); if((A+B)==(A1+A2+A3+A4)){ output.println("YES"); } else{ output.println("NO"); }} output.close();*/ } public static boolean prime(long p){ for(int i=2;i*i<=p;i++){ if(p%i==0) return false; } return true; } public static double area(int x1,int y1,int x2,int y2,int x3,int y3){ double area = 0.0; area = (double)Math.abs((x1*(y2-y3) + x2*(y3-y1) + x3*(y1-y2))/2.0); return area; } public static long gcd(long a,long b){ if(b==0) return a; else return gcd(b,a%b); } public static String pc(char c){ return Character.toString(c); } public static Integer pci(char c){ return pi(Character.toString(c)); } public static Integer pi(String str){ return Integer.parseInt(str); } public static Long pl(String str){ return Long.parseLong(str); } public static String ps(Integer N){ return Integer.toString(N); } public static char[] pcc(String str){ return str.toCharArray(); } public static Integer ni() throws IOException{ if(!token.hasMoreElements()){ token = new StringTokenizer(br.readLine()); } return Integer.parseInt(token.nextToken()); } public static Long nl() throws IOException{ if(!token.hasMoreElements()){ token = new StringTokenizer(br.readLine()); } return Long.parseLong(token.nextToken()); } public static Double nd() throws IOException{ if(!token.hasMoreElements()){ token = new StringTokenizer(br.readLine()); } return Double.parseDouble(token.nextToken()); } public static String ns() throws IOException{ if(!token.hasMoreElements()){ token = new StringTokenizer(br.readLine()); } return token.nextToken(); } public static Integer[] ai(int N) throws IOException{ Integer A[] = new Integer[N]; token = new StringTokenizer(br.readLine()); for(int i=0;i<A.length;i++){ A[i] = pi(token.nextToken()); } return A; } public static long[] al(int N) throws IOException{ long A[] = new long[N]; token = new StringTokenizer(br.readLine()); for(int i=0;i<N;i++){ A[i] = Long.parseLong(token.nextToken()); } return A; } public static char[][] acc(int N,int M) throws IOException{ char C[][] = new char[N][M]; for(int i=0;i<N;i++){ token = new StringTokenizer(br.readLine()); String s = token.nextToken(); for(int j=0;j<M;j++){ C[i][j] = s.charAt(j); } } return C; } public static String[] as(int N) throws IOException{ String S[] = new String[N]; token = new StringTokenizer(br.readLine()); for(int i=0;i<S.length;i++){ S[i] = token.nextToken(); } return S; } public static double ncr(int n, int r){ if(n==r) return 1; else return (fact(n)/(fact(r)*fact(n-r))); } public static long fact(long N){ long fact = 1; for(int i=1;i<=N;i++){ fact = fact * i; } return fact; } public static BigInteger factB(int N){ BigInteger b = new BigInteger("1"); for(int i=1;i<=N;i++){ b = b.multiply(BigInteger.valueOf(i)); } return b; } public static long sod(long N){ long sum = 0; while(N>0){ long x = N%10; sum = sum + x; N = N/10; } return sum; } public static Integer cd(long N){ int count=0; while(N>0){ N = N/10; count++; } return count=0; } } class Pair implements Comparable{ int a,b; public Pair(int a,int b){ this.a = a; this.b = b; } public int compareTo(Object p){ Pair pa = (Pair)p; //if(this.a==pa.a) return this.b - pa.b; return this.a - pa.a; } }class Pair3 implements Comparable{ int a,b,c; public Pair3(int a,int b,int c){ this.a = a; this.b = b; this.c = c; } public int compareTo(Object p){ Pair pa = (Pair)p; //if(this.a==pa.a) return this.b - pa.b; return this.a - pa.a; } } //Copyright Reserved - Mo Abjal.
Java
["3\n3 1 4 6\n2 1 4\n5 10 5 6 4 1", "5\n1 1\n10 10 9 8 7 100 5 4 3 99 1\n5 1 2 3 4 5\n5 4 1 3 2 5\n4 10 1 5 3"]
1 second
["1 4", "1"]
NoteConsider the first example. Arkady woke up three times. The first time he saw a stop with lines $$$1$$$, $$$4$$$, $$$6$$$. The second time he saw a stop with lines $$$1$$$, $$$4$$$. The third time he saw a stop with lines $$$10$$$, $$$5$$$, $$$6$$$, $$$4$$$ and $$$1$$$. He can be in a tram of one of two lines: $$$1$$$ or $$$4$$$.
Java 8
standard input
[ "implementation" ]
16c54cf7d8b484b5e22a7d391fdc5cd3
The first line contains a single integer $$$n$$$ ($$$2 \le n \le 100$$$) — the number of stops Arkady saw. The next $$$n$$$ lines describe the stops. Each of them starts with a single integer $$$r$$$ ($$$1 \le r \le 100$$$) — the number of tram lines that stop there. $$$r$$$ distinct integers follow, each one between $$$1$$$ and $$$100$$$, inclusive, — the line numbers. They can be in arbitrary order. It is guaranteed that Arkady's information is consistent, i.e. there is at least one tram line that Arkady could take.
800
Print all tram lines that Arkady could be in, in arbitrary order.
standard output
PASSED
07054c06a49944a9e243a3d92b54440f
train_003.jsonl
1543163700
Arkady's morning seemed to be straight of his nightmare. He overslept through the whole morning and, still half-asleep, got into the tram that arrived the first. Some time after, leaving the tram, he realized that he was not sure about the line number of the tram he was in.During his ride, Arkady woke up several times and each time he saw the tram stopping at some stop. For each stop he knows which lines of tram stop there. Given this information, can you help Arkady determine what are the possible lines of the tram he was in?
256 megabytes
import java.util.*; public class Solution { public static void main(String args[]) { Scanner sc=new Scanner(System.in); int t=sc.nextInt(); List<Integer> list1=new ArrayList<>(); for(int i=0;i<t;i++) { int n=sc.nextInt(); int arr[]=new int[n]; if(i==0) { for(int j=0;j<n;j++) { arr[j]=sc.nextInt(); list1.add(arr[j]); } } else { List<Integer> list2=new ArrayList<>(); for(int j=0;j<n;j++) { arr[j]=sc.nextInt(); list2.add(arr[j]); } List<Integer> list3=new ArrayList<>(); for(Integer vall:list1) { if(list2.contains(vall)==false) list3.add(vall); } list1.removeAll(list3); } } for (Integer val : list1) System.out.print(val+" "); } }
Java
["3\n3 1 4 6\n2 1 4\n5 10 5 6 4 1", "5\n1 1\n10 10 9 8 7 100 5 4 3 99 1\n5 1 2 3 4 5\n5 4 1 3 2 5\n4 10 1 5 3"]
1 second
["1 4", "1"]
NoteConsider the first example. Arkady woke up three times. The first time he saw a stop with lines $$$1$$$, $$$4$$$, $$$6$$$. The second time he saw a stop with lines $$$1$$$, $$$4$$$. The third time he saw a stop with lines $$$10$$$, $$$5$$$, $$$6$$$, $$$4$$$ and $$$1$$$. He can be in a tram of one of two lines: $$$1$$$ or $$$4$$$.
Java 8
standard input
[ "implementation" ]
16c54cf7d8b484b5e22a7d391fdc5cd3
The first line contains a single integer $$$n$$$ ($$$2 \le n \le 100$$$) — the number of stops Arkady saw. The next $$$n$$$ lines describe the stops. Each of them starts with a single integer $$$r$$$ ($$$1 \le r \le 100$$$) — the number of tram lines that stop there. $$$r$$$ distinct integers follow, each one between $$$1$$$ and $$$100$$$, inclusive, — the line numbers. They can be in arbitrary order. It is guaranteed that Arkady's information is consistent, i.e. there is at least one tram line that Arkady could take.
800
Print all tram lines that Arkady could be in, in arbitrary order.
standard output
PASSED
d4baf6c75ef590f6f66da3da5c78c35f
train_003.jsonl
1543163700
Arkady's morning seemed to be straight of his nightmare. He overslept through the whole morning and, still half-asleep, got into the tram that arrived the first. Some time after, leaving the tram, he realized that he was not sure about the line number of the tram he was in.During his ride, Arkady woke up several times and each time he saw the tram stopping at some stop. For each stop he knows which lines of tram stop there. Given this information, can you help Arkady determine what are the possible lines of the tram he was in?
256 megabytes
import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.HashSet; import java.util.InputMismatchException; import java.util.Set; public class A { InputStream is; PrintWriter out; String INPUT = ""; void solve() { int n = ni(); Set<Integer> set = new HashSet<>(); for(int i = 0;i < n;i++){ int r = ni(); Set<Integer> lset = new HashSet<>(); for(int j = 0;j < r;j++){ lset.add(ni()); } if(i == 0){ set = lset; }else{ set.retainAll(lset); } } for(int v : set){ out.print(v + " "); } out.println(); } void run() throws Exception { is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes()); out = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); out.flush(); tr(System.currentTimeMillis()-s+"ms"); } public static void main(String[] args) throws Exception { new A().run(); } private byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; private int readByte() { if(lenbuf == -1)throw new InputMismatchException(); if(ptrbuf >= lenbuf){ ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if(lenbuf <= 0)return -1; } return inbuf[ptrbuf++]; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; } private double nd() { return Double.parseDouble(ns()); } private char nc() { return (char)skip(); } private String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private char[] ns(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while(p < n && !(isSpaceChar(b))){ buf[p++] = (char)b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private char[][] nm(int n, int m) { char[][] map = new char[n][]; for(int i = 0;i < n;i++)map[i] = ns(m); return map; } private int[] na(int n) { int[] a = new int[n]; for(int i = 0;i < n;i++)a[i] = ni(); return a; } private int ni() { int num = 0, b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private long nl() { long num = 0; int b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private boolean oj = System.getProperty("ONLINE_JUDGE") != null; private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); } }
Java
["3\n3 1 4 6\n2 1 4\n5 10 5 6 4 1", "5\n1 1\n10 10 9 8 7 100 5 4 3 99 1\n5 1 2 3 4 5\n5 4 1 3 2 5\n4 10 1 5 3"]
1 second
["1 4", "1"]
NoteConsider the first example. Arkady woke up three times. The first time he saw a stop with lines $$$1$$$, $$$4$$$, $$$6$$$. The second time he saw a stop with lines $$$1$$$, $$$4$$$. The third time he saw a stop with lines $$$10$$$, $$$5$$$, $$$6$$$, $$$4$$$ and $$$1$$$. He can be in a tram of one of two lines: $$$1$$$ or $$$4$$$.
Java 8
standard input
[ "implementation" ]
16c54cf7d8b484b5e22a7d391fdc5cd3
The first line contains a single integer $$$n$$$ ($$$2 \le n \le 100$$$) — the number of stops Arkady saw. The next $$$n$$$ lines describe the stops. Each of them starts with a single integer $$$r$$$ ($$$1 \le r \le 100$$$) — the number of tram lines that stop there. $$$r$$$ distinct integers follow, each one between $$$1$$$ and $$$100$$$, inclusive, — the line numbers. They can be in arbitrary order. It is guaranteed that Arkady's information is consistent, i.e. there is at least one tram line that Arkady could take.
800
Print all tram lines that Arkady could be in, in arbitrary order.
standard output
PASSED
8b6db7827804d07e91877b5351e61d84
train_003.jsonl
1543163700
Arkady's morning seemed to be straight of his nightmare. He overslept through the whole morning and, still half-asleep, got into the tram that arrived the first. Some time after, leaving the tram, he realized that he was not sure about the line number of the tram he was in.During his ride, Arkady woke up several times and each time he saw the tram stopping at some stop. For each stop he knows which lines of tram stop there. Given this information, can you help Arkady determine what are the possible lines of the tram he was in?
256 megabytes
import java.util.Scanner; public class FirstStep { public static void main(String args[]) { Scanner input = new Scanner(System.in); int n = input.nextInt(); int []count = new int[101]; int max = 0; for(int i=0;i<n;i+=1){ int r = input.nextInt(); for (int j=0;j<r;j++){ int t = input.nextInt(); count[t]+=1; } } for (int i = 0;i<count.length;i+=1){ max = Math.max(max, count[i]); } for (int i = 0;i<count.length;i+=1){ if (max==count[i]){ System.out.print(i+" "); } } } }
Java
["3\n3 1 4 6\n2 1 4\n5 10 5 6 4 1", "5\n1 1\n10 10 9 8 7 100 5 4 3 99 1\n5 1 2 3 4 5\n5 4 1 3 2 5\n4 10 1 5 3"]
1 second
["1 4", "1"]
NoteConsider the first example. Arkady woke up three times. The first time he saw a stop with lines $$$1$$$, $$$4$$$, $$$6$$$. The second time he saw a stop with lines $$$1$$$, $$$4$$$. The third time he saw a stop with lines $$$10$$$, $$$5$$$, $$$6$$$, $$$4$$$ and $$$1$$$. He can be in a tram of one of two lines: $$$1$$$ or $$$4$$$.
Java 8
standard input
[ "implementation" ]
16c54cf7d8b484b5e22a7d391fdc5cd3
The first line contains a single integer $$$n$$$ ($$$2 \le n \le 100$$$) — the number of stops Arkady saw. The next $$$n$$$ lines describe the stops. Each of them starts with a single integer $$$r$$$ ($$$1 \le r \le 100$$$) — the number of tram lines that stop there. $$$r$$$ distinct integers follow, each one between $$$1$$$ and $$$100$$$, inclusive, — the line numbers. They can be in arbitrary order. It is guaranteed that Arkady's information is consistent, i.e. there is at least one tram line that Arkady could take.
800
Print all tram lines that Arkady could be in, in arbitrary order.
standard output
PASSED
7b8f2d7c6feaece3edf4f4d2e914ddc4
train_003.jsonl
1543163700
Arkady's morning seemed to be straight of his nightmare. He overslept through the whole morning and, still half-asleep, got into the tram that arrived the first. Some time after, leaving the tram, he realized that he was not sure about the line number of the tram he was in.During his ride, Arkady woke up several times and each time he saw the tram stopping at some stop. For each stop he knows which lines of tram stop there. Given this information, can you help Arkady determine what are the possible lines of the tram he was in?
256 megabytes
import java.util.*; public class A { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); HashSet<Integer> ms = new HashSet<Integer>(100); for (int i = 0; i<=100; i++) { ms.add(i); } for (int i=0; i<n; i++) { int r = in.nextInt(); HashSet<Integer> ost = new HashSet<Integer>(); for(int j=0; j<r; j++) { ost.add(in.nextInt()); } ms.retainAll(ost); } printSet(ms); } private static void printSet(HashSet<Integer> ms) { Iterator<Integer> it = ms.iterator(); while(it.hasNext()) { System.out.print(it.next() + " "); } } }
Java
["3\n3 1 4 6\n2 1 4\n5 10 5 6 4 1", "5\n1 1\n10 10 9 8 7 100 5 4 3 99 1\n5 1 2 3 4 5\n5 4 1 3 2 5\n4 10 1 5 3"]
1 second
["1 4", "1"]
NoteConsider the first example. Arkady woke up three times. The first time he saw a stop with lines $$$1$$$, $$$4$$$, $$$6$$$. The second time he saw a stop with lines $$$1$$$, $$$4$$$. The third time he saw a stop with lines $$$10$$$, $$$5$$$, $$$6$$$, $$$4$$$ and $$$1$$$. He can be in a tram of one of two lines: $$$1$$$ or $$$4$$$.
Java 8
standard input
[ "implementation" ]
16c54cf7d8b484b5e22a7d391fdc5cd3
The first line contains a single integer $$$n$$$ ($$$2 \le n \le 100$$$) — the number of stops Arkady saw. The next $$$n$$$ lines describe the stops. Each of them starts with a single integer $$$r$$$ ($$$1 \le r \le 100$$$) — the number of tram lines that stop there. $$$r$$$ distinct integers follow, each one between $$$1$$$ and $$$100$$$, inclusive, — the line numbers. They can be in arbitrary order. It is guaranteed that Arkady's information is consistent, i.e. there is at least one tram line that Arkady could take.
800
Print all tram lines that Arkady could be in, in arbitrary order.
standard output
PASSED
a40e9f483b244d2cfc791213ecef4dbd
train_003.jsonl
1543163700
Arkady's morning seemed to be straight of his nightmare. He overslept through the whole morning and, still half-asleep, got into the tram that arrived the first. Some time after, leaving the tram, he realized that he was not sure about the line number of the tram he was in.During his ride, Arkady woke up several times and each time he saw the tram stopping at some stop. For each stop he knows which lines of tram stop there. Given this information, can you help Arkady determine what are the possible lines of the tram he was in?
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(); int[] stops = new int[101]; StringBuilder sb = new StringBuilder(); for(int i=0;i<n;i++){ int cant = sc.nextInt(); for(int j=0;j<cant;j++){ int stop = sc.nextInt(); stops[stop]++; if( stops[stop]== n){ sb.append(stop); sb.append(" "); } } } System.out.println(sb); } }
Java
["3\n3 1 4 6\n2 1 4\n5 10 5 6 4 1", "5\n1 1\n10 10 9 8 7 100 5 4 3 99 1\n5 1 2 3 4 5\n5 4 1 3 2 5\n4 10 1 5 3"]
1 second
["1 4", "1"]
NoteConsider the first example. Arkady woke up three times. The first time he saw a stop with lines $$$1$$$, $$$4$$$, $$$6$$$. The second time he saw a stop with lines $$$1$$$, $$$4$$$. The third time he saw a stop with lines $$$10$$$, $$$5$$$, $$$6$$$, $$$4$$$ and $$$1$$$. He can be in a tram of one of two lines: $$$1$$$ or $$$4$$$.
Java 8
standard input
[ "implementation" ]
16c54cf7d8b484b5e22a7d391fdc5cd3
The first line contains a single integer $$$n$$$ ($$$2 \le n \le 100$$$) — the number of stops Arkady saw. The next $$$n$$$ lines describe the stops. Each of them starts with a single integer $$$r$$$ ($$$1 \le r \le 100$$$) — the number of tram lines that stop there. $$$r$$$ distinct integers follow, each one between $$$1$$$ and $$$100$$$, inclusive, — the line numbers. They can be in arbitrary order. It is guaranteed that Arkady's information is consistent, i.e. there is at least one tram line that Arkady could take.
800
Print all tram lines that Arkady could be in, in arbitrary order.
standard output
PASSED
a224c58984c3dcd9f2247eac5d7583c4
train_003.jsonl
1503592500
You are given a sequence a1, a2, ..., an consisting of different integers. It is required to split this sequence into the maximum number of subsequences such that after sorting integers in each of them in increasing order, the total sequence also will be sorted in increasing order.Sorting integers in a subsequence is a process such that the numbers included in a subsequence are ordered in increasing order, and the numbers which are not included in a subsequence don't change their places.Every element of the sequence must appear in exactly one subsequence.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.InputMismatchException; public class Solution123 implements Runnable { static final int MAX = 1000000007; static long[] pow2 = new long[200005]; static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; private BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars==-1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if(numChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } public int nextInt() { int c = read(); while(isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if(c<'0'||c>'9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public double nextDouble() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } double res = 0; while (!isSpaceChar(c) && c != '.') { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } if (c == '.') { c = read(); double m = 1; while (!isSpaceChar(c)) { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return readString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } public static void main(String args[]) throws Exception { new Thread(null, new Solution123(),"Solution123",1<<26).start(); } public void run() { InputReader sc= new InputReader(System.in); PrintWriter w= new PrintWriter(System.out); int n = sc.nextInt(); int[] arr2 = new int[n]; int[] arr = new int[n]; for(int i = 0;i < n;i++){ arr2[i] = sc.nextInt(); } for(int i = 0;i < n;i++){ arr[i] = arr2[i]; } Arrays.sort(arr); HashMap<Integer,Integer> hmap = new HashMap(); for(int i = 0;i < n;i++){ hmap.put(arr[i],i); } ArrayList<String> ar = new ArrayList(); boolean[] bool = new boolean[n]; for(int i = 0;i < n;i++){ if(bool[i]){ continue; } ArrayList<Integer> temp = new ArrayList(); int count = 1; bool[i] = true; temp.add(i + 1); int j = hmap.get(arr2[i]); while(!bool[j]){ temp.add(j+1); bool[j] = true; count++; j = hmap.get(arr2[j]); } StringBuilder st = new StringBuilder(); for(int k = 0;k < temp.size();k++){ st.append(temp.get(k) + " "); } ar.add(count + " " + st.toString()); } w.println(ar.size()); for(int i = 0;i < ar.size();i++){ w.println(ar.get(i)); } w.close(); } static int lcs(String s1,String s2){ int[][] dp = new int[s1.length() + 1][s2.length() + 1]; for(int i = 0;i <= s1.length();i++){ for(int j = 0;j <= s2.length();j++){ if(i == 0 || j == 0){ dp[i][j] = 0; }else if(s1.charAt(i-1) == s2.charAt(j-1)){ dp[i][j] = dp[i-1][j-1] + 1; }else{ dp[i][j] = Math.max(dp[i][j-1],dp[i-1][j]); } } } return dp[s1.length()][s2.length()]; } boolean isPrime(int n) { for(int i=2;i<n;i++) { if(n%i==0) return false; } return true; } static class UnionFind{ int[] arr; int[] size; UnionFind(int length){ arr = new int[length]; size = new int[length]; for(int i = 0;i < length;i++){ arr[i] = i; size[i] = 1; } } int root(int a){ while(arr[a] != a){ arr[a] = arr[arr[a]]; a = arr[a]; } return a; } void union(int a,int b){ int rootA = root(a); int rootB = root(b); if(size[rootA] < size[rootB]){ arr[rootA] = rootB; size[rootB] += size[rootA]; }else{ arr[rootB] = rootA; size[rootA] += size[rootB]; } } boolean find(int a,int b){ if(root(a) == root(b)){ return true; }else{ return false; } } int ans(){ HashSet<Integer> hset = new HashSet(); ArrayList<Integer> ar = new ArrayList(); for(int i = 0;i < arr.length;i++){ int x = root(arr[i]); hset.add(x); } return hset.size(); } } class Pair implements Comparable<Pair>{ int number; Long max; Long num; Pair(int number,long max,long num){ this.number = number; this.max = max; this.num = num; } @Override public int compareTo(Pair p){ return p.max.compareTo(this.max); } } }
Java
["6\n3 2 1 6 5 4", "6\n83 -75 -49 11 37 62"]
1 second
["4\n2 1 3\n1 2\n2 4 6\n1 5", "1\n6 1 2 3 4 5 6"]
NoteIn the first sample output:After sorting the first subsequence we will get sequence 1 2 3 6 5 4.Sorting the second subsequence changes nothing.After sorting the third subsequence we will get sequence 1 2 3 4 5 6.Sorting the last subsequence changes nothing.
Java 8
standard input
[ "dfs and similar", "math" ]
159365b2f037647fbaa656905e6f5252
The first line of input data contains integer n (1 ≤ n ≤ 105) — the length of the sequence. The second line of input data contains n different integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the elements of the sequence. It is guaranteed that all elements of the sequence are distinct.
1,400
In the first line print the maximum number of subsequences k, which the original sequence can be split into while fulfilling the requirements. In the next k lines print the description of subsequences in the following format: the number of elements in subsequence ci (0 &lt; ci ≤ n), then ci integers l1, l2, ..., lci (1 ≤ lj ≤ n) — indices of these elements in the original sequence. Indices could be printed in any order. Every index from 1 to n must appear in output exactly once. If there are several possible answers, print any of them.
standard output
PASSED
a8e9e0e71590580a6f95923f9e2af6f8
train_003.jsonl
1503592500
You are given a sequence a1, a2, ..., an consisting of different integers. It is required to split this sequence into the maximum number of subsequences such that after sorting integers in each of them in increasing order, the total sequence also will be sorted in increasing order.Sorting integers in a subsequence is a process such that the numbers included in a subsequence are ordered in increasing order, and the numbers which are not included in a subsequence don't change their places.Every element of the sequence must appear in exactly one subsequence.
256 megabytes
import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.*; public class Main { public static void main(String[] args) { InputReader in = new InputReader(); PrintWriter out = new PrintWriter(System.out); final long start = System.currentTimeMillis(); new Task1().solve(in, out); @SuppressWarnings("unused") final long duration = System.currentTimeMillis()-start; out.close(); } static class Pair implements Comparable<Pair>{ int first, second; Pair(int first, int second){ this.first = first; this.second = second; } public int compareTo(Pair x){ return first - x.first; } } static class Task1{ static final int MAX = 1000000001; boolean[] marked; ArrayList< ArrayList<Integer> > list; public void solve(InputReader in, PrintWriter out){ int n = in.nextInt(); Pair[] a = new Pair[n]; list = new ArrayList< ArrayList<Integer> >(); for(int i=0; i<n; i++) a[i] = new Pair(in.nextInt(), i); Arrays.sort(a); marked = new boolean[n]; for(int i=0; i<n; i++){ if(!marked[i]){ ArrayList<Integer> curList = new ArrayList<Integer>(); dfs(a, curList, i); list.add(curList); } } out.println(list.size()); for(ArrayList<Integer> curList : list){ out.print(curList.size()+" "); for(Integer i: curList){ out.print((i+1)+" "); } out.println(); } } void dfs(Pair[] a, ArrayList<Integer> curList, int i){ marked[i] = true; curList.add(i); if(!marked[a[i].second]) dfs(a, curList, a[i].second); } int gcd(int a, int b){ while(a>0){ int rem = b%a; b = a; a = rem; } return b; } long expo(long a, long b, long MOD){ long result = 1; while (b>0){ if (b%2==1) result=(result*a) ; b>>=1; a=(a*a) ; } return result ; } long inverseModullo(long numerator, long denominator, long MOD){ return ((numerator )*(expo(denominator, MOD-2, MOD))) ; } } static class InputReader{ static int text = 5; final InputStream stream; final byte[] buf = new byte[8192]; int curChar, numChars; SpaceCharFilter filter; public InputReader(){ this.stream = System.in; } 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 long nextLong(){ int c = read(); while(isSpaceChar(c)) c = read(); int sgn = 1; if(c == '-'){ sgn = -1; c = read(); } long res = 0; do{ if(c<'0' || c>'9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while(!isSpaceChar(c)); return res*sgn; } public String next(){ int c = read(); while(isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do{ res.appendCodePoint(c); c = read(); }while(!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c){ if(filter != null) return filter.isSpaceChar(c); return c==' ' || c=='\n' || c=='\r' || c=='\t' || c==-1; } public interface SpaceCharFilter{ public boolean isSpaceChar(int ch); } } }
Java
["6\n3 2 1 6 5 4", "6\n83 -75 -49 11 37 62"]
1 second
["4\n2 1 3\n1 2\n2 4 6\n1 5", "1\n6 1 2 3 4 5 6"]
NoteIn the first sample output:After sorting the first subsequence we will get sequence 1 2 3 6 5 4.Sorting the second subsequence changes nothing.After sorting the third subsequence we will get sequence 1 2 3 4 5 6.Sorting the last subsequence changes nothing.
Java 8
standard input
[ "dfs and similar", "math" ]
159365b2f037647fbaa656905e6f5252
The first line of input data contains integer n (1 ≤ n ≤ 105) — the length of the sequence. The second line of input data contains n different integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the elements of the sequence. It is guaranteed that all elements of the sequence are distinct.
1,400
In the first line print the maximum number of subsequences k, which the original sequence can be split into while fulfilling the requirements. In the next k lines print the description of subsequences in the following format: the number of elements in subsequence ci (0 &lt; ci ≤ n), then ci integers l1, l2, ..., lci (1 ≤ lj ≤ n) — indices of these elements in the original sequence. Indices could be printed in any order. Every index from 1 to n must appear in output exactly once. If there are several possible answers, print any of them.
standard output
PASSED
25721fc4ab5392105272a0f462470fb2
train_003.jsonl
1503592500
You are given a sequence a1, a2, ..., an consisting of different integers. It is required to split this sequence into the maximum number of subsequences such that after sorting integers in each of them in increasing order, the total sequence also will be sorted in increasing order.Sorting integers in a subsequence is a process such that the numbers included in a subsequence are ordered in increasing order, and the numbers which are not included in a subsequence don't change their places.Every element of the sequence must appear in exactly one subsequence.
256 megabytes
import java.util.*; public class j2 { static ArrayList<Integer> tmp; public static void main(String args[]) { Scanner sc=new Scanner(System.in); int n=sc.nextInt(); int arr[]=new int[n]; HashMap<Integer,Integer> mp = new HashMap<>(); int b[]=new int[n]; for(int i=0;i<n;i++) { arr[i] = sc.nextInt(); b[i]=arr[i]; mp.put(arr[i],i); } Arrays.sort(b); ArrayList<Integer>ard[]=new ArrayList[n+1]; for(int i=0;i<=n;i++) ard[i]=new ArrayList<Integer>(); int p=0; for(int i=0;i<n;i++){ if(arr[i]!=b[i]) { ard[mp.get(b[i])].add(i); ard[i].add(mp.get(b[i])); } } int visited[]=new int[n]; ArrayList<Integer> ans[]= new ArrayList[n+1]; for(int i=0;i<n;i++){ if(visited[i]==0){ tmp=new ArrayList<Integer>(); dfs(visited,i,ard); ans[p]=tmp; p++; } } StringBuilder sb=new StringBuilder(); sb.append(p+"\n"); for(int i=0;i<p;i++){ sb.append(ans[i].size()+" "); for(int j:ans[i]) sb.append((j+1)+" "); sb.append("\n"); } System.out.println(sb.toString()); } public static void dfs(int v[],int i,ArrayList<Integer> ard[]){ if(v[i]==1) return ; v[i]=1; tmp.add(i); Iterator<Integer> it = ard[i].listIterator(); while(it.hasNext()){ int x=it.next(); dfs(v,x,ard); } } }
Java
["6\n3 2 1 6 5 4", "6\n83 -75 -49 11 37 62"]
1 second
["4\n2 1 3\n1 2\n2 4 6\n1 5", "1\n6 1 2 3 4 5 6"]
NoteIn the first sample output:After sorting the first subsequence we will get sequence 1 2 3 6 5 4.Sorting the second subsequence changes nothing.After sorting the third subsequence we will get sequence 1 2 3 4 5 6.Sorting the last subsequence changes nothing.
Java 8
standard input
[ "dfs and similar", "math" ]
159365b2f037647fbaa656905e6f5252
The first line of input data contains integer n (1 ≤ n ≤ 105) — the length of the sequence. The second line of input data contains n different integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the elements of the sequence. It is guaranteed that all elements of the sequence are distinct.
1,400
In the first line print the maximum number of subsequences k, which the original sequence can be split into while fulfilling the requirements. In the next k lines print the description of subsequences in the following format: the number of elements in subsequence ci (0 &lt; ci ≤ n), then ci integers l1, l2, ..., lci (1 ≤ lj ≤ n) — indices of these elements in the original sequence. Indices could be printed in any order. Every index from 1 to n must appear in output exactly once. If there are several possible answers, print any of them.
standard output
PASSED
f3aa9d338d2550ed68a6111630f32f4a
train_003.jsonl
1503592500
You are given a sequence a1, a2, ..., an consisting of different integers. It is required to split this sequence into the maximum number of subsequences such that after sorting integers in each of them in increasing order, the total sequence also will be sorted in increasing order.Sorting integers in a subsequence is a process such that the numbers included in a subsequence are ordered in increasing order, and the numbers which are not included in a subsequence don't change their places.Every element of the sequence must appear in exactly one subsequence.
256 megabytes
/** * All cobbled together from old pieces of code. Took way too long. * If it's even correct. */ import java.io.*; import java.util.*; import java.util.stream.*; public class Subsequences { public static void main(String [] av) { Scanner s = new Scanner(); int n = s.nextInt(); List<Integer> up = new ArrayList<>(); for (int i = 0; i < n; i++) up.add(s.nextInt()); Compressor<Integer> comp = new Compressor<Integer>(new ArrayList<>(up)); //System.err.println("uncompressed: " + up); int [] p = new int[n]; for (int i = 0; i < n; i++) { p[i] = comp.compress(up.get(i)); } //System.err.println("compressed: " + Arrays.toString(p)); List<List<Integer>> C = findCycles (p); StringBuffer out = new StringBuffer(); //System.err.println("cycles: " + C); System.out.println(C.size()); String sep = ""; for (List<Integer> c : C) { out.append(sep); sep = "\n"; out.append(c.size()); out.append(" "); out.append(c.stream().map(i -> Integer.valueOf(i+1).toString()).collect(Collectors.joining(" "))); } System.out.println(out.toString()); } static List<List<Integer>> findCycles (int [] p) { // System.out.println(Arrays.toString(p)); List<List<Integer>> cycles = new ArrayList<>(); boolean [] found = new boolean[p.length]; for (int e = 0; e < p.length; e++) { if (found[e]) continue; int start = e; found[start] = true; int j = start; ArrayList<Integer> cycle = new ArrayList<>(); cycle.add(start); while (p[j] != start) { j = p[j]; cycle.add(j); found[j] = true; } cycles.add(cycle); } return cycles; } /** * Illustration of on-the-fly compression, often used * to compress coordinates. O(n log n). */ static class Compressor<T extends Comparable<T>> { List<T> real; // real (coordinate) values Compressor(List<T> real) { Collections.sort(this.real = real); } // compression, usually called once per realval int compress(T realval) { return Collections.binarySearch(real, realval); } // access original value T uncompress(int compval) { return real.get(compval); } } //-----------Scanner class for faster input---------- /* Provides similar API as java.util.Scanner but does not * use regular expression engine. */ public static class Scanner { BufferedReader br; StringTokenizer st; public Scanner(Reader in) { br = new BufferedReader(in); } public Scanner() { this(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } // Slightly different from java.util.Scanner.nextLine(), // which returns any remaining characters in current line, // if any. String readNextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } //-------------------------------------------------------- }
Java
["6\n3 2 1 6 5 4", "6\n83 -75 -49 11 37 62"]
1 second
["4\n2 1 3\n1 2\n2 4 6\n1 5", "1\n6 1 2 3 4 5 6"]
NoteIn the first sample output:After sorting the first subsequence we will get sequence 1 2 3 6 5 4.Sorting the second subsequence changes nothing.After sorting the third subsequence we will get sequence 1 2 3 4 5 6.Sorting the last subsequence changes nothing.
Java 8
standard input
[ "dfs and similar", "math" ]
159365b2f037647fbaa656905e6f5252
The first line of input data contains integer n (1 ≤ n ≤ 105) — the length of the sequence. The second line of input data contains n different integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the elements of the sequence. It is guaranteed that all elements of the sequence are distinct.
1,400
In the first line print the maximum number of subsequences k, which the original sequence can be split into while fulfilling the requirements. In the next k lines print the description of subsequences in the following format: the number of elements in subsequence ci (0 &lt; ci ≤ n), then ci integers l1, l2, ..., lci (1 ≤ lj ≤ n) — indices of these elements in the original sequence. Indices could be printed in any order. Every index from 1 to n must appear in output exactly once. If there are several possible answers, print any of them.
standard output
PASSED
b114b502d2189922f70009d42ea24c19
train_003.jsonl
1503592500
You are given a sequence a1, a2, ..., an consisting of different integers. It is required to split this sequence into the maximum number of subsequences such that after sorting integers in each of them in increasing order, the total sequence also will be sorted in increasing order.Sorting integers in a subsequence is a process such that the numbers included in a subsequence are ordered in increasing order, and the numbers which are not included in a subsequence don't change their places.Every element of the sequence must appear in exactly one subsequence.
256 megabytes
import java.io.*; import java.nio.ByteBuffer; import java.util.*; /** * Created by imahmoud on 5/13/17. */ public class C { static class Writer { private OutputStream out; public Writer(){ out = new BufferedOutputStream(System.out); } public void println() throws IOException { out.write('\n'); } public void println(String str) throws IOException { this.print(str); out.write('\n'); } public void println(char v) throws IOException { this.print(v); out.write('\n'); } public void println(short v) throws IOException { this.print(v); out.write('\n'); } public void println(int v) throws IOException { this.print(v); out.write('\n'); } public void println(long v) throws IOException { this.print(v); out.write('\n'); } public void println(double v) throws IOException { this.print(v); out.write('\n'); } public void println(float v) throws IOException { this.print(v); out.write('\n'); } public void print(String str) throws IOException { out.write(str.getBytes()); } public void print(char v) throws IOException { out.write(String.valueOf(v).getBytes()); } public void print(short v) throws IOException { out.write(String.valueOf(v).getBytes()); } public void print(int v) throws IOException { out.write(String.valueOf(v).getBytes()); } public void print(long v) throws IOException { out.write(String.valueOf(v).getBytes()); } public void print(double v) throws IOException { out.write(String.valueOf(v).getBytes()); } public void print(float v) throws IOException { out.write(String.valueOf(v).getBytes()); } public void flush() throws IOException { out.flush(); out.close(); } } static class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); 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; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); 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; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } public int findIndex(Long[] a, long key) { int lo = 0; int hi = a.length - 1; while (lo <= hi) { // Key is in a[lo..hi] or not present. int mid = lo + (hi - lo) / 2; if (key < a[mid]) hi = mid - 1; else if (key > a[mid]) lo = mid + 1; else return mid; } return -1; } public void solve() throws IOException { Reader in = new Reader(); Writer out = new Writer(); //PrintStream out = new PrintStream(System.out); int N = in.nextInt(); Long[] arr = new Long[N]; for (int i = 0; i < N; i++) { arr[i] = in.nextLong(); } Long[] arr_s = arr.clone(); Arrays.sort(arr_s); boolean[] visited = new boolean[N]; List<List<Integer>> res = new ArrayList<>(); for (int i = 0; i < N; i++) { if(visited[i]) continue; long l = arr[i]; int t_index = findIndex(arr_s, l); int c_index = i; List<Integer> list = new ArrayList<>(); visited[c_index] = true; list.add(c_index); while (t_index != c_index) { long tmp = arr[c_index]; arr[c_index] = arr[t_index]; arr[t_index] = tmp; visited[t_index] = true; list.add(t_index); t_index = findIndex(arr_s, arr[c_index]); } res.add(list); } out.println(res.size()); for (int i = 0; i < res.size(); i++) { List<Integer> list = res.get(i); out.print(list.size()); for (int j = 0; j < list.size(); j++) { out.print(' '); out.print(list.get(j) + 1); } out.println(); } out.flush(); } public static void main(String[] args) throws Exception{ try { new C().solve(); } catch (IOException e) { e.printStackTrace(); } } }
Java
["6\n3 2 1 6 5 4", "6\n83 -75 -49 11 37 62"]
1 second
["4\n2 1 3\n1 2\n2 4 6\n1 5", "1\n6 1 2 3 4 5 6"]
NoteIn the first sample output:After sorting the first subsequence we will get sequence 1 2 3 6 5 4.Sorting the second subsequence changes nothing.After sorting the third subsequence we will get sequence 1 2 3 4 5 6.Sorting the last subsequence changes nothing.
Java 8
standard input
[ "dfs and similar", "math" ]
159365b2f037647fbaa656905e6f5252
The first line of input data contains integer n (1 ≤ n ≤ 105) — the length of the sequence. The second line of input data contains n different integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the elements of the sequence. It is guaranteed that all elements of the sequence are distinct.
1,400
In the first line print the maximum number of subsequences k, which the original sequence can be split into while fulfilling the requirements. In the next k lines print the description of subsequences in the following format: the number of elements in subsequence ci (0 &lt; ci ≤ n), then ci integers l1, l2, ..., lci (1 ≤ lj ≤ n) — indices of these elements in the original sequence. Indices could be printed in any order. Every index from 1 to n must appear in output exactly once. If there are several possible answers, print any of them.
standard output