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
309fc6d092383fc96c7e8b1fc970a8f4
train_003.jsonl
1522850700
Magnus decided to play a classic chess game. Though what he saw in his locker shocked him! His favourite chessboard got broken into 4 pieces, each of size n by n, n is always odd. And what's even worse, some squares were of wrong color. j-th square of the i-th row of k-th piece of the board has color ak, i, j; 1 being black and 0 being white. Now Magnus wants to change color of some squares in such a way that he recolors minimum number of squares and obtained pieces form a valid chessboard. Every square has its color different to each of the neightbouring by side squares in a valid board. Its size should be 2n by 2n. You are allowed to move pieces but not allowed to rotate or flip them.
256 megabytes
import java.util.Scanner; public class codeforces { public static void main(String[] args){ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int[] arr = new int[8]; char c='0'; int ans=0; for (int k=0;k<4;k++) { for (int i = 0; i < n; i++) { String t = sc.next(); for (int j = 0; j < n; j++) { if (t.charAt(j) == c) { ans++; } if (c == '0') c = '1'; else c = '0'; } } arr[k]=ans; arr[k+4]=n*n-ans; ans=0; c='0'; } ans = Math.min(arr[0]+arr[1]+arr[6]+arr[7],arr[0]+arr[2]+arr[5]+arr[7]); ans = Math.min(ans,arr[0]+arr[3]+arr[5]+arr[6]); ans = Math.min(ans,arr[1]+arr[2]+arr[4]+arr[7]); ans = Math.min(ans,arr[1]+arr[3]+arr[4]+arr[6]); ans = Math.min(ans,arr[2]+arr[3]+arr[4]+arr[5]); System.out.print(ans); } }
Java
["1\n0\n\n0\n\n1\n\n0", "3\n101\n010\n101\n\n101\n000\n101\n\n010\n101\n011\n\n010\n101\n010"]
1 second
["1", "2"]
null
Java 8
standard input
[ "implementation", "bitmasks", "brute force" ]
dc46c6cb6b4b9b5e7e6e5b4b7d034874
The first line contains odd integer n (1 ≤ n ≤ 100) — the size of all pieces of the board. Then 4 segments follow, each describes one piece of the board. Each consists of n lines of n characters; j-th one of i-th line is equal to 1 if the square is black initially and 0 otherwise. Segments are separated by an empty line.
1,400
Print one number — minimum number of squares Magnus should recolor to be able to obtain a valid chessboard.
standard output
PASSED
b80a6fa9f82250e65a95d3ac16da07fd
train_003.jsonl
1522850700
Magnus decided to play a classic chess game. Though what he saw in his locker shocked him! His favourite chessboard got broken into 4 pieces, each of size n by n, n is always odd. And what's even worse, some squares were of wrong color. j-th square of the i-th row of k-th piece of the board has color ak, i, j; 1 being black and 0 being white. Now Magnus wants to change color of some squares in such a way that he recolors minimum number of squares and obtained pieces form a valid chessboard. Every square has its color different to each of the neightbouring by side squares in a valid board. Its size should be 2n by 2n. You are allowed to move pieces but not allowed to rotate or flip them.
256 megabytes
//package temp; import java.util.*; public class Main { static final int maxn = 110; static final int dead = 0x7f7f7f7f; public static void main(String[] args) { Scanner in = new Scanner(System.in); int[] cout=new int[5]; int n=in.nextInt(); String temp; for(int i=1;i<=4;i++){ for(int j=1;j<=n;j++) { temp=in.next(); for(int k=0;k<=n-1;k++) { if(temp.charAt(k)=='0'&&((j-1)*n+k+1)%2==1) cout[i]++; else if(temp.charAt(k)=='1'&&((j-1)*n+k+1)%2==0) cout[i]++; } } } int mi=dead; int sum=cout[1]+cout[2]+cout[3]+cout[4]; for(int i=1;i<4;i++) { for(int j=i+1;j<=4;j++) { mi=Math.min(sum-cout[i]-cout[j]+n*n-cout[i]+n*n-cout[j], mi); } } System.out.println(mi); } }
Java
["1\n0\n\n0\n\n1\n\n0", "3\n101\n010\n101\n\n101\n000\n101\n\n010\n101\n011\n\n010\n101\n010"]
1 second
["1", "2"]
null
Java 8
standard input
[ "implementation", "bitmasks", "brute force" ]
dc46c6cb6b4b9b5e7e6e5b4b7d034874
The first line contains odd integer n (1 ≤ n ≤ 100) — the size of all pieces of the board. Then 4 segments follow, each describes one piece of the board. Each consists of n lines of n characters; j-th one of i-th line is equal to 1 if the square is black initially and 0 otherwise. Segments are separated by an empty line.
1,400
Print one number — minimum number of squares Magnus should recolor to be able to obtain a valid chessboard.
standard output
PASSED
56044acb40a8b2146737af6613227dae
train_003.jsonl
1522850700
Magnus decided to play a classic chess game. Though what he saw in his locker shocked him! His favourite chessboard got broken into 4 pieces, each of size n by n, n is always odd. And what's even worse, some squares were of wrong color. j-th square of the i-th row of k-th piece of the board has color ak, i, j; 1 being black and 0 being white. Now Magnus wants to change color of some squares in such a way that he recolors minimum number of squares and obtained pieces form a valid chessboard. Every square has its color different to each of the neightbouring by side squares in a valid board. Its size should be 2n by 2n. You are allowed to move pieces but not allowed to rotate or flip them.
256 megabytes
import java.io.*; import java.util.*; import java.lang.*; public class templ { public static void main(String[] args) throws FileNotFoundException { try { InputReader in = new InputReader(System.in); PrintWriter out = new PrintWriter(System.out); int n=in.nextInt(); int min[]=new int[4]; int i,j,k,temp,x=0; String t=""; for(i=0;i<=3;i++) { for(k=0;k<n;k++) { t=in.nextLine(); for(j=0;j<n;j++) { temp=(int)t.charAt(j)-48; //out.println(temp+" "+i+" "+j); if(((k*3+j)%2==0 && temp==0)||((k*3+j)%2==1 && temp==1)) x++; } } min[i]=x; x=0; } int ans=0; if(n%2==1) { sort(min,0,3); ans=min[0]+min[1]+(2*n*n-min[2]-min[3]); } else { ans=min[0]+min[1]+min[2]+min[3]; ans=Math.min(ans,4*n*n-ans); } out.println(ans); out.close(); } catch(Exception e){ } } public static void merge(int arr[], int l, int m, int r) { int n1 = m - l + 1; int n2 = r - m; int L[] = new int [n1]; int R[] = new int [n2]; for (int i=0; i<n1; ++i) L[i] = arr[l + i]; for (int j=0; j<n2; ++j) R[j] = arr[m + 1+ j]; int i = 0, j = 0; int k = l; while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } while (i < n1) { arr[k] = L[i]; i++; k++; } while (j < n2) { arr[k] = R[j]; j++; k++; } } public static void sort(int arr[], int l, int r) { if (l < r) { int m = (l+r)/2; sort(arr, l, m); sort(arr , m+1, r); merge(arr, l, m, r); } } static class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar, snumChars; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } public String readString() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public String nextLine() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } } }
Java
["1\n0\n\n0\n\n1\n\n0", "3\n101\n010\n101\n\n101\n000\n101\n\n010\n101\n011\n\n010\n101\n010"]
1 second
["1", "2"]
null
Java 8
standard input
[ "implementation", "bitmasks", "brute force" ]
dc46c6cb6b4b9b5e7e6e5b4b7d034874
The first line contains odd integer n (1 ≤ n ≤ 100) — the size of all pieces of the board. Then 4 segments follow, each describes one piece of the board. Each consists of n lines of n characters; j-th one of i-th line is equal to 1 if the square is black initially and 0 otherwise. Segments are separated by an empty line.
1,400
Print one number — minimum number of squares Magnus should recolor to be able to obtain a valid chessboard.
standard output
PASSED
3f1ead9a7436620d51066c9b5bf8a516
train_003.jsonl
1522850700
Magnus decided to play a classic chess game. Though what he saw in his locker shocked him! His favourite chessboard got broken into 4 pieces, each of size n by n, n is always odd. And what's even worse, some squares were of wrong color. j-th square of the i-th row of k-th piece of the board has color ak, i, j; 1 being black and 0 being white. Now Magnus wants to change color of some squares in such a way that he recolors minimum number of squares and obtained pieces form a valid chessboard. Every square has its color different to each of the neightbouring by side squares in a valid board. Its size should be 2n by 2n. You are allowed to move pieces but not allowed to rotate or flip them.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.InputMismatchException; import java.util.StringTokenizer; /* * * daiict * * * */ public class pprac { FastScanner in; PrintWriter out; static int countc = 0; static int minm = countc; static ArrayList[] adj; static ArrayList[] aadj; static int last; static int n; static int m; static int[] dp1; static int[] dp2; static int color[]; static int visited[]; static int[] arr; static long[] brr; static double ans; static int array[]; static int start[]; static int finish[]; static int pref[]; static int tree[]; static int maxval = 32; static int ttt[]; static int sum = 0; static String s; static int cc = 0; static long min = Long.MAX_VALUE; static ArrayList<Integer> segt[]; // for dfs do not delete static int dir[][] = { { 1, 0 }, { 0, 1 }, { 0, -1 }, { -1, 0 } }; static int[] seg; static long count = 1; static long mod = (long) 1e9 + 7; static int parent[]; static int size[]; static int[] l; static int[] r; static int[] next; static int[] cnt; static int[] block; static int bblock = 1001; static HashSet<String> set; static HashSet<String> set2; static int low[]; static int disc[]; static int time; static int acn[]; static HashMap<Long, Integer> map; static class Pair implements Comparable<Pair> { int x; int y; int i; Pair(int l, int m, int i) { this.x = l; this.y = m; this.i = i; } public int compareTo(Pair p) { if (this.x / bblock == p.x / bblock) { return (int) (this.y - p.y); } return (int) (this.x / bblock - p.x / bblock); } public String toString() { return x + " " + y; } public boolean equals(Object o) { if (o instanceof Pair) { Pair a = (Pair) o; return this.x == a.x; } return false; } public int hashCode() { return new Long(x).hashCode() * 31 + new Long(y).hashCode(); } } public static int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } void build(int n) { // build the tree for (int i = n - 1; i > 0; --i) seg[i] = Math.min(seg[i << 1], seg[i << 1 | 1]); } public static void modify(int p, int val, int n) { // set value at position // p for (seg[p += n] = val; p > 1; p >>= 1) seg[p >> 1] = Math.min(seg[p], seg[p ^ 1]); } int query(int l, int r, int n) { // sum on interval [l, r) int res = Integer.MAX_VALUE; if (l > r) { return res; } for (l += n, r += n; l < r; l >>= 1, r >>= 1) { if ((l & 1) == 1) res = Math.min(res, seg[l++]); if ((r & 1) == 1) res = Math.min(res, seg[--r]); } return res; } // public static void update(int x,int val){ // while(x<=maxval){ // tree[x] += val; // x = (x&-x); // } // } public static int read(int idx) { int sum = 0; while (idx >= 0) { sum += tree[idx]; idx -= (idx & (-idx)); } return sum; } public static int find(int i) { if (parent[i] != i) { return find(parent[i]); } return i; } public static void union(int a, int b) { int x = find(a); int y = find(b); if (x != y) { if (size[x] > size[y]) { size[x] += size[y]; parent[y] = x; } else { size[y] += size[x]; parent[x] = y; } } } /* static */ void solve() throws NumberFormatException, InputMismatchException, IOException { // Scanner in = new Scanner(System.in); int n = in.nextInt(); String a[] = new String[n]; String b[] = new String[n]; String c[] = new String[n]; String d[] = new String[n]; for (int i = 0; i < n; i++) { a[i] = in.next(); } for (int i = 0; i < n; i++) { b[i] = in.next(); } for (int i = 0; i < n; i++) { c[i] = in.next(); } for (int i = 0; i < n; i++) { d[i] = in.next(); } int max = Integer.MAX_VALUE; for (int i = 1; i <= 4; i++) { for (int j = 1; j <= 4; j++) { if (i == j) { continue; } for (int k = 1; k <= 4; k++) { if (k == j || k == i) { continue; } for (int r = 1; r <= 4; r++) { if (r == i || r == j || r == k) { continue; } char arr[][] = new char[2 * n][2 * n]; if (i == 1) { for (int ii = 0; ii < n; ii++) { for (int jj = 0; jj < n; jj++) { arr[ii][jj] = a[ii].charAt(jj); } } } else if (i == 2) { for (int ii = 0; ii < n; ii++) { for (int jj = 0; jj < n; jj++) { arr[ii][jj + n] = a[ii].charAt(jj); } } } else if (i == 3) { for (int ii = 0; ii < n; ii++) { for (int jj = 0; jj < n; jj++) { arr[ii + n][jj] = a[ii].charAt(jj); } } } else if (i == 4) { for (int ii = 0; ii < n; ii++) { for (int jj = 0; jj < n; jj++) { arr[ii + n][jj + n] = a[ii].charAt(jj); } } } // j if (j == 1) { for (int ii = 0; ii < n; ii++) { for (int jj = 0; jj < n; jj++) { arr[ii][jj] = b[ii].charAt(jj); } } } else if (j == 2) { for (int ii = 0; ii < n; ii++) { for (int jj = 0; jj < n; jj++) { arr[ii][jj + n] = b[ii].charAt(jj); } } } else if (j == 3) { for (int ii = 0; ii < n; ii++) { for (int jj = 0; jj < n; jj++) { arr[ii + n][jj] = b[ii].charAt(jj); } } } else if (j == 4) { for (int ii = 0; ii < n; ii++) { for (int jj = 0; jj < n; jj++) { arr[ii + n][jj + n] = b[ii].charAt(jj); } } } // k if (k == 1) { for (int ii = 0; ii < n; ii++) { for (int jj = 0; jj < n; jj++) { arr[ii][jj] = c[ii].charAt(jj); } } } else if (k == 2) { for (int ii = 0; ii < n; ii++) { for (int jj = 0; jj < n; jj++) { arr[ii][jj + n] = c[ii].charAt(jj); } } } else if (k == 3) { for (int ii = 0; ii < n; ii++) { for (int jj = 0; jj < n; jj++) { arr[ii + n][jj] = c[ii].charAt(jj); } } } else if (k == 4) { for (int ii = 0; ii < n; ii++) { for (int jj = 0; jj < n; jj++) { arr[ii + n][jj + n] = c[ii].charAt(jj); } } } // r if (r == 1) { for (int ii = 0; ii < n; ii++) { for (int jj = 0; jj < n; jj++) { arr[ii][jj] = d[ii].charAt(jj); } } } else if (r == 2) { for (int ii = 0; ii < n; ii++) { for (int jj = 0; jj < n; jj++) { arr[ii][jj + n] = d[ii].charAt(jj); } } } else if (r == 3) { for (int ii = 0; ii < n; ii++) { for (int jj = 0; jj < n; jj++) { arr[ii + n][jj] = d[ii].charAt(jj); } } } else if (r == 4) { for (int ii = 0; ii < n; ii++) { for (int jj = 0; jj < n; jj++) { arr[ii + n][jj + n] = d[ii].charAt(jj); } } } int cc = call(arr); max = Math.min(cc, max); } } } } out.println(max); } public static int call(char arr[][]) { int cc = 0; char temp[][] = new char[arr.length][arr.length]; char c = '0'; for (int i = 0; i < arr.length; i++) { c = (c == '0') ? '1' : '0'; for (int j = 0; j < arr.length; j++) { temp[i][j] = c; c = (c == '0') ? '1' : '0'; // System.out.print(temp[i][j]); } //System.out.println(); } int n = arr.length; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (arr[i][j] != temp[i][j]) { cc++; } } } int dd = cc; cc = 0; c = '1'; for (int i = 0; i < arr.length; i++) { c = (c == '0') ? '1' : '0'; for (int j = 0; j < arr.length; j++) { temp[i][j] = c; c = (c == '0') ? '1' : '0'; } } n = arr.length; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (arr[i][j] != temp[i][j]) { cc++; } } } return Math.min(cc, dd); } public static HashSet<Integer> call(int a) { HashSet<Integer> list = new HashSet(); while (a % 2 == 0) { list.add(2); a /= 2; } int n = a; for (int i = 3; i <= n; i += 2) { while (a % i == 0) { list.add(i); a = a / i; } } if (a > 2) { list.add(a); } return list; } public static String reverse(String s) { String ans = ""; for (int i = s.length() - 1; i >= 0; i--) { ans += s.charAt(i); } return ans; } public static long sum(long x) { return x < 10 ? x : x % 10 + sum(x / 10); } public static long gcd(long x, long y) { if (x == 0) return y; else return gcd(y % x, x); } static long inv(long x, long mod) { long r, y; for (r = 1, y = mod - 2; y != 0; x = x * x % mod, y >>= 1) { if ((y & 1) == 1) r = r * x % mod; } return r; } public static long pow(long x, long y, long n) { if (y == 0) return 1 % n; if (y % 2 == 0) { long z = pow(x, y / 2, n); return (z * z) % n; } return ((x % n) * pow(x, y - 1, n)) % n; } public static boolean isPrime(long a) { // Corner cases if (a <= 1) return false; if (a <= 3) return true; // This is checked so that we can skip // middle five numbers in below loop if (a % 2 == 0 || a % 3 == 0) return false; for (long i = 5; i * i <= a; i = i + 6) if (a % i == 0 || a % (i + 2) == 0) return false; return true; } void run() throws NumberFormatException, InputMismatchException, IOException { in = new FastScanner(); out = new PrintWriter(System.out); solve(); out.close(); } class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(in.br.readLine()); } catch (IOException e) { // TODO Auto-generated catch block 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[] args) throws NumberFormatException, InputMismatchException, IOException { // new Thread(null ,new Runnable(){ // public void run(){ // try{ // // test(); // // } catch(Exception e){ // e.printStackTrace(); // } // } // },"1",1<<26).start(); // } // static StringBuilder sb; // public static void test() throws IOException{ // sb=new StringBuilder(); // int t=1; // while(t-->0){ // // solve(); // // } // new pprac().run(); } } class Node { int a; int b; public Node(int i, int j) { this.a = i; this.b = j; } } class MyComp implements Comparator<String> { int c = 0; MyComp(int d) { c = d; } @Override public int compare(String a, String b) { // < == -1 String arr[] = a.split(" "); String brr[] = b.split(" "); return arr[c].compareTo(brr[c]); } } class MyComp2 implements Comparator<Node> { @Override public int compare(Node a, Node b) { // < == -1 if (a.b > b.b) { return -1; } else { return 1; } } }
Java
["1\n0\n\n0\n\n1\n\n0", "3\n101\n010\n101\n\n101\n000\n101\n\n010\n101\n011\n\n010\n101\n010"]
1 second
["1", "2"]
null
Java 8
standard input
[ "implementation", "bitmasks", "brute force" ]
dc46c6cb6b4b9b5e7e6e5b4b7d034874
The first line contains odd integer n (1 ≤ n ≤ 100) — the size of all pieces of the board. Then 4 segments follow, each describes one piece of the board. Each consists of n lines of n characters; j-th one of i-th line is equal to 1 if the square is black initially and 0 otherwise. Segments are separated by an empty line.
1,400
Print one number — minimum number of squares Magnus should recolor to be able to obtain a valid chessboard.
standard output
PASSED
d8cd1532f6825bb5ac93fb573093a480
train_003.jsonl
1522850700
Magnus decided to play a classic chess game. Though what he saw in his locker shocked him! His favourite chessboard got broken into 4 pieces, each of size n by n, n is always odd. And what's even worse, some squares were of wrong color. j-th square of the i-th row of k-th piece of the board has color ak, i, j; 1 being black and 0 being white. Now Magnus wants to change color of some squares in such a way that he recolors minimum number of squares and obtained pieces form a valid chessboard. Every square has its color different to each of the neightbouring by side squares in a valid board. Its size should be 2n by 2n. You are allowed to move pieces but not allowed to rotate or flip them.
256 megabytes
//package com.company; import java.util.Scanner; import static java.lang.Math.min; public class Main { public static void main(String[] args) { int n; Scanner sc = new Scanner(System.in); n = sc.nextInt(); String s[][] = new String[4][n]; for (int i = 0; i < 4; i++) { for(int j = 0; j < n; j++) { s[i][j] = sc.next(); } } int cnt[][] = new int[4][2]; for (int i = 0; i < 4; i++) { for(int c = 0; c < 2; c++) { for (int j = 0; j < n; j++) { for (int k = 0; k < n; k++) { if((int)s[i][j].charAt(k) - (int)'0' != (c + j*n + k) % 2 ){ cnt[i][c]++; } } } // System.out.println(cnt[i][c]); } } int res = 4*n*n; for(int i = 0; i < (1 << 4); i++) { if(Integer.bitCount(i) == 2) { int x = i, temp = 0, t = 0; while(t < 4) { temp += cnt[t][x%2]; x /= 2; t++; } res = min(res, temp); } } System.out.println(res); } }
Java
["1\n0\n\n0\n\n1\n\n0", "3\n101\n010\n101\n\n101\n000\n101\n\n010\n101\n011\n\n010\n101\n010"]
1 second
["1", "2"]
null
Java 8
standard input
[ "implementation", "bitmasks", "brute force" ]
dc46c6cb6b4b9b5e7e6e5b4b7d034874
The first line contains odd integer n (1 ≤ n ≤ 100) — the size of all pieces of the board. Then 4 segments follow, each describes one piece of the board. Each consists of n lines of n characters; j-th one of i-th line is equal to 1 if the square is black initially and 0 otherwise. Segments are separated by an empty line.
1,400
Print one number — minimum number of squares Magnus should recolor to be able to obtain a valid chessboard.
standard output
PASSED
d2f36f307a4fc5782a97c04e5c1ad139
train_003.jsonl
1522850700
Magnus decided to play a classic chess game. Though what he saw in his locker shocked him! His favourite chessboard got broken into 4 pieces, each of size n by n, n is always odd. And what's even worse, some squares were of wrong color. j-th square of the i-th row of k-th piece of the board has color ak, i, j; 1 being black and 0 being white. Now Magnus wants to change color of some squares in such a way that he recolors minimum number of squares and obtained pieces form a valid chessboard. Every square has its color different to each of the neightbouring by side squares in a valid board. Its size should be 2n by 2n. You are allowed to move pieces but not allowed to rotate or flip them.
256 megabytes
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.Writer; import java.util.Arrays; import java.util.StringTokenizer; public class Solution { static InputReader in = new InputReader(System.in); static OutputWriter out = new OutputWriter(System.out); static int exp = (int) (1e9); private static int getSingleBoardChanges(char[][] board, int size, char first, char second) { int changes = 0; for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { if (((i & 1) == 0 && (j & 1) == 0) || ((i & 1) == 1 && (j & 1) == 1)) { if (board[i][j] == first) { changes++; } } else if (board[i][j] == second) { changes++; } } } return changes; } private static Pair getChanges(char[][] board, int n) { return new Pair(getSingleBoardChanges(board, n, '1', '0'), getSingleBoardChanges(board, n, '0', '1')); } public static void main(String[] args) { Board[] boards = new Board[4]; int n = in.nextInt(); for (int i = 0; i < 4; i++) { char[][] mat = new char[n][n]; for (int j = 0; j < n; j++) { mat[j] = in.readLine().toCharArray(); } if (i < 3) { in.readLine(); } boards[i] = new Board(mat); } Pair p0 = getChanges(boards[0].board, n); Pair p1 = getChanges(boards[1].board, n); Pair p2 = getChanges(boards[2].board, n); Pair p3 = getChanges(boards[3].board, n); int[] scores = new int[6]; scores[0] = p0.white + p1.white + p2.black + p3.black; scores[1] = p0.white + p2.white + p1.black + p3.black; scores[2] = p0.white + p3.white + p1.black + p2.black; scores[3] = p1.white + p2.white + p0.black + p3.black; scores[4] = p1.white + p3.white + p0.black + p2.black; scores[5] = p2.white + p3.white + p0.black + p1.black; int res = Integer.MAX_VALUE; for (Integer v : scores) { res = Math.min(res, v); } System.out.println(res); } } class Board { char[][] board; Board(char[][] board) { this.board = board; } @Override public String toString() { return "Board [board=" + Arrays.deepToString(board) + "]"; } }; class Pair { int white; int black; public Pair(int white, int black) { super(); this.white = white; this.black = black; } @Override public String toString() { return "Pair [white=" + white + ", black=" + black + "]"; } }; class OutputWriter { public PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.print(objects[i]); } } public void println(Object... objects) { print(objects); writer.println(); } public void close() { writer.close(); } } class InputReader { private BufferedReader reader; private StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public String readLine() { try { return reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } } public char nextChar() { return next().charAt(0); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public float nextFloat() { return Float.parseFloat(next()); } }
Java
["1\n0\n\n0\n\n1\n\n0", "3\n101\n010\n101\n\n101\n000\n101\n\n010\n101\n011\n\n010\n101\n010"]
1 second
["1", "2"]
null
Java 8
standard input
[ "implementation", "bitmasks", "brute force" ]
dc46c6cb6b4b9b5e7e6e5b4b7d034874
The first line contains odd integer n (1 ≤ n ≤ 100) — the size of all pieces of the board. Then 4 segments follow, each describes one piece of the board. Each consists of n lines of n characters; j-th one of i-th line is equal to 1 if the square is black initially and 0 otherwise. Segments are separated by an empty line.
1,400
Print one number — minimum number of squares Magnus should recolor to be able to obtain a valid chessboard.
standard output
PASSED
790fe0a9c5dc6304bb0c38af403c9c65
train_003.jsonl
1522850700
Magnus decided to play a classic chess game. Though what he saw in his locker shocked him! His favourite chessboard got broken into 4 pieces, each of size n by n, n is always odd. And what's even worse, some squares were of wrong color. j-th square of the i-th row of k-th piece of the board has color ak, i, j; 1 being black and 0 being white. Now Magnus wants to change color of some squares in such a way that he recolors minimum number of squares and obtained pieces form a valid chessboard. Every square has its color different to each of the neightbouring by side squares in a valid board. Its size should be 2n by 2n. You are allowed to move pieces but not allowed to rotate or flip them.
256 megabytes
import java.io.*; import java.util.StringTokenizer; public class C { /********************************************************************************************** * DEBUG * **********************************************************************************************/ private interface InputType { int STANDARD = 0; int HARDCODE = 2; } private final static int INPUT_TYPE = InputType.STANDARD; private final static String[] HARDCODE_INPUT = { "1\n" + "0\n" + "\n" + "0\n" + "\n" + "1\n" + "\n" + "0", "3\n" + "000\n" + "000\n" + "000\n" + "\n" + "000\n" + "000\n" + "000\n" + "\n" + "111\n" + "111\n" + "111\n" + "\n" + "000\n" + "000\n" + "000", }; /********************************************************************************************** * MAIN * **********************************************************************************************/ private static class Solver { private static final int MIN = -999_999_999; private static final int MAX = 999_999_999; public void solve(Reader in, PrintWriter out) throws IOException { int n = in.nextInt(); char[][][] a = new char[4][n][]; for (int i = 0; i < 4; i++) { for (int j = 0; j < n; j++) { a[i][j] = in.nextWord().toCharArray(); } } int[][] check = new int[4][2]; for (int i = 0; i < 4; i++) { check[i][0] = check(a[i], '0'); check[i][1] = check(a[i], '1'); } out.print(pick(check, 0, 0, 0)); } private int pick(int[][] check, int one, int zero, int i) { if (one + zero == 4) return one == 2 ? 0 : MAX; return Math.min(check[i][0] + pick(check, one, zero + 1, i + 1), check[i][1] + pick(check, one + 1, zero, i + 1)); } private int check(char[][] a, char first) { int n = a.length; int res = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (a[i][j] != first) res++; first = next(first); } } return res; } private char next(char c) { return (char)('0' + (c - '0' + 1) % 2); } } /********************************************************************************************** * TEMPLATE * **********************************************************************************************/ public static void main(String[] args) throws IOException { PrintWriter out; Reader in; if (INPUT_TYPE == InputType.HARDCODE) { for (String s : HARDCODE_INPUT) { solveHardCode(s); } } else { // STANDARD in = new Reader(System.in); out = new PrintWriter(System.out); new Solver().solve(in, out); out.flush(); } } private static void solveHardCode(String input) throws IOException { // prepare Reader in = new Reader(new ByteArrayInputStream(input.getBytes())); PrintWriter out = new PrintWriter(System.out); out.println("===>>> INPUT"); out.println(input + "\n\n"); out.println("===>>> OUTPUT"); // solve long start = System.currentTimeMillis(); new Solver().solve(in, out); long end = System.currentTimeMillis(); // log out.println("\n"); out.println("==========="); out.println("Took: " + (end - start) + "ms"); out.println("===================================================================="); out.println(); out.println(); // flush out.flush(); } /** Reader **/ private static class Reader { private BufferedReader reader; private StringTokenizer tokenizer; public Reader(InputStream input) { reader = new BufferedReader( new InputStreamReader(input)); tokenizer = new StringTokenizer(""); } private String nextWord() throws IOException { while (!tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } private int nextInt() throws IOException { return Integer.parseInt(nextWord()); } private long nextLong() throws IOException { return Long.parseLong(nextWord()); } private double nextDouble() throws IOException { return Double.parseDouble(nextWord()); } } }
Java
["1\n0\n\n0\n\n1\n\n0", "3\n101\n010\n101\n\n101\n000\n101\n\n010\n101\n011\n\n010\n101\n010"]
1 second
["1", "2"]
null
Java 8
standard input
[ "implementation", "bitmasks", "brute force" ]
dc46c6cb6b4b9b5e7e6e5b4b7d034874
The first line contains odd integer n (1 ≤ n ≤ 100) — the size of all pieces of the board. Then 4 segments follow, each describes one piece of the board. Each consists of n lines of n characters; j-th one of i-th line is equal to 1 if the square is black initially and 0 otherwise. Segments are separated by an empty line.
1,400
Print one number — minimum number of squares Magnus should recolor to be able to obtain a valid chessboard.
standard output
PASSED
cf21b3d0e44c9db6eeb422ff85274049
train_003.jsonl
1522850700
Magnus decided to play a classic chess game. Though what he saw in his locker shocked him! His favourite chessboard got broken into 4 pieces, each of size n by n, n is always odd. And what's even worse, some squares were of wrong color. j-th square of the i-th row of k-th piece of the board has color ak, i, j; 1 being black and 0 being white. Now Magnus wants to change color of some squares in such a way that he recolors minimum number of squares and obtained pieces form a valid chessboard. Every square has its color different to each of the neightbouring by side squares in a valid board. Its size should be 2n by 2n. You are allowed to move pieces but not allowed to rotate or flip them.
256 megabytes
import java.util.Scanner; public class Solution { public static void main(String[] args){ Solution solution = new Solution(); solution.solve(); } private void solve() { Scanner in = new Scanner(System.in); int n = in.nextInt(); String[][] chess = new String[4][n]; int[][] r = new int[4][2]; int total1 = 0; for (int i = 0; i < 4; ++i){ for (int j = 0; j < n; ++j){ chess[i][j] = in.next(); } for (int j = 0; j < n; ++j){ for (int k = 0; k < n; ++k){ int c = chess[i][j].charAt(k) - '0'; r[i][0] += (j + k) % 2 == 0 ? c : 1 - c; r[i][1] += (j + k) % 2 == 0 ? 1 - c : c; } } total1 += r[i][1]; } int min = 40001; for (int i = 0; i < 3; ++i){ for (int j = i + 1; j < 4; ++j){ min = Math.min(min, r[i][0] + r[j][0] + total1 - r[i][1] - r[j][1]); } } System.out.println(min); } }
Java
["1\n0\n\n0\n\n1\n\n0", "3\n101\n010\n101\n\n101\n000\n101\n\n010\n101\n011\n\n010\n101\n010"]
1 second
["1", "2"]
null
Java 8
standard input
[ "implementation", "bitmasks", "brute force" ]
dc46c6cb6b4b9b5e7e6e5b4b7d034874
The first line contains odd integer n (1 ≤ n ≤ 100) — the size of all pieces of the board. Then 4 segments follow, each describes one piece of the board. Each consists of n lines of n characters; j-th one of i-th line is equal to 1 if the square is black initially and 0 otherwise. Segments are separated by an empty line.
1,400
Print one number — minimum number of squares Magnus should recolor to be able to obtain a valid chessboard.
standard output
PASSED
64832f88cfb69822db7838e743893543
train_003.jsonl
1522850700
Magnus decided to play a classic chess game. Though what he saw in his locker shocked him! His favourite chessboard got broken into 4 pieces, each of size n by n, n is always odd. And what's even worse, some squares were of wrong color. j-th square of the i-th row of k-th piece of the board has color ak, i, j; 1 being black and 0 being white. Now Magnus wants to change color of some squares in such a way that he recolors minimum number of squares and obtained pieces form a valid chessboard. Every square has its color different to each of the neightbouring by side squares in a valid board. Its size should be 2n by 2n. You are allowed to move pieces but not allowed to rotate or flip them.
256 megabytes
import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.Writer; import java.util.InputMismatchException; public class A3 { static int n; static int compare(char[][] x, char[][] y) { int count = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (x[i][j] != y[i][j]) { count++; } } } return count; } public static void main(String[] args) { InputReader in = new InputReader(System.in); OutputWriter out = new OutputWriter(System.out); n = in.readInt(); long ans = 0; char a[][] = new char[n][n]; char b[][] = new char[n][n]; char c[][] = new char[n][n]; char d[][] = new char[n][n]; char[][] first = new char[n][n]; char[][] second = new char[n][n]; int j = 0; while (j < n) { a[j] = in.readString().toCharArray(); j++; } j = 0; while (j < n) { b[j] = in.readString().toCharArray(); j++; } j = 0; while (j < n) { c[j] = in.readString().toCharArray(); j++; } j = 0; while (j < n) { d[j] = in.readString().toCharArray(); j++; } first[0][0] = '0'; if (n > 1) first[1][0] = '1'; for (j = 1; j < n; j++) { if (first[0][j - 1] == '0') { first[0][j] = '1'; } else { first[0][j] = '0'; } } if (n > 1) { for (j = 1; j < n; j++) { if (first[1][j - 1] == '0') { first[1][j] = '1'; } else { first[1][j] = '0'; } } } for (int i = 2; i < n; i++) { first[i] = first[i - 2]; } for (int i = 0; i < n; i++) { for (j = 0; j < n; j++) { if (first[i][j] == '0') { second[i][j] = '1'; } else { second[i][j] = '0'; } } } // for (int i = 0; i < n; i++) { // for (j = 0; j < n; j++) { // System.out.print(second[i][j] + " "); // } // System.out.println(); // } ans = Integer.MAX_VALUE; ans = Math.min(ans, compare(a, first) + compare(b, first) + compare(c, second) + compare(d, second)); ans = Math.min(ans, compare(a, first) + compare(c, first) + compare(b, second) + compare(d, second)); ans = Math.min(ans, compare(a, first) + compare(d, first) + compare(c, second) + compare(b, second)); ans = Math.min(ans, compare(c, first) + compare(b, first) + compare(a, second) + compare(d, second)); ans = Math.min(ans, compare(d, first) + compare(b, first) + compare(c, second) + compare(a, second)); ans = Math.min(ans, compare(c, first) + compare(d, first) + compare(a, second) + compare(b, second)); System.out.println(ans); out.close(); } private static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public long readLong() { int c = read(); while (isSpaceChar(c)) c = read(); long sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int 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(); StringBuffer res = new StringBuffer(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } static boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return readString(); } } private static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(outputStream); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.print(objects[i]); } } public void printLine(Object... objects) { print(objects); writer.println(); } public void close() { writer.close(); } } }
Java
["1\n0\n\n0\n\n1\n\n0", "3\n101\n010\n101\n\n101\n000\n101\n\n010\n101\n011\n\n010\n101\n010"]
1 second
["1", "2"]
null
Java 8
standard input
[ "implementation", "bitmasks", "brute force" ]
dc46c6cb6b4b9b5e7e6e5b4b7d034874
The first line contains odd integer n (1 ≤ n ≤ 100) — the size of all pieces of the board. Then 4 segments follow, each describes one piece of the board. Each consists of n lines of n characters; j-th one of i-th line is equal to 1 if the square is black initially and 0 otherwise. Segments are separated by an empty line.
1,400
Print one number — minimum number of squares Magnus should recolor to be able to obtain a valid chessboard.
standard output
PASSED
f6411430f4cb411b05ab19ca767e7727
train_003.jsonl
1522850700
Magnus decided to play a classic chess game. Though what he saw in his locker shocked him! His favourite chessboard got broken into 4 pieces, each of size n by n, n is always odd. And what's even worse, some squares were of wrong color. j-th square of the i-th row of k-th piece of the board has color ak, i, j; 1 being black and 0 being white. Now Magnus wants to change color of some squares in such a way that he recolors minimum number of squares and obtained pieces form a valid chessboard. Every square has its color different to each of the neightbouring by side squares in a valid board. Its size should be 2n by 2n. You are allowed to move pieces but not allowed to rotate or flip them.
256 megabytes
import java.io.*; import java.util.*; public class Question { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int n = sc.nextInt(); boolean[][] arrOne = new boolean[n][n]; boolean[][] arrTwo = new boolean[n][n]; boolean here = true; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { arrOne[i][j] = here; arrTwo[i][j] = !here; here = !here; } } boolean[][][] grids = new boolean[4][n][n]; for (int k = 0; k < 4; k++) { for (int i = 0; i < n; i++) { String input = sc.next(); for (int m = 0; m < n; m++) grids[k][i][m] = input.charAt(m) == '1'; } } ArrayList<Integer> arrMin = new ArrayList<>(); for (int k = 0; k < 4; k++) { int resOne = 0; int resTwo = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (grids[k][i][j] != arrOne[i][j]) { resOne++; } if (grids[k][i][j] != arrTwo[i][j]) { resTwo++; } } } arrMin.add(resOne); arrMin.add(resTwo); } int a = arrMin.get(0) + arrMin.get(2) + arrMin.get(5) + arrMin.get(7); int b = arrMin.get(1) + arrMin.get(3) + arrMin.get(4) + arrMin.get(6); int c = arrMin.get(0) + arrMin.get(3) + arrMin.get(5) + arrMin.get(6); int d = arrMin.get(1) + arrMin.get(2) + arrMin.get(4) + arrMin.get(7); int e = arrMin.get(1) + arrMin.get(2) + arrMin.get(6) + arrMin.get(5); int f = arrMin.get(0) + arrMin.get(3) + arrMin.get(4) + arrMin.get(7); int z = Math.min(Math.min(c, d),Math.min(e, f)); out.println(Math.min(z, Math.min(a, b))); out.flush(); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream System) { br = new BufferedReader(new InputStreamReader(System)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public String nextLine() throws IOException { return br.readLine(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public char nextChar() throws IOException { return next().charAt(0); } public Long nextLong() throws IOException { return Long.parseLong(next()); } public boolean ready() throws IOException { return br.ready(); } public void waitForInput() { for (long i = 0; i < 3e9; i++) ; } } } class Pair implements Comparable<Pair> { int a; int b; public Pair(int a, int b) { this.a = a; this.b = b; } @Override public int compareTo(Pair o) { // TODO Auto-generated method stub return this.a - o.a; } }
Java
["1\n0\n\n0\n\n1\n\n0", "3\n101\n010\n101\n\n101\n000\n101\n\n010\n101\n011\n\n010\n101\n010"]
1 second
["1", "2"]
null
Java 8
standard input
[ "implementation", "bitmasks", "brute force" ]
dc46c6cb6b4b9b5e7e6e5b4b7d034874
The first line contains odd integer n (1 ≤ n ≤ 100) — the size of all pieces of the board. Then 4 segments follow, each describes one piece of the board. Each consists of n lines of n characters; j-th one of i-th line is equal to 1 if the square is black initially and 0 otherwise. Segments are separated by an empty line.
1,400
Print one number — minimum number of squares Magnus should recolor to be able to obtain a valid chessboard.
standard output
PASSED
29c8c1bde7bda6bde6128f44522dacfc
train_003.jsonl
1522850700
Magnus decided to play a classic chess game. Though what he saw in his locker shocked him! His favourite chessboard got broken into 4 pieces, each of size n by n, n is always odd. And what's even worse, some squares were of wrong color. j-th square of the i-th row of k-th piece of the board has color ak, i, j; 1 being black and 0 being white. Now Magnus wants to change color of some squares in such a way that he recolors minimum number of squares and obtained pieces form a valid chessboard. Every square has its color different to each of the neightbouring by side squares in a valid board. Its size should be 2n by 2n. You are allowed to move pieces but not allowed to rotate or flip them.
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.stream.IntStream; import java.util.Arrays; import java.io.BufferedWriter; import java.util.InputMismatchException; import java.io.IOException; import java.util.stream.Collectors; import java.util.ArrayList; import java.util.List; import java.util.stream.Stream; import java.io.Writer; import java.io.OutputStreamWriter; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author dmytro.prytula prituladima@gmail.com */ 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); LSHahmatnayaDoska solver = new LSHahmatnayaDoska(); solver.solve(1, in, out); out.close(); } static class LSHahmatnayaDoska { int n; int ans = 0; int INF = Integer.MAX_VALUE; int[] a; List<List<Integer>> perm = new ArrayList<>(); public void solve(int testNumber, InputReader in, OutputWriter out) { n = in.nextInt(); int[][][] M = new int[4][n][n]; for (int k = 0; k < 4; k++) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { M[k][i][j] += in.readCharacter() == '1' ? 1 : 0; } } } a = new int[]{0, 1, 2, 3}; permute(a, 0, a.length - 1); ans = INF; for (List<Integer> order : perm) { int cur = 0; for (int i1 = 0; i1 < order.size(); i1++) { int k = order.get(i1); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (i1 == 0 || i1 == 2) { if ((i + j) % 2 == 0 && M[k][i][j] == 0) cur++; if ((i + j) % 2 == 1 && M[k][i][j] == 1) cur++; } else { if ((i + j) % 2 == 0 && M[k][i][j] == 1) cur++; if ((i + j) % 2 == 1 && M[k][i][j] == 0) cur++; } } } } ans = Math.min(ans, cur); } out.printLine(ans); } void permute(int[] a, int l, int r) { int i; if (l == r) perm.add(Arrays.stream(a).boxed().collect(Collectors.toList())); else { for (i = l; i <= r; i++) { swap(a, l, i); permute(a, l + 1, r); swap(a, l, i); //backtrack } } } void swap(int[] a, int i, int j) { int temp; temp = a[i]; a[i] = a[j]; a[j] = temp; } } 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 OutputWriter printLine(int i) { writer.println(i); return this; } } 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; } 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 (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; } private boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } private static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public char readCharacter() { int c = read(); while (isSpaceChar(c)) { c = read(); } return (char) c; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["1\n0\n\n0\n\n1\n\n0", "3\n101\n010\n101\n\n101\n000\n101\n\n010\n101\n011\n\n010\n101\n010"]
1 second
["1", "2"]
null
Java 8
standard input
[ "implementation", "bitmasks", "brute force" ]
dc46c6cb6b4b9b5e7e6e5b4b7d034874
The first line contains odd integer n (1 ≤ n ≤ 100) — the size of all pieces of the board. Then 4 segments follow, each describes one piece of the board. Each consists of n lines of n characters; j-th one of i-th line is equal to 1 if the square is black initially and 0 otherwise. Segments are separated by an empty line.
1,400
Print one number — minimum number of squares Magnus should recolor to be able to obtain a valid chessboard.
standard output
PASSED
06a9b1db7d6cb092ccdc0a5085d3152e
train_003.jsonl
1522850700
Magnus decided to play a classic chess game. Though what he saw in his locker shocked him! His favourite chessboard got broken into 4 pieces, each of size n by n, n is always odd. And what's even worse, some squares were of wrong color. j-th square of the i-th row of k-th piece of the board has color ak, i, j; 1 being black and 0 being white. Now Magnus wants to change color of some squares in such a way that he recolors minimum number of squares and obtained pieces form a valid chessboard. Every square has its color different to each of the neightbouring by side squares in a valid board. Its size should be 2n by 2n. You are allowed to move pieces but not allowed to rotate or flip them.
256 megabytes
import java.util.*; import java.io.*; public class C961 { static int n; static char[][][] board; public static void main(String[] args) throws Exception { st = new StringTokenizer(in.readLine()); n = i(); board = new char[4][n][n]; for (int i = 0; i < 4; i++) { for (int j = 0; j < n; j++) { board[i][j] = in.readLine().toCharArray(); } if (i < 3) in.readLine(); } int min = 1 << 27; for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { if (j == i) continue; for (int k = 0; k < 4; k++) { if (k == i || k == j) continue; for (int l = 0; l < 4; l++) { if (l == i || l == j || l == k) continue; min = Math.min(min, diff(i, j, k, l, 0)); min = Math.min(min, diff(i, j, k, l, 1)); } } } } out.println(min); out.close(); } static int diff(int tl, int tr, int bl, int br, int flag) { int diff = 0; for (int r = 0; r < n; r++) { for (int c = 0; c < n; c++) { if (board[tl][r][c] != '1' - (r + c & 1) + flag) diff++; if (board[br][r][c] != '1' - (r + c & 1) + flag) diff++; if (board[tr][r][c] != '1' - (r + c + 1 & 1) + flag) diff++; if (board[bl][r][c] != '1' - (r + c + 1 & 1) + flag) diff++; } } return diff; } static BufferedReader in; static StringTokenizer st; static PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); static { try { in = new BufferedReader(new FileReader("cf.in")); } catch (Exception e) { in = new BufferedReader(new InputStreamReader(System.in)); } } static int i() {return Integer.parseInt(st.nextToken());} static double d() {return Double.parseDouble(st.nextToken());} static String s() {return st.nextToken();} static long l() {return Long.parseLong(st.nextToken());} }
Java
["1\n0\n\n0\n\n1\n\n0", "3\n101\n010\n101\n\n101\n000\n101\n\n010\n101\n011\n\n010\n101\n010"]
1 second
["1", "2"]
null
Java 8
standard input
[ "implementation", "bitmasks", "brute force" ]
dc46c6cb6b4b9b5e7e6e5b4b7d034874
The first line contains odd integer n (1 ≤ n ≤ 100) — the size of all pieces of the board. Then 4 segments follow, each describes one piece of the board. Each consists of n lines of n characters; j-th one of i-th line is equal to 1 if the square is black initially and 0 otherwise. Segments are separated by an empty line.
1,400
Print one number — minimum number of squares Magnus should recolor to be able to obtain a valid chessboard.
standard output
PASSED
1dd57c775c237f454770a51498e2f805
train_003.jsonl
1522850700
Magnus decided to play a classic chess game. Though what he saw in his locker shocked him! His favourite chessboard got broken into 4 pieces, each of size n by n, n is always odd. And what's even worse, some squares were of wrong color. j-th square of the i-th row of k-th piece of the board has color ak, i, j; 1 being black and 0 being white. Now Magnus wants to change color of some squares in such a way that he recolors minimum number of squares and obtained pieces form a valid chessboard. Every square has its color different to each of the neightbouring by side squares in a valid board. Its size should be 2n by 2n. You are allowed to move pieces but not allowed to rotate or flip them.
256 megabytes
import java.io.*; import java.util.*; public class Solution{ InputStream is; PrintWriter out; String INPUT = ""; Scanner in=new Scanner(System.in); int n; public void solve(){ n = ni(); char[][] m1 = nm(n, n); char[][] m2 = nm(n, n); char[][] m3 = nm(n, n); char[][] m4 = nm(n, n); char[] p = {'1', '2', '3', '4'}; int ans = first(m1) + first(m3) + second(m2) + second(m4); while(next_permutation(p)){ int res = 0; if(p[0] == '1' || p[0] == '3'){ res += first(m1); } else{ res += second(m1); } if(p[1] == '1' || p[1] == '3'){ res += first(m2); } else{ res += second(m2); } if(p[2] == '1' || p[2] == '3'){ res += first(m3); } else{ res += second(m3); } if(p[3] == '1' || p[3] == '3'){ res += first(m4); } else{ res += second(m4); } ans = Math.min(ans, res); } out.println(ans); } boolean next_permutation(char[] p) { for (int a = p.length - 2; a >= 0; --a) if (p[a] < p[a + 1]) for (int b = p.length - 1;; --b) if (p[b] > p[a]) { char t = p[a]; p[a] = p[b]; p[b] = t; for (++a, b = p.length - 1; a < b; ++a, --b) { t = p[a]; p[a] = p[b]; p[b] = t; } return true; } return false; } int second(char[][] map){ char[][] req = new char[n][n]; int cur = 1, ret = 0; for(int i = 0; i < n; i++){ for(int j = 0; j < n; j++){ if(cur == 0){ req[i][j] = '0'; } else{ req[i][j] = '1'; } cur = (cur+1)%2; if(map[i][j] != req[i][j]) ret+=1; } } return ret; } int first(char[][] map){ char[][] req = new char[n][n]; int cur = 0, ret = 0; for(int i = 0; i < n; i++){ for(int j = 0; j < n; j++){ if(cur == 0){ req[i][j] = '0'; } else{ req[i][j] = '1'; } cur = (cur+1)%2; if(map[i][j] != req[i][j]) ret+=1; } } return ret; } void run(){ is = new DataInputStream(System.in); out = new PrintWriter(System.out); int t=1;while(t-->0)solve(); out.flush(); } public static void main(String[] args)throws Exception{new Solution().run();} //Fast I/O code is copied from uwi code. 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(); } } static int i(long x){return (int)Math.round(x);} static int i(double x){return (int)Math.round(x);} static class Pair implements Comparable<Pair>{ long fs,sc; Pair(long a,long b){ fs=a;sc=b; } public int compareTo(Pair p){ if(this.fs>p.fs)return 1; else if(this.fs<p.fs)return -1; else{ return i(this.sc-p.sc); } //return i(this.sc-p.sc); } public String toString(){ return "("+fs+","+sc+")"; } } }
Java
["1\n0\n\n0\n\n1\n\n0", "3\n101\n010\n101\n\n101\n000\n101\n\n010\n101\n011\n\n010\n101\n010"]
1 second
["1", "2"]
null
Java 8
standard input
[ "implementation", "bitmasks", "brute force" ]
dc46c6cb6b4b9b5e7e6e5b4b7d034874
The first line contains odd integer n (1 ≤ n ≤ 100) — the size of all pieces of the board. Then 4 segments follow, each describes one piece of the board. Each consists of n lines of n characters; j-th one of i-th line is equal to 1 if the square is black initially and 0 otherwise. Segments are separated by an empty line.
1,400
Print one number — minimum number of squares Magnus should recolor to be able to obtain a valid chessboard.
standard output
PASSED
ebe26f812a98b46d91c3c1136de39122
train_003.jsonl
1522850700
Magnus decided to play a classic chess game. Though what he saw in his locker shocked him! His favourite chessboard got broken into 4 pieces, each of size n by n, n is always odd. And what's even worse, some squares were of wrong color. j-th square of the i-th row of k-th piece of the board has color ak, i, j; 1 being black and 0 being white. Now Magnus wants to change color of some squares in such a way that he recolors minimum number of squares and obtained pieces form a valid chessboard. Every square has its color different to each of the neightbouring by side squares in a valid board. Its size should be 2n by 2n. You are allowed to move pieces but not allowed to rotate or flip them.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); ProblemCChessboard solver = new ProblemCChessboard(); solver.solve(1, in, out); out.close(); } static class ProblemCChessboard { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.readInt(); char[][][] piece = new char[4][n][n]; for (int i = 0; i < 4; i++) { for (int j = 0; j < n; j++) piece[i][j] = in.readLine().toCharArray(); } int ans = Integer.MAX_VALUE; for (int i = 0; i < (1 << 4); i++) { if (Integer.bitCount(i) != 2) continue; int cnt = 0; for (int j = 0; j < 4; j++) { int c = (i >> j) & 1; for (int x = 0; x < n; x++) { for (int y = 0; y < n; y++) { if (piece[j][x][y] - '0' != c) cnt++; c = 1 - c; } } } ans = Math.min(ans, cnt); } out.println(ans); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private String readLine0() { StringBuilder buf = new StringBuilder(); int c = read(); while (c != '\n' && c != -1) { if (c != '\r') buf.appendCodePoint(c); c = read(); } return buf.toString(); } public String readLine() { String s = readLine0(); while (s.trim().length() == 0) s = readLine0(); return s; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["1\n0\n\n0\n\n1\n\n0", "3\n101\n010\n101\n\n101\n000\n101\n\n010\n101\n011\n\n010\n101\n010"]
1 second
["1", "2"]
null
Java 8
standard input
[ "implementation", "bitmasks", "brute force" ]
dc46c6cb6b4b9b5e7e6e5b4b7d034874
The first line contains odd integer n (1 ≤ n ≤ 100) — the size of all pieces of the board. Then 4 segments follow, each describes one piece of the board. Each consists of n lines of n characters; j-th one of i-th line is equal to 1 if the square is black initially and 0 otherwise. Segments are separated by an empty line.
1,400
Print one number — minimum number of squares Magnus should recolor to be able to obtain a valid chessboard.
standard output
PASSED
0b47fdb155646697df50e8a95185312d
train_003.jsonl
1522850700
Magnus decided to play a classic chess game. Though what he saw in his locker shocked him! His favourite chessboard got broken into 4 pieces, each of size n by n, n is always odd. And what's even worse, some squares were of wrong color. j-th square of the i-th row of k-th piece of the board has color ak, i, j; 1 being black and 0 being white. Now Magnus wants to change color of some squares in such a way that he recolors minimum number of squares and obtained pieces form a valid chessboard. Every square has its color different to each of the neightbouring by side squares in a valid board. Its size should be 2n by 2n. You are allowed to move pieces but not allowed to rotate or flip them.
256 megabytes
import java.io.*; import java.util.*; public class ec { static InputStream is; public static void main(String[] args) throws IOException { is = System.in; int n = ni(); int[] z = new int[4]; int[] o = new int[4]; for(int i =0; i< 4; i++){ for(int j = 0; j < n; j++){ char[] line = ns().toCharArray(); for(int k =0; k < n; k++){ if(((j&1)^(line[k]-'0')^(k&1)) == 0){ z[i]++; } else o[i]++; } } } int sum = 0; int[] diff = new int[4]; for(int i =0; i < 4; i++){ sum += z[i]; diff[i] = o[i]-z[i]; } int min = 987654321; for(int i =0; i <4; i++){ for(int j = i+1; j < 4; j++){ min = Math.min(min, sum+diff[i]+diff[j]); } } System.out.println(min); } private static byte[] inbuf = new byte[1024]; public static int lenbuf = 0, ptrbuf = 0; private static 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 static boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private static int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; } private static double nd() { return Double.parseDouble(ns()); } private static char nc() { return (char)skip(); } private static 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 static 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 static 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 static int[] na(int n) { int[] a = new int[n]; for(int i = 0;i < n;i++)a[i] = ni(); return a; } private static 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 static 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(); } } }
Java
["1\n0\n\n0\n\n1\n\n0", "3\n101\n010\n101\n\n101\n000\n101\n\n010\n101\n011\n\n010\n101\n010"]
1 second
["1", "2"]
null
Java 8
standard input
[ "implementation", "bitmasks", "brute force" ]
dc46c6cb6b4b9b5e7e6e5b4b7d034874
The first line contains odd integer n (1 ≤ n ≤ 100) — the size of all pieces of the board. Then 4 segments follow, each describes one piece of the board. Each consists of n lines of n characters; j-th one of i-th line is equal to 1 if the square is black initially and 0 otherwise. Segments are separated by an empty line.
1,400
Print one number — minimum number of squares Magnus should recolor to be able to obtain a valid chessboard.
standard output
PASSED
1565a24487efcd6fbc2c8cfb60432e47
train_003.jsonl
1522850700
Magnus decided to play a classic chess game. Though what he saw in his locker shocked him! His favourite chessboard got broken into 4 pieces, each of size n by n, n is always odd. And what's even worse, some squares were of wrong color. j-th square of the i-th row of k-th piece of the board has color ak, i, j; 1 being black and 0 being white. Now Magnus wants to change color of some squares in such a way that he recolors minimum number of squares and obtained pieces form a valid chessboard. Every square has its color different to each of the neightbouring by side squares in a valid board. Its size should be 2n by 2n. You are allowed to move pieces but not allowed to rotate or flip them.
256 megabytes
import java.util.*; import java.io.*; import java.math.*; public class code5 { InputStream is; PrintWriter out; static long mod=pow(10,9)+7; int dx[]= {0,0,1,-1},dy[]={+1,-1,0,0}; void solve() { int n=ni(); char arr[][][]=new char[4][n][n]; for(int i=0;i<4;i++) { for(int j=0;j<n;j++) { String s=ns(); arr[i][j]=s.toCharArray(); } } int count[][]=new int[4][2]; for(int i=0;i<4;i++) { int need=0; for(int j=0;j<n;j++) { for(int k=0;k<n;k++) { if(arr[i][j][k]-'0'!=need) count[i][0]++; need^=1; } } need=1; for(int j=0;j<n;j++) { for(int k=0;k<n;k++) { if(arr[i][j][k]-'0'!=need) count[i][1]++; need^=1; } } } int sum=Integer.MAX_VALUE; for(int i=0;i<4;i++) { for(int j=i+1;j<4;j++) { int temp=0; for(int k=0;k<4;k++) { if(k!=i&&k!=j) temp+=count[k][1]; } sum=Math.min(sum,count[i][0]+count[j][0]+temp); } } out.println(sum); } ArrayList<Integer>al []; void take(int n,int m) { al=new ArrayList[n]; for(int i=0;i<n;i++) al[i]=new ArrayList<Integer>(); for(int i=0;i<m;i++) { int x=ni()-1; int y=ni()-1; al[x].add(y); al[y].add(x); } } int arr[][]; int small[]; void pre(int n) { small=new int[n+1]; for(int i=2;i*i<=n;i++) { for(int j=i;j*i<=n;j++) { if(small[i*j]==0) small[i*j]=i; } } for(int i=0;i<=n;i++) { if(small[i]==0) small[i]=i; } } public static int count(int x) { int num=0; while(x!=0) { x=x&(x-1); num++; } return num; } static long d, x, y; void extendedEuclid(long A, long B) { if(B == 0) { d = A; x = 1; y = 0; } else { extendedEuclid(B, A%B); long temp = x; x = y; y = temp - (A/B)*y; } } long modInverse(long A,long M) //A and M are coprime { extendedEuclid(A,M); return (x%M+M)%M; //x may be negative } public static void mergeSort(int[] arr, int l ,int r){ if((r-l)>=1){ int mid = (l+r)/2; mergeSort(arr,l,mid); mergeSort(arr,mid+1,r); merge(arr,l,r,mid); } } public static void merge(int arr[], int l, int r, int mid){ int n1 = (mid-l+1), n2 = (r-mid); int left[] = new int[n1]; int right[] = new int[n2]; for(int i =0 ;i<n1;i++) left[i] = arr[l+i]; for(int i =0 ;i<n2;i++) right[i] = arr[mid+1+i]; int i =0, j =0, k = l; while(i<n1 && j<n2){ if(left[i]>right[j]){ arr[k++] = right[j++]; } else{ arr[k++] = left[i++]; } } while(i<n1) arr[k++] = left[i++]; while(j<n2) arr[k++] = right[j++]; } public static void mergeSort(long[] arr, int l ,int r){ if((r-l)>=1){ int mid = (l+r)/2; mergeSort(arr,l,mid); mergeSort(arr,mid+1,r); merge(arr,l,r,mid); } } public static void merge(long arr[], int l, int r, int mid){ int n1 = (mid-l+1), n2 = (r-mid); long left[] = new long[n1]; long right[] = new long[n2]; for(int i =0 ;i<n1;i++) left[i] = arr[l+i]; for(int i =0 ;i<n2;i++) right[i] = arr[mid+1+i]; int i =0, j =0, k = l; while(i<n1 && j<n2){ if(left[i]>right[j]){ arr[k++] = right[j++]; } else{ arr[k++] = left[i++]; } } while(i<n1) arr[k++] = left[i++]; while(j<n2) arr[k++] = right[j++]; } static class Pair implements Comparable<Pair>{ long x; int y,k,i; Pair (long x,int y){ this.x=x; this.y=y; } public int compareTo(Pair o) { if(this.x!=o.x) return Long.compare(this.x,o.x); return this.y-o.y; } public boolean equals(Object o) { if (o instanceof Pair) { Pair p = (Pair)o; return p.x == x && p.y == y; } return false; } public int hashCode() { return new Long(x).hashCode()*31 + new Long(y).hashCode() ; } @Override public String toString() { return "("+x + " " + y +" "+k+" "+i+" )"; } } public static boolean isPal(String s){ for(int i=0, j=s.length()-1;i<=j;i++,j--){ if(s.charAt(i)!=s.charAt(j)) return false; } return true; } public static String rev(String s){ StringBuilder sb=new StringBuilder(s); sb.reverse(); return sb.toString(); } public static long gcd(long x,long y){ if(x%y==0) return y; else return gcd(y,x%y); } public static int gcd(int x,int y){ if(y==0) return x; return gcd(y,x%y); } public static long gcdExtended(long a,long b,long[] x){ if(a==0){ x[0]=0; x[1]=1; return b; } long[] y=new long[2]; long gcd=gcdExtended(b%a, a, y); x[0]=y[1]-(b/a)*y[0]; x[1]=y[0]; return gcd; } public static int abs(int a,int b){ return (int)Math.abs(a-b); } public static long abs(long a,long b){ return (long)Math.abs(a-b); } public static int max(int a,int b){ if(a>b) return a; else return b; } public static int min(int a,int b){ if(a>b) return b; else return a; } public static long max(long a,long b){ if(a>b) return a; else return b; } public static long min(long a,long b){ if(a>b) return b; else return a; } 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; } public static void debug(Object... o) { System.out.println(Arrays.deepToString(o)); } void run() throws Exception { is = System.in; out = new PrintWriter(System.out); solve(); out.flush(); } public static void main(String[] args) throws Exception { new Thread(null, new Runnable() { public void run() { try { new code5().run(); } catch (Exception e) { e.printStackTrace(); } } }, "1", 1 << 26).start(); } 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 long[] nl(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nl(); return a; } private int ni() { int num = 0, b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 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(); } } }
Java
["1\n0\n\n0\n\n1\n\n0", "3\n101\n010\n101\n\n101\n000\n101\n\n010\n101\n011\n\n010\n101\n010"]
1 second
["1", "2"]
null
Java 8
standard input
[ "implementation", "bitmasks", "brute force" ]
dc46c6cb6b4b9b5e7e6e5b4b7d034874
The first line contains odd integer n (1 ≤ n ≤ 100) — the size of all pieces of the board. Then 4 segments follow, each describes one piece of the board. Each consists of n lines of n characters; j-th one of i-th line is equal to 1 if the square is black initially and 0 otherwise. Segments are separated by an empty line.
1,400
Print one number — minimum number of squares Magnus should recolor to be able to obtain a valid chessboard.
standard output
PASSED
f1fbc01b70fd7db6fa22728c07ae6114
train_003.jsonl
1522850700
Magnus decided to play a classic chess game. Though what he saw in his locker shocked him! His favourite chessboard got broken into 4 pieces, each of size n by n, n is always odd. And what's even worse, some squares were of wrong color. j-th square of the i-th row of k-th piece of the board has color ak, i, j; 1 being black and 0 being white. Now Magnus wants to change color of some squares in such a way that he recolors minimum number of squares and obtained pieces form a valid chessboard. Every square has its color different to each of the neightbouring by side squares in a valid board. Its size should be 2n by 2n. You are allowed to move pieces but not allowed to rotate or flip them.
256 megabytes
import java.util.Arrays; import java.util.Scanner; public class Solution { private static int minColoring(int n, int[][][] boards) { int[][] defects = new int[2][4]; for (int board = 0; board < 4; board++) for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) defects[((i ^ j) & 1) ^ boards[board][i][j]][board]++; int total = 0; int[] diff = new int[4]; for (int board = 0; board < 4; board++) { total += defects[0][board]; diff[board] = defects[1][board] - defects[0][board]; } Arrays.sort(diff); total += diff[0] + diff[1]; return total; } public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int[][][] boards = new int[4][n][n]; for (int board = 0; board < 4; board++) { for (int i = 0; i < n; i++) { String s = in.next(); for (int j = 0; j < n; j++) boards[board][i][j] = s.charAt(j) - '0'; } } int result = minColoring(n, boards); System.out.println(result); } }
Java
["1\n0\n\n0\n\n1\n\n0", "3\n101\n010\n101\n\n101\n000\n101\n\n010\n101\n011\n\n010\n101\n010"]
1 second
["1", "2"]
null
Java 8
standard input
[ "implementation", "bitmasks", "brute force" ]
dc46c6cb6b4b9b5e7e6e5b4b7d034874
The first line contains odd integer n (1 ≤ n ≤ 100) — the size of all pieces of the board. Then 4 segments follow, each describes one piece of the board. Each consists of n lines of n characters; j-th one of i-th line is equal to 1 if the square is black initially and 0 otherwise. Segments are separated by an empty line.
1,400
Print one number — minimum number of squares Magnus should recolor to be able to obtain a valid chessboard.
standard output
PASSED
ee9b002fbbe5cbef768b07c8a037d2ac
train_003.jsonl
1522850700
Magnus decided to play a classic chess game. Though what he saw in his locker shocked him! His favourite chessboard got broken into 4 pieces, each of size n by n, n is always odd. And what's even worse, some squares were of wrong color. j-th square of the i-th row of k-th piece of the board has color ak, i, j; 1 being black and 0 being white. Now Magnus wants to change color of some squares in such a way that he recolors minimum number of squares and obtained pieces form a valid chessboard. Every square has its color different to each of the neightbouring by side squares in a valid board. Its size should be 2n by 2n. You are allowed to move pieces but not allowed to rotate or flip them.
256 megabytes
import java.util.Scanner; public class C { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int N = sc.nextInt(); int[][] dosk1 = new int[N][N]; int[][] dosk2 = new int[N][N]; int[][] dosk3 = new int[N][N]; int[][] dosk4 = new int[N][N]; int w1 = 0; int w2 = 0; int w3 = 0; int w4 = 0; int b1 = 0; int b2 = 0; int b3 = 0; int b4 = 0; sc.nextLine(); for(int i = 0; i < N; i++){ String line = sc.nextLine(); for(int j = 0; j< N; j++){ dosk1[i][j] = Character.getNumericValue(line.charAt(j)); } } sc.nextLine(); for(int i = 0; i < N; i++){ String line = sc.nextLine(); for(int j = 0; j< N; j++){ dosk2[i][j] = Character.getNumericValue(line.charAt(j)); } } sc.nextLine(); for(int i = 0; i < N; i++){ String line = sc.nextLine(); for(int j = 0; j< N; j++){ dosk3[i][j] = Character.getNumericValue(line.charAt(j)); } } sc.nextLine(); for(int i = 0; i < N; i++){ String line = sc.nextLine(); for(int j = 0; j< N; j++){ dosk4[i][j] = Character.getNumericValue(line.charAt(j)); } } int count1 = 0; for(int i = 0; i < N; i++){ for(int j = 0; j< N; j++){ if(dosk1[i][j] != count1%2){ w1++; }else{ b1++; } count1++; } } count1 = 0; for(int i = 0; i < N; i++){ for(int j = 0; j< N; j++){ if(dosk2[i][j] != count1%2){ w2++; }else{ b2++; } count1++; } } count1 = 0; for(int i = 0; i < N; i++){ for(int j = 0; j< N; j++){ if(dosk3[i][j] != count1%2){ w3++; }else{ b3++; } count1++; } } count1 = 0; for(int i = 0; i < N; i++){ for(int j = 0; j< N; j++){ if(dosk4[i][j] != count1%2){ w4++; }else{ b4++; } count1++; } } int res1 = w1 + w3 + b2 + b4; int res2 = w1 + w2 + b3 + b4; int res3 = w1 + w4 + b3 + b2; int res4 = b1 + b3 + w2 + w4; int res5 = b1 + b2 + w3 + w4; int res6 = b1 + b4 + w3 + w2; int res = Math.min(res1, res2); res = Math.min(res, res3); res = Math.min(res, res4); res = Math.min(res, res5); res = Math.min(res, res6); System.out.println(res); } }
Java
["1\n0\n\n0\n\n1\n\n0", "3\n101\n010\n101\n\n101\n000\n101\n\n010\n101\n011\n\n010\n101\n010"]
1 second
["1", "2"]
null
Java 8
standard input
[ "implementation", "bitmasks", "brute force" ]
dc46c6cb6b4b9b5e7e6e5b4b7d034874
The first line contains odd integer n (1 ≤ n ≤ 100) — the size of all pieces of the board. Then 4 segments follow, each describes one piece of the board. Each consists of n lines of n characters; j-th one of i-th line is equal to 1 if the square is black initially and 0 otherwise. Segments are separated by an empty line.
1,400
Print one number — minimum number of squares Magnus should recolor to be able to obtain a valid chessboard.
standard output
PASSED
e7fbbbc1930d31149e66a588c6ae6150
train_003.jsonl
1522850700
Magnus decided to play a classic chess game. Though what he saw in his locker shocked him! His favourite chessboard got broken into 4 pieces, each of size n by n, n is always odd. And what's even worse, some squares were of wrong color. j-th square of the i-th row of k-th piece of the board has color ak, i, j; 1 being black and 0 being white. Now Magnus wants to change color of some squares in such a way that he recolors minimum number of squares and obtained pieces form a valid chessboard. Every square has its color different to each of the neightbouring by side squares in a valid board. Its size should be 2n by 2n. You are allowed to move pieces but not allowed to rotate or flip them.
256 megabytes
import java.util.Scanner; public class C { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int N = sc.nextInt(); int[][] dosk1 = new int[N][N]; int[][] dosk2 = new int[N][N]; int[][] dosk3 = new int[N][N]; int[][] dosk4 = new int[N][N]; int w1 = 0; int w2 = 0; int w3 = 0; int w4 = 0; int b1 = 0; int b2 = 0; int b3 = 0; int b4 = 0; sc.nextLine(); for(int i = 0; i < N; i++){ String line = sc.nextLine(); for(int j = 0; j< N; j++){ dosk1[i][j] = Character.getNumericValue(line.charAt(j)); } } sc.nextLine(); for(int i = 0; i < N; i++){ String line = sc.nextLine(); for(int j = 0; j< N; j++){ dosk2[i][j] = Character.getNumericValue(line.charAt(j)); } } sc.nextLine(); for(int i = 0; i < N; i++){ String line = sc.nextLine(); for(int j = 0; j< N; j++){ dosk3[i][j] = Character.getNumericValue(line.charAt(j)); } } sc.nextLine(); for(int i = 0; i < N; i++){ String line = sc.nextLine(); for(int j = 0; j< N; j++){ dosk4[i][j] = Character.getNumericValue(line.charAt(j)); } } int count1 = 0; for(int i = 0; i < N; i++){ for(int j = 0; j< N; j++){ if(dosk1[i][j] != count1%2){ w1++; }else{ b1++; } count1++; } } count1 = 0; for(int i = 0; i < N; i++){ for(int j = 0; j< N; j++){ if(dosk2[i][j] != count1%2){ w2++; }else{ b2++; } count1++; } } count1 = 0; for(int i = 0; i < N; i++){ for(int j = 0; j< N; j++){ if(dosk3[i][j] != count1%2){ w3++; }else{ b3++; } count1++; } } count1 = 0; for(int i = 0; i < N; i++){ for(int j = 0; j< N; j++){ if(dosk4[i][j] != count1%2){ w4++; }else{ b4++; } count1++; } } int res1 = w1 + w3 + b2 + b4; int res2 = w1 + w2 + b3 + b4; int res3 = w1 + w4 + b3 + b2; int res4 = b1 + b3 + w2 + w4; int res5 = b1 + b2 + w3 + w4; int res6 = b1 + b4 + w3 + w2; int res = Math.min(res1, res2); res = Math.min(res, res3); res = Math.min(res, res4); res = Math.min(res, res5); res = Math.min(res, res6); System.out.println(res); } }
Java
["1\n0\n\n0\n\n1\n\n0", "3\n101\n010\n101\n\n101\n000\n101\n\n010\n101\n011\n\n010\n101\n010"]
1 second
["1", "2"]
null
Java 8
standard input
[ "implementation", "bitmasks", "brute force" ]
dc46c6cb6b4b9b5e7e6e5b4b7d034874
The first line contains odd integer n (1 ≤ n ≤ 100) — the size of all pieces of the board. Then 4 segments follow, each describes one piece of the board. Each consists of n lines of n characters; j-th one of i-th line is equal to 1 if the square is black initially and 0 otherwise. Segments are separated by an empty line.
1,400
Print one number — minimum number of squares Magnus should recolor to be able to obtain a valid chessboard.
standard output
PASSED
4bb163485280277e44a8eeb6d8f8db97
train_003.jsonl
1522850700
Magnus decided to play a classic chess game. Though what he saw in his locker shocked him! His favourite chessboard got broken into 4 pieces, each of size n by n, n is always odd. And what's even worse, some squares were of wrong color. j-th square of the i-th row of k-th piece of the board has color ak, i, j; 1 being black and 0 being white. Now Magnus wants to change color of some squares in such a way that he recolors minimum number of squares and obtained pieces form a valid chessboard. Every square has its color different to each of the neightbouring by side squares in a valid board. Its size should be 2n by 2n. You are allowed to move pieces but not allowed to rotate or flip them.
256 megabytes
import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Iterator; import java.util.PrimitiveIterator; import java.util.Spliterator; import java.util.Spliterators; import java.util.function.Supplier; import java.util.stream.IntStream; import java.util.stream.LongStream; import java.util.stream.Stream; public class Main{ static FastScanner s=new FastScanner(System.in); static StringBuilder diff=new StringBuilder(); void solve(){ int n=s.nextInt(); for(int a=0;a<2;++a)for(int b=0;b<2;++b) for(int i=0;i<n;++i){ for(int j=0;j<n;++j){ diff.append((i+j+a*n+b*n)%2==0?'1':'0'); } } String a="",b="",c="",d=""; for(int i=0;i<n;++i)a+=s.next(); for(int i=0;i<n;++i)b+=s.next(); for(int i=0;i<n;++i)c+=s.next(); for(int i=0;i<n;++i)d+=s.next(); System.out.println( LongStream.of( f(a,b,c,d), f(a,b,d,c), f(a,c,b,d), f(a,c,d,b), f(a,d,b,c), f(a,d,c,b)) //.peek(System.err::println) .min().getAsLong()); } private long f(String a,String b,String c,String d){ String v=a+b+c+d; return Math.min( IntStream.range(0,v.length()).filter(i->v.charAt(i)!=diff.charAt(i)).count(), IntStream.range(0,v.length()).filter(i->v.charAt(i)==diff.charAt(i)).count() ); } public static void main(String[] $){ new Main().solve(); } int gInt(){ return s.nextInt(); } long gLong(){ return s.nextLong(); } double gDouble(){ return Double.parseDouble(s.next()); } SupplyingIterator<Integer> ints(int n){ return new SupplyingIterator<>(n,this::gInt); } SupplyingIterator<Long> longs(int n){ return new SupplyingIterator<>(n,this::gLong); } SupplyingIterator<Double> doubles(int n){ return new SupplyingIterator<>(n,this::gDouble); } SupplyingIterator<String> strs(int n){ return new SupplyingIterator<>(n,s::next); } Range rep(int i){ return Range.rep(i); } Range rep(int f,int t,int d){ return Range.rep(f,t,d); } Range rep(int f,int t){ return rep(f,t,1); } Range rrep(int f,int t){ return rep(t,f,-1); } IntStream INTS(int n){ return IntStream.generate(this::gInt).limit(n); } Stream<String> STRS(int n){ return Stream.generate(s::next).limit(n); } } class FastScanner{ private final BufferedInputStream in; private static final int bufSize =1<<16; private final byte buf[] =new byte[bufSize]; private int i =bufSize,k=bufSize; private final StringBuilder str =new StringBuilder(); FastScanner(InputStream in){ this.in=new BufferedInputStream(in,bufSize); } int nextInt(){ return (int)nextLong(); } long nextLong(){ int c; long x=0; boolean sign=true; while((c=nextChar())<=32) ; if(c=='-'){ sign=false; c=nextChar(); } if(c=='+'){ c=nextChar(); } while(c>='0'){ x=x*10+(c-'0'); c=nextChar(); } return sign?x:-x; } private int nextChar(){ if(i==k){ try{ k=in.read(buf,i=0,bufSize); }catch(IOException e){ System.exit(-1); } } return i>=k?-1:buf[i++]; } String next(){ int c; str.setLength(0); while((c=nextChar())<=32&&c!=-1) ; if(c==-1) return null; while(c>32){ str.append((char)c); c=nextChar(); } return str.toString(); } String nextLine(){ int c; str.setLength(0); while((c=nextChar())<=32&&c!=-1) ; if(c==-1) return null; while(c!='\n'){ str.append((char)c); c=nextChar(); } return str.toString(); } } class SupplyingIterator<T> implements Iterable<T>,Iterator<T>{ private int remain; Supplier<T> supplier; SupplyingIterator(int t,Supplier<T> supplier){ this.remain=t; this.supplier=supplier; } @Override public Iterator<T> iterator(){ return this; } @Override public boolean hasNext(){ return remain>0; } @Override public T next(){ --remain; return supplier.get(); } } class Range implements Iterable<Integer>,PrimitiveIterator.OfInt{ public final int from,to,d; private int cur; Range(int from,int to,int d){ this.from=from; this.cur=from-d; this.to=to; this.d=d; } Range(int n){ this(0,n-1,1); } @Override public Iterator<Integer> iterator(){ return this; } @Override public boolean hasNext(){ return cur+d==to||(cur!=to&&(cur<to==cur+d<to)); } @Override public int nextInt(){ return cur+=d; } protected final int CHARACTERISTICS=Spliterator.SIZED|Spliterator.DISTINCT|Spliterator.IMMUTABLE|Spliterator.NONNULL; @Override public Spliterator.OfInt spliterator(){ return Spliterators.spliterator(this,(to-from)/d+1,CHARACTERISTICS); } IntStream stream(){ return d==1?IntStream.rangeClosed(from,to):java.util.stream.StreamSupport.intStream(this.spliterator(),false); } static Range rep(int i){ return new Range(i); } static Range rep(int f,int t,int d){ return new Range(f,t,d); } static Range rep(int f,int t){ return rep(f,t,1); } static Range rrep(int f,int t){ return rep(t,f,-1); } }
Java
["1\n0\n\n0\n\n1\n\n0", "3\n101\n010\n101\n\n101\n000\n101\n\n010\n101\n011\n\n010\n101\n010"]
1 second
["1", "2"]
null
Java 8
standard input
[ "implementation", "bitmasks", "brute force" ]
dc46c6cb6b4b9b5e7e6e5b4b7d034874
The first line contains odd integer n (1 ≤ n ≤ 100) — the size of all pieces of the board. Then 4 segments follow, each describes one piece of the board. Each consists of n lines of n characters; j-th one of i-th line is equal to 1 if the square is black initially and 0 otherwise. Segments are separated by an empty line.
1,400
Print one number — minimum number of squares Magnus should recolor to be able to obtain a valid chessboard.
standard output
PASSED
5299a55968a570299d35fd27521a5ad7
train_003.jsonl
1522850700
Magnus decided to play a classic chess game. Though what he saw in his locker shocked him! His favourite chessboard got broken into 4 pieces, each of size n by n, n is always odd. And what's even worse, some squares were of wrong color. j-th square of the i-th row of k-th piece of the board has color ak, i, j; 1 being black and 0 being white. Now Magnus wants to change color of some squares in such a way that he recolors minimum number of squares and obtained pieces form a valid chessboard. Every square has its color different to each of the neightbouring by side squares in a valid board. Its size should be 2n by 2n. You are allowed to move pieces but not allowed to rotate or flip them.
256 megabytes
import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.InputMismatchException; /** * todo * * @author hemenghai * @date 2019/1/23 18:50 */ public class Main { private static int cur, pos, sum, len; private static int max, min, ans, res; private static int ai, bi, ci, di; private static int[] aix, bix; private static long al, bl, cl, dl; private static long[] alx, blx; private static double ad, bd, cd, dd; private static double[] adx, bdx; private static boolean ab, bb, cb, db; private static boolean[] abx, bbx; private static boolean[][] abxx, bbxx; private static char ac, bc, cc, dc; private static char[] acx, bcx; private static char[][] acxx, bcxx; private static String as, bs, cs, ds; private static String[] asx, bsx; private static InputReader in = new InputReader(System.in); private static PrintWriter out = new PrintWriter(System.out); public static void main(String[] args) { len = in.nextInt(); aix = new int[4]; bix = new int[4]; acxx = new char[len][]; for (int i = 0; i < 4; i++) { for (int j = 0; j < len; j++) { as = in.next(); acxx[j] = as.toCharArray(); } aix[i] = toA(); bix[i] = toB(); } solve(); System.out.println(ans); } private static void solve() { ans = Integer.MAX_VALUE; dfs(0, 2, 2, 0); } private static void dfs(int p, int a, int b, int v) { if (p == 4) { ans = Math.min(v, ans); return; } if (a > 0) { dfs(p + 1, a - 1, b, v + aix[p]); } if (b > 0) { dfs(p + 1, a, b - 1, v + bix[p]); } } private static int toB() { return toX('1', '0'); } private static int toA() { return toX('0', '1'); } private static int toX(char even, char odd) { int diff = 0; for (int i = 0; i < len; i++) { for (int j = 0; j < len; j++) { if ((i + j) % 2 == 0) { if (acxx[i][j] != even) { diff++; } } else { if (acxx[i][j] != odd) { diff++; } } } } return diff; } private static class InputReader { private static final char MINUS = '-'; private static final char POINT = '.'; private static final char ZERO = '0'; private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } public String next() { return readString(); } public int nextInt() { return (int) nextLong(); } public long nextLong() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == MINUS) { sgn = -1; c = read(); } long res = 0; do { res *= 10; res += c - ZERO; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public double nextDouble() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == MINUS) { sgn = -1; c = read(); } double res = 0; while (!isSpaceChar(c) && c != POINT) { if (c == 'e' || c == 'E') { return res * Math.pow(10, nextInt()); } res *= 10; res += c - ZERO; c = read(); } if (c == POINT) { c = read(); double m = 1.0D; while (!isSpaceChar(c)) { if (c == 'e' || c == 'E') { return res * Math.pow(10, nextInt()); } m /= 10; res += (c - ZERO) * m; c = read(); } } return res * sgn; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private 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(); } 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++]; } } }
Java
["1\n0\n\n0\n\n1\n\n0", "3\n101\n010\n101\n\n101\n000\n101\n\n010\n101\n011\n\n010\n101\n010"]
1 second
["1", "2"]
null
Java 8
standard input
[ "implementation", "bitmasks", "brute force" ]
dc46c6cb6b4b9b5e7e6e5b4b7d034874
The first line contains odd integer n (1 ≤ n ≤ 100) — the size of all pieces of the board. Then 4 segments follow, each describes one piece of the board. Each consists of n lines of n characters; j-th one of i-th line is equal to 1 if the square is black initially and 0 otherwise. Segments are separated by an empty line.
1,400
Print one number — minimum number of squares Magnus should recolor to be able to obtain a valid chessboard.
standard output
PASSED
25a371c0eaee611615a09c0df4c39c70
train_003.jsonl
1522850700
Magnus decided to play a classic chess game. Though what he saw in his locker shocked him! His favourite chessboard got broken into 4 pieces, each of size n by n, n is always odd. And what's even worse, some squares were of wrong color. j-th square of the i-th row of k-th piece of the board has color ak, i, j; 1 being black and 0 being white. Now Magnus wants to change color of some squares in such a way that he recolors minimum number of squares and obtained pieces form a valid chessboard. Every square has its color different to each of the neightbouring by side squares in a valid board. Its size should be 2n by 2n. You are allowed to move pieces but not allowed to rotate or flip them.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; public class C { static int convert (char [][]a,int x) { int n=a.length; int ans=0; for(int i=0;i<n;i++) for(int j=0;j<n;j++) { if(a[i][j]-'0'!=x) ans++; x=1-x; } return ans; } public static void main(String[] args) throws IOException { Scanner sc=new Scanner(System.in); PrintWriter pw=new PrintWriter(System.out); int n=sc.nextInt(); int []ones=new int [4],zeroes=new int [4]; for(int rep=0;rep<4;rep++) { char [][]a=new char[n][n]; for(int i=0;i<n;i++) a[i]=sc.nextLine().toCharArray(); sc.nextLine(); ones[rep]=convert(a,1); zeroes[rep]=convert(a,0); } int other=0; for(int x:zeroes) other+=x; int ans=4*n*n; for(int i=0;i<4;i++) for(int j=i+1;j<4;j++) { int s=other; s+=ones[i]+ones[j]; s=s-(zeroes[i]+zeroes[j]); ans=Math.min(ans, s); } pw.println(ans); pw.close(); } static class Scanner { BufferedReader br; StringTokenizer st; public Scanner(InputStream s) { br=new BufferedReader(new InputStreamReader(s)); } public String nextLine() throws IOException { return br.readLine(); } public String next() throws IOException { while(st==null || !st.hasMoreTokens()) st=new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public boolean ready() throws IOException { return br.ready(); } public long nextLong() throws IOException { return Long.parseLong(next()); } } }
Java
["1\n0\n\n0\n\n1\n\n0", "3\n101\n010\n101\n\n101\n000\n101\n\n010\n101\n011\n\n010\n101\n010"]
1 second
["1", "2"]
null
Java 8
standard input
[ "implementation", "bitmasks", "brute force" ]
dc46c6cb6b4b9b5e7e6e5b4b7d034874
The first line contains odd integer n (1 ≤ n ≤ 100) — the size of all pieces of the board. Then 4 segments follow, each describes one piece of the board. Each consists of n lines of n characters; j-th one of i-th line is equal to 1 if the square is black initially and 0 otherwise. Segments are separated by an empty line.
1,400
Print one number — minimum number of squares Magnus should recolor to be able to obtain a valid chessboard.
standard output
PASSED
dd2a2754dbc44938beebbd4dacaf6f53
train_003.jsonl
1522850700
Magnus decided to play a classic chess game. Though what he saw in his locker shocked him! His favourite chessboard got broken into 4 pieces, each of size n by n, n is always odd. And what's even worse, some squares were of wrong color. j-th square of the i-th row of k-th piece of the board has color ak, i, j; 1 being black and 0 being white. Now Magnus wants to change color of some squares in such a way that he recolors minimum number of squares and obtained pieces form a valid chessboard. Every square has its color different to each of the neightbouring by side squares in a valid board. Its size should be 2n by 2n. You are allowed to move pieces but not allowed to rotate or flip them.
256 megabytes
/* package codechef; // don't place package name! */ import java.util.*; import java.lang.*; import java.io.*; /* Name of the class has to be "Main" only if the class is public. */ public class Codechef { public class Obj implements Comparable<Obj>{ public int start; public int end; public Obj(int start_, int end_){ this.start = start_; this.end = end_; } public int compareTo(Obj other){ if (other.start == this.start){ return this.end - other.end; } return this.start - other.start; } } public static void main (String[] args) throws java.lang.Exception { // your code goes here Codechef cf = new Codechef(); cf.Solve(); } public void Solve(){ MyScanner sc = new MyScanner(); int n = sc.nextInt(); int[][] boardWhite = new int[2 * n][2 * n]; int[][] boardBlack = new int[2 * n][2 * n]; for (int i = 0; i < 2*n; ++i){ for (int j = 0; j < 2*n; ++j){ if (i % 2 == 0){ if (j % 2 == 0){ boardWhite[i][j] = 0; }else{ boardWhite[i][j] = 1; } }else{ if (j % 2 == 0){ boardWhite[i][j] = 1; }else{ boardWhite[i][j] = 0; } } boardBlack[i][j] = 1 - boardWhite[i][j]; // System.out.print(boardBlack[i][j] + " "); } // System.out.println(); } int[][][] arr = new int[4][n][n]; // System.out.println("n: " + n); for (int i = 0; i < 4; ++i){ for (int k = 0; k < n; ++k){ String s = sc.nextLine(); // System.out.println("s: " + s); for (int j = 0; j < n; ++j){ // System.out.println("j: " + j + " " + s.charAt(j)); if (s.charAt(j) == '1'){ arr[i][k][j] = 1; }else{ arr[i][k][j] = 0; } } } sc.nextLine(); } int[][] board = new int[2*n][2*n]; int res = 4 * n * n + 1; for (int i1 = 0; i1 < 4; ++i1){ for (int i2 = 0; i2 < 4; ++i2){ if (i2 == i1) continue; for (int i3 = 0; i3 < 4; ++i3){ if (i3 == i2 || i3 == i1) continue; for (int i4 = 0; i4 < 4; ++i4){ if (i4 == i1 || i4 == i2 || i4 == i3) continue; makeBoard(arr, board, n, i1, i2, i3, i4); int k = comp(n, board, boardWhite, boardBlack); res = Math.min(res, k); } } } } System.out.println(res); } public void makeBoard(int[][][] arr, int[][] board, int n, int i1, int i2, int i3, int i4){ for (int i = 0; i < n; ++i){ for (int j = 0; j < n; ++j){ board[i][j] = arr[i1][i][j]; board[i][j+n] = arr[i2][i][j]; board[i+n][j] = arr[i3][i][j]; board[i+n][j+n] = arr[i4][i][j]; } } // System.out.println("board: " + board); // for (int i = 0; i < 2 * n; ++i){ // for (int j = 0; j < 2 * n; ++j){ // System.out.print(board[i][j] + " "); // } // System.out.println(); // } } public int comp(int n, int[][] board, int[][] boardWhite, int[][] boardBlack){ int dW = 0; int dB = 0; for (int i = 0; i < 2 * n; ++i){ for (int j = 0; j < 2 * n; ++j){ if (board[i][j] != boardWhite[i][j]){ dW++; } if (board[i][j] != boardBlack[i][j]){ dB++; } } } return Math.min(dW, dB); } //-----------PrintWriter for faster output--------------------------------- public static PrintWriter out; //-----------MyScanner class for faster input---------- public static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine(){ String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["1\n0\n\n0\n\n1\n\n0", "3\n101\n010\n101\n\n101\n000\n101\n\n010\n101\n011\n\n010\n101\n010"]
1 second
["1", "2"]
null
Java 8
standard input
[ "implementation", "bitmasks", "brute force" ]
dc46c6cb6b4b9b5e7e6e5b4b7d034874
The first line contains odd integer n (1 ≤ n ≤ 100) — the size of all pieces of the board. Then 4 segments follow, each describes one piece of the board. Each consists of n lines of n characters; j-th one of i-th line is equal to 1 if the square is black initially and 0 otherwise. Segments are separated by an empty line.
1,400
Print one number — minimum number of squares Magnus should recolor to be able to obtain a valid chessboard.
standard output
PASSED
2d2010af0de0144cdc6b712642058a8a
train_003.jsonl
1522850700
Magnus decided to play a classic chess game. Though what he saw in his locker shocked him! His favourite chessboard got broken into 4 pieces, each of size n by n, n is always odd. And what's even worse, some squares were of wrong color. j-th square of the i-th row of k-th piece of the board has color ak, i, j; 1 being black and 0 being white. Now Magnus wants to change color of some squares in such a way that he recolors minimum number of squares and obtained pieces form a valid chessboard. Every square has its color different to each of the neightbouring by side squares in a valid board. Its size should be 2n by 2n. You are allowed to move pieces but not allowed to rotate or flip them.
256 megabytes
import java.util.*; import java.lang.*; import java.math.*; import java.io.*; import java.util.HashSet; import java.util.Arrays; import java.util.Scanner; import java.util.Set; import java.util.ArrayList; import java.util.Collections; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.text.DecimalFormat; import java.lang.Math; import java.util.Iterator; import java.util.TreeSet; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigDecimal; import java.util.*; public class C1343{ public static PrintWriter out = new PrintWriter (new BufferedOutputStream(System.out)); static long MOD = (long)(1e9+7); static FastReader sc = new FastReader(); static int pInf = Integer.MAX_VALUE; static int nInf = Integer.MIN_VALUE; public static void main(String[] args) { int t = 1; int n = sc.nextInt(); if(n>1){ // int n = sc.nextInt(); char[][][] a = new char[4][n][n]; // char[][] a2 = new char[n][n]; // char[][] a3 = new char[n][n]; // char[][] a4 = new char[n][n]; char[][] t1 = new char[n][n]; char[][] t2 = new char[n][n]; StringBuffer s1 = new StringBuffer(""); StringBuffer s2 = new StringBuffer(""); for(int i = 0; i < n; i++){ if((i&1)==0){ s1.append('1'); s2.append('0'); } else{ s1.append('0'); s2.append('1'); } } for(int i = 0; i < n; i++){ if((i&1)==0){ t1[i] = s1.toString().toCharArray(); t2[i] = s2.toString().toCharArray(); } else{ t1[i] = s2.toString().toCharArray(); t2[i] = s1.toString().toCharArray(); } } int[][] score = new int[2][4]; for(int g = 0; g < 4; g++){ for(int i = 0; i < n; i++){ String s; if(i==n-1){ s = sc.nextLine(); } else{ s = sc.next(); } for(int j = 0; j < n; j++){ a[g][i][j] = s.charAt(j); if(a[g][i][j]!=t1[i][j]){ score[0][g]++; } if(a[g][i][j]!=t2[i][j]){ score[1][g]++; } } } } long ans = 0; for(int i = 0; i < 2; i++){ Arrays.sort(score[i]); for(int j = 0; j < 2; j++){ ans += score[i][j]; } } out.println(ans); /* for(int i = 0; i < n; i++){ for(int j = 0; j < n; j++){ out.print(t1[i][j]+" "); } out.println(); } out.println(); for(int i = 0; i < n; i++){ for(int j = 0; j < n; j++){ out.print(t2[i][j]+" "); } out.println(); }*/ } else{ String s1 = sc.next(); String s2 = sc.next(); String s3 = sc.next(); String s4 = sc.next(); int c1 = 0; if(s1.equals("1")){ c1++; } if(s2.equals("1")){ c1++; } if(s3.equals("1")){ c1++; } if(s4.equals("1")){ c1++; } //out.println(c1); if(c1==0|| c1==4){ out.println(2); } else if(c1==1 || c1==3){ out.println(1); } else if(c1==2){ out.println(0); } } out.close(); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //Merge Sort static void merge(long arr[], int l, int m, int r) { // Find sizes of two subarrays to be merged int n1 = m - l + 1; int n2 = r - m; /* Create temp arrays */ long L[] = new long [n1]; long R[] = new long [n2]; /*Copy data to temp arrays*/ for (int i=0; i<n1; ++i) L[i] = arr[l + i]; for (int j=0; j<n2; ++j) R[j] = arr[m + 1+ j]; /* Merge the temp arrays */ // Initial indexes of first and second subarrays int i = 0, j = 0; // Initial index of merged subarry array int k = l; while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } /* Copy remaining elements of L[] if any */ while (i < n1) { arr[k] = L[i]; i++; k++; } /* Copy remaining elements of R[] if any */ while (j < n2) { arr[k] = R[j]; j++; k++; } } // Main function that sorts arr[l..r] using // merge() static void sort(long arr[], int l, int r) { if (l < r) { // Find the middle point int m = (l+r)/2; // Sort first and second halves sort(arr, l, m); sort(arr , m+1, r); // Merge the sorted halves merge(arr, l, m, r); } } static class Pair implements Comparable<Pair>{ int x; int y; public Pair(int x, int y) { this.x = x; this.y = y; } @Override public int compareTo(Pair o) { // TODO Auto-generated method stub if(this.x==o.x){ return (this.y-o.y); } return (this.x-o.x); } } //Brian Kernighan’s Algorithm static long countSetBits(long n){ if(n==0) return 0; return 1+countSetBits(n&(n-1)); } //Factorial static long factorial(long n){ if(n==1) return 1; if(n==2) return 2; if(n==3) return 6; return n*factorial(n-1); } //Euclidean Algorithm static long gcd(long A,long B){ if(B==0) return A; return gcd(B,A%B); } //Modular Exponentiation static long fastExpo(long x,long n){ if(n==0) return 1; if((n&1)==0) return fastExpo((x*x)%MOD,n/2)%MOD; return ((x%MOD)*fastExpo((x*x)%MOD,(n-1)/2))%MOD; } //AKS Algorithm static boolean isPrime(long n){ if(n<=1) return false; if(n<=3) return true; if(n%2==0 || n%3==0) return false; for(int i=5;i*i<=n;i+=6) if(n%i==0 || n%(i+2)==0) return false; return true; } //Sieve of eratosthenes static int[] findPrimes(int n){ boolean isPrime[]=new boolean[n+1]; ArrayList<Integer> a=new ArrayList<>(); int result[]; Arrays.fill(isPrime,true); isPrime[0]=false; isPrime[1]=false; for(int i=2;i*i<=n;++i){ if(isPrime[i]==true){ for(int j=i*i;j<=n;j+=i) isPrime[j]=false; } } for(int i=0;i<=n;i++) if(isPrime[i]==true) a.add(i); result=new int[a.size()]; for(int i=0;i<a.size();i++) result[i]=a.get(i); return result; } //Euler Totent function static long countCoprimes(long n){ ArrayList<Long> prime_factors=new ArrayList<>(); long x=n,flag=0; while(x%2==0){ if(flag==0) prime_factors.add(2L); flag=1; x/=2; } for(long i=3;i*i<=x;i+=2){ flag=0; while(x%i==0){ if(flag==0) prime_factors.add(i); flag=1; x/=i; } } if(x>2) prime_factors.add(x); double ans=(double)n; for(Long p:prime_factors){ ans*=(1.0-(Double)1.0/p); } return (long)ans; } public static int bSearch(int n,ArrayList<Integer> A){ int s = 0; int e = A.size()-1; while(s<=e){ int m = s+(e-s)/2; if(A.get(m)==(long)n){ return A.get(m); } else if(A.get(m)>(long)n){ e = m-1; } else{ s = m+1; } } return A.get(e); } static long modulo = (long)1e9+7; public static long modinv(long x){ return modpow(x, modulo-2); } public static long modpow(long a, long b){ if(b==0){ return 1; } long x = modpow(a, b/2); x = (x*x)%modulo; if(b%2==1){ return (x*a)%modulo; } return x; } public static class FastReader { BufferedReader br; StringTokenizer st; //it reads the data about the specified point and divide the data about it ,it is quite fast //than using direct public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception r) { r.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next());//converts string to integer } double nextDouble() { return Double.parseDouble(next()); } long nextLong() { return Long.parseLong(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (Exception r) { r.printStackTrace(); } return str; } } }
Java
["1\n0\n\n0\n\n1\n\n0", "3\n101\n010\n101\n\n101\n000\n101\n\n010\n101\n011\n\n010\n101\n010"]
1 second
["1", "2"]
null
Java 8
standard input
[ "implementation", "bitmasks", "brute force" ]
dc46c6cb6b4b9b5e7e6e5b4b7d034874
The first line contains odd integer n (1 ≤ n ≤ 100) — the size of all pieces of the board. Then 4 segments follow, each describes one piece of the board. Each consists of n lines of n characters; j-th one of i-th line is equal to 1 if the square is black initially and 0 otherwise. Segments are separated by an empty line.
1,400
Print one number — minimum number of squares Magnus should recolor to be able to obtain a valid chessboard.
standard output
PASSED
5f7b673b7842a4f9d6db163fd13d9ded
train_003.jsonl
1522850700
Magnus decided to play a classic chess game. Though what he saw in his locker shocked him! His favourite chessboard got broken into 4 pieces, each of size n by n, n is always odd. And what's even worse, some squares were of wrong color. j-th square of the i-th row of k-th piece of the board has color ak, i, j; 1 being black and 0 being white. Now Magnus wants to change color of some squares in such a way that he recolors minimum number of squares and obtained pieces form a valid chessboard. Every square has its color different to each of the neightbouring by side squares in a valid board. Its size should be 2n by 2n. You are allowed to move pieces but not allowed to rotate or flip them.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; public class Main { public static void main(String[] args) throws IOException{ // write your code here BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.valueOf(br.readLine().split(" ")[0]); Helper helper = new Helper(); String [][][] str = new String[4][n][n]; for (int i = 0; i < 3; i ++){ for (int j = 0; j < n; j ++){ str[i][j] = br.readLine().split(""); } br.readLine(); } for (int j = 0; j < n; j ++){ str[3][j] = br.readLine().split(""); } int [] ans = new int[4]; for (int i = 0; i < 4; i ++){ ans[i] = helper.getMist(str[i], n); } Arrays.sort(ans); int summ = ans[0] + ans[1] + 2 * n * n - ans[2] - ans[3]; System.out.println(summ); } } class Helper { public int getMist(String[][] a, int n){ int mist = 0; for (int i = 0; i < n; i ++){ for (int j = 0; j < n; j ++){ if ((i + j) % 2 == 0 && Integer.valueOf(a[i][j]) == 1){ mist += 1; } else if ((i + j) % 2 == 1 && Integer.valueOf(a[i][j]) == 0){ mist += 1; } } } return mist; } }
Java
["1\n0\n\n0\n\n1\n\n0", "3\n101\n010\n101\n\n101\n000\n101\n\n010\n101\n011\n\n010\n101\n010"]
1 second
["1", "2"]
null
Java 8
standard input
[ "implementation", "bitmasks", "brute force" ]
dc46c6cb6b4b9b5e7e6e5b4b7d034874
The first line contains odd integer n (1 ≤ n ≤ 100) — the size of all pieces of the board. Then 4 segments follow, each describes one piece of the board. Each consists of n lines of n characters; j-th one of i-th line is equal to 1 if the square is black initially and 0 otherwise. Segments are separated by an empty line.
1,400
Print one number — minimum number of squares Magnus should recolor to be able to obtain a valid chessboard.
standard output
PASSED
70f70778b70859e69d94c13326bbfa35
train_003.jsonl
1522850700
Magnus decided to play a classic chess game. Though what he saw in his locker shocked him! His favourite chessboard got broken into 4 pieces, each of size n by n, n is always odd. And what's even worse, some squares were of wrong color. j-th square of the i-th row of k-th piece of the board has color ak, i, j; 1 being black and 0 being white. Now Magnus wants to change color of some squares in such a way that he recolors minimum number of squares and obtained pieces form a valid chessboard. Every square has its color different to each of the neightbouring by side squares in a valid board. Its size should be 2n by 2n. You are allowed to move pieces but not allowed to rotate or flip them.
256 megabytes
import java.util.*; import java.math.*; import java.io.*; public class CF961C { class Quadrant { char[][] grid; public Quadrant(char[][] gg) {grid = gg;} int length() {return grid.length;} char[] row(int i) {return grid[i];}; } class ChessBoard { int n; Quadrant[] q; char[][] grid; public ChessBoard(Quadrant...qq) { q = new Quadrant[] {qq[0], qq[1], qq[2], qq[3]}; n = qq[0].length() * 2; grid = new char[n][n]; for(int i = 0, j = n / 2 ; i < n / 2 ; i++, j++) { grid[i] = (new String(q[0].row(i)) + new String(q[1].row(i))).toCharArray(); grid[j] = (new String(q[2].row(i)) + new String(q[3].row(i))).toCharArray(); } } int minChanges() { char[] key1 = new char[n]; char[] key2 = new char[n]; for(int i = 0 ; i < n ; i++) { if(i % 2 == 0) { key1[i] = '0'; key2[i] = '1'; } else { key1[i] = '1'; key2[i] = '0'; } } int res1 = 0, res2 = 0; for(int i = 0 ; i < n ; i++) { int t = i % 2; for(int j = 0 ; j < n ; j++) { if(t == 0) { if(grid[i][j] != key1[j]) res1++; if(grid[i][j] != key2[j]) res2++; } else { if(grid[i][j] != key2[j]) res1++; if(grid[i][j] != key1[j]) res2++; } } } return Math.min(res1, res2); } void printGrid() { for(int i = 0 ; i < n ; i++) System.out.println(new String(grid[i])); System.out.println(); } } final int MOD = (int) 1e9 + 7; final double ERROR = 1e-9; final double oo = 1e50; public CF961C(SuperScanner scan, PrintWriter out) { int n = scan.nextInt(); Quadrant[] a = new Quadrant[4]; for(int k = 0 ; k < 4 ; k++) { char[][] grid = new char[n][n]; for(int i = 0 ; i < n ; i++) grid[i] = scan.next().toCharArray(); a[k] = new Quadrant(grid); } System.out.println(permute(new Quadrant[4], a, 0, 0)); } int permute(Quadrant[] q, Quadrant[] a, int d, int v) { if(d == 4) return new ChessBoard(q).minChanges(); int res = Integer.MAX_VALUE; for(int i = 0 ; i < 4 ; i++) { if((v & (1 << i)) == 0) { q[d] = a[i]; res = Math.min(res, permute(q, a, d + 1, v | (1 << i))); } } return res; } static class SuperScanner { public int BS = 1 << 16; public char NC = (char) 0; byte[] buf = new byte[BS]; int bId = 0, size = 0; char c = NC; double num = 1; BufferedInputStream in; public SuperScanner() { in = new BufferedInputStream(System.in, BS); } public SuperScanner(String s) throws FileNotFoundException { in = new BufferedInputStream(new FileInputStream(new File(s)), BS); } public char nextChar() { while (bId == size) { try { size = in.read(buf); } catch (Exception e) { return NC; } if (size == -1) return NC; bId = 0; } return (char) buf[bId++]; } public int nextInt() { return (int) nextLong(); } public long nextLong() { num = 1; boolean neg = false; if (c == NC) c = nextChar(); for (; (c < '0' || c > '9'); c = nextChar()) { if (c == '-') neg = true; } long res = 0; for (; c >= '0' && c <= '9'; c = nextChar()) { res = (res << 3) + (res << 1) + c - '0'; num *= 10; } return neg ? -res : res; } public double nextDouble() { double cur = nextLong(); return c != '.' ? cur : cur + nextLong() / num; } public String next() { StringBuilder res = new StringBuilder(); while (c <= 32) c = nextChar(); while (c > 32) { res.append(c); c = nextChar(); } return res.toString(); } public String nextLine() { StringBuilder res = new StringBuilder(); while (c <= 32) c = nextChar(); while (c != '\n') { res.append(c); c = nextChar(); } return res.toString(); } public boolean hasNext() { if (c > 32) return true; while (true) { c = nextChar(); if (c == NC) return false; else if (c > 32) return true; } } } public static void main(String[] args) { SuperScanner scan = new SuperScanner(); PrintWriter out = new PrintWriter(System.out); new CF961C(scan, out); out.close(); } }
Java
["1\n0\n\n0\n\n1\n\n0", "3\n101\n010\n101\n\n101\n000\n101\n\n010\n101\n011\n\n010\n101\n010"]
1 second
["1", "2"]
null
Java 8
standard input
[ "implementation", "bitmasks", "brute force" ]
dc46c6cb6b4b9b5e7e6e5b4b7d034874
The first line contains odd integer n (1 ≤ n ≤ 100) — the size of all pieces of the board. Then 4 segments follow, each describes one piece of the board. Each consists of n lines of n characters; j-th one of i-th line is equal to 1 if the square is black initially and 0 otherwise. Segments are separated by an empty line.
1,400
Print one number — minimum number of squares Magnus should recolor to be able to obtain a valid chessboard.
standard output
PASSED
8647ed2802bd9401f9997ba16b656234
train_003.jsonl
1522850700
Magnus decided to play a classic chess game. Though what he saw in his locker shocked him! His favourite chessboard got broken into 4 pieces, each of size n by n, n is always odd. And what's even worse, some squares were of wrong color. j-th square of the i-th row of k-th piece of the board has color ak, i, j; 1 being black and 0 being white. Now Magnus wants to change color of some squares in such a way that he recolors minimum number of squares and obtained pieces form a valid chessboard. Every square has its color different to each of the neightbouring by side squares in a valid board. Its size should be 2n by 2n. You are allowed to move pieces but not allowed to rotate or flip them.
256 megabytes
import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class ChessBoard { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = Integer.parseInt(sc.nextLine()); List<List<Integer>> boards = new ArrayList<>(); for (int i = 0; i < 4; i++) { List<Integer> board = new ArrayList<>(); for (int j = 0; j < n; j++) { String line = sc.nextLine(); for (int k = 0; k < n; k++) { board.add(line.charAt(k) == '1' ? 1 : 0); } } if (i < 3) sc.nextLine(); boards.add(board); } List<Integer> changes = new ArrayList<>(); for (List<Integer> board : boards) { int numToChangeToBe1 = 0; for (int i = 0; i < board.size(); i++) { if (i % 2 == 0 && board.get(i) == 0) { numToChangeToBe1++; } if (i % 2 == 1 && board.get(i) == 1) { numToChangeToBe1++; } } int numToChangeToBe0 = 0; for (int i = 0; i < board.size(); i++) { if (i % 2 == 0 && board.get(i) == 1) { numToChangeToBe0++; } if (i % 2 == 1 && board.get(i) == 0) { numToChangeToBe0++; } } changes.add(numToChangeToBe1); changes.add(numToChangeToBe0); } int min = Integer.MAX_VALUE; int aBlack = changes.get(0); int aWhite = changes.get(1); int bBlack = changes.get(2); int bWhite = changes.get(3); int cBlack = changes.get(4); int cWhite = changes.get(5); int dBlack = changes.get(6); int dWhite = changes.get(7); // a, b black, c, d white min = Math.min(min, aBlack + bBlack + cWhite + dWhite); // a, c black min = Math.min(min, aBlack + cBlack + bWhite + dWhite); // a, d black min = Math.min(min, aBlack + dBlack + cWhite + bWhite); // now whites min = Math.min(min, aWhite + bWhite + cBlack + dBlack); min = Math.min(min, aWhite + cWhite + bBlack + dBlack); min = Math.min(min, aWhite + dWhite + cBlack + bBlack); System.out.println(min); } }
Java
["1\n0\n\n0\n\n1\n\n0", "3\n101\n010\n101\n\n101\n000\n101\n\n010\n101\n011\n\n010\n101\n010"]
1 second
["1", "2"]
null
Java 8
standard input
[ "implementation", "bitmasks", "brute force" ]
dc46c6cb6b4b9b5e7e6e5b4b7d034874
The first line contains odd integer n (1 ≤ n ≤ 100) — the size of all pieces of the board. Then 4 segments follow, each describes one piece of the board. Each consists of n lines of n characters; j-th one of i-th line is equal to 1 if the square is black initially and 0 otherwise. Segments are separated by an empty line.
1,400
Print one number — minimum number of squares Magnus should recolor to be able to obtain a valid chessboard.
standard output
PASSED
63ee4c3ef98881d5859435a1623843cd
train_003.jsonl
1522850700
Magnus decided to play a classic chess game. Though what he saw in his locker shocked him! His favourite chessboard got broken into 4 pieces, each of size n by n, n is always odd. And what's even worse, some squares were of wrong color. j-th square of the i-th row of k-th piece of the board has color ak, i, j; 1 being black and 0 being white. Now Magnus wants to change color of some squares in such a way that he recolors minimum number of squares and obtained pieces form a valid chessboard. Every square has its color different to each of the neightbouring by side squares in a valid board. Its size should be 2n by 2n. You are allowed to move pieces but not allowed to rotate or flip them.
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.util.InputMismatchException; import java.io.IOException; import java.util.ArrayList; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.Collections; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.nextInt(); ArrayList<Integer> zeroMis = new ArrayList<>(); ArrayList<Integer> oneMis = new ArrayList<>(); String[] mat1 = new String[n]; for (int i = 0; i < n; i++) { mat1[i] = in.nextString(); } zeroMis.add(zeoMistake(mat1)); oneMis.add(oneMistake(mat1)); String[] mat2 = new String[n]; for (int i = 0; i < n; i++) { mat2[i] = in.nextString(); } zeroMis.add(zeoMistake(mat2)); oneMis.add(oneMistake(mat2)); String[] mat3 = new String[n]; for (int i = 0; i < n; i++) { mat3[i] = in.nextString(); } zeroMis.add(zeoMistake(mat3)); oneMis.add(oneMistake(mat3)); String[] mat4 = new String[n]; for (int i = 0; i < n; i++) { mat4[i] = in.nextString(); } zeroMis.add(zeoMistake(mat4)); oneMis.add(oneMistake(mat4)); Collections.sort(zeroMis); Collections.sort(oneMis); int ans = oneMis.get(0) + oneMis.get(1) + zeroMis.get(0) + zeroMis.get(1); out.print(ans); } private Integer oneMistake(String[] mat1) { int n = mat1.length; char[][] arr = new char[n][n]; for (int i = 0; i < n; i++) { arr[i] = mat1[i].toCharArray(); } int ans = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if ((i + j) % 2 == 0 && arr[i][j] != '1') { ans++; } else if ((i + j) % 2 == 1 && arr[i][j] != '0') { ans++; } } } return ans; } private Integer zeoMistake(String[] mat1) { int n = mat1.length; char[][] arr = new char[n][n]; for (int i = 0; i < n; i++) { arr[i] = mat1[i].toCharArray(); } int ans = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if ((i + j) % 2 == 0 && arr[i][j] != '0') { ans++; } else if ((i + j) % 2 == 1 && arr[i][j] != '1') { ans++; } } } return 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 print(int i) { writer.print(i); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int 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 String nextString() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { if (Character.isValidCodePoint(c)) { res.appendCodePoint(c); } c = read(); } while (!isSpaceChar(c)); return res.toString(); } 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\n0\n\n0\n\n1\n\n0", "3\n101\n010\n101\n\n101\n000\n101\n\n010\n101\n011\n\n010\n101\n010"]
1 second
["1", "2"]
null
Java 8
standard input
[ "implementation", "bitmasks", "brute force" ]
dc46c6cb6b4b9b5e7e6e5b4b7d034874
The first line contains odd integer n (1 ≤ n ≤ 100) — the size of all pieces of the board. Then 4 segments follow, each describes one piece of the board. Each consists of n lines of n characters; j-th one of i-th line is equal to 1 if the square is black initially and 0 otherwise. Segments are separated by an empty line.
1,400
Print one number — minimum number of squares Magnus should recolor to be able to obtain a valid chessboard.
standard output
PASSED
c4a0bf13b3f6b70412367ae70e8ef62c
train_003.jsonl
1522850700
Magnus decided to play a classic chess game. Though what he saw in his locker shocked him! His favourite chessboard got broken into 4 pieces, each of size n by n, n is always odd. And what's even worse, some squares were of wrong color. j-th square of the i-th row of k-th piece of the board has color ak, i, j; 1 being black and 0 being white. Now Magnus wants to change color of some squares in such a way that he recolors minimum number of squares and obtained pieces form a valid chessboard. Every square has its color different to each of the neightbouring by side squares in a valid board. Its size should be 2n by 2n. You are allowed to move pieces but not allowed to rotate or flip them.
256 megabytes
import java.io.PrintWriter; import java.util.Arrays; import java.util.Scanner; public class cf961c { static int[] item,perm; static boolean[] used; static char[][][] map; static char[][] aa; static char[][] bb; static int min; static int size; public static void main(String[] args) { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); size = sc.nextInt(); min = Integer.MAX_VALUE; map = new char[4][size][size]; aa = new char[size*2][size*2]; bb = new char[size*2][size*2]; for (int d =0 ; d < size*2; d++) { int set = d % 2; for (int a = 0 ; a < size*2; a++) { if (set %2 == 0) { aa[d][a] = '0'; bb[d][a] = '1'; }else { aa[d][a] = '1'; bb[d][a] = '0'; } set++; } } sc.nextLine(); for (int i = 0; i < 4; i++) { for (int g = 0; g < size; g++) { char[] in = sc.nextLine().toCharArray(); for (int a = 0; a < size; a++){ map[i][g][a] = in[a]; } } if (i != 3) { sc.nextLine(); } } // for (int d =0 ; d < size; d++) { // System.out.println(Arrays.toString(bb[d])); // } item = new int[]{0,1,2,3}; perm = new int[4]; used = new boolean[4]; permute(0); System.out.println(min); } public static void permute(int pos) { int j = 0; if (pos >= used.length) { // process current array char[][] m = new char[size*2][size*2]; for (int d =0 ; d < size; d++) { for (int a =0 ; a < size; a++) { m[d][a] = map[perm[0]][d][a]; } } for (int d =0 ; d < size; d++) { for (int a =0 ; a < size; a++) { m[d][a+size] = map[perm[1]][d][a]; } } for (int d =0 ; d < size; d++) { for (int a =0 ; a < size; a++) { m[d+size][a] = map[perm[2]][d][a]; } } for (int d =0 ; d < size; d++) { for (int a =0 ; a < size; a++) { m[d+size][a+size] = map[perm[3]][d][a]; } } // System.out.println("st\n\n"); // for (int d =0 ; d < size*2; d++) { // System.out.println(Arrays.toString(m[d])); // } int diffa = 0; int diffb = 0; for (int d =0 ; d < size*2; d++) { for (int a =0 ; a < size*2; a++) { if (m[d][a] != aa[d][a]) { diffa++; } if (m[d][a] != bb[d][a]) { diffb++; } } } min = Math.min(min, Math.min(diffa, diffb)); }else { for (j = 0; j < used.length; j++) { if (!used[j]) { used[j] = true; perm[pos] = item[j]; permute(pos+1); used[j] = false; } } } } } /* 3 101 010 101 101 000 101 010 101 011 010 101 010 101010 010101 101010 010101 1010BB 01B1BB 2 11 11 11 11 11 11 00 00 1 0 0 1 0 */
Java
["1\n0\n\n0\n\n1\n\n0", "3\n101\n010\n101\n\n101\n000\n101\n\n010\n101\n011\n\n010\n101\n010"]
1 second
["1", "2"]
null
Java 8
standard input
[ "implementation", "bitmasks", "brute force" ]
dc46c6cb6b4b9b5e7e6e5b4b7d034874
The first line contains odd integer n (1 ≤ n ≤ 100) — the size of all pieces of the board. Then 4 segments follow, each describes one piece of the board. Each consists of n lines of n characters; j-th one of i-th line is equal to 1 if the square is black initially and 0 otherwise. Segments are separated by an empty line.
1,400
Print one number — minimum number of squares Magnus should recolor to be able to obtain a valid chessboard.
standard output
PASSED
680528e6ac05a1b9e40f16e92dba280b
train_003.jsonl
1522850700
Magnus decided to play a classic chess game. Though what he saw in his locker shocked him! His favourite chessboard got broken into 4 pieces, each of size n by n, n is always odd. And what's even worse, some squares were of wrong color. j-th square of the i-th row of k-th piece of the board has color ak, i, j; 1 being black and 0 being white. Now Magnus wants to change color of some squares in such a way that he recolors minimum number of squares and obtained pieces form a valid chessboard. Every square has its color different to each of the neightbouring by side squares in a valid board. Its size should be 2n by 2n. You are allowed to move pieces but not allowed to rotate or flip them.
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.util.List; import java.util.ArrayList; import java.util.Collections; public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); Task solver = new Task(); solver.solve(in, out); out.close(); } static class Task { public void solve(InputReader in, PrintWriter out) { int n = in.nextInt(); int[] steps = new int[8]; int min = Integer.MAX_VALUE; String[] pieces = new String[n*4]; for (int i = 0; i < n*4; i++) { pieces[i] = in.next(); } for (int i = 0; i < 4; i++) { int count0 = 0; int count1 = 0; for (int j = 0; j < n; j++) { for (int k = 0; k < n; k++) { if (pieces[n*i + j].substring(k, k+1).equals("0")) { if ((k + j) % 2 == 0) count0 += 1; else count1 += 1; } else if ((k + j) % 2 == 0) count1 += 1; else count0 += 1; } } steps[i*2] = count0; steps[i*2 + 1] = count1; } for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { if (j == i) continue; for (int k = 0; k < 4; k++) { if (k == i || k == j) continue; for (int l = 0; l < 4; l++) { if (l == i || l == j || l == k) continue; if (steps[i*2] + steps[j*2] + steps[k*2+1] + steps[l*2+1] < min) min = steps[i*2] + steps[j*2] + steps[k*2+1] + steps[l*2+1]; } } } } out.println(min); } } 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 long nextLong() { return Long.parseLong(next()); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["1\n0\n\n0\n\n1\n\n0", "3\n101\n010\n101\n\n101\n000\n101\n\n010\n101\n011\n\n010\n101\n010"]
1 second
["1", "2"]
null
Java 8
standard input
[ "implementation", "bitmasks", "brute force" ]
dc46c6cb6b4b9b5e7e6e5b4b7d034874
The first line contains odd integer n (1 ≤ n ≤ 100) — the size of all pieces of the board. Then 4 segments follow, each describes one piece of the board. Each consists of n lines of n characters; j-th one of i-th line is equal to 1 if the square is black initially and 0 otherwise. Segments are separated by an empty line.
1,400
Print one number — minimum number of squares Magnus should recolor to be able to obtain a valid chessboard.
standard output
PASSED
91771be05e0b5051717f1f0afd131d33
train_003.jsonl
1522850700
Magnus decided to play a classic chess game. Though what he saw in his locker shocked him! His favourite chessboard got broken into 4 pieces, each of size n by n, n is always odd. And what's even worse, some squares were of wrong color. j-th square of the i-th row of k-th piece of the board has color ak, i, j; 1 being black and 0 being white. Now Magnus wants to change color of some squares in such a way that he recolors minimum number of squares and obtained pieces form a valid chessboard. Every square has its color different to each of the neightbouring by side squares in a valid board. Its size should be 2n by 2n. You are allowed to move pieces but not allowed to rotate or flip them.
256 megabytes
import java.util.*; import java.io.*; public class P961C { public static void main(String[] args) { Scanner in = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int n = in.nextInt(); Board[] boards = new Board[4]; for(int i = 0; i < 4; ++i) { String[] g = new String[n]; for(int j = 0; j < n; ++j) { g[j] = in.next(); } boards[i] = new Board(g); } int minimum = Integer.MAX_VALUE; Permutation p = new Permutation(4); while(p.hasNext()) { int[] order = p.next(); int t = boards[order[0]].topLeftOne + boards[order[1]].topLeftZero + boards[order[2]].topLeftZero + boards[order[3]].topLeftOne; minimum = Math.min(minimum, t); t = boards[order[0]].topLeftZero + boards[order[1]].topLeftOne + boards[order[2]].topLeftOne + boards[order[3]].topLeftZero; minimum = Math.min(minimum, t); } out.println(minimum); out.close(); } private static class Board { private String[] grids; int topLeftZero; int topLeftOne; public Board(String[] g) { grids = g; topLeftZero = topLeft('0'); topLeftOne = topLeft('1'); } private int topLeft(char c) { int cost = 0; for(int i = 0; i < grids.length; ++i) { for(int j = 0; j < grids[i].length(); ++j) { if((i + j) % 2 == 0) { if(grids[i].charAt(j) != c) { ++cost; } } else { if(grids[i].charAt(j) == c) { ++cost; } } } } return cost; } } private static class Permutation { private int[] numbers; private boolean first; public Permutation(int n) { numbers = new int[n]; for(int i = 0; i < n; ++i) { numbers[i] = i; } first = true; } public boolean hasNext() { if(first) { return true; } for(int i = 0; i + 1 < numbers.length; ++i) { if(numbers[i] < numbers[i + 1]) { return true; } } return false; } public int[] next() { if(first) { first = false; return numbers; } for(int i = numbers.length - 1; i >= 0; --i) { if(numbers[i - 1] < numbers[i]) { int j = i + 1; while(j < numbers.length && numbers[j] > numbers[i - 1]) { ++j; } int t = numbers[j - 1]; numbers[j - 1] = numbers[i - 1]; numbers[i - 1] = t; j = numbers.length - 1; while(i < j) { t = numbers[j]; numbers[j] = numbers[i]; numbers[i] = t; ++i; --j; } break; } } return numbers; } } }
Java
["1\n0\n\n0\n\n1\n\n0", "3\n101\n010\n101\n\n101\n000\n101\n\n010\n101\n011\n\n010\n101\n010"]
1 second
["1", "2"]
null
Java 8
standard input
[ "implementation", "bitmasks", "brute force" ]
dc46c6cb6b4b9b5e7e6e5b4b7d034874
The first line contains odd integer n (1 ≤ n ≤ 100) — the size of all pieces of the board. Then 4 segments follow, each describes one piece of the board. Each consists of n lines of n characters; j-th one of i-th line is equal to 1 if the square is black initially and 0 otherwise. Segments are separated by an empty line.
1,400
Print one number — minimum number of squares Magnus should recolor to be able to obtain a valid chessboard.
standard output
PASSED
8395b464b7d091900ea6b39a9590cba6
train_003.jsonl
1522850700
Magnus decided to play a classic chess game. Though what he saw in his locker shocked him! His favourite chessboard got broken into 4 pieces, each of size n by n, n is always odd. And what's even worse, some squares were of wrong color. j-th square of the i-th row of k-th piece of the board has color ak, i, j; 1 being black and 0 being white. Now Magnus wants to change color of some squares in such a way that he recolors minimum number of squares and obtained pieces form a valid chessboard. Every square has its color different to each of the neightbouring by side squares in a valid board. Its size should be 2n by 2n. You are allowed to move pieces but not allowed to rotate or flip them.
256 megabytes
import java.util.*; public class Main { public int getCount(boolean[][] board){ boolean rowElem = true; int res = 0; for(int i = 0; i < board.length; i++){ boolean colElem = rowElem = rowElem ^ true; for(int j = 0; j < board.length; j++){ if(board[i][j] != colElem) { res++; } colElem = colElem ^ true; } } return Math.min(res, board.length * board.length - res); } public boolean[][] getBoard(boolean[][] part1, boolean[][] part2, boolean[][] part3, boolean[][] part4 ){ boolean[][] board = new boolean[2*part1.length][2*part1.length]; for(int i = 0; i < part1.length; i++) for(int j = 0; j < part1.length; j++) board[i][j] = part1[i][j]; for(int i = part1.length; i < 2*part1.length; i++) for(int j = 0; j < part1.length; j++) board[i][j] = part3[i - part1.length][j]; for(int i = 0; i < part1.length; i++) for(int j = part1.length; j < 2*part1.length; j++) board[i][j] = part2[i][j - part1.length]; for(int i = part1.length; i < 2*part1.length; i++) for(int j = part1.length; j < 2*part1.length; j++) board[i][j] = part4[i - part1.length][j - part1.length]; return board; } public int getSolution(boolean[][] part1, boolean[][] part2, boolean[][] part3, boolean[][] part4 ){ Map<Integer, boolean[][]> map = new HashMap<>(); map.put(1, part1); map.put(2, part2); map.put(3, part3); map.put(0, part4); int res = Integer.MAX_VALUE; boolean[] taken = new boolean[4]; for(int i = 0; i < taken.length; i++){ if(taken[i]) continue; taken[i] = true; for(int j = 0; j < taken.length; j++){ if (taken[j]) continue;; taken[j] = true; for(int k = 0; k < taken.length; k++){ if(taken[k]) continue;; taken[k] = true; for(int l = 0; l < taken.length; l++){ if (taken[l]) continue; taken[l] = true; boolean[][] board = getBoard(map.get(i), map.get(j), map.get(k), map.get(l)); res = Math.min(res, getCount(board)); taken[l] = false; } taken[k] = false; } taken[j] = false; } taken[i] = false; } return res; } public static void main(String[] arg) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); boolean[][] part1 = new boolean[n][n]; boolean[][] part2 = new boolean[n][n]; boolean[][] part3 = new boolean[n][n]; boolean[][] part4 = new boolean[n][n]; for(int i = 0; i < n; i++){ String str = scanner.next(); for (int j = 0; j < n; j++) part1[i][j] = str.charAt(j) == '1'; } for(int i = 0; i < n; i++){ String str = scanner.next(); for (int j = 0; j < n; j++) part2[i][j] = str.charAt(j) == '1'; } for(int i = 0; i < n; i++){ String str = scanner.next(); for (int j = 0; j < n; j++) part3[i][j] = str.charAt(j) == '1'; } for(int i = 0; i < n; i++){ String str = scanner.next(); for (int j = 0; j < n; j++) part4[i][j] = str.charAt(j) == '1'; } Main main = new Main(); int res = main.getSolution(part1, part2, part3, part4); System.out.println(res); } }
Java
["1\n0\n\n0\n\n1\n\n0", "3\n101\n010\n101\n\n101\n000\n101\n\n010\n101\n011\n\n010\n101\n010"]
1 second
["1", "2"]
null
Java 8
standard input
[ "implementation", "bitmasks", "brute force" ]
dc46c6cb6b4b9b5e7e6e5b4b7d034874
The first line contains odd integer n (1 ≤ n ≤ 100) — the size of all pieces of the board. Then 4 segments follow, each describes one piece of the board. Each consists of n lines of n characters; j-th one of i-th line is equal to 1 if the square is black initially and 0 otherwise. Segments are separated by an empty line.
1,400
Print one number — minimum number of squares Magnus should recolor to be able to obtain a valid chessboard.
standard output
PASSED
94759d0fb940ec39ee6ef5a9a1c3cc7e
train_003.jsonl
1522850700
Magnus decided to play a classic chess game. Though what he saw in his locker shocked him! His favourite chessboard got broken into 4 pieces, each of size n by n, n is always odd. And what's even worse, some squares were of wrong color. j-th square of the i-th row of k-th piece of the board has color ak, i, j; 1 being black and 0 being white. Now Magnus wants to change color of some squares in such a way that he recolors minimum number of squares and obtained pieces form a valid chessboard. Every square has its color different to each of the neightbouring by side squares in a valid board. Its size should be 2n by 2n. You are allowed to move pieces but not allowed to rotate or flip them.
256 megabytes
import java.io.*; import java.util.*; public class Source { static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } public FastScanner(String s) { try { br = new BufferedReader(new FileReader(s)); } catch (FileNotFoundException e) { e.printStackTrace(); } } public String nextToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(nextToken()); } public long nextLong() { return Long.parseLong(nextToken()); } public double nextDouble() { return Double.parseDouble(nextToken()); } } public static void main(String args[]){ FastScanner scanner = new FastScanner(); PrintWriter writer = new PrintWriter(System.out); int n = scanner.nextInt(); boolean[][]target = new boolean[n*2][n*2]; for(int i=0;i<n*2;i++){ for(int j=i;j<n*2;j++){ boolean t = i % 2 == 0; if (j>0){ t = !target[i][j-1]; } target[i][j] = t; target[j][i] = t; } } boolean[][][]blocks =new boolean[4][n][n]; for(int t=0;t<4;t++){ for(int i=0;i<n;i++){ String line = scanner.nextToken(); for(int j=0;j<n;j++){ blocks[t][i][j] = line.charAt(j) == '1'; } } } /* 1234, 1243, 1324, 1342, 1423, 1432, 2134, 2143, 2314, 2341, 2413, 2431, 3124, 3142, 3214, 3241, 3412, 3421, 4123, 4132, 4213, 4231, 4312, 4321. */ int min = f(target,blocks[0],blocks[1], blocks[2],blocks[3]); min = Math.min(min, f(target,blocks[0],blocks[1], blocks[3],blocks[2])); min = Math.min(min, f(target,blocks[0],blocks[2], blocks[1],blocks[3])); min = Math.min(min, f(target,blocks[0],blocks[2], blocks[3],blocks[1])); min = Math.min(min, f(target,blocks[0],blocks[3], blocks[1],blocks[2])); min = Math.min(min, f(target,blocks[0],blocks[3], blocks[2],blocks[1])); min = Math.min(min, f(target,blocks[1],blocks[0], blocks[2],blocks[3])); min = Math.min(min, f(target,blocks[1],blocks[0], blocks[3],blocks[2])); min = Math.min(min, f(target,blocks[1],blocks[2], blocks[0],blocks[3])); min = Math.min(min, f(target,blocks[1],blocks[2], blocks[3],blocks[0])); min = Math.min(min, f(target,blocks[1],blocks[3], blocks[0],blocks[2])); min = Math.min(min, f(target,blocks[1],blocks[3], blocks[2],blocks[0])); min = Math.min(min, f(target,blocks[2],blocks[0], blocks[1],blocks[3])); min = Math.min(min, f(target,blocks[2],blocks[0], blocks[3],blocks[1])); min = Math.min(min, f(target,blocks[2],blocks[1], blocks[0],blocks[3])); min = Math.min(min, f(target,blocks[2],blocks[1], blocks[3],blocks[0])); min = Math.min(min, f(target,blocks[2],blocks[3], blocks[0],blocks[1])); min = Math.min(min, f(target,blocks[2],blocks[3], blocks[1],blocks[0])); min = Math.min(min, f(target,blocks[3],blocks[0], blocks[1],blocks[2])); min = Math.min(min, f(target,blocks[3],blocks[0], blocks[2],blocks[1])); min = Math.min(min, f(target,blocks[3],blocks[1], blocks[0],blocks[2])); min = Math.min(min, f(target,blocks[3],blocks[1], blocks[2],blocks[0])); min = Math.min(min, f(target,blocks[3],blocks[2], blocks[0],blocks[1])); min = Math.min(min, f(target,blocks[3],blocks[2], blocks[1],blocks[0])); writer.println(min); writer.close(); } static int f(boolean[][]target, boolean[][]b1, boolean[][]b2, boolean[][]b3, boolean[][]b4){ int n = b1.length; int ans1 = 0; int ans2 = 0; for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ if(b1[i][j] != target[i][j]){ ans1++; } else { ans2++; } } } for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ if(b2[i][j] != target[i][j+n]){ ans1++; } else { ans2++; } } } for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ if(b3[i][j] != target[i+n][j]){ ans1++; } else { ans2++; } } } for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ if(b4[i][j] != target[i+n][j+n]){ ans1++; } else { ans2++; } } } return Math.min(ans1,ans2); } }
Java
["1\n0\n\n0\n\n1\n\n0", "3\n101\n010\n101\n\n101\n000\n101\n\n010\n101\n011\n\n010\n101\n010"]
1 second
["1", "2"]
null
Java 8
standard input
[ "implementation", "bitmasks", "brute force" ]
dc46c6cb6b4b9b5e7e6e5b4b7d034874
The first line contains odd integer n (1 ≤ n ≤ 100) — the size of all pieces of the board. Then 4 segments follow, each describes one piece of the board. Each consists of n lines of n characters; j-th one of i-th line is equal to 1 if the square is black initially and 0 otherwise. Segments are separated by an empty line.
1,400
Print one number — minimum number of squares Magnus should recolor to be able to obtain a valid chessboard.
standard output
PASSED
ffdcb5b5c543f5193abf36e6ecab5d7b
train_003.jsonl
1522850700
Magnus decided to play a classic chess game. Though what he saw in his locker shocked him! His favourite chessboard got broken into 4 pieces, each of size n by n, n is always odd. And what's even worse, some squares were of wrong color. j-th square of the i-th row of k-th piece of the board has color ak, i, j; 1 being black and 0 being white. Now Magnus wants to change color of some squares in such a way that he recolors minimum number of squares and obtained pieces form a valid chessboard. Every square has its color different to each of the neightbouring by side squares in a valid board. Its size should be 2n by 2n. You are allowed to move pieces but not allowed to rotate or flip them.
256 megabytes
import java.util.*; import org.omg.PortableInterceptor.INACTIVE; import java.awt.List; import java.io.*; import java.lang.*; public class code2 { public static void main(String[] args) { InputReader in = new InputReader(System.in); PrintWriter pw = new PrintWriter(System.out); //Code starts.. int n = in.nextInt(); String[] s1 = new String[n]; String[] s2 = new String[n]; String[] s3 = new String[n]; String[] s4 = new String[n]; for(int i=0; i<n; i++) s1[i] = in.nextLine(); for(int i=0; i<n; i++) s2[i] = in.nextLine(); for(int i=0; i<n; i++) s3[i] = in.nextLine(); for(int i=0; i<n; i++) s4[i] = in.nextLine(); int min = 0; int[] tb = new int[4]; int[] tw = new int[4]; tb[0] = count(s1, 1); tb[1] = count(s2, 1); tb[2] = count(s3, 1); tb[3] = count(s4, 1); tw[0] = n*n - tb[0]; tw[1] = n*n - tb[1]; tw[2] = n*n - tb[2]; tw[3] = n*n - tb[3]; int ans = Integer.MAX_VALUE; ans = Math.min(ans, tb[0]+tb[1]+tw[2]+tw[3]); ans = Math.min(ans, tb[0]+tb[2]+tw[1]+tw[3]); ans = Math.min(ans, tb[0]+tb[3]+tw[2]+tw[1]); ans = Math.min(ans, tb[1]+tb[2]+tw[0]+tw[3]); ans = Math.min(ans, tb[1]+tb[3]+tw[0]+tw[2]); ans = Math.min(ans, tb[2]+tb[3]+tw[1]+tw[0]); pw.println(ans); //Code ends.... pw.flush(); pw.close(); } static class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar, snumChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int snext() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } public String readString() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isSpaceChar(c)); return res.toString(); } public String nextLine() { int c = snext(); while (isSpaceChar(c)) c = snext(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isEndOfLine(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } public static long c = 0; public static long mod = 1000000007; public static int d; public static int p; public static int q; public static boolean flag; public static int count(String[] s, int f) { int count = 0; int n = s[0].length(); if(f==1) { for(int i = 0; i<n; i++) { for(int j=0; j<n; j++) { if(i%2==0) { if(j%2==0 && s[i].charAt(j)=='0') count++; if(j%2==1 && s[i].charAt(j)=='1') count++; } if(i%2==1) { if(j%2==1 && s[i].charAt(j)=='0') count++; if(j%2==0 && s[i].charAt(j)=='1') count++; } } } } else { count = 0; for(int i = 0; i<n; i++) { for(int j=0; j<n; j++) { if(i%2==1) { if(j%2==0 && s[i].charAt(j)=='0') count++; if(j%2==1 && s[i].charAt(j)=='1') count++; } if(i%2==0) { if(j%2==1 && s[i].charAt(j)=='0') count++; if(j%2==0 && s[i].charAt(j)=='1') count++; } } } } return count; } public static int gcd(int p2, int p22) { if (p2 == 0) return (int) p22; return gcd(p22%p2, p2); } public static int findGCD(int arr[], int n) { int result = arr[0]; for (int i=1; i<n; i++) result = gcd(arr[i], result); return result; } public static void nextGreater(long[] a, int[] ans) { Stack<Integer> stk = new Stack<>(); stk.push(0); for(int i=1; i<a.length; i++) { if(!stk.isEmpty()) { int s = stk.pop(); while(a[s]<a[i]) { ans[s] = i; if(!stk.isEmpty()) s = stk.pop(); else break; } if(a[s]>=a[i]) stk.push(s); } stk.push(i); } return; } public static void nextGreaterRev(long[] a, int[] ans) { int n = a.length; int[] pans = new int[n]; Arrays.fill(pans, -1); long[] arev = new long[n]; for(int i=0; i<n; i++) arev[i] = a[n-1-i]; Stack<Integer> stk = new Stack<>(); stk.push(0); for(int i=1; i<n; i++) { if(!stk.isEmpty()) { int s = stk.pop(); while(arev[s]<arev[i]) { pans[s] = n - i-1; if(!stk.isEmpty()) s = stk.pop(); else break; } if(arev[s]>=arev[i]) stk.push(s); } stk.push(i); } //for(int i=0; i<n; i++) //System.out.print(pans[i]+" "); for(int i=0; i<n; i++) ans[i] = pans[n-i-1]; return; } public static void nextSmaller(long[] a, int[] ans) { Stack<Integer> stk = new Stack<>(); stk.push(0); for(int i=1; i<a.length; i++) { if(!stk.isEmpty()) { int s = stk.pop(); while(a[s]>a[i]) { ans[s] = i; if(!stk.isEmpty()) s = stk.pop(); else break; } if(a[s]<=a[i]) stk.push(s); } stk.push(i); } return; } public static long lcm(int[] numbers) { long lcm = 1; int divisor = 2; while (true) { int cnt = 0; boolean divisible = false; for (int i = 0; i < numbers.length; i++) { if (numbers[i] == 0) { return 0; } else if (numbers[i] < 0) { numbers[i] = numbers[i] * (-1); } if (numbers[i] == 1) { cnt++; } if (numbers[i] % divisor == 0) { divisible = true; numbers[i] = numbers[i] / divisor; } } if (divisible) { lcm = lcm * divisor; } else { divisor++; } if (cnt == numbers.length) { return lcm; } } } public static long fact(long n) { long factorial = 1; for(int i = 1; i <= n; i++) { factorial *= i; } return factorial; } public static int lowerLimit(int[] a, int n) { int ans = 0; int ll = 0; int rl = a.length-1; // System.out.println(a[rl]+" "+n); if(a[0]>n) return 0; if(a[0]==n) return 1; else if(a[rl]<=n) return rl+1; while(ll<=rl) { int mid = (ll+rl)/2; if(a[mid]==n) { ans = mid + 1; break; } else if(a[mid]>n) { rl = mid-1; } else { ans = mid+1; ll = mid+1; } } return ans; } public static long choose(long total, long choose){ if(total < choose) return 0; if(choose == 0 || choose == total) return 1; return (choose(total-1,choose-1)+choose(total-1,choose))%mod; } public static int[] suffle(int[] a,Random gen) { int n = a.length; for(int i=0;i<n;i++) { int ind = gen.nextInt(n-i)+i; int temp = a[ind]; a[ind] = a[i]; a[i] = temp; } return a; } public static int floorSearch(int arr[], int low, int high, int x) { if (low > high) return -1; if (x > arr[high]) return high; int mid = (low+high)/2; if (mid > 0 && arr[mid-1] < x && x < arr[mid]) return mid-1; if (x < arr[mid]) return floorSearch(arr, low, mid-1, x); return floorSearch(arr, mid+1, high, x); } public static void swap(int a, int b){ int temp = a; a = b; b = temp; } public static ArrayList<Integer> primeFactorization(int n) { ArrayList<Integer> a =new ArrayList<Integer>(); for(int i=2;i*i<=n;i++) { while(n%i==0) { a.add(i); n/=i; } } if(n!=1) a.add(n); return a; } public static void sieve(boolean[] isPrime,int n) { for(int i=1;i<n;i++) isPrime[i] = true; isPrime[0] = false; isPrime[1] = false; for(int i=2;i*i<n;i++) { if(isPrime[i] == true) { for(int j=(2*i);j<n;j+=i) isPrime[j] = false; } } } public static int lowerbound(ArrayList<Long> net, long c2) { int i=Collections.binarySearch(net, c2); if(i<0) i = -(i+2); return i; } public static int uperbound(ArrayList<Long> net, long c2) { int i=Collections.binarySearch(net, c2); if(i<0) i = -(i+1); return i; } public static int GCD(int a,int b) { if(b==0) return a; else return GCD(b,a%b); } public static long GCD(long a,long b) { if(b==0) return a; else return GCD(b,a%b); } public static void extendedEuclid(int A,int B) { if(B==0) { d = A; p = 1 ; q = 0; } else { extendedEuclid(B, A%B); int temp = p; p = q; q = temp - (A/B)*q; } } public static long LCM(long a,long b) { return (a*b)/GCD(a,b); } public static int LCM(int a,int b) { return (a*b)/GCD(a,b); } public static int binaryExponentiation(int x,int n) { int result=1; while(n>0) { if(n % 2 ==1) result=result * x; x=x*x; n=n/2; } return result; } public static int[] countDer(int n) { int der[] = new int[n + 1]; der[0] = 1; der[1] = 0; der[2] = 1; for (int i = 3; i <= n; ++i) der[i] = (i - 1) * (der[i - 1] + der[i - 2]); // Return result for n return der; } static long binomialCoeff(int n, int k) { long C[][] = new long[n+1][k+1]; int i, j; // Calculate value of Binomial Coefficient in bottom up manner for (i = 0; i <= n; i++) { for (j = 0; j <= Math.min(i, k); j++) { // Base Cases if (j == 0 || j == i) C[i][j] = 1; // Calculate value using previosly stored values else C[i][j] = C[i-1][j-1] + C[i-1][j]; } } return C[n][k]; } public static long binaryExponentiation(long x,long n) { long result=1; while(n>0) { if(n % 2 ==1) result=result * x; x=(x%mod * x%mod)%mod; n=n/2; } return result; } public static int modularExponentiation(int x,int n,int M) { int result=1; while(n>0) { if(n % 2 ==1) result=(result * x)%M; x=(x*x)%M; n=n/2; } return result; } public static long modularExponentiation(long x,long n,long M) { long result=1; while(n>0) { if(n % 2 ==1) result=(result * x)%M; x=(x*x)%M; n=n/2; } return result; } public static int modInverse(int A,int M) { return modularExponentiation(A,M-2,M); } public static long modInverse(long A,long M) { return modularExponentiation(A,M-2,M); } public static boolean checkYear(int year) { if (year % 400 == 0) return true; if (year % 100 == 0) return false; if (year % 4 == 0) return true; return false; } public static boolean isPrime(int n) { if (n <= 1) return false; if (n <= 3) return true; if (n%2 == 0 || n%3 == 0) return false; for (int i=5; i*i<=n; i=i+6) { if (n%i == 0 || n%(i+2) == 0) return false; } return true; } static class pair implements Comparable<pair> { Integer x, y; pair(int x,int y) { this.x=x; this.y=y; } public int compareTo(pair o) { int result = x.compareTo(o.x); if(result==0) result = y.compareTo(o.y); return result; } public String toString() { return x+" "+y; } public boolean equals(Object o) { if (o instanceof pair) { pair p = (pair)o; return p.x == x && p.y == y ; } return false; } public int hashCode() { return new Long(x).hashCode()*31 + new Long(y).hashCode(); } } static class triplet implements Comparable<triplet> { Integer x,y,z; triplet(int x,int y,int z) { this.x = x; this.y = y; this.z = z; } public int compareTo(triplet o) { int result = x.compareTo(o.x); if(result==0) result = y.compareTo(o.y); if(result==0) result = z.compareTo(o.z); return result; } public boolean equlas(Object o) { if(o instanceof triplet) { triplet p = (triplet)o; return x==p.x && y==p.y && z==p.z; } return false; } public String toString() { return x+" "+y+" "+z; } public int hashCode() { return new Long(x).hashCode()*31 + new Long(y).hashCode() + new Long(z).hashCode(); } } static class node implements Comparable<node> { Integer x, y, z; node(int x,int y, int z) { this.x=x; this.y=y; this.z=z; } public int compareTo(pair o) { int result = x.compareTo(o.x); if(result==0) result = y.compareTo(o.y); if(result==0) result = z.compareTo(z); return result; } @Override public int compareTo(node o) { // TODO Auto-generated method stub return 0; } } }
Java
["1\n0\n\n0\n\n1\n\n0", "3\n101\n010\n101\n\n101\n000\n101\n\n010\n101\n011\n\n010\n101\n010"]
1 second
["1", "2"]
null
Java 8
standard input
[ "implementation", "bitmasks", "brute force" ]
dc46c6cb6b4b9b5e7e6e5b4b7d034874
The first line contains odd integer n (1 ≤ n ≤ 100) — the size of all pieces of the board. Then 4 segments follow, each describes one piece of the board. Each consists of n lines of n characters; j-th one of i-th line is equal to 1 if the square is black initially and 0 otherwise. Segments are separated by an empty line.
1,400
Print one number — minimum number of squares Magnus should recolor to be able to obtain a valid chessboard.
standard output
PASSED
64bbdf7a58f650e4ecd37c9397c6a1c8
train_003.jsonl
1522850700
Magnus decided to play a classic chess game. Though what he saw in his locker shocked him! His favourite chessboard got broken into 4 pieces, each of size n by n, n is always odd. And what's even worse, some squares were of wrong color. j-th square of the i-th row of k-th piece of the board has color ak, i, j; 1 being black and 0 being white. Now Magnus wants to change color of some squares in such a way that he recolors minimum number of squares and obtained pieces form a valid chessboard. Every square has its color different to each of the neightbouring by side squares in a valid board. Its size should be 2n by 2n. You are allowed to move pieces but not allowed to rotate or flip them.
256 megabytes
import java.util.Scanner; import java.util.Arrays; import java.math.*; import java.util.Collections; public class codeforce{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int[] nb0 = new int[4]; int[] nb1 = new int[4]; String[][] s = new String[4][n]; for(int k=0;k<4;k++){ for(int i=0;i<n;i++){ s[k][i] = sc.next(); } } for(int k=0;k<4;k++){ boolean ok = true; nb0[k] = 0; nb1[k] = 0; for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ if(ok){ ok = false; if(s[k][i].charAt(j)!='0') nb0[k]++; else nb1[k]++; } else{ ok = true; if(s[k][i].charAt(j)=='0') nb0[k]++; else nb1[k]++; } } } } int max; max = nb0[0] + nb0[1] +nb1[2] + nb1[3]; int test; for(int k=0;k<3;k++){ for(int kk=k+1;kk<4;kk++){ if(k==0&&kk==1) continue; test = nb0[k]+nb0[kk]; for(int i=0;i<4;i++){ if(i!=k && i!=kk) test += nb1[i]; } if(max>test) max = test; } } System.out.println(max); } }
Java
["1\n0\n\n0\n\n1\n\n0", "3\n101\n010\n101\n\n101\n000\n101\n\n010\n101\n011\n\n010\n101\n010"]
1 second
["1", "2"]
null
Java 8
standard input
[ "implementation", "bitmasks", "brute force" ]
dc46c6cb6b4b9b5e7e6e5b4b7d034874
The first line contains odd integer n (1 ≤ n ≤ 100) — the size of all pieces of the board. Then 4 segments follow, each describes one piece of the board. Each consists of n lines of n characters; j-th one of i-th line is equal to 1 if the square is black initially and 0 otherwise. Segments are separated by an empty line.
1,400
Print one number — minimum number of squares Magnus should recolor to be able to obtain a valid chessboard.
standard output
PASSED
982d7e7732747a4d4800ae4578681f0d
train_003.jsonl
1522850700
Magnus decided to play a classic chess game. Though what he saw in his locker shocked him! His favourite chessboard got broken into 4 pieces, each of size n by n, n is always odd. And what's even worse, some squares were of wrong color. j-th square of the i-th row of k-th piece of the board has color ak, i, j; 1 being black and 0 being white. Now Magnus wants to change color of some squares in such a way that he recolors minimum number of squares and obtained pieces form a valid chessboard. Every square has its color different to each of the neightbouring by side squares in a valid board. Its size should be 2n by 2n. You are allowed to move pieces but not allowed to rotate or flip them.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.IOException; import java.util.Scanner; import java.util.Arrays; import java.util.Collections; import java.util.ArrayList; public class Main { public static void main (String[] args) throws IOException { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); ArrayList<meh> grids = new ArrayList<>(); for(int c = 0; c < 4; c++){ sc.nextLine(); int numChangesEven = 0, numChangesOdd = 0; for(int i = 0; i < n; i++){ String in = sc.nextLine(); for(int j = 0; j < n; j++){ int check = (int)(in.charAt(j) - '0'); if((i + j) % 2 == check){ numChangesEven++; } else{ numChangesOdd++; } } } grids.add(new meh(numChangesEven, numChangesOdd)); } Collections.sort(grids, (a, b) -> { return (int)Math.min(a.numChangesEven, a.numChangesOdd) - (int)Math.min(b.numChangesEven, b.numChangesOdd); }); int even = 2, odd = 2; int out = 0; for(int i = 0; i < 4; i++){ meh curr = grids.get(i); if(even == 0){ out += curr.numChangesOdd; odd--; } else if(odd == 0){ out += curr.numChangesEven; even--; } else{ if(curr.wantsEven()){ out += curr.numChangesEven; even--; } else{ out += curr.numChangesOdd; odd--; } } } System.out.println(out); } } class meh{ int numChangesEven, numChangesOdd; meh(int numChangesEvenIn, int numChangesOddIn){ numChangesEven = numChangesEvenIn; numChangesOdd = numChangesOddIn; } boolean wantsEven(){ if(numChangesEven < numChangesOdd) return true; return false; } }
Java
["1\n0\n\n0\n\n1\n\n0", "3\n101\n010\n101\n\n101\n000\n101\n\n010\n101\n011\n\n010\n101\n010"]
1 second
["1", "2"]
null
Java 8
standard input
[ "implementation", "bitmasks", "brute force" ]
dc46c6cb6b4b9b5e7e6e5b4b7d034874
The first line contains odd integer n (1 ≤ n ≤ 100) — the size of all pieces of the board. Then 4 segments follow, each describes one piece of the board. Each consists of n lines of n characters; j-th one of i-th line is equal to 1 if the square is black initially and 0 otherwise. Segments are separated by an empty line.
1,400
Print one number — minimum number of squares Magnus should recolor to be able to obtain a valid chessboard.
standard output
PASSED
994f1fe6fa1d22292baec0e79f815f32
train_003.jsonl
1522850700
Magnus decided to play a classic chess game. Though what he saw in his locker shocked him! His favourite chessboard got broken into 4 pieces, each of size n by n, n is always odd. And what's even worse, some squares were of wrong color. j-th square of the i-th row of k-th piece of the board has color ak, i, j; 1 being black and 0 being white. Now Magnus wants to change color of some squares in such a way that he recolors minimum number of squares and obtained pieces form a valid chessboard. Every square has its color different to each of the neightbouring by side squares in a valid board. Its size should be 2n by 2n. You are allowed to move pieces but not allowed to rotate or flip them.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.Random; import java.util.StringTokenizer; public class Main { public static void main(String[] args) throws IOException, InterruptedException { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { static boolean visited[] ; static boolean found = false; static int steps = 0 ; static int n ; static boolean memo [][] ; static int dp[][] ; static char matrix[][] ; static ArrayList<Integer> p ; public void solve(int testNumber, InputReader in, PrintWriter out) throws IOException, InterruptedException { int n=in.nextInt() ; int[][]matrix1 = new int[n][n]; for (int i = 0; i < n; i++) { String x = in.next(); for (int j = 0; j <n; j++) { if(x.charAt(j)=='1')matrix1[i][j]=1 ; else matrix1[i][j]=0 ; } } int[][]matrix2 = new int[n][n]; for (int i = 0; i < n; i++) { String x = in.next(); for (int j = 0; j <n; j++) { if(x.charAt(j)=='1')matrix2[i][j]=1 ; else matrix2[i][j]=0 ; } } int[][]matrix3 = new int[n][n]; for (int i = 0; i < n; i++) { String x = in.next(); for (int j = 0; j <n; j++) { if(x.charAt(j)=='1')matrix3[i][j]=1 ; else matrix3[i][j]=0 ; } } int[][]matrix4 = new int[n][n]; for (int i = 0; i < n; i++) { String x = in.next(); for (int j = 0; j <n; j++) { if(x.charAt(j)=='1')matrix4[i][j]=1 ; else matrix4[i][j]=0 ; } } int mat11=cnt1(matrix1) ; int mat21=cnt1(matrix2) ; int mat31=cnt1(matrix3) ; int mat41=cnt1(matrix4) ; int[] m = new int[4]; m[0]=mat11 ; m[1]=mat21 ; m[2]=mat31; m[3] = mat41 ; Arrays.sort(m); int res =0 ; res = m[0]+m[1]+(2*(n*n))-m[2]-m[3] ; System.out.println(res); } public static int cnt1(int mat[][]) //how many swaps to be a 1 matrix { int m = mat.length ; int c=0 ; for (int i = 0; i < mat.length; i++) { for (int j = 0; j < mat.length; j++) { int x = (i*m) +j ; if(x%2==0 && mat[i][j]==0) c++; if(x%2!=0 && mat[i][j]==1) c++; } } return c; } public static int cnt0(int mat[][]) { int m = mat.length ; int c=0 ; for (int i = 0; i < mat.length; i++) { for (int j = 0; j < mat.length; j++) { int x = (i*m) +j ; if(x%2!=0 && mat[i][j]==0) c++; if(x%2==0 && mat[i][j]==1) c++; } } return c; } public static boolean canFit2(int x1, int y1 , int x2 , int y2 , int x3 , int y3){ if(x1==x2) if(x1==x3) return true ; else return false ; else if(x1==x3) return false ; else { long a = 1l*(y2-y1)*(x3-x2) ; long b = 1l*(y3-y2)*(x2-x1) ; if(a==b) return true; else return false ; } } public static void shuffle(int c[]){ if(c.length==1) return ; for (int i = 0; i < c.length; i++) { Random rand = new Random(); int n = rand.nextInt(c.length-1) + 0; int temp = c[i] ; c[i] = c[n] ; c[n] = temp ; } } public static int binary(ArrayList<Long> arr, int l, int r, long x) /// begin by 0 and n-1 { if (r>=l) { int mid = l + (r - l)/2; if (arr.get(mid) == x) return mid; if (arr.get(mid)> x) return binary(arr, l, mid-1, x); return binary(arr, mid+1, r, x); } return -1; } /// searching for the index of first elment greater than x public static int binary1(ArrayList<Long> arr , long left) { int low = 0, high = arr.size(); // numElems is the size of the array i.e arr.size() while (low != high) { int mid = (low + high) / 2; // Or a fancy way to avoid int overflow if (arr.get(mid) <= left) { /* This index, and everything below it, must not be the first element * greater than what we're looking for because this element is no greater * than the element. */ low = mid + 1; } else { /* This element is at least as large as the element, so anything after it can't * be the first element that's at least as large. */ high = mid; } } return low ; // return high ; } private static boolean triangle(int a, int b , int c){ if(a+b>c && a+c>b && b+c>a) return true ; else return false ; } private static boolean segment(int a, int b , int c){ if(a+b==c || a+c==b && b+c==a) return true ; else return false ; } private static int gcdThing(long a, long b) { BigInteger b1 = BigInteger.valueOf(a); BigInteger b2 = BigInteger.valueOf(b); BigInteger gcd = b1.gcd(b2); return gcd.intValue(); } public static boolean is(int i){ if(Math.log(i)/ Math.log(2) ==(int) (Math.log(i)/ Math.log(2))) return true ; if(Math.log(i)/ Math.log(3) ==(int) (Math.log(i)/ Math.log(3)) ) return true ; if(Math.log(i)/ Math.log(6) ==(int) (Math.log(i)/ Math.log(6)) ) return true ; return false; } public static boolean contains(int b[] , int x) { for (int i = 0; i < b.length; i++) { if(b[i]==x) return true ; } return false ; } public static int binary(long []arr , long target , int low , long shift) { int high = arr.length; while (low != high) { int mid = (low + high) / 2; if (arr[mid]-shift <= target) { low = mid + 1; } else { high = mid; } } return low ; // return high ; } public static boolean isLetter(char x){ if(x+0 <=122 && x+0 >=97 ) return true ; else if (x+0 <=90 && x+0 >=65 ) return true ; else return false; } public static long getPrimes(long x ){ if(x==2 || x==3 || x==1) return 2 ; if(isPrime(x)) return 5 ; for (int i = 2; i*i<=x; i++) { if(x%i==0 && isPrime(i)) return getPrimes(x/i) ; } return -1; } public static String solve(String x){ int n = x.length() ; String y = "" ; for (int i = 0; i < n-2; i+=2) { if(ifPalindrome(x.substring(i, i+2))) y+= x.substring(i, i+2) ; else break ; } return y+ solve1(x.substring(y.length(),x.length())) ; } public static String solve1(String x){ String y = x.substring(0 , x.length()/2) ; return "" ; } public static String reverse(String x){ String y ="" ; for (int i = 0; i < x.length(); i++) { y = x.charAt(i) + y ; } return y ; } public static boolean ifPalindrome(String x){ int numbers[] = new int[10] ; for (int i = 0; i < x.length(); i++) { int z = Integer.parseInt(x.charAt(i)+"") ; numbers[z] ++ ; } for (int i = 0; i < numbers.length; i++) { if(numbers[i]%2!=0) return false; } return true ; } public static int get(int n){ return n*(n+1)/2 ; } // public static long getSmallestDivisor( long y){ // if(isPrime(y)) // return -1; // // for (long i = 2; i*i <= y; i++) // { // if(y%i ==0) // { // return i; // } // } // return -1; // } // public static void lis(pair []a , int n){ // int lis[] = new int[n] ; // Arrays.fill(lis,1) ; // // for(int i=1;i<n;i++) // for(int j=0 ; j<i; j++) // if (a[i].y>a[j].y && lis[i] < lis[j]+1) // lis[i] = lis[j] + 1; // // int max = lis[0]; // // for(int i=1; i<n ; i++) // if (max < lis[i]) // max = lis[i] ; // System.out.println(max); // // ArrayList<Integer> s = new ArrayList<Integer>() ; // for (int i = n-1; i >=0; i--) // { // if(lis[i]==max) // { // s.add(a[i].z); // max --; // } // } // // for (int i = s.size()-1 ; i>=0 ; i--) // { // System.out.print(s.get(i)+" "); // } // // return ; // } public static int calcDepth(Vertix node){ if(node.depth>0) return node.depth; // meaning it has been updated before; if(node.parent != null) return 1+ calcDepth(node.parent); else return -1; } public static boolean isPrime (long num){ if (num < 2) return false; if (num == 2) return true; if (num % 2 == 0) return false; for (int i = 3; i * i <= num; i += 2) if (num % i == 0) return false; return true; } public static int[] getDiv(int n) { int result[] = new int[7] ; ArrayList<Integer> f = new ArrayList<Integer>() ; while (n%2==0) { if(!f.contains(2))f.add(2) ; n /= 2; } // n must be odd at this point. So we can // skip one element (Note i = i +2) for (int i = 3; i <= Math.sqrt(n); i+= 2) { // While i divides n, print i and divide n while (n%i == 0) { if(!f.contains(i))f.add(i); n /= i; } } // This condition is to handle the case whien // n is a prime number greater than 2 if (n > 2) if(!f.contains(n))f.add(n); for (int i = 0, j=0; i < f.size(); i++) { result[j++]=f.get(i); } return result ; } public static boolean dfs(Vertix v , int target){ try{ visited[v.i]= true ; } catch (NullPointerException e) { System.out.println(v.i); } if(v.i == target) return true ; for (int i =0 ; i< v.neighbours.size() ; i++) { Vertix child = v.neighbours.get(i) ; if(child.i == target){ found = true ; } if(visited[child.i]==false){ found |= dfs(child, target) ; } } return found; } } 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 static class Vertix{ int i ; int depth ; ArrayList<Vertix> neighbours ; Vertix parent ; public Vertix(int i){ this.i = i ; this.neighbours = new ArrayList<Vertix> () ; this.parent = null ; depth =-1; } } public static class pair implements Comparable<pair>{ int x ; int y ; public pair(int x, int y , int z){ this.x=x ; this.y=y ; } @Override public int compareTo(pair p) { if(this.x > p.x) return 1 ; else return -1 ; } } }
Java
["1\n0\n\n0\n\n1\n\n0", "3\n101\n010\n101\n\n101\n000\n101\n\n010\n101\n011\n\n010\n101\n010"]
1 second
["1", "2"]
null
Java 8
standard input
[ "implementation", "bitmasks", "brute force" ]
dc46c6cb6b4b9b5e7e6e5b4b7d034874
The first line contains odd integer n (1 ≤ n ≤ 100) — the size of all pieces of the board. Then 4 segments follow, each describes one piece of the board. Each consists of n lines of n characters; j-th one of i-th line is equal to 1 if the square is black initially and 0 otherwise. Segments are separated by an empty line.
1,400
Print one number — minimum number of squares Magnus should recolor to be able to obtain a valid chessboard.
standard output
PASSED
8afa87656a6d6fb877bfa5282264bab4
train_003.jsonl
1522850700
Magnus decided to play a classic chess game. Though what he saw in his locker shocked him! His favourite chessboard got broken into 4 pieces, each of size n by n, n is always odd. And what's even worse, some squares were of wrong color. j-th square of the i-th row of k-th piece of the board has color ak, i, j; 1 being black and 0 being white. Now Magnus wants to change color of some squares in such a way that he recolors minimum number of squares and obtained pieces form a valid chessboard. Every square has its color different to each of the neightbouring by side squares in a valid board. Its size should be 2n by 2n. You are allowed to move pieces but not allowed to rotate or flip them.
256 megabytes
import java.io.*; import java.util.*; import java.lang.*; import static java.lang.Math.min; import static java.lang.Math.max; public class Main { static class Task { int n, ans = Integer.MAX_VALUE; String s1 = "", s2 = ""; String[] a1; void permutation(int pos, int[] a) { if (pos == a.length - 1) { String[] s = new String[2 * n]; for (int i = 0; i < 2 * n; i++) { s[i] = ""; } for (int i = 0; i < n; i++) { s[i] += a1[n * a[0] + i]; s[i] += a1[n * a[3] + i]; } int f = 0; for (int i = n; i < 2 * n; i++) { s[i] += a1[n * a[1] + f]; s[i] += a1[n * a[2] + f]; f++; } int cnt1 = 0, cnt2 = 0; for (int i = 0; i < 2 * n; i++) { for (int j = 0; j < 2 * n; j++) { if (i % 2 == 0) { if (s1.charAt(j) != s[i].charAt(j)) { cnt1++; } if (s2.charAt(j) != s[i].charAt(j)) { cnt2++; } } else { if (s2.charAt(j) != s[i].charAt(j)) { cnt1++; } if (s1.charAt(j) != s[i].charAt(j)) { cnt2++; } } } } ans = min(ans, min(cnt1, cnt2)); } else { for (int i = pos; i < a.length; i++) { int temp = a[i]; a[i] = a[pos]; a[pos] = temp; permutation(pos + 1, a); temp = a[i]; a[i] = a[pos]; a[pos] = temp; } } } void solve(int test, FastScanner in, PrintWriter out) throws IOException { n = in.nextInt(); a1 = new String[4 * n]; for (int i = 0; i < 4 * n; i++) { a1[i] = in.nextToken(); } for (int i = 0; i < 2 * n; i++) { if (i % 2 == 0) { s1 += '0'; s2 += '1'; } else { s2 += '0'; s1 += '1'; } } int[] a = new int[4]; for (int i = 0; i < 4; i++) { a[i] = i; } permutation(0, a); out.println(ans); } } public static void main(String[] args) throws IOException { FastScanner in = new FastScanner(System.in); PrintWriter out = new PrintWriter(System.out); // FastScanner in = new FastScanner("lemonade.in"); // PrintWriter out = new PrintWriter(new FileWriter("lemonade.out")); new Task().solve(1, in, out); out.close(); } static class FastScanner { BufferedReader br; StringTokenizer token; public FastScanner(InputStream is) { br = new BufferedReader(new InputStreamReader(System.in)); } public FastScanner(String s) { try { br = new BufferedReader(new FileReader(s)); } catch (FileNotFoundException e) { e.printStackTrace(); } } public String nextToken() { while (token == null || !token.hasMoreTokens()) { try { token = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return token.nextToken(); } public int nextInt() { return Integer.parseInt(nextToken()); } public long nextLong() { return Long.parseLong(nextToken()); } public double nextDouble() { return Double.parseDouble(nextToken()); } } }
Java
["1\n0\n\n0\n\n1\n\n0", "3\n101\n010\n101\n\n101\n000\n101\n\n010\n101\n011\n\n010\n101\n010"]
1 second
["1", "2"]
null
Java 8
standard input
[ "implementation", "bitmasks", "brute force" ]
dc46c6cb6b4b9b5e7e6e5b4b7d034874
The first line contains odd integer n (1 ≤ n ≤ 100) — the size of all pieces of the board. Then 4 segments follow, each describes one piece of the board. Each consists of n lines of n characters; j-th one of i-th line is equal to 1 if the square is black initially and 0 otherwise. Segments are separated by an empty line.
1,400
Print one number — minimum number of squares Magnus should recolor to be able to obtain a valid chessboard.
standard output
PASSED
ea394a7e6d3245b9667f734b607264a3
train_003.jsonl
1522850700
Magnus decided to play a classic chess game. Though what he saw in his locker shocked him! His favourite chessboard got broken into 4 pieces, each of size n by n, n is always odd. And what's even worse, some squares were of wrong color. j-th square of the i-th row of k-th piece of the board has color ak, i, j; 1 being black and 0 being white. Now Magnus wants to change color of some squares in such a way that he recolors minimum number of squares and obtained pieces form a valid chessboard. Every square has its color different to each of the neightbouring by side squares in a valid board. Its size should be 2n by 2n. You are allowed to move pieces but not allowed to rotate or flip them.
256 megabytes
//package main; import java.io.*; import java.util.*; import java.math.*; public final class Main { BufferedReader br; StringTokenizer stk; public static void main(String[] args) throws Exception { new Main().run(); } { stk = null; br = new BufferedReader(new InputStreamReader(System.in)); } boolean tests = false; long mod = 1000_000_000 + 7; StringBuilder res = new StringBuilder(1000005); void run() throws Exception { int t = tests ? ni() : 1; for(int i = 1; i <= t; i++) { go(i); } System.out.print(res.length() == 0 ? "" : res); } void go(int T) throws Exception { int n = ni(); char[][] a = new char[n][]; char[][] b = new char[n][]; char[][] c = new char[n][]; char[][] d = new char[n][]; for(int i = 0; i < n; i++) { a[i] = nc(); } for(int i = 0; i < n; i++) { b[i] = nc(); } for(int i = 0; i < n; i++) { c[i] = nc(); } for(int i = 0; i < n; i++) { d[i] = nc(); } int max = Integer.MAX_VALUE; char[][][] bds = new char[][][] {a, b, c, d}; for(int i = 0; i < 4; i++) { for(int j = 0; j < 4; j++) { for(int k = 0; k < 4; k++) { for(int l = 0; l < 4; l++) { int[] arr = new int[4]; arr[i]++; arr[j]++; arr[k]++; arr[l]++; if(arr[0] == 1 && arr[1] == 1 && arr[2] == 1 && arr[3] == 1) { max = Math.min(max, evaluate(arrange(bds[i], bds[j], bds[k], bds[l]))); } } } } } res.append(max).append("\n"); } char[][] arrange(char[][] a, char[][] b, char[][] c, char[][] d) { int n = a.length; char[][] comp = new char[2 * n][2 * n]; int row = 0, col = 0; for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { comp[row][col++] = a[i][j]; } for(int j = 0; j < n; j++) { comp[row][col++] = b[i][j]; } row++; col = 0; } for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { comp[row][col++] = c[i][j]; } for(int j = 0; j < n; j++) { comp[row][col++] = d[i][j]; } row++; col = 0; } return comp; } int evaluate(char[][] a) { int n = a.length; char[][] x = new char[n][n]; char[][] y = new char[n][n]; x[0][0] = '0'; y[0][0] = '1'; for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { if(x[i][j] == '0') { continue; } if(j != 0) { x[i][j] = (x[i][j - 1] == '0') ? '1' : '0'; } else { x[i][j] = (x[i - 1][j] == '0') ? '1' : '0'; } y[i][j] = (x[i][j] == '0') ? '1' : '0'; } } int mx = 0, my = 0; for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { if(x[i][j] != a[i][j]) { mx++; } if(y[i][j] != a[i][j]) { my++; } } } return Math.min(mx, my); } //Reader & Writer String nt() throws Exception { if (stk == null || !stk.hasMoreTokens()) stk = new StringTokenizer(br.readLine(), " "); if(!stk.hasMoreElements()) stk = new StringTokenizer(br.readLine(), " "); return stk.nextToken(); } char[] nc() throws Exception { return nt().toCharArray(); } int ni() throws Exception { return Integer.parseInt(nt()); } long nl() throws Exception { return Long.parseLong(nt()); } double nd() throws Exception { return Double.parseDouble(nt()); } //Some Misc methods int get(int l, int r, int[] a) { return l == 0 ? a[r] : a[r] - a[l - 1]; } void shuffle(long[] a) { Random r = new Random(); for(int i = 0; i < a.length; i++) { int idx = r.nextInt(a.length); long temp = a[i]; a[i] = a[idx]; a[idx] = temp; } } void reverse(long[] a) { for(int i = 0, j = a.length - 1; i < j; i++, j--) { long temp = a[i]; a[i] = a[j]; a[j] = temp; } } void print(int[] a) { System.out.println(Arrays.toString(a)); } void print(long[] a) { System.out.println(Arrays.toString(a)); } }
Java
["1\n0\n\n0\n\n1\n\n0", "3\n101\n010\n101\n\n101\n000\n101\n\n010\n101\n011\n\n010\n101\n010"]
1 second
["1", "2"]
null
Java 8
standard input
[ "implementation", "bitmasks", "brute force" ]
dc46c6cb6b4b9b5e7e6e5b4b7d034874
The first line contains odd integer n (1 ≤ n ≤ 100) — the size of all pieces of the board. Then 4 segments follow, each describes one piece of the board. Each consists of n lines of n characters; j-th one of i-th line is equal to 1 if the square is black initially and 0 otherwise. Segments are separated by an empty line.
1,400
Print one number — minimum number of squares Magnus should recolor to be able to obtain a valid chessboard.
standard output
PASSED
ccf5a9a6594bdca49120b5582f734aaa
train_003.jsonl
1522850700
Magnus decided to play a classic chess game. Though what he saw in his locker shocked him! His favourite chessboard got broken into 4 pieces, each of size n by n, n is always odd. And what's even worse, some squares were of wrong color. j-th square of the i-th row of k-th piece of the board has color ak, i, j; 1 being black and 0 being white. Now Magnus wants to change color of some squares in such a way that he recolors minimum number of squares and obtained pieces form a valid chessboard. Every square has its color different to each of the neightbouring by side squares in a valid board. Its size should be 2n by 2n. You are allowed to move pieces but not allowed to rotate or flip them.
256 megabytes
import java.io.*; import java.util.*; public class Main { static int pt=0; static int[][] p; public static void main(String args[]) { Scanner in = new Scanner(new BufferedReader(new InputStreamReader(System.in))); PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)), false); p = new int[24][4]; permute(new int[]{1,2,3,4}, 0,3); // Permutations... // for(int[] t:p){ // for(int j:t){ // out.print(j+" "); // }out.println(); // } int n = in.nextInt(); int a[][][] = new int[4][n][n]; for(int i=0;i<4;i++){ for(int j=0;j<n;j++){ String s = in.next(); for(int k=0;k<n;k++){ a[i][j][k] = s.charAt(k)=='0'?0:1; } } } int cost[] = new int[4]; for(int i=0;i<4;i++){ cost[i] = compute(a[i]); } // for(int i:cost) out.println("cst: "+i); int mn = Integer.MAX_VALUE; int cst=0; for(int[] i:p){ cst=0; for(int j=0;j<2;j++){ cst+=cost[i[j]-1]; } for(int j=2;j<4;j++){ cst+=(n*n-cost[i[j]-1]); } // out.println("C: "+cst); mn = Math.min(cst, mn); } out.println(mn); in.close();out.flush();out.close(); } static int compute(int a[][]){ int n = a.length; int cst = 0; int mark=1; for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ if(a[i][j]!=mark) cst++; mark = 1 - mark; } } return cst; } static void permute(int[] ar, int l, int r){ if(l==r){ for(int i=0;i<4;i++) p[pt][i] = ar[i]; ++pt; }else{ int tmp=0; for(int i=l;i<=r;i++){ tmp = ar[l]; ar[l] = ar[i]; ar[i] = tmp; permute(ar,l+1,r); tmp = ar[l]; ar[l] = ar[i]; ar[i] = tmp; } } } }
Java
["1\n0\n\n0\n\n1\n\n0", "3\n101\n010\n101\n\n101\n000\n101\n\n010\n101\n011\n\n010\n101\n010"]
1 second
["1", "2"]
null
Java 8
standard input
[ "implementation", "bitmasks", "brute force" ]
dc46c6cb6b4b9b5e7e6e5b4b7d034874
The first line contains odd integer n (1 ≤ n ≤ 100) — the size of all pieces of the board. Then 4 segments follow, each describes one piece of the board. Each consists of n lines of n characters; j-th one of i-th line is equal to 1 if the square is black initially and 0 otherwise. Segments are separated by an empty line.
1,400
Print one number — minimum number of squares Magnus should recolor to be able to obtain a valid chessboard.
standard output
PASSED
58f9a3cfa782ebb74ca3bbc4bd38e74d
train_003.jsonl
1522850700
Magnus decided to play a classic chess game. Though what he saw in his locker shocked him! His favourite chessboard got broken into 4 pieces, each of size n by n, n is always odd. And what's even worse, some squares were of wrong color. j-th square of the i-th row of k-th piece of the board has color ak, i, j; 1 being black and 0 being white. Now Magnus wants to change color of some squares in such a way that he recolors minimum number of squares and obtained pieces form a valid chessboard. Every square has its color different to each of the neightbouring by side squares in a valid board. Its size should be 2n by 2n. You are allowed to move pieces but not allowed to rotate or flip them.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.StringTokenizer; public class C { public static void main(String[] args) { FastScanner fs=new FastScanner(); int n=fs.nextInt(); int[] counts=new int[4]; for (int b=0; b<4; b++) { int count=0; for (int y=0; y<n; y++) { String line=fs.next(); for (int x=0; x<n; x++) { boolean white=(x+y)%2==0; boolean isW=line.charAt(x)=='0'; if (white^isW) count++; } } counts[b]=count; } Arrays.sort(counts); long min=counts[0]+counts[1]+n*n+n*n-counts[2]-counts[3]; // System.out.println(Arrays.toString(counts)); System.out.println(min); } static class Rect { int x1, x2, y1, y2; public Rect(int x1, int y1, int x2, int y2) { this.x1=x1; this.x2=x2; this.y1=y1; this.y2=y2; } public Rect union(Rect o) { return new Rect(Math.max(x1, o.x1), Math.max(y1, o.y1), Math.min(x2, o.x2), Math.min(y2, o.y2)); } public boolean valid() { return x1<=x2&&y1<=y2; } } static class Song implements Comparable<Song> { long uncompressed, compressed; public Song(long uncompressed, long compressed) { this.uncompressed=uncompressed; this.compressed=compressed; } public int compareTo(Song o) { long diff=(uncompressed-compressed); long oDiff=o.uncompressed-o.compressed; return Long.compare(oDiff, diff); } } static double eval(int first, int second) { return (first*(double)first+second*second)/(first*second); } static class FastScanner { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); public String next() { while (!st.hasMoreElements()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public int[] readArray(int n) { int[] a=new int[n]; for (int i=0; i<n; i++) { a[i]=nextInt(); } return a; } public double nextDouble() { return Double.parseDouble(next()); } } }
Java
["1\n0\n\n0\n\n1\n\n0", "3\n101\n010\n101\n\n101\n000\n101\n\n010\n101\n011\n\n010\n101\n010"]
1 second
["1", "2"]
null
Java 8
standard input
[ "implementation", "bitmasks", "brute force" ]
dc46c6cb6b4b9b5e7e6e5b4b7d034874
The first line contains odd integer n (1 ≤ n ≤ 100) — the size of all pieces of the board. Then 4 segments follow, each describes one piece of the board. Each consists of n lines of n characters; j-th one of i-th line is equal to 1 if the square is black initially and 0 otherwise. Segments are separated by an empty line.
1,400
Print one number — minimum number of squares Magnus should recolor to be able to obtain a valid chessboard.
standard output
PASSED
854736ea4cff2e2e11a772c1e4e2e25c
train_003.jsonl
1522850700
Magnus decided to play a classic chess game. Though what he saw in his locker shocked him! His favourite chessboard got broken into 4 pieces, each of size n by n, n is always odd. And what's even worse, some squares were of wrong color. j-th square of the i-th row of k-th piece of the board has color ak, i, j; 1 being black and 0 being white. Now Magnus wants to change color of some squares in such a way that he recolors minimum number of squares and obtained pieces form a valid chessboard. Every square has its color different to each of the neightbouring by side squares in a valid board. Its size should be 2n by 2n. You are allowed to move pieces but not allowed to rotate or flip them.
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 sumit */ 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); CChessboard solver = new CChessboard(); solver.solve(1, in, out); out.close(); } static class CChessboard { int[] nextPermutation(int[] array) { int i = array.length - 1; while (i > 0 && array[i - 1] >= array[i]) { i--; } if (i <= 0) { return null; } int j = array.length - 1; while (array[j] <= array[i - 1]) { j--; } int temp = array[i - 1]; array[i - 1] = array[j]; array[j] = temp; j = array.length - 1; while (i < j) { temp = array[i]; array[i] = array[j]; array[j] = temp; i++; j--; } return array; } public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.nextInt(); int arr[][][] = new int[4][n][n]; int sum[] = new int[4]; for (int k = 0; k < 4; k++) { for (int i = 0; i < n; i++) { String str = in.next(); for (int j = 0; j < n; j++) { arr[k][i][j] = (str.charAt(j) - '0'); } } } for (int k = 0; k < 4; k++) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if ((i + j) % 2 == arr[k][i][j]) sum[k]++; } } } int perm[] = new int[4]; for (int i = 0; i < 4; i++) perm[i] = i; int min = Integer.MAX_VALUE; while (true) { perm = nextPermutation(perm); if (perm == null) break; int sm = 0; for (int j = 0; j < 4; j++) { if (j % 2 == 0) { sm += (sum[perm[j]]); } else { sm += (n * n - sum[perm[j]]); } } min = Math.min(min, sm); sm = 0; for (int j = 0; j < 4; j++) { if (j % 2 == 0) { sm += (n * n - sum[perm[j]]); } else { sm += (sum[perm[j]]); } } min = Math.min(sm, min); } out.printLine(min); } } 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 printLine(int i) { writer.println(i); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c & 15; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String next() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } }
Java
["1\n0\n\n0\n\n1\n\n0", "3\n101\n010\n101\n\n101\n000\n101\n\n010\n101\n011\n\n010\n101\n010"]
1 second
["1", "2"]
null
Java 8
standard input
[ "implementation", "bitmasks", "brute force" ]
dc46c6cb6b4b9b5e7e6e5b4b7d034874
The first line contains odd integer n (1 ≤ n ≤ 100) — the size of all pieces of the board. Then 4 segments follow, each describes one piece of the board. Each consists of n lines of n characters; j-th one of i-th line is equal to 1 if the square is black initially and 0 otherwise. Segments are separated by an empty line.
1,400
Print one number — minimum number of squares Magnus should recolor to be able to obtain a valid chessboard.
standard output
PASSED
af5f3bc4e99f4a1e018e8f9f37017083
train_003.jsonl
1522850700
Magnus decided to play a classic chess game. Though what he saw in his locker shocked him! His favourite chessboard got broken into 4 pieces, each of size n by n, n is always odd. And what's even worse, some squares were of wrong color. j-th square of the i-th row of k-th piece of the board has color ak, i, j; 1 being black and 0 being white. Now Magnus wants to change color of some squares in such a way that he recolors minimum number of squares and obtained pieces form a valid chessboard. Every square has its color different to each of the neightbouring by side squares in a valid board. Its size should be 2n by 2n. You are allowed to move pieces but not allowed to rotate or flip them.
256 megabytes
/** * Date: 13 Apr, 2018 * Link: * * @author Prasad-Chaudhari * @email prasadc8897@gmail.com */ import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class newProgram { public static void main(String[] args) throws IOException { // TODO code application logic here FastIO2 in = new FastIO2(); int n = in.ni(); int a[][] = new int[n][n]; int b[][] = new int[n][n]; int c[][] = new int[n][n]; int d[][] = new int[n][n]; for(int i=0;i<n;i++){ String s = in.next(); for(int j=0;j<n;j++){ a[i][j] = s.charAt(j)-'0'; } } in.next(); for(int i=0;i<n;i++){ String s = in.next(); for(int j=0;j<n;j++){ b[i][j] = s.charAt(j)-'0'; } } in.next(); for(int i=0;i<n;i++){ String s = in.next(); for(int j=0;j<n;j++){ c[i][j] = s.charAt(j)-'0'; } } in.next(); for(int i=0;i<n;i++){ String s = in.next(); for(int j=0;j<n;j++){ d[i][j] = s.charAt(j)-'0'; } } int min = 2*n*2*n+1; min = Math.min(min, compute(a,b,c,d)); min = Math.min(min, compute(a,b,d,c)); min = Math.min(min, compute(a,c,b,d)); min = Math.min(min, compute(a,c,d,b)); min = Math.min(min, compute(b,a,c,d)); min = Math.min(min, compute(b,c,a,d)); min = Math.min(min, compute(b,c,d,a)); min = Math.min(min, compute(b,d,a,c)); min = Math.min(min, compute(b,d,c,a)); min = Math.min(min, compute(a,d,b,c)); min = Math.min(min, compute(a,d,c,b)); min = Math.min(min, compute(c,a,b,d)); min = Math.min(min, compute(c,a,d,b)); min = Math.min(min, compute(c,b,a,d)); min = Math.min(min, compute(c,b,d,a)); min = Math.min(min, compute(c,d,a,b)); min = Math.min(min, compute(c,d,b,a)); min = Math.min(min, compute(b,a,d,c)); min = Math.min(min, compute(d,a,b,c)); min = Math.min(min, compute(d,a,c,b)); min = Math.min(min, compute(d,b,a,c)); min = Math.min(min, compute(d,b,c,a)); min = Math.min(min, compute(d,c,a,b)); min = Math.min(min, compute(d,c,b,a)); System.out.println(min); } private static int compute(int[][] a, int[][] b, int[][] c, int[][] d) { int n = a.length; int cell[][] = new int[2*n][2*n]; int f[][] = new int[2*n][2*n]; int overlap = 0; int overlap2 = 0; for(int i=0;i<n;i++){ System.arraycopy(a[i], 0, f[i], 0, n); } for(int i=0;i<n;i++){ System.arraycopy(b[i], 0, f[i], n, n); } for(int i=0;i<n;i++){ System.arraycopy(c[i], 0, f[i+n], 0, n); } for(int i=0;i<n;i++){ System.arraycopy(d[i], 0, f[i+n], n, n); } // for(int []i:f){ // for(int j:i){ // System.out.print(j+""); // } // System.out.println(""); // } for(int i=0;i<2*n;i++){ for(int j=0;j<2*n;j++){ cell[i][j] = (i+j)%2; } } // for(int []i:cell){ // for(int j:i){ // System.out.print(j+""); // } // System.out.println(""); // } for(int i=0;i<2*n;i++){ for(int j=0;j<n*2;j++){ if(cell[i][j]!=f[i][j]){ overlap++; } } } for(int i=0;i<2*n;i++){ for(int j=0;j<2*n;j++){ cell[i][j] = ((i+j)%2)^1; } } // for(int []i:cell){ // for(int j:i){ // System.out.print(j+""); // } // System.out.println(""); // } for(int i=0;i<2*n;i++){ for(int j=0;j<n*2;j++){ if(cell[i][j]!=f[i][j]){ overlap2++; } } } // System.out.println(Math.min(overlap, overlap2)); // System.out.println(""); return Math.min(overlap, overlap2); } static class FastIO2 { private final BufferedReader br; private String s[]; private int index; public FastIO2() throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); s = br.readLine().split(" "); index = 0; } public int ni() throws IOException { return Integer.parseInt(nextToken()); } public double nd() throws IOException { return Double.parseDouble(nextToken()); } public long nl() throws IOException { return Long.parseLong(nextToken()); } public String next() throws IOException { return nextToken(); } public String nli() throws IOException { try { return br.readLine(); } catch (IOException ex) { } return null; } public int[] gia(int n) throws IOException { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = ni(); } return a; } public int[] gia(int n, int start, int end) throws IOException { validate(n, start, end); int a[] = new int[n]; for (int i = start; i < end; i++) { a[i] = ni(); } return a; } public double[] gda(int n) throws IOException { double a[] = new double[n]; for (int i = 0; i < n; i++) { a[i] = nd(); } return a; } public double[] gda(int n, int start, int end) throws IOException { validate(n, start, end); double a[] = new double[n]; for (int i = start; i < end; i++) { a[i] = nd(); } return a; } public long[] gla(int n) throws IOException { long a[] = new long[n]; for (int i = 0; i < n; i++) { a[i] = ni(); } return a; } public long[] gla(int n, int start, int end) throws IOException { validate(n, start, end); long a[] = new long[n]; for (int i = start; i < end; i++) { a[i] = ni(); } return a; } private String nextToken() throws IndexOutOfBoundsException, IOException { if (index == s.length) { s = br.readLine().split(" "); index = 0; } return s[index++]; } private void validate(int n, int start, int end) { if (start < 0 || end >= n) { throw new IllegalArgumentException(); } } } }
Java
["1\n0\n\n0\n\n1\n\n0", "3\n101\n010\n101\n\n101\n000\n101\n\n010\n101\n011\n\n010\n101\n010"]
1 second
["1", "2"]
null
Java 8
standard input
[ "implementation", "bitmasks", "brute force" ]
dc46c6cb6b4b9b5e7e6e5b4b7d034874
The first line contains odd integer n (1 ≤ n ≤ 100) — the size of all pieces of the board. Then 4 segments follow, each describes one piece of the board. Each consists of n lines of n characters; j-th one of i-th line is equal to 1 if the square is black initially and 0 otherwise. Segments are separated by an empty line.
1,400
Print one number — minimum number of squares Magnus should recolor to be able to obtain a valid chessboard.
standard output
PASSED
13a52126333ec0e18250f593998ebec6
train_003.jsonl
1522850700
Magnus decided to play a classic chess game. Though what he saw in his locker shocked him! His favourite chessboard got broken into 4 pieces, each of size n by n, n is always odd. And what's even worse, some squares were of wrong color. j-th square of the i-th row of k-th piece of the board has color ak, i, j; 1 being black and 0 being white. Now Magnus wants to change color of some squares in such a way that he recolors minimum number of squares and obtained pieces form a valid chessboard. Every square has its color different to each of the neightbouring by side squares in a valid board. Its size should be 2n by 2n. You are allowed to move pieces but not allowed to rotate or flip them.
256 megabytes
import java.util.*; import java.io.*; import java.math.*; public class c { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); ArrayList<StringBuffer> a = new ArrayList<StringBuffer>(); ArrayList<StringBuffer> b = new ArrayList<StringBuffer>(); ArrayList<StringBuffer> c = new ArrayList<StringBuffer>(); ArrayList<StringBuffer> d = new ArrayList<StringBuffer>(); readinput(in, a, n); readinput(in, b, n); readinput(in, c, n); readinput(in, d, n); // First conf should be a b \n c d ArrayList<StringBuffer> conf1 = new ArrayList<StringBuffer>(); for(int i = 0; i < n; i++) conf1.add(new StringBuffer(a.get(i).toString() + b.get(i).toString())); for(int i = 0; i < n; i++) conf1.add(new StringBuffer(c.get(i).toString() + d.get(i).toString())); int min = Math.min(getNumberOfFlips('0', conf1), getNumberOfFlips('1', conf1)); conf1 = new ArrayList<StringBuffer>(); for(int i = 0; i < n; i++) conf1.add(new StringBuffer(a.get(i).toString() + b.get(i).toString())); for(int i = 0; i < n; i++) conf1.add(new StringBuffer(d.get(i).toString() + c.get(i).toString())); int flips = Math.min(getNumberOfFlips('0', conf1), getNumberOfFlips('1', conf1)); if(flips < min) min = flips; // Second Conf conf1 = new ArrayList<StringBuffer>(); for(int i = 0; i < n; i++) conf1.add(new StringBuffer(a.get(i).toString() + c.get(i).toString())); for(int i = 0; i < n; i++) conf1.add(new StringBuffer(b.get(i).toString() + d.get(i).toString())); flips = Math.min(getNumberOfFlips('0', conf1), getNumberOfFlips('1', conf1)); if(flips < min) min = flips; conf1 = new ArrayList<StringBuffer>(); for(int i = 0; i < n; i++) conf1.add(new StringBuffer(a.get(i).toString() + c.get(i).toString())); for(int i = 0; i < n; i++) conf1.add(new StringBuffer(d.get(i).toString() + b.get(i).toString())); flips = Math.min(getNumberOfFlips('0', conf1), getNumberOfFlips('1', conf1)); if(flips < min) min = flips; conf1 = new ArrayList<StringBuffer>(); for(int i = 0; i < n; i++) conf1.add(new StringBuffer(a.get(i).toString() + d.get(i).toString())); for(int i = 0; i < n; i++) conf1.add(new StringBuffer(b.get(i).toString() + c.get(i).toString())); flips = Math.min(getNumberOfFlips('0', conf1), getNumberOfFlips('1', conf1)); if(flips < min) min = flips; conf1 = new ArrayList<StringBuffer>(); for(int i = 0; i < n; i++) conf1.add(new StringBuffer(a.get(i).toString() + d.get(i).toString())); for(int i = 0; i < n; i++) conf1.add(new StringBuffer(c.get(i).toString() + b.get(i).toString())); flips = Math.min(getNumberOfFlips('0', conf1), getNumberOfFlips('1', conf1)); if(flips < min) min = flips; conf1 = new ArrayList<StringBuffer>(); for(int i = 0; i < n; i++) conf1.add(new StringBuffer(b.get(i).toString() + a.get(i).toString())); for(int i = 0; i < n; i++) conf1.add(new StringBuffer(c.get(i).toString() + d.get(i).toString())); flips = Math.min(getNumberOfFlips('0', conf1), getNumberOfFlips('1', conf1)); if(flips < min) min = flips; conf1 = new ArrayList<StringBuffer>(); for(int i = 0; i < n; i++) conf1.add(new StringBuffer(b.get(i).toString() + a.get(i).toString())); for(int i = 0; i < n; i++) conf1.add(new StringBuffer(d.get(i).toString() + c.get(i).toString())); flips = Math.min(getNumberOfFlips('0', conf1), getNumberOfFlips('1', conf1)); if(flips < min) min = flips; conf1 = new ArrayList<StringBuffer>(); for(int i = 0; i < n; i++) conf1.add(new StringBuffer(b.get(i).toString() + c.get(i).toString())); for(int i = 0; i < n; i++) conf1.add(new StringBuffer(a.get(i).toString() + d.get(i).toString())); flips = Math.min(getNumberOfFlips('0', conf1), getNumberOfFlips('1', conf1)); if(flips < min) min = flips; conf1 = new ArrayList<StringBuffer>(); for(int i = 0; i < n; i++) conf1.add(new StringBuffer(b.get(i).toString() + c.get(i).toString())); for(int i = 0; i < n; i++) conf1.add(new StringBuffer(d.get(i).toString() + a.get(i).toString())); flips = Math.min(getNumberOfFlips('0', conf1), getNumberOfFlips('1', conf1)); if(flips < min) min = flips; conf1 = new ArrayList<StringBuffer>(); for(int i = 0; i < n; i++) conf1.add(new StringBuffer(b.get(i).toString() + d.get(i).toString())); for(int i = 0; i < n; i++) conf1.add(new StringBuffer(a.get(i).toString() + c.get(i).toString())); flips = Math.min(getNumberOfFlips('0', conf1), getNumberOfFlips('1', conf1)); if(flips < min) min = flips; conf1 = new ArrayList<StringBuffer>(); for(int i = 0; i < n; i++) conf1.add(new StringBuffer(b.get(i).toString() + d.get(i).toString())); for(int i = 0; i < n; i++) conf1.add(new StringBuffer(c.get(i).toString() + a.get(i).toString())); flips = Math.min(getNumberOfFlips('0', conf1), getNumberOfFlips('1', conf1)); if(flips < min) min = flips; conf1 = new ArrayList<StringBuffer>(); for(int i = 0; i < n; i++) conf1.add(new StringBuffer(c.get(i).toString() + a.get(i).toString())); for(int i = 0; i < n; i++) conf1.add(new StringBuffer(b.get(i).toString() + d.get(i).toString())); flips = Math.min(getNumberOfFlips('0', conf1), getNumberOfFlips('1', conf1)); if(flips < min) min = flips; conf1 = new ArrayList<StringBuffer>(); for(int i = 0; i < n; i++) conf1.add(new StringBuffer(c.get(i).toString() + a.get(i).toString())); for(int i = 0; i < n; i++) conf1.add(new StringBuffer(d.get(i).toString() + b.get(i).toString())); flips = Math.min(getNumberOfFlips('0', conf1), getNumberOfFlips('1', conf1)); if(flips < min) min = flips; conf1 = new ArrayList<StringBuffer>(); for(int i = 0; i < n; i++) conf1.add(new StringBuffer(c.get(i).toString() + b.get(i).toString())); for(int i = 0; i < n; i++) conf1.add(new StringBuffer(a.get(i).toString() + d.get(i).toString())); flips = Math.min(getNumberOfFlips('0', conf1), getNumberOfFlips('1', conf1)); if(flips < min) min = flips; conf1 = new ArrayList<StringBuffer>(); for(int i = 0; i < n; i++) conf1.add(new StringBuffer(c.get(i).toString() + b.get(i).toString())); for(int i = 0; i < n; i++) conf1.add(new StringBuffer(d.get(i).toString() + a.get(i).toString())); flips = Math.min(getNumberOfFlips('0', conf1), getNumberOfFlips('1', conf1)); if(flips < min) min = flips; conf1 = new ArrayList<StringBuffer>(); for(int i = 0; i < n; i++) conf1.add(new StringBuffer(c.get(i).toString() + d.get(i).toString())); for(int i = 0; i < n; i++) conf1.add(new StringBuffer(a.get(i).toString() + b.get(i).toString())); flips = Math.min(getNumberOfFlips('0', conf1), getNumberOfFlips('1', conf1)); if(flips < min) min = flips; conf1 = new ArrayList<StringBuffer>(); for(int i = 0; i < n; i++) conf1.add(new StringBuffer(c.get(i).toString() + d.get(i).toString())); for(int i = 0; i < n; i++) conf1.add(new StringBuffer(b.get(i).toString() + a.get(i).toString())); flips = Math.min(getNumberOfFlips('0', conf1), getNumberOfFlips('1', conf1)); if(flips < min) min = flips; conf1 = new ArrayList<StringBuffer>(); for(int i = 0; i < n; i++) conf1.add(new StringBuffer(d.get(i).toString() + a.get(i).toString())); for(int i = 0; i < n; i++) conf1.add(new StringBuffer(b.get(i).toString() + c.get(i).toString())); flips = Math.min(getNumberOfFlips('0', conf1), getNumberOfFlips('1', conf1)); if(flips < min) min = flips; conf1 = new ArrayList<StringBuffer>(); for(int i = 0; i < n; i++) conf1.add(new StringBuffer(d.get(i).toString() + a.get(i).toString())); for(int i = 0; i < n; i++) conf1.add(new StringBuffer(c.get(i).toString() + b.get(i).toString())); flips = Math.min(getNumberOfFlips('0', conf1), getNumberOfFlips('1', conf1)); if(flips < min) min = flips; conf1 = new ArrayList<StringBuffer>(); for(int i = 0; i < n; i++) conf1.add(new StringBuffer(d.get(i).toString() + b.get(i).toString())); for(int i = 0; i < n; i++) conf1.add(new StringBuffer(a.get(i).toString() + c.get(i).toString())); flips = Math.min(getNumberOfFlips('0', conf1), getNumberOfFlips('1', conf1)); if(flips < min) min = flips; conf1 = new ArrayList<StringBuffer>(); for(int i = 0; i < n; i++) conf1.add(new StringBuffer(d.get(i).toString() + b.get(i).toString())); for(int i = 0; i < n; i++) conf1.add(new StringBuffer(c.get(i).toString() + a.get(i).toString())); flips = Math.min(getNumberOfFlips('0', conf1), getNumberOfFlips('1', conf1)); if(flips < min) min = flips; conf1 = new ArrayList<StringBuffer>(); for(int i = 0; i < n; i++) conf1.add(new StringBuffer(d.get(i).toString() + c.get(i).toString())); for(int i = 0; i < n; i++) conf1.add(new StringBuffer(a.get(i).toString() + b.get(i).toString())); flips = Math.min(getNumberOfFlips('0', conf1), getNumberOfFlips('1', conf1)); if(flips < min) min = flips; conf1 = new ArrayList<StringBuffer>(); for(int i = 0; i < n; i++) conf1.add(new StringBuffer(d.get(i).toString() + c.get(i).toString())); for(int i = 0; i < n; i++) conf1.add(new StringBuffer(b.get(i).toString() + a.get(i).toString())); flips = Math.min(getNumberOfFlips('0', conf1), getNumberOfFlips('1', conf1)); if(flips < min) min = flips; System.out.println(min); } public static void readinput(Scanner in, ArrayList<StringBuffer> a, int n) { for(int i = 0; i < n; i++) a.add(new StringBuffer(in.next())); } public static int getNumberOfFlips(char starting, ArrayList<StringBuffer> a) { ArrayList<StringBuffer> toCompare = new ArrayList<StringBuffer>(); for(int i = 0; i < a.size(); i++) { toCompare.add(new StringBuffer()); if(starting == '0' && i % 2 == 0) for(int j = 0; j < a.size(); j++) if(j%2 == 0) toCompare.get(i).append("0"); else toCompare.get(i).append("1"); else if(starting == '1' && i % 2 == 0) for(int j = 0; j < a.size(); j++) if(j % 2 == 0) toCompare.get(i).append("1"); else toCompare.get(i).append("0"); else if(starting == '0' && i % 2 == 1) for(int j = 0; j < a.size(); j++) if(j%2 == 0) toCompare.get(i).append("1"); else toCompare.get(i).append("0"); else if(starting == '1' && i % 2 == 1) for(int j = 0; j < a.size(); j++) if(j%2 == 0) toCompare.get(i).append("0"); else toCompare.get(i).append("1"); } int flips = 0; for(int i = 0; i < a.size(); i++) { String orig = a.get(i).toString(); String shouldbe = toCompare.get(i).toString(); for(int j = 0; j < orig.length(); j++) if(orig.charAt(j) != shouldbe.charAt(j)) flips++; } return flips; } }
Java
["1\n0\n\n0\n\n1\n\n0", "3\n101\n010\n101\n\n101\n000\n101\n\n010\n101\n011\n\n010\n101\n010"]
1 second
["1", "2"]
null
Java 8
standard input
[ "implementation", "bitmasks", "brute force" ]
dc46c6cb6b4b9b5e7e6e5b4b7d034874
The first line contains odd integer n (1 ≤ n ≤ 100) — the size of all pieces of the board. Then 4 segments follow, each describes one piece of the board. Each consists of n lines of n characters; j-th one of i-th line is equal to 1 if the square is black initially and 0 otherwise. Segments are separated by an empty line.
1,400
Print one number — minimum number of squares Magnus should recolor to be able to obtain a valid chessboard.
standard output
PASSED
fac5a8cc0db01d6ab35daa2710570b4a
train_003.jsonl
1522850700
Magnus decided to play a classic chess game. Though what he saw in his locker shocked him! His favourite chessboard got broken into 4 pieces, each of size n by n, n is always odd. And what's even worse, some squares were of wrong color. j-th square of the i-th row of k-th piece of the board has color ak, i, j; 1 being black and 0 being white. Now Magnus wants to change color of some squares in such a way that he recolors minimum number of squares and obtained pieces form a valid chessboard. Every square has its color different to each of the neightbouring by side squares in a valid board. Its size should be 2n by 2n. You are allowed to move pieces but not allowed to rotate or flip them.
256 megabytes
import java.io.*; import java.util.*; public class Main { public static void main(String[] args) throws java.lang.Exception { fast s = new fast(); PrintWriter out=new PrintWriter(System.out); StringBuilder final_ans = new StringBuilder(); int n=s.nextInt(); int [][] a=new int[n][n]; int [][] b=new int[n][n]; int c[]=new int[4]; int d[]=new int[4]; int temp[]=new int[4]; String[] arr=new String[n]; for(int i=0;i<n;i++) { if(i==0) {a[0][0]=0; b[0][0]=1;} else {a[i][0]=1-a[i-1][0]; b[i][0]=1-b[i-1][0];} for(int j=1;j<n;j++) { a[i][j]=1-a[i][j-1]; b[i][j]=1-b[i][j-1]; } } for(int i=0;i<4;i++) { arr=new String[n]; for(int j=0;j<n;j++) { arr[j]=s.nextLine(); } for(int j=0;j<n;j++) { for(int k=0;k<n;k++) { if(arr[j].charAt(k)!=(char)(a[j][k]+'0')) c[i]++; if(arr[j].charAt(k)!=(char)(b[j][k]+'0')) d[i]++; } } } int sum=0;int ans=Integer.MAX_VALUE; for(int i=0;i<4;i++) { for(int j=0;j<4;j++) { temp=new int[4]; if(i==j) continue; sum=c[i]+c[j]; temp[i]=1; temp[j]=1; for(int k=0;k<4;k++) if(temp[k]==0) sum+=d[k]; ans=Math.min(ans,sum); } } System.out.println(ans); } static class fast { private InputStream i; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public fast() { this(System.in); } public fast(InputStream is) { i = is; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = i.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public String nextString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } } }
Java
["1\n0\n\n0\n\n1\n\n0", "3\n101\n010\n101\n\n101\n000\n101\n\n010\n101\n011\n\n010\n101\n010"]
1 second
["1", "2"]
null
Java 8
standard input
[ "implementation", "bitmasks", "brute force" ]
dc46c6cb6b4b9b5e7e6e5b4b7d034874
The first line contains odd integer n (1 ≤ n ≤ 100) — the size of all pieces of the board. Then 4 segments follow, each describes one piece of the board. Each consists of n lines of n characters; j-th one of i-th line is equal to 1 if the square is black initially and 0 otherwise. Segments are separated by an empty line.
1,400
Print one number — minimum number of squares Magnus should recolor to be able to obtain a valid chessboard.
standard output
PASSED
507afa709dfa5ce3ff57e38fb236b247
train_003.jsonl
1522850700
Magnus decided to play a classic chess game. Though what he saw in his locker shocked him! His favourite chessboard got broken into 4 pieces, each of size n by n, n is always odd. And what's even worse, some squares were of wrong color. j-th square of the i-th row of k-th piece of the board has color ak, i, j; 1 being black and 0 being white. Now Magnus wants to change color of some squares in such a way that he recolors minimum number of squares and obtained pieces form a valid chessboard. Every square has its color different to each of the neightbouring by side squares in a valid board. Its size should be 2n by 2n. You are allowed to move pieces but not allowed to rotate or flip them.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Scanner; import java.util.StringTokenizer; public class P961C { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int n = scan.nextInt(); int[][][] color = new int[4][n][n]; for (int k = 0; k < 4; k++) { for (int i = 0; i < n; i++) { char[] row = scan.next().toCharArray(); for (int j = 0; j < n; j++) { color[k][i][j] = row[j]-'0'; } } } int min = 999999; for (int a = 0; a < 4; a++) { for (int b = 0; b < 4; b++) { if (b == a) continue; for (int c = 0; c < 4; c++) { if (c == a || c == b) continue; for (int d = 0; d < 4; d++) { if (d == a || d == b || d == c) continue; int ops = 0; ops += flips(color[a], 1); ops += flips(color[b], 0); ops += flips(color[c], 1); ops += flips(color[d], 0); min = Math.min(min, ops); } } } } System.out.println(min); } private static int flips(int[][] color, int start) { int f = 0; for (int i = 0; i < color.length; i++) { for (int j = 0; j < color[0].length; j++) { if (color[i][j] != (i+j+start) % 2) f++; } } return f; } static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner() { try { br = new BufferedReader(new InputStreamReader(System.in)); st = new StringTokenizer(br.readLine()); } catch (Exception e) { e.printStackTrace(); } } public String next() { if (st.hasMoreTokens()) return st.nextToken(); try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { e.printStackTrace(); } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public String nextLine() { String line = ""; try { line = br.readLine(); } catch (Exception e) { e.printStackTrace(); } return line; } } }
Java
["1\n0\n\n0\n\n1\n\n0", "3\n101\n010\n101\n\n101\n000\n101\n\n010\n101\n011\n\n010\n101\n010"]
1 second
["1", "2"]
null
Java 8
standard input
[ "implementation", "bitmasks", "brute force" ]
dc46c6cb6b4b9b5e7e6e5b4b7d034874
The first line contains odd integer n (1 ≤ n ≤ 100) — the size of all pieces of the board. Then 4 segments follow, each describes one piece of the board. Each consists of n lines of n characters; j-th one of i-th line is equal to 1 if the square is black initially and 0 otherwise. Segments are separated by an empty line.
1,400
Print one number — minimum number of squares Magnus should recolor to be able to obtain a valid chessboard.
standard output
PASSED
6384bae386b7298008ad363de90ff431
train_003.jsonl
1522850700
Magnus decided to play a classic chess game. Though what he saw in his locker shocked him! His favourite chessboard got broken into 4 pieces, each of size n by n, n is always odd. And what's even worse, some squares were of wrong color. j-th square of the i-th row of k-th piece of the board has color ak, i, j; 1 being black and 0 being white. Now Magnus wants to change color of some squares in such a way that he recolors minimum number of squares and obtained pieces form a valid chessboard. Every square has its color different to each of the neightbouring by side squares in a valid board. Its size should be 2n by 2n. You are allowed to move pieces but not allowed to rotate or flip them.
256 megabytes
// CodeForces Round #667 B competition import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.sql.Array; import java.util.Arrays; public class Chessboard { class Square implements Comparable<Square> { int [][]m; int difSd; int difSnd; int ddif; Square() { m = new int[n][n]; } void readSquare(BufferedReader bin) throws IOException { for (int i=0; i<n; i++) { String s = bin.readLine(); for (int j=0; j<n; j++) { m[i][j] = (int)(s.charAt(j) - '0'); } } } void setSquare(boolean diag) { for (int i=0; i<n; i++) { for (int j=0; j<n; j++) { int d = (i + j) % 2; m[i][j] = (diag ? 1-d : d); } } } int diff(Square b) { int df = 0; for (int i=0; i<n; i++) { for (int j=0; j<n; j++) { df += (m[i][j] == b.m[i][j] ? 0 : 1); } } return df; } void countDiffs() { difSd = diff(sd); difSnd = diff(snd); ddif = difSd - difSnd; } @Override public int compareTo(Square o) { return ddif - o.ddif; } } int n; Square []sqs; Square sd, snd; int minSq; private void readData(BufferedReader bin) throws IOException { String s = bin.readLine(); String []ss = s.split(" "); n = Integer.parseInt(ss[0]); // read a sd = new Square(); snd = new Square(); sd.setSquare(true); snd.setSquare(false); sqs = new Square[4]; for (int i=0; i<4; i++) { sqs[i] = new Square(); sqs[i].readSquare(bin); sqs[i].countDiffs(); if (i<3) { bin.readLine(); } } } void printRes() { System.out.println(minSq); } private void calculate() { Arrays.sort(sqs); // 0,1 - diag, 2, 3 - not diag minSq = sqs[0].difSd + sqs[1].difSd; minSq += sqs[2].difSnd + sqs[3].difSnd; } public static void main(String[] args) throws IOException { // BufferedReader bin = new BufferedReader(new FileReader("cactus.in")); BufferedReader bin = new BufferedReader( new InputStreamReader(System.in)); Chessboard l = new Chessboard(); l.readData(bin); l.calculate(); l.printRes(); } }
Java
["1\n0\n\n0\n\n1\n\n0", "3\n101\n010\n101\n\n101\n000\n101\n\n010\n101\n011\n\n010\n101\n010"]
1 second
["1", "2"]
null
Java 8
standard input
[ "implementation", "bitmasks", "brute force" ]
dc46c6cb6b4b9b5e7e6e5b4b7d034874
The first line contains odd integer n (1 ≤ n ≤ 100) — the size of all pieces of the board. Then 4 segments follow, each describes one piece of the board. Each consists of n lines of n characters; j-th one of i-th line is equal to 1 if the square is black initially and 0 otherwise. Segments are separated by an empty line.
1,400
Print one number — minimum number of squares Magnus should recolor to be able to obtain a valid chessboard.
standard output
PASSED
7f61193c7e012beb1a069c54278c1229
train_003.jsonl
1522850700
Magnus decided to play a classic chess game. Though what he saw in his locker shocked him! His favourite chessboard got broken into 4 pieces, each of size n by n, n is always odd. And what's even worse, some squares were of wrong color. j-th square of the i-th row of k-th piece of the board has color ak, i, j; 1 being black and 0 being white. Now Magnus wants to change color of some squares in such a way that he recolors minimum number of squares and obtained pieces form a valid chessboard. Every square has its color different to each of the neightbouring by side squares in a valid board. Its size should be 2n by 2n. You are allowed to move pieces but not allowed to rotate or flip them.
256 megabytes
/* / フフ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀ム / )\⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀ Y (⠀⠀| ( ͡° ͜ʖ ͡°)⠀⌒(⠀ ノ (⠀ ノ⌒ Y ⌒ヽ-く __/ | _⠀。ノ| ノ。 |/ (⠀ー '_人`ー ノ ⠀|\  ̄ _人'彡ノ ⠀ )\⠀⠀ 。⠀⠀ / ⠀⠀(\⠀ #⠀ / ⠀/⠀⠀⠀/ὣ====================D- /⠀⠀⠀/⠀ \ \⠀⠀\ ( (⠀)⠀⠀⠀⠀ ) ).⠀) (⠀⠀)⠀⠀⠀⠀⠀( | / |⠀ /⠀⠀⠀⠀⠀⠀ | / [_] ⠀⠀⠀⠀⠀[___] */ // Main Code at the Bottom import java.util.*; import java.lang.*; import java.io.*; public class Main { //Fast IO class static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { boolean env=System.getProperty("ONLINE_JUDGE") != null; if(!env) { try { br=new BufferedReader(new FileReader("src\\input.txt")); } catch (FileNotFoundException e) { e.printStackTrace(); } } else br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } static long MOD=1000000000+7; //Euclidean Algorithm static long gcd(long A,long B){ if(B==0) return A; return gcd(B,A%B); } //Modular Exponentiation static long fastExpo(long x,long n){ if(n==0) return 1; if((n&1)==0) return fastExpo((x*x)%MOD,n/2)%MOD; return ((x%MOD)*fastExpo((x*x)%MOD,(n-1)/2))%MOD; } //Prime Number Algorithm static boolean isPrime(long n){ if(n<=1) return false; if(n<=3) return true; if(n%2==0 || n%3==0) return false; for(int i=5;i*i<=n;i+=6) if(n%i==0 || n%(i+2)==0) return false; return true; } //Reverse an array static <T> void reverse(T arr[],int l,int r){ Collections.reverse(Arrays.asList(arr).subList(l, r)); } //Print array static <T> void print1d(T arr[]) { out.println(Arrays.toString(arr)); } static <T> void print2d(T arr[][]) { for(T a[]: arr) out.println(Arrays.toString(a)); } // Pair static class pair{ long x,y; pair(long a,long b){ this.x=a; this.y=b; } public boolean equals(Object obj) { if(obj == null || obj.getClass()!= this.getClass()) return false; pair p = (pair) obj; return (this.x==p.x && this.y==p.y); } public int hashCode() { return Objects.hash(x,y); } } static FastReader sc=new FastReader(); static PrintWriter out=new PrintWriter(System.out); //Main function(The main code starts from here) public static void main (String[] args) throws java.lang.Exception { int test=1; while(test-->0) { int n=sc.nextInt(),ans=0,visited[]=new int[4]; char s[][][]=new char[4][n][n]; for(int i=0;i<4;i++) { for(int j=0;j<n;j++) s[i][j]=sc.nextLine().toCharArray(); sc.nextLine(); } int start='0'; for(int itr=0;itr<2;itr++) { char tmp[][]=new char[n][n]; for(int x=0;x<n;x++) { for(int y=0;y<n;y++) tmp[x][y]=(char) (((x+y)%2==0)?start:('1'-start+'0')); } start='1'; //for(int i=0;i<n;i++) out.println(Arrays.toString(tmp[i])); for(int i=0;i<2;i++) { int min=Integer.MAX_VALUE,idx=-1; for(int j=0;j<4;j++) { if(visited[j]==1) continue; int cnt=0; for(int x=0;x<n;x++) { for(int y=0;y<n;y++) if(tmp[x][y]!=s[j][x][y]) cnt++; } if(cnt<min) { min=cnt; idx=j; } } ans+=min; //System.out.println(idx+" "+min); visited[idx]=1; } } out.println(ans); } out.flush(); out.close(); } }
Java
["1\n0\n\n0\n\n1\n\n0", "3\n101\n010\n101\n\n101\n000\n101\n\n010\n101\n011\n\n010\n101\n010"]
1 second
["1", "2"]
null
Java 8
standard input
[ "implementation", "bitmasks", "brute force" ]
dc46c6cb6b4b9b5e7e6e5b4b7d034874
The first line contains odd integer n (1 ≤ n ≤ 100) — the size of all pieces of the board. Then 4 segments follow, each describes one piece of the board. Each consists of n lines of n characters; j-th one of i-th line is equal to 1 if the square is black initially and 0 otherwise. Segments are separated by an empty line.
1,400
Print one number — minimum number of squares Magnus should recolor to be able to obtain a valid chessboard.
standard output
PASSED
8adcbb48a5b8bdd35911661a80027e02
train_003.jsonl
1522850700
Magnus decided to play a classic chess game. Though what he saw in his locker shocked him! His favourite chessboard got broken into 4 pieces, each of size n by n, n is always odd. And what's even worse, some squares were of wrong color. j-th square of the i-th row of k-th piece of the board has color ak, i, j; 1 being black and 0 being white. Now Magnus wants to change color of some squares in such a way that he recolors minimum number of squares and obtained pieces form a valid chessboard. Every square has its color different to each of the neightbouring by side squares in a valid board. Its size should be 2n by 2n. You are allowed to move pieces but not allowed to rotate or flip them.
256 megabytes
import java.io.IOException; import java.io.InputStream; import java.util.InputMismatchException; public class A { public static int getScore(int[][] mat, int N, boolean parity){ int total = 0; for(int i = 0; i<N; i++){ for(int j = 0; j<N; j++){ if(parity && (i + j) % 2 == mat[i][j]) total++; if(!parity && (i + j) % 2 != mat[i][j]) total++; } } return total; } public static void main(String[] args) { FastScannerA sc = new FastScannerA(System.in); int N = sc.nextInt(); int[][][] arr = new int[4][N][N]; for(int k = 0; k < 4; k++){ for(int i = 0; i < N; i++){ String line = sc.next(); for(int j = 0; j < N; j++){ arr[k][i][j] = line.charAt(j) - '0'; } } } int[][] table = new int[2][4]; for(int i = 0; i < 4; i++) table[0][i] = getScore(arr[i], N, true); for(int i = 0; i < 4; i++) table[1][i] = getScore(arr[i], N, false); // for(int i = 0; i<2; i++){ // for(int j = 0; j<4; j++){ // System.out.print(table[i][j] + " "); // } // System.out.println(); // } // calculate result int[] sums = new int[6]; sums[0] = table[0][0] + table[0][1] + table[1][2] + table[1][3]; sums[1] = table[0][0] + table[1][1] + table[0][2] + table[1][3]; sums[2] = table[0][0] + table[1][1] + table[1][2] + table[0][3]; sums[3] = table[1][0] + table[0][1] + table[1][2] + table[0][3]; sums[4] = table[1][0] + table[0][1] + table[0][2] + table[1][3]; sums[5] = table[1][0] + table[1][1] + table[0][2] + table[0][3]; int min = Integer.MAX_VALUE; for(int i = 0; i < 6; i++) min = Math.min(min, sums[i]); System.out.println(min); } } class FastScannerA{ private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public FastScannerA(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 String next() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public String nextLine() { int c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isLineEndChar(c)); return res.toString(); } public double nextDouble() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } double res = 0; while (!isSpaceChar(c) && c != '.') { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } if (c == '.') { c = read(); double m = 1; while (!isSpaceChar(c)) { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } public 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 boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public boolean isLineEndChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == '\n' || c == '\r' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } }
Java
["1\n0\n\n0\n\n1\n\n0", "3\n101\n010\n101\n\n101\n000\n101\n\n010\n101\n011\n\n010\n101\n010"]
1 second
["1", "2"]
null
Java 8
standard input
[ "implementation", "bitmasks", "brute force" ]
dc46c6cb6b4b9b5e7e6e5b4b7d034874
The first line contains odd integer n (1 ≤ n ≤ 100) — the size of all pieces of the board. Then 4 segments follow, each describes one piece of the board. Each consists of n lines of n characters; j-th one of i-th line is equal to 1 if the square is black initially and 0 otherwise. Segments are separated by an empty line.
1,400
Print one number — minimum number of squares Magnus should recolor to be able to obtain a valid chessboard.
standard output
PASSED
47f4914faf326b331db1d8a388b9cdb9
train_003.jsonl
1522850700
Magnus decided to play a classic chess game. Though what he saw in his locker shocked him! His favourite chessboard got broken into 4 pieces, each of size n by n, n is always odd. And what's even worse, some squares were of wrong color. j-th square of the i-th row of k-th piece of the board has color ak, i, j; 1 being black and 0 being white. Now Magnus wants to change color of some squares in such a way that he recolors minimum number of squares and obtained pieces form a valid chessboard. Every square has its color different to each of the neightbouring by side squares in a valid board. Its size should be 2n by 2n. You are allowed to move pieces but not allowed to rotate or flip them.
256 megabytes
import java.util.*; /** * Created by Admin on 2018-01-16. */ public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); /* int iloscSłow = in.nextInt(),iloscGrup = in.nextInt(),iloscKoncowychSlow = in.nextInt(); String [] słowa = new String[iloscSłow]; HashMap <String,Integer> SlowoCena = new HashMap<String,Integer>(); for (int i = 0; i < iloscSłow; i++) { String slowo = in.next(); słowa [i] = slowo; } int [] ceny = new int[iloscSłow]; for (int i = 0; i < iloscSłow; i++) { int cena = in.nextInt(); ceny[i] = cena; } */ int n = in.nextInt(); String[] a = new String[4]; Arrays.fill(a, ""); for (int i = 0; i < 4; ++i) { for (int j = 0; j < n; ++j) { a[i] += in.next(); } } char[][] o = new char[2][n * n]; for (int i = 0; i < n * n; ++i) o[0][i] = i % 2 == 0 ? '1' : '0'; for (int i = 0; i < n * n; ++i) o[1][i] = i % 2 == 0 ? '0' : '1'; int[][] best = new int[4][2]; for (int i = 0; i < 4; ++i) { for (int j = 0; j < 2; ++j) { int cnt = 0; for (int k = 0; k < n * n; ++k) { if (a[i].charAt(k) != o[j][k]) ++cnt; } best[i][j] = cnt; } } int res = Integer.MAX_VALUE; res = Math.min(res, best[0][0] + best[1][0] + best[2][1] + best[3][1]); res = Math.min(res, best[0][1] + best[1][1] + best[2][0] + best[3][0]); res = Math.min(res, best[0][1] + best[1][0] + best[2][1] + best[3][0]); res = Math.min(res, best[0][0] + best[1][1] + best[2][0] + best[3][1]); res = Math.min(res, best[0][0] + best[1][1] + best[2][1] + best[3][0]); res = Math.min(res, best[0][1] + best[1][0] + best[2][0] + best[3][1]); System.out.println(res); } }
Java
["1\n0\n\n0\n\n1\n\n0", "3\n101\n010\n101\n\n101\n000\n101\n\n010\n101\n011\n\n010\n101\n010"]
1 second
["1", "2"]
null
Java 8
standard input
[ "implementation", "bitmasks", "brute force" ]
dc46c6cb6b4b9b5e7e6e5b4b7d034874
The first line contains odd integer n (1 ≤ n ≤ 100) — the size of all pieces of the board. Then 4 segments follow, each describes one piece of the board. Each consists of n lines of n characters; j-th one of i-th line is equal to 1 if the square is black initially and 0 otherwise. Segments are separated by an empty line.
1,400
Print one number — minimum number of squares Magnus should recolor to be able to obtain a valid chessboard.
standard output
PASSED
030c45539f6eb394f45acaef70c730d1
train_003.jsonl
1522850700
Magnus decided to play a classic chess game. Though what he saw in his locker shocked him! His favourite chessboard got broken into 4 pieces, each of size n by n, n is always odd. And what's even worse, some squares were of wrong color. j-th square of the i-th row of k-th piece of the board has color ak, i, j; 1 being black and 0 being white. Now Magnus wants to change color of some squares in such a way that he recolors minimum number of squares and obtained pieces form a valid chessboard. Every square has its color different to each of the neightbouring by side squares in a valid board. Its size should be 2n by 2n. You are allowed to move pieces but not allowed to rotate or flip them.
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 Washoum */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; inputClass in = new inputClass(inputStream); PrintWriter out = new PrintWriter(outputStream); CChessboard solver = new CChessboard(); solver.solve(1, in, out); out.close(); } static class CChessboard { static int count(StringBuilder a) { int res = 0; for (int i = 0; i < a.length(); i++) { if (a.charAt(i) == '1') { res++; } } return res; } static int countgrid(char[][] grid, int n, char yebda) { int res = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (((n * i) + j) % 2 == 0 && grid[i][j] != yebda) { res++; } else if (((n * i) + j) % 2 == 1 && grid[i][j] == yebda) { res++; } } } return res; } public void solve(int testNumber, inputClass sc, PrintWriter out) { int n = sc.nextInt(); char[][][] grids = new char[4][n][n]; for (int i = 0; i < 4; i++) { for (int j = 0; j < n; j++) { grids[i][j] = sc.nextLine().toCharArray(); } sc.nextLine(); } int ans = Integer.MAX_VALUE; int act; char yebda; StringBuilder s; for (int i = 2; i < 13; i++) { s = new StringBuilder(Integer.toBinaryString(i)); if (count(s) == 2) { while (s.length() < 4) { s.insert(0, '0'); } act = 0; for (int j = 0; j < 4; j++) { if (s.charAt(j) == '0') { yebda = '0'; } else { yebda = '1'; } act += countgrid(grids[j], n, yebda); } ans = Math.min(ans, act); } } out.println(ans); } } static class inputClass { BufferedReader br; StringTokenizer st; public inputClass(InputStream in) { br = new BufferedReader(new InputStreamReader(in)); } public String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["1\n0\n\n0\n\n1\n\n0", "3\n101\n010\n101\n\n101\n000\n101\n\n010\n101\n011\n\n010\n101\n010"]
1 second
["1", "2"]
null
Java 8
standard input
[ "implementation", "bitmasks", "brute force" ]
dc46c6cb6b4b9b5e7e6e5b4b7d034874
The first line contains odd integer n (1 ≤ n ≤ 100) — the size of all pieces of the board. Then 4 segments follow, each describes one piece of the board. Each consists of n lines of n characters; j-th one of i-th line is equal to 1 if the square is black initially and 0 otherwise. Segments are separated by an empty line.
1,400
Print one number — minimum number of squares Magnus should recolor to be able to obtain a valid chessboard.
standard output
PASSED
6a476b834a886e8e74c7b36556b0cd9d
train_003.jsonl
1522850700
Magnus decided to play a classic chess game. Though what he saw in his locker shocked him! His favourite chessboard got broken into 4 pieces, each of size n by n, n is always odd. And what's even worse, some squares were of wrong color. j-th square of the i-th row of k-th piece of the board has color ak, i, j; 1 being black and 0 being white. Now Magnus wants to change color of some squares in such a way that he recolors minimum number of squares and obtained pieces form a valid chessboard. Every square has its color different to each of the neightbouring by side squares in a valid board. Its size should be 2n by 2n. You are allowed to move pieces but not allowed to rotate or flip them.
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 Jenish */ 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 IS = System.in; OutputStream OS = System.out; ScanReader in = new ScanReader(IS); PrintWriter out = new PrintWriter(OS); ProblemCChessboard problemcchessboard = new ProblemCChessboard(); problemcchessboard.solve(1, in, out); out.close(); } static class ProblemCChessboard { public void solve(int testNumber, ScanReader in, PrintWriter out) { int n = in.scanInt(); long R[] = new long[4]; long L[] = new long[4]; for (int i = 0; i < 4; i++) { int arr[][] = new int[n][n]; for (int j = 0; j < n; j++) { String str = in.scanString(); for (int k = 0; k < n; k++) { if (str.charAt(k) == '1') arr[j][k] = 1; else { arr[j][k] = 0; } } } long tR = 0; int pre = 1; for (int j = 0; j < n; j++) { for (int k = 0; k < n; k++) { if (arr[j][k] == pre) { } else { tR++; } pre = 1 - pre; } } R[i] = tR; long tL = 0; pre = 0; for (int j = 0; j < n; j++) { for (int k = 0; k < n; k++) { if (arr[j][k] == pre) { } else { tL++; } pre = 1 - pre; } } L[i] = tL; } long ans = Long.MAX_VALUE; ans = Math.min(R[2] + R[3] + L[0] + L[1], ans); ans = Math.min(R[1] + R[2] + L[0] + L[3], ans); ans = Math.min(R[0] + R[1] + L[2] + L[3], ans); ans = Math.min(R[1] + R[3] + L[0] + L[2], ans); ans = Math.min(R[0] + R[2] + L[3] + L[1], ans); ans = Math.min(R[0] + R[3] + L[2] + L[1], ans); out.println(ans); } } static class ScanReader { private byte[] buf = new byte[4 * 1024]; private int index; private BufferedInputStream in; private int Total_Char; public ScanReader(InputStream inputStream) { in = new BufferedInputStream(inputStream); } private int scan() { if (index >= Total_Char) { index = 0; try { Total_Char = in.read(buf); } catch (Exception e) { e.printStackTrace(); } if (Total_Char <= 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; } public String scanString() { int c = scan(); while (isWhiteSpace(c)) c = scan(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = scan(); } while (!isWhiteSpace(c)); return res.toString(); } private boolean isWhiteSpace(int n) { if (n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1) return true; else return false; } } }
Java
["1\n0\n\n0\n\n1\n\n0", "3\n101\n010\n101\n\n101\n000\n101\n\n010\n101\n011\n\n010\n101\n010"]
1 second
["1", "2"]
null
Java 8
standard input
[ "implementation", "bitmasks", "brute force" ]
dc46c6cb6b4b9b5e7e6e5b4b7d034874
The first line contains odd integer n (1 ≤ n ≤ 100) — the size of all pieces of the board. Then 4 segments follow, each describes one piece of the board. Each consists of n lines of n characters; j-th one of i-th line is equal to 1 if the square is black initially and 0 otherwise. Segments are separated by an empty line.
1,400
Print one number — minimum number of squares Magnus should recolor to be able to obtain a valid chessboard.
standard output
PASSED
537469eb2b7b42a3a43fe93f258d0025
train_003.jsonl
1522850700
Magnus decided to play a classic chess game. Though what he saw in his locker shocked him! His favourite chessboard got broken into 4 pieces, each of size n by n, n is always odd. And what's even worse, some squares were of wrong color. j-th square of the i-th row of k-th piece of the board has color ak, i, j; 1 being black and 0 being white. Now Magnus wants to change color of some squares in such a way that he recolors minimum number of squares and obtained pieces form a valid chessboard. Every square has its color different to each of the neightbouring by side squares in a valid board. Its size should be 2n by 2n. You are allowed to move pieces but not allowed to rotate or flip them.
256 megabytes
//package mar18; import java.io.*; import java.util.*; public class HR27 { InputStream is; PrintWriter out; String INPUT = ""; //boolean codechef=true; boolean codechef=true; void solve() { int n=ni(); int[][][] mat=new int[4][n][n]; for(int i=0;i<4;i++) { for(int j=0;j<n;j++) { String s=ns(); for(int k=0;k<n;k++) { mat[i][j][k]=(int)(s.charAt(k)-'0'); } } } //System.out.println("jk"); int[][] cr1=makeMat(n,0); int[][] cr2=makeMat(n,1); int[] diff1=new int[4]; int[] diff2=new int[4]; for(int i=0;i<4;i++) { diff1[i]=diff(cr1, mat[i]); diff2[i]=diff(cr2,mat[i]); } int[] f=new int[6]; f[0]=diff1[0]+diff1[1]+diff2[2]+diff2[3]; f[1]=diff1[0]+diff1[2]+diff2[1]+diff2[3]; f[2]=diff1[0]+diff1[3]+diff2[1]+diff2[2]; f[3]=diff2[0]+diff2[1]+diff1[2]+diff1[3]; f[4]=diff2[0]+diff2[2]+diff1[1]+diff1[3]; f[5]=diff2[0]+diff2[3]+diff1[1]+diff1[2]; Arrays.sort(f); out.println(f[0]); } void solveD() { int n=ni(); Pair[] pr=new Pair[n]; for(int i=0;i<n;i++) { pr[i]=new Pair(ni(),ni()); } if(n==1) { out.println("YES");return; } long num=(pr[1].y-pr[0].y); long den=(pr[1].x-pr[0].x); Arrays.sort(pr,new Comparator<Pair>() { @Override public int compare(Pair o1, Pair o2) { // TODO Auto-generated method stub long currn=(o2.y-o1.y); long currd=(o2.x-o1.x); if(currn*den-currd*num==0)return 0; return 1; }}); for(Pair p:pr) { out.println(p.x+" "+p.y); } } void solveB() { int n=ni(),k=ni(); int[] a=na(n); int[] t=na(n); int[] onwake=new int[n]; if(t[0]==1)onwake[0]=a[0]; for(int i=1;i<n;i++) { if(t[i]==1) { onwake[i]=onwake[i-1]+a[i]; } else onwake[i]=onwake[i-1]; } int[] kcont=new int[n]; for(int i=0;i<k;i++) { kcont[0]+=a[i]; } for(int i=1;i<=n-k;i++) { kcont[i]=kcont[i-1]+a[k-1+i]-a[i-1]; } int max=onwake[n-1]; for(int i=0;i<n-k;i++) { max=Math.max(max, onwake[i]+kcont[i+1]); } out.println(max); } void solveA() { int n=ni(),m=ni(); int[] c=na(m); int[] f=new int[n]; int cnt=0; for(int i=0;i<m;i++) { f[c[i]-1]++; boolean ch=false; for(int j=0;j<n;j++) { if(f[j]==0) { ch=true;break; } } if(!ch) { for(int j=0;j<n;j++) { f[j]--; } cnt++; } } out.println(cnt); } static int[][] makeMat(int n,int st) { int[][] mat=new int[n][n]; for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { if(st==0) { if((i+j)%2!=0)mat[i][j]=1; } else { if((i+j)%2==0)mat[i][j]=1; } } } return mat; } static int diff(int[][] a1,int[][] a2) { int n=a1.length,cnt=0; for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { if(a1[i][j]!=a2[i][j])cnt++; } } return cnt; } static class Pair { long x; long y; public Pair(long x,long y) { this.x=x; this.y=y; } } static long lcm(int a,int b) { long val=a; val*=b; return (val/gcd(a,b)); } static int gcd(int a,int b) { if(a==0)return b; return gcd(b%a,a); } static int pow(int a, int b, int p) { long ans = 1, base = a; while (b!=0) { if ((b & 1)!=0) { ans *= base; ans%= p; } base *= base; base%= p; b >>= 1; } return (int)ans; } static int inv(int x, int p) { return pow(x, p - 2, p); } void run() throws Exception { if(codechef)oj=true; 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 HR27().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
["1\n0\n\n0\n\n1\n\n0", "3\n101\n010\n101\n\n101\n000\n101\n\n010\n101\n011\n\n010\n101\n010"]
1 second
["1", "2"]
null
Java 8
standard input
[ "implementation", "bitmasks", "brute force" ]
dc46c6cb6b4b9b5e7e6e5b4b7d034874
The first line contains odd integer n (1 ≤ n ≤ 100) — the size of all pieces of the board. Then 4 segments follow, each describes one piece of the board. Each consists of n lines of n characters; j-th one of i-th line is equal to 1 if the square is black initially and 0 otherwise. Segments are separated by an empty line.
1,400
Print one number — minimum number of squares Magnus should recolor to be able to obtain a valid chessboard.
standard output
PASSED
2b4875ed8bf65a1dfef85e304dcecc13
train_003.jsonl
1522850700
Magnus decided to play a classic chess game. Though what he saw in his locker shocked him! His favourite chessboard got broken into 4 pieces, each of size n by n, n is always odd. And what's even worse, some squares were of wrong color. j-th square of the i-th row of k-th piece of the board has color ak, i, j; 1 being black and 0 being white. Now Magnus wants to change color of some squares in such a way that he recolors minimum number of squares and obtained pieces form a valid chessboard. Every square has its color different to each of the neightbouring by side squares in a valid board. Its size should be 2n by 2n. You are allowed to move pieces but not allowed to rotate or flip them.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Scanner; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Swatantra */ 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); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { public void solve(int testNumber, Scanner in, PrintWriter out) { int n = Integer.parseInt(in.nextLine()); String wb[][] = new String[4][n]; int i, j, p, k; //in.nextLine(); for (i = 0; i < 4; i++) { for (j = 0; j < n; j++) { // System.out.println("n="+n); wb[i][j] = in.nextLine(); //System.out.println("w="+wb[i][j]); } if (i != 3) in.nextLine(); } int cb[][][] = new int[2][n][n]; int color = 0; for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { cb[0][i][j] = color; cb[1][i][j] = 1 - color; color = 1 - color; } } int res = Integer.MAX_VALUE; for (i = 3; i <= 16; i++) { int myc = Integer.MAX_VALUE; if (Integer.bitCount(i) == 2) { myc = 0; for (j = 0; j < 4; j++) { int bp = ((1 << j) & i) != 0 ? 1 : 0; for (p = 0; p < n; p++) { for (k = 0; k < n; k++) { // System.out.println("bp="+bp+" p="+p+"k="+k); if (cb[bp][p][k] != (wb[j][p].charAt(k) - '0')) { myc++; } } } } } res = Math.min(res, myc); } out.println(res); } } }
Java
["1\n0\n\n0\n\n1\n\n0", "3\n101\n010\n101\n\n101\n000\n101\n\n010\n101\n011\n\n010\n101\n010"]
1 second
["1", "2"]
null
Java 8
standard input
[ "implementation", "bitmasks", "brute force" ]
dc46c6cb6b4b9b5e7e6e5b4b7d034874
The first line contains odd integer n (1 ≤ n ≤ 100) — the size of all pieces of the board. Then 4 segments follow, each describes one piece of the board. Each consists of n lines of n characters; j-th one of i-th line is equal to 1 if the square is black initially and 0 otherwise. Segments are separated by an empty line.
1,400
Print one number — minimum number of squares Magnus should recolor to be able to obtain a valid chessboard.
standard output
PASSED
af71eb00e16201b47c5413224087490f
train_003.jsonl
1522850700
Magnus decided to play a classic chess game. Though what he saw in his locker shocked him! His favourite chessboard got broken into 4 pieces, each of size n by n, n is always odd. And what's even worse, some squares were of wrong color. j-th square of the i-th row of k-th piece of the board has color ak, i, j; 1 being black and 0 being white. Now Magnus wants to change color of some squares in such a way that he recolors minimum number of squares and obtained pieces form a valid chessboard. Every square has its color different to each of the neightbouring by side squares in a valid board. Its size should be 2n by 2n. You are allowed to move pieces but not allowed to rotate or flip them.
256 megabytes
import java.util.*; import java.io.*; public class tr0 { static PrintWriter out; static StringBuilder sb; static int mod = 998244353; static long inf = (long) 1e18 + 1; static int[] col; static int n, m; static ArrayList<pair>[] ad; static long[][][] memo; static HashSet<Integer> h; static int[] a; static char[][][] g; static int ans = Integer.MAX_VALUE; public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); out = new PrintWriter(System.out); n = sc.nextInt(); g = new char[4][n][n]; for (int i = 0; i < n; i++) g[0][i] = sc.nextLine().toCharArray(); sc.nextLine(); for (int i = 0; i < n; i++) g[1][i] = sc.nextLine().toCharArray(); sc.nextLine(); for (int i = 0; i < n; i++) g[2][i] = sc.nextLine().toCharArray(); sc.nextLine(); for (int i = 0; i < n; i++) g[3][i] = sc.nextLine().toCharArray(); prm = new int[4]; Arrays.fill(prm, -1); cal(0); System.out.println(ans); out.flush(); } static int[] prm; static void cal(int i) { if (i == 4) { int tem = 0; char[][] ch = new char[2 * n][2 * n]; for (int o = 0; o < 2 * n; o++) for (int oo = 0; oo < 2 * n; oo++) { if (o >= n && oo >= n) ch[o][oo] = g[prm[2]][o - n][oo - n]; else if (o >= n) ch[o][oo] = g[prm[3]][o - n][oo]; else if (oo >= n) { ch[o][oo] = g[prm[1]][o][oo - n]; } else ch[o][oo] = g[prm[0]][o][oo]; } for (int o = 0; o < 2 * n; o++) for (int oo = 0; oo < 2 * n; oo++) { if ((o + oo) % 2 == 0 && ch[o][oo] != '0') tem++; if ((o + oo) % 2 == 1 && ch[o][oo] != '1') tem++; } ans = Math.min(ans, tem); tem = 0; for (int o = 0; o < 2 * n; o++) for (int oo = 0; oo < 2 * n; oo++) { if ((o + oo) % 2 == 0 && ch[o][oo] != '1') tem++; if ((o + oo) % 2 == 1 && ch[o][oo] != '0') tem++; } ans = Math.min(ans, tem); return; } for (int j = 0; j < 4; j++) { if (prm[j] == -1) { prm[j] = i; cal(i + 1); prm[j] = -1; } } } static class pair implements Comparable<pair> { int to; int number; pair(int t, int n) { number = n; to = t; } public String toString() { return to + " " + number; } @Override public int compareTo(pair o) { if (to == o.to) return number - o.number; return to - o.to; } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream system) { br = new BufferedReader(new InputStreamReader(system)); } public Scanner(String file) throws Exception { br = new BufferedReader(new FileReader(file)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public String nextLine() throws IOException { return br.readLine(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public char nextChar() throws IOException { return next().charAt(0); } public Long nextLong() throws IOException { return Long.parseLong(next()); } public int[] nextArrInt(int n) throws IOException { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public long[] nextArrLong(int n) throws IOException { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } public boolean ready() throws IOException { return br.ready(); } public void waitForInput() throws InterruptedException { Thread.sleep(3000); } } }
Java
["1\n0\n\n0\n\n1\n\n0", "3\n101\n010\n101\n\n101\n000\n101\n\n010\n101\n011\n\n010\n101\n010"]
1 second
["1", "2"]
null
Java 8
standard input
[ "implementation", "bitmasks", "brute force" ]
dc46c6cb6b4b9b5e7e6e5b4b7d034874
The first line contains odd integer n (1 ≤ n ≤ 100) — the size of all pieces of the board. Then 4 segments follow, each describes one piece of the board. Each consists of n lines of n characters; j-th one of i-th line is equal to 1 if the square is black initially and 0 otherwise. Segments are separated by an empty line.
1,400
Print one number — minimum number of squares Magnus should recolor to be able to obtain a valid chessboard.
standard output
PASSED
9ea5375654cbdbce524e8cded28800ee
train_003.jsonl
1522850700
Magnus decided to play a classic chess game. Though what he saw in his locker shocked him! His favourite chessboard got broken into 4 pieces, each of size n by n, n is always odd. And what's even worse, some squares were of wrong color. j-th square of the i-th row of k-th piece of the board has color ak, i, j; 1 being black and 0 being white. Now Magnus wants to change color of some squares in such a way that he recolors minimum number of squares and obtained pieces form a valid chessboard. Every square has its color different to each of the neightbouring by side squares in a valid board. Its size should be 2n by 2n. You are allowed to move pieces but not allowed to rotate or flip them.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Arrays; import java.io.BufferedWriter; import java.util.InputMismatchException; import java.io.IOException; 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) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); ProblemCChessboard solver = new ProblemCChessboard(); solver.solve(1, in, out); out.close(); } static class ProblemCChessboard { public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.nextInt(); String[] a = new String[4]; Arrays.fill(a, ""); for (int i = 0; i < 4; ++i) { for (int j = 0; j < n; ++j) { a[i] += in.next(); } } char[][] o = new char[2][n * n]; for (int i = 0; i < n * n; ++i) o[0][i] = i % 2 == 0 ? '1' : '0'; for (int i = 0; i < n * n; ++i) o[1][i] = i % 2 == 0 ? '0' : '1'; int[][] best = new int[4][2]; for (int i = 0; i < 4; ++i) { for (int j = 0; j < 2; ++j) { int cnt = 0; for (int k = 0; k < n * n; ++k) { if (a[i].charAt(k) != o[j][k]) ++cnt; } best[i][j] = cnt; } } int res = Integer.MAX_VALUE; res = Math.min(res, best[0][0] + best[1][0] + best[2][1] + best[3][1]); res = Math.min(res, best[0][1] + best[1][1] + best[2][0] + best[3][0]); res = Math.min(res, best[0][1] + best[1][0] + best[2][1] + best[3][0]); res = Math.min(res, best[0][0] + best[1][1] + best[2][0] + best[3][1]); res = Math.min(res, best[0][0] + best[1][1] + best[2][1] + best[3][0]); res = Math.min(res, best[0][1] + best[1][0] + best[2][0] + best[3][1]); out.println(res); } } 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 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 String nextString() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { if (Character.isValidCodePoint(c)) { res.appendCodePoint(c); } c = read(); } while (!isSpaceChar(c)); return res.toString(); } 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 String next() { return nextString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["1\n0\n\n0\n\n1\n\n0", "3\n101\n010\n101\n\n101\n000\n101\n\n010\n101\n011\n\n010\n101\n010"]
1 second
["1", "2"]
null
Java 8
standard input
[ "implementation", "bitmasks", "brute force" ]
dc46c6cb6b4b9b5e7e6e5b4b7d034874
The first line contains odd integer n (1 ≤ n ≤ 100) — the size of all pieces of the board. Then 4 segments follow, each describes one piece of the board. Each consists of n lines of n characters; j-th one of i-th line is equal to 1 if the square is black initially and 0 otherwise. Segments are separated by an empty line.
1,400
Print one number — minimum number of squares Magnus should recolor to be able to obtain a valid chessboard.
standard output
PASSED
797ee7f522b3204b38171bcdb480274b
train_003.jsonl
1522850700
Magnus decided to play a classic chess game. Though what he saw in his locker shocked him! His favourite chessboard got broken into 4 pieces, each of size n by n, n is always odd. And what's even worse, some squares were of wrong color. j-th square of the i-th row of k-th piece of the board has color ak, i, j; 1 being black and 0 being white. Now Magnus wants to change color of some squares in such a way that he recolors minimum number of squares and obtained pieces form a valid chessboard. Every square has its color different to each of the neightbouring by side squares in a valid board. Its size should be 2n by 2n. You are allowed to move pieces but not allowed to rotate or flip them.
256 megabytes
import java.util.ArrayList; import java.util.Scanner; public final class ChessBoardCF { public static int min=Integer.MAX_VALUE; public static void main(String[] args) { Scanner sc=new Scanner(System.in); int n=sc.nextInt(); int first[][]=new int[n][n]; int second[][]=new int[n][n]; int third[][]=new int[n][n]; int fourth[][]=new int[n][n]; for(int i=0;i<n;i++){ String s=sc.next(); for(int j=0;j<n;j++){ first[i][j]=Integer.parseInt(s.charAt(j)+""); } } for(int i=0;i<n;i++){ String s=sc.next(); for(int j=0;j<n;j++){ second[i][j]=Integer.parseInt(s.charAt(j)+""); } } for(int i=0;i<n;i++){ String s=sc.next(); for(int j=0;j<n;j++){ third[i][j]=Integer.parseInt(s.charAt(j)+""); } } for(int i=0;i<n;i++){ String s=sc.next(); for(int j=0;j<n;j++){ fourth[i][j]=Integer.parseInt(s.charAt(j)+""); } } ArrayList<int[][]> l=new ArrayList<>(); l.add(first); l.add(second); l.add(third); l.add(fourth); int arr[]=new int[4]; for(int i=0;i<4;i++) arr[i]=i+1; boolean vis[]=new boolean[4]; int ans[]=new int[4]; helper(l,n,arr,0,vis,ans,0,4); System.out.println(min); } private static void helper(ArrayList<int [][]> l, int n, int[] arr, int start, boolean[] vis, int[] ans, int index, int size) { if(start==size){ helper2(l,n,ans); return; } for(int i=0;i<size;i++){ if(!vis[i]){ ans[index]=arr[i]; vis[i]=true; helper(l, n, arr, start+1, vis, ans, index+1, size); vis[i]=false; } } } private static void helper2(ArrayList<int [][]> l, int n, int[] ans) { int first[][]=l.get(ans[0]-1); int second[][]=l.get(ans[1]-1); int third[][]=l.get(ans[2]-1); int fourth[][]=l.get(ans[3]-1); int count=0; for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ if((i+j)%2==0){ if(first[i][j]!=1) count++; if(fourth[i][j]!=1) count++; }else{ if(first[i][j]!=0) count++; if(fourth[i][j]!=0) count++; } } } for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ if((i+j)%2==0){ if(second[i][j]!=0) count++; if(third[i][j]!=0) count++; }else{ if(second[i][j]!=1) count++; if(third[i][j]!=1) count++; } } } min=Math.min(min,count); } }
Java
["1\n0\n\n0\n\n1\n\n0", "3\n101\n010\n101\n\n101\n000\n101\n\n010\n101\n011\n\n010\n101\n010"]
1 second
["1", "2"]
null
Java 8
standard input
[ "implementation", "bitmasks", "brute force" ]
dc46c6cb6b4b9b5e7e6e5b4b7d034874
The first line contains odd integer n (1 ≤ n ≤ 100) — the size of all pieces of the board. Then 4 segments follow, each describes one piece of the board. Each consists of n lines of n characters; j-th one of i-th line is equal to 1 if the square is black initially and 0 otherwise. Segments are separated by an empty line.
1,400
Print one number — minimum number of squares Magnus should recolor to be able to obtain a valid chessboard.
standard output
PASSED
75ec474840d050469b775743a13813e4
train_003.jsonl
1522850700
Magnus decided to play a classic chess game. Though what he saw in his locker shocked him! His favourite chessboard got broken into 4 pieces, each of size n by n, n is always odd. And what's even worse, some squares were of wrong color. j-th square of the i-th row of k-th piece of the board has color ak, i, j; 1 being black and 0 being white. Now Magnus wants to change color of some squares in such a way that he recolors minimum number of squares and obtained pieces form a valid chessboard. Every square has its color different to each of the neightbouring by side squares in a valid board. Its size should be 2n by 2n. You are allowed to move pieces but not allowed to rotate or flip them.
256 megabytes
import java.io.*; import java.util.*; /** * * @author akashvermaofskt * Coding is love <3! */ public class C { public static void main(String args[]) { try { int n=nextInt(); int A[][]=new int[n][n]; int B[][]=new int[n][n]; int C[][]=new int[n][n]; int D[][]=new int[n][n]; int P[][]=new int[n][n]; int Q[][]=new int[n][n]; for (int i = 0; i < n; i++) { String s=next(); for (int j = 0; j < n; j++) { A[i][j]=Integer.parseInt(s.charAt(j)+""); } } for (int i = 0; i < n; i++) { String s=next(); for (int j = 0; j < n; j++) { B[i][j]=Integer.parseInt(s.charAt(j)+""); } } for (int i = 0; i < n; i++) { String s=next(); for (int j = 0; j < n; j++) { C[i][j]=Integer.parseInt(s.charAt(j)+""); } } for (int i = 0; i < n; i++) { String s=next(); for (int j = 0; j < n; j++) { D[i][j]=Integer.parseInt(s.charAt(j)+""); } } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if((i+j)%2==0){ P[i][j]=0; Q[i][j]=1; }else{ P[i][j]=1; Q[i][j]=0; } } //System.out.println(""+Arrays.toString(P[i])); } int mat[][]=new int[4][2]; for (int k = 0; k < n; k++) { for (int l = 0; l < n; l++) { if(A[k][l]!=P[k][l]) mat[0][0]++; } } for (int k = 0; k < n; k++) { for (int l = 0; l < n; l++) { if(A[k][l]!=Q[k][l]) mat[0][1]++; } } for (int k = 0; k < n; k++) { for (int l = 0; l < n; l++) { if(B[k][l]!=P[k][l]) mat[1][0]++; } } for (int k = 0; k < n; k++) { for (int l = 0; l < n; l++) { if(B[k][l]!=Q[k][l]) mat[1][1]++; } } for (int k = 0; k < n; k++) { for (int l = 0; l < n; l++) { if(C[k][l]!=P[k][l]) mat[2][0]++; } } for (int k = 0; k < n; k++) { for (int l = 0; l < n; l++) { if(C[k][l]!=Q[k][l]) mat[2][1]++; } } for (int k = 0; k < n; k++) { for (int l = 0; l < n; l++) { if(D[k][l]!=P[k][l]) mat[3][0]++; } } for (int k = 0; k < n; k++) { for (int l = 0; l < n; l++) { if(D[k][l]!=Q[k][l]) mat[3][1]++; } } // for (int i = 0; i < 4; i++) { // System.out.println(""+Arrays.toString(mat[i])); // } long ans1=mat[0][0]+mat[1][0]+mat[2][1]+mat[3][1]; long ans2=mat[0][0]+mat[1][1]+mat[2][1]+mat[3][0]; long ans3=mat[0][1]+mat[1][1]+mat[2][0]+mat[3][0]; long ans4=mat[0][1]+mat[1][0]+mat[2][0]+mat[3][1]; long ans5=mat[0][1]+mat[1][0]+mat[2][1]+mat[3][0]; long ans6=mat[0][0]+mat[1][1]+mat[2][0]+mat[3][1]; long ans=Math.min(Math.min(ans1, ans2), Math.min(ans3, ans4)); ans=Math.min(ans, Math.min(ans5, ans6)); bw.write(ans+"\n"); bw.flush(); } catch (Exception e) { e.printStackTrace(); } } //TEMPLATE //****************************************************************************** // Fast I/O static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); static StringTokenizer st = null; static int mod=1000000007; static String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } static int nextInt() { return Integer.parseInt(next()); } static long nextLong() { return Long.parseLong(next()); } static double nextDouble() { return Double.parseDouble(next()); } static int b_search(int l,int r,int A[],int key){ int ans=0; l=0;r=1000000000; while(l<r){ //System.out.println(ans); ans=(l+r)/2; long temp=0; for (int i = 0; i < A.length; i++) { temp+=(long)Math.ceil((double)A[i]/(double)ans); } if(temp<=key){ r=ans; } else{ l=ans+1; ans=r; } } return ans; } //****************************************************************************** //Modulo and FastExpo static long modInverse(long a) { return power(a, mod - 2,mod); } // To compute x^y under modulo m static long power(long x, long y, int p) { // Initialize result long res = 1; // Update x if it is more // than or equal to p x = x % p; while (y > 0) { // If y is odd, multiply x // with result if((y & 1)==1) res = (res * x) % p; // y must be even now // y = y / 2 y = y >> 1; x = (x * x) % p; } return res; } //****************************************************************************** //GCD static long gcd(long a, long b) { if (a == 0) return b; return gcd(b%a, a); } //****************************************************************************** // Useful user datatype static class Pair{ public long x; public long y; public Pair(long first, long second){ this.x = first; this.y = second; } @Override public String toString() { return "(" + x + "," + y + ")"; } } static Comparator csort=new Comparator<Pair>(){ public int compare(Pair a, Pair b) { if(a.x < b.x) return -1; else if (a.x > b.x) return 1; else if(a.y < b.y) return -1; else if (a.y > b.y) return 1; else return 0; } }; //****************************************************************************** //N choose K public static long choose(long total, long choose){ if(total < choose) return 0; if(choose == 0 || choose == total) return 1; return choose(total-1,choose-1)+choose(total-1,choose); } //****************************************************************************** //Permutations // simply prints all permutation - to see how it works private static void printPermutations( Comparable[] c ) { System.out.println( Arrays.toString( c ) ); while ( ( c = nextPermutation( c ) ) != null ) { System.out.println( Arrays.toString( c ) ); } } // modifies c to next permutation or returns null if such permutation does not exist private static Comparable[] nextPermutation( final Comparable[] c ) { // 1. finds the largest k, that c[k] < c[k+1] int first = getFirst( c ); if ( first == -1 ) return null; // no greater permutation // 2. find last index toSwap, that c[k] < c[toSwap] int toSwap = c.length - 1; while ( c[ first ].compareTo( c[ toSwap ] ) >= 0 ) --toSwap; // 3. swap elements with indexes first and last swap( c, first++, toSwap ); // 4. reverse sequence from k+1 to n (inclusive) toSwap = c.length - 1; while ( first < toSwap ) swap( c, first++, toSwap-- ); return c; } // finds the largest k, that c[k] < c[k+1] // if no such k exists (there is not greater permutation), return -1 private static int getFirst( final Comparable[] c ) { for ( int i = c.length - 2; i >= 0; --i ) if ( c[ i ].compareTo( c[ i + 1 ] ) < 0 ) return i; return -1; } // swaps two elements (with indexes i and j) in array private static void swap( final Comparable[] c, final int i, final int j ) { final Comparable tmp = c[ i ]; c[ i ] = c[ j ]; c[ j ] = tmp; } //****************************************************************************** // DSU //Maintain an Array A with N elements and Array size for size of each set, intialize A[i]=i and size[i]=1 static int root(int A[],int i){ while(A[i]!=i){ A[i]=A[A[i]]; i=A[i]; } return i; } static boolean find(int A[],int a,int b){ if(root(A,a)==root(A,b))return true; else return false; } static void union(int A[],int size[],int a,int b){ int ra=root(A,a); int rb=root(A,b); if(ra==rb)return; if(size[ra]<size[rb]){ A[ra]=A[rb]; size[rb]+=size[ra]; }else{ A[rb]=A[ra]; size[ra]+=size[rb]; } } //************************************************************************** //BinarySearch /* binary search for 5: v-- lower bound 1 2 3 4 5 5 5 6 7 9 ^-- upper bound binary search for 8 v-- lower bound 1 2 3 4 5 5 5 6 7 9 ^-- upper bound */ //For finding greater than static int upper_bound(int A[],int key){ int first = 0; int last = A.length; int mid; while (first < last) { mid =first+(last - first)/2; if (A[mid] <= key) first = mid + 1; else last = mid; } return first; } //For finding greater than equal to static int lower_bound(int A[],int key){ int first = 0; int last = A.length; int mid=0; while (first < last) { mid = first + ((last - first) >> 1); if (A[mid] < key) first = mid + 1; else last = mid; } return first; } //************************************************************************** }
Java
["1\n0\n\n0\n\n1\n\n0", "3\n101\n010\n101\n\n101\n000\n101\n\n010\n101\n011\n\n010\n101\n010"]
1 second
["1", "2"]
null
Java 8
standard input
[ "implementation", "bitmasks", "brute force" ]
dc46c6cb6b4b9b5e7e6e5b4b7d034874
The first line contains odd integer n (1 ≤ n ≤ 100) — the size of all pieces of the board. Then 4 segments follow, each describes one piece of the board. Each consists of n lines of n characters; j-th one of i-th line is equal to 1 if the square is black initially and 0 otherwise. Segments are separated by an empty line.
1,400
Print one number — minimum number of squares Magnus should recolor to be able to obtain a valid chessboard.
standard output
PASSED
6b1f621068a0f689bf167043881dffea
train_003.jsonl
1522850700
Magnus decided to play a classic chess game. Though what he saw in his locker shocked him! His favourite chessboard got broken into 4 pieces, each of size n by n, n is always odd. And what's even worse, some squares were of wrong color. j-th square of the i-th row of k-th piece of the board has color ak, i, j; 1 being black and 0 being white. Now Magnus wants to change color of some squares in such a way that he recolors minimum number of squares and obtained pieces form a valid chessboard. Every square has its color different to each of the neightbouring by side squares in a valid board. Its size should be 2n by 2n. You are allowed to move pieces but not allowed to rotate or flip them.
256 megabytes
import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.BitSet; import java.util.Calendar; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.PriorityQueue; import java.util.SortedSet; import java.util.Stack; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.TreeSet; /** * # * @author pttrung */ public class C_Edu_Round_41 { public static long MOD = 1000000007; public static void main(String[] args) throws FileNotFoundException { // PrintWriter out = new PrintWriter(new FileOutputStream(new File( // "output.txt"))); PrintWriter out = new PrintWriter(System.out); Scanner in = new Scanner(); int n = in.nextInt(); String[][] data = new String[4][n]; for (int i = 0; i < 4; i++) { for (int j = 0; j < n; j++) { data[i][j] = in.next(); } in.nextLine(); } int[][][] sample = new int[2][n][n]; int start = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { sample[0][i][j] = start; sample[1][i][j] = 1 - start; start = 1 - start; } } int re = Integer.MAX_VALUE; for (int z = 0; z < 16; z++) { if (Integer.bitCount(z) == 2) { int tmp = 0; for (int i = 0; i < 4; i++) { int index = (((1 << i) & z) != 0) ? 0 : 1; for (int j = 0; j < n; j++) { for (int k = 0; k < n; k++) { int v = data[i][j].charAt(k) - '0'; if (v != sample[index][j][k]) { tmp++; } } } } re = Integer.min(re, tmp); } } out.println(re); out.close(); } public static int[] KMP(String val) { int i = 0; int j = -1; int[] result = new int[val.length() + 1]; result[0] = -1; while (i < val.length()) { while (j >= 0 && val.charAt(j) != val.charAt(i)) { j = result[j]; } j++; i++; result[i] = j; } return result; } 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 int digit(long n) { int result = 0; while (n > 0) { n /= 10; result++; } return result; } public static double dist(long a, long b, long x, long y) { double val = (b - a) * (b - a) + (x - y) * (x - y); val = Math.sqrt(val); double other = x * x + a * a; other = Math.sqrt(other); return val + other; } public static class Point implements Comparable<Point> { int x, y; public Point(int start, int end) { this.x = start; this.y = end; } @Override public int hashCode() { int hash = 5; hash = 47 * hash + this.x; hash = 47 * hash + this.y; return hash; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Point other = (Point) obj; if (this.x != other.x) { return false; } if (this.y != other.y) { return false; } return true; } @Override public int compareTo(Point o) { return Integer.compare(x, o.x); } } public static class FT { long[] data; FT(int n) { data = new long[n]; } public void update(int index, long value) { while (index < data.length) { data[index] += value; index += (index & (-index)); } } public long get(int index) { long result = 0; while (index > 0) { result += data[index]; index -= (index & (-index)); } return result; } } public static long gcd(long a, long b) { if (b == 0) { return a; } return gcd(b, a % b); } public static long pow(long a, long b, long MOD) { if (b == 0) { return 1; } if (b == 1) { return a; } long val = pow(a, b / 2, MOD); if (b % 2 == 0) { return val * val % MOD; } else { return val * (val * a % MOD) % MOD; } } 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 InputStreamReader(new FileInputStream(new File("input.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
["1\n0\n\n0\n\n1\n\n0", "3\n101\n010\n101\n\n101\n000\n101\n\n010\n101\n011\n\n010\n101\n010"]
1 second
["1", "2"]
null
Java 8
standard input
[ "implementation", "bitmasks", "brute force" ]
dc46c6cb6b4b9b5e7e6e5b4b7d034874
The first line contains odd integer n (1 ≤ n ≤ 100) — the size of all pieces of the board. Then 4 segments follow, each describes one piece of the board. Each consists of n lines of n characters; j-th one of i-th line is equal to 1 if the square is black initially and 0 otherwise. Segments are separated by an empty line.
1,400
Print one number — minimum number of squares Magnus should recolor to be able to obtain a valid chessboard.
standard output
PASSED
523e940bc51cc56ff26d2b1e892db660
train_003.jsonl
1522850700
Magnus decided to play a classic chess game. Though what he saw in his locker shocked him! His favourite chessboard got broken into 4 pieces, each of size n by n, n is always odd. And what's even worse, some squares were of wrong color. j-th square of the i-th row of k-th piece of the board has color ak, i, j; 1 being black and 0 being white. Now Magnus wants to change color of some squares in such a way that he recolors minimum number of squares and obtained pieces form a valid chessboard. Every square has its color different to each of the neightbouring by side squares in a valid board. Its size should be 2n by 2n. You are allowed to move pieces but not allowed to rotate or flip them.
256 megabytes
import java.io.BufferedReader; import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; import static java.lang.Math.min; import static java.lang.Math.sqrt; public class Chessboard implements Closeable { private InputReader in = new InputReader(System.in); private PrintWriter out = new PrintWriter(System.out); public void solve() { n = in.ni(); board = new char[2 * n][2 * n]; pieces = new char[4][n][n]; for (int i = 0; i < 4; i++) { for (int j = 0; j < n; j++) { char[] line = in.next().toCharArray(); System.arraycopy(line, 0, pieces[i][j], 0, n); } } for (int i = 0; i < 4; i++) { recurse(0); } out.println(min); } private int n; private int min = (int) 1e8; private char[][] board; private char[][][] pieces; private boolean[] used = new boolean[4]; private void recurse(int count) { if (count == 4) { check(0); check(1); } else { for (int i = 0; i < 4; i++) { if (!used[i]) { used[i] = true; copy(pieces[i], count + 1); recurse(count + 1); used[i] = false; } } } } private void copy(char[][] piece, int place) { int x = 0, y = 0; switch (place) { case 0: { x = 0; y = 0; break; } case 1: { x = 0; y = n; break; } case 2: { x = n; y = 0; break; } case 3: { x = n; y = n; break; } } for (int i = 0; i < n; i++) { System.arraycopy(piece[i], 0, board[x + i], y, n); } } private void check(int even) { int odd = even ^ 1, result = 0; for (int i = 0; i < board.length; i++) { for (int j = 0; j < board.length; j++) { int value = (board[i][j] - '0'); if ((i + j) % 2 == 0) { if (value != even) { result++; } } else { if (value != odd) { result++; } } } } min = Math.min(result, min); } @Override public void close() throws IOException { in.close(); out.close(); } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int ni() { return Integer.parseInt(next()); } public long nl() { return Long.parseLong(next()); } public void close() throws IOException { reader.close(); } } public static void main(String[] args) throws IOException { try (Chessboard instance = new Chessboard()) { instance.solve(); } } }
Java
["1\n0\n\n0\n\n1\n\n0", "3\n101\n010\n101\n\n101\n000\n101\n\n010\n101\n011\n\n010\n101\n010"]
1 second
["1", "2"]
null
Java 8
standard input
[ "implementation", "bitmasks", "brute force" ]
dc46c6cb6b4b9b5e7e6e5b4b7d034874
The first line contains odd integer n (1 ≤ n ≤ 100) — the size of all pieces of the board. Then 4 segments follow, each describes one piece of the board. Each consists of n lines of n characters; j-th one of i-th line is equal to 1 if the square is black initially and 0 otherwise. Segments are separated by an empty line.
1,400
Print one number — minimum number of squares Magnus should recolor to be able to obtain a valid chessboard.
standard output
PASSED
905d3c7da806795bbc32254e7a0861e4
train_003.jsonl
1522850700
Magnus decided to play a classic chess game. Though what he saw in his locker shocked him! His favourite chessboard got broken into 4 pieces, each of size n by n, n is always odd. And what's even worse, some squares were of wrong color. j-th square of the i-th row of k-th piece of the board has color ak, i, j; 1 being black and 0 being white. Now Magnus wants to change color of some squares in such a way that he recolors minimum number of squares and obtained pieces form a valid chessboard. Every square has its color different to each of the neightbouring by side squares in a valid board. Its size should be 2n by 2n. You are allowed to move pieces but not allowed to rotate or flip them.
256 megabytes
//package codeforces; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Scanner; public class Chessboard961 { public static void main(String[] args) { Scanner scan = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); new Chessboard961().solve(scan, out); scan.close(); out.close(); } ArrayList<int[]> perms = new ArrayList<>(); int[] P = {0,1,2,3}; private void solve(Scanner scan, PrintWriter out) { //System.out.println(('1'-'0')); int n = scan.nextInt(); int[][][] boards = new int[4][n][n]; for(int a=0; a<4; a++) { for(int i=0; i<n; i++) { String num = scan.next(); for(int j=0; j<n; j++) { boards[a][i][j] = num.charAt(j)-'0'; //num/=10; //System.out.print(boards[a][i][j] + " "); } //System.out.println(); } scan.nextLine(); } permute(0, new boolean[4], new int[4]); //System.out.println(perms); int minCount = Integer.MAX_VALUE; for(int perm=0; perm<perms.size(); perm++) { int[][] chessboard = new int[2*n][2*n]; for(int piece=0; piece<4; piece++) { int chessPiece = perms.get(perm)[piece]; int k=(piece>=2)?n:0; int l=(piece == 1 || piece==3)?n:0; //System.out.println("piece"+piece); for(int i=0+k; i<n+k; i++) { for(int j=0+l; j<n+l; j++) { //System.out.println("ChessPiece "+chessPiece+" i "+i+" j "+j); chessboard[i][j] = boards[chessPiece][i-k][j-l]; } } } for(int black=0; black<=1; black++) { int count = 0; for(int i=0; i<2*n; i++) { for(int j=0; j<2*n; j++) { //System.out.print(chessboard[i][j]); if((i+j)%2==0) { if(chessboard[i][j]==black) { count++; } } else { if(chessboard[i][j]!=black) { count++; } } } //System.out.println(); } //System.out.println(); if(count < minCount) { minCount = count; } } } out.println(minCount); } private void permute(int size, boolean[] used, int[] perm) { if(size==4) { int[] copy = new int[4]; for(int i=0; i<4; i++) { copy[i]=perm[i]; } perms.add(copy); return; } for(int i=0; i<4; i++) { if(!used[i]) { perm[size] = P[i]; used[i] = true; permute(size+1, used, perm); used[i] = false; } } } }
Java
["1\n0\n\n0\n\n1\n\n0", "3\n101\n010\n101\n\n101\n000\n101\n\n010\n101\n011\n\n010\n101\n010"]
1 second
["1", "2"]
null
Java 8
standard input
[ "implementation", "bitmasks", "brute force" ]
dc46c6cb6b4b9b5e7e6e5b4b7d034874
The first line contains odd integer n (1 ≤ n ≤ 100) — the size of all pieces of the board. Then 4 segments follow, each describes one piece of the board. Each consists of n lines of n characters; j-th one of i-th line is equal to 1 if the square is black initially and 0 otherwise. Segments are separated by an empty line.
1,400
Print one number — minimum number of squares Magnus should recolor to be able to obtain a valid chessboard.
standard output
PASSED
cba92254069d7f5c9af936596e86d6d9
train_003.jsonl
1522850700
Magnus decided to play a classic chess game. Though what he saw in his locker shocked him! His favourite chessboard got broken into 4 pieces, each of size n by n, n is always odd. And what's even worse, some squares were of wrong color. j-th square of the i-th row of k-th piece of the board has color ak, i, j; 1 being black and 0 being white. Now Magnus wants to change color of some squares in such a way that he recolors minimum number of squares and obtained pieces form a valid chessboard. Every square has its color different to each of the neightbouring by side squares in a valid board. Its size should be 2n by 2n. You are allowed to move pieces but not allowed to rotate or flip them.
256 megabytes
import java.io.*; import java.util.*; import java.text.*; import java.lang.*; import java.math.BigInteger; import java.util.regex.*; public class Myclass { public static ArrayList a[]=new ArrayList[200001]; /*static boolean visited[]=new boolean [200001]; static int parent[]=new int[200001]; static int color[]=new int[200001]; static long ans; static void bfs() { Queue<Integer>q=new LinkedList<>(); q.add(1); color[1]=1; parent[1]=0; color[0]=1; ans=1; while(!q.isEmpty()) { int idx=q.poll(); visited[idx]=true; int cnt=1; TreeSet<Integer>tr=new TreeSet<>(); tr.add(color[idx]); tr.add(color[parent[idx]]); for(int i=0;i<a[idx].size();i++) { int id=(int) a[idx].get(i); if(!visited[id]) { while(tr.contains(cnt)) cnt++; parent[id]=idx; color[id]=cnt; ans=Math.max(ans, color[id]); cnt++; q.add(id); } } } }*/ static char s[][][]; static int ans[][]=new int[4][2]; static int n; static int f(int idx) { int cnt=0; for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { if(i%2==0) { if(j%2==0) { if(s[idx][i][j]!='1') cnt++; } else { if(s[idx][i][j]!='0') cnt++; } } else { if(j%2==0) { if(s[idx][i][j]!='0') cnt++; } else { if(s[idx][i][j]!='1') cnt++; } } } } return cnt; } static int f1(int idx) { int cnt=0; for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { if(i%2==0) { if(j%2==0) { if(s[idx][i][j]!='0') cnt++; } else { if(s[idx][i][j]!='1') cnt++; } } else { if(j%2==0) { if(s[idx][i][j]!='1') cnt++; } else { if(s[idx][i][j]!='0') cnt++; } } } } return cnt; } public static void main(String[] args) { InputReader in = new InputReader(System.in); PrintWriter pw = new PrintWriter(System.out); n=in.nextInt(); s=new char[4][n][n]; for(int i=0;i<4;i++) { for(int j=0;j<n;j++) { s[i][j]=in.nextLine().toCharArray(); } } ans[0][0]=f(0); ans[1][0]=f(1); ans[2][0]=f(2); ans[3][0]=f(3); ans[0][1]=f1(0); ans[1][1]=f1(1); ans[2][1]=f1(2); ans[3][1]=f1(3); long fi=Long.MAX_VALUE; fi=Math.min(fi, ans[0][0]+ans[1][0]+ans[2][1]+ans[3][1]); fi=Math.min(fi, ans[0][0]+ans[1][1]+ans[2][0]+ans[3][1]); fi=Math.min(fi, ans[0][0]+ans[1][1]+ans[2][1]+ans[3][0]); fi=Math.min(fi, ans[0][1]+ans[1][0]+ans[2][0]+ans[3][1]); fi=Math.min(fi, ans[0][1]+ans[1][0]+ans[2][1]+ans[3][0]); fi=Math.min(fi, ans[0][1]+ans[1][1]+ans[2][0]+ans[3][0]); pw.println(fi); pw.flush(); pw.close(); } static class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar, snumChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int snext() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } static class tri implements Comparable<tri> { int p, c, l; tri(int p, int c, int l) { this.p = p; this.c = c; this.l = l; } public int compareTo(tri o) { return Integer.compare(l, o.l); } } public String readString() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isSpaceChar(c)); return res.toString(); } public String nextLine() { int c = snext(); while (isSpaceChar(c)) c = snext(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isEndOfLine(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } public static long mod = 1000000007; public static int d; public static int p; public static int q; public static int[] suffle(int[] a,Random gen) { int n = a.length; for(int i=0;i<n;i++) { int ind = gen.nextInt(n-i)+i; int temp = a[ind]; a[ind] = a[i]; a[i] = temp; } return a; } public static void swap(int a, int b){ int temp = a; a = b; b = temp; } public static HashSet<Integer> primeFactorization(int n) { HashSet<Integer> a =new HashSet<Integer>(); for(int i=2;i*i<=n;i++) { while(n%i==0) { a.add(i); n/=i; } } if(n!=1) a.add(n); return a; } public static void sieve(boolean[] isPrime,int n) { for(int i=1;i<n;i++) isPrime[i] = true; isPrime[0] = false; isPrime[1] = false; for(int i=2;i*i<n;i++) { if(isPrime[i] == true) { for(int j=(2*i);j<n;j+=i) isPrime[j] = false; } } } public static int GCD(int a,int b) { if(b==0) return a; else return GCD(b,a%b); } public static long GCD(long a,long b) { if(b==0) return a; else return GCD(b,a%b); } public static void extendedEuclid(int A,int B) { if(B==0) { d = A; p = 1 ; q = 0; } else { extendedEuclid(B, A%B); int temp = p; p = q; q = temp - (A/B)*q; } } public static long LCM(long a,long b) { return (a*b)/GCD(a,b); } public static int LCM(int a,int b) { return (a*b)/GCD(a,b); } public static int binaryExponentiation(int x,int n) { int result=1; while(n>0) { if(n % 2 ==1) result=result * x; x=x*x; n=n/2; } return result; } public static long binaryExponentiation(long x,long n) { long result=1; while(n>0) { if(n % 2 ==1) result=result * x; x=x*x; n=n/2; } return result; } public static int modularExponentiation(int x,int n,int M) { int result=1; while(n>0) { if(n % 2 ==1) result=(result * x)%M; x=(x%M*x)%M; n=n/2; } return result; } public static long modularExponentiation(long x,long n,long M) { long result=1; while(n>0) { if(n % 2 ==1) result=(result%M * x%M)%M; x=(x%M * x%M)%M; n=n/2; } return result; } public static long modInverse(int A,int M) { return modularExponentiation(A,M-2,M); } public static long modInverse(long A,long M) { return modularExponentiation(A,M-2,M); } public static boolean isPrime(int n) { if (n <= 1) return false; if (n <= 3) return true; if (n%2 == 0 || n%3 == 0) return false; for (int i=5; i*i<=n; i=i+6) { if (n%i == 0 || n%(i+2) == 0) return false; } return true; } public static long[] shuffle(long[] a, Random gen){ for(int i = 0, n = a.length;i < n;i++){ int ind = gen.nextInt(n-i)+i; long d = a[i]; a[i] = a[ind]; a[ind] = d; } return a; } static class pair implements Comparable<pair> { Long x; Long y; pair(long a,long m) { this.x=a; this.y=m; } public boolean isEmpty() { // TODO Auto-generated method stub return false; } public int compareTo(pair o) { int result = x.compareTo(o.x); if(result==0) result = y.compareTo(o.y); return result; } public String toString() { return x+" "+y; } public boolean equals(Object o) { if (o instanceof pair) { pair p = (pair)o; return p.x == x && p.y == y ; } return false; } public int hashCode() { return new Long(x).hashCode()*31 + new Long(y).hashCode(); } } }
Java
["1\n0\n\n0\n\n1\n\n0", "3\n101\n010\n101\n\n101\n000\n101\n\n010\n101\n011\n\n010\n101\n010"]
1 second
["1", "2"]
null
Java 8
standard input
[ "implementation", "bitmasks", "brute force" ]
dc46c6cb6b4b9b5e7e6e5b4b7d034874
The first line contains odd integer n (1 ≤ n ≤ 100) — the size of all pieces of the board. Then 4 segments follow, each describes one piece of the board. Each consists of n lines of n characters; j-th one of i-th line is equal to 1 if the square is black initially and 0 otherwise. Segments are separated by an empty line.
1,400
Print one number — minimum number of squares Magnus should recolor to be able to obtain a valid chessboard.
standard output
PASSED
c0925f1b3a68ac57277f737f588ab3fe
train_003.jsonl
1522850700
Magnus decided to play a classic chess game. Though what he saw in his locker shocked him! His favourite chessboard got broken into 4 pieces, each of size n by n, n is always odd. And what's even worse, some squares were of wrong color. j-th square of the i-th row of k-th piece of the board has color ak, i, j; 1 being black and 0 being white. Now Magnus wants to change color of some squares in such a way that he recolors minimum number of squares and obtained pieces form a valid chessboard. Every square has its color different to each of the neightbouring by side squares in a valid board. Its size should be 2n by 2n. You are allowed to move pieces but not allowed to rotate or flip them.
256 megabytes
import java.util.*; import java.io.*; import java.math.*; import java.awt.geom.*; public class ChessBoard{ public static void fill(int[][] a, int n, MyScanner sc){ for(int i=0;i<n;i++){ String s=sc.next(); for(int j=0;j<n;j++) a[i][j]=s.charAt(j)-'0'; } } public static int layer1(int[][] a, int[][] b, int[][] c, int[][] d, int n){ int[] t=new int[6]; t[0]=layer2(a,b,c,d,n); t[1]=layer2(a,b,d,c,n); t[2]=layer2(a,c,b,d,n); t[3]=layer2(a,c,d,b,n); t[4]=layer2(a,d,b,c,n); t[5]=layer2(a,d,c,b,n); int m=Integer.MAX_VALUE; for(int i=0; i<6; i++) { m=Math.min(m, t[i]); } return m; } public static int layer2(int[][] a, int[][] b, int[][] c, int[][] d, int n){ return need(formboard(a,b,c,d,n)); } public static int[][] formboard(int[][] a, int[][] b, int[][] c, int[][] d, int n){ int[][] g=new int[2*n][2*n]; for (int i=0;i<n;i++){ for (int j=0; j<n; j++){ g[i][j] = a[i][j]; } } for (int i=0; i<n; i++){ for (int j=0; j<n; j++){ g[i+n][j]=b[i][j]; } } for (int i=0; i<n; i++){ for (int j=0; j<n; j++){ g[i][j+n]=c[i][j]; } } for (int i=0; i<n; i++){ for (int j=0; j<n; j++){ g[i+n][j+n]=d[i][j]; } } return g; } public static int need(int[][] g){ int p1=0, p2=0; for (int i=0; i<g.length; i++){ for (int j=0; j<g.length; j++){ if (g[i][j] == (i+j)%2){ p1++; } else{ p2++; } } } return Math.min(p1, p2); } public static void main(String[] args) { MyScanner sc=new MyScanner(); int n=sc.ni(); int[][] a=new int[n][n]; int[][] b=new int[n][n]; int[][] c=new int[n][n]; int[][] d=new int[n][n]; fill(a,n,sc); fill(b,n,sc); fill(c,n,sc); fill(d,n,sc); int ans=Integer.MAX_VALUE; ans=Math.min(ans,layer1(a,b,c,d,n)); ans=Math.min(ans,layer1(b,a,c,d,n)); ans=Math.min(ans,layer1(c,b,a,d,n)); ans=Math.min(ans,layer1(d,b,c,a,n)); System.out.println(ans); } private static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int ni() { return Integer.parseInt(next()); } float nf() { return Float.parseFloat(next()); } long nl() { return Long.parseLong(next()); } double nd() { return Double.parseDouble(next()); } String nextLine(){ String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["1\n0\n\n0\n\n1\n\n0", "3\n101\n010\n101\n\n101\n000\n101\n\n010\n101\n011\n\n010\n101\n010"]
1 second
["1", "2"]
null
Java 8
standard input
[ "implementation", "bitmasks", "brute force" ]
dc46c6cb6b4b9b5e7e6e5b4b7d034874
The first line contains odd integer n (1 ≤ n ≤ 100) — the size of all pieces of the board. Then 4 segments follow, each describes one piece of the board. Each consists of n lines of n characters; j-th one of i-th line is equal to 1 if the square is black initially and 0 otherwise. Segments are separated by an empty line.
1,400
Print one number — minimum number of squares Magnus should recolor to be able to obtain a valid chessboard.
standard output
PASSED
626981bbad1e99527e950c4437c18a7e
train_003.jsonl
1522850700
Magnus decided to play a classic chess game. Though what he saw in his locker shocked him! His favourite chessboard got broken into 4 pieces, each of size n by n, n is always odd. And what's even worse, some squares were of wrong color. j-th square of the i-th row of k-th piece of the board has color ak, i, j; 1 being black and 0 being white. Now Magnus wants to change color of some squares in such a way that he recolors minimum number of squares and obtained pieces form a valid chessboard. Every square has its color different to each of the neightbouring by side squares in a valid board. Its size should be 2n by 2n. You are allowed to move pieces but not allowed to rotate or flip them.
256 megabytes
/** * http://codeforces.com/problemset/problem/961/C (Chessboard) * @author Alan Yan * */ import java.util.*; public class Task961C { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = Integer.parseInt(sc.nextLine()); int ret = Integer.MAX_VALUE; int[][][] boards = new int[4][n][n]; int[][][] models = new int[2][n][n]; int[][] numChanges = new int[4][2]; for(int i = 0; i < 4; i++) { for(int j = 0; j < n; j++) { String taco = sc.nextLine(); for(int k = 0; k < n; k++) { boards[i][j][k] = (int) (taco.charAt(k) - '0'); } } if(i < 3) sc.nextLine(); } //create models for(int i = 0; i < n; i++) for(int j = 0; j < n; j++) models[(i+j)%2][i][j] = 1; //create numChanges for(int i = 0; i < 4; i++) for(int j = 0 ; j < 2; j++) for(int a = 0; a < n; a++) for(int b = 0; b < n; b++) if(models[j][a][b] != boards[i][a][b]) numChanges[i][j]++; //choosing which to be of model2 int temp = numChanges[0][0] + numChanges[1][0] + numChanges[2][0] + numChanges[3][0]; for(int i = 0; i < 3; i++) { for(int j = i+1; j < 4; j++) { int x = temp - numChanges[i][0] + numChanges[i][1] - numChanges[j][0] + numChanges[j][1]; ret = Math.min(x, ret); } } System.out.print(ret); sc.close(); } }
Java
["1\n0\n\n0\n\n1\n\n0", "3\n101\n010\n101\n\n101\n000\n101\n\n010\n101\n011\n\n010\n101\n010"]
1 second
["1", "2"]
null
Java 8
standard input
[ "implementation", "bitmasks", "brute force" ]
dc46c6cb6b4b9b5e7e6e5b4b7d034874
The first line contains odd integer n (1 ≤ n ≤ 100) — the size of all pieces of the board. Then 4 segments follow, each describes one piece of the board. Each consists of n lines of n characters; j-th one of i-th line is equal to 1 if the square is black initially and 0 otherwise. Segments are separated by an empty line.
1,400
Print one number — minimum number of squares Magnus should recolor to be able to obtain a valid chessboard.
standard output
PASSED
ccbe3ee9296ddd9f2f999f805906d6dd
train_003.jsonl
1488705300
The evil Bumbershoot corporation produces clones for gruesome experiments in a vast underground lab. On one occasion, the corp cloned a boy Andryusha who was smarter than his comrades. Immediately Andryusha understood that something fishy was going on there. He rallied fellow clones to go on a feud against the evil corp, and they set out to find an exit from the lab. The corp had to reduce to destroy the lab complex.The lab can be pictured as a connected graph with n vertices and m edges. k clones of Andryusha start looking for an exit in some of the vertices. Each clone can traverse any edge once per second. Any number of clones are allowed to be at any vertex simultaneously. Each clone is allowed to stop looking at any time moment, but he must look at his starting vertex at least. The exit can be located at any vertex of the lab, hence each vertex must be visited by at least one clone.Each clone can visit at most vertices before the lab explodes.Your task is to choose starting vertices and searching routes for the clones. Each route can have at most vertices.
256 megabytes
import java.util.*; import java.io.*; public class _0780_E_UndergroundLab { static int N, M; static int ET[]; static int time = 0; static ArrayList<Integer> graph[]; static boolean vis[]; public static void main(String[] args) throws IOException { try { N = readInt(); M = readInt(); int K = readInt(); graph = new ArrayList[N+1]; for(int i = 1; i<=N; i++) graph[i] = new ArrayList<>(); for(int i = 1; i<=M; i++) { int a = readInt(), b = readInt(); graph[a].add(b); graph[b].add(a); } ET = new int[2*N]; vis = new boolean[N+1]; dfs(1); int sz = (2*N+K-1)/(K); int idx = 1; for(int k = 1; k<=K; k++) { ArrayList<Integer> list = new ArrayList<>(); while(list.size() < sz) { list.add(ET[idx++]); if(idx == 2*N) idx = 2; } print(list.size() + " "); for(int n : list) print(n + " "); println(); } } catch (Exception e) { println("1 1"); } exit(); } static void dfs(int n) { ET[++time] = n; vis[n] = true; for(int e : graph[n]) if(!vis[e]){ dfs(e); ET[++time] = n; } } final private static int BUFFER_SIZE = 1 << 16; private static DataInputStream din = new DataInputStream(System.in); private static byte[] buffer = new byte[BUFFER_SIZE]; private static int bufferPointer = 0, bytesRead = 0; static PrintWriter pr = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); public static String readLine() throws IOException { byte[] buf = new byte[64]; // line length int cnt = 0, c; while ((c = Read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public static String read() throws IOException { byte[] ret = new byte[1024]; int idx = 0; byte c = Read(); while (c <= ' ') { c = Read(); } do { ret[idx++] = c; c = Read(); } while (c != -1 && c != ' ' && c != '\n' && c != '\r'); return new String(ret, 0, idx); } public static int readInt() 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 static long readLong() 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 static double readDouble() 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 static void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private static byte Read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } static void print(Object o) { pr.print(o); } static void println(Object o) { pr.println(o); } static void flush() { pr.flush(); } static void println() { pr.println(); } static void exit() throws IOException { din.close(); pr.close(); System.exit(0); } }
Java
["3 2 1\n2 1\n3 1", "5 4 2\n1 2\n1 3\n1 4\n1 5"]
1 second
["3 2 1 3", "3 2 1 3\n3 4 1 5"]
NoteIn the first sample case there is only one clone who may visit vertices in order (2, 1, 3), which fits the constraint of 6 vertices per clone.In the second sample case the two clones can visited vertices in order (2, 1, 3) and (4, 1, 5), which fits the constraint of 5 vertices per clone.
Java 8
standard input
[ "graphs", "constructive algorithms", "dfs and similar", "trees", "brute force" ]
d32d638e5f90f0bfb7b7cec8e541cf7d
The first line contains three integers n, m, and k (1 ≤ n ≤ 2·105, n - 1 ≤ m ≤ 2·105, 1 ≤ k ≤ n) — the number of vertices and edges in the lab, and the number of clones. Each of the next m lines contains two integers xi and yi (1 ≤ xi, yi ≤ n) — indices of vertices connected by the respective edge. The graph is allowed to have self-loops and multiple edges. The graph is guaranteed to be connected.
2,100
You should print k lines. i-th of these lines must start with an integer ci () — the number of vertices visited by i-th clone, followed by ci integers — indices of vertices visited by this clone in the order of visiting. You have to print each vertex every time it is visited, regardless if it was visited earlier or not. It is guaranteed that a valid answer exists.
standard output
PASSED
6991096230055a2ded98d48b83da9f73
train_003.jsonl
1488705300
The evil Bumbershoot corporation produces clones for gruesome experiments in a vast underground lab. On one occasion, the corp cloned a boy Andryusha who was smarter than his comrades. Immediately Andryusha understood that something fishy was going on there. He rallied fellow clones to go on a feud against the evil corp, and they set out to find an exit from the lab. The corp had to reduce to destroy the lab complex.The lab can be pictured as a connected graph with n vertices and m edges. k clones of Andryusha start looking for an exit in some of the vertices. Each clone can traverse any edge once per second. Any number of clones are allowed to be at any vertex simultaneously. Each clone is allowed to stop looking at any time moment, but he must look at his starting vertex at least. The exit can be located at any vertex of the lab, hence each vertex must be visited by at least one clone.Each clone can visit at most vertices before the lab explodes.Your task is to choose starting vertices and searching routes for the clones. Each route can have at most vertices.
256 megabytes
import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class Task781C { static ArrayList<Integer>[] vertices; static boolean[] visited; static List<Integer> path; static void buildPath(Integer node) { path.add(node); visited[node] = true; for (Integer next : vertices[node]) { if (!visited[next]) { buildPath(next); path.add(node); } } } public static void main(String[] args) throws IOException { final int N = nextInt(), M = nextInt(), K = nextInt(); path = new ArrayList<>(2 * N); vertices = new ArrayList[N + 1]; Arrays.setAll(vertices, index -> new ArrayList()); visited = new boolean[N + 1]; for (int i = 0; i < M; i++) { int n1 = nextInt(), n2 = nextInt(); vertices[n1].add(n2); vertices[n2].add(n1); } buildPath(1); int t = (int) Math.ceil(2. * N / K); int p = 0; for (int j = 0; j < K; j++) { while (p < path.size() && !visited[path.get(p)]) { p++; } int rest = Math.min(path.size() - p, t); if (rest == 0) { out.println("1 1"); } else { out.print(rest); while (rest > 0) { out.print(" "); int v = path.get(p++); out.print(v); visited[v] = false; rest--; } out.println(); } } out.close(); } static BufferedInputStream bis = new BufferedInputStream(System.in); static PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); static int nextInt() throws IOException { boolean negative = false; int c = bis.read(); int result = 0; while (c != '-' && (c < '0' || c > '9')) { c = bis.read(); } if (c == '-') { negative = true; c = bis.read(); } while (c >= '0' && c <= '9') { result *= 10; result += c - '0'; c = bis.read(); } return negative ? -result : result; } }
Java
["3 2 1\n2 1\n3 1", "5 4 2\n1 2\n1 3\n1 4\n1 5"]
1 second
["3 2 1 3", "3 2 1 3\n3 4 1 5"]
NoteIn the first sample case there is only one clone who may visit vertices in order (2, 1, 3), which fits the constraint of 6 vertices per clone.In the second sample case the two clones can visited vertices in order (2, 1, 3) and (4, 1, 5), which fits the constraint of 5 vertices per clone.
Java 8
standard input
[ "graphs", "constructive algorithms", "dfs and similar", "trees", "brute force" ]
d32d638e5f90f0bfb7b7cec8e541cf7d
The first line contains three integers n, m, and k (1 ≤ n ≤ 2·105, n - 1 ≤ m ≤ 2·105, 1 ≤ k ≤ n) — the number of vertices and edges in the lab, and the number of clones. Each of the next m lines contains two integers xi and yi (1 ≤ xi, yi ≤ n) — indices of vertices connected by the respective edge. The graph is allowed to have self-loops and multiple edges. The graph is guaranteed to be connected.
2,100
You should print k lines. i-th of these lines must start with an integer ci () — the number of vertices visited by i-th clone, followed by ci integers — indices of vertices visited by this clone in the order of visiting. You have to print each vertex every time it is visited, regardless if it was visited earlier or not. It is guaranteed that a valid answer exists.
standard output
PASSED
a28a923a995e9f3f6655799b3dc664a4
train_003.jsonl
1488705300
The evil Bumbershoot corporation produces clones for gruesome experiments in a vast underground lab. On one occasion, the corp cloned a boy Andryusha who was smarter than his comrades. Immediately Andryusha understood that something fishy was going on there. He rallied fellow clones to go on a feud against the evil corp, and they set out to find an exit from the lab. The corp had to reduce to destroy the lab complex.The lab can be pictured as a connected graph with n vertices and m edges. k clones of Andryusha start looking for an exit in some of the vertices. Each clone can traverse any edge once per second. Any number of clones are allowed to be at any vertex simultaneously. Each clone is allowed to stop looking at any time moment, but he must look at his starting vertex at least. The exit can be located at any vertex of the lab, hence each vertex must be visited by at least one clone.Each clone can visit at most vertices before the lab explodes.Your task is to choose starting vertices and searching routes for the clones. Each route can have at most vertices.
256 megabytes
import java.io.*; import java.util.*; public class C { FastScanner in; PrintWriter out; int[] p; int get(int x) { return p[x] == x ? x : (p[x] = get(p[x])); } void unite(int x, int y) { p[get(x)] = get(y); } ArrayList<Integer>[] g; ArrayList<Integer> result = new ArrayList<Integer>(); void go(int v, int p) { result.add(v); for (int i = 0; i < g[v].size(); i++) { int to = g[v].get(i); if (to == p) { continue; } go(to, v); result.add(v); } } void solve() { int n = in.nextInt(); int m = in.nextInt(); p = new int[n]; g = new ArrayList[n]; int k = in.nextInt(); for (int i = 0; i < n; i++) { p[i] = i; g[i] = new ArrayList<Integer>(); } for (int i = 0; i < m; i++) { int fr = in.nextInt() - 1; int to = in.nextInt() - 1; if (get(fr) == get(to)) { continue; } unite(fr, to); g[fr].add(to); g[to].add(fr); } go(0, 0); int canUse = 1 + (2 * n - 1) / k; int from = 0; for (int i = 0; i < k; i++) { int use = Math.min(canUse, result.size() - from); if (use == 0) { out.println("1 1"); continue; } out.print(use); for (int j = 0; j < use; j++) { out.print(" " + (1 + result.get(j + from))); } out.println(); from += use; } if (from != result.size()) { throw new AssertionError(); } } void run() { try { in = new FastScanner(new File("object.in")); out = new PrintWriter(new File("object.out")); solve(); out.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } } void runIO() { in = new FastScanner(System.in); out = new PrintWriter(System.out); solve(); out.close(); } class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(File f) { try { br = new BufferedReader(new FileReader(f)); } catch (FileNotFoundException e) { e.printStackTrace(); } } public FastScanner(InputStream f) { br = new BufferedReader(new InputStreamReader(f)); } String next() { while (st == null || !st.hasMoreTokens()) { String s = null; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } if (s == null) return null; st = new StringTokenizer(s); } return st.nextToken(); } boolean hasMoreTokens() { while (st == null || !st.hasMoreTokens()) { String s = null; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } if (s == null) return false; st = new StringTokenizer(s); } return true; } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } } public static void main(String[] args) { new C().runIO(); } }
Java
["3 2 1\n2 1\n3 1", "5 4 2\n1 2\n1 3\n1 4\n1 5"]
1 second
["3 2 1 3", "3 2 1 3\n3 4 1 5"]
NoteIn the first sample case there is only one clone who may visit vertices in order (2, 1, 3), which fits the constraint of 6 vertices per clone.In the second sample case the two clones can visited vertices in order (2, 1, 3) and (4, 1, 5), which fits the constraint of 5 vertices per clone.
Java 8
standard input
[ "graphs", "constructive algorithms", "dfs and similar", "trees", "brute force" ]
d32d638e5f90f0bfb7b7cec8e541cf7d
The first line contains three integers n, m, and k (1 ≤ n ≤ 2·105, n - 1 ≤ m ≤ 2·105, 1 ≤ k ≤ n) — the number of vertices and edges in the lab, and the number of clones. Each of the next m lines contains two integers xi and yi (1 ≤ xi, yi ≤ n) — indices of vertices connected by the respective edge. The graph is allowed to have self-loops and multiple edges. The graph is guaranteed to be connected.
2,100
You should print k lines. i-th of these lines must start with an integer ci () — the number of vertices visited by i-th clone, followed by ci integers — indices of vertices visited by this clone in the order of visiting. You have to print each vertex every time it is visited, regardless if it was visited earlier or not. It is guaranteed that a valid answer exists.
standard output
PASSED
526627b810b12e396247bbd7b2bce9c5
train_003.jsonl
1488705300
The evil Bumbershoot corporation produces clones for gruesome experiments in a vast underground lab. On one occasion, the corp cloned a boy Andryusha who was smarter than his comrades. Immediately Andryusha understood that something fishy was going on there. He rallied fellow clones to go on a feud against the evil corp, and they set out to find an exit from the lab. The corp had to reduce to destroy the lab complex.The lab can be pictured as a connected graph with n vertices and m edges. k clones of Andryusha start looking for an exit in some of the vertices. Each clone can traverse any edge once per second. Any number of clones are allowed to be at any vertex simultaneously. Each clone is allowed to stop looking at any time moment, but he must look at his starting vertex at least. The exit can be located at any vertex of the lab, hence each vertex must be visited by at least one clone.Each clone can visit at most vertices before the lab explodes.Your task is to choose starting vertices and searching routes for the clones. Each route can have at most vertices.
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.util.ArrayList; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author ilyakor */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { ArrayList<Integer>[] g; boolean[] u; ArrayList<Integer> path; public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.nextInt(); g = new ArrayList[n]; for (int i = 0; i < n; ++i) { g[i] = new ArrayList<>(); } int m = in.nextInt(); int k = in.nextInt(); for (int i = 0; i < m; ++i) { int x = in.nextInt() - 1; int y = in.nextInt() - 1; g[x].add(y); g[y].add(x); } u = new boolean[n]; path = new ArrayList<>(); dfs(0); Assert.assertTrue(path.size() <= 2 * n); int lim = (2 * n / k) + (2 * n % k == 0 ? 0 : 1); int[] cur = new int[lim]; int s = 0, cnt = 0; for (int x : path) { cur[s++] = x; if (s >= lim) { out.print(s); for (int i = 0; i < s; ++i) { out.print(" " + (cur[i] + 1)); } out.printLine(); s = 0; ++cnt; } } if (s > 0) { out.print(s); for (int i = 0; i < s; ++i) { out.print(" " + (cur[i] + 1)); } out.printLine(); s = 0; ++cnt; } while (cnt < k) { out.printLine("1 1"); ++cnt; } Assert.assertTrue(cnt == k); } void dfs(int x) { u[x] = true; path.add(x); for (int y : g[x]) { if (u[y]) { continue; } dfs(y); path.add(x); } } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) { writer.print(' '); } writer.print(objects[i]); } } public void printLine(Object... objects) { print(objects); writer.println(); } public void close() { writer.close(); } } static class Assert { public static void assertTrue(boolean flag) { // if (!flag) // while (true); if (!flag) { throw new AssertionError(); } } } static class InputReader { private InputStream stream; private byte[] buffer = new byte[10000]; private int cur; private int count; public InputReader(InputStream stream) { this.stream = stream; } public static boolean isSpace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public int read() { if (count == -1) { throw new InputMismatchException(); } try { if (cur >= count) { cur = 0; count = stream.read(buffer); if (count <= 0) { return -1; } } } catch (IOException e) { throw new InputMismatchException(); } return buffer[cur++]; } public int readSkipSpace() { int c; do { c = read(); } while (isSpace(c)); return c; } public int nextInt() { int sgn = 1; int c = readSkipSpace(); if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res = res * 10 + c - '0'; c = read(); } while (!isSpace(c)); res *= sgn; return res; } } }
Java
["3 2 1\n2 1\n3 1", "5 4 2\n1 2\n1 3\n1 4\n1 5"]
1 second
["3 2 1 3", "3 2 1 3\n3 4 1 5"]
NoteIn the first sample case there is only one clone who may visit vertices in order (2, 1, 3), which fits the constraint of 6 vertices per clone.In the second sample case the two clones can visited vertices in order (2, 1, 3) and (4, 1, 5), which fits the constraint of 5 vertices per clone.
Java 8
standard input
[ "graphs", "constructive algorithms", "dfs and similar", "trees", "brute force" ]
d32d638e5f90f0bfb7b7cec8e541cf7d
The first line contains three integers n, m, and k (1 ≤ n ≤ 2·105, n - 1 ≤ m ≤ 2·105, 1 ≤ k ≤ n) — the number of vertices and edges in the lab, and the number of clones. Each of the next m lines contains two integers xi and yi (1 ≤ xi, yi ≤ n) — indices of vertices connected by the respective edge. The graph is allowed to have self-loops and multiple edges. The graph is guaranteed to be connected.
2,100
You should print k lines. i-th of these lines must start with an integer ci () — the number of vertices visited by i-th clone, followed by ci integers — indices of vertices visited by this clone in the order of visiting. You have to print each vertex every time it is visited, regardless if it was visited earlier or not. It is guaranteed that a valid answer exists.
standard output
PASSED
36ed5fe13197f5fb68d50acc3f13e71c
train_003.jsonl
1488705300
The evil Bumbershoot corporation produces clones for gruesome experiments in a vast underground lab. On one occasion, the corp cloned a boy Andryusha who was smarter than his comrades. Immediately Andryusha understood that something fishy was going on there. He rallied fellow clones to go on a feud against the evil corp, and they set out to find an exit from the lab. The corp had to reduce to destroy the lab complex.The lab can be pictured as a connected graph with n vertices and m edges. k clones of Andryusha start looking for an exit in some of the vertices. Each clone can traverse any edge once per second. Any number of clones are allowed to be at any vertex simultaneously. Each clone is allowed to stop looking at any time moment, but he must look at his starting vertex at least. The exit can be located at any vertex of the lab, hence each vertex must be visited by at least one clone.Each clone can visit at most vertices before the lab explodes.Your task is to choose starting vertices and searching routes for the clones. Each route can have at most vertices.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.IOException; import java.util.ArrayList; import java.io.UncheckedIOException; import java.util.List; 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 << 29); 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); CUndergroundLab solver = new CUndergroundLab(); solver.solve(1, in, out); out.close(); } } static class CUndergroundLab { public void solve(int testNumber, FastInput in, FastOutput out) { int n = in.readInt(); Node[] nodes = new Node[n]; for (int i = 0; i < n; i++) { nodes[i] = new Node(); nodes[i].id = i; } int m = in.readInt(); int k = in.readInt(); DSU dsu = new DSU(n); for (int i = 0; i < m; i++) { Node a = nodes[in.readInt() - 1]; Node b = nodes[in.readInt() - 1]; if (dsu.find(a.id) == dsu.find(b.id)) { continue; } dsu.merge(a.id, b.id); a.adj.add(b); b.adj.add(a); } List<Node> trace = new ArrayList<>(2 * n); dfs(nodes[0], null, trace); List<Node>[] ans = new List[k]; int threshold = DigitUtils.ceilDiv(2 * n, k); for (int i = 0; i < k; i++) { ans[i] = new ArrayList(threshold); } int cur = 0; for (Node node : trace) { while (ans[cur].size() >= threshold) { cur++; } ans[cur].add(node); } for (int i = 0; i < k; i++) { if (ans[i].size() == 0) { ans[i].add(nodes[0]); } out.append(ans[i].size()).append(' '); for (Node node : ans[i]) { out.append(node.id + 1).append(' '); } out.println(); } } public void dfs(Node root, Node p, List<Node> trace) { trace.add(root); for (Node node : root.adj) { if (node == p) { continue; } dfs(node, root, trace); trace.add(root); } } } static class Node { List<Node> adj = new ArrayList<>(); int id; } 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 DigitUtils { private DigitUtils() { } public static int floorDiv(int a, int b) { return a < 0 ? -ceilDiv(-a, b) : a / b; } public static int ceilDiv(int a, int b) { if (a < 0) { return -floorDiv(-a, b); } int c = a / b; if (c * b < a) { return c + 1; } return c; } } static class FastOutput implements AutoCloseable, Closeable, Appendable { private StringBuilder cache = new StringBuilder(10 << 20); private final Writer os; public FastOutput append(CharSequence csq) { cache.append(csq); return this; } public FastOutput append(CharSequence csq, int start, int end) { cache.append(csq, start, end); return this; } public FastOutput(Writer os) { this.os = os; } public FastOutput(OutputStream os) { this(new OutputStreamWriter(os)); } public FastOutput append(char c) { cache.append(c); return this; } public FastOutput append(int c) { cache.append(c); return this; } public FastOutput println() { cache.append(System.lineSeparator()); 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 DSU { protected int[] p; protected int[] rank; public DSU(int n) { p = new int[n]; rank = new int[n]; reset(); } public final void reset() { for (int i = 0; i < p.length; i++) { p[i] = i; rank[i] = 0; } } public final int find(int a) { if (p[a] == p[p[a]]) { return p[a]; } return p[a] = find(p[a]); } public final void merge(int a, int b) { a = find(a); b = find(b); if (a == b) { return; } if (rank[a] == rank[b]) { rank[a]++; } if (rank[a] < rank[b]) { int tmp = a; a = b; b = tmp; } p[b] = a; } } }
Java
["3 2 1\n2 1\n3 1", "5 4 2\n1 2\n1 3\n1 4\n1 5"]
1 second
["3 2 1 3", "3 2 1 3\n3 4 1 5"]
NoteIn the first sample case there is only one clone who may visit vertices in order (2, 1, 3), which fits the constraint of 6 vertices per clone.In the second sample case the two clones can visited vertices in order (2, 1, 3) and (4, 1, 5), which fits the constraint of 5 vertices per clone.
Java 8
standard input
[ "graphs", "constructive algorithms", "dfs and similar", "trees", "brute force" ]
d32d638e5f90f0bfb7b7cec8e541cf7d
The first line contains three integers n, m, and k (1 ≤ n ≤ 2·105, n - 1 ≤ m ≤ 2·105, 1 ≤ k ≤ n) — the number of vertices and edges in the lab, and the number of clones. Each of the next m lines contains two integers xi and yi (1 ≤ xi, yi ≤ n) — indices of vertices connected by the respective edge. The graph is allowed to have self-loops and multiple edges. The graph is guaranteed to be connected.
2,100
You should print k lines. i-th of these lines must start with an integer ci () — the number of vertices visited by i-th clone, followed by ci integers — indices of vertices visited by this clone in the order of visiting. You have to print each vertex every time it is visited, regardless if it was visited earlier or not. It is guaranteed that a valid answer exists.
standard output
PASSED
3fda2cbb8299a270c44ee9725c4e4156
train_003.jsonl
1488705300
The evil Bumbershoot corporation produces clones for gruesome experiments in a vast underground lab. On one occasion, the corp cloned a boy Andryusha who was smarter than his comrades. Immediately Andryusha understood that something fishy was going on there. He rallied fellow clones to go on a feud against the evil corp, and they set out to find an exit from the lab. The corp had to reduce to destroy the lab complex.The lab can be pictured as a connected graph with n vertices and m edges. k clones of Andryusha start looking for an exit in some of the vertices. Each clone can traverse any edge once per second. Any number of clones are allowed to be at any vertex simultaneously. Each clone is allowed to stop looking at any time moment, but he must look at his starting vertex at least. The exit can be located at any vertex of the lab, hence each vertex must be visited by at least one clone.Each clone can visit at most vertices before the lab explodes.Your task is to choose starting vertices and searching routes for the clones. Each route can have at most vertices.
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.util.Iterator; import java.io.BufferedWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.NoSuchElementException; 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); OutputWriter out = new OutputWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { int n; int m; int k; BidirectionalGraph graph; IntArrayList order; boolean[] used; private void dfs(int v, int p) { used[v] = true; order.add(v); for (int i = graph.firstOutbound(v); i != -1; i = graph.nextOutbound(i)) { int to = graph.destination(i); if (to == p || used[to]) { continue; } dfs(to, v); order.add(v); } } public void solve(int testNumber, InputReader in, OutputWriter out) { n = in.readInt(); m = in.readInt(); k = in.readInt(); graph = new BidirectionalGraph(n, m); for (int iter = 0; iter < m; iter++) { int a = in.readInt() - 1; int b = in.readInt() - 1; graph.addSimpleEdge(a, b); } order = new IntArrayList(2 * n); used = new boolean[n]; dfs(0, -1); int pos = 0; for (int iter = 0; iter < k; iter++) { int size = (2 * n + k - 1) / k; IntArrayList arr = new IntArrayList(); for (int i = 0; i < size && pos < order.size(); i++) { arr.add(order.get(pos++)); } if (arr.isEmpty()) { arr.add(0); } out.print(arr.size()); for (Integer integer : arr) { out.print(" " + (integer + 1)); } out.printLine(); } } } static interface IntStream extends Iterable<Integer>, Comparable<IntStream> { public IntIterator intIterator(); default public Iterator<Integer> iterator() { return new Iterator<Integer>() { private IntIterator it = intIterator(); public boolean hasNext() { return it.isValid(); } public Integer next() { int result = it.value(); it.advance(); return result; } }; } default public int compareTo(IntStream c) { IntIterator it = intIterator(); IntIterator jt = c.intIterator(); while (it.isValid() && jt.isValid()) { int i = it.value(); int j = jt.value(); if (i < j) { return -1; } else if (i > j) { return 1; } it.advance(); jt.advance(); } if (it.isValid()) { return 1; } if (jt.isValid()) { return -1; } return 0; } } static interface IntReversableCollection extends IntCollection { } static interface IntList extends IntReversableCollection { public abstract int get(int index); public abstract void addAt(int index, int value); public abstract void removeAt(int index); default public IntIterator intIterator() { return new IntIterator() { private int at; private boolean removed; public int value() { if (removed) { throw new IllegalStateException(); } return get(at); } public boolean advance() { at++; removed = false; return isValid(); } public boolean isValid() { return !removed && at < size(); } public void remove() { removeAt(at); at--; removed = true; } }; } default public void add(int value) { addAt(size(), value); } } static class Graph { public static final int REMOVED_BIT = 0; protected int vertexCount; protected int edgeCount; private int[] firstOutbound; private int[] firstInbound; private Edge[] edges; private int[] nextInbound; private int[] nextOutbound; private int[] from; private int[] to; private long[] weight; public long[] capacity; private int[] reverseEdge; private int[] flags; public Graph(int vertexCount) { this(vertexCount, vertexCount); } public Graph(int vertexCount, int edgeCapacity) { this.vertexCount = vertexCount; firstOutbound = new int[vertexCount]; Arrays.fill(firstOutbound, -1); from = new int[edgeCapacity]; to = new int[edgeCapacity]; nextOutbound = new int[edgeCapacity]; flags = new int[edgeCapacity]; } public int addEdge(int fromID, int toID, long weight, long capacity, int reverseEdge) { ensureEdgeCapacity(edgeCount + 1); if (firstOutbound[fromID] != -1) { nextOutbound[edgeCount] = firstOutbound[fromID]; } else { nextOutbound[edgeCount] = -1; } firstOutbound[fromID] = edgeCount; if (firstInbound != null) { if (firstInbound[toID] != -1) { nextInbound[edgeCount] = firstInbound[toID]; } else { nextInbound[edgeCount] = -1; } firstInbound[toID] = edgeCount; } this.from[edgeCount] = fromID; this.to[edgeCount] = toID; if (capacity != 0) { if (this.capacity == null) { this.capacity = new long[from.length]; } this.capacity[edgeCount] = capacity; } if (weight != 0) { if (this.weight == null) { this.weight = new long[from.length]; } this.weight[edgeCount] = weight; } if (reverseEdge != -1) { if (this.reverseEdge == null) { this.reverseEdge = new int[from.length]; Arrays.fill(this.reverseEdge, 0, edgeCount, -1); } this.reverseEdge[edgeCount] = reverseEdge; } if (edges != null) { edges[edgeCount] = createEdge(edgeCount); } return edgeCount++; } protected final GraphEdge createEdge(int id) { return new GraphEdge(id); } public final int addFlowWeightedEdge(int from, int to, long weight, long capacity) { if (capacity == 0) { return addEdge(from, to, weight, 0, -1); } else { int lastEdgeCount = edgeCount; addEdge(to, from, -weight, 0, lastEdgeCount + entriesPerEdge()); return addEdge(from, to, weight, capacity, lastEdgeCount); } } protected int entriesPerEdge() { return 1; } public final int addWeightedEdge(int from, int to, long weight) { return addFlowWeightedEdge(from, to, weight, 0); } public final int addSimpleEdge(int from, int to) { return addWeightedEdge(from, to, 0); } protected final int edgeCapacity() { return from.length; } public final int firstOutbound(int vertex) { int id = firstOutbound[vertex]; while (id != -1 && isRemoved(id)) { id = nextOutbound[id]; } return id; } public final int nextOutbound(int id) { id = nextOutbound[id]; while (id != -1 && isRemoved(id)) { id = nextOutbound[id]; } return id; } public final int destination(int id) { return to[id]; } public final boolean flag(int id, int bit) { return (flags[id] >> bit & 1) != 0; } public final boolean isRemoved(int id) { return flag(id, REMOVED_BIT); } protected void ensureEdgeCapacity(int size) { if (from.length < size) { int newSize = Math.max(size, 2 * from.length); if (edges != null) { edges = resize(edges, newSize); } from = resize(from, newSize); to = resize(to, newSize); nextOutbound = resize(nextOutbound, newSize); if (nextInbound != null) { nextInbound = resize(nextInbound, newSize); } if (weight != null) { weight = resize(weight, newSize); } if (capacity != null) { capacity = resize(capacity, newSize); } if (reverseEdge != null) { reverseEdge = resize(reverseEdge, newSize); } flags = resize(flags, newSize); } } protected final int[] resize(int[] array, int size) { int[] newArray = new int[size]; System.arraycopy(array, 0, newArray, 0, array.length); return newArray; } private long[] resize(long[] array, int size) { long[] newArray = new long[size]; System.arraycopy(array, 0, newArray, 0, array.length); return newArray; } private Edge[] resize(Edge[] array, int size) { Edge[] newArray = new Edge[size]; System.arraycopy(array, 0, newArray, 0, array.length); return newArray; } protected class GraphEdge implements Edge { protected int id; protected GraphEdge(int id) { this.id = id; } } } static class BidirectionalGraph extends Graph { public int[] transposedEdge; public BidirectionalGraph(int vertexCount) { this(vertexCount, vertexCount); } public BidirectionalGraph(int vertexCount, int edgeCapacity) { super(vertexCount, 2 * edgeCapacity); transposedEdge = new int[2 * edgeCapacity]; } public int addEdge(int fromID, int toID, long weight, long capacity, int reverseEdge) { int lastEdgeCount = edgeCount; super.addEdge(fromID, toID, weight, capacity, reverseEdge); super.addEdge(toID, fromID, weight, capacity, reverseEdge == -1 ? -1 : reverseEdge + 1); this.transposedEdge[lastEdgeCount] = lastEdgeCount + 1; this.transposedEdge[lastEdgeCount + 1] = lastEdgeCount; return lastEdgeCount; } protected int entriesPerEdge() { return 2; } protected void ensureEdgeCapacity(int size) { if (size > edgeCapacity()) { super.ensureEdgeCapacity(size); transposedEdge = resize(transposedEdge, edgeCapacity()); } } } static interface IntCollection extends IntStream { public int size(); default public boolean isEmpty() { return size() == 0; } default public void add(int value) { throw new UnsupportedOperationException(); } default public IntCollection addAll(IntStream values) { for (IntIterator it = values.intIterator(); it.isValid(); it.advance()) { add(it.value()); } return this; } } 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() { writer.println(); } public void close() { writer.close(); } public void print(int i) { writer.print(i); } } static interface IntIterator { public int value() throws NoSuchElementException; public boolean advance(); public boolean isValid(); } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } static abstract class IntAbstractStream implements IntStream { public String toString() { StringBuilder builder = new StringBuilder(); boolean first = true; for (IntIterator it = intIterator(); it.isValid(); it.advance()) { if (first) { first = false; } else { builder.append(' '); } builder.append(it.value()); } return builder.toString(); } public boolean equals(Object o) { if (!(o instanceof IntStream)) { return false; } IntStream c = (IntStream) o; IntIterator it = intIterator(); IntIterator jt = c.intIterator(); while (it.isValid() && jt.isValid()) { if (it.value() != jt.value()) { return false; } it.advance(); jt.advance(); } return !it.isValid() && !jt.isValid(); } public int hashCode() { int result = 0; for (IntIterator it = intIterator(); it.isValid(); it.advance()) { result *= 31; result += it.value(); } return result; } } static class IntArrayList extends IntAbstractStream implements IntList { private int size; private int[] data; public IntArrayList() { this(3); } public IntArrayList(int capacity) { data = new int[capacity]; } public IntArrayList(IntCollection c) { this(c.size()); addAll(c); } public IntArrayList(IntStream c) { this(); if (c instanceof IntCollection) { ensureCapacity(((IntCollection) c).size()); } addAll(c); } public IntArrayList(IntArrayList c) { size = c.size(); data = c.data.clone(); } public IntArrayList(int[] arr) { size = arr.length; data = arr.clone(); } public int size() { return size; } public int get(int at) { if (at >= size) { throw new IndexOutOfBoundsException("at = " + at + ", size = " + size); } return data[at]; } private void ensureCapacity(int capacity) { if (data.length >= capacity) { return; } capacity = Math.max(2 * data.length, capacity); data = Arrays.copyOf(data, capacity); } public void addAt(int index, int value) { ensureCapacity(size + 1); if (index > size || index < 0) { throw new IndexOutOfBoundsException("at = " + index + ", size = " + size); } if (index != size) { System.arraycopy(data, index, data, index + 1, size - index); } data[index] = value; size++; } public void removeAt(int index) { if (index >= size || index < 0) { throw new IndexOutOfBoundsException("at = " + index + ", size = " + size); } if (index != size - 1) { System.arraycopy(data, index + 1, data, index, size - index - 1); } size--; } } static interface Edge { } }
Java
["3 2 1\n2 1\n3 1", "5 4 2\n1 2\n1 3\n1 4\n1 5"]
1 second
["3 2 1 3", "3 2 1 3\n3 4 1 5"]
NoteIn the first sample case there is only one clone who may visit vertices in order (2, 1, 3), which fits the constraint of 6 vertices per clone.In the second sample case the two clones can visited vertices in order (2, 1, 3) and (4, 1, 5), which fits the constraint of 5 vertices per clone.
Java 8
standard input
[ "graphs", "constructive algorithms", "dfs and similar", "trees", "brute force" ]
d32d638e5f90f0bfb7b7cec8e541cf7d
The first line contains three integers n, m, and k (1 ≤ n ≤ 2·105, n - 1 ≤ m ≤ 2·105, 1 ≤ k ≤ n) — the number of vertices and edges in the lab, and the number of clones. Each of the next m lines contains two integers xi and yi (1 ≤ xi, yi ≤ n) — indices of vertices connected by the respective edge. The graph is allowed to have self-loops and multiple edges. The graph is guaranteed to be connected.
2,100
You should print k lines. i-th of these lines must start with an integer ci () — the number of vertices visited by i-th clone, followed by ci integers — indices of vertices visited by this clone in the order of visiting. You have to print each vertex every time it is visited, regardless if it was visited earlier or not. It is guaranteed that a valid answer exists.
standard output
PASSED
8089e6796f3e28638b93847a29316203
train_003.jsonl
1488705300
The evil Bumbershoot corporation produces clones for gruesome experiments in a vast underground lab. On one occasion, the corp cloned a boy Andryusha who was smarter than his comrades. Immediately Andryusha understood that something fishy was going on there. He rallied fellow clones to go on a feud against the evil corp, and they set out to find an exit from the lab. The corp had to reduce to destroy the lab complex.The lab can be pictured as a connected graph with n vertices and m edges. k clones of Andryusha start looking for an exit in some of the vertices. Each clone can traverse any edge once per second. Any number of clones are allowed to be at any vertex simultaneously. Each clone is allowed to stop looking at any time moment, but he must look at his starting vertex at least. The exit can be located at any vertex of the lab, hence each vertex must be visited by at least one clone.Each clone can visit at most vertices before the lab explodes.Your task is to choose starting vertices and searching routes for the clones. Each route can have at most vertices.
256 megabytes
import java.io.*; import java.util.*; import java.math.*; public class C { Vector<Vector<Integer>> path; public void solve() throws IOException { InputReader in = new InputReader(System.in); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out)); path = new Vector<>(); int n = in.readInt(); int m = in.readInt(); int k = in.readInt(); Vector<Integer> graph[] = new Vector[n]; for (int i = 0; i < n; i++) { graph[i] = new Vector<>(); } for (int i = 0; i < m; i++) { int u = in.readInt() - 1; int v = in.readInt() - 1; graph[u].add(v); graph[v].add(u); } boolean vis[] = new boolean[n]; int indexOfPath = -1; for (int i = 0; i < k; i++) { indexOfPath++; path.add(new Vector<>()); while(i < n && vis[i]) { i++; } if (i < n) { dfs2(graph, i, vis, indexOfPath, -1); } } Vector<Integer> res = new Vector<>(); res = path.get(0); // for(int ver: res) { // out.write(Integer.toString(ver + 1)+" "); // } // out.newLine(); int oneseg = (int)Math.ceil(2 * (double)n / k); int pointer = 0; for (int i = 0; i < k; i++) { int counter = 0; for (int j = pointer; j < Math.min(pointer + oneseg, res.size()); j++) { counter++; } if (counter == 0) { out.write("1 1"); out.newLine(); continue; } out.write(Integer.toString(counter) + " "); for (int j = pointer; j < Math.min(pointer + oneseg, res.size()); j++) { out.write(Integer.toString(res.get(j) + 1)+" "); } out.newLine(); pointer += counter; } out.close(); } private void dfs2(Vector<Integer> g[], int ver, boolean v[], int indexPath, int parent) { path.get(indexPath).add(ver); v[ver] = true; for (int ch: g[ver]) { if (!v[ch]) { dfs2(g, ch, v, indexPath, ver); } } if (parent != -1) { path.get(indexPath).add(parent); } } public static void main(String args[]) { try { C c = new C(); c.solve(); } catch (Exception e) { e.printStackTrace(); } } } class InputReader { private boolean finished = false; private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int peek() { if (numChars == -1) return -1; if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { return -1; } if (numChars <= 0) return -1; } return buf[curChar]; } public int readInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long readLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String readString() { int length = readInt(); if (length < 0) return null; byte[] bytes = new byte[length]; for (int i = 0; i < length; i++) bytes[i] = (byte) read(); try { return new String(bytes, "UTF-8"); } catch (UnsupportedEncodingException e) { return new String(bytes); } } public static boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private String readLine0() { StringBuffer buf = new StringBuffer(); int c = read(); while (c != '\n' && c != -1) { if (c != '\r') buf.appendCodePoint(c); c = read(); } return buf.toString(); } public String readLine() { String s = readLine0(); while (s.trim().length() == 0) s = readLine0(); return s; } public String readLine(boolean ignoreEmptyLines) { if (ignoreEmptyLines) return readLine(); else return readLine0(); } public BigInteger readBigInteger() { try { return new BigInteger(readString()); } catch (NumberFormatException e) { throw new InputMismatchException(); } } public char readCharacter() { int c = read(); while (isSpaceChar(c)) c = read(); return (char) c; } 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 boolean isExhausted() { int value; while (isSpaceChar(value = peek()) && value != -1) read(); return value == -1; } public String next() { return readString(); } public boolean readBoolean() { return readInt() == 1; } }
Java
["3 2 1\n2 1\n3 1", "5 4 2\n1 2\n1 3\n1 4\n1 5"]
1 second
["3 2 1 3", "3 2 1 3\n3 4 1 5"]
NoteIn the first sample case there is only one clone who may visit vertices in order (2, 1, 3), which fits the constraint of 6 vertices per clone.In the second sample case the two clones can visited vertices in order (2, 1, 3) and (4, 1, 5), which fits the constraint of 5 vertices per clone.
Java 8
standard input
[ "graphs", "constructive algorithms", "dfs and similar", "trees", "brute force" ]
d32d638e5f90f0bfb7b7cec8e541cf7d
The first line contains three integers n, m, and k (1 ≤ n ≤ 2·105, n - 1 ≤ m ≤ 2·105, 1 ≤ k ≤ n) — the number of vertices and edges in the lab, and the number of clones. Each of the next m lines contains two integers xi and yi (1 ≤ xi, yi ≤ n) — indices of vertices connected by the respective edge. The graph is allowed to have self-loops and multiple edges. The graph is guaranteed to be connected.
2,100
You should print k lines. i-th of these lines must start with an integer ci () — the number of vertices visited by i-th clone, followed by ci integers — indices of vertices visited by this clone in the order of visiting. You have to print each vertex every time it is visited, regardless if it was visited earlier or not. It is guaranteed that a valid answer exists.
standard output
PASSED
8405cf4b362ea2583f61d7cdba3eaa7f
train_003.jsonl
1488705300
The evil Bumbershoot corporation produces clones for gruesome experiments in a vast underground lab. On one occasion, the corp cloned a boy Andryusha who was smarter than his comrades. Immediately Andryusha understood that something fishy was going on there. He rallied fellow clones to go on a feud against the evil corp, and they set out to find an exit from the lab. The corp had to reduce to destroy the lab complex.The lab can be pictured as a connected graph with n vertices and m edges. k clones of Andryusha start looking for an exit in some of the vertices. Each clone can traverse any edge once per second. Any number of clones are allowed to be at any vertex simultaneously. Each clone is allowed to stop looking at any time moment, but he must look at his starting vertex at least. The exit can be located at any vertex of the lab, hence each vertex must be visited by at least one clone.Each clone can visit at most vertices before the lab explodes.Your task is to choose starting vertices and searching routes for the clones. Each route can have at most vertices.
256 megabytes
import java.awt.Point; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Set; import java.util.StringTokenizer; import java.util.TreeSet; import com.sun.org.apache.bcel.internal.generic.ALOAD; public class C { static StringTokenizer st; static BufferedReader br; static PrintWriter pw; static ArrayList<Integer>[]ages; static int[]order; static boolean[]used; static int size; public static void main(String[] args) throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); int n = nextInt(); ages = new ArrayList[n+1]; for (int i = 1; i <= n; i++) { ages[i] = new ArrayList<>(); } int m = nextInt(); int k = nextInt(); for (int i = 1; i <= m; i++) { int x = nextInt(); int y = nextInt(); if (x==y) continue; // long hash1 = (long)(n+1) * x + y; // long hash2 = (long)(n+1) * y + x; // if (set.contains(hash1) || set.contains(hash2)) // continue; ages[x].add(y); ages[y].add(x); // set.add(hash1); // set.add(hash2); } used = new boolean[n+1]; order = new int[3*n+1]; dfs(1, 0); int eachLen = 2 * n / k; if (2*n % k > 0) eachLen++; int pos = 0; for (int i = 1; i <= k; i++) { int cnt = Math.min(eachLen, size-pos); if (cnt==0) { pw.println(1+" "+1); continue; } pw.print(cnt+" "); for (int j = 0; j < cnt; j++) { pw.print(order[pos++]+" "); } pw.println(); } pw.close(); } private static void dfs(int v, int p) { used[v] = true; order[size++] = v; for (int to : ages[v]) { if (used[to]) continue; dfs(to, v); order[size++] = v; } } private static int nextInt() throws IOException { return Integer.parseInt(next()); } private static long nextLong() throws IOException { return Long.parseLong(next()); } private static double nextDouble() throws IOException { return Double.parseDouble(next()); } private static String next() throws IOException { while (st==null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } }
Java
["3 2 1\n2 1\n3 1", "5 4 2\n1 2\n1 3\n1 4\n1 5"]
1 second
["3 2 1 3", "3 2 1 3\n3 4 1 5"]
NoteIn the first sample case there is only one clone who may visit vertices in order (2, 1, 3), which fits the constraint of 6 vertices per clone.In the second sample case the two clones can visited vertices in order (2, 1, 3) and (4, 1, 5), which fits the constraint of 5 vertices per clone.
Java 8
standard input
[ "graphs", "constructive algorithms", "dfs and similar", "trees", "brute force" ]
d32d638e5f90f0bfb7b7cec8e541cf7d
The first line contains three integers n, m, and k (1 ≤ n ≤ 2·105, n - 1 ≤ m ≤ 2·105, 1 ≤ k ≤ n) — the number of vertices and edges in the lab, and the number of clones. Each of the next m lines contains two integers xi and yi (1 ≤ xi, yi ≤ n) — indices of vertices connected by the respective edge. The graph is allowed to have self-loops and multiple edges. The graph is guaranteed to be connected.
2,100
You should print k lines. i-th of these lines must start with an integer ci () — the number of vertices visited by i-th clone, followed by ci integers — indices of vertices visited by this clone in the order of visiting. You have to print each vertex every time it is visited, regardless if it was visited earlier or not. It is guaranteed that a valid answer exists.
standard output
PASSED
a95020ebe2cdd6b70a431c241363e6fa
train_003.jsonl
1488705300
The evil Bumbershoot corporation produces clones for gruesome experiments in a vast underground lab. On one occasion, the corp cloned a boy Andryusha who was smarter than his comrades. Immediately Andryusha understood that something fishy was going on there. He rallied fellow clones to go on a feud against the evil corp, and they set out to find an exit from the lab. The corp had to reduce to destroy the lab complex.The lab can be pictured as a connected graph with n vertices and m edges. k clones of Andryusha start looking for an exit in some of the vertices. Each clone can traverse any edge once per second. Any number of clones are allowed to be at any vertex simultaneously. Each clone is allowed to stop looking at any time moment, but he must look at his starting vertex at least. The exit can be located at any vertex of the lab, hence each vertex must be visited by at least one clone.Each clone can visit at most vertices before the lab explodes.Your task is to choose starting vertices and searching routes for the clones. Each route can have at most vertices.
256 megabytes
import java.io.*; import java.util.*; public class pC { ArrayList<Integer>[] nei; boolean[] mark; ArrayList<Integer> path = new ArrayList<>(); void run() { int n = in.nextInt(); int m = in.nextInt(); int w = in.nextInt(); init(n); for (int i = 0; i < n; i++) { nei[i] = new ArrayList<>(); } for (int i = 0; i < m; i++) { int a = in.nextInt() - 1; int b = in.nextInt() - 1; nei[a].add(b); nei[b].add(a); } mark = new boolean[n]; dfs(0); for (int i = 0, j = 0; i < w; i++) { int k = (int) (path.size() * (i + 1L) / w); out.print(k - j); for (; j < k; j++) { out.print(" " + (path.get(j) + 1)); } out.println(); } } void dfs(int v) { path.add(v); mark[v] = true; for (int u : nei[v]) { if (mark[u]) { continue; } dfs(u); path.add(v); } } @SuppressWarnings("unchecked") void init(int n) { nei = new ArrayList[n]; } static MyScanner in; static PrintWriter out; public static void main(String[] args) throws IOException { boolean stdStreams = true; String fileName = pC.class.getSimpleName().replaceFirst("_.*", "").toLowerCase(); String inputFileName = fileName + ".in"; String outputFileName = fileName + ".out"; Locale.setDefault(Locale.US); BufferedReader br; if (stdStreams) { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } else { br = new BufferedReader(new FileReader(inputFileName)); out = new PrintWriter(outputFileName); } in = new MyScanner(br); int tests = 1;//in.nextInt(); for (int test = 0; test < tests; test++) { new pC().run(); } br.close(); out.close(); } static class MyScanner { BufferedReader br; StringTokenizer st; MyScanner(BufferedReader br) { this.br = br; } void findToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } } String next() { findToken(); return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } } }
Java
["3 2 1\n2 1\n3 1", "5 4 2\n1 2\n1 3\n1 4\n1 5"]
1 second
["3 2 1 3", "3 2 1 3\n3 4 1 5"]
NoteIn the first sample case there is only one clone who may visit vertices in order (2, 1, 3), which fits the constraint of 6 vertices per clone.In the second sample case the two clones can visited vertices in order (2, 1, 3) and (4, 1, 5), which fits the constraint of 5 vertices per clone.
Java 8
standard input
[ "graphs", "constructive algorithms", "dfs and similar", "trees", "brute force" ]
d32d638e5f90f0bfb7b7cec8e541cf7d
The first line contains three integers n, m, and k (1 ≤ n ≤ 2·105, n - 1 ≤ m ≤ 2·105, 1 ≤ k ≤ n) — the number of vertices and edges in the lab, and the number of clones. Each of the next m lines contains two integers xi and yi (1 ≤ xi, yi ≤ n) — indices of vertices connected by the respective edge. The graph is allowed to have self-loops and multiple edges. The graph is guaranteed to be connected.
2,100
You should print k lines. i-th of these lines must start with an integer ci () — the number of vertices visited by i-th clone, followed by ci integers — indices of vertices visited by this clone in the order of visiting. You have to print each vertex every time it is visited, regardless if it was visited earlier or not. It is guaranteed that a valid answer exists.
standard output
PASSED
813299f205c2495dea62bce75372ec5d
train_003.jsonl
1488705300
The evil Bumbershoot corporation produces clones for gruesome experiments in a vast underground lab. On one occasion, the corp cloned a boy Andryusha who was smarter than his comrades. Immediately Andryusha understood that something fishy was going on there. He rallied fellow clones to go on a feud against the evil corp, and they set out to find an exit from the lab. The corp had to reduce to destroy the lab complex.The lab can be pictured as a connected graph with n vertices and m edges. k clones of Andryusha start looking for an exit in some of the vertices. Each clone can traverse any edge once per second. Any number of clones are allowed to be at any vertex simultaneously. Each clone is allowed to stop looking at any time moment, but he must look at his starting vertex at least. The exit can be located at any vertex of the lab, hence each vertex must be visited by at least one clone.Each clone can visit at most vertices before the lab explodes.Your task is to choose starting vertices and searching routes for the clones. Each route can have at most vertices.
256 megabytes
import java.io.*; import java.util.*; public class pC { ArrayList<Integer>[] nei; boolean[] mark; ArrayList<Integer> traverse; void run() { int n = in.nextInt(); int m = in.nextInt(); int w = in.nextInt(); nei = new ArrayList[n]; for (int i = 0; i < n; i++) { nei[i] = new ArrayList<>(); } for (int i = 0; i < m; i++) { int a = in.nextInt() - 1; int b = in.nextInt() - 1; nei[a].add(b); nei[b].add(a); } mark = new boolean[n]; traverse = new ArrayList<>(); dfs(0); for (int i = 0, j = 0; i < w; i++) { int k = (int) (traverse.size() * (i + 1L) / w); out.print(k - j); for (; j < k; j++) { out.print(" "); out.print(traverse.get(j) + 1); } out.println(); } } private void dfs(int v) { traverse.add(v); mark[v] = true; for (int u : nei[v]) { if (mark[u]) { continue; } dfs(u); traverse.add(v); } } static MyScanner in; static PrintWriter out; public static void main(String[] args) throws IOException { boolean stdStreams = true; String fileName = pC.class.getSimpleName().replaceFirst("_.*", "").toLowerCase(); String inputFileName = fileName + ".in"; String outputFileName = fileName + ".out"; Locale.setDefault(Locale.US); BufferedReader br; if (stdStreams) { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } else { br = new BufferedReader(new FileReader(inputFileName)); out = new PrintWriter(outputFileName); } in = new MyScanner(br); int tests = 1;//in.nextInt(); for (int test = 0; test < tests; test++) { new pC().run(); } br.close(); out.close(); } static class MyScanner { BufferedReader br; StringTokenizer st; MyScanner(BufferedReader br) { this.br = br; } void findToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } } String next() { findToken(); return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } } }
Java
["3 2 1\n2 1\n3 1", "5 4 2\n1 2\n1 3\n1 4\n1 5"]
1 second
["3 2 1 3", "3 2 1 3\n3 4 1 5"]
NoteIn the first sample case there is only one clone who may visit vertices in order (2, 1, 3), which fits the constraint of 6 vertices per clone.In the second sample case the two clones can visited vertices in order (2, 1, 3) and (4, 1, 5), which fits the constraint of 5 vertices per clone.
Java 8
standard input
[ "graphs", "constructive algorithms", "dfs and similar", "trees", "brute force" ]
d32d638e5f90f0bfb7b7cec8e541cf7d
The first line contains three integers n, m, and k (1 ≤ n ≤ 2·105, n - 1 ≤ m ≤ 2·105, 1 ≤ k ≤ n) — the number of vertices and edges in the lab, and the number of clones. Each of the next m lines contains two integers xi and yi (1 ≤ xi, yi ≤ n) — indices of vertices connected by the respective edge. The graph is allowed to have self-loops and multiple edges. The graph is guaranteed to be connected.
2,100
You should print k lines. i-th of these lines must start with an integer ci () — the number of vertices visited by i-th clone, followed by ci integers — indices of vertices visited by this clone in the order of visiting. You have to print each vertex every time it is visited, regardless if it was visited earlier or not. It is guaranteed that a valid answer exists.
standard output
PASSED
6c181db78c27ab4852b0a2b0487e9fc2
train_003.jsonl
1488705300
The evil Bumbershoot corporation produces clones for gruesome experiments in a vast underground lab. On one occasion, the corp cloned a boy Andryusha who was smarter than his comrades. Immediately Andryusha understood that something fishy was going on there. He rallied fellow clones to go on a feud against the evil corp, and they set out to find an exit from the lab. The corp had to reduce to destroy the lab complex.The lab can be pictured as a connected graph with n vertices and m edges. k clones of Andryusha start looking for an exit in some of the vertices. Each clone can traverse any edge once per second. Any number of clones are allowed to be at any vertex simultaneously. Each clone is allowed to stop looking at any time moment, but he must look at his starting vertex at least. The exit can be located at any vertex of the lab, hence each vertex must be visited by at least one clone.Each clone can visit at most vertices before the lab explodes.Your task is to choose starting vertices and searching routes for the clones. Each route can have at most vertices.
256 megabytes
import java.io.*; import java.util.*; public class UndergroundLab { public static void main(String[] args) { Scanner sc = new Scanner(); int n = sc.nextInt(); int m = sc.nextInt(); int k = sc.nextInt(); adj = new List[n]; for (int i = 0; i < n; i++) { adj[i] = new ArrayList<>(); } for (int i = 0; i < m; i++) { int u = sc.nextInt() - 1; int v = sc.nextInt() - 1; adj[u].add(v); adj[v].add(u); } marked = new boolean[n]; dfs(0); StringBuilder sb = new StringBuilder(); int maxSize = (2 * n + k - 1) / k; int size = maxSize; int count = 0; int goal = 0; for (int i = 0; i < tour.size(); i++) { if (i == goal) { size = Math.min(maxSize, tour.size() - i); sb.append(size); goal += size; } sb.append(' ').append(tour.get(i) + 1); if (i + 1 == goal) { sb.append('\n'); count++; } } while (count < k) { sb.append("1 1\n"); count++; } System.out.print(sb); } static boolean dfs(int u) { if (!marked[u]) { marked[u] = true; tour.add(u); for (int v : adj[u]) { if (dfs(v)) { tour.add(u); // Return to u } } return true; } return false; } static List<Integer> tour = new ArrayList<>(); static List<Integer>[] adj; static boolean[] marked; public static class Scanner { BufferedReader br; StringTokenizer st; public Scanner(Reader in) { br = new BufferedReader(in); } public Scanner() { this(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } // Slightly different from java.util.Scanner.nextLine(), // which returns any remaining characters in current line, // if any. String readNextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } int[] readIntArray(int n) { int[] a = new int[n]; for (int idx = 0; idx < n; idx++) { a[idx] = nextInt(); } return a; } long[] readLongArray(int n) { long[] a = new long[n]; for (int idx = 0; idx < n; idx++) { a[idx] = nextLong(); } return a; } } }
Java
["3 2 1\n2 1\n3 1", "5 4 2\n1 2\n1 3\n1 4\n1 5"]
1 second
["3 2 1 3", "3 2 1 3\n3 4 1 5"]
NoteIn the first sample case there is only one clone who may visit vertices in order (2, 1, 3), which fits the constraint of 6 vertices per clone.In the second sample case the two clones can visited vertices in order (2, 1, 3) and (4, 1, 5), which fits the constraint of 5 vertices per clone.
Java 8
standard input
[ "graphs", "constructive algorithms", "dfs and similar", "trees", "brute force" ]
d32d638e5f90f0bfb7b7cec8e541cf7d
The first line contains three integers n, m, and k (1 ≤ n ≤ 2·105, n - 1 ≤ m ≤ 2·105, 1 ≤ k ≤ n) — the number of vertices and edges in the lab, and the number of clones. Each of the next m lines contains two integers xi and yi (1 ≤ xi, yi ≤ n) — indices of vertices connected by the respective edge. The graph is allowed to have self-loops and multiple edges. The graph is guaranteed to be connected.
2,100
You should print k lines. i-th of these lines must start with an integer ci () — the number of vertices visited by i-th clone, followed by ci integers — indices of vertices visited by this clone in the order of visiting. You have to print each vertex every time it is visited, regardless if it was visited earlier or not. It is guaranteed that a valid answer exists.
standard output
PASSED
ce4880da0173f3c315c6894a7f6a918f
train_003.jsonl
1488705300
The evil Bumbershoot corporation produces clones for gruesome experiments in a vast underground lab. On one occasion, the corp cloned a boy Andryusha who was smarter than his comrades. Immediately Andryusha understood that something fishy was going on there. He rallied fellow clones to go on a feud against the evil corp, and they set out to find an exit from the lab. The corp had to reduce to destroy the lab complex.The lab can be pictured as a connected graph with n vertices and m edges. k clones of Andryusha start looking for an exit in some of the vertices. Each clone can traverse any edge once per second. Any number of clones are allowed to be at any vertex simultaneously. Each clone is allowed to stop looking at any time moment, but he must look at his starting vertex at least. The exit can be located at any vertex of the lab, hence each vertex must be visited by at least one clone.Each clone can visit at most vertices before the lab explodes.Your task is to choose starting vertices and searching routes for the clones. Each route can have at most vertices.
256 megabytes
import java.io.*; import java.util.*; public class DFS_LAB { public static void main(String[] args) { // TODO Auto-generated method stub FastScanner input = new FastScanner(); int n = input.nextInt(); int edges = input.nextInt(); int clones = input.nextInt(); ArrayList<Integer>[] adjList = new ArrayList[n]; for (int a = 0; a < n; a++) { adjList[a] = new ArrayList<Integer>(); } for (int a = 0; a < edges; a++) { int st = input.nextInt() - 1; int end = input.nextInt() - 1; adjList[st].add(end); adjList[end].add(st); } int[] assigned = new int[n]; ArrayList<Integer> orderedNodes = new ArrayList<Integer>(); dfs(adjList, assigned, 0, orderedNodes); int maxNode = (2 * n + clones - 1) / clones; int count = 0; int total = 0; StringBuilder output = new StringBuilder(); int lineCount = 0; for (Integer i : orderedNodes) { if (count == maxNode || count == 0) { lineCount++; if (count == maxNode) { output.append("\n"); } count = 0; output.append(Math.min((orderedNodes.size() - total), maxNode) + " "); } total++; output.append((i+1) + " "); count++; } while(lineCount != clones){ output.append("\n1 1"); lineCount++; } System.out.println(output); } private static void dfs(ArrayList<Integer>[] adjList, int[] assigned, int index, ArrayList<Integer> orderedNodes) { assigned[index] = 1; orderedNodes.add(index); int count = 0; for (Integer i : adjList[index]) { if (assigned[i] == 0) { count++; dfs(adjList, assigned, i, orderedNodes); orderedNodes.add(index); } } } public static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(Reader in) { br = new BufferedReader(in); } public FastScanner() { this(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String readNextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } int[] readIntArray(int n) { int[] a = new int[n]; for (int idx = 0; idx < n; idx++) { a[idx] = nextInt(); } return a; } long[] readLongArray(int n) { long[] a = new long[n]; for (int idx = 0; idx < n; idx++) { a[idx] = nextLong(); } return a; } } }
Java
["3 2 1\n2 1\n3 1", "5 4 2\n1 2\n1 3\n1 4\n1 5"]
1 second
["3 2 1 3", "3 2 1 3\n3 4 1 5"]
NoteIn the first sample case there is only one clone who may visit vertices in order (2, 1, 3), which fits the constraint of 6 vertices per clone.In the second sample case the two clones can visited vertices in order (2, 1, 3) and (4, 1, 5), which fits the constraint of 5 vertices per clone.
Java 8
standard input
[ "graphs", "constructive algorithms", "dfs and similar", "trees", "brute force" ]
d32d638e5f90f0bfb7b7cec8e541cf7d
The first line contains three integers n, m, and k (1 ≤ n ≤ 2·105, n - 1 ≤ m ≤ 2·105, 1 ≤ k ≤ n) — the number of vertices and edges in the lab, and the number of clones. Each of the next m lines contains two integers xi and yi (1 ≤ xi, yi ≤ n) — indices of vertices connected by the respective edge. The graph is allowed to have self-loops and multiple edges. The graph is guaranteed to be connected.
2,100
You should print k lines. i-th of these lines must start with an integer ci () — the number of vertices visited by i-th clone, followed by ci integers — indices of vertices visited by this clone in the order of visiting. You have to print each vertex every time it is visited, regardless if it was visited earlier or not. It is guaranteed that a valid answer exists.
standard output
PASSED
608f4e90861e41792d7ad8fe28011701
train_003.jsonl
1488705300
The evil Bumbershoot corporation produces clones for gruesome experiments in a vast underground lab. On one occasion, the corp cloned a boy Andryusha who was smarter than his comrades. Immediately Andryusha understood that something fishy was going on there. He rallied fellow clones to go on a feud against the evil corp, and they set out to find an exit from the lab. The corp had to reduce to destroy the lab complex.The lab can be pictured as a connected graph with n vertices and m edges. k clones of Andryusha start looking for an exit in some of the vertices. Each clone can traverse any edge once per second. Any number of clones are allowed to be at any vertex simultaneously. Each clone is allowed to stop looking at any time moment, but he must look at his starting vertex at least. The exit can be located at any vertex of the lab, hence each vertex must be visited by at least one clone.Each clone can visit at most vertices before the lab explodes.Your task is to choose starting vertices and searching routes for the clones. Each route can have at most vertices.
256 megabytes
import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.OutputStreamWriter; import java.math.BigDecimal; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Locale; import java.util.Map.Entry; import java.util.PriorityQueue; import java.util.Random; import java.util.TreeSet; public final class CF_403_C{ static boolean verb=true; static void log(Object X){if (verb) System.err.println(X);} static void log(Object[] X){if (verb) {for (Object U:X) System.err.print(U+" ");System.err.println("");}} static void log(int[] X){if (verb) {for (int U:X) System.err.print(U+" ");System.err.println("");}} static void log(double[] X){if (verb) {for (double U:X) System.err.print(U+" ");System.err.println("");}} static void log(long[] X){if (verb) {for (long U:X) System.err.print(U+" ");System.err.println("");}} static void logWln(Object X){if (verb) System.err.print(X);} static void info(Object o){ System.out.println(o);} static void output(Object o){outputWln(""+o+"\n"); } static void outputWln(Object o){try {out.write(""+ o);} catch (Exception e) {}} static long mod=1000000007; static int[][] friends; static int[] anc,h,stack; /* static void test(){ int NTESTS=100000; Random r=new Random(); for (int t=0;t<NTESTS;t++){ n=10; friends=new TreeSet[n]; for (int i=0;i<n;i++){ friends[i]=new TreeSet<Integer>(); } for (int u=1;u<n;u++){ int v=r.nextInt(u); friends[u].add(v); friends[v].add(u); } for (k=1;k<=n;k++){ d=(2*n)/k; if (((2*n)%k)!=0) d++; solve(); } } } */ static void dfsModified(int node){ anc=new int[n]; stack=new int[2*n+1]; h=new int[n]; boolean[] used=new boolean[n]; visited=new boolean[n]; int p=0; stack[p++]=node; h[node]=0; anc[node]=-1; int clone=0; int st=0; used[node]=true; ArrayList<Integer> lst=new ArrayList<Integer>(); while (p>0){ int u=stack[--p]; //log("u:"+(u+1)+" "+visited[u]); //steps[clone].add(u); lst.add(u); st++; //log("don:"+don); if (st==d){ st=0; if (clone<k){ outputWln(lst.size()+" "); for (int i=0;i<lst.size();i++){ outputWln((lst.get(i)+1)+" "); } output(""); } lst=new ArrayList<Integer>(); clone++; } if (visited[u]){ // } else { visited[u]=true; //log("u:"+u); for (int v:friends[u]) { if (v!=anc[u] && !used[v]){ anc[v]=u; //h[v]=h[u]+1; //log("adding:"+(v+1)); //log("p:"+p); stack[p++]=u; stack[p++]=v; used[v]=true; } } } } if (clone<k){ if (lst.size()==0){ output("1 1"); } else { outputWln(lst.size()+" "); for (int i=0;i<lst.size();i++){ outputWln((lst.get(i)+1)+" "); } output(""); } } for (int i=clone+1;i<k;i++){ output("1 1"); } } static boolean[] visited; static ArrayList<Integer>[] steps; static void solve(){ dfsModified(0); } static void readGraph(int N,int M){ try { log("read graph"); friends=new int[N][]; int[] x=new int[M]; int[] y=new int[M]; int[] p=new int[N]; int st=0; for (int i=0;i<M;i++){ int u=reader.readInt()-1; int v=reader.readInt()-1; if (u!=v){ x[st]=u; p[u]++; y[st]=v; p[v]++; st++; } } for (int i=0;i<n;i++){ friends[i]=new int[p[i]]; } for (int i=0;i<st;i++){ int u=x[i]; int v=y[i]; friends[u][--p[u]]=v; friends[v][--p[v]]=u; } } catch (Exception e){log("problem"+e);} } // Global vars static BufferedWriter out; static InputReader reader; static int n,m,k,d; static void process() throws Exception { out = new BufferedWriter(new OutputStreamWriter(System.out)); reader=new InputReader(System.in); //test(); n=reader.readInt(); m=reader.readInt(); k=reader.readInt(); d=(2*n)/k; if (((2*n)%k)!=0) d++; log("d:"+d); readGraph(n,m); solve(); try { out.close(); } catch (Exception e){} } public static void main(String[] args) throws Exception { process(); } static final class InputReader { private final InputStream stream; private final byte[] buf = new byte[1024]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } private int read() throws IOException { if (curChar >= numChars) { curChar = 0; numChars = stream.read(buf); if (numChars <= 0) { return -1; } } return buf[curChar++]; } public final String readString() throws IOException { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res=new StringBuilder(); do { res.append((char)c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public final int readInt() throws IOException { int c = read(); boolean neg=false; while (isSpaceChar(c)) { c = read(); } char d=(char)c; //log("d:"+d); if (d=='-') { neg=true; c = read(); } int res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); //log("res:"+res); if (neg) return -res; return res; } public final long readLong() throws IOException { int c = read(); boolean neg=false; while (isSpaceChar(c)) { c = read(); } char d=(char)c; //log("d:"+d); if (d=='-') { neg=true; c = read(); } long res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); //log("res:"+res); if (neg) return -res; return res; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } } /* algo is buggy: check this: 4 4 2 1 2 2 2 4 2 3 4 1 3 1 2 2 3 3 4 ans: 3 1 2 1 3 */
Java
["3 2 1\n2 1\n3 1", "5 4 2\n1 2\n1 3\n1 4\n1 5"]
1 second
["3 2 1 3", "3 2 1 3\n3 4 1 5"]
NoteIn the first sample case there is only one clone who may visit vertices in order (2, 1, 3), which fits the constraint of 6 vertices per clone.In the second sample case the two clones can visited vertices in order (2, 1, 3) and (4, 1, 5), which fits the constraint of 5 vertices per clone.
Java 8
standard input
[ "graphs", "constructive algorithms", "dfs and similar", "trees", "brute force" ]
d32d638e5f90f0bfb7b7cec8e541cf7d
The first line contains three integers n, m, and k (1 ≤ n ≤ 2·105, n - 1 ≤ m ≤ 2·105, 1 ≤ k ≤ n) — the number of vertices and edges in the lab, and the number of clones. Each of the next m lines contains two integers xi and yi (1 ≤ xi, yi ≤ n) — indices of vertices connected by the respective edge. The graph is allowed to have self-loops and multiple edges. The graph is guaranteed to be connected.
2,100
You should print k lines. i-th of these lines must start with an integer ci () — the number of vertices visited by i-th clone, followed by ci integers — indices of vertices visited by this clone in the order of visiting. You have to print each vertex every time it is visited, regardless if it was visited earlier or not. It is guaranteed that a valid answer exists.
standard output
PASSED
42ec428544fc98eae606044c2374a27a
train_003.jsonl
1488705300
The evil Bumbershoot corporation produces clones for gruesome experiments in a vast underground lab. On one occasion, the corp cloned a boy Andryusha who was smarter than his comrades. Immediately Andryusha understood that something fishy was going on there. He rallied fellow clones to go on a feud against the evil corp, and they set out to find an exit from the lab. The corp had to reduce to destroy the lab complex.The lab can be pictured as a connected graph with n vertices and m edges. k clones of Andryusha start looking for an exit in some of the vertices. Each clone can traverse any edge once per second. Any number of clones are allowed to be at any vertex simultaneously. Each clone is allowed to stop looking at any time moment, but he must look at his starting vertex at least. The exit can be located at any vertex of the lab, hence each vertex must be visited by at least one clone.Each clone can visit at most vertices before the lab explodes.Your task is to choose starting vertices and searching routes for the clones. Each route can have at most vertices.
256 megabytes
import java.io.*; import java.lang.reflect.Array; import java.util.*; public class Main { static int inf = (int) 1e9 + 7; static int n, k; static ArrayList<Integer> gr[], ans[]; static int id = 0; static boolean used[]; static int dfs(int v, int st) { if (st == (2 * n + k - 1) / k + 1) { id++; st = 1; } used[v] = true; ans[id].add(v + 1); for(int i : gr[v]) { if (!used[i]) { st = dfs(i, st + 1); if (st == (2 * n + k - 1) / k + 1) { id++; st = 1; } ans[id].add(v + 1); } } return st + 1; } public static void main(String[] args) throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); pw = new PrintWriter(System.out); n = nextInt(); int m = nextInt(); k = nextInt(); gr = new ArrayList[n]; ans = new ArrayList[n]; for(int i = 0;i < n;i++) { gr[i] = new ArrayList<>(); ans[i] = new ArrayList<>(); } used = new boolean[n]; dsu var = new dsu(n); for(int i = 0;i < m;i++) { int v1 = nextInt() - 1; int v2 = nextInt() - 1; if (var.get(v1) != var.get(v2)) { gr[v1].add(v2); gr[v2].add(v1); var.union(v1, v2); } } dfs(0, 1); while(id < k) { if (ans[id].isEmpty()) ans[id].add(1); id++; } for(int i = 0;i < k;i++) { pw.print(ans[i].size() + " "); for(int j : ans[i]) pw.print(j + " "); pw.println(); } pw.close(); } static BufferedReader br; static StringTokenizer st = new StringTokenizer(""); static PrintWriter pw; static String next() throws IOException { while (!st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } static int nextInt() throws IOException { return Integer.parseInt(next()); } static long nextLong() throws IOException { return Long.parseLong(next()); } } class dsu { int parent[]; dsu (int n) { parent = new int [n]; for(int i = 0;i < n;i++) parent[i] = i; } int get(int v) { if (v == parent[v]) return v; return parent[v] = get(parent[v]); } void union(int a, int b) { parent[get(a)] = get(b); } }
Java
["3 2 1\n2 1\n3 1", "5 4 2\n1 2\n1 3\n1 4\n1 5"]
1 second
["3 2 1 3", "3 2 1 3\n3 4 1 5"]
NoteIn the first sample case there is only one clone who may visit vertices in order (2, 1, 3), which fits the constraint of 6 vertices per clone.In the second sample case the two clones can visited vertices in order (2, 1, 3) and (4, 1, 5), which fits the constraint of 5 vertices per clone.
Java 8
standard input
[ "graphs", "constructive algorithms", "dfs and similar", "trees", "brute force" ]
d32d638e5f90f0bfb7b7cec8e541cf7d
The first line contains three integers n, m, and k (1 ≤ n ≤ 2·105, n - 1 ≤ m ≤ 2·105, 1 ≤ k ≤ n) — the number of vertices and edges in the lab, and the number of clones. Each of the next m lines contains two integers xi and yi (1 ≤ xi, yi ≤ n) — indices of vertices connected by the respective edge. The graph is allowed to have self-loops and multiple edges. The graph is guaranteed to be connected.
2,100
You should print k lines. i-th of these lines must start with an integer ci () — the number of vertices visited by i-th clone, followed by ci integers — indices of vertices visited by this clone in the order of visiting. You have to print each vertex every time it is visited, regardless if it was visited earlier or not. It is guaranteed that a valid answer exists.
standard output
PASSED
57752761144401d837dd16cbd37b2e9f
train_003.jsonl
1488705300
The evil Bumbershoot corporation produces clones for gruesome experiments in a vast underground lab. On one occasion, the corp cloned a boy Andryusha who was smarter than his comrades. Immediately Andryusha understood that something fishy was going on there. He rallied fellow clones to go on a feud against the evil corp, and they set out to find an exit from the lab. The corp had to reduce to destroy the lab complex.The lab can be pictured as a connected graph with n vertices and m edges. k clones of Andryusha start looking for an exit in some of the vertices. Each clone can traverse any edge once per second. Any number of clones are allowed to be at any vertex simultaneously. Each clone is allowed to stop looking at any time moment, but he must look at his starting vertex at least. The exit can be located at any vertex of the lab, hence each vertex must be visited by at least one clone.Each clone can visit at most vertices before the lab explodes.Your task is to choose starting vertices and searching routes for the clones. Each route can have at most vertices.
256 megabytes
import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.Writer; import java.lang.reflect.Constructor; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.InputMismatchException; import java.util.LinkedList; import java.util.StringTokenizer; public class CodeC { private static final boolean SHOULD_BUFFER_OUTPUT = true; static final SuperWriter sw = new SuperWriter(System.out); static final SuperScanner sc = new SuperScanner(); static class DisjointSetImpl { int[] p, rank; public DisjointSetImpl(int size) { rank = new int[size]; p = new int[size]; for (int i = 0; i < size; i++) make_set(i); } public void make_set(int x) { p[x] = x; rank[x] = 0; } public void merge(int x, int y) { link(find_set(x), find_set(y)); } public void link(int x, int y) { if (rank[x] > rank[y]) p[y] = x; else { p[x] = y; if (rank[x] == rank[y]) rank[y] += 1; } } public int find_set(int x) { if (x != p[x]) p[x] = find_set(p[x]); return p[x]; } public int countSets(int n) { HashSet <Integer> sets = new HashSet <Integer> (); for(int i = 0; i < n; i++) sets.add(find_set(i)); return sets.size(); } } static class Robot { final ArrayList<Integer> nodesVisited = new ArrayList<>(); } static class Node { final int id; final LinkedList<Node> pendingChilds = new LinkedList<>(); boolean visited = false; Node parent; Node(int id) { this.id = id; } void setParent(Node parent) { this.parent = parent; for (Node node : pendingChilds) { if (node != parent) { node.setParent(this); } } } } static ArrayList<Robot> solve(Node[] nodes, int k) { int limit = (int) Math.ceil((nodes.length * 2.0d) / k); ArrayList<Robot> robots = new ArrayList<>(); nodes[0].setParent(null); Node currentNode = nodes[0]; Robot currentRobot = null; while (currentNode != null) { while (!currentNode.pendingChilds.isEmpty() && currentNode.pendingChilds.peekFirst() == currentNode.parent) { currentNode.pendingChilds.pollFirst(); } if (currentRobot == null && currentNode.pendingChilds.isEmpty() && !currentNode.visited) { currentRobot = new Robot(); robots.add(currentRobot); } if (currentRobot != null) { currentRobot.nodesVisited.add(currentNode.id); if (currentRobot.nodesVisited.size() == limit) { currentRobot = null; } currentNode.visited = true; } if (currentNode.pendingChilds.isEmpty()) { currentNode = currentNode.parent; } else { currentNode = currentNode.pendingChilds.pollFirst(); } } while (robots.size() != k) { Robot dummyRobot = new Robot(); dummyRobot.nodesVisited.add(1); robots.add(dummyRobot); } return robots; } public static void main() { int n = sc.nextInt(); int m = sc.nextInt(); int k = sc.nextInt(); Node[] nodes = new Node[n]; for (int i = 0; i < n; i++) { nodes[i] = new Node(i + 1); } DisjointSetImpl ds = new DisjointSetImpl(n); for (int i = 0; i < m; i++) { int x = sc.nextInt() - 1; int y = sc.nextInt() - 1; if (ds.find_set(x) != ds.find_set(y)) { nodes[x].pendingChilds.add(nodes[y]); nodes[y].pendingChilds.add(nodes[x]); ds.merge(x, y); } } ArrayList<Robot> robots = solve(nodes, k); for (Robot robot : robots) { sw.printSimple(robot.nodesVisited.size() + " "); sw.printLine(robot.nodesVisited); } } static class LineScanner extends Scanner { private StringTokenizer st; public LineScanner(String input) { st = new StringTokenizer(input); } @Override public String next() { return st.hasMoreTokens() ? st.nextToken() : null; } @Override public String nextLine() { throw new RuntimeException("not supported"); } public boolean hasNext() { return st.hasMoreTokens(); } private final ArrayList<Object> temp = new ArrayList<Object>(); private void fillTemp() { while (st.hasMoreTokens()) { temp.add(st.nextToken()); } } public String[] asStringArray() { fillTemp(); String[] answer = new String[temp.size()]; for (int i = 0; i < answer.length; i++) { answer[i] = (String) temp.get(i); } temp.clear(); return answer; } public int[] asIntArray() { fillTemp(); int[] answer = new int[temp.size()]; for (int i = 0; i < answer.length; i++) { answer[i] = Integer.parseInt((String) temp.get(i)); } temp.clear(); return answer; } public long[] asLongArray() { fillTemp(); long[] answer = new long[temp.size()]; for (int i = 0; i < answer.length; i++) { answer[i] = Long.parseLong((String) temp.get(i)); } temp.clear(); return answer; } public double[] asDoubleArray() { fillTemp(); double[] answer = new double[temp.size()]; for (int i = 0; i < answer.length; i++) { answer[i] = Double.parseDouble((String) temp.get(i)); } temp.clear(); return answer; } } static class SuperScanner extends Scanner { private InputStream stream; private byte[] buf = new byte[8096]; private int curChar; private int numChars; public SuperScanner() { this.stream = System.in; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public static boolean isLineEnd(int c) { return c == '\n' || c == -1; } private final StringBuilder sb = new StringBuilder(); @Override public String next() { int c = read(); while (isWhitespace(c)) { if (c == -1) { return null; } c = read(); } sb.setLength(0); do { sb.append((char) c); c = read(); } while (!isWhitespace(c)); return sb.toString(); } @Override public String nextLine() { sb.setLength(0); int c; while (true) { c = read(); if (!isLineEnd(c)) { sb.append((char) c); } else { break; } } if (c == -1 && sb.length() == 0) { return null; } else { if (sb.length() > 0 && sb.charAt(sb.length() - 1) == '\r') { return sb.substring(0, sb.length() - 1); } else { return sb.toString(); } } } public LineScanner nextLineScanner() { String line = nextLine(); if (line == null) { return null; } else { return new LineScanner(line); } } public LineScanner nextNonEmptyLineScanner() { while (true) { String line = nextLine(); if (line == null) { return null; } else if (!line.isEmpty()) { return new LineScanner(line); } } } @Override 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 = (res << 3) + (res << 1); res += c - '0'; c = read(); } while (!isWhitespace(c)); return res * sgn; } @Override public long nextLong() { int c = read(); while (isWhitespace(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 = (res << 3) + (res << 1); res += c - '0'; c = read(); } while (!isWhitespace(c)); return res * sgn; } } static abstract class Scanner { public abstract String next(); public abstract String nextLine(); public int nextIntOrQuit() { Integer n = nextInteger(); if (n == null) { sw.close(); System.exit(0); } return n.intValue(); } 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] = nextDouble(); 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]; } public String[] nextStringArray(int n) { String[] vals = new String[n]; for (int i = 0; i < n; i++) vals[i] = next(); return vals; } public Integer nextInteger() { String s = next(); if (s == null) return null; return Integer.parseInt(s); } public int[][] nextIntMatrix(int n, int m) { int[][] ans = new int[n][]; for (int i = 0; i < n; i++) ans[i] = nextIntArray(m); return ans; } public char[][] nextGrid(int r) { char[][] grid = new char[r][]; for (int i = 0; i < r; i++) grid[i] = next().toCharArray(); return grid; } public static <T> T fill(T arreglo, int val) { if (arreglo instanceof Object[]) { Object[] a = (Object[]) arreglo; for (Object x : a) fill(x, val); } else if (arreglo instanceof int[]) Arrays.fill((int[]) arreglo, val); else if (arreglo instanceof double[]) Arrays.fill((double[]) arreglo, val); else if (arreglo instanceof long[]) Arrays.fill((long[]) arreglo, val); return arreglo; } public <T> T[] nextObjectArray(Class<T> clazz, int size) { @SuppressWarnings("unchecked") T[] result = (T[]) java.lang.reflect.Array.newInstance(clazz, size); for (int c = 0; c < 3; c++) { Constructor<T> constructor; try { if (c == 0) constructor = clazz.getDeclaredConstructor(Scanner.class, Integer.TYPE); else if (c == 1) constructor = clazz.getDeclaredConstructor(Scanner.class); else constructor = clazz.getDeclaredConstructor(); } catch (Exception e) { continue; } try { for (int i = 0; i < result.length; i++) { if (c == 0) result[i] = constructor.newInstance(this, i); else if (c == 1) result[i] = constructor.newInstance(this); else result[i] = constructor.newInstance(); } } catch (Exception e) { throw new RuntimeException(e); } return result; } throw new RuntimeException("Constructor not found"); } public Collection<Integer> wrap(int[] as) { ArrayList<Integer> ans = new ArrayList<Integer>(); for (int i : as) ans.add(i); return ans; } public int[] unwrap(Collection<Integer> collection) { int[] vals = new int[collection.size()]; int index = 0; for (int i : collection) vals[index++] = i; return vals; } int testCases = Integer.MIN_VALUE; boolean testCases() { if (testCases == Integer.MIN_VALUE) { testCases = nextInt(); } return --testCases >= 0; } } static class SuperWriter { private final PrintWriter writer; public SuperWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public SuperWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void close() { writer.flush(); writer.close(); } public void printLine(String line) { writer.println(line); if (!SHOULD_BUFFER_OUTPUT) { writer.flush(); } } public void printLine(int... vals) { if (vals.length == 0) { writer.println(); } else { writer.print(vals[0]); for (int i = 1; i < vals.length; i++) writer.print(" ".concat(String.valueOf(vals[i]))); writer.println(); } if (!SHOULD_BUFFER_OUTPUT) { writer.flush(); } } public void printLine(long... vals) { if (vals.length == 0) { writer.println(); } else { writer.print(vals[0]); for (int i = 1; i < vals.length; i++) writer.print(" ".concat(String.valueOf(vals[i]))); writer.println(); } if (!SHOULD_BUFFER_OUTPUT) { writer.flush(); } } public void printLine(double... vals) { if (vals.length == 0) { writer.println(); } else { writer.print(vals[0]); for (int i = 1; i < vals.length; i++) writer.print(" ".concat(String.valueOf(vals[i]))); writer.println(); } if (!SHOULD_BUFFER_OUTPUT) { writer.flush(); } } public void printLine(int prec, double... vals) { if (vals.length == 0) { writer.println(); } else { String precision = "%." + prec + "f"; writer.print(String.format(precision, vals[0]).replace(',', '.')); precision = " " + precision; for (int i = 1; i < vals.length; i++) writer.print(String.format(precision, vals[i]).replace(',', '.')); writer.println(); } if (!SHOULD_BUFFER_OUTPUT) { writer.flush(); } } public <E> void printLine(Collection<E> vals) { if (vals.size() == 0) { writer.println(); } else { int i = 0; for (E val : vals) { if (i++ == 0) { writer.print(val.toString()); } else { writer.print(" ".concat(val.toString())); } } writer.println(); } if (!SHOULD_BUFFER_OUTPUT) { writer.flush(); } } public void printSimple(String value) { writer.print(value); if (!SHOULD_BUFFER_OUTPUT) { writer.flush(); } } public boolean ifZeroExit(Number... values) { for (Number number : values) { if (number.doubleValue() != 0.0d || number.longValue() != 0) { return false; } } close(); System.exit(0); return true; } } public static void main(String[] args) { main(); sw.close(); } }
Java
["3 2 1\n2 1\n3 1", "5 4 2\n1 2\n1 3\n1 4\n1 5"]
1 second
["3 2 1 3", "3 2 1 3\n3 4 1 5"]
NoteIn the first sample case there is only one clone who may visit vertices in order (2, 1, 3), which fits the constraint of 6 vertices per clone.In the second sample case the two clones can visited vertices in order (2, 1, 3) and (4, 1, 5), which fits the constraint of 5 vertices per clone.
Java 8
standard input
[ "graphs", "constructive algorithms", "dfs and similar", "trees", "brute force" ]
d32d638e5f90f0bfb7b7cec8e541cf7d
The first line contains three integers n, m, and k (1 ≤ n ≤ 2·105, n - 1 ≤ m ≤ 2·105, 1 ≤ k ≤ n) — the number of vertices and edges in the lab, and the number of clones. Each of the next m lines contains two integers xi and yi (1 ≤ xi, yi ≤ n) — indices of vertices connected by the respective edge. The graph is allowed to have self-loops and multiple edges. The graph is guaranteed to be connected.
2,100
You should print k lines. i-th of these lines must start with an integer ci () — the number of vertices visited by i-th clone, followed by ci integers — indices of vertices visited by this clone in the order of visiting. You have to print each vertex every time it is visited, regardless if it was visited earlier or not. It is guaranteed that a valid answer exists.
standard output
PASSED
5a9b4073a79ba9fee526aa5d4bdb84e4
train_003.jsonl
1488705300
The evil Bumbershoot corporation produces clones for gruesome experiments in a vast underground lab. On one occasion, the corp cloned a boy Andryusha who was smarter than his comrades. Immediately Andryusha understood that something fishy was going on there. He rallied fellow clones to go on a feud against the evil corp, and they set out to find an exit from the lab. The corp had to reduce to destroy the lab complex.The lab can be pictured as a connected graph with n vertices and m edges. k clones of Andryusha start looking for an exit in some of the vertices. Each clone can traverse any edge once per second. Any number of clones are allowed to be at any vertex simultaneously. Each clone is allowed to stop looking at any time moment, but he must look at his starting vertex at least. The exit can be located at any vertex of the lab, hence each vertex must be visited by at least one clone.Each clone can visit at most vertices before the lab explodes.Your task is to choose starting vertices and searching routes for the clones. Each route can have at most vertices.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.List; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.util.LinkedList; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { List<Integer>[] adj; boolean[] marked; int[] tour; int time; public void solve(int testNumber, InputReader in, PrintWriter out) { int N = in.nextInt(); int M = in.nextInt(); int K = in.nextInt(); adj = (List<Integer>[]) new LinkedList[N]; for (int i = 0; i < N; i++) adj[i] = new LinkedList<>(); for (int i = 0; i < M; i++) { int v = in.nextInt() - 1; int w = in.nextInt() - 1; adj[v].add(w); adj[w].add(v); } marked = new boolean[N]; tour = new int[2 * N - 1]; time = 0; dfs(0); int segment = (2 * N + K - 1) / K; for (int k = 0, start = 0; k < K; k++, start += segment) { int end = Math.min(2 * N - 1, start + segment); if (start >= end) { out.println("1 1"); } else { out.print(end - start + " "); for (int i = start; i < end; i++) { out.print(tour[i] + " "); } out.println(); } } } private void dfs(int v) { marked[v] = true; tour[time++] = v + 1; for (int w : adj[v]) { if (!marked[w]) { dfs(w); tour[time++] = v + 1; } } } } 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
["3 2 1\n2 1\n3 1", "5 4 2\n1 2\n1 3\n1 4\n1 5"]
1 second
["3 2 1 3", "3 2 1 3\n3 4 1 5"]
NoteIn the first sample case there is only one clone who may visit vertices in order (2, 1, 3), which fits the constraint of 6 vertices per clone.In the second sample case the two clones can visited vertices in order (2, 1, 3) and (4, 1, 5), which fits the constraint of 5 vertices per clone.
Java 8
standard input
[ "graphs", "constructive algorithms", "dfs and similar", "trees", "brute force" ]
d32d638e5f90f0bfb7b7cec8e541cf7d
The first line contains three integers n, m, and k (1 ≤ n ≤ 2·105, n - 1 ≤ m ≤ 2·105, 1 ≤ k ≤ n) — the number of vertices and edges in the lab, and the number of clones. Each of the next m lines contains two integers xi and yi (1 ≤ xi, yi ≤ n) — indices of vertices connected by the respective edge. The graph is allowed to have self-loops and multiple edges. The graph is guaranteed to be connected.
2,100
You should print k lines. i-th of these lines must start with an integer ci () — the number of vertices visited by i-th clone, followed by ci integers — indices of vertices visited by this clone in the order of visiting. You have to print each vertex every time it is visited, regardless if it was visited earlier or not. It is guaranteed that a valid answer exists.
standard output
PASSED
9a9892135105fc74d57c0aebb2c3de41
train_003.jsonl
1488705300
The evil Bumbershoot corporation produces clones for gruesome experiments in a vast underground lab. On one occasion, the corp cloned a boy Andryusha who was smarter than his comrades. Immediately Andryusha understood that something fishy was going on there. He rallied fellow clones to go on a feud against the evil corp, and they set out to find an exit from the lab. The corp had to reduce to destroy the lab complex.The lab can be pictured as a connected graph with n vertices and m edges. k clones of Andryusha start looking for an exit in some of the vertices. Each clone can traverse any edge once per second. Any number of clones are allowed to be at any vertex simultaneously. Each clone is allowed to stop looking at any time moment, but he must look at his starting vertex at least. The exit can be located at any vertex of the lab, hence each vertex must be visited by at least one clone.Each clone can visit at most vertices before the lab explodes.Your task is to choose starting vertices and searching routes for the clones. Each route can have at most vertices.
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.util.InputMismatchException; import java.io.IOException; import java.util.TreeSet; import java.util.ArrayList; 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) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { ArrayList<Integer>[] adj; ArrayList<Integer> res = new ArrayList<>(); boolean TEST = false; TreeSet<IntIntPair> edges = new TreeSet<>(); void dfs(int cur, int prev) { res.add(cur); for (int nxt : adj[cur]) if (nxt != prev) { dfs(nxt, cur); res.add(cur); } } public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.readInt(), m = in.readInt(), k = in.readInt(); adj = new ArrayList[n]; for (int i = 0; i < adj.length; i++) adj[i] = new ArrayList<>(); RecursiveIndependentSetSystem iss = new RecursiveIndependentSetSystem(n); for (int i = 0; i < m; i++) { int x = in.readInt() - 1, y = in.readInt() - 1; if (!iss.join(x, y)) continue; adj[x].add(y); adj[y].add(x); if (TEST) { edges.add(new IntIntPair(x, y)); edges.add(new IntIntPair(y, x)); } } int max = (2 * n + k - 1) / k; dfs(0, -1); if (res.size() != 2 * n - 1) throw new RuntimeException(Integer.toString(res.size())); if (TEST) { for (int i = 0; i < res.size() - 1; i++) { int a = res.get(i); int b = res.get(i + 1); if (!edges.contains(new IntIntPair(a, b)) && !edges.contains(new IntIntPair(b, a))) { throw new RuntimeException(); } } } int printed = 0; for (int idx = 0; ; ) { int take = Math.min(max, res.size() - idx); if (take == 0) break; out.print(take + " "); for (int i = idx; i < idx + take; i++) { out.print((res.get(i) + 1) + " "); } out.printLine(); idx += take; printed++; } if (printed > k) throw new RuntimeException(); while (printed < k) { out.printLine(1, 1); printed++; } if (printed != k) throw new RuntimeException(); } } static interface IndependentSetSystem { public static interface Listener { public void joined(int joinedRoot, int root); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } 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() { writer.println(); } public void printLine(Object... objects) { print(objects); writer.println(); } public void close() { writer.close(); } } static class RecursiveIndependentSetSystem implements IndependentSetSystem { private final int[] color; private final int[] rank; private int setCount; private IndependentSetSystem.Listener listener; public RecursiveIndependentSetSystem(int size) { color = new int[size]; rank = new int[size]; for (int i = 0; i < size; i++) { color[i] = i; } setCount = size; } public RecursiveIndependentSetSystem(RecursiveIndependentSetSystem other) { color = other.color.clone(); rank = other.rank.clone(); setCount = other.setCount; } public boolean join(int first, int second) { first = get(first); second = get(second); if (first == second) { return false; } if (rank[first] < rank[second]) { int temp = first; first = second; second = temp; } else if (rank[first] == rank[second]) { rank[first]++; } setCount--; color[second] = first; if (listener != null) { listener.joined(second, first); } return true; } public int get(int index) { int start = index; while (color[index] != index) { index = color[index]; } while (start != index) { int next = color[start]; color[start] = index; start = next; } return index; } } static class IntIntPair implements Comparable<IntIntPair> { public final int first; public final int second; public IntIntPair(int first, int second) { this.first = first; this.second = second; } public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } IntIntPair pair = (IntIntPair) o; return first == pair.first && second == pair.second; } public int hashCode() { int result = first; result = 31 * result + second; return result; } public String toString() { return "(" + first + "," + second + ")"; } @SuppressWarnings ({"unchecked"}) public int compareTo(IntIntPair o) { int value = Integer.compare(first, o.first); if (value != 0) { return value; } return Integer.compare(second, o.second); } } }
Java
["3 2 1\n2 1\n3 1", "5 4 2\n1 2\n1 3\n1 4\n1 5"]
1 second
["3 2 1 3", "3 2 1 3\n3 4 1 5"]
NoteIn the first sample case there is only one clone who may visit vertices in order (2, 1, 3), which fits the constraint of 6 vertices per clone.In the second sample case the two clones can visited vertices in order (2, 1, 3) and (4, 1, 5), which fits the constraint of 5 vertices per clone.
Java 8
standard input
[ "graphs", "constructive algorithms", "dfs and similar", "trees", "brute force" ]
d32d638e5f90f0bfb7b7cec8e541cf7d
The first line contains three integers n, m, and k (1 ≤ n ≤ 2·105, n - 1 ≤ m ≤ 2·105, 1 ≤ k ≤ n) — the number of vertices and edges in the lab, and the number of clones. Each of the next m lines contains two integers xi and yi (1 ≤ xi, yi ≤ n) — indices of vertices connected by the respective edge. The graph is allowed to have self-loops and multiple edges. The graph is guaranteed to be connected.
2,100
You should print k lines. i-th of these lines must start with an integer ci () — the number of vertices visited by i-th clone, followed by ci integers — indices of vertices visited by this clone in the order of visiting. You have to print each vertex every time it is visited, regardless if it was visited earlier or not. It is guaranteed that a valid answer exists.
standard output
PASSED
36908f5dd0b3af1c17f47e80c37cd004
train_003.jsonl
1488705300
The evil Bumbershoot corporation produces clones for gruesome experiments in a vast underground lab. On one occasion, the corp cloned a boy Andryusha who was smarter than his comrades. Immediately Andryusha understood that something fishy was going on there. He rallied fellow clones to go on a feud against the evil corp, and they set out to find an exit from the lab. The corp had to reduce to destroy the lab complex.The lab can be pictured as a connected graph with n vertices and m edges. k clones of Andryusha start looking for an exit in some of the vertices. Each clone can traverse any edge once per second. Any number of clones are allowed to be at any vertex simultaneously. Each clone is allowed to stop looking at any time moment, but he must look at his starting vertex at least. The exit can be located at any vertex of the lab, hence each vertex must be visited by at least one clone.Each clone can visit at most vertices before the lab explodes.Your task is to choose starting vertices and searching routes for the clones. Each route can have at most vertices.
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.util.ArrayList; 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); OutputWriter out = new OutputWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { ArrayList<Integer> res = new ArrayList<>(); ArrayList<Integer>[] adj; void add(int val) { res.add(val); } void dfs(int cur, int prev) { add(cur); for (int nxt : adj[cur]) if (nxt != prev) { dfs(nxt, cur); add(cur); } } public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.readInt(), m = in.readInt(), k = in.readInt(); adj = new ArrayList[n]; for (int i = 0; i < adj.length; i++) adj[i] = new ArrayList<>(); RecursiveIndependentSetSystem iss = new RecursiveIndependentSetSystem(n); for (int i = 0; i < m; i++) { int x = in.readInt() - 1; int y = in.readInt() - 1; if (x == y) continue; if (iss.join(x, y)) { adj[x].add(y); adj[y].add(x); } } int max = (2 * n + k - 1) / k; dfs(0, -1); int[] build = new int[max]; int ptr = 0; int printed = 0; for (int i = 0; i < res.size(); i++) { int val = res.get(i); build[ptr++] = val; if (ptr == build.length) { out.print(build.length + " "); for (int j = 0; j < ptr; j++) out.print(build[j] + 1 + " "); out.printLine(); ptr = 0; printed++; } else if (i == res.size() - 1) { out.print(ptr + " "); for (int j = 0; j < ptr; j++) out.print(build[j] + 1 + " "); out.printLine(); printed++; } } while (printed < k) { out.printLine(1, 1); printed++; } if (printed > k) throw new RuntimeException(); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } static interface IndependentSetSystem { public static interface Listener { public void joined(int joinedRoot, int root); } } 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() { writer.println(); } public void printLine(Object... objects) { print(objects); writer.println(); } public void close() { writer.close(); } } static class RecursiveIndependentSetSystem implements IndependentSetSystem { private final int[] color; private final int[] rank; private int setCount; private IndependentSetSystem.Listener listener; public RecursiveIndependentSetSystem(int size) { color = new int[size]; rank = new int[size]; for (int i = 0; i < size; i++) { color[i] = i; } setCount = size; } public RecursiveIndependentSetSystem(RecursiveIndependentSetSystem other) { color = other.color.clone(); rank = other.rank.clone(); setCount = other.setCount; } public boolean join(int first, int second) { first = get(first); second = get(second); if (first == second) { return false; } if (rank[first] < rank[second]) { int temp = first; first = second; second = temp; } else if (rank[first] == rank[second]) { rank[first]++; } setCount--; color[second] = first; if (listener != null) { listener.joined(second, first); } return true; } public int get(int index) { int start = index; while (color[index] != index) { index = color[index]; } while (start != index) { int next = color[start]; color[start] = index; start = next; } return index; } } }
Java
["3 2 1\n2 1\n3 1", "5 4 2\n1 2\n1 3\n1 4\n1 5"]
1 second
["3 2 1 3", "3 2 1 3\n3 4 1 5"]
NoteIn the first sample case there is only one clone who may visit vertices in order (2, 1, 3), which fits the constraint of 6 vertices per clone.In the second sample case the two clones can visited vertices in order (2, 1, 3) and (4, 1, 5), which fits the constraint of 5 vertices per clone.
Java 8
standard input
[ "graphs", "constructive algorithms", "dfs and similar", "trees", "brute force" ]
d32d638e5f90f0bfb7b7cec8e541cf7d
The first line contains three integers n, m, and k (1 ≤ n ≤ 2·105, n - 1 ≤ m ≤ 2·105, 1 ≤ k ≤ n) — the number of vertices and edges in the lab, and the number of clones. Each of the next m lines contains two integers xi and yi (1 ≤ xi, yi ≤ n) — indices of vertices connected by the respective edge. The graph is allowed to have self-loops and multiple edges. The graph is guaranteed to be connected.
2,100
You should print k lines. i-th of these lines must start with an integer ci () — the number of vertices visited by i-th clone, followed by ci integers — indices of vertices visited by this clone in the order of visiting. You have to print each vertex every time it is visited, regardless if it was visited earlier or not. It is guaranteed that a valid answer exists.
standard output
PASSED
f68d15604b24c0e8d83dc6e922eefee2
train_003.jsonl
1488705300
The evil Bumbershoot corporation produces clones for gruesome experiments in a vast underground lab. On one occasion, the corp cloned a boy Andryusha who was smarter than his comrades. Immediately Andryusha understood that something fishy was going on there. He rallied fellow clones to go on a feud against the evil corp, and they set out to find an exit from the lab. The corp had to reduce to destroy the lab complex.The lab can be pictured as a connected graph with n vertices and m edges. k clones of Andryusha start looking for an exit in some of the vertices. Each clone can traverse any edge once per second. Any number of clones are allowed to be at any vertex simultaneously. Each clone is allowed to stop looking at any time moment, but he must look at his starting vertex at least. The exit can be located at any vertex of the lab, hence each vertex must be visited by at least one clone.Each clone can visit at most vertices before the lab explodes.Your task is to choose starting vertices and searching routes for the clones. Each route can have at most vertices.
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.util.InputMismatchException; import java.io.IOException; import java.util.TreeSet; import java.util.ArrayList; 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) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { ArrayList<Integer>[] adj; ArrayList<Integer> res = new ArrayList<>(); boolean TEST = false; TreeSet<IntIntPair> edges = new TreeSet<>(); void dfs(int cur, int prev) { for (int nxt : adj[cur]) if (nxt != prev) { res.add(nxt); dfs(nxt, cur); res.add(cur); } } public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.readInt(), m = in.readInt(), k = in.readInt(); adj = new ArrayList[n]; for (int i = 0; i < adj.length; i++) adj[i] = new ArrayList<>(); RecursiveIndependentSetSystem iss = new RecursiveIndependentSetSystem(n); for (int i = 0; i < m; i++) { int x = in.readInt() - 1, y = in.readInt() - 1; if (!iss.join(x, y)) continue; adj[x].add(y); adj[y].add(x); if (TEST) { edges.add(new IntIntPair(x, y)); edges.add(new IntIntPair(y, x)); } } int max = (2 * n + k - 1) / k; res.add(0); dfs(0, -1); if (res.size() != 2 * n - 1) throw new RuntimeException(Integer.toString(res.size())); if (TEST) { for (int i = 0; i < res.size() - 1; i++) { int a = res.get(i); int b = res.get(i + 1); if (!edges.contains(new IntIntPair(a, b)) && !edges.contains(new IntIntPair(b, a))) { throw new RuntimeException(); } } } int printed = 0; for (int idx = 0; ; ) { int take = Math.min(max, res.size() - idx); if (take == 0) break; out.print(take + " "); for (int i = idx; i < idx + take; i++) { out.print((res.get(i) + 1) + " "); } out.printLine(); idx += take; printed++; } if (printed > k) throw new RuntimeException(); while (printed < k) { out.printLine(1, 1); printed++; } if (printed != k) throw new RuntimeException(); } } static interface IndependentSetSystem { public static interface Listener { public void joined(int joinedRoot, int root); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } 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() { writer.println(); } public void printLine(Object... objects) { print(objects); writer.println(); } public void close() { writer.close(); } } static class RecursiveIndependentSetSystem implements IndependentSetSystem { private final int[] color; private final int[] rank; private int setCount; private IndependentSetSystem.Listener listener; public RecursiveIndependentSetSystem(int size) { color = new int[size]; rank = new int[size]; for (int i = 0; i < size; i++) { color[i] = i; } setCount = size; } public RecursiveIndependentSetSystem(RecursiveIndependentSetSystem other) { color = other.color.clone(); rank = other.rank.clone(); setCount = other.setCount; } public boolean join(int first, int second) { first = get(first); second = get(second); if (first == second) { return false; } if (rank[first] < rank[second]) { int temp = first; first = second; second = temp; } else if (rank[first] == rank[second]) { rank[first]++; } setCount--; color[second] = first; if (listener != null) { listener.joined(second, first); } return true; } public int get(int index) { int start = index; while (color[index] != index) { index = color[index]; } while (start != index) { int next = color[start]; color[start] = index; start = next; } return index; } } static class IntIntPair implements Comparable<IntIntPair> { public final int first; public final int second; public IntIntPair(int first, int second) { this.first = first; this.second = second; } public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } IntIntPair pair = (IntIntPair) o; return first == pair.first && second == pair.second; } public int hashCode() { int result = first; result = 31 * result + second; return result; } public String toString() { return "(" + first + "," + second + ")"; } @SuppressWarnings ({"unchecked"}) public int compareTo(IntIntPair o) { int value = Integer.compare(first, o.first); if (value != 0) { return value; } return Integer.compare(second, o.second); } } }
Java
["3 2 1\n2 1\n3 1", "5 4 2\n1 2\n1 3\n1 4\n1 5"]
1 second
["3 2 1 3", "3 2 1 3\n3 4 1 5"]
NoteIn the first sample case there is only one clone who may visit vertices in order (2, 1, 3), which fits the constraint of 6 vertices per clone.In the second sample case the two clones can visited vertices in order (2, 1, 3) and (4, 1, 5), which fits the constraint of 5 vertices per clone.
Java 8
standard input
[ "graphs", "constructive algorithms", "dfs and similar", "trees", "brute force" ]
d32d638e5f90f0bfb7b7cec8e541cf7d
The first line contains three integers n, m, and k (1 ≤ n ≤ 2·105, n - 1 ≤ m ≤ 2·105, 1 ≤ k ≤ n) — the number of vertices and edges in the lab, and the number of clones. Each of the next m lines contains two integers xi and yi (1 ≤ xi, yi ≤ n) — indices of vertices connected by the respective edge. The graph is allowed to have self-loops and multiple edges. The graph is guaranteed to be connected.
2,100
You should print k lines. i-th of these lines must start with an integer ci () — the number of vertices visited by i-th clone, followed by ci integers — indices of vertices visited by this clone in the order of visiting. You have to print each vertex every time it is visited, regardless if it was visited earlier or not. It is guaranteed that a valid answer exists.
standard output
PASSED
2bec2221d6a9f205de12c7a776d3c293
train_003.jsonl
1488705300
The evil Bumbershoot corporation produces clones for gruesome experiments in a vast underground lab. On one occasion, the corp cloned a boy Andryusha who was smarter than his comrades. Immediately Andryusha understood that something fishy was going on there. He rallied fellow clones to go on a feud against the evil corp, and they set out to find an exit from the lab. The corp had to reduce to destroy the lab complex.The lab can be pictured as a connected graph with n vertices and m edges. k clones of Andryusha start looking for an exit in some of the vertices. Each clone can traverse any edge once per second. Any number of clones are allowed to be at any vertex simultaneously. Each clone is allowed to stop looking at any time moment, but he must look at his starting vertex at least. The exit can be located at any vertex of the lab, hence each vertex must be visited by at least one clone.Each clone can visit at most vertices before the lab explodes.Your task is to choose starting vertices and searching routes for the clones. Each route can have at most vertices.
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.util.ArrayList; 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); OutputWriter out = new OutputWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { ArrayList<Integer> res = new ArrayList<>(); ArrayList<Integer>[] adj; void add(int val) { res.add(val); } void dfs(int cur, int prev) { add(cur); // int added = 0; for (int idx = 0; idx < adj[cur].size(); idx++) { int nxt = adj[cur].get(idx); if (nxt == prev) continue; // add(cur); // added++; dfs(nxt, cur); add(cur); } } public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.readInt(), m = in.readInt(), k = in.readInt(); adj = new ArrayList[n]; for (int i = 0; i < adj.length; i++) adj[i] = new ArrayList<>(); RecursiveIndependentSetSystem iss = new RecursiveIndependentSetSystem(n); for (int i = 0; i < m; i++) { int x = in.readInt() - 1; int y = in.readInt() - 1; if (x == y) continue; if (iss.join(x, y)) { adj[x].add(y); adj[y].add(x); } } int max = (2 * n + k - 1) / k; dfs(0, -1); int[] build = new int[max]; int ptr = 0; int printed = 0; for (int i = 0; i < res.size(); i++) { int val = res.get(i); build[ptr++] = val; if (ptr == build.length) { out.print(build.length + " "); for (int j = 0; j < ptr; j++) out.print(build[j] + 1 + " "); out.printLine(); ptr = 0; printed++; } else if (i == res.size() - 1) { out.print(ptr + " "); for (int j = 0; j < ptr; j++) out.print(build[j] + 1 + " "); out.printLine(); printed++; } } while (printed < k) { out.printLine(1, 1); printed++; } if (printed > k) throw new RuntimeException(); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } static interface IndependentSetSystem { public static interface Listener { public void joined(int joinedRoot, int root); } } 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() { writer.println(); } public void printLine(Object... objects) { print(objects); writer.println(); } public void close() { writer.close(); } } static class RecursiveIndependentSetSystem implements IndependentSetSystem { private final int[] color; private final int[] rank; private int setCount; private IndependentSetSystem.Listener listener; public RecursiveIndependentSetSystem(int size) { color = new int[size]; rank = new int[size]; for (int i = 0; i < size; i++) { color[i] = i; } setCount = size; } public RecursiveIndependentSetSystem(RecursiveIndependentSetSystem other) { color = other.color.clone(); rank = other.rank.clone(); setCount = other.setCount; } public boolean join(int first, int second) { first = get(first); second = get(second); if (first == second) { return false; } if (rank[first] < rank[second]) { int temp = first; first = second; second = temp; } else if (rank[first] == rank[second]) { rank[first]++; } setCount--; color[second] = first; if (listener != null) { listener.joined(second, first); } return true; } public int get(int index) { int start = index; while (color[index] != index) { index = color[index]; } while (start != index) { int next = color[start]; color[start] = index; start = next; } return index; } } }
Java
["3 2 1\n2 1\n3 1", "5 4 2\n1 2\n1 3\n1 4\n1 5"]
1 second
["3 2 1 3", "3 2 1 3\n3 4 1 5"]
NoteIn the first sample case there is only one clone who may visit vertices in order (2, 1, 3), which fits the constraint of 6 vertices per clone.In the second sample case the two clones can visited vertices in order (2, 1, 3) and (4, 1, 5), which fits the constraint of 5 vertices per clone.
Java 8
standard input
[ "graphs", "constructive algorithms", "dfs and similar", "trees", "brute force" ]
d32d638e5f90f0bfb7b7cec8e541cf7d
The first line contains three integers n, m, and k (1 ≤ n ≤ 2·105, n - 1 ≤ m ≤ 2·105, 1 ≤ k ≤ n) — the number of vertices and edges in the lab, and the number of clones. Each of the next m lines contains two integers xi and yi (1 ≤ xi, yi ≤ n) — indices of vertices connected by the respective edge. The graph is allowed to have self-loops and multiple edges. The graph is guaranteed to be connected.
2,100
You should print k lines. i-th of these lines must start with an integer ci () — the number of vertices visited by i-th clone, followed by ci integers — indices of vertices visited by this clone in the order of visiting. You have to print each vertex every time it is visited, regardless if it was visited earlier or not. It is guaranteed that a valid answer exists.
standard output
PASSED
f566ac48c5f48643c717cf6673df1cf1
train_003.jsonl
1488705300
The evil Bumbershoot corporation produces clones for gruesome experiments in a vast underground lab. On one occasion, the corp cloned a boy Andryusha who was smarter than his comrades. Immediately Andryusha understood that something fishy was going on there. He rallied fellow clones to go on a feud against the evil corp, and they set out to find an exit from the lab. The corp had to reduce to destroy the lab complex.The lab can be pictured as a connected graph with n vertices and m edges. k clones of Andryusha start looking for an exit in some of the vertices. Each clone can traverse any edge once per second. Any number of clones are allowed to be at any vertex simultaneously. Each clone is allowed to stop looking at any time moment, but he must look at his starting vertex at least. The exit can be located at any vertex of the lab, hence each vertex must be visited by at least one clone.Each clone can visit at most vertices before the lab explodes.Your task is to choose starting vertices and searching routes for the clones. Each route can have at most vertices.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.OutputStream; import java.io.IOException; import java.util.InputMismatchException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import java.io.Writer; import java.io.BufferedReader; 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); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { static List<Integer>[] edges; static boolean[] was; static int[] path; static int cn; static void dfs(int v) { was[v] = true; path[cn++] = v; for (int i = 0; i < edges[v].size(); i++) { int to = edges[v].get(i); if (was[to]) continue; dfs(to); path[cn++] = v; } } public void solve(int testNumber, FastScanner in, FastPrinter out) { int n = in.nextInt(); int m = in.nextInt(); int k = in.nextInt(); edges = new List[n]; for (int i = 0; i < n; i++) { edges[i] = new ArrayList<>(); } for (int i = 0; i < m; i++) { int a = in.nextInt() - 1; int b = in.nextInt() - 1; edges[a].add(b); edges[b].add(a); } was = new boolean[n]; cn = 0; path = new int[n * 2]; dfs(0); int one = (2 * n + k - 1) / k; int printed = 0; for (int i = 0; i < cn; i += one) { int from = i; int to = Math.min(cn, i + one); out.print(to - from); for (int j = from; j < to; j++) { out.print(" " + (path[j] + 1)); } out.println(); printed++; } if (printed > k) throw new AssertionError(); while (printed < k) { out.println("1 1"); ++printed; } } } static class FastPrinter extends PrintWriter { public FastPrinter(OutputStream out) { super(out); } public FastPrinter(Writer out) { super(out); } } static 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; } } } }
Java
["3 2 1\n2 1\n3 1", "5 4 2\n1 2\n1 3\n1 4\n1 5"]
1 second
["3 2 1 3", "3 2 1 3\n3 4 1 5"]
NoteIn the first sample case there is only one clone who may visit vertices in order (2, 1, 3), which fits the constraint of 6 vertices per clone.In the second sample case the two clones can visited vertices in order (2, 1, 3) and (4, 1, 5), which fits the constraint of 5 vertices per clone.
Java 8
standard input
[ "graphs", "constructive algorithms", "dfs and similar", "trees", "brute force" ]
d32d638e5f90f0bfb7b7cec8e541cf7d
The first line contains three integers n, m, and k (1 ≤ n ≤ 2·105, n - 1 ≤ m ≤ 2·105, 1 ≤ k ≤ n) — the number of vertices and edges in the lab, and the number of clones. Each of the next m lines contains two integers xi and yi (1 ≤ xi, yi ≤ n) — indices of vertices connected by the respective edge. The graph is allowed to have self-loops and multiple edges. The graph is guaranteed to be connected.
2,100
You should print k lines. i-th of these lines must start with an integer ci () — the number of vertices visited by i-th clone, followed by ci integers — indices of vertices visited by this clone in the order of visiting. You have to print each vertex every time it is visited, regardless if it was visited earlier or not. It is guaranteed that a valid answer exists.
standard output
PASSED
f6c9fdf898ef6c9d1a4b70302d453f2b
train_003.jsonl
1488705300
The evil Bumbershoot corporation produces clones for gruesome experiments in a vast underground lab. On one occasion, the corp cloned a boy Andryusha who was smarter than his comrades. Immediately Andryusha understood that something fishy was going on there. He rallied fellow clones to go on a feud against the evil corp, and they set out to find an exit from the lab. The corp had to reduce to destroy the lab complex.The lab can be pictured as a connected graph with n vertices and m edges. k clones of Andryusha start looking for an exit in some of the vertices. Each clone can traverse any edge once per second. Any number of clones are allowed to be at any vertex simultaneously. Each clone is allowed to stop looking at any time moment, but he must look at his starting vertex at least. The exit can be located at any vertex of the lab, hence each vertex must be visited by at least one clone.Each clone can visit at most vertices before the lab explodes.Your task is to choose starting vertices and searching routes for the clones. Each route can have at most vertices.
256 megabytes
import java.util.*; import java.io.*; public class C { List<Integer>[] graph; boolean[] vis; void go(int u) { vis[u] = true; addVertex(u); for (int t = 0; t < graph[u].size(); t++) { int v = graph[u].get(t); if (!vis[v]) { go(v); addVertex(u); } } } private void addVertex(int u) { result[lastClone].add(u); if (result[lastClone].size() == max) { lastClone++; } } List<Integer>[] result; int lastClone = 0; int max; void solve() { int n = in.nextInt(); graph = new List[n]; for (int i = 0; i < n; i++) { graph[i] = new ArrayList<>(); } int m = in.nextInt(); int k = in.nextInt(); for (int i = 0; i < m; i++) { int from = in.nextInt() - 1, to = in.nextInt() - 1; graph[from].add(to); graph[to].add(from); } max = (2 * n + k - 1) / k; vis = new boolean[n]; result = new List[k]; for (int i = 0; i < k; i++) { result[i] = new ArrayList<>(); } go(0); for (int i = 0; i < result.length; i++) { if (result[i].size() == 0) { result[i].add(0); } out.print(result[i].size()); for (int t : result[i]) { out.print(" " + (t + 1)); } out.println(); } } FastScanner in; PrintWriter out; void run() { in = new FastScanner(); out = new PrintWriter(System.out); solve(); out.close(); } class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } public FastScanner(String s) { try { br = new BufferedReader(new FileReader(s)); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public String nextToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(nextToken()); } public long nextLong() { return Long.parseLong(nextToken()); } public double nextDouble() { return Double.parseDouble(nextToken()); } } public static void main(String[] args) { new C().run(); } }
Java
["3 2 1\n2 1\n3 1", "5 4 2\n1 2\n1 3\n1 4\n1 5"]
1 second
["3 2 1 3", "3 2 1 3\n3 4 1 5"]
NoteIn the first sample case there is only one clone who may visit vertices in order (2, 1, 3), which fits the constraint of 6 vertices per clone.In the second sample case the two clones can visited vertices in order (2, 1, 3) and (4, 1, 5), which fits the constraint of 5 vertices per clone.
Java 8
standard input
[ "graphs", "constructive algorithms", "dfs and similar", "trees", "brute force" ]
d32d638e5f90f0bfb7b7cec8e541cf7d
The first line contains three integers n, m, and k (1 ≤ n ≤ 2·105, n - 1 ≤ m ≤ 2·105, 1 ≤ k ≤ n) — the number of vertices and edges in the lab, and the number of clones. Each of the next m lines contains two integers xi and yi (1 ≤ xi, yi ≤ n) — indices of vertices connected by the respective edge. The graph is allowed to have self-loops and multiple edges. The graph is guaranteed to be connected.
2,100
You should print k lines. i-th of these lines must start with an integer ci () — the number of vertices visited by i-th clone, followed by ci integers — indices of vertices visited by this clone in the order of visiting. You have to print each vertex every time it is visited, regardless if it was visited earlier or not. It is guaranteed that a valid answer exists.
standard output
PASSED
429897ce31f3ce992efb89fd8614093e
train_003.jsonl
1488705300
The evil Bumbershoot corporation produces clones for gruesome experiments in a vast underground lab. On one occasion, the corp cloned a boy Andryusha who was smarter than his comrades. Immediately Andryusha understood that something fishy was going on there. He rallied fellow clones to go on a feud against the evil corp, and they set out to find an exit from the lab. The corp had to reduce to destroy the lab complex.The lab can be pictured as a connected graph with n vertices and m edges. k clones of Andryusha start looking for an exit in some of the vertices. Each clone can traverse any edge once per second. Any number of clones are allowed to be at any vertex simultaneously. Each clone is allowed to stop looking at any time moment, but he must look at his starting vertex at least. The exit can be located at any vertex of the lab, hence each vertex must be visited by at least one clone.Each clone can visit at most vertices before the lab explodes.Your task is to choose starting vertices and searching routes for the clones. Each route can have at most vertices.
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; import java.util.concurrent.ConcurrentSkipListSet; public class Main { public static void main(String[] args) throws FileNotFoundException { ConsoleIO io = new ConsoleIO(new InputStreamReader(System.in), new PrintWriter(System.out)); // String test = "kittens"; // ConsoleIO io = new ConsoleIO(new FileReader("D:\\Comp\\GHC\\" + test + ".in"), new PrintWriter(new File("D:\\Comp\\GHC\\" + test + ".optimized"))); new Main(io).solve(); io.close(); } ConsoleIO io; Main(ConsoleIO io) { this.io = io; } long MOD = 1_000_000_007; int INF = Integer.MAX_VALUE / 2; List<List<Integer>> gr = new ArrayList<>(); public void solve() { int n = io.ri(); int m = io.ri(); int k = io.ri(); for(int i = 0;i<n;i++)gr.add(new ArrayList<>()); visit = new boolean[n]; for(int i = 0;i<m;i++) { int u = io.ri() - 1; int v = io.ri() - 1; gr.get(u).add(v); gr.get(v).add(u); } List<Integer> nodes = new ArrayList<>(); dfs(0,nodes); int idx = 0; int lim = (2*n+k-1)/k; StringBuilder sb = new StringBuilder(); for(int i = 0;i<k;i++){ int need = k-i-1; int have = Math.min(lim, nodes.size()-idx-need); sb.append(have); while(have>0) { sb.append(' '); sb.append(nodes.get(idx)+1); idx++; have--; } sb.append(System.lineSeparator()); } io.writeLine(sb.toString()); } boolean[] visit; void dfs(int cur, List<Integer> nodes){ visit[cur] = true; nodes.add(cur); List<Integer> ch = gr.get(cur); for(int i = 0;i<ch.size();i++){ int v = ch.get(i); if(!visit[v]){ dfs(v, nodes); nodes.add(cur); } } } } class ConsoleIO { BufferedReader br; PrintWriter out; public ConsoleIO(Reader reader, PrintWriter writer){br = new BufferedReader(reader);out = writer;} public void flush(){this.out.flush();} public void close(){this.out.close();} public void writeLine(String s) {this.out.println(s);} public void writeInt(int a) {this.out.print(a);this.out.print(' ');} public void writeWord(String s){ this.out.print(s); } public void writeIntArray(int[] a, int k, String separator) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < k; i++) { if (i > 0) sb.append(separator); sb.append(a[i]); } this.writeLine(sb.toString()); } public int read(char[] buf, int len){try {return br.read(buf,0,len);}catch (Exception ex){ return -1; }} public String readLine() {try {return br.readLine();}catch (Exception ex){ return "";}} public long[] readLongArray() { String[]n=this.readLine().trim().split("\\s+");long[]r=new long[n.length]; for(int i=0;i<n.length;i++)r[i]=Long.parseLong(n[i]); return r; } public int[] readIntArray() { String[]n=this.readLine().trim().split("\\s+");int[]r=new int[n.length]; for(int i=0;i<n.length;i++)r[i]=Integer.parseInt(n[i]); return r; } public int[] readIntArray(int n) { int[] res = new int[n]; char[] all = this.readLine().toCharArray(); int cur = 0;boolean have = false; int k = 0; boolean neg = false; for(int i = 0;i<all.length;i++){ if(all[i]>='0' && all[i]<='9'){ cur = cur*10+all[i]-'0'; have = true; }else if(all[i]=='-') { neg = true; } else if(have){ res[k++] = neg?-cur:cur; cur = 0; have = false; neg = false; } } if(have)res[k++] = neg?-cur:cur; return res; } public int ri() { try { int r = 0; boolean start = false; boolean neg = false; while (true) { int c = br.read(); if (c >= '0' && c <= '9') { r = r * 10 + c - '0'; start = true; } else if (!start && c == '-') { start = true; neg = true; } else if (start || c == -1) return neg ? -r : r; } } catch (Exception ex) { return -1; } } public long readLong() { try { long r = 0; boolean start = false; boolean neg = false; while (true) { int c = br.read(); if (c >= '0' && c <= '9') { r = r * 10 + c - '0'; start = true; } else if (!start && c == '-') { start = true; neg = true; } else if (start || c == -1) return neg ? -r : r; } } catch (Exception ex) { return -1; } } public String readWord() { try { boolean start = false; StringBuilder sb = new StringBuilder(); while (true) { int c = br.read(); if (c!= ' ' && c!= '\r' && c!='\n' && c!='\t') { sb.append((char)c); start = true; } else if (start || c == -1) return sb.toString(); } } catch (Exception ex) { return ""; } } public char readSymbol() { try { while (true) { int c = br.read(); if (c != ' ' && c != '\r' && c != '\n' && c != '\t') { return (char) c; } } } catch (Exception ex) { return 0; } } //public char readChar(){try {return (char)br.read();}catch (Exception ex){ return 0; }} }
Java
["3 2 1\n2 1\n3 1", "5 4 2\n1 2\n1 3\n1 4\n1 5"]
1 second
["3 2 1 3", "3 2 1 3\n3 4 1 5"]
NoteIn the first sample case there is only one clone who may visit vertices in order (2, 1, 3), which fits the constraint of 6 vertices per clone.In the second sample case the two clones can visited vertices in order (2, 1, 3) and (4, 1, 5), which fits the constraint of 5 vertices per clone.
Java 8
standard input
[ "graphs", "constructive algorithms", "dfs and similar", "trees", "brute force" ]
d32d638e5f90f0bfb7b7cec8e541cf7d
The first line contains three integers n, m, and k (1 ≤ n ≤ 2·105, n - 1 ≤ m ≤ 2·105, 1 ≤ k ≤ n) — the number of vertices and edges in the lab, and the number of clones. Each of the next m lines contains two integers xi and yi (1 ≤ xi, yi ≤ n) — indices of vertices connected by the respective edge. The graph is allowed to have self-loops and multiple edges. The graph is guaranteed to be connected.
2,100
You should print k lines. i-th of these lines must start with an integer ci () — the number of vertices visited by i-th clone, followed by ci integers — indices of vertices visited by this clone in the order of visiting. You have to print each vertex every time it is visited, regardless if it was visited earlier or not. It is guaranteed that a valid answer exists.
standard output
PASSED
c50d8d1ad4fed1e040b143255f8f7377
train_003.jsonl
1488705300
The evil Bumbershoot corporation produces clones for gruesome experiments in a vast underground lab. On one occasion, the corp cloned a boy Andryusha who was smarter than his comrades. Immediately Andryusha understood that something fishy was going on there. He rallied fellow clones to go on a feud against the evil corp, and they set out to find an exit from the lab. The corp had to reduce to destroy the lab complex.The lab can be pictured as a connected graph with n vertices and m edges. k clones of Andryusha start looking for an exit in some of the vertices. Each clone can traverse any edge once per second. Any number of clones are allowed to be at any vertex simultaneously. Each clone is allowed to stop looking at any time moment, but he must look at his starting vertex at least. The exit can be located at any vertex of the lab, hence each vertex must be visited by at least one clone.Each clone can visit at most vertices before the lab explodes.Your task is to choose starting vertices and searching routes for the clones. Each route can have at most vertices.
256 megabytes
// package codeforces.cf4xx.cf403.div1; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.InputMismatchException; import java.util.List; public class C { public static void main(String[] args) { InputReader in = new InputReader(System.in); PrintWriter out = new PrintWriter(System.out); int n = in.nextInt(); int m = in.nextInt(); int k = in.nextInt(); UnionFind uf = new UnionFind(n); int ei = 0; int[][] edges = new int[n-1][2]; for (int i = 0; i < m ; i++) { int a = in.nextInt()-1; int b = in.nextInt()-1; if (!uf.issame(a, b)) { uf.unite(a, b); edges[ei][0] = a; edges[ei][1] = b; ei++; } uf.unite(a, b); } graph = buildGraph(n, edges); order = new ArrayList<>(); dfs(0, -1); int per = (2*n+k-1)/k; int po = 0; for (int i = 0; i < k ; i++) { StringBuilder line = new StringBuilder(); int t = Math.min(po + per, order.size()); int cnt = 0; for (int j = po ; j < t ; j++) { line.append(' ').append(order.get(j)+1); cnt++; } if (cnt >= 1) { out.println(String.format("%d%s", cnt, line.toString())); } else { out.println("1 1"); } po = t; } out.flush(); } static int[][] graph; static List<Integer> order; static void dfs(int now, int par) { order.add(now); for (int to : graph[now]) { if (to == par) { continue; } dfs(to, now); order.add(now); } } static class UnionFind { int[] rank; int[] parent; int[] cnt; public UnionFind(int n) { rank = new int[n]; parent = new int[n]; cnt = new int[n]; for (int i = 0; i < n; i++) { parent[i] = i; cnt[i] = 1; } } public int find(int a) { if (parent[a] == a) { return a; } parent[a] = find(parent[a]); return parent[a]; } public void unite(int a, int b) { a = find(a); b = find(b); if (a == b) { return; } if (rank[a] < rank[b]) { parent[a] = b; cnt[b] += cnt[a]; cnt[a] = cnt[b]; } else { parent[b] = a; cnt[a] += cnt[b]; cnt[b] = cnt[a]; if (rank[a] == rank[b]) { rank[a]++; } } } public int groupCount(int a) { return cnt[find(a)]; } private boolean issame(int a, int b) { return find(a) == find(b); } } static int[][] buildGraph(int n, int[][] edges) { int m = edges.length; int[][] graph = new int[n][]; int[] deg = new int[n]; for (int i = 0 ; i < m ; i++) { int a = edges[i][0]; int b = edges[i][1]; deg[a]++; deg[b]++; } for (int i = 0 ; i < n ; i++) { graph[i] = new int[deg[i]]; } for (int i = 0 ; i < m ; i++) { int a = edges[i][0]; int b = edges[i][1]; graph[a][--deg[a]] = b; graph[b][--deg[b]] = a; } return graph; } 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; } private int[] nextInts(int n) { int[] ret = new int[n]; for (int i = 0; i < n; i++) { ret[i] = nextInt(); } return ret; } private int[][] nextIntTable(int n, int m) { int[][] ret = new int[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { ret[i][j] = nextInt(); } } return ret; } private long[] nextLongs(int n) { long[] ret = new long[n]; for (int i = 0; i < n; i++) { ret[i] = nextLong(); } return ret; } private long[][] nextLongTable(int n, int m) { long[][] ret = new long[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { ret[i][j] = nextLong(); } } return ret; } private double[] nextDoubles(int n) { double[] ret = new double[n]; for (int i = 0; i < n; i++) { ret[i] = nextDouble(); } return ret; } private int next() { 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 char nextChar() { int c = next(); while (isSpaceChar(c)) c = next(); if ('a' <= c && c <= 'z') { return (char) c; } if ('A' <= c && c <= 'Z') { return (char) c; } throw new InputMismatchException(); } public String nextToken() { int c = next(); while (isSpaceChar(c)) c = next(); StringBuilder res = new StringBuilder(); do { res.append((char) c); c = next(); } while (!isSpaceChar(c)); return res.toString(); } public int nextInt() { int c = next(); while (isSpaceChar(c)) c = next(); int sgn = 1; if (c == '-') { sgn = -1; c = next(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c-'0'; c = next(); } while (!isSpaceChar(c)); return res*sgn; } public long nextLong() { int c = next(); while (isSpaceChar(c)) c = next(); long sgn = 1; if (c == '-') { sgn = -1; c = next(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c-'0'; c = next(); } while (!isSpaceChar(c)); return res*sgn; } public double nextDouble() { return Double.valueOf(nextToken()); } public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } static void debug(Object... o) { System.err.println(Arrays.deepToString(o)); } }
Java
["3 2 1\n2 1\n3 1", "5 4 2\n1 2\n1 3\n1 4\n1 5"]
1 second
["3 2 1 3", "3 2 1 3\n3 4 1 5"]
NoteIn the first sample case there is only one clone who may visit vertices in order (2, 1, 3), which fits the constraint of 6 vertices per clone.In the second sample case the two clones can visited vertices in order (2, 1, 3) and (4, 1, 5), which fits the constraint of 5 vertices per clone.
Java 8
standard input
[ "graphs", "constructive algorithms", "dfs and similar", "trees", "brute force" ]
d32d638e5f90f0bfb7b7cec8e541cf7d
The first line contains three integers n, m, and k (1 ≤ n ≤ 2·105, n - 1 ≤ m ≤ 2·105, 1 ≤ k ≤ n) — the number of vertices and edges in the lab, and the number of clones. Each of the next m lines contains two integers xi and yi (1 ≤ xi, yi ≤ n) — indices of vertices connected by the respective edge. The graph is allowed to have self-loops and multiple edges. The graph is guaranteed to be connected.
2,100
You should print k lines. i-th of these lines must start with an integer ci () — the number of vertices visited by i-th clone, followed by ci integers — indices of vertices visited by this clone in the order of visiting. You have to print each vertex every time it is visited, regardless if it was visited earlier or not. It is guaranteed that a valid answer exists.
standard output
PASSED
e5fb8823003ed95bf0f6045a5aacec65
train_003.jsonl
1488705300
The evil Bumbershoot corporation produces clones for gruesome experiments in a vast underground lab. On one occasion, the corp cloned a boy Andryusha who was smarter than his comrades. Immediately Andryusha understood that something fishy was going on there. He rallied fellow clones to go on a feud against the evil corp, and they set out to find an exit from the lab. The corp had to reduce to destroy the lab complex.The lab can be pictured as a connected graph with n vertices and m edges. k clones of Andryusha start looking for an exit in some of the vertices. Each clone can traverse any edge once per second. Any number of clones are allowed to be at any vertex simultaneously. Each clone is allowed to stop looking at any time moment, but he must look at his starting vertex at least. The exit can be located at any vertex of the lab, hence each vertex must be visited by at least one clone.Each clone can visit at most vertices before the lab explodes.Your task is to choose starting vertices and searching routes for the clones. Each route can have at most vertices.
256 megabytes
/* Did I say something wrong? Did you hear what I was thinking? Did I talk way too long when I told you all my feelings that night? Is it you? Is it me? Did you find somebody better? Someone who isn't me, 'cause I know that I was never your type Never really your type Overthinking's got me drinking Messing with my head, whoa Tell me what you hate about me Whatever it is, I'm sorry Yeah, yeah, yeah, yeah, yeah, yeah I know I can be dramatic But everybody said we had it Yeah, yeah, yeah, yeah, yeah, yeah I'm coming to terms with a broken heart I guess that sometimes good things fall apart When you said it was real, guess I really did believe you Did you fake how you feel when we parked down by the river that night? That night? That night when we fogged up the windows in your best friend's car 'Cause we couldn't leave the windows down in December Whoa Tell me what you hate about me Whatever it is, I'm sorry Yeah, yeah, yeah, yeah, yeah, yeah I know I can be dramatic But everybody said we had it Yeah, yeah, yeah, yeah, yeah, yeah I'm coming to terms with a broken heart I guess that sometimes good things fall apart Overthinking's got me drinking Messing with my head, oh Tell me what you hate about me (about me) Whatever it is, I'm sorry (oh, I'm sorry) Yeah, yeah, yeah (oh, I'm sorry), yeah, yeah, yeah I know I can be dramatic (I know I can be) Everybody said we had it Yeah, yeah, yeah, yeah, yeah, yeah I'm coming to terms with a broken heart I guess that sometimes good things fall apart */ import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Scanner; import java.util.StringTokenizer; import java.util.*; import java.math.*; public class Main { static ArrayList<Integer> a[]; static boolean vis[]=new boolean[2000009]; static int time=0; static int ans[]=new int[2000009]; 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 dfs( int index) { vis[index]=true; ans[time]=index; time++; for( int i=0;i<a[index].size();i++) { if(!vis[a[index].get(i)]) { dfs(a[index].get(i)); ans[time]=index; time++; } } } public static void main(String[] args) { FastReader sc=new FastReader(); int n=sc.nextInt(); int m=sc.nextInt(); int k=sc.nextInt(); a=new ArrayList[n+1]; for( int i=1;i<=n;i++) { a[i]=new ArrayList<>(); } for( int i=0;i<m;i++) { int u=sc.nextInt(); int v=sc.nextInt(); a[u].add(v); a[v].add(u); } dfs(1); int max=(int)Math.ceil((double)(2*n)/(double)k); int g=0; StringBuilder sb=new StringBuilder(); for( int i=0;i<k;i++) { int size_for_cur=Math.min(max,time-g); if(size_for_cur==0) { size_for_cur++; g--; } sb.append(size_for_cur); sb.append(" "); for( int j=0;j<size_for_cur;j++) { sb.append(ans[g]); g++; sb.append(" "); } sb.append("\n"); } System.out.println(sb.toString()); } }
Java
["3 2 1\n2 1\n3 1", "5 4 2\n1 2\n1 3\n1 4\n1 5"]
1 second
["3 2 1 3", "3 2 1 3\n3 4 1 5"]
NoteIn the first sample case there is only one clone who may visit vertices in order (2, 1, 3), which fits the constraint of 6 vertices per clone.In the second sample case the two clones can visited vertices in order (2, 1, 3) and (4, 1, 5), which fits the constraint of 5 vertices per clone.
Java 8
standard input
[ "graphs", "constructive algorithms", "dfs and similar", "trees", "brute force" ]
d32d638e5f90f0bfb7b7cec8e541cf7d
The first line contains three integers n, m, and k (1 ≤ n ≤ 2·105, n - 1 ≤ m ≤ 2·105, 1 ≤ k ≤ n) — the number of vertices and edges in the lab, and the number of clones. Each of the next m lines contains two integers xi and yi (1 ≤ xi, yi ≤ n) — indices of vertices connected by the respective edge. The graph is allowed to have self-loops and multiple edges. The graph is guaranteed to be connected.
2,100
You should print k lines. i-th of these lines must start with an integer ci () — the number of vertices visited by i-th clone, followed by ci integers — indices of vertices visited by this clone in the order of visiting. You have to print each vertex every time it is visited, regardless if it was visited earlier or not. It is guaranteed that a valid answer exists.
standard output
PASSED
39f5ebbd72830f2d253ce4baaaea5a22
train_003.jsonl
1488705300
The evil Bumbershoot corporation produces clones for gruesome experiments in a vast underground lab. On one occasion, the corp cloned a boy Andryusha who was smarter than his comrades. Immediately Andryusha understood that something fishy was going on there. He rallied fellow clones to go on a feud against the evil corp, and they set out to find an exit from the lab. The corp had to reduce to destroy the lab complex.The lab can be pictured as a connected graph with n vertices and m edges. k clones of Andryusha start looking for an exit in some of the vertices. Each clone can traverse any edge once per second. Any number of clones are allowed to be at any vertex simultaneously. Each clone is allowed to stop looking at any time moment, but he must look at his starting vertex at least. The exit can be located at any vertex of the lab, hence each vertex must be visited by at least one clone.Each clone can visit at most vertices before the lab explodes.Your task is to choose starting vertices and searching routes for the clones. Each route can have at most vertices.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Set; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.StringTokenizer; import java.io.BufferedReader; 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; FastScanner in = new FastScanner(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { public void solve(int testNumber, FastScanner in, PrintWriter out) { int n = in.nextInt(); int m = in.nextInt(); int k = in.nextInt(); Set<Integer>[] adj = new Set[n]; for (int i = 0; i < n; i++) { adj[i] = new HashSet<>(); } for (int i = 0; i < m; i++) { int a = in.nextInt() - 1; int b = in.nextInt() - 1; if (a != b) { adj[a].add(b); adj[b].add(a); } } List<Integer> path = new ArrayList<>(); boolean[] was = new boolean[n]; dfs(0, was, adj, path); int each = (2 * n + k - 1) / k; int ptr = 0; for (int step = 0; step < k; step++) { if (ptr == path.size()) { out.println("1 1"); continue; } out.print(Math.min(each, path.size() - ptr)); for (int i = 0; i < each; i++) { if (ptr == path.size()) { break; } out.print(" "); out.print(path.get(ptr) + 1); ++ptr; } out.println(); } } private void dfs(int v, boolean[] was, Set<Integer>[] adj, List<Integer> path) { path.add(v); was[v] = true; for (int u : adj[v]) { if (was[u]) { continue; } dfs(u, was, adj, path); path.add(v); } } } static class FastScanner { private BufferedReader in; private StringTokenizer st; public FastScanner(InputStream stream) { in = new BufferedReader(new InputStreamReader(stream)); } public String next() { 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 nextInt() { return Integer.parseInt(next()); } } }
Java
["3 2 1\n2 1\n3 1", "5 4 2\n1 2\n1 3\n1 4\n1 5"]
1 second
["3 2 1 3", "3 2 1 3\n3 4 1 5"]
NoteIn the first sample case there is only one clone who may visit vertices in order (2, 1, 3), which fits the constraint of 6 vertices per clone.In the second sample case the two clones can visited vertices in order (2, 1, 3) and (4, 1, 5), which fits the constraint of 5 vertices per clone.
Java 8
standard input
[ "graphs", "constructive algorithms", "dfs and similar", "trees", "brute force" ]
d32d638e5f90f0bfb7b7cec8e541cf7d
The first line contains three integers n, m, and k (1 ≤ n ≤ 2·105, n - 1 ≤ m ≤ 2·105, 1 ≤ k ≤ n) — the number of vertices and edges in the lab, and the number of clones. Each of the next m lines contains two integers xi and yi (1 ≤ xi, yi ≤ n) — indices of vertices connected by the respective edge. The graph is allowed to have self-loops and multiple edges. The graph is guaranteed to be connected.
2,100
You should print k lines. i-th of these lines must start with an integer ci () — the number of vertices visited by i-th clone, followed by ci integers — indices of vertices visited by this clone in the order of visiting. You have to print each vertex every time it is visited, regardless if it was visited earlier or not. It is guaranteed that a valid answer exists.
standard output
PASSED
d38818a00f8bdbc914073abf2abe564a
train_003.jsonl
1488705300
The evil Bumbershoot corporation produces clones for gruesome experiments in a vast underground lab. On one occasion, the corp cloned a boy Andryusha who was smarter than his comrades. Immediately Andryusha understood that something fishy was going on there. He rallied fellow clones to go on a feud against the evil corp, and they set out to find an exit from the lab. The corp had to reduce to destroy the lab complex.The lab can be pictured as a connected graph with n vertices and m edges. k clones of Andryusha start looking for an exit in some of the vertices. Each clone can traverse any edge once per second. Any number of clones are allowed to be at any vertex simultaneously. Each clone is allowed to stop looking at any time moment, but he must look at his starting vertex at least. The exit can be located at any vertex of the lab, hence each vertex must be visited by at least one clone.Each clone can visit at most vertices before the lab explodes.Your task is to choose starting vertices and searching routes for the clones. Each route can have at most vertices.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Set; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.StringTokenizer; import java.io.BufferedReader; 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; FastScanner in = new FastScanner(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { public void solve(int testNumber, FastScanner in, PrintWriter out) { int n = in.nextInt(); int m = in.nextInt(); int k = in.nextInt(); int dummyA = -1; int dummyB = -1; Set<Integer>[] adj = new Set[n]; for (int i = 0; i < n; i++) { adj[i] = new HashSet<>(); } for (int i = 0; i < m; i++) { int a = in.nextInt() - 1; int b = in.nextInt() - 1; dummyA = a; dummyB = b; if (a != b) { adj[a].add(b); adj[b].add(a); } } List<Integer> path = new ArrayList<>(); boolean[] was = new boolean[n]; dfs(0, was, adj, path); int each = (2 * n + k - 1) / k; int ptr = 0; for (int step = 0; step < k; step++) { if (ptr == path.size()) { out.println("2 " + (dummyA + 1) + " " + (dummyB + 1)); continue; } out.print(Math.min(each, path.size() - ptr)); for (int i = 0; i < each; i++) { if (ptr == path.size()) { break; } out.print(" "); out.print(path.get(ptr) + 1); ++ptr; } out.println(); } } private void dfs(int v, boolean[] was, Set<Integer>[] adj, List<Integer> path) { path.add(v); was[v] = true; for (int u : adj[v]) { if (was[u]) { continue; } dfs(u, was, adj, path); path.add(v); } } } static class FastScanner { private BufferedReader in; private StringTokenizer st; public FastScanner(InputStream stream) { in = new BufferedReader(new InputStreamReader(stream)); } public String next() { 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 nextInt() { return Integer.parseInt(next()); } } }
Java
["3 2 1\n2 1\n3 1", "5 4 2\n1 2\n1 3\n1 4\n1 5"]
1 second
["3 2 1 3", "3 2 1 3\n3 4 1 5"]
NoteIn the first sample case there is only one clone who may visit vertices in order (2, 1, 3), which fits the constraint of 6 vertices per clone.In the second sample case the two clones can visited vertices in order (2, 1, 3) and (4, 1, 5), which fits the constraint of 5 vertices per clone.
Java 8
standard input
[ "graphs", "constructive algorithms", "dfs and similar", "trees", "brute force" ]
d32d638e5f90f0bfb7b7cec8e541cf7d
The first line contains three integers n, m, and k (1 ≤ n ≤ 2·105, n - 1 ≤ m ≤ 2·105, 1 ≤ k ≤ n) — the number of vertices and edges in the lab, and the number of clones. Each of the next m lines contains two integers xi and yi (1 ≤ xi, yi ≤ n) — indices of vertices connected by the respective edge. The graph is allowed to have self-loops and multiple edges. The graph is guaranteed to be connected.
2,100
You should print k lines. i-th of these lines must start with an integer ci () — the number of vertices visited by i-th clone, followed by ci integers — indices of vertices visited by this clone in the order of visiting. You have to print each vertex every time it is visited, regardless if it was visited earlier or not. It is guaranteed that a valid answer exists.
standard output
PASSED
1791b88d6fc9aa8af80d3801f086cb76
train_003.jsonl
1488705300
The evil Bumbershoot corporation produces clones for gruesome experiments in a vast underground lab. On one occasion, the corp cloned a boy Andryusha who was smarter than his comrades. Immediately Andryusha understood that something fishy was going on there. He rallied fellow clones to go on a feud against the evil corp, and they set out to find an exit from the lab. The corp had to reduce to destroy the lab complex.The lab can be pictured as a connected graph with n vertices and m edges. k clones of Andryusha start looking for an exit in some of the vertices. Each clone can traverse any edge once per second. Any number of clones are allowed to be at any vertex simultaneously. Each clone is allowed to stop looking at any time moment, but he must look at his starting vertex at least. The exit can be located at any vertex of the lab, hence each vertex must be visited by at least one clone.Each clone can visit at most vertices before the lab explodes.Your task is to choose starting vertices and searching routes for the clones. Each route can have at most vertices.
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.List; import java.io.BufferedWriter; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.InputMismatchException; import java.io.IOException; import java.util.ArrayList; 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); _781C solver = new _781C(); solver.solve(1, in, out); out.close(); } static class _781C { public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.nextInt(); int m = in.nextInt(); int k = in.nextInt(); List[] g = new List[n]; for (int i = 0; i < n; i++) g[i] = new ArrayList(); for (int i = 0; i < m; i++) { int u = in.nextInt() - 1; int v = in.nextInt() - 1; g[u].add(v); g[v].add(u); } int size = (2 * n + k - 1) / k; EulerTourTree eulerTour = new EulerTourTree(g, n); List<Integer> et = eulerTour.eulerTour(); int ci = 0; for (int i = 0; i < k; i++) { if (ci + size <= et.size()) { out.print(size + " "); for (int j = ci; j < ci + size; j++) { out.print((et.get(j) + 1) + " "); } ci = ci + size; out.println(); } else { if (ci < et.size()) { out.print((et.size() - ci) + " "); for (int j = ci; j < et.size(); j++) { out.print((et.get(j) + 1) + " "); } ci = et.size(); out.println(); } else { out.print(1 + " "); out.print(1); out.println(); } } } } class EulerTourTree { List[] g; int n; List<Integer> eulerTour; boolean[] vis; public EulerTourTree(List[] g, int n) { this.g = g; this.n = n; this.vis = new boolean[n]; this.eulerTour = new ArrayList<>(); } List<Integer> eulerTour() { dfs(0, -1); return eulerTour; } void dfs(int u, int p) { vis[u] = true; eulerTour.add(u); for (Integer v : (List<Integer>) g[u]) { if (v != p && !vis[v]) { dfs(v, u); eulerTour.add(u); } } } } } 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); } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) { writer.print(' '); } writer.print(objects[i]); } } public void println() { writer.println(); } public void close() { writer.close(); } public void print(int i) { writer.print(i); } } }
Java
["3 2 1\n2 1\n3 1", "5 4 2\n1 2\n1 3\n1 4\n1 5"]
1 second
["3 2 1 3", "3 2 1 3\n3 4 1 5"]
NoteIn the first sample case there is only one clone who may visit vertices in order (2, 1, 3), which fits the constraint of 6 vertices per clone.In the second sample case the two clones can visited vertices in order (2, 1, 3) and (4, 1, 5), which fits the constraint of 5 vertices per clone.
Java 8
standard input
[ "graphs", "constructive algorithms", "dfs and similar", "trees", "brute force" ]
d32d638e5f90f0bfb7b7cec8e541cf7d
The first line contains three integers n, m, and k (1 ≤ n ≤ 2·105, n - 1 ≤ m ≤ 2·105, 1 ≤ k ≤ n) — the number of vertices and edges in the lab, and the number of clones. Each of the next m lines contains two integers xi and yi (1 ≤ xi, yi ≤ n) — indices of vertices connected by the respective edge. The graph is allowed to have self-loops and multiple edges. The graph is guaranteed to be connected.
2,100
You should print k lines. i-th of these lines must start with an integer ci () — the number of vertices visited by i-th clone, followed by ci integers — indices of vertices visited by this clone in the order of visiting. You have to print each vertex every time it is visited, regardless if it was visited earlier or not. It is guaranteed that a valid answer exists.
standard output
PASSED
9838edfbff827c59c89901aca5082055
train_003.jsonl
1488705300
The evil Bumbershoot corporation produces clones for gruesome experiments in a vast underground lab. On one occasion, the corp cloned a boy Andryusha who was smarter than his comrades. Immediately Andryusha understood that something fishy was going on there. He rallied fellow clones to go on a feud against the evil corp, and they set out to find an exit from the lab. The corp had to reduce to destroy the lab complex.The lab can be pictured as a connected graph with n vertices and m edges. k clones of Andryusha start looking for an exit in some of the vertices. Each clone can traverse any edge once per second. Any number of clones are allowed to be at any vertex simultaneously. Each clone is allowed to stop looking at any time moment, but he must look at his starting vertex at least. The exit can be located at any vertex of the lab, hence each vertex must be visited by at least one clone.Each clone can visit at most vertices before the lab explodes.Your task is to choose starting vertices and searching routes for the clones. Each route can have at most vertices.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.List; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; import java.util.ArrayList; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { int totalLines; int curLine; int maxLine; Vertex last; PrintWriter out; public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int m = in.nextInt(); int k = in.nextInt(); Vertex[] vs = new Vertex[n]; for (int i = 0; i < n; ++i) { vs[i] = new Vertex(i + 1); } for (int i = 0; i < m; ++i) { Vertex a = vs[in.nextInt() - 1]; Vertex b = vs[in.nextInt() - 1]; a.adj.add(b); b.adj.add(a); } if (n == 1) { for (int i = 0; i < k; ++i) { out.println("1 1"); } return; } totalLines = 0; curLine = 0; maxLine = (2 * n + k - 1) / k; this.out = out; vs[0].dfs(); while (curLine > 0) { last = last.adj.get(0); last.print(); } if (totalLines > k) throw new RuntimeException(); for (int i = totalLines; i < k; ++i) { out.println("1 1"); } } class Vertex { int index; List<Vertex> adj = new ArrayList<>(); boolean mark = false; public Vertex(int index) { this.index = index; } public void print() { if (curLine > 0) out.print(" "); else out.print(maxLine + " "); out.print(index); last = this; ++curLine; if (curLine == maxLine) { ++totalLines; curLine = 0; out.println(); last = null; } } public void dfs() { mark = true; print(); for (Vertex v : adj) { if (v.mark) continue; v.dfs(); print(); } } } } 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
["3 2 1\n2 1\n3 1", "5 4 2\n1 2\n1 3\n1 4\n1 5"]
1 second
["3 2 1 3", "3 2 1 3\n3 4 1 5"]
NoteIn the first sample case there is only one clone who may visit vertices in order (2, 1, 3), which fits the constraint of 6 vertices per clone.In the second sample case the two clones can visited vertices in order (2, 1, 3) and (4, 1, 5), which fits the constraint of 5 vertices per clone.
Java 8
standard input
[ "graphs", "constructive algorithms", "dfs and similar", "trees", "brute force" ]
d32d638e5f90f0bfb7b7cec8e541cf7d
The first line contains three integers n, m, and k (1 ≤ n ≤ 2·105, n - 1 ≤ m ≤ 2·105, 1 ≤ k ≤ n) — the number of vertices and edges in the lab, and the number of clones. Each of the next m lines contains two integers xi and yi (1 ≤ xi, yi ≤ n) — indices of vertices connected by the respective edge. The graph is allowed to have self-loops and multiple edges. The graph is guaranteed to be connected.
2,100
You should print k lines. i-th of these lines must start with an integer ci () — the number of vertices visited by i-th clone, followed by ci integers — indices of vertices visited by this clone in the order of visiting. You have to print each vertex every time it is visited, regardless if it was visited earlier or not. It is guaranteed that a valid answer exists.
standard output
PASSED
ae5de5899832cf50771af94e77fc747e
train_003.jsonl
1488705300
The evil Bumbershoot corporation produces clones for gruesome experiments in a vast underground lab. On one occasion, the corp cloned a boy Andryusha who was smarter than his comrades. Immediately Andryusha understood that something fishy was going on there. He rallied fellow clones to go on a feud against the evil corp, and they set out to find an exit from the lab. The corp had to reduce to destroy the lab complex.The lab can be pictured as a connected graph with n vertices and m edges. k clones of Andryusha start looking for an exit in some of the vertices. Each clone can traverse any edge once per second. Any number of clones are allowed to be at any vertex simultaneously. Each clone is allowed to stop looking at any time moment, but he must look at his starting vertex at least. The exit can be located at any vertex of the lab, hence each vertex must be visited by at least one clone.Each clone can visit at most vertices before the lab explodes.Your task is to choose starting vertices and searching routes for the clones. Each route can have at most vertices.
256 megabytes
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.HashSet; import java.util.LinkedList; import java.util.Set; import java.util.StringTokenizer; public class R403D1P3 { public static void main(String[] args) throws Exception { BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); PrintWriter writer = new PrintWriter(new BufferedWriter( new OutputStreamWriter(System.out))); StringTokenizer st = new StringTokenizer(bf.readLine()); int n = Integer.parseInt(st.nextToken()); int m = Integer.parseInt(st.nextToken()); int k = Integer.parseInt(st.nextToken()); // n = 200000; // m = 199999; // k = 1276; // n = 10; // m = 20; LinkedList<Integer>[] adjList = new LinkedList[n]; for (int i = 0; i < n; i++) { adjList[i] = new LinkedList<Integer>(); } for (int i = 0; i < m; i++) { st = new StringTokenizer(bf.readLine()); int u = Integer.parseInt(st.nextToken()) - 1; int v = Integer.parseInt(st.nextToken()) - 1; if (u == v) { continue; } adjList[u].add(v); adjList[v].add(u); } // for (int i = 0; i < m; i++) { // int u, v; // if (i < n - 1) { // u = i; // v = i + 1; // } else { // u = (int) (Math.random() * n); // v = (int) (Math.random() * n); // } // if (u == v) { // continue; // } // adjList[u].add(v); // adjList[v].add(u); // } // System.out.println(Arrays.toString(adjList)); // construct st LinkedList<Integer>[] treeAdjList = new LinkedList[n]; for (int i = 0; i < n; i++) { treeAdjList[i] = new LinkedList<Integer>(); } LinkedList<int[]> queue = new LinkedList<>(); boolean[] added = new boolean[n]; added[0] = true; for (Integer adj : adjList[0]) { if (!added[adj]) { queue.add(new int[] { 0, adj }); added[adj] = true; } } while (!queue.isEmpty()) { int[] cur = queue.removeFirst(); // if (added[cur[1]]) { // continue; // } // // added[cur[1]] = true; treeAdjList[cur[0]].add(cur[1]); treeAdjList[cur[1]].add(cur[0]); for (Integer adj : adjList[cur[1]]) { if (!added[adj]) { queue.add(new int[] { cur[1], adj }); added[adj] = true; } } } // System.out.println(Arrays.toString(treeAdjList)); LinkedList<Integer> route = new LinkedList<>(); dfs(0, route, -1, treeAdjList); int numAssigned = 0; // System.out.println("route size: " + route.size()); // System.out.println("max size: " + ((2 * n + k - 1) / k) * k); while (route.size() > 0) { int curCount = Math.min(route.size(), (2 * n + k - 1) / k); writer.print("" + curCount); for (int i = 0; i < curCount; i++) { writer.print(" " + (route.removeFirst() + 1)); } writer.println(); numAssigned++; } for (; numAssigned < k; numAssigned++) { writer.println("1 1"); } writer.close(); } private static void dfs(int i, LinkedList<Integer> route, int parent, LinkedList<Integer>[] treeAdjList) { route.add(i); for (Integer adj : treeAdjList[i]) { if (adj != parent) { dfs(adj, route, i, treeAdjList); route.add(i); } } } }
Java
["3 2 1\n2 1\n3 1", "5 4 2\n1 2\n1 3\n1 4\n1 5"]
1 second
["3 2 1 3", "3 2 1 3\n3 4 1 5"]
NoteIn the first sample case there is only one clone who may visit vertices in order (2, 1, 3), which fits the constraint of 6 vertices per clone.In the second sample case the two clones can visited vertices in order (2, 1, 3) and (4, 1, 5), which fits the constraint of 5 vertices per clone.
Java 8
standard input
[ "graphs", "constructive algorithms", "dfs and similar", "trees", "brute force" ]
d32d638e5f90f0bfb7b7cec8e541cf7d
The first line contains three integers n, m, and k (1 ≤ n ≤ 2·105, n - 1 ≤ m ≤ 2·105, 1 ≤ k ≤ n) — the number of vertices and edges in the lab, and the number of clones. Each of the next m lines contains two integers xi and yi (1 ≤ xi, yi ≤ n) — indices of vertices connected by the respective edge. The graph is allowed to have self-loops and multiple edges. The graph is guaranteed to be connected.
2,100
You should print k lines. i-th of these lines must start with an integer ci () — the number of vertices visited by i-th clone, followed by ci integers — indices of vertices visited by this clone in the order of visiting. You have to print each vertex every time it is visited, regardless if it was visited earlier or not. It is guaranteed that a valid answer exists.
standard output
PASSED
18b3305ea757fc038a93aa057a697d0f
train_003.jsonl
1488705300
The evil Bumbershoot corporation produces clones for gruesome experiments in a vast underground lab. On one occasion, the corp cloned a boy Andryusha who was smarter than his comrades. Immediately Andryusha understood that something fishy was going on there. He rallied fellow clones to go on a feud against the evil corp, and they set out to find an exit from the lab. The corp had to reduce to destroy the lab complex.The lab can be pictured as a connected graph with n vertices and m edges. k clones of Andryusha start looking for an exit in some of the vertices. Each clone can traverse any edge once per second. Any number of clones are allowed to be at any vertex simultaneously. Each clone is allowed to stop looking at any time moment, but he must look at his starting vertex at least. The exit can be located at any vertex of the lab, hence each vertex must be visited by at least one clone.Each clone can visit at most vertices before the lab explodes.Your task is to choose starting vertices and searching routes for the clones. Each route can have at most vertices.
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.util.InputMismatchException; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.stream.Stream; 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) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { List<Integer>[] graph; public int[] ord; public boolean[] vis; public int idx; public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.nextInt(), m = in.nextInt(), k = in.nextInt(); graph = Stream.generate(ArrayList::new).limit(n).toArray(List[]::new); for (int i = 0; i < m; i++) { int a = in.nextInt() - 1, b = in.nextInt() - 1; graph[a].add(b); graph[b].add(a); } ord = new int[2 * n]; vis = new boolean[n]; idx = 0; dfs(0); int lim = (2 * n + k - 1) / k; int cur = 0; for (int i = 0; i < k; i++) { ArrayList<Integer> route = new ArrayList<>(); if (cur >= idx) { route.add(1); } else { for (int j = cur; j < idx && j < cur + lim; j++) { route.add(ord[j] + 1); } cur += lim; } out.print(route.size() + " "); out.println(route.toArray(new Integer[route.size()])); } } public void dfs(int node) { ord[idx++] = node; vis[node] = true; for (int next : graph[node]) { if (!vis[next]) { dfs(next); ord[idx++] = node; } } } } 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 (this.numChars == -1) { throw new InputMismatchException(); } else { if (this.curChar >= this.numChars) { this.curChar = 0; try { this.numChars = this.stream.read(this.buf); } catch (IOException var2) { throw new InputMismatchException(); } if (this.numChars <= 0) { return -1; } } return this.buf[this.curChar++]; } } public int nextInt() { int c; for (c = this.read(); isSpaceChar(c); c = this.read()) { ; } byte sgn = 1; if (c == 45) { sgn = -1; c = this.read(); } int res = 0; while (c >= 48 && c <= 57) { res *= 10; res += c - 48; c = this.read(); if (isSpaceChar(c)) { return res * sgn; } } throw new InputMismatchException(); } public static boolean isSpaceChar(int c) { return c == 32 || c == 10 || c == 13 || c == 9 || c == -1; } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) { writer.print(' '); } writer.print(objects[i]); } } public void println(Object... objects) { print(objects); writer.println(); } public void close() { writer.close(); } } }
Java
["3 2 1\n2 1\n3 1", "5 4 2\n1 2\n1 3\n1 4\n1 5"]
1 second
["3 2 1 3", "3 2 1 3\n3 4 1 5"]
NoteIn the first sample case there is only one clone who may visit vertices in order (2, 1, 3), which fits the constraint of 6 vertices per clone.In the second sample case the two clones can visited vertices in order (2, 1, 3) and (4, 1, 5), which fits the constraint of 5 vertices per clone.
Java 8
standard input
[ "graphs", "constructive algorithms", "dfs and similar", "trees", "brute force" ]
d32d638e5f90f0bfb7b7cec8e541cf7d
The first line contains three integers n, m, and k (1 ≤ n ≤ 2·105, n - 1 ≤ m ≤ 2·105, 1 ≤ k ≤ n) — the number of vertices and edges in the lab, and the number of clones. Each of the next m lines contains two integers xi and yi (1 ≤ xi, yi ≤ n) — indices of vertices connected by the respective edge. The graph is allowed to have self-loops and multiple edges. The graph is guaranteed to be connected.
2,100
You should print k lines. i-th of these lines must start with an integer ci () — the number of vertices visited by i-th clone, followed by ci integers — indices of vertices visited by this clone in the order of visiting. You have to print each vertex every time it is visited, regardless if it was visited earlier or not. It is guaranteed that a valid answer exists.
standard output
PASSED
7c935d41c0c6567cb911ef48cd5c6c43
train_003.jsonl
1488705300
The evil Bumbershoot corporation produces clones for gruesome experiments in a vast underground lab. On one occasion, the corp cloned a boy Andryusha who was smarter than his comrades. Immediately Andryusha understood that something fishy was going on there. He rallied fellow clones to go on a feud against the evil corp, and they set out to find an exit from the lab. The corp had to reduce to destroy the lab complex.The lab can be pictured as a connected graph with n vertices and m edges. k clones of Andryusha start looking for an exit in some of the vertices. Each clone can traverse any edge once per second. Any number of clones are allowed to be at any vertex simultaneously. Each clone is allowed to stop looking at any time moment, but he must look at his starting vertex at least. The exit can be located at any vertex of the lab, hence each vertex must be visited by at least one clone.Each clone can visit at most vertices before the lab explodes.Your task is to choose starting vertices and searching routes for the clones. Each route can have at most vertices.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.List; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; import java.util.ArrayList; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { int totalLines; int curLine; int maxLine; Vertex last; PrintWriter out; public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int m = in.nextInt(); int k = in.nextInt(); Vertex[] vs = new Vertex[n]; for (int i = 0; i < n; ++i) { vs[i] = new Vertex(i + 1); } for (int i = 0; i < m; ++i) { Vertex a = vs[in.nextInt() - 1]; Vertex b = vs[in.nextInt() - 1]; a.adj.add(b); b.adj.add(a); } if (n == 1) { for (int i = 0; i < k; ++i) { out.println("1 1"); } return; } totalLines = 0; curLine = 0; maxLine = (2 * n + k - 1) / k; this.out = out; vs[0].dfs(); while (curLine > 0) { last = last.adj.get(0); last.print(); } if (totalLines > k) throw new RuntimeException(); for (int i = totalLines; i < k; ++i) { out.println("1 1"); } } class Vertex { int index; List<Vertex> adj = new ArrayList<>(); boolean mark = false; public Vertex(int index) { this.index = index; } public void print() { if (curLine > 0) out.print(" "); else out.print(maxLine + " "); out.print(index); last = this; ++curLine; if (curLine == maxLine) { ++totalLines; curLine = 0; out.println(); last = null; } } public void dfs() { mark = true; print(); for (Vertex v : adj) { if (v.mark) continue; v.dfs(); print(); } } } } 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
["3 2 1\n2 1\n3 1", "5 4 2\n1 2\n1 3\n1 4\n1 5"]
1 second
["3 2 1 3", "3 2 1 3\n3 4 1 5"]
NoteIn the first sample case there is only one clone who may visit vertices in order (2, 1, 3), which fits the constraint of 6 vertices per clone.In the second sample case the two clones can visited vertices in order (2, 1, 3) and (4, 1, 5), which fits the constraint of 5 vertices per clone.
Java 8
standard input
[ "graphs", "constructive algorithms", "dfs and similar", "trees", "brute force" ]
d32d638e5f90f0bfb7b7cec8e541cf7d
The first line contains three integers n, m, and k (1 ≤ n ≤ 2·105, n - 1 ≤ m ≤ 2·105, 1 ≤ k ≤ n) — the number of vertices and edges in the lab, and the number of clones. Each of the next m lines contains two integers xi and yi (1 ≤ xi, yi ≤ n) — indices of vertices connected by the respective edge. The graph is allowed to have self-loops and multiple edges. The graph is guaranteed to be connected.
2,100
You should print k lines. i-th of these lines must start with an integer ci () — the number of vertices visited by i-th clone, followed by ci integers — indices of vertices visited by this clone in the order of visiting. You have to print each vertex every time it is visited, regardless if it was visited earlier or not. It is guaranteed that a valid answer exists.
standard output
PASSED
b0c2dc2235e9fbd983017c5c419a5731
train_003.jsonl
1488705300
The evil Bumbershoot corporation produces clones for gruesome experiments in a vast underground lab. On one occasion, the corp cloned a boy Andryusha who was smarter than his comrades. Immediately Andryusha understood that something fishy was going on there. He rallied fellow clones to go on a feud against the evil corp, and they set out to find an exit from the lab. The corp had to reduce to destroy the lab complex.The lab can be pictured as a connected graph with n vertices and m edges. k clones of Andryusha start looking for an exit in some of the vertices. Each clone can traverse any edge once per second. Any number of clones are allowed to be at any vertex simultaneously. Each clone is allowed to stop looking at any time moment, but he must look at his starting vertex at least. The exit can be located at any vertex of the lab, hence each vertex must be visited by at least one clone.Each clone can visit at most vertices before the lab explodes.Your task is to choose starting vertices and searching routes for the clones. Each route can have at most vertices.
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.util.ArrayList; /** * Built using CHelper plug-in * Actual solution is at the top * * @author svilen.marchev@gmail.com */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputStreamReader in = new InputStreamReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskE solver = new TaskE(); solver.solve(1, in, out); out.close(); } static class TaskE { /* From http://codeforces.com/blog/entry/50804?#comment-347500: ------ Put in an array the nodes following the visiting order of a dfs on the graph. Then, for each contiguous block of ceil(2n / k) nodes in the array, assign a robot. If a robot gets no node, just assign any node to it. This works because the dfs spanning tree has exactly n - 1 edges and you visit each of them 2 times (going down and up); hence, 2(n - 1) + 1 nodes will be visited. ------- ceil(2n / k)*k >= 2n  > 2n-1, so there will be enough steps to cover all nodes using this approach. */ final int MAXN = 200010; ArrayList<Integer>[] g = new ArrayList[MAXN + 1]; int n; int m; int k; int maxRouteLen; ArrayList<Integer> curRoute; int numRoutesPrinted; boolean[] visited = new boolean[MAXN + 1]; PrintWriter out; void printAndClearCurRoute() { out.print(curRoute.size()); for (int v : curRoute) { out.print(' '); out.print(v); } out.println(); curRoute.clear(); numRoutesPrinted += 1; } void addToCurRoute(int v) { curRoute.add(v); if (curRoute.size() == maxRouteLen) { printAndClearCurRoute(); } } void dfs(int v) { addToCurRoute(v); visited[v] = true; for (int kid : g[v]) { if (!visited[kid]) { dfs(kid); addToCurRoute(v); } } } public void solve(int testNumber, InputStreamReader in, PrintWriter out_) { out = out_; SvScanner sc = new SvScanner(in); n = sc.nextInt(); m = sc.nextInt(); k = sc.nextInt(); for (int i = 1; i <= n; ++i) { g[i] = new ArrayList<>(); } for (int i = 0; i < m; ++i) { int a = sc.nextInt(); int b = sc.nextInt(); g[a].add(b); g[b].add(a); } maxRouteLen = (2 * n + k - 1) / k; curRoute = new ArrayList<>(maxRouteLen); numRoutesPrinted = 0; dfs(1); if (!curRoute.isEmpty()) { printAndClearCurRoute(); } while (numRoutesPrinted < k) { out.println("1 1"); numRoutesPrinted += 1; } } } static class SvScanner { private BufferedReader reader; private StringTokenizer tokenizer = new StringTokenizer(""); public SvScanner(InputStreamReader in) { reader = new BufferedReader(in); } public String next() { try { while (!tokenizer.hasMoreTokens()) { String nextLine = reader.readLine(); if (nextLine == null) { throw new IllegalStateException("next line is null"); } tokenizer = new StringTokenizer(nextLine); } return tokenizer.nextToken(); } catch (IOException e) { throw new IllegalStateException(e); } } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["3 2 1\n2 1\n3 1", "5 4 2\n1 2\n1 3\n1 4\n1 5"]
1 second
["3 2 1 3", "3 2 1 3\n3 4 1 5"]
NoteIn the first sample case there is only one clone who may visit vertices in order (2, 1, 3), which fits the constraint of 6 vertices per clone.In the second sample case the two clones can visited vertices in order (2, 1, 3) and (4, 1, 5), which fits the constraint of 5 vertices per clone.
Java 8
standard input
[ "graphs", "constructive algorithms", "dfs and similar", "trees", "brute force" ]
d32d638e5f90f0bfb7b7cec8e541cf7d
The first line contains three integers n, m, and k (1 ≤ n ≤ 2·105, n - 1 ≤ m ≤ 2·105, 1 ≤ k ≤ n) — the number of vertices and edges in the lab, and the number of clones. Each of the next m lines contains two integers xi and yi (1 ≤ xi, yi ≤ n) — indices of vertices connected by the respective edge. The graph is allowed to have self-loops and multiple edges. The graph is guaranteed to be connected.
2,100
You should print k lines. i-th of these lines must start with an integer ci () — the number of vertices visited by i-th clone, followed by ci integers — indices of vertices visited by this clone in the order of visiting. You have to print each vertex every time it is visited, regardless if it was visited earlier or not. It is guaranteed that a valid answer exists.
standard output
PASSED
e9fe14c7ff5037a8ea40345125f1bd84
train_003.jsonl
1488705300
The evil Bumbershoot corporation produces clones for gruesome experiments in a vast underground lab. On one occasion, the corp cloned a boy Andryusha who was smarter than his comrades. Immediately Andryusha understood that something fishy was going on there. He rallied fellow clones to go on a feud against the evil corp, and they set out to find an exit from the lab. The corp had to reduce to destroy the lab complex.The lab can be pictured as a connected graph with n vertices and m edges. k clones of Andryusha start looking for an exit in some of the vertices. Each clone can traverse any edge once per second. Any number of clones are allowed to be at any vertex simultaneously. Each clone is allowed to stop looking at any time moment, but he must look at his starting vertex at least. The exit can be located at any vertex of the lab, hence each vertex must be visited by at least one clone.Each clone can visit at most vertices before the lab explodes.Your task is to choose starting vertices and searching routes for the clones. Each route can have at most vertices.
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.util.ArrayList; /** * Built using CHelper plug-in * Actual solution is at the top * * @author svilen.marchev@gmail.com */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputStreamReader in = new InputStreamReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskE solver = new TaskE(); solver.solve(1, in, out); out.close(); } static class TaskE { final int MAXN = 200010; ArrayList<Integer>[] g = new ArrayList[MAXN + 1]; int n; int m; int k; int maxRouteLen; ArrayList<Integer> curRoute; int numRoutesPrinted; boolean[] visited = new boolean[MAXN + 1]; PrintWriter out; void printAndClearCurRoute() { out.print(curRoute.size()); for (int v : curRoute) { out.print(' '); out.print(v); } out.println(); curRoute.clear(); numRoutesPrinted += 1; } void addToCurRoute(int v) { curRoute.add(v); if (curRoute.size() == maxRouteLen) { printAndClearCurRoute(); } } void dfs(int v) { addToCurRoute(v); visited[v] = true; for (int kid : g[v]) { if (!visited[kid]) { dfs(kid); addToCurRoute(v); } } } public void solve(int testNumber, InputStreamReader in, PrintWriter out_) { out = out_; SvScanner sc = new SvScanner(in); n = sc.nextInt(); m = sc.nextInt(); k = sc.nextInt(); for (int i = 1; i <= n; ++i) { g[i] = new ArrayList<>(); } for (int i = 0; i < m; ++i) { int a = sc.nextInt(); int b = sc.nextInt(); g[a].add(b); g[b].add(a); } maxRouteLen = (2 * n + k - 1) / k; curRoute = new ArrayList<>(maxRouteLen); numRoutesPrinted = 0; dfs(1); if (!curRoute.isEmpty()) { printAndClearCurRoute(); } while (numRoutesPrinted < k) { out.println("1 1"); numRoutesPrinted += 1; } } } static class SvScanner { private BufferedReader reader; private StringTokenizer tokenizer = new StringTokenizer(""); public SvScanner(InputStreamReader in) { reader = new BufferedReader(in); } public String next() { try { while (!tokenizer.hasMoreTokens()) { String nextLine = reader.readLine(); if (nextLine == null) { throw new IllegalStateException("next line is null"); } tokenizer = new StringTokenizer(nextLine); } return tokenizer.nextToken(); } catch (IOException e) { throw new IllegalStateException(e); } } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["3 2 1\n2 1\n3 1", "5 4 2\n1 2\n1 3\n1 4\n1 5"]
1 second
["3 2 1 3", "3 2 1 3\n3 4 1 5"]
NoteIn the first sample case there is only one clone who may visit vertices in order (2, 1, 3), which fits the constraint of 6 vertices per clone.In the second sample case the two clones can visited vertices in order (2, 1, 3) and (4, 1, 5), which fits the constraint of 5 vertices per clone.
Java 8
standard input
[ "graphs", "constructive algorithms", "dfs and similar", "trees", "brute force" ]
d32d638e5f90f0bfb7b7cec8e541cf7d
The first line contains three integers n, m, and k (1 ≤ n ≤ 2·105, n - 1 ≤ m ≤ 2·105, 1 ≤ k ≤ n) — the number of vertices and edges in the lab, and the number of clones. Each of the next m lines contains two integers xi and yi (1 ≤ xi, yi ≤ n) — indices of vertices connected by the respective edge. The graph is allowed to have self-loops and multiple edges. The graph is guaranteed to be connected.
2,100
You should print k lines. i-th of these lines must start with an integer ci () — the number of vertices visited by i-th clone, followed by ci integers — indices of vertices visited by this clone in the order of visiting. You have to print each vertex every time it is visited, regardless if it was visited earlier or not. It is guaranteed that a valid answer exists.
standard output
PASSED
c83ea189670c057e2bd57b41feea5136
train_003.jsonl
1601903100
A famous gang of pirates, Sea Dogs, has come back to their hideout from one of their extravagant plunders. They want to split their treasure fairly amongst themselves, that is why You, their trusted financial advisor, devised a game to help them:All of them take a sit at their round table, some of them with the golden coins they have just stolen. At each iteration of the game if one of them has equal or more than 2 coins, he is eligible to the splitting and he gives one coin to each pirate sitting next to him. If there are more candidates (pirates with equal or more than 2 coins) then You are the one that chooses which one of them will do the splitting in that iteration. The game ends when there are no more candidates eligible to do the splitting. Pirates can call it a day, only when the game ends. Since they are beings with a finite amount of time at their disposal, they would prefer if the game that they are playing can end after finite iterations, and if so, they call it a good game. On the other hand, if no matter how You do the splitting, the game cannot end in finite iterations, they call it a bad game. Can You help them figure out before they start playing if the game will be good or bad?
256 megabytes
//package bubblecup13.f; 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 F2 { InputStream is; PrintWriter out; String INPUT = ""; void solve() { int n = ni(), K = ni(); int[] a = new int[K]; int[] b = new int[K]; long num = 0; long v = 0; for(int i = 0;i < K;i++){ a[i] = ni()-1; b[i] = ni(); v += (long)a[i] * b[i]; v %= n; num += b[i]; } boolean ex = false; if(num < n){ ex = true; }else if(num == n){ ex = v == (long)n*(n-1)/2%n; } out.println(ex ? 1 : -1); } 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 F2().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 2\n1 2\n2 2", "6 2\n2 3\n4 1", "3 2\n1 1\n2 2"]
1 second
["1", "1", "-1"]
NoteIn the third example the game has no end, because You always only have only one candidate, after whose splitting you end up in the same position as the starting one.
Java 11
standard input
[ "math" ]
bde1f233c7a49850c6b906af37982c27
The first line of input contains two integer numbers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 10^{9}$$$, $$$0 \le k \le 2\cdot10^5$$$), where $$$n$$$ denotes total number of pirates and $$$k$$$ is the number of pirates that have any coins. The next $$$k$$$ lines of input contain integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \le a_i \le n$$$, $$$1 \le b_i \le 10^{9}$$$), where $$$a_i$$$ denotes the index of the pirate sitting at the round table ($$$n$$$ and $$$1$$$ are neighbours) and $$$b_i$$$ the total number of coins that pirate $$$a_i$$$ has at the start of the game.
2,700
Print $$$1$$$ if the game is a good game: There is a way to do the splitting so the game ends after finite number of iterations. Print $$$-1$$$ if the game is a bad game: No matter how You do the splitting the game does not end in finite number of iterations.
standard output
PASSED
1153c0cff3f8b046a611a1c669525983
train_003.jsonl
1590676500
The game of Berland poker is played with a deck of $$$n$$$ cards, $$$m$$$ of which are jokers. $$$k$$$ players play this game ($$$n$$$ is divisible by $$$k$$$).At the beginning of the game, each player takes $$$\frac{n}{k}$$$ cards from the deck (so each card is taken by exactly one player). The player who has the maximum number of jokers is the winner, and he gets the number of points equal to $$$x - y$$$, where $$$x$$$ is the number of jokers in the winner's hand, and $$$y$$$ is the maximum number of jokers among all other players. If there are two or more players with maximum number of jokers, all of them are winners and they get $$$0$$$ points.Here are some examples: $$$n = 8$$$, $$$m = 3$$$, $$$k = 2$$$. If one player gets $$$3$$$ jokers and $$$1$$$ plain card, and another player gets $$$0$$$ jokers and $$$4$$$ plain cards, then the first player is the winner and gets $$$3 - 0 = 3$$$ points; $$$n = 4$$$, $$$m = 2$$$, $$$k = 4$$$. Two players get plain cards, and the other two players get jokers, so both of them are winners and get $$$0$$$ points; $$$n = 9$$$, $$$m = 6$$$, $$$k = 3$$$. If the first player gets $$$3$$$ jokers, the second player gets $$$1$$$ joker and $$$2$$$ plain cards, and the third player gets $$$2$$$ jokers and $$$1$$$ plain card, then the first player is the winner, and he gets $$$3 - 2 = 1$$$ point; $$$n = 42$$$, $$$m = 0$$$, $$$k = 7$$$. Since there are no jokers, everyone gets $$$0$$$ jokers, everyone is a winner, and everyone gets $$$0$$$ points. Given $$$n$$$, $$$m$$$ and $$$k$$$, calculate the maximum number of points a player can get for winning the game.
256 megabytes
import java.io.*; import java.util.*; public class Codeforces { public static void main(String args[])throws Exception { BufferedReader bu=new BufferedReader(new InputStreamReader(System.in)); StringBuilder sb=new StringBuilder(); int t=Integer.parseInt(bu.readLine()); while(t-->0) { String s[]=bu.readLine().split(" "); int n=Integer.parseInt(s[0]),m=Integer.parseInt(s[1]),k=Integer.parseInt(s[2]); int c=n/k; if(c>=m || m==0) {sb.append(m+"\n"); continue;} int a=c; m-=c; int b=m/(k-1); if(m%(k-1)!=0) b++; a=a-b; if(a<0) a=0; sb.append(a+"\n"); } System.out.print(sb); } }
Java
["4\n8 3 2\n4 2 4\n9 6 3\n42 0 7"]
2 seconds
["3\n0\n1\n0"]
NoteTest cases of the example are described in the statement.
Java 11
standard input
[ "greedy", "math", "brute force" ]
6324ca46b6f072f8952d2619cb4f73e6
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. Then the test cases follow. Each test case contains three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$2 \le n \le 50$$$, $$$0 \le m \le n$$$, $$$2 \le k \le n$$$, $$$k$$$ is a divisors of $$$n$$$).
1,000
For each test case, print one integer — the maximum number of points a player can get for winning the game.
standard output