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
079592a24210bd801e684b36134a858b
train_003.jsonl
1590327300
Polygon is not only the best platform for developing problems but also a square matrix with side $$$n$$$, initially filled with the character 0.On the polygon, military training was held. The soldiers placed a cannon above each cell in the first row and a cannon to the left of each cell in the first column. Thus, exactly $$$2n$$$ cannons were placed. Initial polygon for $$$n=4$$$. Cannons shoot character 1. At any moment of time, no more than one cannon is shooting. When a 1 flies out of a cannon, it flies forward (in the direction of the shot) until it collides with a polygon border or another 1. After that, it takes the cell in which it was before the collision and remains there. Take a look at the examples for better understanding.More formally: if a cannon stands in the row $$$i$$$, to the left of the first column, and shoots with a 1, then the 1 starts its flight from the cell ($$$i, 1$$$) and ends in some cell ($$$i, j$$$); if a cannon stands in the column $$$j$$$, above the first row, and shoots with a 1, then the 1 starts its flight from the cell ($$$1, j$$$) and ends in some cell ($$$i, j$$$). For example, consider the following sequence of shots: 1. Shoot the cannon in the row $$$2$$$.                         2. Shoot the cannon in the row $$$2$$$.                         3. Shoot the cannon in column $$$3$$$. You have a report from the military training on your desk. This report is a square matrix with side length $$$n$$$ consisting of 0 and 1. You wonder if the training actually happened. In other words, is there a sequence of shots such that, after the training, you get the given matrix?Each cannon can make an arbitrary number of shots. Before the training, each cell of the polygon contains 0.
256 megabytes
import java.io.*; import java.util.ArrayDeque; import java.util.Queue; import java.util.StringTokenizer; public class E_PolygonCannons { private static final BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); private static final PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); private static StringTokenizer st; private static long readLong() throws IOException { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(br.readLine()); } return Long.parseLong(st.nextToken()); } private static String readNext() throws IOException { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(br.readLine()); } return st.nextToken(); } public static void main(String[] args) throws IOException { long T = readLong(); for (int __ = 0; __ < T; __++) { final int n = (int) readLong(); char[] previous = readNext().toCharArray(); boolean done = false; int left = n; while (--left > 0) { char[] current = readNext().toCharArray(); if (!done) { for (int i = 0; i < n - 1; i++) { if (previous[i] == '1' && (previous[i + 1] != '1' && current[i] != '1')) { pw.println("NO"); done = true; break; } } previous = current; } } if (!done) { pw.println("YES"); } } pw.close(); } }
Java
["5\n4\n0010\n0011\n0000\n0000\n2\n10\n01\n2\n00\n00\n4\n0101\n1111\n0101\n0111\n4\n0100\n1110\n0101\n0111"]
2 seconds
["YES\nNO\nYES\nYES\nNO"]
NoteThe first test case was explained in the statement.The answer to the second test case is NO, since a 1 in a cell ($$$1, 1$$$) flying out of any cannon would continue its flight further.
Java 11
standard input
[ "dp", "implementation", "graphs", "shortest paths" ]
eea15ff7e939bfcc7002cacbc8a1a3a5
The first line contains an integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case starts with a line containing an integer $$$n$$$ ($$$1 \le n \le 50$$$) — the size of the polygon. This is followed by $$$n$$$ lines of length $$$n$$$, consisting of 0 and 1 — the polygon matrix after the training. The total area of the matrices in all test cases in one test does not exceed $$$10^5$$$.
1,300
For each test case print: YES if there is a sequence of shots leading to a given matrix; NO if such a sequence does not exist. The letters in the words YES and NO can be printed in any case.
standard output
PASSED
6469b52d360660e723c9c468f4f5c87f
train_003.jsonl
1590327300
Polygon is not only the best platform for developing problems but also a square matrix with side $$$n$$$, initially filled with the character 0.On the polygon, military training was held. The soldiers placed a cannon above each cell in the first row and a cannon to the left of each cell in the first column. Thus, exactly $$$2n$$$ cannons were placed. Initial polygon for $$$n=4$$$. Cannons shoot character 1. At any moment of time, no more than one cannon is shooting. When a 1 flies out of a cannon, it flies forward (in the direction of the shot) until it collides with a polygon border or another 1. After that, it takes the cell in which it was before the collision and remains there. Take a look at the examples for better understanding.More formally: if a cannon stands in the row $$$i$$$, to the left of the first column, and shoots with a 1, then the 1 starts its flight from the cell ($$$i, 1$$$) and ends in some cell ($$$i, j$$$); if a cannon stands in the column $$$j$$$, above the first row, and shoots with a 1, then the 1 starts its flight from the cell ($$$1, j$$$) and ends in some cell ($$$i, j$$$). For example, consider the following sequence of shots: 1. Shoot the cannon in the row $$$2$$$.                         2. Shoot the cannon in the row $$$2$$$.                         3. Shoot the cannon in column $$$3$$$. You have a report from the military training on your desk. This report is a square matrix with side length $$$n$$$ consisting of 0 and 1. You wonder if the training actually happened. In other words, is there a sequence of shots such that, after the training, you get the given matrix?Each cannon can make an arbitrary number of shots. Before the training, each cell of the polygon contains 0.
256 megabytes
import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Stack; import java.util.StringTokenizer; public class Main { public static void main(String[] args) { InputStream inputStream = System.in; Scanner in = new Main().new Scanner(inputStream); Main solver = new Main(); solver.solve(in); } class Node implements Comparable<Node> { int x; int y; public Node(int v, int s) { x = v; y = s; } @Override public int compareTo(Node o) { if (o.y < y) return 1; else if (o.y > y) return -1; return 0; } @Override public String toString() { return "Node[x=" + x + ",y=" + y + "]"; } } public void solve(Scanner in) { int t = in.ni(); for (int i = 0; i < t; i++) { int n = in.ni(); Stack<Node> s = new Stack<>(); boolean[][] visited = new boolean[n][n]; boolean[][] arr = new boolean[n][n]; for (int j = 0; j < n; j++) { String line = in.readLine(); for (int j2 = 0; j2 < n; j2++) { arr[j][j2] = line.charAt(j2) == '1'; if((j2 == n-1 || j == n-1) && arr[j][j2]) s.add(new Node(j, j2)); } } while(!s.empty()) { Node next = s.pop(); if(visited[next.x][next.y]) continue; visited[next.x][next.y] = true; if(next.x > 0 && arr[next.x-1][next.y]) s.add(new Node(next.x - 1, next.y)); if(next.y > 0 && arr[next.x][next.y-1]) s.add(new Node(next.x, next.y-1)); } boolean good = true; for (int j = 0; j < n && good; j++) for (int j2 = 0; j2 < n && good; j2++) if(visited[j][j2] != arr[j][j2]) good = false; System.out.println(good ? "YES" : "NO"); } } class Scanner { BufferedReader br; StringTokenizer in; public Scanner(InputStream inputStream) { br = new BufferedReader(new InputStreamReader(inputStream)); } public String next() { return hasMoreTokens() ? in.nextToken() : null; } public String readLine() { try { return br.readLine(); } catch (Exception e) { e.printStackTrace(); return null; } } boolean hasMoreTokens() { while (in == null || !in.hasMoreTokens()) { String s = readLine(); if (s == null) return false; in = new StringTokenizer(s); } return true; } public String nextString() { return next(); } public int ni() { return Integer.parseInt(nextString()); } public double nd() { return Double.parseDouble(nextString()); } public long nl() { return Long.parseLong(nextString()); } public int[] nia(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = ni(); } return a; } public long[] nla(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) { a[i] = ni(); } return a; } } }
Java
["5\n4\n0010\n0011\n0000\n0000\n2\n10\n01\n2\n00\n00\n4\n0101\n1111\n0101\n0111\n4\n0100\n1110\n0101\n0111"]
2 seconds
["YES\nNO\nYES\nYES\nNO"]
NoteThe first test case was explained in the statement.The answer to the second test case is NO, since a 1 in a cell ($$$1, 1$$$) flying out of any cannon would continue its flight further.
Java 11
standard input
[ "dp", "implementation", "graphs", "shortest paths" ]
eea15ff7e939bfcc7002cacbc8a1a3a5
The first line contains an integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case starts with a line containing an integer $$$n$$$ ($$$1 \le n \le 50$$$) — the size of the polygon. This is followed by $$$n$$$ lines of length $$$n$$$, consisting of 0 and 1 — the polygon matrix after the training. The total area of the matrices in all test cases in one test does not exceed $$$10^5$$$.
1,300
For each test case print: YES if there is a sequence of shots leading to a given matrix; NO if such a sequence does not exist. The letters in the words YES and NO can be printed in any case.
standard output
PASSED
688fc4763671b2a2564d9a8324224f6b
train_003.jsonl
1590327300
Polygon is not only the best platform for developing problems but also a square matrix with side $$$n$$$, initially filled with the character 0.On the polygon, military training was held. The soldiers placed a cannon above each cell in the first row and a cannon to the left of each cell in the first column. Thus, exactly $$$2n$$$ cannons were placed. Initial polygon for $$$n=4$$$. Cannons shoot character 1. At any moment of time, no more than one cannon is shooting. When a 1 flies out of a cannon, it flies forward (in the direction of the shot) until it collides with a polygon border or another 1. After that, it takes the cell in which it was before the collision and remains there. Take a look at the examples for better understanding.More formally: if a cannon stands in the row $$$i$$$, to the left of the first column, and shoots with a 1, then the 1 starts its flight from the cell ($$$i, 1$$$) and ends in some cell ($$$i, j$$$); if a cannon stands in the column $$$j$$$, above the first row, and shoots with a 1, then the 1 starts its flight from the cell ($$$1, j$$$) and ends in some cell ($$$i, j$$$). For example, consider the following sequence of shots: 1. Shoot the cannon in the row $$$2$$$.                         2. Shoot the cannon in the row $$$2$$$.                         3. Shoot the cannon in column $$$3$$$. You have a report from the military training on your desk. This report is a square matrix with side length $$$n$$$ consisting of 0 and 1. You wonder if the training actually happened. In other words, is there a sequence of shots such that, after the training, you get the given matrix?Each cannon can make an arbitrary number of shots. Before the training, each cell of the polygon contains 0.
256 megabytes
import java.util.*; import java.io.*; public class Main { public static void main(String[] args) { // write your code here Scanner in = new Scanner(System.in); int t=in.nextInt(); String []ansarr=new String[t]; for(int i=0;i<t;i++) { int n=in.nextInt(); int [][]mat=new int[n][n]; for(int j=0;j<n;j++) { String p=in.next(); for(int k=0;k<n;k++) { mat[j][k]=Integer.parseInt(String.valueOf(p.charAt(k))); } } int count=0; for(int j=0;j<n-1;j++) { for(int k=0;k<n-1;k++) { if(mat[j][k]==1 & mat[j+1][k]==0 & mat[j][k+1]==0) { count=1; break; } } } if(count==1) { ansarr[i]="NO"; } else { ansarr[i]="YES"; } } for(int i=0;i<t;i++) { System.out.println(ansarr[i]); } } }
Java
["5\n4\n0010\n0011\n0000\n0000\n2\n10\n01\n2\n00\n00\n4\n0101\n1111\n0101\n0111\n4\n0100\n1110\n0101\n0111"]
2 seconds
["YES\nNO\nYES\nYES\nNO"]
NoteThe first test case was explained in the statement.The answer to the second test case is NO, since a 1 in a cell ($$$1, 1$$$) flying out of any cannon would continue its flight further.
Java 11
standard input
[ "dp", "implementation", "graphs", "shortest paths" ]
eea15ff7e939bfcc7002cacbc8a1a3a5
The first line contains an integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case starts with a line containing an integer $$$n$$$ ($$$1 \le n \le 50$$$) — the size of the polygon. This is followed by $$$n$$$ lines of length $$$n$$$, consisting of 0 and 1 — the polygon matrix after the training. The total area of the matrices in all test cases in one test does not exceed $$$10^5$$$.
1,300
For each test case print: YES if there is a sequence of shots leading to a given matrix; NO if such a sequence does not exist. The letters in the words YES and NO can be printed in any case.
standard output
PASSED
3cdabf8bb2101999388b468d9a45136b
train_003.jsonl
1590327300
Polygon is not only the best platform for developing problems but also a square matrix with side $$$n$$$, initially filled with the character 0.On the polygon, military training was held. The soldiers placed a cannon above each cell in the first row and a cannon to the left of each cell in the first column. Thus, exactly $$$2n$$$ cannons were placed. Initial polygon for $$$n=4$$$. Cannons shoot character 1. At any moment of time, no more than one cannon is shooting. When a 1 flies out of a cannon, it flies forward (in the direction of the shot) until it collides with a polygon border or another 1. After that, it takes the cell in which it was before the collision and remains there. Take a look at the examples for better understanding.More formally: if a cannon stands in the row $$$i$$$, to the left of the first column, and shoots with a 1, then the 1 starts its flight from the cell ($$$i, 1$$$) and ends in some cell ($$$i, j$$$); if a cannon stands in the column $$$j$$$, above the first row, and shoots with a 1, then the 1 starts its flight from the cell ($$$1, j$$$) and ends in some cell ($$$i, j$$$). For example, consider the following sequence of shots: 1. Shoot the cannon in the row $$$2$$$.                         2. Shoot the cannon in the row $$$2$$$.                         3. Shoot the cannon in column $$$3$$$. You have a report from the military training on your desk. This report is a square matrix with side length $$$n$$$ consisting of 0 and 1. You wonder if the training actually happened. In other words, is there a sequence of shots such that, after the training, you get the given matrix?Each cannon can make an arbitrary number of shots. Before the training, each cell of the polygon contains 0.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Comparator; import java.util.Random; import java.util.StringTokenizer; public class Main { static ArrayList<Integer>[] gr; static boolean[] was; static boolean[] want_h; static int to; static boolean ans; public static void main(String[] args) throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); // br = new BufferedReader(new FileReader(new File("input.txt"))); // out = new PrintWriter(new File("output.txt")); int PUTEN = nextInt(); for (int PUTIN_POMOGI = 0; PUTIN_POMOGI < PUTEN; PUTIN_POMOGI++) { int n = nextInt(); int[][] a = new int[n][n]; for (int i = 0; i < n; i++) { char[] p = next().toCharArray(); for (int j = 0; j < n; j++) { a[i][j] = p[j] - '0'; } } boolean[][] can = new boolean[n][n]; for (int i = 0; i < n; i++) { int ind = n - 1; while (ind >= 0 && a[i][ind] == 1) { can[i][ind] = true; ind--; } } for (int j = 0; j < n; j++) { int ind = n - 1; while (ind >= 0 && a[ind][j] == 1) { can[ind][j] = true; ind--; } } boolean can_can = true; for (int i = n - 1; i >= 0; i--) { if (!can_can) break; for (int j = n - 1; j >= 0; j--) { if (a[i][j] == 1 && !can[i][j]) { if (i + 1 < n && can[i + 1][j]) { can[i][j] = true; } if (j + 1 < n && can[i][j + 1]) { can[i][j] = true; } if (!can[i][j]) can_can = false; } } } if (can_can) out.println("YES"); else out.println("NO"); } out.close(); } static BufferedReader br; static PrintWriter out; static StringTokenizer in = new StringTokenizer(""); static String next() throws IOException { while (!in.hasMoreTokens()) { in = new StringTokenizer(br.readLine()); } return in.nextToken(); } static long fact(long n) { long ans = 1; for (int i = 1; i < n + 1; i++) { ans *= i; } return ans; } static int[] mix(int[] a) { Random rnd = new Random(); for (int i = 1; i < a.length; i++) { int j = rnd.nextInt(i); int temp = a[i]; a[i] = a[j]; a[j] = temp; } return a; } 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()); } static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } static class sort implements Comparator<point> { @Override public int compare(point o1, point o2) { return Integer.compare(o1.ind, o2.ind); } } static void dfs(int from, String want) { if (ans) return; was[from] = true; if (want_h[from] && want.equals("H")) ans = true; if (!want_h[from] && want.equals("G")) ans = true; for (int p : gr[from]) { if (!was[p]) dfs(p, want); } return; } } class point { int ind; int wight; int speed; public point(int ind, int wight, int speed) { this.ind = ind; this.wight = wight; this.speed = speed; } }
Java
["5\n4\n0010\n0011\n0000\n0000\n2\n10\n01\n2\n00\n00\n4\n0101\n1111\n0101\n0111\n4\n0100\n1110\n0101\n0111"]
2 seconds
["YES\nNO\nYES\nYES\nNO"]
NoteThe first test case was explained in the statement.The answer to the second test case is NO, since a 1 in a cell ($$$1, 1$$$) flying out of any cannon would continue its flight further.
Java 11
standard input
[ "dp", "implementation", "graphs", "shortest paths" ]
eea15ff7e939bfcc7002cacbc8a1a3a5
The first line contains an integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case starts with a line containing an integer $$$n$$$ ($$$1 \le n \le 50$$$) — the size of the polygon. This is followed by $$$n$$$ lines of length $$$n$$$, consisting of 0 and 1 — the polygon matrix after the training. The total area of the matrices in all test cases in one test does not exceed $$$10^5$$$.
1,300
For each test case print: YES if there is a sequence of shots leading to a given matrix; NO if such a sequence does not exist. The letters in the words YES and NO can be printed in any case.
standard output
PASSED
fe0c71126fc9d83962a0e17602113926
train_003.jsonl
1590327300
Polygon is not only the best platform for developing problems but also a square matrix with side $$$n$$$, initially filled with the character 0.On the polygon, military training was held. The soldiers placed a cannon above each cell in the first row and a cannon to the left of each cell in the first column. Thus, exactly $$$2n$$$ cannons were placed. Initial polygon for $$$n=4$$$. Cannons shoot character 1. At any moment of time, no more than one cannon is shooting. When a 1 flies out of a cannon, it flies forward (in the direction of the shot) until it collides with a polygon border or another 1. After that, it takes the cell in which it was before the collision and remains there. Take a look at the examples for better understanding.More formally: if a cannon stands in the row $$$i$$$, to the left of the first column, and shoots with a 1, then the 1 starts its flight from the cell ($$$i, 1$$$) and ends in some cell ($$$i, j$$$); if a cannon stands in the column $$$j$$$, above the first row, and shoots with a 1, then the 1 starts its flight from the cell ($$$1, j$$$) and ends in some cell ($$$i, j$$$). For example, consider the following sequence of shots: 1. Shoot the cannon in the row $$$2$$$.                         2. Shoot the cannon in the row $$$2$$$.                         3. Shoot the cannon in column $$$3$$$. You have a report from the military training on your desk. This report is a square matrix with side length $$$n$$$ consisting of 0 and 1. You wonder if the training actually happened. In other words, is there a sequence of shots such that, after the training, you get the given matrix?Each cannon can make an arbitrary number of shots. Before the training, each cell of the polygon contains 0.
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; public class Main { public static void main(String[] args){ Scanner sc=new Scanner(System.in); int t=sc.nextInt(); while(t-->0){ int n=sc.nextInt(); int[][] ar=new int[n][n]; for(int i=0;i<n;i++){ String x=sc.next(); for(int j=0;j<n;j++){ ar[i][j]=(int)x.charAt(j)-48; } } int f=0; for(int i=0;i<n-1;i++){ for(int j=0;j<n-1;j++){ if(ar[i][j]==1){ // System.out.println(i+" "+j); if(ar[i+1][j]==1 || ar[i][j+1]==1){} else{f=1;break;} } } if(f==1)break; } if(f==0)System.out.println("YES"); else System.out.println("NO"); } } }
Java
["5\n4\n0010\n0011\n0000\n0000\n2\n10\n01\n2\n00\n00\n4\n0101\n1111\n0101\n0111\n4\n0100\n1110\n0101\n0111"]
2 seconds
["YES\nNO\nYES\nYES\nNO"]
NoteThe first test case was explained in the statement.The answer to the second test case is NO, since a 1 in a cell ($$$1, 1$$$) flying out of any cannon would continue its flight further.
Java 11
standard input
[ "dp", "implementation", "graphs", "shortest paths" ]
eea15ff7e939bfcc7002cacbc8a1a3a5
The first line contains an integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case starts with a line containing an integer $$$n$$$ ($$$1 \le n \le 50$$$) — the size of the polygon. This is followed by $$$n$$$ lines of length $$$n$$$, consisting of 0 and 1 — the polygon matrix after the training. The total area of the matrices in all test cases in one test does not exceed $$$10^5$$$.
1,300
For each test case print: YES if there is a sequence of shots leading to a given matrix; NO if such a sequence does not exist. The letters in the words YES and NO can be printed in any case.
standard output
PASSED
bed624fe789e166af648d49790d3400b
train_003.jsonl
1590327300
Polygon is not only the best platform for developing problems but also a square matrix with side $$$n$$$, initially filled with the character 0.On the polygon, military training was held. The soldiers placed a cannon above each cell in the first row and a cannon to the left of each cell in the first column. Thus, exactly $$$2n$$$ cannons were placed. Initial polygon for $$$n=4$$$. Cannons shoot character 1. At any moment of time, no more than one cannon is shooting. When a 1 flies out of a cannon, it flies forward (in the direction of the shot) until it collides with a polygon border or another 1. After that, it takes the cell in which it was before the collision and remains there. Take a look at the examples for better understanding.More formally: if a cannon stands in the row $$$i$$$, to the left of the first column, and shoots with a 1, then the 1 starts its flight from the cell ($$$i, 1$$$) and ends in some cell ($$$i, j$$$); if a cannon stands in the column $$$j$$$, above the first row, and shoots with a 1, then the 1 starts its flight from the cell ($$$1, j$$$) and ends in some cell ($$$i, j$$$). For example, consider the following sequence of shots: 1. Shoot the cannon in the row $$$2$$$.                         2. Shoot the cannon in the row $$$2$$$.                         3. Shoot the cannon in column $$$3$$$. You have a report from the military training on your desk. This report is a square matrix with side length $$$n$$$ consisting of 0 and 1. You wonder if the training actually happened. In other words, is there a sequence of shots such that, after the training, you get the given matrix?Each cannon can make an arbitrary number of shots. Before the training, each cell of the polygon contains 0.
256 megabytes
import java.util.*; import java.lang.Math; public class Polygon{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); int t = sc.nextInt(); for(int u = 0; u < t; u++){ int n = sc.nextInt(); boolean[][] grid = new boolean[n][n]; boolean flag = true; for(int i = 0; i < n; i++){ String temp = sc.next(); for(int j = 0; j < n; j++){ grid[i][j] = (temp.charAt(j) == '1'); //temp = temp%(int)(Math.pow(10, n - j - 1)); //System.out.print( grid[i][j]? 1 : 0 ); } if(i == 0){ continue; } for(int j = 0; j < n-1; j++){ if(grid[i-1][j] && (!(grid[i][j]) && !(grid[i-1][j+1]))){ flag = false; break; } } } System.out.println(flag? "YES" : "NO"); } //System.out.println("end"); } }
Java
["5\n4\n0010\n0011\n0000\n0000\n2\n10\n01\n2\n00\n00\n4\n0101\n1111\n0101\n0111\n4\n0100\n1110\n0101\n0111"]
2 seconds
["YES\nNO\nYES\nYES\nNO"]
NoteThe first test case was explained in the statement.The answer to the second test case is NO, since a 1 in a cell ($$$1, 1$$$) flying out of any cannon would continue its flight further.
Java 11
standard input
[ "dp", "implementation", "graphs", "shortest paths" ]
eea15ff7e939bfcc7002cacbc8a1a3a5
The first line contains an integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case starts with a line containing an integer $$$n$$$ ($$$1 \le n \le 50$$$) — the size of the polygon. This is followed by $$$n$$$ lines of length $$$n$$$, consisting of 0 and 1 — the polygon matrix after the training. The total area of the matrices in all test cases in one test does not exceed $$$10^5$$$.
1,300
For each test case print: YES if there is a sequence of shots leading to a given matrix; NO if such a sequence does not exist. The letters in the words YES and NO can be printed in any case.
standard output
PASSED
80c51aeef4d53ecf3274aa9fbab5f527
train_003.jsonl
1590327300
Polygon is not only the best platform for developing problems but also a square matrix with side $$$n$$$, initially filled with the character 0.On the polygon, military training was held. The soldiers placed a cannon above each cell in the first row and a cannon to the left of each cell in the first column. Thus, exactly $$$2n$$$ cannons were placed. Initial polygon for $$$n=4$$$. Cannons shoot character 1. At any moment of time, no more than one cannon is shooting. When a 1 flies out of a cannon, it flies forward (in the direction of the shot) until it collides with a polygon border or another 1. After that, it takes the cell in which it was before the collision and remains there. Take a look at the examples for better understanding.More formally: if a cannon stands in the row $$$i$$$, to the left of the first column, and shoots with a 1, then the 1 starts its flight from the cell ($$$i, 1$$$) and ends in some cell ($$$i, j$$$); if a cannon stands in the column $$$j$$$, above the first row, and shoots with a 1, then the 1 starts its flight from the cell ($$$1, j$$$) and ends in some cell ($$$i, j$$$). For example, consider the following sequence of shots: 1. Shoot the cannon in the row $$$2$$$.                         2. Shoot the cannon in the row $$$2$$$.                         3. Shoot the cannon in column $$$3$$$. You have a report from the military training on your desk. This report is a square matrix with side length $$$n$$$ consisting of 0 and 1. You wonder if the training actually happened. In other words, is there a sequence of shots such that, after the training, you get the given matrix?Each cannon can make an arbitrary number of shots. Before the training, each cell of the polygon contains 0.
256 megabytes
import java.io.*; import java.util.*; import java.math.*; import java.lang.*; import static java.lang.Math.*; public class Cf182 implements Runnable { 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 Cf182(),"Main",1<<27).start(); } public static long gcd(long a, long b) { if (a == 0) return b; return gcd(b % a, a); } // array sorting by colm public static void sortbyColumn(int arr[][], int col) { Arrays.sort(arr, new Comparator<int[]>() { @Override public int compare(final int[] entry1, final int[] entry2) { if (entry1[col] > entry2[col]) return 1; else return -1; } }); } // gcd public static long findGCD(long arr[], int n) { long result = arr[0]; for (int i = 1; i < n; i++) result = gcd(arr[i], result); return result; } // fibonaci static int fib(int n) { int a = 0, b = 1, c; if (n == 0) return a; for (int i = 2; i <= n; i++) { c = a + b; a = b; b = c; } return b; } // sort a string public static String sortString(String inputString) { char tempArray[] = inputString.toCharArray(); Arrays.sort(tempArray); return new String(tempArray); } // pair function // list.add(new Pair<>(sc.nextInt(), i + 1)); // Collections.sort(list, (a, b) -> Integer.compare(b.first, a.first)); private static class Pair<F, S> { private F first; private S second; public Pair() {} public Pair(F first, S second) { this.first = first; this.second = second; } } public void run() { InputReader sc = new InputReader(System.in); PrintWriter w = new PrintWriter(System.out); 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(); int ans = 0; for(int i=0;i<n-1;i++) { if(ans==1) break; for(int j=0;j<n-1;j++) { if(s[i].charAt(j)=='1') { if(s[i].charAt(j+1)!='1' && s[i+1].charAt(j)!='1') { ans=1; break; } } } } if(ans==0) w.println("YES"); else w.println("NO"); } w.flush(); w.close(); } }
Java
["5\n4\n0010\n0011\n0000\n0000\n2\n10\n01\n2\n00\n00\n4\n0101\n1111\n0101\n0111\n4\n0100\n1110\n0101\n0111"]
2 seconds
["YES\nNO\nYES\nYES\nNO"]
NoteThe first test case was explained in the statement.The answer to the second test case is NO, since a 1 in a cell ($$$1, 1$$$) flying out of any cannon would continue its flight further.
Java 11
standard input
[ "dp", "implementation", "graphs", "shortest paths" ]
eea15ff7e939bfcc7002cacbc8a1a3a5
The first line contains an integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case starts with a line containing an integer $$$n$$$ ($$$1 \le n \le 50$$$) — the size of the polygon. This is followed by $$$n$$$ lines of length $$$n$$$, consisting of 0 and 1 — the polygon matrix after the training. The total area of the matrices in all test cases in one test does not exceed $$$10^5$$$.
1,300
For each test case print: YES if there is a sequence of shots leading to a given matrix; NO if such a sequence does not exist. The letters in the words YES and NO can be printed in any case.
standard output
PASSED
67031e07b59a1520cffb2760881fb7b4
train_003.jsonl
1590327300
Polygon is not only the best platform for developing problems but also a square matrix with side $$$n$$$, initially filled with the character 0.On the polygon, military training was held. The soldiers placed a cannon above each cell in the first row and a cannon to the left of each cell in the first column. Thus, exactly $$$2n$$$ cannons were placed. Initial polygon for $$$n=4$$$. Cannons shoot character 1. At any moment of time, no more than one cannon is shooting. When a 1 flies out of a cannon, it flies forward (in the direction of the shot) until it collides with a polygon border or another 1. After that, it takes the cell in which it was before the collision and remains there. Take a look at the examples for better understanding.More formally: if a cannon stands in the row $$$i$$$, to the left of the first column, and shoots with a 1, then the 1 starts its flight from the cell ($$$i, 1$$$) and ends in some cell ($$$i, j$$$); if a cannon stands in the column $$$j$$$, above the first row, and shoots with a 1, then the 1 starts its flight from the cell ($$$1, j$$$) and ends in some cell ($$$i, j$$$). For example, consider the following sequence of shots: 1. Shoot the cannon in the row $$$2$$$.                         2. Shoot the cannon in the row $$$2$$$.                         3. Shoot the cannon in column $$$3$$$. You have a report from the military training on your desk. This report is a square matrix with side length $$$n$$$ consisting of 0 and 1. You wonder if the training actually happened. In other words, is there a sequence of shots such that, after the training, you get the given matrix?Each cannon can make an arbitrary number of shots. Before the training, each cell of the polygon contains 0.
256 megabytes
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.InputStreamReader; import java.io.FileOutputStream; import java.util.StringTokenizer; public class Polygon{ static BufferedWriter out; static FastReader sc; public static void main(String[] args)throws IOException{ sc = new FastReader(); out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(java.io.FileDescriptor.out),"ASCII"),512); int t = sc.nextInt(); while(t-- > 0){ int n = sc.nextInt(); String[] a = new String[n]; char[][] arr = new char[n][n]; for(int i=0;i<n;i++){ a[i] = sc.nextLine(); for(int j=0;j<n;j++){ arr[i][j] = a[i].charAt(j); } } String op = "YES"; k:for(int i=0;i<n-1;i++){ for(int j=0;j<n-1;j++){ if((arr[i][j] == '1') && ((arr[i+1][j]=='0') && (arr[i][j+1]=='0'))){ op = "NO"; break k; } } } System.out.println(op); } } } 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
["5\n4\n0010\n0011\n0000\n0000\n2\n10\n01\n2\n00\n00\n4\n0101\n1111\n0101\n0111\n4\n0100\n1110\n0101\n0111"]
2 seconds
["YES\nNO\nYES\nYES\nNO"]
NoteThe first test case was explained in the statement.The answer to the second test case is NO, since a 1 in a cell ($$$1, 1$$$) flying out of any cannon would continue its flight further.
Java 11
standard input
[ "dp", "implementation", "graphs", "shortest paths" ]
eea15ff7e939bfcc7002cacbc8a1a3a5
The first line contains an integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case starts with a line containing an integer $$$n$$$ ($$$1 \le n \le 50$$$) — the size of the polygon. This is followed by $$$n$$$ lines of length $$$n$$$, consisting of 0 and 1 — the polygon matrix after the training. The total area of the matrices in all test cases in one test does not exceed $$$10^5$$$.
1,300
For each test case print: YES if there is a sequence of shots leading to a given matrix; NO if such a sequence does not exist. The letters in the words YES and NO can be printed in any case.
standard output
PASSED
14401fcbcfb29370848a17b5853f1e95
train_003.jsonl
1590327300
Polygon is not only the best platform for developing problems but also a square matrix with side $$$n$$$, initially filled with the character 0.On the polygon, military training was held. The soldiers placed a cannon above each cell in the first row and a cannon to the left of each cell in the first column. Thus, exactly $$$2n$$$ cannons were placed. Initial polygon for $$$n=4$$$. Cannons shoot character 1. At any moment of time, no more than one cannon is shooting. When a 1 flies out of a cannon, it flies forward (in the direction of the shot) until it collides with a polygon border or another 1. After that, it takes the cell in which it was before the collision and remains there. Take a look at the examples for better understanding.More formally: if a cannon stands in the row $$$i$$$, to the left of the first column, and shoots with a 1, then the 1 starts its flight from the cell ($$$i, 1$$$) and ends in some cell ($$$i, j$$$); if a cannon stands in the column $$$j$$$, above the first row, and shoots with a 1, then the 1 starts its flight from the cell ($$$1, j$$$) and ends in some cell ($$$i, j$$$). For example, consider the following sequence of shots: 1. Shoot the cannon in the row $$$2$$$.                         2. Shoot the cannon in the row $$$2$$$.                         3. Shoot the cannon in column $$$3$$$. You have a report from the military training on your desk. This report is a square matrix with side length $$$n$$$ consisting of 0 and 1. You wonder if the training actually happened. In other words, is there a sequence of shots such that, after the training, you get the given matrix?Each cannon can make an arbitrary number of shots. Before the training, each cell of the polygon contains 0.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.lang.reflect.Array; import java.math.BigInteger; import java.util.*; public class Main { public static void main(String[] args) throws IOException { int test = GetInput.getInt(); while (test-- > 0) { int n = GetInput.getInt(); char [][]ar = new char[n][]; for (int i = 0 ; i < n; i++){ ar[i] = GetInput.getCharArray(); } boolean flag = false; for (int i = 0 ; i < n-1; i++){ if (flag == true){ break; } for (int j = 0; j < n-1; j++){ if (flag==true){ break; } if (ar[i][j] == '1'){ if (ar[i][j+1] != '1' && ar[i+1][j] != '1'){ System.out.println("NO"); flag = true; } } } } if (!flag) System.out.println("YES"); } } private static int mod(int b) { if (b<0){ return -b; } return b; } private static long max(int in, int in1) { if (in > in1){ return in; } return in1; } private static long min(long in, long in1) { if (in>in1){ return in1; } return in; } } class GetInput { static BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in)); static char[] getCharArray() { char[] charArray; try { StringBuilder string = getInputString(); charArray = new char[string.length()]; for (int i = 0; i < string.length(); i++) { charArray[i] = string.charAt(i); } return charArray; } catch (Exception e) { e.printStackTrace(); } charArray = new char[0]; return charArray; } static int[] getArrayInt() { String[] string; int[] array; try { string = bufferedReader.readLine().split("\\s+"); array = new int[string.length]; for (int i = 0; i < string.length; i++) { array[i] = Integer.parseInt(string[i]); } return array; } catch (IOException e) { e.printStackTrace(); } int[] arra = new int[2]; return arra; } static int getInt() { try { String string = bufferedReader.readLine(); return Integer.parseInt(string); } catch (IOException e) { e.printStackTrace(); } return 0; } static StringBuilder getInputString() { try { StringBuilder string = new StringBuilder(); string.append(bufferedReader.readLine()); return string; } catch (IOException e) { e.printStackTrace(); } return new StringBuilder(); } static long getLongInput() { try { String string = bufferedReader.readLine(); return Long.parseLong(string); } catch (IOException e) { e.printStackTrace(); } return 0; } static long[] getLongArrayInput() { String[] string; long[] array; try { string = bufferedReader.readLine().split("\\s+"); array = new long[string.length]; for (int i = 0; i < string.length; i++) { array[i] = Long.parseLong(string[i]); } return array; } catch (IOException e) { e.printStackTrace(); } long[] arra = new long[2]; return arra; } }
Java
["5\n4\n0010\n0011\n0000\n0000\n2\n10\n01\n2\n00\n00\n4\n0101\n1111\n0101\n0111\n4\n0100\n1110\n0101\n0111"]
2 seconds
["YES\nNO\nYES\nYES\nNO"]
NoteThe first test case was explained in the statement.The answer to the second test case is NO, since a 1 in a cell ($$$1, 1$$$) flying out of any cannon would continue its flight further.
Java 11
standard input
[ "dp", "implementation", "graphs", "shortest paths" ]
eea15ff7e939bfcc7002cacbc8a1a3a5
The first line contains an integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case starts with a line containing an integer $$$n$$$ ($$$1 \le n \le 50$$$) — the size of the polygon. This is followed by $$$n$$$ lines of length $$$n$$$, consisting of 0 and 1 — the polygon matrix after the training. The total area of the matrices in all test cases in one test does not exceed $$$10^5$$$.
1,300
For each test case print: YES if there is a sequence of shots leading to a given matrix; NO if such a sequence does not exist. The letters in the words YES and NO can be printed in any case.
standard output
PASSED
b9e2653f8e70771c22726acf97c990c0
train_003.jsonl
1590327300
Polygon is not only the best platform for developing problems but also a square matrix with side $$$n$$$, initially filled with the character 0.On the polygon, military training was held. The soldiers placed a cannon above each cell in the first row and a cannon to the left of each cell in the first column. Thus, exactly $$$2n$$$ cannons were placed. Initial polygon for $$$n=4$$$. Cannons shoot character 1. At any moment of time, no more than one cannon is shooting. When a 1 flies out of a cannon, it flies forward (in the direction of the shot) until it collides with a polygon border or another 1. After that, it takes the cell in which it was before the collision and remains there. Take a look at the examples for better understanding.More formally: if a cannon stands in the row $$$i$$$, to the left of the first column, and shoots with a 1, then the 1 starts its flight from the cell ($$$i, 1$$$) and ends in some cell ($$$i, j$$$); if a cannon stands in the column $$$j$$$, above the first row, and shoots with a 1, then the 1 starts its flight from the cell ($$$1, j$$$) and ends in some cell ($$$i, j$$$). For example, consider the following sequence of shots: 1. Shoot the cannon in the row $$$2$$$.                         2. Shoot the cannon in the row $$$2$$$.                         3. Shoot the cannon in column $$$3$$$. You have a report from the military training on your desk. This report is a square matrix with side length $$$n$$$ consisting of 0 and 1. You wonder if the training actually happened. In other words, is there a sequence of shots such that, after the training, you get the given matrix?Each cannon can make an arbitrary number of shots. Before the training, each cell of the polygon contains 0.
256 megabytes
import java.io.*; import java.util.*; public class E { static Scanner sc = new Scanner(System.in); static PrintWriter pw = new PrintWriter(System.out); static void solve() { int n = sc.nextInt(); int[][] matrix = new int[n][n]; for (int i = 0; i < n; i ++){ char[] s = sc.next().toCharArray(); for (int j = 0; j < n; j ++){ matrix[i][j] = Integer.parseInt(String.valueOf(s[j])); } } for (int i = 0; i < n; i ++){ for (int j = 0; j < n; j ++){ if (matrix[i][j] == 1){ boolean below = false; boolean right = false; if (i < n - 1){ if (matrix[i + 1][j] == 1){ below = true; } } else { below = true; } if (j < n - 1){ if (matrix[i][j + 1] == 1){ right = true; } } else { right = true; } if (!right && !below){ pw.println("NO"); return; } } } } pw.println("YES"); } public static void main(String[] args){ int t = sc.nextInt(); for (int i = 0; i < t; i ++){ solve(); } // solve(); pw.close(); } }
Java
["5\n4\n0010\n0011\n0000\n0000\n2\n10\n01\n2\n00\n00\n4\n0101\n1111\n0101\n0111\n4\n0100\n1110\n0101\n0111"]
2 seconds
["YES\nNO\nYES\nYES\nNO"]
NoteThe first test case was explained in the statement.The answer to the second test case is NO, since a 1 in a cell ($$$1, 1$$$) flying out of any cannon would continue its flight further.
Java 11
standard input
[ "dp", "implementation", "graphs", "shortest paths" ]
eea15ff7e939bfcc7002cacbc8a1a3a5
The first line contains an integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case starts with a line containing an integer $$$n$$$ ($$$1 \le n \le 50$$$) — the size of the polygon. This is followed by $$$n$$$ lines of length $$$n$$$, consisting of 0 and 1 — the polygon matrix after the training. The total area of the matrices in all test cases in one test does not exceed $$$10^5$$$.
1,300
For each test case print: YES if there is a sequence of shots leading to a given matrix; NO if such a sequence does not exist. The letters in the words YES and NO can be printed in any case.
standard output
PASSED
4af78f2fc680738047b4cb4c1b978648
train_003.jsonl
1590327300
Polygon is not only the best platform for developing problems but also a square matrix with side $$$n$$$, initially filled with the character 0.On the polygon, military training was held. The soldiers placed a cannon above each cell in the first row and a cannon to the left of each cell in the first column. Thus, exactly $$$2n$$$ cannons were placed. Initial polygon for $$$n=4$$$. Cannons shoot character 1. At any moment of time, no more than one cannon is shooting. When a 1 flies out of a cannon, it flies forward (in the direction of the shot) until it collides with a polygon border or another 1. After that, it takes the cell in which it was before the collision and remains there. Take a look at the examples for better understanding.More formally: if a cannon stands in the row $$$i$$$, to the left of the first column, and shoots with a 1, then the 1 starts its flight from the cell ($$$i, 1$$$) and ends in some cell ($$$i, j$$$); if a cannon stands in the column $$$j$$$, above the first row, and shoots with a 1, then the 1 starts its flight from the cell ($$$1, j$$$) and ends in some cell ($$$i, j$$$). For example, consider the following sequence of shots: 1. Shoot the cannon in the row $$$2$$$.                         2. Shoot the cannon in the row $$$2$$$.                         3. Shoot the cannon in column $$$3$$$. You have a report from the military training on your desk. This report is a square matrix with side length $$$n$$$ consisting of 0 and 1. You wonder if the training actually happened. In other words, is there a sequence of shots such that, after the training, you get the given matrix?Each cannon can make an arbitrary number of shots. Before the training, each cell of the polygon contains 0.
256 megabytes
/* package codechef; // don't place package name! */ import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; import java.util.*; public class HelloWorld{ public static void main(String []args){ Scanner input = new Scanner(System.in); input.next(); while(input.hasNext()){ int n=input.nextInt(); int[][] l=new int[n][n]; for(int i=0;i<n;i++){ String st=input.next(); for(int j=0;j<n;j++){ l[i][j]=Integer.parseInt(st.substring(j, j+1)); } } bfs(l, n); boolean f=true; for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ if(l[i][j]==1){ f=false; } } } if(f){ System.out.println("YES"); } else{ System.out.println("NO"); } } } public static void bfs(int[][] l, int n){ Queue<int[]> q=new LinkedList<>(); for(int i=0;i<n;i++){ if(l[i][n-1]==1){ l[i][n-1]=0; q.add(new int[]{i, n-1}); } if(l[n-1][i]==1){ l[n-1][i]=0; q.add(new int[]{n-1, i}); } } while(!q.isEmpty()){ int[] s=q.poll(); if(s[0]>0){ if(l[s[0]-1][s[1]]==1){ l[s[0]-1][s[1]]=0; q.add(new int[]{s[0]-1, s[1]}); } } if(s[1]>0){ if(l[s[0]][s[1]-1]==1){ l[s[0]][s[1]-1]=0; q.add(new int[]{s[0], s[1]-1}); } } } } }
Java
["5\n4\n0010\n0011\n0000\n0000\n2\n10\n01\n2\n00\n00\n4\n0101\n1111\n0101\n0111\n4\n0100\n1110\n0101\n0111"]
2 seconds
["YES\nNO\nYES\nYES\nNO"]
NoteThe first test case was explained in the statement.The answer to the second test case is NO, since a 1 in a cell ($$$1, 1$$$) flying out of any cannon would continue its flight further.
Java 11
standard input
[ "dp", "implementation", "graphs", "shortest paths" ]
eea15ff7e939bfcc7002cacbc8a1a3a5
The first line contains an integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case starts with a line containing an integer $$$n$$$ ($$$1 \le n \le 50$$$) — the size of the polygon. This is followed by $$$n$$$ lines of length $$$n$$$, consisting of 0 and 1 — the polygon matrix after the training. The total area of the matrices in all test cases in one test does not exceed $$$10^5$$$.
1,300
For each test case print: YES if there is a sequence of shots leading to a given matrix; NO if such a sequence does not exist. The letters in the words YES and NO can be printed in any case.
standard output
PASSED
a18f22fac413071e99de9b71d309f9b7
train_003.jsonl
1590327300
Polygon is not only the best platform for developing problems but also a square matrix with side $$$n$$$, initially filled with the character 0.On the polygon, military training was held. The soldiers placed a cannon above each cell in the first row and a cannon to the left of each cell in the first column. Thus, exactly $$$2n$$$ cannons were placed. Initial polygon for $$$n=4$$$. Cannons shoot character 1. At any moment of time, no more than one cannon is shooting. When a 1 flies out of a cannon, it flies forward (in the direction of the shot) until it collides with a polygon border or another 1. After that, it takes the cell in which it was before the collision and remains there. Take a look at the examples for better understanding.More formally: if a cannon stands in the row $$$i$$$, to the left of the first column, and shoots with a 1, then the 1 starts its flight from the cell ($$$i, 1$$$) and ends in some cell ($$$i, j$$$); if a cannon stands in the column $$$j$$$, above the first row, and shoots with a 1, then the 1 starts its flight from the cell ($$$1, j$$$) and ends in some cell ($$$i, j$$$). For example, consider the following sequence of shots: 1. Shoot the cannon in the row $$$2$$$.                         2. Shoot the cannon in the row $$$2$$$.                         3. Shoot the cannon in column $$$3$$$. You have a report from the military training on your desk. This report is a square matrix with side length $$$n$$$ consisting of 0 and 1. You wonder if the training actually happened. In other words, is there a sequence of shots such that, after the training, you get the given matrix?Each cannon can make an arbitrary number of shots. Before the training, each cell of the polygon contains 0.
256 megabytes
import java.util.Scanner; public class CF1360E { static Scanner sc = new Scanner(System.in); public static void main(String[] args) { int t = Integer.parseInt(sc.nextLine()); testcase: while (t-- > 0) { int n = Integer.parseInt(sc.nextLine()); boolean [][]trainingReport = new boolean[n][n]; for (int i = 0; i < n; i++) { String rowI = sc.nextLine(); for (int j = 0; j < n; j++) trainingReport[i][j] = rowI.charAt(j) == '1'; } boolean [][]reportCheck = new boolean[n][n]; dfsOnMatrices(trainingReport, reportCheck); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (reportCheck[i][j] != trainingReport[i][j]) { System.out.println("NO"); continue testcase; } } } System.out.println("YES"); } } private static void dfsOnMatrices(boolean [][]trainingReport, boolean [][]reportCheck) { for (int i = 0; i < trainingReport.length; i++) { dfsOnMatrices(trainingReport, reportCheck, trainingReport.length - 1, i); dfsOnMatrices(trainingReport, reportCheck, i, trainingReport.length - 1); } } private static void dfsOnMatrices(boolean [][]trainingReport, boolean [][]reportCheck, int i, int j) { if (i < 0 || i >= trainingReport.length || j < 0 || j >= trainingReport.length) return; if (!trainingReport[i][j]) return; if (reportCheck[i][j]) return; reportCheck[i][j] = true; dfsOnMatrices(trainingReport, reportCheck, i - 1, j); dfsOnMatrices(trainingReport, reportCheck, i, j - 1); } }
Java
["5\n4\n0010\n0011\n0000\n0000\n2\n10\n01\n2\n00\n00\n4\n0101\n1111\n0101\n0111\n4\n0100\n1110\n0101\n0111"]
2 seconds
["YES\nNO\nYES\nYES\nNO"]
NoteThe first test case was explained in the statement.The answer to the second test case is NO, since a 1 in a cell ($$$1, 1$$$) flying out of any cannon would continue its flight further.
Java 11
standard input
[ "dp", "implementation", "graphs", "shortest paths" ]
eea15ff7e939bfcc7002cacbc8a1a3a5
The first line contains an integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case starts with a line containing an integer $$$n$$$ ($$$1 \le n \le 50$$$) — the size of the polygon. This is followed by $$$n$$$ lines of length $$$n$$$, consisting of 0 and 1 — the polygon matrix after the training. The total area of the matrices in all test cases in one test does not exceed $$$10^5$$$.
1,300
For each test case print: YES if there is a sequence of shots leading to a given matrix; NO if such a sequence does not exist. The letters in the words YES and NO can be printed in any case.
standard output
PASSED
ac69bb617644a6218ab1486579519b6c
train_003.jsonl
1590327300
Polygon is not only the best platform for developing problems but also a square matrix with side $$$n$$$, initially filled with the character 0.On the polygon, military training was held. The soldiers placed a cannon above each cell in the first row and a cannon to the left of each cell in the first column. Thus, exactly $$$2n$$$ cannons were placed. Initial polygon for $$$n=4$$$. Cannons shoot character 1. At any moment of time, no more than one cannon is shooting. When a 1 flies out of a cannon, it flies forward (in the direction of the shot) until it collides with a polygon border or another 1. After that, it takes the cell in which it was before the collision and remains there. Take a look at the examples for better understanding.More formally: if a cannon stands in the row $$$i$$$, to the left of the first column, and shoots with a 1, then the 1 starts its flight from the cell ($$$i, 1$$$) and ends in some cell ($$$i, j$$$); if a cannon stands in the column $$$j$$$, above the first row, and shoots with a 1, then the 1 starts its flight from the cell ($$$1, j$$$) and ends in some cell ($$$i, j$$$). For example, consider the following sequence of shots: 1. Shoot the cannon in the row $$$2$$$.                         2. Shoot the cannon in the row $$$2$$$.                         3. Shoot the cannon in column $$$3$$$. You have a report from the military training on your desk. This report is a square matrix with side length $$$n$$$ consisting of 0 and 1. You wonder if the training actually happened. In other words, is there a sequence of shots such that, after the training, you get the given matrix?Each cannon can make an arbitrary number of shots. Before the training, each cell of the polygon contains 0.
256 megabytes
import java.io.*; import java.util.*; public class D { public static void main(String[] args) { int t = sc.nextInt(); while(t-- > 0) solve(); out.close(); } private static void solve() { int n = sc.nextInt(); char[][] grid = new char[n][n]; for(int i = 0; i < n; i++) grid[i] = sc.next().toCharArray(); for(int i = 0; i < n - 1; i ++) { for(int j = 0; j < n - 1; j++) { if(grid[i][j] == '0') continue; if(grid[i+1][j] == '0' && grid[i][j+1] == '0') { out.println("NO"); return; } } } out.println("YES"); } public static PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); public static FastScanner sc = new FastScanner(); 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
["5\n4\n0010\n0011\n0000\n0000\n2\n10\n01\n2\n00\n00\n4\n0101\n1111\n0101\n0111\n4\n0100\n1110\n0101\n0111"]
2 seconds
["YES\nNO\nYES\nYES\nNO"]
NoteThe first test case was explained in the statement.The answer to the second test case is NO, since a 1 in a cell ($$$1, 1$$$) flying out of any cannon would continue its flight further.
Java 11
standard input
[ "dp", "implementation", "graphs", "shortest paths" ]
eea15ff7e939bfcc7002cacbc8a1a3a5
The first line contains an integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case starts with a line containing an integer $$$n$$$ ($$$1 \le n \le 50$$$) — the size of the polygon. This is followed by $$$n$$$ lines of length $$$n$$$, consisting of 0 and 1 — the polygon matrix after the training. The total area of the matrices in all test cases in one test does not exceed $$$10^5$$$.
1,300
For each test case print: YES if there is a sequence of shots leading to a given matrix; NO if such a sequence does not exist. The letters in the words YES and NO can be printed in any case.
standard output
PASSED
33f0194e89c24e466de146c04a9a07b9
train_003.jsonl
1590327300
Polygon is not only the best platform for developing problems but also a square matrix with side $$$n$$$, initially filled with the character 0.On the polygon, military training was held. The soldiers placed a cannon above each cell in the first row and a cannon to the left of each cell in the first column. Thus, exactly $$$2n$$$ cannons were placed. Initial polygon for $$$n=4$$$. Cannons shoot character 1. At any moment of time, no more than one cannon is shooting. When a 1 flies out of a cannon, it flies forward (in the direction of the shot) until it collides with a polygon border or another 1. After that, it takes the cell in which it was before the collision and remains there. Take a look at the examples for better understanding.More formally: if a cannon stands in the row $$$i$$$, to the left of the first column, and shoots with a 1, then the 1 starts its flight from the cell ($$$i, 1$$$) and ends in some cell ($$$i, j$$$); if a cannon stands in the column $$$j$$$, above the first row, and shoots with a 1, then the 1 starts its flight from the cell ($$$1, j$$$) and ends in some cell ($$$i, j$$$). For example, consider the following sequence of shots: 1. Shoot the cannon in the row $$$2$$$.                         2. Shoot the cannon in the row $$$2$$$.                         3. Shoot the cannon in column $$$3$$$. You have a report from the military training on your desk. This report is a square matrix with side length $$$n$$$ consisting of 0 and 1. You wonder if the training actually happened. In other words, is there a sequence of shots such that, after the training, you get the given matrix?Each cannon can make an arbitrary number of shots. Before the training, each cell of the polygon contains 0.
256 megabytes
import java.util.Scanner; public class Polygon { public static void main(String[] args) { // TODO Auto-generated method stub Scanner s=new Scanner(System.in); int t=s.nextInt(); for(int i=0;i<t;i++) { int n=s.nextInt(); String[] box=new String[n]; for(int j=0;j<n;j++) { box[j]=s.next(); } boolean ans=true; for(int j=0;j<n;j++) { for(int k=0;k<n;k++) { if(box[j].charAt(k)=='1' ) { if( ((k+1)<n && box[j].charAt(k+1)!='1') &&( (j+1)<n && box[j+1].charAt(k)!='1' ) ) { ans=false; break; } } } } if(ans) System.out.println("YES"); else { System.out.println("NO"); } } } }
Java
["5\n4\n0010\n0011\n0000\n0000\n2\n10\n01\n2\n00\n00\n4\n0101\n1111\n0101\n0111\n4\n0100\n1110\n0101\n0111"]
2 seconds
["YES\nNO\nYES\nYES\nNO"]
NoteThe first test case was explained in the statement.The answer to the second test case is NO, since a 1 in a cell ($$$1, 1$$$) flying out of any cannon would continue its flight further.
Java 11
standard input
[ "dp", "implementation", "graphs", "shortest paths" ]
eea15ff7e939bfcc7002cacbc8a1a3a5
The first line contains an integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case starts with a line containing an integer $$$n$$$ ($$$1 \le n \le 50$$$) — the size of the polygon. This is followed by $$$n$$$ lines of length $$$n$$$, consisting of 0 and 1 — the polygon matrix after the training. The total area of the matrices in all test cases in one test does not exceed $$$10^5$$$.
1,300
For each test case print: YES if there is a sequence of shots leading to a given matrix; NO if such a sequence does not exist. The letters in the words YES and NO can be printed in any case.
standard output
PASSED
a3b30b0e5abfb42c31846c8e58acddae
train_003.jsonl
1590327300
Polygon is not only the best platform for developing problems but also a square matrix with side $$$n$$$, initially filled with the character 0.On the polygon, military training was held. The soldiers placed a cannon above each cell in the first row and a cannon to the left of each cell in the first column. Thus, exactly $$$2n$$$ cannons were placed. Initial polygon for $$$n=4$$$. Cannons shoot character 1. At any moment of time, no more than one cannon is shooting. When a 1 flies out of a cannon, it flies forward (in the direction of the shot) until it collides with a polygon border or another 1. After that, it takes the cell in which it was before the collision and remains there. Take a look at the examples for better understanding.More formally: if a cannon stands in the row $$$i$$$, to the left of the first column, and shoots with a 1, then the 1 starts its flight from the cell ($$$i, 1$$$) and ends in some cell ($$$i, j$$$); if a cannon stands in the column $$$j$$$, above the first row, and shoots with a 1, then the 1 starts its flight from the cell ($$$1, j$$$) and ends in some cell ($$$i, j$$$). For example, consider the following sequence of shots: 1. Shoot the cannon in the row $$$2$$$.                         2. Shoot the cannon in the row $$$2$$$.                         3. Shoot the cannon in column $$$3$$$. You have a report from the military training on your desk. This report is a square matrix with side length $$$n$$$ consisting of 0 and 1. You wonder if the training actually happened. In other words, is there a sequence of shots such that, after the training, you get the given matrix?Each cannon can make an arbitrary number of shots. Before the training, each cell of the polygon contains 0.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class Learning { public static void main(String[] args) throws Exception { FastInput in = new FastInput(); StringBuilder st = new StringBuilder(); int t = in.nextInt(); while (t-- > 0) { int n = in.nextInt(); int[][] arr = new int[n][n]; for (int i = 0; i < n; i++) { String s = in.next(); for (int j = 0; j < n; j++) { arr[i][j] = s.charAt(j)-'0'; } } String ans = solve(arr, n); st.append(ans + "\n"); } System.out.println(st.toString()); } private static String solve(int[][] arr, int n) { int[][] dp = new int[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (arr[i][j] == 1) { if (!DFS(i, j, arr, dp, n)) { return "NO"; } } } } return "YES"; } private static boolean DFS(int x, int y, int[][] arr, int[][] dp, int n) { if (dp[x][y] == 1) return true; else if (dp[x][y] == -1) return false; if (x == n - 1 || y == n - 1) { dp[x][y] = 1; return true; } int[][] r = new int[][]{{1, 0}, {0, 1}}; for (int[] ints : r) { int newx = x + ints[0]; int newy = y + ints[1]; if (arr[newx][newy] == 1) { if (DFS(newx, newy, arr, dp, n)) { dp[x][y] = 1; return true; } } } dp[x][y] = -1; return false; } } class FastInput { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st; String next() throws IOException { if (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } Integer nextInt() throws IOException { return Integer.parseInt(next()); } Long nextLong() throws IOException { return Long.parseLong(next()); } }
Java
["5\n4\n0010\n0011\n0000\n0000\n2\n10\n01\n2\n00\n00\n4\n0101\n1111\n0101\n0111\n4\n0100\n1110\n0101\n0111"]
2 seconds
["YES\nNO\nYES\nYES\nNO"]
NoteThe first test case was explained in the statement.The answer to the second test case is NO, since a 1 in a cell ($$$1, 1$$$) flying out of any cannon would continue its flight further.
Java 11
standard input
[ "dp", "implementation", "graphs", "shortest paths" ]
eea15ff7e939bfcc7002cacbc8a1a3a5
The first line contains an integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case starts with a line containing an integer $$$n$$$ ($$$1 \le n \le 50$$$) — the size of the polygon. This is followed by $$$n$$$ lines of length $$$n$$$, consisting of 0 and 1 — the polygon matrix after the training. The total area of the matrices in all test cases in one test does not exceed $$$10^5$$$.
1,300
For each test case print: YES if there is a sequence of shots leading to a given matrix; NO if such a sequence does not exist. The letters in the words YES and NO can be printed in any case.
standard output
PASSED
5879fc7b3e8f1d93556a628c5e1b86fa
train_003.jsonl
1590327300
Polygon is not only the best platform for developing problems but also a square matrix with side $$$n$$$, initially filled with the character 0.On the polygon, military training was held. The soldiers placed a cannon above each cell in the first row and a cannon to the left of each cell in the first column. Thus, exactly $$$2n$$$ cannons were placed. Initial polygon for $$$n=4$$$. Cannons shoot character 1. At any moment of time, no more than one cannon is shooting. When a 1 flies out of a cannon, it flies forward (in the direction of the shot) until it collides with a polygon border or another 1. After that, it takes the cell in which it was before the collision and remains there. Take a look at the examples for better understanding.More formally: if a cannon stands in the row $$$i$$$, to the left of the first column, and shoots with a 1, then the 1 starts its flight from the cell ($$$i, 1$$$) and ends in some cell ($$$i, j$$$); if a cannon stands in the column $$$j$$$, above the first row, and shoots with a 1, then the 1 starts its flight from the cell ($$$1, j$$$) and ends in some cell ($$$i, j$$$). For example, consider the following sequence of shots: 1. Shoot the cannon in the row $$$2$$$.                         2. Shoot the cannon in the row $$$2$$$.                         3. Shoot the cannon in column $$$3$$$. You have a report from the military training on your desk. This report is a square matrix with side length $$$n$$$ consisting of 0 and 1. You wonder if the training actually happened. In other words, is there a sequence of shots such that, after the training, you get the given matrix?Each cannon can make an arbitrary number of shots. Before the training, each cell of the polygon contains 0.
256 megabytes
import java.util.*; import java.io.*; public class cf { public static void main(String[] args) { FastReader in = new FastReader(); int t = in.nextInt(); while(t-- >0) { int n = in.nextInt(); boolean flag = false; int[][] arr = new int[n][n]; for(int i=0;i<n;++i) { String row = in.next(); for(int j=0;j<n;++j) { arr[i][j] = Character.getNumericValue(row.charAt(j)); } } for(int i=0;i<n-1;++i) { for(int j=0;j<n-1;++j) { if(arr[i][j]==1) { int val = (arr[i+1][j] | arr[i][j+1]) ; if(val==1) continue; else { flag = true; break; } } } } if(!flag) System.out.println("YES"); else System.out.println("NO"); } } 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()); } char nextChar() { return next().charAt(0); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } int[] nextIntArray(int n) { int[] arr = new int[n]; String[] str = nextLine().split(" "); for(int i=0;i<n;i++) arr[i] = Integer.parseInt(str[i]); return arr; } } }
Java
["5\n4\n0010\n0011\n0000\n0000\n2\n10\n01\n2\n00\n00\n4\n0101\n1111\n0101\n0111\n4\n0100\n1110\n0101\n0111"]
2 seconds
["YES\nNO\nYES\nYES\nNO"]
NoteThe first test case was explained in the statement.The answer to the second test case is NO, since a 1 in a cell ($$$1, 1$$$) flying out of any cannon would continue its flight further.
Java 11
standard input
[ "dp", "implementation", "graphs", "shortest paths" ]
eea15ff7e939bfcc7002cacbc8a1a3a5
The first line contains an integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case starts with a line containing an integer $$$n$$$ ($$$1 \le n \le 50$$$) — the size of the polygon. This is followed by $$$n$$$ lines of length $$$n$$$, consisting of 0 and 1 — the polygon matrix after the training. The total area of the matrices in all test cases in one test does not exceed $$$10^5$$$.
1,300
For each test case print: YES if there is a sequence of shots leading to a given matrix; NO if such a sequence does not exist. The letters in the words YES and NO can be printed in any case.
standard output
PASSED
7c2bcf7987b4b42149dc199d2c02c4d3
train_003.jsonl
1590327300
Polygon is not only the best platform for developing problems but also a square matrix with side $$$n$$$, initially filled with the character 0.On the polygon, military training was held. The soldiers placed a cannon above each cell in the first row and a cannon to the left of each cell in the first column. Thus, exactly $$$2n$$$ cannons were placed. Initial polygon for $$$n=4$$$. Cannons shoot character 1. At any moment of time, no more than one cannon is shooting. When a 1 flies out of a cannon, it flies forward (in the direction of the shot) until it collides with a polygon border or another 1. After that, it takes the cell in which it was before the collision and remains there. Take a look at the examples for better understanding.More formally: if a cannon stands in the row $$$i$$$, to the left of the first column, and shoots with a 1, then the 1 starts its flight from the cell ($$$i, 1$$$) and ends in some cell ($$$i, j$$$); if a cannon stands in the column $$$j$$$, above the first row, and shoots with a 1, then the 1 starts its flight from the cell ($$$1, j$$$) and ends in some cell ($$$i, j$$$). For example, consider the following sequence of shots: 1. Shoot the cannon in the row $$$2$$$.                         2. Shoot the cannon in the row $$$2$$$.                         3. Shoot the cannon in column $$$3$$$. You have a report from the military training on your desk. This report is a square matrix with side length $$$n$$$ consisting of 0 and 1. You wonder if the training actually happened. In other words, is there a sequence of shots such that, after the training, you get the given matrix?Each cannon can make an arbitrary number of shots. Before the training, each cell of the polygon contains 0.
256 megabytes
import java.util.*; import java.io.*; public class cf { static boolean multiple_testcases = true; static FastReader in = new FastReader(); static void solve() { int n = in.nextInt(); boolean flag = false; int[][] arr = new int[n][n]; for(int i=0;i<n;++i) { String row = in.next(); for(int j=0;j<n;++j) { arr[i][j] = Character.getNumericValue(row.charAt(j)); } } for(int i=0;i<n-1;++i) { for(int j=0;j<n-1;++j) { if(arr[i][j]==1) { int val = (arr[i+1][j] | arr[i][j+1]) ; if(val==1) continue; else { flag = true; break; } } } } if(!flag) System.out.println("YES"); else System.out.println("NO"); } public static void main(String[] args) { if(multiple_testcases) { int t = in.nextInt(); while(t-- >0) solve(); } else solve(); } 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()); } char nextChar() { return next().charAt(0); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } int[] nextIntArray(int n) { int[] arr = new int[n]; String[] str = nextLine().split(" "); for(int i=0;i<n;i++) arr[i] = Integer.parseInt(str[i]); return arr; } } }
Java
["5\n4\n0010\n0011\n0000\n0000\n2\n10\n01\n2\n00\n00\n4\n0101\n1111\n0101\n0111\n4\n0100\n1110\n0101\n0111"]
2 seconds
["YES\nNO\nYES\nYES\nNO"]
NoteThe first test case was explained in the statement.The answer to the second test case is NO, since a 1 in a cell ($$$1, 1$$$) flying out of any cannon would continue its flight further.
Java 11
standard input
[ "dp", "implementation", "graphs", "shortest paths" ]
eea15ff7e939bfcc7002cacbc8a1a3a5
The first line contains an integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case starts with a line containing an integer $$$n$$$ ($$$1 \le n \le 50$$$) — the size of the polygon. This is followed by $$$n$$$ lines of length $$$n$$$, consisting of 0 and 1 — the polygon matrix after the training. The total area of the matrices in all test cases in one test does not exceed $$$10^5$$$.
1,300
For each test case print: YES if there is a sequence of shots leading to a given matrix; NO if such a sequence does not exist. The letters in the words YES and NO can be printed in any case.
standard output
PASSED
cf3736617d20b44a727332f87c38bcd6
train_003.jsonl
1590327300
Polygon is not only the best platform for developing problems but also a square matrix with side $$$n$$$, initially filled with the character 0.On the polygon, military training was held. The soldiers placed a cannon above each cell in the first row and a cannon to the left of each cell in the first column. Thus, exactly $$$2n$$$ cannons were placed. Initial polygon for $$$n=4$$$. Cannons shoot character 1. At any moment of time, no more than one cannon is shooting. When a 1 flies out of a cannon, it flies forward (in the direction of the shot) until it collides with a polygon border or another 1. After that, it takes the cell in which it was before the collision and remains there. Take a look at the examples for better understanding.More formally: if a cannon stands in the row $$$i$$$, to the left of the first column, and shoots with a 1, then the 1 starts its flight from the cell ($$$i, 1$$$) and ends in some cell ($$$i, j$$$); if a cannon stands in the column $$$j$$$, above the first row, and shoots with a 1, then the 1 starts its flight from the cell ($$$1, j$$$) and ends in some cell ($$$i, j$$$). For example, consider the following sequence of shots: 1. Shoot the cannon in the row $$$2$$$.                         2. Shoot the cannon in the row $$$2$$$.                         3. Shoot the cannon in column $$$3$$$. You have a report from the military training on your desk. This report is a square matrix with side length $$$n$$$ consisting of 0 and 1. You wonder if the training actually happened. In other words, is there a sequence of shots such that, after the training, you get the given matrix?Each cannon can make an arbitrary number of shots. Before the training, each cell of the polygon contains 0.
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; public class j8 { public static void main (String[] args) throws java.lang.Exception { Scanner in=new Scanner(System.in); int t=in.nextInt(); while(t-->0){ boolean flag=true; int n=in.nextInt(); String s[]=new String[n]; for(int i=0;i<n;i++){ s[i]=in.next(); } for(int i=0;i<(n-1)&&flag;i++){ for(int j=0;j<(n-1);j++){ char ch=s[i].charAt(j); if(ch=='1'){ //System.out.println(s[i+1].charAt(j)+" "+s[i].charAt(j+1)); if((s[i+1].charAt(j))!='1'&&(s[i].charAt(j+1))!='1'){ flag=false; break; } } } } if(flag){ System.out.println("YES"); } else{ System.out.println("NO"); } } } }
Java
["5\n4\n0010\n0011\n0000\n0000\n2\n10\n01\n2\n00\n00\n4\n0101\n1111\n0101\n0111\n4\n0100\n1110\n0101\n0111"]
2 seconds
["YES\nNO\nYES\nYES\nNO"]
NoteThe first test case was explained in the statement.The answer to the second test case is NO, since a 1 in a cell ($$$1, 1$$$) flying out of any cannon would continue its flight further.
Java 11
standard input
[ "dp", "implementation", "graphs", "shortest paths" ]
eea15ff7e939bfcc7002cacbc8a1a3a5
The first line contains an integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case starts with a line containing an integer $$$n$$$ ($$$1 \le n \le 50$$$) — the size of the polygon. This is followed by $$$n$$$ lines of length $$$n$$$, consisting of 0 and 1 — the polygon matrix after the training. The total area of the matrices in all test cases in one test does not exceed $$$10^5$$$.
1,300
For each test case print: YES if there is a sequence of shots leading to a given matrix; NO if such a sequence does not exist. The letters in the words YES and NO can be printed in any case.
standard output
PASSED
6b9598807b938b8881cc669cf1b5bda5
train_003.jsonl
1590327300
Polygon is not only the best platform for developing problems but also a square matrix with side $$$n$$$, initially filled with the character 0.On the polygon, military training was held. The soldiers placed a cannon above each cell in the first row and a cannon to the left of each cell in the first column. Thus, exactly $$$2n$$$ cannons were placed. Initial polygon for $$$n=4$$$. Cannons shoot character 1. At any moment of time, no more than one cannon is shooting. When a 1 flies out of a cannon, it flies forward (in the direction of the shot) until it collides with a polygon border or another 1. After that, it takes the cell in which it was before the collision and remains there. Take a look at the examples for better understanding.More formally: if a cannon stands in the row $$$i$$$, to the left of the first column, and shoots with a 1, then the 1 starts its flight from the cell ($$$i, 1$$$) and ends in some cell ($$$i, j$$$); if a cannon stands in the column $$$j$$$, above the first row, and shoots with a 1, then the 1 starts its flight from the cell ($$$1, j$$$) and ends in some cell ($$$i, j$$$). For example, consider the following sequence of shots: 1. Shoot the cannon in the row $$$2$$$.                         2. Shoot the cannon in the row $$$2$$$.                         3. Shoot the cannon in column $$$3$$$. You have a report from the military training on your desk. This report is a square matrix with side length $$$n$$$ consisting of 0 and 1. You wonder if the training actually happened. In other words, is there a sequence of shots such that, after the training, you get the given matrix?Each cannon can make an arbitrary number of shots. Before the training, each cell of the polygon contains 0.
256 megabytes
//package codeforces; import java.util.Scanner; public class Polygon { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while(t-- > 0) { int n = sc.nextInt(); sc.nextLine(); int mat[][] = new int[n][n]; for(int i = 0;i<n;i++) { String input[] = sc.nextLine().split(""); for(int j = 0;j<n;j++) { mat[i][j] = Integer.parseInt(input[j]); } } System.out.println(solve(mat)); } } private static String solve(int[][] mat) { String y = "YES"; String n = "NO"; int len = mat.length; for(int i = 0;i<len;i++) { for(int j = 0;j<len;j++) { if((i + 1) < len && (j+1) < len) { if(mat[i][j] == 1 && mat[i][j+1] == 0 && mat[i+1][j] == 0) return n; } } } return y; } }
Java
["5\n4\n0010\n0011\n0000\n0000\n2\n10\n01\n2\n00\n00\n4\n0101\n1111\n0101\n0111\n4\n0100\n1110\n0101\n0111"]
2 seconds
["YES\nNO\nYES\nYES\nNO"]
NoteThe first test case was explained in the statement.The answer to the second test case is NO, since a 1 in a cell ($$$1, 1$$$) flying out of any cannon would continue its flight further.
Java 11
standard input
[ "dp", "implementation", "graphs", "shortest paths" ]
eea15ff7e939bfcc7002cacbc8a1a3a5
The first line contains an integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case starts with a line containing an integer $$$n$$$ ($$$1 \le n \le 50$$$) — the size of the polygon. This is followed by $$$n$$$ lines of length $$$n$$$, consisting of 0 and 1 — the polygon matrix after the training. The total area of the matrices in all test cases in one test does not exceed $$$10^5$$$.
1,300
For each test case print: YES if there is a sequence of shots leading to a given matrix; NO if such a sequence does not exist. The letters in the words YES and NO can be printed in any case.
standard output
PASSED
9131bbf79ef5fd1c2a998870460b3903
train_003.jsonl
1590327300
Polygon is not only the best platform for developing problems but also a square matrix with side $$$n$$$, initially filled with the character 0.On the polygon, military training was held. The soldiers placed a cannon above each cell in the first row and a cannon to the left of each cell in the first column. Thus, exactly $$$2n$$$ cannons were placed. Initial polygon for $$$n=4$$$. Cannons shoot character 1. At any moment of time, no more than one cannon is shooting. When a 1 flies out of a cannon, it flies forward (in the direction of the shot) until it collides with a polygon border or another 1. After that, it takes the cell in which it was before the collision and remains there. Take a look at the examples for better understanding.More formally: if a cannon stands in the row $$$i$$$, to the left of the first column, and shoots with a 1, then the 1 starts its flight from the cell ($$$i, 1$$$) and ends in some cell ($$$i, j$$$); if a cannon stands in the column $$$j$$$, above the first row, and shoots with a 1, then the 1 starts its flight from the cell ($$$1, j$$$) and ends in some cell ($$$i, j$$$). For example, consider the following sequence of shots: 1. Shoot the cannon in the row $$$2$$$.                         2. Shoot the cannon in the row $$$2$$$.                         3. Shoot the cannon in column $$$3$$$. You have a report from the military training on your desk. This report is a square matrix with side length $$$n$$$ consisting of 0 and 1. You wonder if the training actually happened. In other words, is there a sequence of shots such that, after the training, you get the given matrix?Each cannon can make an arbitrary number of shots. Before the training, each cell of the polygon contains 0.
256 megabytes
/* package codechef; // don't place package name! */ import javax.swing.text.html.parser.Entity; import java.util.*; import java.lang.*; import java.io.*; /* Name of the class has to be "Main" only if the class is public. */ public class Solution { // Complete the maximumSum function below. public 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); } } static boolean prime(long a){ if(a==2||a==3) return true; if((a-1)%6==0) return true; if((a+1)%6==0) return true; return false; } public static long gcd(long a,long b){ if(b==0) return a; long r=a%b; return gcd(b,r); } static long lcm(long a, long b) { return (a*b)/gcd(a, b); } public class ListNode { int val; ListNode next; ListNode() {} ListNode(int val) { this.val = val; } ListNode(int val, ListNode next) { this.val = val; this.next = next; } } public class TreeNode { int val; TreeNode left; TreeNode right; TreeNode() {} TreeNode(int val) { this.val = val; } TreeNode(int val, TreeNode left, TreeNode right) { this.val = val; this.left = left; this.right = right; } } // private static final FastReader scanner = new FastReader(); public static void main(String[] args) throws IOException { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader sc = new InputReader(inputStream); PrintWriter w = new PrintWriter(outputStream); int t =sc.nextInt(); for(int i=0;i<t;i++) { int n = sc.nextInt(); int a[][]=new int [n][n]; int b[][]=new int [n][2]; int flag=1; for(int y=0;y<n;y++) { String s=sc.next(); for(int x=0;x<n;x++) { a[x][y] =Math.abs(48-s.charAt(x)); } } for(int y=0;y<n;y++) { for(int x=0;x<n;x++) { if(a[x][y]==1) { if(x==n-1||y==n-1) { flag=1; } else if(a[x][y+1]==1||a[x+1][y]==1) { flag=1; } else { flag = 0; break; } } } if(flag==0) { break; } } if(flag==1) { w.write("YES\n"); } else { w.write("NO\n"); } } w.close(); } }
Java
["5\n4\n0010\n0011\n0000\n0000\n2\n10\n01\n2\n00\n00\n4\n0101\n1111\n0101\n0111\n4\n0100\n1110\n0101\n0111"]
2 seconds
["YES\nNO\nYES\nYES\nNO"]
NoteThe first test case was explained in the statement.The answer to the second test case is NO, since a 1 in a cell ($$$1, 1$$$) flying out of any cannon would continue its flight further.
Java 11
standard input
[ "dp", "implementation", "graphs", "shortest paths" ]
eea15ff7e939bfcc7002cacbc8a1a3a5
The first line contains an integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case starts with a line containing an integer $$$n$$$ ($$$1 \le n \le 50$$$) — the size of the polygon. This is followed by $$$n$$$ lines of length $$$n$$$, consisting of 0 and 1 — the polygon matrix after the training. The total area of the matrices in all test cases in one test does not exceed $$$10^5$$$.
1,300
For each test case print: YES if there is a sequence of shots leading to a given matrix; NO if such a sequence does not exist. The letters in the words YES and NO can be printed in any case.
standard output
PASSED
3c524cd90b439061adcb8e7cd32b63b2
train_003.jsonl
1590327300
Polygon is not only the best platform for developing problems but also a square matrix with side $$$n$$$, initially filled with the character 0.On the polygon, military training was held. The soldiers placed a cannon above each cell in the first row and a cannon to the left of each cell in the first column. Thus, exactly $$$2n$$$ cannons were placed. Initial polygon for $$$n=4$$$. Cannons shoot character 1. At any moment of time, no more than one cannon is shooting. When a 1 flies out of a cannon, it flies forward (in the direction of the shot) until it collides with a polygon border or another 1. After that, it takes the cell in which it was before the collision and remains there. Take a look at the examples for better understanding.More formally: if a cannon stands in the row $$$i$$$, to the left of the first column, and shoots with a 1, then the 1 starts its flight from the cell ($$$i, 1$$$) and ends in some cell ($$$i, j$$$); if a cannon stands in the column $$$j$$$, above the first row, and shoots with a 1, then the 1 starts its flight from the cell ($$$1, j$$$) and ends in some cell ($$$i, j$$$). For example, consider the following sequence of shots: 1. Shoot the cannon in the row $$$2$$$.                         2. Shoot the cannon in the row $$$2$$$.                         3. Shoot the cannon in column $$$3$$$. You have a report from the military training on your desk. This report is a square matrix with side length $$$n$$$ consisting of 0 and 1. You wonder if the training actually happened. In other words, is there a sequence of shots such that, after the training, you get the given matrix?Each cannon can make an arbitrary number of shots. Before the training, each cell of the polygon contains 0.
256 megabytes
import java.util.*; public class Polygons { public static int check(int[][][] arr,int n) { for(int j=0;j<n;j++) { for(int k=0;k<n;k++) { if(arr[j][k][0]==1 && j!=n-1 && k!=n-1) { if(arr[j+1][k][0]!=1 && arr[j][k+1][0]!=1) { return -1; } } } } return 1; } 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(); sc.nextLine(); int[][][] arr=new int[n][n][2]; for(int j=0;j<n;j++) { String s=sc.nextLine(); for(int k=0;k<n;k++) { arr[j][k][0]=s.charAt(k)-48; } } if(check(arr,n)==1) { System.out.println("YES"); } else { System.out.println("NO"); } } } }
Java
["5\n4\n0010\n0011\n0000\n0000\n2\n10\n01\n2\n00\n00\n4\n0101\n1111\n0101\n0111\n4\n0100\n1110\n0101\n0111"]
2 seconds
["YES\nNO\nYES\nYES\nNO"]
NoteThe first test case was explained in the statement.The answer to the second test case is NO, since a 1 in a cell ($$$1, 1$$$) flying out of any cannon would continue its flight further.
Java 11
standard input
[ "dp", "implementation", "graphs", "shortest paths" ]
eea15ff7e939bfcc7002cacbc8a1a3a5
The first line contains an integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case starts with a line containing an integer $$$n$$$ ($$$1 \le n \le 50$$$) — the size of the polygon. This is followed by $$$n$$$ lines of length $$$n$$$, consisting of 0 and 1 — the polygon matrix after the training. The total area of the matrices in all test cases in one test does not exceed $$$10^5$$$.
1,300
For each test case print: YES if there is a sequence of shots leading to a given matrix; NO if such a sequence does not exist. The letters in the words YES and NO can be printed in any case.
standard output
PASSED
d16d62ba34414fb7490138a33ec4d15d
train_003.jsonl
1590327300
Polygon is not only the best platform for developing problems but also a square matrix with side $$$n$$$, initially filled with the character 0.On the polygon, military training was held. The soldiers placed a cannon above each cell in the first row and a cannon to the left of each cell in the first column. Thus, exactly $$$2n$$$ cannons were placed. Initial polygon for $$$n=4$$$. Cannons shoot character 1. At any moment of time, no more than one cannon is shooting. When a 1 flies out of a cannon, it flies forward (in the direction of the shot) until it collides with a polygon border or another 1. After that, it takes the cell in which it was before the collision and remains there. Take a look at the examples for better understanding.More formally: if a cannon stands in the row $$$i$$$, to the left of the first column, and shoots with a 1, then the 1 starts its flight from the cell ($$$i, 1$$$) and ends in some cell ($$$i, j$$$); if a cannon stands in the column $$$j$$$, above the first row, and shoots with a 1, then the 1 starts its flight from the cell ($$$1, j$$$) and ends in some cell ($$$i, j$$$). For example, consider the following sequence of shots: 1. Shoot the cannon in the row $$$2$$$.                         2. Shoot the cannon in the row $$$2$$$.                         3. Shoot the cannon in column $$$3$$$. You have a report from the military training on your desk. This report is a square matrix with side length $$$n$$$ consisting of 0 and 1. You wonder if the training actually happened. In other words, is there a sequence of shots such that, after the training, you get the given matrix?Each cannon can make an arbitrary number of shots. Before the training, each cell of the polygon contains 0.
256 megabytes
import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Scanner; public class Polygon { public static void main(String [] args){ Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while (t-->0) { int n = sc.nextInt(); StringBuilder current = new StringBuilder(); for(int i = 0; i<n; i++) { String now = sc.next(); current.append(now); } for (int i = 0; i<n*n; i++){ if(current.charAt(i) == '1') { if (i - 1 >= 0 && current.charAt(i - 1) == '1') { current.replace(i - 1, i, "0"); } if (i - n >= 0 && current.charAt(i - n) == '1') { current.replace(i - n, (i-n)+1, "0"); } if (((i + 1) % n == 0) || (i + 1) > (n * n) - n) current.replace(i, i+1, "0"); } } if(current.toString().contains("1")) System.out.println("NO"); else System.out.println("YES"); } } }
Java
["5\n4\n0010\n0011\n0000\n0000\n2\n10\n01\n2\n00\n00\n4\n0101\n1111\n0101\n0111\n4\n0100\n1110\n0101\n0111"]
2 seconds
["YES\nNO\nYES\nYES\nNO"]
NoteThe first test case was explained in the statement.The answer to the second test case is NO, since a 1 in a cell ($$$1, 1$$$) flying out of any cannon would continue its flight further.
Java 11
standard input
[ "dp", "implementation", "graphs", "shortest paths" ]
eea15ff7e939bfcc7002cacbc8a1a3a5
The first line contains an integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case starts with a line containing an integer $$$n$$$ ($$$1 \le n \le 50$$$) — the size of the polygon. This is followed by $$$n$$$ lines of length $$$n$$$, consisting of 0 and 1 — the polygon matrix after the training. The total area of the matrices in all test cases in one test does not exceed $$$10^5$$$.
1,300
For each test case print: YES if there is a sequence of shots leading to a given matrix; NO if such a sequence does not exist. The letters in the words YES and NO can be printed in any case.
standard output
PASSED
d2b0edcd3fc3b0d457d5c5b7390ce75d
train_003.jsonl
1590327300
Polygon is not only the best platform for developing problems but also a square matrix with side $$$n$$$, initially filled with the character 0.On the polygon, military training was held. The soldiers placed a cannon above each cell in the first row and a cannon to the left of each cell in the first column. Thus, exactly $$$2n$$$ cannons were placed. Initial polygon for $$$n=4$$$. Cannons shoot character 1. At any moment of time, no more than one cannon is shooting. When a 1 flies out of a cannon, it flies forward (in the direction of the shot) until it collides with a polygon border or another 1. After that, it takes the cell in which it was before the collision and remains there. Take a look at the examples for better understanding.More formally: if a cannon stands in the row $$$i$$$, to the left of the first column, and shoots with a 1, then the 1 starts its flight from the cell ($$$i, 1$$$) and ends in some cell ($$$i, j$$$); if a cannon stands in the column $$$j$$$, above the first row, and shoots with a 1, then the 1 starts its flight from the cell ($$$1, j$$$) and ends in some cell ($$$i, j$$$). For example, consider the following sequence of shots: 1. Shoot the cannon in the row $$$2$$$.                         2. Shoot the cannon in the row $$$2$$$.                         3. Shoot the cannon in column $$$3$$$. You have a report from the military training on your desk. This report is a square matrix with side length $$$n$$$ consisting of 0 and 1. You wonder if the training actually happened. In other words, is there a sequence of shots such that, after the training, you get the given matrix?Each cannon can make an arbitrary number of shots. Before the training, each cell of the polygon contains 0.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; public class P { public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in, StandardCharsets.UTF_8)); int n; n = Integer.parseInt(reader.readLine()); for (int i = 0; i < n; ++i) { int m = Integer.parseInt(reader.readLine()); List<String> matrix = new ArrayList<>(); for (int j = 0; j < m; ++j) { matrix.add(reader.readLine()); } boolean no = false; for (int j = 0; j < m - 1; ++j) { for (int k = 0; k < m - 1; ++k) { if (matrix.get(j).charAt(k) == '1') { if (matrix.get(j).charAt(k + 1) != '1' && matrix.get(j + 1).charAt(k) != '1') { no = true; } } } } if (no) { System.out.println("NO"); } else { System.out.println("YES"); } } } }
Java
["5\n4\n0010\n0011\n0000\n0000\n2\n10\n01\n2\n00\n00\n4\n0101\n1111\n0101\n0111\n4\n0100\n1110\n0101\n0111"]
2 seconds
["YES\nNO\nYES\nYES\nNO"]
NoteThe first test case was explained in the statement.The answer to the second test case is NO, since a 1 in a cell ($$$1, 1$$$) flying out of any cannon would continue its flight further.
Java 11
standard input
[ "dp", "implementation", "graphs", "shortest paths" ]
eea15ff7e939bfcc7002cacbc8a1a3a5
The first line contains an integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case starts with a line containing an integer $$$n$$$ ($$$1 \le n \le 50$$$) — the size of the polygon. This is followed by $$$n$$$ lines of length $$$n$$$, consisting of 0 and 1 — the polygon matrix after the training. The total area of the matrices in all test cases in one test does not exceed $$$10^5$$$.
1,300
For each test case print: YES if there is a sequence of shots leading to a given matrix; NO if such a sequence does not exist. The letters in the words YES and NO can be printed in any case.
standard output
PASSED
d4fc78bd4ad2eb05b662a2444b867276
train_003.jsonl
1590327300
Polygon is not only the best platform for developing problems but also a square matrix with side $$$n$$$, initially filled with the character 0.On the polygon, military training was held. The soldiers placed a cannon above each cell in the first row and a cannon to the left of each cell in the first column. Thus, exactly $$$2n$$$ cannons were placed. Initial polygon for $$$n=4$$$. Cannons shoot character 1. At any moment of time, no more than one cannon is shooting. When a 1 flies out of a cannon, it flies forward (in the direction of the shot) until it collides with a polygon border or another 1. After that, it takes the cell in which it was before the collision and remains there. Take a look at the examples for better understanding.More formally: if a cannon stands in the row $$$i$$$, to the left of the first column, and shoots with a 1, then the 1 starts its flight from the cell ($$$i, 1$$$) and ends in some cell ($$$i, j$$$); if a cannon stands in the column $$$j$$$, above the first row, and shoots with a 1, then the 1 starts its flight from the cell ($$$1, j$$$) and ends in some cell ($$$i, j$$$). For example, consider the following sequence of shots: 1. Shoot the cannon in the row $$$2$$$.                         2. Shoot the cannon in the row $$$2$$$.                         3. Shoot the cannon in column $$$3$$$. You have a report from the military training on your desk. This report is a square matrix with side length $$$n$$$ consisting of 0 and 1. You wonder if the training actually happened. In other words, is there a sequence of shots such that, after the training, you get the given matrix?Each cannon can make an arbitrary number of shots. Before the training, each cell of the polygon contains 0.
256 megabytes
import java.util.*; import java.io.*; public class Polygon { // https://codeforces.com/contest/1360/problem/E public static void main(String[] args) throws IOException, FileNotFoundException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); //BufferedReader in = new BufferedReader(new FileReader("Polygon")); int t = Integer.parseInt(in.readLine()); for (int j=0; j<t; j++) { int n= Integer.parseInt(in.readLine()); char[][] arr = new char[n][]; for (int i=0; i<n; i++) { arr[i] = in.readLine().toCharArray(); } boolean w = true; outerloop: for (int i=0; i<n-1; i++) { for (int x=0; x<n-1; x++) { if (arr[i][x] == '1') { if (arr[i+1][x] == '0' && arr[i][x+1] == '0') { w = false; break outerloop; } } } } if (w ) System.out.println("YES"); else System.out.println("NO"); } } }
Java
["5\n4\n0010\n0011\n0000\n0000\n2\n10\n01\n2\n00\n00\n4\n0101\n1111\n0101\n0111\n4\n0100\n1110\n0101\n0111"]
2 seconds
["YES\nNO\nYES\nYES\nNO"]
NoteThe first test case was explained in the statement.The answer to the second test case is NO, since a 1 in a cell ($$$1, 1$$$) flying out of any cannon would continue its flight further.
Java 11
standard input
[ "dp", "implementation", "graphs", "shortest paths" ]
eea15ff7e939bfcc7002cacbc8a1a3a5
The first line contains an integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case starts with a line containing an integer $$$n$$$ ($$$1 \le n \le 50$$$) — the size of the polygon. This is followed by $$$n$$$ lines of length $$$n$$$, consisting of 0 and 1 — the polygon matrix after the training. The total area of the matrices in all test cases in one test does not exceed $$$10^5$$$.
1,300
For each test case print: YES if there is a sequence of shots leading to a given matrix; NO if such a sequence does not exist. The letters in the words YES and NO can be printed in any case.
standard output
PASSED
04a9e4df18faba44e8c3236f2fdb6075
train_003.jsonl
1590327300
Polygon is not only the best platform for developing problems but also a square matrix with side $$$n$$$, initially filled with the character 0.On the polygon, military training was held. The soldiers placed a cannon above each cell in the first row and a cannon to the left of each cell in the first column. Thus, exactly $$$2n$$$ cannons were placed. Initial polygon for $$$n=4$$$. Cannons shoot character 1. At any moment of time, no more than one cannon is shooting. When a 1 flies out of a cannon, it flies forward (in the direction of the shot) until it collides with a polygon border or another 1. After that, it takes the cell in which it was before the collision and remains there. Take a look at the examples for better understanding.More formally: if a cannon stands in the row $$$i$$$, to the left of the first column, and shoots with a 1, then the 1 starts its flight from the cell ($$$i, 1$$$) and ends in some cell ($$$i, j$$$); if a cannon stands in the column $$$j$$$, above the first row, and shoots with a 1, then the 1 starts its flight from the cell ($$$1, j$$$) and ends in some cell ($$$i, j$$$). For example, consider the following sequence of shots: 1. Shoot the cannon in the row $$$2$$$.                         2. Shoot the cannon in the row $$$2$$$.                         3. Shoot the cannon in column $$$3$$$. You have a report from the military training on your desk. This report is a square matrix with side length $$$n$$$ consisting of 0 and 1. You wonder if the training actually happened. In other words, is there a sequence of shots such that, after the training, you get the given matrix?Each cannon can make an arbitrary number of shots. Before the training, each cell of the polygon contains 0.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in Actual solution is at the top * * @author dauom */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); EPolygon solver = new EPolygon(); int testCount = Integer.parseInt(in.next()); for (int i = 1; i <= testCount; i++) solver.solve(i, in, out); out.close(); } static class EPolygon { public final void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); char[][] g = in.nextCharMatrix(n, n); boolean[][] ok = new boolean[n][n]; for (int i = 0; i < n; i++) { if (g[i][n - 1] == '1') { dfs(ok, g, i, n - 1); } if (g[n - 1][i] == '1') { dfs(ok, g, n - 1, i); } } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (g[i][j] == '1' && !ok[i][j]) { out.println("NO"); return; } } } out.println("YES"); } private void dfs(boolean[][] ok, char[][] g, int i, int j) { ok[i][j] = true; if (i - 1 >= 0 && !ok[i - 1][j] && g[i - 1][j] == '1') { dfs(ok, g, i - 1, j); } if (j - 1 >= 0 && !ok[i][j - 1] && g[i][j - 1] == '1') { dfs(ok, g, i, j - 1); } } } static final class InputReader { private final InputStream stream; private final byte[] buf = new byte[1 << 16]; private int curChar; private int numChars; public InputReader() { this.stream = System.in; } public InputReader(final InputStream stream) { this.stream = stream; } private final int read() { if (this.numChars == -1) { throw new UnknownError(); } else { if (this.curChar >= this.numChars) { this.curChar = 0; try { this.numChars = this.stream.read(this.buf); } catch (IOException ex) { throw new InputMismatchException(); } if (this.numChars <= 0) { return -1; } } return this.buf[this.curChar++]; } } public final int nextInt() { int c; for (c = this.read(); isSpaceChar(c); c = this.read()) {} byte sgn = 1; if (c == 45) { // 45 == '-' sgn = -1; c = this.read(); } int res = 0; while (c >= 48 && c <= 57) { // 48 == '0', 57 == '9' res *= 10; res += c - 48; // 48 == '0' c = this.read(); if (isSpaceChar(c)) { return res * sgn; } } throw new InputMismatchException(); } public final String next() { int c; while (isSpaceChar(c = this.read())) {} StringBuilder result = new StringBuilder(); result.appendCodePoint(c); while (!isSpaceChar(c = this.read())) { result.appendCodePoint(c); } return result.toString(); } private static final boolean isSpaceChar(final int c) { return c == 32 || c == 10 || c == 13 || c == 9 || c == -1; // 32 == ' ', 10 == '\n', 13 == '\r', 9 == '\t' } public final char[] nextCharArray() { return next().toCharArray(); } public final char[][] nextCharMatrix(final int n, final int m) { char[][] res = new char[n][m]; for (int i = 0; i < n; ++i) { res[i] = nextCharArray(); } return res; } } }
Java
["5\n4\n0010\n0011\n0000\n0000\n2\n10\n01\n2\n00\n00\n4\n0101\n1111\n0101\n0111\n4\n0100\n1110\n0101\n0111"]
2 seconds
["YES\nNO\nYES\nYES\nNO"]
NoteThe first test case was explained in the statement.The answer to the second test case is NO, since a 1 in a cell ($$$1, 1$$$) flying out of any cannon would continue its flight further.
Java 11
standard input
[ "dp", "implementation", "graphs", "shortest paths" ]
eea15ff7e939bfcc7002cacbc8a1a3a5
The first line contains an integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case starts with a line containing an integer $$$n$$$ ($$$1 \le n \le 50$$$) — the size of the polygon. This is followed by $$$n$$$ lines of length $$$n$$$, consisting of 0 and 1 — the polygon matrix after the training. The total area of the matrices in all test cases in one test does not exceed $$$10^5$$$.
1,300
For each test case print: YES if there is a sequence of shots leading to a given matrix; NO if such a sequence does not exist. The letters in the words YES and NO can be printed in any case.
standard output
PASSED
1abf07697051d31418aff283e516f8c0
train_003.jsonl
1381838400
Hooray! Berl II, the king of Berland is making a knight tournament. The king has already sent the message to all knights in the kingdom and they in turn agreed to participate in this grand event.As for you, you're just a simple peasant. There's no surprise that you slept in this morning and were late for the tournament (it was a weekend, after all). Now you are really curious about the results of the tournament. This time the tournament in Berland went as follows: There are n knights participating in the tournament. Each knight was assigned his unique number — an integer from 1 to n. The tournament consisted of m fights, in the i-th fight the knights that were still in the game with numbers at least li and at most ri have fought for the right to continue taking part in the tournament. After the i-th fight among all participants of the fight only one knight won — the knight number xi, he continued participating in the tournament. Other knights left the tournament. The winner of the last (the m-th) fight (the knight number xm) became the winner of the tournament. You fished out all the information about the fights from your friends. Now for each knight you want to know the name of the knight he was conquered by. We think that the knight number b was conquered by the knight number a, if there was a fight with both of these knights present and the winner was the knight number a.Write the code that calculates for each knight, the name of the knight that beat him.
256 megabytes
import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import java.util.Scanner; import java.util.Set; import java.util.SortedMap; import java.util.SortedSet; import java.util.TreeMap; import java.util.TreeSet; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author mark */ public class KnightTournament { public static void main(String[] args) throws FileNotFoundException { //FileInputStream file = new FileInputStream(new File("/home/mark/tmp/input.txt")); //Scanner scan = new Scanner(file); Scanner scan = new Scanner(System.in); int n=scan.nextInt(); int m = scan.nextInt(); int k[] = new int[n]; int w=0; TreeSet<Integer> map = new TreeSet<>(); for(int i=0;i<n;i++){ map.add(i); } for(int i=0;i<m;i++){ int s=scan.nextInt()-1; int e=scan.nextInt()-1; w=scan.nextInt()-1; Integer s1=map.ceiling(s); Integer e1=map.floor(e); boolean done=false; SortedSet<Integer> set; if (e1==null && s1==null){ continue; } if (e1==null && s1!=null){ set = map.tailSet(s1,true); }else if (s1==null && e1!=null){ set = map.headSet(e1,true); }else{ set = map.subSet(s1, true,e1,true); } List<Integer> tmp =new LinkedList<>(); for(Integer key : set){ if (key!=w){ k[key]=w+1; tmp.add(key); } } map.removeAll(tmp); } k[w]=0; System.out.println(Arrays.toString(k).replace("[","").replace("]","").replace(",","")); } }
Java
["4 3\n1 2 1\n1 3 3\n1 4 4", "8 4\n3 5 4\n3 7 6\n2 8 8\n1 8 1"]
3 seconds
["3 1 4 0", "0 8 4 6 4 8 6 1"]
NoteConsider the first test case. Knights 1 and 2 fought the first fight and knight 1 won. Knights 1 and 3 fought the second fight and knight 3 won. The last fight was between knights 3 and 4, knight 4 won.
Java 7
standard input
[ "data structures" ]
a608eda195166231d14fbeae9c8b31fa
The first line contains two integers n, m (2 ≤ n ≤ 3·105; 1 ≤ m ≤ 3·105) — the number of knights and the number of fights. Each of the following m lines contains three integers li, ri, xi (1 ≤ li &lt; ri ≤ n; li ≤ xi ≤ ri) — the description of the i-th fight. It is guaranteed that the input is correct and matches the problem statement. It is guaranteed that at least two knights took part in each battle.
1,500
Print n integers. If the i-th knight lost, then the i-th number should equal the number of the knight that beat the knight number i. If the i-th knight is the winner, then the i-th number must equal 0.
standard output
PASSED
0eee3dc8094600252af54e2b22a3bc35
train_003.jsonl
1381838400
Hooray! Berl II, the king of Berland is making a knight tournament. The king has already sent the message to all knights in the kingdom and they in turn agreed to participate in this grand event.As for you, you're just a simple peasant. There's no surprise that you slept in this morning and were late for the tournament (it was a weekend, after all). Now you are really curious about the results of the tournament. This time the tournament in Berland went as follows: There are n knights participating in the tournament. Each knight was assigned his unique number — an integer from 1 to n. The tournament consisted of m fights, in the i-th fight the knights that were still in the game with numbers at least li and at most ri have fought for the right to continue taking part in the tournament. After the i-th fight among all participants of the fight only one knight won — the knight number xi, he continued participating in the tournament. Other knights left the tournament. The winner of the last (the m-th) fight (the knight number xm) became the winner of the tournament. You fished out all the information about the fights from your friends. Now for each knight you want to know the name of the knight he was conquered by. We think that the knight number b was conquered by the knight number a, if there was a fight with both of these knights present and the winner was the knight number a.Write the code that calculates for each knight, the name of the knight that beat him.
256 megabytes
import java.io.IOException; import java.io.PrintStream; import java.io.PrintWriter; import java.io.StreamCorruptedException; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.InputMismatchException; import java.util.LinkedList; import java.util.PriorityQueue; import java.util.TreeSet; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Solution { public static void main(String[] args) { new Solution().solve(); } int[] arr; PrintWriter out; public void solve() { out=new PrintWriter(System.out); int n=in.nextInt(); int m=in.nextInt(); int[] arr=new int[n+1]; TreeSet<Integer> set=new TreeSet<Integer>(); for(int i=1;i<=n;i++) { set.add(i); } for(int i=0;i<m;i++) { int l=in.nextInt(); int r=in.nextInt(); int x=in.nextInt(); set.remove(x); while(true) { Integer x1=set.floor(x); if(x1==null || x1<l) { break; } else { set.remove(x1); arr[x1]=x; } } while(true) { Integer x1=set.ceiling(x); if(x1==null || x1>r) { break; } else { set.remove(x1); arr[x1]=x; } } set.add(x); } for(int i=1;i<=n;i++) { out.print(arr[i]+" "); } out.close(); } class s { int start; int stop; int x=0; s left,right; public s(int start,int stop) { // System.out.println("Init "+start+" "+stop ); this.start=start; this.stop=stop; if(start==stop) { return; } else { this.left=new s(start,(start+stop)/2); this.right=new s((start+stop)/2+1,stop); } } public boolean check() { if(this.x==0 && (left==null?true:left.check()) && (right==null?true:right.check())) { return true; } else { return false; } } public void hello(int l,int r,int x) { if(l>r) { return; } //System.out.println("hello "+l+" "+r+" "+this.x+" "+start+" "+stop ); if(this.x!=0) { return; } if(l<=this.start && this.stop<=r && (left==null?true:left.check()) && (right==null?true:right.check())) { // System.out.println("frhg"); this.x=x; return ; } else if(this.stop<l || this.start>r) { return; } else { // System.out.println("fgnfj"); left.hello(l, r, x); right.hello(l, r, x); } } public void pr() { if(this.x!=0) { for(int i=start;i<=stop;i++) { out.print(x+" "); } } else { if(left!=null) { left.pr(); right.pr(); } else { out.print("0 "); } } } } FasterScanner in=new FasterScanner(); public class FasterScanner { private byte[] buf = new byte[1024]; private int curChar; private int numChars; public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = System.in.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public String nextString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = nextInt(); } return arr; } public long[] nextLongArray(int n) { long[] arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = nextLong(); } return arr; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } } }
Java
["4 3\n1 2 1\n1 3 3\n1 4 4", "8 4\n3 5 4\n3 7 6\n2 8 8\n1 8 1"]
3 seconds
["3 1 4 0", "0 8 4 6 4 8 6 1"]
NoteConsider the first test case. Knights 1 and 2 fought the first fight and knight 1 won. Knights 1 and 3 fought the second fight and knight 3 won. The last fight was between knights 3 and 4, knight 4 won.
Java 7
standard input
[ "data structures" ]
a608eda195166231d14fbeae9c8b31fa
The first line contains two integers n, m (2 ≤ n ≤ 3·105; 1 ≤ m ≤ 3·105) — the number of knights and the number of fights. Each of the following m lines contains three integers li, ri, xi (1 ≤ li &lt; ri ≤ n; li ≤ xi ≤ ri) — the description of the i-th fight. It is guaranteed that the input is correct and matches the problem statement. It is guaranteed that at least two knights took part in each battle.
1,500
Print n integers. If the i-th knight lost, then the i-th number should equal the number of the knight that beat the knight number i. If the i-th knight is the winner, then the i-th number must equal 0.
standard output
PASSED
b6e78b842291170684194009bba146bf
train_003.jsonl
1381838400
Hooray! Berl II, the king of Berland is making a knight tournament. The king has already sent the message to all knights in the kingdom and they in turn agreed to participate in this grand event.As for you, you're just a simple peasant. There's no surprise that you slept in this morning and were late for the tournament (it was a weekend, after all). Now you are really curious about the results of the tournament. This time the tournament in Berland went as follows: There are n knights participating in the tournament. Each knight was assigned his unique number — an integer from 1 to n. The tournament consisted of m fights, in the i-th fight the knights that were still in the game with numbers at least li and at most ri have fought for the right to continue taking part in the tournament. After the i-th fight among all participants of the fight only one knight won — the knight number xi, he continued participating in the tournament. Other knights left the tournament. The winner of the last (the m-th) fight (the knight number xm) became the winner of the tournament. You fished out all the information about the fights from your friends. Now for each knight you want to know the name of the knight he was conquered by. We think that the knight number b was conquered by the knight number a, if there was a fight with both of these knights present and the winner was the knight number a.Write the code that calculates for each knight, the name of the knight that beat him.
256 megabytes
import java.io.IOException; import java.io.PrintStream; import java.io.PrintWriter; import java.io.StreamCorruptedException; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.InputMismatchException; import java.util.LinkedList; import java.util.PriorityQueue; import java.util.TreeSet; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Solution { public static void main(String[] args) { new Solution().solve(); } int[] arr; PrintWriter out; public void solve() { out=new PrintWriter(System.out); int n=in.nextInt(); int m=in.nextInt(); int[] arr=new int[n+1]; TreeSet<Integer> set=new TreeSet<Integer>(); for(int i=1;i<=n;i++) { set.add(i); } for(int i=0;i<m;i++) { int l=in.nextInt(); int r=in.nextInt(); int x=in.nextInt(); set.remove(x); while(true) { Integer x1=set.floor(x); if(x1==null || x1<l) { break; } else { set.remove(x1); arr[x1]=x; } } while(true) { Integer x1=set.ceiling(x); if(x1==null || x1>r) { break; } else { set.remove(x1); arr[x1]=x; } } set.add(x); } for(int i=1;i<=n;i++) { out.print(arr[i]+" "); } out.close(); } class s { int start; int stop; int x=0; s left,right; public s(int start,int stop) { // System.out.println("Init "+start+" "+stop ); this.start=start; this.stop=stop; if(start==stop) { return; } else { this.left=new s(start,(start+stop)/2); this.right=new s((start+stop)/2+1,stop); } } public boolean check() { if(this.x==0 && (left==null?true:left.check()) && (right==null?true:right.check())) { return true; } else { return false; } } public void hello(int l,int r,int x) { if(l>r) { return; } //System.out.println("hello "+l+" "+r+" "+this.x+" "+start+" "+stop ); if(this.x!=0) { return; } if(l<=this.start && this.stop<=r && (left==null?true:left.check()) && (right==null?true:right.check())) { // System.out.println("frhg"); this.x=x; return ; } else if(this.stop<l || this.start>r) { return; } else { // System.out.println("fgnfj"); left.hello(l, r, x); right.hello(l, r, x); } } public void pr() { if(this.x!=0) { for(int i=start;i<=stop;i++) { out.print(x+" "); } } else { if(left!=null) { left.pr(); right.pr(); } else { out.print("0 "); } } } } FasterScanner in=new FasterScanner(); public class FasterScanner { private byte[] buf = new byte[1024]; private int curChar; private int numChars; public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = System.in.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public String nextString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = nextInt(); } return arr; } public long[] nextLongArray(int n) { long[] arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = nextLong(); } return arr; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } } }
Java
["4 3\n1 2 1\n1 3 3\n1 4 4", "8 4\n3 5 4\n3 7 6\n2 8 8\n1 8 1"]
3 seconds
["3 1 4 0", "0 8 4 6 4 8 6 1"]
NoteConsider the first test case. Knights 1 and 2 fought the first fight and knight 1 won. Knights 1 and 3 fought the second fight and knight 3 won. The last fight was between knights 3 and 4, knight 4 won.
Java 7
standard input
[ "data structures" ]
a608eda195166231d14fbeae9c8b31fa
The first line contains two integers n, m (2 ≤ n ≤ 3·105; 1 ≤ m ≤ 3·105) — the number of knights and the number of fights. Each of the following m lines contains three integers li, ri, xi (1 ≤ li &lt; ri ≤ n; li ≤ xi ≤ ri) — the description of the i-th fight. It is guaranteed that the input is correct and matches the problem statement. It is guaranteed that at least two knights took part in each battle.
1,500
Print n integers. If the i-th knight lost, then the i-th number should equal the number of the knight that beat the knight number i. If the i-th knight is the winner, then the i-th number must equal 0.
standard output
PASSED
9ef6ced09f6269e8edf8231c979787be
train_003.jsonl
1577457600
Polycarp is sad — New Year is coming in few days but there is still no snow in his city. To bring himself New Year mood, he decided to decorate his house with some garlands.The local store introduced a new service this year, called "Build your own garland". So you can buy some red, green and blue lamps, provide them and the store workers will solder a single garland of them. The resulting garland will have all the lamps you provided put in a line. Moreover, no pair of lamps of the same color will be adjacent to each other in this garland!For example, if you provide $$$3$$$ red, $$$3$$$ green and $$$3$$$ blue lamps, the resulting garland can look like this: "RGBRBGBGR" ("RGB" being the red, green and blue color, respectively). Note that it's ok to have lamps of the same color on the ends of the garland.However, if you provide, say, $$$1$$$ red, $$$10$$$ green and $$$2$$$ blue lamps then the store workers won't be able to build any garland of them. Any garland consisting of these lamps will have at least one pair of lamps of the same color adjacent to each other. Note that the store workers should use all the lamps you provided.So Polycarp has bought some sets of lamps and now he wants to know if the store workers can build a garland from each of them.
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; import java.math.BigInteger; public class Codechef { static long fac[] = new long[1000001]; static void perm() { fac[0]=1; for (int x=1;x<=1000000;x++) fac[x]=fac[x-1]*x; } 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 nPr(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 return ((fac[n] % p) * modInverse(fac[n-r], p) % p) % p; } static long mod(String num, long a) { // Initialize result long res = 0; // One by one process all digits of 'num' for (int i = 0; i < num.length(); i++) res = (res * 10 + (int)num.charAt(i) - '0') % a; return res; } static boolean check (int a) { String s=Integer.toString(a); int f[] = new int[10]; for (int x=0;x<s.length();x++) { f[s.charAt(x)-'0']++; if (f[s.charAt(x)-'0']>1) return (false); } return (true); } static long lcm(int[] element_array) { long lcm_of_array_elements = 1; int divisor = 2; while (true) { int counter = 0; boolean divisible = false; for (int i = 0; i < element_array.length; i++) { // lcm_of_array_elements (n1, n2, ... 0) = 0. // For negative number we convert into // positive and calculate lcm_of_array_elements. if (element_array[i] == 0) { return 0; } else if (element_array[i] < 0) { element_array[i] = element_array[i] * (-1); } if (element_array[i] == 1) { counter++; } // Divide element_array by devisor if complete // division i.e. without remainder then replace // number with quotient; used for find next factor if (element_array[i] % divisor == 0) { divisible = true; element_array[i] = element_array[i] / divisor; } } // If divisor able to completely divide any number // from array multiply with lcm_of_array_elements // and store into lcm_of_array_elements and continue // to same divisor for next factor finding. // else increment divisor if (divisible) { lcm_of_array_elements = lcm_of_array_elements * divisor; } else { divisor++; } // Check if all element_array is 1 indicate // we found all factors and terminate while loop. if (counter == element_array.length) { return lcm_of_array_elements; } } } static boolean find(int N) { String r=""; int rem=1%N; HashMap<Integer, Integer> h = new HashMap<Integer, Integer>(); while ((rem!=0) && !h.containsKey(rem)) { h.put(rem,r.length()); rem=rem*10; r=r+(rem/N); rem=rem%N; } if (rem==0) return (false); else return (true); } static String sorts(String inputString) { // convert input string to char array char tempArray[] = inputString.toCharArray(); // sort tempArray Arrays.sort(tempArray); // return new sorted string return new String(tempArray); } static long qrt(double d) { long k=(long)(d); double x=-1+Math.sqrt(1+(8*d)); x=x/2; long w=(long)(Math.ceil(x)); long sum=w*(w+1); sum=sum/2; //System.out.println (w+"GDSGDS"); while (sum%2!=k%2) { w++; sum=w*(w+1); sum=sum/2; } return (w); } static int knapSack(long W, int wt[], int val[], int n) { // Base Case if (n <=0 || W == 0) return 0; if (wt[n-1] > W) return knapSack(W, wt, val, n-1); else return Math.max( val[n-1] + knapSack(W-wt[n-1], wt, val, n-2), knapSack(W, wt, val, n-1)); } public static void main (String[] args) throws java.lang.Exception { Scanner in = new Scanner(System.in); int T=in.nextInt(); // StringBuilder s = new StringBuilder(); for (int Q=1;Q<=T;Q++) { long a[] = new long[3]; a[0]=in.nextLong(); a[1]=in.nextLong(); a[2]=in.nextLong(); Arrays.sort(a); if (a[0]==a[1] && a[1]==a[2]) {System.out.println ("Yes");continue;} if (a[2]-a[0]-a[1]>1) System.out.println ("No"); else { System.out.println ("Yes"); } } // System.out.println (s.toString()); } 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(); } } }
Java
["3\n3 3 3\n1 10 2\n2 1 1"]
1 second
["Yes\nNo\nYes"]
NoteThe first two sets are desribed in the statement.The third set produces garland "RBRG", for example.
Java 8
standard input
[ "math" ]
34aa41871ee50f06e8acbd5eee94b493
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of sets of lamps Polycarp has bought. Each of the next $$$t$$$ lines contains three integers $$$r$$$, $$$g$$$ and $$$b$$$ ($$$1 \le r, g, b \le 10^9$$$) — the number of red, green and blue lamps in the set, respectively.
900
Print $$$t$$$ lines — for each set of lamps print "Yes" if the store workers can build a garland from them and "No" otherwise.
standard output
PASSED
70dbe2528f582311cb52e65822aea784
train_003.jsonl
1577457600
Polycarp is sad — New Year is coming in few days but there is still no snow in his city. To bring himself New Year mood, he decided to decorate his house with some garlands.The local store introduced a new service this year, called "Build your own garland". So you can buy some red, green and blue lamps, provide them and the store workers will solder a single garland of them. The resulting garland will have all the lamps you provided put in a line. Moreover, no pair of lamps of the same color will be adjacent to each other in this garland!For example, if you provide $$$3$$$ red, $$$3$$$ green and $$$3$$$ blue lamps, the resulting garland can look like this: "RGBRBGBGR" ("RGB" being the red, green and blue color, respectively). Note that it's ok to have lamps of the same color on the ends of the garland.However, if you provide, say, $$$1$$$ red, $$$10$$$ green and $$$2$$$ blue lamps then the store workers won't be able to build any garland of them. Any garland consisting of these lamps will have at least one pair of lamps of the same color adjacent to each other. Note that the store workers should use all the lamps you provided.So Polycarp has bought some sets of lamps and now he wants to know if the store workers can build a garland from each of them.
256 megabytes
/* package whatever; // don't place package name! */ import java.util.*; import java.lang.*; import java.io.*; /* Name of the class has to be "Main" only if the class is public. */ public class Solution { public static void main (String[] args) throws java.lang.Exception { Scanner sc= new Scanner(System.in); int t = sc.nextInt(); while(t-->0){ int[] a = new int[3]; a[0] = sc.nextInt(); a[1] = sc.nextInt(); a[2] = sc.nextInt(); Arrays.sort(a); if(a[2]>a[0]+a[1]+1) System.out.println("NO"); else System.out.println("YES"); } } }
Java
["3\n3 3 3\n1 10 2\n2 1 1"]
1 second
["Yes\nNo\nYes"]
NoteThe first two sets are desribed in the statement.The third set produces garland "RBRG", for example.
Java 8
standard input
[ "math" ]
34aa41871ee50f06e8acbd5eee94b493
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of sets of lamps Polycarp has bought. Each of the next $$$t$$$ lines contains three integers $$$r$$$, $$$g$$$ and $$$b$$$ ($$$1 \le r, g, b \le 10^9$$$) — the number of red, green and blue lamps in the set, respectively.
900
Print $$$t$$$ lines — for each set of lamps print "Yes" if the store workers can build a garland from them and "No" otherwise.
standard output
PASSED
416b41dbcd6fd44c4efb52645a20053a
train_003.jsonl
1577457600
Polycarp is sad — New Year is coming in few days but there is still no snow in his city. To bring himself New Year mood, he decided to decorate his house with some garlands.The local store introduced a new service this year, called "Build your own garland". So you can buy some red, green and blue lamps, provide them and the store workers will solder a single garland of them. The resulting garland will have all the lamps you provided put in a line. Moreover, no pair of lamps of the same color will be adjacent to each other in this garland!For example, if you provide $$$3$$$ red, $$$3$$$ green and $$$3$$$ blue lamps, the resulting garland can look like this: "RGBRBGBGR" ("RGB" being the red, green and blue color, respectively). Note that it's ok to have lamps of the same color on the ends of the garland.However, if you provide, say, $$$1$$$ red, $$$10$$$ green and $$$2$$$ blue lamps then the store workers won't be able to build any garland of them. Any garland consisting of these lamps will have at least one pair of lamps of the same color adjacent to each other. Note that the store workers should use all the lamps you provided.So Polycarp has bought some sets of lamps and now he wants to know if the store workers can build a garland from each of them.
256 megabytes
import java.util.Arrays; import java.util.Scanner; public class New_year_garland { public static void main(String[] args) { Scanner s = new Scanner(System.in); int t = s.nextInt(); while(t-->0) { int[] arr = new int[3]; for(int i=0;i<3;i++) { arr[i] = s.nextInt(); } Arrays.sort(arr); if(arr[0]+arr[1]<arr[2]-1) { System.out.println("No"); }else { System.out.println("Yes"); } } } }
Java
["3\n3 3 3\n1 10 2\n2 1 1"]
1 second
["Yes\nNo\nYes"]
NoteThe first two sets are desribed in the statement.The third set produces garland "RBRG", for example.
Java 8
standard input
[ "math" ]
34aa41871ee50f06e8acbd5eee94b493
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of sets of lamps Polycarp has bought. Each of the next $$$t$$$ lines contains three integers $$$r$$$, $$$g$$$ and $$$b$$$ ($$$1 \le r, g, b \le 10^9$$$) — the number of red, green and blue lamps in the set, respectively.
900
Print $$$t$$$ lines — for each set of lamps print "Yes" if the store workers can build a garland from them and "No" otherwise.
standard output
PASSED
573ea37cc7b4d803f3c8e1dba8f38e32
train_003.jsonl
1577457600
Polycarp is sad — New Year is coming in few days but there is still no snow in his city. To bring himself New Year mood, he decided to decorate his house with some garlands.The local store introduced a new service this year, called "Build your own garland". So you can buy some red, green and blue lamps, provide them and the store workers will solder a single garland of them. The resulting garland will have all the lamps you provided put in a line. Moreover, no pair of lamps of the same color will be adjacent to each other in this garland!For example, if you provide $$$3$$$ red, $$$3$$$ green and $$$3$$$ blue lamps, the resulting garland can look like this: "RGBRBGBGR" ("RGB" being the red, green and blue color, respectively). Note that it's ok to have lamps of the same color on the ends of the garland.However, if you provide, say, $$$1$$$ red, $$$10$$$ green and $$$2$$$ blue lamps then the store workers won't be able to build any garland of them. Any garland consisting of these lamps will have at least one pair of lamps of the same color adjacent to each other. Note that the store workers should use all the lamps you provided.So Polycarp has bought some sets of lamps and now he wants to know if the store workers can build a garland from each of them.
256 megabytes
import java.io.*; import java.util.*; import java.math.*; import java.lang.*; import static java.lang.Math.*; public class Cf232 implements Runnable { 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 Cf232(),"Main",1<<27).start(); } public void run() { InputReader in = new InputReader(System.in); PrintWriter w = new PrintWriter(System.out); int t = in.nextInt(); while(t-->0) { long r = in.nextLong(); long g = in.nextLong(); long b = in.nextLong(); long min = Math.min(r,Math.min(b,g)); long max = Math.max(r,Math.max(b,g)); long diff = max - min; if(diff>r + g+ b -max - min +1) { w.println("No"); } else { w.println("Yes"); } } w.flush(); w.close(); } }
Java
["3\n3 3 3\n1 10 2\n2 1 1"]
1 second
["Yes\nNo\nYes"]
NoteThe first two sets are desribed in the statement.The third set produces garland "RBRG", for example.
Java 8
standard input
[ "math" ]
34aa41871ee50f06e8acbd5eee94b493
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of sets of lamps Polycarp has bought. Each of the next $$$t$$$ lines contains three integers $$$r$$$, $$$g$$$ and $$$b$$$ ($$$1 \le r, g, b \le 10^9$$$) — the number of red, green and blue lamps in the set, respectively.
900
Print $$$t$$$ lines — for each set of lamps print "Yes" if the store workers can build a garland from them and "No" otherwise.
standard output
PASSED
b58310c056e105c701a3ffeb75f7aa01
train_003.jsonl
1577457600
Polycarp is sad — New Year is coming in few days but there is still no snow in his city. To bring himself New Year mood, he decided to decorate his house with some garlands.The local store introduced a new service this year, called "Build your own garland". So you can buy some red, green and blue lamps, provide them and the store workers will solder a single garland of them. The resulting garland will have all the lamps you provided put in a line. Moreover, no pair of lamps of the same color will be adjacent to each other in this garland!For example, if you provide $$$3$$$ red, $$$3$$$ green and $$$3$$$ blue lamps, the resulting garland can look like this: "RGBRBGBGR" ("RGB" being the red, green and blue color, respectively). Note that it's ok to have lamps of the same color on the ends of the garland.However, if you provide, say, $$$1$$$ red, $$$10$$$ green and $$$2$$$ blue lamps then the store workers won't be able to build any garland of them. Any garland consisting of these lamps will have at least one pair of lamps of the same color adjacent to each other. Note that the store workers should use all the lamps you provided.So Polycarp has bought some sets of lamps and now he wants to know if the store workers can build a garland from each of them.
256 megabytes
import java.util.Arrays; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t = toInt(sc.nextLine()); for (int i = 0; i < t ; i++) { int r = sc.nextInt(), g = sc.nextInt(), b = sc.nextInt(); int max = Math.max(Math.max(r,g),b); int min = Math.min(Math.min(r,g),b); int middle = ((r+g-max) + (b -min)); if(max <= min+middle+1) { System.out.println("Yes"); } else { System.out.println("No"); } } } static int[] toArray(String text) { return Arrays.stream(text.split(" ")) .mapToInt(Integer::parseInt) .toArray(); } static int toInt(String text) { return Integer.parseInt(text); } }
Java
["3\n3 3 3\n1 10 2\n2 1 1"]
1 second
["Yes\nNo\nYes"]
NoteThe first two sets are desribed in the statement.The third set produces garland "RBRG", for example.
Java 8
standard input
[ "math" ]
34aa41871ee50f06e8acbd5eee94b493
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of sets of lamps Polycarp has bought. Each of the next $$$t$$$ lines contains three integers $$$r$$$, $$$g$$$ and $$$b$$$ ($$$1 \le r, g, b \le 10^9$$$) — the number of red, green and blue lamps in the set, respectively.
900
Print $$$t$$$ lines — for each set of lamps print "Yes" if the store workers can build a garland from them and "No" otherwise.
standard output
PASSED
df2f47e50d7126012b08322f95b50e89
train_003.jsonl
1577457600
Polycarp is sad — New Year is coming in few days but there is still no snow in his city. To bring himself New Year mood, he decided to decorate his house with some garlands.The local store introduced a new service this year, called "Build your own garland". So you can buy some red, green and blue lamps, provide them and the store workers will solder a single garland of them. The resulting garland will have all the lamps you provided put in a line. Moreover, no pair of lamps of the same color will be adjacent to each other in this garland!For example, if you provide $$$3$$$ red, $$$3$$$ green and $$$3$$$ blue lamps, the resulting garland can look like this: "RGBRBGBGR" ("RGB" being the red, green and blue color, respectively). Note that it's ok to have lamps of the same color on the ends of the garland.However, if you provide, say, $$$1$$$ red, $$$10$$$ green and $$$2$$$ blue lamps then the store workers won't be able to build any garland of them. Any garland consisting of these lamps will have at least one pair of lamps of the same color adjacent to each other. Note that the store workers should use all the lamps you provided.So Polycarp has bought some sets of lamps and now he wants to know if the store workers can build a garland from each of them.
256 megabytes
import java.io.*; import java.util.*; import java.lang.*; public class c1 { public static FScanner scan; public static PrintWriter out; public static void main(String[] args) { scan=new FScanner(); out=new PrintWriter(new BufferedOutputStream(System.out)); // int t=1; int t=scan.nextInt(); while(t-->0) { int[] a=new int[3]; for(int c=0;c<3;c++) a[c]=scan.nextInt(); Arrays.sort(a); out.println((a[2]<=a[0]+a[1]+1)?"Yes":"No"); } out.close(); } //-----------------------------------------------------HERE--------------------------------------------------------- //------------------------------------------------------------------------------------------------------------------ //scanner public static class FScanner { BufferedReader br; StringTokenizer st; public FScanner() { 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\n3 3 3\n1 10 2\n2 1 1"]
1 second
["Yes\nNo\nYes"]
NoteThe first two sets are desribed in the statement.The third set produces garland "RBRG", for example.
Java 8
standard input
[ "math" ]
34aa41871ee50f06e8acbd5eee94b493
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of sets of lamps Polycarp has bought. Each of the next $$$t$$$ lines contains three integers $$$r$$$, $$$g$$$ and $$$b$$$ ($$$1 \le r, g, b \le 10^9$$$) — the number of red, green and blue lamps in the set, respectively.
900
Print $$$t$$$ lines — for each set of lamps print "Yes" if the store workers can build a garland from them and "No" otherwise.
standard output
PASSED
e401a3e5a28f628d7061a16439eef6e6
train_003.jsonl
1577457600
Polycarp is sad — New Year is coming in few days but there is still no snow in his city. To bring himself New Year mood, he decided to decorate his house with some garlands.The local store introduced a new service this year, called "Build your own garland". So you can buy some red, green and blue lamps, provide them and the store workers will solder a single garland of them. The resulting garland will have all the lamps you provided put in a line. Moreover, no pair of lamps of the same color will be adjacent to each other in this garland!For example, if you provide $$$3$$$ red, $$$3$$$ green and $$$3$$$ blue lamps, the resulting garland can look like this: "RGBRBGBGR" ("RGB" being the red, green and blue color, respectively). Note that it's ok to have lamps of the same color on the ends of the garland.However, if you provide, say, $$$1$$$ red, $$$10$$$ green and $$$2$$$ blue lamps then the store workers won't be able to build any garland of them. Any garland consisting of these lamps will have at least one pair of lamps of the same color adjacent to each other. Note that the store workers should use all the lamps you provided.So Polycarp has bought some sets of lamps and now he wants to know if the store workers can build a garland from each of them.
256 megabytes
import java.util.*; public class Main { public static Scanner scanner = new Scanner(System.in); public static void main(String[] args) { int t = scanner.nextInt(); for (int i = 0; i < t; i++) { int r = scanner.nextInt(); int g = scanner.nextInt(); int b = scanner.nextInt(); if (r>g){ int temp = g; g = r; r = temp; } if(g>b){ int temp = b; b = g; g = temp; } if(b <= r + g + 1){ System.out.println("YES"); } else { System.out.println("NO"); } } } }
Java
["3\n3 3 3\n1 10 2\n2 1 1"]
1 second
["Yes\nNo\nYes"]
NoteThe first two sets are desribed in the statement.The third set produces garland "RBRG", for example.
Java 8
standard input
[ "math" ]
34aa41871ee50f06e8acbd5eee94b493
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of sets of lamps Polycarp has bought. Each of the next $$$t$$$ lines contains three integers $$$r$$$, $$$g$$$ and $$$b$$$ ($$$1 \le r, g, b \le 10^9$$$) — the number of red, green and blue lamps in the set, respectively.
900
Print $$$t$$$ lines — for each set of lamps print "Yes" if the store workers can build a garland from them and "No" otherwise.
standard output
PASSED
2ace52adf79e596abf408bae8410d202
train_003.jsonl
1577457600
Polycarp is sad — New Year is coming in few days but there is still no snow in his city. To bring himself New Year mood, he decided to decorate his house with some garlands.The local store introduced a new service this year, called "Build your own garland". So you can buy some red, green and blue lamps, provide them and the store workers will solder a single garland of them. The resulting garland will have all the lamps you provided put in a line. Moreover, no pair of lamps of the same color will be adjacent to each other in this garland!For example, if you provide $$$3$$$ red, $$$3$$$ green and $$$3$$$ blue lamps, the resulting garland can look like this: "RGBRBGBGR" ("RGB" being the red, green and blue color, respectively). Note that it's ok to have lamps of the same color on the ends of the garland.However, if you provide, say, $$$1$$$ red, $$$10$$$ green and $$$2$$$ blue lamps then the store workers won't be able to build any garland of them. Any garland consisting of these lamps will have at least one pair of lamps of the same color adjacent to each other. Note that the store workers should use all the lamps you provided.So Polycarp has bought some sets of lamps and now he wants to know if the store workers can build a garland from each of them.
256 megabytes
import java.util.*; import static java.util.Comparator.*; public class A { public static void main(String args[]) { int cases; Scanner lec = new Scanner(System.in); cases = lec.nextInt(); List lst; for (int i = 0; i < cases; ++i) { double r, g, b; r = lec.nextDouble(); g = lec.nextDouble(); b = lec.nextDouble(); lst = new ArrayList<Double>(); lst.add(r); lst.add(g); lst.add(b); lst.sort(naturalOrder()); double m = (double)lst.get(2); double s = (double)lst.get(1) + (double)lst.get(0); if(m - s <= 1) { System.out.println("Yes"); } else { System.out.println("No"); } } } }
Java
["3\n3 3 3\n1 10 2\n2 1 1"]
1 second
["Yes\nNo\nYes"]
NoteThe first two sets are desribed in the statement.The third set produces garland "RBRG", for example.
Java 8
standard input
[ "math" ]
34aa41871ee50f06e8acbd5eee94b493
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of sets of lamps Polycarp has bought. Each of the next $$$t$$$ lines contains three integers $$$r$$$, $$$g$$$ and $$$b$$$ ($$$1 \le r, g, b \le 10^9$$$) — the number of red, green and blue lamps in the set, respectively.
900
Print $$$t$$$ lines — for each set of lamps print "Yes" if the store workers can build a garland from them and "No" otherwise.
standard output
PASSED
7e4f196cbe3e9c0d9c8c2accfd7b8f23
train_003.jsonl
1537612500
After learning a lot about space exploration, a little girl named Ana wants to change the subject.Ana is a girl who loves palindromes (string that can be read the same backwards as forward). She has learned how to check for a given string whether it's a palindrome or not, but soon she grew tired of this problem, so she came up with a more interesting one and she needs your help to solve it:You are given an array of strings which consist of only small letters of the alphabet. Your task is to find how many palindrome pairs are there in the array. A palindrome pair is a pair of strings such that the following condition holds: at least one permutation of the concatenation of the two strings is a palindrome. In other words, if you have two strings, let's say "aab" and "abcac", and you concatenate them into "aababcac", we have to check if there exists a permutation of this new string such that it is a palindrome (in this case there exists the permutation "aabccbaa"). Two pairs are considered different if the strings are located on different indices. The pair of strings with indices $$$(i,j)$$$ is considered the same as the pair $$$(j,i)$$$.
256 megabytes
//package com.company; import java.util.HashMap; import java.util.Scanner; public class CF_1045_I { public static void main(String args[]) { Scanner sc=new Scanner(System.in); int n=sc.nextInt(); String s[]=new String[n]; for(int i=0;i<n;++i) s[i]=sc.next(); HashMap<Long,Integer> hm=new HashMap<>(); long ans=0; for(int i=0;i<n;++i) { long mask=0; for(int j=0;j<s[i].length();++j) { mask^=1<<(s[i].charAt(j)-'a'); } ans+=hm.getOrDefault(mask,0); for(int j=0;j<26;++j) { ans+=hm.getOrDefault(mask^(1<<j),0); } hm.put(mask,hm.getOrDefault(mask,0)+1); } System.out.println(ans); } }
Java
["3\naa\nbb\ncd", "6\naab\nabcac\ndffe\ned\naa\naade"]
2 seconds
["1", "6"]
NoteThe first example: aa $$$+$$$ bb $$$\to$$$ abba. The second example: aab $$$+$$$ abcac $$$=$$$ aababcac $$$\to$$$ aabccbaa aab $$$+$$$ aa $$$=$$$ aabaa abcac $$$+$$$ aa $$$=$$$ abcacaa $$$\to$$$ aacbcaa dffe $$$+$$$ ed $$$=$$$ dffeed $$$\to$$$ fdeedf dffe $$$+$$$ aade $$$=$$$ dffeaade $$$\to$$$ adfaafde ed $$$+$$$ aade $$$=$$$ edaade $$$\to$$$ aeddea
Java 8
standard input
[ "hashing", "strings" ]
2475df43379ffd450fa661927ae3b734
The first line contains a positive integer $$$N$$$ ($$$1 \le N \le 100\,000$$$), representing the length of the input array. Eacg of the next $$$N$$$ lines contains a string (consisting of lowercase English letters from 'a' to 'z') — an element of the input array. The total number of characters in the input array will be less than $$$1\,000\,000$$$.
1,600
Output one number, representing how many palindrome pairs there are in the array.
standard output
PASSED
a4c70af2bb50c71437d5099dbd82d858
train_003.jsonl
1537612500
After learning a lot about space exploration, a little girl named Ana wants to change the subject.Ana is a girl who loves palindromes (string that can be read the same backwards as forward). She has learned how to check for a given string whether it's a palindrome or not, but soon she grew tired of this problem, so she came up with a more interesting one and she needs your help to solve it:You are given an array of strings which consist of only small letters of the alphabet. Your task is to find how many palindrome pairs are there in the array. A palindrome pair is a pair of strings such that the following condition holds: at least one permutation of the concatenation of the two strings is a palindrome. In other words, if you have two strings, let's say "aab" and "abcac", and you concatenate them into "aababcac", we have to check if there exists a permutation of this new string such that it is a palindrome (in this case there exists the permutation "aabccbaa"). Two pairs are considered different if the strings are located on different indices. The pair of strings with indices $$$(i,j)$$$ is considered the same as the pair $$$(j,i)$$$.
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; public class Solution { public static void findPalPairs(ArrayList<String>[] hash){ OutputStream output = System.out; PrintWriter out = new PrintWriter(output); long ans = 0; if(hash[0].size() > 1){ long n = hash[0].size(); ans = n*(n-1)/2; } for(int i=1; i<=26; i++){ ArrayList<String> list = hash[i]; HashMap<Integer,Long> map = new HashMap(); for(String s : list){ int visited = 0; for(int j=0; j<i; j++){ int key = (s.charAt(j) - 'a') +1; visited|=(1 << key); } map.put(visited,map.getOrDefault(visited,0L)+1L); } for(int key : map.keySet()){ long n = map.get(key); if(n > 1) ans+= n*(n-1)/2; } if(i!=26) ans+=findOddPairs(map,hash[i+1],i+1); } ans+= hash[0].size()*hash[1].size(); out.println(ans); out.close(); } public static long findOddPairs(HashMap<Integer,Long> map, ArrayList<String> b,int n){ if(b.size() == 0) return 0; long ans = 0; int[] index = new int[n]; for(String s: b){ int visited = 0; for(int i=0; i<n; i++){ int key = (s.charAt(i) - 'a')+1; visited|=(1 << key); index[i] = key; } for(int i=0; i<n; i++){ visited ^= (1 << index[i]); if(map.containsKey(visited)) ans+=map.get(visited); visited ^= (1 << index[i]); } } return ans; } public static void main (String[] args) throws java.lang.Exception { InputStreamReader in = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(in); StringTokenizer st = new StringTokenizer(br.readLine()); int n = Integer.parseInt(st.nextToken()); ArrayList<String>[] hash = new ArrayList[27]; for(int i=0; i<=26; i++) hash[i] = new ArrayList(); for(int i=0; i<n; i++){ st = new StringTokenizer(br.readLine()); String s = st.nextToken(); String temp = calPalindrome(s); hash[temp.length()].add(temp); } findPalPairs(hash); } public static String calPalindrome(String s){ StringBuilder sb = new StringBuilder(); int[] occ = new int[26]; for(int i=0; i<s.length(); i++) occ[(s.charAt(i) - 'a')]++; for(int i=0; i<26; i++) if( (occ[i] & 1) != 0) sb.append((char)(i+'a')); return new String(sb); } }
Java
["3\naa\nbb\ncd", "6\naab\nabcac\ndffe\ned\naa\naade"]
2 seconds
["1", "6"]
NoteThe first example: aa $$$+$$$ bb $$$\to$$$ abba. The second example: aab $$$+$$$ abcac $$$=$$$ aababcac $$$\to$$$ aabccbaa aab $$$+$$$ aa $$$=$$$ aabaa abcac $$$+$$$ aa $$$=$$$ abcacaa $$$\to$$$ aacbcaa dffe $$$+$$$ ed $$$=$$$ dffeed $$$\to$$$ fdeedf dffe $$$+$$$ aade $$$=$$$ dffeaade $$$\to$$$ adfaafde ed $$$+$$$ aade $$$=$$$ edaade $$$\to$$$ aeddea
Java 8
standard input
[ "hashing", "strings" ]
2475df43379ffd450fa661927ae3b734
The first line contains a positive integer $$$N$$$ ($$$1 \le N \le 100\,000$$$), representing the length of the input array. Eacg of the next $$$N$$$ lines contains a string (consisting of lowercase English letters from 'a' to 'z') — an element of the input array. The total number of characters in the input array will be less than $$$1\,000\,000$$$.
1,600
Output one number, representing how many palindrome pairs there are in the array.
standard output
PASSED
e401eea14ff30180be12d8a632a4d727
train_003.jsonl
1537612500
After learning a lot about space exploration, a little girl named Ana wants to change the subject.Ana is a girl who loves palindromes (string that can be read the same backwards as forward). She has learned how to check for a given string whether it's a palindrome or not, but soon she grew tired of this problem, so she came up with a more interesting one and she needs your help to solve it:You are given an array of strings which consist of only small letters of the alphabet. Your task is to find how many palindrome pairs are there in the array. A palindrome pair is a pair of strings such that the following condition holds: at least one permutation of the concatenation of the two strings is a palindrome. In other words, if you have two strings, let's say "aab" and "abcac", and you concatenate them into "aababcac", we have to check if there exists a permutation of this new string such that it is a palindrome (in this case there exists the permutation "aabccbaa"). Two pairs are considered different if the strings are located on different indices. The pair of strings with indices $$$(i,j)$$$ is considered the same as the pair $$$(j,i)$$$.
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; public class Solution { public static void findPalPairs(ArrayList<String>[] hash){ OutputStream output = System.out; PrintWriter out = new PrintWriter(output); long ans = 0; if(hash[0].size() > 1){ long n = hash[0].size(); ans = n*(n-1)/2; } for(int i=1; i<=26; i++){ ArrayList<String> list = hash[i]; HashMap<String,Long> map = new HashMap(); for(String s : list){ boolean[] visited = new boolean[26]; for(int j=0; j<i; j++) visited[s.charAt(j) - 'a'] = true; String temp = Arrays.toString(visited); map.put(temp,map.getOrDefault(temp,0L)+1L); } for(String key : map.keySet()){ long n = map.get(key); if(n > 1) ans+= n*(n-1)/2; } if(i!=26) ans+=findOddPairs(map,hash[i+1],i+1); } ans+= hash[0].size()*hash[1].size(); out.println(ans); out.close(); } public static long findOddPairs(HashMap<String,Long> map, ArrayList<String> b,int n){ if(b.size() == 0) return 0; long ans = 0; int[] index = new int[n]; for(String s: b){ boolean[] visited = new boolean[26]; for(int i=0; i<n; i++){ int k = s.charAt(i) - 'a'; visited[k] = true; index[i] = k; } for(int i=0; i<n; i++){ visited[index[i]] = false; String temp = Arrays.toString(visited); if(map.containsKey(temp)) ans+=map.get(temp); visited[index[i]] = true; } } return ans; } public static void main (String[] args) throws java.lang.Exception { InputStreamReader in = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(in); StringTokenizer st = new StringTokenizer(br.readLine()); int n = Integer.parseInt(st.nextToken()); ArrayList<String>[] hash = new ArrayList[27]; for(int i=0; i<=26; i++) hash[i] = new ArrayList(); for(int i=0; i<n; i++){ st = new StringTokenizer(br.readLine()); String s = st.nextToken(); String temp = calPalindrome(s); hash[temp.length()].add(temp); } findPalPairs(hash); } public static String calPalindrome(String s){ StringBuilder sb = new StringBuilder(); int[] occ = new int[26]; for(int i=0; i<s.length(); i++) occ[(s.charAt(i) - 'a')]++; for(int i=0; i<26; i++) if( (occ[i] & 1) != 0) sb.append((char)(i+'a')); return new String(sb); } }
Java
["3\naa\nbb\ncd", "6\naab\nabcac\ndffe\ned\naa\naade"]
2 seconds
["1", "6"]
NoteThe first example: aa $$$+$$$ bb $$$\to$$$ abba. The second example: aab $$$+$$$ abcac $$$=$$$ aababcac $$$\to$$$ aabccbaa aab $$$+$$$ aa $$$=$$$ aabaa abcac $$$+$$$ aa $$$=$$$ abcacaa $$$\to$$$ aacbcaa dffe $$$+$$$ ed $$$=$$$ dffeed $$$\to$$$ fdeedf dffe $$$+$$$ aade $$$=$$$ dffeaade $$$\to$$$ adfaafde ed $$$+$$$ aade $$$=$$$ edaade $$$\to$$$ aeddea
Java 8
standard input
[ "hashing", "strings" ]
2475df43379ffd450fa661927ae3b734
The first line contains a positive integer $$$N$$$ ($$$1 \le N \le 100\,000$$$), representing the length of the input array. Eacg of the next $$$N$$$ lines contains a string (consisting of lowercase English letters from 'a' to 'z') — an element of the input array. The total number of characters in the input array will be less than $$$1\,000\,000$$$.
1,600
Output one number, representing how many palindrome pairs there are in the array.
standard output
PASSED
fd8f59b36de5800e90bbe5e594ab6ff1
train_003.jsonl
1537612500
After learning a lot about space exploration, a little girl named Ana wants to change the subject.Ana is a girl who loves palindromes (string that can be read the same backwards as forward). She has learned how to check for a given string whether it's a palindrome or not, but soon she grew tired of this problem, so she came up with a more interesting one and she needs your help to solve it:You are given an array of strings which consist of only small letters of the alphabet. Your task is to find how many palindrome pairs are there in the array. A palindrome pair is a pair of strings such that the following condition holds: at least one permutation of the concatenation of the two strings is a palindrome. In other words, if you have two strings, let's say "aab" and "abcac", and you concatenate them into "aababcac", we have to check if there exists a permutation of this new string such that it is a palindrome (in this case there exists the permutation "aabccbaa"). Two pairs are considered different if the strings are located on different indices. The pair of strings with indices $$$(i,j)$$$ is considered the same as the pair $$$(j,i)$$$.
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 n = Integer.parseInt(in.readLine()); HashMap<String, Integer> map = new HashMap<>(); String[] input = new String[n]; int lenone = 0; for (int i = 0; i < n; i++) { String string = in.readLine(); int[] count = new int[26]; for (int j = 0; j < string.length(); j++) { count[string.charAt(j)-'a']++; } for (int j = 0; j < 26; j++) { count[j] %= 2; } StringBuilder sb = new StringBuilder(); for (int j = 0; j < 26; j++) { if (count[j] == 1) { sb.append((char)(j + 'a')); } } String transform = sb.toString(); if (transform.length() == 1) { lenone++; } if (!map.containsKey(sb.toString())) { map.put(sb.toString(), 1); } else { map.put(sb.toString(), map.get(sb.toString()) + 1); } input[i] = transform; } double amount = 0; for (int i = 0; i < n; i++) { String string = input[i]; double res = 0; res += ((double)map.get(string) - 1)/2; int[] count = new int[26]; for (int j = 0; j < string.length(); j++) { count[string.charAt(j) - 'a']++; } for (int j = 0; j < 26; j++) { if (count[j] == 0) { continue; } StringBuilder store = new StringBuilder(); for (int k = 0; k < 26; k++) { if (k == j) { continue; } if (count[k] == 1) { store.append((char) (k + 'a')); } } if (map.containsKey(store.toString())) { res += map.get(store.toString()); } } amount += res; } System.out.println((long)amount); } } /* 4 aba aca aa aa 3 aba aca aa */
Java
["3\naa\nbb\ncd", "6\naab\nabcac\ndffe\ned\naa\naade"]
2 seconds
["1", "6"]
NoteThe first example: aa $$$+$$$ bb $$$\to$$$ abba. The second example: aab $$$+$$$ abcac $$$=$$$ aababcac $$$\to$$$ aabccbaa aab $$$+$$$ aa $$$=$$$ aabaa abcac $$$+$$$ aa $$$=$$$ abcacaa $$$\to$$$ aacbcaa dffe $$$+$$$ ed $$$=$$$ dffeed $$$\to$$$ fdeedf dffe $$$+$$$ aade $$$=$$$ dffeaade $$$\to$$$ adfaafde ed $$$+$$$ aade $$$=$$$ edaade $$$\to$$$ aeddea
Java 8
standard input
[ "hashing", "strings" ]
2475df43379ffd450fa661927ae3b734
The first line contains a positive integer $$$N$$$ ($$$1 \le N \le 100\,000$$$), representing the length of the input array. Eacg of the next $$$N$$$ lines contains a string (consisting of lowercase English letters from 'a' to 'z') — an element of the input array. The total number of characters in the input array will be less than $$$1\,000\,000$$$.
1,600
Output one number, representing how many palindrome pairs there are in the array.
standard output
PASSED
2b2b767c99754b5ee218858bc7cb643e
train_003.jsonl
1537612500
After learning a lot about space exploration, a little girl named Ana wants to change the subject.Ana is a girl who loves palindromes (string that can be read the same backwards as forward). She has learned how to check for a given string whether it's a palindrome or not, but soon she grew tired of this problem, so she came up with a more interesting one and she needs your help to solve it:You are given an array of strings which consist of only small letters of the alphabet. Your task is to find how many palindrome pairs are there in the array. A palindrome pair is a pair of strings such that the following condition holds: at least one permutation of the concatenation of the two strings is a palindrome. In other words, if you have two strings, let's say "aab" and "abcac", and you concatenate them into "aababcac", we have to check if there exists a permutation of this new string such that it is a palindrome (in this case there exists the permutation "aabccbaa"). Two pairs are considered different if the strings are located on different indices. The pair of strings with indices $$$(i,j)$$$ is considered the same as the pair $$$(j,i)$$$.
256 megabytes
import java.util.*; import java.io.*; public class Solution { public static void main(String []args) throws IOException { BufferedReader br = new BufferedReader( new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); int n = Integer.parseInt(st.nextToken()); HashMap<Integer,Integer> map = new HashMap<Integer,Integer>(); int arr[] = new int[n]; for(int i = 0 ; i < n ; i++) { String s = br.readLine(); int f[] = new int[26]; for(int j = 0 ; j <s.length() ; j++) { f[s.charAt(j)-'a']++; } int mask = 0; for(int k = 0 ; k < 26 ; k++) { if(f[k]%2 == 1) mask = mask|(1<<k); } if(map.containsKey(mask)) map.replace(mask , map.get(mask)+1); else map.put(mask,1); arr[i] = mask; } long ans = 0; for(int i = 0 ; i < n ; i++) { if(map.get(arr[i]) == 1) map.remove(arr[i]); else map.replace(arr[i] , map.get(arr[i])-1); if(map.containsKey(arr[i])) ans += map.get(arr[i]); for(int j = 0 ; j < 26 ; j++) { int bit = 1<<j; bit = bit^arr[i]; if(map.containsKey(bit)) { ans += map.get(bit); } } } System.out.println(ans); } }
Java
["3\naa\nbb\ncd", "6\naab\nabcac\ndffe\ned\naa\naade"]
2 seconds
["1", "6"]
NoteThe first example: aa $$$+$$$ bb $$$\to$$$ abba. The second example: aab $$$+$$$ abcac $$$=$$$ aababcac $$$\to$$$ aabccbaa aab $$$+$$$ aa $$$=$$$ aabaa abcac $$$+$$$ aa $$$=$$$ abcacaa $$$\to$$$ aacbcaa dffe $$$+$$$ ed $$$=$$$ dffeed $$$\to$$$ fdeedf dffe $$$+$$$ aade $$$=$$$ dffeaade $$$\to$$$ adfaafde ed $$$+$$$ aade $$$=$$$ edaade $$$\to$$$ aeddea
Java 8
standard input
[ "hashing", "strings" ]
2475df43379ffd450fa661927ae3b734
The first line contains a positive integer $$$N$$$ ($$$1 \le N \le 100\,000$$$), representing the length of the input array. Eacg of the next $$$N$$$ lines contains a string (consisting of lowercase English letters from 'a' to 'z') — an element of the input array. The total number of characters in the input array will be less than $$$1\,000\,000$$$.
1,600
Output one number, representing how many palindrome pairs there are in the array.
standard output
PASSED
fd977f5adc8eb73c9a126aa55046d379
train_003.jsonl
1537612500
After learning a lot about space exploration, a little girl named Ana wants to change the subject.Ana is a girl who loves palindromes (string that can be read the same backwards as forward). She has learned how to check for a given string whether it's a palindrome or not, but soon she grew tired of this problem, so she came up with a more interesting one and she needs your help to solve it:You are given an array of strings which consist of only small letters of the alphabet. Your task is to find how many palindrome pairs are there in the array. A palindrome pair is a pair of strings such that the following condition holds: at least one permutation of the concatenation of the two strings is a palindrome. In other words, if you have two strings, let's say "aab" and "abcac", and you concatenate them into "aababcac", we have to check if there exists a permutation of this new string such that it is a palindrome (in this case there exists the permutation "aabccbaa"). Two pairs are considered different if the strings are located on different indices. The pair of strings with indices $$$(i,j)$$$ is considered the same as the pair $$$(j,i)$$$.
256 megabytes
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.StringTokenizer; public class I { static StringTokenizer st; static BufferedReader br; static PrintWriter pw; public static void main(String[] args) throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); int n = nextInt(); long ans = 0; int[]cnt = new int[26]; Map<Integer, Integer> map= new HashMap<>(); for (int i = 0; i < n; i++) { String s = next(); Arrays.fill(cnt, 0); for (int j = 0; j < s.length(); j++) { cnt[s.charAt(j)-'a'] ++; } int mask = 0; for (int j = 0; j < 26; j++) { if ((cnt[j] & 1) != 0) { mask |= (1 << j); } } if (map.containsKey(mask)) ans += map.get(mask); for (int j = 0; j < 26; j++) { int prevmask = mask ^ (1 << j); if (map.containsKey(prevmask)) { ans += map.get(prevmask); } } if (!map.containsKey(mask)) { map.put(mask, 1); } else { map.put(mask, map.get(mask) + 1); } } System.out.println(ans); pw.close(); } private static int nextInt() throws IOException { return Integer.parseInt(next()); } private static long nextLong() throws IOException { return Long.parseLong(next()); } private static double nextDouble() throws IOException { return Double.parseDouble(next()); } private static String next() throws IOException { while (st==null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } }
Java
["3\naa\nbb\ncd", "6\naab\nabcac\ndffe\ned\naa\naade"]
2 seconds
["1", "6"]
NoteThe first example: aa $$$+$$$ bb $$$\to$$$ abba. The second example: aab $$$+$$$ abcac $$$=$$$ aababcac $$$\to$$$ aabccbaa aab $$$+$$$ aa $$$=$$$ aabaa abcac $$$+$$$ aa $$$=$$$ abcacaa $$$\to$$$ aacbcaa dffe $$$+$$$ ed $$$=$$$ dffeed $$$\to$$$ fdeedf dffe $$$+$$$ aade $$$=$$$ dffeaade $$$\to$$$ adfaafde ed $$$+$$$ aade $$$=$$$ edaade $$$\to$$$ aeddea
Java 8
standard input
[ "hashing", "strings" ]
2475df43379ffd450fa661927ae3b734
The first line contains a positive integer $$$N$$$ ($$$1 \le N \le 100\,000$$$), representing the length of the input array. Eacg of the next $$$N$$$ lines contains a string (consisting of lowercase English letters from 'a' to 'z') — an element of the input array. The total number of characters in the input array will be less than $$$1\,000\,000$$$.
1,600
Output one number, representing how many palindrome pairs there are in the array.
standard output
PASSED
49f2b953de29856980b7d67e271a747b
train_003.jsonl
1537612500
After learning a lot about space exploration, a little girl named Ana wants to change the subject.Ana is a girl who loves palindromes (string that can be read the same backwards as forward). She has learned how to check for a given string whether it's a palindrome or not, but soon she grew tired of this problem, so she came up with a more interesting one and she needs your help to solve it:You are given an array of strings which consist of only small letters of the alphabet. Your task is to find how many palindrome pairs are there in the array. A palindrome pair is a pair of strings such that the following condition holds: at least one permutation of the concatenation of the two strings is a palindrome. In other words, if you have two strings, let's say "aab" and "abcac", and you concatenate them into "aababcac", we have to check if there exists a permutation of this new string such that it is a palindrome (in this case there exists the permutation "aabccbaa"). Two pairs are considered different if the strings are located on different indices. The pair of strings with indices $$$(i,j)$$$ is considered the same as the pair $$$(j,i)$$$.
256 megabytes
import java.io.*; import java.util.*; public class Main { static int N; static String[] S; public static void main(String[] args) { FastScanner sc = new FastScanner(System.in); N = sc.nextInt(); S = new String[N]; for (int i = 0; i < N; i++) { S[i] = sc.next(); } System.out.println(solve()); } static long solve() { long ans = 0; Map<Integer, Integer> counts = new HashMap<>(); for (int i = 0; i < N; i++) { // false = even, true = odd int flag = 0; String s = S[i]; for (int j = 0; j < s.length(); j++) { char c = s.charAt(j); flag ^= (1 << (c - 'a')); } if( flag == 0 ) { // 0 + 0 = 0 ans += counts.getOrDefault(0, 0); // 0 + a = a for (int j = 0; j < 26; j++) { ans += counts.getOrDefault(1 << j, 0); } } else { for (int j = 0; j < 26; j++) { int b = 1 << j; if( (flag & b) == b ) { // abc + (abc - c) = aabbc ans += counts.getOrDefault(flag ^ b, 0); } else { // abc + (abc + d) = aabbccd ans += counts.getOrDefault(flag | b, 0); } } // abc + abc = 0 ans += counts.getOrDefault(flag, 0); } increment(counts, flag); } return ans; } static int get(Map<Integer, Integer> counts, int flag) { return counts.getOrDefault(flag, 0); } static void increment(Map<Integer, Integer> counts, int flag) { if( counts.containsKey(flag) ) { counts.put(flag, counts.get(flag) + 1); } else { counts.put(flag, 1); } } @SuppressWarnings("unused") static class FastScanner { private BufferedReader reader; private StringTokenizer tokenizer; FastScanner(InputStream in) { reader = new BufferedReader(new InputStreamReader(in)); tokenizer = null; } String next() { if (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } String nextLine() { if (tokenizer == null || !tokenizer.hasMoreTokens()) { try { return reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken("\n"); } long nextLong() { return Long.parseLong(next()); } int nextInt() { return Integer.parseInt(next()); } int[] nextIntArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } int[] nextIntArray(int n, int delta) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt() + delta; return a; } long[] nextLongArray(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } } static void writeLines(int[] as) { PrintWriter pw = new PrintWriter(System.out); for (int a : as) pw.println(a); pw.flush(); } static void writeLines(long[] as) { PrintWriter pw = new PrintWriter(System.out); for (long a : as) pw.println(a); pw.flush(); } static void writeSingleLine(int[] as) { PrintWriter pw = new PrintWriter(System.out); for (int i = 0; i < as.length; i++) { if (i != 0) pw.print(" "); pw.print(i); } pw.println(); pw.flush(); } static int max(int... as) { int max = Integer.MIN_VALUE; for (int a : as) max = Math.max(a, max); return max; } static int min(int... as) { int min = Integer.MAX_VALUE; for (int a : as) min = Math.min(a, min); return min; } static void debug(Object... args) { StringJoiner j = new StringJoiner(" "); for (Object arg : args) { if (arg instanceof int[]) j.add(Arrays.toString((int[]) arg)); else if (arg instanceof long[]) j.add(Arrays.toString((long[]) arg)); else if (arg instanceof double[]) j.add(Arrays.toString((double[]) arg)); else if (arg instanceof Object[]) j.add(Arrays.toString((Object[]) arg)); else j.add(arg == null ? "null" : arg.toString()); } System.err.println(j.toString()); } static void printSingleLine(int[] array) { for (int i = 0; i < array.length; i++) { if (i != 0) System.out.print(" "); System.out.print(array[i]); } System.out.println(); } static int lowerBound(int[] array, int value) { int low = 0, high = array.length, mid; while (low < high) { mid = ((high - low) >>> 1) + low; if (array[mid] < value) low = mid + 1; else high = mid; } return low; } static int upperBound(int[] array, int value) { int low = 0, high = array.length, mid; while (low < high) { mid = ((high - low) >>> 1) + low; if (array[mid] <= value) low = mid + 1; else high = mid; } return low; } }
Java
["3\naa\nbb\ncd", "6\naab\nabcac\ndffe\ned\naa\naade"]
2 seconds
["1", "6"]
NoteThe first example: aa $$$+$$$ bb $$$\to$$$ abba. The second example: aab $$$+$$$ abcac $$$=$$$ aababcac $$$\to$$$ aabccbaa aab $$$+$$$ aa $$$=$$$ aabaa abcac $$$+$$$ aa $$$=$$$ abcacaa $$$\to$$$ aacbcaa dffe $$$+$$$ ed $$$=$$$ dffeed $$$\to$$$ fdeedf dffe $$$+$$$ aade $$$=$$$ dffeaade $$$\to$$$ adfaafde ed $$$+$$$ aade $$$=$$$ edaade $$$\to$$$ aeddea
Java 8
standard input
[ "hashing", "strings" ]
2475df43379ffd450fa661927ae3b734
The first line contains a positive integer $$$N$$$ ($$$1 \le N \le 100\,000$$$), representing the length of the input array. Eacg of the next $$$N$$$ lines contains a string (consisting of lowercase English letters from 'a' to 'z') — an element of the input array. The total number of characters in the input array will be less than $$$1\,000\,000$$$.
1,600
Output one number, representing how many palindrome pairs there are in the array.
standard output
PASSED
cd935ee079d35bf4affea5a06edd7710
train_003.jsonl
1537612500
After learning a lot about space exploration, a little girl named Ana wants to change the subject.Ana is a girl who loves palindromes (string that can be read the same backwards as forward). She has learned how to check for a given string whether it's a palindrome or not, but soon she grew tired of this problem, so she came up with a more interesting one and she needs your help to solve it:You are given an array of strings which consist of only small letters of the alphabet. Your task is to find how many palindrome pairs are there in the array. A palindrome pair is a pair of strings such that the following condition holds: at least one permutation of the concatenation of the two strings is a palindrome. In other words, if you have two strings, let's say "aab" and "abcac", and you concatenate them into "aababcac", we have to check if there exists a permutation of this new string such that it is a palindrome (in this case there exists the permutation "aabccbaa"). Two pairs are considered different if the strings are located on different indices. The pair of strings with indices $$$(i,j)$$$ is considered the same as the pair $$$(j,i)$$$.
256 megabytes
import java.io.*; import java.util.*; public class SOlution { public static void main(String ag[]) { Scanner sc=new Scanner(System.in); int i,j,k; int N=sc.nextInt(); String A[]=new String[N]; for(i=0;i<N;i++) A[i]=sc.next(); HashMap<Long,Long> hm=new HashMap<>(); long hash[]=new long[N]; for(i=0;i<N;i++) { int freq[]=new int[26]; for(j=0;j<A[i].length();j++) { freq[A[i].charAt(j)-'a']=(freq[A[i].charAt(j)-'a']+1)%2; } long HASH=0L; for(j=0;j<26;j++) { if(freq[j]==1) HASH+=(1<<j); } hash[i]=HASH; if(!hm.containsKey(HASH)) hm.put(HASH,1L); else hm.put(HASH,hm.get(HASH)+1); } long ans=0; for(i=0;i<N;i++) { ans+=hm.get(hash[i])-1; for(j=0;j<26;j++) { long num=hash[i]^(1<<j); if(hm.containsKey(num)) ans+=hm.get(num); } } System.out.println(ans/2); } }
Java
["3\naa\nbb\ncd", "6\naab\nabcac\ndffe\ned\naa\naade"]
2 seconds
["1", "6"]
NoteThe first example: aa $$$+$$$ bb $$$\to$$$ abba. The second example: aab $$$+$$$ abcac $$$=$$$ aababcac $$$\to$$$ aabccbaa aab $$$+$$$ aa $$$=$$$ aabaa abcac $$$+$$$ aa $$$=$$$ abcacaa $$$\to$$$ aacbcaa dffe $$$+$$$ ed $$$=$$$ dffeed $$$\to$$$ fdeedf dffe $$$+$$$ aade $$$=$$$ dffeaade $$$\to$$$ adfaafde ed $$$+$$$ aade $$$=$$$ edaade $$$\to$$$ aeddea
Java 8
standard input
[ "hashing", "strings" ]
2475df43379ffd450fa661927ae3b734
The first line contains a positive integer $$$N$$$ ($$$1 \le N \le 100\,000$$$), representing the length of the input array. Eacg of the next $$$N$$$ lines contains a string (consisting of lowercase English letters from 'a' to 'z') — an element of the input array. The total number of characters in the input array will be less than $$$1\,000\,000$$$.
1,600
Output one number, representing how many palindrome pairs there are in the array.
standard output
PASSED
cf648514a415cdbd2a7ea414cea38ae4
train_003.jsonl
1537612500
After learning a lot about space exploration, a little girl named Ana wants to change the subject.Ana is a girl who loves palindromes (string that can be read the same backwards as forward). She has learned how to check for a given string whether it's a palindrome or not, but soon she grew tired of this problem, so she came up with a more interesting one and she needs your help to solve it:You are given an array of strings which consist of only small letters of the alphabet. Your task is to find how many palindrome pairs are there in the array. A palindrome pair is a pair of strings such that the following condition holds: at least one permutation of the concatenation of the two strings is a palindrome. In other words, if you have two strings, let's say "aab" and "abcac", and you concatenate them into "aababcac", we have to check if there exists a permutation of this new string such that it is a palindrome (in this case there exists the permutation "aabccbaa"). Two pairs are considered different if the strings are located on different indices. The pair of strings with indices $$$(i,j)$$$ is considered the same as the pair $$$(j,i)$$$.
256 megabytes
import java.util.*; import java.io.*; import static java.lang.System.out; public class Codeforces { 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; } } static class Print { private BufferedWriter bw; public Print() { this.bw = new BufferedWriter(new OutputStreamWriter(out)); } public void print(Object object) throws IOException { bw.append("" + object); } public void println(Object object) throws IOException { print(object); bw.append("\n"); } public void close() throws IOException { bw.close(); } } static int mod = (int)1e9 + 7; public static void main(String args[]) throws IOException { FastReader fr = new FastReader(); Print print = new Print(); int n = fr.nextInt(); Map<Integer, Integer> map = new HashMap<>(); long ans = 0; while(n-->0){ String s = fr.nextLine(); int x = 0; for (char ch: s.toCharArray()) x ^= (1 << (ch - 'a')); ans += map.getOrDefault(x, 0); for (int i = 0; i < 26; i++){ ans += map.getOrDefault(x ^ (1 << i), 0); } map.put(x, map.getOrDefault(x, 0)+1); } print.println(ans); print.close(); } }
Java
["3\naa\nbb\ncd", "6\naab\nabcac\ndffe\ned\naa\naade"]
2 seconds
["1", "6"]
NoteThe first example: aa $$$+$$$ bb $$$\to$$$ abba. The second example: aab $$$+$$$ abcac $$$=$$$ aababcac $$$\to$$$ aabccbaa aab $$$+$$$ aa $$$=$$$ aabaa abcac $$$+$$$ aa $$$=$$$ abcacaa $$$\to$$$ aacbcaa dffe $$$+$$$ ed $$$=$$$ dffeed $$$\to$$$ fdeedf dffe $$$+$$$ aade $$$=$$$ dffeaade $$$\to$$$ adfaafde ed $$$+$$$ aade $$$=$$$ edaade $$$\to$$$ aeddea
Java 8
standard input
[ "hashing", "strings" ]
2475df43379ffd450fa661927ae3b734
The first line contains a positive integer $$$N$$$ ($$$1 \le N \le 100\,000$$$), representing the length of the input array. Eacg of the next $$$N$$$ lines contains a string (consisting of lowercase English letters from 'a' to 'z') — an element of the input array. The total number of characters in the input array will be less than $$$1\,000\,000$$$.
1,600
Output one number, representing how many palindrome pairs there are in the array.
standard output
PASSED
dcc7a37841c4b256f0dd844e952581f5
train_003.jsonl
1537612500
After learning a lot about space exploration, a little girl named Ana wants to change the subject.Ana is a girl who loves palindromes (string that can be read the same backwards as forward). She has learned how to check for a given string whether it's a palindrome or not, but soon she grew tired of this problem, so she came up with a more interesting one and she needs your help to solve it:You are given an array of strings which consist of only small letters of the alphabet. Your task is to find how many palindrome pairs are there in the array. A palindrome pair is a pair of strings such that the following condition holds: at least one permutation of the concatenation of the two strings is a palindrome. In other words, if you have two strings, let's say "aab" and "abcac", and you concatenate them into "aababcac", we have to check if there exists a permutation of this new string such that it is a palindrome (in this case there exists the permutation "aabccbaa"). Two pairs are considered different if the strings are located on different indices. The pair of strings with indices $$$(i,j)$$$ is considered the same as the pair $$$(j,i)$$$.
256 megabytes
import java.util.*; import java.io.*; import java.math.*; import java.util.regex.*; public class Main4 { public static void main(String[] args)throws Exception { Reader reader = new Reader(); reader.readLine(); int n = reader.readInt(0); HashMap<Integer,Integer> freq = new HashMap<>(); long ans = 0; while (n-- > 0) { /* xor same --> zeroe --> even diff --> 1 --> odd */ reader.readLine(); int mask = 0; for (char ch:reader.readString(0).toCharArray()) { mask ^= (1 << (ch - 'a')); } ans += freq.getOrDefault(mask, 0); //System.out.println(" **** "); //System.out.println(Integer.toBinaryString(mask)); for (int i=0;i < 26;++i) { //System.out.println(Integer.toBinaryString(mask^(1<<i))); ans += freq.getOrDefault(mask ^ (1 << i), 0); } freq.put(mask, freq.getOrDefault(mask, 0) + 1); } System.out.println(ans); reader.close(); } } class Reader { private BufferedReader reader; private String line[]; public Reader() { reader = new BufferedReader(new InputStreamReader(System.in)); } public String[] getLine() { return line; } public boolean readLine() throws IOException { String str = reader.readLine(); if (str == null || str.isEmpty()) return false; line = line = str.split(" "); return true; } public List<Integer> getIntegersList() { List<Integer> res = new ArrayList<>(); for (String str:line) res.add(Integer.parseInt(str)); return res; } public List<Long> getLongsList() { List<Long> res = new ArrayList<>(); for (String str:line) res.add(Long.parseLong(str)); return res; } public int readInt(int pos)throws IOException { return Integer.parseInt(line[pos]); } public double readDouble(int pos)throws IOException { return Double.parseDouble(line[pos]); } public long readLong(int pos)throws IOException { return Long.parseLong(line[pos]); } public String readString(int pos)throws IOException { return line[pos]; } public void close()throws IOException { reader.close(); } }
Java
["3\naa\nbb\ncd", "6\naab\nabcac\ndffe\ned\naa\naade"]
2 seconds
["1", "6"]
NoteThe first example: aa $$$+$$$ bb $$$\to$$$ abba. The second example: aab $$$+$$$ abcac $$$=$$$ aababcac $$$\to$$$ aabccbaa aab $$$+$$$ aa $$$=$$$ aabaa abcac $$$+$$$ aa $$$=$$$ abcacaa $$$\to$$$ aacbcaa dffe $$$+$$$ ed $$$=$$$ dffeed $$$\to$$$ fdeedf dffe $$$+$$$ aade $$$=$$$ dffeaade $$$\to$$$ adfaafde ed $$$+$$$ aade $$$=$$$ edaade $$$\to$$$ aeddea
Java 8
standard input
[ "hashing", "strings" ]
2475df43379ffd450fa661927ae3b734
The first line contains a positive integer $$$N$$$ ($$$1 \le N \le 100\,000$$$), representing the length of the input array. Eacg of the next $$$N$$$ lines contains a string (consisting of lowercase English letters from 'a' to 'z') — an element of the input array. The total number of characters in the input array will be less than $$$1\,000\,000$$$.
1,600
Output one number, representing how many palindrome pairs there are in the array.
standard output
PASSED
cc7c4f76eff011a46f2d93c6cf4acd5c
train_003.jsonl
1537612500
After learning a lot about space exploration, a little girl named Ana wants to change the subject.Ana is a girl who loves palindromes (string that can be read the same backwards as forward). She has learned how to check for a given string whether it's a palindrome or not, but soon she grew tired of this problem, so she came up with a more interesting one and she needs your help to solve it:You are given an array of strings which consist of only small letters of the alphabet. Your task is to find how many palindrome pairs are there in the array. A palindrome pair is a pair of strings such that the following condition holds: at least one permutation of the concatenation of the two strings is a palindrome. In other words, if you have two strings, let's say "aab" and "abcac", and you concatenate them into "aababcac", we have to check if there exists a permutation of this new string such that it is a palindrome (in this case there exists the permutation "aabccbaa"). Two pairs are considered different if the strings are located on different indices. The pair of strings with indices $$$(i,j)$$$ is considered the same as the pair $$$(j,i)$$$.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.StreamTokenizer; public class Main { static int[][] count; static long[] result; static long[] sameCount; static long des; public static void main(String[] args) throws IOException { StreamTokenizer streamTokenizer = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in))); streamTokenizer.nextToken(); int n = (int) streamTokenizer.nval; String s; char[] chars; count = new int[n][26]; result = new long[n]; sameCount = new long[n]; int length; int exp; for (int i = 0; i < n; i++) { streamTokenizer.nextToken(); s = streamTokenizer.sval; chars = s.toCharArray(); length = chars.length; for (int j = 0; j < length; j++) count[i][chars[j] - 'a'] = 1 - count[i][chars[j] - 'a']; exp = 1; for (int j = 0; j < 26; j++) { result[i] += exp * count[i][j]; exp *= 2; } } sort(0, n - 1); // for (int i = 0; i < n; i++) // System.out.println(result[i]); long cnt = 1; long ans = 0; for (int i = 1; i < n; i++) { if (result[i] == result[i-1]) cnt++; else { for (int j = (int) cnt; j > 0; j--) sameCount[i - j] = cnt; ans += cnt * (cnt - 1) / 2; cnt = 1; } } for (int i = (int) cnt; i > 0; i--) sameCount[n - i] = cnt; ans += cnt * (cnt - 1) / 2; int index; for (int i = 0; i < n; i++) { exp = 1; for (int j = 0; j < 26; j++) { if (count[i][j] == 1) { des = result[i] - exp; index = find(0, n - 1); if (-1 != index) ans += sameCount[index]; } exp *= 2; } } System.out.println(ans); } public static void sort(int left, int right) { long mid = result[(left + right + 1) / 2]; int x = left; int y = right; long temp; int[] tempArray; while (x <= y) { while (x <= right && result[x] < mid) x++; while (y >= left && result[y] > mid) y--; if (x <= y) { temp = result[x]; result[x] = result[y]; result[y] = temp; tempArray = count[x]; count[x] = count[y]; count[y] = tempArray; x++; y--; } } if (x < right) sort(x, right); if (y > left) sort(left, y); } public static int find(int left, int right) { if (left > right) return -1; if (left == right) { if (result[left] == des) return left; return -1; } int mid = (left + right + 1) / 2; if (result[mid] > des) return find(left, mid - 1); else if (result[mid] < des) return find(mid + 1, right); return mid; } }
Java
["3\naa\nbb\ncd", "6\naab\nabcac\ndffe\ned\naa\naade"]
2 seconds
["1", "6"]
NoteThe first example: aa $$$+$$$ bb $$$\to$$$ abba. The second example: aab $$$+$$$ abcac $$$=$$$ aababcac $$$\to$$$ aabccbaa aab $$$+$$$ aa $$$=$$$ aabaa abcac $$$+$$$ aa $$$=$$$ abcacaa $$$\to$$$ aacbcaa dffe $$$+$$$ ed $$$=$$$ dffeed $$$\to$$$ fdeedf dffe $$$+$$$ aade $$$=$$$ dffeaade $$$\to$$$ adfaafde ed $$$+$$$ aade $$$=$$$ edaade $$$\to$$$ aeddea
Java 8
standard input
[ "hashing", "strings" ]
2475df43379ffd450fa661927ae3b734
The first line contains a positive integer $$$N$$$ ($$$1 \le N \le 100\,000$$$), representing the length of the input array. Eacg of the next $$$N$$$ lines contains a string (consisting of lowercase English letters from 'a' to 'z') — an element of the input array. The total number of characters in the input array will be less than $$$1\,000\,000$$$.
1,600
Output one number, representing how many palindrome pairs there are in the array.
standard output
PASSED
4e8cdad86cf981c80be9a465bbb093da
train_003.jsonl
1537612500
After learning a lot about space exploration, a little girl named Ana wants to change the subject.Ana is a girl who loves palindromes (string that can be read the same backwards as forward). She has learned how to check for a given string whether it's a palindrome or not, but soon she grew tired of this problem, so she came up with a more interesting one and she needs your help to solve it:You are given an array of strings which consist of only small letters of the alphabet. Your task is to find how many palindrome pairs are there in the array. A palindrome pair is a pair of strings such that the following condition holds: at least one permutation of the concatenation of the two strings is a palindrome. In other words, if you have two strings, let's say "aab" and "abcac", and you concatenate them into "aababcac", we have to check if there exists a permutation of this new string such that it is a palindrome (in this case there exists the permutation "aabccbaa"). Two pairs are considered different if the strings are located on different indices. The pair of strings with indices $$$(i,j)$$$ is considered the same as the pair $$$(j,i)$$$.
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.*; public class Code { public static String odds(String s) { int[] arr = new int[28]; for(int i=0;i<s.length();i++) { arr[s.charAt(i)-'a']++; } String r = ""; //System.out.println(Arrays.toString(arr)); for(int i=0;i<arr.length;i++) if(arr[i]%2==1) r+=(char)(i+'a'); return r; } public static String inOrder(String s,int n) { int[] arr = new int[28]; for(int i=0;i<s.length();i++) { if(i!=n) arr[s.charAt(i)-'a']++; } String r = ""; //System.out.println(Arrays.toString(arr)); for(int i=0;i<arr.length;i++) if(arr[i]>0) r+=(char)(i+'a'); return r; } public static void main(String[] args) throws IOException{ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); HashMap<String,Integer>h = new HashMap<>(); HashMap<String,Integer>hodds = new HashMap<>(); String[] ss = new String[n]; int c = 0; int c2 =0; for(int i=0;i<n;i++) { String s =odds(sc.next()); for(int v=0;v<s.length();v++) { String tmp = inOrder(s,v); if(hodds.containsKey(tmp)) { hodds.put(tmp,hodds.get(tmp)+1); }else { hodds.put(tmp, 1); } } if(s.length()==1) c++; if(s.length()==0) c2++; ss[i]=s; if(h.containsKey(s)) { h.put(s, h.get(s)+1); }else { h.put(s, 1); } } //System.out.println(h); //System.out.println(hodds); long r = 0; for(int i=0;i<ss.length;i++) { if(h.get(ss[i])>0) { r+= (h.get(ss[i])-1); h.put(ss[i], h.get(ss[i])-1); } if(hodds.containsKey(ss[i])) r+=hodds.get(ss[i]); } System.out.println(r); } } 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() 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 double nextDouble() throws IOException { String x = next(); StringBuilder sb = new StringBuilder("0"); double res = 0, f = 1; boolean dec = false, neg = false; int start = 0; if (x.charAt(0) == '-') { neg = true; start++; } for (int i = start; i < x.length(); i++) if (x.charAt(i) == '.') { res = Long.parseLong(sb.toString()); sb = new StringBuilder("0"); dec = true; } else { sb.append(x.charAt(i)); if (dec) f *= 10; } res += Long.parseLong(sb.toString()) / f; return res * (neg ? -1 : 1); } public boolean ready() throws IOException { return br.ready(); } }
Java
["3\naa\nbb\ncd", "6\naab\nabcac\ndffe\ned\naa\naade"]
2 seconds
["1", "6"]
NoteThe first example: aa $$$+$$$ bb $$$\to$$$ abba. The second example: aab $$$+$$$ abcac $$$=$$$ aababcac $$$\to$$$ aabccbaa aab $$$+$$$ aa $$$=$$$ aabaa abcac $$$+$$$ aa $$$=$$$ abcacaa $$$\to$$$ aacbcaa dffe $$$+$$$ ed $$$=$$$ dffeed $$$\to$$$ fdeedf dffe $$$+$$$ aade $$$=$$$ dffeaade $$$\to$$$ adfaafde ed $$$+$$$ aade $$$=$$$ edaade $$$\to$$$ aeddea
Java 8
standard input
[ "hashing", "strings" ]
2475df43379ffd450fa661927ae3b734
The first line contains a positive integer $$$N$$$ ($$$1 \le N \le 100\,000$$$), representing the length of the input array. Eacg of the next $$$N$$$ lines contains a string (consisting of lowercase English letters from 'a' to 'z') — an element of the input array. The total number of characters in the input array will be less than $$$1\,000\,000$$$.
1,600
Output one number, representing how many palindrome pairs there are in the array.
standard output
PASSED
71361d69d91274ec33fc4046c0664b0a
train_003.jsonl
1537612500
After learning a lot about space exploration, a little girl named Ana wants to change the subject.Ana is a girl who loves palindromes (string that can be read the same backwards as forward). She has learned how to check for a given string whether it's a palindrome or not, but soon she grew tired of this problem, so she came up with a more interesting one and she needs your help to solve it:You are given an array of strings which consist of only small letters of the alphabet. Your task is to find how many palindrome pairs are there in the array. A palindrome pair is a pair of strings such that the following condition holds: at least one permutation of the concatenation of the two strings is a palindrome. In other words, if you have two strings, let's say "aab" and "abcac", and you concatenate them into "aababcac", we have to check if there exists a permutation of this new string such that it is a palindrome (in this case there exists the permutation "aabccbaa"). Two pairs are considered different if the strings are located on different indices. The pair of strings with indices $$$(i,j)$$$ is considered the same as the pair $$$(j,i)$$$.
256 megabytes
import java.util.*; public class PalindromePairs { public static void main(String[] args) { Scanner scan=new Scanner(System.in); int n=scan.nextInt(); HashMap<Integer,Integer> f=new HashMap<>(); int[] masks=new int[n]; for(int i=0;i<n;i++) { String s=scan.next(); int mask=mask(s); f.put(mask,f.getOrDefault(mask,0)+1); masks[i]=mask; } long res=0; for(int i=0;i<n;i++) { int[] could=getPotential(masks[i]); // System.out.println(Integer.toBinaryString(could[i])); // for(int jj:could) { // System.out.println(Integer.toBinaryString(jj)); // } // System.out.println(); for(int j=0;j<could.length;j++) { if(!f.containsKey(could[j])) continue; long add=(long)f.get(could[j]); if(j==0) add--; res+=add; } } System.out.println(res/2); } public static int[] getPotential(int mask) { int[] res=new int[27]; res[0]=mask; for(int i=1;i<27;i++) { res[i]=mask^(1<<(i-1)); } return res; } public static int mask(String s) { int[] f=new int[26]; for(int i=0;i<s.length();i++) f[s.charAt(i)-'a']++; int res=0; for(int i=0;i<26;i++) { if(f[i]%2==0) res|=1<<i; } return res; } }
Java
["3\naa\nbb\ncd", "6\naab\nabcac\ndffe\ned\naa\naade"]
2 seconds
["1", "6"]
NoteThe first example: aa $$$+$$$ bb $$$\to$$$ abba. The second example: aab $$$+$$$ abcac $$$=$$$ aababcac $$$\to$$$ aabccbaa aab $$$+$$$ aa $$$=$$$ aabaa abcac $$$+$$$ aa $$$=$$$ abcacaa $$$\to$$$ aacbcaa dffe $$$+$$$ ed $$$=$$$ dffeed $$$\to$$$ fdeedf dffe $$$+$$$ aade $$$=$$$ dffeaade $$$\to$$$ adfaafde ed $$$+$$$ aade $$$=$$$ edaade $$$\to$$$ aeddea
Java 8
standard input
[ "hashing", "strings" ]
2475df43379ffd450fa661927ae3b734
The first line contains a positive integer $$$N$$$ ($$$1 \le N \le 100\,000$$$), representing the length of the input array. Eacg of the next $$$N$$$ lines contains a string (consisting of lowercase English letters from 'a' to 'z') — an element of the input array. The total number of characters in the input array will be less than $$$1\,000\,000$$$.
1,600
Output one number, representing how many palindrome pairs there are in the array.
standard output
PASSED
64bcbc9155abf0229c35c3c52d6d5cbe
train_003.jsonl
1537612500
After learning a lot about space exploration, a little girl named Ana wants to change the subject.Ana is a girl who loves palindromes (string that can be read the same backwards as forward). She has learned how to check for a given string whether it's a palindrome or not, but soon she grew tired of this problem, so she came up with a more interesting one and she needs your help to solve it:You are given an array of strings which consist of only small letters of the alphabet. Your task is to find how many palindrome pairs are there in the array. A palindrome pair is a pair of strings such that the following condition holds: at least one permutation of the concatenation of the two strings is a palindrome. In other words, if you have two strings, let's say "aab" and "abcac", and you concatenate them into "aababcac", we have to check if there exists a permutation of this new string such that it is a palindrome (in this case there exists the permutation "aabccbaa"). Two pairs are considered different if the strings are located on different indices. The pair of strings with indices $$$(i,j)$$$ is considered the same as the pair $$$(j,i)$$$.
256 megabytes
import java.io.*; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.StringTokenizer; import java.util.*; public class realfast implements Runnable { private static final int INF = (int) 1e9; public void solve() throws IOException { int n = readInt(); HashMap<Integer,Integer> map= new HashMap<>(); long fin=0; for(int f=0;f<n;f++) { String s = readString(); int arr[]= new int[26]; for(int j=0;j<s.length();j++) { int a =(int)s.charAt(j)-97; arr[a]=(arr[a]+1)%2; } int val=0; for(int i=0;i<26;i++) if(arr[i]==1) val= val+ (int)Math.pow(2,i); for(int i=0;i<arr.length;i++) { int cal = (int)Math.pow(2,i); if(map.containsKey(cal^val)) { fin = fin+ map.get(cal^val); } } if(map.containsKey(val)) { fin = fin+ map.get(val); map.put(val,map.get(val)+1); } else map.put(val,1); } out.println(fin); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// public static void main(String[] args) { new Thread(null, new realfast(), "", 128 * (1L << 20)).start(); } private static final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null; private BufferedReader reader; private StringTokenizer tokenizer; private PrintWriter out; @Override public void run() { try { if (ONLINE_JUDGE || !new File("input.txt").exists()) { reader = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } else { reader = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter("output.txt"); } solve(); } catch (IOException e) { throw new RuntimeException(e); } finally { try { reader.close(); } catch (IOException e) { // nothing } out.close(); } } private String readString() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } @SuppressWarnings("unused") private int readInt() throws IOException { return Integer.parseInt(readString()); } @SuppressWarnings("unused") private long readLong() throws IOException { return Long.parseLong(readString()); } @SuppressWarnings("unused") private double readDouble() throws IOException { return Double.parseDouble(readString()); } } class edge implements Comparable<edge>{ int u ; int v ; int val; edge(int u1, int v1 , int val1) { this.u=u1; this.v=v1; this.val=val1; } public int compareTo(edge e) { return this.val-e.val; } }
Java
["3\naa\nbb\ncd", "6\naab\nabcac\ndffe\ned\naa\naade"]
2 seconds
["1", "6"]
NoteThe first example: aa $$$+$$$ bb $$$\to$$$ abba. The second example: aab $$$+$$$ abcac $$$=$$$ aababcac $$$\to$$$ aabccbaa aab $$$+$$$ aa $$$=$$$ aabaa abcac $$$+$$$ aa $$$=$$$ abcacaa $$$\to$$$ aacbcaa dffe $$$+$$$ ed $$$=$$$ dffeed $$$\to$$$ fdeedf dffe $$$+$$$ aade $$$=$$$ dffeaade $$$\to$$$ adfaafde ed $$$+$$$ aade $$$=$$$ edaade $$$\to$$$ aeddea
Java 8
standard input
[ "hashing", "strings" ]
2475df43379ffd450fa661927ae3b734
The first line contains a positive integer $$$N$$$ ($$$1 \le N \le 100\,000$$$), representing the length of the input array. Eacg of the next $$$N$$$ lines contains a string (consisting of lowercase English letters from 'a' to 'z') — an element of the input array. The total number of characters in the input array will be less than $$$1\,000\,000$$$.
1,600
Output one number, representing how many palindrome pairs there are in the array.
standard output
PASSED
14e84f6e46fc833d507c4e8e0b8e7a05
train_003.jsonl
1537612500
After learning a lot about space exploration, a little girl named Ana wants to change the subject.Ana is a girl who loves palindromes (string that can be read the same backwards as forward). She has learned how to check for a given string whether it's a palindrome or not, but soon she grew tired of this problem, so she came up with a more interesting one and she needs your help to solve it:You are given an array of strings which consist of only small letters of the alphabet. Your task is to find how many palindrome pairs are there in the array. A palindrome pair is a pair of strings such that the following condition holds: at least one permutation of the concatenation of the two strings is a palindrome. In other words, if you have two strings, let's say "aab" and "abcac", and you concatenate them into "aababcac", we have to check if there exists a permutation of this new string such that it is a palindrome (in this case there exists the permutation "aabccbaa"). Two pairs are considered different if the strings are located on different indices. The pair of strings with indices $$$(i,j)$$$ is considered the same as the pair $$$(j,i)$$$.
256 megabytes
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ import java.util.HashMap; import java.io.*; /** * * @author arvin */ public class pallindrome_pairs { public static void main(String args[]) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n=Integer.parseInt(br.readLine()); long ans=0; HashMap<Integer,Integer> par=new HashMap<>(); for(int i=0;i<n;i++) { int c=0,ab=0; String s=br.readLine(); for(int j=0;j<s.length();j++) c^=1<<(s.charAt(j)-97); ab=par.getOrDefault(c,0); ans+=ab; for(int j=0;j<26;j++) { ans+=par.getOrDefault(c^(1<<j),0); } par.putIfAbsent(c,1); if(ab!=0) par.put(c,ab+1); else par.put(c,1); } System.out.println(ans); br.close(); } }
Java
["3\naa\nbb\ncd", "6\naab\nabcac\ndffe\ned\naa\naade"]
2 seconds
["1", "6"]
NoteThe first example: aa $$$+$$$ bb $$$\to$$$ abba. The second example: aab $$$+$$$ abcac $$$=$$$ aababcac $$$\to$$$ aabccbaa aab $$$+$$$ aa $$$=$$$ aabaa abcac $$$+$$$ aa $$$=$$$ abcacaa $$$\to$$$ aacbcaa dffe $$$+$$$ ed $$$=$$$ dffeed $$$\to$$$ fdeedf dffe $$$+$$$ aade $$$=$$$ dffeaade $$$\to$$$ adfaafde ed $$$+$$$ aade $$$=$$$ edaade $$$\to$$$ aeddea
Java 8
standard input
[ "hashing", "strings" ]
2475df43379ffd450fa661927ae3b734
The first line contains a positive integer $$$N$$$ ($$$1 \le N \le 100\,000$$$), representing the length of the input array. Eacg of the next $$$N$$$ lines contains a string (consisting of lowercase English letters from 'a' to 'z') — an element of the input array. The total number of characters in the input array will be less than $$$1\,000\,000$$$.
1,600
Output one number, representing how many palindrome pairs there are in the array.
standard output
PASSED
2c1afbdcdffe89f8a465b05554ec3f7e
train_003.jsonl
1537612500
After learning a lot about space exploration, a little girl named Ana wants to change the subject.Ana is a girl who loves palindromes (string that can be read the same backwards as forward). She has learned how to check for a given string whether it's a palindrome or not, but soon she grew tired of this problem, so she came up with a more interesting one and she needs your help to solve it:You are given an array of strings which consist of only small letters of the alphabet. Your task is to find how many palindrome pairs are there in the array. A palindrome pair is a pair of strings such that the following condition holds: at least one permutation of the concatenation of the two strings is a palindrome. In other words, if you have two strings, let's say "aab" and "abcac", and you concatenate them into "aababcac", we have to check if there exists a permutation of this new string such that it is a palindrome (in this case there exists the permutation "aabccbaa"). Two pairs are considered different if the strings are located on different indices. The pair of strings with indices $$$(i,j)$$$ is considered the same as the pair $$$(j,i)$$$.
256 megabytes
import java.io.*; import java.math.*; import java.util.*; public class icpc { static long count = 0L; public static void main(String[] args) throws IOException { // Reader in = new Reader(); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(in.readLine()); String[] A = new String[n]; for (int i=0;i<n;i++) A[i] = in.readLine(); HashMap<Long, Long> h = new HashMap<>(); for (int i=0;i<n;i++) { String b = A[i]; int[] B = new int[26]; for (int j=0;j<b.length();j++) B[b.charAt(j) - 'a']++; StringBuilder baseString = new StringBuilder(); for (int j=0;j<26;j++) baseString.append((char)(B[j] % 2 + '0')); long baseMask = toDecimal(baseString); for (int j=0;j<26;j++) { long toSearchMask = baseMask; if (baseString.charAt(26 - j - 1) == '1') toSearchMask -= Math.pow(2, j); else toSearchMask += Math.pow(2, j); if (h.containsKey(toSearchMask)) count += h.get(toSearchMask); } if (h.containsKey(baseMask)) count += h.get(baseMask); if (!h.containsKey(baseMask)) h.put(baseMask, 1L); else h.put(baseMask, h.get(baseMask) + 1); } System.out.println(count); } public static long toDecimal(StringBuilder stringBuilder) { long ans = 0L; for (int i=0;i<26;i++) { if (stringBuilder.charAt(26 - i - 1) == '1') ans += Math.pow(2, i); } return ans; } } class NumberTheory { public boolean isPrime(long n) { if(n < 2) return false; for(long x = 2;x * x <= n;x++) { if(n % x == 0) return false; } return true; } public ArrayList<Long> primeFactorisation(long n) { ArrayList<Long> f = new ArrayList<>(); for(long x=2;x * x <= n;x++) { while(n % x == 0) { f.add(x); n /= x; } } if(n > 1) f.add(n); return f; } public int[] sieveOfEratosthenes(int n) { int[] sieve = new int[n + 1]; for(int x=2;x<=n;x++) { if(sieve[x] != 0) continue; sieve[x] = x; for(int u=2*x;u<=n;u+=x) if(sieve[u] == 0) sieve[u] = x; } return sieve; } public long gcd(long a, long b) { if(b == 0) return a; return gcd(b, a % b); } public long phi(long n) { double result = n; for(long p=2;p*p<=n;p++) { if(n % p == 0) { while (n % p == 0) n /= p; result *= (1.0 - (1.0 / (double)p)); } } if(n > 1) result *= (1.0 - (1.0 / (double)n)); return (long)result; } public Name extendedEuclid(long a, long b) { if(b == 0) return new Name(a, 1, 0); Name n1 = extendedEuclid(b, a % b); Name n2 = new Name(n1.d, n1.y, n1.x - (long)Math.floor((double)a / b) * n1.y); return n2; } public long modularExponentiation(long a, long b, long n) { long d = 1L; String bString = Long.toBinaryString(b); for(int i=0;i<bString.length();i++) { d = (d * d) % n; if(bString.charAt(i) == '1') d = (d * a) % n; } return d; } } class Name { long d; long x; long y; public Name(long d, long x, long y) { this.d = d; this.x = x; this.y = y; } } class SuffixArray { int ALPHABET_SZ = 256, N; int[] T, lcp, sa, sa2, rank, tmp, c; public SuffixArray(String str) { this(toIntArray(str)); } private static int[] toIntArray(String s) { int[] text = new int[s.length()]; for (int i = 0; i < s.length(); i++) text[i] = s.charAt(i); return text; } public SuffixArray(int[] text) { T = text; N = text.length; sa = new int[N]; sa2 = new int[N]; rank = new int[N]; c = new int[Math.max(ALPHABET_SZ, N)]; construct(); kasai(); } private void construct() { int i, p, r; for (i = 0; i < N; ++i) c[rank[i] = T[i]]++; for (i = 1; i < ALPHABET_SZ; ++i) c[i] += c[i - 1]; for (i = N - 1; i >= 0; --i) sa[--c[T[i]]] = i; for (p = 1; p < N; p <<= 1) { for (r = 0, i = N - p; i < N; ++i) sa2[r++] = i; for (i = 0; i < N; ++i) if (sa[i] >= p) sa2[r++] = sa[i] - p; Arrays.fill(c, 0, ALPHABET_SZ, 0); for (i = 0; i < N; ++i) c[rank[i]]++; for (i = 1; i < ALPHABET_SZ; ++i) c[i] += c[i - 1]; for (i = N - 1; i >= 0; --i) sa[--c[rank[sa2[i]]]] = sa2[i]; for (sa2[sa[0]] = r = 0, i = 1; i < N; ++i) { if (!(rank[sa[i - 1]] == rank[sa[i]] && sa[i - 1] + p < N && sa[i] + p < N && rank[sa[i - 1] + p] == rank[sa[i] + p])) r++; sa2[sa[i]] = r; } tmp = rank; rank = sa2; sa2 = tmp; if (r == N - 1) break; ALPHABET_SZ = r + 1; } } private void kasai() { lcp = new int[N]; int[] inv = new int[N]; for (int i = 0; i < N; i++) inv[sa[i]] = i; for (int i = 0, len = 0; i < N; i++) { if (inv[i] > 0) { int k = sa[inv[i] - 1]; while ((i + len < N) && (k + len < N) && T[i + len] == T[k + len]) len++; lcp[inv[i] - 1] = len; if (len > 0) len--; } } } } class ZAlgorithm { public int[] calculateZ(char input[]) { int Z[] = new int[input.length]; int left = 0; int right = 0; for(int k = 1; k < input.length; k++) { if(k > right) { left = right = k; while(right < input.length && input[right] == input[right - left]) { right++; } Z[k] = right - left; right--; } else { //we are operating inside box int k1 = k - left; //if value does not stretches till right bound then just copy it. if(Z[k1] < right - k + 1) { Z[k] = Z[k1]; } else { //otherwise try to see if there are more matches. left = k; while(right < input.length && input[right] == input[right - left]) { right++; } Z[k] = right - left; right--; } } } return Z; } public ArrayList<Integer> matchPattern(char text[], char pattern[]) { char newString[] = new char[text.length + pattern.length + 1]; int i = 0; for(char ch : pattern) { newString[i] = ch; i++; } newString[i] = '$'; i++; for(char ch : text) { newString[i] = ch; i++; } ArrayList<Integer> result = new ArrayList<>(); int Z[] = calculateZ(newString); for(i = 0; i < Z.length ; i++) { if(Z[i] == pattern.length) { result.add(i - pattern.length - 1); } } return result; } } class KMPAlgorithm { public int[] computeTemporalArray(char[] pattern) { int[] lps = new int[pattern.length]; int index = 0; for(int i=1;i<pattern.length;) { if(pattern[i] == pattern[index]) { lps[i] = index + 1; index++; i++; } else { if(index != 0) { index = lps[index - 1]; } else { lps[i] = 0; i++; } } } return lps; } public ArrayList<Integer> KMPMatcher(char[] text, char[] pattern) { int[] lps = computeTemporalArray(pattern); int j = 0; int i = 0; int n = text.length; int m = pattern.length; ArrayList<Integer> indices = new ArrayList<>(); while(i < n) { if(pattern[j] == text[i]) { i++; j++; } if(j == m) { indices.add(i - j); j = lps[j - 1]; } else if(i < n && pattern[j] != text[i]) { if(j != 0) j = lps[j - 1]; else i = i + 1; } } return indices; } } class Hashing { public long[] computePowers(long p, int n, long m) { long[] powers = new long[n]; powers[0] = 1; for(int i=1;i<n;i++) { powers[i] = (powers[i - 1] * p) % m; } return powers; } public long computeHash(String s) { long p = 31; long m = 1_000_000_009; long hashValue = 0L; long[] powers = computePowers(p, s.length(), m); for(int i=0;i<s.length();i++) { char ch = s.charAt(i); hashValue = (hashValue + (ch - 'a' + 1) * powers[i]) % m; } return hashValue; } } class BasicFunctions { public 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; } public long max(long[] A) { long max = Long.MAX_VALUE; for(int i=0;i<A.length;i++) { max = Math.max(max, A[i]); } return max; } } class Matrix { long a; long b; long c; long d; public Matrix(long a, long b, long c, long d) { this.a = a; this.b = b; this.c = c; this.d = d; } } class MergeSortInt { // Merges two subarrays of arr[]. // First subarray is arr[l..m] // Second subarray is arr[m+1..r] 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() 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); } } } class MergeSortLong { // Merges two subarrays of arr[]. // First subarray is arr[l..m] // Second subarray is arr[m+1..r] void merge(long arr[], int l, int m, int r) { // Find sizes of two subarrays to be merged int n1 = m - l + 1; int n2 = r - m; /* Create temp arrays */ long L[] = new long[n1]; long R[] = new long[n2]; /*Copy data to temp arrays*/ for (int i = 0; i < n1; ++i) L[i] = arr[l + i]; for (int j = 0; j < n2; ++j) R[j] = arr[m + 1 + j]; /* Merge the temp arrays */ // Initial indexes of first and second subarrays int i = 0, j = 0; // Initial index of merged subarry array int k = l; while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } /* Copy remaining elements of L[] if any */ while (i < n1) { arr[k] = L[i]; i++; k++; } /* Copy remaining elements of R[] if any */ while (j < n2) { arr[k] = R[j]; j++; k++; } } // Main function that sorts arr[l..r] using // merge() void sort(long arr[], int l, int r) { if (l < r) { // Find the middle point int m = (l + r) / 2; // Sort first and second halves sort(arr, l, m); sort(arr, m + 1, r); // Merge the sorted halves merge(arr, l, m, r); } } } class Node { int sum; int len; Node(int a, int b) { this.sum = a; this.len = b; } @Override public boolean equals(Object ob) { if(ob == null) return false; if(!(ob instanceof Node)) return false; if(ob == this) return true; Node obj = (Node)ob; if(this.sum == obj.sum && this.len == obj.len) return true; return false; } @Override public int hashCode() { return (int)this.len; } } 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(); } } class FenwickTree { public void update(long[] fenwickTree,long delta,int index) { index += 1; while(index < fenwickTree.length) { fenwickTree[index] += delta; index = index + (index & (-index)); } } public long prefixSum(long[] fenwickTree,int index) { long sum = 0L; index += 1; while(index > 0) { sum += fenwickTree[index]; index -= (index & (-index)); } return sum; } } class SegmentTree { public int nextPowerOfTwo(int num) { if(num == 0) return 1; if(num > 0 && (num & (num - 1)) == 0) return num; while((num &(num - 1)) > 0) { num = num & (num - 1); } return num << 1; } public int[] createSegmentTree(int[] input) { int np2 = nextPowerOfTwo(input.length); int[] segmentTree = new int[np2 * 2 - 1]; for(int i=0;i<segmentTree.length;i++) segmentTree[i] = Integer.MIN_VALUE; constructSegmentTree(segmentTree,input,0,input.length-1,0); return segmentTree; } private void constructSegmentTree(int[] segmentTree,int[] input,int low,int high,int pos) { if(low == high) { segmentTree[pos] = input[low]; return; } int mid = (low + high)/ 2; constructSegmentTree(segmentTree,input,low,mid,2*pos + 1); constructSegmentTree(segmentTree,input,mid+1,high,2*pos + 2); segmentTree[pos] = Math.max(segmentTree[2*pos + 1],segmentTree[2*pos + 2]); } public int rangeMinimumQuery(int []segmentTree,int qlow,int qhigh,int len) { return rangeMinimumQuery(segmentTree,0,len-1,qlow,qhigh,0); } private int rangeMinimumQuery(int segmentTree[],int low,int high,int qlow,int qhigh,int pos) { if(qlow <= low && qhigh >= high){ return segmentTree[pos]; } if(qlow > high || qhigh < low){ return Integer.MIN_VALUE; } int mid = (low+high)/2; return Math.max(rangeMinimumQuery(segmentTree, low, mid, qlow, qhigh, 2 * pos + 1), rangeMinimumQuery(segmentTree, mid + 1, high, qlow, qhigh, 2 * pos + 2)); } }
Java
["3\naa\nbb\ncd", "6\naab\nabcac\ndffe\ned\naa\naade"]
2 seconds
["1", "6"]
NoteThe first example: aa $$$+$$$ bb $$$\to$$$ abba. The second example: aab $$$+$$$ abcac $$$=$$$ aababcac $$$\to$$$ aabccbaa aab $$$+$$$ aa $$$=$$$ aabaa abcac $$$+$$$ aa $$$=$$$ abcacaa $$$\to$$$ aacbcaa dffe $$$+$$$ ed $$$=$$$ dffeed $$$\to$$$ fdeedf dffe $$$+$$$ aade $$$=$$$ dffeaade $$$\to$$$ adfaafde ed $$$+$$$ aade $$$=$$$ edaade $$$\to$$$ aeddea
Java 8
standard input
[ "hashing", "strings" ]
2475df43379ffd450fa661927ae3b734
The first line contains a positive integer $$$N$$$ ($$$1 \le N \le 100\,000$$$), representing the length of the input array. Eacg of the next $$$N$$$ lines contains a string (consisting of lowercase English letters from 'a' to 'z') — an element of the input array. The total number of characters in the input array will be less than $$$1\,000\,000$$$.
1,600
Output one number, representing how many palindrome pairs there are in the array.
standard output
PASSED
7f62af8927842ddd59108d3dd528a8a3
train_003.jsonl
1537612500
After learning a lot about space exploration, a little girl named Ana wants to change the subject.Ana is a girl who loves palindromes (string that can be read the same backwards as forward). She has learned how to check for a given string whether it's a palindrome or not, but soon she grew tired of this problem, so she came up with a more interesting one and she needs your help to solve it:You are given an array of strings which consist of only small letters of the alphabet. Your task is to find how many palindrome pairs are there in the array. A palindrome pair is a pair of strings such that the following condition holds: at least one permutation of the concatenation of the two strings is a palindrome. In other words, if you have two strings, let's say "aab" and "abcac", and you concatenate them into "aababcac", we have to check if there exists a permutation of this new string such that it is a palindrome (in this case there exists the permutation "aabccbaa"). Two pairs are considered different if the strings are located on different indices. The pair of strings with indices $$$(i,j)$$$ is considered the same as the pair $$$(j,i)$$$.
256 megabytes
import java.io.DataInputStream; import java.io.IOException; import java.util.HashMap; import java.util.Scanner; import static java.lang.System.*; public class Main { private int[] num; private HashMap<Integer, Integer> hashtable; private int gcd(int x, int y) { if (x == 0) return y; return this.gcd(y % x, x); } public void readData() throws IOException { Scanner input = new Scanner(in); int n = input.nextInt(); num = new int[n]; hashtable = new HashMap<>(); String s = new String(); int[] cnt = new int[26]; for (int i = 0; i < n; ++i) { s = input.next(); for (int j = 0; j < 26; ++j) cnt[j] = 0; for (int j = 0; j < s.length(); ++j) { cnt[s.charAt(j) - 'a'] ^= 1; } num[i] = 0; for (int j = 0; j < 26; ++j) if (cnt[j] > 0) num[i] |= (1 << j); } } private int getHashCnt(int x) { if (hashtable.containsKey(x)) return hashtable.get(x); return 0; } private void putHashKey(int x) { if (hashtable.containsKey(x)) hashtable.replace(x, hashtable.get(x) + 1); else hashtable.put(x, 1); } public void solveProblem() { long sum = 0; for (int i = 0; i < num.length; ++i) { sum += getHashCnt(num[i]); for (int j = 0; j < 26; ++j) { sum += getHashCnt(num[i] ^ (1 << j)); } putHashKey(num[i]); } out.println(sum); } public static void main(String[] args) throws IOException { Main helper = new Main(); helper.readData(); helper.solveProblem(); } }
Java
["3\naa\nbb\ncd", "6\naab\nabcac\ndffe\ned\naa\naade"]
2 seconds
["1", "6"]
NoteThe first example: aa $$$+$$$ bb $$$\to$$$ abba. The second example: aab $$$+$$$ abcac $$$=$$$ aababcac $$$\to$$$ aabccbaa aab $$$+$$$ aa $$$=$$$ aabaa abcac $$$+$$$ aa $$$=$$$ abcacaa $$$\to$$$ aacbcaa dffe $$$+$$$ ed $$$=$$$ dffeed $$$\to$$$ fdeedf dffe $$$+$$$ aade $$$=$$$ dffeaade $$$\to$$$ adfaafde ed $$$+$$$ aade $$$=$$$ edaade $$$\to$$$ aeddea
Java 8
standard input
[ "hashing", "strings" ]
2475df43379ffd450fa661927ae3b734
The first line contains a positive integer $$$N$$$ ($$$1 \le N \le 100\,000$$$), representing the length of the input array. Eacg of the next $$$N$$$ lines contains a string (consisting of lowercase English letters from 'a' to 'z') — an element of the input array. The total number of characters in the input array will be less than $$$1\,000\,000$$$.
1,600
Output one number, representing how many palindrome pairs there are in the array.
standard output
PASSED
b66ccb83c0a3f244b524f5c7a09a9141
train_003.jsonl
1537612500
After learning a lot about space exploration, a little girl named Ana wants to change the subject.Ana is a girl who loves palindromes (string that can be read the same backwards as forward). She has learned how to check for a given string whether it's a palindrome or not, but soon she grew tired of this problem, so she came up with a more interesting one and she needs your help to solve it:You are given an array of strings which consist of only small letters of the alphabet. Your task is to find how many palindrome pairs are there in the array. A palindrome pair is a pair of strings such that the following condition holds: at least one permutation of the concatenation of the two strings is a palindrome. In other words, if you have two strings, let's say "aab" and "abcac", and you concatenate them into "aababcac", we have to check if there exists a permutation of this new string such that it is a palindrome (in this case there exists the permutation "aabccbaa"). Two pairs are considered different if the strings are located on different indices. The pair of strings with indices $$$(i,j)$$$ is considered the same as the pair $$$(j,i)$$$.
256 megabytes
//package bubble11; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.InputMismatchException; public class I { InputStream is; PrintWriter out; String INPUT = ""; void solve() { int n = ni(); int[] xs = new int[n]; for(int i = 0;i < n;i++){ int x = 0; for(char c : ns().toCharArray()){ x ^= 1<<c-'a'; } xs[i] = x; } Arrays.sort(xs); int[][] uc = uniqcount(xs); int[] u = new int[uc.length]; for(int i = 0;i < uc.length;i++)u[i] = uc[i][0]; long ans = 0; for(int i = 0;i < 26;i++){ for(int j = 0;j < u.length;j++){ int v = u[j]; int ind = Arrays.binarySearch(u, v^1<<i); if(ind >= 0){ if(j < ind){ ans += (long)uc[ind][1] * uc[j][1]; } } } } for(int[] un : uc){ ans += (long)un[1]*(un[1]-1)/2; } out.println(ans); } public static int[][] uniqcount(int[] a) { int n = a.length; int p = 0; int[][] b = new int[n][]; for(int i = 0;i < n;i++){ if(i == 0 || a[i] != a[i-1])b[p++] = new int[]{a[i], 0}; b[p-1][1]++; } return Arrays.copyOf(b, p); } 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 I().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\naa\nbb\ncd", "6\naab\nabcac\ndffe\ned\naa\naade"]
2 seconds
["1", "6"]
NoteThe first example: aa $$$+$$$ bb $$$\to$$$ abba. The second example: aab $$$+$$$ abcac $$$=$$$ aababcac $$$\to$$$ aabccbaa aab $$$+$$$ aa $$$=$$$ aabaa abcac $$$+$$$ aa $$$=$$$ abcacaa $$$\to$$$ aacbcaa dffe $$$+$$$ ed $$$=$$$ dffeed $$$\to$$$ fdeedf dffe $$$+$$$ aade $$$=$$$ dffeaade $$$\to$$$ adfaafde ed $$$+$$$ aade $$$=$$$ edaade $$$\to$$$ aeddea
Java 8
standard input
[ "hashing", "strings" ]
2475df43379ffd450fa661927ae3b734
The first line contains a positive integer $$$N$$$ ($$$1 \le N \le 100\,000$$$), representing the length of the input array. Eacg of the next $$$N$$$ lines contains a string (consisting of lowercase English letters from 'a' to 'z') — an element of the input array. The total number of characters in the input array will be less than $$$1\,000\,000$$$.
1,600
Output one number, representing how many palindrome pairs there are in the array.
standard output
PASSED
f00bad21dc29b989a5f94e0405c88b37
train_003.jsonl
1537612500
After learning a lot about space exploration, a little girl named Ana wants to change the subject.Ana is a girl who loves palindromes (string that can be read the same backwards as forward). She has learned how to check for a given string whether it's a palindrome or not, but soon she grew tired of this problem, so she came up with a more interesting one and she needs your help to solve it:You are given an array of strings which consist of only small letters of the alphabet. Your task is to find how many palindrome pairs are there in the array. A palindrome pair is a pair of strings such that the following condition holds: at least one permutation of the concatenation of the two strings is a palindrome. In other words, if you have two strings, let's say "aab" and "abcac", and you concatenate them into "aababcac", we have to check if there exists a permutation of this new string such that it is a palindrome (in this case there exists the permutation "aabccbaa"). Two pairs are considered different if the strings are located on different indices. The pair of strings with indices $$$(i,j)$$$ is considered the same as the pair $$$(j,i)$$$.
256 megabytes
import java.io.*; import java.util.*; public class i { public static void main(String[] args) { new i(); } i() { FastScanner fs = new FastScanner(); int n = fs.nextInt(); String[] a = new String[n]; for(int i = 0; i < n; i++) { a[i] = fs.next(); } HashMap<Integer, Integer> map = new HashMap<>(); long res = 0; for(int i = 0; i < n; i++) { int myMask = 0; int[] freq = new int[26]; for(int j = 0; j < a[i].length(); j++) { int idx = a[i].charAt(j) - 'a'; freq[idx] ^= 1; } for(int j = 0; j < 26; j++) if(freq[j] > 0) { myMask |= 1 << j; } //even if(map.containsKey(myMask)) { res += map.get(myMask); } //odd for(int ignore = 0; ignore < 26; ignore++) { int newMask = myMask ^ (1 << ignore); if(map.containsKey(newMask)) { res += map.get(newMask); } } if(!map.containsKey(myMask)) map.put(myMask, 0); map.put(myMask, map.get(myMask) + 1); } System.out.println(res); } class FastScanner { BufferedReader br; StringTokenizer st; FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); st = new StringTokenizer(""); } int nextInt() { return Integer.parseInt(next()); } String next() { if(st.hasMoreTokens()) { return st.nextToken(); } else { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) {} return next(); } } } }
Java
["3\naa\nbb\ncd", "6\naab\nabcac\ndffe\ned\naa\naade"]
2 seconds
["1", "6"]
NoteThe first example: aa $$$+$$$ bb $$$\to$$$ abba. The second example: aab $$$+$$$ abcac $$$=$$$ aababcac $$$\to$$$ aabccbaa aab $$$+$$$ aa $$$=$$$ aabaa abcac $$$+$$$ aa $$$=$$$ abcacaa $$$\to$$$ aacbcaa dffe $$$+$$$ ed $$$=$$$ dffeed $$$\to$$$ fdeedf dffe $$$+$$$ aade $$$=$$$ dffeaade $$$\to$$$ adfaafde ed $$$+$$$ aade $$$=$$$ edaade $$$\to$$$ aeddea
Java 8
standard input
[ "hashing", "strings" ]
2475df43379ffd450fa661927ae3b734
The first line contains a positive integer $$$N$$$ ($$$1 \le N \le 100\,000$$$), representing the length of the input array. Eacg of the next $$$N$$$ lines contains a string (consisting of lowercase English letters from 'a' to 'z') — an element of the input array. The total number of characters in the input array will be less than $$$1\,000\,000$$$.
1,600
Output one number, representing how many palindrome pairs there are in the array.
standard output
PASSED
5eb1eef2aaca22d675be8bc5241c50b0
train_003.jsonl
1537612500
After learning a lot about space exploration, a little girl named Ana wants to change the subject.Ana is a girl who loves palindromes (string that can be read the same backwards as forward). She has learned how to check for a given string whether it's a palindrome or not, but soon she grew tired of this problem, so she came up with a more interesting one and she needs your help to solve it:You are given an array of strings which consist of only small letters of the alphabet. Your task is to find how many palindrome pairs are there in the array. A palindrome pair is a pair of strings such that the following condition holds: at least one permutation of the concatenation of the two strings is a palindrome. In other words, if you have two strings, let's say "aab" and "abcac", and you concatenate them into "aababcac", we have to check if there exists a permutation of this new string such that it is a palindrome (in this case there exists the permutation "aabccbaa"). Two pairs are considered different if the strings are located on different indices. The pair of strings with indices $$$(i,j)$$$ is considered the same as the pair $$$(j,i)$$$.
256 megabytes
/* If you want to aim high, aim high Don't let that studying and grades consume you Just live life young ****************************** If I'm the sun, you're the moon Because when I go up, you go down ******************************* */ import java.util.*; import java.io.*; public class x1045I { public static void main(String args[]) throws Exception { //BufferedReader infile = new BufferedReader(new FileReader("cowdate.in")); BufferedReader infile = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(infile.readLine()); int N = Integer.parseInt(st.nextToken()); HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); for(int i=0; i < N; i++) { int mask = genMask(infile.readLine()); if(!map.containsKey(mask)) map.put(mask, 0); map.put(mask, map.get(mask)+1); } long res = 0L; for(int k: map.keySet()) { int v = map.get(k); res += (long)v*(v-1)/2; } //compare long res2 = 0L; for(int mask: map.keySet()) for(int i=0; i < 26; i++) { int submask = mask; if((mask & (1 << i)) == 0) submask += 1 << i; else submask -= 1 << i; if(map.containsKey(submask)) res2 += (long)map.get(mask)*map.get(submask); } res2 /= 2; System.out.println(res+res2); } public static int genMask(String s) { int N = s.length(); char[] arr = new char[26]; for(char c: s.toCharArray()) arr[c-'a']++; int mask = 0; for(int i=0; i < 26; i++) if(arr[i]%2 == 1) mask += (1 << i); return mask; } }
Java
["3\naa\nbb\ncd", "6\naab\nabcac\ndffe\ned\naa\naade"]
2 seconds
["1", "6"]
NoteThe first example: aa $$$+$$$ bb $$$\to$$$ abba. The second example: aab $$$+$$$ abcac $$$=$$$ aababcac $$$\to$$$ aabccbaa aab $$$+$$$ aa $$$=$$$ aabaa abcac $$$+$$$ aa $$$=$$$ abcacaa $$$\to$$$ aacbcaa dffe $$$+$$$ ed $$$=$$$ dffeed $$$\to$$$ fdeedf dffe $$$+$$$ aade $$$=$$$ dffeaade $$$\to$$$ adfaafde ed $$$+$$$ aade $$$=$$$ edaade $$$\to$$$ aeddea
Java 8
standard input
[ "hashing", "strings" ]
2475df43379ffd450fa661927ae3b734
The first line contains a positive integer $$$N$$$ ($$$1 \le N \le 100\,000$$$), representing the length of the input array. Eacg of the next $$$N$$$ lines contains a string (consisting of lowercase English letters from 'a' to 'z') — an element of the input array. The total number of characters in the input array will be less than $$$1\,000\,000$$$.
1,600
Output one number, representing how many palindrome pairs there are in the array.
standard output
PASSED
446cf0620698a6d8b8b660b2d40e8ba6
train_003.jsonl
1537612500
After learning a lot about space exploration, a little girl named Ana wants to change the subject.Ana is a girl who loves palindromes (string that can be read the same backwards as forward). She has learned how to check for a given string whether it's a palindrome or not, but soon she grew tired of this problem, so she came up with a more interesting one and she needs your help to solve it:You are given an array of strings which consist of only small letters of the alphabet. Your task is to find how many palindrome pairs are there in the array. A palindrome pair is a pair of strings such that the following condition holds: at least one permutation of the concatenation of the two strings is a palindrome. In other words, if you have two strings, let's say "aab" and "abcac", and you concatenate them into "aababcac", we have to check if there exists a permutation of this new string such that it is a palindrome (in this case there exists the permutation "aabccbaa"). Two pairs are considered different if the strings are located on different indices. The pair of strings with indices $$$(i,j)$$$ is considered the same as the pair $$$(j,i)$$$.
256 megabytes
import java.io.*; import java.util.HashMap; import java.util.Map; import java.util.StringTokenizer; /** * Created by Katushka on 05.02.2020. */ public class PalindromPairs { public static void main(String[] args) throws FileNotFoundException { InputReader in = new InputReader(System.in); PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); int n = in.nextInt(); Map<String, Integer> all = new HashMap<>(); for (int i = 0; i < n; i++) { String s = in.nextString(); int[] letters = new int[26]; for (int j = 0; j < s.length(); j++) { char ch = s.charAt(j); letters[ch - 'a']++; } StringBuilder str = new StringBuilder(); for (int letter : letters) { if (letter % 2 == 0) { str.append('0'); } else { str.append('1'); } } String s1 = str.toString(); if (all.containsKey(s1)) { all.put(s1, all.get(s1) + 1); } else { all.put(s1, 1); } } long count = 0; for (String s : all.keySet()) { for (int i = 0; i < 26; i++) { StringBuilder str = new StringBuilder(); for (int j = 0; j < s.length(); j++) { if (i == j) { if (s.charAt(j) == '0') { str.append('1'); } else { str.append('0'); } } else { str.append(s.charAt(j)); } } String s1 = str.toString(); if (all.containsKey(s1)) { count += ((long) all.get(s1)) * all.get(s); } } count += ((long) all.get(s)) * (all.get(s) - 1); } System.out.println(count / 2); out.close(); } private static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public String nextString() { try { return reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public char nextChar() { return next().charAt(0); } } }
Java
["3\naa\nbb\ncd", "6\naab\nabcac\ndffe\ned\naa\naade"]
2 seconds
["1", "6"]
NoteThe first example: aa $$$+$$$ bb $$$\to$$$ abba. The second example: aab $$$+$$$ abcac $$$=$$$ aababcac $$$\to$$$ aabccbaa aab $$$+$$$ aa $$$=$$$ aabaa abcac $$$+$$$ aa $$$=$$$ abcacaa $$$\to$$$ aacbcaa dffe $$$+$$$ ed $$$=$$$ dffeed $$$\to$$$ fdeedf dffe $$$+$$$ aade $$$=$$$ dffeaade $$$\to$$$ adfaafde ed $$$+$$$ aade $$$=$$$ edaade $$$\to$$$ aeddea
Java 8
standard input
[ "hashing", "strings" ]
2475df43379ffd450fa661927ae3b734
The first line contains a positive integer $$$N$$$ ($$$1 \le N \le 100\,000$$$), representing the length of the input array. Eacg of the next $$$N$$$ lines contains a string (consisting of lowercase English letters from 'a' to 'z') — an element of the input array. The total number of characters in the input array will be less than $$$1\,000\,000$$$.
1,600
Output one number, representing how many palindrome pairs there are in the array.
standard output
PASSED
c4446bf9bcff762a935af5c70896fbd1
train_003.jsonl
1537612500
After learning a lot about space exploration, a little girl named Ana wants to change the subject.Ana is a girl who loves palindromes (string that can be read the same backwards as forward). She has learned how to check for a given string whether it's a palindrome or not, but soon she grew tired of this problem, so she came up with a more interesting one and she needs your help to solve it:You are given an array of strings which consist of only small letters of the alphabet. Your task is to find how many palindrome pairs are there in the array. A palindrome pair is a pair of strings such that the following condition holds: at least one permutation of the concatenation of the two strings is a palindrome. In other words, if you have two strings, let's say "aab" and "abcac", and you concatenate them into "aababcac", we have to check if there exists a permutation of this new string such that it is a palindrome (in this case there exists the permutation "aabccbaa"). Two pairs are considered different if the strings are located on different indices. The pair of strings with indices $$$(i,j)$$$ is considered the same as the pair $$$(j,i)$$$.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.HashMap; import java.util.Scanner; import java.util.StringTokenizer; 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) { FastReader s=new FastReader(); int n=s.nextInt(); String[] arr=new String[n]; for(int i=0;i<n;i++) { arr[i]=s.next(); } String[] brr=new String[n]; for(int i=0;i<n;i++) { int[] count=new int[26]; for(int j=0;j<arr[i].length();j++) { count[arr[i].charAt(j)-'a']++; } StringBuilder sb=new StringBuilder(); for(int j=0;j<26;j++) { if(count[j]%2!=0) { sb.append((char)('a'+j)); } } brr[i]=sb.toString(); } Arrays.sort(brr); long ans=0; HashMap<String,Long> map=new HashMap<>(); for(int i=0;i<n;i++) { if(map.containsKey(brr[i])) { ans=ans+map.get(brr[i]); } for(int j=0;j<brr[i].length();j++) { StringBuilder temp=new StringBuilder(); for(int k=0;k<brr[i].length();k++) { if(j!=k) { temp.append(brr[i].charAt(k)); } } String check=temp.toString(); if(map.containsKey(check)) { ans=ans+map.get(check); } } int[] count=new int[26]; for(int j=0;j<brr[i].length();j++) { count[brr[i].charAt(j)-'a']++; } for(int j=0;j<26;j++) { if(count[j]==0) { StringBuilder temp=new StringBuilder(); for(int k=0;k<26;k++) { if(count[k]>0||k==j) { temp.append((char)(k+'a')); } } String check=temp.toString(); if(map.containsKey(check)) { ans=ans+map.get(check); } } } if(map.containsKey(brr[i])) { map.put(brr[i],map.get(brr[i])+1); } else { map.put(brr[i],1l); } } System.out.println(ans); } }
Java
["3\naa\nbb\ncd", "6\naab\nabcac\ndffe\ned\naa\naade"]
2 seconds
["1", "6"]
NoteThe first example: aa $$$+$$$ bb $$$\to$$$ abba. The second example: aab $$$+$$$ abcac $$$=$$$ aababcac $$$\to$$$ aabccbaa aab $$$+$$$ aa $$$=$$$ aabaa abcac $$$+$$$ aa $$$=$$$ abcacaa $$$\to$$$ aacbcaa dffe $$$+$$$ ed $$$=$$$ dffeed $$$\to$$$ fdeedf dffe $$$+$$$ aade $$$=$$$ dffeaade $$$\to$$$ adfaafde ed $$$+$$$ aade $$$=$$$ edaade $$$\to$$$ aeddea
Java 8
standard input
[ "hashing", "strings" ]
2475df43379ffd450fa661927ae3b734
The first line contains a positive integer $$$N$$$ ($$$1 \le N \le 100\,000$$$), representing the length of the input array. Eacg of the next $$$N$$$ lines contains a string (consisting of lowercase English letters from 'a' to 'z') — an element of the input array. The total number of characters in the input array will be less than $$$1\,000\,000$$$.
1,600
Output one number, representing how many palindrome pairs there are in the array.
standard output
PASSED
aa7f1b6525f2af891b124b5364ead8b7
train_003.jsonl
1537612500
After learning a lot about space exploration, a little girl named Ana wants to change the subject.Ana is a girl who loves palindromes (string that can be read the same backwards as forward). She has learned how to check for a given string whether it's a palindrome or not, but soon she grew tired of this problem, so she came up with a more interesting one and she needs your help to solve it:You are given an array of strings which consist of only small letters of the alphabet. Your task is to find how many palindrome pairs are there in the array. A palindrome pair is a pair of strings such that the following condition holds: at least one permutation of the concatenation of the two strings is a palindrome. In other words, if you have two strings, let's say "aab" and "abcac", and you concatenate them into "aababcac", we have to check if there exists a permutation of this new string such that it is a palindrome (in this case there exists the permutation "aabccbaa"). Two pairs are considered different if the strings are located on different indices. The pair of strings with indices $$$(i,j)$$$ is considered the same as the pair $$$(j,i)$$$.
256 megabytes
import java.io.*; import java.util.*; public class sonuu{ public static void main(String[] args){ FastReader sc=new FastReader (); PrintWriter out = new PrintWriter(System.out); int n = sc.nextInt(); String str[] = new String[n]; for(int i=0;i<n;i++) str[i] = sc.next(); HashMap<Integer,Integer> hm = new HashMap<Integer,Integer>(); int a[] = new int[n]; for(int i=0;i<n;i++){ int c[] = new int[26]; for(int j=0;j<str[i].length();j++) c[str[i].charAt(j)-'a']=(c[str[i].charAt(j)-'a']+1)%2; int num=0; for(int i1=0;i1<26;i1++) if(c[i1]==1) num=num+(1<<i1); a[i]=num; if(hm.containsKey(num)) hm.put(num,hm.get(num)+1); else hm.put(num,1); } long ans=0; for(int i=0;i<n;i++){ ans=ans+hm.get(a[i])-1; for(int j=0;j<26;j++){ int num = (a[i]^(1<<j)); if(hm.containsKey(num)) ans = ans+hm.get(num); } } ans=ans/2; out.println(ans); out.flush(); } 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\naa\nbb\ncd", "6\naab\nabcac\ndffe\ned\naa\naade"]
2 seconds
["1", "6"]
NoteThe first example: aa $$$+$$$ bb $$$\to$$$ abba. The second example: aab $$$+$$$ abcac $$$=$$$ aababcac $$$\to$$$ aabccbaa aab $$$+$$$ aa $$$=$$$ aabaa abcac $$$+$$$ aa $$$=$$$ abcacaa $$$\to$$$ aacbcaa dffe $$$+$$$ ed $$$=$$$ dffeed $$$\to$$$ fdeedf dffe $$$+$$$ aade $$$=$$$ dffeaade $$$\to$$$ adfaafde ed $$$+$$$ aade $$$=$$$ edaade $$$\to$$$ aeddea
Java 8
standard input
[ "hashing", "strings" ]
2475df43379ffd450fa661927ae3b734
The first line contains a positive integer $$$N$$$ ($$$1 \le N \le 100\,000$$$), representing the length of the input array. Eacg of the next $$$N$$$ lines contains a string (consisting of lowercase English letters from 'a' to 'z') — an element of the input array. The total number of characters in the input array will be less than $$$1\,000\,000$$$.
1,600
Output one number, representing how many palindrome pairs there are in the array.
standard output
PASSED
f761d0209be1a05271212a94b8da34e2
train_003.jsonl
1537612500
After learning a lot about space exploration, a little girl named Ana wants to change the subject.Ana is a girl who loves palindromes (string that can be read the same backwards as forward). She has learned how to check for a given string whether it's a palindrome or not, but soon she grew tired of this problem, so she came up with a more interesting one and she needs your help to solve it:You are given an array of strings which consist of only small letters of the alphabet. Your task is to find how many palindrome pairs are there in the array. A palindrome pair is a pair of strings such that the following condition holds: at least one permutation of the concatenation of the two strings is a palindrome. In other words, if you have two strings, let's say "aab" and "abcac", and you concatenate them into "aababcac", we have to check if there exists a permutation of this new string such that it is a palindrome (in this case there exists the permutation "aabccbaa"). Two pairs are considered different if the strings are located on different indices. The pair of strings with indices $$$(i,j)$$$ is considered the same as the pair $$$(j,i)$$$.
256 megabytes
import java.io.*; import java.util.*; public class I_PalindromePairs { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader inp = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); Solver solver = new Solver(); solver.solve(inp, out); out.close(); } private static class Solver { private void solve(InputReader inp, PrintWriter out) { int n = inp.nextInt(); HashMap<Integer, Integer> cnt = new HashMap<>(); for (int i = 0; i < n; i++) { char[] bits = new char[26]; char[] s = inp.next().toCharArray(); for (char c: s) bits[c - 'a']++; int mask = 0; for (int j = 0; j < 26; j++) { if (bits[j] % 2 == 1) { mask |= (1 << j); } } cnt.put(mask, cnt.getOrDefault(mask, 0) + 1); } long res = 0; for (int mask: cnt.keySet()) { long total = cnt.get(mask); res += total * (total - 1); for (int i = 0; i < 26; i++) { res += total * cnt.getOrDefault(mask ^ (1 << i), 0); } } out.print(res >> 1); } } static class InputReader { BufferedReader reader; StringTokenizer tokenizer; InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } } }
Java
["3\naa\nbb\ncd", "6\naab\nabcac\ndffe\ned\naa\naade"]
2 seconds
["1", "6"]
NoteThe first example: aa $$$+$$$ bb $$$\to$$$ abba. The second example: aab $$$+$$$ abcac $$$=$$$ aababcac $$$\to$$$ aabccbaa aab $$$+$$$ aa $$$=$$$ aabaa abcac $$$+$$$ aa $$$=$$$ abcacaa $$$\to$$$ aacbcaa dffe $$$+$$$ ed $$$=$$$ dffeed $$$\to$$$ fdeedf dffe $$$+$$$ aade $$$=$$$ dffeaade $$$\to$$$ adfaafde ed $$$+$$$ aade $$$=$$$ edaade $$$\to$$$ aeddea
Java 8
standard input
[ "hashing", "strings" ]
2475df43379ffd450fa661927ae3b734
The first line contains a positive integer $$$N$$$ ($$$1 \le N \le 100\,000$$$), representing the length of the input array. Eacg of the next $$$N$$$ lines contains a string (consisting of lowercase English letters from 'a' to 'z') — an element of the input array. The total number of characters in the input array will be less than $$$1\,000\,000$$$.
1,600
Output one number, representing how many palindrome pairs there are in the array.
standard output
PASSED
6486d0b097a5cf388a78ddeaaa9582fa
train_003.jsonl
1537612500
After learning a lot about space exploration, a little girl named Ana wants to change the subject.Ana is a girl who loves palindromes (string that can be read the same backwards as forward). She has learned how to check for a given string whether it's a palindrome or not, but soon she grew tired of this problem, so she came up with a more interesting one and she needs your help to solve it:You are given an array of strings which consist of only small letters of the alphabet. Your task is to find how many palindrome pairs are there in the array. A palindrome pair is a pair of strings such that the following condition holds: at least one permutation of the concatenation of the two strings is a palindrome. In other words, if you have two strings, let's say "aab" and "abcac", and you concatenate them into "aababcac", we have to check if there exists a permutation of this new string such that it is a palindrome (in this case there exists the permutation "aabccbaa"). Two pairs are considered different if the strings are located on different indices. The pair of strings with indices $$$(i,j)$$$ is considered the same as the pair $$$(j,i)$$$.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.OutputStream; import java.util.Map; import java.io.Writer; import java.util.HashMap; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author palayutm */ 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); TaskI solver = new TaskI(); solver.solve(1, in, out); out.close(); } static class TaskI { public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.nextInt(); Map<Integer, Integer> map = new HashMap<>(); long ans = 0; for (int i = 0; i < n; i++) { char[] s = in.next().toCharArray(); int x = 0; for (char c : s) { x ^= (1 << (c - 'a')); } ans += map.getOrDefault(x, 0); for (int j = 0; j < 26; j++) { ans += map.getOrDefault(x ^ (1 << j), 0); } map.put(x, map.getOrDefault(x, 0) + 1); } out.println(ans); } } static class InputReader { private InputStream stream; private byte[] inbuf = new byte[1024]; private int lenbuf = 0; private int ptrbuf = 0; public InputReader(InputStream stream) { this.stream = stream; } private int readByte() { if (lenbuf == -1) throw new UnknownError(); if (ptrbuf >= lenbuf) { ptrbuf = 0; try { lenbuf = stream.read(inbuf); } catch (IOException e) { throw new UnknownError(); } 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; } public String next() { int b = skip(); StringBuilder sb = new StringBuilder(); while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } public int nextInt() { 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(); } } } static class OutputWriter extends PrintWriter { public OutputWriter(OutputStream out) { super(out); } public OutputWriter(Writer out) { super(out); } public void close() { super.close(); } } }
Java
["3\naa\nbb\ncd", "6\naab\nabcac\ndffe\ned\naa\naade"]
2 seconds
["1", "6"]
NoteThe first example: aa $$$+$$$ bb $$$\to$$$ abba. The second example: aab $$$+$$$ abcac $$$=$$$ aababcac $$$\to$$$ aabccbaa aab $$$+$$$ aa $$$=$$$ aabaa abcac $$$+$$$ aa $$$=$$$ abcacaa $$$\to$$$ aacbcaa dffe $$$+$$$ ed $$$=$$$ dffeed $$$\to$$$ fdeedf dffe $$$+$$$ aade $$$=$$$ dffeaade $$$\to$$$ adfaafde ed $$$+$$$ aade $$$=$$$ edaade $$$\to$$$ aeddea
Java 8
standard input
[ "hashing", "strings" ]
2475df43379ffd450fa661927ae3b734
The first line contains a positive integer $$$N$$$ ($$$1 \le N \le 100\,000$$$), representing the length of the input array. Eacg of the next $$$N$$$ lines contains a string (consisting of lowercase English letters from 'a' to 'z') — an element of the input array. The total number of characters in the input array will be less than $$$1\,000\,000$$$.
1,600
Output one number, representing how many palindrome pairs there are in the array.
standard output
PASSED
c4975640835891f3a8caf9c5f2409db6
train_003.jsonl
1537612500
After learning a lot about space exploration, a little girl named Ana wants to change the subject.Ana is a girl who loves palindromes (string that can be read the same backwards as forward). She has learned how to check for a given string whether it's a palindrome or not, but soon she grew tired of this problem, so she came up with a more interesting one and she needs your help to solve it:You are given an array of strings which consist of only small letters of the alphabet. Your task is to find how many palindrome pairs are there in the array. A palindrome pair is a pair of strings such that the following condition holds: at least one permutation of the concatenation of the two strings is a palindrome. In other words, if you have two strings, let's say "aab" and "abcac", and you concatenate them into "aababcac", we have to check if there exists a permutation of this new string such that it is a palindrome (in this case there exists the permutation "aabccbaa"). Two pairs are considered different if the strings are located on different indices. The pair of strings with indices $$$(i,j)$$$ is considered the same as the pair $$$(j,i)$$$.
256 megabytes
import java.util.*; import java.io.*; public class Main { public static void main(String args[]) {new Main().run();} FastReader in = new FastReader(); PrintWriter out = new PrintWriter(System.out); void run(){ work(); out.flush(); } long mod=1000000007; long gcd(long a,long b) { return b==0?a:gcd(b,a%b); } void work() { int n=in.nextInt(); HashMap<Integer,Integer> map=new HashMap<>(); long ret=0; for(int i=0;i<n;i++) { String str=in.next(); int k=0; for(int j=0;j<str.length();j++) { int b=str.charAt(j)-'a'; k=k^(1<<b); } if(map.get(k)==null) { map.put(k,1); }else { ret+=map.get(k); map.put(k,map.get(k)+1); } for(int j=0;j<26;j++) { if((k&(1<<j))==0) { int k1=(k|(1<<j)); if(map.get(k1)!=null) { ret+=map.get(k1); } } if((k&(1<<j))>0) { int k1=(k-(1<<j)); if(map.get(k1)!=null) { ret+=map.get(k1); } } } } out.println(ret); } } class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br=new BufferedReader(new InputStreamReader(System.in)); } public String next() { if(st==null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } }
Java
["3\naa\nbb\ncd", "6\naab\nabcac\ndffe\ned\naa\naade"]
2 seconds
["1", "6"]
NoteThe first example: aa $$$+$$$ bb $$$\to$$$ abba. The second example: aab $$$+$$$ abcac $$$=$$$ aababcac $$$\to$$$ aabccbaa aab $$$+$$$ aa $$$=$$$ aabaa abcac $$$+$$$ aa $$$=$$$ abcacaa $$$\to$$$ aacbcaa dffe $$$+$$$ ed $$$=$$$ dffeed $$$\to$$$ fdeedf dffe $$$+$$$ aade $$$=$$$ dffeaade $$$\to$$$ adfaafde ed $$$+$$$ aade $$$=$$$ edaade $$$\to$$$ aeddea
Java 8
standard input
[ "hashing", "strings" ]
2475df43379ffd450fa661927ae3b734
The first line contains a positive integer $$$N$$$ ($$$1 \le N \le 100\,000$$$), representing the length of the input array. Eacg of the next $$$N$$$ lines contains a string (consisting of lowercase English letters from 'a' to 'z') — an element of the input array. The total number of characters in the input array will be less than $$$1\,000\,000$$$.
1,600
Output one number, representing how many palindrome pairs there are in the array.
standard output
PASSED
a6886cc793585aff17051cf91b09e550
train_003.jsonl
1537612500
After learning a lot about space exploration, a little girl named Ana wants to change the subject.Ana is a girl who loves palindromes (string that can be read the same backwards as forward). She has learned how to check for a given string whether it's a palindrome or not, but soon she grew tired of this problem, so she came up with a more interesting one and she needs your help to solve it:You are given an array of strings which consist of only small letters of the alphabet. Your task is to find how many palindrome pairs are there in the array. A palindrome pair is a pair of strings such that the following condition holds: at least one permutation of the concatenation of the two strings is a palindrome. In other words, if you have two strings, let's say "aab" and "abcac", and you concatenate them into "aababcac", we have to check if there exists a permutation of this new string such that it is a palindrome (in this case there exists the permutation "aabccbaa"). Two pairs are considered different if the strings are located on different indices. The pair of strings with indices $$$(i,j)$$$ is considered the same as the pair $$$(j,i)$$$.
256 megabytes
import java.io.*; import java.util.*; public class Main2 { static BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); static StringTokenizer st; static String ns() { while(st==null||(!st.hasMoreTokens())) { try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return st.nextToken(); } static int ni() { return Integer.parseInt(ns()); } public static void main(String[]args) throws Exception { int n=ni(); String[]a=new String[n]; int[]nums=new int[n]; Map<Integer,Integer> hola=new HashMap<Integer,Integer>(); for(int i=0; i<n; i++) { a[i]=ns(); for(int j=0; j<a[i].length(); j++) nums[i]^=(1<<(a[i].charAt(j)-'a')); hola.put(nums[i], hola.getOrDefault(nums[i],0)+1); } long ans=0; for(int i:hola.keySet()) { long val=hola.get(i); ans+=((val)*(val-1)); for(int j=0; j<26; j++) ans+=val*hola.getOrDefault(i^(1<<j),0); } System.out.println(ans/2); } }
Java
["3\naa\nbb\ncd", "6\naab\nabcac\ndffe\ned\naa\naade"]
2 seconds
["1", "6"]
NoteThe first example: aa $$$+$$$ bb $$$\to$$$ abba. The second example: aab $$$+$$$ abcac $$$=$$$ aababcac $$$\to$$$ aabccbaa aab $$$+$$$ aa $$$=$$$ aabaa abcac $$$+$$$ aa $$$=$$$ abcacaa $$$\to$$$ aacbcaa dffe $$$+$$$ ed $$$=$$$ dffeed $$$\to$$$ fdeedf dffe $$$+$$$ aade $$$=$$$ dffeaade $$$\to$$$ adfaafde ed $$$+$$$ aade $$$=$$$ edaade $$$\to$$$ aeddea
Java 8
standard input
[ "hashing", "strings" ]
2475df43379ffd450fa661927ae3b734
The first line contains a positive integer $$$N$$$ ($$$1 \le N \le 100\,000$$$), representing the length of the input array. Eacg of the next $$$N$$$ lines contains a string (consisting of lowercase English letters from 'a' to 'z') — an element of the input array. The total number of characters in the input array will be less than $$$1\,000\,000$$$.
1,600
Output one number, representing how many palindrome pairs there are in the array.
standard output
PASSED
e66fb231594b138b0d47cede6a1b7f75
train_003.jsonl
1356622500
A recently found Ancient Prophesy is believed to contain the exact Apocalypse date. The prophesy is a string that only consists of digits and characters "-".We'll say that some date is mentioned in the Prophesy if there is a substring in the Prophesy that is the date's record in the format "dd-mm-yyyy". We'll say that the number of the date's occurrences is the number of such substrings in the Prophesy. For example, the Prophesy "0012-10-2012-10-2012" mentions date 12-10-2012 twice (first time as "0012-10-2012-10-2012", second time as "0012-10-2012-10-2012").The date of the Apocalypse is such correct date that the number of times it is mentioned in the Prophesy is strictly larger than that of any other correct date.A date is correct if the year lies in the range from 2013 to 2015, the month is from 1 to 12, and the number of the day is strictly more than a zero and doesn't exceed the number of days in the current month. Note that a date is written in the format "dd-mm-yyyy", that means that leading zeroes may be added to the numbers of the months or days if needed. In other words, date "1-1-2013" isn't recorded in the format "dd-mm-yyyy", and date "01-01-2013" is recorded in it.Notice, that any year between 2013 and 2015 is not a leap year.
256 megabytes
import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * * @author gargon */ public class JavaApplication41 { /** * @param args the command line arguments */ public static void main(String[] args) { Scanner sc = new Scanner(System.in); String str = sc.next(); Pattern p = Pattern.compile("(\\d\\d)-(\\d\\d)-(\\d\\d\\d\\d)"); Map dates = new HashMap(); int[] md = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; for (int i = 0; i < str.length() - 9; i++) { String date = str.substring(i, i + 10); Matcher matcher = p.matcher(date); while (matcher.find()) { int d = Integer.parseInt(matcher.group(1)); int m = Integer.parseInt(matcher.group(2)); int y = Integer.parseInt(matcher.group(3)); if (y >= 2013 && y <= 2015) { if (m > 0 && m <= 12) { if (d > 0 && d <= md[m-1]) { int num = 0; if (dates.containsKey(date)) { num = (int) dates.get(date); } dates.put(date, ++num); } } } } } int max = 0; String result = null; Iterator it = dates.entrySet().iterator(); while (it.hasNext()) { Map.Entry pairs = (Map.Entry) it.next(); if ((int) pairs.getValue() > max) { max = (int) pairs.getValue(); result = (String) pairs.getKey(); } } System.out.println(result); } }
Java
["777-444---21-12-2013-12-2013-12-2013---444-777"]
1 second
["13-12-2013"]
null
Java 7
standard input
[ "implementation", "brute force", "strings" ]
dd7fd84f7915ad57b0e21f416e2a3ea0
The first line contains the Prophesy: a non-empty string that only consists of digits and characters "-". The length of the Prophesy doesn't exceed 105 characters.
1,600
In a single line print the date of the Apocalypse. It is guaranteed that such date exists and is unique.
standard output
PASSED
f2417deae38e51805bdeadc581b95b85
train_003.jsonl
1356622500
A recently found Ancient Prophesy is believed to contain the exact Apocalypse date. The prophesy is a string that only consists of digits and characters "-".We'll say that some date is mentioned in the Prophesy if there is a substring in the Prophesy that is the date's record in the format "dd-mm-yyyy". We'll say that the number of the date's occurrences is the number of such substrings in the Prophesy. For example, the Prophesy "0012-10-2012-10-2012" mentions date 12-10-2012 twice (first time as "0012-10-2012-10-2012", second time as "0012-10-2012-10-2012").The date of the Apocalypse is such correct date that the number of times it is mentioned in the Prophesy is strictly larger than that of any other correct date.A date is correct if the year lies in the range from 2013 to 2015, the month is from 1 to 12, and the number of the day is strictly more than a zero and doesn't exceed the number of days in the current month. Note that a date is written in the format "dd-mm-yyyy", that means that leading zeroes may be added to the numbers of the months or days if needed. In other words, date "1-1-2013" isn't recorded in the format "dd-mm-yyyy", and date "01-01-2013" is recorded in it.Notice, that any year between 2013 and 2015 is not a leap year.
256 megabytes
import java.io.*; import java.util.*; import static java.lang.Math.*; public class Main { private IO io; private int ioMode = -1; private String problemName = ""; private final String mjArgument = "master_j"; public static void main(String programArguments[]) throws IOException{ if(programArguments != null && programArguments.length > 0) new Main().run(programArguments[0]); else new Main().run(null); } private void run(String programArgument) throws IOException { // _______________________________________________ _________ // | Input Mode | Output Mode | mode | comment | // |------------------|---------------------|----- |---------| // | input.txt | System.out | 0 | mj | // | System.in | System.out | 1 | T / CF | // |<problemName>.in | <problemName>.out | 2 | | // | input.txt | output.txt | 3 | C | // |__________________|_____________________|______|_________| long nanoTime = 0; if(programArgument != null && programArgument.equals(mjArgument)) // mj ioMode = 0; else if(System.getProperty("ONLINE_JUDGE") != null) // T / CF ioMode = 1; else ioMode = 2; switch(ioMode){ case -1: try{ throw new Exception("<ioMode> init failure") ; }catch (Exception e){ e.printStackTrace(); } return; case 0: break; case 1: break; case 2: if(problemName.length() == 0){ try{ throw new Exception("<problemName> init failure"); }catch (Exception e){ e.printStackTrace(); } return; } case 3: break; } io = new IO(ioMode, problemName); if(ioMode == 0){ System.out.println("File output : \n<start>"); System.out.flush(); nanoTime = System.nanoTime(); } solve(); io.flush(); if(ioMode == 0){ System.out.println("</start>"); long t = System.nanoTime() - nanoTime; int d3 = 1000000000, d2 = 1000000, d1 = 1000000; if(t>=d3) System.out.println(t/d3 + "." + t%d3 + " seconds"); else if(t>=d2) System.out.println(t/d2 + "." + t%d2 + " millis"); else if(t>=d1) System.out.println(t/d1 + "." + t%d1 + " millis"); System.out.flush(); } } private void solve() throws IOException { int mnth[] = new int[]{0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; int mnth2[] = new int[mnth.length]; mnth2[0] = mnth[0]; for(int i = 1; i < 12; i++) mnth2[i] = mnth[i] + mnth2[i - 1]; int freq[] = new int[1095], p; int t[] = new int[10]; for(int i = 0; i < t.length; i++){ t[i] = (char)io.br.read() - '0'; } //while((p = io.br.read()) != -1){ do{ if(f(t[0]) && f(t[1]) && !f(t[2]) && f(t[3]) && f(t[4]) && !f(t[5]) && f(t[6]) && f(t[7]) && f(t[8]) && f(t[9])){ int dd = 10*t[0] + t[1], mm = 10*t[3] + t[4], yy = 1000*t[6] + 100*t[7] + 10*t[8] + t[9]; if(2013 <= yy && yy <= 2015 && 1 <= mm && mm <= 12 && 1 <= dd && dd <= 31 && dd <= mnth[mm]) //freq[365*(yy-2013) + mnth[dd-1]*(mm-1) + dd-1]++; freq[365*(yy - 2013) + mnth2[mm - 1] + dd - 1]++; } for(int i = 1; i < t.length; i++) t[i - 1] = t[i]; p = io.br.read(); t[t.length - 1] = p - '0'; }while(p != -1); // t[t.length - 1] = p - '0'; //} int max = -1; for(int i = 0; i < freq.length; i++) max = max(max, freq[i]); for(int mm = 0; mm < 12; mm++) for(int dd = 0; dd < mnth[mm + 1]; dd++) for(int yy = 0; yy < 3; yy++) if(freq[yy*365 + mnth2[mm] + dd] == max){ dd++; mm++; yy += 2013; io.w(dd/10 > 0 ? dd : "0" + dd); io.w('-'); io.w(mm/10 > 0 ? mm : "0" + mm); io.w('-'); io.w(yy); io.wln(); return; } io.wln(-1); }//2.2250738585072012e-308 boolean f(int a){ return 0<=a && a<=9; } /** * Input-output class * @author master_j * @version 0.2.4 */ @SuppressWarnings("unused") private class IO{ private boolean alwaysFlush; StreamTokenizer in; PrintWriter out; BufferedReader br; Reader reader; Writer writer; public IO(int ioMode, String problemName) throws IOException{ Locale.setDefault(Locale.US); // _______________________________________________ _________ // | Input Mode | Output Mode | mode | comment | // |------------------|---------------------|----- |---------| // | input.txt | System.out | 0 | mj | // | System.in | System.out | 1 | T / CF | // |<problemName>.in | <problemName>.out | 2 | | // | input.txt | output.txt | 3 | C | // |__________________|_____________________|______|_________| switch(ioMode){ case 0: reader = new FileReader("input.txt"); writer = new OutputStreamWriter(System.out); break; case 1: reader = new InputStreamReader(System.in); writer = new OutputStreamWriter(System.out); break; case 2: reader = new FileReader(problemName + ".in"); writer = new FileWriter(problemName + ".out"); break; case 3: reader = new FileReader("input.txt"); writer = new FileWriter("output.txt"); break; } br = new BufferedReader(reader); in = new StreamTokenizer(br); out = new PrintWriter(writer); alwaysFlush = false; } public void setAlwaysFlush(boolean arg){alwaysFlush = arg;} public void wln(){out.println(); if(alwaysFlush)flush();} public void wln(int arg){out.println(arg); if(alwaysFlush)flush();} public void wln(long arg){out.println(arg); if(alwaysFlush)flush();} public void wln(double arg){out.println(arg); if(alwaysFlush)flush();} public void wln(String arg){out.println(arg); if(alwaysFlush)flush();} public void wln(boolean arg){out.println(arg); if(alwaysFlush)flush();} public void wln(char arg){out.println(arg); if(alwaysFlush)flush();} public void wln(float arg){out.println(arg); if(alwaysFlush)flush();} public void wln(Object arg){out.println(arg); if(alwaysFlush)flush();} public void w(int arg){out.print(arg); if(alwaysFlush)flush();} public void w(long arg){out.print(arg); if(alwaysFlush)flush();} public void w(double arg){out.print(arg); if(alwaysFlush)flush();} public void w(String arg){out.print(arg); if(alwaysFlush)flush();} public void w(boolean arg){out.print(arg); if(alwaysFlush)flush();} public void w(char arg){out.print(arg); if(alwaysFlush)flush();} public void w(float arg){out.print(arg); if(alwaysFlush)flush();} public void w(Object arg){out.print(arg); if(alwaysFlush)flush();} public void wf(String format, Object...args){out.printf(format, args); if(alwaysFlush)flush();} public void flush(){out.flush();} public int nI() throws IOException {in.nextToken(); return(int)in.nval;} public long nL() throws IOException {in.nextToken(); return(long)in.nval;} public String nS() throws IOException {in.nextToken(); return in.sval;} public double nD() throws IOException {in.nextToken(); return in.nval;} public float nF() throws IOException {in.nextToken(); return (float)in.nval;} public char nC() throws IOException {return (char)br.read();} public void wc(char...arg){for(char c : arg){in.ordinaryChar(c);in.wordChars(c, c);}} public void wc(String arg){wc(arg.toCharArray());} public void wc(char arg0, char arg1){in.ordinaryChars(arg0, arg1); in.wordChars(arg0, arg1);} public boolean eof(){return in.ttype == StreamTokenizer.TT_EOF;} public boolean eol(){return in.ttype == StreamTokenizer.TT_EOL;} } }
Java
["777-444---21-12-2013-12-2013-12-2013---444-777"]
1 second
["13-12-2013"]
null
Java 7
standard input
[ "implementation", "brute force", "strings" ]
dd7fd84f7915ad57b0e21f416e2a3ea0
The first line contains the Prophesy: a non-empty string that only consists of digits and characters "-". The length of the Prophesy doesn't exceed 105 characters.
1,600
In a single line print the date of the Apocalypse. It is guaranteed that such date exists and is unique.
standard output
PASSED
119b3a8cc6234a599381348fcdcedaf7
train_003.jsonl
1356622500
A recently found Ancient Prophesy is believed to contain the exact Apocalypse date. The prophesy is a string that only consists of digits and characters "-".We'll say that some date is mentioned in the Prophesy if there is a substring in the Prophesy that is the date's record in the format "dd-mm-yyyy". We'll say that the number of the date's occurrences is the number of such substrings in the Prophesy. For example, the Prophesy "0012-10-2012-10-2012" mentions date 12-10-2012 twice (first time as "0012-10-2012-10-2012", second time as "0012-10-2012-10-2012").The date of the Apocalypse is such correct date that the number of times it is mentioned in the Prophesy is strictly larger than that of any other correct date.A date is correct if the year lies in the range from 2013 to 2015, the month is from 1 to 12, and the number of the day is strictly more than a zero and doesn't exceed the number of days in the current month. Note that a date is written in the format "dd-mm-yyyy", that means that leading zeroes may be added to the numbers of the months or days if needed. In other words, date "1-1-2013" isn't recorded in the format "dd-mm-yyyy", and date "01-01-2013" is recorded in it.Notice, that any year between 2013 and 2015 is not a leap year.
256 megabytes
import java.util.*; public class AncientProphesy { static final int DATE_LEN = 10; // dd-mm-yyyy static final int[] DAYS_PER_MONTH = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; static boolean isValid(String date) { String[] parts = date.split("-"); if (parts.length != 3) return false; if (parts[0].length() != 2 || parts[1].length() != 2 || parts[2].length() != 4) return false; int day = Integer.parseInt(parts[0]); int month = Integer.parseInt(parts[1]); int year = Integer.parseInt(parts[2]); return year >= 2013 && year <= 2015 && month >= 1 && month <= 12 && day > 0 && day <= DAYS_PER_MONTH[month - 1]; } static String solve(String prophesy) { Map<String, Integer> count = new HashMap<String, Integer>(); String apocalypseDate = ""; count.put(apocalypseDate, 0); for (int i = 0; i + DATE_LEN <= prophesy.length(); ++i) { String candidate = prophesy.substring(i, i + DATE_LEN); if (isValid(candidate)) { if (!count.containsKey(candidate)) { count.put(candidate, 0); } count.put(candidate, count.get(candidate) + 1); if (count.get(candidate) > count.get(apocalypseDate)) { apocalypseDate = candidate; } } } return apocalypseDate; } public static void main(String[] args) { Scanner in = new Scanner(System.in); String prophesy = in.next(); System.out.println(solve(prophesy)); in.close(); System.exit(0); } }
Java
["777-444---21-12-2013-12-2013-12-2013---444-777"]
1 second
["13-12-2013"]
null
Java 7
standard input
[ "implementation", "brute force", "strings" ]
dd7fd84f7915ad57b0e21f416e2a3ea0
The first line contains the Prophesy: a non-empty string that only consists of digits and characters "-". The length of the Prophesy doesn't exceed 105 characters.
1,600
In a single line print the date of the Apocalypse. It is guaranteed that such date exists and is unique.
standard output
PASSED
a7dec69ba5da674058ab421c5446f139
train_003.jsonl
1356622500
A recently found Ancient Prophesy is believed to contain the exact Apocalypse date. The prophesy is a string that only consists of digits and characters "-".We'll say that some date is mentioned in the Prophesy if there is a substring in the Prophesy that is the date's record in the format "dd-mm-yyyy". We'll say that the number of the date's occurrences is the number of such substrings in the Prophesy. For example, the Prophesy "0012-10-2012-10-2012" mentions date 12-10-2012 twice (first time as "0012-10-2012-10-2012", second time as "0012-10-2012-10-2012").The date of the Apocalypse is such correct date that the number of times it is mentioned in the Prophesy is strictly larger than that of any other correct date.A date is correct if the year lies in the range from 2013 to 2015, the month is from 1 to 12, and the number of the day is strictly more than a zero and doesn't exceed the number of days in the current month. Note that a date is written in the format "dd-mm-yyyy", that means that leading zeroes may be added to the numbers of the months or days if needed. In other words, date "1-1-2013" isn't recorded in the format "dd-mm-yyyy", and date "01-01-2013" is recorded in it.Notice, that any year between 2013 and 2015 is not a leap year.
256 megabytes
import java.util.Map; import java.io.InputStreamReader; import java.io.IOException; import java.util.HashMap; import java.util.Set; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author c0der */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } } class TaskB { int[] days = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; boolean validText(String s) { for (int i=0; i<s.length(); i++) { if ( i==2 || i==5 ) { if ( s.charAt(i) != '-' ) return false; } else { if ( Character.isDigit( s.charAt(i) ) == false ) return false; } } StringTokenizer st = new StringTokenizer(s, "-"); int d = Integer.parseInt( st.nextToken() ); int m = Integer.parseInt( st.nextToken() ); int y = Integer.parseInt( st.nextToken() ); return y >= 2013 && y <= 2015 && m >= 1 && m <= 12 && d >= 1 && d <= days[ m-1 ]; } public void solve(int testNumber, InputReader in, PrintWriter out) { String str = in.next(); HashMap< String, Integer > mp = new HashMap<String, Integer>(); for (int i=0; i<=str.length()-10; i++) { String s = str.substring( i, i+10 ); if ( validText(s) ) { if ( mp.containsKey( s ) ) mp.put( s, mp.get(s)+1 ); else mp.put( s, 1 ); } } String ans = ""; int count = 0; for (Map.Entry<String, Integer> e : mp.entrySet()) { if ( e.getValue() > count ) { ans = e.getKey(); count = e.getValue(); } } out.println( ans ); } } class InputReader { BufferedReader br; StringTokenizer st; public InputReader(InputStream in) { br = new BufferedReader(new InputStreamReader(in)); st = null; } public String next() { while (st==null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return st.nextToken(); } }
Java
["777-444---21-12-2013-12-2013-12-2013---444-777"]
1 second
["13-12-2013"]
null
Java 7
standard input
[ "implementation", "brute force", "strings" ]
dd7fd84f7915ad57b0e21f416e2a3ea0
The first line contains the Prophesy: a non-empty string that only consists of digits and characters "-". The length of the Prophesy doesn't exceed 105 characters.
1,600
In a single line print the date of the Apocalypse. It is guaranteed that such date exists and is unique.
standard output
PASSED
f5abc9b9d21ad94667be2486aba01a0d
train_003.jsonl
1356622500
A recently found Ancient Prophesy is believed to contain the exact Apocalypse date. The prophesy is a string that only consists of digits and characters "-".We'll say that some date is mentioned in the Prophesy if there is a substring in the Prophesy that is the date's record in the format "dd-mm-yyyy". We'll say that the number of the date's occurrences is the number of such substrings in the Prophesy. For example, the Prophesy "0012-10-2012-10-2012" mentions date 12-10-2012 twice (first time as "0012-10-2012-10-2012", second time as "0012-10-2012-10-2012").The date of the Apocalypse is such correct date that the number of times it is mentioned in the Prophesy is strictly larger than that of any other correct date.A date is correct if the year lies in the range from 2013 to 2015, the month is from 1 to 12, and the number of the day is strictly more than a zero and doesn't exceed the number of days in the current month. Note that a date is written in the format "dd-mm-yyyy", that means that leading zeroes may be added to the numbers of the months or days if needed. In other words, date "1-1-2013" isn't recorded in the format "dd-mm-yyyy", and date "01-01-2013" is recorded in it.Notice, that any year between 2013 and 2015 is not a leap year.
256 megabytes
import java.util.*; public class B{ static final int [] DAYS = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; public static void main(String [] args){ Scanner s = new Scanner(System.in); final String line = s.nextLine(); String res = ""; int count = 0; for (int y = 2013; y <= 2015; ++y){ for (int m = 1; m <= 12; ++m){ for (int d = 1; d <= DAYS[m - 1]; ++d){ final String date = String.format("%02d-%02d-%04d", d, m, y); int c = 0; for (int i = line.indexOf(date, 0); i >= 0; i = line.indexOf(date, i + 1)){ c++; } if (c > count){ count = c; res = date; } } } } System.out.println(res); } }
Java
["777-444---21-12-2013-12-2013-12-2013---444-777"]
1 second
["13-12-2013"]
null
Java 7
standard input
[ "implementation", "brute force", "strings" ]
dd7fd84f7915ad57b0e21f416e2a3ea0
The first line contains the Prophesy: a non-empty string that only consists of digits and characters "-". The length of the Prophesy doesn't exceed 105 characters.
1,600
In a single line print the date of the Apocalypse. It is guaranteed that such date exists and is unique.
standard output
PASSED
1a6dafb17993eaedd7d3d8800fcdaf84
train_003.jsonl
1356622500
A recently found Ancient Prophesy is believed to contain the exact Apocalypse date. The prophesy is a string that only consists of digits and characters "-".We'll say that some date is mentioned in the Prophesy if there is a substring in the Prophesy that is the date's record in the format "dd-mm-yyyy". We'll say that the number of the date's occurrences is the number of such substrings in the Prophesy. For example, the Prophesy "0012-10-2012-10-2012" mentions date 12-10-2012 twice (first time as "0012-10-2012-10-2012", second time as "0012-10-2012-10-2012").The date of the Apocalypse is such correct date that the number of times it is mentioned in the Prophesy is strictly larger than that of any other correct date.A date is correct if the year lies in the range from 2013 to 2015, the month is from 1 to 12, and the number of the day is strictly more than a zero and doesn't exceed the number of days in the current month. Note that a date is written in the format "dd-mm-yyyy", that means that leading zeroes may be added to the numbers of the months or days if needed. In other words, date "1-1-2013" isn't recorded in the format "dd-mm-yyyy", and date "01-01-2013" is recorded in it.Notice, that any year between 2013 and 2015 is not a leap year.
256 megabytes
import java.util.Scanner; public class ElephantChess { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int freq[][][] = new int[31][12][3]; int monthLen[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; String stroka = sc.nextLine(); int maxDay = 0, maxMonth = 0, maxYear = 0, maxFreq = 0; startPoint: for(int i = 0; i + 9 < stroka.length(); i++){ if(stroka.charAt(i + 2) != '-' && stroka.charAt(i + 5) != '=') continue; for(int j = 0; j < 10; j++) if(stroka.charAt(i + j) == '-' && j != 2 && j != 5) continue startPoint; int year = new Integer(stroka.substring(i + 6, i + 10)); if (year < 2013 || year > 2015) continue; int month = new Integer(stroka.substring(i + 3, i + 5)); if (month > 12 || month < 1) continue; int day = new Integer(stroka.substring(i, i + 2)); if(day > monthLen[month - 1] || day < 1) continue; freq[day - 1][month - 1][year - 2013]++; if(maxFreq < freq[day - 1][month - 1][year - 2013]){ maxFreq++; maxDay = day; maxMonth = month; maxYear = year; } } System.out.printf("%d%d-%d%d-%d\n",maxDay / 10 , maxDay % 10, maxMonth /10 , maxMonth % 10, maxYear); } }
Java
["777-444---21-12-2013-12-2013-12-2013---444-777"]
1 second
["13-12-2013"]
null
Java 7
standard input
[ "implementation", "brute force", "strings" ]
dd7fd84f7915ad57b0e21f416e2a3ea0
The first line contains the Prophesy: a non-empty string that only consists of digits and characters "-". The length of the Prophesy doesn't exceed 105 characters.
1,600
In a single line print the date of the Apocalypse. It is guaranteed that such date exists and is unique.
standard output
PASSED
826565f8eef161a1f92f902093b57a98
train_003.jsonl
1356622500
A recently found Ancient Prophesy is believed to contain the exact Apocalypse date. The prophesy is a string that only consists of digits and characters "-".We'll say that some date is mentioned in the Prophesy if there is a substring in the Prophesy that is the date's record in the format "dd-mm-yyyy". We'll say that the number of the date's occurrences is the number of such substrings in the Prophesy. For example, the Prophesy "0012-10-2012-10-2012" mentions date 12-10-2012 twice (first time as "0012-10-2012-10-2012", second time as "0012-10-2012-10-2012").The date of the Apocalypse is such correct date that the number of times it is mentioned in the Prophesy is strictly larger than that of any other correct date.A date is correct if the year lies in the range from 2013 to 2015, the month is from 1 to 12, and the number of the day is strictly more than a zero and doesn't exceed the number of days in the current month. Note that a date is written in the format "dd-mm-yyyy", that means that leading zeroes may be added to the numbers of the months or days if needed. In other words, date "1-1-2013" isn't recorded in the format "dd-mm-yyyy", and date "01-01-2013" is recorded in it.Notice, that any year between 2013 and 2015 is not a leap year.
256 megabytes
import java.util.*; import java.io.*; import java.math.BigInteger; public class Main { Map<Integer, Integer> mp = new HashMap<Integer, Integer>(); int[] days = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; void gao(char[] s, int base) { for (int i = 0; i < 10; ++i) { if (base + i >= s.length) return; if (i == 2 || i == 5) { if (s[i + base] != '-') return; } else if (s[i + base] == '-') return; } int d = (s[0 + base] - '0') * 10 + s[1 + base] - '0'; int m = (s[3 + base] - '0') * 10 + s[4 + base] - '0'; int y = (s[6 + base] - '0') * 1000 + (s[7 + base] - '0') * 100 + (s[8 + base] - '0') * 10 + s[9 + base] - '0'; if (y < 2013 || y > 2015) return; if (m < 1 || m > 12) return; if (d < 1 || d > days[m - 1]) return; int state = y * 10000 + m * 100 + d; Integer num = mp.get(state); if (num == null) num = 0; mp.put(state, num + 1); } void run(int nT) { char[] s = cin.next().toCharArray(); for (int i = 0; i < s.length; ++i) { gao(s, i); } Integer state = null, num = null; for (Map.Entry<Integer, Integer> entry : mp.entrySet()) { Integer s1 = entry.getKey(); Integer s2 = entry.getValue(); //System.out.println(s1 + " " + s2); if (num == null || s2 > num) { state = s1; num = s2; } } int y = state / 10000; state %= 10000; int m = state / 100; state %= 100; int d = state; out.printf("%02d-%02d-%d\n", d, m, y); } public static void main(String[] argv) { Main solved = new Main(); //solved.init(); int T = 1; //T = solved.cin.nextInt(); for (int nT = 1; nT <= T; ++nT) { solved.run(nT); } solved.out.close(); } InputReader cin = new InputReader(System.in); PrintWriter out = new PrintWriter(System.out); } class InputReader { BufferedReader reader; StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } }
Java
["777-444---21-12-2013-12-2013-12-2013---444-777"]
1 second
["13-12-2013"]
null
Java 7
standard input
[ "implementation", "brute force", "strings" ]
dd7fd84f7915ad57b0e21f416e2a3ea0
The first line contains the Prophesy: a non-empty string that only consists of digits and characters "-". The length of the Prophesy doesn't exceed 105 characters.
1,600
In a single line print the date of the Apocalypse. It is guaranteed that such date exists and is unique.
standard output
PASSED
7a8ef0574d70364f15b44b250d38d003
train_003.jsonl
1356622500
A recently found Ancient Prophesy is believed to contain the exact Apocalypse date. The prophesy is a string that only consists of digits and characters "-".We'll say that some date is mentioned in the Prophesy if there is a substring in the Prophesy that is the date's record in the format "dd-mm-yyyy". We'll say that the number of the date's occurrences is the number of such substrings in the Prophesy. For example, the Prophesy "0012-10-2012-10-2012" mentions date 12-10-2012 twice (first time as "0012-10-2012-10-2012", second time as "0012-10-2012-10-2012").The date of the Apocalypse is such correct date that the number of times it is mentioned in the Prophesy is strictly larger than that of any other correct date.A date is correct if the year lies in the range from 2013 to 2015, the month is from 1 to 12, and the number of the day is strictly more than a zero and doesn't exceed the number of days in the current month. Note that a date is written in the format "dd-mm-yyyy", that means that leading zeroes may be added to the numbers of the months or days if needed. In other words, date "1-1-2013" isn't recorded in the format "dd-mm-yyyy", and date "01-01-2013" is recorded in it.Notice, that any year between 2013 and 2015 is not a leap year.
256 megabytes
import java.io.*; import java.util.*; import java.math.*; import java.text.*; public class P260B { private final int [] days = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; private boolean isDigit(char c) { return (c >= '0' && c <= '9'); } private boolean isMinus(char c) { return (c == '-'); } private boolean isGood(String s) { if (isDigit(s.charAt(0)) && isDigit(s.charAt(1)) && isMinus(s.charAt(2)) && isDigit(s.charAt(3)) && isDigit(s.charAt(4)) && isMinus(s.charAt(5)) && isDigit(s.charAt(6)) && isDigit(s.charAt(7)) && isDigit(s.charAt(8)) && isDigit(s.charAt(9))) { int d = Integer.valueOf(s.substring(0, 2)); int m = Integer.valueOf(s.substring(3, 5)); int y = Integer.valueOf(s.substring(6, 10)); return ((y > 2012) && (y <= 2015) && (m > 0) && (m < 13) && (d > 0) && (d <= days[m - 1])); } return false; } @SuppressWarnings("unchecked") public void run() throws Exception { String s = next(); TreeMap<String, Integer> dc = new TreeMap(); for (int i = 0; i <= s.length() - 10; i++) { String ss = s.substring(i, i + 10); if (isGood(ss)) { Integer c = dc.get(ss); dc.put(ss, c == null ? 1 : c + 1); } } int c = 0; String d = ""; for (Iterator<Map.Entry<String, Integer>> i = dc.entrySet().iterator(); i.hasNext(); ) { Map.Entry<String, Integer> e = i.next(); if (e.getValue() > c) { c = e.getValue(); d = e.getKey(); } } println(d); } public static void main(String... args) throws Exception { br = new BufferedReader(new InputStreamReader(System.in)); pw = new PrintWriter(new BufferedOutputStream(System.out)); new P260B().run(); br.close(); pw.close(); } static BufferedReader br; static PrintWriter pw; StringTokenizer stok; String nextToken() throws IOException { while (stok == null || !stok.hasMoreTokens()) { String s = br.readLine(); if (s == null) { return null; } stok = new StringTokenizer(s); } return stok.nextToken(); } void print(byte b) { print("" + b); } void print(int i) { print("" + i); } void print(long l) { print("" + l); } void print(double d) { print("" + d); } void print(char c) { print("" + c); } void print(Object o) { if (o instanceof int[]) { print(Arrays.toString((int [])o)); } else if (o instanceof long[]) { print(Arrays.toString((long [])o)); } else if (o instanceof char[]) { print(Arrays.toString((char [])o)); } else if (o instanceof byte[]) { print(Arrays.toString((byte [])o)); } else if (o instanceof short[]) { print(Arrays.toString((short [])o)); } else if (o instanceof boolean[]) { print(Arrays.toString((boolean [])o)); } else if (o instanceof float[]) { print(Arrays.toString((float [])o)); } else if (o instanceof double[]) { print(Arrays.toString((double [])o)); } else if (o instanceof Object[]) { print(Arrays.toString((Object [])o)); } else { println("" + o); } } void print(String s) { pw.print(s); } void println() { println(""); } void println(byte b) { println("" + b); } void println(int i) { println("" + i); } void println(long l) { println("" + l); } void println(double d) { println("" + d); } void println(char c) { println("" + c); } void println(String s) { pw.println(s); } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } char nextChar() throws IOException { return (char) (br.read()); } String next() throws IOException { return nextToken(); } String nextLine() throws IOException { return br.readLine(); } int [] readInt(int size) throws IOException { int [] array = new int [size]; for (int i = 0; i < size; i++) { array[i] = nextInt(); } return array; } long [] readLong(int size) throws IOException { long [] array = new long [size]; for (int i = 0; i < size; i++) { array[i] = nextLong(); } return array; } double [] readDouble(int size) throws IOException { double [] array = new double [size]; for (int i = 0; i < size; i++) { array[i] = nextDouble(); } return array; } String [] readLines(int size) throws IOException { String [] array = new String [size]; for (int i = 0; i < size; i++) { array[i] = nextLine(); } return array; } }
Java
["777-444---21-12-2013-12-2013-12-2013---444-777"]
1 second
["13-12-2013"]
null
Java 7
standard input
[ "implementation", "brute force", "strings" ]
dd7fd84f7915ad57b0e21f416e2a3ea0
The first line contains the Prophesy: a non-empty string that only consists of digits and characters "-". The length of the Prophesy doesn't exceed 105 characters.
1,600
In a single line print the date of the Apocalypse. It is guaranteed that such date exists and is unique.
standard output
PASSED
211fae8999dd8593857c0c8611ef6dc1
train_003.jsonl
1356622500
A recently found Ancient Prophesy is believed to contain the exact Apocalypse date. The prophesy is a string that only consists of digits and characters "-".We'll say that some date is mentioned in the Prophesy if there is a substring in the Prophesy that is the date's record in the format "dd-mm-yyyy". We'll say that the number of the date's occurrences is the number of such substrings in the Prophesy. For example, the Prophesy "0012-10-2012-10-2012" mentions date 12-10-2012 twice (first time as "0012-10-2012-10-2012", second time as "0012-10-2012-10-2012").The date of the Apocalypse is such correct date that the number of times it is mentioned in the Prophesy is strictly larger than that of any other correct date.A date is correct if the year lies in the range from 2013 to 2015, the month is from 1 to 12, and the number of the day is strictly more than a zero and doesn't exceed the number of days in the current month. Note that a date is written in the format "dd-mm-yyyy", that means that leading zeroes may be added to the numbers of the months or days if needed. In other words, date "1-1-2013" isn't recorded in the format "dd-mm-yyyy", and date "01-01-2013" is recorded in it.Notice, that any year between 2013 and 2015 is not a leap year.
256 megabytes
import java.io.InputStreamReader; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.BufferedWriter; import java.util.Hashtable; import java.util.ArrayList; import java.util.Set; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.io.Writer; import java.util.StringTokenizer; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author Lokesh Khandelwal */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } } class TaskB { public void solve(int testNumber, InputReader in, OutputWriter out) { String s=in.next(); int n=s.length(); ArrayList<String > a=new ArrayList<String>(100000); StringBuilder prev=new StringBuilder(""); for(int i=0;i<n;i++) { if(s.charAt(i)=='-') { a.add(prev.toString()); prev=new StringBuilder(""); } else { prev.append(s.charAt(i)); } } a.add(prev.toString()); // DebugUtils.print(a); String c[]=new String[a.size()]; int k=0; for(String s1 : a) c[k++]=s1; int days[]={31,28,31,30,31,30,31,31,30,31,30,31}; Hashtable<String,Integer> hash=new Hashtable<String,Integer>(); //DebugUtils.print(c); for(int i= 0;i<k-2;i++) { if(c[i].length()>=2&&c[i+1].length()==2&&c[i+2].length()>=4) { String date=c[i].substring(c[i].length()-2,c[i].length()); String month=c[i+1]; String year=c[i+2].substring(0,4); int y=Integer.parseInt(year),m=Integer.parseInt(month),d=Integer.parseInt(date); //DebugUtils.print(d,m,y); if(y>=2013&&y<=2015) { if(m>=1&&m<=12) { if(d>=1&&days[m-1]>=d) { String key=date+"-"+month+"-"+year; if(hash.containsKey(key)) { hash.put(key,hash.get(key)+1); } else hash.put(key,1); } } } } } int max=0; String ans=""; //DebugUtils.print(hash); for(String key: hash.keySet()) { if(hash.get(key)>max) { max=hash.get(key); ans=key; } } out.printLine(ans); } } class InputReader { BufferedReader in; StringTokenizer tokenizer=null; public InputReader(InputStream inputStream) { in=new BufferedReader(new InputStreamReader(inputStream)); } public String next() { try{ while (tokenizer==null||!tokenizer.hasMoreTokens()) { tokenizer=new StringTokenizer(in.readLine()); } return tokenizer.nextToken(); } catch (IOException e) { return null; } } } 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(); } }
Java
["777-444---21-12-2013-12-2013-12-2013---444-777"]
1 second
["13-12-2013"]
null
Java 7
standard input
[ "implementation", "brute force", "strings" ]
dd7fd84f7915ad57b0e21f416e2a3ea0
The first line contains the Prophesy: a non-empty string that only consists of digits and characters "-". The length of the Prophesy doesn't exceed 105 characters.
1,600
In a single line print the date of the Apocalypse. It is guaranteed that such date exists and is unique.
standard output
PASSED
c7c33ed473cf6d36d7d9a4879a0c37f4
train_003.jsonl
1356622500
A recently found Ancient Prophesy is believed to contain the exact Apocalypse date. The prophesy is a string that only consists of digits and characters "-".We'll say that some date is mentioned in the Prophesy if there is a substring in the Prophesy that is the date's record in the format "dd-mm-yyyy". We'll say that the number of the date's occurrences is the number of such substrings in the Prophesy. For example, the Prophesy "0012-10-2012-10-2012" mentions date 12-10-2012 twice (first time as "0012-10-2012-10-2012", second time as "0012-10-2012-10-2012").The date of the Apocalypse is such correct date that the number of times it is mentioned in the Prophesy is strictly larger than that of any other correct date.A date is correct if the year lies in the range from 2013 to 2015, the month is from 1 to 12, and the number of the day is strictly more than a zero and doesn't exceed the number of days in the current month. Note that a date is written in the format "dd-mm-yyyy", that means that leading zeroes may be added to the numbers of the months or days if needed. In other words, date "1-1-2013" isn't recorded in the format "dd-mm-yyyy", and date "01-01-2013" is recorded in it.Notice, that any year between 2013 and 2015 is not a leap year.
256 megabytes
import java.util.Map; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.FileReader; import java.io.BufferedWriter; import java.util.HashMap; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.io.File; import java.io.Writer; import java.util.StringTokenizer; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author monsterspy */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastScanner in = new FastScanner(inputStream); Output out = new Output(outputStream); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } } class TaskB { public void solve(int testNumber, FastScanner s, Output ww) { try{ String str = s.nextString(); int len = str.length(); int[] M = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; Map<String,Integer> mm = new HashMap<String,Integer>(); String max = ""; for(int i=0;i+10<=len;i++){ if(str.charAt(i+2) != '-' || str.charAt(i+5) != '-') continue; else{ try { int day = Integer.parseInt(str.substring(i, i + 2)); int mth = Integer.parseInt(str.substring(i + 3, i + 5)); int yr = Integer.parseInt(str.substring(i + 6, i + 10)); if (yr < 2013 || yr > 2015) continue; if (mth < 1 || mth > 12) continue; if (day < 1 || day > M[mth - 1]) continue; String temp = str.substring(i, i + 10); if (!mm.containsKey(temp)) mm.put(temp, 1); else mm.put(temp, mm.get(temp) + 1); if (!mm.containsKey(max) || mm.get(temp) > mm.get(max)) max = temp; }catch(Exception e){ } } } ww.print(max); }catch(Exception e){ e.printStackTrace(); } } } class FastScanner { BufferedReader s; StringTokenizer st; public FastScanner(InputStream InputStream){ st = new StringTokenizer(""); s = new BufferedReader(new InputStreamReader(InputStream)); } public FastScanner(File f) throws FileNotFoundException{ st = new StringTokenizer(""); s = new BufferedReader (new FileReader(f)); } public String nextString() throws IOException{ if(st.hasMoreTokens()) return st.nextToken(); else{ st = new StringTokenizer(s.readLine()); return nextString(); } } } class Output { private final PrintWriter writer; public Output(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public Output(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 close() { writer.close(); } }
Java
["777-444---21-12-2013-12-2013-12-2013---444-777"]
1 second
["13-12-2013"]
null
Java 7
standard input
[ "implementation", "brute force", "strings" ]
dd7fd84f7915ad57b0e21f416e2a3ea0
The first line contains the Prophesy: a non-empty string that only consists of digits and characters "-". The length of the Prophesy doesn't exceed 105 characters.
1,600
In a single line print the date of the Apocalypse. It is guaranteed that such date exists and is unique.
standard output
PASSED
033d0a6cfbe562124e94ce785a305fa0
train_003.jsonl
1576386300
You are an all-powerful being and you have created a rectangular world. In fact, your world is so bland that it could be represented by a $$$r \times c$$$ grid. Each cell on the grid represents a country. Each country has a dominant religion. There are only two religions in your world. One of the religions is called Beingawesomeism, who do good for the sake of being good. The other religion is called Pushingittoofarism, who do murders for the sake of being bad.Oh, and you are actually not really all-powerful. You just have one power, which you can use infinitely many times! Your power involves missionary groups. When a missionary group of a certain country, say $$$a$$$, passes by another country $$$b$$$, they change the dominant religion of country $$$b$$$ to the dominant religion of country $$$a$$$.In particular, a single use of your power is this: You choose a horizontal $$$1 \times x$$$ subgrid or a vertical $$$x \times 1$$$ subgrid. That value of $$$x$$$ is up to you; You choose a direction $$$d$$$. If you chose a horizontal subgrid, your choices will either be NORTH or SOUTH. If you choose a vertical subgrid, your choices will either be EAST or WEST; You choose the number $$$s$$$ of steps; You command each country in the subgrid to send a missionary group that will travel $$$s$$$ steps towards direction $$$d$$$. In each step, they will visit (and in effect convert the dominant religion of) all $$$s$$$ countries they pass through, as detailed above. The parameters $$$x$$$, $$$d$$$, $$$s$$$ must be chosen in such a way that any of the missionary groups won't leave the grid. The following image illustrates one possible single usage of your power. Here, A represents a country with dominant religion Beingawesomeism and P represents a country with dominant religion Pushingittoofarism. Here, we've chosen a $$$1 \times 4$$$ subgrid, the direction NORTH, and $$$s = 2$$$ steps. You are a being which believes in free will, for the most part. However, you just really want to stop receiving murders that are attributed to your name. Hence, you decide to use your powers and try to make Beingawesomeism the dominant religion in every country.What is the minimum number of usages of your power needed to convert everyone to Beingawesomeism?With god, nothing is impossible. But maybe you're not god? If it is impossible to make Beingawesomeism the dominant religion in all countries, you must also admit your mortality and say so.
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.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.PriorityQueue; import java.util.StringTokenizer; import java.util.TreeSet; /* * 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. */ public class b { static StringBuilder res; static int[] num; static int n; public static void main(String[] args) { FS in = new FS(System.in); PrintWriter out = new PrintWriter(System.out); int t = in.nextInt(); while(t-->0) { int n = in.nextInt(); int m = in.nextInt(); int numA = 0; int[] numR = new int[n]; int[] numC = new int[m]; boolean hasCorn = false; for(int i = 0; i < n; i++) { char[] arr = in.next().toCharArray(); for(int j = 0; j < m; j++) { if(arr[j] == 'A') { numA++; numR[i]++; numC[j]++; if((i == 0 || i == n-1) && (j == 0 || j == m-1)) hasCorn = true; } } } if(numA == n*m) { System.out.println(0); } else if(numR[0] == m || numR[n-1] == m || numC[0] == n || numC[m-1] == n) { System.out.println(1); } else { boolean has = false; for(int a : numR) has |= a == m; for(int a : numC) has |= a == n; if(has || hasCorn) { System.out.println(2); } else { if(numR[0] > 0 || numR[n-1] > 0 || numC[0] > 0 || numC[m-1] > 0) { System.out.println(3); } else { if(numA > 0) { System.out.println(4); } else { System.out.println("MORTAL"); } } } } } out.close(); } static class FS { BufferedReader in; StringTokenizer token; public FS(InputStream str) { in = new BufferedReader(new InputStreamReader(str)); } public String next() { if (token == null || !token.hasMoreElements()) { try { token = new StringTokenizer(in.readLine()); } catch (IOException ex) { } return next(); } return token.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["4\n7 8\nAAPAAAAA\nPPPPAAAA\nPPPPAAAA\nAPAAPPPP\nAPAPPAPP\nAAAAPPAP\nAAAAPPAA\n6 5\nAAAAA\nAAAAA\nAAPAA\nAAPAP\nAAAPP\nAAAPP\n4 4\nPPPP\nPPPP\nPPPP\nPPPP\n3 4\nPPPP\nPAAP\nPPPP"]
2 seconds
["2\n1\nMORTAL\n4"]
NoteIn the first test case, it can be done in two usages, as follows:Usage 1: Usage 2: In the second test case, it can be done with just one usage of the power. In the third test case, it is impossible to convert everyone to Beingawesomeism, so the answer is "MORTAL".
Java 8
standard input
[ "constructive algorithms", "implementation", "greedy", "math" ]
da18ca9f125d1524e7c0a2637b1fa3df
The first line of input contains a single integer $$$t$$$ ($$$1 \le t \le 2\cdot 10^4$$$) denoting the number of test cases. The first line of each test case contains two space-separated integers $$$r$$$ and $$$c$$$ denoting the dimensions of the grid ($$$1 \le r, c \le 60$$$). The next $$$r$$$ lines each contains $$$c$$$ characters describing the dominant religions in the countries. In particular, the $$$j$$$-th character in the $$$i$$$-th line describes the dominant religion in the country at the cell with row $$$i$$$ and column $$$j$$$, where: "A" means that the dominant religion is Beingawesomeism; "P" means that the dominant religion is Pushingittoofarism. It is guaranteed that the grid will only contain "A" or "P" characters. It is guaranteed that the sum of the $$$r \cdot c$$$ in a single file is at most $$$3 \cdot 10^6$$$.
1,800
For each test case, output a single line containing the minimum number of usages of your power needed to convert everyone to Beingawesomeism, or the string "MORTAL" (without quotes) if it is impossible to do so.
standard output
PASSED
ac86bd12159695a157a83614a70a2e75
train_003.jsonl
1576386300
You are an all-powerful being and you have created a rectangular world. In fact, your world is so bland that it could be represented by a $$$r \times c$$$ grid. Each cell on the grid represents a country. Each country has a dominant religion. There are only two religions in your world. One of the religions is called Beingawesomeism, who do good for the sake of being good. The other religion is called Pushingittoofarism, who do murders for the sake of being bad.Oh, and you are actually not really all-powerful. You just have one power, which you can use infinitely many times! Your power involves missionary groups. When a missionary group of a certain country, say $$$a$$$, passes by another country $$$b$$$, they change the dominant religion of country $$$b$$$ to the dominant religion of country $$$a$$$.In particular, a single use of your power is this: You choose a horizontal $$$1 \times x$$$ subgrid or a vertical $$$x \times 1$$$ subgrid. That value of $$$x$$$ is up to you; You choose a direction $$$d$$$. If you chose a horizontal subgrid, your choices will either be NORTH or SOUTH. If you choose a vertical subgrid, your choices will either be EAST or WEST; You choose the number $$$s$$$ of steps; You command each country in the subgrid to send a missionary group that will travel $$$s$$$ steps towards direction $$$d$$$. In each step, they will visit (and in effect convert the dominant religion of) all $$$s$$$ countries they pass through, as detailed above. The parameters $$$x$$$, $$$d$$$, $$$s$$$ must be chosen in such a way that any of the missionary groups won't leave the grid. The following image illustrates one possible single usage of your power. Here, A represents a country with dominant religion Beingawesomeism and P represents a country with dominant religion Pushingittoofarism. Here, we've chosen a $$$1 \times 4$$$ subgrid, the direction NORTH, and $$$s = 2$$$ steps. You are a being which believes in free will, for the most part. However, you just really want to stop receiving murders that are attributed to your name. Hence, you decide to use your powers and try to make Beingawesomeism the dominant religion in every country.What is the minimum number of usages of your power needed to convert everyone to Beingawesomeism?With god, nothing is impossible. But maybe you're not god? If it is impossible to make Beingawesomeism the dominant religion in all countries, you must also admit your mortality and say so.
256 megabytes
import java.io.*; import java.util.*; public class CF607D { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); int t = Integer.parseInt(br.readLine()); while (t-- > 0) { String[] inputs = br.readLine().split(" "); int r = Integer.parseInt(inputs[0]); int c = Integer.parseInt(inputs[1]); char[][] grid = new char[r][c]; for (int ii = 0; ii < r; ii++) { grid[ii] = br.readLine().toCharArray(); } bw.write(solve(r, c, grid) + "\n"); } bw.flush(); } private static String solve(int r, int c, char[][] grid) { // --- int countA = 0; int countASide = 0; for (int ii = 0; ii < r; ii++) { for (int jj = 0; jj < c; jj++) { if (grid[ii][jj] == 'A') { countA++; if (ii == 0 || ii == r-1 || jj == 0 || jj == c-1) countASide++; } } } if (countA == r * c) return "0"; // --- boolean isSideUAllA = true; for (int jj = 0; jj < c; jj++) { if (grid[0][jj] == 'P') isSideUAllA = false; } boolean isSideDAllA = true; for (int jj = 0; jj < c; jj++) { if (grid[r-1][jj] == 'P') isSideDAllA = false; } boolean isSideLAllA = true; for (int ii = 0; ii < r; ii++) { if (grid[ii][0] == 'P') isSideLAllA = false; } boolean isSideRAllA = true; for (int ii = 0; ii < r; ii++) { if (grid[ii][c-1] == 'P') isSideRAllA = false; } if (isSideUAllA || isSideDAllA || isSideLAllA || isSideRAllA) return "1"; // --- if (grid[0][0] == 'A' || grid[0][c-1] == 'A' || grid[r-1][0] == 'A' || grid[r-1][c-1] == 'A') return "2"; // -- for (int ii = 0; ii < r; ii++) { boolean isHorizontalA = true; for (int jj = 0; jj < c; jj++) { if (grid[ii][jj] == 'P') isHorizontalA = false; } if (isHorizontalA) return "2"; } for (int jj = 0; jj < c; jj++) { boolean isVerticalA = true; for (int ii = 0; ii < r; ii++) { if (grid[ii][jj] == 'P') isVerticalA = false; } if (isVerticalA) return "2"; } // --- if (countASide > 0) return "3"; // --- if (countA > 0) return "4"; // --- return "MORTAL"; } } /* IF (one side all A) then 1 IF (one of corner is A) then 2 IF (none of corner is A but there's A in side) then 3 IF (there's A) then 4 MORTAL */
Java
["4\n7 8\nAAPAAAAA\nPPPPAAAA\nPPPPAAAA\nAPAAPPPP\nAPAPPAPP\nAAAAPPAP\nAAAAPPAA\n6 5\nAAAAA\nAAAAA\nAAPAA\nAAPAP\nAAAPP\nAAAPP\n4 4\nPPPP\nPPPP\nPPPP\nPPPP\n3 4\nPPPP\nPAAP\nPPPP"]
2 seconds
["2\n1\nMORTAL\n4"]
NoteIn the first test case, it can be done in two usages, as follows:Usage 1: Usage 2: In the second test case, it can be done with just one usage of the power. In the third test case, it is impossible to convert everyone to Beingawesomeism, so the answer is "MORTAL".
Java 8
standard input
[ "constructive algorithms", "implementation", "greedy", "math" ]
da18ca9f125d1524e7c0a2637b1fa3df
The first line of input contains a single integer $$$t$$$ ($$$1 \le t \le 2\cdot 10^4$$$) denoting the number of test cases. The first line of each test case contains two space-separated integers $$$r$$$ and $$$c$$$ denoting the dimensions of the grid ($$$1 \le r, c \le 60$$$). The next $$$r$$$ lines each contains $$$c$$$ characters describing the dominant religions in the countries. In particular, the $$$j$$$-th character in the $$$i$$$-th line describes the dominant religion in the country at the cell with row $$$i$$$ and column $$$j$$$, where: "A" means that the dominant religion is Beingawesomeism; "P" means that the dominant religion is Pushingittoofarism. It is guaranteed that the grid will only contain "A" or "P" characters. It is guaranteed that the sum of the $$$r \cdot c$$$ in a single file is at most $$$3 \cdot 10^6$$$.
1,800
For each test case, output a single line containing the minimum number of usages of your power needed to convert everyone to Beingawesomeism, or the string "MORTAL" (without quotes) if it is impossible to do so.
standard output
PASSED
8b8102c1025f783d518070b3a8bb69e2
train_003.jsonl
1576386300
You are an all-powerful being and you have created a rectangular world. In fact, your world is so bland that it could be represented by a $$$r \times c$$$ grid. Each cell on the grid represents a country. Each country has a dominant religion. There are only two religions in your world. One of the religions is called Beingawesomeism, who do good for the sake of being good. The other religion is called Pushingittoofarism, who do murders for the sake of being bad.Oh, and you are actually not really all-powerful. You just have one power, which you can use infinitely many times! Your power involves missionary groups. When a missionary group of a certain country, say $$$a$$$, passes by another country $$$b$$$, they change the dominant religion of country $$$b$$$ to the dominant religion of country $$$a$$$.In particular, a single use of your power is this: You choose a horizontal $$$1 \times x$$$ subgrid or a vertical $$$x \times 1$$$ subgrid. That value of $$$x$$$ is up to you; You choose a direction $$$d$$$. If you chose a horizontal subgrid, your choices will either be NORTH or SOUTH. If you choose a vertical subgrid, your choices will either be EAST or WEST; You choose the number $$$s$$$ of steps; You command each country in the subgrid to send a missionary group that will travel $$$s$$$ steps towards direction $$$d$$$. In each step, they will visit (and in effect convert the dominant religion of) all $$$s$$$ countries they pass through, as detailed above. The parameters $$$x$$$, $$$d$$$, $$$s$$$ must be chosen in such a way that any of the missionary groups won't leave the grid. The following image illustrates one possible single usage of your power. Here, A represents a country with dominant religion Beingawesomeism and P represents a country with dominant religion Pushingittoofarism. Here, we've chosen a $$$1 \times 4$$$ subgrid, the direction NORTH, and $$$s = 2$$$ steps. You are a being which believes in free will, for the most part. However, you just really want to stop receiving murders that are attributed to your name. Hence, you decide to use your powers and try to make Beingawesomeism the dominant religion in every country.What is the minimum number of usages of your power needed to convert everyone to Beingawesomeism?With god, nothing is impossible. But maybe you're not god? If it is impossible to make Beingawesomeism the dominant religion in all countries, you must also admit your mortality and say so.
256 megabytes
import java.util.*; import java.io.*; public class Main { public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); int cases = Integer.parseInt(in.readLine()); outer: for (int test = 0; test < cases; test++) { StringTokenizer st = new StringTokenizer(in.readLine()); int rows = Integer.parseInt(st.nextToken()); int cols = Integer.parseInt(st.nextToken()); char[][] grid = new char[rows][cols]; boolean[] containsPRows = new boolean[rows]; boolean[] containsPCols = new boolean[cols]; boolean possible = false; boolean allA = true; for (int row = 0; row < rows; row++) { String string = in.readLine(); for (int col = 0; col < cols; col++) { grid[row][col] = string.charAt(col); if (grid[row][col] == 'P') { allA = false; } if (grid[row][col] == 'A') { possible = true; } else { containsPRows[row] = true; containsPCols[col] = true; } } } if (allA) { System.out.println("0"); continue outer; } // check if possible if (!possible) { System.out.println("MORTAL"); continue outer; } // check if one move if (!containsPCols[0] || !containsPCols[cols-1] || !containsPRows[0] || !containsPRows[rows-1]) { System.out.println("1"); continue outer; } // check if two moves for (int i = 0; i < cols; i++) { if (!containsPCols[i]) { System.out.println("2"); continue outer; } } for (int i = 0; i < rows; i++) { if (!containsPRows[i]) { System.out.println("2"); continue outer; } } if (grid[0][0] == 'A' || grid[0][cols-1] == 'A' || grid[rows-1][0] == 'A' || grid[rows-1][cols-1] == 'A') { System.out.println("2"); continue outer; } // check if 3 moves for (int i = 0; i < cols; i++) { if (grid[0][i] == 'A' || grid[rows-1][i] == 'A') { System.out.println("3"); continue outer; } } for (int i = 0; i < rows; i++) { if (grid[i][0] == 'A' || grid[i][cols-1] == 'A') { System.out.println("3"); continue outer; } } System.out.println("4"); } } } /* */
Java
["4\n7 8\nAAPAAAAA\nPPPPAAAA\nPPPPAAAA\nAPAAPPPP\nAPAPPAPP\nAAAAPPAP\nAAAAPPAA\n6 5\nAAAAA\nAAAAA\nAAPAA\nAAPAP\nAAAPP\nAAAPP\n4 4\nPPPP\nPPPP\nPPPP\nPPPP\n3 4\nPPPP\nPAAP\nPPPP"]
2 seconds
["2\n1\nMORTAL\n4"]
NoteIn the first test case, it can be done in two usages, as follows:Usage 1: Usage 2: In the second test case, it can be done with just one usage of the power. In the third test case, it is impossible to convert everyone to Beingawesomeism, so the answer is "MORTAL".
Java 8
standard input
[ "constructive algorithms", "implementation", "greedy", "math" ]
da18ca9f125d1524e7c0a2637b1fa3df
The first line of input contains a single integer $$$t$$$ ($$$1 \le t \le 2\cdot 10^4$$$) denoting the number of test cases. The first line of each test case contains two space-separated integers $$$r$$$ and $$$c$$$ denoting the dimensions of the grid ($$$1 \le r, c \le 60$$$). The next $$$r$$$ lines each contains $$$c$$$ characters describing the dominant religions in the countries. In particular, the $$$j$$$-th character in the $$$i$$$-th line describes the dominant religion in the country at the cell with row $$$i$$$ and column $$$j$$$, where: "A" means that the dominant religion is Beingawesomeism; "P" means that the dominant religion is Pushingittoofarism. It is guaranteed that the grid will only contain "A" or "P" characters. It is guaranteed that the sum of the $$$r \cdot c$$$ in a single file is at most $$$3 \cdot 10^6$$$.
1,800
For each test case, output a single line containing the minimum number of usages of your power needed to convert everyone to Beingawesomeism, or the string "MORTAL" (without quotes) if it is impossible to do so.
standard output
PASSED
8c159a2769091c257bf2e50d24ebd49f
train_003.jsonl
1576386300
You are an all-powerful being and you have created a rectangular world. In fact, your world is so bland that it could be represented by a $$$r \times c$$$ grid. Each cell on the grid represents a country. Each country has a dominant religion. There are only two religions in your world. One of the religions is called Beingawesomeism, who do good for the sake of being good. The other religion is called Pushingittoofarism, who do murders for the sake of being bad.Oh, and you are actually not really all-powerful. You just have one power, which you can use infinitely many times! Your power involves missionary groups. When a missionary group of a certain country, say $$$a$$$, passes by another country $$$b$$$, they change the dominant religion of country $$$b$$$ to the dominant religion of country $$$a$$$.In particular, a single use of your power is this: You choose a horizontal $$$1 \times x$$$ subgrid or a vertical $$$x \times 1$$$ subgrid. That value of $$$x$$$ is up to you; You choose a direction $$$d$$$. If you chose a horizontal subgrid, your choices will either be NORTH or SOUTH. If you choose a vertical subgrid, your choices will either be EAST or WEST; You choose the number $$$s$$$ of steps; You command each country in the subgrid to send a missionary group that will travel $$$s$$$ steps towards direction $$$d$$$. In each step, they will visit (and in effect convert the dominant religion of) all $$$s$$$ countries they pass through, as detailed above. The parameters $$$x$$$, $$$d$$$, $$$s$$$ must be chosen in such a way that any of the missionary groups won't leave the grid. The following image illustrates one possible single usage of your power. Here, A represents a country with dominant religion Beingawesomeism and P represents a country with dominant religion Pushingittoofarism. Here, we've chosen a $$$1 \times 4$$$ subgrid, the direction NORTH, and $$$s = 2$$$ steps. You are a being which believes in free will, for the most part. However, you just really want to stop receiving murders that are attributed to your name. Hence, you decide to use your powers and try to make Beingawesomeism the dominant religion in every country.What is the minimum number of usages of your power needed to convert everyone to Beingawesomeism?With god, nothing is impossible. But maybe you're not god? If it is impossible to make Beingawesomeism the dominant religion in all countries, you must also admit your mortality and say so.
256 megabytes
import java.io.*; import java.util.*; @SuppressWarnings("unused") public class Main { FastScanner in; PrintWriter out; int MOD = (int)1e9+7; long ceil(long a, long b){return (a + b - 1) / b;} long gcd(long a, long b){return b == 0 ? a : gcd(b, a % b);} long lcm(long a, long b){return a / gcd(a, b) * b;} void solve() { int t = in.nextInt(); for(int i = 0; i < t; i++){ solveMain(); } } void solveMain(){ int h = in.nextInt(), w = in.nextInt(); boolean[][] isA = new boolean[h][w]; int numA = 0; int[] sumH = new int[w], sumW = new int[h]; int[] numEdge = new int[4]; for(int i = 0; i < h; i++){ for(int j = 0; j < w; j++){ isA[i][j] = in.nextChar() == 'A'; if(isA[i][j]){ numA++; sumH[j]++; sumW[i]++; if(i == 0) numEdge[0]++; if(i == h-1) numEdge[2]++; if(j == 0) numEdge[1]++; if(j == w-1) numEdge[3]++; } } } int maxSumH = 0, maxSumW = 0; for(int i = 0; i < w; i++) maxSumH = Math.max(maxSumH, sumH[i]); for(int i = 0; i < h; i++) maxSumW = Math.max(maxSumW, sumW[i]); if(numA == 0){ out.println("MORTAL"); }else if(numA == h * w){ out.println("0"); }else if(h == 1 || w == 1){ if(isA[0][0] || isA[h-1][0] || isA[0][w-1] || isA[h-1][w-1]) out.println("1"); else out.println("2"); }else if(numEdge[0] + numEdge[1] + numEdge[2] + numEdge[3] == 0){ out.println("4"); }else if(numEdge[0] == w || numEdge[2] == w || numEdge[1] == h || numEdge[3] == h){ out.println("1"); }else if(isA[0][0] || isA[h-1][0] || isA[0][w-1] || isA[h-1][w-1] || maxSumH == h || maxSumW == w){ out.println("2"); }else{ out.println("3"); } } public static void main(String[] args) { new Main().m(); } private void m() { in = new FastScanner(System.in); out = new PrintWriter(System.out); /* try { String path = "output.txt"; out = new PrintWriter(new BufferedWriter(new FileWriter(new File(path)))); }catch (IOException e){ e.printStackTrace(); } */ solve(); out.flush(); in.close(); out.close(); } static class FastScanner { private Reader input; public FastScanner() {this(System.in);} public FastScanner(InputStream stream) {this.input = new BufferedReader(new InputStreamReader(stream));} public void close() { try { this.input.close(); } catch (IOException e) { e.printStackTrace(); } } public int nextInt() {return (int) nextLong();} public long nextLong() { try { int sign = 1; int b = input.read(); while ((b < '0' || '9' < b) && b != '-' && b != '+') { b = input.read(); } if (b == '-') { sign = -1; b = input.read(); } else if (b == '+') { b = input.read(); } long ret = b - '0'; while (true) { b = input.read(); if (b < '0' || '9' < b) return ret * sign; ret *= 10; ret += b - '0'; } } catch (IOException e) { e.printStackTrace(); return -1; } } public double nextDouble() { try { double sign = 1; int b = input.read(); while ((b < '0' || '9' < b) && b != '-' && b != '+') { b = input.read(); } if (b == '-') { sign = -1; b = input.read(); } else if (b == '+') { b = input.read(); } double ret = b - '0'; while (true) { b = input.read(); if (b < '0' || '9' < b) break; ret *= 10; ret += b - '0'; } if (b != '.') return sign * ret; double div = 1; b = input.read(); while ('0' <= b && b <= '9') { ret *= 10; ret += b - '0'; div *= 10; b = input.read(); } return sign * ret / div; } catch (IOException e) { e.printStackTrace(); return Double.NaN; } } public char nextChar() { try { int b = input.read(); while (Character.isWhitespace(b)) { b = input.read(); } return (char) b; } catch (IOException e) { e.printStackTrace(); return 0; } } public String nextStr() { try { StringBuilder sb = new StringBuilder(); int b = input.read(); while (Character.isWhitespace(b)) { b = input.read(); } while (b != -1 && !Character.isWhitespace(b)) { sb.append((char) b); b = input.read(); } return sb.toString(); } catch (IOException e) { e.printStackTrace(); return ""; } } public String nextLine() { try { StringBuilder sb = new StringBuilder(); int b = input.read(); while (b != -1 && b != '\n') { sb.append((char) b); b = input.read(); } return sb.toString(); } catch (IOException e) { e.printStackTrace(); return ""; } } public int[] nextIntArray(int n) { int[] res = new int[n]; for (int i = 0; i < n; i++) { res[i] = nextInt(); } return res; } public int[] nextIntArrayDec(int n) { int[] res = new int[n]; for (int i = 0; i < n; i++) { res[i] = nextInt() - 1; } return res; } public int[] nextIntArray1Index(int n) { int[] res = new int[n + 1]; for (int i = 0; i < n; i++) { res[i + 1] = nextInt(); } return res; } public long[] nextLongArray(int n) { long[] res = new long[n]; for (int i = 0; i < n; i++) { res[i] = nextLong(); } return res; } public long[] nextLongArrayDec(int n) { long[] res = new long[n]; for (int i = 0; i < n; i++) { res[i] = nextLong() - 1; } return res; } public long[] nextLongArray1Index(int n) { long[] res = new long[n + 1]; for (int i = 0; i < n; i++) { res[i + 1] = nextLong(); } return res; } public double[] nextDoubleArray(int n) { double[] res = new double[n]; for (int i = 0; i < n; i++) { res[i] = nextDouble(); } return res; } } }
Java
["4\n7 8\nAAPAAAAA\nPPPPAAAA\nPPPPAAAA\nAPAAPPPP\nAPAPPAPP\nAAAAPPAP\nAAAAPPAA\n6 5\nAAAAA\nAAAAA\nAAPAA\nAAPAP\nAAAPP\nAAAPP\n4 4\nPPPP\nPPPP\nPPPP\nPPPP\n3 4\nPPPP\nPAAP\nPPPP"]
2 seconds
["2\n1\nMORTAL\n4"]
NoteIn the first test case, it can be done in two usages, as follows:Usage 1: Usage 2: In the second test case, it can be done with just one usage of the power. In the third test case, it is impossible to convert everyone to Beingawesomeism, so the answer is "MORTAL".
Java 8
standard input
[ "constructive algorithms", "implementation", "greedy", "math" ]
da18ca9f125d1524e7c0a2637b1fa3df
The first line of input contains a single integer $$$t$$$ ($$$1 \le t \le 2\cdot 10^4$$$) denoting the number of test cases. The first line of each test case contains two space-separated integers $$$r$$$ and $$$c$$$ denoting the dimensions of the grid ($$$1 \le r, c \le 60$$$). The next $$$r$$$ lines each contains $$$c$$$ characters describing the dominant religions in the countries. In particular, the $$$j$$$-th character in the $$$i$$$-th line describes the dominant religion in the country at the cell with row $$$i$$$ and column $$$j$$$, where: "A" means that the dominant religion is Beingawesomeism; "P" means that the dominant religion is Pushingittoofarism. It is guaranteed that the grid will only contain "A" or "P" characters. It is guaranteed that the sum of the $$$r \cdot c$$$ in a single file is at most $$$3 \cdot 10^6$$$.
1,800
For each test case, output a single line containing the minimum number of usages of your power needed to convert everyone to Beingawesomeism, or the string "MORTAL" (without quotes) if it is impossible to do so.
standard output
PASSED
8a7a61358ea071e7e91eb3412298b40f
train_003.jsonl
1576386300
You are an all-powerful being and you have created a rectangular world. In fact, your world is so bland that it could be represented by a $$$r \times c$$$ grid. Each cell on the grid represents a country. Each country has a dominant religion. There are only two religions in your world. One of the religions is called Beingawesomeism, who do good for the sake of being good. The other religion is called Pushingittoofarism, who do murders for the sake of being bad.Oh, and you are actually not really all-powerful. You just have one power, which you can use infinitely many times! Your power involves missionary groups. When a missionary group of a certain country, say $$$a$$$, passes by another country $$$b$$$, they change the dominant religion of country $$$b$$$ to the dominant religion of country $$$a$$$.In particular, a single use of your power is this: You choose a horizontal $$$1 \times x$$$ subgrid or a vertical $$$x \times 1$$$ subgrid. That value of $$$x$$$ is up to you; You choose a direction $$$d$$$. If you chose a horizontal subgrid, your choices will either be NORTH or SOUTH. If you choose a vertical subgrid, your choices will either be EAST or WEST; You choose the number $$$s$$$ of steps; You command each country in the subgrid to send a missionary group that will travel $$$s$$$ steps towards direction $$$d$$$. In each step, they will visit (and in effect convert the dominant religion of) all $$$s$$$ countries they pass through, as detailed above. The parameters $$$x$$$, $$$d$$$, $$$s$$$ must be chosen in such a way that any of the missionary groups won't leave the grid. The following image illustrates one possible single usage of your power. Here, A represents a country with dominant religion Beingawesomeism and P represents a country with dominant religion Pushingittoofarism. Here, we've chosen a $$$1 \times 4$$$ subgrid, the direction NORTH, and $$$s = 2$$$ steps. You are a being which believes in free will, for the most part. However, you just really want to stop receiving murders that are attributed to your name. Hence, you decide to use your powers and try to make Beingawesomeism the dominant religion in every country.What is the minimum number of usages of your power needed to convert everyone to Beingawesomeism?With god, nothing is impossible. But maybe you're not god? If it is impossible to make Beingawesomeism the dominant religion in all countries, you must also admit your mortality and say so.
256 megabytes
// package com.company; import java.util.*; import java.lang.*; import java.io.*; //****Use Integer Wrapper Class for Arrays.sort()**** public class BD4 { public static void main(String[] Args){ FastReader scan=new FastReader(); int t=scan.nextInt(); StringBuilder print=new StringBuilder(); while(t-->0){ int r=scan.nextInt(); int c=scan.nextInt(); String[] arr=new String[r]; for(int i=0;i<r;i++){ arr[i]=scan.next(); } int ac=0; int[] rs=new int[r]; int[] cs=new int[c]; for(int i=0;i<r;i++){ for(int j=0;j<c;j++){ if(arr[i].charAt(j)=='A'){ ac++; rs[i]++; cs[j]++; } } } if(ac==0){ print.append("MORTAL\n"); } else{ if(ac==r*c){ print.append("0\n"); } else { if(rs[0]==c||rs[r-1]==c||cs[0]==r||cs[c-1]==r){ print.append("1\n"); } else{ boolean mid=false; for(int i=0;i<r;i++){ if(rs[i]==c){ mid=true; } } for(int i=0;i<c;i++){ if(cs[i]==r){ mid=true; } } if(arr[0].charAt(0)=='A'){ mid=true; }if(arr[0].charAt(c-1)=='A'){ mid=true; }if(arr[r-1].charAt(0)=='A'){ mid=true; }if(arr[r-1].charAt(c-1)=='A'){ mid=true; } if(mid){ print.append("2\n"); } else{ if(rs[0]>0||rs[r-1]>0||cs[0]>0||cs[c-1]>0){ print.append("3\n"); } else{ print.append("4\n"); } } } } } } System.out.println(print); } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["4\n7 8\nAAPAAAAA\nPPPPAAAA\nPPPPAAAA\nAPAAPPPP\nAPAPPAPP\nAAAAPPAP\nAAAAPPAA\n6 5\nAAAAA\nAAAAA\nAAPAA\nAAPAP\nAAAPP\nAAAPP\n4 4\nPPPP\nPPPP\nPPPP\nPPPP\n3 4\nPPPP\nPAAP\nPPPP"]
2 seconds
["2\n1\nMORTAL\n4"]
NoteIn the first test case, it can be done in two usages, as follows:Usage 1: Usage 2: In the second test case, it can be done with just one usage of the power. In the third test case, it is impossible to convert everyone to Beingawesomeism, so the answer is "MORTAL".
Java 8
standard input
[ "constructive algorithms", "implementation", "greedy", "math" ]
da18ca9f125d1524e7c0a2637b1fa3df
The first line of input contains a single integer $$$t$$$ ($$$1 \le t \le 2\cdot 10^4$$$) denoting the number of test cases. The first line of each test case contains two space-separated integers $$$r$$$ and $$$c$$$ denoting the dimensions of the grid ($$$1 \le r, c \le 60$$$). The next $$$r$$$ lines each contains $$$c$$$ characters describing the dominant religions in the countries. In particular, the $$$j$$$-th character in the $$$i$$$-th line describes the dominant religion in the country at the cell with row $$$i$$$ and column $$$j$$$, where: "A" means that the dominant religion is Beingawesomeism; "P" means that the dominant religion is Pushingittoofarism. It is guaranteed that the grid will only contain "A" or "P" characters. It is guaranteed that the sum of the $$$r \cdot c$$$ in a single file is at most $$$3 \cdot 10^6$$$.
1,800
For each test case, output a single line containing the minimum number of usages of your power needed to convert everyone to Beingawesomeism, or the string "MORTAL" (without quotes) if it is impossible to do so.
standard output
PASSED
3ea9291be74d3de2a4b38ba97efbdef9
train_003.jsonl
1576386300
You are an all-powerful being and you have created a rectangular world. In fact, your world is so bland that it could be represented by a $$$r \times c$$$ grid. Each cell on the grid represents a country. Each country has a dominant religion. There are only two religions in your world. One of the religions is called Beingawesomeism, who do good for the sake of being good. The other religion is called Pushingittoofarism, who do murders for the sake of being bad.Oh, and you are actually not really all-powerful. You just have one power, which you can use infinitely many times! Your power involves missionary groups. When a missionary group of a certain country, say $$$a$$$, passes by another country $$$b$$$, they change the dominant religion of country $$$b$$$ to the dominant religion of country $$$a$$$.In particular, a single use of your power is this: You choose a horizontal $$$1 \times x$$$ subgrid or a vertical $$$x \times 1$$$ subgrid. That value of $$$x$$$ is up to you; You choose a direction $$$d$$$. If you chose a horizontal subgrid, your choices will either be NORTH or SOUTH. If you choose a vertical subgrid, your choices will either be EAST or WEST; You choose the number $$$s$$$ of steps; You command each country in the subgrid to send a missionary group that will travel $$$s$$$ steps towards direction $$$d$$$. In each step, they will visit (and in effect convert the dominant religion of) all $$$s$$$ countries they pass through, as detailed above. The parameters $$$x$$$, $$$d$$$, $$$s$$$ must be chosen in such a way that any of the missionary groups won't leave the grid. The following image illustrates one possible single usage of your power. Here, A represents a country with dominant religion Beingawesomeism and P represents a country with dominant religion Pushingittoofarism. Here, we've chosen a $$$1 \times 4$$$ subgrid, the direction NORTH, and $$$s = 2$$$ steps. You are a being which believes in free will, for the most part. However, you just really want to stop receiving murders that are attributed to your name. Hence, you decide to use your powers and try to make Beingawesomeism the dominant religion in every country.What is the minimum number of usages of your power needed to convert everyone to Beingawesomeism?With god, nothing is impossible. But maybe you're not god? If it is impossible to make Beingawesomeism the dominant religion in all countries, you must also admit your mortality and say so.
256 megabytes
import java.io.*; import java.util.*; import java.math.*; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Beingawesomeism { public static void main(String[] args) throws IOException { OutputStream outputStream = System.out; Reader in = new Reader(); PrintWriter out = new PrintWriter(outputStream); TaskA solver = new TaskA(); solver.solve(in.nextInt(), in, out); out.close(); } static class TaskA { long mod = (long)(1000000007); public void solve(int testNumber, Reader in, PrintWriter out) throws IOException{ while(testNumber-->0){ int r = in.nextInt(); int c = in.nextInt(); in.next(); char a[][] = new char[r][c]; for(int i=0;i<r;i++){ String b = in.next(); for(int j=0;j<c;j++) a[i][j] = b.charAt(j); } // for(int i=0;i<r;i++) // out.println(a[i]); int value = ans(a , a.length , a[0].length); a = invert(a); value = Math.min(value , ans(a , a.length , a[0].length)); if(value == Integer.MAX_VALUE) out.println("MORTAL"); else out.println(value); } } public int ans(char a[][], int r , int c){ int value = Integer.MAX_VALUE; boolean containA = false; boolean atleastFrontEnd = false; int countA = 0; for(int i=0;i<r;i++){ boolean found = false; for(int j=0;j<c;j++){ // System.out.print(a[i][j] + " "); if((i == 0 || i==r-1) && a[i][j] == 'A') atleastFrontEnd = true; if(a[i][j] == 'A'){ containA = true; countA++; } if(a[i][j] == 'P'){ found = true; } } // System.out.println(); if(!found){ if(i==0 || i==r-1) value = Math.min(value , 1); else value = Math.min(value , 2); } } // System.out.println(atleastFrontEnd); if(countA == r*c) value = Math.min(value , 0); if(!containA) return value; if(a[0][0]=='A' || a[0][c-1] == 'A' || a[r-1][0] == 'A' || a[r-1][c-1] == 'A') value = Math.min(value , 2); if(atleastFrontEnd) value = Math.min(value , 3); else value = Math.min(value , 4); return value; } public char[][] invert(char a[][]){ char c[][] = new char[a[0].length][a.length]; for(int i=0;i<a.length;i++) for(int j=0;j<a[i].length;j++) c[j][i] = a[i][j]; return c; } public void sieve(int a[]){ a[0] = a[1] = 1; int i; for(i=2;i*i<=a.length;i++){ if(a[i] != 0) continue; a[i] = i; for(int k = (i)*(i);k<a.length;k+=i){ if(a[k] != 0) continue; a[k] = i; } } } public int [][] matrixExpo(int c[][] , int n){ int a[][] = new int[c.length][c[0].length]; int b[][] = new int[a.length][a[0].length]; for(int i=0;i<c.length;i++) for(int j=0;j<c[0].length;j++) a[i][j] = c[i][j]; for(int i=0;i<a.length;i++) b[i][i] = 1; while(n!=1){ if(n%2 == 1){ b = matrixMultiply(a , a); n--; } a = matrixMultiply(a , a); n/=2; } return matrixMultiply(a , b); } public int [][] matrixMultiply(int a[][] , int b[][]){ int r1 = a.length; int c1 = a[0].length; int c2 = b[0].length; int c[][] = new int[r1][c2]; for(int i=0;i<r1;i++){ for(int j=0;j<c2;j++){ for(int k=0;k<c1;k++) c[i][j] += a[i][k]*b[k][j]; } } return c; } public long nCrPFermet(int n , int r , long p){ if(r==0) return 1l; long fact[] = new long[n+1]; fact[0] = 1; for(int i=1;i<=n;i++) fact[i] = (i*fact[i-1])%p; long modInverseR = pow(fact[r] , p-2 , 1l , p); long modInverseNR = pow(fact[n-r] , p-2 , 1l , p); long w = (((fact[n]*modInverseR)%p)*modInverseNR)%p; return w; } public long pow(long a , long b , long res , long mod){ if(b==0) return res; if(b==1) return (res*a)%mod; if(b%2==1){ res *= a; res %= mod; b--; } // System.out.println(a + " " + b + " " + res); return pow((a*a)%mod , b/2 , res , mod); } public long pow(long a , long b , long res){ if(b == 0) return res; if(b==1) return res*a; if(b%2==1){ res *= a; b--; } return pow(a*a , b/2 , res); } public void swap(int a[] , int p1 , int p2){ int x = a[p1]; a[p1] = a[p2]; a[p2] = x; } public void sortedArrayToBST(TreeSet<Integer> a , int start, int end) { if (start > end) { return; } int mid = (start + end) / 2; a.add(mid); sortedArrayToBST(a, start, mid - 1); sortedArrayToBST(a, mid + 1, end); } class Combine{ int value; int delete; Combine(int val , int delete){ this.value = val; this.delete = delete; } } class Sort2 implements Comparator<Combine>{ public int compare(Combine a , Combine b){ if(a.value > b.value) return 1; else if(a.value == b.value && a.delete>b.delete) return 1; else if(a.value == b.value && a.delete == b.delete) return 0; return -1; } } public int lowerLastBound(ArrayList<Integer> a , int x){ int l = 0; int r = a.size()-1; if(a.get(l)>=x) return -1; if(a.get(r)<x) return r; int mid = -1; while(l<=r){ mid = (l+r)/2; if(a.get(mid) == x && a.get(mid-1)<x) return mid-1; else if(a.get(mid)>=x) r = mid-1; else if(a.get(mid)<x && a.get(mid+1)>=x) return mid; else if(a.get(mid)<x && a.get(mid+1)<x) l = mid+1; } return mid; } public int upperFirstBound(ArrayList<Integer> a , Integer x){ int l = 0; int r = a.size()-1; if(a.get(l)>x) return l; if(a.get(r)<=x) return r+1; int mid = -1; while(l<=r){ mid = (l+r)/2; if(a.get(mid) == x && a.get(mid+1)>x) return mid+1; else if(a.get(mid)<=x) l = mid+1; else if(a.get(mid)>x && a.get(mid-1)<=x) return mid; else if(a.get(mid)>x && a.get(mid-1)>x) r = mid-1; } return mid; } public int lowerLastBound(int a[] , int x){ int l = 0; int r = a.length-1; if(a[l]>=x) return -1; if(a[r]<x) return r; int mid = -1; while(l<=r){ mid = (l+r)/2; if(a[mid] == x && a[mid-1]<x) return mid-1; else if(a[mid]>=x) r = mid-1; else if(a[mid]<x && a[mid+1]>=x) return mid; else if(a[mid]<x && a[mid+1]<x) l = mid+1; } return mid; } public int upperFirstBound(long a[] , long x){ int l = 0; int r = a.length-1; if(a[l]>x) return l; if(a[r]<=x) return r+1; int mid = -1; while(l<=r){ mid = (l+r)/2; if(a[mid] == x && a[mid+1]>x) return mid+1; else if(a[mid]<=x) l = mid+1; else if(a[mid]>x && a[mid-1]<=x) return mid; else if(a[mid]>x && a[mid-1]>x) r = mid-1; } return mid; } public long log(float number , int base){ return (long) Math.floor((Math.log(number) / Math.log(base))); } public long gcd(long a , long b){ if(a<b){ long c = b; b = a; a = c; } if(a%b==0) return b; return gcd(b , a%b); } public void print2d(long a[][] , PrintWriter out){ for(int i=0;i<a.length;i++){ for(int j=0;j<a[i].length;j++) out.print(a[i][j] + " "); out.println(); } out.println(); } public void print1d(int a[] , PrintWriter out){ for(int i=0;i<a.length;i++) out.print(a[i] + " "); out.println(); out.println(); } } 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 next() 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(); } } }
Java
["4\n7 8\nAAPAAAAA\nPPPPAAAA\nPPPPAAAA\nAPAAPPPP\nAPAPPAPP\nAAAAPPAP\nAAAAPPAA\n6 5\nAAAAA\nAAAAA\nAAPAA\nAAPAP\nAAAPP\nAAAPP\n4 4\nPPPP\nPPPP\nPPPP\nPPPP\n3 4\nPPPP\nPAAP\nPPPP"]
2 seconds
["2\n1\nMORTAL\n4"]
NoteIn the first test case, it can be done in two usages, as follows:Usage 1: Usage 2: In the second test case, it can be done with just one usage of the power. In the third test case, it is impossible to convert everyone to Beingawesomeism, so the answer is "MORTAL".
Java 8
standard input
[ "constructive algorithms", "implementation", "greedy", "math" ]
da18ca9f125d1524e7c0a2637b1fa3df
The first line of input contains a single integer $$$t$$$ ($$$1 \le t \le 2\cdot 10^4$$$) denoting the number of test cases. The first line of each test case contains two space-separated integers $$$r$$$ and $$$c$$$ denoting the dimensions of the grid ($$$1 \le r, c \le 60$$$). The next $$$r$$$ lines each contains $$$c$$$ characters describing the dominant religions in the countries. In particular, the $$$j$$$-th character in the $$$i$$$-th line describes the dominant religion in the country at the cell with row $$$i$$$ and column $$$j$$$, where: "A" means that the dominant religion is Beingawesomeism; "P" means that the dominant religion is Pushingittoofarism. It is guaranteed that the grid will only contain "A" or "P" characters. It is guaranteed that the sum of the $$$r \cdot c$$$ in a single file is at most $$$3 \cdot 10^6$$$.
1,800
For each test case, output a single line containing the minimum number of usages of your power needed to convert everyone to Beingawesomeism, or the string "MORTAL" (without quotes) if it is impossible to do so.
standard output
PASSED
5dcda8796c212ebf2a4dad3a7ed0a1f6
train_003.jsonl
1576386300
You are an all-powerful being and you have created a rectangular world. In fact, your world is so bland that it could be represented by a $$$r \times c$$$ grid. Each cell on the grid represents a country. Each country has a dominant religion. There are only two religions in your world. One of the religions is called Beingawesomeism, who do good for the sake of being good. The other religion is called Pushingittoofarism, who do murders for the sake of being bad.Oh, and you are actually not really all-powerful. You just have one power, which you can use infinitely many times! Your power involves missionary groups. When a missionary group of a certain country, say $$$a$$$, passes by another country $$$b$$$, they change the dominant religion of country $$$b$$$ to the dominant religion of country $$$a$$$.In particular, a single use of your power is this: You choose a horizontal $$$1 \times x$$$ subgrid or a vertical $$$x \times 1$$$ subgrid. That value of $$$x$$$ is up to you; You choose a direction $$$d$$$. If you chose a horizontal subgrid, your choices will either be NORTH or SOUTH. If you choose a vertical subgrid, your choices will either be EAST or WEST; You choose the number $$$s$$$ of steps; You command each country in the subgrid to send a missionary group that will travel $$$s$$$ steps towards direction $$$d$$$. In each step, they will visit (and in effect convert the dominant religion of) all $$$s$$$ countries they pass through, as detailed above. The parameters $$$x$$$, $$$d$$$, $$$s$$$ must be chosen in such a way that any of the missionary groups won't leave the grid. The following image illustrates one possible single usage of your power. Here, A represents a country with dominant religion Beingawesomeism and P represents a country with dominant religion Pushingittoofarism. Here, we've chosen a $$$1 \times 4$$$ subgrid, the direction NORTH, and $$$s = 2$$$ steps. You are a being which believes in free will, for the most part. However, you just really want to stop receiving murders that are attributed to your name. Hence, you decide to use your powers and try to make Beingawesomeism the dominant religion in every country.What is the minimum number of usages of your power needed to convert everyone to Beingawesomeism?With god, nothing is impossible. But maybe you're not god? If it is impossible to make Beingawesomeism the dominant religion in all countries, you must also admit your mortality and say so.
256 megabytes
import java.io.*; import java.util.*; public class Main { static InputReader in = new InputReader(System.in); static PrintWriter out = new PrintWriter(System.out); static int oo = (int)1e9; // static long oo = (long)1e15; static int mod = 1_000_000_007; static int[] di = {1, 0, 0, -1}; static int[] dj = {0, -1, 1, 0}; static int M = 40; static double EPS = 1e-13; public static void main(String[] args) throws IOException { int t = in.nextInt(); out: while(t --> 0) { int n = in.nextInt(); int m = in.nextInt(); char[][] a = new char[n][]; for(int i = 0; i < n; ++i) a[i] = in.readString().toCharArray(); boolean p0 = false, p1 = false, p2 = false, p3 = false; int cnt = 0; for(int i = 0; i < n; ++i) { boolean allA = true; for(int j = 0; j < m; ++j) { if(a[i][j] == 'A') { if(isCorner(n, m, i, j)) p2 = true; if(isEdge(n, m, i, j)) p3 = true; cnt++; } else allA = false; } if(allA) { if(i == 0 || i == n-1) p1 = true; else p2 = true; } } if(cnt == n * m) { p0 = true; } else if(cnt == 0) { System.out.println("MORTAL"); continue out; } for(int j = 0; j < m; ++j) { boolean allA = true; for(int i = 0; i < n; ++i) { if(a[i][j] == 'A') { } else allA = false; } if(allA) { if(j == 0 || j == m-1) p1 = true; else p2 = true; } } if(p0) System.out.println(0); else if(p1) System.out.println(1); else if(p2) System.out.println(2); else if(p3) System.out.println(3); else System.out.println(4); } out.close(); } static boolean isCorner(int n, int m, int i, int j) { return (i == 0 || i == n-1) && (j == 0 || j == m-1); } static boolean isEdge(int n, int m, int i, int j) { return i == 0 || i == n-1 || j == 0 || j == m-1; } static int find(int[] g, int x) { return g[x] = g[x] == x ? x : find(g, g[x]); } static void union(int[] g, int[] size, int x, int y) { x = find(g, x); y = find(g, y); if(x == y) return; if(size[x] < size[y]) { g[x] = y; size[y] += size[x]; } else { g[y] = x; size[x] += size[y]; } } static class Segment { Segment left, right; int size, val; int time, lazy; public Segment(int[] a, int l, int r) { super(); if(l == r) { return; } int mid = (l + r) / 2; left = new Segment(a, l, mid); right = new Segment(a, mid+1, r); } boolean covered(int ll, int rr, int l, int r) { return ll <= l && rr >= r; } boolean noIntersection(int ll, int rr, int l, int r) { return ll > r || rr < l; } void lazyPropagation() { if(lazy != 0) { if(left != null) { left.setLazy(this.time, this.lazy); right.setLazy(this.time, this.lazy); } else { val = lazy; } } } void setLazy(int time, int lazy) { if(this.time != 0 && this.time <= time) return; this.time = time; this.lazy = lazy; } int query(int ll, int rr, int l, int r) { lazyPropagation(); if(noIntersection(ll, rr, l, r)) return 0; if(covered(ll, rr, l, r)) return val; int mid = (l + r) / 2; int leftSum = left.query(ll, rr, l, mid); int rightSum = right.query(ll, rr, mid+1, r); return leftSum + rightSum; } int query(int k, int l, int r) { Segment trace = this; while(l < r) { int mid = (l + r) / 2; if(trace.left.size > k) { trace = trace.left; r = mid; } else { k -= trace.left.size; trace = trace.right; l = mid + 1; } } return l; } void update(int ll, int rr, int time, int knight, int l, int r) { lazyPropagation(); if(noIntersection(ll, rr, l, r)) return; if(covered(ll, rr, l, r)) { setLazy(time, knight); return; } int mid = (l + r) / 2; left.update(ll, rr, time, knight, l, mid); right.update(ll, rr, time, knight, mid+1, r); } } static long pow(long a, long n, long mod) { if(n == 0) return 1; if(n % 2 == 1) return a * pow(a, n-1, mod) % mod; long x = pow(a, n / 2, mod); return x * x % mod; } static int[] getPi(char[] a) { int m = a.length; int j = 0; int[] pi = new int[m]; for(int i = 1; i < m; ++i) { while(j > 0 && a[i] != a[j]) j = pi[j-1]; if(a[i] == a[j]) { pi[i] = j + 1; j++; } } return pi; } static long lcm(long a, long b) { return a * b / gcd(a, b); } static boolean nextPermutation(int[] a) { for(int i = a.length - 2; i >= 0; --i) { if(a[i] < a[i+1]) { for(int j = a.length - 1; ; --j) { if(a[i] < a[j]) { int t = a[i]; a[i] = a[j]; a[j] = t; for(i++, j = a.length - 1; i < j; ++i, --j) { t = a[i]; a[i] = a[j]; a[j] = t; } return true; } } } } return false; } static void shuffle(Object[] a) { Random r = new Random(); for(int i = a.length - 1; i > 0; --i) { int si = r.nextInt(i); Object t = a[si]; a[si] = a[i]; a[i] = t; } } static void shuffle(int[] a) { Random r = new Random(); for(int i = a.length - 1; i > 0; --i) { int si = r.nextInt(i); int t = a[si]; a[si] = a[i]; a[i] = t; } } static void shuffle(long[] a) { Random r = new Random(); for(int i = a.length - 1; i > 0; --i) { int si = r.nextInt(i); long t = a[si]; a[si] = a[i]; a[i] = t; } } static int lower_bound(int[] a, int n, int k) { int s = 0; int e = n; int m; while (e - s > 0) { m = (s + e) / 2; if (a[m] < k) s = m + 1; else e = m; } return e; } static int lower_bound(long[] a, int n, long k) { int s = 0; int e = n; int m; while (e - s > 0) { m = (s + e) / 2; if (a[m] < k) s = m + 1; else e = m; } return e; } static int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); } static long gcd(long a, long b) { return b == 0 ? a : gcd(b, a % b); } static class Pair implements Comparable<Pair> { int first, second; public Pair(int first, int second) { super(); this.first = first; this.second = second; } @Override public int compareTo(Pair o) { return this.first != o.first ? this.first - o.first : this.second - o.second; } // @Override // public int compareTo(Pair o) { // return this.first != o.first ? o.first - this.first : o.second - this.second; // } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + first; result = prime * result + second; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Pair other = (Pair) obj; if (first != other.first) return false; if (second != other.second) return false; return true; } } } 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 nextInt() { 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 nextLong() { 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[] 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 = 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; } }
Java
["4\n7 8\nAAPAAAAA\nPPPPAAAA\nPPPPAAAA\nAPAAPPPP\nAPAPPAPP\nAAAAPPAP\nAAAAPPAA\n6 5\nAAAAA\nAAAAA\nAAPAA\nAAPAP\nAAAPP\nAAAPP\n4 4\nPPPP\nPPPP\nPPPP\nPPPP\n3 4\nPPPP\nPAAP\nPPPP"]
2 seconds
["2\n1\nMORTAL\n4"]
NoteIn the first test case, it can be done in two usages, as follows:Usage 1: Usage 2: In the second test case, it can be done with just one usage of the power. In the third test case, it is impossible to convert everyone to Beingawesomeism, so the answer is "MORTAL".
Java 8
standard input
[ "constructive algorithms", "implementation", "greedy", "math" ]
da18ca9f125d1524e7c0a2637b1fa3df
The first line of input contains a single integer $$$t$$$ ($$$1 \le t \le 2\cdot 10^4$$$) denoting the number of test cases. The first line of each test case contains two space-separated integers $$$r$$$ and $$$c$$$ denoting the dimensions of the grid ($$$1 \le r, c \le 60$$$). The next $$$r$$$ lines each contains $$$c$$$ characters describing the dominant religions in the countries. In particular, the $$$j$$$-th character in the $$$i$$$-th line describes the dominant religion in the country at the cell with row $$$i$$$ and column $$$j$$$, where: "A" means that the dominant religion is Beingawesomeism; "P" means that the dominant religion is Pushingittoofarism. It is guaranteed that the grid will only contain "A" or "P" characters. It is guaranteed that the sum of the $$$r \cdot c$$$ in a single file is at most $$$3 \cdot 10^6$$$.
1,800
For each test case, output a single line containing the minimum number of usages of your power needed to convert everyone to Beingawesomeism, or the string "MORTAL" (without quotes) if it is impossible to do so.
standard output
PASSED
a5ab19a9141cf0a9a8dc93b2e2fdf0ba
train_003.jsonl
1576386300
You are an all-powerful being and you have created a rectangular world. In fact, your world is so bland that it could be represented by a $$$r \times c$$$ grid. Each cell on the grid represents a country. Each country has a dominant religion. There are only two religions in your world. One of the religions is called Beingawesomeism, who do good for the sake of being good. The other religion is called Pushingittoofarism, who do murders for the sake of being bad.Oh, and you are actually not really all-powerful. You just have one power, which you can use infinitely many times! Your power involves missionary groups. When a missionary group of a certain country, say $$$a$$$, passes by another country $$$b$$$, they change the dominant religion of country $$$b$$$ to the dominant religion of country $$$a$$$.In particular, a single use of your power is this: You choose a horizontal $$$1 \times x$$$ subgrid or a vertical $$$x \times 1$$$ subgrid. That value of $$$x$$$ is up to you; You choose a direction $$$d$$$. If you chose a horizontal subgrid, your choices will either be NORTH or SOUTH. If you choose a vertical subgrid, your choices will either be EAST or WEST; You choose the number $$$s$$$ of steps; You command each country in the subgrid to send a missionary group that will travel $$$s$$$ steps towards direction $$$d$$$. In each step, they will visit (and in effect convert the dominant religion of) all $$$s$$$ countries they pass through, as detailed above. The parameters $$$x$$$, $$$d$$$, $$$s$$$ must be chosen in such a way that any of the missionary groups won't leave the grid. The following image illustrates one possible single usage of your power. Here, A represents a country with dominant religion Beingawesomeism and P represents a country with dominant religion Pushingittoofarism. Here, we've chosen a $$$1 \times 4$$$ subgrid, the direction NORTH, and $$$s = 2$$$ steps. You are a being which believes in free will, for the most part. However, you just really want to stop receiving murders that are attributed to your name. Hence, you decide to use your powers and try to make Beingawesomeism the dominant religion in every country.What is the minimum number of usages of your power needed to convert everyone to Beingawesomeism?With god, nothing is impossible. But maybe you're not god? If it is impossible to make Beingawesomeism the dominant religion in all countries, you must also admit your mortality and say so.
256 megabytes
import java.util.*; import java.io.*; import java.io.FileWriter; import java.math.BigInteger; import java.math.BigDecimal; // Solution public class Main { public static void main (String[] argv) { new Main(); } boolean test = false; final int[][] dirs8 = {{0,1}, {0,-1}, {-1,0}, {1,0}, {1,1},{1,-1},{-1,1},{-1,-1}}; final int[][] dirs4 = {{0,1}, {0,-1}, {-1,0}, {1,0}}; final int MOD = 1000000007; //998244353; final int WALL = -1; final int EMPTY = -2; final int VISITED = 1; final int FULL = 2; final int START = 1; final int END = 0; int[] fac; int[] ifac; int[] rfac; int[] pow2; int[] mobius; int[] sieve; int[][] factors; final int UNVISITED = -2; public Main() { FastReader in = new FastReader(new BufferedReader(new InputStreamReader(System.in))); // FastReader in = new FastReader(new BufferedReader(new FileReader("Main.in"))); int nt = in.nextInt(); //int nt = 1; StringBuilder sb = new StringBuilder(); char[][] b = new char[60][60]; for (int it = 0; it < nt; it++) { //long k = in.nextLong(); int n = in.nextInt(); int m = in.nextInt(); int na = 0; for (int i = 0; i < n; i++) { String line = in.next(); for (int j = 0; j < m; j++) { b[i][j] = line.charAt(j); if (b[i][j] == 'A') na++; } } if (na == 0) sb.append("MORTAL\n"); else { if (na == n * m) sb.append("0\n"); else if (allRow(b, n, m, 0) == m || allRow(b, n, m, n-1) == m || allCol(b, n, m, 0) == n || allCol(b, n, m, m - 1) == n) sb.append("1\n"); else if (b[0][0] == 'A' || b[0][m-1] == 'A' || b[n-1][0] == 'A' || b[n-1][m-1] == 'A' || hasOne(b, n, m)) sb.append("2\n"); else if (allRow(b, n, m, 0) > 0 || allRow(b, n, m, n-1) > 0 || allCol(b, n, m, 0) > 0 || allCol(b, n, m, m - 1) > 0) sb.append("3\n"); else sb.append("4\n"); } } System.out.print(sb); } private boolean hasOne(char[][]b, int n, int m) { for (int i = 0; i < n; i++) if (allRow(b, n, m, i) == m) return true; for (int i = 0; i < m; i++) if (allCol(b, n, m, i) == n) return true; return false; } private int allCol(char[][] b, int n, int m, int r) { int c = 0; for (int i = 0; i < n; i++) if (b[i][r] == 'A') c++; return c; } private int allRow(char[][] b, int n, int m, int r) { int c = 0; for (int i = 0; i < m; i++) if (b[r][i] == 'A') c++; return c; } class Node implements Comparable<Node>{ int lo, hi; public Node(int lo, int hi) { this.lo = lo; this.hi = hi; } @Override public int compareTo(Node o){ if (lo != o.lo) return lo - o.lo; return hi - o.hi; } } private long[][] matIdentity(int n) { long[][] a = new long[n][n]; for (int i = 0; i < n; i++) a[i][i] = 1; return a; } private long[][] matPow(long[][] mat0, long p) { int n = mat0.length; long[][] ans = matIdentity(n); long[][] mat = matCopy(mat0); while (p > 0) { if (p % 2 == 1){ ans = matMul(ans, mat); } p /= 2; mat = matMul(mat, mat); } return ans; } private long[][] matCopy(long[][] a) { int n = a.length; long[][] b = new long[n][n]; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) b[i][j] = a[i][j]; return b; } private long[][] matMul(long[][] a, long[][] b) { int n = a.length; long[][] c = new long[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { for (int k = 0; k < n; k++) c[i][j] = (c[i][j] + a[i][k] * b[k][j]) % MOD; } } return c; } private long[] matMul(long[][] a, long[] b) { int n = a.length; long[] c = new long[n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) c[i] = (c[i] + a[i][j] * b[j]) % MOD; } return c; } class Mark implements Comparable<Mark> { int type, h; long x; public Mark(int h, long x, int type) { this.h = h; this.x = x; this.type = type; } @Override public int compareTo(Mark o) { if (this.x == o.x) return type - o.type; // let end comes before start return Long.compare(x, o.x); } } private boolean coLinear(int[] p, int[] q, int[] r) { return 1L * (p[1] - r[1]) * (q[0] - r[0]) == 1L * (q[1] - r[1]) * (p[0] - r[0]); } private void fill(char[] a, int lo, int c, char letter) { //System.out.println("fill " + lo + " " + c + " " + letter); for (int i = lo; i < lo + c; i++) a[i] = letter; } private int cntBitOne(String s){ int c = 0, n = s.length(); for (int i = 0; i < n; i++) if (s.charAt(i) == '1') c++; return c; } class DSU { int n; int[] par; int[] sz; int nGroup; public DSU(int n) { this.n = n; par = new int[n]; sz = new int[n]; for (int i = 0; i < n; i++){ par[i] = i; sz[i] = 1; } nGroup = n; } private boolean add(int p, int q) { int rp = find(p); int rq = find(q); if (rq == rp) return false; if (sz[rp] <= sz[rq]) { sz[rq] += sz[rp]; par[rp] = rq; }else { sz[rp] += sz[rq]; par[rq] = rp; } nGroup--; return true; } private int find(int p) { int r = p; while (par[r] != r) r = par[r]; while (r != p) { int t = par[p]; par[p] = r; p = t; } return r; } } // μ(n) = 1 if n is a square-free positive integer with an even number of prime factors. e.g. 6, 15 // μ(n) = −1 if n is a square-free positive integer with an odd number of prime factors. e.g. 2, 3, 5, 2*3*5 // μ(n) = 0 if n has a squared prime factor. e.g : 2*2, 3*3*5 private void build_pow2_function(int n) { pow2 = new int[n+1]; pow2[0] = 1; for (int i = 1; i <= n; i++) pow2[i] = (int)(1L * pow2[i-1] * 2 % MOD); } private void build_fac_function(int n) { fac = new int[n+1]; fac[0] = 1; for (int i = 1; i <= n; i++) fac[i] = (int)(1L * fac[i-1] * i % MOD); } private void build_ifac_function(int n) { ifac = new int[n+1]; ifac[0] = 1; for (int i = 1; i <= n; i++) ifac[i] = (int)(1L * ifac[i-1] * inv(i) % MOD); } private void build_sieve_function(int n) { sieve = new int[n+1]; for (int i = 2; i <= n; i++) sieve[i] = i; for (int i = 2; i <= n; i++) { if (sieve[i] == i){ for (long j = 1L * i * i; j <= n; j += i) sieve[(int)j] = i; } } } private void build_mobius_function(int n) { mobius = new int[n+1]; sieve = new int[n+1]; factors = new int[n+1][]; //for (int i = 1; i <= n; i++)factors[i] = new ArrayList<>(); for (int i = 2; i <= n; i++) sieve[i] = i; for (int i = 2; i <= n; i++) { if (sieve[i] == i){ mobius[i] = -1; for (long j = 1L * i * i; j <= n; j += i) sieve[(int)j] = i; } } for (int i = 6; i <= n; i++) { if (sieve[i] != i) { int pre = i / sieve[i]; if (pre % sieve[i] != 0) mobius[i] = -mobius[pre]; } } int[] sz = new int[n+1]; long tot = 0; for (int i = 2; i <= n; i++) { if (mobius[i] != 0) { for (int j = i * 2; j <= n; j += i) { sz[j]++; tot++; } } } for (int i = 2; i <= n; i++) { factors[i] = new int[sz[i]]; sz[i] = 0; } for (int i = 2; i <= n; i++) { if (mobius[i] != 0) { for (int j = i * 2; j <= n; j += i) { factors[j][sz[j]++] = i; //factors[j].add(i); } } } //System.out.println("tot = " + tot); } private int[] build_z_function(String s) { int n = s.length(); int[] zfun = new int[n]; int l = -1, r = -1; for (int i = 1; i < n; i++) { // Set the start value if (i <= r) zfun[i] = Math.min(zfun[i-l], r - i + 1); while (i + zfun[i] < n && s.charAt(i + zfun[i]) == s.charAt(zfun[i])) zfun[i]++; if (i + zfun[i] - 1> r){ l = i; r = i + zfun[i] - 1; } } if (test) { System.out.println("Z-function of " + s); for (int i = 0; i < n; i++) System.out.print(zfun[i] + " "); System.out.println(); } return zfun; } class BIT { int[] bit; int n; public BIT(int n){ this.n = n; bit = new int[n+1]; } private int query(int p) { int sum = 0; for (; p > 0; p -= (p & (-p))) sum += bit[p]; return sum; } private void add(int p, int val) { //System.out.println("add to BIT " + p); for (; p <= n; p += (p & (-p))) bit[p] += val; } } private List<Integer> getMinFactor(int sum) { List<Integer> factors = new ArrayList<>(); for (int sz = 2; sz <= sum / sz; sz++){ if (sum % sz == 0) { factors.add(sz); factors.add(sum / sz); } } if (factors.size() == 0) factors.add(sum); return factors; } /* Tree class */ class Tree { int V = 0; int root = 0; List<Integer>[] nbs; int[][] timeRange; int[] subTreeSize; int t; boolean dump = false; public Tree(int V, int root) { if (dump) System.out.println("build tree with size = " + V + ", root = " + root); this.V = V; this.root = root; nbs = new List[V]; subTreeSize = new int[V]; for (int i = 0; i < V; i++) nbs[i] = new ArrayList<>(); } public void doneInput() { dfsEuler(); } public void addEdge(int p, int q) { nbs[p].add(q); nbs[q].add(p); } private void dfsEuler() { timeRange = new int[V][2]; t = 1; dfs(root); } private void dfs(int node) { if (dump) System.out.println("dfs on node " + node + ", at time " + t); timeRange[node][0] = t; for (int next : nbs[node]) { if (timeRange[next][0] == 0) { ++t; dfs(next); } } timeRange[node][1] = t; subTreeSize[node] = t - timeRange[node][0] + 1; } public List<Integer> getNeighbors(int p) { return nbs[p]; } public int[] getSubTreeSize(){ return subTreeSize; } public int[][] getTimeRange() { if (dump){ for (int i = 0; i < V; i++){ System.out.println(i + ": " + timeRange[i][0] + " - " + timeRange[i][1]); } } return timeRange; } } /* segment tree */ class SegTree { int[] a; int[] tree; int[] treeMin; int[] treeMax; int[] lazy; int n; boolean dump = false; public SegTree(int n) { if (dump) System.out.println("create segTree with size " + n); this.n = n; treeMin = new int[n*4]; treeMax = new int[n*4]; lazy = new int[n*4]; } public SegTree(int n, int[] a) { this(n); this.a = a; buildTree(1, 0, n-1); } private void buildTree(int node, int lo, int hi) { if (lo == hi) { tree[node] = lo; return; } int m = (lo + hi) / 2; buildTree(node * 2, lo, m); buildTree(node * 2 + 1, m + 1, hi); pushUp(node, lo, hi); } private void pushUp(int node, int lo, int hi) { if (lo >= hi) return; // note that, if we need to call pushUp on a node, then lazy[node] must be zero. //the true value is the value + lazy treeMin[node] = Math.min(treeMin[node * 2] + lazy[node * 2], treeMin[node * 2 + 1] + lazy[node * 2 + 1]); treeMax[node] = Math.max(treeMax[node * 2] + lazy[node * 2], treeMax[node * 2 + 1] + lazy[node * 2 + 1]); // add combine fcn } private void pushDown(int node, int lo, int hi) { if (lazy[node] == 0) return; int lz = lazy[node]; lazy[node] = 0; treeMin[node] += lz; treeMax[node] += lz; if (lo == hi) return; int mid = (lo + hi) / 2; lazy[node * 2] += lz; lazy[node * 2 + 1] += lz; } public int rangeQueryMax(int fr, int to) { return rangeQueryMax(1, 0, n-1, fr, to); } public int rangeQueryMax(int node, int lo, int hi, int fr, int to) { if (lo == fr && hi == to) return treeMax[node] + lazy[node]; int mid = (lo + hi) / 2; pushDown(node, lo, hi); if (to <= mid) { return rangeQueryMax(node * 2, lo, mid, fr, to); }else if (fr > mid) return rangeQueryMax(node * 2 + 1, mid + 1, hi, fr, to); else { return Math.max(rangeQueryMax(node * 2, lo, mid, fr, mid), rangeQueryMax(node * 2 + 1, mid + 1, hi, mid + 1, to)); } } public int rangeQueryMin(int fr, int to) { return rangeQueryMin(1, 0, n-1, fr, to); } public int rangeQueryMin(int node, int lo, int hi, int fr, int to) { if (lo == fr && hi == to) return treeMin[node] + lazy[node]; int mid = (lo + hi) / 2; pushDown(node, lo, hi); if (to <= mid) { return rangeQueryMin(node * 2, lo, mid, fr, to); }else if (fr > mid) return rangeQueryMin(node * 2 + 1, mid + 1, hi, fr, to); else { return Math.min(rangeQueryMin(node * 2, lo, mid, fr, mid), rangeQueryMin(node * 2 + 1, mid + 1, hi, mid + 1, to)); } } public void rangeUpdate(int fr, int to, int delta){ rangeUpdate(1, 0, n-1, fr, to, delta); } public void rangeUpdate(int node, int lo, int hi, int fr, int to, int delta){ pushDown(node, lo, hi); if (fr == lo && to == hi) { lazy[node] = delta; return; } int m = (lo + hi) / 2; if (to <= m) rangeUpdate(node * 2, lo, m, fr, to, delta); else if (fr > m) rangeUpdate(node * 2 + 1, m + 1, hi, fr, to, delta); else { rangeUpdate(node * 2, lo, m, fr, m, delta); rangeUpdate(node * 2 + 1, m + 1, hi, m + 1, to, delta); } // re-set the in-variant pushUp(node, lo, hi); } public int query(int node, int lo, int hi, int fr, int to) { if (fr == lo && to == hi) return tree[node]; int m = (lo + hi) / 2; if (to <= m) return query(node * 2, lo, m, fr, to); else if (fr > m) return query(node * 2 + 1, m + 1, hi, fr, to); int lid = query(node * 2, lo, m, fr, m); int rid = query(node * 2 + 1, m + 1, hi, m + 1, to); return a[lid] >= a[rid] ? lid : rid; } } private long inv(long v) { return pow(v, MOD-2); } private long pow(long v, long p) { long ans = 1; while (p > 0) { if (p % 2 == 1) ans = ans * v % MOD; v = v * v % MOD; p = p / 2; } return ans; } private double dist(double x, double y, double xx, double yy) { return Math.sqrt((xx - x) * (xx - x) + (yy - y) * (yy - y)); } private int mod_add(int a, int b) { int v = a + b; if (v >= MOD) v -= MOD; return v; } private long overlap(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4) { if (x1 > x3) return overlap(x3, y3, x4, y4, x1, y1, x2, y2); if (x3 > x2 || y4 < y1 || y3 > y2) return 0L; //(x3, ?, x2, ?) int yL = Math.max(y1, y3); int yH = Math.min(y2, y4); int xH = Math.min(x2, x4); return f(x3, yL, xH, yH); } //return #black cells in rectangle private long f(int x1, int y1, int x2, int y2) { long dx = 1L + x2 - x1; long dy = 1L + y2 - y1; if (dx % 2 == 0 || dy % 2 == 0 || (x1 + y1) % 2 == 0) return 1L * dx * dy / 2; return 1L * dx * dy / 2 + 1; } private int distM(int x, int y, int xx, int yy) { return abs(x - xx) + abs(y - yy); } private boolean less(int x, int y, int xx, int yy) { return x < xx || y > yy; } private int mul(int x, int y) { return (int)(1L * x * y % MOD); } private int nBit1(int v) { int v0 = v; int c = 0; while (v != 0) { ++c; v = v & (v - 1); } return c; } private long abs(long v) { return v > 0 ? v : -v; } private int abs(int v) { return v > 0 ? v : -v; } private int common(int v) { int c = 0; while (v != 1) { v = (v >>> 1); ++c; } return c; } private void reverse(char[] a, int i, int j) { while (i < j) { swap(a, i++, j--); } } private void swap(char[] a, int i, int j) { char t = a[i]; a[i] = a[j]; a[j] = t; } private int gcd(int x, int y) { if (y == 0) return x; return gcd(y, x % y); } private long gcd(long x, long y) { if (y == 0) return x; return gcd(y, x % y); } private int max(int a, int b) { return a > b ? a : b; } private long max(long a, long b) { return a > b ? a : b; } private int min(int a, int b) { return a > b ? b : a; } private long min(long a, long b) { return a > b ? b : a; } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader(BufferedReader in) { br = in; } String next() { while (st == null || !st.hasMoreElements()) { try { String line = br.readLine(); if (line == null || line.length() == 0) return ""; st = new StringTokenizer(line); } catch (IOException e) { return ""; //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) { return null; //e.printStackTrace(); } return str; } } }
Java
["4\n7 8\nAAPAAAAA\nPPPPAAAA\nPPPPAAAA\nAPAAPPPP\nAPAPPAPP\nAAAAPPAP\nAAAAPPAA\n6 5\nAAAAA\nAAAAA\nAAPAA\nAAPAP\nAAAPP\nAAAPP\n4 4\nPPPP\nPPPP\nPPPP\nPPPP\n3 4\nPPPP\nPAAP\nPPPP"]
2 seconds
["2\n1\nMORTAL\n4"]
NoteIn the first test case, it can be done in two usages, as follows:Usage 1: Usage 2: In the second test case, it can be done with just one usage of the power. In the third test case, it is impossible to convert everyone to Beingawesomeism, so the answer is "MORTAL".
Java 8
standard input
[ "constructive algorithms", "implementation", "greedy", "math" ]
da18ca9f125d1524e7c0a2637b1fa3df
The first line of input contains a single integer $$$t$$$ ($$$1 \le t \le 2\cdot 10^4$$$) denoting the number of test cases. The first line of each test case contains two space-separated integers $$$r$$$ and $$$c$$$ denoting the dimensions of the grid ($$$1 \le r, c \le 60$$$). The next $$$r$$$ lines each contains $$$c$$$ characters describing the dominant religions in the countries. In particular, the $$$j$$$-th character in the $$$i$$$-th line describes the dominant religion in the country at the cell with row $$$i$$$ and column $$$j$$$, where: "A" means that the dominant religion is Beingawesomeism; "P" means that the dominant religion is Pushingittoofarism. It is guaranteed that the grid will only contain "A" or "P" characters. It is guaranteed that the sum of the $$$r \cdot c$$$ in a single file is at most $$$3 \cdot 10^6$$$.
1,800
For each test case, output a single line containing the minimum number of usages of your power needed to convert everyone to Beingawesomeism, or the string "MORTAL" (without quotes) if it is impossible to do so.
standard output
PASSED
6f9f2da60dc435130c56ccfe5471bc44
train_003.jsonl
1576386300
You are an all-powerful being and you have created a rectangular world. In fact, your world is so bland that it could be represented by a $$$r \times c$$$ grid. Each cell on the grid represents a country. Each country has a dominant religion. There are only two religions in your world. One of the religions is called Beingawesomeism, who do good for the sake of being good. The other religion is called Pushingittoofarism, who do murders for the sake of being bad.Oh, and you are actually not really all-powerful. You just have one power, which you can use infinitely many times! Your power involves missionary groups. When a missionary group of a certain country, say $$$a$$$, passes by another country $$$b$$$, they change the dominant religion of country $$$b$$$ to the dominant religion of country $$$a$$$.In particular, a single use of your power is this: You choose a horizontal $$$1 \times x$$$ subgrid or a vertical $$$x \times 1$$$ subgrid. That value of $$$x$$$ is up to you; You choose a direction $$$d$$$. If you chose a horizontal subgrid, your choices will either be NORTH or SOUTH. If you choose a vertical subgrid, your choices will either be EAST or WEST; You choose the number $$$s$$$ of steps; You command each country in the subgrid to send a missionary group that will travel $$$s$$$ steps towards direction $$$d$$$. In each step, they will visit (and in effect convert the dominant religion of) all $$$s$$$ countries they pass through, as detailed above. The parameters $$$x$$$, $$$d$$$, $$$s$$$ must be chosen in such a way that any of the missionary groups won't leave the grid. The following image illustrates one possible single usage of your power. Here, A represents a country with dominant religion Beingawesomeism and P represents a country with dominant religion Pushingittoofarism. Here, we've chosen a $$$1 \times 4$$$ subgrid, the direction NORTH, and $$$s = 2$$$ steps. You are a being which believes in free will, for the most part. However, you just really want to stop receiving murders that are attributed to your name. Hence, you decide to use your powers and try to make Beingawesomeism the dominant religion in every country.What is the minimum number of usages of your power needed to convert everyone to Beingawesomeism?With god, nothing is impossible. But maybe you're not god? If it is impossible to make Beingawesomeism the dominant religion in all countries, you must also admit your mortality and say so.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } static class TaskD { public void solve(int testNumber, InputReader in, PrintWriter out) { int T = in.nextInt(); for (int iter = 0; iter < T; iter++) { int r = in.nextInt(); int c = in.nextInt(); char[][] board = new char[r][c]; for (int i = 0; i < r; i++) { board[i] = in.next().toCharArray(); } if (only(board, r, c)) { out.println(0); } else if (isSide(board, r, c)) { out.println(1); } else if ((board[0][0] == 'A') || (board[r - 1][0] == 'A') || (board[r - 1][c - 1] == 'A') || (board[0][c - 1] == 'A') || (isRow(board, r, c)) || (isCol(board, r, c))) { out.println(2); } else if (containsOnSide(board, r, c)) { out.println(3); } else if (contains(board)) { out.println(4); } else { out.println("MORTAL"); } } } public boolean only(char[][] board, int r, int c) { for (int i = 0; i < r; i++) { for (int j = 0; j < c; j++) { if (board[i][j] == 'P') { return false; } } } return true; } public boolean contains(char[][] c) { for (int i = 0; i < c.length; i++) { for (int j = 0; j < c[0].length; j++) { if (c[i][j] == 'A') { return true; } } } return false; } boolean isRow(char[][] board, int r, int c) { for (int i = 0; i < r; i++) { boolean flag = true; for (int j = 0; j < c; j++) { if (board[i][j] == 'P') { flag = false; break; } } if (flag) { return flag; } } return false; } boolean isCol(char[][] board, int r, int c) { for (int i = 0; i < c; i++) { boolean flag = true; for (int j = 0; j < r; j++) { if (board[j][i] == 'P') { flag = false; break; } } if (flag) { return flag; } } return false; } boolean containsOnSide(char[][] board, int r, int c) { for (int i = 0; i < c; i++) { if (board[0][i] == 'A') { return true; } } for (int i = 0; i < c; i++) { if (board[r - 1][i] == 'A') { return true; } } for (int i = 0; i < r; i++) { if (board[i][0] == 'A') { return true; } } for (int i = 0; i < r; i++) { if (board[i][c - 1] == 'A') { return true; } } return false; } boolean isSide(char[][] board, int r, int c) { boolean top = true; for (int i = 0; i < c; i++) { if (board[0][i] == 'P') { top = false; break; } } boolean bot = true; for (int i = 0; i < c; i++) { if (board[r - 1][i] == 'P') { bot = false; break; } } boolean left = true; for (int i = 0; i < r; i++) { if (board[i][0] == 'P') { left = false; break; } } boolean right = true; for (int i = 0; i < r; i++) { if (board[i][c - 1] == 'P') { right = false; break; } } return (right || left || top || bot); } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["4\n7 8\nAAPAAAAA\nPPPPAAAA\nPPPPAAAA\nAPAAPPPP\nAPAPPAPP\nAAAAPPAP\nAAAAPPAA\n6 5\nAAAAA\nAAAAA\nAAPAA\nAAPAP\nAAAPP\nAAAPP\n4 4\nPPPP\nPPPP\nPPPP\nPPPP\n3 4\nPPPP\nPAAP\nPPPP"]
2 seconds
["2\n1\nMORTAL\n4"]
NoteIn the first test case, it can be done in two usages, as follows:Usage 1: Usage 2: In the second test case, it can be done with just one usage of the power. In the third test case, it is impossible to convert everyone to Beingawesomeism, so the answer is "MORTAL".
Java 8
standard input
[ "constructive algorithms", "implementation", "greedy", "math" ]
da18ca9f125d1524e7c0a2637b1fa3df
The first line of input contains a single integer $$$t$$$ ($$$1 \le t \le 2\cdot 10^4$$$) denoting the number of test cases. The first line of each test case contains two space-separated integers $$$r$$$ and $$$c$$$ denoting the dimensions of the grid ($$$1 \le r, c \le 60$$$). The next $$$r$$$ lines each contains $$$c$$$ characters describing the dominant religions in the countries. In particular, the $$$j$$$-th character in the $$$i$$$-th line describes the dominant religion in the country at the cell with row $$$i$$$ and column $$$j$$$, where: "A" means that the dominant religion is Beingawesomeism; "P" means that the dominant religion is Pushingittoofarism. It is guaranteed that the grid will only contain "A" or "P" characters. It is guaranteed that the sum of the $$$r \cdot c$$$ in a single file is at most $$$3 \cdot 10^6$$$.
1,800
For each test case, output a single line containing the minimum number of usages of your power needed to convert everyone to Beingawesomeism, or the string "MORTAL" (without quotes) if it is impossible to do so.
standard output
PASSED
c43f2d45814ec8cc5dbccb7cd77656e0
train_003.jsonl
1576386300
You are an all-powerful being and you have created a rectangular world. In fact, your world is so bland that it could be represented by a $$$r \times c$$$ grid. Each cell on the grid represents a country. Each country has a dominant religion. There are only two religions in your world. One of the religions is called Beingawesomeism, who do good for the sake of being good. The other religion is called Pushingittoofarism, who do murders for the sake of being bad.Oh, and you are actually not really all-powerful. You just have one power, which you can use infinitely many times! Your power involves missionary groups. When a missionary group of a certain country, say $$$a$$$, passes by another country $$$b$$$, they change the dominant religion of country $$$b$$$ to the dominant religion of country $$$a$$$.In particular, a single use of your power is this: You choose a horizontal $$$1 \times x$$$ subgrid or a vertical $$$x \times 1$$$ subgrid. That value of $$$x$$$ is up to you; You choose a direction $$$d$$$. If you chose a horizontal subgrid, your choices will either be NORTH or SOUTH. If you choose a vertical subgrid, your choices will either be EAST or WEST; You choose the number $$$s$$$ of steps; You command each country in the subgrid to send a missionary group that will travel $$$s$$$ steps towards direction $$$d$$$. In each step, they will visit (and in effect convert the dominant religion of) all $$$s$$$ countries they pass through, as detailed above. The parameters $$$x$$$, $$$d$$$, $$$s$$$ must be chosen in such a way that any of the missionary groups won't leave the grid. The following image illustrates one possible single usage of your power. Here, A represents a country with dominant religion Beingawesomeism and P represents a country with dominant religion Pushingittoofarism. Here, we've chosen a $$$1 \times 4$$$ subgrid, the direction NORTH, and $$$s = 2$$$ steps. You are a being which believes in free will, for the most part. However, you just really want to stop receiving murders that are attributed to your name. Hence, you decide to use your powers and try to make Beingawesomeism the dominant religion in every country.What is the minimum number of usages of your power needed to convert everyone to Beingawesomeism?With god, nothing is impossible. But maybe you're not god? If it is impossible to make Beingawesomeism the dominant religion in all countries, you must also admit your mortality and say so.
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; // written by luchy0120 public class Main { public static void main(String[] args) throws Exception { new Main().run(); } int color[],dfn[],low[],stack[],cnt[]; boolean vis[]; boolean iscut[]; int deep,top,n,m,sum,ans; List<Integer> g[]; void tarjan(int u,int fa) { int child = 0; dfn[u]=++deep; low[u]=deep; vis[u]=true; stack[++top]=u; int sz=g[u].size(); for(int i=0;i<sz;i++) { int v =g[u].get(i); if(v==fa) continue; if(dfn[v]==0) { child++; tarjan(v,u); low[u]=Math.min(low[u],low[v]); } else { if(vis[v]) { low[u]=Math.min(low[u],low[v]); } } } if(fa<0&&child==1){ iscut[u] =true; } if(dfn[u]==low[u]) { iscut[u] = true; color[u]=++sum; vis[u]=false; while(stack[top]!=u) { color[stack[top]]=sum; vis[stack[top--]]=false; } top--; } } boolean hasV = false; boolean hasU = false; long ct = 0; void dfs(int u,int fa,int a,int b){ ct++; vis[u] = true; int sz=g[u].size(); for(int i=0;i<sz;i++) { int v = g[u].get(i); if (v == fa) continue; if(vis[v]) continue; if(v==a){ hasV = true; continue; } if(v==b){ hasU = true; continue; } dfs(v,u,a,b); } } // void solve() { // // } // int get_room(int i,int j){ // return i/3*3 + j/3; // } // int a[][] = new int[9][9]; // int space = 0; // // boolean vis_row[][] = new boolean[9][10]; // boolean vis_col[][] = new boolean[9][10]; // boolean vis_room[][] = new boolean[9][10]; // int val[][][] =new int[9][9][]; // int prepare[][]; // // void dfs(int rt){ // // } void solve(){ int t =ni(); ot:for(int i=0;i<t;++i) { int r = ni(); int c = ni(); char mp[][] = nm(r, c); int z = 0; int x = 0; for (int j = 0; j < r; ++j) { for (int k = 0; k < c; ++k) { if (mp[j][k] == 'A') { z++; } else { x++; } } } if (z == r * c) { println(0); continue; } else if (x == r * c) { println("MORTAL"); continue; } int z1 = 0; int zr = 0; for (int j = 0; j < c; ++j) { z1 += mp[0][j] == 'A' ? 1 : 0; zr += mp[r - 1][j] == 'A' ? 1 : 0; } int z2 = 0; int zc = 0; for (int j = 0; j < r; ++j) { z2 += mp[j][0] == 'A' ? 1 : 0; zc += mp[j][c - 1] == 'A' ? 1 : 0; } if(z1==c||zr==c||z2==r||zc==r){ println(1);continue; } if(z1==0&&zr==0&&z2==0&&zc==0){ println(4);continue; } if(mp[0][0]=='A'||mp[0][c-1]=='A'||mp[r-1][0]=='A'||mp[r-1][c-1]=='A'){ println(2);continue ; } int sum[][] = new int[c][r+1]; int sum1[][] = new int[c+1][r]; for(int j=0;j<r;++j){ for(int l=0;l<c;++l){ sum[l][j+1] = sum[l][j] + (mp[j][l]=='A'?1:0); sum1[l+1][j] = sum1[l][j] + (mp[j][l]=='A'?1:0); } } for(int j=0;j<r;++j){ for(int k=j;k<r;++k){ boolean ok = false; for(int l=0;l<c;++l){ if(sum[l][k+1]-sum[l][j]==k-j+1){ ok = true; } } int ck1 = sum[0][j] + sum[0][r]-sum[0][k+1]; int ck2 = sum[c-1][j] + sum[c-1][r]-sum[c-1][k+1]; if(ok&&(ck1+k-j+1==r||ck2+k-j+1==r)){ println(2);continue ot; } } } for(int j=0;j<c;++j){ for(int k=j;k<c;++k){ boolean ok = false; for(int l=0;l<r;++l){ if(sum1[k+1][l]-sum1[j][l]==k-j+1){ ok = true; } } int ck1 = sum1[j][0] + sum1[c][0]-sum1[k+1][0]; int ck2 = sum1[j][r-1] + sum1[c][r-1]-sum1[k+1][r-1]; if(ok&&(ck1+k-j+1==c||ck2+k-j+1==c)){ println(2);continue ot; } } } println(3); } } // int gt(char v){ // if(v=='('){ // return 4; // }else if(v=='+'||v=='-'){ // return 1; // }else if(v=='8'){ // return 2; // } // return 3; // } // // void solve() { // String s = ns(); // int n = ni(); // // '(' 4 '+' 1 '-' 1 '*' 2 '^' 3 // // long mod = 100007; // ot: // for (int i = 0; i < n; ++i) { // char[] p = ns().toCharArray(); // int len = p.length; // int op = 0; // for (int j = 0; j < len; ++j) { // if (p[j] == '(') { // op++; // } else if (p[j] == ')') { // op--; // } // if (op < 0) { // continue ot; // } // } // // for(long val = 1;val<=1000;++val) { // char stop[] = new char[len]; // int p1 = 0; // long stnum[] = new long[len]; // int p2 = 0; // long cur = 0; // for (int j = 0; j < len; ) { // if (p[j] == '(') { // stop[p1++] = p[j]; // j++; // } else if (p[j] == ')') { // j++; // while(stop[p1-1]!='('){ // p1--; // char c = stop[p1]; // long op1 = stnum[--p2]; // long op2 = stnum[--p2]; // if (c == '+') { // stnum[p2++] = (op1 + op2) % mod; // } else if (c == '-') { // stnum[p2++] = (op2 - op1) % mod; // } else if (c == '*') { // stnum[p2++] = (op2 * op1) % mod; // } else if (c == '^') { // stnum[p2++] = mod_pow(op2, op1, mod); // } // } // p1--; // } else if (p[j] >= '0' && p[j] <= '9') { // while (j < len && p[j] >= '0' && p[j] <= '9') { // cur = cur * 10 + (p[j] - '0'); // j++; // } // stnum[p2++] = cur; // cur = 0; // } else if (p[j] == 'a') { // stnum[p2++] = val; // } else { // int me = gt(p[j]); // if (p1 > 0 && gt(stop[p1 - 1]) >= me) { // p1--; // char c = stop[p1]; // long op1 = stnum[--p2]; // long op2 = stnum[--p2]; // if (c == '+') { // stnum[p2++] = (op1 + op2) % mod; // } else if (c == '-') { // stnum[p2++] = (op2 - op1) % mod; // } else if (c == '*') { // stnum[p2++] = (op2 * op1) % mod; // } else if (c == '^') { // stnum[p2++] = mod_pow(op2, op1, mod); // } // } // stop[p1++] = p[j]; // } // } // while (p1 > 0) { // p1--; // char c = stop[p1]; // long op1 = stnum[--p2]; // long op2 = stnum[--p2]; // if (c == '+') { // stnum[p2++] = (op1 + op2) % mod; // } else if (c == '-') { // stnum[p2++] = (op2 - op1) % mod; // } else if (c == '*') { // stnum[p2++] = (op2 * op1) % mod; // } else if (c == '^') { // stnum[p2++] = mod_pow(op2, op1, mod); // } // } // long res= stnum[0]; // } // // // } // } // // // // // // // // // // // // // // // // // // // // // // // // // // // // } static long mul(long a, long b, long p) { long res=0,base=a; while(b>0) { if((b&1L)>0) res=(res+base)%p; base=(base+base)%p; b>>=1; } return res; } static long mod_pow(long k,long n,long p){ long res = 1L; long temp = k%p; while(n!=0L){ if((n&1L)==1L){ res = mul(res,temp,p); } temp = mul(temp,temp,p); n = n>>1L; } return res%p; } public static String roundS(double result, int scale){ String fmt = String.format("%%.%df", scale); return String.format(fmt, result); } // void solve() { // // for(int i=0;i<9;++i) { // for (int j = 0; j < 9; ++j) { // int v = ni(); // a[i][j] = v; // if(v>0) { // vis_row[i][v] = true; // vis_col[j][v] = true; // vis_room[get_room(i, j)][v] = true; // }else{ // space++; // } // } // } // // // prepare = new int[space][2]; // // int p = 0; // // for(int i=0;i<9;++i) { // for (int j = 0; j < 9; ++j) { // if(a[i][j]==0){ // prepare[p][0] = i; // prepare[p][1]= j;p++; // List<Integer> temp =new ArrayList<>(); // for(int k=1;k<=9;++k){ // if(!vis_col[j][k]&&!vis_row[i][k]&&!vis_room[get_room(i,j)][k]){ // temp.add(k); // } // } // int sz = temp.size(); // val[i][j] = new int[sz]; // for(int k=0;k<sz;++k){ // val[i][j][k] = temp.get(k); // } // } // } // } // Arrays.sort(prepare,(x,y)->{ // return Integer.compare(val[x[0]][x[1]].length,val[y[0]][y[1]].length); // }); // dfs(0); // // // // // // // // // // // } InputStream is; PrintWriter out; void run() throws Exception { is = System.in; out = new PrintWriter(System.out); solve(); out.flush(); } 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 char ncc() { int b = readByte(); return (char) b; } 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 String nline() { int b = skip(); StringBuilder sb = new StringBuilder(); while (!isSpaceChar(b) || b == ' ') { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private char[][] nm(int n, int m) { char[][] a = new char[n][]; for (int i = 0; i < n; i++) a[i] = ns(m); return a; } private int[] na(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = ni(); return a; } private long[] nal(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nl(); 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 << 3) + (num << 1) + (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(); } } void print(Object obj) { out.print(obj); } void println(Object obj) { out.println(obj); } void println() { out.println(); } void printArray(int a[],int from){ int l = a.length; for(int i=from;i<l;++i){ print(a[i]); if(i!=l-1){ print(" "); } } println(); } void printArray(long a[],int from){ int l = a.length; for(int i=from;i<l;++i){ print(a[i]); if(i!=l-1){ print(" "); } } println(); } }
Java
["4\n7 8\nAAPAAAAA\nPPPPAAAA\nPPPPAAAA\nAPAAPPPP\nAPAPPAPP\nAAAAPPAP\nAAAAPPAA\n6 5\nAAAAA\nAAAAA\nAAPAA\nAAPAP\nAAAPP\nAAAPP\n4 4\nPPPP\nPPPP\nPPPP\nPPPP\n3 4\nPPPP\nPAAP\nPPPP"]
2 seconds
["2\n1\nMORTAL\n4"]
NoteIn the first test case, it can be done in two usages, as follows:Usage 1: Usage 2: In the second test case, it can be done with just one usage of the power. In the third test case, it is impossible to convert everyone to Beingawesomeism, so the answer is "MORTAL".
Java 8
standard input
[ "constructive algorithms", "implementation", "greedy", "math" ]
da18ca9f125d1524e7c0a2637b1fa3df
The first line of input contains a single integer $$$t$$$ ($$$1 \le t \le 2\cdot 10^4$$$) denoting the number of test cases. The first line of each test case contains two space-separated integers $$$r$$$ and $$$c$$$ denoting the dimensions of the grid ($$$1 \le r, c \le 60$$$). The next $$$r$$$ lines each contains $$$c$$$ characters describing the dominant religions in the countries. In particular, the $$$j$$$-th character in the $$$i$$$-th line describes the dominant religion in the country at the cell with row $$$i$$$ and column $$$j$$$, where: "A" means that the dominant religion is Beingawesomeism; "P" means that the dominant religion is Pushingittoofarism. It is guaranteed that the grid will only contain "A" or "P" characters. It is guaranteed that the sum of the $$$r \cdot c$$$ in a single file is at most $$$3 \cdot 10^6$$$.
1,800
For each test case, output a single line containing the minimum number of usages of your power needed to convert everyone to Beingawesomeism, or the string "MORTAL" (without quotes) if it is impossible to do so.
standard output
PASSED
4c4f57ed6c5898a3065bb0d291947326
train_003.jsonl
1576386300
You are an all-powerful being and you have created a rectangular world. In fact, your world is so bland that it could be represented by a $$$r \times c$$$ grid. Each cell on the grid represents a country. Each country has a dominant religion. There are only two religions in your world. One of the religions is called Beingawesomeism, who do good for the sake of being good. The other religion is called Pushingittoofarism, who do murders for the sake of being bad.Oh, and you are actually not really all-powerful. You just have one power, which you can use infinitely many times! Your power involves missionary groups. When a missionary group of a certain country, say $$$a$$$, passes by another country $$$b$$$, they change the dominant religion of country $$$b$$$ to the dominant religion of country $$$a$$$.In particular, a single use of your power is this: You choose a horizontal $$$1 \times x$$$ subgrid or a vertical $$$x \times 1$$$ subgrid. That value of $$$x$$$ is up to you; You choose a direction $$$d$$$. If you chose a horizontal subgrid, your choices will either be NORTH or SOUTH. If you choose a vertical subgrid, your choices will either be EAST or WEST; You choose the number $$$s$$$ of steps; You command each country in the subgrid to send a missionary group that will travel $$$s$$$ steps towards direction $$$d$$$. In each step, they will visit (and in effect convert the dominant religion of) all $$$s$$$ countries they pass through, as detailed above. The parameters $$$x$$$, $$$d$$$, $$$s$$$ must be chosen in such a way that any of the missionary groups won't leave the grid. The following image illustrates one possible single usage of your power. Here, A represents a country with dominant religion Beingawesomeism and P represents a country with dominant religion Pushingittoofarism. Here, we've chosen a $$$1 \times 4$$$ subgrid, the direction NORTH, and $$$s = 2$$$ steps. You are a being which believes in free will, for the most part. However, you just really want to stop receiving murders that are attributed to your name. Hence, you decide to use your powers and try to make Beingawesomeism the dominant religion in every country.What is the minimum number of usages of your power needed to convert everyone to Beingawesomeism?With god, nothing is impossible. But maybe you're not god? If it is impossible to make Beingawesomeism the dominant religion in all countries, you must also admit your mortality and say so.
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; // written by luchy0120 public class Main { public static void main(String[] args) throws Exception { new Main().run(); } int color[],dfn[],low[],stack[],cnt[]; boolean vis[]; boolean iscut[]; int deep,top,n,m,sum,ans; List<Integer> g[]; void tarjan(int u,int fa) { int child = 0; dfn[u]=++deep; low[u]=deep; vis[u]=true; stack[++top]=u; int sz=g[u].size(); for(int i=0;i<sz;i++) { int v =g[u].get(i); if(v==fa) continue; if(dfn[v]==0) { child++; tarjan(v,u); low[u]=Math.min(low[u],low[v]); } else { if(vis[v]) { low[u]=Math.min(low[u],low[v]); } } } if(fa<0&&child==1){ iscut[u] =true; } if(dfn[u]==low[u]) { iscut[u] = true; color[u]=++sum; vis[u]=false; while(stack[top]!=u) { color[stack[top]]=sum; vis[stack[top--]]=false; } top--; } } boolean hasV = false; boolean hasU = false; long ct = 0; void dfs(int u,int fa,int a,int b){ ct++; vis[u] = true; int sz=g[u].size(); for(int i=0;i<sz;i++) { int v = g[u].get(i); if (v == fa) continue; if(vis[v]) continue; if(v==a){ hasV = true; continue; } if(v==b){ hasU = true; continue; } dfs(v,u,a,b); } } // void solve() { // // } // int get_room(int i,int j){ // return i/3*3 + j/3; // } // int a[][] = new int[9][9]; // int space = 0; // // boolean vis_row[][] = new boolean[9][10]; // boolean vis_col[][] = new boolean[9][10]; // boolean vis_room[][] = new boolean[9][10]; // int val[][][] =new int[9][9][]; // int prepare[][]; // // void dfs(int rt){ // // } void solve(){ int t =ni(); ot:for(int i=0;i<t;++i) { int r = ni(); int c = ni(); char mp[][] = nm(r, c); int z = 0; int x = 0; for (int j = 0; j < r; ++j) { for (int k = 0; k < c; ++k) { if (mp[j][k] == 'A') { z++; } else { x++; } } } if (z == r * c) { println(0); continue; } else if (x == r * c) { println("MORTAL"); continue; } int z1 = 0; int zr = 0; for (int j = 0; j < c; ++j) { z1 += mp[0][j] == 'A' ? 1 : 0; zr += mp[r - 1][j] == 'A' ? 1 : 0; } int z2 = 0; int zc = 0; for (int j = 0; j < r; ++j) { z2 += mp[j][0] == 'A' ? 1 : 0; zc += mp[j][c - 1] == 'A' ? 1 : 0; } if(z1==c||zr==c||z2==r||zc==r){ println(1);continue; } if(z1==0&&zr==0&&z2==0&&zc==0){ println(4);continue; } int sum[][] = new int[c][r+1]; int sum1[][] = new int[c+1][r]; for(int j=0;j<r;++j){ for(int l=0;l<c;++l){ sum[l][j+1] = sum[l][j] + (mp[j][l]=='A'?1:0); sum1[l+1][j] = sum1[l][j] + (mp[j][l]=='A'?1:0); } } for(int j=0;j<r;++j){ for(int k=j;k<r;++k){ boolean ok = false; for(int l=0;l<c;++l){ if(sum[l][k+1]-sum[l][j]==k-j+1){ ok = true; } } int ck1 = sum[0][j] + sum[0][r]-sum[0][k+1]; int ck2 = sum[c-1][j] + sum[c-1][r]-sum[c-1][k+1]; if(ok&&(ck1+k-j+1==r||ck2+k-j+1==r)){ println(2);continue ot; } } } for(int j=0;j<c;++j){ for(int k=j;k<c;++k){ boolean ok = false; for(int l=0;l<r;++l){ if(sum1[k+1][l]-sum1[j][l]==k-j+1){ ok = true; } } int ck1 = sum1[j][0] + sum1[c][0]-sum1[k+1][0]; int ck2 = sum1[j][r-1] + sum1[c][r-1]-sum1[k+1][r-1]; if(ok&&(ck1+k-j+1==c||ck2+k-j+1==c)){ println(2);continue ot; } } } if(mp[0][0]=='A'||mp[0][c-1]=='A'||mp[r-1][0]=='A'||mp[r-1][c-1]=='A'){ println(2);continue ; } println(3); } } // int gt(char v){ // if(v=='('){ // return 4; // }else if(v=='+'||v=='-'){ // return 1; // }else if(v=='8'){ // return 2; // } // return 3; // } // // void solve() { // String s = ns(); // int n = ni(); // // '(' 4 '+' 1 '-' 1 '*' 2 '^' 3 // // long mod = 100007; // ot: // for (int i = 0; i < n; ++i) { // char[] p = ns().toCharArray(); // int len = p.length; // int op = 0; // for (int j = 0; j < len; ++j) { // if (p[j] == '(') { // op++; // } else if (p[j] == ')') { // op--; // } // if (op < 0) { // continue ot; // } // } // // for(long val = 1;val<=1000;++val) { // char stop[] = new char[len]; // int p1 = 0; // long stnum[] = new long[len]; // int p2 = 0; // long cur = 0; // for (int j = 0; j < len; ) { // if (p[j] == '(') { // stop[p1++] = p[j]; // j++; // } else if (p[j] == ')') { // j++; // while(stop[p1-1]!='('){ // p1--; // char c = stop[p1]; // long op1 = stnum[--p2]; // long op2 = stnum[--p2]; // if (c == '+') { // stnum[p2++] = (op1 + op2) % mod; // } else if (c == '-') { // stnum[p2++] = (op2 - op1) % mod; // } else if (c == '*') { // stnum[p2++] = (op2 * op1) % mod; // } else if (c == '^') { // stnum[p2++] = mod_pow(op2, op1, mod); // } // } // p1--; // } else if (p[j] >= '0' && p[j] <= '9') { // while (j < len && p[j] >= '0' && p[j] <= '9') { // cur = cur * 10 + (p[j] - '0'); // j++; // } // stnum[p2++] = cur; // cur = 0; // } else if (p[j] == 'a') { // stnum[p2++] = val; // } else { // int me = gt(p[j]); // if (p1 > 0 && gt(stop[p1 - 1]) >= me) { // p1--; // char c = stop[p1]; // long op1 = stnum[--p2]; // long op2 = stnum[--p2]; // if (c == '+') { // stnum[p2++] = (op1 + op2) % mod; // } else if (c == '-') { // stnum[p2++] = (op2 - op1) % mod; // } else if (c == '*') { // stnum[p2++] = (op2 * op1) % mod; // } else if (c == '^') { // stnum[p2++] = mod_pow(op2, op1, mod); // } // } // stop[p1++] = p[j]; // } // } // while (p1 > 0) { // p1--; // char c = stop[p1]; // long op1 = stnum[--p2]; // long op2 = stnum[--p2]; // if (c == '+') { // stnum[p2++] = (op1 + op2) % mod; // } else if (c == '-') { // stnum[p2++] = (op2 - op1) % mod; // } else if (c == '*') { // stnum[p2++] = (op2 * op1) % mod; // } else if (c == '^') { // stnum[p2++] = mod_pow(op2, op1, mod); // } // } // long res= stnum[0]; // } // // // } // } // // // // // // // // // // // // // // // // // // // // // // // // // // // // } static long mul(long a, long b, long p) { long res=0,base=a; while(b>0) { if((b&1L)>0) res=(res+base)%p; base=(base+base)%p; b>>=1; } return res; } static long mod_pow(long k,long n,long p){ long res = 1L; long temp = k%p; while(n!=0L){ if((n&1L)==1L){ res = mul(res,temp,p); } temp = mul(temp,temp,p); n = n>>1L; } return res%p; } public static String roundS(double result, int scale){ String fmt = String.format("%%.%df", scale); return String.format(fmt, result); } // void solve() { // // for(int i=0;i<9;++i) { // for (int j = 0; j < 9; ++j) { // int v = ni(); // a[i][j] = v; // if(v>0) { // vis_row[i][v] = true; // vis_col[j][v] = true; // vis_room[get_room(i, j)][v] = true; // }else{ // space++; // } // } // } // // // prepare = new int[space][2]; // // int p = 0; // // for(int i=0;i<9;++i) { // for (int j = 0; j < 9; ++j) { // if(a[i][j]==0){ // prepare[p][0] = i; // prepare[p][1]= j;p++; // List<Integer> temp =new ArrayList<>(); // for(int k=1;k<=9;++k){ // if(!vis_col[j][k]&&!vis_row[i][k]&&!vis_room[get_room(i,j)][k]){ // temp.add(k); // } // } // int sz = temp.size(); // val[i][j] = new int[sz]; // for(int k=0;k<sz;++k){ // val[i][j][k] = temp.get(k); // } // } // } // } // Arrays.sort(prepare,(x,y)->{ // return Integer.compare(val[x[0]][x[1]].length,val[y[0]][y[1]].length); // }); // dfs(0); // // // // // // // // // // // } InputStream is; PrintWriter out; void run() throws Exception { is = System.in; out = new PrintWriter(System.out); solve(); out.flush(); } 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 char ncc() { int b = readByte(); return (char) b; } 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 String nline() { int b = skip(); StringBuilder sb = new StringBuilder(); while (!isSpaceChar(b) || b == ' ') { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private char[][] nm(int n, int m) { char[][] a = new char[n][]; for (int i = 0; i < n; i++) a[i] = ns(m); return a; } private int[] na(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = ni(); return a; } private long[] nal(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nl(); 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 << 3) + (num << 1) + (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(); } } void print(Object obj) { out.print(obj); } void println(Object obj) { out.println(obj); } void println() { out.println(); } void printArray(int a[],int from){ int l = a.length; for(int i=from;i<l;++i){ print(a[i]); if(i!=l-1){ print(" "); } } println(); } void printArray(long a[],int from){ int l = a.length; for(int i=from;i<l;++i){ print(a[i]); if(i!=l-1){ print(" "); } } println(); } }
Java
["4\n7 8\nAAPAAAAA\nPPPPAAAA\nPPPPAAAA\nAPAAPPPP\nAPAPPAPP\nAAAAPPAP\nAAAAPPAA\n6 5\nAAAAA\nAAAAA\nAAPAA\nAAPAP\nAAAPP\nAAAPP\n4 4\nPPPP\nPPPP\nPPPP\nPPPP\n3 4\nPPPP\nPAAP\nPPPP"]
2 seconds
["2\n1\nMORTAL\n4"]
NoteIn the first test case, it can be done in two usages, as follows:Usage 1: Usage 2: In the second test case, it can be done with just one usage of the power. In the third test case, it is impossible to convert everyone to Beingawesomeism, so the answer is "MORTAL".
Java 8
standard input
[ "constructive algorithms", "implementation", "greedy", "math" ]
da18ca9f125d1524e7c0a2637b1fa3df
The first line of input contains a single integer $$$t$$$ ($$$1 \le t \le 2\cdot 10^4$$$) denoting the number of test cases. The first line of each test case contains two space-separated integers $$$r$$$ and $$$c$$$ denoting the dimensions of the grid ($$$1 \le r, c \le 60$$$). The next $$$r$$$ lines each contains $$$c$$$ characters describing the dominant religions in the countries. In particular, the $$$j$$$-th character in the $$$i$$$-th line describes the dominant religion in the country at the cell with row $$$i$$$ and column $$$j$$$, where: "A" means that the dominant religion is Beingawesomeism; "P" means that the dominant religion is Pushingittoofarism. It is guaranteed that the grid will only contain "A" or "P" characters. It is guaranteed that the sum of the $$$r \cdot c$$$ in a single file is at most $$$3 \cdot 10^6$$$.
1,800
For each test case, output a single line containing the minimum number of usages of your power needed to convert everyone to Beingawesomeism, or the string "MORTAL" (without quotes) if it is impossible to do so.
standard output
PASSED
b5c95303155c513d3cdabdc2521f167c
train_003.jsonl
1576386300
You are an all-powerful being and you have created a rectangular world. In fact, your world is so bland that it could be represented by a $$$r \times c$$$ grid. Each cell on the grid represents a country. Each country has a dominant religion. There are only two religions in your world. One of the religions is called Beingawesomeism, who do good for the sake of being good. The other religion is called Pushingittoofarism, who do murders for the sake of being bad.Oh, and you are actually not really all-powerful. You just have one power, which you can use infinitely many times! Your power involves missionary groups. When a missionary group of a certain country, say $$$a$$$, passes by another country $$$b$$$, they change the dominant religion of country $$$b$$$ to the dominant religion of country $$$a$$$.In particular, a single use of your power is this: You choose a horizontal $$$1 \times x$$$ subgrid or a vertical $$$x \times 1$$$ subgrid. That value of $$$x$$$ is up to you; You choose a direction $$$d$$$. If you chose a horizontal subgrid, your choices will either be NORTH or SOUTH. If you choose a vertical subgrid, your choices will either be EAST or WEST; You choose the number $$$s$$$ of steps; You command each country in the subgrid to send a missionary group that will travel $$$s$$$ steps towards direction $$$d$$$. In each step, they will visit (and in effect convert the dominant religion of) all $$$s$$$ countries they pass through, as detailed above. The parameters $$$x$$$, $$$d$$$, $$$s$$$ must be chosen in such a way that any of the missionary groups won't leave the grid. The following image illustrates one possible single usage of your power. Here, A represents a country with dominant religion Beingawesomeism and P represents a country with dominant religion Pushingittoofarism. Here, we've chosen a $$$1 \times 4$$$ subgrid, the direction NORTH, and $$$s = 2$$$ steps. You are a being which believes in free will, for the most part. However, you just really want to stop receiving murders that are attributed to your name. Hence, you decide to use your powers and try to make Beingawesomeism the dominant religion in every country.What is the minimum number of usages of your power needed to convert everyone to Beingawesomeism?With god, nothing is impossible. But maybe you're not god? If it is impossible to make Beingawesomeism the dominant religion in all countries, you must also admit your mortality and say so.
256 megabytes
import java.io.*; import java.math.*; import java.util.*; public class beingawesomeism { public static void main(String[] args) throws IOException { FastScanner scan = new FastScanner(); PrintWriter out = new PrintWriter(System.out); int cases = Integer.parseInt(scan.nextToken()); for (int cc = 0; cc < cases; cc++) { int r = Integer.parseInt(scan.nextToken()); int c = Integer.parseInt(scan.nextToken()); char[][] grid = new char[r][c]; int ans = 0; boolean possible = false; for (int i = 0; i < r; i++) { String s = scan.nextToken(); for (int j = 0; j < c; j++) { grid[i][j] = s.charAt(j); if (grid[i][j] == 'P') ans = 4; if (grid[i][j] == 'A') possible = true; } } if (!possible) { out.println("MORTAL"); } else { if (ans != 0) { boolean one = true; for (int j = 0; j < c; j++) { one = true; for (int i = 0; i < r; i++) { if (grid[i][j] == 'P') { one = false; break; } } if (one == true) { ans = Math.min(ans, 2); if (j == 0 || j == c-1) { ans = Math.min(ans, 1); } } } for (int i = 0; i < r; i++) { one = true; for (int j = 0; j < c; j++) { if (grid[i][j] == 'P') { one = false; break; } } if (one == true) { ans = Math.min(ans, 2); if (i == 0 || i == r-1) { ans = Math.min(ans, 1); } } } if (ans == 4) { for (int i = 0; i < r; i++) { for (int j = 0; j < c; j++) { if (grid[i][j] == 'A') { if ((i == 0 || i == r-1) && (j == 0 || j == c-1)) { ans = Math.min(ans, 2); } if ((i == 0 || i == r-1) || (j == 0 || j == c-1)) { ans = Math.min(ans, 3); } } } } } } out.println(ans); } } out.close(); } public static void shuffle(int[] arr) { Random rgen = new Random(); for (int i = 0; i < arr.length; i++) { int rPos = rgen.nextInt(arr.length); int temp = arr[i]; arr[i] = arr[rPos]; arr[rPos]=temp; } } public static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(String s) { try { br = new BufferedReader(new FileReader(s)); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String nextToken() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return st.nextToken(); } String nextLine() { st = null; try { return br.readLine(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } int nextInt() { return Integer.parseInt(nextToken()); } long nextLong() { return Long.parseLong(nextToken()); } double nextDouble() { return Double.parseDouble(nextToken()); } } }
Java
["4\n7 8\nAAPAAAAA\nPPPPAAAA\nPPPPAAAA\nAPAAPPPP\nAPAPPAPP\nAAAAPPAP\nAAAAPPAA\n6 5\nAAAAA\nAAAAA\nAAPAA\nAAPAP\nAAAPP\nAAAPP\n4 4\nPPPP\nPPPP\nPPPP\nPPPP\n3 4\nPPPP\nPAAP\nPPPP"]
2 seconds
["2\n1\nMORTAL\n4"]
NoteIn the first test case, it can be done in two usages, as follows:Usage 1: Usage 2: In the second test case, it can be done with just one usage of the power. In the third test case, it is impossible to convert everyone to Beingawesomeism, so the answer is "MORTAL".
Java 8
standard input
[ "constructive algorithms", "implementation", "greedy", "math" ]
da18ca9f125d1524e7c0a2637b1fa3df
The first line of input contains a single integer $$$t$$$ ($$$1 \le t \le 2\cdot 10^4$$$) denoting the number of test cases. The first line of each test case contains two space-separated integers $$$r$$$ and $$$c$$$ denoting the dimensions of the grid ($$$1 \le r, c \le 60$$$). The next $$$r$$$ lines each contains $$$c$$$ characters describing the dominant religions in the countries. In particular, the $$$j$$$-th character in the $$$i$$$-th line describes the dominant religion in the country at the cell with row $$$i$$$ and column $$$j$$$, where: "A" means that the dominant religion is Beingawesomeism; "P" means that the dominant religion is Pushingittoofarism. It is guaranteed that the grid will only contain "A" or "P" characters. It is guaranteed that the sum of the $$$r \cdot c$$$ in a single file is at most $$$3 \cdot 10^6$$$.
1,800
For each test case, output a single line containing the minimum number of usages of your power needed to convert everyone to Beingawesomeism, or the string "MORTAL" (without quotes) if it is impossible to do so.
standard output
PASSED
8404b1fe543eb65e49028cee3243ae09
train_003.jsonl
1576386300
You are an all-powerful being and you have created a rectangular world. In fact, your world is so bland that it could be represented by a $$$r \times c$$$ grid. Each cell on the grid represents a country. Each country has a dominant religion. There are only two religions in your world. One of the religions is called Beingawesomeism, who do good for the sake of being good. The other religion is called Pushingittoofarism, who do murders for the sake of being bad.Oh, and you are actually not really all-powerful. You just have one power, which you can use infinitely many times! Your power involves missionary groups. When a missionary group of a certain country, say $$$a$$$, passes by another country $$$b$$$, they change the dominant religion of country $$$b$$$ to the dominant religion of country $$$a$$$.In particular, a single use of your power is this: You choose a horizontal $$$1 \times x$$$ subgrid or a vertical $$$x \times 1$$$ subgrid. That value of $$$x$$$ is up to you; You choose a direction $$$d$$$. If you chose a horizontal subgrid, your choices will either be NORTH or SOUTH. If you choose a vertical subgrid, your choices will either be EAST or WEST; You choose the number $$$s$$$ of steps; You command each country in the subgrid to send a missionary group that will travel $$$s$$$ steps towards direction $$$d$$$. In each step, they will visit (and in effect convert the dominant religion of) all $$$s$$$ countries they pass through, as detailed above. The parameters $$$x$$$, $$$d$$$, $$$s$$$ must be chosen in such a way that any of the missionary groups won't leave the grid. The following image illustrates one possible single usage of your power. Here, A represents a country with dominant religion Beingawesomeism and P represents a country with dominant religion Pushingittoofarism. Here, we've chosen a $$$1 \times 4$$$ subgrid, the direction NORTH, and $$$s = 2$$$ steps. You are a being which believes in free will, for the most part. However, you just really want to stop receiving murders that are attributed to your name. Hence, you decide to use your powers and try to make Beingawesomeism the dominant religion in every country.What is the minimum number of usages of your power needed to convert everyone to Beingawesomeism?With god, nothing is impossible. But maybe you're not god? If it is impossible to make Beingawesomeism the dominant religion in all countries, you must also admit your mortality and say so.
256 megabytes
import java.util.*; import java.io.*; public class P1281D { private static void solve() { int t = nextInt(); while (t-- != 0) { int n = nextInt(); int m = nextInt(); char[][] g = new char[n][m]; for (int i = 0; i < n; i++) { g[i] = next().toCharArray(); } int[] rc = new int[n]; for (int i = 0; i < n; i++) { int cnt = 0; for (int j = 0; j < m; j++) { cnt += (g[i][j] == 'A' ? 1 : 0); } rc[i] = cnt; } int[] cc = new int[m]; for (int i = 0; i < m; i++) { int cnt = 0; for (int j = 0; j < n; j++) { cnt += (g[j][i] == 'A' ? 1 : 0); } cc[i] = cnt; } int[] rm = new int[n]; boolean bad = rc[0] != m; for (int i = 1; i < n; i++) { if (bad) { rm[i]++; } bad |= rc[i] != m; } bad = rc[n - 1] != m; for (int i = n - 2; i >= 0; i--) { if (bad) { rm[i]++; } bad |= rc[i] != m; } int[] cm = new int[m]; bad = cc[0] != n; for (int i = 1; i < m; i++) { if (bad) { cm[i]++; } bad |= cc[i] != n; } bad = cc[m - 1] != n; for (int i = m - 2; i >= 0; i--) { if (bad) { cm[i]++; } bad |= cc[i] != n; } int ans = -1; for (int i = 0; i < n; i++) { int cnt = -1; if (rc[i] == m) { cnt = 0; } else if (rc[i] > 0) { if (g[i][0] == 'A' || g[i][m - 1] == 'A') { cnt = 1; } else { cnt = 2; } } if (cnt != -1) { int req = cnt + rm[i]; if (ans == -1 || ans > req) { ans = req; } } } for (int i = 0; i < m; i++) { int cnt = -1; if (cc[i] == n) { cnt = 0; } else if (cc[i] > 0) { if (g[0][i] == 'A' || g[n - 1][i] == 'A') { cnt = 1; } else { cnt = 2; } } if (cnt != -1) { int req = cnt + cm[i]; if (ans == -1 || ans > req) { ans = req; } } } out.println(ans == -1 ? "MORTAL" : String.valueOf(ans)); } } private static void run() { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); out.close(); } private static StringTokenizer st; private static BufferedReader br; private static PrintWriter out; private static String next() { while (st == null || !st.hasMoreElements()) { String s; try { s = br.readLine(); } catch (IOException e) { return null; } st = new StringTokenizer(s); } return st.nextToken(); } private static int nextInt() { return Integer.parseInt(next()); } private static long nextLong() { return Long.parseLong(next()); } public static void main(String[] args) { run(); } }
Java
["4\n7 8\nAAPAAAAA\nPPPPAAAA\nPPPPAAAA\nAPAAPPPP\nAPAPPAPP\nAAAAPPAP\nAAAAPPAA\n6 5\nAAAAA\nAAAAA\nAAPAA\nAAPAP\nAAAPP\nAAAPP\n4 4\nPPPP\nPPPP\nPPPP\nPPPP\n3 4\nPPPP\nPAAP\nPPPP"]
2 seconds
["2\n1\nMORTAL\n4"]
NoteIn the first test case, it can be done in two usages, as follows:Usage 1: Usage 2: In the second test case, it can be done with just one usage of the power. In the third test case, it is impossible to convert everyone to Beingawesomeism, so the answer is "MORTAL".
Java 8
standard input
[ "constructive algorithms", "implementation", "greedy", "math" ]
da18ca9f125d1524e7c0a2637b1fa3df
The first line of input contains a single integer $$$t$$$ ($$$1 \le t \le 2\cdot 10^4$$$) denoting the number of test cases. The first line of each test case contains two space-separated integers $$$r$$$ and $$$c$$$ denoting the dimensions of the grid ($$$1 \le r, c \le 60$$$). The next $$$r$$$ lines each contains $$$c$$$ characters describing the dominant religions in the countries. In particular, the $$$j$$$-th character in the $$$i$$$-th line describes the dominant religion in the country at the cell with row $$$i$$$ and column $$$j$$$, where: "A" means that the dominant religion is Beingawesomeism; "P" means that the dominant religion is Pushingittoofarism. It is guaranteed that the grid will only contain "A" or "P" characters. It is guaranteed that the sum of the $$$r \cdot c$$$ in a single file is at most $$$3 \cdot 10^6$$$.
1,800
For each test case, output a single line containing the minimum number of usages of your power needed to convert everyone to Beingawesomeism, or the string "MORTAL" (without quotes) if it is impossible to do so.
standard output
PASSED
78ea234fca1f00700a8ee7bc95b29f03
train_003.jsonl
1493391900
Let's call a non-empty sequence of positive integers a1, a2... ak coprime if the greatest common divisor of all elements of this sequence is equal to 1.Given an array a consisting of n positive integers, find the number of its coprime subsequences. Since the answer may be very large, print it modulo 109 + 7.Note that two subsequences are considered different if chosen indices are different. For example, in the array [1, 1] there are 3 different subsequences: [1], [1] and [1, 1].
256 megabytes
///package CodeForce; import java.io.*; import java.util.*; import java.text.*; import java.math.*; import java.util.regex.*; public class EduRound20F { static int[] A; static int[] S; static long[] sum; public static int mod=1000000007; static int[][] dp; static boolean[][] isPalin; static int max1=5000+10; static int[][] g; public static void main(String[] args) throws Exception { InputReader in = new InputReader(System.in); PrintWriter out=new PrintWriter(System.out); int n=in.ii(); int[] a=in.iia(n); int[] f=new int[100001]; for(int v:a) { for(int d=1;d*d<=v;d++) { if(v%d==0) { f[d]++; if(d*d<v)f[v/d]++; } } } long[] dp=new long[100001]; for(int i=100000;i>=1;i--) { dp[i]=pow(2,f[i],mod)-1; for(int j=2*i;j<=100000;j+=i) { dp[i]-=dp[j]; if(dp[i]<0)dp[i]+=mod; } } out.println(dp[1]); out.close(); } public static int[][] packU(int n, int[] from, int[] to, int max) { int[][] g = new int[n][]; int[] p = new int[n]; for (int i = 0; i < max; i++) p[from[i]]++; for (int i = 0; i < max; i++) p[to[i]]++; for (int i = 0; i < n; i++) g[i] = new int[p[i]]; for (int i = 0; i < max; i++) { g[from[i]][--p[from[i]]] = to[i]; g[to[i]][--p[to[i]]] = from[i]; } return g; } public static int[][] parents3(int[][] g, int root) { int n = g.length; int[] par = new int[n]; Arrays.fill(par, -1); int[] depth = new int[n]; depth[0] = 0; int[] q = new int[n]; q[0] = root; for (int p = 0, r = 1; p < r; p++) { int cur = q[p]; for (int nex : g[cur]) { if (par[cur] != nex) { q[r++] = nex; par[nex] = cur; depth[nex] = depth[cur] + 1; } } } return new int[][]{par, q, depth}; } public static int lower_bound(int[] nums, int target) { int low = 0, high = nums.length - 1; while (low < high) { int mid = low + (high - low) / 2; if (nums[mid] < target) low = mid + 1; else high = mid; } return nums[low] == target ? low : -1; } public static int upper_bound(int[] nums, int target) { int low = 0, high = nums.length - 1; while (low < high) { int mid = low + (high + 1 - low) / 2; if (nums[mid] > target) high = mid - 1; else low = mid; } return nums[low] == target ? low : -1; } public static boolean palin(String s) { int i=0; int j=s.length()-1; while(i<j) { if(s.charAt(i)==s.charAt(j)) { i++; j--; } else return false; } return true; } static boolean CountPs(String s,int n) { boolean b=false; char[] S=s.toCharArray(); int[][] dp=new int[n][n]; boolean[][] p=new boolean[n][n]; for(int i=0;i<n;i++)p[i][i]=true; for(int i=0;i<n-1;i++) { if(S[i]==S[i+1]) { p[i][i+1]=true; dp[i][i+1]=1; b=true; } } for(int gap=2;gap<n;gap++) { for(int i=0;i<n-gap;i++) { int j=gap+i; if(S[i]==S[j]&&p[i+1][j-1]){p[i][j]=true;} if(p[i][j]) dp[i][j]=dp[i][j-1]+dp[i+1][j]+1-dp[i+1][j-1]; else dp[i][j]=dp[i][j-1]+dp[i+1][j]-dp[i+1][j-1]; if(dp[i][j]>=1){b=true;} } } return b; // return dp[0][n-1]; } static BigInteger power2(BigInteger x, BigInteger y, BigInteger m){ BigInteger ans = new BigInteger("1"); BigInteger one = new BigInteger("1"); BigInteger two = new BigInteger("2"); BigInteger zero = new BigInteger("0"); while(y.compareTo(zero)>0){ //System.out.println(y); if(y.mod(two).equals(one)){ ans = ans.multiply(x).mod(m); y = y.subtract(one); } else{ x = x.multiply(x).mod(m); y = y.divide(two); } } return ans; } static BigInteger power(BigInteger x, BigInteger y, BigInteger m) { if (y.equals(new BigInteger("0"))) return (new BigInteger("1")); BigInteger p = power(x, y.divide(new BigInteger("2")), m).mod(m); p = (p.multiply(p)).mod(m); return (y.mod(new BigInteger("2")).equals(new BigInteger("0")))? p : (p.multiply(x)).mod(m); } public static int gcd(int x,int y) { if(x%y==0) return y; else return gcd(y,x%y); } public static long pow1(long a, long n, long mod) { // a %= mod; long ret = 1; int x = 63 - Long.numberOfLeadingZeros(n); for (; x >= 0; x--) { ret = ret * ret % mod; if (n << 63 - x < 0) ret = ret * a % mod; } return ret; } public static long pow(long n,long p,long m) { long result = 1; if(p==0) return 1; if (p==1) return n; while(p!=0) { if(p%2==1) result *= n; if(result>=m) result%=m; p >>=1; n*=n; if(n>=m) n%=m; } return result; } public static long pow(long n,long p) { long result = 1; if(p==0) return 1; if (p==1) return n; while(p!=0) { if(p%2==1) result *= n; p >>=1; n*=n; } return result; } static class Edge implements Comparator<Edge> { private int u; private int v; private int w; public Edge() { } public Edge(int u, int v, int w) { this.u=u; this.v=v; this.w=w; } public int getU() { return u; } public void setU(int u) { this.u = u; } public int getV() { return v; } public void setV(int v) { this.v = v; } public int getW() { return w; } public void setW(int w) { this.w = w; } public int compare(Edge o1, Edge o2) { return o2.getW() - o1.getW(); } @Override public String toString() { return "Edge [u=" + u + ", v=" + v + ", w=" + w + "]"; } } static class Pair implements Comparable<Pair> { int a,b; Pair (int a,int b) { this.a=a; this.b=b; } public int compareTo(Pair o) { // TODO Auto-generated method stub if(this.a!=o.a) return -Integer.compare(this.a,o.a); else return -Integer.compare(this.b, o.b); //return 0; } public boolean equals(Object o) { if (o instanceof Pair) { Pair p = (Pair)o; return p.a == a && p.b == b; } return false; } public int hashCode() { return new Integer(a).hashCode() * 31 + new Integer(b).hashCode(); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private SpaceCharFilter filter; byte inbuffer[] = new byte[1024]; int lenbuffer = 0, ptrbuffer = 0; final int M = (int) 1e9 + 7; int md=(int)(1e7+1); int[] SMP=new int[md]; final double eps = 1e-6; final double pi = Math.PI; PrintWriter out; String check = ""; InputStream obj = check.isEmpty() ? System.in : new ByteArrayInputStream(check.getBytes()); public InputReader(InputStream stream) { this.stream = stream; } int readByte() { if (lenbuffer == -1) throw new InputMismatchException(); if (ptrbuffer >= lenbuffer) { ptrbuffer = 0; try { lenbuffer = obj.read(inbuffer); } catch (IOException e) { throw new InputMismatchException(); } } if (lenbuffer <= 0) return -1; return inbuffer[ptrbuffer++]; } public int read() { 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; } String is() { int b = skip(); StringBuilder sb = new StringBuilder(); while (!(isSpaceChar(b))) // when nextLine, (isSpaceChar(b) && b!=' ') { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } public int ii() { 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 il() { 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 root(int i) { while(A[i]!=i) { A[i]=A[A[i]]; i=A[i]; } return i; } public void union(int a,int b ) { int r1=root(a); int r2=root(b); if(S[r1]>S[r2]) { A[r2]=r1; S[r1]+=S[r2]; S[r2]=0; } else { A[r1]=r2; S[r2]+=S[r1]; S[r1]=0; } } boolean isSpaceChar(int c) { return (!(c >= 33 && c <= 126)); } int skip() { int b; while ((b = readByte()) != -1 && isSpaceChar(b)) ; return b; } float nf() { return Float.parseFloat(is()); } double id() { return Double.parseDouble(is()); } char ic() { return (char) skip(); } int[] iia(int n) { int a[] = new int[n]; for (int i = 0; i<n; i++) a[i] = ii(); return a; } long[] ila(int n) { long a[] = new long[n+1]; for (int i = 1; i <=n; i++) a[i] = il(); return a; } String[] isa(int n) { String a[] = new String[n]; for (int i = 0; i < n; i++) a[i] = is(); return a; } long mul(long a, long b) { return a * b % M; } long div(long a, long b) { return mul(a, pow(b, M - 2)); } double[][] idm(int n, int m) { double a[][] = new double[n][m]; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) a[i][j] = id(); return a; } int[][] iim(int n, int m) { int a[][] = new int[n][m]; for (int i = 0; i < n; i++) for (int j = 0; j <m; j++) a[i][j] = ii(); return a; } public String readLine() { 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 interface SpaceCharFilter { public boolean isSpaceChar(int ch); } public boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } } }
Java
["3\n1 2 3", "4\n1 1 1 1", "7\n1 3 5 15 3 105 35"]
2 seconds
["5", "15", "100"]
NoteIn the first example coprime subsequences are: 1 1, 2 1, 3 1, 2, 3 2, 3 In the second example all subsequences are coprime.
Java 8
standard input
[ "combinatorics", "number theory", "bitmasks" ]
2e6eafc13ff8dc91e6803deeaf2ecea5
The first line contains one integer number n (1 ≤ n ≤ 100000). The second line contains n integer numbers a1, a2... an (1 ≤ ai ≤ 100000).
2,000
Print the number of coprime subsequences of a modulo 109 + 7.
standard output
PASSED
def29303b092dbc990951ec484cb7919
train_003.jsonl
1493391900
Let's call a non-empty sequence of positive integers a1, a2... ak coprime if the greatest common divisor of all elements of this sequence is equal to 1.Given an array a consisting of n positive integers, find the number of its coprime subsequences. Since the answer may be very large, print it modulo 109 + 7.Note that two subsequences are considered different if chosen indices are different. For example, in the array [1, 1] there are 3 different subsequences: [1], [1] and [1, 1].
256 megabytes
/* package whatever; // don't place package name! */ import java.util.*; import java.lang.*; import java.io.*; /* Name of the class has to be "Main" only if the class is public. */ public class Main { public static void main (String[] args) throws java.lang.Exception { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); int n=Integer.parseInt(br.readLine()); String[] s=br.readLine().split(" "); int[] A=new int[n]; for(int i=0;i<n;i++){ A[i]=Integer.parseInt(s[i]); } Seq sq=new Seq(n,A); sq.doit(); //System.out.println(sq.ct[1000]); System.out.println(sq.f[1]); } } class Seq{ int[] A; int n; long P=1000000007; int[] ct; //number of A[j] divisible by i long[] f; Seq(int N,int[] arr){ n=N; A=arr; int MAX=100001; ct=new int[MAX]; f=new long[MAX]; for(int i=1;i<MAX;i++){ct[i]=0;f[i]=0;} for(int i=0;i<n;i++){ int x=A[i]; for(int j=1;j*j<=x;j++){ if(x%j==0){ ct[j]++; int t=x/j; if(t!=j){ ct[t]++; } } } } } void doit(){ //x<MAX number of sequences that have gcd=x int MAX=100001; for(int i=MAX-1;i>=1;i--){ f[i]=pow(2,ct[i])-1; for(int j=2;j*i<MAX;j++){ f[i]-=f[j*i]; f[i]=(f[i]+P)%P; } } } long pow(int x,int k){ long base=(long)x; long res=1; while(k>0){ if((k&1)==1){ res=(res*base)%P; } base=(base*base)%P; k>>=1; } return res; } }
Java
["3\n1 2 3", "4\n1 1 1 1", "7\n1 3 5 15 3 105 35"]
2 seconds
["5", "15", "100"]
NoteIn the first example coprime subsequences are: 1 1, 2 1, 3 1, 2, 3 2, 3 In the second example all subsequences are coprime.
Java 8
standard input
[ "combinatorics", "number theory", "bitmasks" ]
2e6eafc13ff8dc91e6803deeaf2ecea5
The first line contains one integer number n (1 ≤ n ≤ 100000). The second line contains n integer numbers a1, a2... an (1 ≤ ai ≤ 100000).
2,000
Print the number of coprime subsequences of a modulo 109 + 7.
standard output
PASSED
d6b7fd7363c6fdbf67773dcd558c19a4
train_003.jsonl
1493391900
Let's call a non-empty sequence of positive integers a1, a2... ak coprime if the greatest common divisor of all elements of this sequence is equal to 1.Given an array a consisting of n positive integers, find the number of its coprime subsequences. Since the answer may be very large, print it modulo 109 + 7.Note that two subsequences are considered different if chosen indices are different. For example, in the array [1, 1] there are 3 different subsequences: [1], [1] and [1, 1].
256 megabytes
import java.util.*; import java.io.*; public class _0803_F_CoprimeSubsequences { public static void main(String[] args) throws IOException { int N = readInt(), maxN = 100000, MOD = 1000000007; boolean seive[] = new boolean[maxN+1]; seive[1] = seive[0] = true; ArrayList<Integer> prime = new ArrayList<>(); for(int i = 2; i<=maxN; i++) if(!seive[i]) { prime.add(i); for(int j = 2*i; j<=maxN; j+=i) seive[j] = true; } int cnt[] = new int[maxN+1]; cnt[1] = 2; for(int q : prime) { for(int i= maxN/q; i>=1; i--) { if(cnt[i] == 0) continue; cnt[i*q] = cnt[i]+1; } } for(int i = 2; i<=maxN; i++) if(cnt[i] == 0) cnt[i] = -1; long pow[] = new long[N+1]; pow[0] = 1; for(int i =1; i<=N; i++) pow[i] = (pow[i-1]*2)%MOD; for(int i= 0; i<=N; i++) pow[i] = (pow[i]-1+MOD)%MOD; int count[] = new int[maxN+1]; for(int i = 1; i<=N; i++) { int n = readInt(); for(int j = 1; j<=Math.sqrt(n); j++) { if(n%j == 0) { count[n/j]++; if(n/j != j) count[j]++; } } } long tot = 0; for(int i = 1; i<=maxN; i++) { if(cnt[i] == -1) continue; if(cnt[i]%2 == 0) { tot = (tot + pow[count[i]])%MOD; } else { tot = ((tot - pow[count[i]])%MOD + MOD)%MOD; } } println(tot); exit(); } final private static int BUFFER_SIZE = 1 << 16; private static DataInputStream din = new DataInputStream(System.in); private static byte[] buffer = new byte[BUFFER_SIZE]; private static int bufferPointer = 0, bytesRead = 0; static PrintWriter pr = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); public static int readInt() throws IOException { int ret = 0; byte c = Read(); while (c <= ' ') c = Read(); do { ret = ret * 10 + c - '0'; } while ((c = Read()) >= '0' && c <= '9'); return ret; } private static void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private static byte Read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } static void print(Object o) { pr.print(o); } static void println(Object o) { pr.println(o); } static void flush() { pr.flush(); } static void println() { pr.println(); } static void exit() throws IOException { din.close(); pr.close(); System.exit(0); } }
Java
["3\n1 2 3", "4\n1 1 1 1", "7\n1 3 5 15 3 105 35"]
2 seconds
["5", "15", "100"]
NoteIn the first example coprime subsequences are: 1 1, 2 1, 3 1, 2, 3 2, 3 In the second example all subsequences are coprime.
Java 8
standard input
[ "combinatorics", "number theory", "bitmasks" ]
2e6eafc13ff8dc91e6803deeaf2ecea5
The first line contains one integer number n (1 ≤ n ≤ 100000). The second line contains n integer numbers a1, a2... an (1 ≤ ai ≤ 100000).
2,000
Print the number of coprime subsequences of a modulo 109 + 7.
standard output
PASSED
f60037f7036315c6479c2de301fb9d07
train_003.jsonl
1493391900
Let's call a non-empty sequence of positive integers a1, a2... ak coprime if the greatest common divisor of all elements of this sequence is equal to 1.Given an array a consisting of n positive integers, find the number of its coprime subsequences. Since the answer may be very large, print it modulo 109 + 7.Note that two subsequences are considered different if chosen indices are different. For example, in the array [1, 1] there are 3 different subsequences: [1], [1] and [1, 1].
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.StringTokenizer; import java.util.TreeSet; import java.util.stream.Stream; public class Main implements Runnable { static final double time = 1e9; static final int MOD = (int) 1e9 + 7; static final long mh = Long.MAX_VALUE; static final Reader in = new Reader(); static final PrintWriter out = new PrintWriter(System.out); StringBuilder answer = new StringBuilder(); long start = System.nanoTime(); public static void main(String[] args) { new Thread(null, new Main(), "persefone", 1 << 28).start(); } @Override public void run() { solve(); printf(); long elapsed = System.nanoTime() - start; // out.println("stamp : " + elapsed / time); // out.println("stamp : " + TimeUnit.SECONDS.convert(elapsed, TimeUnit.NANOSECONDS)); close(); // out.flush(); } void solve() { int m = 100001; int n = in.nextInt(); int[] f = new int[m]; for (int i = 0; i < n; i++) ++f[in.nextInt()]; int[] cnt = new int[m]; for (int i = 2; i < m; i++) for (int j = i; j < m; j += i) cnt[i] += f[j]; long[] mod = new long[n + 1]; mod[0] = 1; for (int i = 1; i <= n; i++) mod[i] = (mod[i - 1] * 2) % MOD; long[] ans = new long[m]; long c = 0; for (int i = m - 1; i > 1; i--) { if (cnt[i] > 0) { ans[i] = (mod[cnt[i]] - 1 + MOD) % MOD; for (int j = 2 * i; j < m; j += i) ans[i] = (ans[i] - ans[j] + MOD) % MOD; } c = (c + ans[i]) % MOD; } printf((mod[n] - 1 - c + 2 * MOD) % MOD); } void printf() { out.print(answer); } void close() { out.close(); } void printf(Stream<?> str) { str.forEach(o -> add(o, " ")); add("\n"); } void printf(Object... obj) { printf(false, obj); } void printfWithDescription(Object... obj) { printf(true, obj); } private void printf(boolean b, Object... obj) { if (obj.length > 1) { for (int i = 0; i < obj.length; i++) { if (b) add(obj[i].getClass().getSimpleName(), " - "); if (obj[i] instanceof Collection<?>) { printf((Collection<?>) obj[i]); } else if (obj[i] instanceof int[][]) { printf((int[][])obj[i]); } else if (obj[i] instanceof long[][]) { printf((long[][])obj[i]); } else if (obj[i] instanceof double[][]) { printf((double[][])obj[i]); } else printf(obj[i]); } return; } if (b) add(obj[0].getClass().getSimpleName(), " - "); printf(obj[0]); } void printf(Object o) { if (o instanceof int[]) printf(Arrays.stream((int[]) o).boxed()); else if (o instanceof char[]) printf(new String((char[]) o)); else if (o instanceof long[]) printf(Arrays.stream((long[]) o).boxed()); else if (o instanceof double[]) printf(Arrays.stream((double[]) o).boxed()); else if (o instanceof boolean[]) { for (boolean b : (boolean[]) o) add(b, " "); add("\n"); } else add(o, "\n"); } void printf(int[]... obj) { for (int i = 0; i < obj.length; i++) printf(obj[i]); } void printf(long[]... obj) { for (int i = 0; i < obj.length; i++) printf(obj[i]); } void printf(double[]... obj) { for (int i = 0; i < obj.length; i++) printf(obj[i]); } void printf(boolean[]... obj) { for (int i = 0; i < obj.length; i++) printf(obj[i]); } void printf(Collection<?> col) { printf(col.stream()); } <T, K> void add(T t, K k) { if (t instanceof Collection<?>) { ((Collection<?>) t).forEach(i -> add(i, " ")); } else if (t instanceof Object[]) { Arrays.stream((Object[]) t).forEach(i -> add(i, " ")); } else add(t); add(k); } <T> void add(T t) { answer.append(t); } @SuppressWarnings("unchecked") <T extends Comparable<? super T>> T min(T... t) { if (t.length == 0) return null; T m = t[0]; for (int i = 1; i < t.length; i++) if (t[i].compareTo(m) < 0) m = t[i]; return m; } @SuppressWarnings("unchecked") <T extends Comparable<? super T>> T max(T... t) { if (t.length == 0) return null; T m = t[0]; for (int i = 1; i < t.length; i++) if (t[i].compareTo(m) > 0) m = t[i]; return m; } int gcd(int a, int b) { return (b == 0) ? a : gcd(b, a % b); } long gcd(long a, long b) { return (b == 0) ? a : gcd(b, a % b); } // c = gcd(a, b) -> extends gcd method: ax + by = c <----> (b % a)p + q = c; int[] ext_gcd(int a, int b) { if (b == 0) return new int[] {a, 1, 0 }; int[] vals = ext_gcd(b, a % b); int d = vals[0]; // gcd int p = vals[2]; // int q = vals[1] - (a / b) * vals[2]; return new int[] { d, p, q }; } // find any solution of the equation: ax + by = c using extends gcd boolean find_any_solution(int a, int b, int c, int[] root) { int[] vals = ext_gcd(Math.abs(a), Math.abs(b)); if (c % vals[0] != 0) return false; printf(vals); root[0] = c * vals[1] / vals[0]; root[1] = c * vals[2] / vals[0]; if (a < 0) root[0] *= -1; if (b < 0) root[1] *= -1; return true; } int mod(int x) { return x % MOD; } int mod(int x, int y) { return mod(mod(x) + mod(y)); } long mod(long x) { return x % MOD; } long mod (long x, long y) { return mod(mod(x) + mod(y)); } int lw(long[] f, int l, int r, long k) { int R = r, m = 0; while (l <= r) { m = l + r >> 1; if (m == R) return m; if (f[m] >= k) r = m - 1; else l = m + 1; } return l; } int up(long[] f, int l, int r, long k) { int R = r, m = 0; while (l <= r) { m = l + r >> 1; if (m == R) return m; if (f[m] > k) r = m - 1; else l = m + 1; } return l; } int lw(int[] f, int l, int r, int k) { int R = r, m = 0; while (l <= r) { m = l + r >> 1; if (m == R) return m; if (f[m] >= k) r = m - 1; else l = m + 1; } return l; } int up(int[] f, int l, int r, int k) { int R = r, m = 0; while (l <= r) { m = l + r >> 1; if (m == R) return m; if (f[m] > k) r = m - 1; else l = m + 1; } return l; } <K extends Comparable<K>> int lw(List<K> li, int l, int r, K k) { int R = r, m = 0; while (l <= r) { m = l + r >> 1; if (m == R) return m; if (li.get(m).compareTo(k) >= 0) r = m - 1; else l = m + 1; } return l; } <K extends Comparable<K>> int up(List<K> li, int l, int r, K k) { int R = r, m = 0; while (l <= r) { m = l + r >> 1; if (m == R) return m; if (li.get(m).compareTo(k) > 0) r = m - 1; else l = m + 1; } return l; } <K extends Comparable<K>> int bs(List<K> li, int l, int r, K k) { while (l <= r) { int m = l + r >> 1; if (li.get(m) == k) return m; else if (li.get(m).compareTo(k) < 0) l = m + 1; else r = m - 1; } return -1; } long calc(int base, int exponent) { if (exponent == 0) return 1; if (exponent == 1) return base % MOD; long m = calc(base, exponent >> 1); if (exponent % 2 == 0) return m * m % MOD; return base * m * m % MOD; } long calc(int base, long exponent) { if (exponent == 0) return 1; if (exponent == 1) return base % MOD; long m = calc(base, exponent >> 1); if (exponent % 2 == 0) return m * m % MOD; return base * m * m % MOD; } long calc(long base, long exponent) { if (exponent == 0) return 1; if (exponent == 1) return base % MOD; long m = calc(base, exponent >> 1); if (exponent % 2 == 0) return m * m % MOD; return base * m * m % MOD; } long power(int base, int exponent) { if (exponent == 0) return 1; long m = power(base, exponent >> 1); if (exponent % 2 == 0) return m * m; return base * m * m; } void swap(int[] a, int i, int j) { a[i] ^= a[j]; a[j] ^= a[i]; a[i] ^= a[j]; } void swap(long[] a, int i, int j) { long tmp = a[i]; a[i] = a[j]; a[j] = tmp; } static class Pair<K extends Comparable<? super K>, V extends Comparable<? super V>> implements Comparable<Pair<K, V>> { private K k; private V v; Pair() {} Pair(K k, V v) { this.k = k; this.v = v; } K getK() { return k; } V getV() { return v; } void setK(K k) { this.k = k; } void setV(V v) { this.v = v; } void setKV(K k, V v) { this.k = k; this.v = v; } @SuppressWarnings("unchecked") @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || !(o instanceof Pair)) return false; Pair<K, V> p = (Pair<K, V>) o; return k.compareTo(p.k) == 0 && v.compareTo(p.v) == 0; } @Override public int hashCode() { int hash = 31; hash = hash * 89 + k.hashCode(); hash = hash * 89 + v.hashCode(); return hash; } @Override public int compareTo(Pair<K, V> pair) { return k.compareTo(pair.k) == 0 ? v.compareTo(pair.v) : k.compareTo(pair.k); } @Override public Pair<K, V> clone() { return new Pair<K, V>(this.k, this.v); } @Override public String toString() { return String.valueOf(k).concat(" ").concat(String.valueOf(v)).concat("\n"); } } static class Reader { private BufferedReader br; private StringTokenizer st; Reader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { try { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(br.readLine()); } } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] nextIntArray(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) arr[i] = nextInt(); return arr; } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String s = ""; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return s; } } }
Java
["3\n1 2 3", "4\n1 1 1 1", "7\n1 3 5 15 3 105 35"]
2 seconds
["5", "15", "100"]
NoteIn the first example coprime subsequences are: 1 1, 2 1, 3 1, 2, 3 2, 3 In the second example all subsequences are coprime.
Java 8
standard input
[ "combinatorics", "number theory", "bitmasks" ]
2e6eafc13ff8dc91e6803deeaf2ecea5
The first line contains one integer number n (1 ≤ n ≤ 100000). The second line contains n integer numbers a1, a2... an (1 ≤ ai ≤ 100000).
2,000
Print the number of coprime subsequences of a modulo 109 + 7.
standard output
PASSED
acd72bd5aeafa87d80fc67c79fe18637
train_003.jsonl
1493391900
Let's call a non-empty sequence of positive integers a1, a2... ak coprime if the greatest common divisor of all elements of this sequence is equal to 1.Given an array a consisting of n positive integers, find the number of its coprime subsequences. Since the answer may be very large, print it modulo 109 + 7.Note that two subsequences are considered different if chosen indices are different. For example, in the array [1, 1] there are 3 different subsequences: [1], [1] and [1, 1].
256 megabytes
import java.util.Arrays; import java.util.Scanner; public class f { static long MOD = (long)1e9+7; static int MAX = 100001; public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); long[] subs = new long[MAX]; Arrays.fill(subs, 1); for(int i=0;i<n;i++) { int v = in.nextInt(); subs[v] *= 2; subs[v] %= MOD; } long[] mu = new long[MAX]; mu[1] = 1; for (int x = 1; x < MAX; x++) for (int y = 2 * x; y < MAX; y += x) mu[y] -= mu[x]; long ans = 0; for(int i=1;i<MAX;i++) { long r = subs[i]; for(int j=i*2;j<MAX;j+=i) { r *= subs[j]; r %= MOD; } r = (r + MOD - 1) % MOD; ans += r * mu[i]; ans %= MOD; } if(ans < 0) ans += MOD; System.out.println(ans); } static int gcd(int a, int b) { return b == 0 ? a : gcd(b,a%b); } }
Java
["3\n1 2 3", "4\n1 1 1 1", "7\n1 3 5 15 3 105 35"]
2 seconds
["5", "15", "100"]
NoteIn the first example coprime subsequences are: 1 1, 2 1, 3 1, 2, 3 2, 3 In the second example all subsequences are coprime.
Java 8
standard input
[ "combinatorics", "number theory", "bitmasks" ]
2e6eafc13ff8dc91e6803deeaf2ecea5
The first line contains one integer number n (1 ≤ n ≤ 100000). The second line contains n integer numbers a1, a2... an (1 ≤ ai ≤ 100000).
2,000
Print the number of coprime subsequences of a modulo 109 + 7.
standard output
PASSED
e65d85c2c95fe3a8077f5def010e76fd
train_003.jsonl
1493391900
Let's call a non-empty sequence of positive integers a1, a2... ak coprime if the greatest common divisor of all elements of this sequence is equal to 1.Given an array a consisting of n positive integers, find the number of its coprime subsequences. Since the answer may be very large, print it modulo 109 + 7.Note that two subsequences are considered different if chosen indices are different. For example, in the array [1, 1] there are 3 different subsequences: [1], [1] and [1, 1].
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.BufferedWriter; import java.io.Writer; import java.io.OutputStreamWriter; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Jialin Ouyang (Jialin.Ouyang@gmail.com) */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; QuickScanner in = new QuickScanner(inputStream); QuickWriter out = new QuickWriter(outputStream); TaskF solver = new TaskF(); solver.solve(1, in, out); out.close(); } static class TaskF { static int MAXN = 100000 + 1; int[] minP; boolean[] isSF; boolean[] sfEven; int n; int[] aCnt; int[] cnt; IntModular mod; int[] pow2; public void solve(int testNumber, QuickScanner in, QuickWriter out) { initSF(); aCnt = new int[MAXN]; n = in.nextInt(); for (int i = 0; i < n; ++i) { ++aCnt[in.nextInt()]; } cnt = new int[MAXN]; for (int i = 2; i < MAXN; ++i) { for (int j = i; j < MAXN; j += i) { cnt[i] += aCnt[j]; } } mod = new IntModular(); pow2 = new int[MAXN]; pow2[0] = 1; for (int i = 1; i < MAXN; ++i) pow2[i] = mod.add(pow2[i - 1], pow2[i - 1]); out.println(calc()); } void initSF() { minP = new int[MAXN]; for (int i = 2; i < MAXN; ++i) { for (int j = i; j < MAXN; j += i) { if (minP[j] == 0) minP[j] = i; } } isSF = new boolean[MAXN]; sfEven = new boolean[MAXN]; isSF[1] = true; sfEven[1] = true; for (int i = 2; i < MAXN; ++i) { int j = i / minP[i]; isSF[i] = isSF[j] && j % minP[i] > 0; sfEven[i] = !sfEven[j]; } } int calc() { int res = mod.sub(pow2[n], 1); for (int i = 2; i < MAXN; ++i) if (isSF[i] && cnt[i] > 0) { int delta = mod.sub(pow2[cnt[i]], 1); if (sfEven[i]) { res = mod.add(res, delta); } else { res = mod.sub(res, delta); } } return res; } } static class QuickWriter { private final PrintWriter writer; public QuickWriter(OutputStream outputStream) { this.writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public QuickWriter(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 println(Object... objects) { print(objects); writer.print('\n'); } public void close() { writer.close(); } } static class IntModular { private static final int MOD = 1000000007; public final int mod; private final int[] x; public IntModular() { this(MOD); } public IntModular(int mod) { this.mod = mod; this.x = new int[2]; } public int add(int a, int b) { return fix(a + b); } public int sub(int a, int b) { return fix(a - b); } public int fix(int a) { a = slightFix(a); return 0 <= a && a < mod ? a : slightFix(a % mod); } private int slightFix(int a) { return a >= mod ? a - mod : a < 0 ? a + mod : a; } } static class QuickScanner { private static final int BUFFER_SIZE = 1024; private InputStream stream; private byte[] buffer; private int currentPosition; private int numberOfChars; public QuickScanner(InputStream stream) { this.stream = stream; this.buffer = new byte[BUFFER_SIZE]; this.currentPosition = 0; this.numberOfChars = 0; } public int nextInt() { int c = nextNonSpaceChar(); boolean positive = true; if (c == '-') { positive = false; c = nextChar(); } int res = 0; do { if (c < '0' || '9' < c) throw new RuntimeException(); res = res * 10 + c - '0'; c = nextChar(); } while (!isSpaceChar(c)); return positive ? res : -res; } public int nextNonSpaceChar() { int res = nextChar(); for (; isSpaceChar(res) || res < 0; res = nextChar()) ; return res; } public int nextChar() { if (numberOfChars == -1) { throw new RuntimeException(); } if (currentPosition >= numberOfChars) { currentPosition = 0; try { numberOfChars = stream.read(buffer); } catch (Exception e) { throw new RuntimeException(e); } if (numberOfChars <= 0) { return -1; } } return buffer[currentPosition++]; } public boolean isSpaceChar(int c) { return c == ' ' || c == '\t' || isEndOfLineChar(c); } public boolean isEndOfLineChar(int c) { return c == '\n' || c == '\r' || c < 0; } } }
Java
["3\n1 2 3", "4\n1 1 1 1", "7\n1 3 5 15 3 105 35"]
2 seconds
["5", "15", "100"]
NoteIn the first example coprime subsequences are: 1 1, 2 1, 3 1, 2, 3 2, 3 In the second example all subsequences are coprime.
Java 8
standard input
[ "combinatorics", "number theory", "bitmasks" ]
2e6eafc13ff8dc91e6803deeaf2ecea5
The first line contains one integer number n (1 ≤ n ≤ 100000). The second line contains n integer numbers a1, a2... an (1 ≤ ai ≤ 100000).
2,000
Print the number of coprime subsequences of a modulo 109 + 7.
standard output
PASSED
57569a94c7f2920dce3d20299325df53
train_003.jsonl
1493391900
Let's call a non-empty sequence of positive integers a1, a2... ak coprime if the greatest common divisor of all elements of this sequence is equal to 1.Given an array a consisting of n positive integers, find the number of its coprime subsequences. Since the answer may be very large, print it modulo 109 + 7.Note that two subsequences are considered different if chosen indices are different. For example, in the array [1, 1] there are 3 different subsequences: [1], [1] and [1, 1].
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; public class Main { static BufferedReader in; static PrintWriter out; static StringTokenizer buffer; static int MAX = 100100; static long MOD = 1_000_000_007; static long add(long a, long b) { long res = (a % MOD + b % MOD) % MOD; if (res < 0) res += MOD; return res; } static long sub(long a, long b) { long res = a % MOD - b % MOD; if (res < 0) res += MOD; return res; } static long mult(long a, long b) { long res = (a % MOD * b % MOD) % MOD; if (res<0) res+=MOD; return res; } public static void solve() { int n = ni(); long[]cnt = new long[MAX]; Arrays.fill(cnt, 1L); for (int i=0;i<n;i++) { int x = ni(); cnt[x] = add(cnt[x], cnt[x]); // calculate 2^cnt } // All multiples of x for (int i=1;i<MAX;i++) { for (int j=2*i;j<MAX;j+=i) { cnt[i] = mult(cnt[i], cnt[j]); } } int[]mob = new int[MAX]; mob[1] = 1; for (int m1 = 1; m1 < MAX; m1++) for (int m2 = 2 * m1; m2 < MAX; m2 += m1) mob[m2] -= mob[m1]; long res = 0; for (int i=1;i<MAX;i++) { res = add(res, mult(mob[i], sub(cnt[i], 1L))); } out.println(res); } public static void main(String[] args) throws IOException { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); out.close(); } static String next() { while (buffer == null || !buffer.hasMoreElements()) { try { buffer = new StringTokenizer(in.readLine()); } catch (IOException e) { // } } return buffer.nextToken(); } static int ni() { return Integer.parseInt(next()); } static long nl() { return Long.parseLong(next()); } static double nd() { return Double.parseDouble(next()); } static String ns() { return next(); } static int[] ni(int n) { int[] res = new int[n]; for (int i = 0; i < n; i++) res[i] = Integer.parseInt(next()); return res; } static long[] nl(int n) { long[] res = new long[n]; for (int i = 0; i < n; i++) res[i] = Long.parseLong(next()); return res; } static double[] nd(int n) { double[] res = new double[n]; for (int i = 0; i < n; i++) res[i] = Double.parseDouble(next()); return res; } static String[] ns(int n) { String[] res = new String[n]; for (int i = 0; i < n; i++) res[i] = next(); return res; } static String nln() { try { return in.readLine(); } catch (IOException e) { // } return null; } }
Java
["3\n1 2 3", "4\n1 1 1 1", "7\n1 3 5 15 3 105 35"]
2 seconds
["5", "15", "100"]
NoteIn the first example coprime subsequences are: 1 1, 2 1, 3 1, 2, 3 2, 3 In the second example all subsequences are coprime.
Java 8
standard input
[ "combinatorics", "number theory", "bitmasks" ]
2e6eafc13ff8dc91e6803deeaf2ecea5
The first line contains one integer number n (1 ≤ n ≤ 100000). The second line contains n integer numbers a1, a2... an (1 ≤ ai ≤ 100000).
2,000
Print the number of coprime subsequences of a modulo 109 + 7.
standard output
PASSED
dff266eeccf3ca8666745ce411ced1eb
train_003.jsonl
1493391900
Let's call a non-empty sequence of positive integers a1, a2... ak coprime if the greatest common divisor of all elements of this sequence is equal to 1.Given an array a consisting of n positive integers, find the number of its coprime subsequences. Since the answer may be very large, print it modulo 109 + 7.Note that two subsequences are considered different if chosen indices are different. For example, in the array [1, 1] there are 3 different subsequences: [1], [1] and [1, 1].
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; public class Main { static BufferedReader in; static PrintWriter out; static StringTokenizer buffer; static int MAX = 100100; static long MOD = 1_000_000_007; static long add(long a, long b) { long res = (a % MOD + b % MOD) % MOD; if (res < 0) res += MOD; return res; } static long sub(long a, long b) { long res = a % MOD - b % MOD; if (res < 0) res += MOD; return res; } static long mult(long a, long b) { long res = (a % MOD * b % MOD) % MOD; if (res<0) res+=MOD; return res; } public static void solve() { int n = ni(); long[]cnt = new long[MAX]; Arrays.fill(cnt, 1L); for (int i=0;i<n;i++) { int x = ni(); cnt[x] = add(cnt[x], cnt[x]); // calculate 2^cnt } // All multiples of x for (int i=1;i<MAX;i++) { for (int j=2*i;j<MAX;j+=i) { cnt[i] = mult(cnt[i], cnt[j]); } } int[]mob = new int[MAX]; mob[1] = 1; for (int m1 = 1; m1 < MAX; m1++) for (int m2 = 2 * m1; m2 < MAX; m2 += m1) mob[m2] -= mob[m1]; long res = 0; for (int i=1;i<MAX;i++) { res = add(res, mult(mob[i], sub(cnt[i], 1L))); } out.println(res); } public static void main(String[] args) throws IOException { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); out.close(); } static String next() { while (buffer == null || !buffer.hasMoreElements()) { try { buffer = new StringTokenizer(in.readLine()); } catch (IOException e) { // } } return buffer.nextToken(); } static int ni() { return Integer.parseInt(next()); } static long nl() { return Long.parseLong(next()); } static double nd() { return Double.parseDouble(next()); } static String ns() { return next(); } static int[] ni(int n) { int[] res = new int[n]; for (int i = 0; i < n; i++) res[i] = Integer.parseInt(next()); return res; } static long[] nl(int n) { long[] res = new long[n]; for (int i = 0; i < n; i++) res[i] = Long.parseLong(next()); return res; } static double[] nd(int n) { double[] res = new double[n]; for (int i = 0; i < n; i++) res[i] = Double.parseDouble(next()); return res; } static String[] ns(int n) { String[] res = new String[n]; for (int i = 0; i < n; i++) res[i] = next(); return res; } static String nln() { try { return in.readLine(); } catch (IOException e) { // } return null; } }
Java
["3\n1 2 3", "4\n1 1 1 1", "7\n1 3 5 15 3 105 35"]
2 seconds
["5", "15", "100"]
NoteIn the first example coprime subsequences are: 1 1, 2 1, 3 1, 2, 3 2, 3 In the second example all subsequences are coprime.
Java 8
standard input
[ "combinatorics", "number theory", "bitmasks" ]
2e6eafc13ff8dc91e6803deeaf2ecea5
The first line contains one integer number n (1 ≤ n ≤ 100000). The second line contains n integer numbers a1, a2... an (1 ≤ ai ≤ 100000).
2,000
Print the number of coprime subsequences of a modulo 109 + 7.
standard output
PASSED
536eed982a7b63552402fb744df599c0
train_003.jsonl
1493391900
Let's call a non-empty sequence of positive integers a1, a2... ak coprime if the greatest common divisor of all elements of this sequence is equal to 1.Given an array a consisting of n positive integers, find the number of its coprime subsequences. Since the answer may be very large, print it modulo 109 + 7.Note that two subsequences are considered different if chosen indices are different. For example, in the array [1, 1] there are 3 different subsequences: [1], [1] and [1, 1].
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.OutputStream; import java.util.Arrays; import java.io.IOException; import java.io.InputStreamReader; import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.StringTokenizer; import java.io.Writer; import java.io.BufferedReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author kessido */ 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); FCoprimeSubsequences solver = new FCoprimeSubsequences(); solver.solve(1, in, out); out.close(); } static class FCoprimeSubsequences { private static final long MOD = MathExtensions.DEFAULT_MOD; private static final int[] factors = MathExtensions.getFactors(100000); public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.NextInt(); int[] a = in.NextIntArray(n); long[] resPerFactor = new long[100001]; for (final int i : a) { int[] factors = getAllCombination(getFactors(i)); for (int factor : factors) { resPerFactor[factor] = (resPerFactor[factor] * 2 + 1) % MOD; } } ArrayList<ArrayList<Integer>> perFactors = new ArrayList<>(); for (int i = 0; i < 13; i++) { perFactors.add(new ArrayList<>()); } for (int i = 1; i < resPerFactor.length; i++) { perFactors.get(getNumberOfFactors(i)).add(i); } long res = 0; long curSign = 1; for (int i = 0; i < perFactors.size(); i++) { for (int j : perFactors.get(i)) { res += curSign * resPerFactor[j]; res %= MOD; } if (res < 0) res += MOD; curSign *= -1; } out.println(res); } private int[] getAllCombination(ArrayList<Integer> factors) { int len = 1 << factors.size(); int[] res = new int[len]; for (int i = 0; i < len; i++) { int bitCheck = 1; int cur = 1; for (int factor : factors) { if ((i & bitCheck) != 0) { cur *= factor; } bitCheck <<= 1; } res[i] = cur; } return res; } int getNumberOfFactors(int x) { return getFactors(x).size(); } ArrayList<Integer> getFactors(int x) { ArrayList<Integer> res = new ArrayList<>(); while (x != 1) { int p = factors[x]; if (p == 1) p = x; while (x % p == 0) { x /= p; } res.add(p); } return res; } } static class MathExtensions { public static final long DEFAULT_MOD = 1_000_000_007L; private static int[] getFactors(final int limitInc, final int checkLimit) { int[] res = new int[limitInc + 1]; Arrays.fill(res, 1); for (int i = 4; i <= limitInc; i += 2) { res[i] = 2; } for (int i = 3; i <= checkLimit; i += 2) { if (res[i] != 1) continue; for (int j = i + i; j <= limitInc; j += i) { res[j] = i; } } return res; } public static int[] getFactors(final int limitInc) { return getFactors(limitInc, (int) Math.sqrt((double) limitInc)); } } static class OutputWriter extends PrintWriter { public OutputWriter(Writer out) { super(out); } public OutputWriter(File file) throws FileNotFoundException { super(file); } public OutputWriter(OutputStream out) { super(out); } } static class InputReader { BufferedReader reader; StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine(), " \t\n\r\f,"); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int NextInt() { return Integer.parseInt(next()); } public int[] NextIntArray(int n) { return NextIntArray(n, 0); } public int[] NextIntArray(int n, int offset) { int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = NextInt() + offset; } return a; } } }
Java
["3\n1 2 3", "4\n1 1 1 1", "7\n1 3 5 15 3 105 35"]
2 seconds
["5", "15", "100"]
NoteIn the first example coprime subsequences are: 1 1, 2 1, 3 1, 2, 3 2, 3 In the second example all subsequences are coprime.
Java 8
standard input
[ "combinatorics", "number theory", "bitmasks" ]
2e6eafc13ff8dc91e6803deeaf2ecea5
The first line contains one integer number n (1 ≤ n ≤ 100000). The second line contains n integer numbers a1, a2... an (1 ≤ ai ≤ 100000).
2,000
Print the number of coprime subsequences of a modulo 109 + 7.
standard output
PASSED
bc6a844e3a3213454a27c50d9364d942
train_003.jsonl
1493391900
Let's call a non-empty sequence of positive integers a1, a2... ak coprime if the greatest common divisor of all elements of this sequence is equal to 1.Given an array a consisting of n positive integers, find the number of its coprime subsequences. Since the answer may be very large, print it modulo 109 + 7.Note that two subsequences are considered different if chosen indices are different. For example, in the array [1, 1] there are 3 different subsequences: [1], [1] and [1, 1].
256 megabytes
import java.util.*; import java.io.*; public class A { static int mod = (int) (1e9+7); static InputReader in; static PrintWriter out; static long mul(long a, long b) { a %= mod; b %= mod; long c = a * b; return c % mod; } public static void main(String[] args) { in = new InputReader(System.in); out = new PrintWriter(System.out); int n = in.nextInt(); int maxn = 100005; long[] ans = new long[maxn]; int[] cnt = new int[maxn]; long[] p = new long[maxn]; for(int i = 0; i < n; i++) { cnt[in.nextInt()]++; } p[0] = 1; for(int i = 1; i < maxn; i++) p[i] = mul(p[i - 1], 2); for(int i = maxn - 1; i >= 1; i--) { int res = 0; for(int j = i; j < maxn; j += i) { res += cnt[j]; } long tmp = (p[res] - 1 + mod) % mod; for(int j = i + i; j < maxn; j += i) tmp = (tmp - ans[j] + mod) % mod; ans[i] = tmp; } out.println(ans[1]); out.close(); } static void debug(Object... o) { System.out.println(Arrays.deepToString(o)); } static class Pair implements Comparable<Pair> { int x,y; Pair (int x,int y) { this.x = x; this.y = y; } public int compareTo(Pair o) { return Integer.compare(this.x,o.x); //return 0; } public boolean equals(Object o) { if (o instanceof Pair) { Pair p = (Pair)o; return p.x == x && p.y==y; } return false; } @Override public String toString() { return x + " "+ y; } public int hashCode() { return new Long(x).hashCode() * 31 + new Long(y).hashCode(); } } static long gcd(long x,long y) { if(y==0) return x; else return gcd(y,x%y); } static int gcd(int x,int y) { if(y==0) return x; else return gcd(y,x%y); } static long pow(long n,long p,long m) { long result = 1; if(p==0) return 1; while(p!=0) { if(p%2==1) result *= n; if(result>=m) result%=m; p >>=1; n*=n; if(n>=m) n%=m; } return result; } static long pow(long n,long p) { long result = 1; if(p==0) return 1; while(p!=0) { if(p%2==1) result *= n; p >>=1; n*=n; } return result; } 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 long[] nextLongArray(int n) { long a[] = new long[n]; for (int i = 0; i < n; i++) { a[i] = nextLong(); } 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); } } }
Java
["3\n1 2 3", "4\n1 1 1 1", "7\n1 3 5 15 3 105 35"]
2 seconds
["5", "15", "100"]
NoteIn the first example coprime subsequences are: 1 1, 2 1, 3 1, 2, 3 2, 3 In the second example all subsequences are coprime.
Java 8
standard input
[ "combinatorics", "number theory", "bitmasks" ]
2e6eafc13ff8dc91e6803deeaf2ecea5
The first line contains one integer number n (1 ≤ n ≤ 100000). The second line contains n integer numbers a1, a2... an (1 ≤ ai ≤ 100000).
2,000
Print the number of coprime subsequences of a modulo 109 + 7.
standard output
PASSED
67a7f8b195f73f712eda7f3b25062e6b
train_003.jsonl
1493391900
Let's call a non-empty sequence of positive integers a1, a2... ak coprime if the greatest common divisor of all elements of this sequence is equal to 1.Given an array a consisting of n positive integers, find the number of its coprime subsequences. Since the answer may be very large, print it modulo 109 + 7.Note that two subsequences are considered different if chosen indices are different. For example, in the array [1, 1] there are 3 different subsequences: [1], [1] and [1, 1].
256 megabytes
/** * author: derrick20 * created: 11/4/20 1:42 PM */ import java.io.*; import java.util.*; import static java.lang.Math.*; public class CoprimeMobius { public static void main(String[] args) { FastScanner sc = new FastScanner(); PrintWriter out = new PrintWriter(System.out); int N = sc.nextInt(); int[] a = sc.nextInts(N); int MAX = (int) 1e5; int[] mobius = new int[MAX + 1]; /* Key idea: mobius[x] = the exact sign necessary for us to do inclusion-exclusion on primes. */ Arrays.fill(mobius, 1); boolean[] prime = new boolean[MAX + 1]; Arrays.fill(prime, true); prime[1] = false; for (int i = 2; i <= MAX; i++) { if (prime[i]) { mobius[i] = -1; for (int j = 2 * i; j <= MAX; j += i) { prime[j] = false; if (j / i >= i && j % (i * i) == 0) { mobius[j] = 0; } else { // it only has single primes, so this prime mobius[j] *= -1; } } } } // System.out.println(Arrays.toString(mobius)); long[] dp = new long[MAX + 1]; // dp[g] = ways for a subsequence to have gcd = k * g // specifically, the mobius enables us to count the ways // for each event (divisible by p_i) in a way for (int v : a) { for (int p = 1; p * p <= v; p++) { if (v % p == 0) { if (dp[p] == 0) dp[p] = 1; if (dp[v / p] == 0) { dp[v / p] = 1; } dp[p] = (dp[p] * 2) % mod; if (p * p != v) dp[v / p] = (dp[v / p] * 2) % mod; } } } long ans = 0; for (int i = 1; i <= MAX; i++) { if (dp[i] != 0) { ans = (ans + mobius[i] * (dp[i] - 1)) % mod; } } if (ans < 0) ans += mod; out.println(ans); out.close(); } static long mod = (long) 1e9 + 7; static class FastScanner { private int BS = 1 << 16; private char NC = (char) 0; private byte[] buf = new byte[BS]; private int bId = 0, size = 0; private char c = NC; private double cnt = 1; private BufferedInputStream in; public FastScanner() { in = new BufferedInputStream(System.in, BS); } public FastScanner(String s) { try { in = new BufferedInputStream(new FileInputStream(new File(s)), BS); } catch (Exception e) { in = new BufferedInputStream(System.in, BS); } } private char getChar() { while (bId == size) { try { size = in.read(buf); } catch (Exception e) { return NC; } if (size == -1) return NC; bId = 0; } return (char) buf[bId++]; } public int nextInt() { return (int) nextLong(); } public int[] nextInts(int N) { int[] res = new int[N]; for (int i = 0; i < N; i++) { res[i] = (int) nextLong(); } return res; } public long[] nextLongs(int N) { long[] res = new long[N]; for (int i = 0; i < N; i++) { res[i] = nextLong(); } return res; } public long nextLong() { cnt = 1; boolean neg = false; if (c == NC) c = getChar(); for (; (c < '0' || c > '9'); c = getChar()) { if (c == '-') neg = true; } long res = 0; for (; c >= '0' && c <= '9'; c = getChar()) { res = (res << 3) + (res << 1) + c - '0'; cnt *= 10; } return neg ? -res : res; } public double nextDouble() { double cur = nextLong(); return c != '.' ? cur : cur + nextLong() / cnt; } public double[] nextDoubles(int N) { double[] res = new double[N]; for (int i = 0; i < N; i++) { res[i] = nextDouble(); } return res; } public String next() { StringBuilder res = new StringBuilder(); while (c <= 32) c = getChar(); while (c > 32) { res.append(c); c = getChar(); } return res.toString(); } public String nextLine() { StringBuilder res = new StringBuilder(); while (c <= 32) c = getChar(); while (c != '\n') { res.append(c); c = getChar(); } return res.toString(); } public boolean hasNext() { if (c > 32) return true; while (true) { c = getChar(); if (c == NC) return false; else if (c > 32) return true; } } } static void ASSERT(boolean assertion, String message) { if (!assertion) throw new AssertionError(message); } static void ASSERT(boolean assertion) { if (!assertion) throw new AssertionError(); } }
Java
["3\n1 2 3", "4\n1 1 1 1", "7\n1 3 5 15 3 105 35"]
2 seconds
["5", "15", "100"]
NoteIn the first example coprime subsequences are: 1 1, 2 1, 3 1, 2, 3 2, 3 In the second example all subsequences are coprime.
Java 8
standard input
[ "combinatorics", "number theory", "bitmasks" ]
2e6eafc13ff8dc91e6803deeaf2ecea5
The first line contains one integer number n (1 ≤ n ≤ 100000). The second line contains n integer numbers a1, a2... an (1 ≤ ai ≤ 100000).
2,000
Print the number of coprime subsequences of a modulo 109 + 7.
standard output
PASSED
a04e7aea64ef00940e7d24bab406125b
train_003.jsonl
1493391900
Let's call a non-empty sequence of positive integers a1, a2... ak coprime if the greatest common divisor of all elements of this sequence is equal to 1.Given an array a consisting of n positive integers, find the number of its coprime subsequences. Since the answer may be very large, print it modulo 109 + 7.Note that two subsequences are considered different if chosen indices are different. For example, in the array [1, 1] there are 3 different subsequences: [1], [1] and [1, 1].
256 megabytes
/** * author: derrick20 * created: 11/4/20 2:31 PM */ import java.io.*; import java.util.*; import static java.lang.Math.*; public class CoprimeMobiusSimple { public static void main(String[] args) { FastScanner sc = new FastScanner(); PrintWriter out = new PrintWriter(System.out); int N = sc.nextInt(); int[] a = sc.nextInts(N); int MAX = (int) 1e5; ArrayList<Integer>[] divisors = new ArrayList[MAX + 1]; Arrays.setAll(divisors, v -> new ArrayList<>()); /* Key idea: instead of going through each value and finding divisors in total Nsqrt(N) go through divisors, and easily put them into multiples of d in amortized NlogN. */ /* for (int v = 1; v <= MAX; v++) { for (int d = 1; d * d <= v; d++) { if (v % d == 0) { divisors[v].add(d); if (d != v / d) { divisors[v].add(v / d); } } } } System.out.println(Arrays.toString(divisors)); Arrays.setAll(divisors, v -> new ArrayList<>()); */ for (int d = 1; d <= MAX; d++) { for (int v = d; v <= MAX; v += d) { divisors[v].add(d); } } // System.out.println(Arrays.toString(divisors)); // System.out.println(Arrays.toString(divisors)); int[] mobius = new int[MAX + 1]; mobius[1] = 1; /* key idea/fact: Convolution of mobius with `1` (identity function) = epsilon (1 if x = 1, 0 otherwise) mobius(divisors of 1) = 1 mobius(divisors of p^k) = 1 + -1 + 0 + 0 + ... = 0 Since mobius is multiplicative, we can check the cases (square-free case: sign = parity of number of primes is multiplicative) (not square-free case: multiplying two non square-free numbers is another non-squarefree number, so still 0) mobius(divisors of p1^k p2^k...) = mobius(divisors of p1^k) + ... = 0 Thus, mu(x) + mu(divisors) = 0 (if x > 1) mu(x) = -mu(divisors) */ for (int v = 2; v <= MAX; v++) { for (int d : divisors[v]) { if (d != v) mobius[v] -= mobius[d]; } } // System.out.println(Arrays.toString(mobius)); long[] dp = new long[MAX + 1]; for (int v : a) { for (int d : divisors[v]) { if (dp[d] == 0) dp[d] = 1; dp[d] = (2 * dp[d]) % mod; } } long ans = 0; for (int i = 1; i <= MAX; i++) { if (dp[i] != 0) { ans = (ans + mobius[i] * (dp[i] - 1)) % mod; } } if (ans < 0) // key bug! NEG ANSWER ans += mod; out.println(ans); out.close(); } static long mod = (long) 1e9 + 7; static class FastScanner { private int BS = 1 << 16; private char NC = (char) 0; private byte[] buf = new byte[BS]; private int bId = 0, size = 0; private char c = NC; private double cnt = 1; private BufferedInputStream in; public FastScanner() { in = new BufferedInputStream(System.in, BS); } public FastScanner(String s) { try { in = new BufferedInputStream(new FileInputStream(new File(s)), BS); } catch (Exception e) { in = new BufferedInputStream(System.in, BS); } } private char getChar() { while (bId == size) { try { size = in.read(buf); } catch (Exception e) { return NC; } if (size == -1) return NC; bId = 0; } return (char) buf[bId++]; } public int nextInt() { return (int) nextLong(); } public int[] nextInts(int N) { int[] res = new int[N]; for (int i = 0; i < N; i++) { res[i] = (int) nextLong(); } return res; } public long[] nextLongs(int N) { long[] res = new long[N]; for (int i = 0; i < N; i++) { res[i] = nextLong(); } return res; } public long nextLong() { cnt = 1; boolean neg = false; if (c == NC) c = getChar(); for (; (c < '0' || c > '9'); c = getChar()) { if (c == '-') neg = true; } long res = 0; for (; c >= '0' && c <= '9'; c = getChar()) { res = (res << 3) + (res << 1) + c - '0'; cnt *= 10; } return neg ? -res : res; } public double nextDouble() { double cur = nextLong(); return c != '.' ? cur : cur + nextLong() / cnt; } public double[] nextDoubles(int N) { double[] res = new double[N]; for (int i = 0; i < N; i++) { res[i] = nextDouble(); } return res; } public String next() { StringBuilder res = new StringBuilder(); while (c <= 32) c = getChar(); while (c > 32) { res.append(c); c = getChar(); } return res.toString(); } public String nextLine() { StringBuilder res = new StringBuilder(); while (c <= 32) c = getChar(); while (c != '\n') { res.append(c); c = getChar(); } return res.toString(); } public boolean hasNext() { if (c > 32) return true; while (true) { c = getChar(); if (c == NC) return false; else if (c > 32) return true; } } } static void ASSERT(boolean assertion, String message) { if (!assertion) throw new AssertionError(message); } static void ASSERT(boolean assertion) { if (!assertion) throw new AssertionError(); } }
Java
["3\n1 2 3", "4\n1 1 1 1", "7\n1 3 5 15 3 105 35"]
2 seconds
["5", "15", "100"]
NoteIn the first example coprime subsequences are: 1 1, 2 1, 3 1, 2, 3 2, 3 In the second example all subsequences are coprime.
Java 8
standard input
[ "combinatorics", "number theory", "bitmasks" ]
2e6eafc13ff8dc91e6803deeaf2ecea5
The first line contains one integer number n (1 ≤ n ≤ 100000). The second line contains n integer numbers a1, a2... an (1 ≤ ai ≤ 100000).
2,000
Print the number of coprime subsequences of a modulo 109 + 7.
standard output
PASSED
e32c52c2c7479ca5aa0b34be62aceb98
train_003.jsonl
1493391900
Let's call a non-empty sequence of positive integers a1, a2... ak coprime if the greatest common divisor of all elements of this sequence is equal to 1.Given an array a consisting of n positive integers, find the number of its coprime subsequences. Since the answer may be very large, print it modulo 109 + 7.Note that two subsequences are considered different if chosen indices are different. For example, in the array [1, 1] there are 3 different subsequences: [1], [1] and [1, 1].
256 megabytes
/** * author: derrick20 * created: 11/4/20 2:31 PM */ import java.io.*; import java.util.*; import static java.lang.Math.*; public class CoprimeMobiusSimple { public static void main(String[] args) { FastScanner sc = new FastScanner(); PrintWriter out = new PrintWriter(System.out); int N = sc.nextInt(); int[] a = sc.nextInts(N); int MAX = (int) 1e5; ArrayList<Integer>[] divisors = new ArrayList[MAX + 1]; Arrays.setAll(divisors, v -> new ArrayList<>()); /* Key idea: instead of going through each value and finding divisors in total Nsqrt(N) go through divisors, and easily put them into multiples of d in amortized NlogN. */ // /* for (int v = 1; v <= MAX; v++) { for (int d = 1; d * d <= v; d++) { if (v % d == 0) { divisors[v].add(d); if (d != v / d) { divisors[v].add(v / d); } } } } // System.out.println(Arrays.toString(divisors)); // Arrays.setAll(divisors, v -> new ArrayList<>()); // */ // for (int d = 1; d <= MAX; d++) { // for (int v = d; v <= MAX; v += d) { // divisors[v].add(d); // } // } // System.out.println(Arrays.toString(divisors)); // System.out.println(Arrays.toString(divisors)); int[] mobius = new int[MAX + 1]; mobius[1] = 1; /* key idea/fact: Convolution of mobius with `1` (identity function) = epsilon (1 if x = 1, 0 otherwise) mobius(divisors of 1) = 1 mobius(divisors of p^k) = 1 + -1 + 0 + 0 + ... = 0 Since mobius is multiplicative, we can check the cases (square-free case: sign = parity of number of primes is multiplicative) (not square-free case: multiplying two non square-free numbers is another non-squarefree number, so still 0) mobius(divisors of p1^k p2^k...) = mobius(divisors of p1^k) + ... = 0 Thus, mu(x) + mu(divisors) = 0 (if x > 1) mu(x) = -mu(divisors) */ for (int v = 2; v <= MAX; v++) { for (int d : divisors[v]) { if (d != v) mobius[v] -= mobius[d]; } } // System.out.println(Arrays.toString(mobius)); long[] dp = new long[MAX + 1]; for (int v : a) { for (int d : divisors[v]) { if (dp[d] == 0) dp[d] = 1; dp[d] = (2 * dp[d]) % mod; } } long ans = 0; for (int i = 1; i <= MAX; i++) { if (dp[i] != 0) { ans = (ans + mobius[i] * (dp[i] - 1)) % mod; } } if (ans < 0) // key bug! NEG ANSWER ans += mod; out.println(ans); out.close(); } static long mod = (long) 1e9 + 7; static class FastScanner { private int BS = 1 << 16; private char NC = (char) 0; private byte[] buf = new byte[BS]; private int bId = 0, size = 0; private char c = NC; private double cnt = 1; private BufferedInputStream in; public FastScanner() { in = new BufferedInputStream(System.in, BS); } public FastScanner(String s) { try { in = new BufferedInputStream(new FileInputStream(new File(s)), BS); } catch (Exception e) { in = new BufferedInputStream(System.in, BS); } } private char getChar() { while (bId == size) { try { size = in.read(buf); } catch (Exception e) { return NC; } if (size == -1) return NC; bId = 0; } return (char) buf[bId++]; } public int nextInt() { return (int) nextLong(); } public int[] nextInts(int N) { int[] res = new int[N]; for (int i = 0; i < N; i++) { res[i] = (int) nextLong(); } return res; } public long[] nextLongs(int N) { long[] res = new long[N]; for (int i = 0; i < N; i++) { res[i] = nextLong(); } return res; } public long nextLong() { cnt = 1; boolean neg = false; if (c == NC) c = getChar(); for (; (c < '0' || c > '9'); c = getChar()) { if (c == '-') neg = true; } long res = 0; for (; c >= '0' && c <= '9'; c = getChar()) { res = (res << 3) + (res << 1) + c - '0'; cnt *= 10; } return neg ? -res : res; } public double nextDouble() { double cur = nextLong(); return c != '.' ? cur : cur + nextLong() / cnt; } public double[] nextDoubles(int N) { double[] res = new double[N]; for (int i = 0; i < N; i++) { res[i] = nextDouble(); } return res; } public String next() { StringBuilder res = new StringBuilder(); while (c <= 32) c = getChar(); while (c > 32) { res.append(c); c = getChar(); } return res.toString(); } public String nextLine() { StringBuilder res = new StringBuilder(); while (c <= 32) c = getChar(); while (c != '\n') { res.append(c); c = getChar(); } return res.toString(); } public boolean hasNext() { if (c > 32) return true; while (true) { c = getChar(); if (c == NC) return false; else if (c > 32) return true; } } } static void ASSERT(boolean assertion, String message) { if (!assertion) throw new AssertionError(message); } static void ASSERT(boolean assertion) { if (!assertion) throw new AssertionError(); } }
Java
["3\n1 2 3", "4\n1 1 1 1", "7\n1 3 5 15 3 105 35"]
2 seconds
["5", "15", "100"]
NoteIn the first example coprime subsequences are: 1 1, 2 1, 3 1, 2, 3 2, 3 In the second example all subsequences are coprime.
Java 8
standard input
[ "combinatorics", "number theory", "bitmasks" ]
2e6eafc13ff8dc91e6803deeaf2ecea5
The first line contains one integer number n (1 ≤ n ≤ 100000). The second line contains n integer numbers a1, a2... an (1 ≤ ai ≤ 100000).
2,000
Print the number of coprime subsequences of a modulo 109 + 7.
standard output
PASSED
5099f40915fb485e4ce177678634c38e
train_003.jsonl
1493391900
Let's call a non-empty sequence of positive integers a1, a2... ak coprime if the greatest common divisor of all elements of this sequence is equal to 1.Given an array a consisting of n positive integers, find the number of its coprime subsequences. Since the answer may be very large, print it modulo 109 + 7.Note that two subsequences are considered different if chosen indices are different. For example, in the array [1, 1] there are 3 different subsequences: [1], [1] and [1, 1].
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Hieu Le */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskF solver = new TaskF(); solver.solve(1, in, out); out.close(); } static class TaskF { private static final int MAX_VALUE = (int) 1e5; private static final long MOD = (long) 1e9 + 7; private long[] powers; public TaskF() { powers = new long[MAX_VALUE + 1]; powers[0] = 1; for (int i = 1; i < powers.length; ++i) powers[i] = powers[i - 1] * 2 % MOD; } public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int[] nMultiples = new int[MAX_VALUE + 1]; for (int i = 0; i < n; ++i) { int value = in.nextInt(); int upperBound = (int) Math.sqrt(value); for (int d = 1; d <= upperBound; ++d) { if (value % d == 0) { nMultiples[d]++; if (d != value / d) nMultiples[value / d]++; } } } long result = 0; for (int i = 1; i < nMultiples.length; ++i) { if (nMultiples[i] > 0) { int mobiusValue = calcMobius(i); long increase = (MOD + mobiusValue) * (powers[nMultiples[i]] + MOD - 1) % MOD; result = (result + increase) % MOD; } } out.println(result); } private int calcMobius(int n) { int primeDivisor = 2; int nPrimeDivisors = 0; int upperBound = (int) Math.sqrt(n); while (n > 1 && primeDivisor <= upperBound) { if (n % primeDivisor == 0) { ++nPrimeDivisors; int count = 0; while (n % primeDivisor == 0) { ++count; n /= primeDivisor; } if (count > 1) return 0; } ++primeDivisor; } if (n > 1) { ++nPrimeDivisors; } return nPrimeDivisors % 2 == 0 ? 1 : -1; } } static class InputReader { private BufferedReader reader; private StringTokenizer tokenizer; private static final int BUFFER_SIZE = 32768; public InputReader(InputStream stream) { reader = new BufferedReader( new InputStreamReader(stream), BUFFER_SIZE); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["3\n1 2 3", "4\n1 1 1 1", "7\n1 3 5 15 3 105 35"]
2 seconds
["5", "15", "100"]
NoteIn the first example coprime subsequences are: 1 1, 2 1, 3 1, 2, 3 2, 3 In the second example all subsequences are coprime.
Java 8
standard input
[ "combinatorics", "number theory", "bitmasks" ]
2e6eafc13ff8dc91e6803deeaf2ecea5
The first line contains one integer number n (1 ≤ n ≤ 100000). The second line contains n integer numbers a1, a2... an (1 ≤ ai ≤ 100000).
2,000
Print the number of coprime subsequences of a modulo 109 + 7.
standard output