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 | 1a13383d6534ffb88536cd9170546587 | train_004.jsonl | 1410103800 | Over time, Alexey's mail box got littered with too many letters. Some of them are read, while others are unread.Alexey's mail program can either show a list of all letters or show the content of a single letter. As soon as the program shows the content of an unread letter, it becomes read letter (if the program shows the content of a read letter nothing happens). In one click he can do any of the following operations: Move from the list of letters to the content of any single letter. Return to the list of letters from single letter viewing mode. In single letter viewing mode, move to the next or to the previous letter in the list. You cannot move from the first letter to the previous one or from the last letter to the next one.The program cannot delete the letters from the list or rearrange them.Alexey wants to read all the unread letters and go watch football. Now he is viewing the list of all letters and for each letter he can see if it is read or unread. What minimum number of operations does Alexey need to perform to read all unread letters? | 256 megabytes | import java.util.Scanner;
public class B {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int [] a = new int[n+1];
int f=0,l=0;
for (int i = 1; i <= n; i++) {
a[i] = sc.nextInt();
if(a[i]==1){l=i;}
f+=a[i];
}
if(f==1){System.out.println("1");return;}
int k = 0; boolean rost = false;
for (int i = 1; i <=l; i++) {
if (a[i]==1) {
k++; rost = true;
}else if(rost){
k++; rost = false;
}
}
System.out.println(k);
}
}
| Java | ["5\n0 1 0 1 0", "5\n1 1 0 0 1", "2\n0 0"] | 1 second | ["3", "4", "0"] | NoteIn the first sample Alexey needs three operations to cope with the task: open the second letter, move to the third one, move to the fourth one.In the second sample the action plan: open the first letter, move to the second letter, return to the list, open the fifth letter.In the third sample all letters are already read. | Java 7 | standard input | [
"implementation"
] | 0fbc306d919d7ffc3cb02239cb9c2ab0 | The first line contains a single integer n (1 ≤ n ≤ 1000) — the number of letters in the mailbox. The second line contains n space-separated integers (zeros and ones) — the state of the letter list. The i-th number equals either 1, if the i-th number is unread, or 0, if the i-th letter is read. | 1,000 | Print a single number — the minimum number of operations needed to make all the letters read. | standard output | |
PASSED | 685f443691e751d85dad58036f144333 | train_004.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 random_practiceQuestions;
import java.util.*;
public class E1360 {
public static void main(String[] args){
Scanner s = new Scanner(System.in);
int a = s.nextInt();
String ytguyh = s.nextLine();
for (int i=0;i<a;i++){
int length = s.nextInt();
String ytguyhiu = s.nextLine();
int[][] list = new int[length][length];
for (int j=0;j<length;j++){
String row = s.nextLine();
int[] l = new int[length];
for (int k=0;k<row.length();k++){
l[k]=Integer.parseInt(row.substring(k,k+1));
}
list[j]=l;
}
boolean check=true;
for (int row=0;row<list.length-1;row++){
if (!check){
break;
}
for (int column = 0;column<list.length-1;column++){
if (list[row][column]==1){
boolean c = list[row+1][column]==1 || list[row][column+1]==1;
check = c&✓
}
if (!check){
break;
}
}
}
if (check){
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 | b0f09aa58a4a1d2cc9835b0e864553a5 | train_004.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 Main {
public static void main(String[] args) {
MyScanner sc = new MyScanner();
int testCasesQuantity = sc.nextInt();
out = new PrintWriter(new BufferedOutputStream(System.out));
for (int i = 0; i < testCasesQuantity; i++) {
int testCaseLength = sc.nextInt();
int[][] testCase = new int[testCaseLength][testCaseLength];
for (int j = 0; j < testCaseLength; j++) {
testCase[j] = sc.nextIntArray();
}
boolean validCase = true;
for (int j = 0; j < testCaseLength; j++) {
for (int k = 0; k < testCaseLength; k++) {
if (!isValidTraining(j, k, testCase)) {
validCase = false;
break;
}
}
}
if (validCase) {
System.out.println("YES");
} else {
System.out.println("NO");
}
}
out.close();
}
public static boolean isValidTraining(int i, int j, int[][] testCase) {
if (testCase[i][j]==0)
return true;
else if (i == testCase.length - 1) {
return true;
} else if (j == testCase[i].length - 1) {
return true;
} else if (testCase[i + 1][j] == 1) {
return true;
} else {
return testCase[i][j + 1] == 1;
}
}
public static PrintWriter out;
public static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
int[] nextIntArray() {
return next().chars().map(Character::getNumericValue).toArray();
}
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 | fa7bc820137c4836d07656ef19960695 | train_004.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 Solution {
public static void main(String[] args) {
var scanner = new Scanner(System.in);
var result = new StringBuilder();
String tStr = scanner.nextLine();
int t = Integer.parseInt(tStr);
for (var i = 0; i < t; i++) {
int n = Integer.parseInt(scanner.nextLine());
int[][] expectedResult = new int[n][n];
for (var j = 0; j < n; j++) {
String[] split = scanner.nextLine().split("");
for (var k = 0; k < split.length; k++) {
expectedResult[j][k] = Integer.parseInt(split[k]);
}
}
long l = System.nanoTime();
result.append(questionE(n, expectedResult));
if (i != t - 1) result.append("\n");
}
System.out.print(result);
// System.out.println(questionE(3, new int[][] {
// {1, 1, 1},
// {1, 1, 1},
// {1, 1, 1}
// }));
}
private static String questionE(int n, int[][] trainingResult) {
List<Point> unvisitedPoints = new LinkedList<>();
Set<Point> visitedPoints = new HashSet<>();
for (var row = 0; row < n; row++) {
for (var col = 0; col < n; col++) {
if (trainingResult[row][col] == 1) {
unvisitedPoints.add(new Point(row, col));
}
}
}
for (Point point : unvisitedPoints) {
if (visitedPoints.contains(point)) {
continue;
}
if (!dfs(n, trainingResult, point, new HashSet<>(), visitedPoints)) {
return "NO";
}
}
return "YES";
}
private static boolean dfs(int n, int[][] trainingResult, Point point, Set<Point> currentPaths, Set<Point> visitedPoints) {
currentPaths.add(point);
if (visitedPoints.contains(point)) {
visitedPoints.addAll(currentPaths);
currentPaths.remove(point);
return true;
}
if (point.row == n - 1 || point.col == n - 1) {
visitedPoints.addAll(currentPaths);
currentPaths.remove(point);
return true;
}
if (trainingResult[point.row + 1][point.col] == 0 && trainingResult[point.row][point.col + 1] == 0) {
currentPaths.remove(point);
return false;
}
if (trainingResult[point.row + 1][point.col] == 1) {
Point nextPoint = new Point(point.row + 1, point.col);
if (!dfs(n, trainingResult, nextPoint, currentPaths, visitedPoints)) {
currentPaths.remove(point);
return false;
}
}
if (trainingResult[point.row][point.col + 1] == 1) {
Point nextPoint = new Point(point.row, point.col + 1);
if (!dfs(n, trainingResult, nextPoint, currentPaths, visitedPoints)) {
currentPaths.remove(point);
return false;
}
}
currentPaths.remove(point);
return true;
}
static class Point {
int row;
int col;
public Point(int row, int col) {
this.row = row;
this.col = col;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Point point = (Point) o;
return row == point.row &&
col == point.col;
}
@Override
public int hashCode() {
return Objects.hash(row, col);
}
}
private static int questionD(int n, int k) {
if (k >= n) return 1;
if (k == 1) return n;
for (var i = 2; i * i <= n; i++) {
if (n % i == 0 && n / i <= k) {
return i;
}
}
return n;
}
}
| 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 | 2668c89397cd417b439ad62391e85413 | train_004.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 Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int t = Integer.parseInt(scan.nextLine());
String line;
int[][] nums;
boolean yes;
for (int i = 0; i < t; i++) {
int n = Integer.parseInt(scan.nextLine());
nums = new int[n][n];
yes = true;
for (int j = 0; j < n; j++) {
line = scan.nextLine();
for (int k = 0; k < n; k++) {
nums[j][k] = Integer.parseInt(Character.toString(line.charAt(k)));
}
}
for (int j = 0; j < n; j++) {
for (int k = 0; k < n; k++) {
if (j != n - 1 && k != n - 1) {
if ((nums[j][k] == 1) && (nums[j + 1][k] != 1 && nums[j][k + 1] != 1)) {
yes = false;
break;
}
}
}
if (!yes) break;
}
if (yes) 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 | 41e72c2567f6a2a92ae71f8b23a0ddd0 | train_004.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;
import java.util.*;
public class file {
private static final Scanner scn = new Scanner(System.in);
private static void foo() {
int n = scn.nextInt();
int[][] arr = new int[n][n];
for (int i = 0; i < n; i++) {
String line = scn.next();
for(int j = 0 ; j < line.length(); j++) {
arr[i][j] = line.charAt(j)-'0';
}
}
boolean check = true;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (arr[i][j] == 1) {
if (j+1 == n || i+1 == n) check = true;
else if (arr[i+1][j] == 1 || arr[i][j+1] == 1) check = true;
else {
check = false;
System.out.println("NO");
return;
}
}
}
}
System.out.println(check ? "YES" : "NO");
}
public static void main(String[] args) {
int t = scn.nextInt();
while (t-- > 0) {
foo();
}
}
}
| 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 | 6c6bc8a95e7a3f6e52831913de11fe82 | train_004.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 Main {
public static void main(String[] args) throws Exception {
new Main().go();
}
PrintWriter out;
Reader in;
BufferedReader br;
Main() throws IOException {
try {
//br = new BufferedReader( new FileReader("input.txt") );
//in = new Reader("input.txt");
in = new Reader("input.txt");
out = new PrintWriter( new BufferedWriter(new FileWriter("output.txt")) );
}
catch (Exception e) {
//br = new BufferedReader( new InputStreamReader( System.in ) );
in = new Reader();
out = new PrintWriter( new BufferedWriter(new OutputStreamWriter(System.out)) );
}
}
void go() throws Exception {
//int t = in.nextInt();
int t = 1;
while (t > 0) {
solve();
t--;
}
out.flush();
out.close();
}
int inf = 2000000000;
int mod = 1000000007;
double eps = 0.000000001;
int n;
int m;
ArrayList<Integer>[] g;
int[] a;
void solve() throws IOException {
int t = in.nextInt();
while (t > 0) {
int n = in.nextInt();
int[][] a = new int[n][n];
for (int i = 0; i < n; i++) {
String s = in.nextLine();
for (int j = 0; j < n; j++)
a[i][j] = s.charAt(j) - '0';
}
boolean ok = true;
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
if (a[i][j] == 1) {
if (i != n - 1 && j != n - 1) {
ok &= a[i][j + 1] == 1 || a[i + 1][j] == 1;
}
}
out.println(ok ? "YES" : "NO");
t--;
}
}
static class Pair<A extends Comparable<A>, B extends Comparable<B>> implements Comparable<Pair<A, B>> {
public final A a;
public final B b;
Pair(A a, B b) {
this.a = a;
this.b = b;
}
public int compareTo(Pair<A, B> p) {
if (!a.equals(p.a))
return a.compareTo(p.a);
else
return b.compareTo(p.b);
}
}
class Item {
int a;
int b;
int c;
Item(int a, int b, int c) {
this.a = a;
this.b = b;
this.c = c;
}
}
class Reader {
BufferedReader br;
StringTokenizer tok;
Reader(String file) throws IOException {
br = new BufferedReader( new FileReader(file) );
}
Reader() throws IOException {
br = new BufferedReader( new InputStreamReader(System.in) );
}
String next() throws IOException {
while (tok == null || !tok.hasMoreElements())
tok = new StringTokenizer(br.readLine());
return tok.nextToken();
}
int nextInt() throws NumberFormatException, IOException {
return Integer.valueOf(next());
}
long nextLong() throws NumberFormatException, IOException {
return Long.valueOf(next());
}
double nextDouble() throws NumberFormatException, IOException {
return Double.valueOf(next());
}
String nextLine() throws IOException {
return br.readLine();
}
}
static class InputReader
{
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public InputReader()
{
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public InputReader(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 | ["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 | a2fbf08b5a81068b07feae8b46f263dd | train_004.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) {
Scanner input = new Scanner(System.in);
int t = input.nextInt();
while(t>0) {
int n = input.nextInt();
char[][] matrix = new char[n][n];
String s1= new String();
String s2 = new String();
for(int i = 0; i<n; i++) {
s2 = input.next();
s1 += s2;
}
int index = 0;
for(int i =0; i<n; i++) {
for(int j=0; j<n; j++) {
matrix[i][j] = s1.charAt(index);
index++;
}
}
boolean exist = true;
for(int i =0; i<n-1; i++) {
for(int j=0; j<n-1; j++) {
if(matrix[i][j]=='1'&&matrix[i+1][j]=='0'&&matrix[i][j+1]=='0') {
exist = false;
}
}
}
if(exist) {
System.out.println("YES");
}
else {
System.out.println("NO");
}
t--;
}
input.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 | dcc71ef687cacd352c8ad25d446101bf | train_004.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 {
// File file = new File("input.txt");
// Scanner in = new Scanner(file);
// PrintWriter out = new PrintWriter(new FileWriter("output.txt"));
public static void main(String[] args) {
// Scanner in = new Scanner(System.in);
FastReader in = new FastReader();
int t = in.nextInt();
while(t-- > 0) {
int n = in.nextInt();
int[][] a = new int[n][n];
for(int i = 0; i<n; i++) {
String k = in.next();
for(int j = 0; j<k.length(); j++) {
a[i][j] = (int)(k.charAt(j)-'0');
}
}
boolean ans = true;
for(int i = 0; i<n; i++) {
for(int j = 0; j<n; j++) {
if(a[i][j]==1) {
if(j==n-1 || i==n-1 || a[i][j+1]==1 || a[i+1][j]==1) {
// do nothing
}else {
ans = false;
break;
}
}
}
if(!ans) break;
}
if(!ans) System.out.println("No");
else System.out.println("Yes");
}
}
private static int gcd(int a, int b) {
if(b==0) return a;
return gcd(b, a%b);
}
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 | ["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 | 1a5925517dd7f995d96a4e0743fa9e59 | train_004.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;
import java.lang.Math;
public class Hello{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
for(int i = 0; i<t; i++){
int n = sc.nextInt();
String[] field = new String[n];
sc.nextLine();
for(int j = 0; j<n;j++)
field[j] = sc.nextLine();
boolean possible = true;
for(int j = 0; j<n; j++)
for(int k = 0; k<n;k++)
if(field[j].charAt(k)=='1' &&!(k==n-1 || j==n-1 ||field[j].charAt(k+1) == '1'||field[j+1].charAt(k)=='1'))
possible = false;
System.out.println(possible? "YES" : "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 | de599bdbee737abc06ba84a5c1f5834d | train_004.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 TestClass {
public static void main(String args[]) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(br.readLine());
for(int cases = 0; cases < t; cases++){
int n = Integer.parseInt(br.readLine());
int done = 0;
String first = br.readLine();
String second = "";
for(int j = 0; j<n-1; j++) {
second = br.readLine();
for(int i = 0; i<n;i++) {
if(first.charAt(i) == '1' && done == 0) {
if(second.charAt(i) == '0') {
if(i<n-1 && first.charAt(i+1) == '0') {
done = 1;
break;
}
}
}
}
first = second;
}
if(done == 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 | 7279cf981d56a870e61fca45de7daa81 | train_004.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 {
public static void main(String[] args) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(br.readLine());
StringBuilder ans = new StringBuilder();
for(int tc = 1; tc <= t; ++tc) {
int n = Integer.parseInt(br.readLine());
int[][] arr = new int[n][n];
for(int i = 0; i < n; ++i) {
String line = br.readLine();
for(int j = 0; j < n; ++j) {
arr[i][j] = line.charAt(j)-'0';
}
}
boolean check = true;
f: for(int i = 0; i < n-1; ++i) {
for(int j = 0; j < n-1; ++j) {
if(arr[i][j] == 1) {
if(arr[i+1][j] == 1 || arr[i][j+1] == 1) {
// ok
}else {
check = false;
break f;
}
}
}
}if(check) {
ans.append("YES\n");
}else {
ans.append("NO\n");
}
}
System.out.println(ans);
}
} | 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 | a669824acb9f332350c3f354e37841ed | train_004.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 Mat{
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
while(t-->0){
int n=sc.nextInt();
int arr[][]=new int[n][n];
for(int i=0;i<n;i++){
char chararr[]=sc.next().toCharArray();
for (int j=0;j<n;j++)
arr[i][j]=(int)chararr[j] -48;
}
int res=1;
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
if(arr[i][j]==1){
if(i+1==n|| j+1==n || arr[i][j+1]==1 || arr[i+1][j]==1)
res=1;
else{
// System.out.println("found for "+i+" "+j);
res=0;
break;
}
}
}
if(res==0)
break;
}
if(res==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 | f1b42794b563d7c2ca2d622ce1378bbb | train_004.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 Problem1360e {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while(t-->0) {
int n = sc.nextInt();
int[][] matrix = new int[n][n];
for(int i = 0; i < n; i++) {
String row = sc.next();
for(int j = 0; j < n; j++) {
matrix[i][j] = row.charAt(j);
}
}
boolean ans = true;
for (int i = n - 2; i >= 0; i--) {
for (int j = n - 2; j >= 0; j--) {
boolean ij;
boolean i1j;
boolean ij1;
if(matrix[i][j] == '0') {
ij = false;
}
else {
ij = true;
}
if(matrix[i+1][j] == '0') {
i1j = false;
}
else {
i1j = true;
}
if(matrix[i][j+1] == '0') {
ij1 = false;
}
else {
ij1 = true;
}
if (ij && !i1j && !ij1) {
ans = false;
}
}
}
System.out.println(ans ? "YES" : "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 | 43749b26e70c6da199d23590af021470 | train_004.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.lang.*;
public class Polygon{
public static void main(String[] args)throws IOException{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(in.readLine());
while(t-->0){
int n = Integer.parseInt(in.readLine());
int[][] matrix = new int[n][n];
for(int i = 0; i<n ;i++){
String temp = in.readLine();
for(int j = 0; j<n ; j++)
matrix[i][j] = Integer.parseInt(String.valueOf(temp.charAt(j)));
}
boolean flag = true;
for(int i = 0; i < n-1 && flag; i++){
for(int j = 0; j<n-1 && flag; j++){
if(matrix[i][j]==1 && matrix[i][j+1]==0 && matrix[i+1][j]==0){
flag = false;
}
}
}
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 | 50a6d1dd669501a52f121af852f40a71 | train_004.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.util.*;
import java.lang.*;
import java.io.*;
public class Codechef
{
public static void main (String[] args) throws java.lang.Exception
{
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
while(t-->0)
{
int n=sc.nextInt();
int a[][]=new int[n][n];
for( int i=0;i<n;i++)
{
String str=sc.next();
for( int j=0;j<n;j++)
{
a[i][j]=(int)(str.charAt(j)-'0');
}
}
boolean vis[][]=new boolean[n][n];
for( int j=n-1;j>=0;j--)
{
for( int i=n-1;i>=0;i--)
{
if(a[i][j]==1)
{
vis[i][j]=true;
}
else
break;
}
}
for( int i=n-1;i>=0;i--)
{
for( int j=n-1;j>=0;j--)
{
if(a[i][j]==1)
{
vis[i][j]=true;
}
else
break;
}
}
boolean check=true;
for( int i=n-1;i>=0;i--)
{
for( int j=n-1;j>=0;j--)
{
if(a[i][j]==1&&vis[i][j]==true)
{
for( int k=i-1;k>=0;k--)
{
if(a[k][j]==1)
vis[k][j]=true;
else
break;
}
for( int k=j-1;k>=0;k--)
{
if(a[i][k]==1)
vis[i][k]=true;
else
break;
}
}
}
}
for( int i=0;i<n;i++)
{
for( int j=0;j<n;j++)
{
if(a[i][j]==1&&vis[i][j]==false)
{
check=false;
break;
}
}
}
if(check)
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 | 75ce43899529c985704788e462ac03a8 | train_004.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.io.FilterInputStream;
import java.io.BufferedInputStream;
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;
ScanReader in = new ScanReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
EPolygon solver = new EPolygon();
solver.solve(1, in, out);
out.close();
}
static class EPolygon {
int[][] arr;
int n;
boolean[][] visited;
int[] dx = new int[]{-1, 0};
int[] dy = new int[]{0, -1};
public void solve(int testNumber, ScanReader in, PrintWriter out) {
int t = in.scanInt();
while (t-- > 0) {
n = in.scanInt();
arr = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
arr[i][j] = in.scanChar() - '0';
}
}
if (canMake()) {
out.println("YES");
} else {
out.println("NO");
}
}
}
boolean canMake() {
visited = new boolean[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (i == n - 1 || j == n - 1) {
if (arr[i][j] == 1) {
if (!visited[i][j]) {
dfs(i, j);
}
}
}
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (arr[i][j] == 1 && !visited[i][j]) return false;
}
}
return true;
}
boolean isvalid(int i, int j) {
return i >= 0 && j >= 0 && i < n && j < n;
}
void dfs(int i, int j) {
visited[i][j] = true;
for (int k = 0; k < 2; k++) {
int nx = i + dx[k];
int ny = j + dy[k];
if (isvalid(nx, ny) && !visited[nx][ny] && arr[nx][ny] == 1) {
dfs(nx, ny);
}
}
}
}
static class ScanReader {
private byte[] buf = new byte[4 * 1024];
private int INDEX;
private BufferedInputStream in;
private int TOTAL;
public ScanReader(InputStream inputStream) {
in = new BufferedInputStream(inputStream);
}
private int scan() {
if (INDEX >= TOTAL) {
INDEX = 0;
try {
TOTAL = in.read(buf);
} catch (Exception e) {
e.printStackTrace();
}
if (TOTAL <= 0) return -1;
}
return buf[INDEX++];
}
public char scanChar() {
int c = scan();
while (isWhiteSpace(c)) c = scan();
return (char) c;
}
public int scanInt() {
int I = 0;
int n = scan();
while (isWhiteSpace(n)) n = scan();
int neg = 1;
if (n == '-') {
neg = -1;
n = scan();
}
while (!isWhiteSpace(n)) {
if (n >= '0' && n <= '9') {
I *= 10;
I += n - '0';
n = scan();
}
}
return neg * I;
}
private boolean isWhiteSpace(int n) {
if (n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1) return true;
else return false;
}
}
}
| 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 | dc2b764c128b35160f194b49ca3d911f | train_004.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 Solution{
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
for(int k=0;k<t;k++){
int n=sc.nextInt();
int arr[][]=toArray(sc,n);
boolean flag=false;
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
if(arr[i][j]==1){
if(i!=(n-1) && j!=(n-1)){
if(arr[i+1][j]!=1 && arr[i][j+1]!=1){
System.out.println("NO");
flag=true;
break;
}
}
}
}
if(flag)
break;
}
if(!flag)
System.out.println("YES");
}
}
static int[][] toArray(Scanner sc,int n){
int a[][]=new int[n][n];
for(int i=0;i<n;i++){
String s=sc.next();
//System.out.println(s);
for(int j=0;j<n;j++){
a[i][j]=s.charAt(j)-'0';
}
}
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 | 223c8a4dcf528facaacfc95725f7749a | train_004.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 | /*
Author: Anthony Ngene
Created: 05/08/2020 - 06:56
*/
import java.io.*;
import java.util.*;
public class E {
// Being deeply loved by someone gives you strength, while loving someone deeply gives you courage. - Lao Tzu
public static void main(String[] args) throws IOException {
in = new FastScanner();
int cases = in.intNext();
for (int t = 1; t <= cases; t++) {
int n = in.intNext();
char[][] grid = new char[n][];
for (int i = 0; i < n; i++) grid[i] = in.next().toCharArray();
out.println(solve(n, grid));
}
out.close();
}
static String solve(int n, char[][] grid) {
for (int i = n - 1; i >= 0; i--) {
for (int j = n - 1; j >= 0; j--) {
char ch = grid[i][j];
if (i == n - 1 || j == n - 1 || ch == '0' || grid[i][j+1] == '1' || grid[i+1][j] == '1') continue;
return "NO";
}
}
return "YES";
}
private static final FastWriter out = new FastWriter();
private static FastScanner in;
static ArrayList<Integer>[] adj;
private static long e97 = (long)1e9 + 7;
static class FastWriter {
private static final int IO_BUFFERS = 128 * 1024;
private final StringBuilder out;
public FastWriter() {
out = new StringBuilder(IO_BUFFERS);
}
public FastWriter p(Object object) {
out.append(object);
return this;
}
public FastWriter p(String format, Object... args) {
out.append(String.format(format, args));
return this;
}
public FastWriter pp(Object... args) {
for (Object ob : args) {
out.append(ob).append(" ");
}
out.append("\n");
return this;
}
public FastWriter println(Object object) {
out.append(object).append("\n");
return this;
}
public void toFile(String fileName) throws IOException {
BufferedWriter writer = new BufferedWriter(new FileWriter(fileName));
writer.write(out.toString());
writer.close();
}
public void close() throws IOException {
System.out.print(out);
}
}
static class FastScanner {
private InputStream sin = System.in;
private final byte[] buffer = new byte[1024];
private int ptr = 0;
private int buflen = 0;
public FastScanner(){}
public FastScanner(String filename) throws FileNotFoundException {
File file = new File(filename);
sin = new FileInputStream(file);
}
private boolean hasNextByte() {
if (ptr < buflen) {
return true;
}else{
ptr = 0;
try {
buflen = sin.read(buffer);
} catch (IOException e) {
e.printStackTrace();
}
if (buflen <= 0) {
return false;
}
}
return true;
}
private int readByte() { if (hasNextByte()) return buffer[ptr++]; else return -1;}
private static boolean isPrintableChar(int c) { return 33 <= c && c <= 126;}
public boolean hasNext() { while(hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++; return hasNextByte();}
public String next() {
if (!hasNext()) throw new NoSuchElementException();
StringBuilder sb = new StringBuilder();
int b = readByte();
while(isPrintableChar(b)) {
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
public long longNext() {
if (!hasNext()) throw new NoSuchElementException();
long n = 0;
boolean minus = false;
int b = readByte();
if (b == '-') {
minus = true;
b = readByte();
}
if (b < '0' || '9' < b) {
throw new NumberFormatException();
}
while(true){
if ('0' <= b && b <= '9') {
n *= 10;
n += b - '0';
}else if(b == -1 || !isPrintableChar(b) || b == ':'){
return minus ? -n : n;
}else{
throw new NumberFormatException();
}
b = readByte();
}
}
public int intNext() {
long nl = longNext();
if (nl < Integer.MIN_VALUE || nl > Integer.MAX_VALUE) throw new NumberFormatException();
return (int) nl;
}
public double doubleNext() { return Double.parseDouble(next());}
public long[] nextLongArray(final int n){
final long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = longNext();
return a;
}
public int[] nextIntArray(final int n){
final int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = intNext();
return a;
}
public ArrayList<Integer>[] getAdj(int n) {
ArrayList<Integer>[] adj = new ArrayList[n + 1];
for (int i = 1; i <= n; i++) adj[i] = new ArrayList<>();
return adj;
}
public ArrayList<Integer>[] adjacencyList(int n, int m) throws IOException {
adj = getAdj(n);
for (int i = 0; i < m; i++) {
int a = intNext(), b = intNext();
adj[a].add(b);
adj[b].add(a);
}
return adj;
}
}
}
| 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 | a11bf5c4176a521251e810ce7578046f | train_004.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 Compression {
static void solve(int[][] matrix) {
for (int i = 0; i < matrix.length; i++) {
if (matrix[i][matrix.length - 1] == 1) {
dfs(matrix, i, matrix.length - 1);
}
if (matrix[matrix.length - 1][i] == 1) {
dfs(matrix, matrix.length - 1, i);
}
}
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix.length; j++) {
if (matrix[i][j] == 1) {
System.out.println("NO");
return;
}
}
}
System.out.println("YES");
}
static void dfs(int[][] matrix, int i, int j) {
if (i < 0 || j < 0 || matrix[i][j] == 0) {
return;
}
matrix[i][j] = 0;
dfs(matrix, i - 1, j);
dfs(matrix, i, j - 1);
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int t = scanner.nextInt();
for (int i = 0; i < t; i++) {
int n = scanner.nextInt();
int[][] matrix = new int[n][n];
for (int j = 0; j < n; j++) {
String string = scanner.next();
for (int k = 0; k < n; k++) {
matrix[j][k] = Integer.parseInt(String.valueOf(string.charAt(k)));
}
}
solve(matrix);
}
}
}
| 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 | 1b2b9414efdd09ef85aeccf9e99ab286 | train_004.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.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
while(n>0) {
n--;
int k = scan.nextInt();
char[][] array = new char[k][k];
for(int i=0;i<k;i++) {
String str = scan.next();
for(int j=0;j<k;j++) {
array[i][j] = str.charAt(j);
}
}
boolean end = false;
for(int i=0;i<k-1;i++) {
for(int j=0;j<k-1;j++) {
if(array[i][j] == '1' && array[i+1][j] == '0' && array[i][j+1] == '0') {
end = true;
}
}
if(end) {
System.out.println("NO");
break;
}
}
if(!end) {
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 | 5e2c96471ade6cf94c8695edd6d1430f | train_004.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 Solution{
public static void fillTable(boolean[][] dp,char[][] mat){
int n = mat.length;
for(int j = 0 ; j < n ; j++){
if(mat[n-1][j] == '1'){
dp[n-1][j] = true;
}
if(mat[j][n-1] == '1'){
dp[j][n-1] = true;
}
}
}
public static void main(String []args){
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while(t > 0){
int n = sc.nextInt();
char[][] mat = new char[n][n];
for(int i = 0 ; i < n ; i++){
String s = sc.next();
for(int j = 0 ; j < n ; j++){
mat[i][j] = s.charAt(j);
//System.out.println(mat[i][j]);
}
sc.nextLine();
}
boolean[][] dp = new boolean[n][n];
boolean res = true;
fillTable(dp,mat);
for(int i = n - 2 ; i >= 0 ; i--){
for(int j = n - 2 ; j >= 0; j--){
if(mat[i][j] == '1'){
dp[i][j]=dp[i+1][j] | dp[i][j+1];
if(dp[i][j] == false){
res = false;
break;
}
}
}
if(res == false){
break;
}
}
if(res == true){
System.out.println("YES");
}
else{
System.out.println("NO");
}
//System.out.println(colors);
t -= 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 | 570e5c5a2c96436e0eb1058a7457d4d4 | train_004.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.*;
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;
}
}
static int t, n;
static int[][] arr;
public static void main(String args[]) throws Exception {
FastReader cin = new FastReader();
t = cin.nextInt();
for (int i = 0; i < t; i++) {
n = cin.nextInt();
arr = new int[n][n];
for (int j = 0; j < n; j++) {
String s = cin.nextLine();
for (int k = 0; k < n; k++) {
arr[j][k] = Character.getNumericValue(s.charAt(k));
}
}
boolean hasAns = true;
for (int j = 0; j < n; j++) {
for (int k = 0; k < n; k++) {
if (arr[j][k] == 1) {
boolean hasNext = false;
if (j == n - 1 || k == n - 1) {
hasNext = true;
}
if (k < n - 1) {
if (arr[j][k + 1] == 1) {
hasNext = true;
}
}
if (j < n - 1) {
if (arr[j + 1][k] == 1) {
hasNext = true;
}
}
if (!hasNext) {
hasAns = false;
}
}
}
}
if (hasAns) {
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 | ab567c56caccfbe31beb9a8ca1fb91b4 | train_004.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 codeforces
{
public static void main(String[] args)
{
Scanner s=new Scanner(System.in);
int t=s.nextInt();
for(int kk=0;kk<t;kk++)
{
int n=s.nextInt();
String arr[]=new String[n];
for(int i=0;i<n;i++)
arr[i]=s.next();
boolean ans=true;
for(int i=0;i<n&&ans;i++)
for(int j=0;j<n&&ans;j++)
{
boolean left=arr[i].charAt(j)=='1'&&(j+1<n)&&arr[i].charAt(j+1)=='0';
boolean down=arr[i].charAt(j)=='1'&&(i+1<n)&&arr[i+1].charAt(j)=='0';
if(left&&down)
ans=false;
}
System.out.println(ans?"YES":"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 | 614dc9d00305393e775463ee45252829 | train_004.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.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.PriorityQueue;
import java.util.Scanner;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.lang.Math.*;
import java.util.TreeSet;
public class Main {
static ArrayList<Integer> adj[];
static PrintWriter out = new PrintWriter(System.out);
public static long mod;
static int [][]notmemo;
static int k;
static int[] a;
static long b[];
static int m;
static char c[][];
static class Pair implements Comparable<Pair>{
int v,cost,energy;
public Pair(int a1,int a2,int e ) {
v=a1;
cost=a2;
energy=e;
}
@Override
public int compareTo(Pair o) {
if(o.energy==this.energy)
return this.cost-o.cost;
return o.energy-this.energy;
}
}
static Pair s1[];
static long s[];
static ArrayList<Pair> adjlist[];
static int n1;
static int n2;
static int k1;
static int k2;
static int skip=0;
public static void main(String args[]) throws IOException {
Scanner sc = new Scanner(System.in);
int t=sc.nextInt();
while(t-->0) {
int n=sc.nextInt();
char c[][]=new char[n][n];
for (int i = 0; i < c.length; i++) {
c[i]=sc.nextLine().toCharArray();
}
boolean f=true;
for (int i = 0; i < c.length-1; i++) {
for (int j = 0; j < c.length-1; j++) {
if(c[i][j]=='1') {
if(c[i+1][j]!='1'&&c[i][j+1]!='1') {
f=false;
}
}
}
}
if(f)
System.out.println("YES");
else
System.out.println("NO");
}
}
static int backtobackdp(int idx,int state) {
if(idx*2>n) {
return 1;
}
if(memo[idx][state]!=-1)
return memo[idx][state];
int ans=1;
int ans2=-1;
if(state==0)
ans2=backtobackdp(idx+1,0);
for (int i =idx*2; i <=n; i+=idx) {
if(a[idx]<a[i]) {
ans=Math.max(ans,1+backtobackdp(i,1));
}
}
return memo[idx][state]=Math.max(ans2,ans);
}
static int reali,realj;
static int dx[]= {1,-1,0,0};
static int dy[]= {0,0,1,-1};
static char curchar;
public static boolean ddfs(int i, int j, int size) {
boolean f=false;
for (int k = 0; k < dx.length; k++) {
int x=dx[k]+i;
int y=dy[k]+j;
if(valid(x,y,curchar)) {
if(visit[x][y]&&size>=4&&reali==x&&realj==y) {
// System.out.println(reali+" "+realj+" "+size);
// System.out.println(i+" "+j);
//
return true;
}
else if(!visit[x][y]){
visit[x][y]=true;
//System.out.println(x+" "+y+" "+size);
f|=ddfs(x,y,size+1);
}
}
}
return f;
}
public static boolean valid(int x, int y, char curchar2) {
if(x>=n||y>=m||x<0||y<0||c[x][y]!=curchar2) {
return false;
}
return true;
}
private static int lcm(int a2, int b2) {
return (a2*b2)/gcd(a2,b2);
}
static boolean visit[][];
static Boolean zero[][];
static int small[];
static void dfs(int s, int e)
{
small[s] = 1;
for(int u: adj[s])
{
if(u == e)
continue;
dfs(u ,s);
small[s] +=small[u];
}
}
static int idx=0;
static long dpdp[][][][];
static int modd=(int) 1e8;
static class Edge implements Comparable<Edge>
{
int node;long cost;
Edge(int a, long b) { node = a; cost = b; }
public int compareTo(Edge e){ return Long.compare(cost,e.cost); }
}
static void sieve(int N) // O(N log log N)
{
isComposite = new int[N+1];
isComposite[0] = isComposite[1] = 1; // 0 indicates a prime number
primes = new ArrayList<Integer>();
for (int i = 2; i <= N; ++i) //can loop till i*i <= N if primes array is not needed O(N log log sqrt(N))
if (isComposite[i] == 0) //can loop in 2 and odd integers for slightly better performance
{
primes.add(i);
if(1l * i * i <= N)
for (int j = i * i; j <= N; j += i) // j = i * 2 will not affect performance too much, may alter in modified sieve
isComposite[j] = 1;
}
}
static TreeSet<Integer> factors;
static ArrayList<Integer> primeFactors(int N) // O(sqrt(N) / ln sqrt(N))
{
ArrayList<Integer> factors = new ArrayList<Integer>(); //take abs(N) in case of -ve integers
int idx = 0, p = primes.get(idx);
while(1l*p * p <= N)
{
while(N % p == 0) { factors.add(p); N /= p; }
p = primes.get(++idx);
}
if(N != 1) // last prime factor may be > sqrt(N)
factors.add(N); // for integers whose largest prime factor has a power of 1
return factors;
}
static String y;
static int nomnom[];
static long fac[];
static boolean f = true;
static class SegmentTree { // 1-based DS, OOP
int N; // the number of elements in the array as a power of 2 (i.e. after padding)
int[] array, sTree, lazy;
SegmentTree(int[] in) {
array = in;
N = in.length - 1;
sTree = new int[N << 1]; // no. of nodes = 2*N - 1, we add one to cross out index zero
lazy = new int[N << 1];
//build(1, 1, N);
}
void build(int node, int b, int e) // O(n)
{
if (b == e)
sTree[node] = array[b];
else {
int mid = b + e >> 1;
build(node << 1, b, mid);
build(node << 1 | 1, mid + 1, e);
sTree[node] = sTree[node << 1] + sTree[node << 1 | 1];
}
}
void update_point(int index, int val) // O(log n)
{
index += N - 1;
sTree[index] = val;
while(index>1)
{
index >>= 1;
sTree[index] = Math.max(sTree[index<<1] ,sTree[index<<1|1]);
}
}
void update_range(int i, int j, int val) // O(log n)
{
update_range(1, 1, N, i, j, val);
}
void update_range(int node, int b, int e, int i, int j, int val) {
if (i > e || j < b)
return;
if (b >= i && e <= j) {
sTree[node] += (e - b + 1) * val;
lazy[node] += val;
} else {
int mid = b + e >> 1;
propagate(node, b, mid, e);
update_range(node << 1, b, mid, i, j, val);
update_range(node << 1 | 1, mid + 1, e, i, j, val);
sTree[node] = sTree[node << 1] + sTree[node << 1 | 1];
}
}
void propagate(int node, int b, int mid, int e) {
lazy[node << 1] += lazy[node];
lazy[node << 1 | 1] += lazy[node];
sTree[node << 1] += (mid - b + 1) * lazy[node];
sTree[node << 1 | 1] += (e - mid) * lazy[node];
lazy[node] = 0;
}
int query(int i, int j) {
return query(1, 1, N, i, j);
}
int query(int node, int b, int e, int i, int j) // O(log n)
{
if (i > e || j < b)
return 0;
if (b >= i && e <= j)
return sTree[node];
int mid = b + e >> 1;
// propagate(node, b, mid, e);
int q1 = query(node << 1, b, mid, i, j);
int q2 = query(node << 1 | 1, mid + 1, e, i, j);
return Math.max(q1,q2);
}
}
static int[][] memo;
static class UnionFind {
int[] p, rank, setSize;
int numSets;
int max[];
public UnionFind(int N) {
p = new int[numSets = N];
rank = new int[N];
setSize = new int[N];
for (int i = 0; i < N; i++) {
p[i] = i;
setSize[i] = 1;
}
}
public int findSet(int i) {
return p[i] == i ? i : (p[i] = findSet(p[i]));
}
public boolean isSameSet(int i, int j) {
return findSet(i) == findSet(j);
}
public int chunion(int i,int j, int x2) {
if (isSameSet(i, j))
return 0;
numSets--;
int x = findSet(i), y = findSet(j);
int z=findSet(x2);
p[x]=z;;
p[y]=z;
return x;
}
public void unionSet(int i, int j) {
if (isSameSet(i, j))
return;
numSets--;
int x = findSet(i), y = findSet(j);
if (rank[x] > rank[y]) {
p[y] = x;
setSize[x] += setSize[y];
} else {
p[x] = y;
setSize[y] += setSize[x];
if (rank[x] == rank[y])
rank[y]++;
}
}
public int numDisjointSets() {
return numSets;
}
public int sizeOfSet(int i) {
return setSize[findSet(i)];
}
}
/**
* private static void trace(int i, int time) { if(i==n) return;
*
*
* long ans=dp(i,time);
* if(time+a[i].t<a[i].burn&&(ans==dp(i+1,time+a[i].t)+a[i].cost)) {
*
* trace(i+1, time+a[i].t);
*
* l1.add(a[i].idx); return; } trace(i+1,time);
*
* }
**/
static class incpair implements Comparable<incpair> {
int a;
long b;
int idx;
incpair(int a, long dirg, int i) {
this.a = a;
b = dirg;
idx = i;
}
public int compareTo(incpair e) {
return (int) (b - e.b);
}
}
static class decpair implements Comparable<decpair> {
int a;
long b;
int idx;
decpair(int a, long dirg, int i) {
this.a = a;
b = dirg;
idx = i;
}
public int compareTo(decpair e) {
return (int) (e.b - b);
}
}
static long allpowers[];
static class Quad implements Comparable<Quad> {
int u;
int v;
char state;
int turns;
public Quad(int i, int j, char c, int k) {
u = i;
v = j;
state = c;
turns = k;
}
public int compareTo(Quad e) {
return (int) (turns - e.turns);
}
}
static long dirg[][];
static Edge[] driver;
static int n;
static long manhatandistance(long x, long x2, long y, long y2) {
return Math.abs(x - x2) + Math.abs(y - y2);
}
static long fib[];
static long fib(int n) {
if (n == 1 || n == 0) {
return 1;
}
if (fib[n] != -1) {
return fib[n];
} else
return fib[n] = ((fib(n - 2) % mod + fib(n - 1) % mod) % mod);
}
static class Point implements Comparable<Point>{
long x, y;
Point(long counth, long counts) {
x = counth;
y = counts;
}
@Override
public int compareTo(Point p )
{
return Long.compare(p.y*1l*x, p.x*1l*y);
}
}
static long[][] comb;
static class Triple implements Comparable<Triple> {
int l;
int r;
long cost;
int idx;
public Triple(int a, int b, long l1, int l2) {
l = a;
r = b;
cost = l1;
idx = l2;
}
public int compareTo(Triple x) {
if (l != x.l || idx == x.idx)
return l - x.l;
return -idx;
}
}
static TreeSet<Long> primeFactors(long N) // O(sqrt(N) / ln sqrt(N))
{
TreeSet<Long> factors = new TreeSet<Long>(); // take abs(N) in case of -ve integers
int idx = 0, p = primes.get(idx);
while (p * p <= N) {
while (N % p == 0) {
factors.add((long) p);
N /= p;
}
if (primes.size() > idx + 1)
p = primes.get(++idx);
else
break;
}
if (N != 1) // last prime factor may be > sqrt(N)
factors.add(N); // for integers whose largest prime factor has a power of 1
return factors;
}
static boolean visited[];
/**
* static int bfs(int s) { Queue<Integer> q = new LinkedList<Integer>();
* q.add(s); int count=0; int maxcost=0; int dist[]=new int[n]; dist[s]=0;
* while(!q.isEmpty()) {
*
* int u = q.remove(); if(dist[u]==k) { break; } for(Pair v: adj[u]) {
* maxcost=Math.max(maxcost, v.cost);
*
*
*
* if(!visited[v.v]) {
*
* visited[v.v]=true; q.add(v.v); dist[v.v]=dist[u]+1; maxcost=Math.max(maxcost,
* v.cost); } }
*
* } return maxcost; }
**/
public static boolean FindAllElements(int n, int k) {
int sum = k;
int[] A = new int[k];
Arrays.fill(A, 0, k, 1);
for (int i = k - 1; i >= 0; --i) {
while (sum + A[i] <= n) {
sum += A[i];
A[i] *= 2;
}
}
if (sum == n) {
return true;
} else
return false;
}
static boolean[] vis2;
static boolean f2 = false;
static long[][] matMul(long[][] a2, long[][] b, int p, int q, int r) // C(p x r) = A(p x q) x (q x r) -- O(p x q x
// r)
{
long[][] C = new long[p][r];
for (int i = 0; i < p; ++i) {
for (int j = 0; j < r; ++j) {
for (int k = 0; k < q; ++k) {
C[i][j] = (C[i][j] + (a2[i][k] % mod * b[k][j] % mod)) % mod;
C[i][j] %= mod;
}
}
}
return C;
}
public static int[] schuffle(int[] a2) {
for (int i = 0; i < a2.length; i++) {
int x = (int) (Math.random() * a2.length);
int temp = a2[x];
a2[x] = a2[i];
a2[i] = temp;
}
return a2;
}
static int memo1[];
static boolean vis[];
static TreeSet<Integer> set = new TreeSet<Integer>();
static long modPow(long ways, long count, long mod) // O(log e)
{
ways %= mod;
long res = 1;
while (count > 0) {
if ((count & 1) == 1)
res = (res * ways) % mod;
ways = (ways * ways) % mod;
count >>= 1;
}
return res % mod;
}
static int gcd(int ans, int b) {
if (b == 0) {
return ans;
}
return gcd(b, ans % b);
}
static int[] isComposite;
static int[] valid;
static ArrayList<Integer> primes;
static ArrayList<Integer> l1;
static TreeSet<Integer> primus = new TreeSet<Integer>();
static void sieveLinear(int N)
{
int[] lp = new int[N + 1]; //lp[i] = least prime divisor of i
for(int i = 2; i <= N; ++i)
{
if(lp[i] == 0)
{
primus.add(i);
lp[i] = i;
}
int curLP = lp[i];
for(int p: primus)
if(p > curLP || p * i > N)
break;
else
lp[p * i] = i;
}
}
public static long[] schuffle(long[] a2) {
for (int i = 0; i < a2.length; i++) {
int x = (int) (Math.random() * a2.length);
long temp = a2[x];
a2[x] = a2[i];
a2[i] = temp;
}
return a2;
}
static int V;
static long INF = (long) 1E16;
static class Edge2 {
int node;
long cost;
long next;
Edge2(int a, int c, Long long1) {
node = a;
cost = long1;
next = c;
}
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream system) {
br = new BufferedReader(new InputStreamReader(system));
}
public Scanner(String file) throws Exception {
br = new BufferedReader(new FileReader(file));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public String nextLine() throws IOException {
return br.readLine();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public char nextChar() throws IOException {
return next().charAt(0);
}
public Long nextLong() throws IOException {
return Long.parseLong(next());
}
public boolean ready() throws IOException {
return br.ready();
}
public void waitForInput() throws InterruptedException {
Thread.sleep(3000);
}
public int[] nxtArr(int n) throws IOException {
int[] ans = new int[n];
for (int i = 0; i < n; i++)
ans[i] = nextInt();
return ans;
}
}
public static int[] sortarray(int a[]) {
schuffle(a);
Arrays.sort(a);
return a;
}
public static long[] sortarray(long a[]) {
schuffle(a);
Arrays.sort(a);
return a;
}
} | Java | ["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 | df59aa0726f404c7f1fa52d4b84f20a4 | train_004.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.BufferedReader;
import java.io.InputStreamReader;
public class Main{
static final int maxn = 55;
static String arr[] = new String[maxn];
public static void main(String[] args) {
Scanner in = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
int t = in.nextInt();
while(t-- > 0){
int n = in.nextInt();
for(int i = 0; i < n; ++i){
arr[i] = in.next();
}
int ok = 1;
for(int i = 0; i < n; ++i){
for(int j = 0; j < arr[i].length(); ++j){
if(arr[i].charAt(j) == '1'){
int cnt = 0;
if(i == n - 1 || j == n - 1) continue;
if(arr[i+1].charAt(j) == '1') cnt = 1;
if(arr[i].charAt(j+1) == '1') cnt = 1;
if(cnt == 0){
ok = 0;
break;
}
}
}
}
System.out.println(ok == 1 ? "Yes" : "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 | 8fc1065b73785e54e76f1d314138e12d | train_004.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 Main {
static FastReader sc=null;
public static void main(String[] args) {
sc=new FastReader();
int t=sc.nextInt();
while(t-->0) {
int n=sc.nextInt();
char a[][]=new char[n][n];
for(int i=0;i<n;i++) {
char line[]=sc.next().toCharArray();
for(int j=0;j<n;j++) {
a[i][j]=line[j];
}
}
boolean po=true;
for(int i=0;i<n-1;i++) {
for(int j=0;j<n-1;j++) {
if(a[i][j]=='1') {
if(legal(i+1,j,n) && a[i+1][j]=='1')continue;
if(legal(i,j+1,n) && a[i][j+1]=='1')continue;
po=false;
}
}
}
System.out.println(po?"YES":"NO");
}
}
static boolean legal(int x,int y,int n) {
return x>=0 && y>=0 && x<n && y<n;
}
static int[] reverse(int a[]) {
ArrayList<Integer> al=new ArrayList<>();
for(int i:a)al.add(i);
Collections.sort(al,Collections.reverseOrder());
for(int i=0;i<a.length;i++)a[i]=al.get(i);
return a;
}
static void print(int a[]) {
for(int e:a) {
System.out.print(e+" ");
}
System.out.println();
}
static void print(long a[]) {
for(long e:a) {
System.out.print(e+" ");
}
System.out.println();
}
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;
}
int[] readArray(int n) {
int a[]=new int [n];
for(int i=0;i<n;i++) {
a[i]=sc.nextInt();
}
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 | f72a76c8fdf1ed57b843bc80907f14a3 | train_004.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 Polygon {
public static void main(String[] args) throws Exception {
BufferedReader buffer = new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb = new StringBuilder();
int t = Integer.parseInt(buffer.readLine());
while (t-- > 0) {
int n = Integer.parseInt(buffer.readLine());
char [] inp;
char [][] matrix = new char[n][n];
for(int rowPos = 0; rowPos < n; rowPos++)
{
inp = buffer.readLine().toCharArray();
for(int colPos = 0; colPos < n; colPos++)
{
matrix[rowPos][colPos] = inp[colPos];
}
}
boolean check = true;
for (int rowPos = 0; rowPos < n - 1; rowPos++) {
for (int colPos = 0; colPos < n - 1; colPos++) {
if (matrix[rowPos][colPos]=='1' && matrix[rowPos+1][colPos]!='1' && matrix[rowPos][colPos+1]!='1') {
check = false;
break;
}
}
}
if (check)
sb.append("YES\n");
else
sb.append("NO\n");
}
System.out.println(sb);
}
}
| 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 | 7079d9bb5314f1767c8e6736ac7925a1 | train_004.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 C
{
static int n;
static int[][] mat;
static String str;
public static void main(String[] args) throws IOException
{
Flash f = new Flash();
int T = f.ni();
for(int t = 1; t <= T; t++){
n = f.ni();
mat = new int[n][n];
for(int i = 0; i < n; i++){
String s = f.next();
for(int j = 0; j < s.length(); j++) mat[i][j] = s.charAt(j) - '0';
}
System.out.println(fn());
}
}
static String fn()
{
boolean[][] vis = new boolean[n][n];
for(int i = 0; i < n; i++) if(mat[i][n-1] == 1 && !vis[i][n-1]) dfs(i, n-1, vis);
for(int j = 0; j < n; j++) if(mat[n-1][j] == 1 && !vis[n-1][j]) dfs(n-1, j, vis);
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
if(mat[i][j] == 1 && !vis[i][j]) return "NO";
}
}
return "YES";
}
static void dfs(int i, int j, boolean[][] vis){
vis[i][j] = true;
if(isValid(i-1, j) && mat[i-1][j] == 1 && !vis[i-1][j]) dfs(i-1, j, vis);
if(isValid(i, j-1) && mat[i][j-1] == 1 && !vis[i][j-1]) dfs(i, j-1, vis);
}
static boolean isValid(int i, int j){
return (i >= 0 && i < n && j >= 0 && j < n);
}
static void sort(int[] a){
List<Integer> A = new ArrayList<>();
for(int i : a) A.add(i);
Collections.sort(A);
for(int i = 0; i < A.size(); i++) a[i] = A.get(i);
}
static int swap(int itself, int dummy)
{
return itself;
}
static class Flash
{
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();
}
String nextLine(){
String s = new String();
try{
s = br.readLine().trim();
}catch(IOException e){
e.printStackTrace();
}
return s;
}
//nextInt()
int ni(){
return Integer.parseInt(next());
}
int[] arr(int n){
int[] a = new int[n];
for(int i = 0; i < n; i++) a[i] = ni();
return a;
}
//nextlong()
long nl(){
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 | d5f9b4661b662a5ae33a1fbcf823882c | train_004.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 Solution
{
static void solve(int arr[][], int n)
{
int i, j;
int flag = 0;
for(i=0; i<arr.length-1; i++)
{
for(j=0; j<arr[i].length-1; j++)
{
if(arr[i][j] == 49 && arr[i+1][j] != 49 && arr[i][j+1] != 49)
{
flag = 1;
break;
}
}//for(j
if(flag == 1)
break;
}//for(i
if(flag == 1)
System.out.println("No");
else
System.out.println("yes");
}//solve
public static void main(String args[])
{
Scanner scan = new Scanner(System.in);
int t= scan.nextInt();
int n, k, i, j;
int arr[][];
scan.nextLine();
for(i=0; i<t; i++)
{
n = scan.nextInt();
scan.nextLine();
arr = new int[n][n];
for(j=0; j<n; j++)
{
String s = scan.nextLine();
for(k=0; k<n; k++)
arr[j][k] = (s.charAt(k));
}//for(j
solve(arr, n);
}//for(i
}//main
}//Solution
| 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 | e7fbaf7320b19d49edb90fd49d1c61ef | train_004.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.Scanner;
public class e {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int t = scanner.nextInt();
for(int i=0;i<t;i++){
int n = scanner.nextInt();
ArrayList<String> mat = new ArrayList<>();
for(int j=0;j<n;j++){
mat.add(scanner.next());
}
solve2(mat);
}
}
public static void solve2(ArrayList<String> mat){
int n = mat.size();
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
if(mat.get(i).charAt(j)=='1' && i!=n-1 && j!=n-1){
if(!((i<n-1 && mat.get(i+1).charAt(j)=='1') || (j<n-1 && mat.get(i).charAt(j+1)=='1'))){
System.out.println("No");
return;
}
}
}
}
System.out.println("Yes");
}
public static void solve(ArrayList<String> mat){
int n = mat.size();
boolean[][] rightFilled = new boolean[n][n], downFilled = new boolean[n][n];
for(int i=0;i<n;i++){
rightFilled[i][n-1] = (mat.get(i).charAt(n-1) == '1');
for(int j=n-2;j>=0;j--){
if(rightFilled[i][j+1])
rightFilled[i][j] = true;
else{
rightFilled[i][j] = false;
break;
}
}
}
for(int j=0;j<n;j++){
downFilled[n-1][j] = (mat.get(n-1).charAt(j) == '1');
for(int i = n-2; i >=0; i--){
if(downFilled[i+1][j])
downFilled[i][j] = true;
else{
downFilled[i][j] = false;
break;
}
}
}
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
if(mat.get(i).charAt(j)=='1' && !rightFilled[i][j] && !downFilled[i][j]){
System.out.println("NO");
return;
}
}
}
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 | dc5649027b0c996abc1ea593e45d12e6 | train_004.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 Main {
static Scanner sc = new Scanner(System.in);
static PrintWriter out = new PrintWriter(System.out);
static int arr[][], n;
static boolean check(int r, int c) {
return r >= 0 && c >= 0 && arr[r][c] == 1;
}
static void dfs(int r, int c) {
arr[r][c] = 0;
if(check(r - 1,c)) dfs(r - 1,c);
if(check(r, c - 1)) dfs(r, c - 1);
}
static boolean solve() throws Exception {
n = sc.nextInt();
arr = new int[n][n];
for(int i = 0; i < n; i++) {
String s = sc.nextLine();
for(int j = 0; j < n; j++) {
if(s.charAt(j) == '1') arr[i][j] = 1;
}
}
for(int i = 0; i < n; i++) {
if(arr[i][n - 1] == 1) dfs(i, n - 1);
if(arr[n - 1][i] == 1) dfs(n - 1, i);
}
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
if(arr[i][j] == 1) {
return false;
}
}
}
return true;
}
public static void main(String[] args) throws Exception {
int t = sc.nextInt();
while (t-- > 0) {
out.println(solve() ? "YES" : "NO");
}
out.close();
}
}
class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream system) {
br = new BufferedReader(new InputStreamReader(system));
}
public Scanner(String file) throws Exception {
br = new BufferedReader(new FileReader(file));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public String nextLine() throws IOException {
return br.readLine();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public 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 | 89816e248cbe0f0c17cb9a5831ddcbe1 | train_004.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 rec
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
while(t-->0)
{
int n=sc.nextInt();
int[][] a=new int[n][n];
for(int i=0;i<n;i++)
{
String s=sc.next();
for(int j=0;j<n;j++)
{
char c=s.charAt(j);
a[i][j]=c-'0';
}
}
String ans="YES";
for(int i=0;i<n-1;i++)
{
for(int j=0;j<n-1;j++)
{
if(a[i][j]==1 && a[i+1][j]!=1 && a[i][j+1]!=1)
{
ans="NO";
}
}
}
System.out.println(ans);
}
}
}
| 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 | f6df2f638e15c5105a6535e79c0d68ec | train_004.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 cannons {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
int cases = input.nextInt();
loop:
for (int l = 0; l < cases; l++) {
int rows = input.nextInt();
int columns = rows;
char[][] matrix = new char[rows][columns];
for (int r = 0; r < rows; r++) {
char[] array = input.next().toCharArray();
for (int c = 0; c < columns; c++) {
matrix[r][c] = array[c];
}
}
for (int r = 0; r < rows - 1; r++) {
for (int c = 0; c < columns - 1; c++) {
if (matrix[r][c] == '1' && matrix[r][c + 1] == '0' && matrix[r + 1][c] == '0') {
System.out.println("NO");
continue loop;
}
}
}
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 | 48ded7237b84f6a9edd55522957d0399 | train_004.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 com.company.codeforces;
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int t = input.nextInt();
while (t-->0){
int n=input.nextInt();
int a[][]=new int[n][n];
for (int i = 0; i <n ; i++) {
String str=input.next();
for (int j = 0; j <n ; j++) {
a[i][j]=Integer.parseInt(str.charAt(j)+"");
}
}
Boolean flag=false;
for (int i = n-2; i >=0; i--) {
for (int j = n-1; j >=0 ; j--) {
boolean down=true;
boolean right=true;
if (a[i][j]==1){
//dpwn support
if (i!=n-1){
if (a[i+1][j]!=1){
down=false;
}
}
if (j!=n-1){
if (a[i][j+1]!=1){
right=false;
}
}
}
if (!right && !down){
flag=true;
break;
}
}
if (flag){
break;
}
}
if (flag){
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 | 40cfd59533b9514b635ef5af5a18a2be | train_004.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.math.*;
import java.util.*;
// printArr() - prints the array
// intList, doubleList, longList
// nextIntArray
/* stuff you should look for
* int overflow, array bounds
* special cases (n=1?)
* do smth instead of nothing and stay organized
* WRITE STUFF DOWN
*/
public class current {
public static void main(String[] args) {
FastReader fr = new FastReader();
int a = fr.nextInt();
for (int i = 0; i < a; i++) {
int b = fr.nextInt();
char[][] arr = new char[b][b];
for (int j = 0; j < b; j++) {
arr[j] = fr.nextLine().toCharArray();
}
solve(arr);
}
}
public static void solve(char[][] arr) {
int l = arr.length;
// row
for (int i = 0; i < l; i++) {
// col
for (int j = 0; j < l; j++) {
if (arr[i][j] == '0') {
continue;
}
if (i == l-1 || j == l-1) {
continue;
}
if (arr[i+1][j] == '1' || arr[i][j+1] == '1') {
continue;
}
System.out.println("NO");
return;
}
}
System.out.println("YES");
}
public static double factorial(long n) {
double c = 1;
for (double i = 1; i <= n; i++) {
c *= i;
}
return c;
}
public static Set<Integer> get(List<Set<Integer>> graph, int i) {
try {
return graph.get(i);
} catch (IndexOutOfBoundsException e) {
return new HashSet<>();
}
}
public static void printArr(int[] a) {
System.out.println(Arrays.toString(a));
}
public static int[] bfs(List<Set<Integer>> graph, int v) {
int l = graph.size();
Deque<Integer> list = new ArrayDeque<>();
list.add(v);
boolean[] seen = new boolean[l];
int distance = 0;
int node = v;
int size = 1;
int index = 0;
// Iterate over every single vertice and edge
// O(V+E) -> O(V) for trees
while (!list.isEmpty()) {
int cur = list.poll();
seen[cur] = true;
node = cur;
index++;
if (index > size) {
distance++;
size = list.size();
index = 0;
}
for (int i : graph.get(cur)) {
if (!seen[i]) {
seen[i] = true;
list.add(i);
}
}
}
return new int[]{node, distance};
}
static class SegTree {
int startIndex, endIndex;
long sum;
SegTree lchild, rchild;
SegTree(int[] arr) {this(0, arr.length-1, arr);}
SegTree(int startIndex, int endIndex, int[] arr) {
this.startIndex = startIndex;
this.endIndex = endIndex;
if (startIndex == endIndex) sum = arr[startIndex];
else {
int mid = (startIndex + endIndex) / 2;
lchild = new SegTree(startIndex, mid, arr);
rchild = new SegTree(mid + 1, endIndex, arr);
sum = lchild.sum + rchild.sum;
recalc();
}
}
void recalc() {
if (startIndex == endIndex) return; sum = lchild.sum + rchild.sum;
}
public void valueUpdate(int index, int value) {
if (startIndex == endIndex) {sum = value; return;}
if (index > lchild.endIndex) rchild.valueUpdate(index, value); else lchild.valueUpdate(index, value); recalc();
}
public long rangeSum(int startIndex, int endIndex) {
if (endIndex < this.startIndex || startIndex > this.endIndex) return 0;
if (startIndex <= this.startIndex && endIndex >= this.endIndex) return sum;
return lchild.rangeSum(startIndex, endIndex) + rchild.rangeSum(startIndex, endIndex);
}
}
public static double sum(List<Long> n) {
double a = 0;
for (long i : n) {
a += i;
}
return a;
}
public static int toInt(String n) {
return Integer.parseInt(n);
}
public static double toDouble(String n) {
return Double.parseDouble(n);
}
public static long toLong(String n) {
return Long.parseLong(n);
}
static class FastReader {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
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());
}
double nextDouble() {
return Double.parseDouble(next());
}
long nextLong() {
return Long.parseLong(next());
}
String nextLine() {
String a = "";
try {
a = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return a;
}
int[] nextIntArray() {
return intArray(nextLine().split(" "));
}
long[] nextLongArray() {
return longArray(nextLine().split(" "));
}
double[] nextDoubleArray() {
return doubleArray(nextLine().split(" "));
}
public int getInt(int index) {
String[] arr = nextLine().split(" ");
return Integer.parseInt(arr[index]);
}
public long getLong(int index) {
String[] arr = nextLine().split(" ");
return Long.parseLong(arr[index]);
}
public double getDouble(int index) {
String[] arr = nextLine().split(" ");
return Double.parseDouble(arr[index]);
}
public List<String> stringList() {
String[] arr = nextLine().split(" ");
return Arrays.asList(arr);
}
public List<Integer> intList() {
String[] arr = nextLine().split(" ");
List<Integer> a = new ArrayList<>();
for (String i : arr) {
a.add(Integer.parseInt(i));
}
return a;
}
public List<Double> doubleList() {
String[] arr = nextLine().split(" ");
List<Double> a = new ArrayList<>();
for (String i : arr) {
a.add(Double.parseDouble(i));
}
return a;
}
public List<Long> longList() {
String[] arr = nextLine().split(" ");
List<Long> a = new ArrayList<>();
for (String i : arr) {
a.add(Long.parseLong(i));
}
return a;
}
}
public static int[] intArray(String[] arr) {
int l = arr.length;
int[] a = new int[l];
for (int i = 0; i < l; i++) {
a[i] = Integer.parseInt(arr[i]);
}
return a;
}
public static long[] longArray(String[] arr) {
int l = arr.length;
long[] a = new long[l];
for (int i = 0; i < l; i++) {
a[i] = Long.parseLong(arr[i]);
}
return a;
}
public static double[] doubleArray(String[] arr) {
int l = arr.length;
double[] a = new double[l];
for (int i = 0; i < l; i++) {
a[i] = Double.parseDouble(arr[i]);
}
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 | cc20e78aab52d856431db56e7a78bd0c | train_004.jsonl | 1339342200 | As Valeric and Valerko were watching one of the last Euro Championship games in a sports bar, they broke a mug. Of course, the guys paid for it but the barman said that he will let them watch football in his bar only if they help his son complete a programming task. The task goes like that.Let's consider a set of functions of the following form: Let's define a sum of n functions y1(x), ..., yn(x) of the given type as function s(x) = y1(x) + ... + yn(x) for any x. It's easy to show that in this case the graph s(x) is a polyline. You are given n functions of the given type, your task is to find the number of angles that do not equal 180 degrees, in the graph s(x), that is the sum of the given functions.Valeric and Valerko really want to watch the next Euro Championship game, so they asked you to help them. | 256 megabytes | import java.io.Closeable;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.HashSet;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.StringTokenizer;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author Jacob Jiang
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
QuickScanner in = new QuickScanner(inputStream);
ExtendedPrintWriter out = new ExtendedPrintWriter(outputStream);
TaskD solver = new TaskD();
solver.solve(1, in, out);
out.close();
}
}
class TaskD {
public void solve(int testNumber, QuickScanner in, ExtendedPrintWriter out) {
int n = in.nextInt();
HashSet<Pair<Integer, Integer>> set = new HashSet<Pair<Integer, Integer>>();
for (int i = 0; i < n; i++) {
int a = in.nextInt();
int b = in.nextInt();
if (a == 0) {
continue;
}
if (a < 0) {
a = -a;
b = -b;
}
int g = NumberUtils.gcd(a, b);
a /= g;
b /= g;
set.add(Pair.makePair(a, b));
}
out.println(set.size());
}
}
class QuickScanner implements Iterator<String>, Closeable {
BufferedReader reader;
StringTokenizer tokenizer;
boolean endOfFile = false;
public QuickScanner(InputStream inputStream){
reader = new BufferedReader(new InputStreamReader(inputStream));
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (Exception e) {
endOfFile = true;
}
}
public boolean hasNext() {
if (!tokenizer.hasMoreTokens()) {
try {
checkNext();
} catch (NoSuchElementException ignored) {
}
}
return !endOfFile;
}
private void checkNext() {
if (endOfFile) {
throw new NoSuchElementException();
}
try {
while (!tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
} catch (Exception e) {
endOfFile = true;
throw new NoSuchElementException();
}
}
public String next() {
checkNext();
return tokenizer.nextToken();
}
public void remove() {
throw new UnsupportedOperationException();
}
public int nextInt() {
return Integer.parseInt(next());
}
public void close() {
try {
reader.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
class ExtendedPrintWriter extends PrintWriter {
public ExtendedPrintWriter(Writer out) {
super(out);
}
public ExtendedPrintWriter(OutputStream out) {
super(out);
}
}
class NumberUtils {
public static int gcd(int a, int b) {
if (a == 0 && b == 0) {
throw new IllegalArgumentException();
}
return privateGcd(Math.abs(a), Math.abs(b));
}
private static int privateGcd(int a, int b) {
return b == 0 ? a : privateGcd(b, a % b);
}
}
class Pair<A,B> implements Comparable<Pair<A, B>> {
public final A first;
public final B second;
public Pair(A first, B second) {
this.first = first;
this.second = second;
}
public static <A, B> Pair<A, B> makePair(A first, B second) {
return new Pair<A, B>(first, second);
}
public int compareTo(Pair<A, B> anotherPair) {
int result = ((Comparable<A>)first).compareTo(anotherPair.first);
if (result != 0) {
return result;
}
return ((Comparable<B>)second).compareTo(anotherPair.second);
}
public int hashCode() {
int result = 0;
if (first != null) {
result = first.hashCode();
}
if (second != null) {
result = result * 31 + second.hashCode();
}
return result;
}
public String toString() {
return "(" + first + ", " + second + ")";
}
public boolean equals(Object obj) {
try {
return this.first.equals(((Pair<A, B>) obj).first) &&
this.second.equals(((Pair<A, B>) obj).second);
} catch (ClassCastException e) {
return false;
}
}
}
| Java | ["1\n1 0", "3\n1 0\n0 2\n-1 1", "3\n-2 -4\n1 7\n-5 1"] | 2 seconds | ["1", "2", "3"] | null | Java 7 | standard input | [
"sortings",
"geometry",
"math"
] | d436c7a3b7f07c9f026d00bdf677908d | The first line contains integer n (1 ≤ n ≤ 105) — the number of functions. Each of the following n lines contains two space-separated integer numbers ki, bi ( - 109 ≤ ki, bi ≤ 109) that determine the i-th function. | 1,900 | Print a single number — the number of angles that do not equal 180 degrees in the graph of the polyline that equals the sum of the given functions. | standard output | |
PASSED | d8a83a4234469762b1bdae2f64fd7827 | train_004.jsonl | 1339342200 | As Valeric and Valerko were watching one of the last Euro Championship games in a sports bar, they broke a mug. Of course, the guys paid for it but the barman said that he will let them watch football in his bar only if they help his son complete a programming task. The task goes like that.Let's consider a set of functions of the following form: Let's define a sum of n functions y1(x), ..., yn(x) of the given type as function s(x) = y1(x) + ... + yn(x) for any x. It's easy to show that in this case the graph s(x) is a polyline. You are given n functions of the given type, your task is to find the number of angles that do not equal 180 degrees, in the graph s(x), that is the sum of the given functions.Valeric and Valerko really want to watch the next Euro Championship game, so they asked you to help them. | 256 megabytes | import java.util.HashSet;
import java.util.Scanner;
public class d2_123_d {
public static class Node {
boolean sign;
long k;
long b;
public Node(long k, long b) {
this.k = Math.abs(k);
this.b = Math.abs(b);
if (k*b < 0) {
sign = false;
} else {
sign = true;
}
}
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || o.getClass() != this.getClass()) {
return false;
}
Node node = (Node) o;
return sign == node.sign && k == node.k && b == node.b;
}
public int hashCode() {
return (int)(k * 31 + b * 17);
}
}
public static long gcd(long a, long b) {
if (a == 0) {
return b;
}
return gcd(b%a, a);
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
HashSet<Node> set = new HashSet<Node>();
for (int i=0; i<n; i++) {
int k = sc.nextInt();
int b = sc.nextInt();
if (k != 0) {
long g = gcd(Math.abs(k), Math.abs(b));
Node node = new Node(k/g, b/g);
set.add(node);
}
}
System.out.println(set.size());
}
}
| Java | ["1\n1 0", "3\n1 0\n0 2\n-1 1", "3\n-2 -4\n1 7\n-5 1"] | 2 seconds | ["1", "2", "3"] | null | Java 7 | standard input | [
"sortings",
"geometry",
"math"
] | d436c7a3b7f07c9f026d00bdf677908d | The first line contains integer n (1 ≤ n ≤ 105) — the number of functions. Each of the following n lines contains two space-separated integer numbers ki, bi ( - 109 ≤ ki, bi ≤ 109) that determine the i-th function. | 1,900 | Print a single number — the number of angles that do not equal 180 degrees in the graph of the polyline that equals the sum of the given functions. | standard output | |
PASSED | 9b37cec3cde783eca254ac708dbe3d95 | train_004.jsonl | 1527863700 | There are $$$n$$$ distinct points on a coordinate line, the coordinate of $$$i$$$-th point equals to $$$x_i$$$. Choose a subset of the given set of points such that the distance between each pair of points in a subset is an integral power of two. It is necessary to consider each pair of points, not only adjacent. Note that any subset containing one element satisfies the condition above. Among all these subsets, choose a subset with maximum possible size.In other words, you have to choose the maximum possible number of points $$$x_{i_1}, x_{i_2}, \dots, x_{i_m}$$$ such that for each pair $$$x_{i_j}$$$, $$$x_{i_k}$$$ it is true that $$$|x_{i_j} - x_{i_k}| = 2^d$$$ where $$$d$$$ is some non-negative integer number (not necessarily the same for each pair of points). | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.stream.IntStream;
import java.util.Arrays;
import java.util.Set;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.stream.Stream;
import java.util.StringTokenizer;
import java.io.BufferedReader;
import java.util.Comparator;
import java.util.Collections;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author The Viet Nguyen
*/
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 n = in.nextInt(), x[] = new int[n];
Set<Integer> s = new HashSet<>(n);
List<Integer>[] ss = new List[n];
for (int i = 0; i < n; ++i) {
x[i] = in.nextInt();
s.add(x[i]);
}
x = Arrays.stream(x).limit(n).boxed().sorted()
.mapToInt(Integer::intValue).toArray();
ss[0] = Collections.singletonList(x[0]);
for (int i = 0; i < n; ++i) {
for (int k = 0; k < 31 && x[i] + (1 << k) <= x[n - 1]; ++k) {
int start = x[i];
List<Integer> l = new ArrayList<>();
do {
if (s.contains(start)) {
l.add(start);
if (l.size() == 3)
break;
} else break;
start = start + (1 << k);
} while (start <= x[n - 1]);
if (ss[i] == null || ss[i].size() < l.size())
ss[i] = l;
}
}
Arrays.sort(ss, Comparator.nullsFirst(Comparator.comparingInt(List::size)));
List<Integer> max = ss[n - 1];
int maxSize = max.size();
out.println(maxSize);
for (int i = 0; i < maxSize; ++i) {
out.print(max.get(i));
if (i == maxSize - 1) out.println();
else out.print(" ");
}
}
}
static class InputReader {
private BufferedReader reader;
private StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
| Java | ["6\n3 5 4 7 10 12", "5\n-1 2 5 8 11"] | 4 seconds | ["3\n7 3 5", "1\n8"] | NoteIn the first example the answer is $$$[7, 3, 5]$$$. Note, that $$$|7-3|=4=2^2$$$, $$$|7-5|=2=2^1$$$ and $$$|3-5|=2=2^1$$$. You can't find a subset having more points satisfying the required property. | Java 8 | standard input | [
"brute force",
"math"
] | f413556df7dc980ca7e7bd1168d700d2 | The first line contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of points. The second line contains $$$n$$$ pairwise distinct integers $$$x_1, x_2, \dots, x_n$$$ ($$$-10^9 \le x_i \le 10^9$$$) — the coordinates of points. | 1,800 | In the first line print $$$m$$$ — the maximum possible number of points in a subset that satisfies the conditions described above. In the second line print $$$m$$$ integers — the coordinates of points in the subset you have chosen. If there are multiple answers, print any of them. | standard output | |
PASSED | 13f24eeaef0a6142e301747d9e51d209 | train_004.jsonl | 1527863700 | There are $$$n$$$ distinct points on a coordinate line, the coordinate of $$$i$$$-th point equals to $$$x_i$$$. Choose a subset of the given set of points such that the distance between each pair of points in a subset is an integral power of two. It is necessary to consider each pair of points, not only adjacent. Note that any subset containing one element satisfies the condition above. Among all these subsets, choose a subset with maximum possible size.In other words, you have to choose the maximum possible number of points $$$x_{i_1}, x_{i_2}, \dots, x_{i_m}$$$ such that for each pair $$$x_{i_j}$$$, $$$x_{i_k}$$$ it is true that $$$|x_{i_j} - x_{i_k}| = 2^d$$$ where $$$d$$$ is some non-negative integer number (not necessarily the same for each pair of points). | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.io.BufferedWriter;
import java.util.Set;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.HashSet;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author prakharjain
*/
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);
_988D solver = new _988D();
solver.solve(1, in, out);
out.close();
}
static class _988D {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.nextInt();
Integer[] a = new Integer[n];
for (int i = 0; i < n; i++) {
a[i] = in.nextInt();
}
Arrays.sort(a);
Set<Long> s = new HashSet<>();
for (Integer val : a) {
s.add((long) val);
}
int ans = 0;
long st = -1;
int cnt = 0;
long gap = 0;
int k = 0;
for (long num : a) {
if (ans == 3)
break;
for (int d = 0; d < 32; d++) {
long val = 1l << d;
int ca = 0;
for (long i = num, j = 0; j < 3; i += val, j++) {
if (s.contains(i)) {
ca++;
} else {
break;
}
}
if (ca > ans) {
st = num;
cnt = ca;
gap = val;
ans = ca;
}
}
k++;
}
out.println(ans);
for (long i = st, j = 0; j < cnt; j++, i += gap) {
out.print(i + " ");
}
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void close() {
writer.close();
}
public void println(int i) {
writer.println(i);
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
| Java | ["6\n3 5 4 7 10 12", "5\n-1 2 5 8 11"] | 4 seconds | ["3\n7 3 5", "1\n8"] | NoteIn the first example the answer is $$$[7, 3, 5]$$$. Note, that $$$|7-3|=4=2^2$$$, $$$|7-5|=2=2^1$$$ and $$$|3-5|=2=2^1$$$. You can't find a subset having more points satisfying the required property. | Java 8 | standard input | [
"brute force",
"math"
] | f413556df7dc980ca7e7bd1168d700d2 | The first line contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of points. The second line contains $$$n$$$ pairwise distinct integers $$$x_1, x_2, \dots, x_n$$$ ($$$-10^9 \le x_i \le 10^9$$$) — the coordinates of points. | 1,800 | In the first line print $$$m$$$ — the maximum possible number of points in a subset that satisfies the conditions described above. In the second line print $$$m$$$ integers — the coordinates of points in the subset you have chosen. If there are multiple answers, print any of them. | standard output | |
PASSED | e509815b67a2ff24cd752864dfa17719 | train_004.jsonl | 1527863700 | There are $$$n$$$ distinct points on a coordinate line, the coordinate of $$$i$$$-th point equals to $$$x_i$$$. Choose a subset of the given set of points such that the distance between each pair of points in a subset is an integral power of two. It is necessary to consider each pair of points, not only adjacent. Note that any subset containing one element satisfies the condition above. Among all these subsets, choose a subset with maximum possible size.In other words, you have to choose the maximum possible number of points $$$x_{i_1}, x_{i_2}, \dots, x_{i_m}$$$ such that for each pair $$$x_{i_j}$$$, $$$x_{i_k}$$$ it is true that $$$|x_{i_j} - x_{i_k}| = 2^d$$$ where $$$d$$$ is some non-negative integer number (not necessarily the same for each pair of points). | 256 megabytes | import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Scanner;
public class Main {
public static void main(String args[]) {
Scanner io = new Scanner(System.in);
int items = io.nextInt();
ArrayList<Long> arr = new ArrayList<Long>();
int size = items;
if (items == 1) {
System.out.println(1);
System.out.println(io.nextInt());
return;
}
while(items-- > 0)
arr.add(io.nextLong());
Collections.sort(arr);
HashSet<Long> hs = new HashSet<Long>(arr);
long lb = arr.get(0);
long ub = arr.get(size - 1);
boolean found2 = false;
boolean found3 = false;
long ans = 0, pow2 = 0;
for (long x : arr) {
// assume x is middle element
// check all elements min(x - lb, ub - x) < y < x for powers of 2
long lim = Math.max(x-lb, ub-x);
for (long i = 1; i <= lim; i*=2) {
if (found3)
break;
if (hs.contains(x - i)) {
found2 = true;
if (hs.contains(x + i))
found3 = true;
ans = x;
pow2 = i;
}
}
/* for (int y: arr) {
if (y >= x || found3)
break;
int diff = x - y;
// if found, then check if x + that pow of 2 exists (and flip 'found2' flag)
if (diff <= lim && (diff & (diff-1)) == 0) {
found2 = true;
if (hs.contains(diff + x))
found3 = true;
ans = x;
pow2 = diff;
}
}
*/
// if it does, then print then done (flip found3)
if (found3)
break;
}
if(found3)
System.out.println("3\n" + (ans-pow2) + " " + ans + " " + (ans+pow2));
else if(found2)
System.out.println("2\n" + (ans-pow2) + " " + ans);
else
System.out.println("1\n" + arr.get(0));
io.close();
}
} | Java | ["6\n3 5 4 7 10 12", "5\n-1 2 5 8 11"] | 4 seconds | ["3\n7 3 5", "1\n8"] | NoteIn the first example the answer is $$$[7, 3, 5]$$$. Note, that $$$|7-3|=4=2^2$$$, $$$|7-5|=2=2^1$$$ and $$$|3-5|=2=2^1$$$. You can't find a subset having more points satisfying the required property. | Java 8 | standard input | [
"brute force",
"math"
] | f413556df7dc980ca7e7bd1168d700d2 | The first line contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of points. The second line contains $$$n$$$ pairwise distinct integers $$$x_1, x_2, \dots, x_n$$$ ($$$-10^9 \le x_i \le 10^9$$$) — the coordinates of points. | 1,800 | In the first line print $$$m$$$ — the maximum possible number of points in a subset that satisfies the conditions described above. In the second line print $$$m$$$ integers — the coordinates of points in the subset you have chosen. If there are multiple answers, print any of them. | standard output | |
PASSED | 4cf9835201f47fb0c9a0717094824f87 | train_004.jsonl | 1527863700 | There are $$$n$$$ distinct points on a coordinate line, the coordinate of $$$i$$$-th point equals to $$$x_i$$$. Choose a subset of the given set of points such that the distance between each pair of points in a subset is an integral power of two. It is necessary to consider each pair of points, not only adjacent. Note that any subset containing one element satisfies the condition above. Among all these subsets, choose a subset with maximum possible size.In other words, you have to choose the maximum possible number of points $$$x_{i_1}, x_{i_2}, \dots, x_{i_m}$$$ such that for each pair $$$x_{i_j}$$$, $$$x_{i_k}$$$ it is true that $$$|x_{i_j} - x_{i_k}| = 2^d$$$ where $$$d$$$ is some non-negative integer number (not necessarily the same for each pair of points). | 256 megabytes | import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.StringTokenizer;
public class E486 {
static ArrayList<Long>[] amp;
ArrayList<Pair>[][] pmp;
public static void main(String args[]) throws FileNotFoundException {
InputReader in = new InputReader(System.in);
OutputStream outputStream = System.out;
PrintWriter out = new PrintWriter(outputStream);
StringBuilder sb = new StringBuilder();
// ----------My Code----------
int n = in.nextInt();
long arr[] = new long[n];
long min = Integer.MAX_VALUE;
HashSet<Long> hs = new HashSet<>();
amp = (ArrayList<Long>[]) new ArrayList[n];
for (int i = 0; i < n; i++) {
arr[i] = in.nextInt();
hs.add(arr[i]);
amp[i] = new ArrayList<>();
}
int pow[] = new int[32];
pow[0] = 1;
for (int i = 1; i < 32; i++)
pow[i] = pow[i - 1] * 2;
for (int i = n - 1; i >= 0; i--) {
long val = arr[i];
amp[i].add(arr[i]);
int max = 0, temp = -1;
for (int j = 1; j < 32; j++) {
int val1 = 0;
if (hs.contains(val - pow[j]))
val1++;
if (hs.contains(val - pow[j - 1]))
val1++;
if (val1 >= max) {
max = val1;
temp = j;
}
}
if (hs.contains(arr[i] - pow[temp - 1]))
amp[i].add(arr[i] - pow[temp - 1]);
if (hs.contains(arr[i] - pow[temp]))
amp[i].add(arr[i] - pow[temp]);
}
int size = 0, ans = -1;
for (int i = 0; i < n; i++) {
if (amp[i].size() > size) {
size = amp[i].size();
ans = i;
}
}
System.out.println(size);
for (long i : amp[ans])
System.out.print(i + " ");
// ---------------The End------------------
out.close();
}
static boolean isPossible(int x, int y) {
if (x >= 0 && y >= 0 && x < 4 && y < 4)
return true;
return false;
}
// ---------------Extra Methods------------------
public static long pow(long x, long n, long mod) {
long res = 1;
x %= mod;
while (n > 0) {
if (n % 2 == 1) {
res = (res * x) % mod;
}
x = (x * x) % mod;
n /= 2;
}
return res;
}
public static boolean isPal(String s) {
for (int i = 0, j = s.length() - 1; i <= j; i++, j--) {
if (s.charAt(i) != s.charAt(j))
return false;
}
return true;
}
public static String rev(String s) {
StringBuilder sb = new StringBuilder(s);
sb.reverse();
return sb.toString();
}
public static long gcd(long x, long y) {
if (x % y == 0)
return y;
else
return gcd(y, x % y);
}
public static int gcd(int x, int y) {
if (x % y == 0)
return y;
else
return gcd(y, x % y);
}
public static long gcdExtended(long a, long b, long[] x) {
if (a == 0) {
x[0] = 0;
x[1] = 1;
return b;
}
long[] y = new long[2];
long gcd = gcdExtended(b % a, a, y);
x[0] = y[1] - (b / a) * y[0];
x[1] = y[0];
return gcd;
}
public static int abs(int a, int b) {
return (int) Math.abs(a - b);
}
public static long abs(long a, long b) {
return (long) Math.abs(a - b);
}
public static int max(int a, int b) {
if (a > b)
return a;
else
return b;
}
public static int min(int a, int b) {
if (a > b)
return b;
else
return a;
}
public static long max(long a, long b) {
if (a > b)
return a;
else
return b;
}
public static long min(long a, long b) {
if (a > b)
return b;
else
return a;
}
// ---------------Extra Methods------------------
public static void debug(Object... o) {
System.out.println(Arrays.deepToString(o));
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream inputstream) {
reader = new BufferedReader(new InputStreamReader(inputstream));
tokenizer = null;
}
public String nextLine() {
String fullLine = null;
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
fullLine = reader.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
return fullLine;
}
return fullLine;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public char nextChar() {
return next().charAt(0);
}
public long nextLong() {
return Long.parseLong(next());
}
public int nextInt() {
return Integer.parseInt(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public int[] nextIntArray(int n, int f) {
if (f == 0) {
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = nextInt();
}
return arr;
} else {
int[] arr = new int[n + 1];
for (int i = 1; i < n + 1; i++) {
arr[i] = nextInt();
}
return arr;
}
}
public long[] nextLongArray(int n, int f) {
if (f == 0) {
long[] arr = new long[n];
for (int i = 0; i < n; i++) {
arr[i] = nextLong();
}
return arr;
} else {
long[] arr = new long[n + 1];
for (int i = 1; i < n + 1; i++) {
arr[i] = nextLong();
}
return arr;
}
}
public double[] nextDoubleArray(int n, int f) {
if (f == 0) {
double[] arr = new double[n];
for (int i = 0; i < n; i++) {
arr[i] = nextDouble();
}
return arr;
} else {
double[] arr = new double[n + 1];
for (int i = 1; i < n + 1; i++) {
arr[i] = nextDouble();
}
return arr;
}
}
}
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);
}
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();
}
}
} | Java | ["6\n3 5 4 7 10 12", "5\n-1 2 5 8 11"] | 4 seconds | ["3\n7 3 5", "1\n8"] | NoteIn the first example the answer is $$$[7, 3, 5]$$$. Note, that $$$|7-3|=4=2^2$$$, $$$|7-5|=2=2^1$$$ and $$$|3-5|=2=2^1$$$. You can't find a subset having more points satisfying the required property. | Java 8 | standard input | [
"brute force",
"math"
] | f413556df7dc980ca7e7bd1168d700d2 | The first line contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of points. The second line contains $$$n$$$ pairwise distinct integers $$$x_1, x_2, \dots, x_n$$$ ($$$-10^9 \le x_i \le 10^9$$$) — the coordinates of points. | 1,800 | In the first line print $$$m$$$ — the maximum possible number of points in a subset that satisfies the conditions described above. In the second line print $$$m$$$ integers — the coordinates of points in the subset you have chosen. If there are multiple answers, print any of them. | standard output | |
PASSED | 55276f9aa08921c3b0190b72185bc74e | train_004.jsonl | 1527863700 | There are $$$n$$$ distinct points on a coordinate line, the coordinate of $$$i$$$-th point equals to $$$x_i$$$. Choose a subset of the given set of points such that the distance between each pair of points in a subset is an integral power of two. It is necessary to consider each pair of points, not only adjacent. Note that any subset containing one element satisfies the condition above. Among all these subsets, choose a subset with maximum possible size.In other words, you have to choose the maximum possible number of points $$$x_{i_1}, x_{i_2}, \dots, x_{i_m}$$$ such that for each pair $$$x_{i_j}$$$, $$$x_{i_k}$$$ it is true that $$$|x_{i_j} - x_{i_k}| = 2^d$$$ where $$$d$$$ is some non-negative integer number (not necessarily the same for each pair of points). | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.StringTokenizer;
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);
Task solver = new Task();
solver.solve(1, in, out);
out.close();
}
static class Task {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
Set<Integer> x = new HashSet<>();
int first = 0;
int second = 0;
int isSet = 0;
for (int i = 0; i < n; i++) {
x.add(in.nextInt());
}
for (long power = 1; power <= 2000000000; power *= 2) {
for (int t : x) {
int left = (int) (t - power);
int right = (int) (t + power);
if (x.contains(left) && x.contains(right)) {
out.println(3);
out.println(left + " " + t + " " + right);
return;
} else if (x.contains(left) && isSet == 0) {
first = t;
second = left;
isSet = 1;
} else if (x.contains(right) && isSet == 0) {
first = t;
second = right;
isSet = 1;
}
}
}
if (isSet == 1) {
out.println(2);
out.println(first + " " + second);
return;
}
out.println(1);
out.println(x.toArray()[0]);
return;
}
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public Long nextLong() {
return Long.parseLong(next());
}
}
} | Java | ["6\n3 5 4 7 10 12", "5\n-1 2 5 8 11"] | 4 seconds | ["3\n7 3 5", "1\n8"] | NoteIn the first example the answer is $$$[7, 3, 5]$$$. Note, that $$$|7-3|=4=2^2$$$, $$$|7-5|=2=2^1$$$ and $$$|3-5|=2=2^1$$$. You can't find a subset having more points satisfying the required property. | Java 8 | standard input | [
"brute force",
"math"
] | f413556df7dc980ca7e7bd1168d700d2 | The first line contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of points. The second line contains $$$n$$$ pairwise distinct integers $$$x_1, x_2, \dots, x_n$$$ ($$$-10^9 \le x_i \le 10^9$$$) — the coordinates of points. | 1,800 | In the first line print $$$m$$$ — the maximum possible number of points in a subset that satisfies the conditions described above. In the second line print $$$m$$$ integers — the coordinates of points in the subset you have chosen. If there are multiple answers, print any of them. | standard output | |
PASSED | b7202d6761294c367f94dc10c3d49545 | train_004.jsonl | 1527863700 | There are $$$n$$$ distinct points on a coordinate line, the coordinate of $$$i$$$-th point equals to $$$x_i$$$. Choose a subset of the given set of points such that the distance between each pair of points in a subset is an integral power of two. It is necessary to consider each pair of points, not only adjacent. Note that any subset containing one element satisfies the condition above. Among all these subsets, choose a subset with maximum possible size.In other words, you have to choose the maximum possible number of points $$$x_{i_1}, x_{i_2}, \dots, x_{i_m}$$$ such that for each pair $$$x_{i_j}$$$, $$$x_{i_k}$$$ it is true that $$$|x_{i_j} - x_{i_k}| = 2^d$$$ where $$$d$$$ is some non-negative integer number (not necessarily the same for each pair of points). | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.StringTokenizer;
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);
Task solver = new Task();
solver.solve(1, in, out);
out.close();
}
static class Task {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
Set<Long> x = new HashSet<>();
long first = 0;
long second = 0;
int isSet = 0;
for (int i = 0; i < n; i++) {
x.add(in.nextLong());
}
for (long power = 1; power <= 2000000000; power *= 2) {
for (long t : x) {
long right = (t + power);
if (x.contains(right)) {
if (isSet == 0) {
first = t;
second = right;
isSet = 1;
}
if (x.contains(right + power)) {
out.println(3);
out.println(t + " " + right + " " + (right + power));
return;
}
}
}
}
if (isSet == 1) {
out.println(2);
out.println(first + " " + second);
return;
}
out.println(1);
out.println(x.toArray()[0]);
return;
}
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public Long nextLong() {
return Long.parseLong(next());
}
}
} | Java | ["6\n3 5 4 7 10 12", "5\n-1 2 5 8 11"] | 4 seconds | ["3\n7 3 5", "1\n8"] | NoteIn the first example the answer is $$$[7, 3, 5]$$$. Note, that $$$|7-3|=4=2^2$$$, $$$|7-5|=2=2^1$$$ and $$$|3-5|=2=2^1$$$. You can't find a subset having more points satisfying the required property. | Java 8 | standard input | [
"brute force",
"math"
] | f413556df7dc980ca7e7bd1168d700d2 | The first line contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of points. The second line contains $$$n$$$ pairwise distinct integers $$$x_1, x_2, \dots, x_n$$$ ($$$-10^9 \le x_i \le 10^9$$$) — the coordinates of points. | 1,800 | In the first line print $$$m$$$ — the maximum possible number of points in a subset that satisfies the conditions described above. In the second line print $$$m$$$ integers — the coordinates of points in the subset you have chosen. If there are multiple answers, print any of them. | standard output | |
PASSED | 41731a4fc7998ae9909e32f69723d882 | train_004.jsonl | 1527863700 | There are $$$n$$$ distinct points on a coordinate line, the coordinate of $$$i$$$-th point equals to $$$x_i$$$. Choose a subset of the given set of points such that the distance between each pair of points in a subset is an integral power of two. It is necessary to consider each pair of points, not only adjacent. Note that any subset containing one element satisfies the condition above. Among all these subsets, choose a subset with maximum possible size.In other words, you have to choose the maximum possible number of points $$$x_{i_1}, x_{i_2}, \dots, x_{i_m}$$$ such that for each pair $$$x_{i_j}$$$, $$$x_{i_k}$$$ it is true that $$$|x_{i_j} - x_{i_k}| = 2^d$$$ where $$$d$$$ is some non-negative integer number (not necessarily the same for each pair of points). | 256 megabytes |
import java.io.*;
import java.math.*;
import java.sql.Timestamp;
import java.text.*;
import java.time.LocalDateTime;
import java.util.*;
public class Watermelon {
static int count=0,ans=0;
static int n,m,k,s;
static HashMap<Integer,ArrayList<Integer>> map=new HashMap<>();
static int[][] goods;
static int[][] dist;
static int[][] adj;
public static void main(String[] args) throws IOException, ParseException {
Reader sc=new Reader();
n=sc.nextInt();
int[] arr=new int[n];
HashMap<Integer,Boolean> map=new HashMap<>();
for(int i=0;i<n;i++){
arr[i]=sc.nextInt();
map.putIfAbsent(arr[i],true);
}
int[] res=new int[3];
Arrays.fill(res,Integer.MAX_VALUE);
res[0]=arr[0];
int ans=1;
for(int i=0;i<n;i++){
for(int j=0;j<31;j++){
boolean l=map.getOrDefault(arr[i]-(1<<j),false);
boolean r=map.getOrDefault(arr[i]+(1<<j),false);
if(l&&r&&ans<3){
res[0]=arr[i]-(1<<j);res[1]=arr[i];res[2]=arr[i]+(1<<j);
ans=3;
}
if(l&&ans<2){
res[0]=arr[i]-(1<<j);res[1]=arr[i];
ans=2;
}
if(r&&ans<2){
res[0]=arr[i];res[1]=arr[i]+(1<<j);
ans=2;
}
}
}
System.out.println(ans);
for(int i=0;i<3;i++)
if(res[i]!=Integer.MAX_VALUE)
System.out.print(res[i]+" ");
else break;
}
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 | ["6\n3 5 4 7 10 12", "5\n-1 2 5 8 11"] | 4 seconds | ["3\n7 3 5", "1\n8"] | NoteIn the first example the answer is $$$[7, 3, 5]$$$. Note, that $$$|7-3|=4=2^2$$$, $$$|7-5|=2=2^1$$$ and $$$|3-5|=2=2^1$$$. You can't find a subset having more points satisfying the required property. | Java 8 | standard input | [
"brute force",
"math"
] | f413556df7dc980ca7e7bd1168d700d2 | The first line contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of points. The second line contains $$$n$$$ pairwise distinct integers $$$x_1, x_2, \dots, x_n$$$ ($$$-10^9 \le x_i \le 10^9$$$) — the coordinates of points. | 1,800 | In the first line print $$$m$$$ — the maximum possible number of points in a subset that satisfies the conditions described above. In the second line print $$$m$$$ integers — the coordinates of points in the subset you have chosen. If there are multiple answers, print any of them. | standard output | |
PASSED | 5c252b443723ac3ae2f41b6fa10e0eb0 | train_004.jsonl | 1527863700 | There are $$$n$$$ distinct points on a coordinate line, the coordinate of $$$i$$$-th point equals to $$$x_i$$$. Choose a subset of the given set of points such that the distance between each pair of points in a subset is an integral power of two. It is necessary to consider each pair of points, not only adjacent. Note that any subset containing one element satisfies the condition above. Among all these subsets, choose a subset with maximum possible size.In other words, you have to choose the maximum possible number of points $$$x_{i_1}, x_{i_2}, \dots, x_{i_m}$$$ such that for each pair $$$x_{i_j}$$$, $$$x_{i_k}$$$ it is true that $$$|x_{i_j} - x_{i_k}| = 2^d$$$ where $$$d$$$ is some non-negative integer number (not necessarily the same for each pair of points). | 256 megabytes | import java.io.*;
import java.math.BigInteger;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
Task t = new Task();
t.solve(in, out);
out.close();
}
static class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
static class Task {
public void solve(InputReader in, PrintWriter out) throws IOException {
long tStart = System.currentTimeMillis();
//System.out.println((long)Math.pow(2, 31));
int n = in.nextInt();
int arr[] = new int[n];
HashMap<Integer,Integer> mp = new HashMap<Integer,Integer>();
for(int i=0;i<n;i++){
arr[i] = in.nextInt();
mp.put(arr[i], 1);
}
int re[] = new int[3];
re[0] = arr[0];
int x=1;
for(int i=0;i<n;i++){
for(int j=0;j<=31;j++){
int gap = (int) Math.pow(2, j);
if(x<2){
if(mp.containsKey(arr[i]+gap)){
x=2;
re[0] = arr[i];
re[1] = arr[i]+gap;
}else if(mp.containsKey(arr[i]-gap)){
x=2;
re[0] = arr[i];
re[1] = arr[i]-gap;
}
}
if(x<3){
if(mp.containsKey(arr[i]+gap)&&mp.containsKey(arr[i]-gap)){
x=3;
re[0] = arr[i];
re[1] = arr[i]-gap;
re[2] = arr[i]+gap;
}
}
}
}
out.println(x);
for(int i=0;i<x;i++){
out.print(re[i]+" ");
}
out.println();
//Dumper.print(shortestPathLength(arr));
}
public int shortestPathLength(int[][] graph) {
int n = graph.length;
if(n==1) return 0;
int g[][] = new int[n][n];
for(int i=0;i<n;i++){
Arrays.fill(g[i], 99999999);
g[i][i] = 0;
for(int j:graph[i]){
g[i][j] = 1;
}
}
for(int k=0;k<n;k++){
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
g[i][j] = Math.min(g[i][j], g[i][k]+g[k][j]);
}
}
}
int p[] = new int[(int)Math.pow(2, n)];
Arrays.fill(p, 99999999);
int target = (int)Math.pow(2, n)-1;
for(int i=0;i<n;i++){
//Dumper.print(Integer.toBinaryString(1<<i));
dp(g,p,1<<i,i,0,target);
}
//Dumper.print_2d_arr(g, n, n);
Dumper.print_int_arr(p);
return p[target];
}
int dp(int[][] g, int[] p, int status, int cur, int step, int target){
if(p[status]<=step) return p[status];
if(status==target) {
Dumper.print(step);
return p[status] = step;
}
int min = 99999999;
for(int i=0;i<g.length;i++){
if(g[cur][i]==0||(status & (1L << i)) != 0) continue;
min = Math.min(min, dp(g,p,status|(1<<i),i,step+1,target));
}
return p[status] = min;
}
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
int l1=0; int l2=0; int r1=nums1.length-1; int r2=nums2.length-1;
int n = nums1.length; int m = nums2.length;
if(n==0){
if(m==0) return 0.0;
if(m%2==1) return nums2[m/2];
else return 1.0*(nums2[m/2]+nums2[m/2-1])/2.0;
}
if(m==0){
if(n%2==1) return nums1[n/2];
else return 1.0*(nums1[n/2]+nums1[n/2-1])/2.0;
}
int t=(m+n-1)/2;
while((l1<r1-1)||(l2<r2-1)){
int mid1 = l1+(r1-l1)/2;
int mid2 = l2+(r2-l2)/2;
int n1 = find(nums2, nums1[mid1]);
int n2 = find(nums1, nums2[mid2]);
Dumper.print(mid1+" "+mid2+" "+n1+" "+n2);
if(n1+mid1==t){
if((m+n)%2==1) return nums1[mid1];
else return 1.0*(nums1[mid1]+nums2[n1])/2.0;
}else if(n1+mid1>t){
if(l2<r2-1) l2=mid2;//r2=Math.min(n1, r2);
if(l1<r1-1) r1=mid1;//l1=Math.max(l1, n2);
}else{
if(l2<r2-1) r2=mid2;//l2=Math.max(n2, l2);
if(l1<r1-1) l1=mid1;//r1=Math.min(r1, n2);
}
}
int a=find(nums2,nums1[l1]);
int b=find(nums2,nums1[r1]);
int c=find(nums1,nums2[l2]);
int d=find(nums1,nums2[r2]);
if(a+l1==t){
if((m+n)%2==1) return nums1[l1];
else{
int tmp = nums1[r1];
if(nums2[l2]>=tmp&&nums2[l2]<nums1[r1]) tmp = nums2[l2];
return 1.0*(nums1[l1]+tmp)/2.0;
}
}
if(b+r1==t){
if((m+n)%2==1) return nums1[r1];
else{
int tmp = nums2[l2];
return 1.0*(nums1[r1]+tmp)/2.0;
}
}
if(c+l2==t){
if((m+n)%2==1) return nums2[l2];
else{
int tmp = nums2[r2];
if(nums1[l1]>=tmp&&nums1[l1]<nums2[r2]) tmp = nums1[l1];
return 1.0*(nums2[l2]+tmp)/2.0;
}
}
if(d+r2==t){
if((m+n)%2==1) return nums2[r2];
else{
int tmp = nums1[l1];
return 1.0*(nums2[r2]+tmp)/2.0;
}
}
return 1.0;
}
int find(int arr[], int v){
int l=0; int r=arr.length-1;
while(l<r-1){
int mid = l+(r-l)/2;
if(arr[mid]<v){
l=mid;
}else{
r=mid;
}
}
if(arr[r]<=v) return r+1;
if(arr[l]<=v) return l+1;
return 0;
}
public List<Integer> fallingSquares(int[][] positions) {
int n = positions.length;
ArrayList<Integer> arr = new ArrayList<Integer>();
for(int i=0;i<n;i++){
arr.add(positions[i][0]);
arr.add(positions[i][0]+positions[i][1]-1);
}
Collections.sort(arr);
HashMap<Integer, Integer> mp = new HashMap<Integer,Integer>();
for(int i=0,j=0;i<arr.size();i++){
if(!mp.containsKey(arr.get(i))){
mp.put(arr.get(i),j++);
}
}
int square[][] = new int[n][3];
for(int i=0;i<n;i++){
square[i][0] = mp.get(positions[i][0]);
square[i][1] = mp.get(positions[i][0]+positions[i][1]-1);
square[i][2] = positions[i][1];
}
List<Integer> result = new ArrayList<Integer>();
seg_tree t = new seg_tree(mp.size());
int tmp_v = 1;
while(tmp_v<mp.size()) {
tmp_v*=2;
}
for(int i=0;i<n;i++){
int tmp = t.query1(square[i][0], square[i][1]+1, 0, 0, tmp_v);
System.out.println(tmp);
t.update(square[i][0], square[i][1]+1, 0, 0, tmp_v, square[i][2]+tmp);
tmp = t.query(0,tmp_v, 0, 0, tmp_v);
result.add(tmp);
}
return result;
}
class seg_tree{
int n;
int arr_leaf[];
int arr_node[];
public seg_tree(int x) {
n=1;
while(n<x) {
n*=2;
}
arr_leaf = new int[2*n-1];
arr_node = new int[2*n-1];
}
public int update(int a, int b, int k, int i, int j, int v) {
if(a<=i&&j<=b) {
arr_leaf[k]=v;
return Math.max(arr_leaf[k], arr_node[k]);
}else if(i<b&&a<j){
int t1 = update(a,b,k*2+1,i,(i+j)/2,v);
int t2 = update(a,b,k*2+2,(i+j)/2,j,v);
arr_node[k] = Math.max(arr_node[k], Math.max(t1, t2));
return arr_node[k];
}else {
return 0;
}
}
public int query(int a, int b, int k, int i, int j) {
if(b<=i||j<=a) {
return 0;
}else if(a<=i&&j<=b) {
return Math.max(arr_leaf[k], arr_node[k]);
}else {
int t1 = query(a,b,k*2+1,i,(i+j)/2);
int t2 = query(a,b,k*2+2,(i+j)/2,j);
return Math.max(t1,t2);
}
}
public int query1(int a, int b, int k, int i, int j) {
if(b<=i||j<=a) {
return 0;
}else if(a<=i&&j<=b) {
return Math.max(arr_leaf[k], arr_node[k]);
}else {
//if(arr_leaf[k]!=0) return arr_leaf[k];
int t1 = query1(a,b,k*2+1,i,(i+j)/2);
int t2 = query1(a,b,k*2+2,(i+j)/2,j);
return Math.max(arr_leaf[k], Math.max(t1,t2));
}
}
}
public ListNode reverseKGroup(ListNode head, int k) {
if(k<=1||head==null||head.next==null) return head;
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode pre1 = dummy;
ListNode pre2 = pre1;
ListNode p = head;
ListNode q = p;
while(true){
int c=1;
boolean flag = true;
while(q!=null&&q.next!=null&&c<k){
q = q.next;
c++;
flag = false;
}
if(c<k||flag) break;
int d = k;
c=1;
q=p;
ListNode end = q;
while(c<d&&d>1){
c=1;
while(c<d){
q=q.next;
pre2=pre2.next;
c++;
}
//System.out.println(p.val+" "+q.val);
if(d==2){
p.next=q.next;
q.next=p;
pre1.next=q;
}else{
ListNode tmp = p.next;
p.next=q.next;
q.next=tmp;
pre1.next=q;
pre2.next=p;
}
Dumper.print_listnode(dummy);
if(d>3){
p=q.next;
pre1=q;
}else{
pre1=end;
p=end.next;
}
q=p;
pre2=pre1;
c=0;
d-=2;
}
}
return dummy.next;
}
ListNode create(int arr[]){
int p=1;
ListNode head = new ListNode(arr[0]);
ListNode pre = head;
while(p<arr.length){
ListNode tmp = new ListNode(arr[p++]);
pre.next=tmp;
pre=pre.next;
}
return head;
}
public int[] maxNumber1(int[] nums1, int[] nums2, int k) {
int m = nums1.length;
int n = nums2.length;
int arr1[] = new int[m];
int arr2[] = new int[n];
for(int i=0;i<m;i++) arr1[i] = nums1[i];
for(int i=0;i<n;i++) arr2[i] = nums2[i];
String dp[][][] = new String[m+1][n+1][k+1];
for(int i=0;i<=m;i++){
for(int j=0;j<=n;j++){
for(int p=0;p<=k;p++){
dp[i][j][p] = "";
}
}
}
for(int i=0;i<=m;i++){
for(int j=0;j<=n;j++){
for(int p=1;p<=Math.min(i+j, k);p++){
if(i>=1&&dp[i-1][j][p].compareTo(dp[i][j][p])>0) {
dp[i][j][p] = dp[i-1][j][p];
}
if(j>=1&&dp[i][j-1][p].compareTo(dp[i][j][p])>0) {
dp[i][j][p] = dp[i][j-1][p];
}
String t1 = "";
String t2 = "";
if(i>=1) t1 = dp[i-1][j][p-1]+arr1[i-1];
if(j>=1) t2 = dp[i][j-1][p-1]+arr2[j-1];
if(t1.compareTo((dp[i][j][p]))>0) {
dp[i][j][p] = t1;
}
if(t2.compareTo((dp[i][j][p]))>0) {
dp[i][j][p] = t2;
}
}
}
}
int result[] = new int[k];
char tmp[] = dp[m][n][k].toCharArray();
for(int i=0;i<k;i++){
result[i] = tmp[i]-'0';
}
return result;
}
class TreeNode {
int val;
TreeNode left;
TreeNode right;
public TreeNode(int a) {
val = a;
}
}
public class Interval {
int start;
int end;
Interval() {
start = 0;
end = 0;
}
Interval(int s, int e) {
start = s;
end = e;
}
}
}
// default class
static class InputReader {
public BufferedReader re;
public StringTokenizer st;
public InputReader(InputStream input) {
re = new BufferedReader(new InputStreamReader(input));
st = null;
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(re.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return st.nextToken();
}
public String nextLine() {
String tmp = null;
try {
tmp = re.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
return tmp;
}
public boolean hasNext() {
String tmp;
if (st != null && st.hasMoreTokens())
return true;
else {
try {
tmp = re.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
if (tmp != null) {
st = new StringTokenizer(tmp);
return true;
} else {
return false;
}
}
}
public int nextInt() {
return Integer.parseInt(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public long nextLong() {
return Long.parseLong(next());
}
}
static class Dumper {
static void print_int_arr(int[] arr) {
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
System.out.println("---------------------");
}
static void print_char_arr(char[] arr) {
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
System.out.println("---------------------");
}
static void print_double_arr(double[] arr) {
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
System.out.println("---------------------");
}
static void print_2d_arr(int[][] arr, int x, int y) {
for (int i = 0; i < x; i++) {
for (int j = 0; j < y; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
System.out.println();
System.out.println("---------------------");
}
static void print_2d_arr(boolean[][] arr, int x, int y) {
for (int i = 0; i < x; i++) {
for (int j = 0; j < y; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
System.out.println();
System.out.println("---------------------");
}
static void print(Object o) {
System.out.println(o.toString());
}
static void getc() {
System.out.println("here");
}
static void print_listnode(ListNode x){
while(x!=null){
System.out.print(x.val+" ");
x=x.next;
}
System.out.println();
}
}
} | Java | ["6\n3 5 4 7 10 12", "5\n-1 2 5 8 11"] | 4 seconds | ["3\n7 3 5", "1\n8"] | NoteIn the first example the answer is $$$[7, 3, 5]$$$. Note, that $$$|7-3|=4=2^2$$$, $$$|7-5|=2=2^1$$$ and $$$|3-5|=2=2^1$$$. You can't find a subset having more points satisfying the required property. | Java 8 | standard input | [
"brute force",
"math"
] | f413556df7dc980ca7e7bd1168d700d2 | The first line contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of points. The second line contains $$$n$$$ pairwise distinct integers $$$x_1, x_2, \dots, x_n$$$ ($$$-10^9 \le x_i \le 10^9$$$) — the coordinates of points. | 1,800 | In the first line print $$$m$$$ — the maximum possible number of points in a subset that satisfies the conditions described above. In the second line print $$$m$$$ integers — the coordinates of points in the subset you have chosen. If there are multiple answers, print any of them. | standard output | |
PASSED | 9e1418548ff9d56aa577b8d714f7a237 | train_004.jsonl | 1527863700 | There are $$$n$$$ distinct points on a coordinate line, the coordinate of $$$i$$$-th point equals to $$$x_i$$$. Choose a subset of the given set of points such that the distance between each pair of points in a subset is an integral power of two. It is necessary to consider each pair of points, not only adjacent. Note that any subset containing one element satisfies the condition above. Among all these subsets, choose a subset with maximum possible size.In other words, you have to choose the maximum possible number of points $$$x_{i_1}, x_{i_2}, \dots, x_{i_m}$$$ such that for each pair $$$x_{i_j}$$$, $$$x_{i_k}$$$ it is true that $$$|x_{i_j} - x_{i_k}| = 2^d$$$ where $$$d$$$ is some non-negative integer number (not necessarily the same for each pair of points). | 256 megabytes | import java.io.*;
import java.math.BigInteger;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
Task t = new Task();
t.solve(in, out);
out.close();
}
static class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
static class Task {
public void solve(InputReader in, PrintWriter out) throws IOException {
long tStart = System.currentTimeMillis();
//System.out.println((long)Math.pow(2, 31));
int n = in.nextInt();
int arr[] = new int[n];
HashMap<Integer,Integer> mp = new HashMap<Integer,Integer>();
for(int i=0;i<n;i++){
arr[i] = in.nextInt();
mp.put(arr[i], 1);
}
int re[] = new int[3];
re[0] = arr[0];
int x=1;
for(int i=0;i<n;i++){
for(int j=0;j<=31;j++){
int gap = (int) Math.pow(2, j);
if(x<2){
if(mp.containsKey(arr[i]+gap)){
x=2;
re[0] = arr[i];
re[1] = arr[i]+gap;
}else if(mp.containsKey(arr[i]-gap)){
x=2;
re[0] = arr[i];
re[1] = arr[i]-gap;
}
}
if(x<3){
if(mp.containsKey(arr[i]+gap)&&mp.containsKey(arr[i]-gap)){
x=3;
re[0] = arr[i];
re[1] = arr[i]-gap;
re[2] = arr[i]+gap;
out.println(x);
for(int p=0;p<x;p++){
out.print(re[p]+" ");
}
out.println();
return;
}
}
}
}
out.println(x);
for(int i=0;i<x;i++){
out.print(re[i]+" ");
}
out.println();
//Dumper.print(shortestPathLength(arr));
}
public int shortestPathLength(int[][] graph) {
int n = graph.length;
if(n==1) return 0;
int g[][] = new int[n][n];
for(int i=0;i<n;i++){
Arrays.fill(g[i], 99999999);
g[i][i] = 0;
for(int j:graph[i]){
g[i][j] = 1;
}
}
for(int k=0;k<n;k++){
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
g[i][j] = Math.min(g[i][j], g[i][k]+g[k][j]);
}
}
}
int p[] = new int[(int)Math.pow(2, n)];
Arrays.fill(p, 99999999);
int target = (int)Math.pow(2, n)-1;
for(int i=0;i<n;i++){
//Dumper.print(Integer.toBinaryString(1<<i));
dp(g,p,1<<i,i,0,target);
}
//Dumper.print_2d_arr(g, n, n);
Dumper.print_int_arr(p);
return p[target];
}
int dp(int[][] g, int[] p, int status, int cur, int step, int target){
if(p[status]<=step) return p[status];
if(status==target) {
Dumper.print(step);
return p[status] = step;
}
int min = 99999999;
for(int i=0;i<g.length;i++){
if(g[cur][i]==0||(status & (1L << i)) != 0) continue;
min = Math.min(min, dp(g,p,status|(1<<i),i,step+1,target));
}
return p[status] = min;
}
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
int l1=0; int l2=0; int r1=nums1.length-1; int r2=nums2.length-1;
int n = nums1.length; int m = nums2.length;
if(n==0){
if(m==0) return 0.0;
if(m%2==1) return nums2[m/2];
else return 1.0*(nums2[m/2]+nums2[m/2-1])/2.0;
}
if(m==0){
if(n%2==1) return nums1[n/2];
else return 1.0*(nums1[n/2]+nums1[n/2-1])/2.0;
}
int t=(m+n-1)/2;
while((l1<r1-1)||(l2<r2-1)){
int mid1 = l1+(r1-l1)/2;
int mid2 = l2+(r2-l2)/2;
int n1 = find(nums2, nums1[mid1]);
int n2 = find(nums1, nums2[mid2]);
Dumper.print(mid1+" "+mid2+" "+n1+" "+n2);
if(n1+mid1==t){
if((m+n)%2==1) return nums1[mid1];
else return 1.0*(nums1[mid1]+nums2[n1])/2.0;
}else if(n1+mid1>t){
if(l2<r2-1) l2=mid2;//r2=Math.min(n1, r2);
if(l1<r1-1) r1=mid1;//l1=Math.max(l1, n2);
}else{
if(l2<r2-1) r2=mid2;//l2=Math.max(n2, l2);
if(l1<r1-1) l1=mid1;//r1=Math.min(r1, n2);
}
}
int a=find(nums2,nums1[l1]);
int b=find(nums2,nums1[r1]);
int c=find(nums1,nums2[l2]);
int d=find(nums1,nums2[r2]);
if(a+l1==t){
if((m+n)%2==1) return nums1[l1];
else{
int tmp = nums1[r1];
if(nums2[l2]>=tmp&&nums2[l2]<nums1[r1]) tmp = nums2[l2];
return 1.0*(nums1[l1]+tmp)/2.0;
}
}
if(b+r1==t){
if((m+n)%2==1) return nums1[r1];
else{
int tmp = nums2[l2];
return 1.0*(nums1[r1]+tmp)/2.0;
}
}
if(c+l2==t){
if((m+n)%2==1) return nums2[l2];
else{
int tmp = nums2[r2];
if(nums1[l1]>=tmp&&nums1[l1]<nums2[r2]) tmp = nums1[l1];
return 1.0*(nums2[l2]+tmp)/2.0;
}
}
if(d+r2==t){
if((m+n)%2==1) return nums2[r2];
else{
int tmp = nums1[l1];
return 1.0*(nums2[r2]+tmp)/2.0;
}
}
return 1.0;
}
int find(int arr[], int v){
int l=0; int r=arr.length-1;
while(l<r-1){
int mid = l+(r-l)/2;
if(arr[mid]<v){
l=mid;
}else{
r=mid;
}
}
if(arr[r]<=v) return r+1;
if(arr[l]<=v) return l+1;
return 0;
}
public List<Integer> fallingSquares(int[][] positions) {
int n = positions.length;
ArrayList<Integer> arr = new ArrayList<Integer>();
for(int i=0;i<n;i++){
arr.add(positions[i][0]);
arr.add(positions[i][0]+positions[i][1]-1);
}
Collections.sort(arr);
HashMap<Integer, Integer> mp = new HashMap<Integer,Integer>();
for(int i=0,j=0;i<arr.size();i++){
if(!mp.containsKey(arr.get(i))){
mp.put(arr.get(i),j++);
}
}
int square[][] = new int[n][3];
for(int i=0;i<n;i++){
square[i][0] = mp.get(positions[i][0]);
square[i][1] = mp.get(positions[i][0]+positions[i][1]-1);
square[i][2] = positions[i][1];
}
List<Integer> result = new ArrayList<Integer>();
seg_tree t = new seg_tree(mp.size());
int tmp_v = 1;
while(tmp_v<mp.size()) {
tmp_v*=2;
}
for(int i=0;i<n;i++){
int tmp = t.query1(square[i][0], square[i][1]+1, 0, 0, tmp_v);
System.out.println(tmp);
t.update(square[i][0], square[i][1]+1, 0, 0, tmp_v, square[i][2]+tmp);
tmp = t.query(0,tmp_v, 0, 0, tmp_v);
result.add(tmp);
}
return result;
}
class seg_tree{
int n;
int arr_leaf[];
int arr_node[];
public seg_tree(int x) {
n=1;
while(n<x) {
n*=2;
}
arr_leaf = new int[2*n-1];
arr_node = new int[2*n-1];
}
public int update(int a, int b, int k, int i, int j, int v) {
if(a<=i&&j<=b) {
arr_leaf[k]=v;
return Math.max(arr_leaf[k], arr_node[k]);
}else if(i<b&&a<j){
int t1 = update(a,b,k*2+1,i,(i+j)/2,v);
int t2 = update(a,b,k*2+2,(i+j)/2,j,v);
arr_node[k] = Math.max(arr_node[k], Math.max(t1, t2));
return arr_node[k];
}else {
return 0;
}
}
public int query(int a, int b, int k, int i, int j) {
if(b<=i||j<=a) {
return 0;
}else if(a<=i&&j<=b) {
return Math.max(arr_leaf[k], arr_node[k]);
}else {
int t1 = query(a,b,k*2+1,i,(i+j)/2);
int t2 = query(a,b,k*2+2,(i+j)/2,j);
return Math.max(t1,t2);
}
}
public int query1(int a, int b, int k, int i, int j) {
if(b<=i||j<=a) {
return 0;
}else if(a<=i&&j<=b) {
return Math.max(arr_leaf[k], arr_node[k]);
}else {
//if(arr_leaf[k]!=0) return arr_leaf[k];
int t1 = query1(a,b,k*2+1,i,(i+j)/2);
int t2 = query1(a,b,k*2+2,(i+j)/2,j);
return Math.max(arr_leaf[k], Math.max(t1,t2));
}
}
}
public ListNode reverseKGroup(ListNode head, int k) {
if(k<=1||head==null||head.next==null) return head;
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode pre1 = dummy;
ListNode pre2 = pre1;
ListNode p = head;
ListNode q = p;
while(true){
int c=1;
boolean flag = true;
while(q!=null&&q.next!=null&&c<k){
q = q.next;
c++;
flag = false;
}
if(c<k||flag) break;
int d = k;
c=1;
q=p;
ListNode end = q;
while(c<d&&d>1){
c=1;
while(c<d){
q=q.next;
pre2=pre2.next;
c++;
}
//System.out.println(p.val+" "+q.val);
if(d==2){
p.next=q.next;
q.next=p;
pre1.next=q;
}else{
ListNode tmp = p.next;
p.next=q.next;
q.next=tmp;
pre1.next=q;
pre2.next=p;
}
Dumper.print_listnode(dummy);
if(d>3){
p=q.next;
pre1=q;
}else{
pre1=end;
p=end.next;
}
q=p;
pre2=pre1;
c=0;
d-=2;
}
}
return dummy.next;
}
ListNode create(int arr[]){
int p=1;
ListNode head = new ListNode(arr[0]);
ListNode pre = head;
while(p<arr.length){
ListNode tmp = new ListNode(arr[p++]);
pre.next=tmp;
pre=pre.next;
}
return head;
}
public int[] maxNumber1(int[] nums1, int[] nums2, int k) {
int m = nums1.length;
int n = nums2.length;
int arr1[] = new int[m];
int arr2[] = new int[n];
for(int i=0;i<m;i++) arr1[i] = nums1[i];
for(int i=0;i<n;i++) arr2[i] = nums2[i];
String dp[][][] = new String[m+1][n+1][k+1];
for(int i=0;i<=m;i++){
for(int j=0;j<=n;j++){
for(int p=0;p<=k;p++){
dp[i][j][p] = "";
}
}
}
for(int i=0;i<=m;i++){
for(int j=0;j<=n;j++){
for(int p=1;p<=Math.min(i+j, k);p++){
if(i>=1&&dp[i-1][j][p].compareTo(dp[i][j][p])>0) {
dp[i][j][p] = dp[i-1][j][p];
}
if(j>=1&&dp[i][j-1][p].compareTo(dp[i][j][p])>0) {
dp[i][j][p] = dp[i][j-1][p];
}
String t1 = "";
String t2 = "";
if(i>=1) t1 = dp[i-1][j][p-1]+arr1[i-1];
if(j>=1) t2 = dp[i][j-1][p-1]+arr2[j-1];
if(t1.compareTo((dp[i][j][p]))>0) {
dp[i][j][p] = t1;
}
if(t2.compareTo((dp[i][j][p]))>0) {
dp[i][j][p] = t2;
}
}
}
}
int result[] = new int[k];
char tmp[] = dp[m][n][k].toCharArray();
for(int i=0;i<k;i++){
result[i] = tmp[i]-'0';
}
return result;
}
class TreeNode {
int val;
TreeNode left;
TreeNode right;
public TreeNode(int a) {
val = a;
}
}
public class Interval {
int start;
int end;
Interval() {
start = 0;
end = 0;
}
Interval(int s, int e) {
start = s;
end = e;
}
}
}
// default class
static class InputReader {
public BufferedReader re;
public StringTokenizer st;
public InputReader(InputStream input) {
re = new BufferedReader(new InputStreamReader(input));
st = null;
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(re.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return st.nextToken();
}
public String nextLine() {
String tmp = null;
try {
tmp = re.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
return tmp;
}
public boolean hasNext() {
String tmp;
if (st != null && st.hasMoreTokens())
return true;
else {
try {
tmp = re.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
if (tmp != null) {
st = new StringTokenizer(tmp);
return true;
} else {
return false;
}
}
}
public int nextInt() {
return Integer.parseInt(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public long nextLong() {
return Long.parseLong(next());
}
}
static class Dumper {
static void print_int_arr(int[] arr) {
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
System.out.println("---------------------");
}
static void print_char_arr(char[] arr) {
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
System.out.println("---------------------");
}
static void print_double_arr(double[] arr) {
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
System.out.println("---------------------");
}
static void print_2d_arr(int[][] arr, int x, int y) {
for (int i = 0; i < x; i++) {
for (int j = 0; j < y; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
System.out.println();
System.out.println("---------------------");
}
static void print_2d_arr(boolean[][] arr, int x, int y) {
for (int i = 0; i < x; i++) {
for (int j = 0; j < y; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
System.out.println();
System.out.println("---------------------");
}
static void print(Object o) {
System.out.println(o.toString());
}
static void getc() {
System.out.println("here");
}
static void print_listnode(ListNode x){
while(x!=null){
System.out.print(x.val+" ");
x=x.next;
}
System.out.println();
}
}
} | Java | ["6\n3 5 4 7 10 12", "5\n-1 2 5 8 11"] | 4 seconds | ["3\n7 3 5", "1\n8"] | NoteIn the first example the answer is $$$[7, 3, 5]$$$. Note, that $$$|7-3|=4=2^2$$$, $$$|7-5|=2=2^1$$$ and $$$|3-5|=2=2^1$$$. You can't find a subset having more points satisfying the required property. | Java 8 | standard input | [
"brute force",
"math"
] | f413556df7dc980ca7e7bd1168d700d2 | The first line contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of points. The second line contains $$$n$$$ pairwise distinct integers $$$x_1, x_2, \dots, x_n$$$ ($$$-10^9 \le x_i \le 10^9$$$) — the coordinates of points. | 1,800 | In the first line print $$$m$$$ — the maximum possible number of points in a subset that satisfies the conditions described above. In the second line print $$$m$$$ integers — the coordinates of points in the subset you have chosen. If there are multiple answers, print any of them. | standard output | |
PASSED | a9087c9178c2e51d10969d6ea677828a | train_004.jsonl | 1527863700 | There are $$$n$$$ distinct points on a coordinate line, the coordinate of $$$i$$$-th point equals to $$$x_i$$$. Choose a subset of the given set of points such that the distance between each pair of points in a subset is an integral power of two. It is necessary to consider each pair of points, not only adjacent. Note that any subset containing one element satisfies the condition above. Among all these subsets, choose a subset with maximum possible size.In other words, you have to choose the maximum possible number of points $$$x_{i_1}, x_{i_2}, \dots, x_{i_m}$$$ such that for each pair $$$x_{i_j}$$$, $$$x_{i_k}$$$ it is true that $$$|x_{i_j} - x_{i_k}| = 2^d$$$ where $$$d$$$ is some non-negative integer number (not necessarily the same for each pair of points). | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws Exception {
new Main().go();
}
PrintWriter out;
Reader in;
BufferedReader br;
Main() throws IOException {
try {
//br = new BufferedReader( new FileReader("input.txt") );
//in = new Reader("input.txt");
in = new Reader("input.txt");
out = new PrintWriter( new BufferedWriter(new FileWriter("output.txt")) );
}
catch (Exception e) {
//br = new BufferedReader( new InputStreamReader( System.in ) );
in = new Reader();
out = new PrintWriter( new BufferedWriter(new OutputStreamWriter(System.out)) );
}
}
void go() throws Exception {
//int t = in.nextInt();
int t = 1;
while (t > 0) {
solve();
t--;
}
out.flush();
out.close();
}
int inf = 2000000000;
int mod = 1000000007;
double eps = 0.000000001;
int n;
int m;
ArrayList<Integer>[] g;
void solve() throws IOException {
int n = in.nextInt();
int[] a = new int[n];
HashSet<Long> set = new HashSet<>();
for (int i = 0; i < n; i++) {
a[i] = in.nextInt();
set.add((long)a[i]);
}
Arrays.sort(a);
long[] ans = new long[3];
int len = 1;
ans[0] = a[0];
for (int i = 0; i < 32; i++) {
long st = 1L << i;
for (int j = 0; j < n; j++) {
if (len < 3 && set.contains(a[j] + st)) {
len = 2;
ans[0] = a[j];
ans[1] = a[j] + st;
if (set.contains(st * 2 + a[j])) {
len = 3;
ans[2] = st * 2 + a[j];
}
}
}
}
out.println(len);
for (int i = 0; i < len; i++) {
out.print(ans[i] + " ");
}
}
class Pair implements Comparable<Pair>{
int a;
int b;
Pair(int a, int b) {
this.a = a;
this.b = b;
}
public int compareTo(Pair p) {
if (a != p.a)
return Integer.compare(a, p.a);
else
return Integer.compare(b, p.b);
}
}
class Item {
int a;
int b;
int c;
Item(int a, int b, int c) {
this.a = a;
this.b = b;
this.c = c;
}
}
class Reader {
BufferedReader br;
StringTokenizer tok;
Reader(String file) throws IOException {
br = new BufferedReader( new FileReader(file) );
}
Reader() throws IOException {
br = new BufferedReader( new InputStreamReader(System.in) );
}
String next() throws IOException {
while (tok == null || !tok.hasMoreElements())
tok = new StringTokenizer(br.readLine());
return tok.nextToken();
}
int nextInt() throws NumberFormatException, IOException {
return Integer.valueOf(next());
}
long nextLong() throws NumberFormatException, IOException {
return Long.valueOf(next());
}
double nextDouble() throws NumberFormatException, IOException {
return Double.valueOf(next());
}
String nextLine() throws IOException {
return br.readLine();
}
}
static class InputReader
{
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public InputReader()
{
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public InputReader(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 | ["6\n3 5 4 7 10 12", "5\n-1 2 5 8 11"] | 4 seconds | ["3\n7 3 5", "1\n8"] | NoteIn the first example the answer is $$$[7, 3, 5]$$$. Note, that $$$|7-3|=4=2^2$$$, $$$|7-5|=2=2^1$$$ and $$$|3-5|=2=2^1$$$. You can't find a subset having more points satisfying the required property. | Java 8 | standard input | [
"brute force",
"math"
] | f413556df7dc980ca7e7bd1168d700d2 | The first line contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of points. The second line contains $$$n$$$ pairwise distinct integers $$$x_1, x_2, \dots, x_n$$$ ($$$-10^9 \le x_i \le 10^9$$$) — the coordinates of points. | 1,800 | In the first line print $$$m$$$ — the maximum possible number of points in a subset that satisfies the conditions described above. In the second line print $$$m$$$ integers — the coordinates of points in the subset you have chosen. If there are multiple answers, print any of them. | standard output | |
PASSED | a6eb0ef645fa2a0b46634bf33691823c | train_004.jsonl | 1527863700 | There are $$$n$$$ distinct points on a coordinate line, the coordinate of $$$i$$$-th point equals to $$$x_i$$$. Choose a subset of the given set of points such that the distance between each pair of points in a subset is an integral power of two. It is necessary to consider each pair of points, not only adjacent. Note that any subset containing one element satisfies the condition above. Among all these subsets, choose a subset with maximum possible size.In other words, you have to choose the maximum possible number of points $$$x_{i_1}, x_{i_2}, \dots, x_{i_m}$$$ such that for each pair $$$x_{i_j}$$$, $$$x_{i_k}$$$ it is true that $$$|x_{i_j} - x_{i_k}| = 2^d$$$ where $$$d$$$ is some non-negative integer number (not necessarily the same for each pair of points). | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Stack;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.TreeSet;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Main {
public static class CC {
public int i, j, d;
public CC() {
}
@Override
public int hashCode() {
return d;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
CC other = (CC) obj;
if (d != other.d)
return false;
return true;
}
}
public static void main(String[] args) throws IOException {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
PrintWriter out = new PrintWriter(outputStream);
InputReader in = new InputReader(inputStream);
int n = in.nextInt();
long[] x = new long[n];
Set<Long> S = new HashSet<Long>();
for (int i = 0; i < n; i++) {
x[i] = in.nextLong();
S.add(x[i]);
}
//Arrays.sort(x);
// 3
for (int i = 0; i < n; i++) {
for (int k = 0; k <= 32; k++) {
if (S.contains(x[i] + (1L << k)) && S.contains(x[i] + (1L << k) + (1L << k))) {
out.println(3);
out.println(x[i] + " " + (x[i] + (1L << k)) + " " + (x[i] + (1L << k) + (1L << k)));
out.close();
return;
}
}
}
// 2
for (int i = 0; i < n; i++) {
for (int k = 0; k <= 32; k++) {
if (S.contains(x[i] + (1L << k))) {
out.println(2);
out.println(x[i] + " " + (x[i] + (1L << k)));
out.close();
return;
}
}
}
out.println(1);
out.println(x[0]);
out.close();
}
static class InputReader {
BufferedReader reader;
StringTokenizer tokenizer;
public InputReader(InputStream inputStream) {
reader = new BufferedReader(new InputStreamReader(inputStream), 32624);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException ex) {
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
private long nextLong() {
return Long.parseLong(next());
}
private double nextDouble() {
return Double.parseDouble(next());
}
public int[] nextArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = nextInt();
}
return a;
}
public long[] nextArrayl(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++) {
a[i] = nextLong();
}
return a;
}
public double[] nextArrayd(int n) {
double[] a = new double[n];
for (int i = 0; i < n; i++) {
a[i] = nextDouble();
}
return a;
}
private BigInteger nextBigInteger() {
return new BigInteger(next());
}
public void printAr(int[] a) {
System.out.print("[");
for (long x : a) {
System.out.print(x + ",");
}
System.out.print("]");
}
}
} | Java | ["6\n3 5 4 7 10 12", "5\n-1 2 5 8 11"] | 4 seconds | ["3\n7 3 5", "1\n8"] | NoteIn the first example the answer is $$$[7, 3, 5]$$$. Note, that $$$|7-3|=4=2^2$$$, $$$|7-5|=2=2^1$$$ and $$$|3-5|=2=2^1$$$. You can't find a subset having more points satisfying the required property. | Java 8 | standard input | [
"brute force",
"math"
] | f413556df7dc980ca7e7bd1168d700d2 | The first line contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of points. The second line contains $$$n$$$ pairwise distinct integers $$$x_1, x_2, \dots, x_n$$$ ($$$-10^9 \le x_i \le 10^9$$$) — the coordinates of points. | 1,800 | In the first line print $$$m$$$ — the maximum possible number of points in a subset that satisfies the conditions described above. In the second line print $$$m$$$ integers — the coordinates of points in the subset you have chosen. If there are multiple answers, print any of them. | standard output | |
PASSED | 7a548e60c227fbe64e3063627d1934e9 | train_004.jsonl | 1527863700 | There are $$$n$$$ distinct points on a coordinate line, the coordinate of $$$i$$$-th point equals to $$$x_i$$$. Choose a subset of the given set of points such that the distance between each pair of points in a subset is an integral power of two. It is necessary to consider each pair of points, not only adjacent. Note that any subset containing one element satisfies the condition above. Among all these subsets, choose a subset with maximum possible size.In other words, you have to choose the maximum possible number of points $$$x_{i_1}, x_{i_2}, \dots, x_{i_m}$$$ such that for each pair $$$x_{i_j}$$$, $$$x_{i_k}$$$ it is true that $$$|x_{i_j} - x_{i_k}| = 2^d$$$ where $$$d$$$ is some non-negative integer number (not necessarily the same for each pair of points). | 256 megabytes | /*
ЗАПУСКАЕМ ВЫСОКОГО
░ГУСЯ░▄▀▀▀▄░РАБОТЯГИ░░
▄███▀░◐░░░▌░░░░░░░
░░░░▌░░░░░▐░░░░░░░
░░░░▐░░░░░▐░░░░░░░
░░░░▌░░░░░▐▄▄░░░░
░░░░▌░░░░▄▀▒▒▀▀▀▀▄
░░░▐░░░░▐▒▒▒▒▒▒▒▒▀▀▄
░░░▐░░░░▐▄▒▒▒▒▒▒▒▒▒▒▀▄
░░░░▀▄░░░░▀▄▒▒▒▒▒▒▒▒▒▒▀▄
░░░░░░▀▄▄▄▄▄█▄▄▄▄▄▄▄▄▄▄▄▀▄
░░░░░░░░░░░▌▌░▌▌░░░░░
░░░░░░░░░░░▌▌░▌▌░░░░░
░░░░░░░░░▄▄▌▌▄▌▌░░░░░
*/
import java.io.*;
import java.util.*;
public class Main {
void solve() throws IOException {
int n = readInt();
long[] x = new long[n];
for (int i = 0; i < n; i++) x[i] = readInt();
HashSet<Long> set = new HashSet<>();
for (long a : x) set.add(a);
long[] pow2 = new long[31];
pow2[0] = 1;
for (int i = 1; i < 31; i++) pow2[i] = pow2[i - 1] << 1;
long[] ans = new long[3];
int answer = 0;
long[] preans = new long[3];
for (long f : set) {
Arrays.fill(preans, -Integer.MAX_VALUE);
int cur = 1;
preans[0] = f;
boolean f1, f2;
for (long d : pow2) {
int pre = 1;
f1 = false;
f2 = false;
if (set.contains(f - d)) {
pre++;
f1 = true;
}
if (set.contains(f + d)) {
pre++;
f2 = true;
}
if (pre > cur) {
cur = pre;
if (f1) preans[1] = f - d;
if (f2) preans[2] = f + d;
}
}
Arrays.sort(preans);
if (answer < cur) {
answer = cur;
ans = preans.clone();
}
}
out.println(answer);
for (int i = 0; i < 3; i++)
if (ans[i] != -Integer.MAX_VALUE)
out.print(ans[i] + " ");
}
public static void main(String[] args) throws IOException {
new Main().run();
}
BufferedReader in;
PrintWriter out;
StringTokenizer tok;
Main() throws FileNotFoundException {
try {
in = new BufferedReader(new FileReader("input.txt"));
out = new PrintWriter("output.txt");
} catch (Exception e) {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
}
tok = new StringTokenizer("");
}
void run() throws IOException {
solve();
out.close();
}
String delimiter = " ";
String readLine() throws IOException {
return in.readLine();
}
String readString() throws IOException {
while (!tok.hasMoreTokens()) {
String nextLine = readLine();
if (null == nextLine) return null;
tok = new StringTokenizer(nextLine);
}
return tok.nextToken(delimiter);
}
int readInt() throws IOException {
return Integer.parseInt(readString());
}
long readLong() throws IOException {
return Long.parseLong(readString());
}
double readDouble() throws IOException {
return Double.parseDouble(readString());
}
int[] readIntArray(int b) {
int a[] = new int[b];
for (int i = 0; i < b; i++)
try {
a[i] = readInt();
} catch (IOException e) {
e.printStackTrace();
}
return a;
}
int[] readSortedIntArray(int size) throws IOException {
Integer[] array = new Integer[size];
for (int index = 0; index < size; ++index) array[index] = readInt();
Arrays.sort(array);
int[] sortedArray = new int[size];
for (int index = 0; index < size; ++index) sortedArray[index] = array[index];
return sortedArray;
}
int[] sortedIntArray(int size, int[] array) throws IOException {
for (int index = 0; index < size; ++index) array[index] = readInt();
Arrays.sort(array);
int[] sortedArray = new int[size];
for (int index = 0; index < size; ++index) sortedArray[index] = array[index];
return sortedArray;
}
int minInt(int... values) {
int min = Integer.MAX_VALUE;
for (int value : values) min = Math.min(min, value);
return min;
}
int maxInt(int... values) {
int max = Integer.MIN_VALUE;
for (int value : values) max = Math.max(max, value);
return max;
}
long minLong(long... values) {
long min = Long.MAX_VALUE;
for (long value : values) min = Math.min(min, value);
return min;
}
long maxLong(long... values) {
long max = Long.MIN_VALUE;
for (long value : values) max = Math.max(max, value);
return max;
}
boolean checkIndex(int index, int size) {
return (0 <= index && index < size);
}
int abs(int a) {
if (a < 0) return -a;
return a;
}
} | Java | ["6\n3 5 4 7 10 12", "5\n-1 2 5 8 11"] | 4 seconds | ["3\n7 3 5", "1\n8"] | NoteIn the first example the answer is $$$[7, 3, 5]$$$. Note, that $$$|7-3|=4=2^2$$$, $$$|7-5|=2=2^1$$$ and $$$|3-5|=2=2^1$$$. You can't find a subset having more points satisfying the required property. | Java 8 | standard input | [
"brute force",
"math"
] | f413556df7dc980ca7e7bd1168d700d2 | The first line contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of points. The second line contains $$$n$$$ pairwise distinct integers $$$x_1, x_2, \dots, x_n$$$ ($$$-10^9 \le x_i \le 10^9$$$) — the coordinates of points. | 1,800 | In the first line print $$$m$$$ — the maximum possible number of points in a subset that satisfies the conditions described above. In the second line print $$$m$$$ integers — the coordinates of points in the subset you have chosen. If there are multiple answers, print any of them. | standard output | |
PASSED | c20ed2c39ce2f3421ecfb51b23ee76b2 | train_004.jsonl | 1527863700 | There are $$$n$$$ distinct points on a coordinate line, the coordinate of $$$i$$$-th point equals to $$$x_i$$$. Choose a subset of the given set of points such that the distance between each pair of points in a subset is an integral power of two. It is necessary to consider each pair of points, not only adjacent. Note that any subset containing one element satisfies the condition above. Among all these subsets, choose a subset with maximum possible size.In other words, you have to choose the maximum possible number of points $$$x_{i_1}, x_{i_2}, \dots, x_{i_m}$$$ such that for each pair $$$x_{i_j}$$$, $$$x_{i_k}$$$ it is true that $$$|x_{i_j} - x_{i_k}| = 2^d$$$ where $$$d$$$ is some non-negative integer number (not necessarily the same for each pair of points). | 256 megabytes | /*
ЗАПУСКАЕМ ВЫСОКОГО
░ГУСЯ░▄▀▀▀▄░РАБОТЯГИ░░
▄███▀░◐░░░▌░░░░░░░
░░░░▌░░░░░▐░░░░░░░
░░░░▐░░░░░▐░░░░░░░
░░░░▌░░░░░▐▄▄░░░░
░░░░▌░░░░▄▀▒▒▀▀▀▀▄
░░░▐░░░░▐▒▒▒▒▒▒▒▒▀▀▄
░░░▐░░░░▐▄▒▒▒▒▒▒▒▒▒▒▀▄
░░░░▀▄░░░░▀▄▒▒▒▒▒▒▒▒▒▒▀▄
░░░░░░▀▄▄▄▄▄█▄▄▄▄▄▄▄▄▄▄▄▀▄
░░░░░░░░░░░▌▌░▌▌░░░░░
░░░░░░░░░░░▌▌░▌▌░░░░░
░░░░░░░░░▄▄▌▌▄▌▌░░░░░
*/
import java.io.*;
import java.util.*;
public class Main {
void solve() throws IOException {
int n = readInt();
long[] x = new long[n];
for (int i = 0; i < n; i++) x[i] = readInt();
HashSet<Long> set = new HashSet<>();
for (long a : x) set.add(a);
long[] pow2 = new long[31];
pow2[0] = 1;
for (int i = 1; i < 31; i++) pow2[i] = pow2[i - 1] << 1;
long[] ans = new long[3];
int answer = 0;
long[] preans = new long[3];
for (long f : set) {
Arrays.fill(preans, -Integer.MAX_VALUE);
int cur = 1;
preans[0] = f;
boolean f1, f2;
for (long d : pow2) {
int pre = 1;
f1 = false;
f2 = false;
if (set.contains(f - d)) {
pre++;
f1 = true;
}
if (set.contains(f + d)) {
pre++;
f2 = true;
}
if (pre > cur) {
cur = pre;
if (f1) preans[1] = f - d;
if (f2) preans[2] = f + d;
}
}
if (answer < cur) {
answer = cur;
ans = preans.clone();
}
}
out.println(answer);
for (int i = 0; i < 3; i++)
if (ans[i] != -Integer.MAX_VALUE)
out.print(ans[i] + " ");
}
public static void main(String[] args) throws IOException {
new Main().run();
}
BufferedReader in;
PrintWriter out;
StringTokenizer tok;
Main() throws FileNotFoundException {
try {
in = new BufferedReader(new FileReader("input.txt"));
out = new PrintWriter("output.txt");
} catch (Exception e) {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
}
tok = new StringTokenizer("");
}
void run() throws IOException {
solve();
out.close();
}
String delimiter = " ";
String readLine() throws IOException {
return in.readLine();
}
String readString() throws IOException {
while (!tok.hasMoreTokens()) {
String nextLine = readLine();
if (null == nextLine) return null;
tok = new StringTokenizer(nextLine);
}
return tok.nextToken(delimiter);
}
int readInt() throws IOException {
return Integer.parseInt(readString());
}
long readLong() throws IOException {
return Long.parseLong(readString());
}
double readDouble() throws IOException {
return Double.parseDouble(readString());
}
int[] readIntArray(int b) {
int a[] = new int[b];
for (int i = 0; i < b; i++)
try {
a[i] = readInt();
} catch (IOException e) {
e.printStackTrace();
}
return a;
}
int[] readSortedIntArray(int size) throws IOException {
Integer[] array = new Integer[size];
for (int index = 0; index < size; ++index) array[index] = readInt();
Arrays.sort(array);
int[] sortedArray = new int[size];
for (int index = 0; index < size; ++index) sortedArray[index] = array[index];
return sortedArray;
}
int[] sortedIntArray(int size, int[] array) throws IOException {
for (int index = 0; index < size; ++index) array[index] = readInt();
Arrays.sort(array);
int[] sortedArray = new int[size];
for (int index = 0; index < size; ++index) sortedArray[index] = array[index];
return sortedArray;
}
int minInt(int... values) {
int min = Integer.MAX_VALUE;
for (int value : values) min = Math.min(min, value);
return min;
}
int maxInt(int... values) {
int max = Integer.MIN_VALUE;
for (int value : values) max = Math.max(max, value);
return max;
}
long minLong(long... values) {
long min = Long.MAX_VALUE;
for (long value : values) min = Math.min(min, value);
return min;
}
long maxLong(long... values) {
long max = Long.MIN_VALUE;
for (long value : values) max = Math.max(max, value);
return max;
}
boolean checkIndex(int index, int size) {
return (0 <= index && index < size);
}
int abs(int a) {
if (a < 0) return -a;
return a;
}
} | Java | ["6\n3 5 4 7 10 12", "5\n-1 2 5 8 11"] | 4 seconds | ["3\n7 3 5", "1\n8"] | NoteIn the first example the answer is $$$[7, 3, 5]$$$. Note, that $$$|7-3|=4=2^2$$$, $$$|7-5|=2=2^1$$$ and $$$|3-5|=2=2^1$$$. You can't find a subset having more points satisfying the required property. | Java 8 | standard input | [
"brute force",
"math"
] | f413556df7dc980ca7e7bd1168d700d2 | The first line contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of points. The second line contains $$$n$$$ pairwise distinct integers $$$x_1, x_2, \dots, x_n$$$ ($$$-10^9 \le x_i \le 10^9$$$) — the coordinates of points. | 1,800 | In the first line print $$$m$$$ — the maximum possible number of points in a subset that satisfies the conditions described above. In the second line print $$$m$$$ integers — the coordinates of points in the subset you have chosen. If there are multiple answers, print any of them. | standard output | |
PASSED | 2de4a30c1a807d0a5f691dfb5c5b38a3 | train_004.jsonl | 1527863700 | There are $$$n$$$ distinct points on a coordinate line, the coordinate of $$$i$$$-th point equals to $$$x_i$$$. Choose a subset of the given set of points such that the distance between each pair of points in a subset is an integral power of two. It is necessary to consider each pair of points, not only adjacent. Note that any subset containing one element satisfies the condition above. Among all these subsets, choose a subset with maximum possible size.In other words, you have to choose the maximum possible number of points $$$x_{i_1}, x_{i_2}, \dots, x_{i_m}$$$ such that for each pair $$$x_{i_j}$$$, $$$x_{i_k}$$$ it is true that $$$|x_{i_j} - x_{i_k}| = 2^d$$$ where $$$d$$$ is some non-negative integer number (not necessarily the same for each pair of points). | 256 megabytes | /*
ЗАПУСКАЕМ ВЫСОКОГО
░ГУСЯ░▄▀▀▀▄░РАБОТЯГИ░░
▄███▀░◐░░░▌░░░░░░░
░░░░▌░░░░░▐░░░░░░░
░░░░▐░░░░░▐░░░░░░░
░░░░▌░░░░░▐▄▄░░░░
░░░░▌░░░░▄▀▒▒▀▀▀▀▄
░░░▐░░░░▐▒▒▒▒▒▒▒▒▀▀▄
░░░▐░░░░▐▄▒▒▒▒▒▒▒▒▒▒▀▄
░░░░▀▄░░░░▀▄▒▒▒▒▒▒▒▒▒▒▀▄
░░░░░░▀▄▄▄▄▄█▄▄▄▄▄▄▄▄▄▄▄▀▄
░░░░░░░░░░░▌▌░▌▌░░░░░
░░░░░░░░░░░▌▌░▌▌░░░░░
░░░░░░░░░▄▄▌▌▄▌▌░░░░░
*/
import java.io.*;
import java.util.*;
public class Main {
void solve() throws IOException {
int n = readInt();
long[] x = new long[n];
for (int i = 0; i < n; i++) x[i] = readInt();
HashSet<Long> set = new HashSet<>();
for (long a : x) set.add(a);
long[] pow2 = new long[31];
pow2[0] = 1;
for (int i = 1; i < 31; i++) pow2[i] = pow2[i - 1] << 1;
long[] ans = new long[3];
int answer = 0;
long[] preans = new long[3];
int cur;
boolean f1, f2;
for (long f : set) {
preans[0] = f;
preans[1] = -2147483647;
preans[2] = -2147483647;
cur = 1;
for (long d : pow2) {
int pre = 1;
f1 = false;
f2 = false;
if (set.contains(f - d)) {
pre++;
f1 = true;
}
if (set.contains(f + d)) {
pre++;
f2 = true;
}
if (pre > cur) {
cur = pre;
if (f1) preans[1] = f - d;
if (f2) preans[2] = f + d;
}
}
if (answer < cur) {
answer = cur;
ans = preans.clone();
}
}
out.println(answer);
for (int i = 0; i < 3; i++)
if (ans[i] != -2147483647)
out.print(ans[i] + " ");
}
public static void main(String[] args) throws IOException {
new Main().run();
}
BufferedReader in;
PrintWriter out;
StringTokenizer tok;
Main() throws FileNotFoundException {
try {
in = new BufferedReader(new FileReader("input.txt"));
out = new PrintWriter("output.txt");
} catch (Exception e) {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
}
tok = new StringTokenizer("");
}
void run() throws IOException {
solve();
out.close();
}
String delimiter = " ";
String readLine() throws IOException {
return in.readLine();
}
String readString() throws IOException {
while (!tok.hasMoreTokens()) {
String nextLine = readLine();
if (null == nextLine) return null;
tok = new StringTokenizer(nextLine);
}
return tok.nextToken(delimiter);
}
int readInt() throws IOException {
return Integer.parseInt(readString());
}
long readLong() throws IOException {
return Long.parseLong(readString());
}
double readDouble() throws IOException {
return Double.parseDouble(readString());
}
int[] readIntArray(int b) {
int a[] = new int[b];
for (int i = 0; i < b; i++)
try {
a[i] = readInt();
} catch (IOException e) {
e.printStackTrace();
}
return a;
}
int[] readSortedIntArray(int size) throws IOException {
Integer[] array = new Integer[size];
for (int index = 0; index < size; ++index) array[index] = readInt();
Arrays.sort(array);
int[] sortedArray = new int[size];
for (int index = 0; index < size; ++index) sortedArray[index] = array[index];
return sortedArray;
}
int[] sortedIntArray(int size, int[] array) throws IOException {
for (int index = 0; index < size; ++index) array[index] = readInt();
Arrays.sort(array);
int[] sortedArray = new int[size];
for (int index = 0; index < size; ++index) sortedArray[index] = array[index];
return sortedArray;
}
int minInt(int... values) {
int min = Integer.MAX_VALUE;
for (int value : values) min = Math.min(min, value);
return min;
}
int maxInt(int... values) {
int max = Integer.MIN_VALUE;
for (int value : values) max = Math.max(max, value);
return max;
}
long minLong(long... values) {
long min = Long.MAX_VALUE;
for (long value : values) min = Math.min(min, value);
return min;
}
long maxLong(long... values) {
long max = Long.MIN_VALUE;
for (long value : values) max = Math.max(max, value);
return max;
}
boolean checkIndex(int index, int size) {
return (0 <= index && index < size);
}
int abs(int a) {
if (a < 0) return -a;
return a;
}
} | Java | ["6\n3 5 4 7 10 12", "5\n-1 2 5 8 11"] | 4 seconds | ["3\n7 3 5", "1\n8"] | NoteIn the first example the answer is $$$[7, 3, 5]$$$. Note, that $$$|7-3|=4=2^2$$$, $$$|7-5|=2=2^1$$$ and $$$|3-5|=2=2^1$$$. You can't find a subset having more points satisfying the required property. | Java 8 | standard input | [
"brute force",
"math"
] | f413556df7dc980ca7e7bd1168d700d2 | The first line contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of points. The second line contains $$$n$$$ pairwise distinct integers $$$x_1, x_2, \dots, x_n$$$ ($$$-10^9 \le x_i \le 10^9$$$) — the coordinates of points. | 1,800 | In the first line print $$$m$$$ — the maximum possible number of points in a subset that satisfies the conditions described above. In the second line print $$$m$$$ integers — the coordinates of points in the subset you have chosen. If there are multiple answers, print any of them. | standard output | |
PASSED | 304bce752e8447905b475bb3803c18f4 | train_004.jsonl | 1527863700 | There are $$$n$$$ distinct points on a coordinate line, the coordinate of $$$i$$$-th point equals to $$$x_i$$$. Choose a subset of the given set of points such that the distance between each pair of points in a subset is an integral power of two. It is necessary to consider each pair of points, not only adjacent. Note that any subset containing one element satisfies the condition above. Among all these subsets, choose a subset with maximum possible size.In other words, you have to choose the maximum possible number of points $$$x_{i_1}, x_{i_2}, \dots, x_{i_m}$$$ such that for each pair $$$x_{i_j}$$$, $$$x_{i_k}$$$ it is true that $$$|x_{i_j} - x_{i_k}| = 2^d$$$ where $$$d$$$ is some non-negative integer number (not necessarily the same for each pair of points). | 256 megabytes | /*
ЗАПУСКАЕМ ВЫСОКОГО
░ГУСЯ░▄▀▀▀▄░РАБОТЯГИ░░
▄███▀░◐░░░▌░░░░░░░
░░░░▌░░░░░▐░░░░░░░
░░░░▐░░░░░▐░░░░░░░
░░░░▌░░░░░▐▄▄░░░░
░░░░▌░░░░▄▀▒▒▀▀▀▀▄
░░░▐░░░░▐▒▒▒▒▒▒▒▒▀▀▄
░░░▐░░░░▐▄▒▒▒▒▒▒▒▒▒▒▀▄
░░░░▀▄░░░░▀▄▒▒▒▒▒▒▒▒▒▒▀▄
░░░░░░▀▄▄▄▄▄█▄▄▄▄▄▄▄▄▄▄▄▀▄
░░░░░░░░░░░▌▌░▌▌░░░░░
░░░░░░░░░░░▌▌░▌▌░░░░░
░░░░░░░░░▄▄▌▌▄▌▌░░░░░
*/
import java.io.*;
import java.util.*;
public class Main {
void solve() throws IOException {
int n = readInt();
long[] x = new long[n];
for (int i = 0; i < n; i++) x[i] = readInt();
TreeSet<Long> set = new TreeSet<>();
for (long a : x) set.add(a);
long[] pow2 = new long[34];
pow2[0] = 1;
for (int i = 1; i < 34; i++) {
pow2[i] = pow2[i - 1] * 2;
}
long[] ans = new long[3];
int answer = 0;
for (long f : set) {
long[] preans = new long[3];
Arrays.fill(preans, -Integer.MAX_VALUE);
int cur = 1;
preans[0] = f;
boolean f1 = false, f2 = false;
for (long d : pow2) {
int pre = 1;
f1 = false;
f2 = false;
if (set.contains(f - d)) {
pre++;
f1 = true;
}
if (set.contains(f + d)) {
pre++;
f2 = true;
}
if (pre > cur) {
cur = pre;
if (f1) preans[1] = f - d;
if (f2) preans[2] = f + d;
}
}
Arrays.sort(preans);
if (answer < cur) {
answer = cur;
ans = preans;
}
}
out.println(answer);
for (int i = 2; i >= 3 - answer; i--) {
out.print(ans[i] + " ");
}
}
public static void main(String[] args) throws IOException {
new Main().run();
}
BufferedReader in;
PrintWriter out;
StringTokenizer tok;
Main() throws FileNotFoundException {
try {
in = new BufferedReader(new FileReader("input.txt"));
out = new PrintWriter("output.txt");
} catch (Exception e) {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
}
tok = new StringTokenizer("");
}
void run() throws IOException {
solve();
out.close();
}
String delimiter = " ";
String readLine() throws IOException {
return in.readLine();
}
String readString() throws IOException {
while (!tok.hasMoreTokens()) {
String nextLine = readLine();
if (null == nextLine) return null;
tok = new StringTokenizer(nextLine);
}
return tok.nextToken(delimiter);
}
int readInt() throws IOException {
return Integer.parseInt(readString());
}
long readLong() throws IOException {
return Long.parseLong(readString());
}
double readDouble() throws IOException {
return Double.parseDouble(readString());
}
int[] readIntArray(int b) {
int a[] = new int[b];
for (int i = 0; i < b; i++)
try {
a[i] = readInt();
} catch (IOException e) {
e.printStackTrace();
}
return a;
}
int[] readSortedIntArray(int size) throws IOException {
Integer[] array = new Integer[size];
for (int index = 0; index < size; ++index) array[index] = readInt();
Arrays.sort(array);
int[] sortedArray = new int[size];
for (int index = 0; index < size; ++index) sortedArray[index] = array[index];
return sortedArray;
}
int[] sortedIntArray(int size, int[] array) throws IOException {
for (int index = 0; index < size; ++index) array[index] = readInt();
Arrays.sort(array);
int[] sortedArray = new int[size];
for (int index = 0; index < size; ++index) sortedArray[index] = array[index];
return sortedArray;
}
int minInt(int... values) {
int min = Integer.MAX_VALUE;
for (int value : values) min = Math.min(min, value);
return min;
}
int maxInt(int... values) {
int max = Integer.MIN_VALUE;
for (int value : values) max = Math.max(max, value);
return max;
}
long minLong(long... values) {
long min = Long.MAX_VALUE;
for (long value : values) min = Math.min(min, value);
return min;
}
long maxLong(long... values) {
long max = Long.MIN_VALUE;
for (long value : values) max = Math.max(max, value);
return max;
}
boolean checkIndex(int index, int size) {
return (0 <= index && index < size);
}
int abs(int a) {
if (a < 0) return -a;
return a;
}
} | Java | ["6\n3 5 4 7 10 12", "5\n-1 2 5 8 11"] | 4 seconds | ["3\n7 3 5", "1\n8"] | NoteIn the first example the answer is $$$[7, 3, 5]$$$. Note, that $$$|7-3|=4=2^2$$$, $$$|7-5|=2=2^1$$$ and $$$|3-5|=2=2^1$$$. You can't find a subset having more points satisfying the required property. | Java 8 | standard input | [
"brute force",
"math"
] | f413556df7dc980ca7e7bd1168d700d2 | The first line contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of points. The second line contains $$$n$$$ pairwise distinct integers $$$x_1, x_2, \dots, x_n$$$ ($$$-10^9 \le x_i \le 10^9$$$) — the coordinates of points. | 1,800 | In the first line print $$$m$$$ — the maximum possible number of points in a subset that satisfies the conditions described above. In the second line print $$$m$$$ integers — the coordinates of points in the subset you have chosen. If there are multiple answers, print any of them. | standard output | |
PASSED | 190e457a3a08e9dc451eaf440c66d1d4 | train_004.jsonl | 1527863700 | There are $$$n$$$ distinct points on a coordinate line, the coordinate of $$$i$$$-th point equals to $$$x_i$$$. Choose a subset of the given set of points such that the distance between each pair of points in a subset is an integral power of two. It is necessary to consider each pair of points, not only adjacent. Note that any subset containing one element satisfies the condition above. Among all these subsets, choose a subset with maximum possible size.In other words, you have to choose the maximum possible number of points $$$x_{i_1}, x_{i_2}, \dots, x_{i_m}$$$ such that for each pair $$$x_{i_j}$$$, $$$x_{i_k}$$$ it is true that $$$|x_{i_j} - x_{i_k}| = 2^d$$$ where $$$d$$$ is some non-negative integer number (not necessarily the same for each pair of points). | 256 megabytes | /*
ЗАПУСКАЕМ ВЫСОКОГО
░ГУСЯ░▄▀▀▀▄░РАБОТЯГИ░░
▄███▀░◐░░░▌░░░░░░░
░░░░▌░░░░░▐░░░░░░░
░░░░▐░░░░░▐░░░░░░░
░░░░▌░░░░░▐▄▄░░░░
░░░░▌░░░░▄▀▒▒▀▀▀▀▄
░░░▐░░░░▐▒▒▒▒▒▒▒▒▀▀▄
░░░▐░░░░▐▄▒▒▒▒▒▒▒▒▒▒▀▄
░░░░▀▄░░░░▀▄▒▒▒▒▒▒▒▒▒▒▀▄
░░░░░░▀▄▄▄▄▄█▄▄▄▄▄▄▄▄▄▄▄▀▄
░░░░░░░░░░░▌▌░▌▌░░░░░
░░░░░░░░░░░▌▌░▌▌░░░░░
░░░░░░░░░▄▄▌▌▄▌▌░░░░░
*/
import java.io.*;
import java.util.*;
public class Main {
void solve() throws IOException {
int n = readInt();
long[] x = new long[n];
for (int i = 0; i < n; i++) x[i] = readInt();
HashSet<Long> set = new HashSet<>();
for (long a : x) set.add(a);
long[] pow2 = new long[31];
pow2[0] = 1;
for (int i = 1; i < 31; i++) pow2[i] = pow2[i - 1] << 1;
long[] ans = new long[3];
int answer = 0;
long[] preans = new long[3];
int cur;
boolean f1, f2;
for (long f : set) {
if (answer == 3) break;
preans[0] = f;
preans[1] = -2147483647;
preans[2] = -2147483647;
cur = 1;
for (long d : pow2) {
int pre = 1;
f1 = false;
f2 = false;
if (set.contains(f - d)) {
pre++;
f1 = true;
}
if (set.contains(f + d)) {
pre++;
f2 = true;
}
if (pre > cur) {
cur = pre;
if (f1) preans[1] = f - d;
if (f2) preans[2] = f + d;
}
}
if (answer < cur) {
answer = cur;
ans = preans.clone();
}
}
out.println(answer);
for (int i = 0; i < 3; i++)
if (ans[i] != -2147483647)
out.print(ans[i] + " ");
}
public static void main(String[] args) throws IOException {
new Main().run();
}
BufferedReader in;
PrintWriter out;
StringTokenizer tok;
Main() throws FileNotFoundException {
try {
in = new BufferedReader(new FileReader("input.txt"));
out = new PrintWriter("output.txt");
} catch (Exception e) {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
}
tok = new StringTokenizer("");
}
void run() throws IOException {
solve();
out.close();
}
String delimiter = " ";
String readLine() throws IOException {
return in.readLine();
}
String readString() throws IOException {
while (!tok.hasMoreTokens()) {
String nextLine = readLine();
if (null == nextLine) return null;
tok = new StringTokenizer(nextLine);
}
return tok.nextToken(delimiter);
}
int readInt() throws IOException {
return Integer.parseInt(readString());
}
long readLong() throws IOException {
return Long.parseLong(readString());
}
double readDouble() throws IOException {
return Double.parseDouble(readString());
}
int[] readIntArray(int b) {
int a[] = new int[b];
for (int i = 0; i < b; i++)
try {
a[i] = readInt();
} catch (IOException e) {
e.printStackTrace();
}
return a;
}
int[] readSortedIntArray(int size) throws IOException {
Integer[] array = new Integer[size];
for (int index = 0; index < size; ++index) array[index] = readInt();
Arrays.sort(array);
int[] sortedArray = new int[size];
for (int index = 0; index < size; ++index) sortedArray[index] = array[index];
return sortedArray;
}
int[] sortedIntArray(int size, int[] array) throws IOException {
for (int index = 0; index < size; ++index) array[index] = readInt();
Arrays.sort(array);
int[] sortedArray = new int[size];
for (int index = 0; index < size; ++index) sortedArray[index] = array[index];
return sortedArray;
}
int minInt(int... values) {
int min = Integer.MAX_VALUE;
for (int value : values) min = Math.min(min, value);
return min;
}
int maxInt(int... values) {
int max = Integer.MIN_VALUE;
for (int value : values) max = Math.max(max, value);
return max;
}
long minLong(long... values) {
long min = Long.MAX_VALUE;
for (long value : values) min = Math.min(min, value);
return min;
}
long maxLong(long... values) {
long max = Long.MIN_VALUE;
for (long value : values) max = Math.max(max, value);
return max;
}
boolean checkIndex(int index, int size) {
return (0 <= index && index < size);
}
int abs(int a) {
if (a < 0) return -a;
return a;
}
} | Java | ["6\n3 5 4 7 10 12", "5\n-1 2 5 8 11"] | 4 seconds | ["3\n7 3 5", "1\n8"] | NoteIn the first example the answer is $$$[7, 3, 5]$$$. Note, that $$$|7-3|=4=2^2$$$, $$$|7-5|=2=2^1$$$ and $$$|3-5|=2=2^1$$$. You can't find a subset having more points satisfying the required property. | Java 8 | standard input | [
"brute force",
"math"
] | f413556df7dc980ca7e7bd1168d700d2 | The first line contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of points. The second line contains $$$n$$$ pairwise distinct integers $$$x_1, x_2, \dots, x_n$$$ ($$$-10^9 \le x_i \le 10^9$$$) — the coordinates of points. | 1,800 | In the first line print $$$m$$$ — the maximum possible number of points in a subset that satisfies the conditions described above. In the second line print $$$m$$$ integers — the coordinates of points in the subset you have chosen. If there are multiple answers, print any of them. | standard output | |
PASSED | 33ea04368033feb142195dbf5f4e7de1 | train_004.jsonl | 1527863700 | There are $$$n$$$ distinct points on a coordinate line, the coordinate of $$$i$$$-th point equals to $$$x_i$$$. Choose a subset of the given set of points such that the distance between each pair of points in a subset is an integral power of two. It is necessary to consider each pair of points, not only adjacent. Note that any subset containing one element satisfies the condition above. Among all these subsets, choose a subset with maximum possible size.In other words, you have to choose the maximum possible number of points $$$x_{i_1}, x_{i_2}, \dots, x_{i_m}$$$ such that for each pair $$$x_{i_j}$$$, $$$x_{i_k}$$$ it is true that $$$|x_{i_j} - x_{i_k}| = 2^d$$$ where $$$d$$$ is some non-negative integer number (not necessarily the same for each pair of points). | 256 megabytes | /*
ЗАПУСКАЕМ ВЫСОКОГО
░ГУСЯ░▄▀▀▀▄░РАБОТЯГИ░░
▄███▀░◐░░░▌░░░░░░░
░░░░▌░░░░░▐░░░░░░░
░░░░▐░░░░░▐░░░░░░░
░░░░▌░░░░░▐▄▄░░░░
░░░░▌░░░░▄▀▒▒▀▀▀▀▄
░░░▐░░░░▐▒▒▒▒▒▒▒▒▀▀▄
░░░▐░░░░▐▄▒▒▒▒▒▒▒▒▒▒▀▄
░░░░▀▄░░░░▀▄▒▒▒▒▒▒▒▒▒▒▀▄
░░░░░░▀▄▄▄▄▄█▄▄▄▄▄▄▄▄▄▄▄▀▄
░░░░░░░░░░░▌▌░▌▌░░░░░
░░░░░░░░░░░▌▌░▌▌░░░░░
░░░░░░░░░▄▄▌▌▄▌▌░░░░░
*/
import java.io.*;
import java.util.*;
public class Main {
void solve() throws IOException {
int n = readInt();
long[] x = new long[n];
for (int i = 0; i < n; i++) x[i] = readInt();
HashSet<Long> set = new HashSet<>();
for (long a : x) set.add(a);
long[] pow2 = new long[34];
pow2[0] = 1;
for (int i = 1; i < 34; i++) {
pow2[i] = pow2[i - 1] * 2;
}
long[] ans = new long[3];
int answer = 0;
for (long f : set) {
long[] preans = new long[3];
Arrays.fill(preans, -Integer.MAX_VALUE);
int cur = 1;
preans[0] = f;
boolean f1 = false, f2 = false;
for (long d : pow2) {
int pre = 1;
f1 = false;
f2 = false;
if (set.contains(f - d)) {
pre++;
f1 = true;
}
if (set.contains(f + d)) {
pre++;
f2 = true;
}
if (pre > cur) {
cur = pre;
if (f1) preans[1] = f - d;
if (f2) preans[2] = f + d;
}
}
Arrays.sort(preans);
if (answer < cur) {
answer = cur;
ans = preans;
}
}
out.println(answer);
for (int i = 2; i >= 3 - answer; i--) {
out.print(ans[i] + " ");
}
}
public static void main(String[] args) throws IOException {
new Main().run();
}
BufferedReader in;
PrintWriter out;
StringTokenizer tok;
Main() throws FileNotFoundException {
try {
in = new BufferedReader(new FileReader("input.txt"));
out = new PrintWriter("output.txt");
} catch (Exception e) {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
}
tok = new StringTokenizer("");
}
void run() throws IOException {
solve();
out.close();
}
String delimiter = " ";
String readLine() throws IOException {
return in.readLine();
}
String readString() throws IOException {
while (!tok.hasMoreTokens()) {
String nextLine = readLine();
if (null == nextLine) return null;
tok = new StringTokenizer(nextLine);
}
return tok.nextToken(delimiter);
}
int readInt() throws IOException {
return Integer.parseInt(readString());
}
long readLong() throws IOException {
return Long.parseLong(readString());
}
double readDouble() throws IOException {
return Double.parseDouble(readString());
}
int[] readIntArray(int b) {
int a[] = new int[b];
for (int i = 0; i < b; i++)
try {
a[i] = readInt();
} catch (IOException e) {
e.printStackTrace();
}
return a;
}
int[] readSortedIntArray(int size) throws IOException {
Integer[] array = new Integer[size];
for (int index = 0; index < size; ++index) array[index] = readInt();
Arrays.sort(array);
int[] sortedArray = new int[size];
for (int index = 0; index < size; ++index) sortedArray[index] = array[index];
return sortedArray;
}
int[] sortedIntArray(int size, int[] array) throws IOException {
for (int index = 0; index < size; ++index) array[index] = readInt();
Arrays.sort(array);
int[] sortedArray = new int[size];
for (int index = 0; index < size; ++index) sortedArray[index] = array[index];
return sortedArray;
}
int minInt(int... values) {
int min = Integer.MAX_VALUE;
for (int value : values) min = Math.min(min, value);
return min;
}
int maxInt(int... values) {
int max = Integer.MIN_VALUE;
for (int value : values) max = Math.max(max, value);
return max;
}
long minLong(long... values) {
long min = Long.MAX_VALUE;
for (long value : values) min = Math.min(min, value);
return min;
}
long maxLong(long... values) {
long max = Long.MIN_VALUE;
for (long value : values) max = Math.max(max, value);
return max;
}
boolean checkIndex(int index, int size) {
return (0 <= index && index < size);
}
int abs(int a) {
if (a < 0) return -a;
return a;
}
} | Java | ["6\n3 5 4 7 10 12", "5\n-1 2 5 8 11"] | 4 seconds | ["3\n7 3 5", "1\n8"] | NoteIn the first example the answer is $$$[7, 3, 5]$$$. Note, that $$$|7-3|=4=2^2$$$, $$$|7-5|=2=2^1$$$ and $$$|3-5|=2=2^1$$$. You can't find a subset having more points satisfying the required property. | Java 8 | standard input | [
"brute force",
"math"
] | f413556df7dc980ca7e7bd1168d700d2 | The first line contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of points. The second line contains $$$n$$$ pairwise distinct integers $$$x_1, x_2, \dots, x_n$$$ ($$$-10^9 \le x_i \le 10^9$$$) — the coordinates of points. | 1,800 | In the first line print $$$m$$$ — the maximum possible number of points in a subset that satisfies the conditions described above. In the second line print $$$m$$$ integers — the coordinates of points in the subset you have chosen. If there are multiple answers, print any of them. | standard output | |
PASSED | b2c7b9c5405fd78f9960898d821c22a4 | train_004.jsonl | 1527863700 | There are $$$n$$$ distinct points on a coordinate line, the coordinate of $$$i$$$-th point equals to $$$x_i$$$. Choose a subset of the given set of points such that the distance between each pair of points in a subset is an integral power of two. It is necessary to consider each pair of points, not only adjacent. Note that any subset containing one element satisfies the condition above. Among all these subsets, choose a subset with maximum possible size.In other words, you have to choose the maximum possible number of points $$$x_{i_1}, x_{i_2}, \dots, x_{i_m}$$$ such that for each pair $$$x_{i_j}$$$, $$$x_{i_k}$$$ it is true that $$$|x_{i_j} - x_{i_k}| = 2^d$$$ where $$$d$$$ is some non-negative integer number (not necessarily the same for each pair of points). | 256 megabytes | /*
ЗАПУСКАЕМ ВЫСОКОГО
░ГУСЯ░▄▀▀▀▄░РАБОТЯГИ░░
▄███▀░◐░░░▌░░░░░░░
░░░░▌░░░░░▐░░░░░░░
░░░░▐░░░░░▐░░░░░░░
░░░░▌░░░░░▐▄▄░░░░
░░░░▌░░░░▄▀▒▒▀▀▀▀▄
░░░▐░░░░▐▒▒▒▒▒▒▒▒▀▀▄
░░░▐░░░░▐▄▒▒▒▒▒▒▒▒▒▒▀▄
░░░░▀▄░░░░▀▄▒▒▒▒▒▒▒▒▒▒▀▄
░░░░░░▀▄▄▄▄▄█▄▄▄▄▄▄▄▄▄▄▄▀▄
░░░░░░░░░░░▌▌░▌▌░░░░░
░░░░░░░░░░░▌▌░▌▌░░░░░
░░░░░░░░░▄▄▌▌▄▌▌░░░░░
*/
import java.io.*;
import java.util.*;
public class Main {
void solve() throws IOException {
int n = readInt();
long[] x = new long[n];
for (int i = 0; i < n; i++) x[i] = readInt();
HashSet<Long> set = new HashSet<>();
for (long a : x) set.add(a);
long[] pow2 = new long[31];
pow2[0] = 1;
for (int i = 1; i < 31; i++) pow2[i] = pow2[i - 1] << 1;
long[] ans = new long[3];
int answer = 0;
long[] preans = new long[3];
int cur;
boolean f1, f2;
for (long f : set) {
preans[0] = f;
preans[1] = -Integer.MAX_VALUE;
preans[2] = -Integer.MAX_VALUE;
cur = 1;
for (long d : pow2) {
int pre = 1;
f1 = false;
f2 = false;
if (set.contains(f - d)) {
pre++;
f1 = true;
}
if (set.contains(f + d)) {
pre++;
f2 = true;
}
if (pre > cur) {
cur = pre;
if (f1) preans[1] = f - d;
if (f2) preans[2] = f + d;
}
}
if (answer < cur) {
answer = cur;
ans = preans.clone();
}
}
out.println(answer);
for (int i = 0; i < 3; i++)
if (ans[i] != -Integer.MAX_VALUE)
out.print(ans[i] + " ");
}
public static void main(String[] args) throws IOException {
new Main().run();
}
BufferedReader in;
PrintWriter out;
StringTokenizer tok;
Main() throws FileNotFoundException {
try {
in = new BufferedReader(new FileReader("input.txt"));
out = new PrintWriter("output.txt");
} catch (Exception e) {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
}
tok = new StringTokenizer("");
}
void run() throws IOException {
solve();
out.close();
}
String delimiter = " ";
String readLine() throws IOException {
return in.readLine();
}
String readString() throws IOException {
while (!tok.hasMoreTokens()) {
String nextLine = readLine();
if (null == nextLine) return null;
tok = new StringTokenizer(nextLine);
}
return tok.nextToken(delimiter);
}
int readInt() throws IOException {
return Integer.parseInt(readString());
}
long readLong() throws IOException {
return Long.parseLong(readString());
}
double readDouble() throws IOException {
return Double.parseDouble(readString());
}
int[] readIntArray(int b) {
int a[] = new int[b];
for (int i = 0; i < b; i++)
try {
a[i] = readInt();
} catch (IOException e) {
e.printStackTrace();
}
return a;
}
int[] readSortedIntArray(int size) throws IOException {
Integer[] array = new Integer[size];
for (int index = 0; index < size; ++index) array[index] = readInt();
Arrays.sort(array);
int[] sortedArray = new int[size];
for (int index = 0; index < size; ++index) sortedArray[index] = array[index];
return sortedArray;
}
int[] sortedIntArray(int size, int[] array) throws IOException {
for (int index = 0; index < size; ++index) array[index] = readInt();
Arrays.sort(array);
int[] sortedArray = new int[size];
for (int index = 0; index < size; ++index) sortedArray[index] = array[index];
return sortedArray;
}
int minInt(int... values) {
int min = Integer.MAX_VALUE;
for (int value : values) min = Math.min(min, value);
return min;
}
int maxInt(int... values) {
int max = Integer.MIN_VALUE;
for (int value : values) max = Math.max(max, value);
return max;
}
long minLong(long... values) {
long min = Long.MAX_VALUE;
for (long value : values) min = Math.min(min, value);
return min;
}
long maxLong(long... values) {
long max = Long.MIN_VALUE;
for (long value : values) max = Math.max(max, value);
return max;
}
boolean checkIndex(int index, int size) {
return (0 <= index && index < size);
}
int abs(int a) {
if (a < 0) return -a;
return a;
}
} | Java | ["6\n3 5 4 7 10 12", "5\n-1 2 5 8 11"] | 4 seconds | ["3\n7 3 5", "1\n8"] | NoteIn the first example the answer is $$$[7, 3, 5]$$$. Note, that $$$|7-3|=4=2^2$$$, $$$|7-5|=2=2^1$$$ and $$$|3-5|=2=2^1$$$. You can't find a subset having more points satisfying the required property. | Java 8 | standard input | [
"brute force",
"math"
] | f413556df7dc980ca7e7bd1168d700d2 | The first line contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of points. The second line contains $$$n$$$ pairwise distinct integers $$$x_1, x_2, \dots, x_n$$$ ($$$-10^9 \le x_i \le 10^9$$$) — the coordinates of points. | 1,800 | In the first line print $$$m$$$ — the maximum possible number of points in a subset that satisfies the conditions described above. In the second line print $$$m$$$ integers — the coordinates of points in the subset you have chosen. If there are multiple answers, print any of them. | standard output | |
PASSED | a7c07fb23f34a92eb12b1683a3dc20c5 | train_004.jsonl | 1527863700 | There are $$$n$$$ distinct points on a coordinate line, the coordinate of $$$i$$$-th point equals to $$$x_i$$$. Choose a subset of the given set of points such that the distance between each pair of points in a subset is an integral power of two. It is necessary to consider each pair of points, not only adjacent. Note that any subset containing one element satisfies the condition above. Among all these subsets, choose a subset with maximum possible size.In other words, you have to choose the maximum possible number of points $$$x_{i_1}, x_{i_2}, \dots, x_{i_m}$$$ such that for each pair $$$x_{i_j}$$$, $$$x_{i_k}$$$ it is true that $$$|x_{i_j} - x_{i_k}| = 2^d$$$ where $$$d$$$ is some non-negative integer number (not necessarily the same for each pair of points). | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashSet;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author prakhar897
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
static class TaskA {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.nextInt();
HashSet<Integer> m = new HashSet<Integer>();
int arr[] = new int[31];
int i, j, a;
int ans = 1;
int val = 0, diff = 0;
int ay[] = new int[n];
for (i = 0; i < n; i++) {
ay[i] = in.nextInt();
m.add(ay[i]);
}
arr[0] = 1;
for (i = 1; i < 31; i++) {
arr[i] = 2 * arr[i - 1];
}
for (i = 0; i < n; i++) {
a = ay[i];
for (j = 0; j < 31; j++) {
if ((m.contains(a - arr[j])) && (m.contains(a - (2 * arr[j])))) {
out.println(3);
out.println(a + " " + (a - arr[j]) + " " + (a - (2 * arr[j])));
return;
}
}
}
for (i = 0; i < n; i++) {
a = ay[i];
for (j = 0; j < 31; j++) {
if (m.contains(a - arr[j])) {
out.println(2);
out.println(a + " " + (a - arr[j]));
return;
}
}
}
out.println(1);
out.println(ay[0]);
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void println(Object... objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
public void println(int i) {
writer.println(i);
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
| Java | ["6\n3 5 4 7 10 12", "5\n-1 2 5 8 11"] | 4 seconds | ["3\n7 3 5", "1\n8"] | NoteIn the first example the answer is $$$[7, 3, 5]$$$. Note, that $$$|7-3|=4=2^2$$$, $$$|7-5|=2=2^1$$$ and $$$|3-5|=2=2^1$$$. You can't find a subset having more points satisfying the required property. | Java 8 | standard input | [
"brute force",
"math"
] | f413556df7dc980ca7e7bd1168d700d2 | The first line contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of points. The second line contains $$$n$$$ pairwise distinct integers $$$x_1, x_2, \dots, x_n$$$ ($$$-10^9 \le x_i \le 10^9$$$) — the coordinates of points. | 1,800 | In the first line print $$$m$$$ — the maximum possible number of points in a subset that satisfies the conditions described above. In the second line print $$$m$$$ integers — the coordinates of points in the subset you have chosen. If there are multiple answers, print any of them. | standard output | |
PASSED | 2ae24362beeb88d418c4da967d0d6f0d | train_004.jsonl | 1527863700 | There are $$$n$$$ distinct points on a coordinate line, the coordinate of $$$i$$$-th point equals to $$$x_i$$$. Choose a subset of the given set of points such that the distance between each pair of points in a subset is an integral power of two. It is necessary to consider each pair of points, not only adjacent. Note that any subset containing one element satisfies the condition above. Among all these subsets, choose a subset with maximum possible size.In other words, you have to choose the maximum possible number of points $$$x_{i_1}, x_{i_2}, \dots, x_{i_m}$$$ such that for each pair $$$x_{i_j}$$$, $$$x_{i_k}$$$ it is true that $$$|x_{i_j} - x_{i_k}| = 2^d$$$ where $$$d$$$ is some non-negative integer number (not necessarily the same for each pair of points). | 256 megabytes |
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Scanner;
import java.util.Set;
public class CF {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int max = 0;
List<Integer> ans = new ArrayList<>();
Set<Integer> set = new HashSet<>();
for (int i = 0; i < n; i++) {
int num = in.nextInt();
set.add(num);
}
for (int num : set) {
for (int k = 0; k <= 30; k++) {
int p = 1 << k;
if (max == 0) {
ans = new ArrayList<>();
ans.add(num);
max = 1;
}
int n1 = num - p;
int n2 = num + p;
if (set.contains(n1) && max < 2) {
ans = new ArrayList<>();
ans.add(n1);
ans.add(num);
max = 2;
}
if (set.contains(n2) && max < 2) {
ans = new ArrayList<>();
ans.add(n2);
ans.add(num);
max = 2;
}
if (set.contains(n1) && set.contains(n2)) {
max = 3;
ans = new ArrayList<>();
ans.add(n1);
ans.add(n2);
ans.add(num);
}
}
}
System.out.println(max);
for (int i : ans) {
System.out.print(i + " ");
}
}
}
| Java | ["6\n3 5 4 7 10 12", "5\n-1 2 5 8 11"] | 4 seconds | ["3\n7 3 5", "1\n8"] | NoteIn the first example the answer is $$$[7, 3, 5]$$$. Note, that $$$|7-3|=4=2^2$$$, $$$|7-5|=2=2^1$$$ and $$$|3-5|=2=2^1$$$. You can't find a subset having more points satisfying the required property. | Java 8 | standard input | [
"brute force",
"math"
] | f413556df7dc980ca7e7bd1168d700d2 | The first line contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of points. The second line contains $$$n$$$ pairwise distinct integers $$$x_1, x_2, \dots, x_n$$$ ($$$-10^9 \le x_i \le 10^9$$$) — the coordinates of points. | 1,800 | In the first line print $$$m$$$ — the maximum possible number of points in a subset that satisfies the conditions described above. In the second line print $$$m$$$ integers — the coordinates of points in the subset you have chosen. If there are multiple answers, print any of them. | standard output | |
PASSED | f581069ea633b77966fa8e1c389a17e5 | train_004.jsonl | 1527863700 | There are $$$n$$$ distinct points on a coordinate line, the coordinate of $$$i$$$-th point equals to $$$x_i$$$. Choose a subset of the given set of points such that the distance between each pair of points in a subset is an integral power of two. It is necessary to consider each pair of points, not only adjacent. Note that any subset containing one element satisfies the condition above. Among all these subsets, choose a subset with maximum possible size.In other words, you have to choose the maximum possible number of points $$$x_{i_1}, x_{i_2}, \dots, x_{i_m}$$$ such that for each pair $$$x_{i_j}$$$, $$$x_{i_k}$$$ it is true that $$$|x_{i_j} - x_{i_k}| = 2^d$$$ where $$$d$$$ is some non-negative integer number (not necessarily the same for each pair of points). | 256 megabytes | import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.StringTokenizer;
public class E486 {
static ArrayList<Long>[] amp;
ArrayList<Pair>[][] pmp;
public static void main(String args[]) throws FileNotFoundException {
InputReader in = new InputReader(System.in);
OutputStream outputStream = System.out;
PrintWriter out = new PrintWriter(outputStream);
StringBuilder sb = new StringBuilder();
// ----------My Code----------
int n = in.nextInt();
long arr[] = new long[n];
long min = Integer.MAX_VALUE;
HashSet<Long> hs = new HashSet<>();
amp = (ArrayList<Long>[]) new ArrayList[n];
for (int i = 0; i < n; i++) {
arr[i] = in.nextInt();
hs.add(arr[i]);
amp[i] = new ArrayList<>();
}
int pow[] = new int[32];
pow[0] = 1;
for (int i = 1; i < 32; i++)
pow[i] = pow[i - 1] * 2;
for (int i = n - 1; i >= 0; i--) {
long val = arr[i];
amp[i].add(arr[i]);
int max = 0, temp = -1;
for (int j = 1; j < 32; j++) {
int val1 = 0;
if (hs.contains(val - pow[j]))
val1++;
if (hs.contains(val - pow[j - 1]))
val1++;
if (val1 >= max) {
max = val1;
temp = j;
}
}
if (hs.contains(arr[i] - pow[temp - 1]))
amp[i].add(arr[i] - pow[temp - 1]);
if (hs.contains(arr[i] - pow[temp]))
amp[i].add(arr[i] - pow[temp]);
}
int size = 0, ans = -1;
for (int i = 0; i < n; i++) {
if (amp[i].size() > size) {
size = amp[i].size();
ans = i;
}
}
System.out.println(size);
for (long i : amp[ans])
System.out.print(i + " ");
// ---------------The End------------------
out.close();
}
static boolean isPossible(int x, int y) {
if (x >= 0 && y >= 0 && x < 4 && y < 4)
return true;
return false;
}
// ---------------Extra Methods------------------
public static long pow(long x, long n, long mod) {
long res = 1;
x %= mod;
while (n > 0) {
if (n % 2 == 1) {
res = (res * x) % mod;
}
x = (x * x) % mod;
n /= 2;
}
return res;
}
public static boolean isPal(String s) {
for (int i = 0, j = s.length() - 1; i <= j; i++, j--) {
if (s.charAt(i) != s.charAt(j))
return false;
}
return true;
}
public static String rev(String s) {
StringBuilder sb = new StringBuilder(s);
sb.reverse();
return sb.toString();
}
public static long gcd(long x, long y) {
if (x % y == 0)
return y;
else
return gcd(y, x % y);
}
public static int gcd(int x, int y) {
if (x % y == 0)
return y;
else
return gcd(y, x % y);
}
public static long gcdExtended(long a, long b, long[] x) {
if (a == 0) {
x[0] = 0;
x[1] = 1;
return b;
}
long[] y = new long[2];
long gcd = gcdExtended(b % a, a, y);
x[0] = y[1] - (b / a) * y[0];
x[1] = y[0];
return gcd;
}
public static int abs(int a, int b) {
return (int) Math.abs(a - b);
}
public static long abs(long a, long b) {
return (long) Math.abs(a - b);
}
public static int max(int a, int b) {
if (a > b)
return a;
else
return b;
}
public static int min(int a, int b) {
if (a > b)
return b;
else
return a;
}
public static long max(long a, long b) {
if (a > b)
return a;
else
return b;
}
public static long min(long a, long b) {
if (a > b)
return b;
else
return a;
}
// ---------------Extra Methods------------------
public static void debug(Object... o) {
System.out.println(Arrays.deepToString(o));
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream inputstream) {
reader = new BufferedReader(new InputStreamReader(inputstream));
tokenizer = null;
}
public String nextLine() {
String fullLine = null;
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
fullLine = reader.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
return fullLine;
}
return fullLine;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public char nextChar() {
return next().charAt(0);
}
public long nextLong() {
return Long.parseLong(next());
}
public int nextInt() {
return Integer.parseInt(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public int[] nextIntArray(int n, int f) {
if (f == 0) {
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = nextInt();
}
return arr;
} else {
int[] arr = new int[n + 1];
for (int i = 1; i < n + 1; i++) {
arr[i] = nextInt();
}
return arr;
}
}
public long[] nextLongArray(int n, int f) {
if (f == 0) {
long[] arr = new long[n];
for (int i = 0; i < n; i++) {
arr[i] = nextLong();
}
return arr;
} else {
long[] arr = new long[n + 1];
for (int i = 1; i < n + 1; i++) {
arr[i] = nextLong();
}
return arr;
}
}
public double[] nextDoubleArray(int n, int f) {
if (f == 0) {
double[] arr = new double[n];
for (int i = 0; i < n; i++) {
arr[i] = nextDouble();
}
return arr;
} else {
double[] arr = new double[n + 1];
for (int i = 1; i < n + 1; i++) {
arr[i] = nextDouble();
}
return arr;
}
}
}
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);
}
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();
}
}
} | Java | ["6\n3 5 4 7 10 12", "5\n-1 2 5 8 11"] | 4 seconds | ["3\n7 3 5", "1\n8"] | NoteIn the first example the answer is $$$[7, 3, 5]$$$. Note, that $$$|7-3|=4=2^2$$$, $$$|7-5|=2=2^1$$$ and $$$|3-5|=2=2^1$$$. You can't find a subset having more points satisfying the required property. | Java 8 | standard input | [
"brute force",
"math"
] | f413556df7dc980ca7e7bd1168d700d2 | The first line contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of points. The second line contains $$$n$$$ pairwise distinct integers $$$x_1, x_2, \dots, x_n$$$ ($$$-10^9 \le x_i \le 10^9$$$) — the coordinates of points. | 1,800 | In the first line print $$$m$$$ — the maximum possible number of points in a subset that satisfies the conditions described above. In the second line print $$$m$$$ integers — the coordinates of points in the subset you have chosen. If there are multiple answers, print any of them. | standard output | |
PASSED | 944ca62636d379d731dc930def8bdc8d | train_004.jsonl | 1527863700 | There are $$$n$$$ distinct points on a coordinate line, the coordinate of $$$i$$$-th point equals to $$$x_i$$$. Choose a subset of the given set of points such that the distance between each pair of points in a subset is an integral power of two. It is necessary to consider each pair of points, not only adjacent. Note that any subset containing one element satisfies the condition above. Among all these subsets, choose a subset with maximum possible size.In other words, you have to choose the maximum possible number of points $$$x_{i_1}, x_{i_2}, \dots, x_{i_m}$$$ such that for each pair $$$x_{i_j}$$$, $$$x_{i_k}$$$ it is true that $$$|x_{i_j} - x_{i_k}| = 2^d$$$ where $$$d$$$ is some non-negative integer number (not necessarily the same for each pair of points). | 256 megabytes | /*
If you want to aim high, aim high
Don't let that studying and grades consume you
Just live life young
******************************
What do you think? What do you think?
1st on Billboard, what do you think of it
Next is a Grammy, what do you think of it
However you think, I’m sorry, but shit, I have no fcking interest
*******************************
I'm standing on top of my Monopoly board
That means I'm on top of my game and it don't stop
til my hip don't hop anymore
https://www.a2oj.com/Ladder16.html
*******************************
300iq as writer = Sad!
*/
import java.util.*;
import java.io.*;
import java.math.*;
public class D2
{
public static void main(String hi[]) throws Exception
{
BufferedReader infile = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(infile.readLine());
int N = Integer.parseInt(st.nextToken());
long[] arr = new long[N];
st = new StringTokenizer(infile.readLine());
HashSet<Long> set = new HashSet<Long>();
for(int i=0; i < N; i++)
{
arr[i] = Long.parseLong(st.nextToken());
set.add(arr[i]);
}
ArrayList<Long> res = new ArrayList<Long>();
outer:for(int i=0; i < N; i++)
if(i == 0 || arr[i] != arr[i-1])
for(int b=0; b <= 31; b++)
{
long diff = 1L<<b;
if(set.contains(arr[i]-diff))
break;
ArrayList<Long> temp = new ArrayList<Long>();
temp.add(arr[i]);
long curr = arr[i]+diff;
while(set.contains(curr))
{
temp.add(curr);
curr += diff;
if(temp.size() == 3)
break;
}
if(temp.size() > res.size())
{
res = temp;
if(res.size() == 3)
break outer;
}
}
System.out.println(res.size());
StringBuilder sb = new StringBuilder();
for(long x: res)
sb.append(x+" ");
System.out.println(sb);
}
} | Java | ["6\n3 5 4 7 10 12", "5\n-1 2 5 8 11"] | 4 seconds | ["3\n7 3 5", "1\n8"] | NoteIn the first example the answer is $$$[7, 3, 5]$$$. Note, that $$$|7-3|=4=2^2$$$, $$$|7-5|=2=2^1$$$ and $$$|3-5|=2=2^1$$$. You can't find a subset having more points satisfying the required property. | Java 8 | standard input | [
"brute force",
"math"
] | f413556df7dc980ca7e7bd1168d700d2 | The first line contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of points. The second line contains $$$n$$$ pairwise distinct integers $$$x_1, x_2, \dots, x_n$$$ ($$$-10^9 \le x_i \le 10^9$$$) — the coordinates of points. | 1,800 | In the first line print $$$m$$$ — the maximum possible number of points in a subset that satisfies the conditions described above. In the second line print $$$m$$$ integers — the coordinates of points in the subset you have chosen. If there are multiple answers, print any of them. | standard output | |
PASSED | 6d088c9fdbf0ab6d8c1df63cfe3a992d | train_004.jsonl | 1527863700 | There are $$$n$$$ distinct points on a coordinate line, the coordinate of $$$i$$$-th point equals to $$$x_i$$$. Choose a subset of the given set of points such that the distance between each pair of points in a subset is an integral power of two. It is necessary to consider each pair of points, not only adjacent. Note that any subset containing one element satisfies the condition above. Among all these subsets, choose a subset with maximum possible size.In other words, you have to choose the maximum possible number of points $$$x_{i_1}, x_{i_2}, \dots, x_{i_m}$$$ such that for each pair $$$x_{i_j}$$$, $$$x_{i_k}$$$ it is true that $$$|x_{i_j} - x_{i_k}| = 2^d$$$ where $$$d$$$ is some non-negative integer number (not necessarily the same for each pair of points). | 256 megabytes | import java.io.*;
import java.lang.reflect.Array;
import java.util.*;
public class Main {
static class Edge {
int a;
int b;
Edge(int a, int b) {
this.a = a;
this.b = b;
}
}
static boolean d2(long k){
long ans = 1;
while (ans < k){
ans *= 2;
}
if(ans == k) return true;
else return false;
}
public static void main(String[] args) throws IOException {
FastScanner in = new FastScanner(System.in);
FastPrinter out = new FastPrinter(System.out);
//FastScanner in = new FastScanner(new InputStreamReader(new FileInputStream(new File("mars.in"))));
//FastPrinter out = new FastPrinter(new OutputStreamWriter(new FileOutputStream(new File("mars.out"))));
int n = in.nextInt();
long[] mas = new long[n];
HashMap<Long, Integer> map = new HashMap<>();
for(int i = 0; i < n; i++){
mas[i] = in.nextLong();
map.put(mas[i], 1);
}
int k = 1;
long ans1 = 0;
long ans2 = 0;
long ans3 = 0;
long o = 1;
o <<= 35;
for(int i = 0; i < n; i++) {
if(ans3 != 0) break;
for (long j = 1; j < o; j <<= 1) {
if (map.get(mas[i] + j) != null) {
ans1 = mas[i];
ans2 = mas[i] + j;
k = 2;
if (map.get(mas[i] + 2 * j) != null) {
k = 3;
ans3 = mas[i] + j * 2;
break;
}
}
}
}
System.out.println(k);
if(k == 3){
System.out.println(ans1 + " " + ans2 + " " + ans3);
}
else if (k == 2){
System.out.println(ans1 + " " + ans2);
}
else System.out.println(mas[0]);
System.out.close();
}
}
class FastPrinter {
private final PrintWriter writer;
public FastPrinter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public FastPrinter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void close() {
writer.close();
}
public void println(long i) {
writer.println(i);
}
public void println(double d) {
writer.println(d);
}
public void println(String s) {
writer.println(s);
}
public void println(String format, Object... args) {
println(String.format(format, args));
}
public void println() {
writer.println();
}
public void print(long i) {
writer.print(i);
}
public void print(char c) {
writer.print(c);
}
public void print(double d) {
writer.print(d);
}
public void print(String s) {
writer.print(s);
}
public void print(String format, Object... args) {
print(String.format(format, args));
}
public void flush() {
writer.flush();
}
}
class FastScanner {
private BufferedReader reader;
private StringTokenizer st;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public FastScanner(InputStream stream) {
this.reader = new BufferedReader(new InputStreamReader(stream));
this.st = new StringTokenizer("");
}
public FastScanner(InputStreamReader stream) {
this.reader = new BufferedReader(stream);
this.st = new StringTokenizer("");
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public String next() {
while (!st.hasMoreTokens()) {
st = new StringTokenizer(readLine());
}
return st.nextToken();
}
public String nextLine() {
st = new StringTokenizer("");
return readLine();
}
public String tryNextLine() {
st = new StringTokenizer("");
return tryReadLine();
}
private String readLine() {
String line = tryReadLine();
if (line == null) throw new InputMismatchException();
return line;
}
private String tryReadLine() {
try {
return reader.readLine();
} catch (IOException e) {
throw new InputMismatchException();
}
}
public int[] nextIntArray(int size) {
int[] array = new int[size];
for (int i = 0; i < size; i++)
array[i] = nextInt();
return array;
}
public int[][] nextIntTable(int rowCount, int columnCount) {
int[][] table = new int[rowCount][];
for (int i = 0; i < rowCount; i++)
table[i] = nextIntArray(columnCount);
return table;
}
public long[] nextLongArray(int size) {
long[] array = new long[size];
for (int i = 0; i < size; i++)
array[i] = nextLong();
return array;
}
public long[][] nextLongTable(int rowCount, int columnCount) {
long[][] table = new long[rowCount][];
for (int i = 0; i < rowCount; i++)
table[i] = nextLongArray(columnCount);
return table;
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\t' || isEOL(c);
}
public static boolean isEOL(int c) {
return c == '\n' || c == '\r' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
} | Java | ["6\n3 5 4 7 10 12", "5\n-1 2 5 8 11"] | 4 seconds | ["3\n7 3 5", "1\n8"] | NoteIn the first example the answer is $$$[7, 3, 5]$$$. Note, that $$$|7-3|=4=2^2$$$, $$$|7-5|=2=2^1$$$ and $$$|3-5|=2=2^1$$$. You can't find a subset having more points satisfying the required property. | Java 8 | standard input | [
"brute force",
"math"
] | f413556df7dc980ca7e7bd1168d700d2 | The first line contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of points. The second line contains $$$n$$$ pairwise distinct integers $$$x_1, x_2, \dots, x_n$$$ ($$$-10^9 \le x_i \le 10^9$$$) — the coordinates of points. | 1,800 | In the first line print $$$m$$$ — the maximum possible number of points in a subset that satisfies the conditions described above. In the second line print $$$m$$$ integers — the coordinates of points in the subset you have chosen. If there are multiple answers, print any of them. | standard output | |
PASSED | 39e59d3a4fcdb86c97032bdaf86d2c10 | train_004.jsonl | 1596638100 | You are given a binary string $$$s$$$ consisting of $$$n$$$ zeros and ones.Your task is to divide the given string into the minimum number of subsequences in such a way that each character of the string belongs to exactly one subsequence and each subsequence looks like "010101 ..." or "101010 ..." (i.e. the subsequence should not contain two adjacent zeros or ones).Recall that a subsequence is a sequence that can be derived from the given sequence by deleting zero or more elements without changing the order of the remaining elements. For example, subsequences of "1011101" are "0", "1", "11111", "0111", "101", "1001", but not "000", "101010" and "11100".You have to answer $$$t$$$ independent test cases. | 256 megabytes | //package compete;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.lang.reflect.Array;
import java.security.acl.LastOwnerException;
import java.util.*;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Deque;
import java.util.HashMap;
import java.util.PriorityQueue;
import java.util.StringTokenizer;
public class Main {
public static PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
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[] nextSArray() {
String sr[] = null;
try {
sr = br.readLine().trim().split(" ");
} catch (IOException e) {
e.printStackTrace();
}
return sr;
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
//static ArrayList<Integer>al=new ArrayList<>()
//
static class Pair{
char ch;
int count;
Pair(char ch,int count){
this.ch=ch;
this.count=count;
}
Pair(){}
}
static int MAX=Integer.MAX_VALUE,MIN=Integer.MIN_VALUE;
public static void main(String[] args) throws Exception{
FastReader sc=new FastReader();
int t=sc.nextInt();
while (t-->0){
int n=sc.nextInt();
String s=sc.nextLine();
int count=1,x=0;
Deque<Integer> zero=new ArrayDeque<>(),one=new ArrayDeque<>();
StringBuilder sb=new StringBuilder();
for(int i=0;i<s.length();i++){
char ch=s.charAt(i);
int p=0;
if(ch=='0'){
if(one.isEmpty()){
p=count;
zero.push(count++);
}else{
int temp=one.pop();
p=temp;
zero.push(temp);
}
}else{
if(zero.isEmpty()){
p=count;
one.push(count++);
}else{
int temp=zero.pop();
p=temp;
one.push(temp);
}
}
sb.append(p+" ");
}
out.println(count-1);
out.println(sb);
}
out.close();
}
} | Java | ["4\n4\n0011\n6\n111111\n5\n10101\n8\n01010000"] | 2 seconds | ["2\n1 2 2 1 \n6\n1 2 3 4 5 6 \n1\n1 1 1 1 1 \n4\n1 1 1 1 1 2 3 4"] | null | Java 8 | standard input | [
"data structures",
"constructive algorithms",
"implementation",
"greedy"
] | de57b6b1aa2b6ec4686d1348988c0c63 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of $$$s$$$. The second line of the test case contains $$$n$$$ characters '0' and '1' — the string $$$s$$$. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$). | 1,500 | For each test case, print the answer: in the first line print one integer $$$k$$$ ($$$1 \le k \le n$$$) — the minimum number of subsequences you can divide the string $$$s$$$ to. In the second line print $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le k$$$), where $$$a_i$$$ is the number of subsequence the $$$i$$$-th character of $$$s$$$ belongs to. If there are several answers, you can print any. | standard output | |
PASSED | 367978025571d938777fe2fb3a66ae8f | train_004.jsonl | 1596638100 | You are given a binary string $$$s$$$ consisting of $$$n$$$ zeros and ones.Your task is to divide the given string into the minimum number of subsequences in such a way that each character of the string belongs to exactly one subsequence and each subsequence looks like "010101 ..." or "101010 ..." (i.e. the subsequence should not contain two adjacent zeros or ones).Recall that a subsequence is a sequence that can be derived from the given sequence by deleting zero or more elements without changing the order of the remaining elements. For example, subsequences of "1011101" are "0", "1", "11111", "0111", "101", "1001", but not "000", "101010" and "11100".You have to answer $$$t$$$ independent test cases. | 256 megabytes |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Stack;
public class BinaryStringToSubsequences {
static void findLargestSubstring(String str){
int[] mark = new int[str.length()];
int i = 0, j = 0, count = 0, numberOfSubstring = 0;
Stack<Integer> so = new Stack<>();
Stack<Integer> sz = new Stack<>();
while(i < str.length()){
char temp = str.charAt(i);
if (temp == '0'){
if(so.empty()){
sz.push(++count);
mark[i] = count;
}else{
mark[i] = so.pop();
sz.push(mark[i]);
}
}
if (temp == '1'){
if(sz.empty()){
so.push(++count);
mark[i] = count;
}else{
mark[i] = sz.pop();
so.push(mark[i]);
}
}
i++;
}
System.out.println(count);
for (int k : mark) {
System.out.print(k + " ");
}
}
public static void main(String[] args) throws IOException{
BufferedReader reader =new BufferedReader(new InputStreamReader(System.in));
int testCases = Integer.parseInt(reader.readLine());
String[] arr = new String[testCases];
for(int i=0; i< testCases; i++){
long length = Integer.parseInt(reader.readLine());
arr[i] = reader.readLine();
}
for(int i=0; i< testCases; i++){
findLargestSubstring(arr[i]);
System.out.println("");
}
}
} | Java | ["4\n4\n0011\n6\n111111\n5\n10101\n8\n01010000"] | 2 seconds | ["2\n1 2 2 1 \n6\n1 2 3 4 5 6 \n1\n1 1 1 1 1 \n4\n1 1 1 1 1 2 3 4"] | null | Java 8 | standard input | [
"data structures",
"constructive algorithms",
"implementation",
"greedy"
] | de57b6b1aa2b6ec4686d1348988c0c63 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of $$$s$$$. The second line of the test case contains $$$n$$$ characters '0' and '1' — the string $$$s$$$. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$). | 1,500 | For each test case, print the answer: in the first line print one integer $$$k$$$ ($$$1 \le k \le n$$$) — the minimum number of subsequences you can divide the string $$$s$$$ to. In the second line print $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le k$$$), where $$$a_i$$$ is the number of subsequence the $$$i$$$-th character of $$$s$$$ belongs to. If there are several answers, you can print any. | standard output | |
PASSED | 6b10a5ba3e319d1aadf079190d77a6ad | train_004.jsonl | 1596638100 | You are given a binary string $$$s$$$ consisting of $$$n$$$ zeros and ones.Your task is to divide the given string into the minimum number of subsequences in such a way that each character of the string belongs to exactly one subsequence and each subsequence looks like "010101 ..." or "101010 ..." (i.e. the subsequence should not contain two adjacent zeros or ones).Recall that a subsequence is a sequence that can be derived from the given sequence by deleting zero or more elements without changing the order of the remaining elements. For example, subsequences of "1011101" are "0", "1", "11111", "0111", "101", "1001", but not "000", "101010" and "11100".You have to answer $$$t$$$ independent test cases. | 256 megabytes | import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
/**
* @author Crazy
* @since August 30, 2020 8:23 AM
*/
public class Problem {
private static final Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
new Problem().solve();
}
private void solve() {
int cycle = scanner.nextInt();
for (int loop = 0; loop < cycle; loop ++) {
int n = scanner.nextInt();
String bin = scanner.next();
int temp = 0;
int subsequences = 0;
int[] list = new int[n];
List<Integer> zero = new ArrayList<>();
List<Integer> one = new ArrayList<>();
for (int i = 0; i < n; i ++) {
if (bin.charAt(i) == '0') {
if (one.size() > 0) {
temp = one.get(0);
one.remove(0);
} else {
temp = ++subsequences;
}
zero.add(temp);
} else {
if (zero.size() > 0) {
temp = zero.get(0);
zero.remove(0);
} else {
temp = ++subsequences;
}
one.add(temp);
}
list[i] = temp;
}
System.out.println(subsequences);
for (int elem : list) System.out.print(elem + " ");
System.out.println();
}
}
}
| Java | ["4\n4\n0011\n6\n111111\n5\n10101\n8\n01010000"] | 2 seconds | ["2\n1 2 2 1 \n6\n1 2 3 4 5 6 \n1\n1 1 1 1 1 \n4\n1 1 1 1 1 2 3 4"] | null | Java 8 | standard input | [
"data structures",
"constructive algorithms",
"implementation",
"greedy"
] | de57b6b1aa2b6ec4686d1348988c0c63 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of $$$s$$$. The second line of the test case contains $$$n$$$ characters '0' and '1' — the string $$$s$$$. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$). | 1,500 | For each test case, print the answer: in the first line print one integer $$$k$$$ ($$$1 \le k \le n$$$) — the minimum number of subsequences you can divide the string $$$s$$$ to. In the second line print $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le k$$$), where $$$a_i$$$ is the number of subsequence the $$$i$$$-th character of $$$s$$$ belongs to. If there are several answers, you can print any. | standard output | |
PASSED | d9bdad4b03f39bdc762054fc046761fa | train_004.jsonl | 1596638100 | You are given a binary string $$$s$$$ consisting of $$$n$$$ zeros and ones.Your task is to divide the given string into the minimum number of subsequences in such a way that each character of the string belongs to exactly one subsequence and each subsequence looks like "010101 ..." or "101010 ..." (i.e. the subsequence should not contain two adjacent zeros or ones).Recall that a subsequence is a sequence that can be derived from the given sequence by deleting zero or more elements without changing the order of the remaining elements. For example, subsequences of "1011101" are "0", "1", "11111", "0111", "101", "1001", but not "000", "101010" and "11100".You have to answer $$$t$$$ independent test cases. | 256 megabytes |
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
public class Main {
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int readInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public long readLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String 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 class Pair {
int x;
int y;
Pair(int x, int y) {
this.x = x;
this.y = y;
}
}
public static int biggestDivisor(int n) {
int max = 1;
for(int i=2;i*i<=n;i++) {
if(i*i == n) {
if(i > max) {
max = i;
}
}
else {
if(n%i == 0) {
if(i > max) {
max = i;
}
if(n/i > max) {
max = n/i;
}
}
}
}
return max;
}
public static void main (String[] args)
{
InputReader in = new InputReader(System.in);
int t = in.readInt();
while(t != 0) {
int n = in.readInt();
String st = in.readString();
LinkedHashMap<Integer, Integer> hmap0= new LinkedHashMap<>();
HashMap<Integer, Integer> hmap1= new LinkedHashMap<>();
int res[] = new int[n];
int r0 = 1, r1 = 1;
int s0 = 0, s1 = 0;
int subseq = 0;
for(int i=0;i<n;i++) {
if(st.charAt(i) == '0') {
if(hmap1.size() == 0) {
subseq++;
hmap0.put(s0 + 1, subseq);
s0++;
res[i] = subseq;
}
else {
int x = hmap1.get(r1);
hmap1.remove(r1);
r1++;
hmap0.put(s0+1, x);
s0++;
res[i] = x;
}
}
else {
if(hmap0.size() == 0) {
subseq++;
hmap1.put(s1+1, subseq);
s1++;
res[i] = subseq;
}
else {
int x = hmap0.get(r0);
hmap0.remove(r0);
r0++;
hmap1.put(s1+1, x);
s1++;
res[i] = x;
}
}
}
System.out.println(subseq);
for(int i=0;i<res.length;i++) {
System.out.print(res[i] + " ");
}
System.out.println();
t--;
}
}
} | Java | ["4\n4\n0011\n6\n111111\n5\n10101\n8\n01010000"] | 2 seconds | ["2\n1 2 2 1 \n6\n1 2 3 4 5 6 \n1\n1 1 1 1 1 \n4\n1 1 1 1 1 2 3 4"] | null | Java 8 | standard input | [
"data structures",
"constructive algorithms",
"implementation",
"greedy"
] | de57b6b1aa2b6ec4686d1348988c0c63 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of $$$s$$$. The second line of the test case contains $$$n$$$ characters '0' and '1' — the string $$$s$$$. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$). | 1,500 | For each test case, print the answer: in the first line print one integer $$$k$$$ ($$$1 \le k \le n$$$) — the minimum number of subsequences you can divide the string $$$s$$$ to. In the second line print $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le k$$$), where $$$a_i$$$ is the number of subsequence the $$$i$$$-th character of $$$s$$$ belongs to. If there are several answers, you can print any. | standard output | |
PASSED | ae5005d13cc3fbac66043f69ca8002e1 | train_004.jsonl | 1596638100 | You are given a binary string $$$s$$$ consisting of $$$n$$$ zeros and ones.Your task is to divide the given string into the minimum number of subsequences in such a way that each character of the string belongs to exactly one subsequence and each subsequence looks like "010101 ..." or "101010 ..." (i.e. the subsequence should not contain two adjacent zeros or ones).Recall that a subsequence is a sequence that can be derived from the given sequence by deleting zero or more elements without changing the order of the remaining elements. For example, subsequences of "1011101" are "0", "1", "11111", "0111", "101", "1001", but not "000", "101010" and "11100".You have to answer $$$t$$$ independent test cases. | 256 megabytes | import java.util.*;
import java.io.*;
public class vivek{
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();
}
char nextChar()
{
return next().charAt(0);
}
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;
}
int[] nextArray(int rows)
{
int arr[] = new int[rows];
for (int i = 0; i < rows; i++)
arr[i] = nextInt();
return arr;
}
long[] nextLongArray(int rows)
{
long arr[] = new long[rows];
for (int i = 0; i < rows; i++)
arr[i] = nextLong();
return arr;
}
char[] nextCharArray(int rows)
{
char arr[] = new char[rows];
for (int i = 0; i < rows; i++)
arr[i] = next().charAt(0);
return arr;
}
int[][] nextMatrix(int rows, int columns)
{
int mat[][] = new int[rows][columns];
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < columns; j++)
{
mat[i][j] = nextInt();
}
}
return mat;
}
}
public static void main(String args[]){
FastReader sc=new FastReader();
PrintWriter p=new PrintWriter(System.out);
int t=sc.nextInt();
while(t-->0){
int n=sc.nextInt();
String s=sc.next();
int a[]=new int[n];
LinkedList <Integer> zero=new LinkedList();
LinkedList <Integer> one=new LinkedList();
int count=1;
for(int i=0;i<n;i++){
int c=s.charAt(i);
if(c=='0' && one.isEmpty()){
a[i]=count;
zero.add(a[i]);
count++;
}
else if(c=='0' && !one.isEmpty()){
a[i]=one.poll();
zero.add(a[i]);
}
if(c=='1' && zero.isEmpty()){
a[i]=count;
one.add(a[i]);
count++;
}
else if(c=='1' && !zero.isEmpty()){
a[i]=zero.poll();
one.add(a[i]);
}
}
p.println(--count);
for(int i=0;i<n;i++)
p.print(a[i]+" ");
p.println();
}
p.flush();
}
} | Java | ["4\n4\n0011\n6\n111111\n5\n10101\n8\n01010000"] | 2 seconds | ["2\n1 2 2 1 \n6\n1 2 3 4 5 6 \n1\n1 1 1 1 1 \n4\n1 1 1 1 1 2 3 4"] | null | Java 8 | standard input | [
"data structures",
"constructive algorithms",
"implementation",
"greedy"
] | de57b6b1aa2b6ec4686d1348988c0c63 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of $$$s$$$. The second line of the test case contains $$$n$$$ characters '0' and '1' — the string $$$s$$$. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$). | 1,500 | For each test case, print the answer: in the first line print one integer $$$k$$$ ($$$1 \le k \le n$$$) — the minimum number of subsequences you can divide the string $$$s$$$ to. In the second line print $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le k$$$), where $$$a_i$$$ is the number of subsequence the $$$i$$$-th character of $$$s$$$ belongs to. If there are several answers, you can print any. | standard output | |
PASSED | b54d5d3c9c2047a7fc312fa4127fd150 | train_004.jsonl | 1596638100 | You are given a binary string $$$s$$$ consisting of $$$n$$$ zeros and ones.Your task is to divide the given string into the minimum number of subsequences in such a way that each character of the string belongs to exactly one subsequence and each subsequence looks like "010101 ..." or "101010 ..." (i.e. the subsequence should not contain two adjacent zeros or ones).Recall that a subsequence is a sequence that can be derived from the given sequence by deleting zero or more elements without changing the order of the remaining elements. For example, subsequences of "1011101" are "0", "1", "11111", "0111", "101", "1001", but not "000", "101010" and "11100".You have to answer $$$t$$$ independent test cases. | 256 megabytes |
import java.util.*;
public class DIV3661 {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
while(t-->0) {
int n=sc.nextInt();
String s=sc.next();
char a[]=s.toCharArray();
int aa[]=new int[n];
Stack<Integer> sz=new Stack<>();
Stack<Integer> so=new Stack<>();
int comp=1;
for(int i=0;i<n;i++) {
if(a[i]=='0') {
if(!so.isEmpty()) {
int k=so.pop();
aa[i]=(k);
sz.push(k);
}else {
sz.push(comp);
aa[i]=(comp);
comp++;
}
}else {
if(!sz.isEmpty()) {
int k=sz.pop();
aa[i]=(k);
so.push(k);
}else {
so.push(comp);
aa[i]=(comp);
comp++;
}
}
}
System.out.println(comp-1);
for(int i:aa) {
System.out.print(i+" ");
}
System.out.println();
}
}}
//12
//110110001010
//3
//1 2 1 1 3 2 1 3 2 2 1 1
| Java | ["4\n4\n0011\n6\n111111\n5\n10101\n8\n01010000"] | 2 seconds | ["2\n1 2 2 1 \n6\n1 2 3 4 5 6 \n1\n1 1 1 1 1 \n4\n1 1 1 1 1 2 3 4"] | null | Java 8 | standard input | [
"data structures",
"constructive algorithms",
"implementation",
"greedy"
] | de57b6b1aa2b6ec4686d1348988c0c63 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of $$$s$$$. The second line of the test case contains $$$n$$$ characters '0' and '1' — the string $$$s$$$. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$). | 1,500 | For each test case, print the answer: in the first line print one integer $$$k$$$ ($$$1 \le k \le n$$$) — the minimum number of subsequences you can divide the string $$$s$$$ to. In the second line print $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le k$$$), where $$$a_i$$$ is the number of subsequence the $$$i$$$-th character of $$$s$$$ belongs to. If there are several answers, you can print any. | standard output | |
PASSED | 372ea3d2731437fd8d7d63da25e5d772 | train_004.jsonl | 1596638100 | You are given a binary string $$$s$$$ consisting of $$$n$$$ zeros and ones.Your task is to divide the given string into the minimum number of subsequences in such a way that each character of the string belongs to exactly one subsequence and each subsequence looks like "010101 ..." or "101010 ..." (i.e. the subsequence should not contain two adjacent zeros or ones).Recall that a subsequence is a sequence that can be derived from the given sequence by deleting zero or more elements without changing the order of the remaining elements. For example, subsequences of "1011101" are "0", "1", "11111", "0111", "101", "1001", but not "000", "101010" and "11100".You have to answer $$$t$$$ independent test cases. | 256 megabytes | import java.util.*;
import java.lang.*;
import java.io.*;
import java.math.BigInteger;
public class CF {
public static void subsequence_possible (TreeSet<Integer> t1, TreeSet<Integer> t2, int[] arr, int round) {
if (t1.first() > t2.first()) {
subsequence_possible(t2, t1, arr, round);
return;
}
Integer cur1 = -1;
Integer cur2 = -1;
while (true) {
cur1 = t1.higher(cur2);
if (cur1 == null) return;
arr[cur1] = round;
t1.remove(cur1);
if (t1.isEmpty() && t2.isEmpty()) return;
cur2 = t2.higher(cur1);
if (cur2 == null) return;
arr[cur2] = round;
t2.remove(cur2);
if (t1.isEmpty() && t2.isEmpty()) return;
}
}
public static void main (String[] args) {
Scanner sc=new Scanner(System.in);
int t = sc.nextInt();
sc.nextLine();
while (t-- > 0) {
int n = sc.nextInt();
sc.nextLine();
String s = sc.nextLine();
TreeSet<Integer> t1 = new TreeSet<>();
TreeSet<Integer> t2 = new TreeSet<>();
for (int i = 0; i < n; i++) {
if (s.charAt(i) == '0') t1.add(i);
else t2.add(i);
}
int round = 1;
int[] arr = new int[n];
while (!t1.isEmpty() && !t2.isEmpty()) {
subsequence_possible(t1, t2, arr, round);
round++;
}
while (!t1.isEmpty()) {
arr[t1.first()] = round;
t1.remove(t1.first());
round++;
}
while (!t2.isEmpty()) {
arr[t2.first()] = round;
t2.remove(t2.first());
round++;
}
System.out.println(round-1);
for (int elem: arr) System.out.print(elem + " ");
System.out.println();
}
}
}
| Java | ["4\n4\n0011\n6\n111111\n5\n10101\n8\n01010000"] | 2 seconds | ["2\n1 2 2 1 \n6\n1 2 3 4 5 6 \n1\n1 1 1 1 1 \n4\n1 1 1 1 1 2 3 4"] | null | Java 8 | standard input | [
"data structures",
"constructive algorithms",
"implementation",
"greedy"
] | de57b6b1aa2b6ec4686d1348988c0c63 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of $$$s$$$. The second line of the test case contains $$$n$$$ characters '0' and '1' — the string $$$s$$$. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$). | 1,500 | For each test case, print the answer: in the first line print one integer $$$k$$$ ($$$1 \le k \le n$$$) — the minimum number of subsequences you can divide the string $$$s$$$ to. In the second line print $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le k$$$), where $$$a_i$$$ is the number of subsequence the $$$i$$$-th character of $$$s$$$ belongs to. If there are several answers, you can print any. | standard output | |
PASSED | 93e8dab368d6a089990bf3e797c02868 | train_004.jsonl | 1596638100 | You are given a binary string $$$s$$$ consisting of $$$n$$$ zeros and ones.Your task is to divide the given string into the minimum number of subsequences in such a way that each character of the string belongs to exactly one subsequence and each subsequence looks like "010101 ..." or "101010 ..." (i.e. the subsequence should not contain two adjacent zeros or ones).Recall that a subsequence is a sequence that can be derived from the given sequence by deleting zero or more elements without changing the order of the remaining elements. For example, subsequences of "1011101" are "0", "1", "11111", "0111", "101", "1001", but not "000", "101010" and "11100".You have to answer $$$t$$$ independent test cases. | 256 megabytes | import java.util.*;
import java.lang.*;
import java.io.*;
import java.math.BigInteger;
public class CF {
public static void subsequence_possible (TreeSet<Integer> t1, TreeSet<Integer> t2, int[] arr, int round) {
if (t1.first() > t2.first()) {
subsequence_possible(t2, t1, arr, round);
return;
}
Integer cur1 = -1;
Integer cur2 = -1;
while (true) {
//System.out.println("round " + round + " Here with cur1 " + cur1 + " and cur2 " + cur2);
//System.out.println(t1);
//System.out.println(t2);
if (t1.isEmpty()) {
//System.out.println("t1 is empty .return " + t1.size());
return;
}
//System.out.println("Continuing.. t1 is empty .return " + t1.size());
cur1 = t1.higher(cur2);
if (cur1 == null) {
////System.out.println("cur1 is (null) --> " + cur1);
return;
}
arr[cur1] = round;
t1.remove(cur1);
if (t1.isEmpty() && t2.isEmpty()) return;
cur2 = t2.higher(cur1);
if (cur2 == null) return;
arr[cur2] = round;
t2.remove(cur2);
if (t1.isEmpty() && t2.isEmpty()) return;
}
}
public static void main (String[] args) {
Scanner sc=new Scanner(System.in);
int t = sc.nextInt();
sc.nextLine();
while (t-- > 0) {
int n = sc.nextInt();
sc.nextLine();
String s = sc.nextLine();
TreeSet<Integer> t1 = new TreeSet<>();
TreeSet<Integer> t2 = new TreeSet<>();
for (int i = 0; i < n; i++) {
if (s.charAt(i) == '0') t1.add(i);
else t2.add(i);
}
//System.out.println(t1);
//System.out.println(t2);
boolean possible = true;
int round = 1;
int[] arr = new int[n];
while (!t1.isEmpty() && !t2.isEmpty()) {
//System.out.println("Calling round " + round);
subsequence_possible(t1, t2, arr, round);
round++;
}
while (!t1.isEmpty()) {
arr[t1.first()] = round;
t1.remove(t1.first());
round++;
}
while (!t2.isEmpty()) {
arr[t2.first()] = round;
t2.remove(t2.first());
round++;
}
System.out.println(round-1);
for (int elem: arr) System.out.print(elem + " ");
System.out.println();
}
}
}
| Java | ["4\n4\n0011\n6\n111111\n5\n10101\n8\n01010000"] | 2 seconds | ["2\n1 2 2 1 \n6\n1 2 3 4 5 6 \n1\n1 1 1 1 1 \n4\n1 1 1 1 1 2 3 4"] | null | Java 8 | standard input | [
"data structures",
"constructive algorithms",
"implementation",
"greedy"
] | de57b6b1aa2b6ec4686d1348988c0c63 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of $$$s$$$. The second line of the test case contains $$$n$$$ characters '0' and '1' — the string $$$s$$$. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$). | 1,500 | For each test case, print the answer: in the first line print one integer $$$k$$$ ($$$1 \le k \le n$$$) — the minimum number of subsequences you can divide the string $$$s$$$ to. In the second line print $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le k$$$), where $$$a_i$$$ is the number of subsequence the $$$i$$$-th character of $$$s$$$ belongs to. If there are several answers, you can print any. | standard output | |
PASSED | ca53e5dc1c1a4eedb94f7986d8227ab4 | train_004.jsonl | 1596638100 | You are given a binary string $$$s$$$ consisting of $$$n$$$ zeros and ones.Your task is to divide the given string into the minimum number of subsequences in such a way that each character of the string belongs to exactly one subsequence and each subsequence looks like "010101 ..." or "101010 ..." (i.e. the subsequence should not contain two adjacent zeros or ones).Recall that a subsequence is a sequence that can be derived from the given sequence by deleting zero or more elements without changing the order of the remaining elements. For example, subsequences of "1011101" are "0", "1", "11111", "0111", "101", "1001", but not "000", "101010" and "11100".You have to answer $$$t$$$ independent test cases. | 256 megabytes | /* package codechef; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
public class Codechef
{
public static void main (String[] args) throws java.lang.Exception
{
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
for(int y=0;y<t;++y)
{
int n=sc.nextInt();
String s=sc.next();
char[] ch=s.toCharArray();
long arr[]=new long[n];
long nom=0;
char prev=ch[0];
Stack<Long> s0=new Stack<Long>();
Stack<Long> s1=new Stack<Long>();
//if(=='1')
// arr[0]=1;
for(int i=0;i<n;++i)
{
if(s.charAt(i)=='0')
{
if(s0.isEmpty())
{
arr[i]= ++nom;
}
else
{
arr[i]=s0.pop();
}
s1.push(arr[i]);
}
else{
if(s1.isEmpty())
{
arr[i]= ++nom;
}
else
{
arr[i]=s1.pop();
}
s0.push(arr[i]);
}
}
System.out.println(nom);
for(int i=0;i<n;++i)
System.out.print(arr[i]+" ");
System.out.println();
}
}
}
| Java | ["4\n4\n0011\n6\n111111\n5\n10101\n8\n01010000"] | 2 seconds | ["2\n1 2 2 1 \n6\n1 2 3 4 5 6 \n1\n1 1 1 1 1 \n4\n1 1 1 1 1 2 3 4"] | null | Java 8 | standard input | [
"data structures",
"constructive algorithms",
"implementation",
"greedy"
] | de57b6b1aa2b6ec4686d1348988c0c63 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of $$$s$$$. The second line of the test case contains $$$n$$$ characters '0' and '1' — the string $$$s$$$. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$). | 1,500 | For each test case, print the answer: in the first line print one integer $$$k$$$ ($$$1 \le k \le n$$$) — the minimum number of subsequences you can divide the string $$$s$$$ to. In the second line print $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le k$$$), where $$$a_i$$$ is the number of subsequence the $$$i$$$-th character of $$$s$$$ belongs to. If there are several answers, you can print any. | standard output | |
PASSED | fc5092104abd6924c3865a6d4deb033d | train_004.jsonl | 1596638100 | You are given a binary string $$$s$$$ consisting of $$$n$$$ zeros and ones.Your task is to divide the given string into the minimum number of subsequences in such a way that each character of the string belongs to exactly one subsequence and each subsequence looks like "010101 ..." or "101010 ..." (i.e. the subsequence should not contain two adjacent zeros or ones).Recall that a subsequence is a sequence that can be derived from the given sequence by deleting zero or more elements without changing the order of the remaining elements. For example, subsequences of "1011101" are "0", "1", "11111", "0111", "101", "1001", but not "000", "101010" and "11100".You have to answer $$$t$$$ independent test cases. | 256 megabytes | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;
public class D {
final static long MOD = 1000000007;
public static void main(String[] args) {
FastScanner fs = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
int t = fs.nextInt();
while(t > 0) {
t-=1;
int n = fs.nextInt();
char [] ch = fs.nextCharArray();
int [] a = new int[n];
for(int i = 0; i < n; i++) {
a[i] = ch[i] - '0';
}
Deque<Integer> zeros = new ArrayDeque<>();
Deque<Integer> ones = new ArrayDeque<>();;
int [] ans = new int[n];
for(int i = 0; i < n; i++) {
int current_pos = zeros.size() + ones.size();
if(a[i] == 0) {
if(ones.isEmpty())
zeros.add(current_pos);
else {
current_pos = ones.removeLast();
zeros.push(current_pos);
}
}
else {
if(zeros.isEmpty())
ones.add(current_pos);
else {
current_pos = zeros.removeLast();
ones.push(current_pos);
}
}
ans[i] = current_pos;
}
out.println(Arrays.stream(ans).max().getAsInt()+1);
for(int i = 0; i < n; i++) {
out.print(ans[i]+1+" ");
}
out.println();
}
out.flush();
out.close();
}
class Pair{
int index;
int val;
Pair(int index, int val) {
this.val = val;
this.index = index;
}
}
public static String rString(String s) {
return new StringBuilder(s).reverse().toString();
}
public static int powoftwo(long n){
int count = 0;
while(n != 0) {
n >>= 1;
count++;
}
return count - 1;
}
public static void rotate(int[] nums, int k) {
int n = nums.length;
if(k > 0) {
for(int j = 0; j < k; j++) {
for (int i = 0; i < n; i++) {
int temp = nums[(i + k) % n];
nums[(i + k) % n] = nums[i];
nums[i] = temp;
}
}
}
}
static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner() {
try {
br = new BufferedReader(new InputStreamReader(System.in));
// br = new BufferedReader(new FileReader("chat.txt"));
st = new StringTokenizer("");
} catch (Exception e) {
e.printStackTrace();
}
}
public String next() {
if (st.hasMoreTokens())
return st.nextToken();
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
e.printStackTrace();
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public String nextLine() {
String line = "";
try {
line = br.readLine();
} catch (Exception e) {
e.printStackTrace();
}
return line;
}
public char nextChar() {
return next().charAt(0);
}
public Integer[] nextIntegerArray(int n) {
Integer[] a = new Integer[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
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 char[] nextCharArray() {
return nextLine().toCharArray();
}
}
}
/*class Pair implements Comparable<Pair> {
int V;
int H;
public Pair(int count, int val) {
this.V = count;
this.H = val;
}
public void setV(int v) {
V = v;
}
public void setH(int h) {
H = h;
}
@Override
public int compareTo(Pair o) {
if(this.V != o.V)
return Integer.compare(this.V, o.V);
else
return Integer.compare(this.H, o.H);
}
public boolean equals(Pair o) {
return this.H == o.H && this.V == o.V;
}
}*/
| Java | ["4\n4\n0011\n6\n111111\n5\n10101\n8\n01010000"] | 2 seconds | ["2\n1 2 2 1 \n6\n1 2 3 4 5 6 \n1\n1 1 1 1 1 \n4\n1 1 1 1 1 2 3 4"] | null | Java 8 | standard input | [
"data structures",
"constructive algorithms",
"implementation",
"greedy"
] | de57b6b1aa2b6ec4686d1348988c0c63 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of $$$s$$$. The second line of the test case contains $$$n$$$ characters '0' and '1' — the string $$$s$$$. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$). | 1,500 | For each test case, print the answer: in the first line print one integer $$$k$$$ ($$$1 \le k \le n$$$) — the minimum number of subsequences you can divide the string $$$s$$$ to. In the second line print $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le k$$$), where $$$a_i$$$ is the number of subsequence the $$$i$$$-th character of $$$s$$$ belongs to. If there are several answers, you can print any. | standard output | |
PASSED | f92bc0fb2bf442df5a359bab56aa4035 | train_004.jsonl | 1596638100 | You are given a binary string $$$s$$$ consisting of $$$n$$$ zeros and ones.Your task is to divide the given string into the minimum number of subsequences in such a way that each character of the string belongs to exactly one subsequence and each subsequence looks like "010101 ..." or "101010 ..." (i.e. the subsequence should not contain two adjacent zeros or ones).Recall that a subsequence is a sequence that can be derived from the given sequence by deleting zero or more elements without changing the order of the remaining elements. For example, subsequences of "1011101" are "0", "1", "11111", "0111", "101", "1001", but not "000", "101010" and "11100".You have to answer $$$t$$$ independent test cases. | 256 megabytes |
import java.io.*;
import java.lang.annotation.Native;
import java.math.BigInteger;
import java.util.*;
import java.util.ArrayList;
import java.util.Scanner;
public class main {
static class pair {
String first;
String second;
pair(String a, String b) {
first = a;
second = b;
}
}
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 final int mod = 1000000007;
static final int mod1 = 1073741824;
public static int gcd(int a, int b) {
if (a == 0)
return b;
return gcd(b % a, a);
}
static boolean prime[] = new boolean[1000001];
public static void merge(long arr[][], int l, int m, int r)
{
// Find sizes of two subarrays to be merged
int n1 = m - l + 1;
int n2 = r - m;
/* Create temp arrays */
long L[][] = new long[n1][2];
long R[][] = new long[n2][2];
/*Copy data to temp arrays*/
for (int i = 0; i < n1; ++i)
{
L[i][0] = arr[l + i][0];
L[i][1] = arr[l + i][1];
}
for (int j = 0; j < n2; ++j) {
R[j][0] = arr[m + 1 + j][0];
R[j][1] = arr[m + 1 + j][1];
}
/* 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][0] <= R[j][0]) {
arr[k][0] = L[i][0];
arr[k][1] = L[i][1];
i++;
}
else {
arr[k][0] = R[j][0];
arr[k][1] = R[j][1];
j++;
}
k++;
}
/* Copy remaining elements of L[] if any */
while (i < n1) {
arr[k][0] = L[i][0];
arr[k][1] = L[i][1];
i++;
k++;
}
/* Copy remaining elements of R[] if any */
while (j < n2) {
arr[k][0] = R[j][0];
arr[k][1] = R[j][1];
j++;
k++;
}
}
public static long[][] sort2elementarray(long arr[][], int l, int r)
{
if (l < r) {
// Find the middle point
int m = (l + r) / 2;
// Sort first and second halves
sort2elementarray(arr, l, m);
sort2elementarray(arr, m + 1, r);
// Merge the sorted halves
merge(arr, l, m, r);
}
return arr;
}
static int f=1;
static int vertices=0;
static int edges=0;
public static void dfs(ArrayList<Integer>[]li,int v,HashMap<Integer,Integer>hm)
{
hm.put(v,1);
//System.out.print(v+" ");
//System.out.println(a[v]+" "+cost);
vertices++;
edges+=li[v].size();
for (int j = 0; j < li[v].size(); j++)
{
if (hm.get(li[v].get(j)) == null)
{
dfs(li, li[v].get(j), hm);
}
}
}
public static void dfsutil(ArrayList<Integer>[]li,int n,int v)
{
HashMap<Integer,Integer>hm=new HashMap<>();
int c=0;
for(int j=1;j<=n;j++)
{
if(hm.get(j)==null)
{
vertices=0;
edges=0;
dfs(li,j,hm);
if(edges!=vertices*(vertices-1)) {
System.out.println("NO");
System.exit(0);
}
}
}
System.out.println("YES");
}
public static void bipartite(ArrayList<Integer>[]li,int n) {
int f = 1;
int col[] = new int[n + 1];
int fl = 1;
Arrays.fill(col, -1);
for (int i = 1; i <= n; i++) {
if (col[i] == -1) {
col[i] = 1;
Queue<Integer> q = new LinkedList<>();
q.add(i);
while (!q.isEmpty()) {
int x = q.peek();
q.remove();
for (int j = 0; j < li[x].size(); j++) {
if (col[li[x].get(j)] == -1) {
col[li[x].get(j)] = 1 - col[x];
q.add(li[x].get(j));
} else if (col[li[x].get(j)] == col[x]) {
f = 0;
break;
}
}
}
if (f == 0) {
fl = 0;
break;
}
}
}
/*if(fl==0)
// System.out.println(-1);
//else
{*/
long l1 = 0;
long l2 = 0;
for (int j = 1; j <= n; j++) {
if (col[j] == 1) {
l1++;
//sb.append(j+" ");
} else {
l2++;
//sb1.append(j+" ");
}
}
long ans=(l1*l2)-(n-1);
System.out.println(ans);
//}
}
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
for(int test=0;test<t;test++) {
int n = sc.nextInt();
sc.nextLine();
String s=sc.nextLine();
int dp[]=new int[n];
Stack<Integer>s1=new Stack<>();
int c=1;
Stack<Integer>s0=new Stack<>();
for(int j=0;j<n;j++)
{
int q=-1;
if(s.charAt(j)=='0')
{
if(s1.isEmpty())
{
q=c++;
}
else
{
q=s1.peek();
s1.pop();
}
s0.push(q);
}
else
{
if(s0.isEmpty())
{
q=c++;
}
else
{
q=s0.peek();
s0.pop();
}
s1.push(q);
}
dp[j]=q;
}
StringBuilder sb=new StringBuilder();
int max=1;
for(int j=0;j<n;j++)
{
if(dp[j]>max)
max=dp[j];
sb.append(dp[j]+" ");
}
System.out.println(max);
System.out.println(sb);
}
}
} | Java | ["4\n4\n0011\n6\n111111\n5\n10101\n8\n01010000"] | 2 seconds | ["2\n1 2 2 1 \n6\n1 2 3 4 5 6 \n1\n1 1 1 1 1 \n4\n1 1 1 1 1 2 3 4"] | null | Java 8 | standard input | [
"data structures",
"constructive algorithms",
"implementation",
"greedy"
] | de57b6b1aa2b6ec4686d1348988c0c63 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of $$$s$$$. The second line of the test case contains $$$n$$$ characters '0' and '1' — the string $$$s$$$. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$). | 1,500 | For each test case, print the answer: in the first line print one integer $$$k$$$ ($$$1 \le k \le n$$$) — the minimum number of subsequences you can divide the string $$$s$$$ to. In the second line print $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le k$$$), where $$$a_i$$$ is the number of subsequence the $$$i$$$-th character of $$$s$$$ belongs to. If there are several answers, you can print any. | standard output | |
PASSED | f5322b7b10f7afbd7395d7d56009068a | train_004.jsonl | 1596638100 | You are given a binary string $$$s$$$ consisting of $$$n$$$ zeros and ones.Your task is to divide the given string into the minimum number of subsequences in such a way that each character of the string belongs to exactly one subsequence and each subsequence looks like "010101 ..." or "101010 ..." (i.e. the subsequence should not contain two adjacent zeros or ones).Recall that a subsequence is a sequence that can be derived from the given sequence by deleting zero or more elements without changing the order of the remaining elements. For example, subsequences of "1011101" are "0", "1", "11111", "0111", "101", "1001", but not "000", "101010" and "11100".You have to answer $$$t$$$ independent test cases. | 256 megabytes | import java.util.*;
public class Main{
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
for(int z=0;z<t;z++)
{
int n=sc.nextInt();
String temp=sc.nextLine();
String s=sc.nextLine();
Stack<Integer> s1=new Stack<Integer>();
Stack<Integer> s2=new Stack<Integer>();
int num=1;
int a[]=new int[n];
for(int i=0;i<n;i++)
{
if(s.charAt(i)=='0')
{
if(s2.isEmpty())
{
s1.push(num);
a[i]=num;
num++;
}
else
{
int k=s2.pop();
s1.push(k);
a[i]=k;
}
}
else
{
if(s1.isEmpty())
{
s2.push(num);
a[i]=num;
num++;
}
else
{
int k=s1.pop();
s2.push(k);
a[i]=k;
}
}
}
System.out.println(num-1);
for(int i=0;i<n;i++)
System.out.print(a[i]+" ");
System.out.println();
}
}
}
| Java | ["4\n4\n0011\n6\n111111\n5\n10101\n8\n01010000"] | 2 seconds | ["2\n1 2 2 1 \n6\n1 2 3 4 5 6 \n1\n1 1 1 1 1 \n4\n1 1 1 1 1 2 3 4"] | null | Java 8 | standard input | [
"data structures",
"constructive algorithms",
"implementation",
"greedy"
] | de57b6b1aa2b6ec4686d1348988c0c63 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of $$$s$$$. The second line of the test case contains $$$n$$$ characters '0' and '1' — the string $$$s$$$. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$). | 1,500 | For each test case, print the answer: in the first line print one integer $$$k$$$ ($$$1 \le k \le n$$$) — the minimum number of subsequences you can divide the string $$$s$$$ to. In the second line print $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le k$$$), where $$$a_i$$$ is the number of subsequence the $$$i$$$-th character of $$$s$$$ belongs to. If there are several answers, you can print any. | standard output | |
PASSED | 236e8b419b41f0ad8cef75808531efba | train_004.jsonl | 1596638100 | You are given a binary string $$$s$$$ consisting of $$$n$$$ zeros and ones.Your task is to divide the given string into the minimum number of subsequences in such a way that each character of the string belongs to exactly one subsequence and each subsequence looks like "010101 ..." or "101010 ..." (i.e. the subsequence should not contain two adjacent zeros or ones).Recall that a subsequence is a sequence that can be derived from the given sequence by deleting zero or more elements without changing the order of the remaining elements. For example, subsequences of "1011101" are "0", "1", "11111", "0111", "101", "1001", but not "000", "101010" and "11100".You have to answer $$$t$$$ independent test cases. | 256 megabytes | import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class D {
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
int cases = scn.nextInt();
while (cases-- > 0) {
scn.nextInt();
String bin = scn.next();
Queue<Integer> ones = new LinkedList<>();
Queue<Integer> zeros = new LinkedList<>();
int count = 0;
int[] pos = new int[bin.length()];
for (int i = 0; i < bin.length(); i++) {
if (i == 0) {
count++;
if (bin.charAt(i) == '1') {
ones.add(count);
} else {
zeros.add(count);
}
pos[i] = count;
} else {
if (bin.charAt(i) == '1') {
if (zeros.size() > 0) {
pos[i] = zeros.remove();
ones.add(pos[i]);
} else {
count++;
pos[i] = count;
ones.add(count);
}
} else {
if (ones.size() > 0) {
pos[i] = ones.remove();
zeros.add(pos[i]);
} else {
count++;
pos[i] = count;
zeros.add(count);
}
}
}
}
System.out.println(count);
for (int i = 0; i < pos.length; i++) {
System.out.print(pos[i] + " ");
}
System.out.println();
}
}
}
| Java | ["4\n4\n0011\n6\n111111\n5\n10101\n8\n01010000"] | 2 seconds | ["2\n1 2 2 1 \n6\n1 2 3 4 5 6 \n1\n1 1 1 1 1 \n4\n1 1 1 1 1 2 3 4"] | null | Java 8 | standard input | [
"data structures",
"constructive algorithms",
"implementation",
"greedy"
] | de57b6b1aa2b6ec4686d1348988c0c63 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of $$$s$$$. The second line of the test case contains $$$n$$$ characters '0' and '1' — the string $$$s$$$. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$). | 1,500 | For each test case, print the answer: in the first line print one integer $$$k$$$ ($$$1 \le k \le n$$$) — the minimum number of subsequences you can divide the string $$$s$$$ to. In the second line print $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le k$$$), where $$$a_i$$$ is the number of subsequence the $$$i$$$-th character of $$$s$$$ belongs to. If there are several answers, you can print any. | standard output | |
PASSED | 7bd93450eec3a571efa69e8cdd43c7c9 | train_004.jsonl | 1596638100 | You are given a binary string $$$s$$$ consisting of $$$n$$$ zeros and ones.Your task is to divide the given string into the minimum number of subsequences in such a way that each character of the string belongs to exactly one subsequence and each subsequence looks like "010101 ..." or "101010 ..." (i.e. the subsequence should not contain two adjacent zeros or ones).Recall that a subsequence is a sequence that can be derived from the given sequence by deleting zero or more elements without changing the order of the remaining elements. For example, subsequences of "1011101" are "0", "1", "11111", "0111", "101", "1001", but not "000", "101010" and "11100".You have to answer $$$t$$$ independent test cases. | 256 megabytes | import java.io.PrintWriter;
import java.util.Scanner;
import java.util.Set;
import java.util.TreeSet;
public class Main {
static Scanner in;
static PrintWriter out;
public static void main(String[] args) {
in = new Scanner(System.in);
out = new PrintWriter(System.out);
int t = in.nextInt();
while (t-- > 0) {
int n = in.nextInt();
String s = in.next();
char[] sa = s.toCharArray();
Set[] st = new TreeSet[2];
st[0] = new TreeSet<Integer>();
st[1] = new TreeSet<Integer>();
int[] res = new int[n];
int id = 1;
int ans = 0;
for (int i = 0; i < sa.length; i++) {
int c = sa[i] - '0';
if (st[c ^ 1].isEmpty()) {
st[c].add(id++);
res[i] = id - 1;
ans = id - 1;
} else {
Integer c1 = (Integer) st[c ^ 1].iterator().next();
st[c ^ 1].remove(c1);
st[c].add(c1);
res[i] = c1;
}
}
out.println(ans);
for (int x : res) {
out.print(x + " ");
}
out.println();
}
out.close();
}
} | Java | ["4\n4\n0011\n6\n111111\n5\n10101\n8\n01010000"] | 2 seconds | ["2\n1 2 2 1 \n6\n1 2 3 4 5 6 \n1\n1 1 1 1 1 \n4\n1 1 1 1 1 2 3 4"] | null | Java 8 | standard input | [
"data structures",
"constructive algorithms",
"implementation",
"greedy"
] | de57b6b1aa2b6ec4686d1348988c0c63 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of $$$s$$$. The second line of the test case contains $$$n$$$ characters '0' and '1' — the string $$$s$$$. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$). | 1,500 | For each test case, print the answer: in the first line print one integer $$$k$$$ ($$$1 \le k \le n$$$) — the minimum number of subsequences you can divide the string $$$s$$$ to. In the second line print $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le k$$$), where $$$a_i$$$ is the number of subsequence the $$$i$$$-th character of $$$s$$$ belongs to. If there are several answers, you can print any. | standard output | |
PASSED | 3b7d3859b4c6c6bfb3a98ed01a5dc808 | train_004.jsonl | 1596638100 | You are given a binary string $$$s$$$ consisting of $$$n$$$ zeros and ones.Your task is to divide the given string into the minimum number of subsequences in such a way that each character of the string belongs to exactly one subsequence and each subsequence looks like "010101 ..." or "101010 ..." (i.e. the subsequence should not contain two adjacent zeros or ones).Recall that a subsequence is a sequence that can be derived from the given sequence by deleting zero or more elements without changing the order of the remaining elements. For example, subsequences of "1011101" are "0", "1", "11111", "0111", "101", "1001", but not "000", "101010" and "11100".You have to answer $$$t$$$ independent test cases. | 256 megabytes | //package CFR661;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Random;
import java.util.StringTokenizer;
/*
1
4
0011
*/
public class D {
public static void main(String[] args) {
FastScanner fs=new FastScanner();
int T=fs.nextInt();
PrintWriter out=new PrintWriter(System.out);
for (int tt=0; tt<T; tt++) {
int n=fs.nextInt();
char[] a=fs.next().toCharArray();
ArrayDeque<Integer> zs=new ArrayDeque<>(),
os=new ArrayDeque<>();
int[] ans=new int[n];
int nPiles=0;
int index=0;
for (char c:a) {
if (c=='0') {
if (zs.isEmpty()) {
nPiles++;
ans[index]=nPiles;
os.addLast(nPiles);
}
else {
int p=zs.removeFirst();
ans[index]=p;
os.addLast(p);
}
}
else {
if (os.isEmpty()) {
nPiles++;
ans[index]=nPiles;
zs.addLast(nPiles);
}
else {
int p=os.removeFirst();
ans[index]=p;
zs.addLast(p);
}
}
index++;
}
out.println(nPiles);
for (int i:ans) out.print(i+" ");
out.println();
}
out.close();
}
static final Random random=new Random();
static void ruffleSort(int[] a) {
int n=a.length;//shuffle, then sort
for (int i=0; i<n; i++) {
int oi=random.nextInt(n), temp=a[oi];
a[oi]=a[i]; a[i]=temp;
}
Arrays.sort(a);
}
static class 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 | ["4\n4\n0011\n6\n111111\n5\n10101\n8\n01010000"] | 2 seconds | ["2\n1 2 2 1 \n6\n1 2 3 4 5 6 \n1\n1 1 1 1 1 \n4\n1 1 1 1 1 2 3 4"] | null | Java 8 | standard input | [
"data structures",
"constructive algorithms",
"implementation",
"greedy"
] | de57b6b1aa2b6ec4686d1348988c0c63 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of $$$s$$$. The second line of the test case contains $$$n$$$ characters '0' and '1' — the string $$$s$$$. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$). | 1,500 | For each test case, print the answer: in the first line print one integer $$$k$$$ ($$$1 \le k \le n$$$) — the minimum number of subsequences you can divide the string $$$s$$$ to. In the second line print $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le k$$$), where $$$a_i$$$ is the number of subsequence the $$$i$$$-th character of $$$s$$$ belongs to. If there are several answers, you can print any. | standard output | |
PASSED | 617b470a311fecc7bbbee923a0ef2d14 | train_004.jsonl | 1596638100 | You are given a binary string $$$s$$$ consisting of $$$n$$$ zeros and ones.Your task is to divide the given string into the minimum number of subsequences in such a way that each character of the string belongs to exactly one subsequence and each subsequence looks like "010101 ..." or "101010 ..." (i.e. the subsequence should not contain two adjacent zeros or ones).Recall that a subsequence is a sequence that can be derived from the given sequence by deleting zero or more elements without changing the order of the remaining elements. For example, subsequences of "1011101" are "0", "1", "11111", "0111", "101", "1001", but not "000", "101010" and "11100".You have to answer $$$t$$$ independent test cases. | 256 megabytes | import java.io.*;
import java.lang.*;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.IOException;
import java.util.Stack;
import java.util.StringTokenizer;
import java.math.BigInteger;
public class Upsolve {
static InputReader in = new InputReader(System.in);
static PrintWriter out = new PrintWriter(System.out);
public static void main(String[] args) {
int q = in.nextInt();
while(q-->0){
int n = in.nextInt();
String s = in.next();
Stack<Integer> z = new Stack<Integer>();
Stack<Integer> o = new Stack<Integer>();
int count = 0;
int[] ans = new int[n];
for(int i = 0; i<n; i++){
if(s.charAt(i)=='1'){
if(!z.isEmpty()){
int temp = z.pop();
ans[i] = temp;
o.push(temp);
}
else{
++count;
ans[i] = count;
o.push(count);
}
}
else{
if(!o.isEmpty()){
int temp = o.pop();
ans[i] = temp;
z.push(temp);
}
else{
++count;
ans[i] = count;
z.push(count);
}
}
}
out.println(count);
for(int i : ans){
out.print(i + " ");
}
out.println();
}
out.close();
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public String nextLine() {
try {
return reader.readLine();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public boolean hasNext() {
String next = null;
try {
next = reader.readLine();
} catch (Exception e) {
}
if (next == null) {
return false;
}
tokenizer = new StringTokenizer(next);
return true;
}
public BigInteger nextBigInteger() {
return new BigInteger(next());
}
}
}
| Java | ["4\n4\n0011\n6\n111111\n5\n10101\n8\n01010000"] | 2 seconds | ["2\n1 2 2 1 \n6\n1 2 3 4 5 6 \n1\n1 1 1 1 1 \n4\n1 1 1 1 1 2 3 4"] | null | Java 8 | standard input | [
"data structures",
"constructive algorithms",
"implementation",
"greedy"
] | de57b6b1aa2b6ec4686d1348988c0c63 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of $$$s$$$. The second line of the test case contains $$$n$$$ characters '0' and '1' — the string $$$s$$$. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$). | 1,500 | For each test case, print the answer: in the first line print one integer $$$k$$$ ($$$1 \le k \le n$$$) — the minimum number of subsequences you can divide the string $$$s$$$ to. In the second line print $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le k$$$), where $$$a_i$$$ is the number of subsequence the $$$i$$$-th character of $$$s$$$ belongs to. If there are several answers, you can print any. | standard output | |
PASSED | 22636bb19f484ff0d1e75c4116ef9ace | train_004.jsonl | 1596638100 | You are given a binary string $$$s$$$ consisting of $$$n$$$ zeros and ones.Your task is to divide the given string into the minimum number of subsequences in such a way that each character of the string belongs to exactly one subsequence and each subsequence looks like "010101 ..." or "101010 ..." (i.e. the subsequence should not contain two adjacent zeros or ones).Recall that a subsequence is a sequence that can be derived from the given sequence by deleting zero or more elements without changing the order of the remaining elements. For example, subsequences of "1011101" are "0", "1", "11111", "0111", "101", "1001", but not "000", "101010" and "11100".You have to answer $$$t$$$ independent test cases. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class D1399 {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int test = Integer.parseInt(br.readLine());
while (test-- > 0){
int n = Integer.parseInt(br.readLine());
String s = br.readLine();
int ans[] = new int[n];
int cnt0=0;
int cnt1=0;
List<Integer> pos0 = new ArrayList<>();
List<Integer> pos1 = new ArrayList<>();
int mx = 0;
for (int i=0;i<n;++i) {
int npos = pos0.size() + pos1.size();
if (s.charAt(i) == '1'){
if (pos0.size() == 0){
pos1.add(npos);
} else {
int lastIndex = pos0.size() - 1;
npos = pos0.get(lastIndex);
pos0.remove(lastIndex);
pos1.add(npos);
}
} else {
if (pos1.size() == 0){
pos0.add(npos);
} else {
int lastIndex = pos1.size() - 1;
npos = pos1.get(lastIndex);
pos1.remove(lastIndex);
pos0.add(npos);
}
}
ans[i] = npos;
mx = Math.max(npos, mx);
}
System.out.println(mx+1);
for (int i=0;i<n;++i){
System.out.print((ans[i]+1) + " ");
}
System.out.println("");
}
}
}
| Java | ["4\n4\n0011\n6\n111111\n5\n10101\n8\n01010000"] | 2 seconds | ["2\n1 2 2 1 \n6\n1 2 3 4 5 6 \n1\n1 1 1 1 1 \n4\n1 1 1 1 1 2 3 4"] | null | Java 8 | standard input | [
"data structures",
"constructive algorithms",
"implementation",
"greedy"
] | de57b6b1aa2b6ec4686d1348988c0c63 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of $$$s$$$. The second line of the test case contains $$$n$$$ characters '0' and '1' — the string $$$s$$$. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$). | 1,500 | For each test case, print the answer: in the first line print one integer $$$k$$$ ($$$1 \le k \le n$$$) — the minimum number of subsequences you can divide the string $$$s$$$ to. In the second line print $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le k$$$), where $$$a_i$$$ is the number of subsequence the $$$i$$$-th character of $$$s$$$ belongs to. If there are several answers, you can print any. | standard output | |
PASSED | afe58e4ceb7eff32412f4e948db958e8 | train_004.jsonl | 1596638100 | You are given a binary string $$$s$$$ consisting of $$$n$$$ zeros and ones.Your task is to divide the given string into the minimum number of subsequences in such a way that each character of the string belongs to exactly one subsequence and each subsequence looks like "010101 ..." or "101010 ..." (i.e. the subsequence should not contain two adjacent zeros or ones).Recall that a subsequence is a sequence that can be derived from the given sequence by deleting zero or more elements without changing the order of the remaining elements. For example, subsequences of "1011101" are "0", "1", "11111", "0111", "101", "1001", but not "000", "101010" and "11100".You have to answer $$$t$$$ independent test cases. | 256 megabytes | import java.util.*;
import java.lang.*;
import java.io.*;
public class Codechef
{
public static void main (String[] args) throws java.lang.Exception
{
// Scanner sc=new Scanner(System.in);
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
// int t=1;
//t=sc.nextInt();
int t=Integer.parseInt(br.readLine());
while(--t>=0){
// int n=sc.nextInt();
int n=Integer.parseInt(br.readLine());
// int k=sc.nextInt();
String s=br.readLine();
int a[]=new int[n];
// StringTokenizer st=new StringTokenizer(br.readLine());
// int n=Integer.parseInt(st.nextToken());
//for(int i=0;i<n;i++)a[i]=sc.nextInt();
int c=1;
int k=1;
a[0]=1;
for(int i=1;i<n;i++){
if(s.charAt(0)=='1'){
if(s.charAt(i)=='1')
{
c++;
a[i]=c;
}
else{
a[i]=c;
c--;
}
}
if(s.charAt(0)=='0'){
if(s.charAt(i)=='0')
{
c++;
a[i]=c;
}
else{
a[i]=c;
c--;
}
}
k=Math.max(k,c);
}
int q=k;
for(int i=0;i<n;i++){
if(a[i]<=0){
a[i]=k+Math.abs(a[i])+1;
}
q=Math.max(a[i],q);
}
System.out.println(q);
for(int i=0;i<n;i++)
System.out.print(a[i]+" ");
System.out.println();
// for(int i=0;i<n;i++)
// System.out.print(arr[i]+" ");
}
}
}
| Java | ["4\n4\n0011\n6\n111111\n5\n10101\n8\n01010000"] | 2 seconds | ["2\n1 2 2 1 \n6\n1 2 3 4 5 6 \n1\n1 1 1 1 1 \n4\n1 1 1 1 1 2 3 4"] | null | Java 8 | standard input | [
"data structures",
"constructive algorithms",
"implementation",
"greedy"
] | de57b6b1aa2b6ec4686d1348988c0c63 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of $$$s$$$. The second line of the test case contains $$$n$$$ characters '0' and '1' — the string $$$s$$$. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$). | 1,500 | For each test case, print the answer: in the first line print one integer $$$k$$$ ($$$1 \le k \le n$$$) — the minimum number of subsequences you can divide the string $$$s$$$ to. In the second line print $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le k$$$), where $$$a_i$$$ is the number of subsequence the $$$i$$$-th character of $$$s$$$ belongs to. If there are several answers, you can print any. | standard output | |
PASSED | a7cd74d35e21a92799abc4070e88aae6 | train_004.jsonl | 1596638100 | You are given a binary string $$$s$$$ consisting of $$$n$$$ zeros and ones.Your task is to divide the given string into the minimum number of subsequences in such a way that each character of the string belongs to exactly one subsequence and each subsequence looks like "010101 ..." or "101010 ..." (i.e. the subsequence should not contain two adjacent zeros or ones).Recall that a subsequence is a sequence that can be derived from the given sequence by deleting zero or more elements without changing the order of the remaining elements. For example, subsequences of "1011101" are "0", "1", "11111", "0111", "101", "1001", but not "000", "101010" and "11100".You have to answer $$$t$$$ independent test cases. | 256 megabytes | import java.util.*;
import java.lang.*;
import java.io.*;
public class Codechef
{
public static void main (String[] args) throws java.lang.Exception
{
// Scanner sc=new Scanner(System.in);
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
// int t=1;
//t=sc.nextInt();
int t=Integer.parseInt(br.readLine());
while(--t>=0){
// int n=sc.nextInt();
int n=Integer.parseInt(br.readLine());
// int k=sc.nextInt();
String s=br.readLine();
int a[]=new int[n];
// StringTokenizer st=new StringTokenizer(br.readLine());
// int n=Integer.parseInt(st.nextToken());
//for(int i=0;i<n;i++)a[i]=sc.nextInt();
int c=1;
int k=1;
a[0]=1;
for(int i=1;i<n;i++){
if(s.charAt(0)=='1'){
if(s.charAt(i)=='1')
{
c++;
a[i]=c;
}
else{
a[i]=c;
c--;
}
}
if(s.charAt(0)=='0'){
if(s.charAt(i)=='0')
{
c++;
a[i]=c;
}
else{
a[i]=c;
c--;
}
}
k=Math.max(k,c);
}
int q=k;
for(int i=0;i<n;i++){
if(a[i]<=0){
a[i]=k+Math.abs(a[i])+1;
}
q=Math.max(a[i],q);
}
System.out.println(q);
for(int i=0;i<n;i++)
System.out.print(a[i]+" ");
System.out.println();
// for(int i=0;i<n;i++)
// System.out.print(arr[i]+" ");
}
}
}
| Java | ["4\n4\n0011\n6\n111111\n5\n10101\n8\n01010000"] | 2 seconds | ["2\n1 2 2 1 \n6\n1 2 3 4 5 6 \n1\n1 1 1 1 1 \n4\n1 1 1 1 1 2 3 4"] | null | Java 8 | standard input | [
"data structures",
"constructive algorithms",
"implementation",
"greedy"
] | de57b6b1aa2b6ec4686d1348988c0c63 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of $$$s$$$. The second line of the test case contains $$$n$$$ characters '0' and '1' — the string $$$s$$$. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$). | 1,500 | For each test case, print the answer: in the first line print one integer $$$k$$$ ($$$1 \le k \le n$$$) — the minimum number of subsequences you can divide the string $$$s$$$ to. In the second line print $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le k$$$), where $$$a_i$$$ is the number of subsequence the $$$i$$$-th character of $$$s$$$ belongs to. If there are several answers, you can print any. | standard output | |
PASSED | 5d9491ea4613d7171d416f789630baf8 | train_004.jsonl | 1596638100 | You are given a binary string $$$s$$$ consisting of $$$n$$$ zeros and ones.Your task is to divide the given string into the minimum number of subsequences in such a way that each character of the string belongs to exactly one subsequence and each subsequence looks like "010101 ..." or "101010 ..." (i.e. the subsequence should not contain two adjacent zeros or ones).Recall that a subsequence is a sequence that can be derived from the given sequence by deleting zero or more elements without changing the order of the remaining elements. For example, subsequences of "1011101" are "0", "1", "11111", "0111", "101", "1001", but not "000", "101010" and "11100".You have to answer $$$t$$$ independent test cases. | 256 megabytes | import java.util.*;
import java.io.*;
public class Solution{
public static void main(String[] args){
FastReader sc1 = new FastReader();
StringBuilder sb = new StringBuilder();
int tc = Integer.parseInt(sc1.nextLine());
int ch = 0;
while(ch<tc){
int n = Integer.parseInt(sc1.nextLine());
String str = sc1.nextLine();
Stack<Integer> ones = new Stack<>();
Stack<Integer> zeros = new Stack<>();
int csub = 0;
int[] res = new int[n];
for(int i=0; i<n; i++){
if(str.charAt(i) == '1'){
if(zeros.isEmpty()){
csub++;
ones.push(csub);
res[i] = csub;
}
else{
int sub = zeros.pop();
ones.push(sub);
res[i] = sub;
}
}
else{
if(ones.isEmpty()){
csub++;
zeros.push(csub);
res[i] = csub;
}
else{
int sub = ones.pop();
zeros.push(sub);
res[i] = sub;
}
}
}
sb.append(csub+"\n");
for(int i=0; i<n; i++){
sb.append(res[i]+" ");
}
sb.append("\n");
ch++;
}
System.out.print(sb.toString());
}
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\n4\n0011\n6\n111111\n5\n10101\n8\n01010000"] | 2 seconds | ["2\n1 2 2 1 \n6\n1 2 3 4 5 6 \n1\n1 1 1 1 1 \n4\n1 1 1 1 1 2 3 4"] | null | Java 8 | standard input | [
"data structures",
"constructive algorithms",
"implementation",
"greedy"
] | de57b6b1aa2b6ec4686d1348988c0c63 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of $$$s$$$. The second line of the test case contains $$$n$$$ characters '0' and '1' — the string $$$s$$$. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$). | 1,500 | For each test case, print the answer: in the first line print one integer $$$k$$$ ($$$1 \le k \le n$$$) — the minimum number of subsequences you can divide the string $$$s$$$ to. In the second line print $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le k$$$), where $$$a_i$$$ is the number of subsequence the $$$i$$$-th character of $$$s$$$ belongs to. If there are several answers, you can print any. | standard output | |
PASSED | 714e49c0d45564ef7fb834eda1236236 | train_004.jsonl | 1596638100 | You are given a binary string $$$s$$$ consisting of $$$n$$$ zeros and ones.Your task is to divide the given string into the minimum number of subsequences in such a way that each character of the string belongs to exactly one subsequence and each subsequence looks like "010101 ..." or "101010 ..." (i.e. the subsequence should not contain two adjacent zeros or ones).Recall that a subsequence is a sequence that can be derived from the given sequence by deleting zero or more elements without changing the order of the remaining elements. For example, subsequences of "1011101" are "0", "1", "11111", "0111", "101", "1001", but not "000", "101010" and "11100".You have to answer $$$t$$$ independent test cases. | 256 megabytes | //package codeforces.D1399;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.StringTokenizer;
/**
* @author muhossain
* @since 2020-08-14
*/
public class D2 {
public static void main(String[] args) {
FastReader fs = new FastReader();
int testCases = fs.nextInt();
StringBuilder output = new StringBuilder();
for (int t = 0; t < testCases; t++) {
int n = fs.nextInt();
String input = fs.nextLine();
StringBuilder result = new StringBuilder();
int totalPile = 0;
Deque<Integer> zeroQueue = new ArrayDeque<>();
Deque<Integer> oneQueue = new ArrayDeque<>();
for (int i = 0; i < n; i++) {
if (input.charAt(i) == '0') {
if (zeroQueue.isEmpty()) {
totalPile++;
result.append(totalPile).append(" ");
oneQueue.addLast(totalPile);
} else {
int zQ = zeroQueue.pollFirst();
result.append(zQ).append(" ");
oneQueue.addLast(zQ);
}
} else {
if (oneQueue.isEmpty()) {
totalPile++;
result.append(totalPile).append(" ");
zeroQueue.addLast(totalPile);
} else {
int oQ = oneQueue.pollFirst();
result.append(oQ).append(" ");
zeroQueue.addLast(oQ);
}
}
}
output.append(totalPile).append("\n");
output.append(result.substring(0, result.length())).append("\n");
}
System.out.print(output);
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
public static FastReader getFileReader(String fileName) throws FileNotFoundException {
return new FastReader(new InputStreamReader(new FileInputStream(new File(fileName))));
}
public static FastReader getDefaultReader() throws FileNotFoundException {
return new FastReader();
}
public FastReader(InputStreamReader inputStreamReader) {
br = new BufferedReader(inputStreamReader);
}
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\n4\n0011\n6\n111111\n5\n10101\n8\n01010000"] | 2 seconds | ["2\n1 2 2 1 \n6\n1 2 3 4 5 6 \n1\n1 1 1 1 1 \n4\n1 1 1 1 1 2 3 4"] | null | Java 8 | standard input | [
"data structures",
"constructive algorithms",
"implementation",
"greedy"
] | de57b6b1aa2b6ec4686d1348988c0c63 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of $$$s$$$. The second line of the test case contains $$$n$$$ characters '0' and '1' — the string $$$s$$$. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$). | 1,500 | For each test case, print the answer: in the first line print one integer $$$k$$$ ($$$1 \le k \le n$$$) — the minimum number of subsequences you can divide the string $$$s$$$ to. In the second line print $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le k$$$), where $$$a_i$$$ is the number of subsequence the $$$i$$$-th character of $$$s$$$ belongs to. If there are several answers, you can print any. | standard output | |
PASSED | c5fa9b964d555b4c056f40373a255e82 | train_004.jsonl | 1596638100 | You are given a binary string $$$s$$$ consisting of $$$n$$$ zeros and ones.Your task is to divide the given string into the minimum number of subsequences in such a way that each character of the string belongs to exactly one subsequence and each subsequence looks like "010101 ..." or "101010 ..." (i.e. the subsequence should not contain two adjacent zeros or ones).Recall that a subsequence is a sequence that can be derived from the given sequence by deleting zero or more elements without changing the order of the remaining elements. For example, subsequences of "1011101" are "0", "1", "11111", "0111", "101", "1001", but not "000", "101010" and "11100".You have to answer $$$t$$$ independent test cases. | 256 megabytes | import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.PriorityQueue;
import java.util.Scanner;
import java.util.Set;
import java.util.Stack;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;
public class Main {
static FastReader sc= new FastReader();
static List<Integer> C;
static List<Long> B;
static int mod=(int)Math.pow(10, 9)+7;
public static void main(String[] args) {
int t=sc.nextInt();
while(t-->0) {
int n=sc.nextInt();
String s=sc.next();
C=new ArrayList<>();
Stack<Integer> z=new Stack<Integer>();
Stack<Integer> o=new Stack<Integer>();
if(s.charAt(0)=='1')o.add(1);
else z.add(1);
C.add(1);
int k=2;
for(int i=1;i<n;i++) {
if(s.charAt(i)=='1') {
if(!z.isEmpty()) {
C.add(z.peek());
o.add(z.pop());
}
else {
o.add(k);
C.add(k);
k++;
}
}
else if(s.charAt(i)=='0') {
if(!o.isEmpty()) {
C.add(o.peek());
z.add(o.pop());
}
else {
//int k=z.peek()+1;
z.add(k);
C.add(k);
k++;
}
}
}
System.out.println(Collections.max(C));
for(int i=0;i<n;i++)System.out.print(C.get(i)+" ");
System.out.println();
}
}
static boolean isPossible(List<Integer> C,int m,int k) {
if(m==0)return false;
for(int i=0;i<C.size();i++) {
if(C.get(i)>m) {
k-=C.get(i)/m;
}
if(k<0)return false;
}
return true;
}
static boolean isSubsetSum(int set[], int n, int sum)
{
// The value of subset[i][j] will be
// true if there is a subset of
// set[0..j-1] with sum equal to i
boolean subset[][] = new boolean[sum + 1][n + 1];
// If sum is 0, then answer is true
for (int i = 0; i <= n; i++)
subset[0][i] = true;
// If sum is not 0 and set is empty,
// then answer is false
for (int i = 1; i <= sum; i++)
subset[i][0] = false;
// Fill the subset table in botton
// up manner
for (int i = 1; i <= sum; i++) {
for (int j = 1; j <= n; j++) {
subset[i][j] = subset[i][j - 1];
if (i >= set[j - 1])
subset[i][j] = subset[i][j]
|| subset[i - set[j - 1]][j - 1];
}
}
return subset[sum][n];
}
static boolean search(ArrayList<Integer> a,int m,int h) {
PriorityQueue<Integer> p=new PriorityQueue<Integer>(new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
// TODO Auto-generated method stub
return o2-o1;
}
});
for(int i=0;i<m;i++) {
p.add(a.get(i));
}
int c=0;
//System.out.println(p);
while(!p.isEmpty()) {
//System.out.println(p);
h-=p.poll();
if(h<0)break;
c++;
// System.out.println(h+" "+p+" "+c+" "+m);
if(!p.isEmpty()) {
p.poll();
c++;}
}
// System.out.println(c!=m);
if(c!=m)return false;
return true;
}
// static int key=-1;
static boolean isPowerOfTwo(long n)
{
if (n == 0)
return false;
while (n != 1)
{
if (n % 2 != 0)
return false;
n = n / 2;
}
return true;
}
static boolean isPerfectSquare(double x)
{
// Find floating point value of
// square root of x.
double sr = Math.sqrt(x);
// If square root is an integer
return ((sr - Math.floor(sr)) == 0);
}
static int binarySearch(ArrayList<Long> arr, int l, int r, long x,int key)
{
if (r >= l) {
int mid = (r + l) / 2;
// if(mid>=arr.size())return -1;
// If the element is present at the
// middle itself
if (arr.get(mid) == x)
return mid+1;
// If element is smaller than mid, then
// it can only be present in left subarray
if (arr.get(mid) > x) {
return binarySearch(arr, l, mid - 1, x,key);
}
// Else the element can only be present
// in right subarray
key=mid+1;
return binarySearch(arr, mid + 1, r, x,key);
}
// We reach here when element is not present
// in array
return key;
}
static boolean isPrime(long n)
{
// Corner cases
if (n <= 1)
return false;
if (n <= 3)
return true;
// This is checked so that we can skip
// middle five numbers in below loop
if (n % 2 == 0 || n % 3 == 0)
return false;
for (int i = 5; i * i <= n; i = i + 6)
if (n % i == 0 || n % (i + 2) == 0)
return false;
return true;
}
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;
}
}
}
class Sol {
int value;int in;int i;
Sol(int value,int in,int i){
this.value=value;
this.in=in;
this.i=i;
}
}
class SegmentTree {
SegNode st[];
int n;
// long arr[];
public SegmentTree(int n) {
this.n=n;
//this.arr=arr;
st=new SegNode[4*n];
}
void init(long n) {
for(int i=0;i<4*n;i++) {
st[i]=new SegNode();
}
}
void set(int i,long v,int x,int lx,int rx) {
if(rx-lx==1) {
st[x].sum=v;
st[x].max=v;
return ;
}
int m=lx+(rx-lx)/2;
if(i<m) set(i,v,2*x+1,lx,m);
else set(i,v,2*x+2,m,rx);
st[x].sum=st[2*x+1].sum+st[2*x+2].sum;
long ma=Math.max(st[2*x+1].max,st[2*x+2].max);
st[x].max=Math.max(ma,st[x].sum);
}
void set (int i,long v) {
set(i,v,0,0,n);
}
long max=Integer.MIN_VALUE;
long sum(int l,int r,int x,int lx,int rx) {
if(lx>=r||l>=rx)return 0;
if(lx>=l||rx<=r)return st[x].sum;
int m=(rx+lx)/2;
long s1=sum(l,r,2*x+1,lx,m);
long s2=sum(l,r,2*x+2,m,rx);
return max= Math.max(Math.max(Math.max(s1,s2),s1+s2),max);
}
long sum(int l,int r) {
return sum(l,r,0,0,n);
}
}
class SegNode{
long max;long sum;
public SegNode() {
// TODO Auto-generated constructor stub
sum=0;
max=Integer.MIN_VALUE;
}
}
| Java | ["4\n4\n0011\n6\n111111\n5\n10101\n8\n01010000"] | 2 seconds | ["2\n1 2 2 1 \n6\n1 2 3 4 5 6 \n1\n1 1 1 1 1 \n4\n1 1 1 1 1 2 3 4"] | null | Java 8 | standard input | [
"data structures",
"constructive algorithms",
"implementation",
"greedy"
] | de57b6b1aa2b6ec4686d1348988c0c63 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of $$$s$$$. The second line of the test case contains $$$n$$$ characters '0' and '1' — the string $$$s$$$. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$). | 1,500 | For each test case, print the answer: in the first line print one integer $$$k$$$ ($$$1 \le k \le n$$$) — the minimum number of subsequences you can divide the string $$$s$$$ to. In the second line print $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le k$$$), where $$$a_i$$$ is the number of subsequence the $$$i$$$-th character of $$$s$$$ belongs to. If there are several answers, you can print any. | standard output | |
PASSED | 6e11bd0f7fcb5e0cfa51812f617910a2 | train_004.jsonl | 1525791900 | The city of Fishtopia can be imagined as a grid of $$$4$$$ rows and an odd number of columns. It has two main villages; the first is located at the top-left cell $$$(1,1)$$$, people who stay there love fishing at the Tuna pond at the bottom-right cell $$$(4, n)$$$. The second village is located at $$$(4, 1)$$$ and its people love the Salmon pond at $$$(1, n)$$$.The mayor of Fishtopia wants to place $$$k$$$ hotels in the city, each one occupying one cell. To allow people to enter the city from anywhere, hotels should not be placed on the border cells.A person can move from one cell to another if those cells are not occupied by hotels and share a side.Can you help the mayor place the hotels in a way such that there are equal number of shortest paths from each village to its preferred pond? | 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 llamaoo7
*/
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);
BMarlin solver = new BMarlin();
solver.solve(1, in, out);
out.close();
}
static class BMarlin {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
int k = in.nextInt();
char[][] city = new char[4][n];
for (int j = 0; j < 4; j++)
for (int i = 0; i < n; i++) {
city[j][i] = '.';
}
int p = 0;
while (k > 2) {
city[1 + p % 2][1 + p / 2] = '#';
city[1 + p % 2][n - 2 - p / 2] = '#';
p += 1;
k -= 2;
}
if (k >= 1) {
city[1][n / 2] = '#';
}
if (k == 2) city[2][n / 2] = '#';
out.println("YES");
for (int i = 0; i < 4; i++) out.println(city[i]);
}
}
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 | ["7 2", "5 3"] | 1 second | ["YES\n.......\n.#.....\n.#.....\n.......", "YES\n.....\n.###.\n.....\n....."] | null | Java 8 | standard input | [
"constructive algorithms"
] | 2669feb8200769869c4b2c29012059ed | The first line of input contain two integers, $$$n$$$ and $$$k$$$ ($$$3 \leq n \leq 99$$$, $$$0 \leq k \leq 2\times(n-2)$$$), $$$n$$$ is odd, the width of the city, and the number of hotels to be placed, respectively. | 1,600 | Print "YES", if it is possible to place all the hotels in a way that satisfies the problem statement, otherwise print "NO". If it is possible, print an extra $$$4$$$ lines that describe the city, each line should have $$$n$$$ characters, each of which is "#" if that cell has a hotel on it, or "." if not. | standard output | |
PASSED | fc842002aea87349ee30d2ed8de355f9 | train_004.jsonl | 1525791900 | The city of Fishtopia can be imagined as a grid of $$$4$$$ rows and an odd number of columns. It has two main villages; the first is located at the top-left cell $$$(1,1)$$$, people who stay there love fishing at the Tuna pond at the bottom-right cell $$$(4, n)$$$. The second village is located at $$$(4, 1)$$$ and its people love the Salmon pond at $$$(1, n)$$$.The mayor of Fishtopia wants to place $$$k$$$ hotels in the city, each one occupying one cell. To allow people to enter the city from anywhere, hotels should not be placed on the border cells.A person can move from one cell to another if those cells are not occupied by hotels and share a side.Can you help the mayor place the hotels in a way such that there are equal number of shortest paths from each village to its preferred pond? | 256 megabytes | import java.io.*;
import java.util.*;
public class TaskB
{
public static void main(String[] args)
{
new TaskB(System.in, System.out);
}
static class Solver implements Runnable
{
int n, k;
// BufferedReader in;
InputReader in;
PrintWriter out;
void solve() throws IOException
{
n = in.nextInt();
k = in.nextInt();
int tot = 4 * n;
tot -= 2 * n;
tot -= 4;
if (k > tot)
out.println("NO");
else
{
char[][] mat = new char[4][n];
for (int i = 0; i < 4; i++)
Arrays.fill(mat[i], '.');
boolean left = true;
for (int i = 1, j = n - 2; i <= j && k > 0; )
{
// System.out.println("i : " + i + ", j : " + j + ", k : " + k);
if (k > 3)
{
mat[1][i] = mat[2][i] = '#';
i++;
mat[1][j] = mat[2][j] = '#';
j--;
k -= 4;
}
else if (k == 3)
{
if (n / 2 == 1)
{
out.println("NO");
return;
}
mat[1][n / 2] = mat[1][n / 2 - 1] = mat[1][n / 2 + 1] = '#';
k -= 3;
}
else if (k == 2)
{
mat[1][n / 2] = mat[2][n / 2] = '#';
k -= 2;
}
else
{
mat[1][n / 2] = '#';
k--;
}
left = !left;
}
out.println("YES");
for (int i = 0; i < 4; i++, out.println())
for (int j = 0; j < n; j++)
out.print(mat[i][j]);
}
}
void debug(Object... o)
{
System.err.println(Arrays.deepToString(o));
}
// uncomment below line to change to BufferedReader
// public Solver(BufferedReader in, PrintWriter out)
public Solver(InputReader in, PrintWriter out)
{
this.in = in;
this.out = out;
}
@Override public void run()
{
try
{
solve();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
static class InputReader
{
private InputStream stream;
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 = stream.read(buf);
}
catch (IOException e)
{
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt()
{
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
int res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c & 15;
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int arraySize)
{
int array[] = new int[arraySize];
for (int i = 0; i < arraySize; i++)
array[i] = nextInt();
return array;
}
public long nextLong()
{
int c = read();
while (isSpaceChar(c))
c = read();
int sign = 1;
if (c == '-')
{
sign = -1;
c = read();
}
long result = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
result *= 10;
result += c & 15;
c = read();
} while (!isSpaceChar(c));
return result * sign;
}
public long[] nextLongArray(int arraySize)
{
long array[] = new long[arraySize];
for (int i = 0; i < arraySize; i++)
array[i] = nextLong();
return array;
}
public float nextFloat()
{
float result, div;
byte c;
result = 0;
div = 1;
c = (byte) read();
while (c <= ' ')
c = (byte) read();
boolean isNegative = (c == '-');
if (isNegative)
c = (byte) read();
do
{
result = result * 10 + c - '0';
} while ((c = (byte) read()) >= '0' && c <= '9');
if (c == '.')
while ((c = (byte) read()) >= '0' && c <= '9')
result += (c - '0') / (div *= 10);
if (isNegative)
return -result;
return result;
}
public double nextDouble()
{
double ret = 0, div = 1;
byte c = (byte) read();
while (c <= ' ')
c = (byte) read();
boolean neg = (c == '-');
if (neg)
c = (byte) read();
do
{
ret = ret * 10 + c - '0';
} while ((c = (byte) read()) >= '0' && c <= '9');
if (c == '.')
while ((c = (byte) read()) >= '0' && c <= '9')
ret += (c - '0') / (div *= 10);
if (neg)
return -ret;
return ret;
}
public String next()
{
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public String nextLine()
{
int c = read();
StringBuilder result = new StringBuilder();
do
{
result.appendCodePoint(c);
c = read();
} while (!isNewLine(c));
return result.toString();
}
public boolean isNewLine(int c)
{
return c == '\n';
}
public boolean isSpaceChar(int c)
{
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public void close()
{
try
{
stream.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
public InputReader(InputStream stream)
{
this.stream = stream;
}
}
static class CMath
{
static long power(long number, long power)
{
if (number == 1 || number == 0 || power == 0)
return 1;
if (power == 1)
return number;
if (power % 2 == 0)
return power(number * number, power / 2);
else
return power(number * number, power / 2) * number;
}
static long modPower(long number, long power, long mod)
{
if (number == 1 || number == 0 || power == 0)
return 1;
number = mod(number, mod);
if (power == 1)
return number;
long square = mod(number * number, mod);
if (power % 2 == 0)
return modPower(square, power / 2, mod);
else
return mod(modPower(square, power / 2, mod) * number, mod);
}
static long moduloInverse(long number, long mod)
{
return modPower(number, mod - 2, mod);
}
static long mod(long number, long mod)
{
return number - (number / mod) * mod;
}
static int gcd(int a, int b)
{
if (b == 0)
return a;
else
return gcd(b, a % b);
}
static long min(long... arr)
{
long min = arr[0];
for (int i = 1; i < arr.length; i++)
min = Math.min(min, arr[i]);
return min;
}
static long max(long... arr)
{
long max = arr[0];
for (int i = 1; i < arr.length; i++)
max = Math.max(max, arr[i]);
return max;
}
static int min(int... arr)
{
int min = arr[0];
for (int i = 1; i < arr.length; i++)
min = Math.min(min, arr[i]);
return min;
}
static int max(int... arr)
{
int max = arr[0];
for (int i = 1; i < arr.length; i++)
max = Math.max(max, arr[i]);
return max;
}
}
static class Utils
{
static boolean nextPermutation(int[] arr)
{
for (int a = arr.length - 2; a >= 0; --a)
{
if (arr[a] < arr[a + 1])
{
for (int b = arr.length - 1; ; --b)
{
if (arr[b] > arr[a])
{
int t = arr[a];
arr[a] = arr[b];
arr[b] = t;
for (++a, b = arr.length - 1; a < b; ++a, --b)
{
t = arr[a];
arr[a] = arr[b];
arr[b] = t;
}
return true;
}
}
}
}
return false;
}
}
public TaskB(InputStream inputStream, OutputStream outputStream)
{
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
Thread thread = new Thread(null, new Solver(in, out), "TaskB", 1 << 29);
try
{
thread.start();
thread.join();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
finally
{
in.close();
out.flush();
out.close();
}
}
}
/*
11 17
5 5
*/
| Java | ["7 2", "5 3"] | 1 second | ["YES\n.......\n.#.....\n.#.....\n.......", "YES\n.....\n.###.\n.....\n....."] | null | Java 8 | standard input | [
"constructive algorithms"
] | 2669feb8200769869c4b2c29012059ed | The first line of input contain two integers, $$$n$$$ and $$$k$$$ ($$$3 \leq n \leq 99$$$, $$$0 \leq k \leq 2\times(n-2)$$$), $$$n$$$ is odd, the width of the city, and the number of hotels to be placed, respectively. | 1,600 | Print "YES", if it is possible to place all the hotels in a way that satisfies the problem statement, otherwise print "NO". If it is possible, print an extra $$$4$$$ lines that describe the city, each line should have $$$n$$$ characters, each of which is "#" if that cell has a hotel on it, or "." if not. | standard output | |
PASSED | aa56e723473bd7a8b59b9e72b2197791 | train_004.jsonl | 1525791900 | The city of Fishtopia can be imagined as a grid of $$$4$$$ rows and an odd number of columns. It has two main villages; the first is located at the top-left cell $$$(1,1)$$$, people who stay there love fishing at the Tuna pond at the bottom-right cell $$$(4, n)$$$. The second village is located at $$$(4, 1)$$$ and its people love the Salmon pond at $$$(1, n)$$$.The mayor of Fishtopia wants to place $$$k$$$ hotels in the city, each one occupying one cell. To allow people to enter the city from anywhere, hotels should not be placed on the border cells.A person can move from one cell to another if those cells are not occupied by hotels and share a side.Can you help the mayor place the hotels in a way such that there are equal number of shortest paths from each village to its preferred pond? | 256 megabytes | import java.util.Scanner;
public class B_Marlin {
private static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
int n = scanner.nextInt();
int k = scanner.nextInt();
String dot = "";
for (int i = 0; i < n; i++) {
dot += ".";
}
String hotelAndDot = ".";
if (k % 2 == 0) {
// Correct
System.out.println("YES");
System.out.println(dot);
System.out.println(evenK(n, k));
System.out.println(evenK(n, k));
System.out.println(dot);
} else if (k < 2 * (n - 2)) {
System.out.println("YES");
System.out.println(dot);
hotelAndDot = ".";
if (k <= n - 2) {
System.out.println(f(n,k));
System.out.println(dot);
System.out.println(dot);
} else {
String hotel = ".";
for (int i = 0; i < n-2; i++) {
hotel+="#";
}
hotel+=".";
System.out.println(hotel);
k = k - (n - 2);
hotelAndDot = ".";
int remainDot = (n - 2) - k;
hotel = "";
for (int i = 0; i < k/2; i++) {
hotel += "#";
}
String remainDotString = "";
for (int i = 0; i < remainDot / 2; i++) {
remainDotString += ".";
}
hotelAndDot += hotel;
hotelAndDot += remainDotString;
hotelAndDot+=".";
hotelAndDot += remainDotString;
hotelAndDot += hotel;
hotelAndDot += ".";
System.out.println(hotelAndDot);
System.out.println(dot);
}
} else {
System.out.println("NO");
}
}
private static String f(int n, int k) {
String hotelAndDot = ".";
int k2 = (k - 1) / 2;
int remainDot = (n - 2) - k;
String hotel = "";
for (int i = 0; i < k2; i++) {
hotel += "#";
}
String remainDotString = "";
for (int i = 0; i < remainDot / 2; i++) {
remainDotString += ".";
}
hotelAndDot += hotel;
hotelAndDot += remainDotString;
hotelAndDot += "#";
hotelAndDot += remainDotString;
hotelAndDot += hotel;
hotelAndDot += ".";
return hotelAndDot;
}
private static String evenK(int n, int k) {
String hotelAndDot = ".";
for (int i = 0; i < k / 2; i++) {
hotelAndDot += "#";
}
for (int i = 0; i < (n - 2) - (k / 2); i++) {
hotelAndDot += ".";
}
hotelAndDot += ".";
return hotelAndDot;
}
}
| Java | ["7 2", "5 3"] | 1 second | ["YES\n.......\n.#.....\n.#.....\n.......", "YES\n.....\n.###.\n.....\n....."] | null | Java 8 | standard input | [
"constructive algorithms"
] | 2669feb8200769869c4b2c29012059ed | The first line of input contain two integers, $$$n$$$ and $$$k$$$ ($$$3 \leq n \leq 99$$$, $$$0 \leq k \leq 2\times(n-2)$$$), $$$n$$$ is odd, the width of the city, and the number of hotels to be placed, respectively. | 1,600 | Print "YES", if it is possible to place all the hotels in a way that satisfies the problem statement, otherwise print "NO". If it is possible, print an extra $$$4$$$ lines that describe the city, each line should have $$$n$$$ characters, each of which is "#" if that cell has a hotel on it, or "." if not. | standard output | |
PASSED | edc6f01ad983c0aa6cf3bb5b31a8481a | train_004.jsonl | 1525791900 | The city of Fishtopia can be imagined as a grid of $$$4$$$ rows and an odd number of columns. It has two main villages; the first is located at the top-left cell $$$(1,1)$$$, people who stay there love fishing at the Tuna pond at the bottom-right cell $$$(4, n)$$$. The second village is located at $$$(4, 1)$$$ and its people love the Salmon pond at $$$(1, n)$$$.The mayor of Fishtopia wants to place $$$k$$$ hotels in the city, each one occupying one cell. To allow people to enter the city from anywhere, hotels should not be placed on the border cells.A person can move from one cell to another if those cells are not occupied by hotels and share a side.Can you help the mayor place the hotels in a way such that there are equal number of shortest paths from each village to its preferred pond? | 256 megabytes |
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int n = s.nextInt(), k = s.nextInt();
char[][] arr = new char[4][n];
for(int i = 0; i < arr.length; i++){
for(int j = 0; j < arr[0].length; j++){
arr[i][j] = '.';
}
}
/* if(k == 2 * (n - 2)){
System.out.println("NO");
return;
}*/
if(k % 2 == 1){
int center = n / 2;
if(k > n - 2){
int def = 1;
for(int i = 1; i < n - 1; i++){
arr[1][i] = '#';
}
k -= n - 2;
int i = 1;
while(k > 0){
arr[2][i] = arr[2][n - i - 1] = '#';
k -= 2;
i++;
}
}else{
int def = 1;
arr[1][center] = '#';
k--;
while(k > 0 && center - def > 0){
arr[1][center - def] = '#';
k--;
arr[1][center + def] = '#';
k--;
def++;
}
}
}else{
for(int i = 1; i <= k / 2; i++){
arr[1][i] = arr[2][i] = '#';
}
}
System.out.println("YES");
for(int i = 0; i < 4; i++){
for(int j = 0; j < n; j++){
System.out.print(arr[i][j]);
}
System.out.println();
}
}
}
| Java | ["7 2", "5 3"] | 1 second | ["YES\n.......\n.#.....\n.#.....\n.......", "YES\n.....\n.###.\n.....\n....."] | null | Java 8 | standard input | [
"constructive algorithms"
] | 2669feb8200769869c4b2c29012059ed | The first line of input contain two integers, $$$n$$$ and $$$k$$$ ($$$3 \leq n \leq 99$$$, $$$0 \leq k \leq 2\times(n-2)$$$), $$$n$$$ is odd, the width of the city, and the number of hotels to be placed, respectively. | 1,600 | Print "YES", if it is possible to place all the hotels in a way that satisfies the problem statement, otherwise print "NO". If it is possible, print an extra $$$4$$$ lines that describe the city, each line should have $$$n$$$ characters, each of which is "#" if that cell has a hotel on it, or "." if not. | standard output | |
PASSED | ef0eccc0ea2ba4536c9a7390962583b6 | train_004.jsonl | 1525791900 | The city of Fishtopia can be imagined as a grid of $$$4$$$ rows and an odd number of columns. It has two main villages; the first is located at the top-left cell $$$(1,1)$$$, people who stay there love fishing at the Tuna pond at the bottom-right cell $$$(4, n)$$$. The second village is located at $$$(4, 1)$$$ and its people love the Salmon pond at $$$(1, n)$$$.The mayor of Fishtopia wants to place $$$k$$$ hotels in the city, each one occupying one cell. To allow people to enter the city from anywhere, hotels should not be placed on the border cells.A person can move from one cell to another if those cells are not occupied by hotels and share a side.Can you help the mayor place the hotels in a way such that there are equal number of shortest paths from each village to its preferred pond? | 256 megabytes | import java.util.Scanner;
/*
3 4 2
1 3 3 3
0 3 3 2
3 0 1 1
*/
public class Main {
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
int rows=4;
int columns=s.nextInt();
int k=s.nextInt();
int available=rows*columns-(2*(rows+columns)-4);
if(k>available){
System.out.println("NO");
}else if(k==available){
System.out.println("YES");
StringBuilder str=new StringBuilder("");
for(int i=0;i<columns;i++){
str.append(".");
}
System.out.println(str);
for(int j=1;j<3;j++){
StringBuilder ansStr=new StringBuilder("");
for(int i=0;i<columns;i++) {
if(i==0||i==columns-1){
ansStr.append(".");
}else {
ansStr.append("#");
}
}
System.out.println(ansStr);
}
System.out.println(str);
}
else if(k==available-1){
System.out.println("YES");
StringBuilder str=new StringBuilder("");
for(int i=0;i<columns;i++){
str.append(".");
}
System.out.println(str);
for(int j=1;j<2;j++){
StringBuilder ansStr=new StringBuilder("");
for(int i=0;i<columns;i++) {
if(i==0||i==columns-1){
ansStr.append(".");
}else {
ansStr.append("#");
}
}
System.out.println(ansStr);
}
int middle=((columns+1)/2) -1;
for(int j=1;j<2;j++){
StringBuilder ansStr=new StringBuilder("");
for(int i=0;i<columns;i++) {
if(i==0||i==columns-1){
ansStr.append(".");
}else if(i==middle){
ansStr.append(".");
}else {
ansStr.append("#");
}
}
System.out.println(ansStr);
}
System.out.println(str);
}else {
System.out.println("YES");
StringBuilder str=new StringBuilder("");
for(int i=0;i<columns;i++){
str.append(".");
}
int half=k/2;
int extra=k-half*2;
int middle=((columns+1)/2) -1;
System.out.println(str);
for(int j=1;j<3;j++){
StringBuilder ansStr=new StringBuilder("");
int i=0;
for(;i<middle;i++){
if(i==0){
ansStr.append(".");
}else if(half>0){
ansStr.append("#");
half--;
}else {
ansStr.append(".");
}
}
StringBuilder temp=new StringBuilder(ansStr);
ansStr.reverse();
if(extra>0){
temp.append("#");
extra--;
}else {
temp.append(".");
}
temp.append(ansStr);
System.out.println(temp);
}
System.out.println(str);
}
}
}
| Java | ["7 2", "5 3"] | 1 second | ["YES\n.......\n.#.....\n.#.....\n.......", "YES\n.....\n.###.\n.....\n....."] | null | Java 8 | standard input | [
"constructive algorithms"
] | 2669feb8200769869c4b2c29012059ed | The first line of input contain two integers, $$$n$$$ and $$$k$$$ ($$$3 \leq n \leq 99$$$, $$$0 \leq k \leq 2\times(n-2)$$$), $$$n$$$ is odd, the width of the city, and the number of hotels to be placed, respectively. | 1,600 | Print "YES", if it is possible to place all the hotels in a way that satisfies the problem statement, otherwise print "NO". If it is possible, print an extra $$$4$$$ lines that describe the city, each line should have $$$n$$$ characters, each of which is "#" if that cell has a hotel on it, or "." if not. | standard output | |
PASSED | 6155d94688174c06695172b66f04156d | train_004.jsonl | 1525791900 | The city of Fishtopia can be imagined as a grid of $$$4$$$ rows and an odd number of columns. It has two main villages; the first is located at the top-left cell $$$(1,1)$$$, people who stay there love fishing at the Tuna pond at the bottom-right cell $$$(4, n)$$$. The second village is located at $$$(4, 1)$$$ and its people love the Salmon pond at $$$(1, n)$$$.The mayor of Fishtopia wants to place $$$k$$$ hotels in the city, each one occupying one cell. To allow people to enter the city from anywhere, hotels should not be placed on the border cells.A person can move from one cell to another if those cells are not occupied by hotels and share a side.Can you help the mayor place the hotels in a way such that there are equal number of shortest paths from each village to its preferred pond? | 256 megabytes | import java.io.*;
import java.util.Arrays;
import java.util.StringJoiner;
import java.util.StringTokenizer;
import java.util.function.Function;
public class Main {
static int N, K;
public static void main(String[] args) {
FastScanner sc = new FastScanner(System.in);
N = sc.nextInt();
K = sc.nextInt();
PrintWriter pw = new PrintWriter(System.out);
char[][] ans = solve();
if( ans != null ) {
pw.println("YES");
for (char[] row : ans) {
pw.println( new String(row) );
}
} else {
pw.println("NO");
}
pw.flush();
}
static char[][] solve() {
char[][] ans = new char[4][N];
for (char[] row : ans) {
Arrays.fill(row, '.');
}
if( K == 0 ) return ans;
if( K % 2 == 0 ) {
ans[1][N/2] = '#';
ans[2][N/2] = '#';
K -= 2;
} else {
ans[1][N/2] = '#';
K -= 1;
}
int half = (N-2)/2;
for (int i = 0; i < K/2; i++) {
int row = i < half ? 1 : 2;
int col = i % half + 1;
ans[row][col] = '#';
ans[row][N-col-1] = '#'; // opposite
}
return ans;
}
@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 <A> void writeLines(A[] as, Function<A, String> f) {
PrintWriter pw = new PrintWriter(System.out);
for (A a : as) {
pw.println(f.apply(a));
}
pw.flush();
}
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 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.toString());
}
System.err.println(j.toString());
}
}
| Java | ["7 2", "5 3"] | 1 second | ["YES\n.......\n.#.....\n.#.....\n.......", "YES\n.....\n.###.\n.....\n....."] | null | Java 8 | standard input | [
"constructive algorithms"
] | 2669feb8200769869c4b2c29012059ed | The first line of input contain two integers, $$$n$$$ and $$$k$$$ ($$$3 \leq n \leq 99$$$, $$$0 \leq k \leq 2\times(n-2)$$$), $$$n$$$ is odd, the width of the city, and the number of hotels to be placed, respectively. | 1,600 | Print "YES", if it is possible to place all the hotels in a way that satisfies the problem statement, otherwise print "NO". If it is possible, print an extra $$$4$$$ lines that describe the city, each line should have $$$n$$$ characters, each of which is "#" if that cell has a hotel on it, or "." if not. | standard output | |
PASSED | 8b7be1d3de12fc15b56643beedc55841 | train_004.jsonl | 1525791900 | The city of Fishtopia can be imagined as a grid of $$$4$$$ rows and an odd number of columns. It has two main villages; the first is located at the top-left cell $$$(1,1)$$$, people who stay there love fishing at the Tuna pond at the bottom-right cell $$$(4, n)$$$. The second village is located at $$$(4, 1)$$$ and its people love the Salmon pond at $$$(1, n)$$$.The mayor of Fishtopia wants to place $$$k$$$ hotels in the city, each one occupying one cell. To allow people to enter the city from anywhere, hotels should not be placed on the border cells.A person can move from one cell to another if those cells are not occupied by hotels and share a side.Can you help the mayor place the hotels in a way such that there are equal number of shortest paths from each village to its preferred pond? | 256 megabytes |
import java.util.Scanner;
public class B {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int k = in.nextInt();
System.out.println("YES");
if((k % (n - 2)) == 0) {
print(n, '.');
System.out.println();
int r = k / (n - 2);
for(int i = 0; i < r; i++) {
System.out.print('.');
print(n - 2, '#');
System.out.println('.');
}
for(int i = 0; i < 4 - r - 1; i++) {
print(n, '.');
System.out.println();
}
} else if(k % 2 == 0) {
print(n, '.');
System.out.println();
int r = k / 2;
for(int i = 0; i < 2; i++) {
System.out.print('.');
print(r, '#');
print(n - r - 2, '.');
System.out.println('.');
}
print(n, '.');
System.out.println();
} else if(k <= n - 2 && k % 2 == 1) {
print(n, '.');
System.out.println();
print((n - k) / 2, '.');
print(k, '#');
print((n - k) / 2, '.');
System.out.println();
print(n, '.');
System.out.println();
print(n, '.');
System.out.println();
} else {
print(n, '.');
System.out.println();
print(1, '.');
print(n - 2, '#');
System.out.println('.');
k -= n - 2;
print((n - k) / 2, '.');
print(k - 1, '#');
print(1, '.');
print(1, '#');
print((n - k) / 2, '.');
System.out.println();
print(n, '.');
System.out.println();
}
in.close();
}
static void print(int n, char c) {
for(int i = 0; i < n; i++) {
System.out.print(c);
}
}
} | Java | ["7 2", "5 3"] | 1 second | ["YES\n.......\n.#.....\n.#.....\n.......", "YES\n.....\n.###.\n.....\n....."] | null | Java 8 | standard input | [
"constructive algorithms"
] | 2669feb8200769869c4b2c29012059ed | The first line of input contain two integers, $$$n$$$ and $$$k$$$ ($$$3 \leq n \leq 99$$$, $$$0 \leq k \leq 2\times(n-2)$$$), $$$n$$$ is odd, the width of the city, and the number of hotels to be placed, respectively. | 1,600 | Print "YES", if it is possible to place all the hotels in a way that satisfies the problem statement, otherwise print "NO". If it is possible, print an extra $$$4$$$ lines that describe the city, each line should have $$$n$$$ characters, each of which is "#" if that cell has a hotel on it, or "." if not. | standard output | |
PASSED | 0faa70e64e907849aaf306fda3fa8a94 | train_004.jsonl | 1525791900 | The city of Fishtopia can be imagined as a grid of $$$4$$$ rows and an odd number of columns. It has two main villages; the first is located at the top-left cell $$$(1,1)$$$, people who stay there love fishing at the Tuna pond at the bottom-right cell $$$(4, n)$$$. The second village is located at $$$(4, 1)$$$ and its people love the Salmon pond at $$$(1, n)$$$.The mayor of Fishtopia wants to place $$$k$$$ hotels in the city, each one occupying one cell. To allow people to enter the city from anywhere, hotels should not be placed on the border cells.A person can move from one cell to another if those cells are not occupied by hotels and share a side.Can you help the mayor place the hotels in a way such that there are equal number of shortest paths from each village to its preferred pond? | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
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 Vadim
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastScanner in = new FastScanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
B solver = new B();
solver.solve(1, in, out);
out.close();
}
static class B {
public void solve(int testNumber, FastScanner in, PrintWriter out) {
int n = in.ni(), k = in.ni();
char[][] map = new char[4][n];
for (int i = 0; i < 4; i++) {
Arrays.fill(map[i], '.');
}
if (k % 2 == 0) {
for (int i = 0; i < k / 2; i++) {
map[1][i + 1] = map[2][i + 1] = '#';
}
} else if (k > 3) {
for (int i = 0; i < k / 2 + 1; i++) {
map[1][i + 1] = map[2][i + 1] = '#';
}
map[1][k / 2] = '.';
} else if (k == 3) {
map[1][n / 2] = map[1][n / 2 - 1] = map[1][n / 2 + 1] = '#';
} else if (k == 1) {
map[1][n / 2] = '#';
} else throw new RuntimeException("Shouldn't be reachable");
out.println("YES");
for (int i = 0; i < 4; i++) {
out.println(String.valueOf(map[i]));
}
}
}
static class FastScanner {
private BufferedReader in;
private StringTokenizer st;
public FastScanner(InputStream stream) {
in = new BufferedReader(new InputStreamReader(stream));
}
public String ns() {
while (st == null || !st.hasMoreTokens()) {
try {
String rl = in.readLine();
if (rl == null) {
return null;
}
st = new StringTokenizer(rl);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return st.nextToken();
}
public int ni() {
return Integer.parseInt(ns());
}
}
}
| Java | ["7 2", "5 3"] | 1 second | ["YES\n.......\n.#.....\n.#.....\n.......", "YES\n.....\n.###.\n.....\n....."] | null | Java 8 | standard input | [
"constructive algorithms"
] | 2669feb8200769869c4b2c29012059ed | The first line of input contain two integers, $$$n$$$ and $$$k$$$ ($$$3 \leq n \leq 99$$$, $$$0 \leq k \leq 2\times(n-2)$$$), $$$n$$$ is odd, the width of the city, and the number of hotels to be placed, respectively. | 1,600 | Print "YES", if it is possible to place all the hotels in a way that satisfies the problem statement, otherwise print "NO". If it is possible, print an extra $$$4$$$ lines that describe the city, each line should have $$$n$$$ characters, each of which is "#" if that cell has a hotel on it, or "." if not. | standard output | |
PASSED | 5dbaa648222f207855b7bd45d6588560 | train_004.jsonl | 1525791900 | The city of Fishtopia can be imagined as a grid of $$$4$$$ rows and an odd number of columns. It has two main villages; the first is located at the top-left cell $$$(1,1)$$$, people who stay there love fishing at the Tuna pond at the bottom-right cell $$$(4, n)$$$. The second village is located at $$$(4, 1)$$$ and its people love the Salmon pond at $$$(1, n)$$$.The mayor of Fishtopia wants to place $$$k$$$ hotels in the city, each one occupying one cell. To allow people to enter the city from anywhere, hotels should not be placed on the border cells.A person can move from one cell to another if those cells are not occupied by hotels and share a side.Can you help the mayor place the hotels in a way such that there are equal number of shortest paths from each village to its preferred pond? | 256 megabytes |
import java.util.*;
import java.io.*;
public class B {
static void go() {
int n = in.nextInt(), k = in.nextInt();
char[][] ans = new char[4][n];
for (char[] l : ans) Arrays.fill(l, '.');
for (int r = 1; r <= 2; r++)
for (int i = 1, j = n - 2; i < j - 1 && k > 1; i++, j--) {
ans[r][i] = ans[r][j] = '#';
k -= 2;
}
if (k == 1) {
ans[1][n / 2] = '#';
} else if (k == 2) {
ans[1][n / 2] = ans[2][n / 2] = '#';
}
out.println("YES");
for (char[] l : ans)
out.println(l);
}
static InputReader in;
static PrintWriter out;
public static void main(String[] args) {
in = new InputReader(System.in);
out = new PrintWriter(System.out);
go();
out.close();
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int[] nextIntArray(int len) {
int[] ret = new int[len];
for (int i = 0; i < len; i++)
ret[i] = nextInt();
return ret;
}
public long[] nextLongArray(int len) {
long[] ret = new long[len];
for (int i = 0; i < len; i++)
ret[i] = nextLong();
return ret;
}
public int nextInt() {
return (int) nextLong();
}
public long nextLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String nextLine() {
StringBuilder sb = new StringBuilder(1024);
int c = read();
while (!(c == '\n' || c == '\r' || c == -1)) {
sb.append((char) c);
c = read();
}
return sb.toString();
}
public char nextChar() {
int c = read();
while (isSpaceChar(c))
c = read();
return (char) c;
}
public String nextString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder sb = new StringBuilder(1024);
do {
sb.append((char) c);
c = read();
} while (!isSpaceChar(c));
return sb.toString();
}
public char[] nextCharArray(int n) {
char[] ca = new char[n];
for (int i = 0; i < n; i++) {
int c = read();
while (isSpaceChar(c))
c = read();
ca[i] = (char) c;
}
return ca;
}
public static boolean isSpaceChar(int c) {
switch (c) {
case -1:
case ' ':
case '\n':
case '\r':
case '\t':
return true;
default:
return false;
}
}
}
} | Java | ["7 2", "5 3"] | 1 second | ["YES\n.......\n.#.....\n.#.....\n.......", "YES\n.....\n.###.\n.....\n....."] | null | Java 8 | standard input | [
"constructive algorithms"
] | 2669feb8200769869c4b2c29012059ed | The first line of input contain two integers, $$$n$$$ and $$$k$$$ ($$$3 \leq n \leq 99$$$, $$$0 \leq k \leq 2\times(n-2)$$$), $$$n$$$ is odd, the width of the city, and the number of hotels to be placed, respectively. | 1,600 | Print "YES", if it is possible to place all the hotels in a way that satisfies the problem statement, otherwise print "NO". If it is possible, print an extra $$$4$$$ lines that describe the city, each line should have $$$n$$$ characters, each of which is "#" if that cell has a hotel on it, or "." if not. | standard output | |
PASSED | 3f0191c207a8c1d37a71862b8f7ea0cf | train_004.jsonl | 1525791900 | The city of Fishtopia can be imagined as a grid of $$$4$$$ rows and an odd number of columns. It has two main villages; the first is located at the top-left cell $$$(1,1)$$$, people who stay there love fishing at the Tuna pond at the bottom-right cell $$$(4, n)$$$. The second village is located at $$$(4, 1)$$$ and its people love the Salmon pond at $$$(1, n)$$$.The mayor of Fishtopia wants to place $$$k$$$ hotels in the city, each one occupying one cell. To allow people to enter the city from anywhere, hotels should not be placed on the border cells.A person can move from one cell to another if those cells are not occupied by hotels and share a side.Can you help the mayor place the hotels in a way such that there are equal number of shortest paths from each village to its preferred pond? | 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
*/
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);
BMarlin solver = new BMarlin();
solver.solve(1, in, out);
out.close();
}
static class BMarlin {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.readInt();
int k = in.readInt();
out.println("YES");
for (int i = 0; i < n; i++) out.print('.');
out.println();
if (k % 2 == 0) {
for (int i = 0; i < 2; i++) {
for (int j = 0; j < n; j++) {
if (j > 0 && j <= k / 2) out.print('#');
else out.print('.');
}
out.println();
}
for (int i = 0; i < n; i++) out.print('.');
} else {
for (int j = 0; j < n; j++) {
int v = Math.min(k, n - 2);
if (j >= n / 2 - v / 2 && j <= n / 2 + v / 2) out.print('#');
else out.print('.');
}
out.println();
for (int i = 0; i < n; i++) {
if (i > 0 && k > n - 2 && i <= k - (n - 2) - 1) out.print('#');
else if (k > n - 2 && i == n - 2) out.print('#');
else out.print('.');
}
out.println();
for (int i = 0; i < n; i++) out.print('.');
}
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int readInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
| Java | ["7 2", "5 3"] | 1 second | ["YES\n.......\n.#.....\n.#.....\n.......", "YES\n.....\n.###.\n.....\n....."] | null | Java 8 | standard input | [
"constructive algorithms"
] | 2669feb8200769869c4b2c29012059ed | The first line of input contain two integers, $$$n$$$ and $$$k$$$ ($$$3 \leq n \leq 99$$$, $$$0 \leq k \leq 2\times(n-2)$$$), $$$n$$$ is odd, the width of the city, and the number of hotels to be placed, respectively. | 1,600 | Print "YES", if it is possible to place all the hotels in a way that satisfies the problem statement, otherwise print "NO". If it is possible, print an extra $$$4$$$ lines that describe the city, each line should have $$$n$$$ characters, each of which is "#" if that cell has a hotel on it, or "." if not. | standard output | |
PASSED | d71bbbd13e0c801f51f87a76411ad404 | train_004.jsonl | 1525791900 | The city of Fishtopia can be imagined as a grid of $$$4$$$ rows and an odd number of columns. It has two main villages; the first is located at the top-left cell $$$(1,1)$$$, people who stay there love fishing at the Tuna pond at the bottom-right cell $$$(4, n)$$$. The second village is located at $$$(4, 1)$$$ and its people love the Salmon pond at $$$(1, n)$$$.The mayor of Fishtopia wants to place $$$k$$$ hotels in the city, each one occupying one cell. To allow people to enter the city from anywhere, hotels should not be placed on the border cells.A person can move from one cell to another if those cells are not occupied by hotels and share a side.Can you help the mayor place the hotels in a way such that there are equal number of shortest paths from each village to its preferred pond? | 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 Aneesh Dandime
*/
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();
}
static class TaskB {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
int k = in.nextInt();
char[][] grid = new char[4][n];
for (int i = 0; i < 4; ++i) {
for (int j = 0; j < n; ++j) {
grid[i][j] = '.';
}
}
int row = 1;
int low = 1;
int high = n - 2;
while (k >= 2 && low < high) {
grid[row][low] = grid[row][high] = '#';
++low;
--high;
k -= 2;
}
row = 2;
low = 1;
high = n - 2;
while (k >= 2 && low < high) {
grid[row][low] = grid[row][high] = '#';
++low;
--high;
k -= 2;
}
row = 1;
low = high = n / 2;
while (k > 0) {
grid[row][low] = '#';
row++;
k--;
}
out.println("YES");
for (int i = 0; i < 4; ++i) {
for (int j = 0; j < n; ++j) {
out.print(grid[i][j]);
}
out.println();
}
}
}
static class InputReader {
public BufferedReader reader;
public 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());
}
}
}
| Java | ["7 2", "5 3"] | 1 second | ["YES\n.......\n.#.....\n.#.....\n.......", "YES\n.....\n.###.\n.....\n....."] | null | Java 8 | standard input | [
"constructive algorithms"
] | 2669feb8200769869c4b2c29012059ed | The first line of input contain two integers, $$$n$$$ and $$$k$$$ ($$$3 \leq n \leq 99$$$, $$$0 \leq k \leq 2\times(n-2)$$$), $$$n$$$ is odd, the width of the city, and the number of hotels to be placed, respectively. | 1,600 | Print "YES", if it is possible to place all the hotels in a way that satisfies the problem statement, otherwise print "NO". If it is possible, print an extra $$$4$$$ lines that describe the city, each line should have $$$n$$$ characters, each of which is "#" if that cell has a hotel on it, or "." if not. | standard output | |
PASSED | e09552b76e61d07f9d35fb3ea365298d | train_004.jsonl | 1525791900 | The city of Fishtopia can be imagined as a grid of $$$4$$$ rows and an odd number of columns. It has two main villages; the first is located at the top-left cell $$$(1,1)$$$, people who stay there love fishing at the Tuna pond at the bottom-right cell $$$(4, n)$$$. The second village is located at $$$(4, 1)$$$ and its people love the Salmon pond at $$$(1, n)$$$.The mayor of Fishtopia wants to place $$$k$$$ hotels in the city, each one occupying one cell. To allow people to enter the city from anywhere, hotels should not be placed on the border cells.A person can move from one cell to another if those cells are not occupied by hotels and share a side.Can you help the mayor place the hotels in a way such that there are equal number of shortest paths from each village to its preferred pond? | 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 Atharva Nagarkar
*/
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);
BMarlin solver = new BMarlin();
solver.solve(1, in, out);
out.close();
}
static class BMarlin {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
int k = in.nextInt();
boolean[][] grid = new boolean[4][n];
if (k % 2 == 1) {
grid[1][n / 2] = true;
k--;
}
for (int lcol = 1, rcol = n - 2; k > 0 && lcol <= rcol; ++lcol, --rcol) {
if (grid[1][lcol]) continue;
grid[1][lcol] = grid[1][rcol] = true;
if (lcol == rcol) {
k--;
} else {
k -= 2;
}
}
if (k % 2 == 1) {
grid[2][n / 2] = true;
k--;
}
for (int lcol = 1, rcol = n - 2; k > 0 && lcol <= rcol; ++lcol, --rcol) {
if (grid[2][lcol]) continue;
grid[2][lcol] = grid[2][rcol] = true;
if (lcol == rcol) {
k--;
} else {
k -= 2;
}
}
out.println("YES");
for (int r = 0; r < 4; ++r) {
for (int c = 0; c < n; ++c) {
out.print(grid[r][c] ? "#" : ".");
}
out.println();
}
}
}
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 | ["7 2", "5 3"] | 1 second | ["YES\n.......\n.#.....\n.#.....\n.......", "YES\n.....\n.###.\n.....\n....."] | null | Java 8 | standard input | [
"constructive algorithms"
] | 2669feb8200769869c4b2c29012059ed | The first line of input contain two integers, $$$n$$$ and $$$k$$$ ($$$3 \leq n \leq 99$$$, $$$0 \leq k \leq 2\times(n-2)$$$), $$$n$$$ is odd, the width of the city, and the number of hotels to be placed, respectively. | 1,600 | Print "YES", if it is possible to place all the hotels in a way that satisfies the problem statement, otherwise print "NO". If it is possible, print an extra $$$4$$$ lines that describe the city, each line should have $$$n$$$ characters, each of which is "#" if that cell has a hotel on it, or "." if not. | standard output | |
PASSED | 252606e19ba7cdb6c2defd6d303bed8f | train_004.jsonl | 1525791900 | The city of Fishtopia can be imagined as a grid of $$$4$$$ rows and an odd number of columns. It has two main villages; the first is located at the top-left cell $$$(1,1)$$$, people who stay there love fishing at the Tuna pond at the bottom-right cell $$$(4, n)$$$. The second village is located at $$$(4, 1)$$$ and its people love the Salmon pond at $$$(1, n)$$$.The mayor of Fishtopia wants to place $$$k$$$ hotels in the city, each one occupying one cell. To allow people to enter the city from anywhere, hotels should not be placed on the border cells.A person can move from one cell to another if those cells are not occupied by hotels and share a side.Can you help the mayor place the hotels in a way such that there are equal number of shortest paths from each village to its preferred pond? | 256 megabytes | import java.io.*;
import java.util.*;
import static java.lang.Math.*;
public class Main {
private final static long mod = 1000000007;
private static void printArr2(long arr[][]) {
int i, j, n = arr.length, m = arr[0].length;
for (i = 0; i < n; i++) {
for (j = 0; j < m; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
private static void printArr(int arr[][]) {
int i, j, n = arr.length, m = arr[0].length;
for (i = 0; i < n; i++) {
for (j = 0; j < m; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
private static long power(long x, long y) {
long temp;
if (y == 0)
return 1;
temp = power(x, y / 2);
temp = (temp * temp) % mod;
if (y % 2 == 0)
return temp;
else
return ((x % mod) * temp) % mod;
}
private static int gcd(int a, int b) {
if (b == 0) return a;
return gcd(b, a % b);
}
private static class Obj{
int len;
int parent;
int idx;
public Obj(int len, int parent, int idx) {
this.len = len;
this.parent = parent;
this.idx = idx;
}
}
public static void main(String[] args) throws IOException {
FastReader in = new FastReader();
FastWriter out = new FastWriter();
int t, i, j, k, w, r, x, y, l=0, n, m=0;
long ans = 0;
//for (t = in.nextInt(); t > 0; t--)
{
n=in.nextInt();
k=in.nextInt();
if(k%2==0){
out.println("YES");
out.printCharN('.',n);
out.println();
out.print(".");
out.printCharN('#',k/2);
out.printCharN('.',n-k/2-1);
out.println();
out.print(".");
out.printCharN('#',k/2);
out.printCharN('.',n-k/2-1);
out.println();
out.printCharN('.',n);
out.println();
}
else{
if(k<n){
out.println("YES");
out.printCharN('.',n);
out.println();
out.printCharN('.',(n-k)/2);
out.printCharN('#',k);
out.printCharN('.',(n-k)/2);
out.println();
out.printCharN('.',n);
out.println();
out.printCharN('.',n);
out.println();
}
else{
if(k>4){
k++;
out.println("YES");
out.printCharN('.',n);
out.println();
out.print(".");
out.printCharN('#',k/2);
out.printCharN('.',n-k/2-1);
out.println();
out.print(".#.");
out.printCharN('#',k/2-2);
out.printCharN('.',n-k/2-1);
out.println();
out.printCharN('.',n);
out.println();
}
else
out.println("NO");
}
}
out.println();
}
}
static class FastReader {
private BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
private StringTokenizer st;
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception 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;
}
int[] nextIntArr(int n) {
int []arr=new int[n];
for(int i=0;i<n;i++){
arr[i]=nextInt();
}
return arr;
}
long[] nextLongArr(int n) {
long []arr=new long[n];
for(int i=0;i<n;i++){
arr[i]=nextLong();
}
return arr;
}
}
static class FastWriter {
BufferedWriter bw;
List<String> list = new ArrayList<>();
Set<String> set = new HashSet<>();
FastWriter() {
bw = new BufferedWriter(new OutputStreamWriter(System.out));
}
<T> void print(T obj) throws IOException {
bw.write(obj.toString());
bw.flush();
}
void println() throws IOException {
print("\n");
}
<T> void println(T obj) throws IOException {
print(obj.toString() + "\n");
}
<T> void printArrLn(T[] arr) throws IOException{
for(int i=0;i<arr.length;i++){
print(arr[i]+" ");
}
println();
}
void printCharN(char c, int n) throws IOException {
for(int i=0;i<n;i++){
print(c);
}
}
}
}
| Java | ["7 2", "5 3"] | 1 second | ["YES\n.......\n.#.....\n.#.....\n.......", "YES\n.....\n.###.\n.....\n....."] | null | Java 8 | standard input | [
"constructive algorithms"
] | 2669feb8200769869c4b2c29012059ed | The first line of input contain two integers, $$$n$$$ and $$$k$$$ ($$$3 \leq n \leq 99$$$, $$$0 \leq k \leq 2\times(n-2)$$$), $$$n$$$ is odd, the width of the city, and the number of hotels to be placed, respectively. | 1,600 | Print "YES", if it is possible to place all the hotels in a way that satisfies the problem statement, otherwise print "NO". If it is possible, print an extra $$$4$$$ lines that describe the city, each line should have $$$n$$$ characters, each of which is "#" if that cell has a hotel on it, or "." if not. | standard output | |
PASSED | ce551542b1f1a3b7a6f5ed13289676e2 | train_004.jsonl | 1525791900 | The city of Fishtopia can be imagined as a grid of $$$4$$$ rows and an odd number of columns. It has two main villages; the first is located at the top-left cell $$$(1,1)$$$, people who stay there love fishing at the Tuna pond at the bottom-right cell $$$(4, n)$$$. The second village is located at $$$(4, 1)$$$ and its people love the Salmon pond at $$$(1, n)$$$.The mayor of Fishtopia wants to place $$$k$$$ hotels in the city, each one occupying one cell. To allow people to enter the city from anywhere, hotels should not be placed on the border cells.A person can move from one cell to another if those cells are not occupied by hotels and share a side.Can you help the mayor place the hotels in a way such that there are equal number of shortest paths from each village to its preferred pond? | 256 megabytes | import java.util.Scanner;
public class Marlin {
public static void main (String[] args){
Scanner sc = new Scanner(System.in);
int cols = sc.nextInt();
int numVil = sc.nextInt();
System.out.println("YES");
for(int i = 0; i < cols; i++){
System.out.print(".");
}
System.out.println();
if(numVil % 2 == 0) {
for (int n = 0; n < 2; n++) {
System.out.print(".");
for (int c = 0; c < cols - 2; c++) {
if (c < numVil / 2) {
System.out.print("#");
} else {
System.out.print(".");
}
}
System.out.print(".");
System.out.println();
}
}
else {
int odd = (numVil / 2) + 1;
int even = numVil / 2;
if((even % 2) != 0){
int temp = even;
even = odd;
odd = temp;
}
int sideVil = even / 2;
int padding = (cols - 2 - odd) / 2;
int padding2 = ((cols - 2)/2) - sideVil;
System.out.print(".");
for(int i = 0; i < padding; i++) {
System.out.print(".");
}
for(int i = 0; i < odd; i++) {
System.out.print("#");
}
for(int i = 0; i < padding; i++) {
System.out.print(".");
}
System.out.print(".");
System.out.println();
System.out.print(".");
for(int i = 0; i < padding2; i++) {
System.out.print(".");
}
for(int i = 0; i < sideVil; i++) {
System.out.print("#");
}
System.out.print(".");
for(int i = 0; i < sideVil; i++) {
System.out.print("#");
}
for(int i = 0; i < padding2; i++) {
System.out.print(".");
}
System.out.print(".");
System.out.println();
}
for(int i = 0; i < cols; i++){
System.out.print(".");
}
}
}
| Java | ["7 2", "5 3"] | 1 second | ["YES\n.......\n.#.....\n.#.....\n.......", "YES\n.....\n.###.\n.....\n....."] | null | Java 8 | standard input | [
"constructive algorithms"
] | 2669feb8200769869c4b2c29012059ed | The first line of input contain two integers, $$$n$$$ and $$$k$$$ ($$$3 \leq n \leq 99$$$, $$$0 \leq k \leq 2\times(n-2)$$$), $$$n$$$ is odd, the width of the city, and the number of hotels to be placed, respectively. | 1,600 | Print "YES", if it is possible to place all the hotels in a way that satisfies the problem statement, otherwise print "NO". If it is possible, print an extra $$$4$$$ lines that describe the city, each line should have $$$n$$$ characters, each of which is "#" if that cell has a hotel on it, or "." if not. | standard output | |
PASSED | e758f29809fcc16215543be313535e74 | train_004.jsonl | 1525791900 | The city of Fishtopia can be imagined as a grid of $$$4$$$ rows and an odd number of columns. It has two main villages; the first is located at the top-left cell $$$(1,1)$$$, people who stay there love fishing at the Tuna pond at the bottom-right cell $$$(4, n)$$$. The second village is located at $$$(4, 1)$$$ and its people love the Salmon pond at $$$(1, n)$$$.The mayor of Fishtopia wants to place $$$k$$$ hotels in the city, each one occupying one cell. To allow people to enter the city from anywhere, hotels should not be placed on the border cells.A person can move from one cell to another if those cells are not occupied by hotels and share a side.Can you help the mayor place the hotels in a way such that there are equal number of shortest paths from each village to its preferred pond? | 256 megabytes | import javafx.util.Pair;
import java.util.*;
import java.io.*;
//prob id: 980B Codeforces Round #480 (Div. 2)
public class marlin{
public static void main(String[] args) {
Scanner ps = new Scanner(System.in);
int n = ps.nextInt();
int k = ps.nextInt();
System.out.println("YES");
for(int i = 0; i < 4; i++){
if(i == 0 || i == 3){
for(int j = 0; j < n; j++){
System.out.print(".");
}
}
else{
Set<Integer> colPts = createSymmetry(k, n);
k -= colPts.size();
for(int j = 0; j < n; j++){
if(colPts.contains(j)){
System.out.print("#");
}
else{
System.out.print(".");
}
}
}
System.out.println();
}
}
//return a set with column coordinates where hotels should be placed in order to create a symmetry
//this shall exclude column 0 and last column (n-1)
public static Set<Integer> createSymmetry(int hotels, int n){
Set<Integer> colPts = new HashSet<>();
if(hotels % 2 != 0){
colPts.add(n/2); //n is an integer, so decimal part will be truncated off, which will result in middle column
--hotels;
}
//guaranteed that hotels is even at this point
int leftSide = 1;
int rightSide = (n-(leftSide+1));
while(hotels > 0 && leftSide <= rightSide){
//leftSide might be equal to rightSide at middle column
//hence leftSide <= rightSide in while condition
colPts.add(leftSide);
colPts.add(rightSide);
rightSide = (n-(++leftSide+1));
hotels -= 2;
}
return colPts;
}
} | Java | ["7 2", "5 3"] | 1 second | ["YES\n.......\n.#.....\n.#.....\n.......", "YES\n.....\n.###.\n.....\n....."] | null | Java 8 | standard input | [
"constructive algorithms"
] | 2669feb8200769869c4b2c29012059ed | The first line of input contain two integers, $$$n$$$ and $$$k$$$ ($$$3 \leq n \leq 99$$$, $$$0 \leq k \leq 2\times(n-2)$$$), $$$n$$$ is odd, the width of the city, and the number of hotels to be placed, respectively. | 1,600 | Print "YES", if it is possible to place all the hotels in a way that satisfies the problem statement, otherwise print "NO". If it is possible, print an extra $$$4$$$ lines that describe the city, each line should have $$$n$$$ characters, each of which is "#" if that cell has a hotel on it, or "." if not. | standard output | |
PASSED | 716b0c6b63dd2858d4a5398ef867ae89 | train_004.jsonl | 1525791900 | The city of Fishtopia can be imagined as a grid of $$$4$$$ rows and an odd number of columns. It has two main villages; the first is located at the top-left cell $$$(1,1)$$$, people who stay there love fishing at the Tuna pond at the bottom-right cell $$$(4, n)$$$. The second village is located at $$$(4, 1)$$$ and its people love the Salmon pond at $$$(1, n)$$$.The mayor of Fishtopia wants to place $$$k$$$ hotels in the city, each one occupying one cell. To allow people to enter the city from anywhere, hotels should not be placed on the border cells.A person can move from one cell to another if those cells are not occupied by hotels and share a side.Can you help the mayor place the hotels in a way such that there are equal number of shortest paths from each village to its preferred pond? | 256 megabytes | import javafx.util.Pair;
import java.util.*;
public class marlin{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int k = sc.nextInt();
System.out.println("YES");
for(int i = 0; i < 4; i++){
if(i == 0 || i == 3){
for(int j = 0; j < n; j++){
System.out.print(".");
}
}
else{
Set<Integer> colPts = createSymmetry(k, n);
k -= colPts.size();
for(int j = 0; j < n; j++){
if(colPts.contains(j)){
System.out.print("#");
}
else{
System.out.print(".");
}
}
}
System.out.println();
}
}
//return a set with column coordinates where hotels should be placed in order to create a symmetry
//this shall exclude column 0 and last column (n-1)
public static Set<Integer> createSymmetry(int hotels, int n){
Set<Integer> colPts = new HashSet<>();
if(hotels % 2 != 0){
colPts.add(n/2); //n is an integer, so decimal part will be truncated off, which will result in middle column
--hotels;
}
//guaranteed that hotels is even at this point
int leftSide = 1;
int rightSide = (n-(leftSide+1));
while(hotels > 0){
colPts.add(leftSide);
colPts.add(rightSide);
leftSide++;
rightSide = (n-(leftSide+1));
hotels -= 2;
}
return colPts;
}
}
| Java | ["7 2", "5 3"] | 1 second | ["YES\n.......\n.#.....\n.#.....\n.......", "YES\n.....\n.###.\n.....\n....."] | null | Java 8 | standard input | [
"constructive algorithms"
] | 2669feb8200769869c4b2c29012059ed | The first line of input contain two integers, $$$n$$$ and $$$k$$$ ($$$3 \leq n \leq 99$$$, $$$0 \leq k \leq 2\times(n-2)$$$), $$$n$$$ is odd, the width of the city, and the number of hotels to be placed, respectively. | 1,600 | Print "YES", if it is possible to place all the hotels in a way that satisfies the problem statement, otherwise print "NO". If it is possible, print an extra $$$4$$$ lines that describe the city, each line should have $$$n$$$ characters, each of which is "#" if that cell has a hotel on it, or "." if not. | standard output | |
PASSED | 988396d0494b4a79b9f8b0b9014e2af6 | train_004.jsonl | 1525791900 | The city of Fishtopia can be imagined as a grid of $$$4$$$ rows and an odd number of columns. It has two main villages; the first is located at the top-left cell $$$(1,1)$$$, people who stay there love fishing at the Tuna pond at the bottom-right cell $$$(4, n)$$$. The second village is located at $$$(4, 1)$$$ and its people love the Salmon pond at $$$(1, n)$$$.The mayor of Fishtopia wants to place $$$k$$$ hotels in the city, each one occupying one cell. To allow people to enter the city from anywhere, hotels should not be placed on the border cells.A person can move from one cell to another if those cells are not occupied by hotels and share a side.Can you help the mayor place the hotels in a way such that there are equal number of shortest paths from each village to its preferred pond? | 256 megabytes | import javafx.util.Pair;
import java.util.*;
import java.io.*;
//prob id: 980B Codeforces Round #480 (Div. 2)
public class marlin{
public static void main(String[] args) throws Exception{
Parser ps = new Parser(System.in);
int n = ps.nextInt();
int k = ps.nextInt();
System.out.println("YES");
for(int i = 0; i < 4; i++){
if(i == 0 || i == 3){
for(int j = 0; j < n; j++){
System.out.print(".");
}
}
else{
Set<Integer> colPts = createSymmetry(k, n);
k -= colPts.size();
for(int j = 0; j < n; j++){
if(colPts.contains(j)){
System.out.print("#");
}
else{
System.out.print(".");
}
}
}
System.out.println();
}
}
//return a set with column coordinates where hotels should be placed in order to create a symmetry
//this shall exclude column 0 and last column (n-1)
public static Set<Integer> createSymmetry(int hotels, int n){
Set<Integer> colPts = new HashSet<>();
if(hotels % 2 != 0){
colPts.add(n/2); //n is an integer, so decimal part will be truncated off, which will result in middle column
--hotels;
}
//guaranteed that hotels is even at this point
int leftSide = 1;
int rightSide = (n-(leftSide+1));
while(hotels > 0 && leftSide <= rightSide){
//leftSide might be equal to rightSide at middle column
//hence leftSide <= rightSide in while condition
colPts.add(leftSide);
colPts.add(rightSide);
rightSide = (n-(++leftSide+1));
hotels -= 2;
}
return colPts;
}
}
class Parser
{
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Parser(InputStream in)
{
din = new DataInputStream(in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public long nextLong() throws Exception
{
long ret = 0;
byte c = read();
while (c <= ' ') c = read();
boolean neg = c == '-';
if (neg) c = read();
do
{
ret = ret * 10 + c - '0';
c = read();
} while (c > ' ');
if (neg) return -ret;
return ret;
}
//reads in the next string
public String next() throws Exception
{
StringBuilder ret = new StringBuilder();
byte c = read();
while (c <= ' ') c = read();
do
{
ret = ret.append((char)c);
c = read();
} while (c > ' ');
return ret.toString();
}
public int nextInt() throws Exception
{
int ret = 0;
byte c = read();
while (c <= ' ') c = read();
boolean neg = c == '-';
if (neg) c = read();
do
{
ret = ret * 10 + c - '0';
c = read();
} while (c > ' ');
if (neg) return -ret;
return ret;
}
private void fillBuffer() throws Exception
{
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1) buffer[0] = -1;
}
private byte read() throws Exception
{
if (bufferPointer == bytesRead) fillBuffer();
return buffer[bufferPointer++];
}
}
| Java | ["7 2", "5 3"] | 1 second | ["YES\n.......\n.#.....\n.#.....\n.......", "YES\n.....\n.###.\n.....\n....."] | null | Java 8 | standard input | [
"constructive algorithms"
] | 2669feb8200769869c4b2c29012059ed | The first line of input contain two integers, $$$n$$$ and $$$k$$$ ($$$3 \leq n \leq 99$$$, $$$0 \leq k \leq 2\times(n-2)$$$), $$$n$$$ is odd, the width of the city, and the number of hotels to be placed, respectively. | 1,600 | Print "YES", if it is possible to place all the hotels in a way that satisfies the problem statement, otherwise print "NO". If it is possible, print an extra $$$4$$$ lines that describe the city, each line should have $$$n$$$ characters, each of which is "#" if that cell has a hotel on it, or "." if not. | standard output |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.