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 | 7bbc722978be15b48a9e134a27f07432 | train_001.jsonl | 1416238500 | A traveler is planning a water hike along the river. He noted the suitable rest points for the night and wrote out their distances from the starting point. Each of these locations is further characterized by its picturesqueness, so for the i-th rest point the distance from the start equals xi, and its picturesqueness equals bi. The traveler will move down the river in one direction, we can assume that he will start from point 0 on the coordinate axis and rest points are points with coordinates xi.Every day the traveler wants to cover the distance l. In practice, it turns out that this is not always possible, because he needs to end each day at one of the resting points. In addition, the traveler is choosing between two desires: cover distance l every day and visit the most picturesque places.Let's assume that if the traveler covers distance rj in a day, then he feels frustration , and his total frustration over the hike is calculated as the total frustration on all days.Help him plan the route so as to minimize the relative total frustration: the total frustration divided by the total picturesqueness of all the rest points he used.The traveler's path must end in the farthest rest point. | 256 megabytes | /**
* Created by ckboss on 14-11-22.
*/
import java.util.*;
public class CF489E {
int n,l;
class Point{
public int x,b;
}
Point[] p = new Point[1100];
double[] dp = new double[1100];
int[] pre = new int[1100];
boolean check(double L){
Arrays.fill(dp,-1e8);
Arrays.fill(pre,-1);
dp[0]=0;
for(int i=1;i<=n;i++){
dp[i] = dp[0] + L*p[i].b - Math.sqrt(Math.abs(p[i].x-l));
pre[i]=0;
for(int j=1;j<i;j++){
double r=1.*p[i].x-p[j].x;
double tr = dp[j] + L*p[i].b - Math.sqrt(Math.abs(r-1.*l));
if(dp[i]<tr) {
dp[i]= Math.max(dp[i], tr);
pre[i]=j;
}
}
}
/*
for(int i=0;i<=n;i++){
System.out.println(i+": "+dp[i]+" ... "+pre[i]);
}
*/
if(dp[n]>0) return true;
return false;
}
CF489E(){
Scanner in = new Scanner(System.in);
n=in.nextInt(); l=in.nextInt();
for(int i=1;i<=n;i++) {
p[i]=new Point();
p[i].x=in.nextInt();
p[i].b=in.nextInt();
}
//boolean bo=check(1000);
//System.out.println(bo);
double low=0,high=1e7,mid = 0,ans = 0;
while(Math.abs(high-low)>1e-7){
mid=(low+high)/2;
//System.out.println(low+" <---- "+mid+" ----> "+high);
if(check(mid)==true){
ans=high=mid;
}
else low=mid;
}
//System.out.println("ans: " + ans);
check(ans);
int u=n;
List<Integer> as = new ArrayList<Integer>();
as.add(u);
//System.out.println("AFTER");
while(pre[u]!=-1){
u=pre[u];
if(u==0) continue;
as.add(u);
}
for(int i=as.size()-1;i>=0;i--)
System.out.printf("%d ",as.get(i));
}
public static void main(String[] args){
new CF489E();
}
} | Java | ["5 9\n10 10\n20 10\n30 1\n31 5\n40 10"] | 1 second | ["1 2 4 5"] | NoteIn the sample test the minimum value of relative total frustration approximately equals 0.097549. This value can be calculated as . | Java 7 | standard input | [
"dp",
"binary search"
] | 9ea7a7b892fefaaf8197cf48e92eb9f1 | The first line of the input contains integers n,βl (1ββ€βnββ€β1000,β1ββ€βlββ€β105) β the number of rest points and the optimal length of one day path. Then n lines follow, each line describes one rest point as a pair of integers xi,βbi (1ββ€βxi,βbiββ€β106). No two rest points have the same xi, the lines are given in the order of strictly increasing xi. | 2,300 | Print the traveler's path as a sequence of the numbers of the resting points he used in the order he used them. Number the points from 1 to n in the order of increasing xi. The last printed number must be equal to n. | standard output | |
PASSED | fba224f0f8f179e92dc19d684586ff75 | train_001.jsonl | 1416238500 | A traveler is planning a water hike along the river. He noted the suitable rest points for the night and wrote out their distances from the starting point. Each of these locations is further characterized by its picturesqueness, so for the i-th rest point the distance from the start equals xi, and its picturesqueness equals bi. The traveler will move down the river in one direction, we can assume that he will start from point 0 on the coordinate axis and rest points are points with coordinates xi.Every day the traveler wants to cover the distance l. In practice, it turns out that this is not always possible, because he needs to end each day at one of the resting points. In addition, the traveler is choosing between two desires: cover distance l every day and visit the most picturesque places.Let's assume that if the traveler covers distance rj in a day, then he feels frustration , and his total frustration over the hike is calculated as the total frustration on all days.Help him plan the route so as to minimize the relative total frustration: the total frustration divided by the total picturesqueness of all the rest points he used.The traveler's path must end in the farthest rest point. | 256 megabytes | import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.InputMismatchException;
import java.util.LinkedList;
import java.util.Map.Entry;
import java.util.Queue;
import java.util.Random;
import java.util.Set;
import java.util.SortedSet;
import java.util.Stack;
import java.util.TreeMap;
import java.util.TreeSet;
public class Main
{
private final double EPS = 1e-8;
private int n;
private int len;
private double[] x;
private double[] b;
private int[] pre;
public boolean test(double ans)
{
double[] dp = new double[n + 1];
for(int i = 1;i <= n;++i)
{
dp[i] = 1e30;
for(int j = 0;j < i;++j)
{
double tmp = dp[j] + Math.sqrt(Math.abs((double)(x[i] - x[j] - len))) - ans * b[i];
if(dp[i] > tmp)
{
dp[i] = tmp;
pre[i] = j;
}
}
}
return dp[n] < 0;
}
public void foo()
{
MyScanner scan = new MyScanner();
n = scan.nextInt();
len = scan.nextInt();
x = new double[n + 1];
b = new double[n + 1];
for(int i = 1;i <= n;++i)
{
x[i] = scan.nextDouble();
b[i] = scan.nextDouble();
}
pre = new int[n + 1];
double left = 0, right = 1e9, mid = 0;
while(right - left > EPS)
{
mid = (left + right) / 2;
if(test(mid))
{
right = mid;
}
else
{
left = mid;
}
}
test(left);
ArrayList<Integer> arr = new ArrayList<Integer>();
int p = n;
while(p != 0)
{
arr.add(p);
p = pre[p];
}
for(int i = arr.size() - 1;i >= 0;--i)
{
System.out.print(arr.get(i) + " ");
}
System.out.println();
}
public static void main(String[] args)
{
new Main().foo();
}
class MyScanner
{
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
BufferedInputStream bis = new BufferedInputStream(System.in);
public int read()
{
if (-1 == numChars)
{
throw new InputMismatchException();
}
if (curChar >= numChars)
{
curChar = 0;
try
{
numChars = bis.read(buf);
}
catch (IOException e)
{
throw new InputMismatchException();
}
if (numChars <= 0)
{
return -1;
}
}
return buf[curChar++];
}
public int nextInt()
{
int c = read();
while (isSpaceChar(c))
{
c = read();
}
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
int res = 0;
do
{
if (c < '0' || c > '9')
{
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong()
{
int c = read();
while (isSpaceChar(c))
{
c = read();
}
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
long res = 0;
do
{
if (c < '0' || c > '9')
{
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public double nextDouble()
{
int c = read();
while (isSpaceChar(c))
{
c = read();
}
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.')
{
if (c == 'e' || c == 'E')
{
return res * Math.pow(10, nextInt());
}
if (c < '0' || c > '9')
{
throw new InputMismatchException();
}
res *= 10;
res += c & 15;
c = read();
}
if (c == '.')
{
c = read();
double m = 1;
while (!isSpaceChar(c))
{
if (c == 'e' || c == 'E')
{
return res * Math.pow(10, nextInt());
}
if (c < '0' || c > '9')
{
throw new InputMismatchException();
}
m /= 10;
res += (c & 15) * m;
c = read();
}
}
return res * sgn;
}
public String next()
{
int c = read();
while (isSpaceChar(c))
{
c = read();
}
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
private boolean isSpaceChar(int c)
{
return ' ' == c || '\n' == c || '\r' == c || '\t' == c || -1 == c;
}
}
} | Java | ["5 9\n10 10\n20 10\n30 1\n31 5\n40 10"] | 1 second | ["1 2 4 5"] | NoteIn the sample test the minimum value of relative total frustration approximately equals 0.097549. This value can be calculated as . | Java 7 | standard input | [
"dp",
"binary search"
] | 9ea7a7b892fefaaf8197cf48e92eb9f1 | The first line of the input contains integers n,βl (1ββ€βnββ€β1000,β1ββ€βlββ€β105) β the number of rest points and the optimal length of one day path. Then n lines follow, each line describes one rest point as a pair of integers xi,βbi (1ββ€βxi,βbiββ€β106). No two rest points have the same xi, the lines are given in the order of strictly increasing xi. | 2,300 | Print the traveler's path as a sequence of the numbers of the resting points he used in the order he used them. Number the points from 1 to n in the order of increasing xi. The last printed number must be equal to n. | standard output | |
PASSED | ee9118e09bab37f58ae58fec8c2348a8 | train_001.jsonl | 1346427000 | The Little Elephant enjoys recursive functions.This time he enjoys the sorting function. Let a is a permutation of an integers from 1 to n, inclusive, and ai denotes the i-th element of the permutation. The Little Elephant's recursive function f(x), that sorts the first x permutation's elements, works as follows: If xβ=β1, exit the function. Otherwise, call f(xβ-β1), and then make swap(axβ-β1,βax) (swap the x-th and (xβ-β1)-th elements of a). The Little Elephant's teacher believes that this function does not work correctly. But that-be do not get an F, the Little Elephant wants to show the performance of its function. Help him, find a permutation of numbers from 1 to n, such that after performing the Little Elephant's function (that is call f(n)), the permutation will be sorted in ascending order. | 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 masterbios
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
static class TaskA {
public void solve(int testNumber, InputReader in, PrintWriter out) {
// 4 1 2 3 1 4 3 2
int n = in.nextInt();
out.print(n + " ");
for (int i = 1; i < n; i++) {
out.print(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.hasMoreElements()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
| Java | ["1", "2"] | 2 seconds | ["1", "2 1"] | null | Java 8 | standard input | [
"implementation",
"math"
] | d9ba1dfe11cf3dae177f8898f3abeefd | A single line contains integer n (1ββ€βnββ€β1000) β the size of permutation. | 1,000 | In a single line print n distinct integers from 1 to n β the required permutation. Numbers in a line should be separated by spaces. It is guaranteed that the answer exists. | standard output | |
PASSED | 3059ea095ab9fa854226076ede558e5b | train_001.jsonl | 1346427000 | The Little Elephant enjoys recursive functions.This time he enjoys the sorting function. Let a is a permutation of an integers from 1 to n, inclusive, and ai denotes the i-th element of the permutation. The Little Elephant's recursive function f(x), that sorts the first x permutation's elements, works as follows: If xβ=β1, exit the function. Otherwise, call f(xβ-β1), and then make swap(axβ-β1,βax) (swap the x-th and (xβ-β1)-th elements of a). The Little Elephant's teacher believes that this function does not work correctly. But that-be do not get an F, the Little Elephant wants to show the performance of its function. Help him, find a permutation of numbers from 1 to n, such that after performing the Little Elephant's function (that is call f(n)), the permutation will be sorted in ascending order. | 256 megabytes | import java.io.*;
import java.util.*;
import java.math.*;
public class codeforces
{
public static void main(String[] args)throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
System.out.print(n+" ");
for(int i=1;i<=n-1;i++)
{
System.out.print(i+" ");
}
}
} | Java | ["1", "2"] | 2 seconds | ["1", "2 1"] | null | Java 8 | standard input | [
"implementation",
"math"
] | d9ba1dfe11cf3dae177f8898f3abeefd | A single line contains integer n (1ββ€βnββ€β1000) β the size of permutation. | 1,000 | In a single line print n distinct integers from 1 to n β the required permutation. Numbers in a line should be separated by spaces. It is guaranteed that the answer exists. | standard output | |
PASSED | 9078a758607b91a8a71d2ee7d8059917 | train_001.jsonl | 1346427000 | The Little Elephant enjoys recursive functions.This time he enjoys the sorting function. Let a is a permutation of an integers from 1 to n, inclusive, and ai denotes the i-th element of the permutation. The Little Elephant's recursive function f(x), that sorts the first x permutation's elements, works as follows: If xβ=β1, exit the function. Otherwise, call f(xβ-β1), and then make swap(axβ-β1,βax) (swap the x-th and (xβ-β1)-th elements of a). The Little Elephant's teacher believes that this function does not work correctly. But that-be do not get an F, the Little Elephant wants to show the performance of its function. Help him, find a permutation of numbers from 1 to n, such that after performing the Little Elephant's function (that is call f(n)), the permutation will be sorted in ascending order. | 256 megabytes | import java.util.Scanner;
public class Forsolving {
public static void main(String[] args) {
Scanner enter = new Scanner (System.in);
int n = enter.nextInt();
System.out.println(n);
for(int i = 1; i < n ; i++)
System.out.println(i+" ");
}
}
| Java | ["1", "2"] | 2 seconds | ["1", "2 1"] | null | Java 8 | standard input | [
"implementation",
"math"
] | d9ba1dfe11cf3dae177f8898f3abeefd | A single line contains integer n (1ββ€βnββ€β1000) β the size of permutation. | 1,000 | In a single line print n distinct integers from 1 to n β the required permutation. Numbers in a line should be separated by spaces. It is guaranteed that the answer exists. | standard output | |
PASSED | b3701335f91a3f7d87804f6ed5bb610e | train_001.jsonl | 1346427000 | The Little Elephant enjoys recursive functions.This time he enjoys the sorting function. Let a is a permutation of an integers from 1 to n, inclusive, and ai denotes the i-th element of the permutation. The Little Elephant's recursive function f(x), that sorts the first x permutation's elements, works as follows: If xβ=β1, exit the function. Otherwise, call f(xβ-β1), and then make swap(axβ-β1,βax) (swap the x-th and (xβ-β1)-th elements of a). The Little Elephant's teacher believes that this function does not work correctly. But that-be do not get an F, the Little Elephant wants to show the performance of its function. Help him, find a permutation of numbers from 1 to n, such that after performing the Little Elephant's function (that is call f(n)), the permutation will be sorted in ascending order. | 256 megabytes | import java.util.Scanner;
public class Forsolving {
public static void main(String[] args) {
Scanner enter = new Scanner (System.in);
int n = enter.nextInt();
System.out.print(n+" ");
for(int i = 1; i < n ; i++)
System.out.print(i+" ");
}
}
| Java | ["1", "2"] | 2 seconds | ["1", "2 1"] | null | Java 8 | standard input | [
"implementation",
"math"
] | d9ba1dfe11cf3dae177f8898f3abeefd | A single line contains integer n (1ββ€βnββ€β1000) β the size of permutation. | 1,000 | In a single line print n distinct integers from 1 to n β the required permutation. Numbers in a line should be separated by spaces. It is guaranteed that the answer exists. | standard output | |
PASSED | 632d198da9a5e26c0f5b6bab4c16a4d3 | train_001.jsonl | 1346427000 | The Little Elephant enjoys recursive functions.This time he enjoys the sorting function. Let a is a permutation of an integers from 1 to n, inclusive, and ai denotes the i-th element of the permutation. The Little Elephant's recursive function f(x), that sorts the first x permutation's elements, works as follows: If xβ=β1, exit the function. Otherwise, call f(xβ-β1), and then make swap(axβ-β1,βax) (swap the x-th and (xβ-β1)-th elements of a). The Little Elephant's teacher believes that this function does not work correctly. But that-be do not get an F, the Little Elephant wants to show the performance of its function. Help him, find a permutation of numbers from 1 to n, such that after performing the Little Elephant's function (that is call f(n)), the permutation will be sorted in ascending order. | 256 megabytes |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
public class problem {
static void p(int num) {
if(num >= 1) {
System.out.print(num+" ");
for(int i = 1 ; i < num ; i++) {
System.out.print(i + " ");
}
}
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader (new InputStreamReader (System.in));
int n = Integer.parseInt(br.readLine());
p(n);
}
} | Java | ["1", "2"] | 2 seconds | ["1", "2 1"] | null | Java 8 | standard input | [
"implementation",
"math"
] | d9ba1dfe11cf3dae177f8898f3abeefd | A single line contains integer n (1ββ€βnββ€β1000) β the size of permutation. | 1,000 | In a single line print n distinct integers from 1 to n β the required permutation. Numbers in a line should be separated by spaces. It is guaranteed that the answer exists. | standard output | |
PASSED | ae07eb39654366f0fee7cf26d48b79e8 | train_001.jsonl | 1346427000 | The Little Elephant enjoys recursive functions.This time he enjoys the sorting function. Let a is a permutation of an integers from 1 to n, inclusive, and ai denotes the i-th element of the permutation. The Little Elephant's recursive function f(x), that sorts the first x permutation's elements, works as follows: If xβ=β1, exit the function. Otherwise, call f(xβ-β1), and then make swap(axβ-β1,βax) (swap the x-th and (xβ-β1)-th elements of a). The Little Elephant's teacher believes that this function does not work correctly. But that-be do not get an F, the Little Elephant wants to show the performance of its function. Help him, find a permutation of numbers from 1 to n, such that after performing the Little Elephant's function (that is call f(n)), the permutation will be sorted in ascending order. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.BufferedReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Omar-Handouk
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
Scanner in = new Scanner(inputStream);
OutputWriter out = new OutputWriter(outputStream);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
static class TaskA {
int[] num;
int n;
public void solve(int testNumber, Scanner in, OutputWriter out) {
n = in.nextInt();
num = new int[n + 1];
for (int i = 1; i <= n; ++i)
num[i] = i;
perm(1);
for (int i = 1; i <= n; ++i)
out.print(num[i] + " ");
}
void perm(int c) {
if (c == n)
return;
perm(c + 1);
int temp = num[c];
num[c] = num[c + 1];
num[c + 1] = temp;
}
}
static class Scanner {
private BufferedReader bufferedReader;
private StringTokenizer stringTokenizer;
public Scanner(InputStream stream) {
bufferedReader = new BufferedReader(new InputStreamReader(stream));
}
public String next() {
while (stringTokenizer == null || !stringTokenizer.hasMoreTokens()) {
try {
stringTokenizer = new StringTokenizer(bufferedReader.readLine());
} catch (IOException Error) {
Error.printStackTrace();
;
}
}
return stringTokenizer.nextToken();
}
public int nextInt() {
int number = Integer.parseInt(this.next());
return number;
}
}
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();
}
}
}
| Java | ["1", "2"] | 2 seconds | ["1", "2 1"] | null | Java 8 | standard input | [
"implementation",
"math"
] | d9ba1dfe11cf3dae177f8898f3abeefd | A single line contains integer n (1ββ€βnββ€β1000) β the size of permutation. | 1,000 | In a single line print n distinct integers from 1 to n β the required permutation. Numbers in a line should be separated by spaces. It is guaranteed that the answer exists. | standard output | |
PASSED | e6b777128b9ede6b01556a7d6ce2b15e | train_001.jsonl | 1346427000 | The Little Elephant enjoys recursive functions.This time he enjoys the sorting function. Let a is a permutation of an integers from 1 to n, inclusive, and ai denotes the i-th element of the permutation. The Little Elephant's recursive function f(x), that sorts the first x permutation's elements, works as follows: If xβ=β1, exit the function. Otherwise, call f(xβ-β1), and then make swap(axβ-β1,βax) (swap the x-th and (xβ-β1)-th elements of a). The Little Elephant's teacher believes that this function does not work correctly. But that-be do not get an F, the Little Elephant wants to show the performance of its function. Help him, find a permutation of numbers from 1 to n, such that after performing the Little Elephant's function (that is call f(n)), the permutation will be sorted in ascending order. | 256 megabytes | import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class LittleElephantAndFunction {
public static void main(String[] args) {
out = new PrintWriter(new BufferedOutputStream(System.out));
Reader in = new Reader();
int n = in.readInt();
out.print(n + " ");
for(int i = 1; i < n; i++) out.print(i + " ");
in.close();
out.close();
}
static PrintWriter out;
static class Reader {
BufferedReader br;
StringTokenizer st;
public Reader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String read() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int readInt() {
return Integer.parseInt(read());
}
long readLong() {
return Long.parseLong(read());
}
double readDouble() {
return Double.parseDouble(read());
}
char readChar() {
return read().charAt(0);
}
int[] readIntArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = readInt();
return a;
}
long[] readLongArray(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = readLong();
return a;
}
double[] readDoubleArray(int n) {
double[] a = new double[n];
for (int i = 0; i < n; i++)
a[i] = readDouble();
return a;
}
String[] readStringArray(int n) {
String[] s = new String[n];
for (int i = 0; i < n; i++)
s[i] = read();
return s;
}
char[] readCharArray(int n) {
char[] ch = new char[n];
for (int i = 0; i < n; i++)
ch[i] = readChar();
return ch;
}
String readLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
void close() {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
} | Java | ["1", "2"] | 2 seconds | ["1", "2 1"] | null | Java 8 | standard input | [
"implementation",
"math"
] | d9ba1dfe11cf3dae177f8898f3abeefd | A single line contains integer n (1ββ€βnββ€β1000) β the size of permutation. | 1,000 | In a single line print n distinct integers from 1 to n β the required permutation. Numbers in a line should be separated by spaces. It is guaranteed that the answer exists. | standard output | |
PASSED | dccb411ef6cec32809b962667d50bbaf | train_001.jsonl | 1346427000 | The Little Elephant enjoys recursive functions.This time he enjoys the sorting function. Let a is a permutation of an integers from 1 to n, inclusive, and ai denotes the i-th element of the permutation. The Little Elephant's recursive function f(x), that sorts the first x permutation's elements, works as follows: If xβ=β1, exit the function. Otherwise, call f(xβ-β1), and then make swap(axβ-β1,βax) (swap the x-th and (xβ-β1)-th elements of a). The Little Elephant's teacher believes that this function does not work correctly. But that-be do not get an F, the Little Elephant wants to show the performance of its function. Help him, find a permutation of numbers from 1 to n, such that after performing the Little Elephant's function (that is call f(n)), the permutation will be sorted in ascending order. | 256 megabytes | import java.io.*;
import java.util.*;
public class A {
public static void solution(BufferedReader reader, PrintWriter out)
throws IOException {
In in = new In(reader);
int n = in.nextInt();
out.print(n);
for (int i = 1; i < n; i++)
out.print(" " + i);
out.println();
}
public static void main(String[] args) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(
System.in));
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(System.out)));
solution(reader, out);
out.close();
}
protected static class In {
private BufferedReader reader;
private StringTokenizer tokenizer = new StringTokenizer("");
public In(BufferedReader reader) {
this.reader = reader;
}
public String next() throws IOException {
while (!tokenizer.hasMoreTokens())
tokenizer = new StringTokenizer(reader.readLine());
return tokenizer.nextToken();
}
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 | ["1", "2"] | 2 seconds | ["1", "2 1"] | null | Java 8 | standard input | [
"implementation",
"math"
] | d9ba1dfe11cf3dae177f8898f3abeefd | A single line contains integer n (1ββ€βnββ€β1000) β the size of permutation. | 1,000 | In a single line print n distinct integers from 1 to n β the required permutation. Numbers in a line should be separated by spaces. It is guaranteed that the answer exists. | standard output | |
PASSED | fb5eb89ac28a0387cee5b29b47ee4fec | train_001.jsonl | 1346427000 | The Little Elephant enjoys recursive functions.This time he enjoys the sorting function. Let a is a permutation of an integers from 1 to n, inclusive, and ai denotes the i-th element of the permutation. The Little Elephant's recursive function f(x), that sorts the first x permutation's elements, works as follows: If xβ=β1, exit the function. Otherwise, call f(xβ-β1), and then make swap(axβ-β1,βax) (swap the x-th and (xβ-β1)-th elements of a). The Little Elephant's teacher believes that this function does not work correctly. But that-be do not get an F, the Little Elephant wants to show the performance of its function. Help him, find a permutation of numbers from 1 to n, such that after performing the Little Elephant's function (that is call f(n)), the permutation will be sorted in ascending order. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.PrintStream;
import java.util.Scanner;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
Scanner in = new Scanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
ProblemALittleElephantAndFunction solver = new ProblemALittleElephantAndFunction();
solver.solve(1, in, out);
out.close();
}
static class ProblemALittleElephantAndFunction {
public void solve(int testNumber, Scanner in, PrintWriter out) {
int n = in.nextInt();
System.out.printf("%d ", n);
for (int i = 1; i < n; i++) {
System.out.printf("%d ", i);
}
}
}
}
| Java | ["1", "2"] | 2 seconds | ["1", "2 1"] | null | Java 8 | standard input | [
"implementation",
"math"
] | d9ba1dfe11cf3dae177f8898f3abeefd | A single line contains integer n (1ββ€βnββ€β1000) β the size of permutation. | 1,000 | In a single line print n distinct integers from 1 to n β the required permutation. Numbers in a line should be separated by spaces. It is guaranteed that the answer exists. | standard output | |
PASSED | c045e8a85d0a8e7f762b45e041e5bd04 | train_001.jsonl | 1346427000 | The Little Elephant enjoys recursive functions.This time he enjoys the sorting function. Let a is a permutation of an integers from 1 to n, inclusive, and ai denotes the i-th element of the permutation. The Little Elephant's recursive function f(x), that sorts the first x permutation's elements, works as follows: If xβ=β1, exit the function. Otherwise, call f(xβ-β1), and then make swap(axβ-β1,βax) (swap the x-th and (xβ-β1)-th elements of a). The Little Elephant's teacher believes that this function does not work correctly. But that-be do not get an F, the Little Elephant wants to show the performance of its function. Help him, find a permutation of numbers from 1 to n, such that after performing the Little Elephant's function (that is call f(n)), the permutation will be sorted in ascending order. | 256 megabytes | import java.util.Scanner;
public final class Scratch {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
printNumbersAsc(input.nextInt());
}
private static void printNumbersAsc(int n) {
System.out.print(n + " ");
for (int i =1; i<n; i++ ){
System.out.print(i + " ");
}
}
} | Java | ["1", "2"] | 2 seconds | ["1", "2 1"] | null | Java 8 | standard input | [
"implementation",
"math"
] | d9ba1dfe11cf3dae177f8898f3abeefd | A single line contains integer n (1ββ€βnββ€β1000) β the size of permutation. | 1,000 | In a single line print n distinct integers from 1 to n β the required permutation. Numbers in a line should be separated by spaces. It is guaranteed that the answer exists. | standard output | |
PASSED | d6c60e93e46cd281af8f49b5f340f710 | train_001.jsonl | 1346427000 | The Little Elephant enjoys recursive functions.This time he enjoys the sorting function. Let a is a permutation of an integers from 1 to n, inclusive, and ai denotes the i-th element of the permutation. The Little Elephant's recursive function f(x), that sorts the first x permutation's elements, works as follows: If xβ=β1, exit the function. Otherwise, call f(xβ-β1), and then make swap(axβ-β1,βax) (swap the x-th and (xβ-β1)-th elements of a). The Little Elephant's teacher believes that this function does not work correctly. But that-be do not get an F, the Little Elephant wants to show the performance of its function. Help him, find a permutation of numbers from 1 to n, such that after performing the Little Elephant's function (that is call f(n)), the permutation will be sorted in ascending order. | 256 megabytes | import java.util.*;
public class A221 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
StringBuffer ans = new StringBuffer();
for (int i = 0; i < n; i++) {
int cur = (i) % n;
if (cur == 0) {
cur = n;
}
ans.append(cur + " ");
}
System.out.print(ans);
}
} | Java | ["1", "2"] | 2 seconds | ["1", "2 1"] | null | Java 8 | standard input | [
"implementation",
"math"
] | d9ba1dfe11cf3dae177f8898f3abeefd | A single line contains integer n (1ββ€βnββ€β1000) β the size of permutation. | 1,000 | In a single line print n distinct integers from 1 to n β the required permutation. Numbers in a line should be separated by spaces. It is guaranteed that the answer exists. | standard output | |
PASSED | e338ec34342cb946b57a89ee3968fb28 | train_001.jsonl | 1346427000 | The Little Elephant enjoys recursive functions.This time he enjoys the sorting function. Let a is a permutation of an integers from 1 to n, inclusive, and ai denotes the i-th element of the permutation. The Little Elephant's recursive function f(x), that sorts the first x permutation's elements, works as follows: If xβ=β1, exit the function. Otherwise, call f(xβ-β1), and then make swap(axβ-β1,βax) (swap the x-th and (xβ-β1)-th elements of a). The Little Elephant's teacher believes that this function does not work correctly. But that-be do not get an F, the Little Elephant wants to show the performance of its function. Help him, find a permutation of numbers from 1 to n, such that after performing the Little Elephant's function (that is call f(n)), the permutation will be sorted in ascending order. | 256 megabytes | import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n = input.nextInt();
System.out.print(n);
for (int i = 1; i < n; i++)
System.out.print(" " + i);
input.close();
}
} | Java | ["1", "2"] | 2 seconds | ["1", "2 1"] | null | Java 8 | standard input | [
"implementation",
"math"
] | d9ba1dfe11cf3dae177f8898f3abeefd | A single line contains integer n (1ββ€βnββ€β1000) β the size of permutation. | 1,000 | In a single line print n distinct integers from 1 to n β the required permutation. Numbers in a line should be separated by spaces. It is guaranteed that the answer exists. | standard output | |
PASSED | 7fa533babf015d668539828b051e3d46 | train_001.jsonl | 1346427000 | The Little Elephant enjoys recursive functions.This time he enjoys the sorting function. Let a is a permutation of an integers from 1 to n, inclusive, and ai denotes the i-th element of the permutation. The Little Elephant's recursive function f(x), that sorts the first x permutation's elements, works as follows: If xβ=β1, exit the function. Otherwise, call f(xβ-β1), and then make swap(axβ-β1,βax) (swap the x-th and (xβ-β1)-th elements of a). The Little Elephant's teacher believes that this function does not work correctly. But that-be do not get an F, the Little Elephant wants to show the performance of its function. Help him, find a permutation of numbers from 1 to n, such that after performing the Little Elephant's function (that is call f(n)), the permutation will be sorted in ascending order. | 256 megabytes | import java.util.Arrays;
import java.util.Scanner;
public class CF_221A {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
System.out.print(n);
for(int j=1;j<n;j++) {
System.out.print(' ');
System.out.print(j);
}
System.out.println();
}
}
| Java | ["1", "2"] | 2 seconds | ["1", "2 1"] | null | Java 8 | standard input | [
"implementation",
"math"
] | d9ba1dfe11cf3dae177f8898f3abeefd | A single line contains integer n (1ββ€βnββ€β1000) β the size of permutation. | 1,000 | In a single line print n distinct integers from 1 to n β the required permutation. Numbers in a line should be separated by spaces. It is guaranteed that the answer exists. | standard output | |
PASSED | 1172772f101f0f4df8e1c53f315c7cce | train_001.jsonl | 1346427000 | The Little Elephant enjoys recursive functions.This time he enjoys the sorting function. Let a is a permutation of an integers from 1 to n, inclusive, and ai denotes the i-th element of the permutation. The Little Elephant's recursive function f(x), that sorts the first x permutation's elements, works as follows: If xβ=β1, exit the function. Otherwise, call f(xβ-β1), and then make swap(axβ-β1,βax) (swap the x-th and (xβ-β1)-th elements of a). The Little Elephant's teacher believes that this function does not work correctly. But that-be do not get an F, the Little Elephant wants to show the performance of its function. Help him, find a permutation of numbers from 1 to n, such that after performing the Little Elephant's function (that is call f(n)), the permutation will be sorted in ascending order. | 256 megabytes | import java.io.*;
import java.math.*;
import java.util.*;
import java.util.stream.*;
@SuppressWarnings("unchecked")
public class P221A {
int [] a;
void sort(int n) {
if (n == 0) {
return;
}
a[n - 1] ^= a[n];
a[n] ^= a[n - 1];
a[n - 1] ^= a[n];
sort(n - 1);
}
public void run() throws Exception {
int n = nextInt();
a = new int [n];
for (int i = 0; i < n; a[i] = i + 1, i++);
sort(n - 1);
Arrays.stream(a).forEach(v -> print(v + " "));
}
public static void main(String... args) throws Exception {
br = new BufferedReader(new InputStreamReader(System.in));
pw = new PrintWriter(new BufferedOutputStream(System.out));
new P221A().run();
br.close();
pw.close();
System.err.println("\n[Time : " + (System.currentTimeMillis() - startTime) + " ms]");
}
static long startTime = System.currentTimeMillis();
static BufferedReader br;
static PrintWriter pw;
StringTokenizer stok;
String nextToken() throws IOException {
while (stok == null || !stok.hasMoreTokens()) {
String s = br.readLine();
if (s == null) { return null; }
stok = new StringTokenizer(s);
}
return stok.nextToken();
}
void print(byte b) { print("" + b); }
void print(int i) { print("" + i); }
void print(long l) { print("" + l); }
void print(double d) { print("" + d); }
void print(char c) { print("" + c); }
void print(Object o) {
if (o instanceof int[]) { print(Arrays.toString((int [])o));
} else if (o instanceof long[]) { print(Arrays.toString((long [])o));
} else if (o instanceof char[]) { print(Arrays.toString((char [])o));
} else if (o instanceof byte[]) { print(Arrays.toString((byte [])o));
} else if (o instanceof short[]) { print(Arrays.toString((short [])o));
} else if (o instanceof boolean[]) { print(Arrays.toString((boolean [])o));
} else if (o instanceof float[]) { print(Arrays.toString((float [])o));
} else if (o instanceof double[]) { print(Arrays.toString((double [])o));
} else if (o instanceof Object[]) { print(Arrays.toString((Object [])o));
} else { print("" + o); }
}
void print(String s) { pw.print(s); }
void println() { println(""); }
void println(byte b) { println("" + b); }
void println(int i) { println("" + i); }
void println(long l) { println("" + l); }
void println(double d) { println("" + d); }
void println(char c) { println("" + c); }
void println(Object o) { print(o); println(); }
void println(String s) { pw.println(s); }
int nextInt() throws IOException { return Integer.parseInt(nextToken()); }
long nextLong() throws IOException { return Long.parseLong(nextToken()); }
double nextDouble() throws IOException { return Double.parseDouble(nextToken()); }
char nextChar() throws IOException { return (char) (br.read()); }
String next() throws IOException { return nextToken(); }
String nextLine() throws IOException { return br.readLine(); }
int [] readInt(int size) throws IOException {
int [] array = new int [size];
for (int i = 0; i < size; i++) { array[i] = nextInt(); }
return array;
}
long [] readLong(int size) throws IOException {
long [] array = new long [size];
for (int i = 0; i < size; i++) { array[i] = nextLong(); }
return array;
}
double [] readDouble(int size) throws IOException {
double [] array = new double [size];
for (int i = 0; i < size; i++) { array[i] = nextDouble(); }
return array;
}
String [] readLines(int size) throws IOException {
String [] array = new String [size];
for (int i = 0; i < size; i++) { array[i] = nextLine(); }
return array;
}
int gcd(int a, int b) {
if (a == 0) return Math.abs(b); if (b == 0) return Math.abs(a);
a = Math.abs(a); b = Math.abs(b);
int az = Integer.numberOfTrailingZeros(a), bz = Integer.numberOfTrailingZeros(b);
a >>>= az; b >>>= bz;
while (a != b) {
if (a > b) { a -= b; a >>>= Integer.numberOfTrailingZeros(a); }
else { b -= a; b >>>= Integer.numberOfTrailingZeros(b); }
}
return (a << Math.min(az, bz));
}
long gcd(long a, long b) {
if (a == 0) return Math.abs(b); if (b == 0) return Math.abs(a);
a = Math.abs(a); b = Math.abs(b);
int az = Long.numberOfTrailingZeros(a), bz = Long.numberOfTrailingZeros(b);
a >>>= az; b >>>= bz;
while (a != b) {
if (a > b) { a -= b; a >>>= Long.numberOfTrailingZeros(a); }
else { b -= a; b >>>= Long.numberOfTrailingZeros(b); }
}
return (a << Math.min(az, bz));
}
} | Java | ["1", "2"] | 2 seconds | ["1", "2 1"] | null | Java 8 | standard input | [
"implementation",
"math"
] | d9ba1dfe11cf3dae177f8898f3abeefd | A single line contains integer n (1ββ€βnββ€β1000) β the size of permutation. | 1,000 | In a single line print n distinct integers from 1 to n β the required permutation. Numbers in a line should be separated by spaces. It is guaranteed that the answer exists. | standard output | |
PASSED | 32012cf53c685f6dea3d2f1b0ee43ae4 | train_001.jsonl | 1346427000 | The Little Elephant enjoys recursive functions.This time he enjoys the sorting function. Let a is a permutation of an integers from 1 to n, inclusive, and ai denotes the i-th element of the permutation. The Little Elephant's recursive function f(x), that sorts the first x permutation's elements, works as follows: If xβ=β1, exit the function. Otherwise, call f(xβ-β1), and then make swap(axβ-β1,βax) (swap the x-th and (xβ-β1)-th elements of a). The Little Elephant's teacher believes that this function does not work correctly. But that-be do not get an F, the Little Elephant wants to show the performance of its function. Help him, find a permutation of numbers from 1 to n, such that after performing the Little Elephant's function (that is call f(n)), the permutation will be sorted in ascending order. | 256 megabytes | import java.io.*;
import java.math.*;
import java.util.*;
import java.util.stream.*;
@SuppressWarnings("unchecked")
public class P221A {
public void run() throws Exception {
int n = nextInt();
print(n + " ");
for (int i = 1; i < n; print(i + " "), i++);
}
public static void main(String... args) throws Exception {
br = new BufferedReader(new InputStreamReader(System.in));
pw = new PrintWriter(new BufferedOutputStream(System.out));
new P221A().run();
br.close();
pw.close();
System.err.println("\n[Time : " + (System.currentTimeMillis() - startTime) + " ms]");
}
static long startTime = System.currentTimeMillis();
static BufferedReader br;
static PrintWriter pw;
StringTokenizer stok;
String nextToken() throws IOException {
while (stok == null || !stok.hasMoreTokens()) {
String s = br.readLine();
if (s == null) { return null; }
stok = new StringTokenizer(s);
}
return stok.nextToken();
}
void print(byte b) { print("" + b); }
void print(int i) { print("" + i); }
void print(long l) { print("" + l); }
void print(double d) { print("" + d); }
void print(char c) { print("" + c); }
void print(Object o) {
if (o instanceof int[]) { print(Arrays.toString((int [])o));
} else if (o instanceof long[]) { print(Arrays.toString((long [])o));
} else if (o instanceof char[]) { print(Arrays.toString((char [])o));
} else if (o instanceof byte[]) { print(Arrays.toString((byte [])o));
} else if (o instanceof short[]) { print(Arrays.toString((short [])o));
} else if (o instanceof boolean[]) { print(Arrays.toString((boolean [])o));
} else if (o instanceof float[]) { print(Arrays.toString((float [])o));
} else if (o instanceof double[]) { print(Arrays.toString((double [])o));
} else if (o instanceof Object[]) { print(Arrays.toString((Object [])o));
} else { print("" + o); }
}
void print(String s) { pw.print(s); }
void println() { println(""); }
void println(byte b) { println("" + b); }
void println(int i) { println("" + i); }
void println(long l) { println("" + l); }
void println(double d) { println("" + d); }
void println(char c) { println("" + c); }
void println(Object o) { print(o); println(); }
void println(String s) { pw.println(s); }
int nextInt() throws IOException { return Integer.parseInt(nextToken()); }
long nextLong() throws IOException { return Long.parseLong(nextToken()); }
double nextDouble() throws IOException { return Double.parseDouble(nextToken()); }
char nextChar() throws IOException { return (char) (br.read()); }
String next() throws IOException { return nextToken(); }
String nextLine() throws IOException { return br.readLine(); }
int [] readInt(int size) throws IOException {
int [] array = new int [size];
for (int i = 0; i < size; i++) { array[i] = nextInt(); }
return array;
}
long [] readLong(int size) throws IOException {
long [] array = new long [size];
for (int i = 0; i < size; i++) { array[i] = nextLong(); }
return array;
}
double [] readDouble(int size) throws IOException {
double [] array = new double [size];
for (int i = 0; i < size; i++) { array[i] = nextDouble(); }
return array;
}
String [] readLines(int size) throws IOException {
String [] array = new String [size];
for (int i = 0; i < size; i++) { array[i] = nextLine(); }
return array;
}
int gcd(int a, int b) {
if (a == 0) return Math.abs(b); if (b == 0) return Math.abs(a);
a = Math.abs(a); b = Math.abs(b);
int az = Integer.numberOfTrailingZeros(a), bz = Integer.numberOfTrailingZeros(b);
a >>>= az; b >>>= bz;
while (a != b) {
if (a > b) { a -= b; a >>>= Integer.numberOfTrailingZeros(a); }
else { b -= a; b >>>= Integer.numberOfTrailingZeros(b); }
}
return (a << Math.min(az, bz));
}
long gcd(long a, long b) {
if (a == 0) return Math.abs(b); if (b == 0) return Math.abs(a);
a = Math.abs(a); b = Math.abs(b);
int az = Long.numberOfTrailingZeros(a), bz = Long.numberOfTrailingZeros(b);
a >>>= az; b >>>= bz;
while (a != b) {
if (a > b) { a -= b; a >>>= Long.numberOfTrailingZeros(a); }
else { b -= a; b >>>= Long.numberOfTrailingZeros(b); }
}
return (a << Math.min(az, bz));
}
} | Java | ["1", "2"] | 2 seconds | ["1", "2 1"] | null | Java 8 | standard input | [
"implementation",
"math"
] | d9ba1dfe11cf3dae177f8898f3abeefd | A single line contains integer n (1ββ€βnββ€β1000) β the size of permutation. | 1,000 | In a single line print n distinct integers from 1 to n β the required permutation. Numbers in a line should be separated by spaces. It is guaranteed that the answer exists. | standard output | |
PASSED | 687957cd3a3ff5694572d9af7fb0085b | train_001.jsonl | 1346427000 | The Little Elephant enjoys recursive functions.This time he enjoys the sorting function. Let a is a permutation of an integers from 1 to n, inclusive, and ai denotes the i-th element of the permutation. The Little Elephant's recursive function f(x), that sorts the first x permutation's elements, works as follows: If xβ=β1, exit the function. Otherwise, call f(xβ-β1), and then make swap(axβ-β1,βax) (swap the x-th and (xβ-β1)-th elements of a). The Little Elephant's teacher believes that this function does not work correctly. But that-be do not get an F, the Little Elephant wants to show the performance of its function. Help him, find a permutation of numbers from 1 to n, such that after performing the Little Elephant's function (that is call f(n)), the permutation will be sorted in ascending order. | 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 neuivn
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
static class TaskA {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int N = in.nextInt();
out.println(N);
for (int i = 1; i <= N - 1; ++i) out.print(" " + i);
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 | ["1", "2"] | 2 seconds | ["1", "2 1"] | null | Java 8 | standard input | [
"implementation",
"math"
] | d9ba1dfe11cf3dae177f8898f3abeefd | A single line contains integer n (1ββ€βnββ€β1000) β the size of permutation. | 1,000 | In a single line print n distinct integers from 1 to n β the required permutation. Numbers in a line should be separated by spaces. It is guaranteed that the answer exists. | standard output | |
PASSED | 4690d81dde315dd9bd47d4fe4b6cee97 | train_001.jsonl | 1346427000 | The Little Elephant enjoys recursive functions.This time he enjoys the sorting function. Let a is a permutation of an integers from 1 to n, inclusive, and ai denotes the i-th element of the permutation. The Little Elephant's recursive function f(x), that sorts the first x permutation's elements, works as follows: If xβ=β1, exit the function. Otherwise, call f(xβ-β1), and then make swap(axβ-β1,βax) (swap the x-th and (xβ-β1)-th elements of a). The Little Elephant's teacher believes that this function does not work correctly. But that-be do not get an F, the Little Elephant wants to show the performance of its function. Help him, find a permutation of numbers from 1 to n, such that after performing the Little Elephant's function (that is call f(n)), the permutation will be sorted in ascending order. | 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 neuivn
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
static class TaskA {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int N = in.nextInt();
if (N == 1) {
out.println(1);
} else if (N == 2) {
out.println("2 1");
} else {
out.print(N);
for (int i = 1; i <= N - 1; ++i) {
out.print(" " + i);
}
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 | ["1", "2"] | 2 seconds | ["1", "2 1"] | null | Java 8 | standard input | [
"implementation",
"math"
] | d9ba1dfe11cf3dae177f8898f3abeefd | A single line contains integer n (1ββ€βnββ€β1000) β the size of permutation. | 1,000 | In a single line print n distinct integers from 1 to n β the required permutation. Numbers in a line should be separated by spaces. It is guaranteed that the answer exists. | standard output | |
PASSED | 6e09e30a544fd1232fc27249ee0647d1 | train_001.jsonl | 1346427000 | The Little Elephant enjoys recursive functions.This time he enjoys the sorting function. Let a is a permutation of an integers from 1 to n, inclusive, and ai denotes the i-th element of the permutation. The Little Elephant's recursive function f(x), that sorts the first x permutation's elements, works as follows: If xβ=β1, exit the function. Otherwise, call f(xβ-β1), and then make swap(axβ-β1,βax) (swap the x-th and (xβ-β1)-th elements of a). The Little Elephant's teacher believes that this function does not work correctly. But that-be do not get an F, the Little Elephant wants to show the performance of its function. Help him, find a permutation of numbers from 1 to n, such that after performing the Little Elephant's function (that is call f(n)), the permutation will be sorted in ascending order. | 256 megabytes | import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// write your code here
Scanner in = new Scanner (System.in);
int n = in.nextInt();
System.out.print(n + " ");
for (int i = 1; i < n; ++i)
System.out.print(i + " ");
}
}
| Java | ["1", "2"] | 2 seconds | ["1", "2 1"] | null | Java 8 | standard input | [
"implementation",
"math"
] | d9ba1dfe11cf3dae177f8898f3abeefd | A single line contains integer n (1ββ€βnββ€β1000) β the size of permutation. | 1,000 | In a single line print n distinct integers from 1 to n β the required permutation. Numbers in a line should be separated by spaces. It is guaranteed that the answer exists. | standard output | |
PASSED | 90a4e1dc138ed400a8a03e988c256deb | train_001.jsonl | 1346427000 | The Little Elephant enjoys recursive functions.This time he enjoys the sorting function. Let a is a permutation of an integers from 1 to n, inclusive, and ai denotes the i-th element of the permutation. The Little Elephant's recursive function f(x), that sorts the first x permutation's elements, works as follows: If xβ=β1, exit the function. Otherwise, call f(xβ-β1), and then make swap(axβ-β1,βax) (swap the x-th and (xβ-β1)-th elements of a). The Little Elephant's teacher believes that this function does not work correctly. But that-be do not get an F, the Little Elephant wants to show the performance of its function. Help him, find a permutation of numbers from 1 to n, such that after performing the Little Elephant's function (that is call f(n)), the permutation will be sorted in ascending order. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.*;
import java.util.Scanner;
/*f
*/
//---------------------------------------------------------------------------------------------------------------
public class Main {
public static void main(String[] args) {
// Scanner sc = new Scanner(System.in);
FastScanner sc = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
int n=sc.nextInt();
System.out.print(n+" ");
for (int i=1;i<n;i++){
System.out.print(i+" ");
}
out.flush();
}
//------------------------------------------------------------------------------------------------------------
static void sort(int[] a) {
ArrayList<Integer> l=new ArrayList<>();
for (int i:a) l.add(i);
Collections.sort(l);
for (int i=0; i<a.length; i++) a[i]=l.get(i);
}
static int[] find(int n,int start,int diff){
int a[]= new int[n];
a[0]=start;
for (int i=1;i<n;i++)a[i]=a[i-1]+diff;
return a;
}
static void swap(int a,int b){
int c=a;
a=b;
b=c;
}
static void printArray(int a[]){
for (int i=0;i<a.length;i++){
System.out.print(a[i]+" ");
}
}
static boolean sorted(int a[]){
int n=a.length;
boolean flag=true;
for (int i=0;i<n-1;i++){
if (a[i]>a[i+1])flag=false;
}
if (flag)return true;
else return false;
}
public static int findlog(long n){
if(n == 0)
return 0;
if(n == 1)
return 0;
if(n == 2)
return 1;
double num = Math.log(n);
double den = Math.log(2);
if(den == 0)
return 0;
return (int)(num/den);
}
public static long gcd(long a,long b){
if(b%a == 0)
return a;
return gcd(b%a,a);
}
public static int gcdInt(int a,int b){
if(b%a == 0)
return a;
return gcdInt(b%a,a);
}
static void sortReverse(long[] a) {
ArrayList<Long> l=new ArrayList<>();
for (long i:a) l.add(i);
// Collections.sort.(l);
Collections.sort(l,Collections.reverseOrder());
for (int i=0; i<a.length; i++) a[i]=l.get(i);
}
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[] readArrayLong(long n) {
long[] a=new long[(int)n];
for (int i=0; i<n; i++) a[i]=nextLong();
return a;
}
long nextLong() {
return Long.parseLong(next());
}
}
} | Java | ["1", "2"] | 2 seconds | ["1", "2 1"] | null | Java 8 | standard input | [
"implementation",
"math"
] | d9ba1dfe11cf3dae177f8898f3abeefd | A single line contains integer n (1ββ€βnββ€β1000) β the size of permutation. | 1,000 | In a single line print n distinct integers from 1 to n β the required permutation. Numbers in a line should be separated by spaces. It is guaranteed that the answer exists. | standard output | |
PASSED | 4cd39020077ca642bb35689c95ba7868 | train_001.jsonl | 1346427000 | The Little Elephant enjoys recursive functions.This time he enjoys the sorting function. Let a is a permutation of an integers from 1 to n, inclusive, and ai denotes the i-th element of the permutation. The Little Elephant's recursive function f(x), that sorts the first x permutation's elements, works as follows: If xβ=β1, exit the function. Otherwise, call f(xβ-β1), and then make swap(axβ-β1,βax) (swap the x-th and (xβ-β1)-th elements of a). The Little Elephant's teacher believes that this function does not work correctly. But that-be do not get an F, the Little Elephant wants to show the performance of its function. Help him, find a permutation of numbers from 1 to n, such that after performing the Little Elephant's function (that is call f(n)), the permutation will be sorted in ascending order. | 256 megabytes | import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Spandan Mishra
*/
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);
ALittleElephantAndFunction solver = new ALittleElephantAndFunction();
solver.solve(1, in, out);
out.close();
}
static class ALittleElephantAndFunction {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.readInt();
StringBuilder sb = new StringBuilder();
sb.append(n + " ");
for (int i = 1; i < n; i++)
sb.append(i + " ");
System.out.println(sb);
}
}
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 RuntimeException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new RuntimeException();
}
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 {
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
}
}
| Java | ["1", "2"] | 2 seconds | ["1", "2 1"] | null | Java 8 | standard input | [
"implementation",
"math"
] | d9ba1dfe11cf3dae177f8898f3abeefd | A single line contains integer n (1ββ€βnββ€β1000) β the size of permutation. | 1,000 | In a single line print n distinct integers from 1 to n β the required permutation. Numbers in a line should be separated by spaces. It is guaranteed that the answer exists. | standard output | |
PASSED | 086a793b421ee4180ff8b50cea2faf57 | train_001.jsonl | 1346427000 | The Little Elephant enjoys recursive functions.This time he enjoys the sorting function. Let a is a permutation of an integers from 1 to n, inclusive, and ai denotes the i-th element of the permutation. The Little Elephant's recursive function f(x), that sorts the first x permutation's elements, works as follows: If xβ=β1, exit the function. Otherwise, call f(xβ-β1), and then make swap(axβ-β1,βax) (swap the x-th and (xβ-β1)-th elements of a). The Little Elephant's teacher believes that this function does not work correctly. But that-be do not get an F, the Little Elephant wants to show the performance of its function. Help him, find a permutation of numbers from 1 to n, such that after performing the Little Elephant's function (that is call f(n)), the permutation will be sorted in ascending order. | 256 megabytes | import java.util.Scanner;
public class Binarysearch {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n = input.nextInt();
System.out.printf("%d%s",n,(n==1)?"\n":" ");
for(int i=1;i<=(n-1);i++){
System.out.printf("%d%s",i,(i== n-1)?"\n":" ");
}
}
} | Java | ["1", "2"] | 2 seconds | ["1", "2 1"] | null | Java 8 | standard input | [
"implementation",
"math"
] | d9ba1dfe11cf3dae177f8898f3abeefd | A single line contains integer n (1ββ€βnββ€β1000) β the size of permutation. | 1,000 | In a single line print n distinct integers from 1 to n β the required permutation. Numbers in a line should be separated by spaces. It is guaranteed that the answer exists. | standard output | |
PASSED | b04f8083b71946e2eae2cd5d3b8673f4 | train_001.jsonl | 1346427000 | The Little Elephant enjoys recursive functions.This time he enjoys the sorting function. Let a is a permutation of an integers from 1 to n, inclusive, and ai denotes the i-th element of the permutation. The Little Elephant's recursive function f(x), that sorts the first x permutation's elements, works as follows: If xβ=β1, exit the function. Otherwise, call f(xβ-β1), and then make swap(axβ-β1,βax) (swap the x-th and (xβ-β1)-th elements of a). The Little Elephant's teacher believes that this function does not work correctly. But that-be do not get an F, the Little Elephant wants to show the performance of its function. Help him, find a permutation of numbers from 1 to n, such that after performing the Little Elephant's function (that is call f(n)), the permutation will be sorted in ascending order. | 256 megabytes | import java.util.Scanner;
public class LittleElephantandFunction
{
public static void main(String[] args)
{
Scanner z=new Scanner(System.in);
int n=z.nextInt();
int[] a=new int[n];
while(n>=1){
a[n-1]=n;
n--;
}
int temp=0;
for(int x=a.length-1;x>0;x--)
{
temp=a[x];
a[x]=a[x-1];
a[x-1]=temp;
}
for(int aa:a)
System.out.print(aa+" ");
}
}
| Java | ["1", "2"] | 2 seconds | ["1", "2 1"] | null | Java 8 | standard input | [
"implementation",
"math"
] | d9ba1dfe11cf3dae177f8898f3abeefd | A single line contains integer n (1ββ€βnββ€β1000) β the size of permutation. | 1,000 | In a single line print n distinct integers from 1 to n β the required permutation. Numbers in a line should be separated by spaces. It is guaranteed that the answer exists. | standard output | |
PASSED | 82f4429f9c7272b1c8f487eab9c6d6e0 | train_001.jsonl | 1346427000 | The Little Elephant enjoys recursive functions.This time he enjoys the sorting function. Let a is a permutation of an integers from 1 to n, inclusive, and ai denotes the i-th element of the permutation. The Little Elephant's recursive function f(x), that sorts the first x permutation's elements, works as follows: If xβ=β1, exit the function. Otherwise, call f(xβ-β1), and then make swap(axβ-β1,βax) (swap the x-th and (xβ-β1)-th elements of a). The Little Elephant's teacher believes that this function does not work correctly. But that-be do not get an F, the Little Elephant wants to show the performance of its function. Help him, find a permutation of numbers from 1 to n, such that after performing the Little Elephant's function (that is call f(n)), the permutation will be sorted in ascending order. | 256 megabytes | import java.util.Scanner;
public class LittleElephantandFunction {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n=scan.nextInt();
int[] a= new int[n];
for(int i=0;i<n;i++)
{
a[i]=i+1;
}
System.out.print(a[a.length-1]+" ");
for(int i=0;i<n-1;i++)
{
System.out.print(a[i]+" ");
}
}
}
| Java | ["1", "2"] | 2 seconds | ["1", "2 1"] | null | Java 8 | standard input | [
"implementation",
"math"
] | d9ba1dfe11cf3dae177f8898f3abeefd | A single line contains integer n (1ββ€βnββ€β1000) β the size of permutation. | 1,000 | In a single line print n distinct integers from 1 to n β the required permutation. Numbers in a line should be separated by spaces. It is guaranteed that the answer exists. | standard output | |
PASSED | a472a98b305e1665f5bfe65934a2fca2 | train_001.jsonl | 1346427000 | The Little Elephant enjoys recursive functions.This time he enjoys the sorting function. Let a is a permutation of an integers from 1 to n, inclusive, and ai denotes the i-th element of the permutation. The Little Elephant's recursive function f(x), that sorts the first x permutation's elements, works as follows: If xβ=β1, exit the function. Otherwise, call f(xβ-β1), and then make swap(axβ-β1,βax) (swap the x-th and (xβ-β1)-th elements of a). The Little Elephant's teacher believes that this function does not work correctly. But that-be do not get an F, the Little Elephant wants to show the performance of its function. Help him, find a permutation of numbers from 1 to n, such that after performing the Little Elephant's function (that is call f(n)), the permutation will be sorted in ascending order. | 256 megabytes |
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class LittleElephantAndFunction {
public static void main(String[] args) {
out = new PrintWriter(new BufferedOutputStream(System.out));
Reader in = new Reader();
int n = in.readInt();
out.print(n + " ");
for(int i = 1; i < n; i++) out.print(i + " ");
in.close();
out.close();
}
static PrintWriter out;
static class Reader {
BufferedReader br;
StringTokenizer st;
public Reader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String read() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int readInt() {
return Integer.parseInt(read());
}
long readLong() {
return Long.parseLong(read());
}
double readDouble() {
return Double.parseDouble(read());
}
char readChar() {
return read().charAt(0);
}
int[] readIntArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = readInt();
return a;
}
long[] readLongArray(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = readLong();
return a;
}
double[] readDoubleArray(int n) {
double[] a = new double[n];
for (int i = 0; i < n; i++)
a[i] = readDouble();
return a;
}
String[] readStringArray(int n) {
String[] s = new String[n];
for (int i = 0; i < n; i++)
s[i] = read();
return s;
}
char[] readCharArray(int n) {
char[] ch = new char[n];
for (int i = 0; i < n; i++)
ch[i] = readChar();
return ch;
}
String readLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
void close() {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
| Java | ["1", "2"] | 2 seconds | ["1", "2 1"] | null | Java 8 | standard input | [
"implementation",
"math"
] | d9ba1dfe11cf3dae177f8898f3abeefd | A single line contains integer n (1ββ€βnββ€β1000) β the size of permutation. | 1,000 | In a single line print n distinct integers from 1 to n β the required permutation. Numbers in a line should be separated by spaces. It is guaranteed that the answer exists. | standard output | |
PASSED | 542ec10f61d904b952a25507ef85f028 | train_001.jsonl | 1346427000 | The Little Elephant enjoys recursive functions.This time he enjoys the sorting function. Let a is a permutation of an integers from 1 to n, inclusive, and ai denotes the i-th element of the permutation. The Little Elephant's recursive function f(x), that sorts the first x permutation's elements, works as follows: If xβ=β1, exit the function. Otherwise, call f(xβ-β1), and then make swap(axβ-β1,βax) (swap the x-th and (xβ-β1)-th elements of a). The Little Elephant's teacher believes that this function does not work correctly. But that-be do not get an F, the Little Elephant wants to show the performance of its function. Help him, find a permutation of numbers from 1 to n, such that after performing the Little Elephant's function (that is call f(n)), the permutation will be sorted in ascending order. | 256 megabytes |
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
import java.lang.*;
public class P221A{
static long mod=1000000007;
public static void main(String[] args) throws Exception{
InputReader in = new InputReader(System.in);
PrintWriter pw=new PrintWriter(System.out);
//int t=in.readInt();
// while(t-->0)
//{
int n=in.readInt();
//long n=in.readLong();
/*int a[]=new int[n];
for(int i=0;i<n;i++)
{
a[i]=in.readInt();
}*/
//String a=in.readString();
pw.print(n+" ");
for(int i=1;i<=n-1;i++)
pw.print(i+" ");
// pw.print("1");
//pw.println(" ");
//}
pw.close();
}
/* returns nCr mod m */
public static long comb(long n, long r, long m)
{
long p1 = 1, p2 = 1;
for (long i = r + 1; i <= n; i++) {
p1 = (p1 * i) % m;
}
p2 = factMod(n - r, m);
p1 = divMod(p1, p2, m);
return p1 % m;
}
/* returns a/b mod m, works only if m is prime and b divides a */
public static long divMod(long a, long b, long m)
{
long c = powerMod(b, m - 2, m);
return ((a % m) * (c % m)) % m;
}
/* calculates factorial(n) mod m */
public static long factMod(long n, long m) {
long result = 1;
if (n <= 1)
return 1;
while (n != 1) {
result = ((result * n--) % m);
}
return result;
}
/* This method takes a, b and c as inputs and returns (a ^ b) mod c */
public static long powerMod(long a, long b, long c) {
long result = 1;
long temp = 1;
long mask = 1;
for (int i = 0; i < 64; i++) {
mask = (i == 0) ? 1 : (mask * 2);
temp = (i == 0) ? (a % c) : (temp * temp) % c;
/* Check if (i + 1)th bit of power b is set */
if ((b & mask) == mask) {
result = (result * temp) % c;
}
}
return result;
}
static boolean isPrime(int number) {
if (number <= 1) {
return false;
}
if (number <= 3) {
return true;
}
if (number % 2 == 0 || number % 3 == 0) {
return false;
}
int i = 5;
while (i * i <= number) {
if (number % i == 0 || number % (i + 2) == 0) {
return false;
}
i += 6;
}
return true;
}
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 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;
}
static boolean isPowerOfTwo (long v) {
return (v & (v - 1)) == 0;
}
public static long pow(long n,long p,long m)
{
long result = 1;
if(p==0)
return 1;
if (p==1)
return n;
while(p!=0)
{
if(p%2==1)
result *= n;
if(result>=m)
result%=m;
p >>=1;
n*=n;
if(n>=m)
n%=m;
}
return result;
}
public static long pow(long n,long p)
{
long result = 1;
if(p==0)
return 1;
if (p==1)
return n;
while(p!=0)
{
if(p%2==1)
result *= n;
p >>=1;
n*=n;
}
return result;
}
static class Pair implements Comparable<Pair>
{
int a,b;
Pair (int a,int b)
{
this.a=a;
this.b=b;
}
public int compareTo(Pair o) {
// TODO Auto-generated method stub
if(this.a!=o.a)
return Integer.compare(this.a,o.a);
else
return Integer.compare(this.b, o.b);
//return 0;
}
public boolean equals(Object o) {
if (o instanceof Pair) {
Pair p = (Pair)o;
return p.a == a && p.b == b;
}
return false;
}
public int hashCode() {
return new Integer(a).hashCode() * 31 + new Integer(b).hashCode();
}
}
static long sort(int a[],int n)
{ int b[]=new int[n];
return mergeSort(a,b,0,n-1);}
static long mergeSort(int a[],int b[],long left,long right)
{ long c=0;if(left<right)
{ long mid=left+(right-left)/2;
c= mergeSort(a,b,left,mid);
c+=mergeSort(a,b,mid+1,right);
c+=merge(a,b,left,mid+1,right); }
return c; }
static long merge(int a[],int b[],long left,long mid,long right)
{long c=0;int i=(int)left;int j=(int)mid; int k=(int)left;
while(i<=(int)mid-1&&j<=(int)right)
{ if(a[i]<=a[j]) {b[k++]=a[i++]; }
else { b[k++]=a[j++];c+=mid-i;}}
while (i <= (int)mid - 1) b[k++] = a[i++];
while (j <= (int)right) b[k++] = a[j++];
for (i=(int)left; i <= (int)right; i++)
a[i] = b[i]; return c; }
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 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 double readDouble() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.') {
if (c == 'e' || c == 'E')
return res * Math.pow(10, readInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
if (c == '.') {
c = read();
double m = 1;
while (!isSpaceChar(c)) {
if (c == 'e' || c == 'E')
return res * Math.pow(10, readInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
m /= 10;
res += (c - '0') * m;
c = read();
}
}
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 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 OutputWriter
{
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream)
{
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer)
{
this.writer = new PrintWriter(writer);
}
public void print(Object... objects)
{
for (int i = 0; i < objects.length; i++)
{
if (i != 0)
writer.print(' ');
writer.print(objects[i]);
}
}
public void printLine(Object... objects)
{
print(objects);
writer.println();
}
public void close()
{
writer.close();
}
public void flush()
{
writer.flush();
}
}
/* USAGE
//initialize
InputReader in = new InputReader(System.in);
OutputWriter out = new OutputWriter(System.out);
//read int
int i = in.readInt();
//read string
String s = in.readString();
//read int array of size N
int[] x = IOUtils.readIntArray(in,N);
//printline
out.printLine("X");
//flush output
out.flush();
//remember to close the
//outputstream, at the end
out.close();
*/
static class IOUtils {
public static int[] readIntArray(InputReader in, int size) {
int[] array = new int[size];
for (int i = 0; i < size; i++)
array[i] = in.readInt();
return array;
}
}
//BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
//StringBuilder sb=new StringBuilder("");
//InputReader in = new InputReader(System.in);
// OutputWriter out = new OutputWriter(System.out);
//PrintWriter pw=new PrintWriter(System.out);
//String line=br.readLine().trim();
//int t=Integer.parseInt(br.readLine());
// while(t-->0)
//{
//int n=Integer.parseInt(br.readLine());
//long n=Long.parseLong(br.readLine());
//String l[]=br.readLine().split(" ");
//int m=Integer.parseInt(l[0]);
//int k=Integer.parseInt(l[1]);
//String l[]=br.readLine().split(" ");
//l=br.readLine().split(" ");
/*int a[]=new int[n];
for(int i=0;i<n;i++)
{
a[i]=Integer.parseInt(l[i]);
}*/
//System.out.println(" ");
//}
}
| Java | ["1", "2"] | 2 seconds | ["1", "2 1"] | null | Java 8 | standard input | [
"implementation",
"math"
] | d9ba1dfe11cf3dae177f8898f3abeefd | A single line contains integer n (1ββ€βnββ€β1000) β the size of permutation. | 1,000 | In a single line print n distinct integers from 1 to n β the required permutation. Numbers in a line should be separated by spaces. It is guaranteed that the answer exists. | standard output | |
PASSED | eea64ec9efb7bea251fd7212815cdab9 | train_001.jsonl | 1346427000 | The Little Elephant enjoys recursive functions.This time he enjoys the sorting function. Let a is a permutation of an integers from 1 to n, inclusive, and ai denotes the i-th element of the permutation. The Little Elephant's recursive function f(x), that sorts the first x permutation's elements, works as follows: If xβ=β1, exit the function. Otherwise, call f(xβ-β1), and then make swap(axβ-β1,βax) (swap the x-th and (xβ-β1)-th elements of a). The Little Elephant's teacher believes that this function does not work correctly. But that-be do not get an F, the Little Elephant wants to show the performance of its function. Help him, find a permutation of numbers from 1 to n, such that after performing the Little Elephant's function (that is call f(n)), the permutation will be sorted in ascending order. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class LittleElephantAndFunction {
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int permutationCount = Integer.parseInt(br.readLine());
String toDisplay = "";
for(int i = 1; i < permutationCount; i++){
toDisplay += " " + i;
}
toDisplay = permutationCount + toDisplay;
System.out.println(toDisplay);
}
} | Java | ["1", "2"] | 2 seconds | ["1", "2 1"] | null | Java 8 | standard input | [
"implementation",
"math"
] | d9ba1dfe11cf3dae177f8898f3abeefd | A single line contains integer n (1ββ€βnββ€β1000) β the size of permutation. | 1,000 | In a single line print n distinct integers from 1 to n β the required permutation. Numbers in a line should be separated by spaces. It is guaranteed that the answer exists. | standard output | |
PASSED | 43fa7f6d0cf181e476893356ea5d83fd | train_001.jsonl | 1346427000 | The Little Elephant enjoys recursive functions.This time he enjoys the sorting function. Let a is a permutation of an integers from 1 to n, inclusive, and ai denotes the i-th element of the permutation. The Little Elephant's recursive function f(x), that sorts the first x permutation's elements, works as follows: If xβ=β1, exit the function. Otherwise, call f(xβ-β1), and then make swap(axβ-β1,βax) (swap the x-th and (xβ-β1)-th elements of a). The Little Elephant's teacher believes that this function does not work correctly. But that-be do not get an F, the Little Elephant wants to show the performance of its function. Help him, find a permutation of numbers from 1 to n, such that after performing the Little Elephant's function (that is call f(n)), the permutation will be sorted in ascending order. | 256 megabytes | import java.util.*;
import java.io.*;
import java.math.BigInteger;
public class a
{
public static void main(String[] arg) throws IOException
{
new a();
}
public a() throws IOException
{
FastScanner in = new FastScanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = in.nextInt();
out.print(n + " ");
for(int i = 1; i < n; i++)
{
out.print(i + " ");
}
in.close(); out.close();
}
class FastScanner
{
BufferedReader br;
StringTokenizer st;
public FastScanner(InputStream in)
{
br = new BufferedReader(new InputStreamReader(in));
st = new StringTokenizer("");
}
public String next() throws IOException
{
while(!st.hasMoreTokens()) st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException
{
return Integer.parseInt(next());
}
public void close() throws IOException
{
br.close();
}
}
}
| Java | ["1", "2"] | 2 seconds | ["1", "2 1"] | null | Java 8 | standard input | [
"implementation",
"math"
] | d9ba1dfe11cf3dae177f8898f3abeefd | A single line contains integer n (1ββ€βnββ€β1000) β the size of permutation. | 1,000 | In a single line print n distinct integers from 1 to n β the required permutation. Numbers in a line should be separated by spaces. It is guaranteed that the answer exists. | standard output | |
PASSED | 47e99cfcaa38aaad9e4004d6b9b5401f | train_001.jsonl | 1346427000 | The Little Elephant enjoys recursive functions.This time he enjoys the sorting function. Let a is a permutation of an integers from 1 to n, inclusive, and ai denotes the i-th element of the permutation. The Little Elephant's recursive function f(x), that sorts the first x permutation's elements, works as follows: If xβ=β1, exit the function. Otherwise, call f(xβ-β1), and then make swap(axβ-β1,βax) (swap the x-th and (xβ-β1)-th elements of a). The Little Elephant's teacher believes that this function does not work correctly. But that-be do not get an F, the Little Elephant wants to show the performance of its function. Help him, find a permutation of numbers from 1 to n, such that after performing the Little Elephant's function (that is call f(n)), the permutation will be sorted in ascending order. | 256 megabytes |
import java.util.*;
import java.io.*;
public class Q2A {
// main method
public static void main(String[] args) throws IOException {
//BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
Scanner sc = new Scanner(System.in);
int n =sc.nextInt();
System.out.print(n+" ");
for(int i=1;i<n;i++)
System.out.print(i+" ");
// end of main
}
}
| Java | ["1", "2"] | 2 seconds | ["1", "2 1"] | null | Java 8 | standard input | [
"implementation",
"math"
] | d9ba1dfe11cf3dae177f8898f3abeefd | A single line contains integer n (1ββ€βnββ€β1000) β the size of permutation. | 1,000 | In a single line print n distinct integers from 1 to n β the required permutation. Numbers in a line should be separated by spaces. It is guaranteed that the answer exists. | standard output | |
PASSED | 4f10e225be8d495aed36ac714cf3f65b | train_001.jsonl | 1346427000 | The Little Elephant enjoys recursive functions.This time he enjoys the sorting function. Let a is a permutation of an integers from 1 to n, inclusive, and ai denotes the i-th element of the permutation. The Little Elephant's recursive function f(x), that sorts the first x permutation's elements, works as follows: If xβ=β1, exit the function. Otherwise, call f(xβ-β1), and then make swap(axβ-β1,βax) (swap the x-th and (xβ-β1)-th elements of a). The Little Elephant's teacher believes that this function does not work correctly. But that-be do not get an F, the Little Elephant wants to show the performance of its function. Help him, find a permutation of numbers from 1 to n, such that after performing the Little Elephant's function (that is call f(n)), the permutation will be sorted in ascending order. | 256 megabytes | import java.util.*;
public class LittleElephantFunction {
static Scanner scn = new Scanner(System.in);
public static void main(String[] args) {
helper();
}
public static void helper() {
int n = (int)input();
print(n + " ");
for (int i = 1; i < n; i++)
print(i + " ");
print();
}
public static long input() {
return scn.nextLong();
}
public static String input(int... var) {
return scn.next();
}
public static void TakeInput(int[] arr) {
for (int i = 0; i < arr.length; i++)
arr[i] = (int)input();
}
public static <T> void printArray(T[] arr) {
for (T val : arr)
print(val + " ");
print("\n");
}
public static <T> void print(T t) {
System.out.print(t);
}
public static void print() {
System.out.println();
}
} | Java | ["1", "2"] | 2 seconds | ["1", "2 1"] | null | Java 8 | standard input | [
"implementation",
"math"
] | d9ba1dfe11cf3dae177f8898f3abeefd | A single line contains integer n (1ββ€βnββ€β1000) β the size of permutation. | 1,000 | In a single line print n distinct integers from 1 to n β the required permutation. Numbers in a line should be separated by spaces. It is guaranteed that the answer exists. | standard output | |
PASSED | 55713e2a8dab89673ae08f0873473510 | train_001.jsonl | 1346427000 | The Little Elephant enjoys recursive functions.This time he enjoys the sorting function. Let a is a permutation of an integers from 1 to n, inclusive, and ai denotes the i-th element of the permutation. The Little Elephant's recursive function f(x), that sorts the first x permutation's elements, works as follows: If xβ=β1, exit the function. Otherwise, call f(xβ-β1), and then make swap(axβ-β1,βax) (swap the x-th and (xβ-β1)-th elements of a). The Little Elephant's teacher believes that this function does not work correctly. But that-be do not get an F, the Little Elephant wants to show the performance of its function. Help him, find a permutation of numbers from 1 to n, such that after performing the Little Elephant's function (that is call f(n)), the permutation will be sorted in ascending order. | 256 megabytes | import java.util.Scanner;
public class LittleElephant {
public static void main(String arg[])
{
Scanner sc=new Scanner(System.in);
StringBuilder sb=new StringBuilder();
int n=sc.nextInt();
if(n==1)
{
System.out.println("1");
return;
}
else
{
System.out.print(n+" ");
for(int i=1;i<n;i++)
{
System.out.print(i+" ");
}
}
}
}
| Java | ["1", "2"] | 2 seconds | ["1", "2 1"] | null | Java 8 | standard input | [
"implementation",
"math"
] | d9ba1dfe11cf3dae177f8898f3abeefd | A single line contains integer n (1ββ€βnββ€β1000) β the size of permutation. | 1,000 | In a single line print n distinct integers from 1 to n β the required permutation. Numbers in a line should be separated by spaces. It is guaranteed that the answer exists. | standard output | |
PASSED | 84aaa37a4951c3ddb940e9b4e9d347ba | train_001.jsonl | 1346427000 | The Little Elephant enjoys recursive functions.This time he enjoys the sorting function. Let a is a permutation of an integers from 1 to n, inclusive, and ai denotes the i-th element of the permutation. The Little Elephant's recursive function f(x), that sorts the first x permutation's elements, works as follows: If xβ=β1, exit the function. Otherwise, call f(xβ-β1), and then make swap(axβ-β1,βax) (swap the x-th and (xβ-β1)-th elements of a). The Little Elephant's teacher believes that this function does not work correctly. But that-be do not get an F, the Little Elephant wants to show the performance of its function. Help him, find a permutation of numbers from 1 to n, such that after performing the Little Elephant's function (that is call f(n)), the permutation will be sorted in ascending order. | 256 megabytes | import java.util.*;
import java.lang.*;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.io.*;
public class Solution {
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());
}
public int[] readIntArray(int n) {
int[] arr = new int[n];
for(int i=0; i<n; ++i)
arr[i]=nextInt();
return arr;
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try{
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
static void swap(int a, int b) {
int temp = a;
a = b;
b = temp;
System.out.print(a+" ");
}
static void solve(int n) {
System.out.print(n+" ");
for(int i=1;i<n;i++) {
System.out.print(i+" ");
}
}
public static void main(String args[]) {
FastReader sc = new FastReader();
long start = System.currentTimeMillis();
int n = sc.nextInt();
solve(n);
long end = System.currentTimeMillis();
NumberFormat formatter = new DecimalFormat("#0.00000");
//System.out.print("Execution time is " + formatter.format((end - start) / 1000d) + " seconds");
}
}
| Java | ["1", "2"] | 2 seconds | ["1", "2 1"] | null | Java 8 | standard input | [
"implementation",
"math"
] | d9ba1dfe11cf3dae177f8898f3abeefd | A single line contains integer n (1ββ€βnββ€β1000) β the size of permutation. | 1,000 | In a single line print n distinct integers from 1 to n β the required permutation. Numbers in a line should be separated by spaces. It is guaranteed that the answer exists. | standard output | |
PASSED | bca334f177c6d2089668e485f57f3c78 | train_001.jsonl | 1346427000 | The Little Elephant enjoys recursive functions.This time he enjoys the sorting function. Let a is a permutation of an integers from 1 to n, inclusive, and ai denotes the i-th element of the permutation. The Little Elephant's recursive function f(x), that sorts the first x permutation's elements, works as follows: If xβ=β1, exit the function. Otherwise, call f(xβ-β1), and then make swap(axβ-β1,βax) (swap the x-th and (xβ-β1)-th elements of a). The Little Elephant's teacher believes that this function does not work correctly. But that-be do not get an F, the Little Elephant wants to show the performance of its function. Help him, find a permutation of numbers from 1 to n, such that after performing the Little Elephant's function (that is call f(n)), the permutation will be sorted in ascending order. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
import java.util.StringTokenizer;
import java.lang.*;
import java.util.*;
public class Main
{
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
public static void main(String[] args)
{
FastReader ob=new FastReader();
int n = ob.nextInt();
System.out.print(n+" ");
int i=1;
while(i<n){
System.out.print(i+" ");
i++;
}
}
} | Java | ["1", "2"] | 2 seconds | ["1", "2 1"] | null | Java 8 | standard input | [
"implementation",
"math"
] | d9ba1dfe11cf3dae177f8898f3abeefd | A single line contains integer n (1ββ€βnββ€β1000) β the size of permutation. | 1,000 | In a single line print n distinct integers from 1 to n β the required permutation. Numbers in a line should be separated by spaces. It is guaranteed that the answer exists. | standard output | |
PASSED | 51c18259c021a142fe8a345649694cd8 | train_001.jsonl | 1346427000 | The Little Elephant enjoys recursive functions.This time he enjoys the sorting function. Let a is a permutation of an integers from 1 to n, inclusive, and ai denotes the i-th element of the permutation. The Little Elephant's recursive function f(x), that sorts the first x permutation's elements, works as follows: If xβ=β1, exit the function. Otherwise, call f(xβ-β1), and then make swap(axβ-β1,βax) (swap the x-th and (xβ-β1)-th elements of a). The Little Elephant's teacher believes that this function does not work correctly. But that-be do not get an F, the Little Elephant wants to show the performance of its function. Help him, find a permutation of numbers from 1 to n, such that after performing the Little Elephant's function (that is call f(n)), the permutation will be sorted in ascending order. | 256 megabytes | import java.io.*;
import java.util.*;
import java.util.Map.*;
public class j {
public static void main(String[] args) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
System.out.print(n+" ");
for(int i=1;i<n;i++) System.out.print(i+" ");
}
} | Java | ["1", "2"] | 2 seconds | ["1", "2 1"] | null | Java 8 | standard input | [
"implementation",
"math"
] | d9ba1dfe11cf3dae177f8898f3abeefd | A single line contains integer n (1ββ€βnββ€β1000) β the size of permutation. | 1,000 | In a single line print n distinct integers from 1 to n β the required permutation. Numbers in a line should be separated by spaces. It is guaranteed that the answer exists. | standard output | |
PASSED | 1f168d6d2c5b35908457fe6e589e3035 | train_001.jsonl | 1346427000 | The Little Elephant enjoys recursive functions.This time he enjoys the sorting function. Let a is a permutation of an integers from 1 to n, inclusive, and ai denotes the i-th element of the permutation. The Little Elephant's recursive function f(x), that sorts the first x permutation's elements, works as follows: If xβ=β1, exit the function. Otherwise, call f(xβ-β1), and then make swap(axβ-β1,βax) (swap the x-th and (xβ-β1)-th elements of a). The Little Elephant's teacher believes that this function does not work correctly. But that-be do not get an F, the Little Elephant wants to show the performance of its function. Help him, find a permutation of numbers from 1 to n, such that after performing the Little Elephant's function (that is call f(n)), the permutation will be sorted in ascending order. | 256 megabytes |
import java.util.*;
public class TRISQ {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
System.out.print(n);
for(int i=1; i<n;i++){
System.out.print(" "+i);
}
}
} | Java | ["1", "2"] | 2 seconds | ["1", "2 1"] | null | Java 8 | standard input | [
"implementation",
"math"
] | d9ba1dfe11cf3dae177f8898f3abeefd | A single line contains integer n (1ββ€βnββ€β1000) β the size of permutation. | 1,000 | In a single line print n distinct integers from 1 to n β the required permutation. Numbers in a line should be separated by spaces. It is guaranteed that the answer exists. | standard output | |
PASSED | bce201434141e72e582b67351fad63be | train_001.jsonl | 1346427000 | The Little Elephant enjoys recursive functions.This time he enjoys the sorting function. Let a is a permutation of an integers from 1 to n, inclusive, and ai denotes the i-th element of the permutation. The Little Elephant's recursive function f(x), that sorts the first x permutation's elements, works as follows: If xβ=β1, exit the function. Otherwise, call f(xβ-β1), and then make swap(axβ-β1,βax) (swap the x-th and (xβ-β1)-th elements of a). The Little Elephant's teacher believes that this function does not work correctly. But that-be do not get an F, the Little Elephant wants to show the performance of its function. Help him, find a permutation of numbers from 1 to n, such that after performing the Little Elephant's function (that is call f(n)), the permutation will be sorted in ascending order. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author o_panda_o(emailofpanda@yahoo.com)
*/
public class Code_221A_LittleElephantAndFunction{
public static void main(String[] args){
InputStream inputStream=System.in;
OutputStream outputStream=System.out;
InputReader in=new InputReader(inputStream);
OutputWriter out=new OutputWriter(outputStream);
_221A_ solver=new _221A_();
solver.solve(1,in,out);
out.close();
}
static class _221A_{
public void solve(int testNumber,InputReader in,OutputWriter out){
int n=in.nextInt();
out.print(n,"");
for(int i=1;i<=n-1;++i) 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();
}
}
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 | ["1", "2"] | 2 seconds | ["1", "2 1"] | null | Java 8 | standard input | [
"implementation",
"math"
] | d9ba1dfe11cf3dae177f8898f3abeefd | A single line contains integer n (1ββ€βnββ€β1000) β the size of permutation. | 1,000 | In a single line print n distinct integers from 1 to n β the required permutation. Numbers in a line should be separated by spaces. It is guaranteed that the answer exists. | standard output | |
PASSED | 2c8ac34a801ac639e324f572f9b3c1dd | train_001.jsonl | 1346427000 | The Little Elephant enjoys recursive functions.This time he enjoys the sorting function. Let a is a permutation of an integers from 1 to n, inclusive, and ai denotes the i-th element of the permutation. The Little Elephant's recursive function f(x), that sorts the first x permutation's elements, works as follows: If xβ=β1, exit the function. Otherwise, call f(xβ-β1), and then make swap(axβ-β1,βax) (swap the x-th and (xβ-β1)-th elements of a). The Little Elephant's teacher believes that this function does not work correctly. But that-be do not get an F, the Little Elephant wants to show the performance of its function. Help him, find a permutation of numbers from 1 to n, such that after performing the Little Elephant's function (that is call f(n)), the permutation will be sorted in ascending order. | 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;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
public class Solution {
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();
ArrayList<Integer> ans = new ArrayList<Integer>();
for (int i = 0; i < n; i++) {
if (i == 0) {
ans.add(n);
} else if (i == n - 1) {
ans.add(n - 1);
} else {
ans.add(i);
}
}
for (int i = 0; i < n; i++) {
System.out.print(ans.get(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());
}
public Double nextDouble() {
return Double.parseDouble(next());
}
public long nextLong() {
return Long.parseLong(next());
}
}
}
/*
4 5 1 1 2
1 3 5 7
10 11 12 13 14
*/
| Java | ["1", "2"] | 2 seconds | ["1", "2 1"] | null | Java 8 | standard input | [
"implementation",
"math"
] | d9ba1dfe11cf3dae177f8898f3abeefd | A single line contains integer n (1ββ€βnββ€β1000) β the size of permutation. | 1,000 | In a single line print n distinct integers from 1 to n β the required permutation. Numbers in a line should be separated by spaces. It is guaranteed that the answer exists. | standard output | |
PASSED | e9549b8f6e105766d23ac9d069645f63 | train_001.jsonl | 1346427000 | The Little Elephant enjoys recursive functions.This time he enjoys the sorting function. Let a is a permutation of an integers from 1 to n, inclusive, and ai denotes the i-th element of the permutation. The Little Elephant's recursive function f(x), that sorts the first x permutation's elements, works as follows: If xβ=β1, exit the function. Otherwise, call f(xβ-β1), and then make swap(axβ-β1,βax) (swap the x-th and (xβ-β1)-th elements of a). The Little Elephant's teacher believes that this function does not work correctly. But that-be do not get an F, the Little Elephant wants to show the performance of its function. Help him, find a permutation of numbers from 1 to n, such that after performing the Little Elephant's function (that is call f(n)), the permutation will be sorted in ascending order. | 256 megabytes | import java.util.Scanner;
public class LittleElephantandFunction221A {
public static void main(String[] args) {
Scanner sc= new Scanner(System.in);
int n =sc.nextInt();
System.out.print(n+" ");
for(int i=1;i<n;i++) {
System.out.print(i+" ");
}
}
}
| Java | ["1", "2"] | 2 seconds | ["1", "2 1"] | null | Java 8 | standard input | [
"implementation",
"math"
] | d9ba1dfe11cf3dae177f8898f3abeefd | A single line contains integer n (1ββ€βnββ€β1000) β the size of permutation. | 1,000 | In a single line print n distinct integers from 1 to n β the required permutation. Numbers in a line should be separated by spaces. It is guaranteed that the answer exists. | standard output | |
PASSED | 9e076e0a012aadda9420287f52560e83 | train_001.jsonl | 1346427000 | The Little Elephant enjoys recursive functions.This time he enjoys the sorting function. Let a is a permutation of an integers from 1 to n, inclusive, and ai denotes the i-th element of the permutation. The Little Elephant's recursive function f(x), that sorts the first x permutation's elements, works as follows: If xβ=β1, exit the function. Otherwise, call f(xβ-β1), and then make swap(axβ-β1,βax) (swap the x-th and (xβ-β1)-th elements of a). The Little Elephant's teacher believes that this function does not work correctly. But that-be do not get an F, the Little Elephant wants to show the performance of its function. Help him, find a permutation of numbers from 1 to n, such that after performing the Little Elephant's function (that is call f(n)), the permutation will be sorted in ascending order. | 256 megabytes |
import java.util.Scanner;
public class LittleElephantandFunction {
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
int n=scan.nextInt();
System.out.print(n+" ");
for(int i=1;i<n;i++) {
System.out.print(i+" ");
}
}
}
| Java | ["1", "2"] | 2 seconds | ["1", "2 1"] | null | Java 8 | standard input | [
"implementation",
"math"
] | d9ba1dfe11cf3dae177f8898f3abeefd | A single line contains integer n (1ββ€βnββ€β1000) β the size of permutation. | 1,000 | In a single line print n distinct integers from 1 to n β the required permutation. Numbers in a line should be separated by spaces. It is guaranteed that the answer exists. | standard output | |
PASSED | cd98d13ff190e6dc76cfed01637aefee | train_001.jsonl | 1547217300 | You are given an array $$$a_1, a_2, \dots, a_n$$$ of integer numbers.Your task is to divide the array into the maximum number of segments in such a way that: each element is contained in exactly one segment; each segment contains at least one element; there doesn't exist a non-empty subset of segments such that bitwise XOR of the numbers from them is equal to $$$0$$$. Print the maximum number of segments the array can be divided into. Print -1 if no suitable division exists. | 256 megabytes | import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
public class ZeroXORSubsetLess {
static int mod = 1000000007;
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[10005]; // 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();
}
}
static int LOG_A = 31;
/**
* f(v) stores the position of rightmost set bit of vector v
*/
static int basis[] = new int[LOG_A]; // basis[i] keeps the mask of the vector whose f value is i
static int sz; // Current size of the basis
static void insertVector(int mask) {
for (int i = 0; i < LOG_A; i++) {
if ((mask & 1 << i) == 0)
continue; // continue if i != f(mask)
if (basis[i] == 0) { // If there is no basis vector with the i'th bit set, then insert this vector
// into the basis
basis[i] = mask;
++sz;
return;
}
mask ^= basis[i]; // Otherwise subtract the basis vector from this vector
}
}
public static void main(String[] args) throws IOException {
Reader in = new Reader();
int i, t, n;
n = in.nextInt();
int a[] = new int[n];
int pref = 0;
for (i = 0; i < n; i++) {
a[i] = in.nextInt();
insertVector(a[i]);
pref ^= a[i];
}
if (pref == 0) {
System.out.println("-1");
return;
}
int ans = 0;
for (i = 0; i < LOG_A; i++) {
if (basis[i] > 0)
ans++;
}
System.out.println(ans);
}
}
| Java | ["4\n5 5 7 2", "3\n1 2 3", "3\n3 1 10"] | 2 seconds | ["2", "-1", "3"] | NoteIn the first example $$$2$$$ is the maximum number. If you divide the array into $$$\{[5], [5, 7, 2]\}$$$, the XOR value of the subset of only the second segment is $$$5 \oplus 7 \oplus 2 = 0$$$. $$$\{[5, 5], [7, 2]\}$$$ has the value of the subset of only the first segment being $$$5 \oplus 5 = 0$$$. However, $$$\{[5, 5, 7], [2]\}$$$ will lead to subsets $$$\{[5, 5, 7]\}$$$ of XOR $$$7$$$, $$$\{[2]\}$$$ of XOR $$$2$$$ and $$$\{[5, 5, 7], [2]\}$$$ of XOR $$$5 \oplus 5 \oplus 7 \oplus 2 = 5$$$.Let's take a look at some division on $$$3$$$ segments β $$$\{[5], [5, 7], [2]\}$$$. It will produce subsets: $$$\{[5]\}$$$, XOR $$$5$$$; $$$\{[5, 7]\}$$$, XOR $$$2$$$; $$$\{[5], [5, 7]\}$$$, XOR $$$7$$$; $$$\{[2]\}$$$, XOR $$$2$$$; $$$\{[5], [2]\}$$$, XOR $$$7$$$; $$$\{[5, 7], [2]\}$$$, XOR $$$0$$$; $$$\{[5], [5, 7], [2]\}$$$, XOR $$$5$$$; As you can see, subset $$$\{[5, 7], [2]\}$$$ has its XOR equal to $$$0$$$, which is unacceptable. You can check that for other divisions of size $$$3$$$ or $$$4$$$, non-empty subset with $$$0$$$ XOR always exists.The second example has no suitable divisions.The third example array can be divided into $$$\{[3], [1], [10]\}$$$. No subset of these segments has its XOR equal to $$$0$$$. | Java 8 | standard input | [
"math",
"matrices"
] | 0e0f30521f9f5eb5cff2549cd391da3c | The first line contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β the size of the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 10^9$$$). | 2,300 | Print the maximum number of segments the array can be divided into while following the given constraints. Print -1 if no suitable division exists. | standard output | |
PASSED | 58de4af2c8d30195aa6ffe0d05a14114 | train_001.jsonl | 1547217300 | You are given an array $$$a_1, a_2, \dots, a_n$$$ of integer numbers.Your task is to divide the array into the maximum number of segments in such a way that: each element is contained in exactly one segment; each segment contains at least one element; there doesn't exist a non-empty subset of segments such that bitwise XOR of the numbers from them is equal to $$$0$$$. Print the maximum number of segments the array can be divided into. Print -1 if no suitable division exists. | 256 megabytes | // upsolve with rainboy
import java.io.*;
import java.util.*;
public class CF1101G {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
int[] pp = new int[30];
int p = 0;
StringTokenizer st = new StringTokenizer(br.readLine());
while (n-- > 0) {
p ^= Integer.parseInt(st.nextToken());
int q = p;
for (int b = 0; b < 30; b++)
if ((q & 1 << b) != 0)
q ^= pp[b];
if (q != 0) {
int b = 0;
while ((q & 1 << b) == 0)
b++;
pp[b] = q;
}
}
int ans = -1;
if (p != 0) {
ans = 0;
for (int b = 0; b < 30; b++)
if (pp[b] != 0)
ans++;
}
System.out.println(ans);
}
}
| Java | ["4\n5 5 7 2", "3\n1 2 3", "3\n3 1 10"] | 2 seconds | ["2", "-1", "3"] | NoteIn the first example $$$2$$$ is the maximum number. If you divide the array into $$$\{[5], [5, 7, 2]\}$$$, the XOR value of the subset of only the second segment is $$$5 \oplus 7 \oplus 2 = 0$$$. $$$\{[5, 5], [7, 2]\}$$$ has the value of the subset of only the first segment being $$$5 \oplus 5 = 0$$$. However, $$$\{[5, 5, 7], [2]\}$$$ will lead to subsets $$$\{[5, 5, 7]\}$$$ of XOR $$$7$$$, $$$\{[2]\}$$$ of XOR $$$2$$$ and $$$\{[5, 5, 7], [2]\}$$$ of XOR $$$5 \oplus 5 \oplus 7 \oplus 2 = 5$$$.Let's take a look at some division on $$$3$$$ segments β $$$\{[5], [5, 7], [2]\}$$$. It will produce subsets: $$$\{[5]\}$$$, XOR $$$5$$$; $$$\{[5, 7]\}$$$, XOR $$$2$$$; $$$\{[5], [5, 7]\}$$$, XOR $$$7$$$; $$$\{[2]\}$$$, XOR $$$2$$$; $$$\{[5], [2]\}$$$, XOR $$$7$$$; $$$\{[5, 7], [2]\}$$$, XOR $$$0$$$; $$$\{[5], [5, 7], [2]\}$$$, XOR $$$5$$$; As you can see, subset $$$\{[5, 7], [2]\}$$$ has its XOR equal to $$$0$$$, which is unacceptable. You can check that for other divisions of size $$$3$$$ or $$$4$$$, non-empty subset with $$$0$$$ XOR always exists.The second example has no suitable divisions.The third example array can be divided into $$$\{[3], [1], [10]\}$$$. No subset of these segments has its XOR equal to $$$0$$$. | Java 8 | standard input | [
"math",
"matrices"
] | 0e0f30521f9f5eb5cff2549cd391da3c | The first line contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β the size of the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 10^9$$$). | 2,300 | Print the maximum number of segments the array can be divided into while following the given constraints. Print -1 if no suitable division exists. | standard output | |
PASSED | 255e2bb72cb0f62a905b0872695fdc98 | train_001.jsonl | 1547217300 | You are given an array $$$a_1, a_2, \dots, a_n$$$ of integer numbers.Your task is to divide the array into the maximum number of segments in such a way that: each element is contained in exactly one segment; each segment contains at least one element; there doesn't exist a non-empty subset of segments such that bitwise XOR of the numbers from them is equal to $$$0$$$. Print the maximum number of segments the array can be divided into. Print -1 if no suitable division exists. | 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);
ecr58G solver = new ecr58G();
solver.solve(1, in, out);
out.close();
}
static class ecr58G {
int[] base = new int[31];
void gaussAdd(int num) {
for (int i = 30; i >= 0; i--) {
if ((num & (1 << i)) != 0) {
if (base[i] == -1) {
base[i] = num;
return;
} else {
num ^= base[i];
}
}
}
}
public void solve(int testNumber, FastScanner in, PrintWriter out) {
int n = in.ni();
int[] a = in.na(n);
int[] pref = new int[n + 1];
for (int i = 0; i < n; i++) {
pref[i + 1] = pref[i] ^ a[i];
}
Arrays.fill(base, -1);
if (pref[n] == 0) {
out.println(-1);
return;
}
for (int i = 1; i <= n; i++) {
gaussAdd(pref[i]);
}
int ans = 0;
for (int i = 0; i < 31; i++) {
if (base[i] != -1)
ans++;
}
out.println(ans);
}
}
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());
}
public int[] na(int n) {
int[] ret = new int[n];
for (int i = 0; i < n; i++) {
ret[i] = ni();
}
return ret;
}
}
}
| Java | ["4\n5 5 7 2", "3\n1 2 3", "3\n3 1 10"] | 2 seconds | ["2", "-1", "3"] | NoteIn the first example $$$2$$$ is the maximum number. If you divide the array into $$$\{[5], [5, 7, 2]\}$$$, the XOR value of the subset of only the second segment is $$$5 \oplus 7 \oplus 2 = 0$$$. $$$\{[5, 5], [7, 2]\}$$$ has the value of the subset of only the first segment being $$$5 \oplus 5 = 0$$$. However, $$$\{[5, 5, 7], [2]\}$$$ will lead to subsets $$$\{[5, 5, 7]\}$$$ of XOR $$$7$$$, $$$\{[2]\}$$$ of XOR $$$2$$$ and $$$\{[5, 5, 7], [2]\}$$$ of XOR $$$5 \oplus 5 \oplus 7 \oplus 2 = 5$$$.Let's take a look at some division on $$$3$$$ segments β $$$\{[5], [5, 7], [2]\}$$$. It will produce subsets: $$$\{[5]\}$$$, XOR $$$5$$$; $$$\{[5, 7]\}$$$, XOR $$$2$$$; $$$\{[5], [5, 7]\}$$$, XOR $$$7$$$; $$$\{[2]\}$$$, XOR $$$2$$$; $$$\{[5], [2]\}$$$, XOR $$$7$$$; $$$\{[5, 7], [2]\}$$$, XOR $$$0$$$; $$$\{[5], [5, 7], [2]\}$$$, XOR $$$5$$$; As you can see, subset $$$\{[5, 7], [2]\}$$$ has its XOR equal to $$$0$$$, which is unacceptable. You can check that for other divisions of size $$$3$$$ or $$$4$$$, non-empty subset with $$$0$$$ XOR always exists.The second example has no suitable divisions.The third example array can be divided into $$$\{[3], [1], [10]\}$$$. No subset of these segments has its XOR equal to $$$0$$$. | Java 8 | standard input | [
"math",
"matrices"
] | 0e0f30521f9f5eb5cff2549cd391da3c | The first line contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β the size of the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 10^9$$$). | 2,300 | Print the maximum number of segments the array can be divided into while following the given constraints. Print -1 if no suitable division exists. | standard output | |
PASSED | 0746a4cec88e963051adf0c008c26d76 | train_001.jsonl | 1547217300 | You are given an array $$$a_1, a_2, \dots, a_n$$$ of integer numbers.Your task is to divide the array into the maximum number of segments in such a way that: each element is contained in exactly one segment; each segment contains at least one element; there doesn't exist a non-empty subset of segments such that bitwise XOR of the numbers from them is equal to $$$0$$$. Print the maximum number of segments the array can be divided into. Print -1 if no suitable division exists. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.io.Closeable;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) throws Exception {
Thread thread = new Thread(null, new TaskAdapter(), "", 1 << 27);
thread.start();
thread.join();
}
static class TaskAdapter implements Runnable {
@Override
public void run() {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastInput in = new FastInput(inputStream);
FastOutput out = new FastOutput(outputStream);
TaskG solver = new TaskG();
solver.solve(1, in, out);
out.close();
}
}
static class TaskG {
public void solve(int testNumber, FastInput in, FastOutput out) {
int n = in.readInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = in.readInt();
}
PreXor px = new PreXor(a);
if (px.prefix(n - 1) == 0) {
out.println(-1);
return;
}
LinearBasis lb = new LinearBasis();
for (int i = 0; i < n; i++) {
lb.add(px.prefix(i));
}
out.println(lb.size());
}
}
static class PreXor {
private long[] pre;
public PreXor(long[] a) {
int n = a.length;
pre = new long[n];
pre[0] = a[0];
for (int i = 1; i < n; i++) {
pre[i] = pre[i - 1] ^ a[i];
}
}
public PreXor(int[] a) {
int n = a.length;
pre = new long[n];
pre[0] = a[0];
for (int i = 1; i < n; i++) {
pre[i] = pre[i - 1] ^ a[i];
}
}
public long prefix(int i) {
return pre[i];
}
}
static class FastInput {
private final InputStream is;
private byte[] buf = new byte[1 << 13];
private int bufLen;
private int bufOffset;
private int next;
public FastInput(InputStream is) {
this.is = is;
}
private int read() {
while (bufLen == bufOffset) {
bufOffset = 0;
try {
bufLen = is.read(buf);
} catch (IOException e) {
bufLen = -1;
}
if (bufLen == -1) {
return -1;
}
}
return buf[bufOffset++];
}
public void skipBlank() {
while (next >= 0 && next <= 32) {
next = read();
}
}
public int readInt() {
int sign = 1;
skipBlank();
if (next == '+' || next == '-') {
sign = next == '+' ? 1 : -1;
next = read();
}
int val = 0;
if (sign == 1) {
while (next >= '0' && next <= '9') {
val = val * 10 + next - '0';
next = read();
}
} else {
while (next >= '0' && next <= '9') {
val = val * 10 - next + '0';
next = read();
}
}
return val;
}
}
static class FastOutput implements AutoCloseable, Closeable {
private StringBuilder cache = new StringBuilder(10 << 20);
private final Writer os;
public FastOutput(Writer os) {
this.os = os;
}
public FastOutput(OutputStream os) {
this(new OutputStreamWriter(os));
}
public FastOutput println(int c) {
cache.append(c).append('\n');
return this;
}
public FastOutput flush() {
try {
os.append(cache);
os.flush();
cache.setLength(0);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
return this;
}
public void close() {
flush();
try {
os.close();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
public String toString() {
return cache.toString();
}
}
static class LinearBasis {
private long[] map = new long[64];
private int size;
public int size() {
return size;
}
private void afterAddBit(int bit) {
for (int i = 63; i >= 0; i--) {
if (i == bit || map[i] == 0) {
continue;
}
if (bitAt(map[i], bit) == 1) {
map[i] ^= map[bit];
}
}
}
public boolean add(long val) {
for (int i = 63; i >= 0 && val != 0; i--) {
if (bitAt(val, i) == 0) {
continue;
}
val ^= map[i];
}
if (val != 0) {
int log = 63 - Long.numberOfLeadingZeros(val);
map[log] = val;
size++;
afterAddBit(log);
return true;
}
return false;
}
private long bitAt(long val, int i) {
return (val >>> i) & 1;
}
}
}
| Java | ["4\n5 5 7 2", "3\n1 2 3", "3\n3 1 10"] | 2 seconds | ["2", "-1", "3"] | NoteIn the first example $$$2$$$ is the maximum number. If you divide the array into $$$\{[5], [5, 7, 2]\}$$$, the XOR value of the subset of only the second segment is $$$5 \oplus 7 \oplus 2 = 0$$$. $$$\{[5, 5], [7, 2]\}$$$ has the value of the subset of only the first segment being $$$5 \oplus 5 = 0$$$. However, $$$\{[5, 5, 7], [2]\}$$$ will lead to subsets $$$\{[5, 5, 7]\}$$$ of XOR $$$7$$$, $$$\{[2]\}$$$ of XOR $$$2$$$ and $$$\{[5, 5, 7], [2]\}$$$ of XOR $$$5 \oplus 5 \oplus 7 \oplus 2 = 5$$$.Let's take a look at some division on $$$3$$$ segments β $$$\{[5], [5, 7], [2]\}$$$. It will produce subsets: $$$\{[5]\}$$$, XOR $$$5$$$; $$$\{[5, 7]\}$$$, XOR $$$2$$$; $$$\{[5], [5, 7]\}$$$, XOR $$$7$$$; $$$\{[2]\}$$$, XOR $$$2$$$; $$$\{[5], [2]\}$$$, XOR $$$7$$$; $$$\{[5, 7], [2]\}$$$, XOR $$$0$$$; $$$\{[5], [5, 7], [2]\}$$$, XOR $$$5$$$; As you can see, subset $$$\{[5, 7], [2]\}$$$ has its XOR equal to $$$0$$$, which is unacceptable. You can check that for other divisions of size $$$3$$$ or $$$4$$$, non-empty subset with $$$0$$$ XOR always exists.The second example has no suitable divisions.The third example array can be divided into $$$\{[3], [1], [10]\}$$$. No subset of these segments has its XOR equal to $$$0$$$. | Java 8 | standard input | [
"math",
"matrices"
] | 0e0f30521f9f5eb5cff2549cd391da3c | The first line contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β the size of the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 10^9$$$). | 2,300 | Print the maximum number of segments the array can be divided into while following the given constraints. Print -1 if no suitable division exists. | standard output | |
PASSED | bc5db33ff0208e6315042bad0eb8e76d | train_001.jsonl | 1547217300 | You are given an array $$$a_1, a_2, \dots, a_n$$$ of integer numbers.Your task is to divide the array into the maximum number of segments in such a way that: each element is contained in exactly one segment; each segment contains at least one element; there doesn't exist a non-empty subset of segments such that bitwise XOR of the numbers from them is equal to $$$0$$$. Print the maximum number of segments the array can be divided into. Print -1 if no suitable division exists. | 256 megabytes | import java.io.*;
import java.util.StringTokenizer;
public class ZeroXORSubsetless
{
public static final long mod=1000000007;
public static final int d=31;
public static void main (String[] args) throws java.lang.Exception {
FastScanner sc = new FastScanner();
PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
int N = sc.nextInt();
int arr[] = new int[N + 1];
for (int i = 1; i <= N; i++) {
arr[i] = sc.nextInt();
arr[i] ^= arr[i - 1];
}
if (arr[N] == 0) {
out.println(-1);
} else {
int basis[] = new int[d];
int size = 0;
for (int i = N; i > 0; i--) {
if (insertVector(arr[i], d, basis, size))
size++;
}
out.println(size);
}
out.close();
}
public static boolean insertVector(int vec,int d,int basis[],int size) {
if (size == d)
return false;
for (int i = d - 1; i >= 0; i--) {
if ((vec & (1 << i)) == 0) continue;
if (basis[i] != 0) {
vec = vec ^ basis[i];
} else {
basis[i] = vec;
return true;
}
}
return false;
}
//finding if x can represented as linear combination of the given basis
public static boolean FindIfXinBasis(int X,int d,int basis[]) {
for (int i = 31; i >= 0; i--) {
if ((X & (1 << i)) == 0) continue;
if (i >= d || basis[i] == 0)
return false;
X = X ^ basis[i];
}
return true;
}
//a power b
static long pow(long a,long b){
if(b==0)
return 1;
else if(b==1)
return a;
long ans=pow(a,b/2);
ans=(ans*ans)%mod;
if(b%2==1)
ans=(ans*a)%mod;
return ans%mod;
}
//-----------MyScanner class for faster input----------
public static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine(){
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
//--------------------------------------------------------
}
| Java | ["4\n5 5 7 2", "3\n1 2 3", "3\n3 1 10"] | 2 seconds | ["2", "-1", "3"] | NoteIn the first example $$$2$$$ is the maximum number. If you divide the array into $$$\{[5], [5, 7, 2]\}$$$, the XOR value of the subset of only the second segment is $$$5 \oplus 7 \oplus 2 = 0$$$. $$$\{[5, 5], [7, 2]\}$$$ has the value of the subset of only the first segment being $$$5 \oplus 5 = 0$$$. However, $$$\{[5, 5, 7], [2]\}$$$ will lead to subsets $$$\{[5, 5, 7]\}$$$ of XOR $$$7$$$, $$$\{[2]\}$$$ of XOR $$$2$$$ and $$$\{[5, 5, 7], [2]\}$$$ of XOR $$$5 \oplus 5 \oplus 7 \oplus 2 = 5$$$.Let's take a look at some division on $$$3$$$ segments β $$$\{[5], [5, 7], [2]\}$$$. It will produce subsets: $$$\{[5]\}$$$, XOR $$$5$$$; $$$\{[5, 7]\}$$$, XOR $$$2$$$; $$$\{[5], [5, 7]\}$$$, XOR $$$7$$$; $$$\{[2]\}$$$, XOR $$$2$$$; $$$\{[5], [2]\}$$$, XOR $$$7$$$; $$$\{[5, 7], [2]\}$$$, XOR $$$0$$$; $$$\{[5], [5, 7], [2]\}$$$, XOR $$$5$$$; As you can see, subset $$$\{[5, 7], [2]\}$$$ has its XOR equal to $$$0$$$, which is unacceptable. You can check that for other divisions of size $$$3$$$ or $$$4$$$, non-empty subset with $$$0$$$ XOR always exists.The second example has no suitable divisions.The third example array can be divided into $$$\{[3], [1], [10]\}$$$. No subset of these segments has its XOR equal to $$$0$$$. | Java 8 | standard input | [
"math",
"matrices"
] | 0e0f30521f9f5eb5cff2549cd391da3c | The first line contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β the size of the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 10^9$$$). | 2,300 | Print the maximum number of segments the array can be divided into while following the given constraints. Print -1 if no suitable division exists. | standard output | |
PASSED | 642340966e253ec8feb28d22d79943c4 | train_001.jsonl | 1547217300 | You are given an array $$$a_1, a_2, \dots, a_n$$$ of integer numbers.Your task is to divide the array into the maximum number of segments in such a way that: each element is contained in exactly one segment; each segment contains at least one element; there doesn't exist a non-empty subset of segments such that bitwise XOR of the numbers from them is equal to $$$0$$$. Print the maximum number of segments the array can be divided into. Print -1 if no suitable division exists. | 256 megabytes | import java.util.Scanner;
//https://codeforces.com/problemset/problem/1101/G
public class ZeroXorSubsetless {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] a = new int[n];
int xor = 0;
for (int i = 0; i < n; i++) {
a[i] = sc.nextInt();
xor^=a[i];
}
if(xor==0){
System.out.println(-1);
return;
}
int count = 0;
for (int i = 1 << 30; i > 0; i >>= 1) {
int val = -1;
for (int j = 0; j < n; j++) {
if ((i & a[j]) != 0) {
if (val == -1) {
val = a[j];
a[j] = i;
count++;
}else{
a[j] ^= val;
}
}
}
}
System.out.println(count);
}
}
| Java | ["4\n5 5 7 2", "3\n1 2 3", "3\n3 1 10"] | 2 seconds | ["2", "-1", "3"] | NoteIn the first example $$$2$$$ is the maximum number. If you divide the array into $$$\{[5], [5, 7, 2]\}$$$, the XOR value of the subset of only the second segment is $$$5 \oplus 7 \oplus 2 = 0$$$. $$$\{[5, 5], [7, 2]\}$$$ has the value of the subset of only the first segment being $$$5 \oplus 5 = 0$$$. However, $$$\{[5, 5, 7], [2]\}$$$ will lead to subsets $$$\{[5, 5, 7]\}$$$ of XOR $$$7$$$, $$$\{[2]\}$$$ of XOR $$$2$$$ and $$$\{[5, 5, 7], [2]\}$$$ of XOR $$$5 \oplus 5 \oplus 7 \oplus 2 = 5$$$.Let's take a look at some division on $$$3$$$ segments β $$$\{[5], [5, 7], [2]\}$$$. It will produce subsets: $$$\{[5]\}$$$, XOR $$$5$$$; $$$\{[5, 7]\}$$$, XOR $$$2$$$; $$$\{[5], [5, 7]\}$$$, XOR $$$7$$$; $$$\{[2]\}$$$, XOR $$$2$$$; $$$\{[5], [2]\}$$$, XOR $$$7$$$; $$$\{[5, 7], [2]\}$$$, XOR $$$0$$$; $$$\{[5], [5, 7], [2]\}$$$, XOR $$$5$$$; As you can see, subset $$$\{[5, 7], [2]\}$$$ has its XOR equal to $$$0$$$, which is unacceptable. You can check that for other divisions of size $$$3$$$ or $$$4$$$, non-empty subset with $$$0$$$ XOR always exists.The second example has no suitable divisions.The third example array can be divided into $$$\{[3], [1], [10]\}$$$. No subset of these segments has its XOR equal to $$$0$$$. | Java 8 | standard input | [
"math",
"matrices"
] | 0e0f30521f9f5eb5cff2549cd391da3c | The first line contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β the size of the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 10^9$$$). | 2,300 | Print the maximum number of segments the array can be divided into while following the given constraints. Print -1 if no suitable division exists. | standard output | |
PASSED | 4496c3a84a5afdc881faa904b0242876 | train_001.jsonl | 1547217300 | You are given an array $$$a_1, a_2, \dots, a_n$$$ of integer numbers.Your task is to divide the array into the maximum number of segments in such a way that: each element is contained in exactly one segment; each segment contains at least one element; there doesn't exist a non-empty subset of segments such that bitwise XOR of the numbers from them is equal to $$$0$$$. Print the maximum number of segments the array can be divided into. Print -1 if no suitable division exists. | 256 megabytes | //created by Whiplash99
import java.io.*;
import java.util.*;
public class G
{
private static void swap(BitSet[] b, int i, int j){BitSet tmp=b[i]; b[i]=b[j]; b[j]=tmp;}
private static int gauss_rank(BitSet[] bitSet, int N, int M)
{
int i,rank=0;
for(int row=0,col=0;row<N&&col<M;++col)
{
for(i=row;i<N;i++)
{
if(bitSet[i].get(col))
{
swap(bitSet,i,row);
break;
}
}
if(i==N) continue;
for(i=row+1;i<N;i++)
if(bitSet[i].get(col)) bitSet[i].xor(bitSet[row]);
++row; ++rank;
}
return rank;
}
private static void assign(int[] a, BitSet[] bitSet)
{
for(int i=0;i<a.length;i++)
{
int k=0;
while (a[i]>0)
{
if((a[i]&1)==1) bitSet[i].set(k);
a[i]>>=1; k++;
}
}
}
public static void main(String[] args) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int i,N;
N=Integer.parseInt(br.readLine().trim());
int[] a=new int[N];
String[] s=br.readLine().trim().split(" ");
for(i=0;i<N;i++) a[i]=Integer.parseInt(s[i]);
int x=0;
for(i=0;i<N;i++) x^=a[i];
if(x==0)
{
System.out.println(-1);
System.exit(0);
}
BitSet[] bitSet=new BitSet[N];
for(i=0;i<N;i++) bitSet[i]=new BitSet(31);
assign(a,bitSet);
System.out.println(gauss_rank(bitSet,N,31));
}
} | Java | ["4\n5 5 7 2", "3\n1 2 3", "3\n3 1 10"] | 2 seconds | ["2", "-1", "3"] | NoteIn the first example $$$2$$$ is the maximum number. If you divide the array into $$$\{[5], [5, 7, 2]\}$$$, the XOR value of the subset of only the second segment is $$$5 \oplus 7 \oplus 2 = 0$$$. $$$\{[5, 5], [7, 2]\}$$$ has the value of the subset of only the first segment being $$$5 \oplus 5 = 0$$$. However, $$$\{[5, 5, 7], [2]\}$$$ will lead to subsets $$$\{[5, 5, 7]\}$$$ of XOR $$$7$$$, $$$\{[2]\}$$$ of XOR $$$2$$$ and $$$\{[5, 5, 7], [2]\}$$$ of XOR $$$5 \oplus 5 \oplus 7 \oplus 2 = 5$$$.Let's take a look at some division on $$$3$$$ segments β $$$\{[5], [5, 7], [2]\}$$$. It will produce subsets: $$$\{[5]\}$$$, XOR $$$5$$$; $$$\{[5, 7]\}$$$, XOR $$$2$$$; $$$\{[5], [5, 7]\}$$$, XOR $$$7$$$; $$$\{[2]\}$$$, XOR $$$2$$$; $$$\{[5], [2]\}$$$, XOR $$$7$$$; $$$\{[5, 7], [2]\}$$$, XOR $$$0$$$; $$$\{[5], [5, 7], [2]\}$$$, XOR $$$5$$$; As you can see, subset $$$\{[5, 7], [2]\}$$$ has its XOR equal to $$$0$$$, which is unacceptable. You can check that for other divisions of size $$$3$$$ or $$$4$$$, non-empty subset with $$$0$$$ XOR always exists.The second example has no suitable divisions.The third example array can be divided into $$$\{[3], [1], [10]\}$$$. No subset of these segments has its XOR equal to $$$0$$$. | Java 8 | standard input | [
"math",
"matrices"
] | 0e0f30521f9f5eb5cff2549cd391da3c | The first line contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β the size of the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 10^9$$$). | 2,300 | Print the maximum number of segments the array can be divided into while following the given constraints. Print -1 if no suitable division exists. | standard output | |
PASSED | 6432f7fb28ecb6e2bc90b51f10e887e9 | train_001.jsonl | 1547217300 | You are given an array $$$a_1, a_2, \dots, a_n$$$ of integer numbers.Your task is to divide the array into the maximum number of segments in such a way that: each element is contained in exactly one segment; each segment contains at least one element; there doesn't exist a non-empty subset of segments such that bitwise XOR of the numbers from them is equal to $$$0$$$. Print the maximum number of segments the array can be divided into. Print -1 if no suitable division exists. | 256 megabytes | /*
I don't understand the solution.
I just saw this: https://codeforces.com/blog/entry/64483?#comment-484135
A bit of understanding: Rank of a matrix is the maximum number of linearly
independent rows, which means that the max number of rows that can't be formed
by some combination of other rows.
Subset xor can't be 0, which means that some number of subset can't be formed
by some combination of other numbers of the subset.
*/
//created by Whiplash99
import java.io.*;
import java.util.*;
public class G
{
private static void swap(BitSet[] b, int i, int j){BitSet tmp=b[i]; b[i]=b[j]; b[j]=tmp;}
private static int gauss_rank(BitSet[] bitSet, int N, int M)
{
int i,rank=0;
for(int row=0,col=0;row<N&&col<M;++col)
{
for(i=row;i<N;i++)
{
if(bitSet[i].get(col))
{
swap(bitSet,i,row);
break;
}
}
if(i==N) continue;
for(i=row+1;i<N;i++)
if(bitSet[i].get(col)) bitSet[i].xor(bitSet[row]);
++row; ++rank;
}
return rank;
}
private static void assign(int[] a, BitSet[] bitSet)
{
for(int i=0;i<a.length;i++)
{
int k=0;
while (a[i]>0)
{
if((a[i]&1)==1) bitSet[i].set(k);
a[i]>>=1; k++;
}
}
}
public static void main(String[] args) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int i,N;
N=Integer.parseInt(br.readLine().trim());
int[] a=new int[N];
String[] s=br.readLine().trim().split(" ");
for(i=0;i<N;i++) a[i]=Integer.parseInt(s[i]);
int x=0;
for(i=0;i<N;i++) x^=a[i];
if(x==0)
{
System.out.println(-1);
System.exit(0);
}
BitSet[] bitSet=new BitSet[N];
for(i=0;i<N;i++) bitSet[i]=new BitSet(30);
assign(a,bitSet);
System.out.println(gauss_rank(bitSet,N,30));
}
} | Java | ["4\n5 5 7 2", "3\n1 2 3", "3\n3 1 10"] | 2 seconds | ["2", "-1", "3"] | NoteIn the first example $$$2$$$ is the maximum number. If you divide the array into $$$\{[5], [5, 7, 2]\}$$$, the XOR value of the subset of only the second segment is $$$5 \oplus 7 \oplus 2 = 0$$$. $$$\{[5, 5], [7, 2]\}$$$ has the value of the subset of only the first segment being $$$5 \oplus 5 = 0$$$. However, $$$\{[5, 5, 7], [2]\}$$$ will lead to subsets $$$\{[5, 5, 7]\}$$$ of XOR $$$7$$$, $$$\{[2]\}$$$ of XOR $$$2$$$ and $$$\{[5, 5, 7], [2]\}$$$ of XOR $$$5 \oplus 5 \oplus 7 \oplus 2 = 5$$$.Let's take a look at some division on $$$3$$$ segments β $$$\{[5], [5, 7], [2]\}$$$. It will produce subsets: $$$\{[5]\}$$$, XOR $$$5$$$; $$$\{[5, 7]\}$$$, XOR $$$2$$$; $$$\{[5], [5, 7]\}$$$, XOR $$$7$$$; $$$\{[2]\}$$$, XOR $$$2$$$; $$$\{[5], [2]\}$$$, XOR $$$7$$$; $$$\{[5, 7], [2]\}$$$, XOR $$$0$$$; $$$\{[5], [5, 7], [2]\}$$$, XOR $$$5$$$; As you can see, subset $$$\{[5, 7], [2]\}$$$ has its XOR equal to $$$0$$$, which is unacceptable. You can check that for other divisions of size $$$3$$$ or $$$4$$$, non-empty subset with $$$0$$$ XOR always exists.The second example has no suitable divisions.The third example array can be divided into $$$\{[3], [1], [10]\}$$$. No subset of these segments has its XOR equal to $$$0$$$. | Java 8 | standard input | [
"math",
"matrices"
] | 0e0f30521f9f5eb5cff2549cd391da3c | The first line contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β the size of the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 10^9$$$). | 2,300 | Print the maximum number of segments the array can be divided into while following the given constraints. Print -1 if no suitable division exists. | standard output | |
PASSED | 80fde69757e72864d5b537b7d7e31eb5 | train_001.jsonl | 1547217300 | You are given an array $$$a_1, a_2, \dots, a_n$$$ of integer numbers.Your task is to divide the array into the maximum number of segments in such a way that: each element is contained in exactly one segment; each segment contains at least one element; there doesn't exist a non-empty subset of segments such that bitwise XOR of the numbers from them is equal to $$$0$$$. Print the maximum number of segments the array can be divided into. Print -1 if no suitable division exists. | 256 megabytes | //created by Whiplash99
import java.io.*;
import java.util.*;
public class G
{
private static void swap(BitSet[] b, int i, int j){BitSet tmp=b[i]; b[i]=b[j]; b[j]=tmp;}
private static int gauss_rank(BitSet[] bitSet, int N, int M)
{
int i,rank=0;
for(int row=0,col=0;row<N&&col<M;++col)
{
for(i=row;i<N;i++)
{
if(bitSet[i].get(col))
{
swap(bitSet,i,row);
break;
}
}
if(i==N) continue;
for(i=row+1;i<N;i++)
if(bitSet[i].get(col)) bitSet[i].xor(bitSet[row]);
++row; ++rank;
}
return rank;
}
private static void assign(Integer[] a, BitSet[] bitSet)
{
for(int i=0;i<a.length;i++)
{
int k=0;
while (a[i]>0)
{
if((a[i]&1)==1) bitSet[i].set(k);
a[i]>>=1; k++;
}
}
}
public static void main(String[] args) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int i,N;
N=Integer.parseInt(br.readLine().trim());
Integer[] a=new Integer[N];
String[] s=br.readLine().trim().split(" ");
for(i=0;i<N;i++) a[i]=Integer.parseInt(s[i]);
Arrays.sort(a,Collections.reverseOrder());
int x=0;
for(i=0;i<N;i++) x^=a[i];
if(x==0)
{
System.out.println(-1);
System.exit(0);
}
BitSet[] bitSet=new BitSet[N];
for(i=0;i<N;i++) bitSet[i]=new BitSet(31);
assign(a,bitSet);
System.out.println(gauss_rank(bitSet,N,31));
}
} | Java | ["4\n5 5 7 2", "3\n1 2 3", "3\n3 1 10"] | 2 seconds | ["2", "-1", "3"] | NoteIn the first example $$$2$$$ is the maximum number. If you divide the array into $$$\{[5], [5, 7, 2]\}$$$, the XOR value of the subset of only the second segment is $$$5 \oplus 7 \oplus 2 = 0$$$. $$$\{[5, 5], [7, 2]\}$$$ has the value of the subset of only the first segment being $$$5 \oplus 5 = 0$$$. However, $$$\{[5, 5, 7], [2]\}$$$ will lead to subsets $$$\{[5, 5, 7]\}$$$ of XOR $$$7$$$, $$$\{[2]\}$$$ of XOR $$$2$$$ and $$$\{[5, 5, 7], [2]\}$$$ of XOR $$$5 \oplus 5 \oplus 7 \oplus 2 = 5$$$.Let's take a look at some division on $$$3$$$ segments β $$$\{[5], [5, 7], [2]\}$$$. It will produce subsets: $$$\{[5]\}$$$, XOR $$$5$$$; $$$\{[5, 7]\}$$$, XOR $$$2$$$; $$$\{[5], [5, 7]\}$$$, XOR $$$7$$$; $$$\{[2]\}$$$, XOR $$$2$$$; $$$\{[5], [2]\}$$$, XOR $$$7$$$; $$$\{[5, 7], [2]\}$$$, XOR $$$0$$$; $$$\{[5], [5, 7], [2]\}$$$, XOR $$$5$$$; As you can see, subset $$$\{[5, 7], [2]\}$$$ has its XOR equal to $$$0$$$, which is unacceptable. You can check that for other divisions of size $$$3$$$ or $$$4$$$, non-empty subset with $$$0$$$ XOR always exists.The second example has no suitable divisions.The third example array can be divided into $$$\{[3], [1], [10]\}$$$. No subset of these segments has its XOR equal to $$$0$$$. | Java 8 | standard input | [
"math",
"matrices"
] | 0e0f30521f9f5eb5cff2549cd391da3c | The first line contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β the size of the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 10^9$$$). | 2,300 | Print the maximum number of segments the array can be divided into while following the given constraints. Print -1 if no suitable division exists. | standard output | |
PASSED | 46caa2659e3a64c8255048ec9ed2e95e | train_001.jsonl | 1547217300 | You are given an array $$$a_1, a_2, \dots, a_n$$$ of integer numbers.Your task is to divide the array into the maximum number of segments in such a way that: each element is contained in exactly one segment; each segment contains at least one element; there doesn't exist a non-empty subset of segments such that bitwise XOR of the numbers from them is equal to $$$0$$$. Print the maximum number of segments the array can be divided into. Print -1 if no suitable division exists. | 256 megabytes | //created by Whiplash99
import java.io.*;
import java.util.*;
public class G
{
private static void swap(BitSet[] b, int i, int j){BitSet tmp=b[i]; b[i]=b[j]; b[j]=tmp;}
private static int gauss_rank(BitSet[] bitSet, int N, int M)
{
int i,rank=0;
for(int row=0,col=0;row<N&&col<M;++col)
{
for(i=row;i<N;i++)
{
if(bitSet[i].get(col))
{
swap(bitSet,i,row);
break;
}
}
if(i==N) continue;
for(i=row+1;i<N;i++)
if(bitSet[i].get(col)) bitSet[i].xor(bitSet[row]);
++row; ++rank;
}
return rank;
}
private static void assign(int[] a, BitSet[] bitSet)
{
for(int i=0;i<a.length;i++)
{
int k=0;
while (a[i]>0)
{
if((a[i]&1)==1) bitSet[i].set(k);
a[i]>>=1; k++;
}
}
}
public static void main(String[] args) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int i,N;
N=Integer.parseInt(br.readLine().trim());
int[] a=new int[N];
String[] s=br.readLine().trim().split(" ");
for(i=0;i<N;i++) a[i]=Integer.parseInt(s[i]);
int x=0;
for(i=0;i<N;i++) x^=a[i];
if(x==0)
{
System.out.println(-1);
System.exit(0);
}
BitSet[] bitSet=new BitSet[N];
for(i=0;i<N;i++) bitSet[i]=new BitSet(30);
assign(a,bitSet);
System.out.println(gauss_rank(bitSet,N,30));
}
} | Java | ["4\n5 5 7 2", "3\n1 2 3", "3\n3 1 10"] | 2 seconds | ["2", "-1", "3"] | NoteIn the first example $$$2$$$ is the maximum number. If you divide the array into $$$\{[5], [5, 7, 2]\}$$$, the XOR value of the subset of only the second segment is $$$5 \oplus 7 \oplus 2 = 0$$$. $$$\{[5, 5], [7, 2]\}$$$ has the value of the subset of only the first segment being $$$5 \oplus 5 = 0$$$. However, $$$\{[5, 5, 7], [2]\}$$$ will lead to subsets $$$\{[5, 5, 7]\}$$$ of XOR $$$7$$$, $$$\{[2]\}$$$ of XOR $$$2$$$ and $$$\{[5, 5, 7], [2]\}$$$ of XOR $$$5 \oplus 5 \oplus 7 \oplus 2 = 5$$$.Let's take a look at some division on $$$3$$$ segments β $$$\{[5], [5, 7], [2]\}$$$. It will produce subsets: $$$\{[5]\}$$$, XOR $$$5$$$; $$$\{[5, 7]\}$$$, XOR $$$2$$$; $$$\{[5], [5, 7]\}$$$, XOR $$$7$$$; $$$\{[2]\}$$$, XOR $$$2$$$; $$$\{[5], [2]\}$$$, XOR $$$7$$$; $$$\{[5, 7], [2]\}$$$, XOR $$$0$$$; $$$\{[5], [5, 7], [2]\}$$$, XOR $$$5$$$; As you can see, subset $$$\{[5, 7], [2]\}$$$ has its XOR equal to $$$0$$$, which is unacceptable. You can check that for other divisions of size $$$3$$$ or $$$4$$$, non-empty subset with $$$0$$$ XOR always exists.The second example has no suitable divisions.The third example array can be divided into $$$\{[3], [1], [10]\}$$$. No subset of these segments has its XOR equal to $$$0$$$. | Java 8 | standard input | [
"math",
"matrices"
] | 0e0f30521f9f5eb5cff2549cd391da3c | The first line contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β the size of the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 10^9$$$). | 2,300 | Print the maximum number of segments the array can be divided into while following the given constraints. Print -1 if no suitable division exists. | standard output | |
PASSED | 4a1c6c205892ea7b849d6849e235420c | train_001.jsonl | 1547217300 | You are given an array $$$a_1, a_2, \dots, a_n$$$ of integer numbers.Your task is to divide the array into the maximum number of segments in such a way that: each element is contained in exactly one segment; each segment contains at least one element; there doesn't exist a non-empty subset of segments such that bitwise XOR of the numbers from them is equal to $$$0$$$. Print the maximum number of segments the array can be divided into. Print -1 if no suitable division exists. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author 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);
GZeroXORSubsetLess solver = new GZeroXORSubsetLess();
solver.solve(1, in, out);
out.close();
}
static class GZeroXORSubsetLess {
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();
// }
int[] a = in.nextIntArray(n);
//Arrays.sort(a, Comparator.reverseOrder());
int xor = 0;
for (int val : a) {
xor ^= val;
}
if (xor == 0) {
out.println(-1);
return;
}
int ans = 0;
// for (int i = 0; i < n; i++) {
// Integer[] b = new Integer[n];
//
// System.arraycopy(a, 0, b, 0, i + 1);
//
// int num = a[i];
//
// if (num == 0)
// break;
// int maxd = Integer.numberOfLeadingZeros(num);
//
// ans++;
//
// for (int j = i + 1; j < n; j++) {
// if (Integer.numberOfLeadingZeros(a[j]) == maxd) {
// b[j] = a[j] ^ num;
// } else {
// b[j] = a[j];
// }
// }
//
// Arrays.sort(b, Comparator.reverseOrder());
//
// a = b;
// }
for (int i = 29; i >= 0; i--) {
int num = -1;
for (int j = 0; j < n; j++) {
if (((1 << i) & a[j]) != 0 && a[j] <= (1 << (i + 1)) - 1) {
if (num == -1) {
num = a[j];
ans++;
} else {
a[j] ^= num;
}
}
}
}
out.println(ans);
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void close() {
writer.close();
}
public void println(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 int[] nextIntArray(int n) {
int[] array = new int[n];
for (int i = 0; i < n; ++i) array[i] = nextInt();
return array;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
| Java | ["4\n5 5 7 2", "3\n1 2 3", "3\n3 1 10"] | 2 seconds | ["2", "-1", "3"] | NoteIn the first example $$$2$$$ is the maximum number. If you divide the array into $$$\{[5], [5, 7, 2]\}$$$, the XOR value of the subset of only the second segment is $$$5 \oplus 7 \oplus 2 = 0$$$. $$$\{[5, 5], [7, 2]\}$$$ has the value of the subset of only the first segment being $$$5 \oplus 5 = 0$$$. However, $$$\{[5, 5, 7], [2]\}$$$ will lead to subsets $$$\{[5, 5, 7]\}$$$ of XOR $$$7$$$, $$$\{[2]\}$$$ of XOR $$$2$$$ and $$$\{[5, 5, 7], [2]\}$$$ of XOR $$$5 \oplus 5 \oplus 7 \oplus 2 = 5$$$.Let's take a look at some division on $$$3$$$ segments β $$$\{[5], [5, 7], [2]\}$$$. It will produce subsets: $$$\{[5]\}$$$, XOR $$$5$$$; $$$\{[5, 7]\}$$$, XOR $$$2$$$; $$$\{[5], [5, 7]\}$$$, XOR $$$7$$$; $$$\{[2]\}$$$, XOR $$$2$$$; $$$\{[5], [2]\}$$$, XOR $$$7$$$; $$$\{[5, 7], [2]\}$$$, XOR $$$0$$$; $$$\{[5], [5, 7], [2]\}$$$, XOR $$$5$$$; As you can see, subset $$$\{[5, 7], [2]\}$$$ has its XOR equal to $$$0$$$, which is unacceptable. You can check that for other divisions of size $$$3$$$ or $$$4$$$, non-empty subset with $$$0$$$ XOR always exists.The second example has no suitable divisions.The third example array can be divided into $$$\{[3], [1], [10]\}$$$. No subset of these segments has its XOR equal to $$$0$$$. | Java 8 | standard input | [
"math",
"matrices"
] | 0e0f30521f9f5eb5cff2549cd391da3c | The first line contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β the size of the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 10^9$$$). | 2,300 | Print the maximum number of segments the array can be divided into while following the given constraints. Print -1 if no suitable division exists. | standard output | |
PASSED | e27373e0943a447b23666240c377229b | train_001.jsonl | 1547217300 | You are given an array $$$a_1, a_2, \dots, a_n$$$ of integer numbers.Your task is to divide the array into the maximum number of segments in such a way that: each element is contained in exactly one segment; each segment contains at least one element; there doesn't exist a non-empty subset of segments such that bitwise XOR of the numbers from them is equal to $$$0$$$. Print the maximum number of segments the array can be divided into. Print -1 if no suitable division exists. | 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.io.Writer;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.Comparator;
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);
GZeroXORSubsetLess solver = new GZeroXORSubsetLess();
solver.solve(1, in, out);
out.close();
}
static class GZeroXORSubsetLess {
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, Comparator.reverseOrder());
int xor = 0;
for (int val : a) {
xor ^= val;
}
if (xor == 0) {
out.println(-1);
return;
}
int ans = 0;
// for (int i = 0; i < n; i++) {
// Integer[] b = new Integer[n];
//
// System.arraycopy(a, 0, b, 0, i + 1);
//
// int num = a[i];
//
// if (num == 0)
// break;
// int maxd = Integer.numberOfLeadingZeros(num);
//
// ans++;
//
// for (int j = i + 1; j < n; j++) {
// if (Integer.numberOfLeadingZeros(a[j]) == maxd) {
// b[j] = a[j] ^ num;
// } else {
// b[j] = a[j];
// }
// }
//
// Arrays.sort(b, Comparator.reverseOrder());
//
// a = b;
// }
for (int i = 29; i >= 0; i--) {
int num = -1;
for (int j = 0; j < n; j++) {
if (((1 << i) & a[j]) != 0 && a[j] <= (1 << (i + 1)) - 1) {
if (num == -1) {
num = a[j];
ans++;
} else {
a[j] ^= num;
}
}
}
}
out.println(ans);
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void close() {
writer.close();
}
public void println(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 | ["4\n5 5 7 2", "3\n1 2 3", "3\n3 1 10"] | 2 seconds | ["2", "-1", "3"] | NoteIn the first example $$$2$$$ is the maximum number. If you divide the array into $$$\{[5], [5, 7, 2]\}$$$, the XOR value of the subset of only the second segment is $$$5 \oplus 7 \oplus 2 = 0$$$. $$$\{[5, 5], [7, 2]\}$$$ has the value of the subset of only the first segment being $$$5 \oplus 5 = 0$$$. However, $$$\{[5, 5, 7], [2]\}$$$ will lead to subsets $$$\{[5, 5, 7]\}$$$ of XOR $$$7$$$, $$$\{[2]\}$$$ of XOR $$$2$$$ and $$$\{[5, 5, 7], [2]\}$$$ of XOR $$$5 \oplus 5 \oplus 7 \oplus 2 = 5$$$.Let's take a look at some division on $$$3$$$ segments β $$$\{[5], [5, 7], [2]\}$$$. It will produce subsets: $$$\{[5]\}$$$, XOR $$$5$$$; $$$\{[5, 7]\}$$$, XOR $$$2$$$; $$$\{[5], [5, 7]\}$$$, XOR $$$7$$$; $$$\{[2]\}$$$, XOR $$$2$$$; $$$\{[5], [2]\}$$$, XOR $$$7$$$; $$$\{[5, 7], [2]\}$$$, XOR $$$0$$$; $$$\{[5], [5, 7], [2]\}$$$, XOR $$$5$$$; As you can see, subset $$$\{[5, 7], [2]\}$$$ has its XOR equal to $$$0$$$, which is unacceptable. You can check that for other divisions of size $$$3$$$ or $$$4$$$, non-empty subset with $$$0$$$ XOR always exists.The second example has no suitable divisions.The third example array can be divided into $$$\{[3], [1], [10]\}$$$. No subset of these segments has its XOR equal to $$$0$$$. | Java 8 | standard input | [
"math",
"matrices"
] | 0e0f30521f9f5eb5cff2549cd391da3c | The first line contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β the size of the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 10^9$$$). | 2,300 | Print the maximum number of segments the array can be divided into while following the given constraints. Print -1 if no suitable division exists. | standard output | |
PASSED | 2303e64ccefa304c6e61c5758c5a2c84 | train_001.jsonl | 1547217300 | You are given an array $$$a_1, a_2, \dots, a_n$$$ of integer numbers.Your task is to divide the array into the maximum number of segments in such a way that: each element is contained in exactly one segment; each segment contains at least one element; there doesn't exist a non-empty subset of segments such that bitwise XOR of the numbers from them is equal to $$$0$$$. Print the maximum number of segments the array can be divided into. Print -1 if no suitable division exists. | 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.io.Writer;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.Comparator;
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);
GZeroXORSubsetLess solver = new GZeroXORSubsetLess();
solver.solve(1, in, out);
out.close();
}
static class GZeroXORSubsetLess {
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, Comparator.reverseOrder());
int xor = 0;
for (int val : a) {
xor ^= val;
}
if (xor == 0) {
out.println(-1);
return;
}
int ans = 0;
for (int i = 0; i < n; i++) {
Integer[] b = new Integer[n];
System.arraycopy(a, 0, b, 0, i + 1);
int num = a[i];
if (num == 0)
break;
int maxd = Integer.numberOfLeadingZeros(num);
ans++;
for (int j = i + 1; j < n; j++) {
if (Integer.numberOfLeadingZeros(a[j]) == maxd) {
b[j] = a[j] ^ num;
} else {
b[j] = a[j];
}
}
Arrays.sort(b, Comparator.reverseOrder());
a = b;
}
out.println(ans);
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void close() {
writer.close();
}
public void println(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 | ["4\n5 5 7 2", "3\n1 2 3", "3\n3 1 10"] | 2 seconds | ["2", "-1", "3"] | NoteIn the first example $$$2$$$ is the maximum number. If you divide the array into $$$\{[5], [5, 7, 2]\}$$$, the XOR value of the subset of only the second segment is $$$5 \oplus 7 \oplus 2 = 0$$$. $$$\{[5, 5], [7, 2]\}$$$ has the value of the subset of only the first segment being $$$5 \oplus 5 = 0$$$. However, $$$\{[5, 5, 7], [2]\}$$$ will lead to subsets $$$\{[5, 5, 7]\}$$$ of XOR $$$7$$$, $$$\{[2]\}$$$ of XOR $$$2$$$ and $$$\{[5, 5, 7], [2]\}$$$ of XOR $$$5 \oplus 5 \oplus 7 \oplus 2 = 5$$$.Let's take a look at some division on $$$3$$$ segments β $$$\{[5], [5, 7], [2]\}$$$. It will produce subsets: $$$\{[5]\}$$$, XOR $$$5$$$; $$$\{[5, 7]\}$$$, XOR $$$2$$$; $$$\{[5], [5, 7]\}$$$, XOR $$$7$$$; $$$\{[2]\}$$$, XOR $$$2$$$; $$$\{[5], [2]\}$$$, XOR $$$7$$$; $$$\{[5, 7], [2]\}$$$, XOR $$$0$$$; $$$\{[5], [5, 7], [2]\}$$$, XOR $$$5$$$; As you can see, subset $$$\{[5, 7], [2]\}$$$ has its XOR equal to $$$0$$$, which is unacceptable. You can check that for other divisions of size $$$3$$$ or $$$4$$$, non-empty subset with $$$0$$$ XOR always exists.The second example has no suitable divisions.The third example array can be divided into $$$\{[3], [1], [10]\}$$$. No subset of these segments has its XOR equal to $$$0$$$. | Java 8 | standard input | [
"math",
"matrices"
] | 0e0f30521f9f5eb5cff2549cd391da3c | The first line contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β the size of the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 10^9$$$). | 2,300 | Print the maximum number of segments the array can be divided into while following the given constraints. Print -1 if no suitable division exists. | standard output | |
PASSED | 9099331bdf1485214184ccd2e897c88e | train_001.jsonl | 1547217300 | You are given an array $$$a_1, a_2, \dots, a_n$$$ of integer numbers.Your task is to divide the array into the maximum number of segments in such a way that: each element is contained in exactly one segment; each segment contains at least one element; there doesn't exist a non-empty subset of segments such that bitwise XOR of the numbers from them is equal to $$$0$$$. Print the maximum number of segments the array can be divided into. Print -1 if no suitable division exists. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author beginner1010
*/
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);
TaskG solver = new TaskG();
solver.solve(1, in, out);
out.close();
}
static class TaskG {
final int maxBit = 32;
int[] basis;
long two(int bit) {
return 1L << bit;
}
boolean contain(long mask, int bit) {
return (two(bit) & mask) > 0;
}
boolean good(int equation) {
for (int col = 0; col <= maxBit; col++) {
if (contain(equation, col) == false)
continue;
if (basis[col] == 0) {
basis[col] = equation;
return true;
}
equation ^= basis[col];
}
return false;
}
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
int[] a = new int[n];
basis = new int[maxBit];
int curXor = 0;
int rank = 0;
for (int i = 0; i < n; i++) {
a[i] = in.nextInt();
curXor ^= a[i];
if (good(curXor))
rank++;
}
if (curXor == 0) out.println(-1);
else
out.println(rank);
}
}
static class InputReader {
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputStream stream;
public InputReader(InputStream stream) {
this.stream = stream;
}
private boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private 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 (isWhitespace(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 (!isWhitespace(c));
return res * sgn;
}
}
}
| Java | ["4\n5 5 7 2", "3\n1 2 3", "3\n3 1 10"] | 2 seconds | ["2", "-1", "3"] | NoteIn the first example $$$2$$$ is the maximum number. If you divide the array into $$$\{[5], [5, 7, 2]\}$$$, the XOR value of the subset of only the second segment is $$$5 \oplus 7 \oplus 2 = 0$$$. $$$\{[5, 5], [7, 2]\}$$$ has the value of the subset of only the first segment being $$$5 \oplus 5 = 0$$$. However, $$$\{[5, 5, 7], [2]\}$$$ will lead to subsets $$$\{[5, 5, 7]\}$$$ of XOR $$$7$$$, $$$\{[2]\}$$$ of XOR $$$2$$$ and $$$\{[5, 5, 7], [2]\}$$$ of XOR $$$5 \oplus 5 \oplus 7 \oplus 2 = 5$$$.Let's take a look at some division on $$$3$$$ segments β $$$\{[5], [5, 7], [2]\}$$$. It will produce subsets: $$$\{[5]\}$$$, XOR $$$5$$$; $$$\{[5, 7]\}$$$, XOR $$$2$$$; $$$\{[5], [5, 7]\}$$$, XOR $$$7$$$; $$$\{[2]\}$$$, XOR $$$2$$$; $$$\{[5], [2]\}$$$, XOR $$$7$$$; $$$\{[5, 7], [2]\}$$$, XOR $$$0$$$; $$$\{[5], [5, 7], [2]\}$$$, XOR $$$5$$$; As you can see, subset $$$\{[5, 7], [2]\}$$$ has its XOR equal to $$$0$$$, which is unacceptable. You can check that for other divisions of size $$$3$$$ or $$$4$$$, non-empty subset with $$$0$$$ XOR always exists.The second example has no suitable divisions.The third example array can be divided into $$$\{[3], [1], [10]\}$$$. No subset of these segments has its XOR equal to $$$0$$$. | Java 8 | standard input | [
"math",
"matrices"
] | 0e0f30521f9f5eb5cff2549cd391da3c | The first line contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β the size of the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 10^9$$$). | 2,300 | Print the maximum number of segments the array can be divided into while following the given constraints. Print -1 if no suitable division exists. | standard output | |
PASSED | 4bb14fe46155c773015b2674afa84ddd | train_001.jsonl | 1547217300 | You are given an array $$$a_1, a_2, \dots, a_n$$$ of integer numbers.Your task is to divide the array into the maximum number of segments in such a way that: each element is contained in exactly one segment; each segment contains at least one element; there doesn't exist a non-empty subset of segments such that bitwise XOR of the numbers from them is equal to $$$0$$$. Print the maximum number of segments the array can be divided into. Print -1 if no suitable division exists. | 256 megabytes | //package educational.round58;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;
public class G {
InputStream is;
PrintWriter out;
String INPUT = "";
void solve()
{
int n = ni();
int[] a = na(n);
long[] bas = new long[64];
int b = 0;
for(int x : a){
b ^= x;
int y = b;
int h = 63-Long.numberOfLeadingZeros(y);
while(y != 0){
if(bas[h] != 0){
y ^= bas[h];
h = 63-Long.numberOfLeadingZeros(y);
}else{
bas[h] = y;
}
}
}
if(b == 0){
out.println(-1);
return;
}
int rank = 0;
for(int i = 0;i < 64;i++){
if(bas[i] != 0)rank++;
}
out.println(rank);
}
void run() throws Exception
{
is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes());
out = new PrintWriter(System.out);
long s = System.currentTimeMillis();
solve();
out.flush();
tr(System.currentTimeMillis()-s+"ms");
}
public static void main(String[] args) throws Exception { new G().run(); }
private byte[] inbuf = new byte[1024];
public int lenbuf = 0, ptrbuf = 0;
private int readByte()
{
if(lenbuf == -1)throw new InputMismatchException();
if(ptrbuf >= lenbuf){
ptrbuf = 0;
try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); }
if(lenbuf <= 0)return -1;
}
return inbuf[ptrbuf++];
}
private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }
private double nd() { return Double.parseDouble(ns()); }
private char nc() { return (char)skip(); }
private String ns()
{
int b = skip();
StringBuilder sb = new StringBuilder();
while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private char[] ns(int n)
{
char[] buf = new char[n];
int b = skip(), p = 0;
while(p < n && !(isSpaceChar(b))){
buf[p++] = (char)b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private char[][] nm(int n, int m)
{
char[][] map = new char[n][];
for(int i = 0;i < n;i++)map[i] = ns(m);
return map;
}
private int[] na(int n)
{
int[] a = new int[n];
for(int i = 0;i < n;i++)a[i] = ni();
return a;
}
private int ni()
{
int num = 0, b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private long nl()
{
long num = 0;
int b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private boolean oj = System.getProperty("ONLINE_JUDGE") != null;
private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); }
}
| Java | ["4\n5 5 7 2", "3\n1 2 3", "3\n3 1 10"] | 2 seconds | ["2", "-1", "3"] | NoteIn the first example $$$2$$$ is the maximum number. If you divide the array into $$$\{[5], [5, 7, 2]\}$$$, the XOR value of the subset of only the second segment is $$$5 \oplus 7 \oplus 2 = 0$$$. $$$\{[5, 5], [7, 2]\}$$$ has the value of the subset of only the first segment being $$$5 \oplus 5 = 0$$$. However, $$$\{[5, 5, 7], [2]\}$$$ will lead to subsets $$$\{[5, 5, 7]\}$$$ of XOR $$$7$$$, $$$\{[2]\}$$$ of XOR $$$2$$$ and $$$\{[5, 5, 7], [2]\}$$$ of XOR $$$5 \oplus 5 \oplus 7 \oplus 2 = 5$$$.Let's take a look at some division on $$$3$$$ segments β $$$\{[5], [5, 7], [2]\}$$$. It will produce subsets: $$$\{[5]\}$$$, XOR $$$5$$$; $$$\{[5, 7]\}$$$, XOR $$$2$$$; $$$\{[5], [5, 7]\}$$$, XOR $$$7$$$; $$$\{[2]\}$$$, XOR $$$2$$$; $$$\{[5], [2]\}$$$, XOR $$$7$$$; $$$\{[5, 7], [2]\}$$$, XOR $$$0$$$; $$$\{[5], [5, 7], [2]\}$$$, XOR $$$5$$$; As you can see, subset $$$\{[5, 7], [2]\}$$$ has its XOR equal to $$$0$$$, which is unacceptable. You can check that for other divisions of size $$$3$$$ or $$$4$$$, non-empty subset with $$$0$$$ XOR always exists.The second example has no suitable divisions.The third example array can be divided into $$$\{[3], [1], [10]\}$$$. No subset of these segments has its XOR equal to $$$0$$$. | Java 8 | standard input | [
"math",
"matrices"
] | 0e0f30521f9f5eb5cff2549cd391da3c | The first line contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β the size of the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 10^9$$$). | 2,300 | Print the maximum number of segments the array can be divided into while following the given constraints. Print -1 if no suitable division exists. | standard output | |
PASSED | 024b5b7a040257ca791803559f3b90e0 | train_001.jsonl | 1547217300 | You are given an array $$$a_1, a_2, \dots, a_n$$$ of integer numbers.Your task is to divide the array into the maximum number of segments in such a way that: each element is contained in exactly one segment; each segment contains at least one element; there doesn't exist a non-empty subset of segments such that bitwise XOR of the numbers from them is equal to $$$0$$$. Print the maximum number of segments the array can be divided into. Print -1 if no suitable division exists. | 256 megabytes | import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
int n=in.nextInt();
int[] a=new int[n+1];
int[] b=new int[33];
for (int i=1;i<=n;++i) {
a[i]=in.nextInt();
a[i]^=a[i-1];
}
if (a[n]==0) {
System.out.println(-1);
return;
}
for (int i=1;i<=n;++i)
for (int j=0;j<33;++j) if ((a[i]>>j&1)==1) {
if (b[j]>0) a[i]^=b[j];
else {
b[j]=a[i];
break;
}
}
int res=0;
for (int i=0;i<33;++i) if (b[i]>0) ++res;
System.out.println(res);
}
} | Java | ["4\n5 5 7 2", "3\n1 2 3", "3\n3 1 10"] | 2 seconds | ["2", "-1", "3"] | NoteIn the first example $$$2$$$ is the maximum number. If you divide the array into $$$\{[5], [5, 7, 2]\}$$$, the XOR value of the subset of only the second segment is $$$5 \oplus 7 \oplus 2 = 0$$$. $$$\{[5, 5], [7, 2]\}$$$ has the value of the subset of only the first segment being $$$5 \oplus 5 = 0$$$. However, $$$\{[5, 5, 7], [2]\}$$$ will lead to subsets $$$\{[5, 5, 7]\}$$$ of XOR $$$7$$$, $$$\{[2]\}$$$ of XOR $$$2$$$ and $$$\{[5, 5, 7], [2]\}$$$ of XOR $$$5 \oplus 5 \oplus 7 \oplus 2 = 5$$$.Let's take a look at some division on $$$3$$$ segments β $$$\{[5], [5, 7], [2]\}$$$. It will produce subsets: $$$\{[5]\}$$$, XOR $$$5$$$; $$$\{[5, 7]\}$$$, XOR $$$2$$$; $$$\{[5], [5, 7]\}$$$, XOR $$$7$$$; $$$\{[2]\}$$$, XOR $$$2$$$; $$$\{[5], [2]\}$$$, XOR $$$7$$$; $$$\{[5, 7], [2]\}$$$, XOR $$$0$$$; $$$\{[5], [5, 7], [2]\}$$$, XOR $$$5$$$; As you can see, subset $$$\{[5, 7], [2]\}$$$ has its XOR equal to $$$0$$$, which is unacceptable. You can check that for other divisions of size $$$3$$$ or $$$4$$$, non-empty subset with $$$0$$$ XOR always exists.The second example has no suitable divisions.The third example array can be divided into $$$\{[3], [1], [10]\}$$$. No subset of these segments has its XOR equal to $$$0$$$. | Java 8 | standard input | [
"math",
"matrices"
] | 0e0f30521f9f5eb5cff2549cd391da3c | The first line contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β the size of the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 10^9$$$). | 2,300 | Print the maximum number of segments the array can be divided into while following the given constraints. Print -1 if no suitable division exists. | standard output | |
PASSED | 09ede9887ee73bb3e797d1c43c0a8235 | train_001.jsonl | 1547217300 | You are given an array $$$a_1, a_2, \dots, a_n$$$ of integer numbers.Your task is to divide the array into the maximum number of segments in such a way that: each element is contained in exactly one segment; each segment contains at least one element; there doesn't exist a non-empty subset of segments such that bitwise XOR of the numbers from them is equal to $$$0$$$. Print the maximum number of segments the array can be divided into. Print -1 if no suitable division exists. | 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;
/**
* @author khokharnikunj8
*/
public class Main {
public static void main(String[] args) {
new Thread(null, new Runnable() {
public void run() {
new Main().solve();
}
}, "1", 1 << 26).start();
}
void solve() {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
ScanReader in = new ScanReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
GZeroXORSubsetLess solver = new GZeroXORSubsetLess();
solver.solve(1, in, out);
out.close();
}
static class GZeroXORSubsetLess {
public void solve(int testNumber, ScanReader in, PrintWriter out) {
int n = in.scanInt();
int[] ar = new int[n];
for (int i = 0; i < n; i++) ar[i] = in.scanInt();
int pre = 0;
int[] basis = new int[32];
int rank = 0;
for (int i = 0; i < n; i++) {
int x = ar[i];
int h = 31 - Integer.numberOfLeadingZeros(x);
while (x != 0) {
if (basis[h] != 0) {
x ^= basis[h];
h = 31 - Integer.numberOfLeadingZeros(x);
} else {
basis[h] = x;
rank++;
}
}
pre ^= ar[i];
}
if (pre == 0) out.println(-1);
else out.println(rank);
}
}
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 int scanInt() {
int integer = 0;
int n = scan();
while (isWhiteSpace(n)) n = scan();
int neg = 1;
if (n == '-') {
neg = -1;
n = scan();
}
while (!isWhiteSpace(n)) {
if (n >= '0' && n <= '9') {
integer *= 10;
integer += n - '0';
n = scan();
}
}
return neg * integer;
}
private boolean isWhiteSpace(int n) {
if (n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1) return true;
else return false;
}
}
}
| Java | ["4\n5 5 7 2", "3\n1 2 3", "3\n3 1 10"] | 2 seconds | ["2", "-1", "3"] | NoteIn the first example $$$2$$$ is the maximum number. If you divide the array into $$$\{[5], [5, 7, 2]\}$$$, the XOR value of the subset of only the second segment is $$$5 \oplus 7 \oplus 2 = 0$$$. $$$\{[5, 5], [7, 2]\}$$$ has the value of the subset of only the first segment being $$$5 \oplus 5 = 0$$$. However, $$$\{[5, 5, 7], [2]\}$$$ will lead to subsets $$$\{[5, 5, 7]\}$$$ of XOR $$$7$$$, $$$\{[2]\}$$$ of XOR $$$2$$$ and $$$\{[5, 5, 7], [2]\}$$$ of XOR $$$5 \oplus 5 \oplus 7 \oplus 2 = 5$$$.Let's take a look at some division on $$$3$$$ segments β $$$\{[5], [5, 7], [2]\}$$$. It will produce subsets: $$$\{[5]\}$$$, XOR $$$5$$$; $$$\{[5, 7]\}$$$, XOR $$$2$$$; $$$\{[5], [5, 7]\}$$$, XOR $$$7$$$; $$$\{[2]\}$$$, XOR $$$2$$$; $$$\{[5], [2]\}$$$, XOR $$$7$$$; $$$\{[5, 7], [2]\}$$$, XOR $$$0$$$; $$$\{[5], [5, 7], [2]\}$$$, XOR $$$5$$$; As you can see, subset $$$\{[5, 7], [2]\}$$$ has its XOR equal to $$$0$$$, which is unacceptable. You can check that for other divisions of size $$$3$$$ or $$$4$$$, non-empty subset with $$$0$$$ XOR always exists.The second example has no suitable divisions.The third example array can be divided into $$$\{[3], [1], [10]\}$$$. No subset of these segments has its XOR equal to $$$0$$$. | Java 8 | standard input | [
"math",
"matrices"
] | 0e0f30521f9f5eb5cff2549cd391da3c | The first line contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β the size of the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 10^9$$$). | 2,300 | Print the maximum number of segments the array can be divided into while following the given constraints. Print -1 if no suitable division exists. | standard output | |
PASSED | f18ac39e451f5f3652407f2d611ac4c1 | train_001.jsonl | 1547217300 | You are given an array $$$a_1, a_2, \dots, a_n$$$ of integer numbers.Your task is to divide the array into the maximum number of segments in such a way that: each element is contained in exactly one segment; each segment contains at least one element; there doesn't exist a non-empty subset of segments such that bitwise XOR of the numbers from them is equal to $$$0$$$. Print the maximum number of segments the array can be divided into. Print -1 if no suitable division exists. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
static PrintWriter out = new PrintWriter(System.out);
static Scanner sc = new Scanner(System.in);
static BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
long mod = 1000000000+7;
long[] frac, inv;
public static void main(String[] args) throws IOException {
Main main = new Main();
// main.solve();
out.println(main.solve());
out.flush();
}
long solve() throws IOException {
int n = sc.nextInt();
int[] a = new int[n];
int sum = 0;
for(int i=0;i<n;i++){
a[i]= sc.nextInt();
sum ^= a[i];
}
if(sum==0) return -1;
int ans = 0;
int[] base = new int[31];
for(int num:a){
int b = num;
if(b==0) continue;
for(int i=30; i>=0; i--){
int mask = 1<<i;
if((mask&b)==0){
continue;
} else{
if(base[i]==0){
base[i] = b;
ans++;
break;
} else{
b = b^base[i];
}
}
}
}
return ans;
}
} | Java | ["4\n5 5 7 2", "3\n1 2 3", "3\n3 1 10"] | 2 seconds | ["2", "-1", "3"] | NoteIn the first example $$$2$$$ is the maximum number. If you divide the array into $$$\{[5], [5, 7, 2]\}$$$, the XOR value of the subset of only the second segment is $$$5 \oplus 7 \oplus 2 = 0$$$. $$$\{[5, 5], [7, 2]\}$$$ has the value of the subset of only the first segment being $$$5 \oplus 5 = 0$$$. However, $$$\{[5, 5, 7], [2]\}$$$ will lead to subsets $$$\{[5, 5, 7]\}$$$ of XOR $$$7$$$, $$$\{[2]\}$$$ of XOR $$$2$$$ and $$$\{[5, 5, 7], [2]\}$$$ of XOR $$$5 \oplus 5 \oplus 7 \oplus 2 = 5$$$.Let's take a look at some division on $$$3$$$ segments β $$$\{[5], [5, 7], [2]\}$$$. It will produce subsets: $$$\{[5]\}$$$, XOR $$$5$$$; $$$\{[5, 7]\}$$$, XOR $$$2$$$; $$$\{[5], [5, 7]\}$$$, XOR $$$7$$$; $$$\{[2]\}$$$, XOR $$$2$$$; $$$\{[5], [2]\}$$$, XOR $$$7$$$; $$$\{[5, 7], [2]\}$$$, XOR $$$0$$$; $$$\{[5], [5, 7], [2]\}$$$, XOR $$$5$$$; As you can see, subset $$$\{[5, 7], [2]\}$$$ has its XOR equal to $$$0$$$, which is unacceptable. You can check that for other divisions of size $$$3$$$ or $$$4$$$, non-empty subset with $$$0$$$ XOR always exists.The second example has no suitable divisions.The third example array can be divided into $$$\{[3], [1], [10]\}$$$. No subset of these segments has its XOR equal to $$$0$$$. | Java 8 | standard input | [
"math",
"matrices"
] | 0e0f30521f9f5eb5cff2549cd391da3c | The first line contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β the size of the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 10^9$$$). | 2,300 | Print the maximum number of segments the array can be divided into while following the given constraints. Print -1 if no suitable division exists. | standard output | |
PASSED | ed44e3d4806e42b469f447b2d711c076 | train_001.jsonl | 1547217300 | You are given an array $$$a_1, a_2, \dots, a_n$$$ of integer numbers.Your task is to divide the array into the maximum number of segments in such a way that: each element is contained in exactly one segment; each segment contains at least one element; there doesn't exist a non-empty subset of segments such that bitwise XOR of the numbers from them is equal to $$$0$$$. Print the maximum number of segments the array can be divided into. Print -1 if no suitable division exists. | 256 megabytes | import java.lang.*;
import java.math.*;
import java.util.*;
import java.io.*;
public class Main {
void solve() {
int n=ni();
int a[]=new int[n+1];
for(int i=1;i<=n;i++){
a[i]=ni()^a[i-1];
}
if(a[n]==0) {
pw.println("-1");
return;
}
int ans=0;
basis=new int[31];
Arrays.fill(basis,-1);
for(int i=1;i<=n;i++) insert(a[i]);
for(int i=0;i<30;i++) if(basis[i]!=-1) ans++;
pw.println(ans);
}
int basis[];
int LOGN=30;
void insert(int x){
for(int i=LOGN-1;i>=0;i--){
if(((x>>i)&1)==0) continue;
if(basis[i]==-1){
basis[i]=x;
break;
}else {
x^=basis[i];
}
}
}
long M= (long)1e9+7;
InputStream is;
PrintWriter pw;
String INPUT = "";
void run() throws Exception {
is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes());
pw = new PrintWriter(System.out);
long s = System.currentTimeMillis();
solve();
pw.flush();
if(!INPUT.isEmpty())tr(System.currentTimeMillis()-s+"ms");
}
public static void main(String[] args) throws Exception { new Main().run(); }
private byte[] inbuf = new byte[1024];
public int lenbuf = 0, ptrbuf = 0;
private int readByte() {
if(lenbuf == -1)throw new InputMismatchException();
if(ptrbuf >= lenbuf){
ptrbuf = 0;
try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); }
if(lenbuf <= 0)return -1;
}
return inbuf[ptrbuf++];
}
private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }
private double nd() { return Double.parseDouble(ns()); }
private char nc() { return (char)skip(); }
private String ns() {
int b = skip();
StringBuilder sb = new StringBuilder();
while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private char[] ns(int n) {
char[] buf = new char[n];
int b = skip(), p = 0;
while(p < n && !(isSpaceChar(b))){
buf[p++] = (char)b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private char[][] nm(int n, int m) {
char[][] map = new char[n][];
for(int i = 0;i < n;i++)map[i] = ns(m);
return map;
}
private int[] na(int n) {
int[] a = new int[n];
for(int i = 0;i < n;i++)a[i] = ni();
return a;
}
private int ni() {
int num = 0, b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private long nl() {
long num = 0;
int b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private boolean oj = System.getProperty("ONLINE_JUDGE") != null;
private void tr(Object... o) { if(INPUT.length() > 0)System.out.println(Arrays.deepToString(o)); }
} | Java | ["4\n5 5 7 2", "3\n1 2 3", "3\n3 1 10"] | 2 seconds | ["2", "-1", "3"] | NoteIn the first example $$$2$$$ is the maximum number. If you divide the array into $$$\{[5], [5, 7, 2]\}$$$, the XOR value of the subset of only the second segment is $$$5 \oplus 7 \oplus 2 = 0$$$. $$$\{[5, 5], [7, 2]\}$$$ has the value of the subset of only the first segment being $$$5 \oplus 5 = 0$$$. However, $$$\{[5, 5, 7], [2]\}$$$ will lead to subsets $$$\{[5, 5, 7]\}$$$ of XOR $$$7$$$, $$$\{[2]\}$$$ of XOR $$$2$$$ and $$$\{[5, 5, 7], [2]\}$$$ of XOR $$$5 \oplus 5 \oplus 7 \oplus 2 = 5$$$.Let's take a look at some division on $$$3$$$ segments β $$$\{[5], [5, 7], [2]\}$$$. It will produce subsets: $$$\{[5]\}$$$, XOR $$$5$$$; $$$\{[5, 7]\}$$$, XOR $$$2$$$; $$$\{[5], [5, 7]\}$$$, XOR $$$7$$$; $$$\{[2]\}$$$, XOR $$$2$$$; $$$\{[5], [2]\}$$$, XOR $$$7$$$; $$$\{[5, 7], [2]\}$$$, XOR $$$0$$$; $$$\{[5], [5, 7], [2]\}$$$, XOR $$$5$$$; As you can see, subset $$$\{[5, 7], [2]\}$$$ has its XOR equal to $$$0$$$, which is unacceptable. You can check that for other divisions of size $$$3$$$ or $$$4$$$, non-empty subset with $$$0$$$ XOR always exists.The second example has no suitable divisions.The third example array can be divided into $$$\{[3], [1], [10]\}$$$. No subset of these segments has its XOR equal to $$$0$$$. | Java 8 | standard input | [
"math",
"matrices"
] | 0e0f30521f9f5eb5cff2549cd391da3c | The first line contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β the size of the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 10^9$$$). | 2,300 | Print the maximum number of segments the array can be divided into while following the given constraints. Print -1 if no suitable division exists. | standard output | |
PASSED | 1bfd241753b40b0c25e63ab5d7431eef | train_001.jsonl | 1371042000 | Smart Beaver decided to be not only smart, but also a healthy beaver! And so he began to attend physical education classes at school X. In this school, physical education has a very creative teacher. One of his favorite warm-up exercises is throwing balls. Students line up. Each one gets a single ball in the beginning. The balls are numbered from 1 to n (by the demand of the inventory commission). Figure 1. The initial position for nβ=β5. After receiving the balls the students perform the warm-up exercise. The exercise takes place in a few throws. For each throw the teacher chooses any two arbitrary different students who will participate in it. The selected students throw their balls to each other. Thus, after each throw the students remain in their positions, and the two balls are swapped. Figure 2. The example of a throw. In this case there was a throw between the students, who were holding the 2-nd and the 4-th balls. Since the warm-up has many exercises, each of them can only continue for little time. Therefore, for each student we know the maximum number of throws he can participate in. For this lessons maximum number of throws will be 1 or 2.Note that after all phases of the considered exercise any ball can end up with any student. Smart Beaver decided to formalize it and introduced the concept of the "ball order". The ball order is a sequence of n numbers that correspond to the order of balls in the line. The first number will match the number of the ball of the first from the left student in the line, the second number will match the ball of the second student, and so on. For example, in figure 2 the order of the balls was (1, 2, 3, 4, 5), and after the throw it was (1, 4, 3, 2, 5). Smart beaver knows the number of students and for each student he knows the maximum number of throws in which he can participate. And now he is wondering: what is the number of distinct ways of ball orders by the end of the exercise. | 256 megabytes | import java.util.*;
import java.io.*;
public class DwithPrecalc {
FastScanner in;
PrintWriter out;
final long mod = 1000_000_000 + 7;
public void solve() throws IOException {
int n = in.nextInt();
int[] a = new int[n];
int count = 0;
for (int i = 0; i < n; i++) {
a[i] = in.nextInt();
if (a[i] == 2) {
count++;
}
}
long[] d = new long[n + 1];
d[0] = 1;
d[1] = 1;
for (int i = 2; i <= n; i++) {
d[i] = (d[i - 1] + (i - 1) * d[i - 2]) % mod;
}
long ans = d[n - count];
for (int i = n - count + 1; i <= n; i++) {
ans = (ans * i) % mod;
}
out.println(ans);
}
public void run() {
try {
in = new FastScanner();
out = new PrintWriter(System.out);
solve();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
class FastScanner {
BufferedReader br;
StringTokenizer st;
FastScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
boolean hasNext() {
while (st == null || !st.hasMoreTokens()) {
try {
String s = br.readLine();
if (s == null) {
return false;
}
st = new StringTokenizer(s);
} catch (IOException e) {
e.printStackTrace();
}
}
return true;
}
String next() {
while (st == null || !st.hasMoreTokens()) {
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());
}
}
public static void main(String[] arg) {
new DwithPrecalc().run();
}
} | Java | ["5\n1 2 2 1 2", "8\n1 2 2 1 2 1 1 2"] | 3 seconds | ["120", "16800"] | null | Java 7 | standard input | [
"dp"
] | 91e8dbe94273e255182aca0f94117bb9 | The first line contains a single number n β the number of students in the line and the number of balls. The next line contains exactly n space-separated integers. Each number corresponds to a student in the line (the i-th number corresponds to the i-th from the left student in the line) and shows the number of throws he can participate in. The input limits for scoring 30 points are (subproblem D1): 1ββ€βnββ€β10. The input limits for scoring 70 points are (subproblems D1+D2): 1ββ€βnββ€β500. The input limits for scoring 100 points are (subproblems D1+D2+D3): 1ββ€βnββ€β1000000. | 2,300 | The output should contain a single integer β the number of variants of ball orders after the warm up exercise is complete. As the number can be rather large, print it modulo 1000000007 (109β+β7). | standard output | |
PASSED | 553bfccc5ed4ae9c7044b011476fdf26 | train_001.jsonl | 1371042000 | Smart Beaver decided to be not only smart, but also a healthy beaver! And so he began to attend physical education classes at school X. In this school, physical education has a very creative teacher. One of his favorite warm-up exercises is throwing balls. Students line up. Each one gets a single ball in the beginning. The balls are numbered from 1 to n (by the demand of the inventory commission). Figure 1. The initial position for nβ=β5. After receiving the balls the students perform the warm-up exercise. The exercise takes place in a few throws. For each throw the teacher chooses any two arbitrary different students who will participate in it. The selected students throw their balls to each other. Thus, after each throw the students remain in their positions, and the two balls are swapped. Figure 2. The example of a throw. In this case there was a throw between the students, who were holding the 2-nd and the 4-th balls. Since the warm-up has many exercises, each of them can only continue for little time. Therefore, for each student we know the maximum number of throws he can participate in. For this lessons maximum number of throws will be 1 or 2.Note that after all phases of the considered exercise any ball can end up with any student. Smart Beaver decided to formalize it and introduced the concept of the "ball order". The ball order is a sequence of n numbers that correspond to the order of balls in the line. The first number will match the number of the ball of the first from the left student in the line, the second number will match the ball of the second student, and so on. For example, in figure 2 the order of the balls was (1, 2, 3, 4, 5), and after the throw it was (1, 4, 3, 2, 5). Smart beaver knows the number of students and for each student he knows the maximum number of throws in which he can participate. And now he is wondering: what is the number of distinct ways of ball orders by the end of the exercise. | 256 megabytes | import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Locale;
import java.util.Scanner;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;
public class Solution {
BufferedReader in;
PrintWriter out;
StringTokenizer st;
String nextToken() throws Exception {
if (st == null || !st.hasMoreTokens()) st = new StringTokenizer(in.readLine());
return st.nextToken();
}
int nextInt() throws Exception {
return Integer.parseInt(nextToken());
}
long[] fkt = new long[1000100];
long modd = 1000000007;
long[][] c = new long[1001][1001];
long[][] cash = new long[501][501];
long f(int n, int t) {
if (cash[n][t] != -1) return cash[n][t];
long res = 0;
if (n == t) res = fkt[n]; else {
for (int i = 0; i <= t; i++) {
long tmp = c[t][i];
res = (res + tmp * fkt[i] % modd * f(n - i - 1, t - i)) % modd;
if (n > t + 1) res = (res + tmp * fkt[i + 1] % modd * f(n - i - 2, t - i) % modd * (n - t - 1)) % modd;
}
}
return cash[n][t] = res;
}
void solve() throws Exception {
for (long[] q : cash) Arrays.fill(q, -1);
fkt[0] = 1;
for (int i = 1; i <= 500; i++) fkt[i] = (fkt[i - 1] * i) % modd;
c[0][0] = 1;
for (int i = 1; i <= 500; i++) {
c[i][0] = 1;
for (int j = 1; j <= i; j++) {
c[i][j] = (c[i - 1][j - 1] + c[i - 1][j]) % modd;
}
}
int n = nextInt();
int t = 0;
for (int i = 0; i < n; i++) {
t += nextInt() - 1;
}
out.println(f(n, t));
}
void run() {
try {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
Locale.setDefault(Locale.US);
solve();
} catch(Exception e) {
e.printStackTrace();
System.exit(1);
} finally {
out.close();
}
}
public static void main(String[] args) {
new Solution().run();
}
}
| Java | ["5\n1 2 2 1 2", "8\n1 2 2 1 2 1 1 2"] | 3 seconds | ["120", "16800"] | null | Java 7 | standard input | [
"dp"
] | 91e8dbe94273e255182aca0f94117bb9 | The first line contains a single number n β the number of students in the line and the number of balls. The next line contains exactly n space-separated integers. Each number corresponds to a student in the line (the i-th number corresponds to the i-th from the left student in the line) and shows the number of throws he can participate in. The input limits for scoring 30 points are (subproblem D1): 1ββ€βnββ€β10. The input limits for scoring 70 points are (subproblems D1+D2): 1ββ€βnββ€β500. The input limits for scoring 100 points are (subproblems D1+D2+D3): 1ββ€βnββ€β1000000. | 2,300 | The output should contain a single integer β the number of variants of ball orders after the warm up exercise is complete. As the number can be rather large, print it modulo 1000000007 (109β+β7). | standard output | |
PASSED | 86fc5ef37a6958ff48413a5740c76ea9 | train_001.jsonl | 1371042000 | Smart Beaver decided to be not only smart, but also a healthy beaver! And so he began to attend physical education classes at school X. In this school, physical education has a very creative teacher. One of his favorite warm-up exercises is throwing balls. Students line up. Each one gets a single ball in the beginning. The balls are numbered from 1 to n (by the demand of the inventory commission). Figure 1. The initial position for nβ=β5. After receiving the balls the students perform the warm-up exercise. The exercise takes place in a few throws. For each throw the teacher chooses any two arbitrary different students who will participate in it. The selected students throw their balls to each other. Thus, after each throw the students remain in their positions, and the two balls are swapped. Figure 2. The example of a throw. In this case there was a throw between the students, who were holding the 2-nd and the 4-th balls. Since the warm-up has many exercises, each of them can only continue for little time. Therefore, for each student we know the maximum number of throws he can participate in. For this lessons maximum number of throws will be 1 or 2.Note that after all phases of the considered exercise any ball can end up with any student. Smart Beaver decided to formalize it and introduced the concept of the "ball order". The ball order is a sequence of n numbers that correspond to the order of balls in the line. The first number will match the number of the ball of the first from the left student in the line, the second number will match the ball of the second student, and so on. For example, in figure 2 the order of the balls was (1, 2, 3, 4, 5), and after the throw it was (1, 4, 3, 2, 5). Smart beaver knows the number of students and for each student he knows the maximum number of throws in which he can participate. And now he is wondering: what is the number of distinct ways of ball orders by the end of the exercise. | 256 megabytes | import java.io.OutputStreamWriter;
import java.io.BufferedWriter;
import java.util.Comparator;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.List;
import java.io.IOException;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.ArrayList;
import java.util.NoSuchElementException;
import java.math.BigInteger;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author Egor Kulikov (egor@egork.net)
*/
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);
TaskD1 solver = new TaskD1();
solver.solve(1, in, out);
out.close();
}
}
class TaskD1 {
long[][] answer;
long[][] c;
long[] f;
static final long MOD = 1000000007;
public void solve(int testNumber, InputReader in, OutputWriter out) {
int count = in.readInt();
int a = 0;
int b = 0;
for (int i = 0; i < count; i++) {
if (in.readInt() == 1)
a++;
else
b++;
}
answer = new long[a + 1][b + 1];
ArrayUtils.fill(answer, -1);
answer[0][0] = 1;
for (int i = 1; i <= b; i++) {
answer[0][i] = answer[0][i - 1] * i % MOD;
}
c = IntegerUtils.generateBinomialCoefficients(a + b + 1, MOD);
f = IntegerUtils.generateFactorial(a + b + 1, MOD);
out.printLine(go(a, b));
}
private long go(int a, int b) {
if (answer[a][b] != -1)
return answer[a][b];
answer[a][b] = 0;
for (int i = 1; i <= a && i <= 2; i++) {
for (int j = 0; j <= b; j++) {
answer[a][b] += c[a - 1][i - 1] * c[b][j] % MOD * f[i + j - 1] % MOD * go(a - i, b - j) % MOD;
}
}
return answer[a][b] %= MOD;
}
}
class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int readInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return 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);
}
}
class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(Object...objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0)
writer.print(' ');
writer.print(objects[i]);
}
}
public void printLine(Object...objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
}
class ArrayUtils {
public static void fill(long[][] array, long value) {
for (long[] row : array)
Arrays.fill(row, value);
}
}
class IntegerUtils {
public static long[][] generateBinomialCoefficients(int n, long module) {
long[][] result = new long[n + 1][n + 1];
if (module == 1)
return result;
for (int i = 0; i <= n; i++) {
result[i][0] = 1;
for (int j = 1; j <= i; j++) {
result[i][j] = result[i - 1][j - 1] + result[i - 1][j];
if (result[i][j] >= module)
result[i][j] -= module;
}
}
return result;
}
public static long[] generateFactorial(int count, long module) {
long[] result = new long[count];
if (module == -1) {
if (count != 0)
result[0] = 1;
for (int i = 1; i < count; i++)
result[i] = result[i - 1] * i;
} else {
if (count != 0)
result[0] = 1 % module;
for (int i = 1; i < count; i++)
result[i] = (result[i - 1] * i) % module;
}
return result;
}
}
| Java | ["5\n1 2 2 1 2", "8\n1 2 2 1 2 1 1 2"] | 3 seconds | ["120", "16800"] | null | Java 7 | standard input | [
"dp"
] | 91e8dbe94273e255182aca0f94117bb9 | The first line contains a single number n β the number of students in the line and the number of balls. The next line contains exactly n space-separated integers. Each number corresponds to a student in the line (the i-th number corresponds to the i-th from the left student in the line) and shows the number of throws he can participate in. The input limits for scoring 30 points are (subproblem D1): 1ββ€βnββ€β10. The input limits for scoring 70 points are (subproblems D1+D2): 1ββ€βnββ€β500. The input limits for scoring 100 points are (subproblems D1+D2+D3): 1ββ€βnββ€β1000000. | 2,300 | The output should contain a single integer β the number of variants of ball orders after the warm up exercise is complete. As the number can be rather large, print it modulo 1000000007 (109β+β7). | standard output | |
PASSED | b5d2fe09638c2286b2d30b0384ae746f | train_001.jsonl | 1371042000 | Smart Beaver decided to be not only smart, but also a healthy beaver! And so he began to attend physical education classes at school X. In this school, physical education has a very creative teacher. One of his favorite warm-up exercises is throwing balls. Students line up. Each one gets a single ball in the beginning. The balls are numbered from 1 to n (by the demand of the inventory commission). Figure 1. The initial position for nβ=β5. After receiving the balls the students perform the warm-up exercise. The exercise takes place in a few throws. For each throw the teacher chooses any two arbitrary different students who will participate in it. The selected students throw their balls to each other. Thus, after each throw the students remain in their positions, and the two balls are swapped. Figure 2. The example of a throw. In this case there was a throw between the students, who were holding the 2-nd and the 4-th balls. Since the warm-up has many exercises, each of them can only continue for little time. Therefore, for each student we know the maximum number of throws he can participate in. For this lessons maximum number of throws will be 1 or 2.Note that after all phases of the considered exercise any ball can end up with any student. Smart Beaver decided to formalize it and introduced the concept of the "ball order". The ball order is a sequence of n numbers that correspond to the order of balls in the line. The first number will match the number of the ball of the first from the left student in the line, the second number will match the ball of the second student, and so on. For example, in figure 2 the order of the balls was (1, 2, 3, 4, 5), and after the throw it was (1, 4, 3, 2, 5). Smart beaver knows the number of students and for each student he knows the maximum number of throws in which he can participate. And now he is wondering: what is the number of distinct ways of ball orders by the end of the exercise. | 256 megabytes | import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.InputMismatchException;
public class A {
static final long mod = 1000000007;
public static void main(String[] args) {
MScanner sc = new MScanner();
PrintWriter out = new PrintWriter(System.out);
int N = sc.nextInt(), ONE = 0, TWO = 0;
for(int a=0;a<N;a++)if(sc.nextInt()==1)ONE++;else TWO++;
long[] inv = new long[N+10];
inv[0]=inv[1]=1;
for(int a=2;a<=ONE;a++)
inv[a]=(inv[a-1]+(a-1)*inv[a-2])%mod;
long ans = inv[ONE];
for(int a=0;a<TWO;a++)
ans = (ans*(TWO+ONE-a))%mod;
out.println(ans);
out.close();
}
static class MScanner{
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public MScanner(){
stream = System.in;
//stream = new FileInputStream(new File("dec.in"));
}
int read(){
if(numChars==-1)
throw new InputMismatchException();
if(curChar>=numChars){
curChar = 0;
try{
numChars = stream.read(buf);
} catch (IOException e){
throw new InputMismatchException();
}
if(numChars <= 0)
return -1;
}
return buf[curChar++];
}
boolean isSpaceChar(int c){
return c==' '||c=='\n'||c=='\r'||c=='\t'||c==-1;
}
boolean isEndline(int c){
return c=='\n'||c=='\r'||c==-1;
}
int nextInt(){
return Integer.parseInt(next());
}
int[] nextInt(int N){
int[] ret = new int[N];
for(int a=0;a<N;a++)
ret[a] = nextInt();
return ret;
}
long nextLong(){
return Long.parseLong(next());
}
long[] nextLong(int N){
long[] ret = new long[N];
for(int a=0;a<N;a++)
ret[a] = nextLong();
return ret;
}
double nextDouble(){
return Double.parseDouble(next());
}
double[] nextDouble(int N){
double[] ret = new double[N];
for(int a=0;a<N;a++)
ret[a] = nextDouble();
return ret;
}
String next(){
int c = read();
while(isSpaceChar(c))
c=read();
StringBuilder res = new StringBuilder();
do{
res.appendCodePoint(c);
c=read();
} while(!isSpaceChar(c));
return res.toString();
}
String[] next(int N){
String[] ret = new String[N];
for(int a=0;a<N;a++)
ret[a] = next();
return ret;
}
String nextLine(){
int c = read();
while(isEndline(c))
c=read();
StringBuilder res = new StringBuilder();
do{
res.appendCodePoint(c);
c = read();
}while(!isEndline(c));
return res.toString();
}
String[] nextLine(int N){
String[] ret = new String[N];
for(int a=0;a<N;a++)
ret[a] = nextLine();
return ret;
}
}
}
| Java | ["5\n1 2 2 1 2", "8\n1 2 2 1 2 1 1 2"] | 3 seconds | ["120", "16800"] | null | Java 7 | standard input | [
"dp"
] | 91e8dbe94273e255182aca0f94117bb9 | The first line contains a single number n β the number of students in the line and the number of balls. The next line contains exactly n space-separated integers. Each number corresponds to a student in the line (the i-th number corresponds to the i-th from the left student in the line) and shows the number of throws he can participate in. The input limits for scoring 30 points are (subproblem D1): 1ββ€βnββ€β10. The input limits for scoring 70 points are (subproblems D1+D2): 1ββ€βnββ€β500. The input limits for scoring 100 points are (subproblems D1+D2+D3): 1ββ€βnββ€β1000000. | 2,300 | The output should contain a single integer β the number of variants of ball orders after the warm up exercise is complete. As the number can be rather large, print it modulo 1000000007 (109β+β7). | standard output | |
PASSED | 2b3a0795440d3ccbb48ec51578843cb7 | train_001.jsonl | 1371042000 | Smart Beaver decided to be not only smart, but also a healthy beaver! And so he began to attend physical education classes at school X. In this school, physical education has a very creative teacher. One of his favorite warm-up exercises is throwing balls. Students line up. Each one gets a single ball in the beginning. The balls are numbered from 1 to n (by the demand of the inventory commission). Figure 1. The initial position for nβ=β5. After receiving the balls the students perform the warm-up exercise. The exercise takes place in a few throws. For each throw the teacher chooses any two arbitrary different students who will participate in it. The selected students throw their balls to each other. Thus, after each throw the students remain in their positions, and the two balls are swapped. Figure 2. The example of a throw. In this case there was a throw between the students, who were holding the 2-nd and the 4-th balls. Since the warm-up has many exercises, each of them can only continue for little time. Therefore, for each student we know the maximum number of throws he can participate in. For this lessons maximum number of throws will be 1 or 2.Note that after all phases of the considered exercise any ball can end up with any student. Smart Beaver decided to formalize it and introduced the concept of the "ball order". The ball order is a sequence of n numbers that correspond to the order of balls in the line. The first number will match the number of the ball of the first from the left student in the line, the second number will match the ball of the second student, and so on. For example, in figure 2 the order of the balls was (1, 2, 3, 4, 5), and after the throw it was (1, 4, 3, 2, 5). Smart beaver knows the number of students and for each student he knows the maximum number of throws in which he can participate. And now he is wondering: what is the number of distinct ways of ball orders by the end of the exercise. | 256 megabytes | import static java.lang.Double.parseDouble;
import static java.lang.Integer.parseInt;
import static java.lang.Long.parseLong;
import static java.lang.System.exit;
import static java.util.Arrays.fill;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;
public class D {
static BufferedReader in;
static PrintWriter out;
static StringTokenizer tok;
static final int MOD = 1000000007;
static int add(int a, int b) {
int res = a + b;
if (res > MOD) {
res -= MOD;
}
return res;
}
static int sub(int a, int b) {
int res = a - b;
if (res < 0) {
res += MOD;
}
return res;
}
static int mul(int a, int b) {
return (int) ((long) a * b % MOD);
}
static void solve() throws Exception {
int n = nextInt();
int ones = 0;
int twos = 0;
for (int i = 0; i < n; i++) {
if (nextInt() == 1) {
++ones;
} else {
++twos;
}
}
// int c[][] = new int[twos + 1][];
// for (int i = 0; i < c.length; i++) {
// c[i] = new int[i + 1];
// c[i][0] = c[i][i] = 1;
// for (int j = 1; j < i; j++) {
// c[i][j] = add(c[i - 1][j - 1], c[i - 1][j]);
// }
// }
int dyn[][] = new int[ones + 1][twos + 1];
fill(dyn[0], 1);
for (int i = 1; i <= ones; i++) {
for (int j = 0; j <= twos; j++) {
int cans = 0;
if (i >= 2) {
for (int k = 0; k <= j; k++) {
cans = add(cans, mul(k + 1, dyn[i - 2][j - k]));
}
cans = mul(cans, i - 1);
}
for (int k = 0; k <= j; k++) {
cans = add(cans, dyn[i - 1][j - k]);
}
dyn[i][j] = cans;
}
}
int ans = dyn[ones][twos];
for (int i = 1; i <= twos; i++) {
ans = mul(ans, i);
}
out.print(ans);
}
static int nextInt() throws IOException {
return parseInt(next());
}
static long nextLong() throws IOException {
return parseLong(next());
}
static double nextDouble() throws IOException {
return parseDouble(next());
}
static String next() throws IOException {
while (tok == null || !tok.hasMoreTokens()) {
tok = new StringTokenizer(in.readLine());
}
return tok.nextToken();
}
public static void main(String[] args) {
try {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(new OutputStreamWriter(System.out));
solve();
in.close();
out.close();
} catch (Throwable e) {
e.printStackTrace();
exit(1);
}
}
}
| Java | ["5\n1 2 2 1 2", "8\n1 2 2 1 2 1 1 2"] | 3 seconds | ["120", "16800"] | null | Java 7 | standard input | [
"dp"
] | 91e8dbe94273e255182aca0f94117bb9 | The first line contains a single number n β the number of students in the line and the number of balls. The next line contains exactly n space-separated integers. Each number corresponds to a student in the line (the i-th number corresponds to the i-th from the left student in the line) and shows the number of throws he can participate in. The input limits for scoring 30 points are (subproblem D1): 1ββ€βnββ€β10. The input limits for scoring 70 points are (subproblems D1+D2): 1ββ€βnββ€β500. The input limits for scoring 100 points are (subproblems D1+D2+D3): 1ββ€βnββ€β1000000. | 2,300 | The output should contain a single integer β the number of variants of ball orders after the warm up exercise is complete. As the number can be rather large, print it modulo 1000000007 (109β+β7). | standard output | |
PASSED | 75a883b01887378abccd58ac8b3d27ca | train_001.jsonl | 1371042000 | Smart Beaver decided to be not only smart, but also a healthy beaver! And so he began to attend physical education classes at school X. In this school, physical education has a very creative teacher. One of his favorite warm-up exercises is throwing balls. Students line up. Each one gets a single ball in the beginning. The balls are numbered from 1 to n (by the demand of the inventory commission). Figure 1. The initial position for nβ=β5. After receiving the balls the students perform the warm-up exercise. The exercise takes place in a few throws. For each throw the teacher chooses any two arbitrary different students who will participate in it. The selected students throw their balls to each other. Thus, after each throw the students remain in their positions, and the two balls are swapped. Figure 2. The example of a throw. In this case there was a throw between the students, who were holding the 2-nd and the 4-th balls. Since the warm-up has many exercises, each of them can only continue for little time. Therefore, for each student we know the maximum number of throws he can participate in. For this lessons maximum number of throws will be 1 or 2.Note that after all phases of the considered exercise any ball can end up with any student. Smart Beaver decided to formalize it and introduced the concept of the "ball order". The ball order is a sequence of n numbers that correspond to the order of balls in the line. The first number will match the number of the ball of the first from the left student in the line, the second number will match the ball of the second student, and so on. For example, in figure 2 the order of the balls was (1, 2, 3, 4, 5), and after the throw it was (1, 4, 3, 2, 5). Smart beaver knows the number of students and for each student he knows the maximum number of throws in which he can participate. And now he is wondering: what is the number of distinct ways of ball orders by the end of the exercise. | 256 megabytes | import java.util.*;
import java.io.*;
public class PE {
final static long mod = 1000000007;
public static void main(String[] args) throws Exception {
Parser in = new Parser(System.in);
int n = in.nextInt();
int count2s = 0;
for(int i = 0; i < n; i++) {
int checker = in.nextInt();
if(checker == 2) {
count2s++;
}
}
long[] dp = new long[n + 1];
dp[0] = dp[1] = 1;
for(int k = 2; k < dp.length; k++) {
dp[k] = (dp[k - 1] + (k - 1) * dp[k - 2]) % mod;
}
long numPerm = dp[n - count2s];
for(int x = n - count2s + 1; x <= n; x++) {
numPerm = (numPerm * x) % mod;
}
System.out.println(numPerm);
}
}
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 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;
}
public double nextDouble() throws Exception
{
double 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 | ["5\n1 2 2 1 2", "8\n1 2 2 1 2 1 1 2"] | 3 seconds | ["120", "16800"] | null | Java 7 | standard input | [
"dp"
] | 91e8dbe94273e255182aca0f94117bb9 | The first line contains a single number n β the number of students in the line and the number of balls. The next line contains exactly n space-separated integers. Each number corresponds to a student in the line (the i-th number corresponds to the i-th from the left student in the line) and shows the number of throws he can participate in. The input limits for scoring 30 points are (subproblem D1): 1ββ€βnββ€β10. The input limits for scoring 70 points are (subproblems D1+D2): 1ββ€βnββ€β500. The input limits for scoring 100 points are (subproblems D1+D2+D3): 1ββ€βnββ€β1000000. | 2,300 | The output should contain a single integer β the number of variants of ball orders after the warm up exercise is complete. As the number can be rather large, print it modulo 1000000007 (109β+β7). | standard output | |
PASSED | 588a51d6b54f022552d14a0ad7d97ae8 | train_001.jsonl | 1371042000 | Smart Beaver decided to be not only smart, but also a healthy beaver! And so he began to attend physical education classes at school X. In this school, physical education has a very creative teacher. One of his favorite warm-up exercises is throwing balls. Students line up. Each one gets a single ball in the beginning. The balls are numbered from 1 to n (by the demand of the inventory commission). Figure 1. The initial position for nβ=β5. After receiving the balls the students perform the warm-up exercise. The exercise takes place in a few throws. For each throw the teacher chooses any two arbitrary different students who will participate in it. The selected students throw their balls to each other. Thus, after each throw the students remain in their positions, and the two balls are swapped. Figure 2. The example of a throw. In this case there was a throw between the students, who were holding the 2-nd and the 4-th balls. Since the warm-up has many exercises, each of them can only continue for little time. Therefore, for each student we know the maximum number of throws he can participate in. For this lessons maximum number of throws will be 1 or 2.Note that after all phases of the considered exercise any ball can end up with any student. Smart Beaver decided to formalize it and introduced the concept of the "ball order". The ball order is a sequence of n numbers that correspond to the order of balls in the line. The first number will match the number of the ball of the first from the left student in the line, the second number will match the ball of the second student, and so on. For example, in figure 2 the order of the balls was (1, 2, 3, 4, 5), and after the throw it was (1, 4, 3, 2, 5). Smart beaver knows the number of students and for each student he knows the maximum number of throws in which he can participate. And now he is wondering: what is the number of distinct ways of ball orders by the end of the exercise. | 256 megabytes | import java.io.InputStreamReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.Writer;
import java.util.HashSet;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author Niyaz Nigmatullin
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastScanner in = new FastScanner(inputStream);
FastPrinter out = new FastPrinter(outputStream);
TaskD1 solver = new TaskD1();
solver.solve(1, in, out);
out.close();
}
}
class TaskD1 {
static final int MOD = 1000000007;
static int get(int n) {
if (n <= 1) return 1;
int[] dp = new int[n + 1];
dp[0] = dp[1] = 1;
for (int i = 2; i <= n; i++) {
dp[i] = (int) ((dp[i - 1] + (long) (i - 1) * dp[i - 2]) % MOD);
}
return dp[n];
}
public void solve(int testNumber, FastScanner in, FastPrinter out) {
int n = in.nextInt();
int[] a = in.readIntArray(n);
int ones = 0;
for (int i : a) {
if (i == 1) {
ones++;
}
}
long dp = get(ones);
for (int i = ones + 1; i <= n; i++) {
dp = dp * i % MOD;
}
out.println(dp);
// if (dp != solve(a)) {
// throw new AssertionError();
// }
// for (int ones = 8; ones <= 8; ones++) {
// for (int n = ones; n <= 8; n++) {
// int twos = n - ones;
// int[] a = new int[n];
// for (int i = 0; i < n; i++) {
// a[i] = i < ones ? 1 : 2;
// }
// System.out.println(n + " " + ones + " " + solve(a));
// }
// }
// int n = in.nextInt();
// int[] a = new int[n];
// for (int i = 0; i < n; i++) {
// a[i] = in.nextInt();
// }
// out.println(solve(a));
}
}
class FastScanner extends BufferedReader {
public FastScanner(InputStream is) {
super(new InputStreamReader(is));
}
public int read() {
try {
int ret = super.read();
// if (isEOF && ret < 0) {
// throw new InputMismatchException();
// }
// isEOF = ret == -1;
return ret;
} catch (IOException e) {
throw new InputMismatchException();
}
}
static boolean isWhiteSpace(int c) {
return c >= 0 && c <= 32;
}
public int nextInt() {
int c = read();
while (isWhiteSpace(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int ret = 0;
while (c >= 0 && !isWhiteSpace(c)) {
if (c < '0' || c > '9') {
throw new NumberFormatException("digit expected " + (char) c
+ " found");
}
ret = ret * 10 + c - '0';
c = read();
}
return ret * sgn;
}
public String readLine() {
try {
return super.readLine();
} catch (IOException e) {
return null;
}
}
public int[] readIntArray(int n) {
int[] ret = new int[n];
for (int i = 0; i < n; i++) {
ret[i] = nextInt();
}
return ret;
}
}
class FastPrinter extends PrintWriter {
public FastPrinter(OutputStream out) {
super(out);
}
public FastPrinter(Writer out) {
super(out);
}
}
| Java | ["5\n1 2 2 1 2", "8\n1 2 2 1 2 1 1 2"] | 3 seconds | ["120", "16800"] | null | Java 7 | standard input | [
"dp"
] | 91e8dbe94273e255182aca0f94117bb9 | The first line contains a single number n β the number of students in the line and the number of balls. The next line contains exactly n space-separated integers. Each number corresponds to a student in the line (the i-th number corresponds to the i-th from the left student in the line) and shows the number of throws he can participate in. The input limits for scoring 30 points are (subproblem D1): 1ββ€βnββ€β10. The input limits for scoring 70 points are (subproblems D1+D2): 1ββ€βnββ€β500. The input limits for scoring 100 points are (subproblems D1+D2+D3): 1ββ€βnββ€β1000000. | 2,300 | The output should contain a single integer β the number of variants of ball orders after the warm up exercise is complete. As the number can be rather large, print it modulo 1000000007 (109β+β7). | standard output | |
PASSED | b906fc1a4445869000d273c36130f493 | train_001.jsonl | 1371042000 | Smart Beaver decided to be not only smart, but also a healthy beaver! And so he began to attend physical education classes at school X. In this school, physical education has a very creative teacher. One of his favorite warm-up exercises is throwing balls. Students line up. Each one gets a single ball in the beginning. The balls are numbered from 1 to n (by the demand of the inventory commission). Figure 1. The initial position for nβ=β5. After receiving the balls the students perform the warm-up exercise. The exercise takes place in a few throws. For each throw the teacher chooses any two arbitrary different students who will participate in it. The selected students throw their balls to each other. Thus, after each throw the students remain in their positions, and the two balls are swapped. Figure 2. The example of a throw. In this case there was a throw between the students, who were holding the 2-nd and the 4-th balls. Since the warm-up has many exercises, each of them can only continue for little time. Therefore, for each student we know the maximum number of throws he can participate in. For this lessons maximum number of throws will be 1 or 2.Note that after all phases of the considered exercise any ball can end up with any student. Smart Beaver decided to formalize it and introduced the concept of the "ball order". The ball order is a sequence of n numbers that correspond to the order of balls in the line. The first number will match the number of the ball of the first from the left student in the line, the second number will match the ball of the second student, and so on. For example, in figure 2 the order of the balls was (1, 2, 3, 4, 5), and after the throw it was (1, 4, 3, 2, 5). Smart beaver knows the number of students and for each student he knows the maximum number of throws in which he can participate. And now he is wondering: what is the number of distinct ways of ball orders by the end of the exercise. | 256 megabytes | import java.io.*;
import java.util.*;
public class D {
static void solve() throws IOException {
int n = nextInt();
int one = 0, two = 0;
for (int i = 0; i < n; i++) {
int ok = nextInt();
if (ok == 1) {
++one;
}
if (ok > 1) {
++two;
}
}
int answer = get(one, two);
out.println(answer);
}
private static int get(int one, int two) {
int[][] dp = new int[one + 1][two + 1];
int[] fact = new int[one + two + 1];
fact[0] = 1;
for (int i = 0; i < fact.length - 1; i++) {
fact[i + 1] = (int) (fact[i] * (i + 1L) % MOD);
}
int[][] c = new int[two + 1][two + 1];
for (int i = 0; i <= two; i++) {
c[i][0] = 1;
for (int j = 1; j <= i; j++) {
c[i][j] = (int) ((long) c[i][j - 1] * (i - j + 1L) % MOD);
}
}
for (int i = 0; i <= one; i++) {
for (int j = 0; j <= two; j++) {
if (i == 0) {
dp[i][j] = fact[j];
continue;
}
long ok = 0;
for (int ones = 1; ones <= i && ones <= 2; ones++) {
for (int twos = 0; twos <= j; twos++) {
long add;
if (twos == 0) {
add = dp[i - ones][j];
if (ones == 2) {
add *= i - 1;
}
// ++ok;
} else {
add = (long)c[j][twos] * dp[i - ones][j - twos];
if (ones == 2) {
add %= MOD;
add *= i - 1;
add *= twos + 1;
}
}
ok += add;
if (ok < 0) {
ok -= MODMOD;
}
}
}
dp[i][j] = (int) (ok % MOD);
}
}
return dp[one][two];
}
static int add(int a, int b) {
a += b;
if (a >= MOD) {
a -= MOD;
}
return a;
}
static final int MOD = 1000000007;
static final long MODMOD = Long.MAX_VALUE / MOD * MOD;
static BufferedReader br;
static StringTokenizer st;
static PrintWriter out;
public static void main(String[] args) throws IOException {
InputStream input = System.in;
PrintStream output = System.out;
File file = new File("d.in");
if (file.exists() && file.canRead()) {
input = new FileInputStream(file);
}
br = new BufferedReader(new InputStreamReader(input));
out = new PrintWriter(output);
solve();
out.close();
}
static long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
static double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
static int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
static String nextToken() throws IOException {
while (st == null || !st.hasMoreTokens()) {
String line = br.readLine();
if (line == null) {
return null;
}
st = new StringTokenizer(line);
}
return st.nextToken();
}
}
| Java | ["5\n1 2 2 1 2", "8\n1 2 2 1 2 1 1 2"] | 3 seconds | ["120", "16800"] | null | Java 7 | standard input | [
"dp"
] | 91e8dbe94273e255182aca0f94117bb9 | The first line contains a single number n β the number of students in the line and the number of balls. The next line contains exactly n space-separated integers. Each number corresponds to a student in the line (the i-th number corresponds to the i-th from the left student in the line) and shows the number of throws he can participate in. The input limits for scoring 30 points are (subproblem D1): 1ββ€βnββ€β10. The input limits for scoring 70 points are (subproblems D1+D2): 1ββ€βnββ€β500. The input limits for scoring 100 points are (subproblems D1+D2+D3): 1ββ€βnββ€β1000000. | 2,300 | The output should contain a single integer β the number of variants of ball orders after the warm up exercise is complete. As the number can be rather large, print it modulo 1000000007 (109β+β7). | standard output | |
PASSED | abaf1482abbdc1be63452347969a28c3 | train_001.jsonl | 1371042000 | Smart Beaver decided to be not only smart, but also a healthy beaver! And so he began to attend physical education classes at school X. In this school, physical education has a very creative teacher. One of his favorite warm-up exercises is throwing balls. Students line up. Each one gets a single ball in the beginning. The balls are numbered from 1 to n (by the demand of the inventory commission). Figure 1. The initial position for nβ=β5. After receiving the balls the students perform the warm-up exercise. The exercise takes place in a few throws. For each throw the teacher chooses any two arbitrary different students who will participate in it. The selected students throw their balls to each other. Thus, after each throw the students remain in their positions, and the two balls are swapped. Figure 2. The example of a throw. In this case there was a throw between the students, who were holding the 2-nd and the 4-th balls. Since the warm-up has many exercises, each of them can only continue for little time. Therefore, for each student we know the maximum number of throws he can participate in. For this lessons maximum number of throws will be 1 or 2.Note that after all phases of the considered exercise any ball can end up with any student. Smart Beaver decided to formalize it and introduced the concept of the "ball order". The ball order is a sequence of n numbers that correspond to the order of balls in the line. The first number will match the number of the ball of the first from the left student in the line, the second number will match the ball of the second student, and so on. For example, in figure 2 the order of the balls was (1, 2, 3, 4, 5), and after the throw it was (1, 4, 3, 2, 5). Smart beaver knows the number of students and for each student he knows the maximum number of throws in which he can participate. And now he is wondering: what is the number of distinct ways of ball orders by the end of the exercise. | 256 megabytes | //package abbyycup2013;
import java.io.*;
public class ProblemD12 {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
PrintWriter writer = new PrintWriter(new OutputStreamWriter(System.out));
ProblemD12() throws IOException {
// reader = new BufferedReader(new FileReader("input.txt"));
// writer = new PrintWriter(new FileWriter("output.txt"));
}
int[] readInts() throws IOException {
String[] strings = reader.readLine().split(" ");
int[] ints = new int[strings.length];
for(int i = 0; i < ints.length; i++) {
ints[i] = Integer.parseInt(strings[i]);
}
return ints;
}
int[] tt = null;
int tx = 0;
int readInt() throws IOException {
if(tt == null || tx >= tt.length) {
tt = readInts();
tx = 0;
}
return tt[tx++];
}
int mod = 1000 * 1000 * 1000 + 7;
int sum(int x, int y) {
x += y;
return x >= mod ? x - mod : x;
}
int mult(int x, int y) {
return (int)((long)x * y % mod);
}
int pow(int x, int k) {
int ret = 1;
while(k > 0) {
if(k % 2 == 1) {
ret = mult(ret, x);
}
x = mult(x, x);
k /= 2;
}
return ret;
}
int inv(int x) {
return pow(x, mod - 2);
}
void solve() throws IOException {
int n = readInt();
int[] a = readInts();
n = 0;
int m = 0;
for(int x : a) if(x == 1) n++; else m++;
int[][] dp = new int[n + 1][m + 1];
dp[0][0] = 1;
int[] f = new int[n + m + 1];
f[0] = 1;
for(int i = 1; i < f.length; i++) {
f[i] = mult(f[i - 1], i);
}
int[] invs = new int[n + m + 1];
for(int i = 0; i < invs.length; i++) {
invs[i] = inv(f[i]);
}
int[][] C = new int[501][501];
for(int N = 0; N <= 500; N++) {
C[N][0] = 1;
for(int K = 1; K <= N; K++) {
C[N][K] = sum(C[N - 1][K - 1], C[N - 1][K]);
}
}
for(int i = 0; i <= n; i++) {
for(int j = 0; j <= m; j++) {
if(i + j == 0) continue;
if(i == 0) {
for(int k = 0; k <= j - 1; k++) {
int A = mult(f[j - 1], invs[j - 1 - k]);
dp[i][j] = sum(dp[i][j], mult(dp[i][j - 1 - k], A));
}
}
else {
for(int k = 0; k <= j; k++) {
int A = mult(f[j], invs[j - k]);
dp[i][j] = sum(dp[i][j], mult(dp[i - 1][j - k], A));
if(i >= 2) {
//dp[i][j] = sum(dp[i][j], mult(mult(dp[i - 2][j - k], i - 1), A));
//int C = mult(f[j], inv(mult(f[k], f[j - k])));
dp[i][j] = sum(dp[i][j], mult(mult(dp[i - 2][j - k], i - 1), mult(C[j][k], f[k + 1])));
}
}
}
}
}
writer.println(dp[n][m]);
writer.flush();
}
void multiSolve() throws IOException {
int n = readInts()[0];
for(int i = 0; i < n; i++) {
solve();
}
writer.flush();
}
public static void main(String[] args) throws IOException{
new ProblemD12().solve();
}
}
| Java | ["5\n1 2 2 1 2", "8\n1 2 2 1 2 1 1 2"] | 3 seconds | ["120", "16800"] | null | Java 7 | standard input | [
"dp"
] | 91e8dbe94273e255182aca0f94117bb9 | The first line contains a single number n β the number of students in the line and the number of balls. The next line contains exactly n space-separated integers. Each number corresponds to a student in the line (the i-th number corresponds to the i-th from the left student in the line) and shows the number of throws he can participate in. The input limits for scoring 30 points are (subproblem D1): 1ββ€βnββ€β10. The input limits for scoring 70 points are (subproblems D1+D2): 1ββ€βnββ€β500. The input limits for scoring 100 points are (subproblems D1+D2+D3): 1ββ€βnββ€β1000000. | 2,300 | The output should contain a single integer β the number of variants of ball orders after the warm up exercise is complete. As the number can be rather large, print it modulo 1000000007 (109β+β7). | standard output | |
PASSED | 65c29e8d73499f1d20cd26a16e6ced33 | train_001.jsonl | 1371042000 | Smart Beaver decided to be not only smart, but also a healthy beaver! And so he began to attend physical education classes at school X. In this school, physical education has a very creative teacher. One of his favorite warm-up exercises is throwing balls. Students line up. Each one gets a single ball in the beginning. The balls are numbered from 1 to n (by the demand of the inventory commission). Figure 1. The initial position for nβ=β5. After receiving the balls the students perform the warm-up exercise. The exercise takes place in a few throws. For each throw the teacher chooses any two arbitrary different students who will participate in it. The selected students throw their balls to each other. Thus, after each throw the students remain in their positions, and the two balls are swapped. Figure 2. The example of a throw. In this case there was a throw between the students, who were holding the 2-nd and the 4-th balls. Since the warm-up has many exercises, each of them can only continue for little time. Therefore, for each student we know the maximum number of throws he can participate in. For this lessons maximum number of throws will be 1 or 2.Note that after all phases of the considered exercise any ball can end up with any student. Smart Beaver decided to formalize it and introduced the concept of the "ball order". The ball order is a sequence of n numbers that correspond to the order of balls in the line. The first number will match the number of the ball of the first from the left student in the line, the second number will match the ball of the second student, and so on. For example, in figure 2 the order of the balls was (1, 2, 3, 4, 5), and after the throw it was (1, 4, 3, 2, 5). Smart beaver knows the number of students and for each student he knows the maximum number of throws in which he can participate. And now he is wondering: what is the number of distinct ways of ball orders by the end of the exercise. | 256 megabytes | import java.io.*;
import java.util.*;
public class cfABBYYCup3D {
BufferedReader br;
PrintWriter out;
StringTokenizer st;
boolean eof;
static final int MOD = 1000000007;
void solve() throws IOException {
int n = nextInt();
String s = br.readLine();
int one = 0;
int two = 0;
for (int i = 0; i < s.length(); i += 2) {
if (s.charAt(i) == '1')
one++;
else
two++;
}
int res = 1;
if (one > 1) {
int a = 1;
int b = 1;
for (int i = 2; i <= one; i++) {
int next = (int)((long)a * (i - 1) % MOD);
next += b;
if (next >= MOD)
next -= MOD;
a = b;
b = next;
}
res = b;
}
for (int i = one + 1; i <= one + two; i++)
res = (int)((long)res * i % MOD);
out.println(res);
}
void inp() throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
solve();
out.close();
}
public static void main(String[] args) throws IOException {
new cfABBYYCup3D().inp();
}
String nextToken() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
eof = true;
return null;
}
}
return st.nextToken();
}
String nextString() {
try {
return br.readLine();
} catch (IOException e) {
eof = true;
return null;
}
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
}
| Java | ["5\n1 2 2 1 2", "8\n1 2 2 1 2 1 1 2"] | 3 seconds | ["120", "16800"] | null | Java 7 | standard input | [
"dp"
] | 91e8dbe94273e255182aca0f94117bb9 | The first line contains a single number n β the number of students in the line and the number of balls. The next line contains exactly n space-separated integers. Each number corresponds to a student in the line (the i-th number corresponds to the i-th from the left student in the line) and shows the number of throws he can participate in. The input limits for scoring 30 points are (subproblem D1): 1ββ€βnββ€β10. The input limits for scoring 70 points are (subproblems D1+D2): 1ββ€βnββ€β500. The input limits for scoring 100 points are (subproblems D1+D2+D3): 1ββ€βnββ€β1000000. | 2,300 | The output should contain a single integer β the number of variants of ball orders after the warm up exercise is complete. As the number can be rather large, print it modulo 1000000007 (109β+β7). | standard output | |
PASSED | f7b504e7d79b0517aa21d6cd525864ea | train_001.jsonl | 1371042000 | Smart Beaver decided to be not only smart, but also a healthy beaver! And so he began to attend physical education classes at school X. In this school, physical education has a very creative teacher. One of his favorite warm-up exercises is throwing balls. Students line up. Each one gets a single ball in the beginning. The balls are numbered from 1 to n (by the demand of the inventory commission). Figure 1. The initial position for nβ=β5. After receiving the balls the students perform the warm-up exercise. The exercise takes place in a few throws. For each throw the teacher chooses any two arbitrary different students who will participate in it. The selected students throw their balls to each other. Thus, after each throw the students remain in their positions, and the two balls are swapped. Figure 2. The example of a throw. In this case there was a throw between the students, who were holding the 2-nd and the 4-th balls. Since the warm-up has many exercises, each of them can only continue for little time. Therefore, for each student we know the maximum number of throws he can participate in. For this lessons maximum number of throws will be 1 or 2.Note that after all phases of the considered exercise any ball can end up with any student. Smart Beaver decided to formalize it and introduced the concept of the "ball order". The ball order is a sequence of n numbers that correspond to the order of balls in the line. The first number will match the number of the ball of the first from the left student in the line, the second number will match the ball of the second student, and so on. For example, in figure 2 the order of the balls was (1, 2, 3, 4, 5), and after the throw it was (1, 4, 3, 2, 5). Smart beaver knows the number of students and for each student he knows the maximum number of throws in which he can participate. And now he is wondering: what is the number of distinct ways of ball orders by the end of the exercise. | 256 megabytes | import java.io.BufferedReader;
import java.io.InputStreamReader;
public class D {
static long M = 1000L*1000*1000+7;
static long A(long x, long y) { return (x+y)%M; }
static long M(long x, long y) { return (x*y)%M; }
static long fac(long n) {
long ans = 1;
for(int i=2; i<=n; i++)
ans = M(ans, i);
return ans;
}
static Long[][] DP_C;
static long C(long n, long k) {
if(DP_C[(int)n][(int)k]!=null) return DP_C[(int)n][(int)k];
long ans = 1;
for(long i=n-k+1; i<=n; i++)
ans = M(ans, i);
return DP_C[(int)n][(int)k]=ans;
}
static Long[][] DP;
public static long f(int a, int b) {
if(a+b <= 1) return 1;
if(DP[a][b]!=null) return DP[a][b];
if(a==0) {
return DP[a][b]=fac(b);
} else {
long ans = f(a-1, b);
if(a>=2) {
for(int k=0; k<=b; k++)
ans = A(ans, M(a-1, M(C(b,k), f(a-2, b-k))));
}
if(b>=1) ans = A(ans, M(b, f(a,b-1)));
return DP[a][b]=ans;
}
}
static int i(String s) { return Integer.parseInt(s); }
public static void main(String[] args) throws Exception {
/*int L = 5;
for(int n=0; n<=L; n++)
for(int a=0; a<=n; a++)
System.out.printf("f(%d,%d) = %d\n", a, n-a, f(a,n-a));*/
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int n = i(in.readLine());
int C1 = 0;
int C2 = 0;
String[] arr = in.readLine().split(" ");
for(int i=0; i<n; i++) {
if(i(arr[i])==1) C1++;
else C2++;
}
DP_C = new Long[n+1][n+1];
DP = new Long[n+1][n+1];
System.out.println(f(C1,C2));
}
}
| Java | ["5\n1 2 2 1 2", "8\n1 2 2 1 2 1 1 2"] | 3 seconds | ["120", "16800"] | null | Java 7 | standard input | [
"dp"
] | 91e8dbe94273e255182aca0f94117bb9 | The first line contains a single number n β the number of students in the line and the number of balls. The next line contains exactly n space-separated integers. Each number corresponds to a student in the line (the i-th number corresponds to the i-th from the left student in the line) and shows the number of throws he can participate in. The input limits for scoring 30 points are (subproblem D1): 1ββ€βnββ€β10. The input limits for scoring 70 points are (subproblems D1+D2): 1ββ€βnββ€β500. The input limits for scoring 100 points are (subproblems D1+D2+D3): 1ββ€βnββ€β1000000. | 2,300 | The output should contain a single integer β the number of variants of ball orders after the warm up exercise is complete. As the number can be rather large, print it modulo 1000000007 (109β+β7). | standard output | |
PASSED | d794599b62b9d2bff3d956f72e50d264 | train_001.jsonl | 1371042000 | Smart Beaver decided to be not only smart, but also a healthy beaver! And so he began to attend physical education classes at school X. In this school, physical education has a very creative teacher. One of his favorite warm-up exercises is throwing balls. Students line up. Each one gets a single ball in the beginning. The balls are numbered from 1 to n (by the demand of the inventory commission). Figure 1. The initial position for nβ=β5. After receiving the balls the students perform the warm-up exercise. The exercise takes place in a few throws. For each throw the teacher chooses any two arbitrary different students who will participate in it. The selected students throw their balls to each other. Thus, after each throw the students remain in their positions, and the two balls are swapped. Figure 2. The example of a throw. In this case there was a throw between the students, who were holding the 2-nd and the 4-th balls. Since the warm-up has many exercises, each of them can only continue for little time. Therefore, for each student we know the maximum number of throws he can participate in. For this lessons maximum number of throws will be 1 or 2.Note that after all phases of the considered exercise any ball can end up with any student. Smart Beaver decided to formalize it and introduced the concept of the "ball order". The ball order is a sequence of n numbers that correspond to the order of balls in the line. The first number will match the number of the ball of the first from the left student in the line, the second number will match the ball of the second student, and so on. For example, in figure 2 the order of the balls was (1, 2, 3, 4, 5), and after the throw it was (1, 4, 3, 2, 5). Smart beaver knows the number of students and for each student he knows the maximum number of throws in which he can participate. And now he is wondering: what is the number of distinct ways of ball orders by the end of the exercise. | 256 megabytes |
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;
public class Solution {
BufferedReader in;
PrintWriter out;
StringTokenizer st;
String nextToken() throws Exception {
if (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(in.readLine());
}
return st.nextToken();
}
int o = 1000000007;
long[][] b = new long[1000][1000];
long[] fak = new long[1000];
long[][] c = new long[1000][1000];
void solve() throws IOException, Exception {
c[0][0] = 1;
c[1][0] = 1;
c[1][1] = 1;
for (int i = 2; i <= 500; i++){
c[i][0] = 1;
for (int j = 1; j <= i; j++){
c[i][j] = (c[i - 1][j] + c[i - 1][j - 1]) % o;
}
}
fak[0] = 1;
for (int i = 1; i <= 500; i++){
fak[i] = (fak[i-1]*i) % o;
}
int d = 0;
for (long[] q : b) Arrays.fill(q, -1);
int n = Integer.parseInt(nextToken());
for (int i = 0; i < n; i++){
int a = Integer.parseInt(nextToken());
if (a == 2) {
d++;
}
}
out.println(rec(n, d));
out.flush();
}
void run() {
try {
//in = new BufferedReader(new FileReader("garland.in"));
//out = new PrintWriter("garland.out");
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(new OutputStreamWriter(System.out));
solve();
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
public static void main(String[] args) {
new Solution().run();
}
private long rec(int n, int d) {
long ans = 0;
if (b[n][d] != -1) {
return b[n][d];
}
if (n <= d + 2){
ans = fak[n];
} else {
for (int i = 0; i <= d; i++){
long w = c[d][i];
long q1 = (w * fak[i]) % o;
ans = (ans + q1 * rec(n - i - 1, d - i)) % o;
if (n > d + 1){
q1 = (w * fak[i+1]) % o;
long q2 = rec(n - i - 2, d - i) * (n - d - 1) % o;
ans = (ans + q1 * q2) % o;
}
}
}
return b[n][d] = ans;
}
} | Java | ["5\n1 2 2 1 2", "8\n1 2 2 1 2 1 1 2"] | 3 seconds | ["120", "16800"] | null | Java 7 | standard input | [
"dp"
] | 91e8dbe94273e255182aca0f94117bb9 | The first line contains a single number n β the number of students in the line and the number of balls. The next line contains exactly n space-separated integers. Each number corresponds to a student in the line (the i-th number corresponds to the i-th from the left student in the line) and shows the number of throws he can participate in. The input limits for scoring 30 points are (subproblem D1): 1ββ€βnββ€β10. The input limits for scoring 70 points are (subproblems D1+D2): 1ββ€βnββ€β500. The input limits for scoring 100 points are (subproblems D1+D2+D3): 1ββ€βnββ€β1000000. | 2,300 | The output should contain a single integer β the number of variants of ball orders after the warm up exercise is complete. As the number can be rather large, print it modulo 1000000007 (109β+β7). | standard output | |
PASSED | 1762219e1a99b17fd291aa81ebcb794c | train_001.jsonl | 1371042000 | Smart Beaver decided to be not only smart, but also a healthy beaver! And so he began to attend physical education classes at school X. In this school, physical education has a very creative teacher. One of his favorite warm-up exercises is throwing balls. Students line up. Each one gets a single ball in the beginning. The balls are numbered from 1 to n (by the demand of the inventory commission). Figure 1. The initial position for nβ=β5. After receiving the balls the students perform the warm-up exercise. The exercise takes place in a few throws. For each throw the teacher chooses any two arbitrary different students who will participate in it. The selected students throw their balls to each other. Thus, after each throw the students remain in their positions, and the two balls are swapped. Figure 2. The example of a throw. In this case there was a throw between the students, who were holding the 2-nd and the 4-th balls. Since the warm-up has many exercises, each of them can only continue for little time. Therefore, for each student we know the maximum number of throws he can participate in. For this lessons maximum number of throws will be 1 or 2.Note that after all phases of the considered exercise any ball can end up with any student. Smart Beaver decided to formalize it and introduced the concept of the "ball order". The ball order is a sequence of n numbers that correspond to the order of balls in the line. The first number will match the number of the ball of the first from the left student in the line, the second number will match the ball of the second student, and so on. For example, in figure 2 the order of the balls was (1, 2, 3, 4, 5), and after the throw it was (1, 4, 3, 2, 5). Smart beaver knows the number of students and for each student he knows the maximum number of throws in which he can participate. And now he is wondering: what is the number of distinct ways of ball orders by the end of the exercise. | 256 megabytes | import java.io.*;
import java.util.*;
import java.math.*;
public class Main {
static final String input = "stdin";
static final String ouput = "stdout";
static final int MAXN = 1000010;
static final int MOD = 1000000007;
long[] F = new long[MAXN];
long[] I = new long[MAXN];
long pow2(long a, long n) {
long res = 1;
while (n > 0) {
if (n % 2 == 1) res = res * a % MOD;
a = a * a % MOD;
n >>= 1;
}
return res;
}
void solved(int nT) throws IOException {
int n = cin.nextInt();
int a = 0, b = 0;
for (int i = 0; i < n; ++i) {
int c = cin.nextInt();
if (c == 1) ++a;
else ++b;
}
long result = F[n] * I[a] % MOD;
result = result * pow2(F[a], MOD - 2) % MOD;
out.println(result);
}
void init() {
F[0] = F[1] = 1;
I[0] = 1; I[1] = 1;
for (int i = 2; i < MAXN; ++i) {
F[i] = F[i - 1] * i % MOD;
I[i] = (I[i - 1] + I[i - 2] * (i - 1)) % MOD;
}
}
public static void main(String[] args) throws IOException {
Main solved = new Main();
solved.init();
int T = 1;
//T = cin.nextInt();
for (int nT = 1; nT <= T; ++nT) {
solved.solved(nT);
}
out.close();
}
static {
try {
File file = new File(input);
if (file.exists() && file.canRead()) {
cin = new InputReader();
out = new PrintWriter(new PrintWriter(ouput));
} else {
cin = new InputReader();
out = new PrintWriter(System.out);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
static InputReader cin;
static PrintWriter out;
}
class InputReader {
BufferedReader reader;
StringTokenizer tokenizer;
InputReader() {
reader = new BufferedReader(new InputStreamReader(System.in));
tokenizer = new StringTokenizer("");
}
String next() throws IOException {
while (!tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
return tokenizer.nextToken();
}
Integer nextInt() throws IOException {
return Integer.parseInt(next());
}
Long nextLong() throws IOException {
return Long.parseLong(next());
}
} | Java | ["5\n1 2 2 1 2", "8\n1 2 2 1 2 1 1 2"] | 3 seconds | ["120", "16800"] | null | Java 7 | standard input | [
"dp"
] | 91e8dbe94273e255182aca0f94117bb9 | The first line contains a single number n β the number of students in the line and the number of balls. The next line contains exactly n space-separated integers. Each number corresponds to a student in the line (the i-th number corresponds to the i-th from the left student in the line) and shows the number of throws he can participate in. The input limits for scoring 30 points are (subproblem D1): 1ββ€βnββ€β10. The input limits for scoring 70 points are (subproblems D1+D2): 1ββ€βnββ€β500. The input limits for scoring 100 points are (subproblems D1+D2+D3): 1ββ€βnββ€β1000000. | 2,300 | The output should contain a single integer β the number of variants of ball orders after the warm up exercise is complete. As the number can be rather large, print it modulo 1000000007 (109β+β7). | standard output | |
PASSED | 57618af45a7b0c8d78cdaff365941090 | train_001.jsonl | 1371042000 | Smart Beaver decided to be not only smart, but also a healthy beaver! And so he began to attend physical education classes at school X. In this school, physical education has a very creative teacher. One of his favorite warm-up exercises is throwing balls. Students line up. Each one gets a single ball in the beginning. The balls are numbered from 1 to n (by the demand of the inventory commission). Figure 1. The initial position for nβ=β5. After receiving the balls the students perform the warm-up exercise. The exercise takes place in a few throws. For each throw the teacher chooses any two arbitrary different students who will participate in it. The selected students throw their balls to each other. Thus, after each throw the students remain in their positions, and the two balls are swapped. Figure 2. The example of a throw. In this case there was a throw between the students, who were holding the 2-nd and the 4-th balls. Since the warm-up has many exercises, each of them can only continue for little time. Therefore, for each student we know the maximum number of throws he can participate in. For this lessons maximum number of throws will be 1 or 2.Note that after all phases of the considered exercise any ball can end up with any student. Smart Beaver decided to formalize it and introduced the concept of the "ball order". The ball order is a sequence of n numbers that correspond to the order of balls in the line. The first number will match the number of the ball of the first from the left student in the line, the second number will match the ball of the second student, and so on. For example, in figure 2 the order of the balls was (1, 2, 3, 4, 5), and after the throw it was (1, 4, 3, 2, 5). Smart beaver knows the number of students and for each student he knows the maximum number of throws in which he can participate. And now he is wondering: what is the number of distinct ways of ball orders by the end of the exercise. | 256 megabytes | import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Set;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.util.HashSet;
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);
TaskD1 solver = new TaskD1();
solver.solve(1, in, out);
out.close();
}
}
class TaskD1 {
static final int MODULO = (int) (1e9 + 7);
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
int n1 = 0;
int n2 = 0;
for (int i = 0; i < n; ++i) {
int a = in.nextInt();
if (a == 1) ++n1; else if (a == 2) ++n2; else throw new RuntimeException();
}
int[] a = new int[Math.max(2, n1 + 1)];
a[0] = 1;
a[1] = 1;
for (int i = 2; i <= n1; ++i) {
a[i] = (int) ((a[i - 1] + (i - 1) * (long) a[i - 2]) % MODULO);
}
int res = a[n1];
for (int i = 0; i < n2; ++i) {
res = (int) (res * (long) (n1 + n2 - i) % MODULO);
}
out.println(res);
}
}
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 | ["5\n1 2 2 1 2", "8\n1 2 2 1 2 1 1 2"] | 3 seconds | ["120", "16800"] | null | Java 7 | standard input | [
"dp"
] | 91e8dbe94273e255182aca0f94117bb9 | The first line contains a single number n β the number of students in the line and the number of balls. The next line contains exactly n space-separated integers. Each number corresponds to a student in the line (the i-th number corresponds to the i-th from the left student in the line) and shows the number of throws he can participate in. The input limits for scoring 30 points are (subproblem D1): 1ββ€βnββ€β10. The input limits for scoring 70 points are (subproblems D1+D2): 1ββ€βnββ€β500. The input limits for scoring 100 points are (subproblems D1+D2+D3): 1ββ€βnββ€β1000000. | 2,300 | The output should contain a single integer β the number of variants of ball orders after the warm up exercise is complete. As the number can be rather large, print it modulo 1000000007 (109β+β7). | standard output | |
PASSED | bfda8944c919acd5aac78849f1ead897 | train_001.jsonl | 1361374200 | Consider an nβΓβm grid. Initially all the cells of the grid are colored white. Lenny has painted some of the cells (at least one) black. We call a painted grid convex if one can walk from any black cell to any another black cell using a path of side-adjacent black cells changing his direction at most once during the path. In the figure below, the left grid is convex while the right one is not convex, because there exist two cells which need more than one time to change direction in their path. You're given a painted grid in the input. Tell Lenny if the grid is convex or not. | 256 megabytes | import java.util.ArrayList;
import java.util.Scanner;
public class B {
public static void main(String[] args) {
Scanner theIn=new Scanner(System.in);
int n=theIn.nextInt();
int m=theIn.nextInt();
boolean t[][]=new boolean[n+1][m+1];
ArrayList<Integer> x=new ArrayList<Integer>();
ArrayList<Integer> y=new ArrayList<Integer>();
for (int i=1; i<=n; i++) {
String str=theIn.next();
for (int j=1; j<=m; j++) {
if (str.charAt(j-1)=='B') {
t[i][j]=true;
x.add(i);
y.add(j);
} else t[i][j]=false;
}
}
boolean result=true;
for (int i=1; i<=n; i++) {
int p=0;
for (int j=1; j<=m; j++) {
if (t[i][j]==true && p==0) { p=1; continue;}
if (t[i][j]==true && p==1) {p=1; continue;}
if (t[i][j]==false && p==0) {p=0; continue;}
if (t[i][j]==false && p==1) {p=2; continue;}
if (t[i][j]==true && p==2) result=false;
}
}
if (!result) {
System.out.println("NO");
return;
}
for (int j=1; j<=m; j++) {
int p=0;
for (int i=1; i<=n; i++) {
if (t[i][j]==true && p==0) p=1;
if (t[i][j]==true && p==1) p=1;
if (t[i][j]==false && p==0) p=0;
if (t[i][j]==false && p==1) p=2;
if (t[i][j]==true && p==2) result=false;
}
}
if (!result) {
System.out.println("NO");
return;
}
for (int i=0; i<x.size(); i++) {
for (int j=i+1; j<x.size(); j++) {
int x_1=x.get(i);
int y_1=y.get(i);
int x_2=x.get(j);
int y_2=y.get(j);
if (t[x_1][y_2]==false && t[x_2][y_1]==false) result=false;
}
}
if (!result) {
System.out.println("NO");
} else System.out.println("YES");
}
} | Java | ["3 4\nWWBW\nBWWW\nWWWB", "3 1\nB\nB\nW"] | 2 seconds | ["NO", "YES"] | null | Java 6 | standard input | [
"constructive algorithms",
"implementation"
] | 3631eba1b28fae473cf438bc2f0552b7 | The first line of the input contains two integers n and m (1ββ€βn,βmββ€β50) β the size of the grid. Each of the next n lines contains m characters "B" or "W". Character "B" denotes a black cell of the grid and "W" denotes a white cell of the grid. It's guaranteed that the grid has at least one black cell. | 1,700 | On the only line of the output print "YES" if the grid is convex, otherwise print "NO". Do not print quotes. | standard output | |
PASSED | 2d62c25e351efa7767372fa1ccf2a8e4 | train_001.jsonl | 1361374200 | Consider an nβΓβm grid. Initially all the cells of the grid are colored white. Lenny has painted some of the cells (at least one) black. We call a painted grid convex if one can walk from any black cell to any another black cell using a path of side-adjacent black cells changing his direction at most once during the path. In the figure below, the left grid is convex while the right one is not convex, because there exist two cells which need more than one time to change direction in their path. You're given a painted grid in the input. Tell Lenny if the grid is convex or not. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
public class B168 {
BufferedReader reader;
StringTokenizer tokenizer;
PrintWriter out;
class Point{
int x;
int y;
public Point(int x, int y){
this.x = x;
this.y = y;
}
}
public void solve() throws IOException {
int N = nextInt();
int M = nextInt();
char[][] map = new char[N][M];
for(int i = 0; i < N; i++){
map[i] = reader.readLine().toCharArray();
}
for(int i = 0; i < N; i++){
for(int j = 0; j < M; j++){
if( map[i][j] == 'B'){
for(int i2 = 0; i2 < N; i2++){
for(int j2 = 0; j2 < M; j2++){
if( map[i2][j2] == 'B' && (i != i2 || j != j2)){
int dirV = i <= i2? 1: -1;
int dirH = j <= j2? 1: -1;
boolean OK = false;
int c = i;
int r = j;
while( c != i2 && map[c+dirV][r] == 'B') c+=dirV;
while( r != j2 && map[c][r+dirH] == 'B') r+=dirH;
if( c == i2 && r == j2 ) OK = true;
if(!OK){
c = i;
r = j;
while( r != j2 && map[c][r+dirH] == 'B') r+=dirH;
while( c != i2 && map[c+dirV][r] == 'B') c+=dirV;
if( c == i2 && r == j2 ) OK = true;
}
if(!OK){
out.println("NO");
// out.println(i + ", " + j + ", " + i2 + ", " + j2);
return;
}
}
}
}
}
}
}
out.println("YES");
}
/**
* @param args
*/
public static void main(String[] args) {
new B168().run();
}
public void run() {
try {
reader = new BufferedReader(new InputStreamReader(System.in));
tokenizer = null;
out = new PrintWriter(System.out);
solve();
reader.close();
out.close();
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
String nextToken() throws IOException {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
return tokenizer.nextToken();
}
}
| Java | ["3 4\nWWBW\nBWWW\nWWWB", "3 1\nB\nB\nW"] | 2 seconds | ["NO", "YES"] | null | Java 6 | standard input | [
"constructive algorithms",
"implementation"
] | 3631eba1b28fae473cf438bc2f0552b7 | The first line of the input contains two integers n and m (1ββ€βn,βmββ€β50) β the size of the grid. Each of the next n lines contains m characters "B" or "W". Character "B" denotes a black cell of the grid and "W" denotes a white cell of the grid. It's guaranteed that the grid has at least one black cell. | 1,700 | On the only line of the output print "YES" if the grid is convex, otherwise print "NO". Do not print quotes. | standard output | |
PASSED | afdc9b81a6b4b082522d1a9ac6d9744c | train_001.jsonl | 1361374200 | Consider an nβΓβm grid. Initially all the cells of the grid are colored white. Lenny has painted some of the cells (at least one) black. We call a painted grid convex if one can walk from any black cell to any another black cell using a path of side-adjacent black cells changing his direction at most once during the path. In the figure below, the left grid is convex while the right one is not convex, because there exist two cells which need more than one time to change direction in their path. You're given a painted grid in the input. Tell Lenny if the grid is convex or not. | 256 megabytes | import java.io.*;
import java.util.*;
public class pr168B implements Runnable {
BufferedReader in;
PrintWriter out;
StringTokenizer str;
public void solve() throws IOException {
int n = nextInt();
int m = nextInt();
int[][] a = new int[n][m];
for (int i = 0; i < n; i++) {
String s = nextToken();
for (int j = 0; j < m; j++)
a[i][j] = s.charAt(j) == 'W' ? 0 : 1;
}
boolean f = true;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
for (int x = 0; x < n; x++) {
for (int y = 0; y < m; y++) {
if (a[i][j] == 1 && a[x][y] == 1) {
boolean f1 = true;
boolean f2 = true;
for (int k = j < y ? j : y; k <= (y > j ? y : j); k++) {
if (a[x][k] == 0)
f1 = false;
if (a[i][k] == 0)
f2 = false;
}
for (int k = x < i ? x : i; k <= (x > i ? x : i); k++) {
if (a[k][j] == 0)
f1 = false;
if (a[k][y] == 0)
f2 = false;
}
f = f && (f1 || f2);
}
}
}
}
}
if (f)
out.println("YES");
else
out.println("NO");
}
public String nextToken() throws IOException {
while (str == null || !str.hasMoreTokens()) {
str = new StringTokenizer(in.readLine());
}
return str.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
public double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
public long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
public void run() {
try {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
solve();
in.close();
out.close();
} catch (IOException e) {
}
}
public static void main(String[] args) {
new Thread(new pr168B()).start();
}
}
| Java | ["3 4\nWWBW\nBWWW\nWWWB", "3 1\nB\nB\nW"] | 2 seconds | ["NO", "YES"] | null | Java 6 | standard input | [
"constructive algorithms",
"implementation"
] | 3631eba1b28fae473cf438bc2f0552b7 | The first line of the input contains two integers n and m (1ββ€βn,βmββ€β50) β the size of the grid. Each of the next n lines contains m characters "B" or "W". Character "B" denotes a black cell of the grid and "W" denotes a white cell of the grid. It's guaranteed that the grid has at least one black cell. | 1,700 | On the only line of the output print "YES" if the grid is convex, otherwise print "NO". Do not print quotes. | standard output | |
PASSED | 94226350ea14310c35a176a86c86d25f | train_001.jsonl | 1361374200 | Consider an nβΓβm grid. Initially all the cells of the grid are colored white. Lenny has painted some of the cells (at least one) black. We call a painted grid convex if one can walk from any black cell to any another black cell using a path of side-adjacent black cells changing his direction at most once during the path. In the figure below, the left grid is convex while the right one is not convex, because there exist two cells which need more than one time to change direction in their path. You're given a painted grid in the input. Tell Lenny if the grid is convex or not. | 256 megabytes | import java.util.*;
import java.io.*;
public class B {
private static boolean[][][] d_x;
private static boolean[][][] d_y;
public static void main(String[] args) throws IOException
{
Scanner ins = new Scanner(System.in);//new FileInputStream(new File("./input.txt")));
PrintStream outs = System.out;
int n=ins.nextInt();
int m=ins.nextInt();
ins.nextLine();
String[] ss = new String[n];
for (int i=0; i<n; i++) ss[i] = ins.nextLine();
boolean s[][] = new boolean[n][m];
boolean mark[][] = new boolean[n][m];
for (int i=0; i<n; i++) {
for (int j=0; j<m; j++) {
mark[i][j] = false;
if (ss[i].charAt(j) == 'B') s[i][j] = true;
else s[i][j] = false;
}
}
d_x = new boolean[m][n][n];
d_y = new boolean[n][m][m];
for (int i=0; i<m; i++)
for (int j=0; j<n; j++)
for (int k=j; k<n; k++) {
boolean tmp=true;
for (int p=j; p<=k; p++) if (s[p][i] == false) {tmp = false; break;}
d_x[i][j][k]=tmp;
}
for (int i=0; i<n; i++)
for (int j=0; j<m; j++)
for (int k=j; k<m; k++) {
boolean tmp=true;
for (int p=j; p<=k; p++) if (s[i][p] == false) {tmp = false; break;}
d_y[i][j][k]=tmp;
}
for (int i=0; i<n; i++) {
for (int j=0; j<m; j++) if (s[i][j]) {
int k,p;
mark[i][j] = true;
for (k=0; k<n; k++)
for (p=0; p<m; p++) if ((k!=i || p!=j) && s[k][p] && (!mark[k][p])) {
if (connect(i, j, k, p) == false) { outs.println("NO"); return;}
}
}
}
outs.println("YES");
}
private static boolean connect(int y1, int x1, int y2, int x2)
{
int a,b,c,d;
a = Math.max(y1, y2);
b = Math.max(x1, x2);
c = Math.min(y1, y2);
d = Math.min(x1, x2);
if ((y1 < y2 && x1 < x2) || (y1 > y2 && x1 > x2))
return (d_x[d][c][a] && d_y[a][d][b]) || (d_x[b][c][a] && d_y[c][d][b]);
if ((y1 > y2 && x1 < x2) || (y1 < y2 && x1 > x2))
return (d_x[b][c][a] && d_y[a][d][b]) || (d_x[d][c][a] && d_y[c][d][b]);
if (y1 == y2) return d_y[y1][d][b];
else return d_x[x1][c][a];
}
}
| Java | ["3 4\nWWBW\nBWWW\nWWWB", "3 1\nB\nB\nW"] | 2 seconds | ["NO", "YES"] | null | Java 6 | standard input | [
"constructive algorithms",
"implementation"
] | 3631eba1b28fae473cf438bc2f0552b7 | The first line of the input contains two integers n and m (1ββ€βn,βmββ€β50) β the size of the grid. Each of the next n lines contains m characters "B" or "W". Character "B" denotes a black cell of the grid and "W" denotes a white cell of the grid. It's guaranteed that the grid has at least one black cell. | 1,700 | On the only line of the output print "YES" if the grid is convex, otherwise print "NO". Do not print quotes. | standard output | |
PASSED | 9f7d8bd3e9d8285453ce0345296370c9 | train_001.jsonl | 1361374200 | Consider an nβΓβm grid. Initially all the cells of the grid are colored white. Lenny has painted some of the cells (at least one) black. We call a painted grid convex if one can walk from any black cell to any another black cell using a path of side-adjacent black cells changing his direction at most once during the path. In the figure below, the left grid is convex while the right one is not convex, because there exist two cells which need more than one time to change direction in their path. You're given a painted grid in the input. Tell Lenny if the grid is convex or not. | 256 megabytes | import java.util.Scanner;
import java.io.OutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
Scanner in = new Scanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskB solver = new TaskB();
solver.solve(1, in, out);
out.close();
}
}
class TaskB {
public void solve(int testNumber, Scanner in, PrintWriter out) {
int n = in.nextInt();
int m = in.nextInt();
char[][] g = IOUtils.readTable(in, n, m);
boolean ok = true;
loop:
for (int i = 0; i < n; ++i)
for (int j = 0; j < m; ++j)
if (g[i][j] == 'B')
for (int ii = 0; ii < n; ++ii)
for (int jj = 0; jj < m; ++jj) {
if (i == ii && j == jj) continue;
if (g[ii][jj] == 'W') continue;
int minI = Math.min(i, ii);
int maxI = Math.max(i, ii);
int minJ = Math.min(j, jj);
int maxJ = Math.max(j, jj);
boolean okRowColumn = true;
for (int iii = minI; iii <= maxI; iii++)
if (g[iii][j] == 'W') {
okRowColumn = false;
break;
}
for (int jjj = minJ; jjj <= maxJ; jjj++)
if (g[ii][jjj] == 'W') {
okRowColumn = false;
break;
}
boolean okColumnRow = true;
for (int jjj = minJ; jjj <= maxJ; jjj++)
if (g[i][jjj] == 'W') {
okColumnRow = false;
break;
}
for (int iii = minI; iii <= maxI; iii++)
if (g[iii][jj] == 'W') {
okColumnRow = false;
break;
}
if (okColumnRow == false && okRowColumn == false) {
ok = false;
break loop;
}
}
if (ok) out.print("YES");
else out.print("NO");
}
}
class IOUtils {
public static char[] readCharArray(Scanner in, int size) {
char[] array = in.next().toCharArray();
return array;
}
public static char[][] readTable(Scanner in, int r, int c) {
char[][] table = new char[r][];
for (int i = 0; i < r; i++)
table[i] = readCharArray(in, c);
return table;
}
}
| Java | ["3 4\nWWBW\nBWWW\nWWWB", "3 1\nB\nB\nW"] | 2 seconds | ["NO", "YES"] | null | Java 6 | standard input | [
"constructive algorithms",
"implementation"
] | 3631eba1b28fae473cf438bc2f0552b7 | The first line of the input contains two integers n and m (1ββ€βn,βmββ€β50) β the size of the grid. Each of the next n lines contains m characters "B" or "W". Character "B" denotes a black cell of the grid and "W" denotes a white cell of the grid. It's guaranteed that the grid has at least one black cell. | 1,700 | On the only line of the output print "YES" if the grid is convex, otherwise print "NO". Do not print quotes. | standard output | |
PASSED | 70bc3558301a2234dbd0ed31a0bec0ca | train_001.jsonl | 1361374200 | Consider an nβΓβm grid. Initially all the cells of the grid are colored white. Lenny has painted some of the cells (at least one) black. We call a painted grid convex if one can walk from any black cell to any another black cell using a path of side-adjacent black cells changing his direction at most once during the path. In the figure below, the left grid is convex while the right one is not convex, because there exist two cells which need more than one time to change direction in their path. You're given a painted grid in the input. Tell Lenny if the grid is convex or not. | 256 megabytes | import java.io.PrintStream;
import java.util.*;
public class Main {
public static void main(String arg[])throws Exception{
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int m=sc.nextInt();
sc.nextLine();
boolean grid[][]=new boolean[n][m];
for (int i=0;i<n;i++){
String str=sc.nextLine();
for (int j=0;j<m;j++){
grid[i][j]=str.charAt(j)=='B';
}
}
for (int i=0;i<n*m;i++){
for (int j=i+1;j<n*m;j++){
int y1=i/m;
int x1=i%m;
int x2=j%m;
int y2=j/m;
if(!grid[y1][x1]||!grid[y2][x2]) continue;
boolean f1=false,f2=false,f3=false,f4=false;
for (int p=Math.min(x1,x2);p<=Math.max(x1,x2);p++){
if (!grid[Math.min(y1,y2)][p]){
f1=true;
break;
}
}
for (int p=Math.min(y1,y2);p<=Math.max(y1,y2);p++){
if (!grid[p][Math.max(x1,x2)]){
f2=true;
break;
}
}
for (int p=Math.min(x1,x2);p<=Math.max(x1,x2);p++){
if (!grid[Math.max(y1,y2)][p]){
f3=true;
break;
}
}
for (int p=Math.min(y1,y2);p<=Math.max(y1,y2);p++){
if (!grid[p][Math.min(x1,x2)]){
f4=true;
break;
}
}
if((x1<x2&&y1<y2)||(x2<x1&&y2<y1)){
if((f1||f2)&&(f3||f4)){
System.out.println("NO");
return;
}
}
else
if((f1||f4)&&(f3||f2)){
System.out.println("NO");
return;
}
}
}
System.out.println("YES");
}
} | Java | ["3 4\nWWBW\nBWWW\nWWWB", "3 1\nB\nB\nW"] | 2 seconds | ["NO", "YES"] | null | Java 6 | standard input | [
"constructive algorithms",
"implementation"
] | 3631eba1b28fae473cf438bc2f0552b7 | The first line of the input contains two integers n and m (1ββ€βn,βmββ€β50) β the size of the grid. Each of the next n lines contains m characters "B" or "W". Character "B" denotes a black cell of the grid and "W" denotes a white cell of the grid. It's guaranteed that the grid has at least one black cell. | 1,700 | On the only line of the output print "YES" if the grid is convex, otherwise print "NO". Do not print quotes. | standard output | |
PASSED | 8c1790c22c599eed343f80f1a5b13352 | train_001.jsonl | 1361374200 | Consider an nβΓβm grid. Initially all the cells of the grid are colored white. Lenny has painted some of the cells (at least one) black. We call a painted grid convex if one can walk from any black cell to any another black cell using a path of side-adjacent black cells changing his direction at most once during the path. In the figure below, the left grid is convex while the right one is not convex, because there exist two cells which need more than one time to change direction in their path. You're given a painted grid in the input. Tell Lenny if the grid is convex or not. | 256 megabytes | import java.util.*;
public class Main {
int [] vx = {0,1,0,-1};
int [] vy = {1,0,-1,0};
char [][] data;
class C{
int x, y, dir, count;
public C(int x, int y, int dir, int count) {
this.x = x;
this.y = y;
this.dir = dir;
this.count = count;
}
}
private void doit(){
Scanner sc = new Scanner(System.in);
while(sc.hasNext()){
int h = sc.nextInt();
int w = sc.nextInt();
data = new char[h][w];
for(int i = 0; i < h; i++){
data[i] = sc.next().toCharArray();
}
boolean flg = true;
for(int i = 0; i < h; i++){
for(int j = 0; j < w; j++){
if(data[i][j] == 'B'){
boolean [][][] close = new boolean[4][h][w];
for(int k = 0; k < 4; k++){
LinkedList<C> open = new LinkedList<Main.C>();
open.add(new C(j, i, k, 0));
close[k][i][j] = true;
while(! open.isEmpty()){
C now = open.poll();
int xx = now.x + vx[now.dir];
int yy = now.y + vy[now.dir];
if(isOK(xx, yy, w, h)){
if(data[yy][xx] == 'B'){
if(close[k][yy][xx] == false){
open.add(new C(xx, yy, now.dir, now.count));
close[k][yy][xx] = true;
}
}
}
for(int ii = 0; ii < vx.length; ii++){
xx = now.x + vx[ii];
yy = now.y + vy[ii];
if(! isOK(xx,yy, w,h)) continue;
if(data[yy][xx] == 'W') continue;
if(close[k][yy][xx]) continue;
if(now.count == 1) continue;
if(now.dir == ii) continue;
open.add(new C(xx, yy, ii, now.count + 1));
close[k][yy][xx] = true;
}
}
}
boolean res = check(close);
if(! res){
flg = false;
break;
}
}
}
if(! flg){
break;
}
}
if(flg){
System.out.println("YES");
}
else{
System.out.println("NO");
}
}
}
private boolean check(boolean[][][] close) {
for(int i = 0; i < close[0].length; i++){
for(int j = 0; j < close[0][i].length; j++){
if(data[i][j] == 'W') continue;
boolean flg = false;
for(int k = 0; k < 4; k++){
if(close[k][i][j] == true){
flg = true;
break;
}
}
if(! flg){
return false;
}
}
}
return true;
}
private boolean isOK(int xx, int yy, int w, int h) {
if(0 <= xx && xx < w && 0<= yy && yy < h) return true;
return false;
}
private void debug(Object... o) {
System.out.println("debug = " + Arrays.deepToString(o));
}
public static void main(String[] args) {
new Main().doit();
}
} | Java | ["3 4\nWWBW\nBWWW\nWWWB", "3 1\nB\nB\nW"] | 2 seconds | ["NO", "YES"] | null | Java 6 | standard input | [
"constructive algorithms",
"implementation"
] | 3631eba1b28fae473cf438bc2f0552b7 | The first line of the input contains two integers n and m (1ββ€βn,βmββ€β50) β the size of the grid. Each of the next n lines contains m characters "B" or "W". Character "B" denotes a black cell of the grid and "W" denotes a white cell of the grid. It's guaranteed that the grid has at least one black cell. | 1,700 | On the only line of the output print "YES" if the grid is convex, otherwise print "NO". Do not print quotes. | standard output | |
PASSED | 73b98c65dddad0f6f7dd11b1d11c1664 | train_001.jsonl | 1361374200 | Consider an nβΓβm grid. Initially all the cells of the grid are colored white. Lenny has painted some of the cells (at least one) black. We call a painted grid convex if one can walk from any black cell to any another black cell using a path of side-adjacent black cells changing his direction at most once during the path. In the figure below, the left grid is convex while the right one is not convex, because there exist two cells which need more than one time to change direction in their path. You're given a painted grid in the input. Tell Lenny if the grid is convex or not. | 256 megabytes |
import static java.lang.Math.min;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StreamTokenizer;
import java.util.Arrays;
import java.util.PriorityQueue;
import java.util.Scanner;
public class Solution {
public static void main(String[] argv) throws IOException {
in = new Scanner(System.in);
out = new PrintWriter(System.out);
n = in.nextInt();
m = in.nextInt();
map = new int[100][100];
String str;
for (int i = 1; i <= n; ++i) {
str = in.next();
for (int j = 1; j <= m; ++j) {
map[i][j] = str.charAt(j - 1) == 'W' ? 0 : 1;
}
}
if (unlink()) {
out.println("NO");
out.close();
return;
}
if (good()) {
out.println("YES");
} else {
out.println("NO");
}
out.close();
}
static boolean unlink() {
buf = new int[100][100];
for (int i = 0; i < 100; ++i)
for (int j = 0; j < 100; ++j)
buf[i][j] = 0;
for (int i = 1; i <= n; ++i)
for (int j = 1; j <= m; ++j)
buf[i][j] = map[i][j];
int amt = 0;
for (int i = 1; i <= n; ++i)
for (int j = 1; j <= m; ++j) {
if (buf[i][j] == 1) {
offer(i, j);
++amt;
}
}
return amt > 1;
}
static int[][] buf;
static void offer(int i, int j) {
buf[i][j] = 0;
for (int t = 0; t < 4; ++t) {
int I, J;
I = i + way[t][0];
J = j + way[t][1];
if (buf[I][J] == 1) {
offer(I, J);
}
}
}
static boolean good() {
boolean[][][] row = new boolean[55][55][55];
boolean[][][] col = new boolean[55][55][55];
for (int i = 1; i <= n; ++i) {
for (int lt = 1; lt <= m; ++lt) {
for (int rt = lt; rt <= m; ++rt) {
row[i][lt][rt] = true;
for (int j = lt; j <= rt; ++j)
if (map[i][j] == 0) {
row[i][lt][rt] = false;
break;
}
}
}
}
for (int j = 1; j <= m; ++j) {
for (int i1 = 1; i1 <= n; ++i1) {
for (int i2 = i1; i2 <= n; ++i2) {
col[j][i1][i2] = true;
for (int i = i1; i <= i2; ++i)
if (map[i][j] == 0) {
col[j][i1][i2] = false;
break;
}
}
}
}
for (int i1 = 1; i1 <= n; ++i1) {
for (int j1 = 1; j1 <= m; ++j1) {
if (map[i1][j1] == 0) continue;
for (int i2 = 1; i2 <= n; ++i2) {
for (int j2 = 1; j2 <= m; ++j2) {
if (i1 == i2 && j1 == j2) continue;
if (map[i2][j2] == 0) continue;
boolean FLAG = false;
if (j1 > j2 || (j1 == j2 && i1 > i2)) {
int tmp = i1;
i1 = i2;
i2 = tmp;
tmp = j1;
j1 = j2;
j2 = tmp;
FLAG = true;
}
if (i1 == i2) {
if (row[i1][j1][j2] == false) return false;
} else
if (j1 == j2) {
if (col[j1][i1][i2] == false) return false;
} else {
if (i1 > i2) {
boolean flag = true;
flag &= (row[i1][j1][j2] && col[j2][i2][i1]) || (row[i2][j1][j2] && col[j1][i2][i1]);
if (!flag) return false;
} else {
boolean flag = true;
flag &= (row[i1][j1][j2] && col[j2][i1][i2]) || (row[i2][j1][j2] && col[j1][i1][i2]);
if (!flag) return false;
}
}
if (FLAG) {
int tmp = i1;
i1 = i2;
i2 = tmp;
tmp = j1;
j1 = j2;
j2 = tmp;
}
}
}
}
}
return true;
}
static int[][] map;
static int n, m;
static int[][] way = {
{0, 1},
{0, -1},
{1, 0},
{-1, 0}
};
static Scanner in;
static PrintWriter out;
}
| Java | ["3 4\nWWBW\nBWWW\nWWWB", "3 1\nB\nB\nW"] | 2 seconds | ["NO", "YES"] | null | Java 6 | standard input | [
"constructive algorithms",
"implementation"
] | 3631eba1b28fae473cf438bc2f0552b7 | The first line of the input contains two integers n and m (1ββ€βn,βmββ€β50) β the size of the grid. Each of the next n lines contains m characters "B" or "W". Character "B" denotes a black cell of the grid and "W" denotes a white cell of the grid. It's guaranteed that the grid has at least one black cell. | 1,700 | On the only line of the output print "YES" if the grid is convex, otherwise print "NO". Do not print quotes. | standard output | |
PASSED | 72e5aa9005d5ea83cd737314f6521c6c | train_001.jsonl | 1361374200 | Consider an nβΓβm grid. Initially all the cells of the grid are colored white. Lenny has painted some of the cells (at least one) black. We call a painted grid convex if one can walk from any black cell to any another black cell using a path of side-adjacent black cells changing his direction at most once during the path. In the figure below, the left grid is convex while the right one is not convex, because there exist two cells which need more than one time to change direction in their path. You're given a painted grid in the input. Tell Lenny if the grid is convex or not. | 256 megabytes | import java.util.*;
import java.io.*;
public class convex {
static int n, m;
static char grid[][];
public static void main(String[] args) throws FileNotFoundException {
Scanner in = new Scanner(System.in);
n = in.nextInt();
m = in.nextInt();
grid = new char[m][n];
for (int i = 0; i < n; i++) {
String s = in.next();
for (int j = 0; j < m; j++) grid[j][i] = s.charAt(j);
}
for (int a = 0; a < m; a++) {
for (int b = 0; b < n; b++) {
for (int c = 0; c < m; c++) {
for (int d = 0; d < n; d++) {
if (grid[a][b] != 'B' || grid[c][d] != 'B') continue;
if (grid[a][d] != 'B' && grid[c][b] != 'B') { System.out.println("NO"); return; }
//boolean left = false; boolean right = false;
boolean x = (grid[a][b] == 'B');
boolean y = (grid[c][d] == 'B');
if (grid[a][d] == 'B') {
for (int i = b+1; i < d; i++) {
if (grid[a][i] != 'B') { x = false; break; }
}
for (int i = a+1; i < c; i++) {
if (grid[i][d] != 'B') { x = false; break; }
}
}
if (grid[c][b] == 'B') {
for (int i = a+1; i < c; i++) {
if (grid[i][b] != 'B') { y = false; break; }
}
for (int i = b+1; i < d; i++) {
if (grid[c][i] != 'B') { y = false; break; }
}
}
if (!x && !y) { System.out.println("NO"); return; }
}
}
}
}
System.out.println("YES"); return;
}
}
| Java | ["3 4\nWWBW\nBWWW\nWWWB", "3 1\nB\nB\nW"] | 2 seconds | ["NO", "YES"] | null | Java 6 | standard input | [
"constructive algorithms",
"implementation"
] | 3631eba1b28fae473cf438bc2f0552b7 | The first line of the input contains two integers n and m (1ββ€βn,βmββ€β50) β the size of the grid. Each of the next n lines contains m characters "B" or "W". Character "B" denotes a black cell of the grid and "W" denotes a white cell of the grid. It's guaranteed that the grid has at least one black cell. | 1,700 | On the only line of the output print "YES" if the grid is convex, otherwise print "NO". Do not print quotes. | standard output | |
PASSED | 4e200060c3c6815e53f4334f9bd02884 | train_001.jsonl | 1361374200 | Consider an nβΓβm grid. Initially all the cells of the grid are colored white. Lenny has painted some of the cells (at least one) black. We call a painted grid convex if one can walk from any black cell to any another black cell using a path of side-adjacent black cells changing his direction at most once during the path. In the figure below, the left grid is convex while the right one is not convex, because there exist two cells which need more than one time to change direction in their path. You're given a painted grid in the input. Tell Lenny if the grid is convex or not. | 256 megabytes | import java.util.*;
import java.io.*;
public class a {
static long mod = 1000000007;
static boolean[][] blacks;
public static void main(String[] args) throws IOException
{
input.init(System.in);
PrintWriter out = new PrintWriter(new PrintStream(System.out));
//Scanner input = new Scanner(new File("input.txt"));
//PrintWriter out = new PrintWriter(new File("output.txt"));
int n = input.nextInt(), m = input.nextInt();
blacks = new boolean[n][m];
int count = 0;
for(int i = 0; i<n; i++)
{
String s = input.next();
for(int j = 0; j<m; j++)
{
blacks[i][j] = s.charAt(j) == 'B';
if(blacks[i][j]) count++;
}
}
boolean good = true;
for(int i = 0; i<n; i++)
for(int j = 0; j<m; j++)
{
int x = 0;
if(!blacks[i][j]) continue;
int[][] grid = new int[n][m];
for(int[] A: grid) Arrays.fill(A, -1);
grid[i][j] = 0;
x++;
int[] dx = new int[]{0, 1, 0, -1}, dy = new int[]{1,0,-1,0};
for(int k = 0; k<4; k++)
{
int nx = j, ny = i;
while(true)
{
nx += dx[k];
ny += dy[k];
if(nx < 0 || ny<0 || nx>=blacks[0].length || ny >= blacks.length) break;
if(grid[ny][nx] == -1 && blacks[ny][nx])
{
//out.println(1+" "+ny+" "+nx);
grid[ny][nx] = 1;
x++;
}
else if(blacks[ny][nx]) continue;
else break;
}
}
for(int ii = 0; ii<n; ii++)
for(int jj = 0; jj<m; jj++)
{
if(grid[ii][jj] != 1) continue;
for(int k = 0; k<4; k++)
{
int nx = jj, ny = ii;
while(true)
{
nx = nx + dx[k];
ny = ny + dy[k];
if(nx < 0 || ny<0 || nx>=blacks[0].length || ny >= blacks.length) break;
if(grid[ny][nx] == -1 && blacks[ny][nx])
{
//out.println(2+" "+ny+" "+nx);
grid[ny][nx] = 2;
x++;
}
else if(blacks[ny][nx]) continue;
else break;
}
}
}
//out.println(i+" "+j+" "+x+" "+count);
good &= x == count;
}
out.println(good?"YES":"NO");
out.close();
}
static long pow(long a, long p)
{
if(p==0) return 1;
if((p&1) == 0)
{
long sqrt = pow(a, p/2);
return (sqrt*sqrt)%mod;
}
else
return (a*pow(a,p-1))%mod;
}
static class input {
static BufferedReader reader;
static StringTokenizer tokenizer;
/** call this method to initialize reader for InputStream */
static void init(InputStream input) {
reader = new BufferedReader(
new InputStreamReader(input) );
tokenizer = new StringTokenizer("");
}
/** get next word */
static String next() throws IOException {
while ( ! tokenizer.hasMoreTokens() ) {
//TODO add check for eof if necessary
tokenizer = new StringTokenizer(
reader.readLine() );
}
return tokenizer.nextToken();
}
static int nextInt() throws IOException {
return Integer.parseInt( next() );
}
static long nextLong() throws IOException {
return Long.parseLong( next() );
}
static double nextDouble() throws IOException {
return Double.parseDouble( next() );
}
static String nextLine() throws IOException {
return reader.readLine();
}
}
} | Java | ["3 4\nWWBW\nBWWW\nWWWB", "3 1\nB\nB\nW"] | 2 seconds | ["NO", "YES"] | null | Java 6 | standard input | [
"constructive algorithms",
"implementation"
] | 3631eba1b28fae473cf438bc2f0552b7 | The first line of the input contains two integers n and m (1ββ€βn,βmββ€β50) β the size of the grid. Each of the next n lines contains m characters "B" or "W". Character "B" denotes a black cell of the grid and "W" denotes a white cell of the grid. It's guaranteed that the grid has at least one black cell. | 1,700 | On the only line of the output print "YES" if the grid is convex, otherwise print "NO". Do not print quotes. | standard output | |
PASSED | 5f644339e0990c8dba8a3974331cd8a1 | train_001.jsonl | 1361374200 | Consider an nβΓβm grid. Initially all the cells of the grid are colored white. Lenny has painted some of the cells (at least one) black. We call a painted grid convex if one can walk from any black cell to any another black cell using a path of side-adjacent black cells changing his direction at most once during the path. In the figure below, the left grid is convex while the right one is not convex, because there exist two cells which need more than one time to change direction in their path. You're given a painted grid in the input. Tell Lenny if the grid is convex or not. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.StringTokenizer;
public class B {
static class Scanner{
BufferedReader br=null;
StringTokenizer tk=null;
public Scanner(){
br=new BufferedReader(new InputStreamReader(System.in));
}
public String next() throws IOException{
while(tk==null || !tk.hasMoreTokens())
tk=new StringTokenizer(br.readLine());
return tk.nextToken();
}
public int nextInt() throws NumberFormatException, IOException{
return Integer.valueOf(next());
}
public double nextDouble() throws NumberFormatException, IOException{
return Double.valueOf(next());
}
}
static boolean[][] m;
static int N,M;
static boolean[][][][] visited;
public static void main(String args[]) throws NumberFormatException, IOException{
Scanner sc=new Scanner();
N=sc.nextInt();
M=sc.nextInt();
m=new boolean[N][M];
visited=new boolean[N][M][4][2];
for(int i=0;i<N;i++){
char[] tmp=sc.next().toCharArray();
for(int j=0;j<M;j++)
m[i][j] = tmp[j]=='B';
}
boolean flag=true;
for(int i=0;i<N && flag;i++){
for(int j=0;j<M && flag;j++){
if (!m[i][j])
continue;
if (!test(i,j))
flag=false;
}
}
if (flag)
System.out.println("YES");
else
System.out.println("NO");
}
static int[] dx={-1,0,1,0};
static int[] dy={0,1,0,-1};
static boolean test(int a, int b) {
for(int i=0;i<N;i++)
for(int j=0;j<M;j++)
for(int k=0;k<4;k++){
visited[i][j][k][0]=false;
visited[i][j][k][1]=false;
}
for(int i=0;i<4;i++)
visited[a][b][i][0] = true;
LinkedList<int[]> q=new LinkedList<int[]>();
for(int i=0;i<4;i++){
int[] current={a,b,i,0};
q.add(current);
}
while(!q.isEmpty()){
int[] current=q.poll();
int x=current[0];int y=current[1];int dir=current[2];int steps=current[3];
if (steps==0){
for(int k=0;k<4;k++){
int nx = x + dx[k];
int ny = y + dy[k];
if (nx>=0 && nx<N && ny>=0 && ny<M && m[nx][ny] && !visited[nx][ny][k][k==dir?0:1]){
visited[nx][ny][k][k==dir?0:1] = true;
int[] t={nx,ny,k,k==dir?0:1};
q.add(t);
}
}
}
else{
int nx = x + dx[dir];
int ny = y + dy[dir];
if (nx>=0 && nx<N && ny>=0 && ny<M && m[nx][ny] && !visited[nx][ny][dir][1]){
visited[nx][ny][dir][1] = true;
int[] t={nx,ny,dir,1};
q.add(t);
}
}
}
for(int i=0;i<N;i++)
for(int j=0;j<M;j++){
if (!m[i][j])
continue;
boolean flag=false;
for(int k=0;k<4;k++){
if (visited[i][j][k][0] || visited[i][j][k][1])
flag=true;
}
if (!flag)
return false;
}
return true;
}
}
| Java | ["3 4\nWWBW\nBWWW\nWWWB", "3 1\nB\nB\nW"] | 2 seconds | ["NO", "YES"] | null | Java 6 | standard input | [
"constructive algorithms",
"implementation"
] | 3631eba1b28fae473cf438bc2f0552b7 | The first line of the input contains two integers n and m (1ββ€βn,βmββ€β50) β the size of the grid. Each of the next n lines contains m characters "B" or "W". Character "B" denotes a black cell of the grid and "W" denotes a white cell of the grid. It's guaranteed that the grid has at least one black cell. | 1,700 | On the only line of the output print "YES" if the grid is convex, otherwise print "NO". Do not print quotes. | standard output | |
PASSED | f82a474a4a43abb45543ce5de55b75a7 | train_001.jsonl | 1361374200 | Consider an nβΓβm grid. Initially all the cells of the grid are colored white. Lenny has painted some of the cells (at least one) black. We call a painted grid convex if one can walk from any black cell to any another black cell using a path of side-adjacent black cells changing his direction at most once during the path. In the figure below, the left grid is convex while the right one is not convex, because there exist two cells which need more than one time to change direction in their path. You're given a painted grid in the input. Tell Lenny if the grid is convex or not. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class CF169B {
private static int contains (int[] a, int[] b){
int result = 1;
int length = a.length;
for (int i=0;i<length;i++){
if (a[i]<b[i]) return 0;
}
return result;
}
private static int isContinue(int[] a){
int length = a.length;
int startPos = length;
int endPos = -1;
for (int i=0;i<length;i++){
if (a[i]==1){
startPos = i;
break;
}
}
for (int i=length-1;i>-1;i--){
if (a[i]==1){
endPos = i;
break;
}
}
for (int i=startPos;i<=endPos;i++){
if (a[i]==0) return 0;
}
return 1;
}
public static void main(String [] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s = br.readLine();
String [] firstLine = s.split(" ");
String res = "YES";
char tempChar = ' ';
int nbLines = Integer.valueOf(firstLine[0]);
int nbColumns = Integer.valueOf(firstLine[1]);
String [] lines = new String[nbLines];
for (int i=0;i<nbLines;i++){
lines[i] = br.readLine();
}
int[][] valueMatrix = new int[nbLines][nbColumns];
for (int i=0;i<nbLines;i++){
for (int j=0;j<nbColumns;j++){
tempChar = lines[i].charAt(j);
if (tempChar=='B'){
valueMatrix[i][j]=1;
}else{
valueMatrix[i][j]=0;
}
}
}
int width[] = new int[nbLines];
int maxWidth = 0;
int longestLine = -1;
for (int i=0;i<nbLines;i++){
for (int j=0;j<nbColumns;j++){
if (valueMatrix[i][j]==1){
width[i]++;
}
}
if (width[i]>maxWidth){
longestLine = i;
maxWidth = width[i];
}
}
for (int i=0;i<nbLines;i++){
if (isContinue(valueMatrix[i])==0){
res = "NO";
break;
}
}
for (int i=longestLine;i<nbLines-1;i++){
if (contains(valueMatrix[i],valueMatrix[i+1])==0){
res = "NO";
break;
}
}
for (int i=longestLine;i>0;i--){
if (contains(valueMatrix[i],valueMatrix[i-1])==0){
res = "NO";
break;
}
}
for (int i=0;i<nbLines;i++){
for (int j=i+1;j<nbLines;j++){
if (contains(valueMatrix[i],valueMatrix[j])==0){
if (contains(valueMatrix[j],valueMatrix[i])==0){
res = "NO";
break;
}
}
}
}
System.out.println(res);
}
}
| Java | ["3 4\nWWBW\nBWWW\nWWWB", "3 1\nB\nB\nW"] | 2 seconds | ["NO", "YES"] | null | Java 6 | standard input | [
"constructive algorithms",
"implementation"
] | 3631eba1b28fae473cf438bc2f0552b7 | The first line of the input contains two integers n and m (1ββ€βn,βmββ€β50) β the size of the grid. Each of the next n lines contains m characters "B" or "W". Character "B" denotes a black cell of the grid and "W" denotes a white cell of the grid. It's guaranteed that the grid has at least one black cell. | 1,700 | On the only line of the output print "YES" if the grid is convex, otherwise print "NO". Do not print quotes. | standard output | |
PASSED | bc830c9ca95e35153d4222d72aa15060 | train_001.jsonl | 1361374200 | Consider an nβΓβm grid. Initially all the cells of the grid are colored white. Lenny has painted some of the cells (at least one) black. We call a painted grid convex if one can walk from any black cell to any another black cell using a path of side-adjacent black cells changing his direction at most once during the path. In the figure below, the left grid is convex while the right one is not convex, because there exist two cells which need more than one time to change direction in their path. You're given a painted grid in the input. Tell Lenny if the grid is convex or not. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class CF169B {
private static int contains (int[] a, int[] b){
int result = 1;
int length = a.length;
for (int i=0;i<length;i++){
if (a[i]<b[i]) return 0;
}
return result;
}
private static int isContinue(int[] a){
int length = a.length;
int startPos = length;
int endPos = -1;
for (int i=0;i<length;i++){
if (a[i]==1){
startPos = i;
break;
}
}
for (int i=length-1;i>-1;i--){
if (a[i]==1){
endPos = i;
break;
}
}
for (int i=startPos;i<=endPos;i++){
if (a[i]==0) return 0;
}
return 1;
}
public static void main(String [] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s = br.readLine();
String [] firstLine = s.split(" ");
String res = "YES";
char tempChar = ' ';
int nbLines = Integer.valueOf(firstLine[0]);
int nbColumns = Integer.valueOf(firstLine[1]);
String [] lines = new String[nbLines];
for (int i=0;i<nbLines;i++){
lines[i] = br.readLine();
}
int[][] valueMatrix = new int[nbLines][nbColumns];
for (int i=0;i<nbLines;i++){
for (int j=0;j<nbColumns;j++){
tempChar = lines[i].charAt(j);
if (tempChar=='B'){
valueMatrix[i][j]=1;
}else{
valueMatrix[i][j]=0;
}
}
}
int width[] = new int[nbLines];
int maxWidth = 0;
int longestLine = -1;
for (int i=0;i<nbLines;i++){
for (int j=0;j<nbColumns;j++){
if (valueMatrix[i][j]==1){
width[i]++;
}
}
if (width[i]>maxWidth){
longestLine = i;
maxWidth = width[i];
}
}
for (int i=0;i<nbLines;i++){
if (isContinue(valueMatrix[i])==0){
res = "NO";
break;
}
}
for (int i=longestLine;i<nbLines-1;i++){
if (contains(valueMatrix[i],valueMatrix[i+1])==0){
res = "NO";
break;
}
}
for (int i=longestLine;i>0;i--){
if (contains(valueMatrix[i],valueMatrix[i-1])==0){
res = "NO";
break;
}
}
for (int i=0;i<nbLines;i++){
for (int j=i+1;j<nbLines;j++){
if (contains(valueMatrix[i],valueMatrix[j])==0){
if (contains(valueMatrix[j],valueMatrix[i])==0){
res = "NO";
break;
}
}
}
}
System.out.println(res);
}
}
| Java | ["3 4\nWWBW\nBWWW\nWWWB", "3 1\nB\nB\nW"] | 2 seconds | ["NO", "YES"] | null | Java 6 | standard input | [
"constructive algorithms",
"implementation"
] | 3631eba1b28fae473cf438bc2f0552b7 | The first line of the input contains two integers n and m (1ββ€βn,βmββ€β50) β the size of the grid. Each of the next n lines contains m characters "B" or "W". Character "B" denotes a black cell of the grid and "W" denotes a white cell of the grid. It's guaranteed that the grid has at least one black cell. | 1,700 | On the only line of the output print "YES" if the grid is convex, otherwise print "NO". Do not print quotes. | standard output | |
PASSED | 8d6fae29e3633e715b821aaa146e0e36 | train_001.jsonl | 1361374200 | Consider an nβΓβm grid. Initially all the cells of the grid are colored white. Lenny has painted some of the cells (at least one) black. We call a painted grid convex if one can walk from any black cell to any another black cell using a path of side-adjacent black cells changing his direction at most once during the path. In the figure below, the left grid is convex while the right one is not convex, because there exist two cells which need more than one time to change direction in their path. You're given a painted grid in the input. Tell Lenny if the grid is convex or not. | 256 megabytes | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.StringTokenizer;
public class CodeD
{
static class Scanner
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer("");
public String nextLine()
{
try
{
return br.readLine();
}
catch(Exception e)
{
throw(new RuntimeException());
}
}
public String next()
{
while(!st.hasMoreTokens())
{
String l = nextLine();
if(l == null)
return null;
st = new StringTokenizer(l);
}
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 int[] nextIntArray(int n)
{
int[] res = new int[n];
for(int i = 0; i < res.length; i++)
res[i] = nextInt();
return res;
}
public long[] nextLongArray(int n)
{
long[] res = new long[n];
for(int i = 0; i < res.length; i++)
res[i] = nextLong();
return res;
}
public double[] nextDoubleArray(int n)
{
double[] res = new double[n];
for(int i = 0; i < res.length; i++)
res[i] = nextLong();
return res;
}
public void sortIntArray(int[] array)
{
Integer[] vals = new Integer[array.length];
for(int i = 0; i < array.length; i++)
vals[i] = array[i];
Arrays.sort(vals);
for(int i = 0; i < array.length; i++)
array[i] = vals[i];
}
public void sortLongArray(long[] array)
{
Long[] vals = new Long[array.length];
for(int i = 0; i < array.length; i++)
vals[i] = array[i];
Arrays.sort(vals);
for(int i = 0; i < array.length; i++)
array[i] = vals[i];
}
public void sortDoubleArray(double[] array)
{
Double[] vals = new Double[array.length];
for(int i = 0; i < array.length; i++)
vals[i] = array[i];
Arrays.sort(vals);
for(int i = 0; i < array.length; i++)
array[i] = vals[i];
}
}
static class Estado
{
int i;
int j;
int direccion;
boolean cambio;
public Estado(int i, int j, int direccion, boolean cambio)
{
this.i = i;
this.j = j;
this.cambio = cambio;
this.direccion = direccion;
}
}
static int[][] direcciones = new int[][]{{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
static int n, m;
static boolean[][] tablero;
static final boolean[][][][] visitados = new boolean[50][50][4][2];
static final boolean[][] visitadosN = new boolean[50][50];
static boolean visitar(int i, int j)
{
for(int k = 0; k < n; k++)
for(int l = 0; l < m; l++)
{
visitadosN[k][l] = false;
for(int m = 0; m < 4; m++)
for(int n = 0; n < 2; n++)
visitados[k][l][m][n] = false;
}
ArrayDeque <Estado> cola = new ArrayDeque <Estado> ();
for(int k = 0; k < direcciones.length; k++)
{
cola.add(new Estado(i, j, k, false));
visitados[i][j][k][0] = true;
}
while(!cola.isEmpty())
{
Estado actual = cola.poll();
visitadosN[actual.i][actual.j] = true;
int iSig = actual.i + direcciones[actual.direccion][0];
int jSig = actual.j + direcciones[actual.direccion][1];
if(valido(iSig, jSig))
{
if(visitados[iSig][jSig][actual.direccion][actual.cambio ? 1 : 0])
continue;
cola.add(new Estado(iSig, jSig, actual.direccion, actual.cambio));
}
if(!actual.cambio)
{
for(int k = 0; k < direcciones.length; k++)
{
if(visitados[actual.i][actual.j][k][1])
continue;
cola.add(new Estado(actual.i, actual.j, k, true));
}
}
}
for(int k = 0; k < n; k++)
for(int l = 0; l < m; l++)
if(tablero[k][l] && !visitadosN[k][l])
return false;
return true;
}
private static boolean valido(int i, int j)
{
return i >= 0 && i < n && j >= 0 && j < m && tablero[i][j];
}
public static void main(String[] args)
{
Scanner sc = new Scanner();
n = sc.nextInt();
m = sc.nextInt();
tablero = new boolean[n][m];
for(int i = 0; i < n; i++)
{
int j = 0;
for(char c : sc.next().toCharArray())
tablero[i][j++] = c == 'B';
}
boolean bien = true;
outer:
for(int i = 0; i < Math.max(n, m); i++)
{
if(i < n)
{
for(int j = i; j < m; j++)
if(tablero[i][j] && !visitar(i, j))
{
bien = false;
break outer;
}
for(int j = 0; j < m; j++)
tablero[i][j] = false;
}
if(i < m)
{
for(int j = i; j < n; j++)
if(tablero[j][i] && !visitar(j, i))
{
bien = false;
break outer;
}
for(int j = 0; j < n; j++)
tablero[j][i] = false;
}
}
System.out.println(bien ? "YES" : "NO");
}
}
| Java | ["3 4\nWWBW\nBWWW\nWWWB", "3 1\nB\nB\nW"] | 2 seconds | ["NO", "YES"] | null | Java 6 | standard input | [
"constructive algorithms",
"implementation"
] | 3631eba1b28fae473cf438bc2f0552b7 | The first line of the input contains two integers n and m (1ββ€βn,βmββ€β50) β the size of the grid. Each of the next n lines contains m characters "B" or "W". Character "B" denotes a black cell of the grid and "W" denotes a white cell of the grid. It's guaranteed that the grid has at least one black cell. | 1,700 | On the only line of the output print "YES" if the grid is convex, otherwise print "NO". Do not print quotes. | standard output | |
PASSED | 4dabb7e9ff521a9ff708197b08589367 | train_001.jsonl | 1361374200 | Consider an nβΓβm grid. Initially all the cells of the grid are colored white. Lenny has painted some of the cells (at least one) black. We call a painted grid convex if one can walk from any black cell to any another black cell using a path of side-adjacent black cells changing his direction at most once during the path. In the figure below, the left grid is convex while the right one is not convex, because there exist two cells which need more than one time to change direction in their path. You're given a painted grid in the input. Tell Lenny if the grid is convex or not. | 256 megabytes | import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Scanner;
public class CodeforcesRound168B {
direction2d[] dir2d = { new direction2d(1, 0), new direction2d(0, 1),
new direction2d(-1, 0), new direction2d(0, -1) };
int n, m;
boolean[][] data;
class direction2d
{
int dx;
int dy;
public direction2d(int i, int j)
{
dx = i;
dy = j;
}
}
class Point
{
int dx;
int dy;
public Point(int i, int j) {
dx = i;
dy = j;
}
}
class Vertex
{
Point point;
int d ;
boolean flag;
public Vertex(Point point, int d, boolean flag) {
this.point = point;
this.d=d;
this.flag=flag;
}
}
public static void main(String[] args)
{
new CodeforcesRound168B().run();
}
public boolean checer(Vertex V)
{
if (
( ((V.point.dx+dir2d[V.d].dx)<m )&& (V.point.dx+dir2d[V.d].dx)>=0)
&&
( ((V.point.dy+dir2d[V.d].dy)<n )&& (V.point.dy+dir2d[V.d].dy)>=0)
&& (data[V.point.dx+dir2d[V.d].dx][V.point.dy+dir2d[V.d].dy])
)
{
return true;
}
else
{
return false;
}
}
public int getLeft(int x)
{
if(x==0)
{
return 3;
}
else
{
return x-1;
}
}
public int getRite(int x)
{
if(x==3)
{
return 0;
}
else
{
return x+1;
}
}
public boolean BFS(Point point)
{
Vertex tempQ;
boolean[][] BFSdata = new boolean[m][n];
LinkedList<Vertex> Q = new LinkedList<Vertex>();
for(int i=0; i<4; i++)
{
Q.add(new Vertex(point, i, false) ) ;
}
BFSdata[point.dx][point.dy]=true;
while(!Q.isEmpty())
{
//ΠΠΎΡΡΠ°Π»ΠΈ Π½ΡΠ»Π΅Π²ΠΎΠΉ ΡΠ»Π΅ΠΌΠ΅Π½Ρ(ΠΏΠ΅ΡΠ²ΡΠΉ Π² ΠΎΡΠ΅ΡΠ΅Π΄ΠΈ)
//Π£Π΄Π°Π»ΠΈΠ» Π½Π°Ρ
Π΅Ρ Π½ΡΠ»Π΅Π²ΠΎΠΉ ΡΠ»Π΅ΠΌΠ΅Π½Ρ
tempQ=Q.poll () ;
if(checer(tempQ))
{
Q.add(new Vertex(new Point( tempQ.point.dx+dir2d[tempQ.d].dx,tempQ.point.dy+dir2d[tempQ.d].dy), tempQ.d, tempQ.flag) ) ;
BFSdata[tempQ.point.dx+dir2d[tempQ.d].dx][tempQ.point.dy+dir2d[tempQ.d].dy]=true;
}
if(tempQ.flag==false)
{
if(checer((new Vertex(new Point(tempQ.point.dx,tempQ.point.dy), getLeft(tempQ.d), false))))
{
Q.add(new Vertex(new Point(tempQ.point.dx+ dir2d[getLeft(tempQ.d)].dx,tempQ.point.dy+ dir2d[getLeft(tempQ.d)].dy), getLeft(tempQ.d), true) ) ;
BFSdata[tempQ.point.dx+ dir2d[getLeft(tempQ.d)].dx][tempQ.point.dy+ dir2d[getLeft(tempQ.d)].dy]=true;
}
if(checer((new Vertex(new Point(tempQ.point.dx,tempQ.point.dy), getRite(tempQ.d), false))))
{
Q.add(new Vertex(new Point(tempQ.point.dx+ dir2d[ getRite(tempQ.d)].dx ,tempQ.point.dy+ dir2d[getRite(tempQ.d)].dy), getRite(tempQ.d), true) ) ;
BFSdata[tempQ.point.dx+ dir2d[getRite(tempQ.d)].dx][tempQ.point.dy+ dir2d[ getRite(tempQ.d)].dy]=true;
}
}
}
for(int i=0; i<n; i++ )
{
for(int j=0; j<m; j++ )
{
if(BFSdata[j][i]!=data[j][i])
{
return false;
}
}
}
return true;
}
public void run()
{
Scanner kde = new Scanner (System.in);
n= kde.nextInt(); //3
m= kde.nextInt(); //4
ArrayList<Point> List = new ArrayList<Point>();
data = new boolean[m][n];
for(int i=0; i<n; i++ )
{
String s = kde.next();
for(int j=0; j<m; j++ )
{
if (s.charAt(j)=='W')
{
data[j][i]=false;
}
else
{
data[j][i]=true;
List.add(new Point(j,i));
}
}
}
for(int i=0; i<List.size(); i++ )
{
if (BFS(List.get(i) )==false)
{
System.out.print("NO");
return;
}
}
//read
System.out.print("YES");
}
}
| Java | ["3 4\nWWBW\nBWWW\nWWWB", "3 1\nB\nB\nW"] | 2 seconds | ["NO", "YES"] | null | Java 6 | standard input | [
"constructive algorithms",
"implementation"
] | 3631eba1b28fae473cf438bc2f0552b7 | The first line of the input contains two integers n and m (1ββ€βn,βmββ€β50) β the size of the grid. Each of the next n lines contains m characters "B" or "W". Character "B" denotes a black cell of the grid and "W" denotes a white cell of the grid. It's guaranteed that the grid has at least one black cell. | 1,700 | On the only line of the output print "YES" if the grid is convex, otherwise print "NO". Do not print quotes. | standard output | |
PASSED | 2adfc09d347d4181321f6a2930c920ce | train_001.jsonl | 1361374200 | Consider an nβΓβm grid. Initially all the cells of the grid are colored white. Lenny has painted some of the cells (at least one) black. We call a painted grid convex if one can walk from any black cell to any another black cell using a path of side-adjacent black cells changing his direction at most once during the path. In the figure below, the left grid is convex while the right one is not convex, because there exist two cells which need more than one time to change direction in their path. You're given a painted grid in the input. Tell Lenny if the grid is convex or not. | 256 megabytes | import java.io.*;
import java.util.*;
public class BR168 {
BufferedReader in;
PrintWriter out;
StringTokenizer st;
private char[][] a;
class Point{
int i, j;
Point(int i, int j){
this.i = i;
this.j = j;
}
}
boolean notHaveWOnLine(int i, int from, int to){
for (int j = from; j <= to; j++)
if (a[i][j] == 'W')
return false;
return true;
}
boolean notHaveWOnCol(int j, int from, int to){
for (int i = from; i <= to; i++)
if (a[i][j] == 'W')
return false;
return true;
}
boolean canGet(Point a, Point b){
if (notHaveWOnCol(a.j, Math.min(a.i, b.i), Math.max(a.i, b.i)) && notHaveWOnLine(b.i, Math.min(a.j, b.j), Math.max(a.j, b.j)))
return true;
if (notHaveWOnCol(b.j, Math.min(a.i, b.i), Math.max(a.i, b.i)) && notHaveWOnLine(a.i, Math.min(a.j, b.j), Math.max(a.j, b.j)))
return true;
return false;
}
void solve() throws IOException {
int n = nextInt();
int m = nextInt();
ArrayList<Point> bl = new ArrayList<Point>();
a = new char[n][m];
for (int i = 0; i < n; i++){
for (int j = 0; j < m; j++){
a[i][j] = (char) in.read();
if (a[i][j] == 'B')
bl.add(new Point(i, j));
}
in.readLine();
}
for (int i = 0; i < bl.size(); i++)
for (int j = 0; j < bl.size(); j++)
if (i != j)
if (!canGet(bl.get(i), bl.get(j))){
out.println("NO");
return;
}
out.println("YES");
}
void run() throws IOException {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(new OutputStreamWriter(System.out));
solve();
in.close();
out.close();
}
public static void main(String[] args) throws IOException {
new BR168().run();
}
String nextToken() throws IOException {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(in.readLine());
}
return st.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
} | Java | ["3 4\nWWBW\nBWWW\nWWWB", "3 1\nB\nB\nW"] | 2 seconds | ["NO", "YES"] | null | Java 6 | standard input | [
"constructive algorithms",
"implementation"
] | 3631eba1b28fae473cf438bc2f0552b7 | The first line of the input contains two integers n and m (1ββ€βn,βmββ€β50) β the size of the grid. Each of the next n lines contains m characters "B" or "W". Character "B" denotes a black cell of the grid and "W" denotes a white cell of the grid. It's guaranteed that the grid has at least one black cell. | 1,700 | On the only line of the output print "YES" if the grid is convex, otherwise print "NO". Do not print quotes. | standard output | |
PASSED | 2ae3498ef149da5b63d07e752c9da33f | train_001.jsonl | 1361374200 | Consider an nβΓβm grid. Initially all the cells of the grid are colored white. Lenny has painted some of the cells (at least one) black. We call a painted grid convex if one can walk from any black cell to any another black cell using a path of side-adjacent black cells changing his direction at most once during the path. In the figure below, the left grid is convex while the right one is not convex, because there exist two cells which need more than one time to change direction in their path. You're given a painted grid in the input. Tell Lenny if the grid is convex or not. | 256 megabytes | import java.io.*;
import java.util.*;
import java.util.StringTokenizer;
import java.math.BigInteger;
public class SolutionB {
BufferedReader in;
StringTokenizer str;
PrintWriter out;
String SK;
long ff[];
String next() throws IOException {
while ((str == null) || (!str.hasMoreTokens())) {
SK = in.readLine();
if (SK == null)
return null;
str = new StringTokenizer(SK);
}
return str.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(next());
}
double nextDouble() throws IOException {
return Double.parseDouble(next());
}
long nextLong() throws IOException {
return Long.parseLong(next());
}
void run() throws IOException {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
//in = new BufferedReader(new FileReader("input.txt"));
//out = new PrintWriter("output.txt");
solve();
out.close();
}
public static void main(String[] args) throws IOException {
new SolutionB().run();
}
void solve() throws IOException {
int n=nextInt();
int m=nextInt();
char bd[][]=new char[n][m];
for(int i=0;i<n;i++){
bd[i]=next().toCharArray();
}
ArrayList<Cell> cell = new ArrayList<Cell>();
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
if(bd[i][j]=='B'){
Cell c=new Cell(i,j);
cell.add(c);
}
}
}
int nn=cell.size();
for(int i=0;i<nn;i++){
Cell c1=cell.get(i);
for(int j=i+1;j<nn;j++){
Cell c2=cell.get(j);
int rr1=Math.min(c1.i,c2.i);
int rr2=Math.max(c1.i,c2.i);
int cc1=Math.min(c1.j,c2.j);
int cc2=Math.max(c1.j,c2.j);
boolean path=true;
for(int r=rr1;r<=rr2;r++){
if(bd[r][c1.j]=='W'){
path=false;
break;
}
}
for(int c=cc1;c<=cc2;c++){
if(bd[c2.i][c]=='W'){
path=false;
break;
}
}
if(path)continue;
path=true;
for(int r=rr1;r<=rr2;r++){
if(bd[r][c2.j]=='W'){
path=false;
break;
}
}
for(int c=cc1;c<=cc2;c++){
if(bd[c1.i][c]=='W'){
path=false;
break;
}
}
if(path)continue;
if(!path){
//System.out.println(c1.i+" "+c1.j+" "+c2.i+" "+c2.j);
out.println("NO");
return;
}
}
}
out.println("YES");
}
}
class Cell{
int i;
int j;
public Cell(int i, int j){
this.i=i;
this.j=j;
}
} | Java | ["3 4\nWWBW\nBWWW\nWWWB", "3 1\nB\nB\nW"] | 2 seconds | ["NO", "YES"] | null | Java 6 | standard input | [
"constructive algorithms",
"implementation"
] | 3631eba1b28fae473cf438bc2f0552b7 | The first line of the input contains two integers n and m (1ββ€βn,βmββ€β50) β the size of the grid. Each of the next n lines contains m characters "B" or "W". Character "B" denotes a black cell of the grid and "W" denotes a white cell of the grid. It's guaranteed that the grid has at least one black cell. | 1,700 | On the only line of the output print "YES" if the grid is convex, otherwise print "NO". Do not print quotes. | standard output | |
PASSED | 6d75db0351fe4897f3842ed7fbc8b4f4 | train_001.jsonl | 1361374200 | Consider an nβΓβm grid. Initially all the cells of the grid are colored white. Lenny has painted some of the cells (at least one) black. We call a painted grid convex if one can walk from any black cell to any another black cell using a path of side-adjacent black cells changing his direction at most once during the path. In the figure below, the left grid is convex while the right one is not convex, because there exist two cells which need more than one time to change direction in their path. You're given a painted grid in the input. Tell Lenny if the grid is convex or not. | 256 megabytes | import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class R168_B implements Runnable{
private void solve() throws IOException {
int N = scanner.nextInt();
int M = scanner.nextInt();
int[][] m = new int[N][M];
int cnt = 0;
List<Pair> pairs = new ArrayList<Pair>();
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
byte color = scanner.nextChar();
if (color == 'B') {
m[i][j] = 1;
pairs.add(new Pair(i,j));
cnt++;
}
}
}
// if (cnt == 1) {
// out.println("YES");
// return;
// }
for (int i = 0; i < pairs.size(); i++) {
for (int j = i+1; j < pairs.size(); j++) {
boolean noRowDown = false, noDownRow = false;
Pair p1 = pairs.get(i);
Pair p2 = pairs.get(j);
int inc = (p1.j <= p2.j) ? 1 : -1;
for (int col = p1.j; col != p2.j; col += inc) {
if (m[p1.i][col] == 0) noRowDown = true;
if (m[p2.i][col] == 0) noDownRow = true;
}
for (int row = p1.i; row != p2.i; row++) {
if (m[row][p2.j]== 0 ) noRowDown = true;
if (m[row][p1.j]== 0 ) noDownRow = true;
}
if (noRowDown && noDownRow) {
out.println("NO");
return;
}
}
}
out.println("YES");
}
private class Pair {
public int i, j;
public Pair(int i, int j) {
this.i = i;
this.j = j;
}
}
/////////////////////////////////////////////////
final int BUF_SIZE = 1024 * 1024 * 8;//important to read long-string tokens properly
final int INPUT_BUFFER_SIZE = 1024 * 1024 * 8 ;
final int BUF_SIZE_INPUT = 1024;
final int BUF_SIZE_OUT = 1024;
boolean inputFromFile = false;
String filenamePrefix = "A-small-attempt0";
String inSuffix = "in.txt";
String outSuffix = "out.txt";
//InputStream bis;
//OutputStream bos;
PrintStream out;
ByteScanner scanner;
ByteWriter writer;
// @Override
public void run() {
try{
InputStream bis = null;
OutputStream bos = null;
//PrintStream out = null;
if (inputFromFile){
File baseFile = new File(getClass().getResource("/").getFile());
bis = new BufferedInputStream(
new FileInputStream(new File(
baseFile, filenamePrefix+inSuffix)),
INPUT_BUFFER_SIZE);
bos = new BufferedOutputStream(
new FileOutputStream(
new File(baseFile, filenamePrefix+outSuffix)));
out = new PrintStream(bos);
}else{
bis = new BufferedInputStream(System.in, INPUT_BUFFER_SIZE);
bos = new BufferedOutputStream(System.out);
out = new PrintStream(bos);
}
scanner = new ByteScanner(bis, BUF_SIZE_INPUT, BUF_SIZE);
writer = new ByteWriter(bos, BUF_SIZE_OUT);
solve();
out.flush();
}catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
public interface Constants{
final static byte ZERO = '0';//48 or 0x30
final static byte NINE = '9';
final static byte SPACEBAR = ' '; //32 or 0x20
final static byte MINUS = '-'; //45 or 0x2d
final static char FLOAT_POINT = '.';
}
public static class EofException extends IOException{
}
public static class ByteWriter implements Constants {
int bufSize = 1024;
byte[] byteBuf = new byte[bufSize];
OutputStream os;
public ByteWriter(OutputStream os, int bufSize){
this.os = os;
this.bufSize = bufSize;
}
public void writeInt(int num) throws IOException{
int byteWriteOffset = byteBuf.length;
if (num==0){
byteBuf[--byteWriteOffset] = ZERO;
}else{
int numAbs = Math.abs(num);
while (numAbs>0){
byteBuf[--byteWriteOffset] = (byte)((numAbs % 10) + ZERO);
numAbs /= 10;
}
if (num<0)
byteBuf[--byteWriteOffset] = MINUS;
}
os.write(byteBuf, byteWriteOffset, byteBuf.length - byteWriteOffset);
}
/**
* Please ensure ar.length <= byteBuf.length!
*
* @param ar
* @throws IOException
*/
public void writeByteAr(byte[] ar) throws IOException{
for (int i = 0; i < ar.length; i++) {
byteBuf[i] = ar[i];
}
os.write(byteBuf,0,ar.length);
}
public void writeSpaceBar() throws IOException{
byteBuf[0] = SPACEBAR;
os.write(byteBuf,0,1);
}
}
public static class ByteScanner implements Constants{
InputStream is;
public ByteScanner(InputStream is, int bufSizeInput, int bufSize){
this.is = is;
this.bufSizeInput = bufSizeInput;
this.bufSize = bufSize;
byteBufInput = new byte[this.bufSizeInput];
byteBuf = new byte[this.bufSize];
}
public ByteScanner(byte[] data){
byteBufInput = data;
bufSizeInput = data.length;
bufSize = data.length;
byteBuf = new byte[bufSize];
byteRead = data.length;
bytePos = 0;
}
private int bufSizeInput;
private int bufSize;
byte[] byteBufInput;
byte by=-1;
int byteRead=-1;
int bytePos=-1;
byte[] byteBuf;
int totalBytes;
boolean eofMet = false;
private byte nextByte() throws IOException{
if (bytePos<0 || bytePos>=byteRead){
byteRead = is==null? -1: is.read(byteBufInput);
bytePos=0;
if (byteRead<0){
byteBufInput[bytePos]=-1;//!!!
if (eofMet)
throw new EofException();
eofMet = true;
}
}
return byteBufInput[bytePos++];
}
/**
* Returns next meaningful character as a byte.<br>
*
* @return
* @throws IOException
*/
public byte nextChar() throws IOException{
while ((by=nextByte())<=0x20);
return by;
}
/**
* Returns next meaningful character OR space as a byte.<br>
*
* @return
* @throws IOException
*/
public byte nextCharOrSpacebar() throws IOException{
while ((by=nextByte())<0x20);
return by;
}
/**
* Reads line.
*
* @return
* @throws IOException
*/
public String nextLine() throws IOException {
readToken((byte)0x20);
return new String(byteBuf,0,totalBytes);
}
public byte[] nextLineAsArray() throws IOException {
readToken((byte)0x20);
byte[] out = new byte[totalBytes];
System.arraycopy(byteBuf, 0, out, 0, totalBytes);
return out;
}
/**
* Reads token. Spacebar is separator char.
*
* @return
* @throws IOException
*/
public String nextToken() throws IOException {
readToken((byte)0x21);
return new String(byteBuf,0,totalBytes);
}
/**
* Spacebar is included as separator char
*
* @throws IOException
*/
private void readToken() throws IOException {
readToken((byte)0x21);
}
private void readToken(byte acceptFrom) throws IOException {
totalBytes = 0;
while ((by=nextByte())<acceptFrom);
byteBuf[totalBytes++] = by;
while ((by=nextByte())>=acceptFrom){
byteBuf[totalBytes++] = by;
}
}
public int nextInt() throws IOException{
readToken();
int num=0, i=0;
boolean sign=false;
if (byteBuf[i]==MINUS){
sign = true;
i++;
}
for (; i<totalBytes; i++){
num*=10;
num+=byteBuf[i]-ZERO;
}
return sign?-num:num;
}
public long nextLong() throws IOException{
readToken();
long num=0;
int i=0;
boolean sign=false;
if (byteBuf[i]==MINUS){
sign = true;
i++;
}
for (; i<totalBytes; i++){
num*=10;
num+=byteBuf[i]-ZERO;
}
return sign?-num:num;
}
/*
//TODO test Unix/Windows formats
public void toNextLine() throws IOException{
while ((ch=nextChar())!='\n');
}
*/
public double nextDouble() throws IOException{
readToken();
char[] token = new char[totalBytes];
for (int i = 0; i < totalBytes; i++) {
token[i] = (char)byteBuf[i];
}
return Double.parseDouble(new String(token));
}
public int[] loadIntArray(int size) throws IOException{
int[] a = new int[size];
for (int i = 0; i < a.length; i++) {
a[i] = nextInt();
}
return a;
}
public long[] loadLongArray(int size) throws IOException{
long[] a = new long[size];
for (int i = 0; i < a.length; i++) {
a[i] = nextLong();
}
return a;
}
}
public static abstract class Timing{
private static int counter = 0;
protected String name = "Timing"+(++counter);
private boolean debug;
public Timing(boolean debug) {
super();
this.debug = debug;
}
public abstract void run();
public void start(){
long time1 = System.currentTimeMillis();
run();
long time2 = System.currentTimeMillis();
if (debug)
System.out.println(name+" time = "+(time2-time1)/1000.0+" ms.");
}
}
public static class Alg{
public static interface BooleanChecker{
public boolean check(long arg);
}
public static class BinarySearch{
/**
* This check returns boolean value, result of function.
* It should be monotonic.
*
* @return
*/
public BooleanChecker bc;
/**
* Returns following element: <pre> 0 0 [1] 1 1</pre>
*/
public long search(long left, long right){
while (left<=right){
long mid = (left+right)/2;
if (bc.check(mid)){
right = mid-1;
}else{
left = mid+1;
}
}
return left;
}
/**
* Optional.<br>
* Returns following element: <pre> 1 1 [1] 0 0</pre>
*/
public long searchInverted(long left, long right){
while (left<=right){
long mid = (left+right)/2;
if (!bc.check(mid)){
right = mid-1;
}else{
left = mid+1;
}
}
return left - 1;
}
}
}
public static class Modulo{
long mod = (long)1e9+7;
public Modulo(long mod) {
super();
this.mod = mod;
}
public long inv(long a) {
long res = pow(a, mod-2);
return res;
}
public long pow(long a, long x) {
if (x==0)
return 1;
long part = 1;
if ((x&1)!=0)
part = a;
return (part * pow((a*a)%mod, x>>1)) % mod;
}
}
public static void main(String[] args) {
new R168_B().run();
}
} | Java | ["3 4\nWWBW\nBWWW\nWWWB", "3 1\nB\nB\nW"] | 2 seconds | ["NO", "YES"] | null | Java 6 | standard input | [
"constructive algorithms",
"implementation"
] | 3631eba1b28fae473cf438bc2f0552b7 | The first line of the input contains two integers n and m (1ββ€βn,βmββ€β50) β the size of the grid. Each of the next n lines contains m characters "B" or "W". Character "B" denotes a black cell of the grid and "W" denotes a white cell of the grid. It's guaranteed that the grid has at least one black cell. | 1,700 | On the only line of the output print "YES" if the grid is convex, otherwise print "NO". Do not print quotes. | standard output | |
PASSED | 35290a051d20a7c23ef791dff69f01fe | train_001.jsonl | 1361374200 | Consider an nβΓβm grid. Initially all the cells of the grid are colored white. Lenny has painted some of the cells (at least one) black. We call a painted grid convex if one can walk from any black cell to any another black cell using a path of side-adjacent black cells changing his direction at most once during the path. In the figure below, the left grid is convex while the right one is not convex, because there exist two cells which need more than one time to change direction in their path. You're given a painted grid in the input. Tell Lenny if the grid is convex or not. | 256 megabytes | import java.io.*;
import java.math.*;
import java.util.*;
public class Main
{
static Input in;
static Output out;
static final boolean OJ = true;
public static void main(String[] args) throws IOException
{
in = new Input(OJ ? System.in : new FileInputStream("in.txt"));
out = new Output(OJ ? System.out : new FileOutputStream("out.txt"));
run();
out.close();
System.exit(0);
}
static int max, n;
static char[] array;
static boolean[] A, B;
private static void run() throws IOException
{
int n = in.nextInt();
int m = in.nextInt();
char[][] M = new char[n][];
List<Position> blacks = new ArrayList<Position>(n * n);
for (int i = 0; i < n; i++)
{
M[i] = in.nextString().toCharArray();
for (int j = 0; j < m; j++)
{
if (M[i][j] == 'B') blacks.add(new Position(i, j));
}
}
out.print(checkPath(blacks, M) ? "YES" : "NO");
}
private static boolean checkPath(List<Position> blacks, char[][] M)
{
for (Position a : blacks)
for (Position b : blacks)
{
if (a.r == b.r) // same row
{
if (a.c == b.c && !travel(a, b, M, 0, 0)) return false; // same pos
else if (a.c < b.c && !travel(a, b, M, 0, 1)) return false; // go right
else if (a.c > b.c && !travel(a, b, M, 0, -1)) return false; // right
}
else if (a.r < b.r) // go down
{
if (a.c == b.c && !travel(a, b, M, 1, 0)) return false; // same column
else if (a.c < b.c && !travel(a, b, M, 1, 1)) return false; // go right
else if (a.c > b.c && !travel(a, b, M, 1, -1)) return false; // go left
}
else // go up
{
if (a.c == b.c && !travel(a, b, M, -1, 0)) return false; // same column
else if (a.c < b.c && !travel(a, b, M, -1, 1)) return false; // left
else if (a.c > b.c && !travel(a, b, M, -1, -1)) return false; // right
}
}
return true;
}
private static boolean travel(Position a, Position b, char[][] M, int ri, int ci)
{
// vertical first
boolean vert = true;
for (int row = a.r; row != b.r && vert; row += ri)
{
if (M[row][a.c] == 'W') vert = false;
}
if (vert)
for (int col = a.c; col != b.c && vert; col += ci)
{
if (M[b.r][col] == 'W') vert = false;
}
if (vert) return true;
// horizontal first
boolean hor = true;
for (int col = a.c; col != b.c && hor; col += ci)
{
if (M[a.r][col] == 'W') hor = false;
}
if (hor)
for (int row = a.r; row != b.r && hor; row += ri)
{
if (M[row][b.c] == 'W') hor = false;
}
return hor;
}
static class Position
{
int r, c;
public Position(int i, int j)
{
r = i; c = j;
}
}
}
class Input
{
final int SIZE = 8192;
private InputStream in;
private byte[] buf = new byte[SIZE];
private int last, current, total;
public Input(InputStream stream) throws IOException
{
in = stream;
last = read();
}
private int read() throws IOException
{
if (total == -1) return -1;
if (current >= total)
{
current = 0;
total = in.read(buf);
if (total <= 0) return -1;
}
return buf[current++];
}
private void advance() throws IOException
{
while (true)
{
if (last == -1) return;
if (!isValidChar(last)) last = read();
else break;
}
}
private boolean isValidChar(int c)
{
return c > 32 && c < 127;
}
public boolean isEOF() throws IOException
{
advance();
return last == -1;
}
public String nextString() throws IOException
{
advance();
if (last == -1) throw new EOFException();
StringBuilder s = new StringBuilder();
while (true)
{
s.appendCodePoint(last);
last = read();
if (!isValidChar(last)) break;
}
return s.toString();
}
public String nextLine() throws IOException
{
if (last == -1) throw new EOFException();
StringBuilder s = new StringBuilder();
while (true)
{
s.appendCodePoint(last);
last = read();
if (last == '\n' || last == -1) break;
}
return s.toString();
}
public String nextLine(boolean ignoreIfEmpty) throws IOException
{
if (!ignoreIfEmpty) return nextLine();
String s = nextLine();
while (s.trim().length() == 0) s = nextLine();
return s;
}
public int nextInt() throws IOException
{
advance();
if (last == -1) throw new EOFException();
int n = 0, s = 1;
if (last == '-')
{
s = -1;
last = read();
if (last == -1) throw new EOFException();
}
while (true)
{
n = n * 10 + last - '0';
last = read();
if (!isValidChar(last)) break;
}
return n * s;
}
public long nextLong() throws IOException
{
advance();
if (last == -1) throw new EOFException();
int s = 1;
if (last == '-')
{
s = -1;
last = read();
if (last == -1) throw new EOFException();
}
long n = 0;
while (true)
{
n = n * 10 + last - '0';
last = read();
if (!isValidChar(last)) break;
}
return n * s;
}
public BigInteger nextBigInt() throws IOException
{
return new BigInteger(nextString());
}
public char nextChar() throws IOException
{
advance();
return (char) last;
}
public double nextDouble() throws IOException
{
advance();
if (last == -1) throw new EOFException();
int s = 1;
if (last == '-')
{
s = -1;
last = read();
if (last == -1) throw new EOFException();
}
double n = 0;
while (true)
{
n = n * 10 + last - '0';
last = read();
if (!isValidChar(last) || last == '.') break;
}
if (last == '.')
{
last = read();
if (last == -1) throw new EOFException();
double m = 1;
while (true)
{
m = m / 10;
n = n + (last - '0') * m;
last = read();
if (!isValidChar(last)) break;
}
}
return n * s;
}
public BigDecimal nextBigDecimal() throws IOException
{
return new BigDecimal(nextString());
}
}
class Output
{
final int SIZE = 4096;
private Writer out;
private char cb[] = new char[SIZE];
private int nChars = SIZE, nextChar = 0;
private char lineSeparator = '\n';
public Output(OutputStream stream)
{
out = new OutputStreamWriter(stream);
}
void flushBuffer() throws IOException
{
if (nextChar == 0) return;
out.write(cb, 0, nextChar);
nextChar = 0;
}
void write(int c) throws IOException
{
if (nextChar >= nChars) flushBuffer();
cb[nextChar++] = (char) c;
}
void write(String s, int off, int len) throws IOException
{
int b = off, t = off + len;
while (b < t)
{
int a = nChars - nextChar, a1 = t - b;
int d = a < a1 ? a : a1;
s.getChars(b, b + d, cb, nextChar);
b += d;
nextChar += d;
if (nextChar >= nChars) flushBuffer();
}
}
void write(String s) throws IOException
{
write(s, 0, s.length());
}
public void print(Object obj) throws IOException
{
write(String.valueOf(obj));
}
public void println(Object obj) throws IOException
{
write(String.valueOf(obj));
write(lineSeparator);
}
public void printf(String format, Object... obj) throws IOException
{
write(String.format(format, obj));
}
public void close() throws IOException
{
flushBuffer();
out.close();
}
} | Java | ["3 4\nWWBW\nBWWW\nWWWB", "3 1\nB\nB\nW"] | 2 seconds | ["NO", "YES"] | null | Java 6 | standard input | [
"constructive algorithms",
"implementation"
] | 3631eba1b28fae473cf438bc2f0552b7 | The first line of the input contains two integers n and m (1ββ€βn,βmββ€β50) β the size of the grid. Each of the next n lines contains m characters "B" or "W". Character "B" denotes a black cell of the grid and "W" denotes a white cell of the grid. It's guaranteed that the grid has at least one black cell. | 1,700 | On the only line of the output print "YES" if the grid is convex, otherwise print "NO". Do not print quotes. | standard output | |
PASSED | 345bcf7dbc1cd80403202c9dde8831bc | train_001.jsonl | 1361374200 | Consider an nβΓβm grid. Initially all the cells of the grid are colored white. Lenny has painted some of the cells (at least one) black. We call a painted grid convex if one can walk from any black cell to any another black cell using a path of side-adjacent black cells changing his direction at most once during the path. In the figure below, the left grid is convex while the right one is not convex, because there exist two cells which need more than one time to change direction in their path. You're given a painted grid in the input. Tell Lenny if the grid is convex or not. | 256 megabytes | import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int m = scanner.nextInt();
int[][] array = new int[n][m];
int count = 0;
boolean make = true;
for (int i = 0; i < n + 1; i++) {
String temp = scanner.nextLine().replace(" ", "");
if (temp.length() > 0) {
for (int j = 0; j < temp.length(); j++) {
if (temp.charAt(j) == 'W') {
array[i - 1][j] = 0;
} else {
array[i - 1][j] = 1;
count++;
}
}
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
int[][] used = new int[n][m];
for (int i1 = 0; i1 < n; i1++)
for (int j1 = 0; j1 < m; j1++) used[i1][j1] = 0;
if (array[i][j] == 1) {
// System.out.println(i + " " + j);
int cur = 1;
used[i][j] = 1;
//niz
for (int z = i + 1; z < n; z++) {
if (array[z][j] == 1 && used[z][j] == 0) {
used[z][j] = 1;
cur++;
// System.out.println("a");
//
for (int k = j - 1; k >= 0 && array[z][k] == 1; k--) {
if (used[z][k] == 0) {
cur++;
used[z][k] = 1;
}
}
for (int k = j + 1; k < m && array[z][k] == 1; k++) {
if (used[z][k] == 0) {
cur++;
used[z][k] = 1;
}
}
} else break;
}
// Π»Π΅Π²ΠΎ
for (int z = j - 1; z >= 0; z--) {
if (array[i][z] == 1 && used[i][z] == 0) {
used[i][z] = 1;
cur++;
for (int k = i + 1; k < n && array[k][z] == 1; k++) {
if (used[k][z] == 0) {
cur++;
used[k][z] = 1;
}
}
// System.out.println("b");
for (int k = i - 1; k >= 0 && array[k][z] == 1; k--) {
if (used[k][z] == 0) {
// System.out.println("AAA");
cur++;
used[k][z] = 1;
}
}
} else break;
}
//ΠΏΡΠ°Π²ΠΎ
for (int z = j + 1; z < m; z++) {
if (array[i][z] == 1 && used[i][z] == 0) {
used[i][z] = 0;
cur++;
for (int k = i + 1; k < n && array[k][z] == 1; k++) {
if (used[k][z] == 0) {
cur++;
used[k][z] = 1;
}
}
// System.out.println("c");
for (int k = i - 1; k >= 0 && array[k][z] == 1; k--) {
if (used[k][z] == 0) {
cur++;
used[k][z] = 1;
}
}
// System.out.println(cur + " ASADASDASDA");
} else break;
}
// verh
for (int z = i - 1; z >= 0; z--) {
if (array[z][j] == 1 && used[z][j] == 0) {
used[z][j] = 1;
cur++;
for (int k = j - 1; k >= 0 && array[z][k] == 1; k--) {
if (used[z][k] == 0) {
cur++;
used[z][k] = 1;
}
}
// System.out.println("d" + " " + z + " " + j);
for (int k = j + 1; k < m && array[z][k] == 1; k++) {
if (used[z][k] == 0) {
cur++;
used[z][k] = 1;
}
}
//System.out.println(cur + " KKKKKKKKKK");
} else break;
}
// System.out.println(cur);
if (cur != count) make = false;
}
}
}
if (!make) System.out.println("NO");
else System.out.println("YES");
}
}
| Java | ["3 4\nWWBW\nBWWW\nWWWB", "3 1\nB\nB\nW"] | 2 seconds | ["NO", "YES"] | null | Java 6 | standard input | [
"constructive algorithms",
"implementation"
] | 3631eba1b28fae473cf438bc2f0552b7 | The first line of the input contains two integers n and m (1ββ€βn,βmββ€β50) β the size of the grid. Each of the next n lines contains m characters "B" or "W". Character "B" denotes a black cell of the grid and "W" denotes a white cell of the grid. It's guaranteed that the grid has at least one black cell. | 1,700 | On the only line of the output print "YES" if the grid is convex, otherwise print "NO". Do not print quotes. | standard output | |
PASSED | 7f898895f654dfdeb6e51259071ada34 | train_001.jsonl | 1361374200 | Consider an nβΓβm grid. Initially all the cells of the grid are colored white. Lenny has painted some of the cells (at least one) black. We call a painted grid convex if one can walk from any black cell to any another black cell using a path of side-adjacent black cells changing his direction at most once during the path. In the figure below, the left grid is convex while the right one is not convex, because there exist two cells which need more than one time to change direction in their path. You're given a painted grid in the input. Tell Lenny if the grid is convex or not. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Task2 {
private static boolean[][] table;
private static State[] rowState, colState;
static BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
static int nextInt(String s) {
Matcher matcher = Pattern.compile("\\d+").matcher(s);
if (!matcher.find()) {
throw new RuntimeException();
}
return Integer.parseInt(matcher.group());
}
public static void main(String[] args) throws IOException {
Matcher matcher = Pattern.compile("(\\d+) (\\d+)").matcher(r.readLine());
matcher.find();
int rows = Integer.parseInt(matcher.group(1));
int cols = Integer.parseInt(matcher.group(2));
table = new boolean[rows][cols];
rowState = new State[rows];
colState = new State[cols];
for (int i = 0; i < rows; i++) {
String line = r.readLine();
for (int j = 0; j < cols; j++) {
boolean isBlack = table[i][j] = line.charAt(j) == 'B';
if (problemsInState(rowState, i, isBlack) || problemsInState(colState, j, isBlack)) {
System.out.println("NO");
return;
}
// System.out.print(line.charAt(j));
}
// System.out.println();
}
for (int i1 = 0; i1 < rows; i1++) {
for (int j1 = 0; j1 < cols; j1++) {
for (int i2 = 0; i2 < rows; i2++) {
for (int j2 = 0; j2 < cols; j2++) {
if (table[i1][j1] && table[i2][j2]) {
if (table[i1][j2] || table[i2][j1]) {
// OK
} else {
System.out.println("NO");
return;
}
}
}
}
}
}
System.out.println("YES");
}
private static boolean problemsInState(State states[], int position, boolean isBlack) {
State state = states[position];
if (isBlack) {
if (state == State.whiteAfterBlack) {
return true;
}
state = State.black;
} else {
if (state == State.black) {
state = State.whiteAfterBlack;
}
}
states[position] = state;
return false;
}
public static enum State {
// null = neverBlack
black,
whiteAfterBlack
}
}
| Java | ["3 4\nWWBW\nBWWW\nWWWB", "3 1\nB\nB\nW"] | 2 seconds | ["NO", "YES"] | null | Java 6 | standard input | [
"constructive algorithms",
"implementation"
] | 3631eba1b28fae473cf438bc2f0552b7 | The first line of the input contains two integers n and m (1ββ€βn,βmββ€β50) β the size of the grid. Each of the next n lines contains m characters "B" or "W". Character "B" denotes a black cell of the grid and "W" denotes a white cell of the grid. It's guaranteed that the grid has at least one black cell. | 1,700 | On the only line of the output print "YES" if the grid is convex, otherwise print "NO". Do not print quotes. | standard output | |
PASSED | 340d33ac78d1bdcfb6020e7ddaae43b2 | train_001.jsonl | 1361374200 | Consider an nβΓβm grid. Initially all the cells of the grid are colored white. Lenny has painted some of the cells (at least one) black. We call a painted grid convex if one can walk from any black cell to any another black cell using a path of side-adjacent black cells changing his direction at most once during the path. In the figure below, the left grid is convex while the right one is not convex, because there exist two cells which need more than one time to change direction in their path. You're given a painted grid in the input. Tell Lenny if the grid is convex or not. | 256 megabytes |
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.StringTokenizer;
import java.util.TreeMap;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
* 6
* 1 0
* 0 0
* 0 0
* 1 1
* 0 1
* 1 1
*
* @author pttrung
*/
public class B {
public static boolean circle;
public static int a, b;
public static int[] x = {0, 1, 0, -1};
public static int[] y = {1, 0, -1, 0};
public static void main(String[] args) throws FileNotFoundException {
PrintWriter out;
Scanner in = new Scanner();
//out = new PrintWriter(new FileOutputStream(new File("output.txt")));
out = new PrintWriter(System.out);
int n = in.nextInt();
int m = in.nextInt();
boolean[][] map = new boolean[n][m];
int count = 0;
for (int i = 0; i < n; i++) {
String line = in.next();
for (int j = 0; j < m; j++) {
map[i][j] = line.charAt(j) == 'B';
if (map[i][j]) {
count++;
}
}
}
boolean found = true;
for (int i = 0; i < n && found; i++) {
for (int j = 0; j < m; j++) {
if (map[i][j]) {
boolean[][] check = new boolean[n][m];
int result = 1;
check[i][j] = true;
for (int k = 0; k < 4; k++) {
int a = x[k] + i;
int b = y[k] + j;
if (a >= 0 && a < map.length && b >= 0 && b < map[0].length && map[a][b]) {
result += dfs(0, k, a, b, check, map);
}
}
if(result == count){
// count--;
// map[a][b] = false;
}else{
found = false;
break;
}
}
}
}
if(found){
out.println("YES");
}else{
out.println("NO");
}
out.close();
}
public static int dfs(int change, int last, int i, int j, boolean[][] check, boolean[][] map) {
int a = x[last] + i;
int b = y[last] + j;
int result = 0;
if (!check[i][j]) {
check[i][j] = true;
result++;
}
if (a >= 0 && a < map.length && b >= 0 && b < map[0].length && map[a][b]) {
result += dfs(change, last, a, b, check, map);
}
if (change == 0) {
for (int k = 0; k < 4; k++) {
if (k != last) {
int c = x[k] + i;
int d = y[k] + j;
if (c >= 0 && c < map.length && d >= 0 && d < map[0].length && map[c][d]) {
result += dfs(change + 1, k, c, d, check, map);
}
}
}
}
return result;
}
public static Line getLine(Point a, Point b) {
int c = (a.x - b.x);
int d = (a.y - b.y);
if (c == 0) {
return new Line(1, 0, -a.x);
} else if (d == 0) {
return new Line(0, 1, -a.y);
} else {
double rate = (double) (-d) / c;
double other = ((double) rate * a.x) + a.y;
//System.out.println(a + "|" + b + ": " + rate + " " + other);
return new Line(rate, 1, -other);
}
}
public static class Line {
double a, b, c;
public Line(double a, double b, double c) {
this.a = a;
this.b = b;
this.c = c;
}
@Override
public int hashCode() {
int hash = 7;
hash = 47 * hash + (int) (Double.doubleToLongBits(this.a) ^ (Double.doubleToLongBits(this.a) >>> 32));
hash = 47 * hash + (int) (Double.doubleToLongBits(this.b) ^ (Double.doubleToLongBits(this.b) >>> 32));
hash = 47 * hash + (int) (Double.doubleToLongBits(this.c) ^ (Double.doubleToLongBits(this.c) >>> 32));
return hash;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Line other = (Line) obj;
if (Double.doubleToLongBits(this.a) != Double.doubleToLongBits(other.a)) {
return false;
}
if (Double.doubleToLongBits(this.b) != Double.doubleToLongBits(other.b)) {
return false;
}
if (Double.doubleToLongBits(this.c) != Double.doubleToLongBits(other.c)) {
return false;
}
return true;
}
@Override
public String toString() {
return a + " " + b + " " + c;
}
}
static class FT {
int[] data;
FT(int n) {
data = new int[n];
}
void update(int index, int val) {
// System.out.println("UPDATE INDEX " + index);
while (index < data.length) {
data[index] += val;
index += index & (-index);
// System.out.println("NEXT " +index);
}
}
int get(int index) {
// System.out.println("GET INDEX " + index);
int result = 0;
while (index > 0) {
result += data[index];
index -= index & (-index);
// System.out.println("BACK " + index);
}
return result;
}
}
public static double dist(Point a, Point b) {
double val = (a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y);
return Math.sqrt(val);
}
public static class Point {
int x, y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public String toString() {
return x + " " + y;
}
}
public static boolean nextPer(int[] data) {
int i = data.length - 1;
while (i > 0 && data[i] < data[i - 1]) {
i--;
}
if (i == 0) {
return false;
}
int j = data.length - 1;
while (data[j] < data[i - 1]) {
j--;
}
int temp = data[i - 1];
data[i - 1] = data[j];
data[j] = temp;
Arrays.sort(data, i, data.length);
return true;
}
public static long pow(int a, int b) {
if (b == 0) {
return 1;
}
if (b == 1) {
return a;
}
long val = pow(a, b / 2);
if (b % 2 == 0) {
return val * val;
} else {
return val * val * a;
}
}
public static long gcd(long a, long b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
public static long lcm(long a, long b) {
return a * b / gcd(a, b);
}
static class Scanner {
BufferedReader br;
StringTokenizer st;
public Scanner() throws FileNotFoundException {
// System.setOut(new PrintStream(new BufferedOutputStream(System.out), true));
br = new BufferedReader(new InputStreamReader(System.in));
// br = new BufferedReader(new FileReader(new File("output.txt")));
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
throw new RuntimeException();
}
}
return st.nextToken();
}
public long nextLong() {
return Long.parseLong(next());
}
public int nextInt() {
return Integer.parseInt(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public String nextLine() {
st = null;
try {
return br.readLine();
} catch (Exception e) {
throw new RuntimeException();
}
}
public boolean endLine() {
try {
String next = br.readLine();
while (next != null && next.trim().isEmpty()) {
next = br.readLine();
}
if (next == null) {
return true;
}
st = new StringTokenizer(next);
return st.hasMoreTokens();
} catch (Exception e) {
throw new RuntimeException();
}
}
}
}
| Java | ["3 4\nWWBW\nBWWW\nWWWB", "3 1\nB\nB\nW"] | 2 seconds | ["NO", "YES"] | null | Java 6 | standard input | [
"constructive algorithms",
"implementation"
] | 3631eba1b28fae473cf438bc2f0552b7 | The first line of the input contains two integers n and m (1ββ€βn,βmββ€β50) β the size of the grid. Each of the next n lines contains m characters "B" or "W". Character "B" denotes a black cell of the grid and "W" denotes a white cell of the grid. It's guaranteed that the grid has at least one black cell. | 1,700 | On the only line of the output print "YES" if the grid is convex, otherwise print "NO". Do not print quotes. | standard output | |
PASSED | 4e59eac68ee36aa623ca453989197996 | train_001.jsonl | 1361374200 | Consider an nβΓβm grid. Initially all the cells of the grid are colored white. Lenny has painted some of the cells (at least one) black. We call a painted grid convex if one can walk from any black cell to any another black cell using a path of side-adjacent black cells changing his direction at most once during the path. In the figure below, the left grid is convex while the right one is not convex, because there exist two cells which need more than one time to change direction in their path. You're given a painted grid in the input. Tell Lenny if the grid is convex or not. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
public class Main{
static char ma[][];
static int row[][];
static int col[][];
public static void main(String[] args) throws Throwable {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(in.readLine());
int n = Integer.parseInt(st.nextToken());
int m = Integer.parseInt(st.nextToken());
ma = new char[n][m];
row = new int[n][m];
col = new int[n][m];
for (int i = 0; i < n; i++) {
ma[i] = in.readLine().toCharArray();
}
int cont = 1;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if(ma[i][j]=='B'){
row[i][j] = cont;
}else{
cont++;
}
}
}
cont = 1;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if(ma[j][i]=='B'){
col[j][i] = cont;
}else{
cont++;
}
}
}
// for (int i = 0; i < n; i++) {
// System.out.println(Arrays.toString(row[i]));
// }
// System.out.println();
// for (int i = 0; i < n; i++) {
// System.out.println(Arrays.toString(col[i]));
// }
boolean si = true;
for (int i = 0; i < n && si; i++) {
for (int j = 0; j < m && si; j++) {
for (int k = 0; k < n && si; k++) {
for (int l = 0; l < m && si; l++) {
if( !(i==k && j==l) && ma[i][j]=='B' && ma[k][l]=='B' ){
if( i == k ){
if( row[i][j] != row[k][l]){
si = false;
// System.out.println("cc");
}
}else if( j == l ){
if( col[i][j] != col[k][l]){
si = false;
// System.out.println("bb");
}
}else{
int x1,y1;
int x2,y2;
int xu,yu;
int xd,yd;
if( i < k ) {
x1 = i; y1 = j; x2 = k; y2 = l; xu = i; xd = k; yu = l; yd = j;
}else{
x1 = k; y1 = l; x2 = i; y2 = j; xu = k; xd = i;yu = j; yd = l;
}
// if( i == 1 && j == 3)
// System.out.println(i+" "+j+" * " + k+" "+l+" * " + xu +" "+yu+" * "+xd+" "+yd);
if( !( row[xu][yu] == row[x1][y1] && col[xu][yu] == col[x2][y2] ) &&
!( row[xd][yd] == row[x2][y2] && col[xd][yd]==col[x1][y1] ) ) {
// System.out.println( "aa ");
si = false;
}
}
}
}
}
}
}
if(si) System.out.println("YES");
else System.out.println("NO");
}
}
| Java | ["3 4\nWWBW\nBWWW\nWWWB", "3 1\nB\nB\nW"] | 2 seconds | ["NO", "YES"] | null | Java 6 | standard input | [
"constructive algorithms",
"implementation"
] | 3631eba1b28fae473cf438bc2f0552b7 | The first line of the input contains two integers n and m (1ββ€βn,βmββ€β50) β the size of the grid. Each of the next n lines contains m characters "B" or "W". Character "B" denotes a black cell of the grid and "W" denotes a white cell of the grid. It's guaranteed that the grid has at least one black cell. | 1,700 | On the only line of the output print "YES" if the grid is convex, otherwise print "NO". Do not print quotes. | standard output | |
PASSED | 3b1ec197e55451a47b89e894006ad3a5 | train_001.jsonl | 1361374200 | Consider an nβΓβm grid. Initially all the cells of the grid are colored white. Lenny has painted some of the cells (at least one) black. We call a painted grid convex if one can walk from any black cell to any another black cell using a path of side-adjacent black cells changing his direction at most once during the path. In the figure below, the left grid is convex while the right one is not convex, because there exist two cells which need more than one time to change direction in their path. You're given a painted grid in the input. Tell Lenny if the grid is convex or not. | 256 megabytes | import java.util.*;
public class ConvexShape {
static int n;
static int m;
static String[] map;
static boolean[][] isVisited;
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
n=sc.nextInt();
m=sc.nextInt();
map=new String[n];
for (int i = 0; i < n; i++) {
map[i]=sc.next();
}
for (int i = 0; i < n; i++) {//y
for (int j = 0; j < m; j++) { //x
if(map[i].charAt(j)=='B')
{
//System.out.println(String.format("%d %d", j,i));
isVisited=new boolean[n][m];
isVisited[i][j]=true;
firstGo(j,i,1,0,0);
firstGo(j, i, -1, 0, 0);
firstGo(j, i, 0, 1, 1);
firstGo(j, i, 0, -1, 1);
for (int zy = 0; zy < n; zy++) {
for (int zx = 0; zx < m; zx++) {
if(!isVisited[zy][zx] && map[zy].charAt(zx)=='B')
{
System.out.println("NO");
return ;
}
}
}
}
}
}
System.out.println("YES");
}
public static void firstGo(int x,int y, int dx,int dy,int id)
{
while(true)
{
int newX=x+dx;
int newY=y+dy;
if(newX<0 || newX>=m) break;
if(newY<0 || newY>=n) break;
if(map[newY].charAt(newX)=='W') break;
isVisited[newY][newX]=true;
if(id==0)
{
secondGo(newX, newY, 0, -1);
secondGo(newX, newY, 0, 1);
}
else
{
secondGo(newX, newY, -1, 0);
secondGo(newX, newY, 1, 0);
}
x+=dx;
y+=dy;
}
}
public static void secondGo(int x,int y,int dx,int dy)
{
while(true)
{
int newX=x+dx;
int newY=y+dy;
if(newX<0 || newX>=m) break;
if(newY<0 || newY>=n) break;
if(map[newY].charAt(newX)=='W') break;
isVisited[newY][newX]=true;
x+=dx;
y+=dy;
}
}
}
| Java | ["3 4\nWWBW\nBWWW\nWWWB", "3 1\nB\nB\nW"] | 2 seconds | ["NO", "YES"] | null | Java 6 | standard input | [
"constructive algorithms",
"implementation"
] | 3631eba1b28fae473cf438bc2f0552b7 | The first line of the input contains two integers n and m (1ββ€βn,βmββ€β50) β the size of the grid. Each of the next n lines contains m characters "B" or "W". Character "B" denotes a black cell of the grid and "W" denotes a white cell of the grid. It's guaranteed that the grid has at least one black cell. | 1,700 | On the only line of the output print "YES" if the grid is convex, otherwise print "NO". Do not print quotes. | standard output | |
PASSED | f7823358cb7e522a8ceaa035264b6338 | train_001.jsonl | 1361374200 | Consider an nβΓβm grid. Initially all the cells of the grid are colored white. Lenny has painted some of the cells (at least one) black. We call a painted grid convex if one can walk from any black cell to any another black cell using a path of side-adjacent black cells changing his direction at most once during the path. In the figure below, the left grid is convex while the right one is not convex, because there exist two cells which need more than one time to change direction in their path. You're given a painted grid in the input. Tell Lenny if the grid is convex or not. | 256 megabytes | import java.io.*;
public class ConvexShape {
/**
* @param args
*/
public static void main(String[] args) {
try{
//BufferedReader br=new BufferedReader(new FileReader("C:/Users/MINTOO/Desktop/Programs/Java/ConvexShape.txt"));
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String s=br.readLine();
String ss[]=s.split(" ");
int n=Integer.parseInt(ss[0]);
int m=Integer.parseInt(ss[1]);
int i=0,j=0,k=0,l=0;
char a[][]=new char[n][m];
for(i=0;i<n;i++)
{
String s2=br.readLine();
for(j=0;j<m;j++)
{
a[i][j]=s2.charAt(j);
}
}
boolean gy=true;
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
{
if(a[i][j]=='B')
{
for(k=i;k<n;k++)
{
for(l=0;l<m;l++)
{
if(a[k][l]=='B')
{
if(!check(a,i,j,k,l,n,m))
{
gy=false;
}
}
}
}
}
}
}
if(gy)
{
System.out.println("YES");
}
else
{
System.out.println("NO");
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
public static boolean check(char a[][],int i,int j,int k,int l,int n,int m)
{
//System.out.println(i+" "+j+" "+k+" "+l+" ");
int r=0,c=0;
boolean y=true,y1=true,y2=true;
//Same Row
if(i==k)
{
if(j<l)
{
for(r=j+1;r<=l;r++)
{
if(a[i][r]!='B')
{
y=false;
break;
}
}
return y;
}
else
{
for(r=j-1;r>=l;r--)
{
if(a[i][r]!='B')
{
y=false;
break;
}
}
return y;
}
}
//Same Column
if(j==l)
{
if(i<k)
{
for(r=i+1;r<=k;r++)
{
if(a[r][j]!='B')
{
y=false;
break;
}
}
return y;
}
else
{
for(r=i-1;r>=k;r--)
{
if(a[r][j]!='B')
{
y=false;
break;
}
}
return y;
}
}
// Left Bottom
if(k>i && l<j)
{
for(r=l-1;r>=j;r--)
{
if(a[i][r]!='B')
{
y1=false;
break;
}
}
if(y1)
{
for(r=k-1;r>=i;r--)
{
if(a[r][l]!='B')
{
y1=false;
break;
}
}
}
if(!y1)
{
for(r=i+1;r<=k;r++)
{
if(a[r][j]!='B')
{
y2=false;
break;
}
}
if(y2)
{
for(r=l+1;r<=j;r++)
{
if(a[k][r]!='B')
{
y2=false;
break;
}
}
}
}
if(y1 || y2)
{
return y;
}
else
{
y=false;
return y;
}
}
// Right Bottom
if(k>i && l>j)
{
for(r=j+1;r<=l;r++)
{
if(a[i][r]!='B')
{
y1=false;
break;
}
}
if(y1)
{
for(r=i+1;r<=k;r++)
{
if(a[r][l]!='B')
{
y1=false;
break;
}
}
}
if(!y1)
{
for(r=i+1;r<=k;r++)
{
if(a[r][j]!='B')
{
y2=false;
break;
}
}
if(y2)
{
for(r=j+1;r<=l;r++)
{
if(a[k][r]!='B')
{
y2=false;
break;
}
}
}
}
if(y1 || y2)
{
return y;
}
else
{
y=false;
return y;
}
}
return y;
}
}
| Java | ["3 4\nWWBW\nBWWW\nWWWB", "3 1\nB\nB\nW"] | 2 seconds | ["NO", "YES"] | null | Java 6 | standard input | [
"constructive algorithms",
"implementation"
] | 3631eba1b28fae473cf438bc2f0552b7 | The first line of the input contains two integers n and m (1ββ€βn,βmββ€β50) β the size of the grid. Each of the next n lines contains m characters "B" or "W". Character "B" denotes a black cell of the grid and "W" denotes a white cell of the grid. It's guaranteed that the grid has at least one black cell. | 1,700 | On the only line of the output print "YES" if the grid is convex, otherwise print "NO". Do not print quotes. | standard output | |
PASSED | 8c66c0023c1fb7d7890c5a54dc6ce51b | train_001.jsonl | 1361374200 | Consider an nβΓβm grid. Initially all the cells of the grid are colored white. Lenny has painted some of the cells (at least one) black. We call a painted grid convex if one can walk from any black cell to any another black cell using a path of side-adjacent black cells changing his direction at most once during the path. In the figure below, the left grid is convex while the right one is not convex, because there exist two cells which need more than one time to change direction in their path. You're given a painted grid in the input. Tell Lenny if the grid is convex or not. | 256 megabytes | import java.io.PrintWriter;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class Main{
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = s.nextInt();
int m = s.nextInt();
int map[][] = new int[n][m];
for (int i = 0; i < n; i++) {
String k = s.next();
for (int j = 0; j < m; j++) {
if(k.charAt(j)=='B')map[i][j] = 1;
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if(map[i][j] == 0) continue;
for (int i2 = 0; i2 < n; i2++) {
for (int j2 = 0; j2 < m; j2++) {
if(map[i2][j2] == 0) continue;
// System.out.printf("%d, %d to %d, %d : %d,%d %d,%d\n", i,j, i2, j2, i,j2, i2, j);
int way = 0;
if(i == 0 && j == 3 && i2 == 3 && j2 == 3){
way = 0;
}
// (i,j) to (i, j2)
int bad = 0;
int x = i;
int y = j2;
int dir = j < j2 ? - 1 : 1;
while(y != j){
if(map[x][y] == 0){
bad++;
break;
}
y += dir;
}
// (i2, j2) to (i,j2)
x = i;
y = j2;
dir = i < i2 ? 1 : -1;
while(x != i2){
if(map[x][y] == 0){
bad++;
break;
}
x+=dir;
}
if(bad == 0) way++;
bad = 0;
// (i, j) to (i2, j)
x = i2;
y = j;
dir = i < i2 ? -1 : 1;
while(x != i){
if(map[x][y] == 0){
bad++;
break;
}
x += dir;
}
// (i2, j2) to (i2, j)
x = i2;
y = j;
dir = j < j2 ? 1:-1;
while(y != j2){
if(map[x][y] == 0){
bad++;
break;
}
y += dir;
}
if(bad == 0)way++;
// if(i == 0 && j == 3 && i2 == 3 && j2 == 3)
// System.out.printf("%d, %d to %d, %d : %d,%d %d,%d way: %d\n", i,j, i2, j2, i,j2, i2, j,way);
if(way == 0){
System.out.println("NO");
return ;
}
}
}
}
}
System.out.println("YES");
}
}
| Java | ["3 4\nWWBW\nBWWW\nWWWB", "3 1\nB\nB\nW"] | 2 seconds | ["NO", "YES"] | null | Java 6 | standard input | [
"constructive algorithms",
"implementation"
] | 3631eba1b28fae473cf438bc2f0552b7 | The first line of the input contains two integers n and m (1ββ€βn,βmββ€β50) β the size of the grid. Each of the next n lines contains m characters "B" or "W". Character "B" denotes a black cell of the grid and "W" denotes a white cell of the grid. It's guaranteed that the grid has at least one black cell. | 1,700 | On the only line of the output print "YES" if the grid is convex, otherwise print "NO". Do not print quotes. | standard output | |
PASSED | e3449c7bd005e65e8a9274ef832e7c66 | train_001.jsonl | 1361374200 | Consider an nβΓβm grid. Initially all the cells of the grid are colored white. Lenny has painted some of the cells (at least one) black. We call a painted grid convex if one can walk from any black cell to any another black cell using a path of side-adjacent black cells changing his direction at most once during the path. In the figure below, the left grid is convex while the right one is not convex, because there exist two cells which need more than one time to change direction in their path. You're given a painted grid in the input. Tell Lenny if the grid is convex or not. | 256 megabytes | import java.awt.Point;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Properties;
import java.util.Stack;
/**
* Works good for CF
*
* @author cykeltillsalu
*/
public class B {
// some local config
static boolean test = false;
static String testDataFile = "testdata.txt";
static String feedFile = "feed.txt";
CompetitionType type = CompetitionType.CF;
private static String ENDL = "\n";
// solution
private void solve() throws Throwable {
int n = iread(), m = iread();
boolean[][] grid = new boolean[n][m];
boolean[][] dfs = new boolean[n][m];
for (int i = 0; i < n; i++) {
String wrd = wread();
for (int j = 0; j < wrd.length(); j++) {
grid[i][j] = wrd.charAt(j) == 'B';
}
}
for (int i = 0; i < n; i++) {
int cnt = 0;
boolean b = false;
for (int j = 0; j < m; j++) {
if (!b && grid[i][j]) {
b = true;
cnt++;
}
if (!grid[i][j]) {
b = false;
}
}
if (cnt > 1) {
System.out.println("NO");
return;
}
}
for (int j = 0; j < m; j++) {
int cnt = 0;
boolean b = false;
for (int i = 0; i < n; i++) {
if (!b && grid[i][j]) {
b = true;
cnt++;
}
if (!grid[i][j]) {
b = false;
}
}
if (cnt > 1) {
System.out.println("NO");
return;
}
}
for (int startx = 0; startx < m; startx++) {
for (int starty = 0; starty < n; starty++) {
boolean[][] walk = new boolean[n][m];
if (!grid[starty][startx]) {
continue;
}
walk[starty][startx] = true;
for (int x = 0; x < m; x++) {
if(!grid[starty][x]){
continue;
}
for (int y = 0; y < n; y++) {
if(!grid[y][x]){
continue;
}
walk[y][x] = true;
}
}
for (int y = 0; y < n; y++) {
if(!grid[y][startx]){
continue;
}
for (int x = 0; x < m; x++) {
if(!grid[y][x]){
continue;
}
walk[y][x] = true;
}
}
for (int i = starty; i < n; i++) {
for (int j = startx; j < m; j++) {
if (i != starty || j != startx) {
if (i > 0) {
walk[i][j] = walk[i][j] || walk[i - 1][j];
}
}
}
}
for (int endx = 0; endx < m; endx++) {
for (int endy = 0; endy < n; endy++) {
if (startx == endx && starty == endy) {
continue;
}
if (grid[starty][startx] && grid[endy][endx]) {
if (!walk[endy][endx]) {
System.out.println("NO");
return;
}
}
}
}
}
}
System.out.println("YES");
out.flush();
}
public int iread() throws Exception {
return Integer.parseInt(wread());
}
public double dread() throws Exception {
return Double.parseDouble(wread());
}
public long lread() throws Exception {
return Long.parseLong(wread());
}
public String wread() throws IOException {
StringBuilder b = new StringBuilder();
int c;
c = in.read();
while (c >= 0 && c <= ' ')
c = in.read();
if (c < 0)
return "";
while (c > ' ') {
b.append((char) c);
c = in.read();
}
return b.toString();
}
public static void main(String[] args) throws Throwable {
if (test) { // run all cases from testfile:
BufferedReader testdataReader = new BufferedReader(new FileReader(testDataFile));
String readLine = testdataReader.readLine();
int casenr = 0;
out: while (true) {
BufferedWriter w = new BufferedWriter(new FileWriter(feedFile));
if (!readLine.equalsIgnoreCase("input")) {
break;
}
while (true) {
readLine = testdataReader.readLine();
if (readLine.equalsIgnoreCase("output")) {
break;
}
w.write(readLine + "\n");
}
w.close();
System.out.println("Answer on case " + (++casenr) + ": ");
new B().solve();
System.out.println("Expected answer: ");
while (true) {
readLine = testdataReader.readLine();
if (readLine == null) {
break out;
}
if (readLine.equalsIgnoreCase("input")) {
break;
}
System.out.println(readLine);
}
System.out.println("----------------");
}
testdataReader.close();
} else { // run on server
new B().solve();
}
out.close();
}
public B() throws Throwable {
if (test) {
in = new BufferedReader(new FileReader(new File(feedFile)));
}
}
InputStreamReader inp = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(inp);
static BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out));
enum CompetitionType {
CF, OTHER
};
} | Java | ["3 4\nWWBW\nBWWW\nWWWB", "3 1\nB\nB\nW"] | 2 seconds | ["NO", "YES"] | null | Java 6 | standard input | [
"constructive algorithms",
"implementation"
] | 3631eba1b28fae473cf438bc2f0552b7 | The first line of the input contains two integers n and m (1ββ€βn,βmββ€β50) β the size of the grid. Each of the next n lines contains m characters "B" or "W". Character "B" denotes a black cell of the grid and "W" denotes a white cell of the grid. It's guaranteed that the grid has at least one black cell. | 1,700 | On the only line of the output print "YES" if the grid is convex, otherwise print "NO". Do not print quotes. | standard output |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.