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
sequencelengths
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
bb255355fe18992fa0b41283d05bca11
train_000.jsonl
1360596600
You've got an n × m matrix. The matrix consists of integers. In one move, you can apply a single transformation to the matrix: choose an arbitrary element of the matrix and increase it by 1. Each element can be increased an arbitrary number of times.You are really curious about prime numbers. Let us remind you that a prime number is a positive integer that has exactly two distinct positive integer divisors: itself and number one. For example, numbers 2, 3, 5 are prime and numbers 1, 4, 6 are not. A matrix is prime if at least one of the two following conditions fulfills: the matrix has a row with prime numbers only; the matrix has a column with prime numbers only; Your task is to count the minimum number of moves needed to get a prime matrix from the one you've got.
256 megabytes
import java.util.*; public class cf271B{ public static void main(String args[]) { Scanner sc = new Scanner(System.in); int n= sc.nextInt(); int m= sc.nextInt(); int[][] matrix = new int[n][m]; int count =0; int[] primes = new int[100010]; int[] new_primes = new int[100010]; int k= 2; while(k<100010) { while(k<100010 && primes[k]!=0 ) k++; new_primes[count++] = k; for(int j=k; j<100010; j+=k) primes[j] = 1; } //System.out.println(new_primes[0]+"new"); count--; int min_row = 1000000000; for(int i=0; i<n;i++) { int sum = 0; for(int j=0; j<m; j++) { matrix[i][j] = sc.nextInt(); int num = bsearch(matrix[i][j],new_primes, 0, count-1); //System.out.println("num"+num); sum += (num - matrix[i][j]); matrix[i][j] = num - matrix[i][j]; } if(sum < min_row) min_row = sum; } for(int i=0; i<m;i++) { int sum = 0; for(int j=0; j<n; j++) { sum += matrix[j][i]; } if(sum < min_row) min_row = sum; } System.out.println(min_row); } public static int bsearch(int val, int[] new_primes, int start, int end) { while(start != end && end - start != 1) { int mid = (start+end)/2; if(new_primes[mid] == val) return val; if(new_primes[mid] < val) { start = mid+1; } else end = mid; } if(start == end) return new_primes[start]; else if(new_primes[start] >= val) return new_primes[start]; else return new_primes[end]; } }
Java
["3 3\n1 2 3\n5 6 1\n4 4 1", "2 3\n4 8 8\n9 2 9", "2 2\n1 3\n4 2"]
2 seconds
["1", "3", "0"]
NoteIn the first sample you need to increase number 1 in cell (1, 1). Thus, the first row will consist of prime numbers: 2, 2, 3.In the second sample you need to increase number 8 in cell (1, 2) three times. Thus, the second column will consist of prime numbers: 11, 2.In the third sample you don't have to do anything as the second column already consists of prime numbers: 3, 2.
Java 6
standard input
[ "binary search", "number theory", "brute force", "math" ]
d549f70d028a884f0313743c09c685f1
The first line contains two integers n, m (1 ≀ n, m ≀ 500) β€” the number of rows and columns in the matrix, correspondingly. Each of the following n lines contains m integers β€” the initial matrix. All matrix elements are positive integers. All numbers in the initial matrix do not exceed 105. The numbers in the lines are separated by single spaces.
1,300
Print a single integer β€” the minimum number of moves needed to get a prime matrix from the one you've got. If you've got a prime matrix, print 0.
standard output
PASSED
a23d3bfba29dfbcfd52d7fd5bb13e853
train_000.jsonl
1360596600
You've got an n × m matrix. The matrix consists of integers. In one move, you can apply a single transformation to the matrix: choose an arbitrary element of the matrix and increase it by 1. Each element can be increased an arbitrary number of times.You are really curious about prime numbers. Let us remind you that a prime number is a positive integer that has exactly two distinct positive integer divisors: itself and number one. For example, numbers 2, 3, 5 are prime and numbers 1, 4, 6 are not. A matrix is prime if at least one of the two following conditions fulfills: the matrix has a row with prime numbers only; the matrix has a column with prime numbers only; Your task is to count the minimum number of moves needed to get a prime matrix from the one you've got.
256 megabytes
import java.awt.Point; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.LinkedList; import java.util.List; import java.util.Scanner; import java.util.Stack; import java.util.StringTokenizer; public class B { public static void main(String[] Args) throws IOException { B b = new B(); b.solve(); } static int[] dx_ = { 0, 0, 1, -1 }; static int[] dy_ = { 1, -1, 0, 0 }; ArrayList<Integer>[] graph; ArrayList<Point> map = new ArrayList<Point>(); // DISCUSS TIME LIMIT EXCEEDED!!!! PROPER DATA STRUCTURE!!! // Use array if possible or the most efficient data structure int[] pr; List<Integer> primes; void solve() throws IOException { pr = arePrimes((int) 1e6); primes = primes(pr); //System.out.println(primes.size()); int n = si(), m = si(); int[][] x = new int[n][m]; int[][] y = new int[m][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { y[j][i] = x[i][j] = si(); } } // for(int[]r : x) System.out.println(Arrays.toString(r)); // System.out.println(); // for(int[]r : y) System.out.println(Arrays.toString(r)); int ans = Math.min(F(x), F(y)); System.out.println(ans); } int F(int[][] x) { int ans = INF; for (int i = 0; i < x.length; i++) { int[] a = x[i].clone(); Arrays.sort(a); int move = 0, p = 0; for (int j = 0; j < a.length; j++) { if (pr[a[j]] != 0) { while (primes.get(p) <= a[j]) p++; move += (primes.get(p) - a[j]); } } ans = Math.min(ans, move); } return ans; } // Using the Sieve of Eratosthenes static List<Integer> primes(int[] a) { List<Integer> v = new ArrayList<Integer>(); for (int i = 0; i < a.length; i++) { if (a[i] == 0) v.add(i); } return v; } // Sieve of Eratosthenes static int[] arePrimes(int n) { // 0=prime, 1=not prime int[] a = new int[n + 1]; a[0] = a[1] = 1; for (int i = 0; i < a.length; i++) { if (a[i] == 0) for (int j = i + i; j < a.length; j += i) { a[j] = 1;// not prime } } return a; } // ----------------------- Library ------------------------ // ----------------------- GRAPH ------------------------ /** * important for speed!!! PrintWriter out=new PrintWriter(new * OutputStreamWriter(System.out)); out.print(...); out.close(); * * @param v */ // leap year is 29 int[] year = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; void initSystem() throws IOException { if (br != null) br.close(); br = new BufferedReader(new InputStreamReader(System.in)); } void initFile() throws IOException { if (br != null) br.close(); br = new BufferedReader(new InputStreamReader(new FileInputStream( "input.txt"))); } void printWriter() { try { PrintWriter pr = new PrintWriter("output.txt"); pr.println("hello world"); pr.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } void comparator() { Point[] v = new Point[10]; Arrays.sort(v, new Comparator<Point>() { @Override public int compare(Point a, Point b) { if (a.x != b.x) return -(a.x - b.x); return a.y - b.y; } }); } double distance(Point a, Point b) { double dx = a.x - b.x, dy = a.y - b.y; return Math.sqrt(dx * dx + dy * dy); } Scanner in = new Scanner(System.in); String ss() { return in.next(); } char[] sc() { return in.next().toCharArray(); } String sline() { return in.nextLine(); } int si() { return in.nextInt(); } long sl() { return in.nextLong(); } int[] sai(int n) { int[] a = new int[n]; for (int i = 0; i < a.length; i++) { a[i] = in.nextInt(); } return a; } int[] si(int n) { int[] a = new int[n]; for (int i = 0; i < a.length; i++) { a[i] = in.nextInt(); } return a; } String[] ss(int n) { String[] a = new String[n]; for (int i = 0; i < a.length; i++) { a[i] = ss(); } return a; } int[] sai_(int n) { int[] a = new int[n + 1]; for (int i = 1; i <= n; i++) { a[i] = in.nextInt(); } return a; } BufferedReader br; StringTokenizer tokenizer; { br = new BufferedReader(new InputStreamReader(System.in)); } void tok() throws IOException { tokenizer = new StringTokenizer(br.readLine()); } int toki() throws IOException { return Integer.parseInt(tokenizer.nextToken()); } int[] rint(int n) throws IOException { int[] a = new int[n]; for (int i = 0; i < a.length; i++) a[i] = Integer.parseInt(tokenizer.nextToken()); return a; } int[] rint_(int n) throws IOException { int[] a = new int[n + 1]; for (int i = 1; i <= n; i++) a[i] = Integer.parseInt(tokenizer.nextToken()); return a; } String[] rstrlines(int n) throws IOException { String[] a = new String[n]; for (int i = 0; i < n; i++) { a[i] = br.readLine(); } return a; } long tokl() { return Long.parseLong(tokenizer.nextToken()); } double tokd() { return Double.parseDouble(tokenizer.nextToken()); } String toks() { return tokenizer.nextToken(); } String rline() throws IOException { return br.readLine(); } List<Integer> toList(int[] a) { List<Integer> v = new ArrayList<Integer>(); for (int i : a) v.add(i); return v; } static void pai(int[] a) { System.out.println(Arrays.toString(a)); } static int toi(Object s) { return Integer.parseInt(s.toString()); } static int[] dx3 = { 1, -1, 0, 0, 0, 0 }; static int[] dy3 = { 0, 0, 1, -1, 0, 0 }; static int[] dz3 = { 0, 0, 0, 0, 1, -1 }; static int[] dx = { 1, 0, -1, 1, -1, 1, 0, -1 }, dy = { 1, 1, 1, 0, 0, -1, -1, -1 }; static int INF = 2147483647; // =2^31-1 // -8 static long LINF = 922337203854775807L; // -8 static short SINF = 32767; // -32768 // finds GCD of a and b using Euclidian algorithm public int GCD(int a, int b) { if (b == 0) return a; return GCD(b, a % b); } static List<String> toList(String[] a) { return Arrays.asList(a); } static String[] toArray(List<String> a) { String[] o = new String[a.size()]; a.toArray(o); return o; } static int[] pair(int... a) { return a; } }
Java
["3 3\n1 2 3\n5 6 1\n4 4 1", "2 3\n4 8 8\n9 2 9", "2 2\n1 3\n4 2"]
2 seconds
["1", "3", "0"]
NoteIn the first sample you need to increase number 1 in cell (1, 1). Thus, the first row will consist of prime numbers: 2, 2, 3.In the second sample you need to increase number 8 in cell (1, 2) three times. Thus, the second column will consist of prime numbers: 11, 2.In the third sample you don't have to do anything as the second column already consists of prime numbers: 3, 2.
Java 6
standard input
[ "binary search", "number theory", "brute force", "math" ]
d549f70d028a884f0313743c09c685f1
The first line contains two integers n, m (1 ≀ n, m ≀ 500) β€” the number of rows and columns in the matrix, correspondingly. Each of the following n lines contains m integers β€” the initial matrix. All matrix elements are positive integers. All numbers in the initial matrix do not exceed 105. The numbers in the lines are separated by single spaces.
1,300
Print a single integer β€” the minimum number of moves needed to get a prime matrix from the one you've got. If you've got a prime matrix, print 0.
standard output
PASSED
344d94740853b55c2b92bc1be59bf026
train_000.jsonl
1360596600
You've got an n × m matrix. The matrix consists of integers. In one move, you can apply a single transformation to the matrix: choose an arbitrary element of the matrix and increase it by 1. Each element can be increased an arbitrary number of times.You are really curious about prime numbers. Let us remind you that a prime number is a positive integer that has exactly two distinct positive integer divisors: itself and number one. For example, numbers 2, 3, 5 are prime and numbers 1, 4, 6 are not. A matrix is prime if at least one of the two following conditions fulfills: the matrix has a row with prime numbers only; the matrix has a column with prime numbers only; Your task is to count the minimum number of moves needed to get a prime matrix from the one you've got.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.StreamTokenizer; public class B_ { static StreamTokenizer st = new StreamTokenizer(new BufferedReader( new InputStreamReader(System.in))); static int nextInt() throws IOException { st.nextToken(); return (int) st.nval; } static char nextChar() throws IOException { st.nextToken(); return st.sval.charAt(0); } static int[] a = new int[9593]; public static void findEasy(){ a[0]=2; a[1]=3; int counter =2; for (int i= 5; i<100004; i+=2) if (iseasy(i)) a[counter++]=i; } public static boolean iseasy(int n){ for (int i=3; i*i<=n; i+=2){ if (n%i==0) return false; } return true; } public static void main(String[] args) throws IOException { // TODO Auto-generated method stub findEasy(); int n = nextInt(); int m = nextInt(); int[] stroki = new int[n]; int[] stolbci = new int[m]; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) { int counter = 0; int t = nextInt(); int d = isEasyAdd(t); stroki[i] += d; stolbci[j] += d; } long min = Long.MAX_VALUE; for (int i = 0; i < n; i++) if (stroki[i] < min) min = stroki[i]; for (int i = 0; i < m; i++) if (stolbci[i] < min) min = stolbci[i]; System.out.println(min); } public static int isEasyAdd(int x) { int l = 0; int r = a.length - 1; int mid = 0; while (l <= r) { mid = (l + r) / 2; if (x < a[mid]) r = mid - 1; else if (x > a[mid]) l = mid + 1; else return 0; // число простоС } if (x < a[mid]) return a[mid] - x; else return a[mid + 1] - x; } }
Java
["3 3\n1 2 3\n5 6 1\n4 4 1", "2 3\n4 8 8\n9 2 9", "2 2\n1 3\n4 2"]
2 seconds
["1", "3", "0"]
NoteIn the first sample you need to increase number 1 in cell (1, 1). Thus, the first row will consist of prime numbers: 2, 2, 3.In the second sample you need to increase number 8 in cell (1, 2) three times. Thus, the second column will consist of prime numbers: 11, 2.In the third sample you don't have to do anything as the second column already consists of prime numbers: 3, 2.
Java 6
standard input
[ "binary search", "number theory", "brute force", "math" ]
d549f70d028a884f0313743c09c685f1
The first line contains two integers n, m (1 ≀ n, m ≀ 500) β€” the number of rows and columns in the matrix, correspondingly. Each of the following n lines contains m integers β€” the initial matrix. All matrix elements are positive integers. All numbers in the initial matrix do not exceed 105. The numbers in the lines are separated by single spaces.
1,300
Print a single integer β€” the minimum number of moves needed to get a prime matrix from the one you've got. If you've got a prime matrix, print 0.
standard output
PASSED
d6588b6831a5602b8369c894a5efc691
train_000.jsonl
1360596600
You've got an n × m matrix. The matrix consists of integers. In one move, you can apply a single transformation to the matrix: choose an arbitrary element of the matrix and increase it by 1. Each element can be increased an arbitrary number of times.You are really curious about prime numbers. Let us remind you that a prime number is a positive integer that has exactly two distinct positive integer divisors: itself and number one. For example, numbers 2, 3, 5 are prime and numbers 1, 4, 6 are not. A matrix is prime if at least one of the two following conditions fulfills: the matrix has a row with prime numbers only; the matrix has a column with prime numbers only; Your task is to count the minimum number of moves needed to get a prime matrix from the one you've got.
256 megabytes
import java.io.*; import java.util.*; import java.lang.Math.*; public class Matrix1 { public static void main(String args[])throws Exception { boolean seive[]=new boolean[1000000]; Arrays.fill(seive,true); BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw = new PrintWriter(System.out); StringTokenizer st=new StringTokenizer(br.readLine()); int n=Integer.parseInt(st.nextToken()); int m=Integer.parseInt(st.nextToken()); int a[][]=new int[n][m]; int i,j,k,l; seive[1]=seive[0]=false; for(i=4;i<1000000;i+=2) { seive[i]=false; } for(i=3;i<1000;i+=2) { if(seive[i]) { for(j=i*i;j<1000000;j+=i) { seive[j]=false; } } } int val; for(i=0;i<n;i++) { st=new StringTokenizer(br.readLine()); for(j=0;j<m;j++) { val=Integer.parseInt(st.nextToken()); for(k=val;k<1000000;k++) { if(seive[k]) { break; } } a[i][j]=k-val; } } int row[]=new int[n]; int col[]=new int[m]; for(i=0;i<n;i++) { for(j=0;j<m;j++) { row[i]+=a[i][j]; } } Arrays.sort(row); for(j=0;j<m;j++) { for(i=0;i<n;i++) { col[j]+=a[i][j]; } } Arrays.sort(col); System.out.println(Math.min(row[0],col[0])); } }
Java
["3 3\n1 2 3\n5 6 1\n4 4 1", "2 3\n4 8 8\n9 2 9", "2 2\n1 3\n4 2"]
2 seconds
["1", "3", "0"]
NoteIn the first sample you need to increase number 1 in cell (1, 1). Thus, the first row will consist of prime numbers: 2, 2, 3.In the second sample you need to increase number 8 in cell (1, 2) three times. Thus, the second column will consist of prime numbers: 11, 2.In the third sample you don't have to do anything as the second column already consists of prime numbers: 3, 2.
Java 6
standard input
[ "binary search", "number theory", "brute force", "math" ]
d549f70d028a884f0313743c09c685f1
The first line contains two integers n, m (1 ≀ n, m ≀ 500) β€” the number of rows and columns in the matrix, correspondingly. Each of the following n lines contains m integers β€” the initial matrix. All matrix elements are positive integers. All numbers in the initial matrix do not exceed 105. The numbers in the lines are separated by single spaces.
1,300
Print a single integer β€” the minimum number of moves needed to get a prime matrix from the one you've got. If you've got a prime matrix, print 0.
standard output
PASSED
d016bce4c487f67a5b141cb430b6eb4e
train_000.jsonl
1360596600
You've got an n × m matrix. The matrix consists of integers. In one move, you can apply a single transformation to the matrix: choose an arbitrary element of the matrix and increase it by 1. Each element can be increased an arbitrary number of times.You are really curious about prime numbers. Let us remind you that a prime number is a positive integer that has exactly two distinct positive integer divisors: itself and number one. For example, numbers 2, 3, 5 are prime and numbers 1, 4, 6 are not. A matrix is prime if at least one of the two following conditions fulfills: the matrix has a row with prime numbers only; the matrix has a column with prime numbers only; Your task is to count the minimum number of moves needed to get a prime matrix from the one you've got.
256 megabytes
import java.io.*; import java.math.*; import java.util.*; import javax.swing.*; public class B { public static void main(String[] args) throws Exception { new B().solve(); // new FileInputStream(new File("input.txt")), // new PrintStream(new FileOutputStream(new File("output.txt")))); } void solve() throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); // Scanner sc = new Scanner(System.in); String[] sp; int max = 200000; boolean[] prime = new boolean[max]; Arrays.fill(prime, true); prime[0] = prime[1] = false; for (int p = 2; p < prime.length; p++) { if (prime[p]) { for (int pp = p * 2; pp < prime.length; pp += p) { prime[pp] = false; } } } int[] toPrime = new int[max]; for (int p = toPrime.length, i = toPrime.length - 1; i >= 0; i--) { if (prime[i]) { p = i; } else { toPrime[i] = p - i; } } sp = in.readLine().split(" "); int R = Integer.parseInt(sp[0]); int C = Integer.parseInt(sp[1]); int[][] move = new int[R][C]; for (int r = 0; r < R; r++) { sp = in.readLine().split(" "); for (int c = 0; c < C; c++) { int elem = Integer.parseInt(sp[c]); move[r][c] = toPrime[elem]; } } int min = Integer.MAX_VALUE; for (int r = 0; r < R; r++) { int m = 0; for (int c = 0; c < C; c++) { m += move[r][c]; } min = Math.min(min, m); } for (int c = 0; c < C; c++) { int m = 0; for (int r = 0; r < R; r++) { m += move[r][c]; } min = Math.min(min, m); } System.out.println(min); } } // // // // // // // // // // // // // // // // // // // // // // // //
Java
["3 3\n1 2 3\n5 6 1\n4 4 1", "2 3\n4 8 8\n9 2 9", "2 2\n1 3\n4 2"]
2 seconds
["1", "3", "0"]
NoteIn the first sample you need to increase number 1 in cell (1, 1). Thus, the first row will consist of prime numbers: 2, 2, 3.In the second sample you need to increase number 8 in cell (1, 2) three times. Thus, the second column will consist of prime numbers: 11, 2.In the third sample you don't have to do anything as the second column already consists of prime numbers: 3, 2.
Java 6
standard input
[ "binary search", "number theory", "brute force", "math" ]
d549f70d028a884f0313743c09c685f1
The first line contains two integers n, m (1 ≀ n, m ≀ 500) β€” the number of rows and columns in the matrix, correspondingly. Each of the following n lines contains m integers β€” the initial matrix. All matrix elements are positive integers. All numbers in the initial matrix do not exceed 105. The numbers in the lines are separated by single spaces.
1,300
Print a single integer β€” the minimum number of moves needed to get a prime matrix from the one you've got. If you've got a prime matrix, print 0.
standard output
PASSED
63b5c6098830442f4e34e125295402d1
train_000.jsonl
1360596600
You've got an n × m matrix. The matrix consists of integers. In one move, you can apply a single transformation to the matrix: choose an arbitrary element of the matrix and increase it by 1. Each element can be increased an arbitrary number of times.You are really curious about prime numbers. Let us remind you that a prime number is a positive integer that has exactly two distinct positive integer divisors: itself and number one. For example, numbers 2, 3, 5 are prime and numbers 1, 4, 6 are not. A matrix is prime if at least one of the two following conditions fulfills: the matrix has a row with prime numbers only; the matrix has a column with prime numbers only; Your task is to count the minimum number of moves needed to get a prime matrix from the one you've got.
256 megabytes
import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.Map; import java.util.Queue; import java.util.Scanner; import java.util.ArrayList; public class Main { static int d[][]; static int N; static boolean used[]; public static void main(String[] args) { Scanner scan = new Scanner(System.in); int maxPrime = 1000003; boolean isPrime[] = new boolean[maxPrime]; Arrays.fill(isPrime,true); isPrime[1] = false; for (int i=2; i*i < maxPrime; i++) if (isPrime[i]) for (int j=i*i; j < maxPrime; j+=i) isPrime[j] = false; int n = scan.nextInt(); int m = scan.nextInt(); int mas[][] = new int[n][m]; for(int i = 0;i<n;i++) { for(int j = 0;j<m;j++) { mas[i][j] = scan.nextInt(); } } int sums[][] = new int[n][m]; for(int i = 0;i<n;i++) { for(int j = 0;j<m;j++) { int temp = mas[i][j]; while(!isPrime[temp]){temp++;sums[i][j]++;} } } long minsum = Long.MAX_VALUE; for(int i = 0;i<n;i++) { int sum = 0; for(int j = 0;j<m;j++) { sum+=sums[i][j]; } if(sum<minsum) minsum = sum; } for(int j = 0;j<m;j++) { int sum = 0; for(int i = 0;i<n;i++) { sum+=sums[i][j]; } if(sum<minsum) minsum = sum; } System.out.print(minsum); } }
Java
["3 3\n1 2 3\n5 6 1\n4 4 1", "2 3\n4 8 8\n9 2 9", "2 2\n1 3\n4 2"]
2 seconds
["1", "3", "0"]
NoteIn the first sample you need to increase number 1 in cell (1, 1). Thus, the first row will consist of prime numbers: 2, 2, 3.In the second sample you need to increase number 8 in cell (1, 2) three times. Thus, the second column will consist of prime numbers: 11, 2.In the third sample you don't have to do anything as the second column already consists of prime numbers: 3, 2.
Java 6
standard input
[ "binary search", "number theory", "brute force", "math" ]
d549f70d028a884f0313743c09c685f1
The first line contains two integers n, m (1 ≀ n, m ≀ 500) β€” the number of rows and columns in the matrix, correspondingly. Each of the following n lines contains m integers β€” the initial matrix. All matrix elements are positive integers. All numbers in the initial matrix do not exceed 105. The numbers in the lines are separated by single spaces.
1,300
Print a single integer β€” the minimum number of moves needed to get a prime matrix from the one you've got. If you've got a prime matrix, print 0.
standard output
PASSED
ccf0f1751b84c2c119c9c05b4e51e9c3
train_000.jsonl
1360596600
You've got an n × m matrix. The matrix consists of integers. In one move, you can apply a single transformation to the matrix: choose an arbitrary element of the matrix and increase it by 1. Each element can be increased an arbitrary number of times.You are really curious about prime numbers. Let us remind you that a prime number is a positive integer that has exactly two distinct positive integer divisors: itself and number one. For example, numbers 2, 3, 5 are prime and numbers 1, 4, 6 are not. A matrix is prime if at least one of the two following conditions fulfills: the matrix has a row with prime numbers only; the matrix has a column with prime numbers only; Your task is to count the minimum number of moves needed to get a prime matrix from the one you've got.
256 megabytes
import java.io.*; import java.util.*; import static java.lang.Math.*; public class Solution { BufferedReader in; StringTokenizer st; PrintWriter out; TreeSet<Integer> sieve() { boolean[] prime = new boolean[500000]; prime[0] = prime[1] = true; for (int i = 2; i < prime.length; ++i) if (prime[i] == false) { for (int j = i + i; j < prime.length; j += i) prime[j] = true; } TreeSet<Integer> set = new TreeSet<Integer>(); for (int i = 0; i < prime.length; ++i) { if (prime[i] == false) set.add(i); } return set; } void solve() throws IOException { TreeSet<Integer> set = sieve(); int n = ni(); int m = ni(); int[][] v = new int[n][m]; for (int i = 0; i < n; ++i) for (int j = 0; j < m; ++j) { int a = ni(); int b = set.ceiling(a); v[i][j] = b - a; } int ret = 1 << 30; for (int i = 0; i < n; ++i) { int a = 0; for (int j = 0; j < m; ++j) a += v[i][j]; ret = min(ret, a); } for (int j = 0; j < m; ++j) { int a = 0; for (int i = 0; i < n; ++i) a += v[i][j]; ret = min(ret, a); } out.println(ret); } public Solution() throws IOException { Locale.setDefault(Locale.US); in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); in.close(); out.close(); } String ns() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(in.readLine()); return st.nextToken(); } int ni() throws IOException { return Integer.valueOf(ns()); } long nl() throws IOException { return Long.valueOf(ns()); } double nd() throws IOException { return Double.valueOf(ns()); } public static void main(String[] args) throws IOException { new Solution(); } }
Java
["3 3\n1 2 3\n5 6 1\n4 4 1", "2 3\n4 8 8\n9 2 9", "2 2\n1 3\n4 2"]
2 seconds
["1", "3", "0"]
NoteIn the first sample you need to increase number 1 in cell (1, 1). Thus, the first row will consist of prime numbers: 2, 2, 3.In the second sample you need to increase number 8 in cell (1, 2) three times. Thus, the second column will consist of prime numbers: 11, 2.In the third sample you don't have to do anything as the second column already consists of prime numbers: 3, 2.
Java 6
standard input
[ "binary search", "number theory", "brute force", "math" ]
d549f70d028a884f0313743c09c685f1
The first line contains two integers n, m (1 ≀ n, m ≀ 500) β€” the number of rows and columns in the matrix, correspondingly. Each of the following n lines contains m integers β€” the initial matrix. All matrix elements are positive integers. All numbers in the initial matrix do not exceed 105. The numbers in the lines are separated by single spaces.
1,300
Print a single integer β€” the minimum number of moves needed to get a prime matrix from the one you've got. If you've got a prime matrix, print 0.
standard output
PASSED
5a01c0b5fd939fdd16ccf35b91b9e062
train_000.jsonl
1360596600
You've got an n × m matrix. The matrix consists of integers. In one move, you can apply a single transformation to the matrix: choose an arbitrary element of the matrix and increase it by 1. Each element can be increased an arbitrary number of times.You are really curious about prime numbers. Let us remind you that a prime number is a positive integer that has exactly two distinct positive integer divisors: itself and number one. For example, numbers 2, 3, 5 are prime and numbers 1, 4, 6 are not. A matrix is prime if at least one of the two following conditions fulfills: the matrix has a row with prime numbers only; the matrix has a column with prime numbers only; Your task is to count the minimum number of moves needed to get a prime matrix from the one you've got.
256 megabytes
import java.util.*; public class PrimeMatrix271B { // WARNING: For efficiency purposes, true means is it NOT prime, false means prime private static boolean[] primesieve(int size) { // True will mean it is NOT prime boolean[] returnme = new boolean[size]; // Default in Java to all false returnme[0] = true; returnme[1] = true; int nextfalse = 2; while (nextfalse < Math.sqrt(size) + 1) { for (int i = nextfalse * nextfalse; i < size; i+=nextfalse) { returnme[i] = true; } nextfalse++; while (returnme[nextfalse] == true) { nextfalse++; } } return returnme; } public static void main(String[] args) { // Set up scanner Scanner sc = new Scanner(System.in); // System.out.println("Input # of rows"); int x = sc.nextInt(); // System.out.println("Input # of cols"); int y = sc.nextInt(); int[][] m = new int[x][y]; // Create and fill matrix for (int r=0; r<x; r++) { for (int c=0; c<y; c++) { // System.out.println("Input next value"); m[r][c] = sc.nextInt(); } } boolean[] a = primesieve(101000); // Create prime matrix int answer = Integer.MAX_VALUE; // Look over all rows for (int r=0; r<x; r++) { int amttoadd = 0; for (int c=0; c<y; c++) { int test = m[r][c]; while (a[test]) { amttoadd++; test++; } } if (amttoadd < answer) { answer = amttoadd; } } // Look over all cols for (int c=0; c<y; c++) { int amttoadd = 0; for (int r=0; r<x; r++) { int test = m[r][c]; while (a[test]) { amttoadd++; test++; } } if (amttoadd < answer) { answer = amttoadd; } } System.out.println(answer); } }
Java
["3 3\n1 2 3\n5 6 1\n4 4 1", "2 3\n4 8 8\n9 2 9", "2 2\n1 3\n4 2"]
2 seconds
["1", "3", "0"]
NoteIn the first sample you need to increase number 1 in cell (1, 1). Thus, the first row will consist of prime numbers: 2, 2, 3.In the second sample you need to increase number 8 in cell (1, 2) three times. Thus, the second column will consist of prime numbers: 11, 2.In the third sample you don't have to do anything as the second column already consists of prime numbers: 3, 2.
Java 6
standard input
[ "binary search", "number theory", "brute force", "math" ]
d549f70d028a884f0313743c09c685f1
The first line contains two integers n, m (1 ≀ n, m ≀ 500) β€” the number of rows and columns in the matrix, correspondingly. Each of the following n lines contains m integers β€” the initial matrix. All matrix elements are positive integers. All numbers in the initial matrix do not exceed 105. The numbers in the lines are separated by single spaces.
1,300
Print a single integer β€” the minimum number of moves needed to get a prime matrix from the one you've got. If you've got a prime matrix, print 0.
standard output
PASSED
1dc52245c4a177b908d61fbf2483148f
train_000.jsonl
1360596600
You've got an n × m matrix. The matrix consists of integers. In one move, you can apply a single transformation to the matrix: choose an arbitrary element of the matrix and increase it by 1. Each element can be increased an arbitrary number of times.You are really curious about prime numbers. Let us remind you that a prime number is a positive integer that has exactly two distinct positive integer divisors: itself and number one. For example, numbers 2, 3, 5 are prime and numbers 1, 4, 6 are not. A matrix is prime if at least one of the two following conditions fulfills: the matrix has a row with prime numbers only; the matrix has a column with prime numbers only; Your task is to count the minimum number of moves needed to get a prime matrix from the one you've got.
256 megabytes
import static java.lang.Math.*; import static java.util.Arrays.*; import java.util.*; import java.io.*; public class Main { int N = 100100; int INF = 1<<28; boolean[] p; int[] dp; void prime() { p = new boolean[N]; dp = new int[N]; fill(dp, 10000); for(int i=2;i<N;i++) if(!p[i]) { for(int j=i*2;j<N;j+=i) p[j] = true; dp[i] = 0; } for(int i=N-2;i>=0;i--) { dp[i] = min(dp[i+1]+1, dp[i]); } } void run() { Scanner sc = new Scanner(System.in); prime(); int r = sc.nextInt(), c = sc.nextInt(); int[] hor = new int[r]; int[] ver = new int[c]; for(int i=0;i<r;i++) for(int j=0;j<c;j++) { int val = sc.nextInt(); hor[i] += dp[val]; ver[j] += dp[val]; } int min = INF; for(int i=0;i<r;i++) min = min(min, hor[i]); for(int i=0;i<c;i++) min = min(min, ver[i]); System.out.println(min); } void debug(Object... os) { System.err.println(Arrays.deepToString(os)); } public static void main(String[] args) { new Main().run(); } }
Java
["3 3\n1 2 3\n5 6 1\n4 4 1", "2 3\n4 8 8\n9 2 9", "2 2\n1 3\n4 2"]
2 seconds
["1", "3", "0"]
NoteIn the first sample you need to increase number 1 in cell (1, 1). Thus, the first row will consist of prime numbers: 2, 2, 3.In the second sample you need to increase number 8 in cell (1, 2) three times. Thus, the second column will consist of prime numbers: 11, 2.In the third sample you don't have to do anything as the second column already consists of prime numbers: 3, 2.
Java 6
standard input
[ "binary search", "number theory", "brute force", "math" ]
d549f70d028a884f0313743c09c685f1
The first line contains two integers n, m (1 ≀ n, m ≀ 500) β€” the number of rows and columns in the matrix, correspondingly. Each of the following n lines contains m integers β€” the initial matrix. All matrix elements are positive integers. All numbers in the initial matrix do not exceed 105. The numbers in the lines are separated by single spaces.
1,300
Print a single integer β€” the minimum number of moves needed to get a prime matrix from the one you've got. If you've got a prime matrix, print 0.
standard output
PASSED
86db47c6e43209c7578fd8da2b76ef5e
train_000.jsonl
1360596600
You've got an n × m matrix. The matrix consists of integers. In one move, you can apply a single transformation to the matrix: choose an arbitrary element of the matrix and increase it by 1. Each element can be increased an arbitrary number of times.You are really curious about prime numbers. Let us remind you that a prime number is a positive integer that has exactly two distinct positive integer divisors: itself and number one. For example, numbers 2, 3, 5 are prime and numbers 1, 4, 6 are not. A matrix is prime if at least one of the two following conditions fulfills: the matrix has a row with prime numbers only; the matrix has a column with prime numbers only; Your task is to count the minimum number of moves needed to get a prime matrix from the one you've got.
256 megabytes
import java.util.Date; import java.util.Scanner; public class Solution1 { /** * @param args */ public static void main(String[] args) { int length = 100005; int[] plainNumbersDistance = new int[length]; int[] plainNumber = new int [length]; for(int i=0;i<plainNumber.length;i++){ plainNumber[i] = i+1; } plainNumber[0] = -1; getNumbers(plainNumber); int prevPlain = 2; plainNumbersDistance[0] = 1; for(int i=2;i<plainNumber.length;i++){ if(plainNumber[i] == -1){ continue; } int currentPlain = plainNumber[i]; for(int j = prevPlain+1;j<currentPlain;j++){ plainNumbersDistance[j-1] = currentPlain-j; } plainNumbersDistance[currentPlain-1]=0; prevPlain = currentPlain; } @SuppressWarnings("resource") Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int m = sc.nextInt(); int[][] input = new int[n][m]; int minRow = Integer.MAX_VALUE; int current = 0; for(int i=0;i<n;i++){ for(int j=0;j<m;j++){ input[i][j] = plainNumbersDistance[sc.nextInt()-1]; current += input[i][j]; } if(current<minRow){ minRow = current; } current=0; } if(minRow==0){ System.out.println(0); return; } current = 0; int minColumn = Integer.MAX_VALUE; for(int i=0;i<m;i++){ for(int j=0;j<n;j++){ current += input[j][i]; } if(current<minColumn){ minColumn = current; } current=0; } if(minColumn<minRow){ System.out.println(minColumn); }else{ System.out.println(minRow); } } private static void getNumbers(int[] plainNumber) { for(int i =2;i<plainNumber.length+1;i++){ int a =2; while(a*i<plainNumber.length){ plainNumber[a*i-1] = -1; a++; } } } private static void sort(double[] coor, int l, int r) { if(l<r){ int q = (l+r)/2; sort(coor, l,q); sort(coor,q+1,r); merge(coor,l,q,r); } } private static void merge(double[] coor, int l, int q, int r) { int n1 = q-l+1; int n2 = r-q; double[] left = new double[n1+1]; double[] right = new double[n2+1]; for(int i=0;i<n1;i++){ left[i] = coor[l+i]; } for(int i=0;i<n2;i++){ right[i] = coor[q+i+1]; } left[n1] = Double.MAX_VALUE; right[n2] = Double.MAX_VALUE; int i=0,j=0; for(int k=l;k<=r;k++){ if(left[i]<right[j]){ coor[k] = left[i]; i++; }else{ coor[k]=right[j]; j++; } } } }
Java
["3 3\n1 2 3\n5 6 1\n4 4 1", "2 3\n4 8 8\n9 2 9", "2 2\n1 3\n4 2"]
2 seconds
["1", "3", "0"]
NoteIn the first sample you need to increase number 1 in cell (1, 1). Thus, the first row will consist of prime numbers: 2, 2, 3.In the second sample you need to increase number 8 in cell (1, 2) three times. Thus, the second column will consist of prime numbers: 11, 2.In the third sample you don't have to do anything as the second column already consists of prime numbers: 3, 2.
Java 6
standard input
[ "binary search", "number theory", "brute force", "math" ]
d549f70d028a884f0313743c09c685f1
The first line contains two integers n, m (1 ≀ n, m ≀ 500) β€” the number of rows and columns in the matrix, correspondingly. Each of the following n lines contains m integers β€” the initial matrix. All matrix elements are positive integers. All numbers in the initial matrix do not exceed 105. The numbers in the lines are separated by single spaces.
1,300
Print a single integer β€” the minimum number of moves needed to get a prime matrix from the one you've got. If you've got a prime matrix, print 0.
standard output
PASSED
cf9fdf54795cedc7f8076caf8917e20a
train_000.jsonl
1360596600
You've got an n × m matrix. The matrix consists of integers. In one move, you can apply a single transformation to the matrix: choose an arbitrary element of the matrix and increase it by 1. Each element can be increased an arbitrary number of times.You are really curious about prime numbers. Let us remind you that a prime number is a positive integer that has exactly two distinct positive integer divisors: itself and number one. For example, numbers 2, 3, 5 are prime and numbers 1, 4, 6 are not. A matrix is prime if at least one of the two following conditions fulfills: the matrix has a row with prime numbers only; the matrix has a column with prime numbers only; Your task is to count the minimum number of moves needed to get a prime matrix from the one you've got.
256 megabytes
import java.io.*; import java.util.*; public class ProblemB { InputReader in; PrintWriter out; boolean[] isPrime = new boolean[1000000]; int f(int a) { int k = 0; while (!isPrime[a + k]) k++; return k; } void solve() { int n = in.nextInt(); int m = in.nextInt(); int[][] a = new int[n][m]; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) a[i][j] = in.nextInt(); Arrays.fill(isPrime, true); isPrime[0] = false; isPrime[1] = false; for (int i = 2; i < 1000000; i++) { for (int j = i + i; j < 1000000; j += i) isPrime[j] = false; } int ans = Integer.MAX_VALUE / 2; for (int i = 0; i < n; i++) { int cur = 0; for (int j = 0; j < m; j++) cur += f(a[i][j]); if (cur < ans) ans = cur; } for (int j = 0; j < m; j++) { int cur = 0; for (int i = 0; i < n; i++) cur += f(a[i][j]); if (cur < ans) ans = cur; } out.println(ans); } ProblemB(){ boolean oj = System.getProperty("ONLINE_JUDGE") != null; try { if (oj) { in = new InputReader(System.in); out = new PrintWriter(System.out); } else { Writer w = new FileWriter("output.txt"); in = new InputReader(new FileReader("input.txt")); out = new PrintWriter(w); } } catch(Exception e) { throw new RuntimeException(e); } solve(); out.close(); } public static void main(String[] args){ new ProblemB(); } } class InputReader { private BufferedReader reader; private StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); tokenizer = null; } public InputReader(FileReader fr) { reader = new BufferedReader(fr); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } }
Java
["3 3\n1 2 3\n5 6 1\n4 4 1", "2 3\n4 8 8\n9 2 9", "2 2\n1 3\n4 2"]
2 seconds
["1", "3", "0"]
NoteIn the first sample you need to increase number 1 in cell (1, 1). Thus, the first row will consist of prime numbers: 2, 2, 3.In the second sample you need to increase number 8 in cell (1, 2) three times. Thus, the second column will consist of prime numbers: 11, 2.In the third sample you don't have to do anything as the second column already consists of prime numbers: 3, 2.
Java 6
standard input
[ "binary search", "number theory", "brute force", "math" ]
d549f70d028a884f0313743c09c685f1
The first line contains two integers n, m (1 ≀ n, m ≀ 500) β€” the number of rows and columns in the matrix, correspondingly. Each of the following n lines contains m integers β€” the initial matrix. All matrix elements are positive integers. All numbers in the initial matrix do not exceed 105. The numbers in the lines are separated by single spaces.
1,300
Print a single integer β€” the minimum number of moves needed to get a prime matrix from the one you've got. If you've got a prime matrix, print 0.
standard output
PASSED
22bf06108d3d1f635850f9998f862a9d
train_000.jsonl
1360596600
You've got an n × m matrix. The matrix consists of integers. In one move, you can apply a single transformation to the matrix: choose an arbitrary element of the matrix and increase it by 1. Each element can be increased an arbitrary number of times.You are really curious about prime numbers. Let us remind you that a prime number is a positive integer that has exactly two distinct positive integer divisors: itself and number one. For example, numbers 2, 3, 5 are prime and numbers 1, 4, 6 are not. A matrix is prime if at least one of the two following conditions fulfills: the matrix has a row with prime numbers only; the matrix has a column with prime numbers only; Your task is to count the minimum number of moves needed to get a prime matrix from the one you've got.
256 megabytes
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.Scanner; /** * * @author DELL */ public class PrimeMatrix { public static void main(String[] args) throws IOException { BufferedReader s = new BufferedReader(new InputStreamReader(System.in)); String[] hold = s.readLine().split(" "); int n, m; n = Integer.parseInt(hold[0]); m = Integer.parseInt(hold[1]); int[][] matrix = new int[n][m]; int[] count = new int[n + m]; int temp; boolean[] prime = new boolean[100004]; for (int i = 0; i < 100004; i++) { temp = i; if (temp == 1 || temp == 0) { prime[i] = false; } else { prime[i] = true; for (int k = 2; k <= Math.sqrt(temp); k++) { if (temp % k == 0) { prime[i] = false; break; } } } } int add = 0, num = 0; boolean yes = false; for (int i = 0; i < n; i++) { add = 0; hold = s.readLine().split(" "); for (int j = 0; j < m; j++) { num = Integer.parseInt(hold[j]); matrix[i][j] = num; if (prime[num] == true) { matrix[i][j] = 0; } else { while (prime[num] == false) { num++; } add += num - matrix[i][j]; matrix[i][j] = num - matrix[i][j]; } } count[i] = add; } for (int i = 0; i < m; i++) { add = 0; for (int j = 0; j < n; j++) { add = add + matrix[j][i]; } count[i + n] = add; } Arrays.sort(count); System.out.println(count[0]); } }
Java
["3 3\n1 2 3\n5 6 1\n4 4 1", "2 3\n4 8 8\n9 2 9", "2 2\n1 3\n4 2"]
2 seconds
["1", "3", "0"]
NoteIn the first sample you need to increase number 1 in cell (1, 1). Thus, the first row will consist of prime numbers: 2, 2, 3.In the second sample you need to increase number 8 in cell (1, 2) three times. Thus, the second column will consist of prime numbers: 11, 2.In the third sample you don't have to do anything as the second column already consists of prime numbers: 3, 2.
Java 6
standard input
[ "binary search", "number theory", "brute force", "math" ]
d549f70d028a884f0313743c09c685f1
The first line contains two integers n, m (1 ≀ n, m ≀ 500) β€” the number of rows and columns in the matrix, correspondingly. Each of the following n lines contains m integers β€” the initial matrix. All matrix elements are positive integers. All numbers in the initial matrix do not exceed 105. The numbers in the lines are separated by single spaces.
1,300
Print a single integer β€” the minimum number of moves needed to get a prime matrix from the one you've got. If you've got a prime matrix, print 0.
standard output
PASSED
2c2ae107fb04ff5e1198e6003a7e2b59
train_000.jsonl
1360596600
You've got an n × m matrix. The matrix consists of integers. In one move, you can apply a single transformation to the matrix: choose an arbitrary element of the matrix and increase it by 1. Each element can be increased an arbitrary number of times.You are really curious about prime numbers. Let us remind you that a prime number is a positive integer that has exactly two distinct positive integer divisors: itself and number one. For example, numbers 2, 3, 5 are prime and numbers 1, 4, 6 are not. A matrix is prime if at least one of the two following conditions fulfills: the matrix has a row with prime numbers only; the matrix has a column with prime numbers only; Your task is to count the minimum number of moves needed to get a prime matrix from the one you've got.
256 megabytes
import java.util.Arrays; import java.util.Scanner; public class Main { private Scanner sc = new Scanner(System.in); private static double EPS = 1e-9; private static final int INF = Integer.MAX_VALUE; public static void main(String[] args) { new Main().run(); } private void run() { read(); solve(); } private int n; private int m; private int[][] matrix; private void read() { n = sc.nextInt(); m = sc.nextInt(); matrix = new int[n][m]; for (int y = 0; y < n; y++) { for (int x = 0; x < m; x++) { matrix[y][x] = sc.nextInt(); } } } private boolean[] sieve; private void init() { sieve = new boolean[200000]; Arrays.fill(sieve, true); sieve[0] = false; sieve[1] = false; for (int i = 2; i < sieve.length; i++) { if (sieve[i]) { for (int j = i * 2; j < sieve.length; j += i) { sieve[j] = false; } } } } private int nextPrime(int num) { for (int i = num; i < sieve.length; i++) { if (sieve[i]) return i; } return -1; } private void solve() { init(); int[][] next = new int[n][m]; for (int y = 0; y < n; y++) { for (int x = 0; x < m; x++) { next[y][x] = nextPrime(matrix[y][x]) - matrix[y][x]; } } int[] row = new int[n]; int[] column = new int[m]; for (int y = 0; y < n; y++) { for (int x = 0; x < m; x++) { row[y] += next[y][x]; } } for (int x = 0; x < m; x++) { for (int y = 0; y < n; y++) { column[x] += next[y][x]; } } Arrays.sort(row); Arrays.sort(column); System.out.println(Math.min(column[0], row[0])); } }
Java
["3 3\n1 2 3\n5 6 1\n4 4 1", "2 3\n4 8 8\n9 2 9", "2 2\n1 3\n4 2"]
2 seconds
["1", "3", "0"]
NoteIn the first sample you need to increase number 1 in cell (1, 1). Thus, the first row will consist of prime numbers: 2, 2, 3.In the second sample you need to increase number 8 in cell (1, 2) three times. Thus, the second column will consist of prime numbers: 11, 2.In the third sample you don't have to do anything as the second column already consists of prime numbers: 3, 2.
Java 6
standard input
[ "binary search", "number theory", "brute force", "math" ]
d549f70d028a884f0313743c09c685f1
The first line contains two integers n, m (1 ≀ n, m ≀ 500) β€” the number of rows and columns in the matrix, correspondingly. Each of the following n lines contains m integers β€” the initial matrix. All matrix elements are positive integers. All numbers in the initial matrix do not exceed 105. The numbers in the lines are separated by single spaces.
1,300
Print a single integer β€” the minimum number of moves needed to get a prime matrix from the one you've got. If you've got a prime matrix, print 0.
standard output
PASSED
f6c662bad1bb6d449fef489d676600ad
train_000.jsonl
1360596600
You've got an n × m matrix. The matrix consists of integers. In one move, you can apply a single transformation to the matrix: choose an arbitrary element of the matrix and increase it by 1. Each element can be increased an arbitrary number of times.You are really curious about prime numbers. Let us remind you that a prime number is a positive integer that has exactly two distinct positive integer divisors: itself and number one. For example, numbers 2, 3, 5 are prime and numbers 1, 4, 6 are not. A matrix is prime if at least one of the two following conditions fulfills: the matrix has a row with prime numbers only; the matrix has a column with prime numbers only; Your task is to count the minimum number of moves needed to get a prime matrix from the one you've got.
256 megabytes
import java.io.PrintWriter; import java.util.Arrays; import java.util.Scanner; import java.util.TreeMap; public class B { static final int MAX = 100500; public static void main(String[] args) { doIt(); } static void doIt() { Scanner sc = new Scanner(System.in); PrintWriter pw = new PrintWriter(System.out); boolean[] prime = new boolean[MAX]; Arrays.fill(prime, true); prime[0] = prime[1] = false; TreeMap<Integer, Integer> map = new TreeMap<Integer, Integer>(); for (int i = 2; i < prime.length; i++) { if(prime[i]){ map.put(i, 0); for (int j = i*2; j < prime.length; j += i) { prime[j] = false; } } } int n = sc.nextInt(); int m = sc.nextInt(); int[][] matrix = new int[n][m]; int[] rowsum = new int[n]; int[] clmsum = new int[m]; for (int i = 0; i < n; i++) { for(int j = 0; j < m; j++) { int e = sc.nextInt(); if(prime[e]) matrix[i][j] = 0; else matrix[i][j] = map.ceilingKey(e) - e; rowsum[i] += matrix[i][j]; clmsum[j] += matrix[i][j]; } } Arrays.sort(rowsum); Arrays.sort(clmsum); System.out.println(Math.min(rowsum[0], clmsum[0])); } }
Java
["3 3\n1 2 3\n5 6 1\n4 4 1", "2 3\n4 8 8\n9 2 9", "2 2\n1 3\n4 2"]
2 seconds
["1", "3", "0"]
NoteIn the first sample you need to increase number 1 in cell (1, 1). Thus, the first row will consist of prime numbers: 2, 2, 3.In the second sample you need to increase number 8 in cell (1, 2) three times. Thus, the second column will consist of prime numbers: 11, 2.In the third sample you don't have to do anything as the second column already consists of prime numbers: 3, 2.
Java 6
standard input
[ "binary search", "number theory", "brute force", "math" ]
d549f70d028a884f0313743c09c685f1
The first line contains two integers n, m (1 ≀ n, m ≀ 500) β€” the number of rows and columns in the matrix, correspondingly. Each of the following n lines contains m integers β€” the initial matrix. All matrix elements are positive integers. All numbers in the initial matrix do not exceed 105. The numbers in the lines are separated by single spaces.
1,300
Print a single integer β€” the minimum number of moves needed to get a prime matrix from the one you've got. If you've got a prime matrix, print 0.
standard output
PASSED
ca486d56816ddb09c8563dd69ef86fd8
train_000.jsonl
1360596600
You've got an n × m matrix. The matrix consists of integers. In one move, you can apply a single transformation to the matrix: choose an arbitrary element of the matrix and increase it by 1. Each element can be increased an arbitrary number of times.You are really curious about prime numbers. Let us remind you that a prime number is a positive integer that has exactly two distinct positive integer divisors: itself and number one. For example, numbers 2, 3, 5 are prime and numbers 1, 4, 6 are not. A matrix is prime if at least one of the two following conditions fulfills: the matrix has a row with prime numbers only; the matrix has a column with prime numbers only; Your task is to count the minimum number of moves needed to get a prime matrix from the one you've got.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.StringTokenizer; public class B { static int[][] nums; static boolean[] v; static int[] primes; public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); int n = Integer.parseInt(st.nextToken()), m = Integer.parseInt(st.nextToken()); nums = new int[n][m]; for (int i = 0; i < n; i++) { st = new StringTokenizer(br.readLine()); for (int j = 0; j < m; j++) nums[i][j] = Integer.parseInt(st.nextToken()); } seive(110000); int[][] cost = new int[n][m]; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) if (v[nums[i][j]]) { int idx = -Arrays.binarySearch(primes, nums[i][j]) - 1; cost[i][j] = primes[idx] - nums[i][j]; } int min = Integer.MAX_VALUE; // rows for (int i = 0; i < n; i++) { int sum = 0; for(int j = 0; j < m; j++) sum += cost[i][j]; min = Math.min(min, sum); } // columns for (int i = 0; i < m; i++) { int sum = 0; for(int j = 0; j < n; j++) sum += cost[j][i]; min = Math.min(min, sum); } System.out.println(min); } static void seive(int n) { v = new boolean[n + 1]; v[1] = true; for (int i = 2; i * i <= n; i += (1 + (i & 1))) for (int j = i + i; j <= n; j += i) v[j] = true; int idx = 0; primes = new int[10453]; for (int i = 2; i <= n; i++) if (!v[i]) primes[idx++] = i; } }
Java
["3 3\n1 2 3\n5 6 1\n4 4 1", "2 3\n4 8 8\n9 2 9", "2 2\n1 3\n4 2"]
2 seconds
["1", "3", "0"]
NoteIn the first sample you need to increase number 1 in cell (1, 1). Thus, the first row will consist of prime numbers: 2, 2, 3.In the second sample you need to increase number 8 in cell (1, 2) three times. Thus, the second column will consist of prime numbers: 11, 2.In the third sample you don't have to do anything as the second column already consists of prime numbers: 3, 2.
Java 6
standard input
[ "binary search", "number theory", "brute force", "math" ]
d549f70d028a884f0313743c09c685f1
The first line contains two integers n, m (1 ≀ n, m ≀ 500) β€” the number of rows and columns in the matrix, correspondingly. Each of the following n lines contains m integers β€” the initial matrix. All matrix elements are positive integers. All numbers in the initial matrix do not exceed 105. The numbers in the lines are separated by single spaces.
1,300
Print a single integer β€” the minimum number of moves needed to get a prime matrix from the one you've got. If you've got a prime matrix, print 0.
standard output
PASSED
19f0c3e80eeedf3c4b059ed5fdc03e88
train_000.jsonl
1360596600
You've got an n × m matrix. The matrix consists of integers. In one move, you can apply a single transformation to the matrix: choose an arbitrary element of the matrix and increase it by 1. Each element can be increased an arbitrary number of times.You are really curious about prime numbers. Let us remind you that a prime number is a positive integer that has exactly two distinct positive integer divisors: itself and number one. For example, numbers 2, 3, 5 are prime and numbers 1, 4, 6 are not. A matrix is prime if at least one of the two following conditions fulfills: the matrix has a row with prime numbers only; the matrix has a column with prime numbers only; Your task is to count the minimum number of moves needed to get a prime matrix from the one you've got.
256 megabytes
import java.util.Scanner; public class B { public static void main(String[] args) { Scanner in = new Scanner(System.in); boolean[] gh = new boolean[1000000]; for (int i = 2; i < 1000000; i++) { if (!gh[i]) { for (int j = i + i; j < 1000000; j += i) { gh[j] = true; } } } gh[0] = gh[1] = true; int n = in.nextInt(); int m = in.nextInt(); int[][] mat = new int[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { mat[i][j] = in.nextInt(); } } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { for (int k = mat[i][j]; k < 1000000; k++) { if (!gh[k]) { mat[i][j] = k - mat[i][j]; break; } } } } int min = 0; for (int i = 0; i < n; i++) { min += mat[i][0]; } for (int i = 0; i < n; i++) { int sum = 0; for (int j = 0; j < m; j++) { sum += mat[i][j]; } min = Math.min(min, sum); } for (int j = 0; j < m; j++) { int sum = 0; for (int i = 0; i < n; i++) { sum += mat[i][j]; } min = Math.min(min, sum); } System.out.println(min); } }
Java
["3 3\n1 2 3\n5 6 1\n4 4 1", "2 3\n4 8 8\n9 2 9", "2 2\n1 3\n4 2"]
2 seconds
["1", "3", "0"]
NoteIn the first sample you need to increase number 1 in cell (1, 1). Thus, the first row will consist of prime numbers: 2, 2, 3.In the second sample you need to increase number 8 in cell (1, 2) three times. Thus, the second column will consist of prime numbers: 11, 2.In the third sample you don't have to do anything as the second column already consists of prime numbers: 3, 2.
Java 6
standard input
[ "binary search", "number theory", "brute force", "math" ]
d549f70d028a884f0313743c09c685f1
The first line contains two integers n, m (1 ≀ n, m ≀ 500) β€” the number of rows and columns in the matrix, correspondingly. Each of the following n lines contains m integers β€” the initial matrix. All matrix elements are positive integers. All numbers in the initial matrix do not exceed 105. The numbers in the lines are separated by single spaces.
1,300
Print a single integer β€” the minimum number of moves needed to get a prime matrix from the one you've got. If you've got a prime matrix, print 0.
standard output
PASSED
31c0fafac458621b7caae8c9347b3054
train_000.jsonl
1360596600
You've got an n × m matrix. The matrix consists of integers. In one move, you can apply a single transformation to the matrix: choose an arbitrary element of the matrix and increase it by 1. Each element can be increased an arbitrary number of times.You are really curious about prime numbers. Let us remind you that a prime number is a positive integer that has exactly two distinct positive integer divisors: itself and number one. For example, numbers 2, 3, 5 are prime and numbers 1, 4, 6 are not. A matrix is prime if at least one of the two following conditions fulfills: the matrix has a row with prime numbers only; the matrix has a column with prime numbers only; Your task is to count the minimum number of moves needed to get a prime matrix from the one you've got.
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; public class Main { public static void main(String[] args) throws IOException { (new Main()).solve(); } public Main() { } MyReader in = new MyReader(); PrintWriter out = new PrintWriter(System.out); void solve() throws IOException { //BufferedReader in = new BufferedReader(new //InputStreamReader(System.in)); //Scanner in = new Scanner(System.in); int K = 100100; boolean[] a = new boolean[K]; a[0] = true; a[1] = true; a[2] = false; for (int i = 2; i < K; i++) { if (!a[i]) { for (int j = i * 2; j < K; j += i) { a[j] = true; } } } int[] next = new int[K]; int cur = -1; for (int i = K - 1; i >= 0; i--) { if (a[i]) { next[i] = cur - i; } else { cur = i; } } int n = in.nextInt(); int m = in.nextInt(); int[][] v = new int[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { v[i][j] = in.nextInt(); } } int min = Integer.MAX_VALUE; for (int i = 0; i < n; i++) { int sum = 0; for (int j = 0; j < m; j++) { sum += next[v[i][j]]; } if (sum < min) { min = sum; } } for (int j = 0; j < m; j++) { int sum = 0; for (int i = 0; i < n; i++) { sum += next[v[i][j]]; } if (sum < min) { min = sum; } } out.println(min); out.close(); } }; class MyReader { private BufferedReader in; String[] parsed; int index = 0; public MyReader() { in = new BufferedReader(new InputStreamReader(System.in)); } public int nextInt() throws NumberFormatException, IOException { if (parsed == null || parsed.length == index) { read(); } return Integer.parseInt(parsed[index++]); } public long nextLong() throws NumberFormatException, IOException { if (parsed == null || parsed.length == index) { read(); } return Long.parseLong(parsed[index++]); } public double nextDouble() throws NumberFormatException, IOException { if (parsed == null || parsed.length == index) { read(); } return Double.parseDouble(parsed[index++]); } public String nextString() throws IOException { if (parsed == null || parsed.length == index) { read(); } return parsed[index++]; } private void read() throws IOException { parsed = in.readLine().split(" "); index = 0; } public String readLine() throws IOException { return in.readLine(); } };
Java
["3 3\n1 2 3\n5 6 1\n4 4 1", "2 3\n4 8 8\n9 2 9", "2 2\n1 3\n4 2"]
2 seconds
["1", "3", "0"]
NoteIn the first sample you need to increase number 1 in cell (1, 1). Thus, the first row will consist of prime numbers: 2, 2, 3.In the second sample you need to increase number 8 in cell (1, 2) three times. Thus, the second column will consist of prime numbers: 11, 2.In the third sample you don't have to do anything as the second column already consists of prime numbers: 3, 2.
Java 6
standard input
[ "binary search", "number theory", "brute force", "math" ]
d549f70d028a884f0313743c09c685f1
The first line contains two integers n, m (1 ≀ n, m ≀ 500) β€” the number of rows and columns in the matrix, correspondingly. Each of the following n lines contains m integers β€” the initial matrix. All matrix elements are positive integers. All numbers in the initial matrix do not exceed 105. The numbers in the lines are separated by single spaces.
1,300
Print a single integer β€” the minimum number of moves needed to get a prime matrix from the one you've got. If you've got a prime matrix, print 0.
standard output
PASSED
508736a793125853102a913cf21626b9
train_000.jsonl
1360596600
You've got an n × m matrix. The matrix consists of integers. In one move, you can apply a single transformation to the matrix: choose an arbitrary element of the matrix and increase it by 1. Each element can be increased an arbitrary number of times.You are really curious about prime numbers. Let us remind you that a prime number is a positive integer that has exactly two distinct positive integer divisors: itself and number one. For example, numbers 2, 3, 5 are prime and numbers 1, 4, 6 are not. A matrix is prime if at least one of the two following conditions fulfills: the matrix has a row with prime numbers only; the matrix has a column with prime numbers only; Your task is to count the minimum number of moves needed to get a prime matrix from the one you've got.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.StringTokenizer; public class round166B { static BufferedReader br = new BufferedReader(new InputStreamReader( System.in)); static StringTokenizer st = new StringTokenizer(""); static int nextInt() throws Exception { return Integer.parseInt(next()); } static String next() throws Exception { while (true) { if (st.hasMoreTokens()) { return st.nextToken(); } String s = br.readLine(); if (s == null) { return null; } st = new StringTokenizer(s); } } static boolean [] prime; public static void generate(int N){ prime = new boolean [N + 1]; Arrays.fill(prime, true); prime[0] = prime[1] = false; for(int i = 2 ; i * i <= N ; ++i){ if(prime[i]){ for(int j = i ; j * i <= N ; ++j) prime[i * j] = false; } } } public static void main(String[] args)throws Exception { int n = nextInt(); int m = nextInt(); int [][] matrix = new int [n][m]; for(int i = 0 ; i < n ; ++i) for(int j = 0 ; j < m ; ++j) matrix[i][j] = nextInt(); generate(1000000); int min = Integer.MAX_VALUE; for(int i = 0 ; i < n ; ++i){//try each row int sum = 0; for(int j = 0 ; j < m ; ++j){ if(prime[matrix[i][j]]) continue; int k = matrix[i][j]; while(k < 1000000 && !prime[k]) ++k; sum += k - matrix[i][j]; } min = Math.min(min, sum); } for(int i = 0 ; i < m ; ++i){//try each column int sum = 0; for(int j = 0 ; j < n ; ++j){ if(prime[matrix[j][i]]) continue; int k = matrix[j][i]; while(k < 1000000 && !prime[k]) ++k; sum += k - matrix[j][i]; } min = Math.min(min, sum); } System.out.println(min); } }
Java
["3 3\n1 2 3\n5 6 1\n4 4 1", "2 3\n4 8 8\n9 2 9", "2 2\n1 3\n4 2"]
2 seconds
["1", "3", "0"]
NoteIn the first sample you need to increase number 1 in cell (1, 1). Thus, the first row will consist of prime numbers: 2, 2, 3.In the second sample you need to increase number 8 in cell (1, 2) three times. Thus, the second column will consist of prime numbers: 11, 2.In the third sample you don't have to do anything as the second column already consists of prime numbers: 3, 2.
Java 6
standard input
[ "binary search", "number theory", "brute force", "math" ]
d549f70d028a884f0313743c09c685f1
The first line contains two integers n, m (1 ≀ n, m ≀ 500) β€” the number of rows and columns in the matrix, correspondingly. Each of the following n lines contains m integers β€” the initial matrix. All matrix elements are positive integers. All numbers in the initial matrix do not exceed 105. The numbers in the lines are separated by single spaces.
1,300
Print a single integer β€” the minimum number of moves needed to get a prime matrix from the one you've got. If you've got a prime matrix, print 0.
standard output
PASSED
f14d98251dab6da37c63e5eedd28a889
train_000.jsonl
1520177700
Anya and Kirill are doing a physics laboratory work. In one of the tasks they have to measure some value n times, and then compute the average value to lower the error.Kirill has already made his measurements, and has got the following integer values: x1, x2, ..., xn. It is important that the values are close to each other, namely, the difference between the maximum value and the minimum value is at most 2.Anya does not want to make the measurements, however, she can't just copy the values from Kirill's work, because the error of each measurement is a random value, and this coincidence will be noted by the teacher. Anya wants to write such integer values y1, y2, ..., yn in her work, that the following conditions are met: the average value of x1, x2, ..., xn is equal to the average value of y1, y2, ..., yn; all Anya's measurements are in the same bounds as all Kirill's measurements, that is, the maximum value among Anya's values is not greater than the maximum value among Kirill's values, and the minimum value among Anya's values is not less than the minimum value among Kirill's values; the number of equal measurements in Anya's work and Kirill's work is as small as possible among options with the previous conditions met. Formally, the teacher goes through all Anya's values one by one, if there is equal value in Kirill's work and it is not strike off yet, he strikes off this Anya's value and one of equal values in Kirill's work. The number of equal measurements is then the total number of strike off values in Anya's work. Help Anya to write such a set of measurements that the conditions above are met.
256 megabytes
import java.io.*; import java.util.*; public class A { public static void main(String[] args) throws Exception { Scanner in = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int n = in.nextInt(); int[] x = new int[n]; int min, max; x[0] = in.nextInt(); min = x[0]; max = x[0]; for (int i = 1; i < n; i++) { x[i] = in.nextInt(); if (x[i] > max) max = x[i]; if (x[i] < min) min = x[i]; } int d = max - min; if (d == 0 || d == 1) { System.out.println(n); for (int i = 0; i < n; i++) System.out.print(x[i] + " "); } if (d == 2) { int z = 0; int m = 0; int p = 0; for (int i = 0; i < n; i++) if (x[i] == min) m++; else if (x[i] == max) p++; else z++; int pmmax = Math.min(p, m); int zmax = z % 2 == 0 ? z : z - 1; if (2 * pmmax > zmax) { System.out.println(n - 2 * pmmax); for (int i = 0; i < z; i++) System.out.print(max - 1 + " "); for (int i = 0; i < pmmax; i++) { System.out.print(max - 1 + " "); System.out.print(max - 1 + " "); } int q = p > m ? max : min; for (int i = 0; i < n - z - pmmax * 2; i++) System.out.print(q + " "); } else { System.out.println(n - zmax); for (int i = 0; i < p; i++) System.out.print(max + " "); for (int i = 0; i < m; i++) System.out.print(min + " "); for (int i = 0; i < zmax / 2; i++) { System.out.print(max + " "); System.out.print(min + " "); } for (int i = 0; i < z - zmax; i++) System.out.print(max - 1 + " "); } } out.close(); } }
Java
["6\n-1 1 1 0 0 -1", "3\n100 100 101", "7\n-10 -9 -10 -8 -10 -9 -9"]
1 second
["2\n0 0 0 0 0 0", "3\n101 100 100", "5\n-10 -10 -9 -9 -9 -9 -9"]
NoteIn the first example Anya can write zeros as here measurements results. The average value is then equal to the average value of Kirill's values, and there are only two equal measurements.In the second example Anya should write two values 100 and one value 101 (in any order), because it is the only possibility to make the average be the equal to the average of Kirill's values. Thus, all three measurements are equal.In the third example the number of equal measurements is 5.
Java 8
standard input
[ "implementation", "math" ]
dbbea6784cafdd4244f56729996e9187
The first line contains a single integer n (1 ≀ n ≀ 100 000) β€” the numeber of measurements made by Kirill. The second line contains a sequence of integers x1, x2, ..., xn ( - 100 000 ≀ xi ≀ 100 000) β€” the measurements made by Kirill. It is guaranteed that the difference between the maximum and minimum values among values x1, x2, ..., xn does not exceed 2.
1,700
In the first line print the minimum possible number of equal measurements. In the second line print n integers y1, y2, ..., yn β€” the values Anya should write. You can print the integers in arbitrary order. Keep in mind that the minimum value among Anya's values should be not less that the minimum among Kirill's values, and the maximum among Anya's values should be not greater than the maximum among Kirill's values. If there are multiple answers, print any of them.
standard output
PASSED
f0944181e9c5a765cf2e0fe22f509d92
train_000.jsonl
1520177700
Anya and Kirill are doing a physics laboratory work. In one of the tasks they have to measure some value n times, and then compute the average value to lower the error.Kirill has already made his measurements, and has got the following integer values: x1, x2, ..., xn. It is important that the values are close to each other, namely, the difference between the maximum value and the minimum value is at most 2.Anya does not want to make the measurements, however, she can't just copy the values from Kirill's work, because the error of each measurement is a random value, and this coincidence will be noted by the teacher. Anya wants to write such integer values y1, y2, ..., yn in her work, that the following conditions are met: the average value of x1, x2, ..., xn is equal to the average value of y1, y2, ..., yn; all Anya's measurements are in the same bounds as all Kirill's measurements, that is, the maximum value among Anya's values is not greater than the maximum value among Kirill's values, and the minimum value among Anya's values is not less than the minimum value among Kirill's values; the number of equal measurements in Anya's work and Kirill's work is as small as possible among options with the previous conditions met. Formally, the teacher goes through all Anya's values one by one, if there is equal value in Kirill's work and it is not strike off yet, he strikes off this Anya's value and one of equal values in Kirill's work. The number of equal measurements is then the total number of strike off values in Anya's work. Help Anya to write such a set of measurements that the conditions above are met.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; import java.io.Writer; import java.io.OutputStreamWriter; import java.io.BufferedReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Vikash Kumar */ 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); CodeChef solver = new CodeChef(); solver.solve(1, in, out); out.close(); } static class CodeChef { public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.ni(); int[] arr = in.nia(n); int min = Integer.MAX_VALUE, max = Integer.MIN_VALUE; for (int i = 0; i < n; i++) { if (arr[i] < min) min = arr[i]; if (arr[i] > max) max = arr[i]; } if (Math.abs(max - min) <= 1) { out.println(n); for (int i = 0; i < n; i++) { out.print(arr[i] + " "); } out.println(); } else { int a = 0, b = 0, c = 0; for (int i = 0; i < n; i++) { if (arr[i] == min) a++; else if (arr[i] == max) c++; else b++; } int t = Math.max(b / 2, Math.min(a, c)); if (t == Math.min(a, c)) { a -= t; c -= t; b += 2 * t; } else { a += t; b -= 2 * t; c += t; } out.println(n - 2 * t); //out.println(a + " " + b + " " + c); int avg = (min + max) / 2; //out.println(avg); for (int i = 0; i < n; i++) { int num = avg; if (i < a) { num += -1; } else if (i < a + c) { num += 1; } out.print(num + " "); } out.println(); } } } 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 println(int i) { writer.println(i); } } static class InputReader { private BufferedReader br; private StringTokenizer st; public InputReader(InputStream inputStream) { br = new BufferedReader(new InputStreamReader(inputStream)); } public String n() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { } } return st.nextToken(); } public int ni() { return Integer.parseInt(n()); } public int[] nia(int n) { int[] array = new int[n]; for (int i = 0; i < n; ++i) array[i] = ni(); return array; } } }
Java
["6\n-1 1 1 0 0 -1", "3\n100 100 101", "7\n-10 -9 -10 -8 -10 -9 -9"]
1 second
["2\n0 0 0 0 0 0", "3\n101 100 100", "5\n-10 -10 -9 -9 -9 -9 -9"]
NoteIn the first example Anya can write zeros as here measurements results. The average value is then equal to the average value of Kirill's values, and there are only two equal measurements.In the second example Anya should write two values 100 and one value 101 (in any order), because it is the only possibility to make the average be the equal to the average of Kirill's values. Thus, all three measurements are equal.In the third example the number of equal measurements is 5.
Java 8
standard input
[ "implementation", "math" ]
dbbea6784cafdd4244f56729996e9187
The first line contains a single integer n (1 ≀ n ≀ 100 000) β€” the numeber of measurements made by Kirill. The second line contains a sequence of integers x1, x2, ..., xn ( - 100 000 ≀ xi ≀ 100 000) β€” the measurements made by Kirill. It is guaranteed that the difference between the maximum and minimum values among values x1, x2, ..., xn does not exceed 2.
1,700
In the first line print the minimum possible number of equal measurements. In the second line print n integers y1, y2, ..., yn β€” the values Anya should write. You can print the integers in arbitrary order. Keep in mind that the minimum value among Anya's values should be not less that the minimum among Kirill's values, and the maximum among Anya's values should be not greater than the maximum among Kirill's values. If there are multiple answers, print any of them.
standard output
PASSED
f39336359ac63a5be4b6c3c64c30037e
train_000.jsonl
1520177700
Anya and Kirill are doing a physics laboratory work. In one of the tasks they have to measure some value n times, and then compute the average value to lower the error.Kirill has already made his measurements, and has got the following integer values: x1, x2, ..., xn. It is important that the values are close to each other, namely, the difference between the maximum value and the minimum value is at most 2.Anya does not want to make the measurements, however, she can't just copy the values from Kirill's work, because the error of each measurement is a random value, and this coincidence will be noted by the teacher. Anya wants to write such integer values y1, y2, ..., yn in her work, that the following conditions are met: the average value of x1, x2, ..., xn is equal to the average value of y1, y2, ..., yn; all Anya's measurements are in the same bounds as all Kirill's measurements, that is, the maximum value among Anya's values is not greater than the maximum value among Kirill's values, and the minimum value among Anya's values is not less than the minimum value among Kirill's values; the number of equal measurements in Anya's work and Kirill's work is as small as possible among options with the previous conditions met. Formally, the teacher goes through all Anya's values one by one, if there is equal value in Kirill's work and it is not strike off yet, he strikes off this Anya's value and one of equal values in Kirill's work. The number of equal measurements is then the total number of strike off values in Anya's work. Help Anya to write such a set of measurements that the conditions above are met.
256 megabytes
import java.io.*; import java.math.*; import java.util.*; import static java.util.Arrays.fill; import static java.lang.Math.*; import static java.util.Arrays.sort; import static java.util.Collections.sort; public class C931 { public static int mod = 1000000007; public static long INF = (1L << 60); static FastScanner2 in = new FastScanner2(); static OutputWriter out = new OutputWriter(System.out); public static void main(String[] args) { long n=in.nextInt(); long initsum=0; long[] arr=new long[(int) n]; TreeSet<Long> ts=new TreeSet<>(); for(int i=0;i<n;i++) { arr[i]=in.nextLong(); initsum+=arr[i]; ts.add(arr[i]); } long[] x=new long[3]; Arrays.fill(x, mod); long n1=0,n2=0,n3=0; int cc=0; while(!ts.isEmpty()) { x[cc++]=ts.first(); ts.remove(ts.first()); } for(int i=0;i<n;i++) { if(arr[i]==x[0]) n1++; else if(arr[i]==x[1]) n2++; else n3++; } if(x[1]==mod && x[2]==mod) { out.println(n); for(int i=1;i<=n1;i++) out.print(x[0]+" "); out.flush(); return; } if(x[2]==mod && x[1]-x[0]<2) { out.println(n); for(int i=1;i<=n1;i++) out.print(x[0]+" "); for(int i=1;i<=n2;i++) out.print(x[1]+" "); out.flush(); return; } //tr(n1+" "+n2+" "+n3); if(x[2]==mod) { x[2]=x[1]; x[1]=x[2]-1; x[0]=x[1]-1; n3=n2; n2=0; } if(n1==n3) { long newn1=n1,newn2=n2,newn3=n3; long answer=mod; for(int i=0;i<=n;i++) { if(i+i>n) break; long tempn1=i; long tempn3=i; long tempn2=n-i-i; if(min(tempn1, n1)+min(tempn2, n2)+min(tempn3, n3)<answer&& tempn1*x[0]+tempn2*x[1]+tempn3*x[2]==initsum) { answer=min(tempn1, n1)+min(tempn2, n2)+min(tempn3, n3); newn1=tempn1; newn2=tempn2; newn3=tempn3; } } out.println(answer); for(int i=1;i<=newn1;i++) out.print(x[0]+" "); for(int i=1;i<=newn2;i++) out.print(x[1]+" "); for(int i=1;i<=newn3;i++) out.print(x[2]+" "); } if(n3>n1) { long c=n3-n1; long newn1=n1,newn2=n2,newn3=n3; long answer=mod; for(int i=0;i<=n;i++) { long tempn1=i; long tempn3=c+i; long tempn2=n-i-c-i; if(tempn2<0 || tempn3>n) continue; if(min(tempn1, n1)+min(tempn2, n2)+min(tempn3, n3)<answer&& tempn1*x[0]+tempn2*x[1]+tempn3*x[2]==initsum) { answer=min(tempn1, n1)+min(tempn2, n2)+min(tempn3, n3); newn1=tempn1; newn2=tempn2; newn3=tempn3; } } out.println(answer); for(int i=1;i<=newn1;i++) out.print(x[0]+" "); for(int i=1;i<=newn2;i++) out.print(x[1]+" "); for(int i=1;i<=newn3;i++) out.print(x[2]+" "); } if(n1>n3) { long c=n1-n3; long newn1=n1,newn2=n2,newn3=n3; long answer=mod; for(int i=0;i<=n;i++) { long tempn1=i; long tempn3=i-c; long tempn2=n-i+c-i; if(tempn2<0 || tempn3<0 || tempn3>n || tempn2>n) continue; if(min(tempn1, n1)+min(tempn2, n2)+min(tempn3, n3)<answer && tempn1*x[0]+tempn2*x[1]+tempn3*x[2]==initsum) { answer=min(tempn1, n1)+min(tempn2, n2)+min(tempn3, n3); newn1=tempn1; newn2=tempn2; newn3=tempn3; } } out.println(answer); for(int i=1;i<=newn1;i++) out.print(x[0]+" "); for(int i=1;i<=newn2;i++) out.print(x[1]+" "); for(int i=1;i<=newn3;i++) out.print(x[2]+" "); } out.close(); } public static long pow(long x, long n) { long res = 1; for (long p = x; n > 0; n >>= 1, p = (p * p)) { if ((n & 1) != 0) { res = (res * p); } } return res; } public static long pow(long x, long n, long mod) { long res = 1; for (long p = x; n > 0; n >>= 1, p = (p * p) % mod) { if ((n & 1) != 0) { res = (res * p % mod); } } return res; } public static long gcd(long n1, long n2) { long r; while (n2 != 0) { r = n1 % n2; n1 = n2; n2 = r; } return n1; } public static long lcm(long n1, long n2) { long answer = (n1 * n2) / (gcd(n1, n2)); return answer; } static class FastScanner2 { private byte[] buf = new byte[1024]; private int curChar; private int snumChars; public int read() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = System.in.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public String nextString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = nextInt(); } return arr; } public long[] nextLongArray(int n) { long[] arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = nextLong(); } return arr; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream inputstream) { reader = new BufferedReader(new InputStreamReader(inputstream)); tokenizer = null; } public String nextLine() { String fullLine = null; while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { fullLine = reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } return fullLine; } return fullLine; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public long nextLong() { return Long.parseLong(next()); } public int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } public long[] nextLongArray(int n) { long a[] = new long[n]; for (int i = 0; i < n; i++) { a[i] = nextLong(); } return a; } public int nextInt() { return Integer.parseInt(next()); } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.print(objects[i]); } } public void println(Object... objects) { print(objects); writer.println(); } public void close() { writer.close(); } public void flush() { writer.flush(); } } private static boolean oj = System.getProperty("ONLINE_JUDGE") != null; private static void tr(Object... o) { if (!oj) System.out.println(Arrays.deepToString(o)); } }
Java
["6\n-1 1 1 0 0 -1", "3\n100 100 101", "7\n-10 -9 -10 -8 -10 -9 -9"]
1 second
["2\n0 0 0 0 0 0", "3\n101 100 100", "5\n-10 -10 -9 -9 -9 -9 -9"]
NoteIn the first example Anya can write zeros as here measurements results. The average value is then equal to the average value of Kirill's values, and there are only two equal measurements.In the second example Anya should write two values 100 and one value 101 (in any order), because it is the only possibility to make the average be the equal to the average of Kirill's values. Thus, all three measurements are equal.In the third example the number of equal measurements is 5.
Java 8
standard input
[ "implementation", "math" ]
dbbea6784cafdd4244f56729996e9187
The first line contains a single integer n (1 ≀ n ≀ 100 000) β€” the numeber of measurements made by Kirill. The second line contains a sequence of integers x1, x2, ..., xn ( - 100 000 ≀ xi ≀ 100 000) β€” the measurements made by Kirill. It is guaranteed that the difference between the maximum and minimum values among values x1, x2, ..., xn does not exceed 2.
1,700
In the first line print the minimum possible number of equal measurements. In the second line print n integers y1, y2, ..., yn β€” the values Anya should write. You can print the integers in arbitrary order. Keep in mind that the minimum value among Anya's values should be not less that the minimum among Kirill's values, and the maximum among Anya's values should be not greater than the maximum among Kirill's values. If there are multiple answers, print any of them.
standard output
PASSED
dcfbf57bb41419a51eb1a79bb2b75a8d
train_000.jsonl
1520177700
Anya and Kirill are doing a physics laboratory work. In one of the tasks they have to measure some value n times, and then compute the average value to lower the error.Kirill has already made his measurements, and has got the following integer values: x1, x2, ..., xn. It is important that the values are close to each other, namely, the difference between the maximum value and the minimum value is at most 2.Anya does not want to make the measurements, however, she can't just copy the values from Kirill's work, because the error of each measurement is a random value, and this coincidence will be noted by the teacher. Anya wants to write such integer values y1, y2, ..., yn in her work, that the following conditions are met: the average value of x1, x2, ..., xn is equal to the average value of y1, y2, ..., yn; all Anya's measurements are in the same bounds as all Kirill's measurements, that is, the maximum value among Anya's values is not greater than the maximum value among Kirill's values, and the minimum value among Anya's values is not less than the minimum value among Kirill's values; the number of equal measurements in Anya's work and Kirill's work is as small as possible among options with the previous conditions met. Formally, the teacher goes through all Anya's values one by one, if there is equal value in Kirill's work and it is not strike off yet, he strikes off this Anya's value and one of equal values in Kirill's work. The number of equal measurements is then the total number of strike off values in Anya's work. Help Anya to write such a set of measurements that the conditions above are met.
256 megabytes
import java.io.DataInputStream; import java.io.IOException; public class Task931C { public static class FastScanner { protected DataInputStream dataInputStream; protected byte[] buffer = new byte[0x10000]; protected int bufferOffset; protected int bufferLength; protected boolean isEndOfFile; public FastScanner() throws IOException { dataInputStream = new DataInputStream(System.in); Read(); } protected void Read() throws IOException { final int length = dataInputStream.read(buffer); if (length > 0) { bufferLength = length; } else { bufferLength = 0; isEndOfFile = true; } bufferOffset = 0; } protected byte nextByte() throws IOException { if (bufferOffset == bufferLength) { if (!isEndOfFile) Read(); if (isEndOfFile) return 0; } return buffer[bufferOffset++]; } public int nextInt() throws IOException { int a = 0; boolean isNegative = false; byte b = nextByte(); while (b <= ' ') b = nextByte(); if (b == '-') { isNegative = true; b = nextByte(); } while (b > ' ') { a = a * 10 + (b - '0'); b = nextByte(); } return isNegative ? -a : a; } } public static void main(final String[] args) throws IOException { final FastScanner scanner = new FastScanner(); final int n = scanner.nextInt(); final int[] x = new int[n]; int xmin = Integer.MAX_VALUE; int xmax = Integer.MIN_VALUE; for (int i = 0; i < n; i++) { x[i] = scanner.nextInt(); xmin = Math.min(xmin, x[i]); xmax = Math.max(xmax, x[i]); } if (xmin == xmax) { System.out.println(n); for (int i = 0; i < n; i++) { System.out.print(xmin + " "); } } else if (xmax == xmin + 1) { System.out.println(n); for (int i = 0; i < n; i++) { System.out.print(x[i] + " "); } } else { final int xavg = (xmin + xmax) / 2; int nmin = 0; int navg = 0; int nmax = 0; for (int i = 0; i < n; i++) { if (x[i] == xmin) nmin++; else if (x[i] == xmax) nmax++; else navg++; } final int nmixPairs = Math.min(nmin, nmax); final int navgPairs = navg / 2; if (navgPairs > nmixPairs) { final int nMatches = nmin + nmax + (navg % 2); System.out.println(nMatches); for (int i = 0; i < nmin; i++) { System.out.print(xmin + " "); } for (int i = 0; i < nmax; i++) { System.out.print(xmax + " "); } for (int i = 0; i < navgPairs; i++) { System.out.print(xmin + " " + xmax + " "); } for (int i = 0; i < navg % 2; i++) { System.out.print(xavg + " "); } } else { final int nMatches = navg + (nmin - nmixPairs) + (nmax - nmixPairs); System.out.println(nMatches); for (int i = 0; i < nmin - nmixPairs; i++) { System.out.print(xmin + " "); } for (int i = 0; i < nmax - nmixPairs; i++) { System.out.print(xmax + " "); } for (int i = 0; i < nmixPairs; i++) { System.out.print(xavg + " " + xavg + " "); } for (int i = 0; i < navg; i++) { System.out.print(xavg + " "); } } } } }
Java
["6\n-1 1 1 0 0 -1", "3\n100 100 101", "7\n-10 -9 -10 -8 -10 -9 -9"]
1 second
["2\n0 0 0 0 0 0", "3\n101 100 100", "5\n-10 -10 -9 -9 -9 -9 -9"]
NoteIn the first example Anya can write zeros as here measurements results. The average value is then equal to the average value of Kirill's values, and there are only two equal measurements.In the second example Anya should write two values 100 and one value 101 (in any order), because it is the only possibility to make the average be the equal to the average of Kirill's values. Thus, all three measurements are equal.In the third example the number of equal measurements is 5.
Java 8
standard input
[ "implementation", "math" ]
dbbea6784cafdd4244f56729996e9187
The first line contains a single integer n (1 ≀ n ≀ 100 000) β€” the numeber of measurements made by Kirill. The second line contains a sequence of integers x1, x2, ..., xn ( - 100 000 ≀ xi ≀ 100 000) β€” the measurements made by Kirill. It is guaranteed that the difference between the maximum and minimum values among values x1, x2, ..., xn does not exceed 2.
1,700
In the first line print the minimum possible number of equal measurements. In the second line print n integers y1, y2, ..., yn β€” the values Anya should write. You can print the integers in arbitrary order. Keep in mind that the minimum value among Anya's values should be not less that the minimum among Kirill's values, and the maximum among Anya's values should be not greater than the maximum among Kirill's values. If there are multiple answers, print any of them.
standard output
PASSED
dd1549c017852d4d4afbbe5cd4135fd4
train_000.jsonl
1520177700
Anya and Kirill are doing a physics laboratory work. In one of the tasks they have to measure some value n times, and then compute the average value to lower the error.Kirill has already made his measurements, and has got the following integer values: x1, x2, ..., xn. It is important that the values are close to each other, namely, the difference between the maximum value and the minimum value is at most 2.Anya does not want to make the measurements, however, she can't just copy the values from Kirill's work, because the error of each measurement is a random value, and this coincidence will be noted by the teacher. Anya wants to write such integer values y1, y2, ..., yn in her work, that the following conditions are met: the average value of x1, x2, ..., xn is equal to the average value of y1, y2, ..., yn; all Anya's measurements are in the same bounds as all Kirill's measurements, that is, the maximum value among Anya's values is not greater than the maximum value among Kirill's values, and the minimum value among Anya's values is not less than the minimum value among Kirill's values; the number of equal measurements in Anya's work and Kirill's work is as small as possible among options with the previous conditions met. Formally, the teacher goes through all Anya's values one by one, if there is equal value in Kirill's work and it is not strike off yet, he strikes off this Anya's value and one of equal values in Kirill's work. The number of equal measurements is then the total number of strike off values in Anya's work. Help Anya to write such a set of measurements that the conditions above are met.
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 Jay Leeds */ 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(); int min = 100001; int[] data = new int[n]; for (int i = 0; i < n; i++) { data[i] = in.nextInt(); min = Math.min(min, data[i]); } int[] count = new int[3]; for (int i = 0; i < n; i++) count[data[i] - min]++; if (count[2] == 0) { out.printLine(n); for (int i = 0; i < n; i++) out.print((data[i]) + " "); } else if (Math.min(count[0], count[2]) > count[1] / 2) { int rem = Math.min(count[0], count[2]); out.printLine(n - 2 * rem); for (int i = 0; i < count[0] - rem; i++) { out.print(min + " "); } for (int i = 0; i < count[1] + 2 * rem; i++) { out.print((min + 1) + " "); } for (int i = 0; i < count[2] - rem; i++) { out.print((min + 2) + " "); } } else { int rem = count[1] / 2; out.printLine(n - 2 * rem); for (int i = 0; i < count[0] + rem; i++) { out.print(min + " "); } for (int i = 0; i < count[1] - 2 * rem; i++) { out.print((min + 1) + " "); } for (int i = 0; i < count[2] + rem; i++) { out.print((min + 2) + " "); } } out.printLine(); } } 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; //Fast IO by Egor Kulikov, modified by myself } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } 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(int i) { writer.println(i); } public void close() { writer.close(); } } }
Java
["6\n-1 1 1 0 0 -1", "3\n100 100 101", "7\n-10 -9 -10 -8 -10 -9 -9"]
1 second
["2\n0 0 0 0 0 0", "3\n101 100 100", "5\n-10 -10 -9 -9 -9 -9 -9"]
NoteIn the first example Anya can write zeros as here measurements results. The average value is then equal to the average value of Kirill's values, and there are only two equal measurements.In the second example Anya should write two values 100 and one value 101 (in any order), because it is the only possibility to make the average be the equal to the average of Kirill's values. Thus, all three measurements are equal.In the third example the number of equal measurements is 5.
Java 8
standard input
[ "implementation", "math" ]
dbbea6784cafdd4244f56729996e9187
The first line contains a single integer n (1 ≀ n ≀ 100 000) β€” the numeber of measurements made by Kirill. The second line contains a sequence of integers x1, x2, ..., xn ( - 100 000 ≀ xi ≀ 100 000) β€” the measurements made by Kirill. It is guaranteed that the difference between the maximum and minimum values among values x1, x2, ..., xn does not exceed 2.
1,700
In the first line print the minimum possible number of equal measurements. In the second line print n integers y1, y2, ..., yn β€” the values Anya should write. You can print the integers in arbitrary order. Keep in mind that the minimum value among Anya's values should be not less that the minimum among Kirill's values, and the maximum among Anya's values should be not greater than the maximum among Kirill's values. If there are multiple answers, print any of them.
standard output
PASSED
1cd622a97a8ee539e20f71f3c977ed38
train_000.jsonl
1520177700
Anya and Kirill are doing a physics laboratory work. In one of the tasks they have to measure some value n times, and then compute the average value to lower the error.Kirill has already made his measurements, and has got the following integer values: x1, x2, ..., xn. It is important that the values are close to each other, namely, the difference between the maximum value and the minimum value is at most 2.Anya does not want to make the measurements, however, she can't just copy the values from Kirill's work, because the error of each measurement is a random value, and this coincidence will be noted by the teacher. Anya wants to write such integer values y1, y2, ..., yn in her work, that the following conditions are met: the average value of x1, x2, ..., xn is equal to the average value of y1, y2, ..., yn; all Anya's measurements are in the same bounds as all Kirill's measurements, that is, the maximum value among Anya's values is not greater than the maximum value among Kirill's values, and the minimum value among Anya's values is not less than the minimum value among Kirill's values; the number of equal measurements in Anya's work and Kirill's work is as small as possible among options with the previous conditions met. Formally, the teacher goes through all Anya's values one by one, if there is equal value in Kirill's work and it is not strike off yet, he strikes off this Anya's value and one of equal values in Kirill's work. The number of equal measurements is then the total number of strike off values in Anya's work. Help Anya to write such a set of measurements that the conditions above are met.
256 megabytes
import java.util.*; import java.io.*; public class Main { static InReader in; static OutWriter out; static int ans[]; static int a[]; static int t[]; static int diff; public static void main(String args[]) throws IOException { in = new InReader(); out = new OutWriter(); int n = in.nextInt(); a = new int[n]; for (int i = 0; i < n; i++) { a[i] = in.nextInt(); } int min = 1000000000; int max=Integer.MIN_VALUE; for (int i = 0; i < n; i++) { min = Math.min(min, a[i]); } for (int i = 0; i < n; i++) { max=Math.max(max,a[i]); } if(max-min==2){ ans = new int[3]; diff=Integer.MAX_VALUE; getans(min); }else { out.println(a.length); for (int i = 0; i < n; i++) { out.prints(a[i]); } } out.close(); } static void getans(int min){ t = new int[3]; for (int i = 0; i < a.length; i++) { t[a[i] - min]++; } int l[] = new int[3]; ans[0]=t[0]; ans[1]=t[1]; ans[2]=t[2]; diff=a.length; l[0] = t[0]; l[1] = t[1]; l[2] = t[2]; int r[] = new int[3]; r[0] = t[0]; r[1] = t[1]; r[2] = t[2]; while (l[1] > 1) { l[1] -= 2; l[0]++; l[2]++; if (diff > getdiff(l)) { diff = getdiff(l); ans[1] = l[1]; ans[0] = l[0]; ans[2] = l[2]; } } while (r[0] > 0 && r[2] > 0) { r[0]--; r[2]--; r[1] += 2; if (diff > getdiff(r)) { diff = getdiff(r); ans[0] = r[0]; ans[1] = r[1]; ans[2] = r[2]; } } out.println(diff); for (int i = 0; i < ans[0]; i++) { out.prints(min); } for (int i = 0; i < ans[1]; i++) { out.prints(min + 1); } for (int i = 0; i < ans[2]; i++) { out.prints(min + 2); } } private static int getdiff(int[] k) { return Math.min(k[0], t[0]) + Math.min(k[1], t[1]) + Math.min(k[2], t[2]); } } class InReader { BufferedReader in; InReader(String name) throws IOException { in = new BufferedReader(new FileReader(name)); } InReader() { in = new BufferedReader(new InputStreamReader(System.in)); } StringTokenizer token = new StringTokenizer(""); void update() throws IOException { if (!token.hasMoreTokens()) { String a = in.readLine(); if (a != null) { token = new StringTokenizer(a); } } } int nextInt() throws IOException { update(); return Integer.parseInt(token.nextToken()); } long nextLong() throws IOException { update(); return Long.parseLong(token.nextToken()); } double nextDouble() throws IOException { update(); return Double.parseDouble(token.nextToken()); } boolean hasNext() throws IOException { update(); return token.hasMoreTokens(); } String next() throws IOException { update(); return token.nextToken(); } } class OutWriter { PrintWriter out; OutWriter() { out = new PrintWriter(System.out); } OutWriter(String name) throws IOException { out = new PrintWriter(new FileWriter(name)); } StringBuilder cout = new StringBuilder(); <T> void print(T a) { cout.append(a); } <T> void println(T a) { cout.append(a); cout.append('\n'); } <T> void prints(T a) { cout.append(a); cout.append(' '); } void close() { out.print(cout.toString()); out.close(); } }
Java
["6\n-1 1 1 0 0 -1", "3\n100 100 101", "7\n-10 -9 -10 -8 -10 -9 -9"]
1 second
["2\n0 0 0 0 0 0", "3\n101 100 100", "5\n-10 -10 -9 -9 -9 -9 -9"]
NoteIn the first example Anya can write zeros as here measurements results. The average value is then equal to the average value of Kirill's values, and there are only two equal measurements.In the second example Anya should write two values 100 and one value 101 (in any order), because it is the only possibility to make the average be the equal to the average of Kirill's values. Thus, all three measurements are equal.In the third example the number of equal measurements is 5.
Java 8
standard input
[ "implementation", "math" ]
dbbea6784cafdd4244f56729996e9187
The first line contains a single integer n (1 ≀ n ≀ 100 000) β€” the numeber of measurements made by Kirill. The second line contains a sequence of integers x1, x2, ..., xn ( - 100 000 ≀ xi ≀ 100 000) β€” the measurements made by Kirill. It is guaranteed that the difference between the maximum and minimum values among values x1, x2, ..., xn does not exceed 2.
1,700
In the first line print the minimum possible number of equal measurements. In the second line print n integers y1, y2, ..., yn β€” the values Anya should write. You can print the integers in arbitrary order. Keep in mind that the minimum value among Anya's values should be not less that the minimum among Kirill's values, and the maximum among Anya's values should be not greater than the maximum among Kirill's values. If there are multiple answers, print any of them.
standard output
PASSED
f0b75f0b23ad20c58d85733254fcc8d1
train_000.jsonl
1520177700
Anya and Kirill are doing a physics laboratory work. In one of the tasks they have to measure some value n times, and then compute the average value to lower the error.Kirill has already made his measurements, and has got the following integer values: x1, x2, ..., xn. It is important that the values are close to each other, namely, the difference between the maximum value and the minimum value is at most 2.Anya does not want to make the measurements, however, she can't just copy the values from Kirill's work, because the error of each measurement is a random value, and this coincidence will be noted by the teacher. Anya wants to write such integer values y1, y2, ..., yn in her work, that the following conditions are met: the average value of x1, x2, ..., xn is equal to the average value of y1, y2, ..., yn; all Anya's measurements are in the same bounds as all Kirill's measurements, that is, the maximum value among Anya's values is not greater than the maximum value among Kirill's values, and the minimum value among Anya's values is not less than the minimum value among Kirill's values; the number of equal measurements in Anya's work and Kirill's work is as small as possible among options with the previous conditions met. Formally, the teacher goes through all Anya's values one by one, if there is equal value in Kirill's work and it is not strike off yet, he strikes off this Anya's value and one of equal values in Kirill's work. The number of equal measurements is then the total number of strike off values in Anya's work. Help Anya to write such a set of measurements that the conditions above are met.
256 megabytes
import java.io.*; import java.math.BigDecimal; import java.math.BigInteger; import java.math.RoundingMode; import java.text.DecimalFormat; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Main { static long mod=(long)(1e+9 + 7); //static long mod=(long)998244353; static int[] sieve; static ArrayList<Integer> primes; static long min=Long.MAX_VALUE; static PrintWriter out; static fast s; static StringBuilder fans; public static void solve() { int n=s.nextInt(); long a[]=new long[n]; long sum=0; for(int i=0;i<n;i++) {a[i]=s.nextLong();sum+=a[i];} Arrays.sort(a); TreeMap<Long,Integer> hm=new TreeMap<Long,Integer>(); for(int i=0;i<n;i++) hm.put(a[i],hm.getOrDefault(a[i], 0)+1); ArrayList<Long> ans=new ArrayList<Long>(); if(hm.size()==1) { for(int i=0;i<a.length;i++) ans.add(a[i]); } else if(hm.size()==2) { long min=hm.firstEntry().getKey(); long max=hm.lastEntry().getKey(); int max_freq=hm.get(max); int min_freq=hm.get(min); if(max-min==1) { for(int i=0;i<a.length;i++) ans.add(a[i]); } else { int req_freq=Math.min(min_freq, max_freq); int temp=req_freq; for(int i=0;i<req_freq;i++) {ans.add(a[i]+1);} for(int i=a.length-1;i>=req_freq;i--) { if(temp>0) ans.add(a[i]-1); else ans.add(a[i]); temp--; } } } else { ArrayList<Long> ans1=new ArrayList<Long>(); ArrayList<Long> ans2=new ArrayList<Long>(); ArrayList<Long> ans3=new ArrayList<Long>(); long min=hm.firstEntry().getKey(); long max=hm.lastEntry().getKey(); long mid=min+1; int max_freq=hm.get(max); int min_freq=hm.get(min); int mid_freq=hm.get(mid); int cnt1=0; int cnt2=0; int cnt3=0; //Mid_Mid for(int i=0;i<min_freq;i++) ans3.add(min); for(int i=0;i<max_freq;i++) ans3.add(max); for(int i=0;i<mid_freq-1;i+=2) { ans3.add(mid-1); ans3.add(mid+1); } if(mid_freq%2==1) ans3.add(mid); //Mid_Low int req_freq=Math.min(min_freq, max_freq); int temp=req_freq; for(int i=0;i<req_freq;i++) {ans1.add(a[i]+1);} for(int i=a.length-1;i>=req_freq;i--) { if(temp>0) ans1.add(a[i]-1); else ans1.add(a[i]); temp--; } //Mid pos? if(mid*n==sum) { for(int i=0;i<n;i++) ans2.add(mid); } Collections.sort(ans1); Collections.sort(ans2); Collections.sort(ans3); HashMap<Long,Integer> fk=new HashMap<Long,Integer>(); for(int i=0;i<ans1.size();i++) fk.put(ans1.get(i), fk.getOrDefault(ans1.get(i), 0)+1); for(Map.Entry<Long, Integer> mp:fk.entrySet()) { long key=mp.getKey(); int val=mp.getValue(); if(hm.containsKey(key)) cnt1+=Math.min(val,hm.get(key)); } fk=new HashMap<Long,Integer>(); for(int i=0;i<ans2.size();i++) fk.put(ans2.get(i), fk.getOrDefault(ans2.get(i), 0)+1); for(Map.Entry<Long, Integer> mp:fk.entrySet()) { long key=mp.getKey(); int val=mp.getValue(); if(hm.containsKey(key)) cnt2+=Math.min(val,hm.get(key)); } fk=new HashMap<Long,Integer>(); for(int i=0;i<ans3.size();i++) fk.put(ans3.get(i), fk.getOrDefault(ans3.get(i), 0)+1); for(Map.Entry<Long, Integer> mp:fk.entrySet()) { long key=mp.getKey(); int val=mp.getValue(); if(hm.containsKey(key)) cnt3+=Math.min(val,hm.get(key)); } if(cnt1==0) cnt1=Integer.MAX_VALUE; if(cnt2==0) cnt2=Integer.MAX_VALUE; if(cnt3==0) cnt3=Integer.MAX_VALUE; if(cnt1<=cnt2 && cnt1<=cnt3) ans=ans1; else if(cnt2<=cnt3 &cnt2<=cnt1) ans=ans2; else if(cnt3<=cnt1 && cnt3<=cnt2) ans=ans3; if(ans1.size()==0 && ans2.size()==0 && ans3.size()==0) { ans.clear(); for(int i=0;i<n;i++) ans.add(a[i]); } } Collections.sort(ans); HashMap<Long,Integer> fk=new HashMap<Long,Integer>(); for(int i=0;i<ans.size();i++) fk.put(ans.get(i), fk.getOrDefault(ans.get(i), 0)+1); int cnt=0; for(Map.Entry<Long, Integer> mp:fk.entrySet()) { long key=mp.getKey(); int val=mp.getValue(); if(hm.containsKey(key)) cnt+=Math.min(val,hm.get(key)); } System.out.println(cnt); for(int i=0;i<ans.size();i++) System.out.print(ans.get(i)+" "); } public static void main(String[] args) throws java.lang.Exception { s = new fast(); out=new PrintWriter(System.out); fans=new StringBuilder(""); int t=1; while(t>0) { solve(); t--; } } static class fast { private InputStream i; private byte[] buf = new byte[1024]; private int curChar; private int numChars; //Return floor log2n public static long log2(long bits) // returns 0 for bits=0 { int log = 0; if( ( bits & 0xffff0000 ) != 0 ) { bits >>>= 16; log = 16; } if( bits >= 256 ) { bits >>>= 8; log += 8; } if( bits >= 16 ) { bits >>>= 4; log += 4; } if( bits >= 4 ) { bits >>>= 2; log += 2; } return log + ( bits >>> 1 ); } public static boolean next_permutation(int a[]) { int i=0,j=0;int index=-1; int n=a.length; for(i=0;i<n-1;i++) if(a[i]<a[i+1]) index=i; if(index==-1) return false; i=index; for(j=i+1;j<n && a[i]<a[j];j++); int temp=a[i]; a[i]=a[j-1]; a[j-1]=temp; for(int p=i+1,q=n-1;p<q;p++,q--) { temp=a[p]; a[p]=a[q]; a[q]=temp; } return true; } public static void division(char ch[],int divisor) { int div=Character.getNumericValue(ch[0]); int mul=10;int remainder=0; StringBuilder quotient=new StringBuilder(""); for(int i=1;i<ch.length;i++) { div=div*mul+Character.getNumericValue(ch[i]); if(div<divisor) {quotient.append("0");continue;} quotient.append(div/divisor); div=div%divisor;mul=10; } remainder=div; while(quotient.charAt(0)=='0')quotient.deleteCharAt(0); System.out.println(quotient+" "+remainder); } public static void sieve(int size) { sieve=new int[size+1]; primes=new ArrayList<Integer>(); sieve[1]=1; for(int i=2;i*i<=size;i++) { if(sieve[i]==0) { for(int j=i*i;j<size;j+=i) {sieve[j]=1;} } } for(int i=2;i<=size;i++) { if(sieve[i]==0) primes.add(i); } } public static long pow(long n, long b, long MOD) { long x=1;long y=n; while(b > 0) { if(b%2 == 1) { x=x*y; if(x>MOD) x=x%(MOD); } y = y*y; if(y>MOD) y=y%(MOD); b >>= 1; } return x; } public static long mod_inv(long n,long mod) { return pow(n,mod-2,mod); } //Returns index of highest number less than or equal to key public static int upper(long[] a,int length,long key) { int low = 0; int high = length-1; int ans=-1; while (low <= high) { int mid = (low + high) / 2; if (key >= a[mid]) { ans=mid; low = mid+1; } else if(a[mid]>key){ high = mid - 1; } } return ans; } //Returns index of least number greater than or equal to key public static int lower(long[] a,int length,long key) { int low = 0; int high = length-1; int ans=-1; while (low <= high) { int mid = (low + high) / 2; if (key<=a[mid]) { ans=mid; high = mid-1; } else{ low=mid+1; } } return ans; } public long gcd(long r,long ans) { if(r==0) return ans; return gcd(ans%r,r); } 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
["6\n-1 1 1 0 0 -1", "3\n100 100 101", "7\n-10 -9 -10 -8 -10 -9 -9"]
1 second
["2\n0 0 0 0 0 0", "3\n101 100 100", "5\n-10 -10 -9 -9 -9 -9 -9"]
NoteIn the first example Anya can write zeros as here measurements results. The average value is then equal to the average value of Kirill's values, and there are only two equal measurements.In the second example Anya should write two values 100 and one value 101 (in any order), because it is the only possibility to make the average be the equal to the average of Kirill's values. Thus, all three measurements are equal.In the third example the number of equal measurements is 5.
Java 8
standard input
[ "implementation", "math" ]
dbbea6784cafdd4244f56729996e9187
The first line contains a single integer n (1 ≀ n ≀ 100 000) β€” the numeber of measurements made by Kirill. The second line contains a sequence of integers x1, x2, ..., xn ( - 100 000 ≀ xi ≀ 100 000) β€” the measurements made by Kirill. It is guaranteed that the difference between the maximum and minimum values among values x1, x2, ..., xn does not exceed 2.
1,700
In the first line print the minimum possible number of equal measurements. In the second line print n integers y1, y2, ..., yn β€” the values Anya should write. You can print the integers in arbitrary order. Keep in mind that the minimum value among Anya's values should be not less that the minimum among Kirill's values, and the maximum among Anya's values should be not greater than the maximum among Kirill's values. If there are multiple answers, print any of them.
standard output
PASSED
b360907eeb263ef2d3aec74cc5b85120
train_000.jsonl
1520177700
Anya and Kirill are doing a physics laboratory work. In one of the tasks they have to measure some value n times, and then compute the average value to lower the error.Kirill has already made his measurements, and has got the following integer values: x1, x2, ..., xn. It is important that the values are close to each other, namely, the difference between the maximum value and the minimum value is at most 2.Anya does not want to make the measurements, however, she can't just copy the values from Kirill's work, because the error of each measurement is a random value, and this coincidence will be noted by the teacher. Anya wants to write such integer values y1, y2, ..., yn in her work, that the following conditions are met: the average value of x1, x2, ..., xn is equal to the average value of y1, y2, ..., yn; all Anya's measurements are in the same bounds as all Kirill's measurements, that is, the maximum value among Anya's values is not greater than the maximum value among Kirill's values, and the minimum value among Anya's values is not less than the minimum value among Kirill's values; the number of equal measurements in Anya's work and Kirill's work is as small as possible among options with the previous conditions met. Formally, the teacher goes through all Anya's values one by one, if there is equal value in Kirill's work and it is not strike off yet, he strikes off this Anya's value and one of equal values in Kirill's work. The number of equal measurements is then the total number of strike off values in Anya's work. Help Anya to write such a set of measurements that the conditions above are met.
256 megabytes
import java.io.*; import java.util.StringTokenizer; public class CFR468C { static int n, x[] = new int[100001], v = 0, kMin = (int)10e5 + 1, kMax; static int b[] = new int[200010]; static String ins[]; static double kAve = 0.; public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); n = Integer.parseInt(br.readLine()); kMax = kMin * -1; StringTokenizer st = new StringTokenizer(br.readLine(), " "); while (st.hasMoreTokens()) { x[v] = Integer.parseInt(st.nextToken()); b[x[v] + 100000]++; kMax = Math.max(kMax, x[v]); kMin = Math.min(kMin, x[v++]); } int count = 0; for (int i = kMin + 100000; i < kMax + 100001; i++) { if (b[i] != 0) count++; } StringBuilder sb = new StringBuilder(); if (count == 1) { sb.append(n);sb.append("\n"); for (int i = 0; i < n; i++) { sb.append(x[i]); if (i < n - 1) sb.append(" "); } }else if (count == 2) { if (b[kMin + 100001] == 0) { int dif = Math.min(b[kMin + 100000], b[kMin + 100002]); b[kMin + 100000] -= dif; b[kMin + 100001] += (dif << 1); b[kMin + 100002] -= dif; sb.append(n - (dif << 1));sb.append("\n"); for (int i = 0; i < b[kMin + 100000]; i++) { sb.append(kMin);sb.append(" "); } for (int i = 0; i < b[kMin + 100001]; i++) { sb.append(kMin + 1);sb.append(" "); } for (int i = 0; i < b[kMin + 100002]; i++) { sb.append(kMin +2);sb.append(" "); } }else { sb.append(n);sb.append("\n"); for (int i = 0; i < n; i++) { sb.append(x[i]); if (i < n - 1) sb.append(" "); } } } else { int dif = Math.min(b[kMin + 100000], b[kMin + 100002]); int t = (b[kMin + 100001] >> 1); if (dif < t) { b[kMin + 100000] += t; b[kMin + 100001] -= (t << 1); b[kMin + 100002] += t; sb.append(n - (t << 1));sb.append("\n"); }else { b[kMin + 100000] -= dif; b[kMin + 100001] += (dif << 1); b[kMin + 100002] -= dif; sb.append(n - (dif << 1));sb.append("\n"); } for (int i = 0; i < b[kMin + 100000]; i++) { sb.append(kMin);sb.append(" "); } for (int i = 0; i < b[kMin + 100001]; i++) { sb.append(kMin + 1);sb.append(" "); } for (int i = 0; i < b[kMin + 100002]; i++) { sb.append(kMin +2);sb.append(" "); } } sb.append("\n"); bw.write(sb.toString()); bw.flush();bw.close(); } }
Java
["6\n-1 1 1 0 0 -1", "3\n100 100 101", "7\n-10 -9 -10 -8 -10 -9 -9"]
1 second
["2\n0 0 0 0 0 0", "3\n101 100 100", "5\n-10 -10 -9 -9 -9 -9 -9"]
NoteIn the first example Anya can write zeros as here measurements results. The average value is then equal to the average value of Kirill's values, and there are only two equal measurements.In the second example Anya should write two values 100 and one value 101 (in any order), because it is the only possibility to make the average be the equal to the average of Kirill's values. Thus, all three measurements are equal.In the third example the number of equal measurements is 5.
Java 8
standard input
[ "implementation", "math" ]
dbbea6784cafdd4244f56729996e9187
The first line contains a single integer n (1 ≀ n ≀ 100 000) β€” the numeber of measurements made by Kirill. The second line contains a sequence of integers x1, x2, ..., xn ( - 100 000 ≀ xi ≀ 100 000) β€” the measurements made by Kirill. It is guaranteed that the difference between the maximum and minimum values among values x1, x2, ..., xn does not exceed 2.
1,700
In the first line print the minimum possible number of equal measurements. In the second line print n integers y1, y2, ..., yn β€” the values Anya should write. You can print the integers in arbitrary order. Keep in mind that the minimum value among Anya's values should be not less that the minimum among Kirill's values, and the maximum among Anya's values should be not greater than the maximum among Kirill's values. If there are multiple answers, print any of them.
standard output
PASSED
524089236495a7c5fba354ec349200dd
train_000.jsonl
1520177700
Anya and Kirill are doing a physics laboratory work. In one of the tasks they have to measure some value n times, and then compute the average value to lower the error.Kirill has already made his measurements, and has got the following integer values: x1, x2, ..., xn. It is important that the values are close to each other, namely, the difference between the maximum value and the minimum value is at most 2.Anya does not want to make the measurements, however, she can't just copy the values from Kirill's work, because the error of each measurement is a random value, and this coincidence will be noted by the teacher. Anya wants to write such integer values y1, y2, ..., yn in her work, that the following conditions are met: the average value of x1, x2, ..., xn is equal to the average value of y1, y2, ..., yn; all Anya's measurements are in the same bounds as all Kirill's measurements, that is, the maximum value among Anya's values is not greater than the maximum value among Kirill's values, and the minimum value among Anya's values is not less than the minimum value among Kirill's values; the number of equal measurements in Anya's work and Kirill's work is as small as possible among options with the previous conditions met. Formally, the teacher goes through all Anya's values one by one, if there is equal value in Kirill's work and it is not strike off yet, he strikes off this Anya's value and one of equal values in Kirill's work. The number of equal measurements is then the total number of strike off values in Anya's work. Help Anya to write such a set of measurements that the conditions above are met.
256 megabytes
import java.io.*; import java.util.*; import java.math.*; /** * Built using CHelper plug-in * Actual solution is at the top */ public class LaboratoryWork { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskA solver = new TaskA(); solver.solve(1, in, out); out.close(); } static class TaskA { long mod = (long)(1000000007); public void solve(int testNumber, InputReader in, PrintWriter out) { while(testNumber-->0){ int n = in.nextInt(); TreeMap<Long , Long> m = new TreeMap<>(); long sum = 0; for(int i=0;i<n;i++){ long x = in.nextLong(); sum += x; if(m.containsKey(x)){ m.replace(x , m.get(x)+1); } else m.put(x , 1l); } long d[] = new long[3]; int k = 0; for(long i:m.keySet()) d[k++] = i; if(m.size() == 1 || (m.size() == 2 && d[1] - d[0] == 1)){ out.println(n); for(long x:m.keySet()){ for(int i=0;i<m.get(x);i++) out.print(x + " "); } out.println(); } else{ long a = m.firstKey(); long x = 0; long c = n*(a+2) - sum; long min = Long.MAX_VALUE; long aMin = Integer.MAX_VALUE; // out.println(c); while(2*x <= c){ // out.println("X " + x); long y = c - 2*(x); long w; if(m.containsKey(a+1)) w = m.get(a+1); else w = 0; long q = Math.min(x , m.get(a)) + Math.min(y , w) + Math.min(n-x-y , m.get(a+2)); // out.println(x + " " + y + " " + (n-x-y)); if(q<min && (a*x + (a+1)*y + (a+2)*(n-x-y) == sum) && n-x-y>=0){ // out.println(q); min = q; aMin = x; } x++; } out.println(min); x = aMin; long y = c-2*x; long b[] = new long[]{x , c-2*x , n-x-y}; for(int i=0;i<3;i++){ for(int j=0;j<b[i];j++) out.print((a+i) + " "); } out.println(); } } } public void sortedArrayToBST(TreeSet<Integer> a , int start, int end) { if (start > end) { return; } int mid = (start + end) / 2; a.add(mid); sortedArrayToBST(a, start, mid - 1); sortedArrayToBST(a, mid + 1, end); } class Combine{ long value; long delete; Combine(long val , long delete){ this.value = val; this.delete = delete; } } class Sort2 implements Comparator<Combine>{ public int compare(Combine a , Combine b){ if(a.value > b.value) return 1; else if(a.value == b.value && a.delete>b.delete) return 1; else if(a.value == b.value && a.delete == b.delete) return 0; return -1; } } public int lowerLastBound(ArrayList<Integer> a , int x){ int l = 0; int r = a.size()-1; if(a.get(l)>=x) return -1; if(a.get(r)<x) return r; int mid = -1; while(l<=r){ mid = (l+r)/2; if(a.get(mid) == x && a.get(mid-1)<x) return mid-1; else if(a.get(mid)>=x) r = mid-1; else if(a.get(mid)<x && a.get(mid+1)>=x) return mid; else if(a.get(mid)<x && a.get(mid+1)<x) l = mid+1; } return mid; } public int upperFirstBound(ArrayList<Integer> a , Integer x){ int l = 0; int r = a.size()-1; if(a.get(l)>x) return l; if(a.get(r)<=x) return r+1; int mid = -1; while(l<=r){ mid = (l+r)/2; if(a.get(mid) == x && a.get(mid+1)>x) return mid+1; else if(a.get(mid)<=x) l = mid+1; else if(a.get(mid)>x && a.get(mid-1)<=x) return mid; else if(a.get(mid)>x && a.get(mid-1)>x) r = mid-1; } return mid; } public int lowerLastBound(int a[] , int x){ int l = 0; int r = a.length-1; if(a[l]>=x) return -1; if(a[r]<x) return r; int mid = -1; while(l<=r){ mid = (l+r)/2; if(a[mid] == x && a[mid-1]<x) return mid-1; else if(a[mid]>=x) r = mid-1; else if(a[mid]<x && a[mid+1]>=x) return mid; else if(a[mid]<x && a[mid+1]<x) l = mid+1; } return mid; } public int upperFirstBound(long a[] , long x){ int l = 0; int r = a.length-1; if(a[l]>x) return l; if(a[r]<=x) return r+1; int mid = -1; while(l<=r){ mid = (l+r)/2; if(a[mid] == x && a[mid+1]>x) return mid+1; else if(a[mid]<=x) l = mid+1; else if(a[mid]>x && a[mid-1]<=x) return mid; else if(a[mid]>x && a[mid-1]>x) r = mid-1; } return mid; } public long log(float number , int base){ return (long) Math.floor((Math.log(number) / Math.log(base))); } public long gcd(long a , long b){ if(a<b){ long c = b; b = a; a = c; } if(a%b==0) return b; return gcd(b , a%b); } public void print2d(int a[][] , PrintWriter out){ for(int i=0;i<a.length;i++){ for(int j=0;j<a[i].length;j++) out.print(a[i][j] + " "); out.println(); } out.println(); } public void print1d(int a[] , PrintWriter out){ for(int i=0;i<a.length;i++) out.print(a[i] + " "); out.println(); out.println(); } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } }
Java
["6\n-1 1 1 0 0 -1", "3\n100 100 101", "7\n-10 -9 -10 -8 -10 -9 -9"]
1 second
["2\n0 0 0 0 0 0", "3\n101 100 100", "5\n-10 -10 -9 -9 -9 -9 -9"]
NoteIn the first example Anya can write zeros as here measurements results. The average value is then equal to the average value of Kirill's values, and there are only two equal measurements.In the second example Anya should write two values 100 and one value 101 (in any order), because it is the only possibility to make the average be the equal to the average of Kirill's values. Thus, all three measurements are equal.In the third example the number of equal measurements is 5.
Java 8
standard input
[ "implementation", "math" ]
dbbea6784cafdd4244f56729996e9187
The first line contains a single integer n (1 ≀ n ≀ 100 000) β€” the numeber of measurements made by Kirill. The second line contains a sequence of integers x1, x2, ..., xn ( - 100 000 ≀ xi ≀ 100 000) β€” the measurements made by Kirill. It is guaranteed that the difference between the maximum and minimum values among values x1, x2, ..., xn does not exceed 2.
1,700
In the first line print the minimum possible number of equal measurements. In the second line print n integers y1, y2, ..., yn β€” the values Anya should write. You can print the integers in arbitrary order. Keep in mind that the minimum value among Anya's values should be not less that the minimum among Kirill's values, and the maximum among Anya's values should be not greater than the maximum among Kirill's values. If there are multiple answers, print any of them.
standard output
PASSED
a4bb50063d5af42ca87898a138356b0d
train_000.jsonl
1520177700
Anya and Kirill are doing a physics laboratory work. In one of the tasks they have to measure some value n times, and then compute the average value to lower the error.Kirill has already made his measurements, and has got the following integer values: x1, x2, ..., xn. It is important that the values are close to each other, namely, the difference between the maximum value and the minimum value is at most 2.Anya does not want to make the measurements, however, she can't just copy the values from Kirill's work, because the error of each measurement is a random value, and this coincidence will be noted by the teacher. Anya wants to write such integer values y1, y2, ..., yn in her work, that the following conditions are met: the average value of x1, x2, ..., xn is equal to the average value of y1, y2, ..., yn; all Anya's measurements are in the same bounds as all Kirill's measurements, that is, the maximum value among Anya's values is not greater than the maximum value among Kirill's values, and the minimum value among Anya's values is not less than the minimum value among Kirill's values; the number of equal measurements in Anya's work and Kirill's work is as small as possible among options with the previous conditions met. Formally, the teacher goes through all Anya's values one by one, if there is equal value in Kirill's work and it is not strike off yet, he strikes off this Anya's value and one of equal values in Kirill's work. The number of equal measurements is then the total number of strike off values in Anya's work. Help Anya to write such a set of measurements that the conditions above are met.
256 megabytes
import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.InputMismatchException; public class D_468 { InputStream is; PrintWriter out; int n; long a[]; private boolean oj = System.getProperty("ONLINE_JUDGE") != null; void solve() { int n = ni(); int min = Integer.MAX_VALUE; int max = Integer.MIN_VALUE; int sum = 0; int arr[] = new int[n]; for (int i = 0; i < n; i++) { int temp = ni(); arr[i] = temp; min = Math.min(min, temp); max = Math.max(max, temp); } if (max - min <= 1) { out.println(n); for (int i = 0; i < n; i++) { out.println(arr[i]); } } else { int c1 = 0; int c2 = 0; int c3 = 0; int x = (max + min) / 2; for (int i = 0; i < n; i++) { if (arr[i] == min) { c1++; } else if (arr[i] == max) { c3++; } else { x = arr[i]; c2++; } } int ans = 0; tr(c1, c2, c3); if (c2 / 2 <= Math.min(c1, c3)) { int count = Math.min(c1, c3); ans = n - 2 * (count); int i = 0; int m = 0; while (i < n && m < count) { if (arr[i] == min) { arr[i] = x; m++; } i++; } i = 0; m = 0; while (i < n && m < count) { if (arr[i] == max) { arr[i] = x; m++; } i++; } } else { int count = c2 / 2; ans = n - 2 * (count); int i = 0; int m = 0; while (i < n && m < count) { if (arr[i] == x) { arr[i] = min; m++; } i++; } i = 0; m = 0; while (i < n && m < count) { if (arr[i] == x) { arr[i] = max; m++; } i++; } } out.println(ans); for (int i = 0; i < n; i++) { out.print(arr[i] + " "); } } } void run() throws Exception { String INPUT = "C:\\Users\\Admin\\Desktop\\input.txt"; is = oj ? System.in : new FileInputStream(INPUT); 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 Thread(null, new Runnable() { public void run() { try { new D_468().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 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 void tr(Object... o) { if (!oj) System.out.println(Arrays.deepToString(o)); } }
Java
["6\n-1 1 1 0 0 -1", "3\n100 100 101", "7\n-10 -9 -10 -8 -10 -9 -9"]
1 second
["2\n0 0 0 0 0 0", "3\n101 100 100", "5\n-10 -10 -9 -9 -9 -9 -9"]
NoteIn the first example Anya can write zeros as here measurements results. The average value is then equal to the average value of Kirill's values, and there are only two equal measurements.In the second example Anya should write two values 100 and one value 101 (in any order), because it is the only possibility to make the average be the equal to the average of Kirill's values. Thus, all three measurements are equal.In the third example the number of equal measurements is 5.
Java 8
standard input
[ "implementation", "math" ]
dbbea6784cafdd4244f56729996e9187
The first line contains a single integer n (1 ≀ n ≀ 100 000) β€” the numeber of measurements made by Kirill. The second line contains a sequence of integers x1, x2, ..., xn ( - 100 000 ≀ xi ≀ 100 000) β€” the measurements made by Kirill. It is guaranteed that the difference between the maximum and minimum values among values x1, x2, ..., xn does not exceed 2.
1,700
In the first line print the minimum possible number of equal measurements. In the second line print n integers y1, y2, ..., yn β€” the values Anya should write. You can print the integers in arbitrary order. Keep in mind that the minimum value among Anya's values should be not less that the minimum among Kirill's values, and the maximum among Anya's values should be not greater than the maximum among Kirill's values. If there are multiple answers, print any of them.
standard output
PASSED
37cbd950e95535db56870edf7a5457b6
train_000.jsonl
1520177700
Anya and Kirill are doing a physics laboratory work. In one of the tasks they have to measure some value n times, and then compute the average value to lower the error.Kirill has already made his measurements, and has got the following integer values: x1, x2, ..., xn. It is important that the values are close to each other, namely, the difference between the maximum value and the minimum value is at most 2.Anya does not want to make the measurements, however, she can't just copy the values from Kirill's work, because the error of each measurement is a random value, and this coincidence will be noted by the teacher. Anya wants to write such integer values y1, y2, ..., yn in her work, that the following conditions are met: the average value of x1, x2, ..., xn is equal to the average value of y1, y2, ..., yn; all Anya's measurements are in the same bounds as all Kirill's measurements, that is, the maximum value among Anya's values is not greater than the maximum value among Kirill's values, and the minimum value among Anya's values is not less than the minimum value among Kirill's values; the number of equal measurements in Anya's work and Kirill's work is as small as possible among options with the previous conditions met. Formally, the teacher goes through all Anya's values one by one, if there is equal value in Kirill's work and it is not strike off yet, he strikes off this Anya's value and one of equal values in Kirill's work. The number of equal measurements is then the total number of strike off values in Anya's work. Help Anya to write such a set of measurements that the conditions above are met.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.OutputStream; import java.util.StringTokenizer; import java.io.Writer; 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 palayutm */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); ProblemCLaboratoryWork solver = new ProblemCLaboratoryWork(); solver.solve(1, in, out); out.close(); } static class ProblemCLaboratoryWork { public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.nextInt(); int[] a = in.nextIntArray(n); int[] count = new int[200001]; for (int i = 0; i < n; i++) { count[a[i] + 100000]++; } int mx = ArrayUtil.max(a); int mi = ArrayUtil.min(a); if (mx - mi < 2) { out.println(n); out.println(a); return; } int ans = Integer.MAX_VALUE; int px = 0, py = 0, pz = 0; long sum = 0; for (int x : a) { sum += x; } for (int i = 0; i <= n; i++) { long now = (long) i * mi; long lower = (long) (n - i) * (mi + 1); long upper = (long) (n - i) * (mi + 2); if (sum - now >= lower && sum - now <= upper) { int x = i, z = (int) (sum - now - lower), y = n - x - z; int cnt = Math.min(x, count[mi + 100000]) + Math.min(y, count[mi + 100001]) + Math.min(z, count[mx + 100000]); if (cnt < ans) { ans = cnt; px = x; py = y; pz = z; } } } out.println(ans); for (int i = 0; i < px; i++) { out.print(mi + " "); } for (int i = 0; i < py; i++) { out.print((mi + 1) + " "); } for (int i = 0; i < pz; i++) { out.print(mx + " "); } } } 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 int[] nextIntArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } } static class ArrayUtil { public static int max(int[] a) { int ret = Integer.MIN_VALUE; for (int x : a) { ret = Math.max(ret, x); } return ret; } public static int min(int[] a) { int ret = Integer.MAX_VALUE; for (int x : a) { ret = Math.min(ret, x); } return ret; } } static class OutputWriter extends PrintWriter { public OutputWriter(OutputStream out) { super(out); } public OutputWriter(Writer out) { super(out); } public void close() { super.close(); } public void print(int[] a) { for (int i = 0; i < a.length; i++) { if (i != 0) { print(' '); } print(a[i]); } } public void println(int[] a) { print(a); println(); } } }
Java
["6\n-1 1 1 0 0 -1", "3\n100 100 101", "7\n-10 -9 -10 -8 -10 -9 -9"]
1 second
["2\n0 0 0 0 0 0", "3\n101 100 100", "5\n-10 -10 -9 -9 -9 -9 -9"]
NoteIn the first example Anya can write zeros as here measurements results. The average value is then equal to the average value of Kirill's values, and there are only two equal measurements.In the second example Anya should write two values 100 and one value 101 (in any order), because it is the only possibility to make the average be the equal to the average of Kirill's values. Thus, all three measurements are equal.In the third example the number of equal measurements is 5.
Java 8
standard input
[ "implementation", "math" ]
dbbea6784cafdd4244f56729996e9187
The first line contains a single integer n (1 ≀ n ≀ 100 000) β€” the numeber of measurements made by Kirill. The second line contains a sequence of integers x1, x2, ..., xn ( - 100 000 ≀ xi ≀ 100 000) β€” the measurements made by Kirill. It is guaranteed that the difference between the maximum and minimum values among values x1, x2, ..., xn does not exceed 2.
1,700
In the first line print the minimum possible number of equal measurements. In the second line print n integers y1, y2, ..., yn β€” the values Anya should write. You can print the integers in arbitrary order. Keep in mind that the minimum value among Anya's values should be not less that the minimum among Kirill's values, and the maximum among Anya's values should be not greater than the maximum among Kirill's values. If there are multiple answers, print any of them.
standard output
PASSED
4b78eb429028105d03db222939f05b9d
train_000.jsonl
1520177700
Anya and Kirill are doing a physics laboratory work. In one of the tasks they have to measure some value n times, and then compute the average value to lower the error.Kirill has already made his measurements, and has got the following integer values: x1, x2, ..., xn. It is important that the values are close to each other, namely, the difference between the maximum value and the minimum value is at most 2.Anya does not want to make the measurements, however, she can't just copy the values from Kirill's work, because the error of each measurement is a random value, and this coincidence will be noted by the teacher. Anya wants to write such integer values y1, y2, ..., yn in her work, that the following conditions are met: the average value of x1, x2, ..., xn is equal to the average value of y1, y2, ..., yn; all Anya's measurements are in the same bounds as all Kirill's measurements, that is, the maximum value among Anya's values is not greater than the maximum value among Kirill's values, and the minimum value among Anya's values is not less than the minimum value among Kirill's values; the number of equal measurements in Anya's work and Kirill's work is as small as possible among options with the previous conditions met. Formally, the teacher goes through all Anya's values one by one, if there is equal value in Kirill's work and it is not strike off yet, he strikes off this Anya's value and one of equal values in Kirill's work. The number of equal measurements is then the total number of strike off values in Anya's work. Help Anya to write such a set of measurements that the conditions above are met.
256 megabytes
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ //package codeforces; import java.util.Scanner; /** * * @author Hemant Dhanuka */ public class four68C { public static void main(String[] args) { Scanner s=new Scanner(System.in); int n=s.nextInt(); int x[]=new int[n]; int y[]=new int[n]; int min=100001; for(int i=0;i<n;i++){ x[i]=s.nextInt(); y[i]=x[i]; if(x[i]<min){ min=x[i]; } } int frequency[]=new int[3]; for(int i=0;i<n;i++){ frequency[x[i]-min]++; } int count=0; for(int i=0;i<3;i++){ if(frequency[i]!=0){ count++; } } int values[]=new int[3]; for(int i=0;i<3;i++){ values[i]=min+i; } int notmatched=0; if(frequency[0] !=0 && frequency[2]!=0){ int t1=Math.min(frequency[0],frequency[2]); int t2=frequency[1]/2; t2=t2*2; if(t2>2*t1){ notmatched=t2; frequency[1]-=t2; frequency[0]+=t2/2; frequency[2]+=t2/2; } else{ notmatched=2*t1; frequency[1]+=2*t1; frequency[0]-=t1; frequency[2]-=t1; } int counter=0; for(int i=0;i<frequency[0];i++){ y[counter]=values[0]; counter++; } for(int i=0;i<frequency[1];i++){ y[counter]=values[1]; counter++; } for(int i=0;i<frequency[2];i++){ y[counter]=values[2]; counter++; } } System.out.println(n-notmatched); for(int y1:y){ System.out.print(y1+" "); } } }
Java
["6\n-1 1 1 0 0 -1", "3\n100 100 101", "7\n-10 -9 -10 -8 -10 -9 -9"]
1 second
["2\n0 0 0 0 0 0", "3\n101 100 100", "5\n-10 -10 -9 -9 -9 -9 -9"]
NoteIn the first example Anya can write zeros as here measurements results. The average value is then equal to the average value of Kirill's values, and there are only two equal measurements.In the second example Anya should write two values 100 and one value 101 (in any order), because it is the only possibility to make the average be the equal to the average of Kirill's values. Thus, all three measurements are equal.In the third example the number of equal measurements is 5.
Java 8
standard input
[ "implementation", "math" ]
dbbea6784cafdd4244f56729996e9187
The first line contains a single integer n (1 ≀ n ≀ 100 000) β€” the numeber of measurements made by Kirill. The second line contains a sequence of integers x1, x2, ..., xn ( - 100 000 ≀ xi ≀ 100 000) β€” the measurements made by Kirill. It is guaranteed that the difference between the maximum and minimum values among values x1, x2, ..., xn does not exceed 2.
1,700
In the first line print the minimum possible number of equal measurements. In the second line print n integers y1, y2, ..., yn β€” the values Anya should write. You can print the integers in arbitrary order. Keep in mind that the minimum value among Anya's values should be not less that the minimum among Kirill's values, and the maximum among Anya's values should be not greater than the maximum among Kirill's values. If there are multiple answers, print any of them.
standard output
PASSED
c1e2b691e15d3cfb01274c79f4407203
train_000.jsonl
1520177700
Anya and Kirill are doing a physics laboratory work. In one of the tasks they have to measure some value n times, and then compute the average value to lower the error.Kirill has already made his measurements, and has got the following integer values: x1, x2, ..., xn. It is important that the values are close to each other, namely, the difference between the maximum value and the minimum value is at most 2.Anya does not want to make the measurements, however, she can't just copy the values from Kirill's work, because the error of each measurement is a random value, and this coincidence will be noted by the teacher. Anya wants to write such integer values y1, y2, ..., yn in her work, that the following conditions are met: the average value of x1, x2, ..., xn is equal to the average value of y1, y2, ..., yn; all Anya's measurements are in the same bounds as all Kirill's measurements, that is, the maximum value among Anya's values is not greater than the maximum value among Kirill's values, and the minimum value among Anya's values is not less than the minimum value among Kirill's values; the number of equal measurements in Anya's work and Kirill's work is as small as possible among options with the previous conditions met. Formally, the teacher goes through all Anya's values one by one, if there is equal value in Kirill's work and it is not strike off yet, he strikes off this Anya's value and one of equal values in Kirill's work. The number of equal measurements is then the total number of strike off values in Anya's work. Help Anya to write such a set of measurements that the conditions above are met.
256 megabytes
import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; // atharva washimkar // May 16, 2018 public class CODEFORCES_931_C { public static void main (String[] t) throws IOException { INPUT in = new INPUT (System.in); PrintWriter out = new PrintWriter (System.out); int N = in.iscan (); int[] arr = new int[N]; Map<Integer, Integer> map = new HashMap<Integer, Integer> (); for (int n = 0; n < N; ++n) { arr[n] = in.iscan (); if (!map.containsKey (arr[n])) map.put (arr[n], 1); else map.put (arr[n], map.get (arr[n]) + 1); } List<Integer> keys = new ArrayList<Integer> (map.keySet ()); Collections.sort (keys); if (keys.size () == 1 || keys.size () == 2 && keys.get (0) + 1 == keys.get (1)) { // do nothing, just use original array } else if (keys.size () == 2) { int key1 = keys.get (0), key2 = keys.get (1); int min = 0, max = 0; if (map.get (key1) > map.get (key2)) { min = key2; max = key1; } else { min = key1; max = key2; } map.put ((min + max) / 2, 2 * map.get (min)); map.put (max, map.get (max) - map.get (min)); map.remove (min); } else { // try replacing two middle elements with one high one low, or vice versa int key1 = keys.get (0), key2 = keys.get (1), key3 = keys.get (2); int middleRemoved = map.get (key2) - (map.get (key2) % 2); int hiloRemoved = 2 * Math.min (map.get (key1), map.get (key3)); if (middleRemoved > hiloRemoved) { map.put (key1, map.get (key1) + middleRemoved / 2); map.put (key3, map.get (key3) + middleRemoved / 2); map.put (key2, map.get (key2) - middleRemoved); } else { map.put (key2, map.get (key2) + hiloRemoved); map.put (key1, map.get (key1) - hiloRemoved / 2); map.put (key3, map.get (key3) - hiloRemoved / 2); } } for (int i : keys) if (map.containsKey (i) && map.get (i) == 0) map.remove (i); List<Integer> ans = new ArrayList<Integer> (); for (int i : map.keySet ()) for (int j = 0; j < map.get (i); ++j) ans.add (i); int measurements = 0; for (int n = 0; n < N; ++n) { if (map.containsKey (arr[n])) { ++measurements; if (map.get (arr[n]) == 1) map.remove (arr[n]); else map.put (arr[n], map.get (arr[n]) - 1); } } out.println (measurements); for (int i : ans) out.print (i + " "); out.close (); } private static class INPUT { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar, numChars; public INPUT (InputStream stream) { this.stream = stream; } public INPUT (String file) throws IOException { this.stream = new FileInputStream (file); } public int cscan () throws IOException { if (curChar >= numChars) { curChar = 0; numChars = stream.read (buf); } if (numChars == -1) return numChars; return buf[curChar++]; } public int iscan () throws IOException { int c = cscan (), sgn = 1; while (space (c)) c = cscan (); if (c == '-') { sgn = -1; c = cscan (); } int res = 0; do { res = (res << 1) + (res << 3); res += c - '0'; c = cscan (); } while (!space (c)); return res * sgn; } public String sscan () throws IOException { int c = cscan (); while (space (c)) c = cscan (); StringBuilder res = new StringBuilder (); do { res.appendCodePoint (c); c = cscan (); } while (!space (c)); return res.toString (); } public double dscan () throws IOException { int c = cscan (), sgn = 1; while (space (c)) c = cscan (); if (c == '-') { sgn = -1; c = cscan (); } double res = 0; while (!space (c) && c != '.') { if (c == 'e' || c == 'E') return res * UTILITIES.fast_pow (10, iscan ()); res *= 10; res += c - '0'; c = cscan (); } if (c == '.') { c = cscan (); double m = 1; while (!space (c)) { if (c == 'e' || c == 'E') return res * UTILITIES.fast_pow (10, iscan ()); m /= 10; res += (c - '0') * m; c = cscan (); } } return res * sgn; } public long lscan () throws IOException { int c = cscan (), sgn = 1; while (space (c)) c = cscan (); if (c == '-') { sgn = -1; c = cscan (); } long res = 0; do { res = (res << 1) + (res << 3); res += c - '0'; c = cscan (); } while (!space (c)); return res * sgn; } public boolean space (int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } public static class UTILITIES { static final double EPS = 10e-6; public static int lower_bound (int[] arr, int x) { int low = 0, high = arr.length, mid = -1; while (low < high) { mid = (low + high) / 2; if (arr[mid] >= x) high = mid; else low = mid + 1; } return low; } public static int upper_bound (int[] arr, int x) { int low = 0, high = arr.length, mid = -1; while (low < high) { mid = (low + high) / 2; if (arr[mid] > x) high = mid; else low = mid + 1; } return low; } public static int gcd (int a, int b) { return b == 0 ? a : gcd (b, a % b); } public static int lcm (int a, int b) { return a * b / gcd (a, b); } public static int fast_pow_mod (int b, int x, int mod) { if (x == 0) return 1; if (x == 1) return b; if (x % 2 == 0) return fast_pow_mod (b * b % mod, x / 2, mod) % mod; return b * fast_pow_mod (b * b % mod, x / 2, mod) % mod; } public static int fast_pow (int b, int x) { if (x == 0) return 1; if (x == 1) return b; if (x % 2 == 0) return fast_pow (b * b, x / 2); return b * fast_pow (b * b, x / 2); } public static long choose (long n, long k) { k = Math.min (k, n - k); long val = 1; for (int i = 0; i < k; ++i) val = val * (n - i) / (i + 1); return val; } public static long permute (int n, int k) { if (n < k) return 0; long val = 1; for (int i = 0; i < k; ++i) val = (val * (n - i)); return val; } } }
Java
["6\n-1 1 1 0 0 -1", "3\n100 100 101", "7\n-10 -9 -10 -8 -10 -9 -9"]
1 second
["2\n0 0 0 0 0 0", "3\n101 100 100", "5\n-10 -10 -9 -9 -9 -9 -9"]
NoteIn the first example Anya can write zeros as here measurements results. The average value is then equal to the average value of Kirill's values, and there are only two equal measurements.In the second example Anya should write two values 100 and one value 101 (in any order), because it is the only possibility to make the average be the equal to the average of Kirill's values. Thus, all three measurements are equal.In the third example the number of equal measurements is 5.
Java 8
standard input
[ "implementation", "math" ]
dbbea6784cafdd4244f56729996e9187
The first line contains a single integer n (1 ≀ n ≀ 100 000) β€” the numeber of measurements made by Kirill. The second line contains a sequence of integers x1, x2, ..., xn ( - 100 000 ≀ xi ≀ 100 000) β€” the measurements made by Kirill. It is guaranteed that the difference between the maximum and minimum values among values x1, x2, ..., xn does not exceed 2.
1,700
In the first line print the minimum possible number of equal measurements. In the second line print n integers y1, y2, ..., yn β€” the values Anya should write. You can print the integers in arbitrary order. Keep in mind that the minimum value among Anya's values should be not less that the minimum among Kirill's values, and the maximum among Anya's values should be not greater than the maximum among Kirill's values. If there are multiple answers, print any of them.
standard output
PASSED
f96851dc01b028090a6ee508812a3bf5
train_000.jsonl
1520177700
Anya and Kirill are doing a physics laboratory work. In one of the tasks they have to measure some value n times, and then compute the average value to lower the error.Kirill has already made his measurements, and has got the following integer values: x1, x2, ..., xn. It is important that the values are close to each other, namely, the difference between the maximum value and the minimum value is at most 2.Anya does not want to make the measurements, however, she can't just copy the values from Kirill's work, because the error of each measurement is a random value, and this coincidence will be noted by the teacher. Anya wants to write such integer values y1, y2, ..., yn in her work, that the following conditions are met: the average value of x1, x2, ..., xn is equal to the average value of y1, y2, ..., yn; all Anya's measurements are in the same bounds as all Kirill's measurements, that is, the maximum value among Anya's values is not greater than the maximum value among Kirill's values, and the minimum value among Anya's values is not less than the minimum value among Kirill's values; the number of equal measurements in Anya's work and Kirill's work is as small as possible among options with the previous conditions met. Formally, the teacher goes through all Anya's values one by one, if there is equal value in Kirill's work and it is not strike off yet, he strikes off this Anya's value and one of equal values in Kirill's work. The number of equal measurements is then the total number of strike off values in Anya's work. Help Anya to write such a set of measurements that the conditions above are met.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class Main { private static int N; private static int[] array; private static int numZero, numOne, numTwo; public static void main(String[] args) throws IOException { BufferedReader f = new BufferedReader(new InputStreamReader(System.in)); N = Integer.parseInt(f.readLine()); array = new int[N]; int min = Integer.MAX_VALUE; int max = Integer.MIN_VALUE; StringTokenizer st = new StringTokenizer(f.readLine()); for (int i = 0; i < N; i++) { int temp = Integer.parseInt(st.nextToken()); array[i] = temp; min = Math.min(min, temp); max = Math.max(max, temp); } StringBuilder sb = new StringBuilder(); if (max - min <= 1) { System.out.println(N); for (int i : array) { sb.append(i + " "); } sb.delete(sb.length() - 1, sb.length()); System.out.println(sb.toString()); System.exit(0); } for (int i = 0; i < N; i++) { if (array[i] == max) { array[i] = 2; numTwo++; } else if (array[i] == min) { array[i] = 0; numZero++; } else { array[i] = 1; numOne++; } } int min02 = Math.min(numZero, numTwo); int result = 0; int result1 = numZero + numTwo + numOne % 2; int result2 = numOne + numZero - min02 + numTwo - min02; if (result1 < result2) { int half = numOne >> 1; result = result1; numZero += half; numTwo += half; numOne -= half * 2; } else { numZero -= min02; numTwo -= min02; result = result2; numOne += min02 * 2; } for (int i = 0; i < numZero; i++) { sb.append(min).append(" "); } for (int i = 0; i < numOne; i++) { sb.append(min + 1).append(" "); } for (int i = 0; i < numTwo; i++) { sb.append(max).append(" "); } System.out.println(result); sb.delete(sb.length() - 1, sb.length()); System.out.println(sb.toString()); } }
Java
["6\n-1 1 1 0 0 -1", "3\n100 100 101", "7\n-10 -9 -10 -8 -10 -9 -9"]
1 second
["2\n0 0 0 0 0 0", "3\n101 100 100", "5\n-10 -10 -9 -9 -9 -9 -9"]
NoteIn the first example Anya can write zeros as here measurements results. The average value is then equal to the average value of Kirill's values, and there are only two equal measurements.In the second example Anya should write two values 100 and one value 101 (in any order), because it is the only possibility to make the average be the equal to the average of Kirill's values. Thus, all three measurements are equal.In the third example the number of equal measurements is 5.
Java 8
standard input
[ "implementation", "math" ]
dbbea6784cafdd4244f56729996e9187
The first line contains a single integer n (1 ≀ n ≀ 100 000) β€” the numeber of measurements made by Kirill. The second line contains a sequence of integers x1, x2, ..., xn ( - 100 000 ≀ xi ≀ 100 000) β€” the measurements made by Kirill. It is guaranteed that the difference between the maximum and minimum values among values x1, x2, ..., xn does not exceed 2.
1,700
In the first line print the minimum possible number of equal measurements. In the second line print n integers y1, y2, ..., yn β€” the values Anya should write. You can print the integers in arbitrary order. Keep in mind that the minimum value among Anya's values should be not less that the minimum among Kirill's values, and the maximum among Anya's values should be not greater than the maximum among Kirill's values. If there are multiple answers, print any of them.
standard output
PASSED
056934a144c6211aaec5ec6448bb66e1
train_000.jsonl
1520177700
Anya and Kirill are doing a physics laboratory work. In one of the tasks they have to measure some value n times, and then compute the average value to lower the error.Kirill has already made his measurements, and has got the following integer values: x1, x2, ..., xn. It is important that the values are close to each other, namely, the difference between the maximum value and the minimum value is at most 2.Anya does not want to make the measurements, however, she can't just copy the values from Kirill's work, because the error of each measurement is a random value, and this coincidence will be noted by the teacher. Anya wants to write such integer values y1, y2, ..., yn in her work, that the following conditions are met: the average value of x1, x2, ..., xn is equal to the average value of y1, y2, ..., yn; all Anya's measurements are in the same bounds as all Kirill's measurements, that is, the maximum value among Anya's values is not greater than the maximum value among Kirill's values, and the minimum value among Anya's values is not less than the minimum value among Kirill's values; the number of equal measurements in Anya's work and Kirill's work is as small as possible among options with the previous conditions met. Formally, the teacher goes through all Anya's values one by one, if there is equal value in Kirill's work and it is not strike off yet, he strikes off this Anya's value and one of equal values in Kirill's work. The number of equal measurements is then the total number of strike off values in Anya's work. Help Anya to write such a set of measurements that the conditions above are met.
256 megabytes
import java.util.*; public class r468c { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int u, v, mid; u = 100000; v = -100000; int a[] = new int[n]; for(int i = 0; i < n; i++) { int x = sc.nextInt(); a[i] = x; if(u > x) { u = x; } if(v < x) { v = x; } // if(x != u && x != v) { // mid = x; // } } int cntu = 0; int cntv = 0; int cntmid = 0; for(int i = 0; i < n; i++) { if(a[i] == u) cntu++; else if(a[i] == v) cntv++; else cntmid++; } int same=0; if(v-u == 0) { same = n; System.out.println(same); for(int i = 0; i < n; i++) { System.out.print(v+" "); } } else if(v-u == 1) { same = n; System.out.println(same); for(int i = 0; i < cntu; i++){ System.out.print(u+" "); } for(int i = 0; i < cntv; i++) { System.out.print(v+" "); } } else { mid = u+1; int m = Math.min(cntu, cntv); int pcntu =cntu- m; int pcntv =cntv- m; int pcntmid = cntmid+ 2*m; int psame = pcntu+pcntv+cntmid; int half = cntmid/2; int qcntu = cntu+half; int qcntv = cntv+half; int qcntmid = cntmid-2*half; int qsame = cntu+cntv+ qcntmid; if(psame <= qsame) { cntu = pcntu; cntv = pcntv; cntmid = pcntmid; same = psame; } else { cntu = qcntu; cntv = qcntv; cntmid = qcntmid; same = qsame; } System.out.println(same); for(int i = 0; i < cntu; i++){ System.out.print(u+" "); } for(int i = 0; i < cntv; i++) { System.out.print(v+" "); } for(int i = 0; i < cntmid; i++) { System.out.print(mid+" "); } } } }
Java
["6\n-1 1 1 0 0 -1", "3\n100 100 101", "7\n-10 -9 -10 -8 -10 -9 -9"]
1 second
["2\n0 0 0 0 0 0", "3\n101 100 100", "5\n-10 -10 -9 -9 -9 -9 -9"]
NoteIn the first example Anya can write zeros as here measurements results. The average value is then equal to the average value of Kirill's values, and there are only two equal measurements.In the second example Anya should write two values 100 and one value 101 (in any order), because it is the only possibility to make the average be the equal to the average of Kirill's values. Thus, all three measurements are equal.In the third example the number of equal measurements is 5.
Java 8
standard input
[ "implementation", "math" ]
dbbea6784cafdd4244f56729996e9187
The first line contains a single integer n (1 ≀ n ≀ 100 000) β€” the numeber of measurements made by Kirill. The second line contains a sequence of integers x1, x2, ..., xn ( - 100 000 ≀ xi ≀ 100 000) β€” the measurements made by Kirill. It is guaranteed that the difference between the maximum and minimum values among values x1, x2, ..., xn does not exceed 2.
1,700
In the first line print the minimum possible number of equal measurements. In the second line print n integers y1, y2, ..., yn β€” the values Anya should write. You can print the integers in arbitrary order. Keep in mind that the minimum value among Anya's values should be not less that the minimum among Kirill's values, and the maximum among Anya's values should be not greater than the maximum among Kirill's values. If there are multiple answers, print any of them.
standard output
PASSED
efd7543fd18f0565a2c8ca9995058a42
train_000.jsonl
1520177700
Anya and Kirill are doing a physics laboratory work. In one of the tasks they have to measure some value n times, and then compute the average value to lower the error.Kirill has already made his measurements, and has got the following integer values: x1, x2, ..., xn. It is important that the values are close to each other, namely, the difference between the maximum value and the minimum value is at most 2.Anya does not want to make the measurements, however, she can't just copy the values from Kirill's work, because the error of each measurement is a random value, and this coincidence will be noted by the teacher. Anya wants to write such integer values y1, y2, ..., yn in her work, that the following conditions are met: the average value of x1, x2, ..., xn is equal to the average value of y1, y2, ..., yn; all Anya's measurements are in the same bounds as all Kirill's measurements, that is, the maximum value among Anya's values is not greater than the maximum value among Kirill's values, and the minimum value among Anya's values is not less than the minimum value among Kirill's values; the number of equal measurements in Anya's work and Kirill's work is as small as possible among options with the previous conditions met. Formally, the teacher goes through all Anya's values one by one, if there is equal value in Kirill's work and it is not strike off yet, he strikes off this Anya's value and one of equal values in Kirill's work. The number of equal measurements is then the total number of strike off values in Anya's work. Help Anya to write such a set of measurements that the conditions above are met.
256 megabytes
import java.io.*; import java.util.*; 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); TaskE solver = new TaskE(); solver.solve(1, in, out); out.flush();out.close(); } static class TaskE { public void solve(int testNumber, InputReader in, PrintWriter out) { int n=in.nextInt(); int a[]=new int[n]; for(int i=0;i<n;i++)a[i]=in.nextInt(); Arrays.sort(a); int v1=a[0],v2=v1+1,v3=a[a.length-1]; if(v1==v3||v1==v3-1){ out.println(n); for(int i=0;i<n;i++)out.print(a[i]+" "); }else{ int f1=0,f2=0,f3=0; for(int i=0;i<n;i++){ if(a[i]==v1)++f1; else if(a[i]==v2)++f2; else ++f3; } int x=Math.min(f1,f3),y=(f2/2)*2; if(2*x>y){ f2+=2*x;f1-=x;f3-=x; out.println(n-2*x); } else{ f2-=y;f1+=y/2;f3+=y/2; out.println(n-y); } for(int i=0;i<f1;i++){ out.print(v1+" "); }for(int i=0;i<f2;i++){ out.print(v2+" "); }for(int i=0;i<f3;i++){ out.print(v3+" "); } } } /*pair ja[][];long w[];int from[],to[],c[]; void make(int n,int m,InputReader in){ ja=new pair[n+1][];w=new long[m];from=new int[m];to=new int[m];c=new int[n+1]; for(int i=0;i<m;i++){ int u=in.nextInt(),v=in.nextInt();long wt=in.nextLong(); c[u]++;c[v]++;from[i]=u;to[i]=v;w[i]=wt; } for(int i=1;i<=n;i++){ ja[i]=new pair[c[i]];c[i]=0; } for(int i=0;i<m;i++){ ja[from[i]][c[from[i]]++]=new pair(to[i],w[i]); ja[to[i]][c[to[i]]++]=new pair(from[i],w[i]); } }*/ int[] radixSort(int[] f){ return radixSort(f, f.length); } int[] radixSort(int[] f, int n) { int[] to = new int[n]; { int[] b = new int[65537]; for(int i = 0;i < n;i++)b[1+(f[i]&0xffff)]++; for(int i = 1;i <= 65536;i++)b[i]+=b[i-1]; for(int i = 0;i < n;i++)to[b[f[i]&0xffff]++] = f[i]; int[] d = f; f = to;to = d; } { int[] b = new int[65537]; for(int i = 0;i < n;i++)b[1+(f[i]>>>16)]++; for(int i = 1;i <= 65536;i++)b[i]+=b[i-1]; for(int i = 0;i < n;i++)to[b[f[i]>>>16]++] = f[i]; int[] d = f; f = to;to = d; } return f; } } static class InputReader { BufferedReader br; StringTokenizer st; public InputReader(InputStream stream) { br = new BufferedReader(new InputStreamReader(stream)); st = null; } 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; } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } } }
Java
["6\n-1 1 1 0 0 -1", "3\n100 100 101", "7\n-10 -9 -10 -8 -10 -9 -9"]
1 second
["2\n0 0 0 0 0 0", "3\n101 100 100", "5\n-10 -10 -9 -9 -9 -9 -9"]
NoteIn the first example Anya can write zeros as here measurements results. The average value is then equal to the average value of Kirill's values, and there are only two equal measurements.In the second example Anya should write two values 100 and one value 101 (in any order), because it is the only possibility to make the average be the equal to the average of Kirill's values. Thus, all three measurements are equal.In the third example the number of equal measurements is 5.
Java 8
standard input
[ "implementation", "math" ]
dbbea6784cafdd4244f56729996e9187
The first line contains a single integer n (1 ≀ n ≀ 100 000) β€” the numeber of measurements made by Kirill. The second line contains a sequence of integers x1, x2, ..., xn ( - 100 000 ≀ xi ≀ 100 000) β€” the measurements made by Kirill. It is guaranteed that the difference between the maximum and minimum values among values x1, x2, ..., xn does not exceed 2.
1,700
In the first line print the minimum possible number of equal measurements. In the second line print n integers y1, y2, ..., yn β€” the values Anya should write. You can print the integers in arbitrary order. Keep in mind that the minimum value among Anya's values should be not less that the minimum among Kirill's values, and the maximum among Anya's values should be not greater than the maximum among Kirill's values. If there are multiple answers, print any of them.
standard output
PASSED
0560469644eab594f9d3a34deb19d804
train_000.jsonl
1520177700
Anya and Kirill are doing a physics laboratory work. In one of the tasks they have to measure some value n times, and then compute the average value to lower the error.Kirill has already made his measurements, and has got the following integer values: x1, x2, ..., xn. It is important that the values are close to each other, namely, the difference between the maximum value and the minimum value is at most 2.Anya does not want to make the measurements, however, she can't just copy the values from Kirill's work, because the error of each measurement is a random value, and this coincidence will be noted by the teacher. Anya wants to write such integer values y1, y2, ..., yn in her work, that the following conditions are met: the average value of x1, x2, ..., xn is equal to the average value of y1, y2, ..., yn; all Anya's measurements are in the same bounds as all Kirill's measurements, that is, the maximum value among Anya's values is not greater than the maximum value among Kirill's values, and the minimum value among Anya's values is not less than the minimum value among Kirill's values; the number of equal measurements in Anya's work and Kirill's work is as small as possible among options with the previous conditions met. Formally, the teacher goes through all Anya's values one by one, if there is equal value in Kirill's work and it is not strike off yet, he strikes off this Anya's value and one of equal values in Kirill's work. The number of equal measurements is then the total number of strike off values in Anya's work. Help Anya to write such a set of measurements that the conditions above are met.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.HashMap; import java.util.Map; public class ProblemC { public static void main(String[] args)throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(reader.readLine()); String[] strs = reader.readLine().split(" "); int[] nums = new int[n]; Map<Integer, Integer> countMap = new HashMap<>(); for(int i = 0; i < n; i++){ nums[i] = Integer.parseInt(strs[i]); countMap.put(nums[i], countMap.getOrDefault(nums[i], 0) + 1); } if(countMap.size() == 1){ printNums(nums, n); System.exit(0); } Arrays.sort(nums); int left = 0, right = n - 1; while(left < countMap.get(nums[0])){ left++; } while(n - right - 1 < countMap.get(nums[n - 1])){ right--; } if(countMap.size() == 2){ if(nums[n - 1] - nums[0] == 1){ printNums(nums, n); System.exit(0); } } int strikeOuter = n - Math.min(left, n - right - 1) * 2; int strikeInner = n - ((right - left + 1) / 2) * 2; boolean walkInner = strikeInner < strikeOuter; if(right < left && !walkInner){ nums[left--]--; nums[right++]++; } while(right >= left && right < n && left >= 0){ if(walkInner){ nums[left]++; nums[right]--; }else if(left > 0 && right < n - 1) { nums[left - 1]++; nums[right + 1]--; } left += walkInner? 1: -1; right -= walkInner? 1: -1; } printNums(nums, Math.min(strikeInner, strikeOuter)); } private static void printNums(int[] nums, int res) { System.out.println(res); for(int i = 0; i < nums.length; i++){ System.out.print(nums[i] + " "); } System.out.println(); } }
Java
["6\n-1 1 1 0 0 -1", "3\n100 100 101", "7\n-10 -9 -10 -8 -10 -9 -9"]
1 second
["2\n0 0 0 0 0 0", "3\n101 100 100", "5\n-10 -10 -9 -9 -9 -9 -9"]
NoteIn the first example Anya can write zeros as here measurements results. The average value is then equal to the average value of Kirill's values, and there are only two equal measurements.In the second example Anya should write two values 100 and one value 101 (in any order), because it is the only possibility to make the average be the equal to the average of Kirill's values. Thus, all three measurements are equal.In the third example the number of equal measurements is 5.
Java 8
standard input
[ "implementation", "math" ]
dbbea6784cafdd4244f56729996e9187
The first line contains a single integer n (1 ≀ n ≀ 100 000) β€” the numeber of measurements made by Kirill. The second line contains a sequence of integers x1, x2, ..., xn ( - 100 000 ≀ xi ≀ 100 000) β€” the measurements made by Kirill. It is guaranteed that the difference between the maximum and minimum values among values x1, x2, ..., xn does not exceed 2.
1,700
In the first line print the minimum possible number of equal measurements. In the second line print n integers y1, y2, ..., yn β€” the values Anya should write. You can print the integers in arbitrary order. Keep in mind that the minimum value among Anya's values should be not less that the minimum among Kirill's values, and the maximum among Anya's values should be not greater than the maximum among Kirill's values. If there are multiple answers, print any of them.
standard output
PASSED
8c58a39dd14c4e5d77c96512626a4214
train_000.jsonl
1520177700
Anya and Kirill are doing a physics laboratory work. In one of the tasks they have to measure some value n times, and then compute the average value to lower the error.Kirill has already made his measurements, and has got the following integer values: x1, x2, ..., xn. It is important that the values are close to each other, namely, the difference between the maximum value and the minimum value is at most 2.Anya does not want to make the measurements, however, she can't just copy the values from Kirill's work, because the error of each measurement is a random value, and this coincidence will be noted by the teacher. Anya wants to write such integer values y1, y2, ..., yn in her work, that the following conditions are met: the average value of x1, x2, ..., xn is equal to the average value of y1, y2, ..., yn; all Anya's measurements are in the same bounds as all Kirill's measurements, that is, the maximum value among Anya's values is not greater than the maximum value among Kirill's values, and the minimum value among Anya's values is not less than the minimum value among Kirill's values; the number of equal measurements in Anya's work and Kirill's work is as small as possible among options with the previous conditions met. Formally, the teacher goes through all Anya's values one by one, if there is equal value in Kirill's work and it is not strike off yet, he strikes off this Anya's value and one of equal values in Kirill's work. The number of equal measurements is then the total number of strike off values in Anya's work. Help Anya to write such a set of measurements that the conditions above are met.
256 megabytes
import java.util.*; import java.io.*; import java.lang.*; import java.math.*; import static java.lang.Math.*; public class Sol implements Runnable { long mod = (long)1e9 + 7; void solve(int total_test_cases, InputReader in, PrintWriter w) { for (int test_case = 1; test_case <= total_test_cases; test_case++) { int n = in.nextInt(); int a[] = new int[n]; for(int i=0;i<n;i++) a[i] = in.nextInt(); Arrays.sort(a); int diff = a[n - 1] - a[0]; if(diff < 2) { w.println(n); for(int i=0;i<n;i++) w.print(a[i]+" "); } else { int min = a[0], max = a[n - 1]; int i = 0, j = n - 1; int val = (min + max) / 2; int change2 = 0; for(int k=0;k<n;k++) if(a[k] == val) change2++; change2 /= 2; change2 *= 2; int change1 = 0; while(true) { if(a[i] != min) break; if(a[j] != max) break; i++; j--; change1 += 2; } if(change1 > change2) { i = 0; j = n - 1; while(true) { if(a[i] != min) break; if(a[j] != max) break; a[i] = val; a[j] = val; i++; j--; } w.println(n - change1); } else { for(int k=0;k<n-1;k++) { if(a[k] == val && a[k + 1] == val) { a[k] = min; a[k + 1] = max; k++; } } w.println(n - change2); } for(int k=0;k<n;k++) w.print(a[k]+" "); } } } // ************* Code ends here *************** void init() throws Exception { //Scanner in; InputReader in; PrintWriter w; boolean online = false; String common_in_fileName = "\\in"; String common_out_fileName = "\\out"; int test_files = 0; for(int file_no = 0; file_no <= test_files; file_no++) { String x = "" + file_no; if (x.length() == 1) x = "0" + x; String in_fileName = common_in_fileName + "" + x; String out_fileName = common_out_fileName + "" + x; if (online) { //in = new Scanner(new File(in_fileName + ".txt")); in = new InputReader(new FileInputStream(new File(in_fileName + ".txt"))); w = new PrintWriter(new FileWriter(out_fileName + ".txt")); } else { //in = new Scanner(System.in); in = new InputReader(System.in); w = new PrintWriter(System.out); } solve(1, in, w); w.close(); } } public void run() { try { init(); } catch(Exception e) { System.out.println(e); e.printStackTrace(); } } public static void main(String args[]) throws Exception { new Thread(null, new Sol(),"Sol",1<<28).start(); } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public String nextLine() { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public double nextDouble() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } double res = 0; while (!isSpaceChar(c) && c != '.') { if (c == 'e' || c == 'E') { return res * Math.pow(10, nextInt()); } if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } if (c == '.') { c = read(); double m = 1; while (!isSpaceChar(c)) { if (c == 'e' || c == 'E') { return res * Math.pow(10, nextInt()); } if (c < '0' || c > '9') { throw new InputMismatchException(); } m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return readString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["6\n-1 1 1 0 0 -1", "3\n100 100 101", "7\n-10 -9 -10 -8 -10 -9 -9"]
1 second
["2\n0 0 0 0 0 0", "3\n101 100 100", "5\n-10 -10 -9 -9 -9 -9 -9"]
NoteIn the first example Anya can write zeros as here measurements results. The average value is then equal to the average value of Kirill's values, and there are only two equal measurements.In the second example Anya should write two values 100 and one value 101 (in any order), because it is the only possibility to make the average be the equal to the average of Kirill's values. Thus, all three measurements are equal.In the third example the number of equal measurements is 5.
Java 8
standard input
[ "implementation", "math" ]
dbbea6784cafdd4244f56729996e9187
The first line contains a single integer n (1 ≀ n ≀ 100 000) β€” the numeber of measurements made by Kirill. The second line contains a sequence of integers x1, x2, ..., xn ( - 100 000 ≀ xi ≀ 100 000) β€” the measurements made by Kirill. It is guaranteed that the difference between the maximum and minimum values among values x1, x2, ..., xn does not exceed 2.
1,700
In the first line print the minimum possible number of equal measurements. In the second line print n integers y1, y2, ..., yn β€” the values Anya should write. You can print the integers in arbitrary order. Keep in mind that the minimum value among Anya's values should be not less that the minimum among Kirill's values, and the maximum among Anya's values should be not greater than the maximum among Kirill's values. If there are multiple answers, print any of them.
standard output
PASSED
d6093f708df20cb3a91bacbc8d51fc58
train_000.jsonl
1520177700
Anya and Kirill are doing a physics laboratory work. In one of the tasks they have to measure some value n times, and then compute the average value to lower the error.Kirill has already made his measurements, and has got the following integer values: x1, x2, ..., xn. It is important that the values are close to each other, namely, the difference between the maximum value and the minimum value is at most 2.Anya does not want to make the measurements, however, she can't just copy the values from Kirill's work, because the error of each measurement is a random value, and this coincidence will be noted by the teacher. Anya wants to write such integer values y1, y2, ..., yn in her work, that the following conditions are met: the average value of x1, x2, ..., xn is equal to the average value of y1, y2, ..., yn; all Anya's measurements are in the same bounds as all Kirill's measurements, that is, the maximum value among Anya's values is not greater than the maximum value among Kirill's values, and the minimum value among Anya's values is not less than the minimum value among Kirill's values; the number of equal measurements in Anya's work and Kirill's work is as small as possible among options with the previous conditions met. Formally, the teacher goes through all Anya's values one by one, if there is equal value in Kirill's work and it is not strike off yet, he strikes off this Anya's value and one of equal values in Kirill's work. The number of equal measurements is then the total number of strike off values in Anya's work. Help Anya to write such a set of measurements that the conditions above are met.
256 megabytes
import java.io.*; import java.util.*; public class check { static boolean DEBUG_FLAG = false; int INF = (int)1e9; long MOD = 1000000007; static void debug(String s) { if(DEBUG_FLAG) { System.out.print(s); } } void solve(InputReader in, PrintWriter out) throws IOException { int n = in.nextInt(); int[] a = new int[n]; int min = INF, max = -INF; for(int i=0; i<n; i++) { a[i] = in.nextInt(); min = Math.min(a[i], min); max = Math.max(a[i], max); } if(max-min<2) { out.println(n); for(int i=0; i<n; i++) { out.print(a[i]+" "); } out.println(); return; } int x = 0, y = 0, z = 0; for(int i=0; i<n; i++) { if(a[i]==min) x++; else if(a[i]==max) y++; else z++; } int m = (min+max)/2; if(z==0) { int mt = 0, dv = 0, dt = 0; if(x>y) { mt = 2*y; dv = min; dt = x-y; } else if(x<=y) { mt = 2*x; dv = max; dt = y-x; } out.println(dt); for(int i=0; i<mt; i++) { out.print(m+" "); } for(int i=0; i<dt; i++) { out.print(dv+" "); } out.println(); return; } int mt = 0, mint = 0, maxt = 0, dt = 0; int combi = Math.min(x, y); if((n-x-y)/2 > combi) { y = y + z/2; x = x + z/2; combi = z/2; } else { x = x - combi; y = y - combi; } // mt = n - mint - maxt; // out.println(Math.min(mint, x)+Math.min(mt, z)+Math.min(maxt, y)); // out.println(mint+" "+mt+" "+maxt); out.println(n-2*combi); for(int i=0; i<x; i++) { out.print(min+" "); } for(int i=0; i<n-x-y; i++) { out.print(m+" "); } for(int i=0; i<y; i++) { out.print(max+" "); } out.println(); } public static void main(String[] args) throws IOException { if(args.length>0 && args[0].equalsIgnoreCase("d")) { DEBUG_FLAG = true; } InputReader in = new InputReader(); PrintWriter out = new PrintWriter(System.out); int t = 1;//in.nextInt(); long start = System.nanoTime(); while(t-- >0) { new check().solve(in, out); } long end = System.nanoTime(); debug("\nTime: " + (end-start)/1e6 + " \n\n"); out.close(); } static class InputReader { static BufferedReader br; static StringTokenizer st; public InputReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } } }
Java
["6\n-1 1 1 0 0 -1", "3\n100 100 101", "7\n-10 -9 -10 -8 -10 -9 -9"]
1 second
["2\n0 0 0 0 0 0", "3\n101 100 100", "5\n-10 -10 -9 -9 -9 -9 -9"]
NoteIn the first example Anya can write zeros as here measurements results. The average value is then equal to the average value of Kirill's values, and there are only two equal measurements.In the second example Anya should write two values 100 and one value 101 (in any order), because it is the only possibility to make the average be the equal to the average of Kirill's values. Thus, all three measurements are equal.In the third example the number of equal measurements is 5.
Java 8
standard input
[ "implementation", "math" ]
dbbea6784cafdd4244f56729996e9187
The first line contains a single integer n (1 ≀ n ≀ 100 000) β€” the numeber of measurements made by Kirill. The second line contains a sequence of integers x1, x2, ..., xn ( - 100 000 ≀ xi ≀ 100 000) β€” the measurements made by Kirill. It is guaranteed that the difference between the maximum and minimum values among values x1, x2, ..., xn does not exceed 2.
1,700
In the first line print the minimum possible number of equal measurements. In the second line print n integers y1, y2, ..., yn β€” the values Anya should write. You can print the integers in arbitrary order. Keep in mind that the minimum value among Anya's values should be not less that the minimum among Kirill's values, and the maximum among Anya's values should be not greater than the maximum among Kirill's values. If there are multiple answers, print any of them.
standard output
PASSED
8969494836bc5b7469527ef2709ee0f7
train_000.jsonl
1520177700
Anya and Kirill are doing a physics laboratory work. In one of the tasks they have to measure some value n times, and then compute the average value to lower the error.Kirill has already made his measurements, and has got the following integer values: x1, x2, ..., xn. It is important that the values are close to each other, namely, the difference between the maximum value and the minimum value is at most 2.Anya does not want to make the measurements, however, she can't just copy the values from Kirill's work, because the error of each measurement is a random value, and this coincidence will be noted by the teacher. Anya wants to write such integer values y1, y2, ..., yn in her work, that the following conditions are met: the average value of x1, x2, ..., xn is equal to the average value of y1, y2, ..., yn; all Anya's measurements are in the same bounds as all Kirill's measurements, that is, the maximum value among Anya's values is not greater than the maximum value among Kirill's values, and the minimum value among Anya's values is not less than the minimum value among Kirill's values; the number of equal measurements in Anya's work and Kirill's work is as small as possible among options with the previous conditions met. Formally, the teacher goes through all Anya's values one by one, if there is equal value in Kirill's work and it is not strike off yet, he strikes off this Anya's value and one of equal values in Kirill's work. The number of equal measurements is then the total number of strike off values in Anya's work. Help Anya to write such a set of measurements that the conditions above are met.
256 megabytes
import java.io.*; import java.util.*; public class check { static boolean DEBUG_FLAG = false; int INF = (int)1e9; long MOD = 1000000007; static void debug(String s) { if(DEBUG_FLAG) { System.out.print(s); } } void solve(InputReader in, PrintWriter out) throws IOException { int n = in.nextInt(); int[] a = new int[n]; int min = INF, max = -INF; for(int i=0; i<n; i++) { a[i] = in.nextInt(); min = Math.min(a[i], min); max = Math.max(a[i], max); } if(max-min<2) { out.println(n); for(int i=0; i<n; i++) { out.print(a[i]+" "); } out.println(); return; } int x = 0, y = 0, z = 0; for(int i=0; i<n; i++) { if(a[i]==min) x++; else if(a[i]==max) y++; else z++; } int m = (min+max)/2; if(z==0) { int mt = 0, dv = 0, dt = 0; if(x>y) { mt = 2*y; dv = min; dt = x-y; } else if(x<=y) { mt = 2*x; dv = max; dt = y-x; } out.println(dt); for(int i=0; i<mt; i++) { out.print(m+" "); } for(int i=0; i<dt; i++) { out.print(dv+" "); } out.println(); return; } int mt = 0, mint = 0, maxt = 0, dt = 0; int combi = Math.min(x, y); if(z/2 > combi) { maxt = y + z/2; mint = x + z/2; } else { mint = x - combi; maxt = y - combi; } mt = n - mint - maxt; out.println(Math.min(mint, x)+Math.min(mt, z)+Math.min(maxt, y)); // out.println(mint+" "+mt+" "+maxt); for(int i=0; i<mint; i++) { out.print(min+" "); } for(int i=0; i<mt; i++) { out.print(m+" "); } for(int i=0; i<maxt; i++) { out.print(max+" "); } out.println(); } public static void main(String[] args) throws IOException { if(args.length>0 && args[0].equalsIgnoreCase("d")) { DEBUG_FLAG = true; } InputReader in = new InputReader(); PrintWriter out = new PrintWriter(System.out); int t = 1;//in.nextInt(); long start = System.nanoTime(); while(t-- >0) { new check().solve(in, out); } long end = System.nanoTime(); debug("\nTime: " + (end-start)/1e6 + " \n\n"); out.close(); } static class InputReader { static BufferedReader br; static StringTokenizer st; public InputReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } } }
Java
["6\n-1 1 1 0 0 -1", "3\n100 100 101", "7\n-10 -9 -10 -8 -10 -9 -9"]
1 second
["2\n0 0 0 0 0 0", "3\n101 100 100", "5\n-10 -10 -9 -9 -9 -9 -9"]
NoteIn the first example Anya can write zeros as here measurements results. The average value is then equal to the average value of Kirill's values, and there are only two equal measurements.In the second example Anya should write two values 100 and one value 101 (in any order), because it is the only possibility to make the average be the equal to the average of Kirill's values. Thus, all three measurements are equal.In the third example the number of equal measurements is 5.
Java 8
standard input
[ "implementation", "math" ]
dbbea6784cafdd4244f56729996e9187
The first line contains a single integer n (1 ≀ n ≀ 100 000) β€” the numeber of measurements made by Kirill. The second line contains a sequence of integers x1, x2, ..., xn ( - 100 000 ≀ xi ≀ 100 000) β€” the measurements made by Kirill. It is guaranteed that the difference between the maximum and minimum values among values x1, x2, ..., xn does not exceed 2.
1,700
In the first line print the minimum possible number of equal measurements. In the second line print n integers y1, y2, ..., yn β€” the values Anya should write. You can print the integers in arbitrary order. Keep in mind that the minimum value among Anya's values should be not less that the minimum among Kirill's values, and the maximum among Anya's values should be not greater than the maximum among Kirill's values. If there are multiple answers, print any of them.
standard output
PASSED
3b02c857da674b4b8d54f14835c9150a
train_000.jsonl
1520177700
Anya and Kirill are doing a physics laboratory work. In one of the tasks they have to measure some value n times, and then compute the average value to lower the error.Kirill has already made his measurements, and has got the following integer values: x1, x2, ..., xn. It is important that the values are close to each other, namely, the difference between the maximum value and the minimum value is at most 2.Anya does not want to make the measurements, however, she can't just copy the values from Kirill's work, because the error of each measurement is a random value, and this coincidence will be noted by the teacher. Anya wants to write such integer values y1, y2, ..., yn in her work, that the following conditions are met: the average value of x1, x2, ..., xn is equal to the average value of y1, y2, ..., yn; all Anya's measurements are in the same bounds as all Kirill's measurements, that is, the maximum value among Anya's values is not greater than the maximum value among Kirill's values, and the minimum value among Anya's values is not less than the minimum value among Kirill's values; the number of equal measurements in Anya's work and Kirill's work is as small as possible among options with the previous conditions met. Formally, the teacher goes through all Anya's values one by one, if there is equal value in Kirill's work and it is not strike off yet, he strikes off this Anya's value and one of equal values in Kirill's work. The number of equal measurements is then the total number of strike off values in Anya's work. Help Anya to write such a set of measurements that the conditions above are met.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; /** * @author Don Li */ public class LaboratoryWork { void solve() { int n = in.nextInt(); int[] x = new int[n]; for (int i = 0; i < n; i++) x[i] = in.nextInt(); int mi = x[0], ma = x[0]; for (int i = 1; i < n; i++) { mi = Math.min(mi, x[i]); ma = Math.max(ma, x[i]); } if (ma - mi < 2) { out.println(n); for (int i = 0; i < n; i++) { if (i > 0) out.print(' '); out.print(x[i]); } return; } int m = mi + 1; int a = 0, b = 0, c = 0; long sum = 0; for (int i = 0; i < n; i++) { if (x[i] == mi) a++; else if (x[i] == m) b++; else c++; sum += x[i]; } long best = n, na = a, nb = b, nc = c; for (int bb = 0; bb <= n; bb++) { long t = (sum - (long) n * m) + (n - bb); if (t % 2 != 0) continue; long cc = t / 2; if (cc >= 0 && cc <= n - bb) { long aa = n - bb - cc; long score = Math.min(a, aa) + Math.min(b, bb) + Math.min(c, cc); if (score < best) { best = score; na = aa; nb = bb; nc = cc; } } } out.println(best); for (int i = 0; i < na; i++) out.print(mi + " "); for (int i = 0; i < nb; i++) out.print(m + " "); for (int i = 0; i < nc; i++) out.print(ma + " "); } public static void main(String[] args) { in = new FastScanner(new BufferedReader(new InputStreamReader(System.in))); out = new PrintWriter(System.out); new LaboratoryWork().solve(); out.close(); } static FastScanner in; static PrintWriter out; static class FastScanner { BufferedReader in; StringTokenizer st; public FastScanner(BufferedReader in) { this.in = in; } public String nextToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(in.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(nextToken()); } public long nextLong() { return Long.parseLong(nextToken()); } public double nextDouble() { return Double.parseDouble(nextToken()); } } }
Java
["6\n-1 1 1 0 0 -1", "3\n100 100 101", "7\n-10 -9 -10 -8 -10 -9 -9"]
1 second
["2\n0 0 0 0 0 0", "3\n101 100 100", "5\n-10 -10 -9 -9 -9 -9 -9"]
NoteIn the first example Anya can write zeros as here measurements results. The average value is then equal to the average value of Kirill's values, and there are only two equal measurements.In the second example Anya should write two values 100 and one value 101 (in any order), because it is the only possibility to make the average be the equal to the average of Kirill's values. Thus, all three measurements are equal.In the third example the number of equal measurements is 5.
Java 8
standard input
[ "implementation", "math" ]
dbbea6784cafdd4244f56729996e9187
The first line contains a single integer n (1 ≀ n ≀ 100 000) β€” the numeber of measurements made by Kirill. The second line contains a sequence of integers x1, x2, ..., xn ( - 100 000 ≀ xi ≀ 100 000) β€” the measurements made by Kirill. It is guaranteed that the difference between the maximum and minimum values among values x1, x2, ..., xn does not exceed 2.
1,700
In the first line print the minimum possible number of equal measurements. In the second line print n integers y1, y2, ..., yn β€” the values Anya should write. You can print the integers in arbitrary order. Keep in mind that the minimum value among Anya's values should be not less that the minimum among Kirill's values, and the maximum among Anya's values should be not greater than the maximum among Kirill's values. If there are multiple answers, print any of them.
standard output
PASSED
4e04acc7f76c28a4919c84552c1317bf
train_000.jsonl
1520177700
Anya and Kirill are doing a physics laboratory work. In one of the tasks they have to measure some value n times, and then compute the average value to lower the error.Kirill has already made his measurements, and has got the following integer values: x1, x2, ..., xn. It is important that the values are close to each other, namely, the difference between the maximum value and the minimum value is at most 2.Anya does not want to make the measurements, however, she can't just copy the values from Kirill's work, because the error of each measurement is a random value, and this coincidence will be noted by the teacher. Anya wants to write such integer values y1, y2, ..., yn in her work, that the following conditions are met: the average value of x1, x2, ..., xn is equal to the average value of y1, y2, ..., yn; all Anya's measurements are in the same bounds as all Kirill's measurements, that is, the maximum value among Anya's values is not greater than the maximum value among Kirill's values, and the minimum value among Anya's values is not less than the minimum value among Kirill's values; the number of equal measurements in Anya's work and Kirill's work is as small as possible among options with the previous conditions met. Formally, the teacher goes through all Anya's values one by one, if there is equal value in Kirill's work and it is not strike off yet, he strikes off this Anya's value and one of equal values in Kirill's work. The number of equal measurements is then the total number of strike off values in Anya's work. Help Anya to write such a set of measurements that the conditions above are met.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Arrays; public class LaboratoryWork{ static int stoi(String s){return Integer.parseInt(s);} public static void main(String[] args) throws Exception{ BufferedReader r = new BufferedReader(new InputStreamReader(System.in)); int n = stoi(r.readLine()); String[] line1 = r.readLine().split(" "); int min = Integer.MAX_VALUE; int max = Integer.MIN_VALUE; int[] c = new int[3]; int[] arr = new int[n]; for(int i = 0; i < line1.length; i++){ arr[i] = stoi(line1[i]); min = Math.min(min, arr[i]); max = Math.max(max, arr[i]); } for(int i = 0; i < n; i++){ arr[i] -= min; c[arr[i]]++; } if(max - min == 0){ System.out.println(n); for(int i = 0; i < n; i++) System.out.print((arr[i] + min) + " "); System.out.println(); }else if(max - min == 1){ System.out.println(n); for(int i = 0; i < n; i++) System.out.print((arr[i] + min) + " "); System.out.println(); }else{ int[] c2 = c.clone(); int best = n; int[] cb = c.clone(); while(c2[0 + 1] >= 2){ c2[0 + 1] -= 2; c2[1 + 1]++; c2[-1 + 1]++; int temp = Math.min(c2[0], c[0]) + Math.min(c2[1], c[1]) + Math.min(c2[2], c[2]); if(temp < best){ best = temp; cb = c2.clone(); } } c2 = c.clone(); while(c2[-1 + 1] >= 1 && c2[1 + 1] >= 1){ c2[0 + 1] += 2; c2[1 + 1]--; c2[-1 + 1]--; //System.out.println(Arrays.toString(c2)); int temp = Math.min(c2[0], c[0]) + Math.min(c2[1], c[1]) + Math.min(c2[2], c[2]); if(temp < best){ best = temp; cb = c2.clone(); } } //System.out.println(Arrays.toString(cb)); System.out.println(best); for(int i = 0; i < 3; i++){ for(int j = 0; j < cb[i]; j++){ System.out.print((i + min) + " "); } } System.out.println(); } r.close(); } }
Java
["6\n-1 1 1 0 0 -1", "3\n100 100 101", "7\n-10 -9 -10 -8 -10 -9 -9"]
1 second
["2\n0 0 0 0 0 0", "3\n101 100 100", "5\n-10 -10 -9 -9 -9 -9 -9"]
NoteIn the first example Anya can write zeros as here measurements results. The average value is then equal to the average value of Kirill's values, and there are only two equal measurements.In the second example Anya should write two values 100 and one value 101 (in any order), because it is the only possibility to make the average be the equal to the average of Kirill's values. Thus, all three measurements are equal.In the third example the number of equal measurements is 5.
Java 8
standard input
[ "implementation", "math" ]
dbbea6784cafdd4244f56729996e9187
The first line contains a single integer n (1 ≀ n ≀ 100 000) β€” the numeber of measurements made by Kirill. The second line contains a sequence of integers x1, x2, ..., xn ( - 100 000 ≀ xi ≀ 100 000) β€” the measurements made by Kirill. It is guaranteed that the difference between the maximum and minimum values among values x1, x2, ..., xn does not exceed 2.
1,700
In the first line print the minimum possible number of equal measurements. In the second line print n integers y1, y2, ..., yn β€” the values Anya should write. You can print the integers in arbitrary order. Keep in mind that the minimum value among Anya's values should be not less that the minimum among Kirill's values, and the maximum among Anya's values should be not greater than the maximum among Kirill's values. If there are multiple answers, print any of them.
standard output
PASSED
df00916ecb282cad32a26c4234a03167
train_000.jsonl
1520177700
Anya and Kirill are doing a physics laboratory work. In one of the tasks they have to measure some value n times, and then compute the average value to lower the error.Kirill has already made his measurements, and has got the following integer values: x1, x2, ..., xn. It is important that the values are close to each other, namely, the difference between the maximum value and the minimum value is at most 2.Anya does not want to make the measurements, however, she can't just copy the values from Kirill's work, because the error of each measurement is a random value, and this coincidence will be noted by the teacher. Anya wants to write such integer values y1, y2, ..., yn in her work, that the following conditions are met: the average value of x1, x2, ..., xn is equal to the average value of y1, y2, ..., yn; all Anya's measurements are in the same bounds as all Kirill's measurements, that is, the maximum value among Anya's values is not greater than the maximum value among Kirill's values, and the minimum value among Anya's values is not less than the minimum value among Kirill's values; the number of equal measurements in Anya's work and Kirill's work is as small as possible among options with the previous conditions met. Formally, the teacher goes through all Anya's values one by one, if there is equal value in Kirill's work and it is not strike off yet, he strikes off this Anya's value and one of equal values in Kirill's work. The number of equal measurements is then the total number of strike off values in Anya's work. Help Anya to write such a set of measurements that the conditions above are met.
256 megabytes
import java.io.*; import java.util.*; public class Main { static int N; static int[] X; public static void main(String[] args) { FastScanner sc = new FastScanner(System.in); N = sc.nextInt(); X = sc.nextIntArray(N); Answer answer = solve(); System.out.println( answer.n ); writeSingleLine(answer.y); } static Answer solve() { int min = Integer.MAX_VALUE; int max = Integer.MIN_VALUE; Map<Integer, Integer> cnt = new HashMap<>(); for (int i = 0; i < N; i++) { int x = X[i]; cnt.put(x, cnt.getOrDefault(x, 0) + 1); max = Math.max(x, max); min = Math.min(x, min); } if( max - min < 2 ) { return new Answer(N, X); } int mid = (min+max)/2; int a = cnt.get(min); int b = cnt.getOrDefault(mid, 0); int c = cnt.get(max); int mini = -Math.min(a, c); int maxi = b/2; int maxd = -1; int maxdi = Integer.MIN_VALUE; for (int i = mini; i <= maxi; i++) { int a_ = a + i; int b_ = b - i*2; int c_ = c + i; int d = N - (Math.min(a, a_) + Math.min(b, b_) + Math.min(c, c_)); if( maxd < d ) { maxd = d; maxdi = i; } } int a_ = a + maxdi; int b_ = b - maxdi*2; int c_ = c + maxdi; int[] y = new int[N]; for (int i = 0; i < N; i++) { if( i < a_ ) { y[i] = min; } else if( i < a_ + b_ ) { y[i] = mid; } else { y[i] = max; } } return new Answer(N-maxd, y); } private static class Answer { int n; int[] y; public Answer(int n, int[] y) { this.n = n; this.y = y; } } @SuppressWarnings("unused") static class FastScanner { private BufferedReader reader; private StringTokenizer tokenizer; FastScanner(InputStream in) { reader = new BufferedReader(new InputStreamReader(in)); tokenizer = null; } String next() { if (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } String nextLine() { if (tokenizer == null || !tokenizer.hasMoreTokens()) { try { return reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken("\n"); } long nextLong() { return Long.parseLong(next()); } int nextInt() { return Integer.parseInt(next()); } int[] nextIntArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } int[] nextIntArray(int n, int delta) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt() + delta; return a; } long[] nextLongArray(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } } static void writeLines(int[] as) { PrintWriter pw = new PrintWriter(System.out); for (int a : as) pw.println(a); pw.flush(); } static void writeLines(long[] as) { PrintWriter pw = new PrintWriter(System.out); for (long a : as) pw.println(a); pw.flush(); } static void writeSingleLine(int[] as) { PrintWriter pw = new PrintWriter(System.out); for (int i = 0; i < as.length; i++) { if (i != 0) pw.print(" "); pw.print(as[i]); } pw.println(); pw.flush(); } static int max(int... as) { int max = Integer.MIN_VALUE; for (int a : as) max = Math.max(a, max); return max; } static int min(int... as) { int min = Integer.MAX_VALUE; for (int a : as) min = Math.min(a, min); return min; } static void debug(Object... args) { StringJoiner j = new StringJoiner(" "); for (Object arg : args) { if (arg instanceof int[]) j.add(Arrays.toString((int[]) arg)); else if (arg instanceof long[]) j.add(Arrays.toString((long[]) arg)); else if (arg instanceof double[]) j.add(Arrays.toString((double[]) arg)); else if (arg instanceof Object[]) j.add(Arrays.toString((Object[]) arg)); else j.add(arg == null ? "null" : arg.toString()); } System.err.println(j.toString()); } static void printSingleLine(int[] array) { for (int i = 0; i < array.length; i++) { if (i != 0) System.out.print(" "); System.out.print(array[i]); } System.out.println(); } static int lowerBound(int[] array, int value) { int low = 0, high = array.length, mid; while (low < high) { mid = ((high - low) >>> 1) + low; if (array[mid] < value) low = mid + 1; else high = mid; } return low; } static int upperBound(int[] array, int value) { int low = 0, high = array.length, mid; while (low < high) { mid = ((high - low) >>> 1) + low; if (array[mid] <= value) low = mid + 1; else high = mid; } return low; } }
Java
["6\n-1 1 1 0 0 -1", "3\n100 100 101", "7\n-10 -9 -10 -8 -10 -9 -9"]
1 second
["2\n0 0 0 0 0 0", "3\n101 100 100", "5\n-10 -10 -9 -9 -9 -9 -9"]
NoteIn the first example Anya can write zeros as here measurements results. The average value is then equal to the average value of Kirill's values, and there are only two equal measurements.In the second example Anya should write two values 100 and one value 101 (in any order), because it is the only possibility to make the average be the equal to the average of Kirill's values. Thus, all three measurements are equal.In the third example the number of equal measurements is 5.
Java 8
standard input
[ "implementation", "math" ]
dbbea6784cafdd4244f56729996e9187
The first line contains a single integer n (1 ≀ n ≀ 100 000) β€” the numeber of measurements made by Kirill. The second line contains a sequence of integers x1, x2, ..., xn ( - 100 000 ≀ xi ≀ 100 000) β€” the measurements made by Kirill. It is guaranteed that the difference between the maximum and minimum values among values x1, x2, ..., xn does not exceed 2.
1,700
In the first line print the minimum possible number of equal measurements. In the second line print n integers y1, y2, ..., yn β€” the values Anya should write. You can print the integers in arbitrary order. Keep in mind that the minimum value among Anya's values should be not less that the minimum among Kirill's values, and the maximum among Anya's values should be not greater than the maximum among Kirill's values. If there are multiple answers, print any of them.
standard output
PASSED
b8cb0e9a836bc8969f4ced1f4744f359
train_000.jsonl
1520177700
Anya and Kirill are doing a physics laboratory work. In one of the tasks they have to measure some value n times, and then compute the average value to lower the error.Kirill has already made his measurements, and has got the following integer values: x1, x2, ..., xn. It is important that the values are close to each other, namely, the difference between the maximum value and the minimum value is at most 2.Anya does not want to make the measurements, however, she can't just copy the values from Kirill's work, because the error of each measurement is a random value, and this coincidence will be noted by the teacher. Anya wants to write such integer values y1, y2, ..., yn in her work, that the following conditions are met: the average value of x1, x2, ..., xn is equal to the average value of y1, y2, ..., yn; all Anya's measurements are in the same bounds as all Kirill's measurements, that is, the maximum value among Anya's values is not greater than the maximum value among Kirill's values, and the minimum value among Anya's values is not less than the minimum value among Kirill's values; the number of equal measurements in Anya's work and Kirill's work is as small as possible among options with the previous conditions met. Formally, the teacher goes through all Anya's values one by one, if there is equal value in Kirill's work and it is not strike off yet, he strikes off this Anya's value and one of equal values in Kirill's work. The number of equal measurements is then the total number of strike off values in Anya's work. Help Anya to write such a set of measurements that the conditions above are met.
256 megabytes
import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; /** * Created by vlad on 08.11.15. */ public class problemC { public void solve(Scanner in, PrintWriter out) { int n = in.nextInt(); Map<Integer, Integer> map = new HashMap<>(); for (int i = 0; i < n; i++) { int t = in.nextInt(); map.put(t, map.getOrDefault(t, 0) + 1); } int min = Integer.MAX_VALUE; int max = Integer.MIN_VALUE; for (Integer value : map.keySet()) { min = Math.min(value, min); max = Math.max(value, max); } if (map.keySet().size() == 1 || map.keySet().size() == 2 && max - min != 2) { out.println(n); for (Integer value : map.keySet()) { for (int i = 0; i < map.get(value); i++) { out.print(value + " "); } } } else { int mid = (max + min) / 2; int midCount = 0; int minCount = Integer.MAX_VALUE; for (Integer i : map.keySet()) { if (i == mid) { midCount = map.get(i); } else { minCount = Math.min(map.get(i), minCount); } } int ans1 = n - midCount + midCount % 2; int ans2 = n - minCount * 2; if (ans1 <= ans2) { out.println(ans1); for (Integer value : map.keySet()) { if (value == mid && midCount % 2 == 0) { continue; } if (value == mid) { out.print(mid + " "); continue; } for (int i = 0; i < map.get(value) + midCount / 2; i++) { out.print(value + " "); } } } else { out.println(ans2); for (int i = 0; i < map.get(min) - minCount; i++) { out.print(min + " "); } for (int i = 0; i < map.getOrDefault(mid, 0) + 2 * minCount; i++) { out.print(mid + " "); } for (int i = 0; i < map.get(max) - minCount; i++) { out.print(max + " "); } // for (Integer value : map.keySet()) { // int to = 0; // if (value == mid) { // to = map.get(value) + 2 * minCount; // } else { // to = map.get(value) - minCount; // } // for (int i = 0; i < to; i++) { // out.print(value + " "); // } // } } } } public static void main(String args[]) { Scanner in = new Scanner(new BufferedReader(new InputStreamReader(System.in))); PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); new problemC().solve(in, out); in.close(); out.close(); } }
Java
["6\n-1 1 1 0 0 -1", "3\n100 100 101", "7\n-10 -9 -10 -8 -10 -9 -9"]
1 second
["2\n0 0 0 0 0 0", "3\n101 100 100", "5\n-10 -10 -9 -9 -9 -9 -9"]
NoteIn the first example Anya can write zeros as here measurements results. The average value is then equal to the average value of Kirill's values, and there are only two equal measurements.In the second example Anya should write two values 100 and one value 101 (in any order), because it is the only possibility to make the average be the equal to the average of Kirill's values. Thus, all three measurements are equal.In the third example the number of equal measurements is 5.
Java 8
standard input
[ "implementation", "math" ]
dbbea6784cafdd4244f56729996e9187
The first line contains a single integer n (1 ≀ n ≀ 100 000) β€” the numeber of measurements made by Kirill. The second line contains a sequence of integers x1, x2, ..., xn ( - 100 000 ≀ xi ≀ 100 000) β€” the measurements made by Kirill. It is guaranteed that the difference between the maximum and minimum values among values x1, x2, ..., xn does not exceed 2.
1,700
In the first line print the minimum possible number of equal measurements. In the second line print n integers y1, y2, ..., yn β€” the values Anya should write. You can print the integers in arbitrary order. Keep in mind that the minimum value among Anya's values should be not less that the minimum among Kirill's values, and the maximum among Anya's values should be not greater than the maximum among Kirill's values. If there are multiple answers, print any of them.
standard output
PASSED
2bbc9d11798d40e8b45f677eb0ab3aa1
train_000.jsonl
1520177700
Anya and Kirill are doing a physics laboratory work. In one of the tasks they have to measure some value n times, and then compute the average value to lower the error.Kirill has already made his measurements, and has got the following integer values: x1, x2, ..., xn. It is important that the values are close to each other, namely, the difference between the maximum value and the minimum value is at most 2.Anya does not want to make the measurements, however, she can't just copy the values from Kirill's work, because the error of each measurement is a random value, and this coincidence will be noted by the teacher. Anya wants to write such integer values y1, y2, ..., yn in her work, that the following conditions are met: the average value of x1, x2, ..., xn is equal to the average value of y1, y2, ..., yn; all Anya's measurements are in the same bounds as all Kirill's measurements, that is, the maximum value among Anya's values is not greater than the maximum value among Kirill's values, and the minimum value among Anya's values is not less than the minimum value among Kirill's values; the number of equal measurements in Anya's work and Kirill's work is as small as possible among options with the previous conditions met. Formally, the teacher goes through all Anya's values one by one, if there is equal value in Kirill's work and it is not strike off yet, he strikes off this Anya's value and one of equal values in Kirill's work. The number of equal measurements is then the total number of strike off values in Anya's work. Help Anya to write such a set of measurements that the conditions above are met.
256 megabytes
import java.io.*; import java.util.*; public class CF931_D2_C{ public static void main(String[] args)throws Throwable { MyScanner sc=new MyScanner(); PrintWriter pw=new PrintWriter(System.out); int n=sc.nextInt(); long sum=0; int [] arr=new int [n]; TreeMap<Integer, Integer> map=new TreeMap<Integer, Integer>(); for(int i=0;i<n;i++){ arr[i]=sc.nextInt(); sum+=arr[i]; map.put(arr[i], map.getOrDefault(arr[i], 0)+1); } int [] x=new int [3]; int [] y=new int [3]; int p=0; for(java.util.Map.Entry<Integer, Integer> e : map.entrySet() ){ if(p>0 && e.getKey()!=x[p-1]+1) p++; x[p]=e.getKey(); y[p++]=e.getValue(); } x[1]=x[0]+1; x[2]=x[1]+1; long mn=n+1,bst=0; for(int i=0;i<=n;i++){ int m=n-i; long cnt=Math.min(y[0], i); long c=sum-1L*x[0]*i; long b=c-1L*m*x[1]; long a=m-b; if(b<0 || b>m || a<0 || a>m) continue; if(b>0 && y[2]==0) continue; if(i+b+a!=n) continue; if(sum!=1L*i*x[0]+1L*a*x[1]+1L*b*x[2]) continue; cnt+=Math.min(b, y[2]); cnt+=Math.min(a, y[1]); if(cnt<mn){ mn=cnt; bst=i; } } pw.println(mn); long m=n-bst; long c=sum-1L*x[0]*bst; long b=c-1L*m*x[1]; long a=m-b; for(int i=0;i<bst;i++) pw.print(x[0]+" "); for(int i=0;i<a;i++) pw.print(x[1]+" "); for(int i=0;i<b;i++) pw.print(x[2]+" "); pw.flush(); pw.close(); } 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
["6\n-1 1 1 0 0 -1", "3\n100 100 101", "7\n-10 -9 -10 -8 -10 -9 -9"]
1 second
["2\n0 0 0 0 0 0", "3\n101 100 100", "5\n-10 -10 -9 -9 -9 -9 -9"]
NoteIn the first example Anya can write zeros as here measurements results. The average value is then equal to the average value of Kirill's values, and there are only two equal measurements.In the second example Anya should write two values 100 and one value 101 (in any order), because it is the only possibility to make the average be the equal to the average of Kirill's values. Thus, all three measurements are equal.In the third example the number of equal measurements is 5.
Java 8
standard input
[ "implementation", "math" ]
dbbea6784cafdd4244f56729996e9187
The first line contains a single integer n (1 ≀ n ≀ 100 000) β€” the numeber of measurements made by Kirill. The second line contains a sequence of integers x1, x2, ..., xn ( - 100 000 ≀ xi ≀ 100 000) β€” the measurements made by Kirill. It is guaranteed that the difference between the maximum and minimum values among values x1, x2, ..., xn does not exceed 2.
1,700
In the first line print the minimum possible number of equal measurements. In the second line print n integers y1, y2, ..., yn β€” the values Anya should write. You can print the integers in arbitrary order. Keep in mind that the minimum value among Anya's values should be not less that the minimum among Kirill's values, and the maximum among Anya's values should be not greater than the maximum among Kirill's values. If there are multiple answers, print any of them.
standard output
PASSED
9f55ce8de23c8924b0bf20952b9e913c
train_000.jsonl
1520177700
Anya and Kirill are doing a physics laboratory work. In one of the tasks they have to measure some value n times, and then compute the average value to lower the error.Kirill has already made his measurements, and has got the following integer values: x1, x2, ..., xn. It is important that the values are close to each other, namely, the difference between the maximum value and the minimum value is at most 2.Anya does not want to make the measurements, however, she can't just copy the values from Kirill's work, because the error of each measurement is a random value, and this coincidence will be noted by the teacher. Anya wants to write such integer values y1, y2, ..., yn in her work, that the following conditions are met: the average value of x1, x2, ..., xn is equal to the average value of y1, y2, ..., yn; all Anya's measurements are in the same bounds as all Kirill's measurements, that is, the maximum value among Anya's values is not greater than the maximum value among Kirill's values, and the minimum value among Anya's values is not less than the minimum value among Kirill's values; the number of equal measurements in Anya's work and Kirill's work is as small as possible among options with the previous conditions met. Formally, the teacher goes through all Anya's values one by one, if there is equal value in Kirill's work and it is not strike off yet, he strikes off this Anya's value and one of equal values in Kirill's work. The number of equal measurements is then the total number of strike off values in Anya's work. Help Anya to write such a set of measurements that the conditions above are met.
256 megabytes
import java.util.*; import java.io.*; public class C931 { public static void main(String[] args) throws Exception { int n = Integer.parseInt(in.readLine()); TreeMap<Integer, Integer> map = new TreeMap<Integer, Integer>(); st = new StringTokenizer(in.readLine()); for (int i = 0; i < n; i++) { int j = i(); if (!map.containsKey(j)) map.put(j, 0); map.put(j, map.get(j) + 1); } if (map.lastKey() - map.firstKey() == 2) { int low = map.firstKey(); int high = map.lastKey(); int mid = low + high >> 1; if (!map.containsKey(mid)) map.put(mid, 0); if (map.get(mid) / 2 >= Math.min(map.get(low), map.get(high))) { n -= map.get(mid) / 2 * 2; map.put(low, map.get(low) + map.get(mid) / 2); map.put(high, map.get(high) + map.get(mid) / 2); map.put(mid, map.get(mid) - map.get(mid) / 2 * 2); } else { int min = Math.min(map.get(low), map.get(high)); n -= min * 2; map.put(mid, map.get(mid) + 2 * min); map.put(low, map.get(low) - min); map.put(high, map.get(high) - min); } } out.println(n); StringBuilder sb = new StringBuilder(); for (int key : map.keySet()) { for (int i = 0; i < map.get(key); i++) { sb.append(key); sb.append(" "); } } sb.deleteCharAt(sb.length() - 1); out.println(sb.toString()); out.close(); } 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
["6\n-1 1 1 0 0 -1", "3\n100 100 101", "7\n-10 -9 -10 -8 -10 -9 -9"]
1 second
["2\n0 0 0 0 0 0", "3\n101 100 100", "5\n-10 -10 -9 -9 -9 -9 -9"]
NoteIn the first example Anya can write zeros as here measurements results. The average value is then equal to the average value of Kirill's values, and there are only two equal measurements.In the second example Anya should write two values 100 and one value 101 (in any order), because it is the only possibility to make the average be the equal to the average of Kirill's values. Thus, all three measurements are equal.In the third example the number of equal measurements is 5.
Java 8
standard input
[ "implementation", "math" ]
dbbea6784cafdd4244f56729996e9187
The first line contains a single integer n (1 ≀ n ≀ 100 000) β€” the numeber of measurements made by Kirill. The second line contains a sequence of integers x1, x2, ..., xn ( - 100 000 ≀ xi ≀ 100 000) β€” the measurements made by Kirill. It is guaranteed that the difference between the maximum and minimum values among values x1, x2, ..., xn does not exceed 2.
1,700
In the first line print the minimum possible number of equal measurements. In the second line print n integers y1, y2, ..., yn β€” the values Anya should write. You can print the integers in arbitrary order. Keep in mind that the minimum value among Anya's values should be not less that the minimum among Kirill's values, and the maximum among Anya's values should be not greater than the maximum among Kirill's values. If there are multiple answers, print any of them.
standard output
PASSED
93db2e1c4b014a8c6c1e54b3273cb3da
train_000.jsonl
1520177700
Anya and Kirill are doing a physics laboratory work. In one of the tasks they have to measure some value n times, and then compute the average value to lower the error.Kirill has already made his measurements, and has got the following integer values: x1, x2, ..., xn. It is important that the values are close to each other, namely, the difference between the maximum value and the minimum value is at most 2.Anya does not want to make the measurements, however, she can't just copy the values from Kirill's work, because the error of each measurement is a random value, and this coincidence will be noted by the teacher. Anya wants to write such integer values y1, y2, ..., yn in her work, that the following conditions are met: the average value of x1, x2, ..., xn is equal to the average value of y1, y2, ..., yn; all Anya's measurements are in the same bounds as all Kirill's measurements, that is, the maximum value among Anya's values is not greater than the maximum value among Kirill's values, and the minimum value among Anya's values is not less than the minimum value among Kirill's values; the number of equal measurements in Anya's work and Kirill's work is as small as possible among options with the previous conditions met. Formally, the teacher goes through all Anya's values one by one, if there is equal value in Kirill's work and it is not strike off yet, he strikes off this Anya's value and one of equal values in Kirill's work. The number of equal measurements is then the total number of strike off values in Anya's work. Help Anya to write such a set of measurements that the conditions above are met.
256 megabytes
import java.util.*; import java.text.*; import java.io.*; import java.math.*; public class code5 { InputStream is; PrintWriter out; static long mod=pow(10,9)+7; static int dx[]={0,0,1,-1},dy[]={1,-1,0,0}; ArrayList<Integer> al[]; void solve() throws IOException { int n=ni(); int a[]=na(n); Arrays.sort(a); TreeMap<Integer,Integer> ts=new TreeMap<Integer,Integer>(); for(int i=0;i<n;i++) { if(ts.containsKey(a[i])) ts.put(a[i],ts.get(a[i])+1); else ts.put(a[i],1); } if(ts.size()==1||(ts.size()==2&&ts.lastKey()-ts.firstKey()==1)) { out.println(n); for(int i:a) out.print(i+" "); } else if(ts.size()==2) { Integer fk=ts.firstKey(); Integer f=ts.pollFirstEntry().getValue(); Integer sk=ts.firstKey(); Integer s=ts.pollFirstEntry().getValue(); int mid=Math.min(f,s); out.println(f+s-2*mid); for(int i=1;i<=f-mid;i++) out.print(fk+" "); for(int i=1;i<=s-mid;i++) out.print(sk+" "); for(int i=1;i<=2*mid;i++) out.print((fk+1)+" "); } else { Integer fk=ts.firstKey(); Integer f=ts.pollFirstEntry().getValue(); Integer sk=ts.firstKey(); Integer s=ts.pollFirstEntry().getValue(); Integer tk=ts.firstKey(); Integer t=ts.pollFirstEntry().getValue(); int mid=Math.min(f,t); int t1=s+t-mid+f-mid; int t2=s%2+f+t; if(t1<=t2) { out.println(t1); for(int i=1;i<=s+2*mid;i++) out.print(sk+" "); for(int i=1;i<=f-mid;i++) out.print(fk+" "); for(int i=1;i<=t-mid;i++) out.print(tk+" "); } else { out.println(t2); for(int i=1;i<=s%2;i++) out.print(sk+" "); for(int i=1;i<=f+s/2;i++) out.print(fk+" "); for(int i=1;i<=t+s/2;i++) out.print(tk+" "); } } } long ncr[][]; 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; } } int sum(int i) { int sum=0; while(i!=0) { if((i%10)%2==1) sum+=i%10; i/=10; } return 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 check(long n) { int count=0; while(n!=0) { if(n%10!=0) break; n/=10; count++; } return count; } 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>{ int x,y,k; int i,dir; long val; double pos; Pair (int x,int y){ this.x=x; this.y=y; } public int compareTo(Pair o) { return Double.compare(this.pos,o.pos); } public String toString(){ return x+" "+y+" "+k+" "+i+" "+val;} 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() ; } } 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(y==0) return x; 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(); //new code5().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 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
["6\n-1 1 1 0 0 -1", "3\n100 100 101", "7\n-10 -9 -10 -8 -10 -9 -9"]
1 second
["2\n0 0 0 0 0 0", "3\n101 100 100", "5\n-10 -10 -9 -9 -9 -9 -9"]
NoteIn the first example Anya can write zeros as here measurements results. The average value is then equal to the average value of Kirill's values, and there are only two equal measurements.In the second example Anya should write two values 100 and one value 101 (in any order), because it is the only possibility to make the average be the equal to the average of Kirill's values. Thus, all three measurements are equal.In the third example the number of equal measurements is 5.
Java 8
standard input
[ "implementation", "math" ]
dbbea6784cafdd4244f56729996e9187
The first line contains a single integer n (1 ≀ n ≀ 100 000) β€” the numeber of measurements made by Kirill. The second line contains a sequence of integers x1, x2, ..., xn ( - 100 000 ≀ xi ≀ 100 000) β€” the measurements made by Kirill. It is guaranteed that the difference between the maximum and minimum values among values x1, x2, ..., xn does not exceed 2.
1,700
In the first line print the minimum possible number of equal measurements. In the second line print n integers y1, y2, ..., yn β€” the values Anya should write. You can print the integers in arbitrary order. Keep in mind that the minimum value among Anya's values should be not less that the minimum among Kirill's values, and the maximum among Anya's values should be not greater than the maximum among Kirill's values. If there are multiple answers, print any of them.
standard output
PASSED
926b8b5790bc5caa41759c87cde50be0
train_000.jsonl
1520177700
Anya and Kirill are doing a physics laboratory work. In one of the tasks they have to measure some value n times, and then compute the average value to lower the error.Kirill has already made his measurements, and has got the following integer values: x1, x2, ..., xn. It is important that the values are close to each other, namely, the difference between the maximum value and the minimum value is at most 2.Anya does not want to make the measurements, however, she can't just copy the values from Kirill's work, because the error of each measurement is a random value, and this coincidence will be noted by the teacher. Anya wants to write such integer values y1, y2, ..., yn in her work, that the following conditions are met: the average value of x1, x2, ..., xn is equal to the average value of y1, y2, ..., yn; all Anya's measurements are in the same bounds as all Kirill's measurements, that is, the maximum value among Anya's values is not greater than the maximum value among Kirill's values, and the minimum value among Anya's values is not less than the minimum value among Kirill's values; the number of equal measurements in Anya's work and Kirill's work is as small as possible among options with the previous conditions met. Formally, the teacher goes through all Anya's values one by one, if there is equal value in Kirill's work and it is not strike off yet, he strikes off this Anya's value and one of equal values in Kirill's work. The number of equal measurements is then the total number of strike off values in Anya's work. Help Anya to write such a set of measurements that the conditions above are met.
256 megabytes
import java.util.*; import java.io.*; public class cfr468c { public static void main(String[] args) { Scanner kb=new Scanner(System.in); int n=kb.nextInt(); int[] a=new int[n]; TreeMap<Integer,Integer> tm=new TreeMap<Integer,Integer>(); for(int i=0;i<n;i++){ a[i]=kb.nextInt(); if(!tm.containsKey(a[i])){ tm.put(a[i],1); } else{ tm.put(a[i], tm.get(a[i])+1); } } if(tm.size()==2){ int x=tm.ceilingKey(Integer.MIN_VALUE); int y=tm.floorKey(Integer.MAX_VALUE); if(x-y!=1&&x-y!=-1){ int numx=Math.min(tm.get(x),tm.get(y)); int numy=numx; for(int i=0;i<n;i++){ if(a[i]==x&&numx>0){ a[i]=a[i]+1; numx--; } if(a[i]==y&&numy>0){ a[i]=a[i]-1; numy--; } } } } else if(tm.size()==3){ int x=tm.ceilingKey(Integer.MIN_VALUE); int y=tm.floorKey(Integer.MAX_VALUE); int z=x+1; if(2*Math.min(tm.get(x),tm.get(y))>tm.get(z)){ int numx=Math.min(tm.get(x),tm.get(y)); int numy=numx; for(int i=0;i<n;i++){ if(a[i]==x&&numx>0){ a[i]=a[i]+1; numx--; } if(a[i]==y&&numy>0){ a[i]=a[i]-1; numy--; } } } else{ int last=-1; for(int i=0;i<n;i++){ if(a[i]==z){ if(last==-1){ last=i; } else{ a[last]=a[last]-1; a[i]=a[i]+1; last=-1; } } } } } print(a,tm); } private static void print(int[] a,TreeMap<Integer,Integer> tm) { int count=0; for(int q:tm.keySet()){ int c2=0; for(int i=0;i<a.length;i++){ if(a[i]==q){ c2++; } } count+=Math.min(c2, tm.get(q)); } System.out.println(count); for(int i=0;i<a.length-1;i++){ System.out.print(a[i]+" "); } System.out.println(a[a.length-1]); } }
Java
["6\n-1 1 1 0 0 -1", "3\n100 100 101", "7\n-10 -9 -10 -8 -10 -9 -9"]
1 second
["2\n0 0 0 0 0 0", "3\n101 100 100", "5\n-10 -10 -9 -9 -9 -9 -9"]
NoteIn the first example Anya can write zeros as here measurements results. The average value is then equal to the average value of Kirill's values, and there are only two equal measurements.In the second example Anya should write two values 100 and one value 101 (in any order), because it is the only possibility to make the average be the equal to the average of Kirill's values. Thus, all three measurements are equal.In the third example the number of equal measurements is 5.
Java 8
standard input
[ "implementation", "math" ]
dbbea6784cafdd4244f56729996e9187
The first line contains a single integer n (1 ≀ n ≀ 100 000) β€” the numeber of measurements made by Kirill. The second line contains a sequence of integers x1, x2, ..., xn ( - 100 000 ≀ xi ≀ 100 000) β€” the measurements made by Kirill. It is guaranteed that the difference between the maximum and minimum values among values x1, x2, ..., xn does not exceed 2.
1,700
In the first line print the minimum possible number of equal measurements. In the second line print n integers y1, y2, ..., yn β€” the values Anya should write. You can print the integers in arbitrary order. Keep in mind that the minimum value among Anya's values should be not less that the minimum among Kirill's values, and the maximum among Anya's values should be not greater than the maximum among Kirill's values. If there are multiple answers, print any of them.
standard output
PASSED
100fbbb306ecb3efde4220b8f2c42bd2
train_000.jsonl
1544884500
You are given an undirected unweighted graph consisting of $$$n$$$ vertices and $$$m$$$ edges.You have to write a number on each vertex of the graph. Each number should be $$$1$$$, $$$2$$$ or $$$3$$$. The graph becomes beautiful if for each edge the sum of numbers on vertices connected by this edge is odd.Calculate the number of possible ways to write numbers $$$1$$$, $$$2$$$ and $$$3$$$ on vertices so the graph becomes beautiful. Since this number may be large, print it modulo $$$998244353$$$.Note that you have to write exactly one number on each vertex.The graph does not have any self-loops or multiple edges.
256 megabytes
import java.io.*; import java.util.*; public class Main { static List<Integer> g[];static int vis[]; static int col[]; static int par[]; static long k=998244353; static boolean at[]; static int low[];static int disc[]; static int t=0; static int n1=0,n2=0; public static void main(String[] args)throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); int t=Integer.parseInt(br.readLine()); while(t-->0) { StringTokenizer tk = new StringTokenizer(br.readLine()); int n=Integer.parseInt(tk.nextToken()); int m=Integer.parseInt(tk.nextToken()); g=new ArrayList[n+1]; vis=new int[n+1]; par=new int[n+1]; col=new int[n+1]; for(int i=1;i<=n;i++) { g[i]=new ArrayList<Integer>(); } for(int i=1;i<=m;i++) { tk = new StringTokenizer(br.readLine()); int u=Integer.parseInt(tk.nextToken()); int v=Integer.parseInt(tk.nextToken()); g[u].add(v); g[v].add(u); } boolean b=true; long res=1; for(int i=1;i<=n;i++) { if(vis[i]==0) { n1=0; n2=0; b=b&&dfs(i,0); if(b==false) break; long v1=modexp(2,n1,k); long v2=modexp(2,n2,k); res=(((v1+v2)%k)*res)%k; } } if(!b) { out.println(0); out.flush(); continue; } out.println(res); out.flush(); } } static boolean dfs(int u, int c) { vis[u]=1; col[u]=c; if(c==1) n1++; else n2++; for(int i=0;i<g[u].size();i++) { int v=g[u].get(i); if(vis[v]==0) { if(dfs(v,c^1)==false) return false; } else { if(col[u]==col[v]) return false; } } return true; } static long modexp(long a,long n, long p) { long res=1; while(n>0) { if(n%2==1) { res=((res%p)*(a%p))%p; n--; } a=(a*a)%p; n>>=1; } return res; } }
Java
["2\n2 1\n1 2\n4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4"]
2 seconds
["4\n0"]
NotePossible ways to distribute numbers in the first test: the vertex $$$1$$$ should contain $$$1$$$, and $$$2$$$ should contain $$$2$$$; the vertex $$$1$$$ should contain $$$3$$$, and $$$2$$$ should contain $$$2$$$; the vertex $$$1$$$ should contain $$$2$$$, and $$$2$$$ should contain $$$1$$$; the vertex $$$1$$$ should contain $$$2$$$, and $$$2$$$ should contain $$$3$$$. In the second test there is no way to distribute numbers.
Java 8
standard input
[ "dfs and similar", "graphs" ]
332340a793eb3ec14131948e2b6bdf2f
The first line contains one integer $$$t$$$ ($$$1 \le t \le 3 \cdot 10^5$$$) β€” the number of tests in the input. The first line of each test contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5, 0 \le m \le 3 \cdot 10^5$$$) β€” the number of vertices and the number of edges, respectively. Next $$$m$$$ lines describe edges: $$$i$$$-th line contains two integers $$$u_i$$$, $$$ v_i$$$ ($$$1 \le u_i, v_i \le n; u_i \neq v_i$$$) β€” indices of vertices connected by $$$i$$$-th edge. It is guaranteed that $$$\sum\limits_{i=1}^{t} n \le 3 \cdot 10^5$$$ and $$$\sum\limits_{i=1}^{t} m \le 3 \cdot 10^5$$$.
1,700
For each test print one line, containing one integer β€” the number of possible ways to write numbers $$$1$$$, $$$2$$$, $$$3$$$ on the vertices of given graph so it becomes beautiful. Since answers may be large, print them modulo $$$998244353$$$.
standard output
PASSED
096eee14930d7b61aa73fd72bb47b032
train_000.jsonl
1544884500
You are given an undirected unweighted graph consisting of $$$n$$$ vertices and $$$m$$$ edges.You have to write a number on each vertex of the graph. Each number should be $$$1$$$, $$$2$$$ or $$$3$$$. The graph becomes beautiful if for each edge the sum of numbers on vertices connected by this edge is odd.Calculate the number of possible ways to write numbers $$$1$$$, $$$2$$$ and $$$3$$$ on vertices so the graph becomes beautiful. Since this number may be large, print it modulo $$$998244353$$$.Note that you have to write exactly one number on each vertex.The graph does not have any self-loops or multiple edges.
256 megabytes
import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; @SuppressWarnings("unchecked") public class D1093 { final int mod = 998244353; int mult(long a, long b) { long ans = a * b % mod; return (int) ans; } int n, m; int[] whichLayer, pow; boolean[] visited, vis2; ArrayList<Integer>[] vs, layers; long go(int root) { for(int i = 0; i < n; ++i) { if(layers[i].isEmpty()) break; layers[i].clear(); } ArrayDeque<Integer> q = new ArrayDeque<>(); int totalLayers = 0; q.add(root); q.add(0); visited[root] = true; while(!q.isEmpty()) { int node = q.poll(); int layer = q.poll(); layers[layer].add(node); totalLayers = Math.max(totalLayers, layer); for(int v : vs[node]) { if(!visited[v]) { visited[v] = true; whichLayer[v] = layer + 1; q.add(v); q.add(layer + 1); } else { if(layer % 2 == whichLayer[v] % 2) { return 0; } } } } long oddFirst = 1, evenFirst = 1; for(int layer = 0; layer <= totalLayers; ++layer) { int size = layers[layer].size(); if(layer % 2 == 0) oddFirst = mult(oddFirst, pow[size]); else evenFirst = mult(evenFirst, pow[size]); } long ans = oddFirst + evenFirst; return ans % mod; } public void solve(JoltyScanner in, PrintWriter out) { int t = in.nextInt(); while(t-->0) { n = in.nextInt(); m = in.nextInt(); vs = new ArrayList[n]; layers = new ArrayList[n]; visited = new boolean[n]; vis2 = new boolean[n]; whichLayer = new int[n]; pow = new int[n + 1]; for(int i = 0; i < n; ++i) layers[i] = new ArrayList<>(); for(int i = 0; i < n; ++i) vs[i] = new ArrayList<>(); for(int i = 0; i < m; ++i) { int u = in.nextInt() - 1, v = in.nextInt() - 1; vs[u].add(v); vs[v].add(u); } pow[0] = 1; for(int i = 1; i <= n; ++i) pow[i] = mult(pow[i - 1], 2); long ans = 1; for(int root = 0; root < n; ++root) if(!visited[root]) { ans = mult(ans, go(root)); } out.println(ans); } } static class SuperBIT { long[] dataMul, dataAdd; SuperBIT(int n) { n += 10; dataMul = new long[n]; dataAdd = new long[n]; } void update(int left, int right, long val) { left += 5; right += 5; internalUpdate(left, val, -val * (left - 1)); internalUpdate(right, -val, val * right); } void internalUpdate(int at, long mul, long add) { while (at < dataMul.length) { dataMul[at] += mul; dataAdd[at] += add; at |= (at + 1); } } long query(int at) { long mul = 0; long add = 0; int start = at; while (at >= 0) { mul += dataMul[at]; add += dataAdd[at]; at = (at & (at + 1)) - 1; } return mul * start + add; } long query(int left, int right) { left += 5; right += 5; if (left > right) { int temp = left; left = right; right = temp; } return query(right) - query(left - 1); } } public static void main(String[] args) { JoltyScanner in = new JoltyScanner(); PrintWriter out = new PrintWriter(System.out); new D1093().solve(in, out); out.close(); } static class JoltyScanner { 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 JoltyScanner() { in = new BufferedInputStream(System.in, BS); } public JoltyScanner(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() { while(c!='.'&&c!='-'&&(c <'0' || c>'9')) c = nextChar(); boolean neg = c=='-'; if(neg)c=nextChar(); boolean fl = c=='.'; double cur = nextLong(); if(fl) return neg ? -cur/num : cur/num; if(c == '.') { double next = nextLong(); return neg ? -cur-next/num : cur+next/num; } else return neg ? -cur : cur; } 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; } } } }
Java
["2\n2 1\n1 2\n4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4"]
2 seconds
["4\n0"]
NotePossible ways to distribute numbers in the first test: the vertex $$$1$$$ should contain $$$1$$$, and $$$2$$$ should contain $$$2$$$; the vertex $$$1$$$ should contain $$$3$$$, and $$$2$$$ should contain $$$2$$$; the vertex $$$1$$$ should contain $$$2$$$, and $$$2$$$ should contain $$$1$$$; the vertex $$$1$$$ should contain $$$2$$$, and $$$2$$$ should contain $$$3$$$. In the second test there is no way to distribute numbers.
Java 8
standard input
[ "dfs and similar", "graphs" ]
332340a793eb3ec14131948e2b6bdf2f
The first line contains one integer $$$t$$$ ($$$1 \le t \le 3 \cdot 10^5$$$) β€” the number of tests in the input. The first line of each test contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5, 0 \le m \le 3 \cdot 10^5$$$) β€” the number of vertices and the number of edges, respectively. Next $$$m$$$ lines describe edges: $$$i$$$-th line contains two integers $$$u_i$$$, $$$ v_i$$$ ($$$1 \le u_i, v_i \le n; u_i \neq v_i$$$) β€” indices of vertices connected by $$$i$$$-th edge. It is guaranteed that $$$\sum\limits_{i=1}^{t} n \le 3 \cdot 10^5$$$ and $$$\sum\limits_{i=1}^{t} m \le 3 \cdot 10^5$$$.
1,700
For each test print one line, containing one integer β€” the number of possible ways to write numbers $$$1$$$, $$$2$$$, $$$3$$$ on the vertices of given graph so it becomes beautiful. Since answers may be large, print them modulo $$$998244353$$$.
standard output
PASSED
17efe198f15a9a9957ca62b93a0d2973
train_000.jsonl
1544884500
You are given an undirected unweighted graph consisting of $$$n$$$ vertices and $$$m$$$ edges.You have to write a number on each vertex of the graph. Each number should be $$$1$$$, $$$2$$$ or $$$3$$$. The graph becomes beautiful if for each edge the sum of numbers on vertices connected by this edge is odd.Calculate the number of possible ways to write numbers $$$1$$$, $$$2$$$ and $$$3$$$ on vertices so the graph becomes beautiful. Since this number may be large, print it modulo $$$998244353$$$.Note that you have to write exactly one number on each vertex.The graph does not have any self-loops or multiple edges.
256 megabytes
import java.util.*; public class Main { public static int mod = 998244353; public static class Node { public Node(int index) { this.index = index; } public List<Node> neighbors = new ArrayList<>(); public int index; } public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); String[] answer = new String[t]; for (int i = 0; i < t; i++) { answer[i] = Integer.toString(calculateAnswer(readGraph(sc))); } System.out.println(String.join("\n", answer)); } public static Node[] readGraph(Scanner sc) { int n = sc.nextInt(); int m = sc.nextInt(); Node[] graph = new Node[n]; for (int i = 0; i < n; i++) graph[i] = new Node(i); for (int i = 0; i < m; i++) { int index1 = sc.nextInt() - 1; int index2 = sc.nextInt() - 1; graph[index1].neighbors.add(graph[index2]); graph[index2].neighbors.add(graph[index1]); } return graph; } public static int calculateAnswer(Node[] graph) { List<Integer> depth = calculateCombDepth(graph); if (depth == null) return 0; long answer = 1; for (Integer d : depth) { answer = (answer * d) % mod; } return (int) answer; } public static int powMod(int d) { int answer = 1; for (int i = 0; i < d; i++) answer = (answer * 2) % mod; return answer; } public static int combinations(int a, int b) { return (powMod(a) + powMod(b)) % mod; } public static List<Integer> calculateCombDepth(Node[] graph) { boolean[] visited = new boolean[graph.length]; int[] visitedStep = new int[graph.length]; ArrayList<Integer> answer = new ArrayList<>(); for (int i = 0; i < graph.length; i++) { if (!visited[i]) { visited[i] = true; visitedStep[i] = 1; int d = depthFromNode(graph[i], visited, visitedStep); answer.add(d); if (d == -1) return null; } } return answer; } public static int depthFromNode(Node root, boolean[] visited, int[] visitedStep) { int answer = 0; int a = 1; int b = 0; ArrayList<Node> fringe = new ArrayList<>(); fringe.add(root); while (fringe.size() > 0) { answer += 1; ArrayList<Node> newFringe = new ArrayList<>(); for (Node node : fringe) { for (Node neighbor: node.neighbors) { if (!visited[neighbor.index]) { if ((answer + 1) % 2 == 0) { b += 1; } else { a += 1; } visitedStep[neighbor.index] = answer + 1; newFringe.add(neighbor); visited[neighbor.index] = true; } else { if (visitedStep[neighbor.index] % 2 != (answer + 1) % 2) return -1; } } } fringe = newFringe; } return combinations(a, b); } }
Java
["2\n2 1\n1 2\n4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4"]
2 seconds
["4\n0"]
NotePossible ways to distribute numbers in the first test: the vertex $$$1$$$ should contain $$$1$$$, and $$$2$$$ should contain $$$2$$$; the vertex $$$1$$$ should contain $$$3$$$, and $$$2$$$ should contain $$$2$$$; the vertex $$$1$$$ should contain $$$2$$$, and $$$2$$$ should contain $$$1$$$; the vertex $$$1$$$ should contain $$$2$$$, and $$$2$$$ should contain $$$3$$$. In the second test there is no way to distribute numbers.
Java 8
standard input
[ "dfs and similar", "graphs" ]
332340a793eb3ec14131948e2b6bdf2f
The first line contains one integer $$$t$$$ ($$$1 \le t \le 3 \cdot 10^5$$$) β€” the number of tests in the input. The first line of each test contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5, 0 \le m \le 3 \cdot 10^5$$$) β€” the number of vertices and the number of edges, respectively. Next $$$m$$$ lines describe edges: $$$i$$$-th line contains two integers $$$u_i$$$, $$$ v_i$$$ ($$$1 \le u_i, v_i \le n; u_i \neq v_i$$$) β€” indices of vertices connected by $$$i$$$-th edge. It is guaranteed that $$$\sum\limits_{i=1}^{t} n \le 3 \cdot 10^5$$$ and $$$\sum\limits_{i=1}^{t} m \le 3 \cdot 10^5$$$.
1,700
For each test print one line, containing one integer β€” the number of possible ways to write numbers $$$1$$$, $$$2$$$, $$$3$$$ on the vertices of given graph so it becomes beautiful. Since answers may be large, print them modulo $$$998244353$$$.
standard output
PASSED
d4a366f76e98f588613f8698fa858ea7
train_000.jsonl
1544884500
You are given an undirected unweighted graph consisting of $$$n$$$ vertices and $$$m$$$ edges.You have to write a number on each vertex of the graph. Each number should be $$$1$$$, $$$2$$$ or $$$3$$$. The graph becomes beautiful if for each edge the sum of numbers on vertices connected by this edge is odd.Calculate the number of possible ways to write numbers $$$1$$$, $$$2$$$ and $$$3$$$ on vertices so the graph becomes beautiful. Since this number may be large, print it modulo $$$998244353$$$.Note that you have to write exactly one number on each vertex.The graph does not have any self-loops or multiple edges.
256 megabytes
import org.omg.CORBA.MARSHAL; import java.awt.event.InputEvent; import java.awt.image.AreaAveragingScaleFilter; import java.io.*; import java.net.CookieHandler; import java.util.*; import java.math.*; import java.lang.*; public class Main implements Runnable { static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; private BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars==-1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if(numChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } public int nextInt() { int c = read(); while(isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if(c<'0'||c>'9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public double nextDouble() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } double res = 0; while (!isSpaceChar(c) && c != '.') { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } if (c == '.') { c = read(); double m = 1; while (!isSpaceChar(c)) { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return readString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } public static void main(String args[]) throws Exception { new Thread(null, new Main(),"Main",1<<26).start(); } static long gcd(long a,long b){ if(b==0)return a;return gcd(b,a%b); } static long modPow(long a,long p,long m){ if(a==1)return 1;long ans=1;while (p>0){ if(p%2==1)ans=(ans*a)%m;a=(a*a)%m;p>>=1; }return ans; } static long modInv(long a,long m){return modPow(a,m-2,m);} int val[],visited[]; long temp=1,mod=998244353; void dfs(int u,int par,int parity,ArrayList<Integer> l[],PrintWriter out,int c0,int c1){ visited[u]=1; for(int v:l[u]){ if(v==par)continue; if(val[v]!=c0 && val[v]!=c1){ if(parity==c0){ temp=(temp*2)%mod; val[v]=c1; dfs(v,u,c1,l,out,c0,c1); } else{ val[v]=c0; dfs(v,u,c0,l,out,c0,c1); } } else{ if(val[v]==(parity)){ // out.println("ha"); //out.println(u+" "+v+" "+val[v]+" "+parity+" "+c0+" "+c1); /* for (int i = 0; i <l.length ; i++) { out.print(val[i]+" "); } out.println();*/ temp = 0; return; } } } } public void run() { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int t=sc.nextInt(); while (t-->0){ long ans=1; int n=sc.nextInt(); ArrayList<Integer> l[]=new ArrayList[n]; for (int i = 0; i < n; i++) { l[i]=new ArrayList<>(); } int m=sc.nextInt(); while (m-->0){ int u=sc.nextInt()-1; int v=sc.nextInt()-1; l[u].add(v); l[v].add(u); } visited=new int[n]; val=new int[n]; Arrays.fill(val,-1); int cc=0; for (int i = 0; i <n ; i++) { if(visited[i]==0){ temp=1; long comp=0; val[i]=cc; dfs(i,-1,cc,l,out,cc,cc+1); comp=(comp+temp)%mod; // out.println("t"+temp); cc+=2; temp=1; val[i]=cc+1; dfs(i,-1,cc+1,l,out,cc,cc+1); comp=(comp+(temp*2)%mod)%mod; // out.println("t"+temp); ans=(ans*comp)%mod; cc++; } } out.println(ans); } out.close(); } }
Java
["2\n2 1\n1 2\n4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4"]
2 seconds
["4\n0"]
NotePossible ways to distribute numbers in the first test: the vertex $$$1$$$ should contain $$$1$$$, and $$$2$$$ should contain $$$2$$$; the vertex $$$1$$$ should contain $$$3$$$, and $$$2$$$ should contain $$$2$$$; the vertex $$$1$$$ should contain $$$2$$$, and $$$2$$$ should contain $$$1$$$; the vertex $$$1$$$ should contain $$$2$$$, and $$$2$$$ should contain $$$3$$$. In the second test there is no way to distribute numbers.
Java 8
standard input
[ "dfs and similar", "graphs" ]
332340a793eb3ec14131948e2b6bdf2f
The first line contains one integer $$$t$$$ ($$$1 \le t \le 3 \cdot 10^5$$$) β€” the number of tests in the input. The first line of each test contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5, 0 \le m \le 3 \cdot 10^5$$$) β€” the number of vertices and the number of edges, respectively. Next $$$m$$$ lines describe edges: $$$i$$$-th line contains two integers $$$u_i$$$, $$$ v_i$$$ ($$$1 \le u_i, v_i \le n; u_i \neq v_i$$$) β€” indices of vertices connected by $$$i$$$-th edge. It is guaranteed that $$$\sum\limits_{i=1}^{t} n \le 3 \cdot 10^5$$$ and $$$\sum\limits_{i=1}^{t} m \le 3 \cdot 10^5$$$.
1,700
For each test print one line, containing one integer β€” the number of possible ways to write numbers $$$1$$$, $$$2$$$, $$$3$$$ on the vertices of given graph so it becomes beautiful. Since answers may be large, print them modulo $$$998244353$$$.
standard output
PASSED
7d66762038df935ef33108019da866ab
train_000.jsonl
1544884500
You are given an undirected unweighted graph consisting of $$$n$$$ vertices and $$$m$$$ edges.You have to write a number on each vertex of the graph. Each number should be $$$1$$$, $$$2$$$ or $$$3$$$. The graph becomes beautiful if for each edge the sum of numbers on vertices connected by this edge is odd.Calculate the number of possible ways to write numbers $$$1$$$, $$$2$$$ and $$$3$$$ on vertices so the graph becomes beautiful. Since this number may be large, print it modulo $$$998244353$$$.Note that you have to write exactly one number on each vertex.The graph does not have any self-loops or multiple edges.
256 megabytes
import java.util.*; import java.io.*; public class waw{ static HashMap<Integer,Node> luckup = new HashMap<Integer,Node>(); public static class Node{ int id; int nb; LinkedList<Integer> neighbers = new LinkedList<Integer>(); public Node(int i){ id = i; nb = 0; } } public static Node getNode(int id){ return luckup.get(id); } public static void addEdges(int first,int second){ Node f = getNode(first); f.neighbers.add(second); } public static long bfs(int start,int n,long M){ LinkedList<Integer> nextToVisit = new LinkedList<Integer>(); nextToVisit.add(start); getNode(start).nb = 1; int max = 1; int a=0,b=0; while(!nextToVisit.isEmpty()){ Node node = getNode(nextToVisit.poll()); if(node.nb%2==0) a++; else b++; for(int neighber:node.neighbers){ if(getNode(neighber).nb==0){ getNode(neighber).nb = node.nb+1; nextToVisit.add(neighber); } else if(getNode(neighber).nb%2==node.nb%2){ max = -1; break; } } if(max == -1) break; } if(max==-1) return max; long val = 0,nba=1,nbb=1; for(int i=0;i<a;i++) { nba *= 2; nba %= M; } for(int i=0;i<b;i++) { nbb *= 2; nbb %= M; } val = nba + nbb; val %= M; return val; } public static void main(String[] args) throws Exception{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); StringTokenizer st = new StringTokenizer(br.readLine()); int t = Integer.parseInt(st.nextToken()); int n,m,u,v; long rep = 1,val = 0; long M = 998244353; for(int z=0;z<t;z++){ st = new StringTokenizer(br.readLine()); n = Integer.parseInt(st.nextToken()); m = Integer.parseInt(st.nextToken()); for(int i=1;i<=n;i++){ luckup.put(i,new Node(i)); } for(int i=0;i<m;i++){ st = new StringTokenizer(br.readLine()); u = Integer.parseInt(st.nextToken()); v = Integer.parseInt(st.nextToken()); addEdges(u,v); addEdges(v,u); } for(int i=1;i<=n;i++){ if(getNode(i).nb==0){ val = bfs(i,n,M); if(val == -1){ break; } rep *= val; rep %= M; } } if(val==-1) out.println("0"); else out.println(rep); luckup.clear(); rep = 1; } out.flush(); } }
Java
["2\n2 1\n1 2\n4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4"]
2 seconds
["4\n0"]
NotePossible ways to distribute numbers in the first test: the vertex $$$1$$$ should contain $$$1$$$, and $$$2$$$ should contain $$$2$$$; the vertex $$$1$$$ should contain $$$3$$$, and $$$2$$$ should contain $$$2$$$; the vertex $$$1$$$ should contain $$$2$$$, and $$$2$$$ should contain $$$1$$$; the vertex $$$1$$$ should contain $$$2$$$, and $$$2$$$ should contain $$$3$$$. In the second test there is no way to distribute numbers.
Java 8
standard input
[ "dfs and similar", "graphs" ]
332340a793eb3ec14131948e2b6bdf2f
The first line contains one integer $$$t$$$ ($$$1 \le t \le 3 \cdot 10^5$$$) β€” the number of tests in the input. The first line of each test contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5, 0 \le m \le 3 \cdot 10^5$$$) β€” the number of vertices and the number of edges, respectively. Next $$$m$$$ lines describe edges: $$$i$$$-th line contains two integers $$$u_i$$$, $$$ v_i$$$ ($$$1 \le u_i, v_i \le n; u_i \neq v_i$$$) β€” indices of vertices connected by $$$i$$$-th edge. It is guaranteed that $$$\sum\limits_{i=1}^{t} n \le 3 \cdot 10^5$$$ and $$$\sum\limits_{i=1}^{t} m \le 3 \cdot 10^5$$$.
1,700
For each test print one line, containing one integer β€” the number of possible ways to write numbers $$$1$$$, $$$2$$$, $$$3$$$ on the vertices of given graph so it becomes beautiful. Since answers may be large, print them modulo $$$998244353$$$.
standard output
PASSED
a40c5d001cf9e12aa5bc8d1238998b41
train_000.jsonl
1544884500
You are given an undirected unweighted graph consisting of $$$n$$$ vertices and $$$m$$$ edges.You have to write a number on each vertex of the graph. Each number should be $$$1$$$, $$$2$$$ or $$$3$$$. The graph becomes beautiful if for each edge the sum of numbers on vertices connected by this edge is odd.Calculate the number of possible ways to write numbers $$$1$$$, $$$2$$$ and $$$3$$$ on vertices so the graph becomes beautiful. Since this number may be large, print it modulo $$$998244353$$$.Note that you have to write exactly one number on each vertex.The graph does not have any self-loops or multiple edges.
256 megabytes
import java.io.*; import java.util.*; import java.lang.*; import java.math.*; public class Main extends Thread { boolean[] prime; FastScanner sc; PrintWriter pw; long startTime = System.currentTimeMillis(); final 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 long nlo() { return Long.parseLong(next()); } 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 ni() { return Integer.parseInt(next()); } public String nli() { String line = ""; if (st.hasMoreTokens()) line = st.nextToken(); else try { return br.readLine(); } catch (IOException e) { e.printStackTrace(); } while (st.hasMoreTokens()) line += " " + st.nextToken(); return line; } public double nd() { return Double.parseDouble(next()); } } public Main(ThreadGroup t,Runnable r,String s,long d ) { super(t,r,s,d); } public void run() { sc=new FastScanner(); pw=new PrintWriter(System.out); solve(); pw.flush(); pw.close(); } public static void main(String[] args) { new Main(null,null,"",1<<25).start(); } /////////////------------------------------------////////////// ////////////------------------Main-Logic--------////////////// ///////////-------------------------------------////////////// public static int[] visit,col; public static ArrayList<Integer>[] adj; public static long mod,c1,c2; public void solve() { int t=sc.ni(); while(t-->0) { int n=sc.ni(); mod= 998244353L; visit=new int[n]; c1=0;c2=0; adj=new ArrayList[n]; for(int i=0;i<n;i++) adj[i]=new ArrayList(); col=new int[n]; int m=sc.ni(); for(int i=0;i<m;i++) { int x=sc.ni()-1; int y=sc.ni()-1; adj[x].add(y); adj[y].add(x); } int res=0; long ans=1; for(int i=0;i<n;i++) { if(visit[i]==0) { bfs(i); if(c1==-1) break; long tmp=(pow(c1)+pow(c2))%mod; ans*=tmp; ans%=mod; c1=0;c2=0; } } if(c1==-1) pw.println("0"); else pw.println(ans); } } public static void bfs(int x) { if(adj[x].size()==0) { visit[x]=1; c1=0; c2=1; return; } Queue<Integer> qu=new ArrayDeque<Integer>(); qu.add(x); visit[x]=1; col[x]=1; c1++; while(!qu.isEmpty()) { x=qu.poll(); for(int y:adj[x]) { if(visit[y]==0) { visit[y]=1; if(col[x]==1) {c2++;col[y]=2;} else {col[y]=1;c1++;} qu.add(y); } else { if(col[x]==col[y]) { c1=-1; return; } } } } } public static long pow(long y) { if(y==1L) return 2L; if(y==0) return 1L; long ans=1L; long ans1=1L; long x=2L; while(y>1L) { if((y&1L)==1L) ans1*=x; y/=2L; x=x*x; x%=mod; ans1%=mod; } ans=(x*ans1)%mod; return ans; } }
Java
["2\n2 1\n1 2\n4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4"]
2 seconds
["4\n0"]
NotePossible ways to distribute numbers in the first test: the vertex $$$1$$$ should contain $$$1$$$, and $$$2$$$ should contain $$$2$$$; the vertex $$$1$$$ should contain $$$3$$$, and $$$2$$$ should contain $$$2$$$; the vertex $$$1$$$ should contain $$$2$$$, and $$$2$$$ should contain $$$1$$$; the vertex $$$1$$$ should contain $$$2$$$, and $$$2$$$ should contain $$$3$$$. In the second test there is no way to distribute numbers.
Java 8
standard input
[ "dfs and similar", "graphs" ]
332340a793eb3ec14131948e2b6bdf2f
The first line contains one integer $$$t$$$ ($$$1 \le t \le 3 \cdot 10^5$$$) β€” the number of tests in the input. The first line of each test contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5, 0 \le m \le 3 \cdot 10^5$$$) β€” the number of vertices and the number of edges, respectively. Next $$$m$$$ lines describe edges: $$$i$$$-th line contains two integers $$$u_i$$$, $$$ v_i$$$ ($$$1 \le u_i, v_i \le n; u_i \neq v_i$$$) β€” indices of vertices connected by $$$i$$$-th edge. It is guaranteed that $$$\sum\limits_{i=1}^{t} n \le 3 \cdot 10^5$$$ and $$$\sum\limits_{i=1}^{t} m \le 3 \cdot 10^5$$$.
1,700
For each test print one line, containing one integer β€” the number of possible ways to write numbers $$$1$$$, $$$2$$$, $$$3$$$ on the vertices of given graph so it becomes beautiful. Since answers may be large, print them modulo $$$998244353$$$.
standard output
PASSED
900b246d3e72ab6f4ea0d434f89bea94
train_000.jsonl
1544884500
You are given an undirected unweighted graph consisting of $$$n$$$ vertices and $$$m$$$ edges.You have to write a number on each vertex of the graph. Each number should be $$$1$$$, $$$2$$$ or $$$3$$$. The graph becomes beautiful if for each edge the sum of numbers on vertices connected by this edge is odd.Calculate the number of possible ways to write numbers $$$1$$$, $$$2$$$ and $$$3$$$ on vertices so the graph becomes beautiful. Since this number may be large, print it modulo $$$998244353$$$.Note that you have to write exactly one number on each vertex.The graph does not have any self-loops or multiple edges.
256 megabytes
import java.io.*; import java.util.*; public class D { long mod = 998244353; void solve() { int t = in.nextInt(); for (int tt = 0; tt < t; tt++) { int n = in.nextInt(); int m = in.nextInt(); ArrayList<ArrayList<Integer>> adj = new ArrayList<>(); for (int i = 0; i < n; i++) { adj.add(new ArrayList<>()); } for (int i = 0; i < m; i++) { int u = in.nextInt() - 1; int v = in.nextInt() - 1; adj.get(u).add(v); adj.get(v).add(u); } long ans = 1; int[] mark = new int[n]; for (int i = 0; i < n; i++) { if (mark[i] == 0) { long ways = canMark(i, n, m, adj, mark); ans = mul(ans, ways, mod); } } out.println(ans); } } private long canMark(int start, int n, int m, ArrayList<ArrayList<Integer>> adj, int[] mark) { if (mark[start] != 0) throw new RuntimeException("zxc"); mark[start] = 1; long ones = 1; long twos = 1; Queue<Integer> queue = new ArrayDeque<>(); queue.add(start); while (!queue.isEmpty()) { int v = queue.poll(); if (mark[v] == 1) ones = mul(ones, 2, mod); else twos = mul(twos, 2, mod); int opposite = opposite(mark[v]); List<Integer> to = adj.get(v); for (int next : to) { if (mark[next] == 0) { mark[next] = opposite; queue.add(next); } else if (mark[next] != opposite) { return 0; } } } return add(ones, twos, mod); } long mul(long a, long b, long mod) { return (a * b) % mod; } long add(long a, long b, long mod) { long res = a + b; if (res >= mod) res -= mod; return res; } int opposite(int n) { return n == 1 ? 2 : 1; } long pow(long a, long b, long n){ long x=1, y=a; while (b > 0) { if (b%2 == 1) { x = (x*y) % n; } y = (y*y) % n; b /= 2; } return x % n; } Scanner in; PrintWriter out; void run() { try { in = new Scanner(new File("A.in")); out = new PrintWriter(new File("A.out")); solve(); out.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } } void runIO() { in = new Scanner(System.in); out = new PrintWriter(System.out); solve(); out.close(); } class Scanner { BufferedReader br; StringTokenizer st; public Scanner(File f) { try { br = new BufferedReader(new FileReader(f)); } catch (FileNotFoundException e) { e.printStackTrace(); } } public Scanner(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(); } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while ((b = read()) != -1 && isSpaceChar(b)) ; return b; } private int read() { int res = -1; try { res = br.read(); } catch (IOException e) { e.printStackTrace(); } return res; } char[] nextCharArray(int size) { char[] buf = new char[size]; int b = skip(), p = 0; while (p < size && !(isSpaceChar(b))) { buf[p++] = (char) b; b = read(); } return size == p ? buf : Arrays.copyOf(buf, p); } char[][] nextCharMap(int n, int m) { char[][] map = new char[n][]; for (int i = 0; i < n; i++) { map[i] = nextCharArray(m); } return map; } int[] na(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = in.nextInt(); } return arr; } 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 D().runIO(); } }
Java
["2\n2 1\n1 2\n4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4"]
2 seconds
["4\n0"]
NotePossible ways to distribute numbers in the first test: the vertex $$$1$$$ should contain $$$1$$$, and $$$2$$$ should contain $$$2$$$; the vertex $$$1$$$ should contain $$$3$$$, and $$$2$$$ should contain $$$2$$$; the vertex $$$1$$$ should contain $$$2$$$, and $$$2$$$ should contain $$$1$$$; the vertex $$$1$$$ should contain $$$2$$$, and $$$2$$$ should contain $$$3$$$. In the second test there is no way to distribute numbers.
Java 8
standard input
[ "dfs and similar", "graphs" ]
332340a793eb3ec14131948e2b6bdf2f
The first line contains one integer $$$t$$$ ($$$1 \le t \le 3 \cdot 10^5$$$) β€” the number of tests in the input. The first line of each test contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5, 0 \le m \le 3 \cdot 10^5$$$) β€” the number of vertices and the number of edges, respectively. Next $$$m$$$ lines describe edges: $$$i$$$-th line contains two integers $$$u_i$$$, $$$ v_i$$$ ($$$1 \le u_i, v_i \le n; u_i \neq v_i$$$) β€” indices of vertices connected by $$$i$$$-th edge. It is guaranteed that $$$\sum\limits_{i=1}^{t} n \le 3 \cdot 10^5$$$ and $$$\sum\limits_{i=1}^{t} m \le 3 \cdot 10^5$$$.
1,700
For each test print one line, containing one integer β€” the number of possible ways to write numbers $$$1$$$, $$$2$$$, $$$3$$$ on the vertices of given graph so it becomes beautiful. Since answers may be large, print them modulo $$$998244353$$$.
standard output
PASSED
8d481150b3de1af666d8d678d88007f6
train_000.jsonl
1544884500
You are given an undirected unweighted graph consisting of $$$n$$$ vertices and $$$m$$$ edges.You have to write a number on each vertex of the graph. Each number should be $$$1$$$, $$$2$$$ or $$$3$$$. The graph becomes beautiful if for each edge the sum of numbers on vertices connected by this edge is odd.Calculate the number of possible ways to write numbers $$$1$$$, $$$2$$$ and $$$3$$$ on vertices so the graph becomes beautiful. Since this number may be large, print it modulo $$$998244353$$$.Note that you have to write exactly one number on each vertex.The graph does not have any self-loops or multiple edges.
256 megabytes
// package BigD; import java.util.*; import java.io.*; import java.lang.reflect.Array; import java.math.*; public class Main { static int[] color; static ArrayList G[]; static int[] num, pw; public static void main(String[] args) { Scanner in = new Scanner(System.in); int N = (int)3e5 + 10, M = 998244353; pw = new int[N]; num = new int[5]; pw[0] = 1; for(int i = 1; i < N; i++) pw[i] = pw[i-1] * 2 % M; int T = in.nextInt(); for(int cas = 1; cas <= T; cas++) { int n = in.nextInt(), m = in.nextInt(); if(n == 1 && m == 0) { System.out.printf("3\n"); }else { color = new int[n]; G = new ArrayList[n]; for(int i = 0; i < n; i++) G[i] = new ArrayList(); for(int i = 0; i < m; i++) { int u = in.nextInt() - 1, v = in.nextInt() - 1; // System.out.println("?? " + u + " " + v); G[u].add(v); G[v].add(u); } boolean f = true; long ans = 1; for(int i = 0; i < n && f; i++) if(color[i] == 0) { color[i] = 1; num[1] = 1; num[2] = 0; f = dfs(i); ans = (ans * (pw[num[1]] + pw[num[2]])) % M; } if(f == false) ans = 0; System.out.println(ans); } } in.close(); } static boolean dfs(int u) { for(int i = 0; i < G[u].size(); i++) { int v = (int)G[u].get(i); if(color[v] == 0) { color[v] = 3 - color[u]; num[color[v]]++; if(dfs(v) == false) return false; }else if(color[v] == color[u]) return false; } return true; } }
Java
["2\n2 1\n1 2\n4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4"]
2 seconds
["4\n0"]
NotePossible ways to distribute numbers in the first test: the vertex $$$1$$$ should contain $$$1$$$, and $$$2$$$ should contain $$$2$$$; the vertex $$$1$$$ should contain $$$3$$$, and $$$2$$$ should contain $$$2$$$; the vertex $$$1$$$ should contain $$$2$$$, and $$$2$$$ should contain $$$1$$$; the vertex $$$1$$$ should contain $$$2$$$, and $$$2$$$ should contain $$$3$$$. In the second test there is no way to distribute numbers.
Java 8
standard input
[ "dfs and similar", "graphs" ]
332340a793eb3ec14131948e2b6bdf2f
The first line contains one integer $$$t$$$ ($$$1 \le t \le 3 \cdot 10^5$$$) β€” the number of tests in the input. The first line of each test contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5, 0 \le m \le 3 \cdot 10^5$$$) β€” the number of vertices and the number of edges, respectively. Next $$$m$$$ lines describe edges: $$$i$$$-th line contains two integers $$$u_i$$$, $$$ v_i$$$ ($$$1 \le u_i, v_i \le n; u_i \neq v_i$$$) β€” indices of vertices connected by $$$i$$$-th edge. It is guaranteed that $$$\sum\limits_{i=1}^{t} n \le 3 \cdot 10^5$$$ and $$$\sum\limits_{i=1}^{t} m \le 3 \cdot 10^5$$$.
1,700
For each test print one line, containing one integer β€” the number of possible ways to write numbers $$$1$$$, $$$2$$$, $$$3$$$ on the vertices of given graph so it becomes beautiful. Since answers may be large, print them modulo $$$998244353$$$.
standard output
PASSED
09cdb297a2e43faea4c10d3158c503cf
train_000.jsonl
1544884500
You are given an undirected unweighted graph consisting of $$$n$$$ vertices and $$$m$$$ edges.You have to write a number on each vertex of the graph. Each number should be $$$1$$$, $$$2$$$ or $$$3$$$. The graph becomes beautiful if for each edge the sum of numbers on vertices connected by this edge is odd.Calculate the number of possible ways to write numbers $$$1$$$, $$$2$$$ and $$$3$$$ on vertices so the graph becomes beautiful. Since this number may be large, print it modulo $$$998244353$$$.Note that you have to write exactly one number on each vertex.The graph does not have any self-loops or multiple edges.
256 megabytes
// package test1; import java.util.*; import java.io.*; import java.lang.reflect.Array; import java.math.*; public class Main { private static StringTokenizer ST; private static BufferedReader BR; private static PrintWriter PW; static int[] color; static ArrayList<Integer> G[]; static int[] num, pw; public static void main(String[] args) throws IOException { BR = new BufferedReader(new InputStreamReader(System.in)); PW = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); int N = (int)3e5 + 10, M = 998244353; pw = new int[N]; pw[0] = 1; for(int i = 1; i < N; i++) pw[i] = pw[i-1] * 2 % M; int T = nextInt(); for(int cas = 1; cas <= T; cas++) { int n = nextInt(), m = nextInt(); color = new int[n]; G = new ArrayList[n]; num = new int[5]; for(int i = 0; i < n; i++) G[i] = new ArrayList<Integer>(); for(int i = 0; i < m; i++) { int u = nextInt() - 1, v = nextInt() - 1; // System.out.println("?? " + u + " " + v); G[u].add(v); G[v].add(u); } boolean f = true; long ans = 1; for(int i = 0; i < n && f; i++) if(color[i] == 0) { color[i] = 1; num[1] = 1; num[2] = 0; f = dfs(i); ans = (ans * (pw[num[1]] + pw[num[2]])) % M; } if(f == false) ans = 0; PW.println(ans); } PW.close(); } static boolean dfs(int u) { for(int v : G[u]) { if(color[v] == 0) { color[v] = 3 - color[u]; num[color[v]]++; if(dfs(v) == false) return false; }else if(color[v] == color[u]) return false; } return true; } 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
["2\n2 1\n1 2\n4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4"]
2 seconds
["4\n0"]
NotePossible ways to distribute numbers in the first test: the vertex $$$1$$$ should contain $$$1$$$, and $$$2$$$ should contain $$$2$$$; the vertex $$$1$$$ should contain $$$3$$$, and $$$2$$$ should contain $$$2$$$; the vertex $$$1$$$ should contain $$$2$$$, and $$$2$$$ should contain $$$1$$$; the vertex $$$1$$$ should contain $$$2$$$, and $$$2$$$ should contain $$$3$$$. In the second test there is no way to distribute numbers.
Java 8
standard input
[ "dfs and similar", "graphs" ]
332340a793eb3ec14131948e2b6bdf2f
The first line contains one integer $$$t$$$ ($$$1 \le t \le 3 \cdot 10^5$$$) β€” the number of tests in the input. The first line of each test contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5, 0 \le m \le 3 \cdot 10^5$$$) β€” the number of vertices and the number of edges, respectively. Next $$$m$$$ lines describe edges: $$$i$$$-th line contains two integers $$$u_i$$$, $$$ v_i$$$ ($$$1 \le u_i, v_i \le n; u_i \neq v_i$$$) β€” indices of vertices connected by $$$i$$$-th edge. It is guaranteed that $$$\sum\limits_{i=1}^{t} n \le 3 \cdot 10^5$$$ and $$$\sum\limits_{i=1}^{t} m \le 3 \cdot 10^5$$$.
1,700
For each test print one line, containing one integer β€” the number of possible ways to write numbers $$$1$$$, $$$2$$$, $$$3$$$ on the vertices of given graph so it becomes beautiful. Since answers may be large, print them modulo $$$998244353$$$.
standard output
PASSED
34bbce235f10a36497db23602a903b92
train_000.jsonl
1544884500
You are given an undirected unweighted graph consisting of $$$n$$$ vertices and $$$m$$$ edges.You have to write a number on each vertex of the graph. Each number should be $$$1$$$, $$$2$$$ or $$$3$$$. The graph becomes beautiful if for each edge the sum of numbers on vertices connected by this edge is odd.Calculate the number of possible ways to write numbers $$$1$$$, $$$2$$$ and $$$3$$$ on vertices so the graph becomes beautiful. Since this number may be large, print it modulo $$$998244353$$$.Note that you have to write exactly one number on each vertex.The graph does not have any self-loops or multiple edges.
256 megabytes
import java.io.*; import java.util.*; public class A { static ArrayList<Integer>[]adj; static int []col; static int MOD=998244353; static int ones; static int dfs(int u) { int ans=1; for(int v:adj[u]) if(col[v]==-1) { col[v]=col[u]^1; if(col[v]==1) ones++; int tmp=dfs(v); if(tmp==-1) return -1; ans+=tmp; } else if(col[v]==col[u]) return -1; return ans; } public static void main(String[] args) throws IOException { Scanner sc = new Scanner(); PrintWriter out = new PrintWriter(System.out); int MAX=(int)3e5+4; int []pow=new int [MAX]; pow[0]=1; for(int i=1;i<MAX;i++) { pow[i]=pow[i-1]<<1; if(pow[i]>=MOD) pow[i]-=MOD; } int tc=sc.nextInt(); while(tc-->0) { int n=sc.nextInt(),m=sc.nextInt(); col=new int [n]; adj=new ArrayList[n]; for(int i=0;i<n;i++) { adj[i]=new ArrayList(); col[i]=-1; } while(m-->0) { int u=sc.nextInt()-1,v=sc.nextInt()-1; adj[u].add(v); adj[v].add(u); } long ans=1; for(int i=0;i<n;i++) if(col[i]==-1) { col[i]=0; ones=0; int curr=dfs(i); if(curr==-1) { ans=0; break; } ans*=(pow[ones]+pow[curr-ones]); ans%=MOD; } out.println(ans); } out.close(); } static class Scanner { BufferedReader br; StringTokenizer st; Scanner() { br = new BufferedReader(new InputStreamReader(System.in)); } Scanner(String fileName) throws FileNotFoundException { br = new BufferedReader(new FileReader(fileName)); } String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } String nextLine() throws IOException { return br.readLine(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws NumberFormatException, IOException { return Long.parseLong(next()); } double nextDouble() throws NumberFormatException, IOException { return Double.parseDouble(next()); } } }
Java
["2\n2 1\n1 2\n4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4"]
2 seconds
["4\n0"]
NotePossible ways to distribute numbers in the first test: the vertex $$$1$$$ should contain $$$1$$$, and $$$2$$$ should contain $$$2$$$; the vertex $$$1$$$ should contain $$$3$$$, and $$$2$$$ should contain $$$2$$$; the vertex $$$1$$$ should contain $$$2$$$, and $$$2$$$ should contain $$$1$$$; the vertex $$$1$$$ should contain $$$2$$$, and $$$2$$$ should contain $$$3$$$. In the second test there is no way to distribute numbers.
Java 8
standard input
[ "dfs and similar", "graphs" ]
332340a793eb3ec14131948e2b6bdf2f
The first line contains one integer $$$t$$$ ($$$1 \le t \le 3 \cdot 10^5$$$) β€” the number of tests in the input. The first line of each test contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5, 0 \le m \le 3 \cdot 10^5$$$) β€” the number of vertices and the number of edges, respectively. Next $$$m$$$ lines describe edges: $$$i$$$-th line contains two integers $$$u_i$$$, $$$ v_i$$$ ($$$1 \le u_i, v_i \le n; u_i \neq v_i$$$) β€” indices of vertices connected by $$$i$$$-th edge. It is guaranteed that $$$\sum\limits_{i=1}^{t} n \le 3 \cdot 10^5$$$ and $$$\sum\limits_{i=1}^{t} m \le 3 \cdot 10^5$$$.
1,700
For each test print one line, containing one integer β€” the number of possible ways to write numbers $$$1$$$, $$$2$$$, $$$3$$$ on the vertices of given graph so it becomes beautiful. Since answers may be large, print them modulo $$$998244353$$$.
standard output
PASSED
0b80b81e4f6e44e9c2f5c12c012c9236
train_000.jsonl
1544884500
You are given an undirected unweighted graph consisting of $$$n$$$ vertices and $$$m$$$ edges.You have to write a number on each vertex of the graph. Each number should be $$$1$$$, $$$2$$$ or $$$3$$$. The graph becomes beautiful if for each edge the sum of numbers on vertices connected by this edge is odd.Calculate the number of possible ways to write numbers $$$1$$$, $$$2$$$ and $$$3$$$ on vertices so the graph becomes beautiful. Since this number may be large, print it modulo $$$998244353$$$.Note that you have to write exactly one number on each vertex.The graph does not have any self-loops or multiple edges.
256 megabytes
import java.io.*; import java.lang.reflect.Array; import java.math.BigInteger; import java.util.*; public class B { String fileName = ""; ////////////////////// SOLUTION SOLUTION SOLUTION ////////////////////////////// long INF = Long.MAX_VALUE / 1000; long MODULO = 998244353 ; int[][] steps = {{0, 1}, {1, 0}, {-1, 0}, {0, -1}}; private final static Random rnd = new Random(); double eps = 1e-1; class Pair implements Comparable<Pair>{ int val, ind; public Pair(int val, int ind) { this.val = val; this.ind = ind; } @Override public int compareTo(Pair o) { return -Integer.compare(this.val, o.val); } } ArrayList<Integer>[] graph; boolean[] used; int[] dist; boolean flag = true; int[] count = new int[2]; long[] pows; void solve() throws IOException { int t = readInt(); int INF = 1000000; pows = new long[INF]; pows[0] = 1; for (int i=1; i<INF; ++i) { pows[i] = 2 * pows[i - 1]; pows[i] %= MODULO; } ArrayDeque<Integer> q = new ArrayDeque<>(); while (t-- > 0){ int n = readInt(); int m = readInt(); flag = true; dist = new int[n]; used = new boolean[n]; Arrays.fill(dist, INF); graph = new ArrayList[n]; for (int i=0; i<n; ++i) graph[i] = new ArrayList<>(); for (int i=0; i<m; ++i) { int from = readInt() - 1; int to = readInt() - 1; graph[from].add(to); graph[to].add(from); } long ans = 1; for (int i=0; i<n; ++i){ if (dist[i] == INF){ count[0] = 0; count[1] = 0; dist[i] = 0; q.add(i); int countV = 0; while (q.size() > 0){ int cur = q.poll(); countV++; for (int to: graph[cur]){ if (dist[to] == INF){ q.add(to); dist[to] = dist[cur] + 1; } } } dfs(i); if (!flag){ out.println(0); break; }else{ if (countV == 1){ ans *= 3; ans %= MODULO; continue; } long curAns = pows[count[0]]; curAns += pows[count[1]]; ans *= curAns; ans %= MODULO; } } } if (flag){ out.println(ans); } } } void dfs(int from){ used[from] = true; count[dist[from] % 2]++; for (int to: graph[from]){ if (dist[to] %2 == dist[from] % 2) flag = false; if (!used[to]) dfs(to); } } class SegmentTree{ long[] t; int n; SegmentTree(long[] arr, int n){ t = new long[n*4]; build(arr, 1, 1, n); } void build(long[] arr, int v, int tl , int tr){ if (tl == tr) { t[v] = arr[tl]; return; } int tm = (tl + tr) / 2; build(arr, 2 * v, tl, tm); build(arr, 2 * v + 1, tm + 1, tr); t[v] = Math.max(t[2*v], t[2*v + 1]); } long get(int v, int tl , int tr, int l , int r){ if (l > r) return -1; if (tl == l && tr == r) return t[v]; int tm = (tl + tr) / 2; long val1 = get(2 * v, tl, tm, l, Math.min(tm, r)); long val2 = get(2 * v + 1, tm + 1, tr, Math.max(tm + 1, l), r); return Math.max(val1, val2); } } void brute(){ int n = 10; int[] arr = new int[n]; int[] b = new int[n]; for (int it=0; it < 100; ++it){ for (int i=0; i< n; ++i) { arr[i] = rnd.nextInt(100); b[i] = arr[i]; } Arrays.sort(b); for (int k=0; k<n; ++k){ int ans = orderStatistic(arr, k, 0, n-1); if (ans != b[k]) { out.println("HACK!!!"); out.println(n +" " + (k+1)); for (int i: arr) out.print(i +" "); out.println(); out.println(b[k] + " " + ans); } } } } int orderStatistic(int[] arr, int k, int l , int r){ int part = partition(arr, l , r); if (part == k) return arr[part]; if (part > k) return orderStatistic(arr, k, l, part); return orderStatistic(arr, k, part, r); } int partition(int[] arr, int l, int r){ int i = l; int j = r; if (i == j) return i; int pivot = arr[l + rnd.nextInt(r - l)]; while (true){ while (arr[i] < pivot) i++; while (arr[j] > pivot) j--; if (j <= i) return j; int temp = arr[j]; arr[j] = arr[i]; arr[i] = temp; j--; i++; } } long binPow(long a, long b, long m) { if (b == 0) { return 1; } if (b % 2 == 1) { return ((a % m) * (binPow(a, b - 1, m) % m)) % m; } else { long c = binPow(a, b / 2, m); return (c * c) % m; } } class Fenwik { int[] t; int n; Fenwik(int n){ t = new int[n]; this.n = n; } void inc(int r, int delta){ for (; r < n; r = r | (r + 1)) t[r] += delta; } int getSum(int r){ int res = 0; for (; r >=0; r = (r & (r + 1) ) - 1) res += t[r]; return res; } } boolean isPrime(int n){ for (int i=2; i*i<=n; ++i){ if (n%i==0) return false; } return true; } class Number implements Comparable<Number>{ int x, cost; Number(int x, int cost){ this.x = x; this.cost = cost; } @Override public int compareTo(Number o) { return Integer.compare(this.cost, o.cost); } } /////////////////////////////////////////////////////////////////////////////////////////// class SparseTable{ int[][] rmq; int[] logTable; int n; SparseTable(int[] a){ n = a.length; logTable = new int[n+1]; for(int i = 2; i <= n; ++i){ logTable[i] = logTable[i >> 1] + 1; } rmq = new int[logTable[n] + 1][n]; for(int i=0; i<n; ++i){ rmq[0][i] = a[i]; } for(int k=1; (1 << k) < n; ++k){ for(int i=0; i + (1 << k) <= n; ++i){ int max1 = rmq[k - 1][i]; int max2 = rmq[k-1][i + (1 << (k-1))]; rmq[k][i] = Math.max(max1, max2); } } } int max(int l, int r){ int k = logTable[r - l]; int max1 = rmq[k][l]; int max2 = rmq[k][r - (1 << k) + 1]; return Math.max(max1, max2); } } long checkBit(long mask, int bit){ return (mask >> bit) & 1; } static int checkBit(int mask, int bit) { return (mask >> bit) & 1; } boolean isLower(char c){ return c >= 'a' && c <= 'z'; } class Edge{ int to, dist; public Edge(int to, int dist) { this.to = to; this.dist = dist; } } class Vertex implements Comparable<Vertex>{ int from, count; public Vertex(int from, int count) { this.from = from; this.count = count; } @Override public int compareTo(Vertex o) { return Long.compare(this.count, o.count); } } //////////////////////////////////////////////////////////// int gcd(int a, int b){ return b == 0 ? a : gcd(b, a%b); } long gcd(long a, long b){ return b == 0 ? a : gcd(b, a%b); } double binPow(double a, int pow){ if (pow == 0) return 1; if (pow % 2 == 1) { return a * binPow(a, pow - 1); } else { double c = binPow(a, pow / 2); return c * c; } } int minInt(int... values) { int min = Integer.MAX_VALUE; for (int value : values) min = Math.min(min, value); return min; } int maxInt(int... values) { int max = Integer.MIN_VALUE; for (int value : values) max = Math.max(max, value); return max; } public static void main(String[] args) throws NumberFormatException, IOException { // TODO Auto-generated method stub new B().run(); } void run() throws NumberFormatException, IOException { solve(); out.close(); }; BufferedReader in; PrintWriter out; StringTokenizer tok; String delim = " "; B() throws FileNotFoundException { try { in = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter("output.txt"); } catch (Exception e) { if (fileName.isEmpty()) { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } else { in = new BufferedReader(new FileReader(fileName + ".in")); out = new PrintWriter(fileName + ".out"); } } tok = new StringTokenizer(""); } String readLine() throws IOException { return in.readLine(); } String readString() throws IOException { while (!tok.hasMoreTokens()) { String nextLine = readLine(); if (null == nextLine) { return null; } tok = new StringTokenizer(nextLine); } return tok.nextToken(); } int readInt() throws NumberFormatException, IOException { return Integer.parseInt(readString()); } byte readByte() throws NumberFormatException, IOException { return Byte.parseByte(readString()); } int[] readIntArray (int n) throws NumberFormatException, IOException { int[] a = new int[n]; for(int i=0; i<n; ++i){ a[i] = readInt(); } return a; } int[] readIntArrayWithDecrease (int n) throws NumberFormatException, IOException { int[] a = new int[n]; for(int i=0; i<n; ++i){ a[i] = readInt() - 1; } return a; } Integer[] readIntegerArray (int n) throws NumberFormatException, IOException { Integer[] a = new Integer[n]; for(int i=0; i<n; ++i){ a[i] = readInt(); } return a; } long readLong() throws NumberFormatException, IOException { return Long.parseLong(readString()); } double readDouble() throws NumberFormatException, IOException { return Double.parseDouble(readString()); } }
Java
["2\n2 1\n1 2\n4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4"]
2 seconds
["4\n0"]
NotePossible ways to distribute numbers in the first test: the vertex $$$1$$$ should contain $$$1$$$, and $$$2$$$ should contain $$$2$$$; the vertex $$$1$$$ should contain $$$3$$$, and $$$2$$$ should contain $$$2$$$; the vertex $$$1$$$ should contain $$$2$$$, and $$$2$$$ should contain $$$1$$$; the vertex $$$1$$$ should contain $$$2$$$, and $$$2$$$ should contain $$$3$$$. In the second test there is no way to distribute numbers.
Java 8
standard input
[ "dfs and similar", "graphs" ]
332340a793eb3ec14131948e2b6bdf2f
The first line contains one integer $$$t$$$ ($$$1 \le t \le 3 \cdot 10^5$$$) β€” the number of tests in the input. The first line of each test contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5, 0 \le m \le 3 \cdot 10^5$$$) β€” the number of vertices and the number of edges, respectively. Next $$$m$$$ lines describe edges: $$$i$$$-th line contains two integers $$$u_i$$$, $$$ v_i$$$ ($$$1 \le u_i, v_i \le n; u_i \neq v_i$$$) β€” indices of vertices connected by $$$i$$$-th edge. It is guaranteed that $$$\sum\limits_{i=1}^{t} n \le 3 \cdot 10^5$$$ and $$$\sum\limits_{i=1}^{t} m \le 3 \cdot 10^5$$$.
1,700
For each test print one line, containing one integer β€” the number of possible ways to write numbers $$$1$$$, $$$2$$$, $$$3$$$ on the vertices of given graph so it becomes beautiful. Since answers may be large, print them modulo $$$998244353$$$.
standard output
PASSED
c38ddf9b1c5891fefb157360746da4a7
train_000.jsonl
1544884500
You are given an undirected unweighted graph consisting of $$$n$$$ vertices and $$$m$$$ edges.You have to write a number on each vertex of the graph. Each number should be $$$1$$$, $$$2$$$ or $$$3$$$. The graph becomes beautiful if for each edge the sum of numbers on vertices connected by this edge is odd.Calculate the number of possible ways to write numbers $$$1$$$, $$$2$$$ and $$$3$$$ on vertices so the graph becomes beautiful. Since this number may be large, print it modulo $$$998244353$$$.Note that you have to write exactly one number on each vertex.The graph does not have any self-loops or multiple edges.
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; 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); d1093 solver = new d1093(); int testCount = Integer.parseInt(in.next()); for (int i = 1; i <= testCount; i++) solver.solve(i, in, out); out.close(); } static class d1093 { int mod = 998244353; int even1; int odd1; int even2; int odd2; ArrayList<edge> chkEdges = new ArrayList<>(); public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int m = in.nextInt(); node[] nodes = new node[n + 1]; ArrayList<edge> edges = new ArrayList<>(); for (int i = 0; i < m; i++) { int u = in.nextInt(); int v = in.nextInt(); edge e = new edge(); if (nodes[u] == null) { nodes[u] = new node(); } if (nodes[v] == null) { nodes[v] = new node(); } e.u = nodes[u]; e.v = nodes[v]; edges.add(e); nodes[u].edges.add(e); nodes[v].edges.add(e); } int nullNode = 0; long ans = 1; for (int nNode = 1; nNode <= n; nNode++) { if (nodes[nNode] == null) { nullNode++; continue; } if (!nodes[nNode].used) { even1 = 1; odd1 = 0; even2 = 0; odd2 = 1; nodes[nNode].val1 = 0; nodes[nNode].val2 = 1; chkEdges.clear(); dfs(nodes[nNode]); boolean err1 = false, err2 = false; for (edge curEdge : chkEdges) { if ((curEdge.u.val1 + curEdge.v.val1) % 2 == 0) { err1 = true; } if ((curEdge.u.val2 + curEdge.v.val2) % 2 == 0) { err2 = true; } } if (err1 && err2) { out.println(0); return; } long curAns = 0; if (!err1) { curAns = pow(2, odd1); } if (!err2) { curAns += pow(2, odd2); } ans = (ans * curAns) % mod; } } out.println((ans * pow(3, nullNode) % mod)); } void dfs(node n) { n.used = true; for (edge e : n.edges) { if (e.u == n) { chkEdges.add(e); if (!e.v.used) { e.v.val1 = 1 - n.val1; if (e.v.val1 == 0) { even1++; } else { odd1++; } e.v.val2 = 1 - n.val2; if (e.v.val2 == 0) { even2++; } else { odd2++; } dfs(e.v); } } if (e.v == n) { if (!e.u.used) { e.u.val1 = 1 - n.val1; if (e.u.val1 == 0) { even1++; } else { odd1++; } e.u.val2 = 1 - n.val2; if (e.u.val2 == 0) { even2++; } else { odd2++; } dfs(e.u); } } } } long pow(long a, long n) { if (n == 0) return 1; if (n == 1) return a; long tmp = pow(a, n / 2); if (n % 2 == 0) return (tmp * tmp) % mod; return (((tmp * tmp) % mod) * a) % mod; } class node { int val1; int val2; boolean used; ArrayList<edge> edges = new ArrayList<>(); } class edge { node u; node v; } } static class InputReader { private BufferedReader reader; private StringTokenizer stt; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); } public String nextLine() { try { return reader.readLine(); } catch (IOException e) { return null; } } public String next() { while (stt == null || !stt.hasMoreTokens()) { stt = new StringTokenizer(nextLine()); } return stt.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["2\n2 1\n1 2\n4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4"]
2 seconds
["4\n0"]
NotePossible ways to distribute numbers in the first test: the vertex $$$1$$$ should contain $$$1$$$, and $$$2$$$ should contain $$$2$$$; the vertex $$$1$$$ should contain $$$3$$$, and $$$2$$$ should contain $$$2$$$; the vertex $$$1$$$ should contain $$$2$$$, and $$$2$$$ should contain $$$1$$$; the vertex $$$1$$$ should contain $$$2$$$, and $$$2$$$ should contain $$$3$$$. In the second test there is no way to distribute numbers.
Java 8
standard input
[ "dfs and similar", "graphs" ]
332340a793eb3ec14131948e2b6bdf2f
The first line contains one integer $$$t$$$ ($$$1 \le t \le 3 \cdot 10^5$$$) β€” the number of tests in the input. The first line of each test contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5, 0 \le m \le 3 \cdot 10^5$$$) β€” the number of vertices and the number of edges, respectively. Next $$$m$$$ lines describe edges: $$$i$$$-th line contains two integers $$$u_i$$$, $$$ v_i$$$ ($$$1 \le u_i, v_i \le n; u_i \neq v_i$$$) β€” indices of vertices connected by $$$i$$$-th edge. It is guaranteed that $$$\sum\limits_{i=1}^{t} n \le 3 \cdot 10^5$$$ and $$$\sum\limits_{i=1}^{t} m \le 3 \cdot 10^5$$$.
1,700
For each test print one line, containing one integer β€” the number of possible ways to write numbers $$$1$$$, $$$2$$$, $$$3$$$ on the vertices of given graph so it becomes beautiful. Since answers may be large, print them modulo $$$998244353$$$.
standard output
PASSED
49d0c4e6f22bae600e89025138afd7e6
train_000.jsonl
1544884500
You are given an undirected unweighted graph consisting of $$$n$$$ vertices and $$$m$$$ edges.You have to write a number on each vertex of the graph. Each number should be $$$1$$$, $$$2$$$ or $$$3$$$. The graph becomes beautiful if for each edge the sum of numbers on vertices connected by this edge is odd.Calculate the number of possible ways to write numbers $$$1$$$, $$$2$$$ and $$$3$$$ on vertices so the graph becomes beautiful. Since this number may be large, print it modulo $$$998244353$$$.Note that you have to write exactly one number on each vertex.The graph does not have any self-loops or multiple edges.
256 megabytes
import java.io.*; import java.util.*; import java.text.*; import java.lang.*; import java.lang.reflect.Array; import java.math.BigInteger; import java.util.regex.*; public class Main { public static ArrayList a[]=new ArrayList[300001]; static boolean visited[]; static Vector<Integer>id=new Vector<>(); static long value[][]=new long[3000001][2]; static void dfs(int n) { visited[n]=true; id.add(n); for(int i=0;i<a[n].size();i++) { visited[n]=true; int idx=(int) a[n].get(i); if(!visited[idx]) { value[idx][0]=(value[n][0]==1?2:1); value[idx][1]=(value[n][1]==1?2:1); dfs(idx); } } } static pair chk() { mod=998244353; pair p=new pair(1L,1L); for(int i=0;i<id.size();i++) { boolean chk=false; for(int j=0;j<a[id.get(i)].size();j++) { int idx=(int) a[id.get(i)].get(j); if(value[id.get(i)][0]==value[idx][0] || value[id.get(i)][1]==value[idx][1]) { chk=true; } } //debug(chk); if(chk) { id.clear(); return new pair(0L,0L); } p.x=(p.x*value[id.get(i)][0])%mod; p.y=(p.y*value[id.get(i)][1])%mod; } id.clear(); return p; } public static void main(String[] args) { InputReader in = new InputReader(System.in); PrintWriter pw = new PrintWriter(System.out); int t=in.nextInt(); while(t-->0) { int n=in.nextInt(); int m=in.nextInt(); visited=new boolean [n+1]; for(int i=0;i<=n;i++) { a[i]=new ArrayList<Integer>(); } for(int i=0;i<m;i++) { int x=in.nextInt(); int y=in.nextInt(); a[x].add(y); a[y].add(x); } long part[][]=new long[n][2]; int idx=0; for(int i=1;i<=n;i++) { if(!visited[i]) { value[i][0]=1; value[i][1]=2; dfs(i); pair p=chk(); part[idx][0]=p.x; part[idx][1]=p.y; idx++; } } long ans=0L; long start=part[0][0]; long start1=0L; for(int i=1;i<idx;i++) { start1=(start1+((start)*(part[i][0]))%mod)%mod; start1=(start1+((start)*(part[i][1]))%mod)%mod; start=start1; start1=0L; } long x=start; start=part[0][1]; start1=0L; for(int i=1;i<idx;i++) { start1=(start1+((start)*(part[i][0]))%mod)%mod; start1=(start1+((start)*(part[i][1]))%mod)%mod; start=start1; start1=0L; } x=(x+start)%mod; pw.println(x); } pw.flush(); pw.close(); } private static void debug(Object... o) { System.out.println(Arrays.deepToString(o)); } 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 y1,long y2) { this.x=y1; this.y=y2; } 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
["2\n2 1\n1 2\n4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4"]
2 seconds
["4\n0"]
NotePossible ways to distribute numbers in the first test: the vertex $$$1$$$ should contain $$$1$$$, and $$$2$$$ should contain $$$2$$$; the vertex $$$1$$$ should contain $$$3$$$, and $$$2$$$ should contain $$$2$$$; the vertex $$$1$$$ should contain $$$2$$$, and $$$2$$$ should contain $$$1$$$; the vertex $$$1$$$ should contain $$$2$$$, and $$$2$$$ should contain $$$3$$$. In the second test there is no way to distribute numbers.
Java 8
standard input
[ "dfs and similar", "graphs" ]
332340a793eb3ec14131948e2b6bdf2f
The first line contains one integer $$$t$$$ ($$$1 \le t \le 3 \cdot 10^5$$$) β€” the number of tests in the input. The first line of each test contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5, 0 \le m \le 3 \cdot 10^5$$$) β€” the number of vertices and the number of edges, respectively. Next $$$m$$$ lines describe edges: $$$i$$$-th line contains two integers $$$u_i$$$, $$$ v_i$$$ ($$$1 \le u_i, v_i \le n; u_i \neq v_i$$$) β€” indices of vertices connected by $$$i$$$-th edge. It is guaranteed that $$$\sum\limits_{i=1}^{t} n \le 3 \cdot 10^5$$$ and $$$\sum\limits_{i=1}^{t} m \le 3 \cdot 10^5$$$.
1,700
For each test print one line, containing one integer β€” the number of possible ways to write numbers $$$1$$$, $$$2$$$, $$$3$$$ on the vertices of given graph so it becomes beautiful. Since answers may be large, print them modulo $$$998244353$$$.
standard output
PASSED
291a086afc25f1bb88654a419a01204b
train_000.jsonl
1544884500
You are given an undirected unweighted graph consisting of $$$n$$$ vertices and $$$m$$$ edges.You have to write a number on each vertex of the graph. Each number should be $$$1$$$, $$$2$$$ or $$$3$$$. The graph becomes beautiful if for each edge the sum of numbers on vertices connected by this edge is odd.Calculate the number of possible ways to write numbers $$$1$$$, $$$2$$$ and $$$3$$$ on vertices so the graph becomes beautiful. Since this number may be large, print it modulo $$$998244353$$$.Note that you have to write exactly one number on each vertex.The graph does not have any self-loops or multiple edges.
256 megabytes
import java.io.*; import java.util.*; @SuppressWarnings("unchecked") public class C{ static int maxN=300000; static List<Integer>[] g; static int[] color,count; public static long power(long a,int n){ long res=1; while(n>0){ if(n%2==1){ res=(res*a)%M; } n>>=1; a=(a*a)%M; } return res; } public static boolean dfs(int i,int c){ color[i]=c; count[c]++; // System.out.println("dfs "+i+","+c); for(int to : g[i]){ if(color[to]==-1){ // System.out.println("to "+to); if(!dfs(to,c^1)) return false; }else if(color[i]==color[to]) return false; } return true; } public static void main(String args[])throws IOException{ PrintWriter out =new PrintWriter(System.out); int t=sc.nextInt(); g = new ArrayList[maxN+1]; color = new int[maxN+1]; count = new int[2]; for(int i=0;i<=maxN;i++) g[i] = new ArrayList<>(); while(t-->0){ int n,m,a,b; n=sc.nextInt(); m=sc.nextInt(); for(int i=0;i<n;i++){ g[i].clear(); color[i]=-1; } for(int i=0;i<m;i++){ a=sc.nextInt()-1; b=sc.nextInt()-1; g[a].add(b); g[b].add(a); } boolean valid=true; long res=1; for(int i=0;i<n && valid;i++){ if(color[i]==-1){ count[0]=0;count[1]=0; // odd - 0, even - 1 valid = dfs(i,0); // System.out.println(count[0]+","+count[1]); res = (res*(power(2,count[0])+power(2,count[1])))%M; } } if(valid) out.println(res); else out.println(0); } out.close(); } static int M=998244353; static class Pair{ int p1,p2; Pair(int p1,int p2){ this.p1=p1; this.p2=p2; } } static FastScanner sc = new FastScanner(); static class FastScanner { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readArray(int n) { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } long nextLong() { return Long.parseLong(next()); } public long[] readLongArray(int n) { long[] a=new long[n]; for (int i=0; i<n; i++) a[i]=nextLong(); return a; } } }
Java
["2\n2 1\n1 2\n4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4"]
2 seconds
["4\n0"]
NotePossible ways to distribute numbers in the first test: the vertex $$$1$$$ should contain $$$1$$$, and $$$2$$$ should contain $$$2$$$; the vertex $$$1$$$ should contain $$$3$$$, and $$$2$$$ should contain $$$2$$$; the vertex $$$1$$$ should contain $$$2$$$, and $$$2$$$ should contain $$$1$$$; the vertex $$$1$$$ should contain $$$2$$$, and $$$2$$$ should contain $$$3$$$. In the second test there is no way to distribute numbers.
Java 8
standard input
[ "dfs and similar", "graphs" ]
332340a793eb3ec14131948e2b6bdf2f
The first line contains one integer $$$t$$$ ($$$1 \le t \le 3 \cdot 10^5$$$) β€” the number of tests in the input. The first line of each test contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5, 0 \le m \le 3 \cdot 10^5$$$) β€” the number of vertices and the number of edges, respectively. Next $$$m$$$ lines describe edges: $$$i$$$-th line contains two integers $$$u_i$$$, $$$ v_i$$$ ($$$1 \le u_i, v_i \le n; u_i \neq v_i$$$) β€” indices of vertices connected by $$$i$$$-th edge. It is guaranteed that $$$\sum\limits_{i=1}^{t} n \le 3 \cdot 10^5$$$ and $$$\sum\limits_{i=1}^{t} m \le 3 \cdot 10^5$$$.
1,700
For each test print one line, containing one integer β€” the number of possible ways to write numbers $$$1$$$, $$$2$$$, $$$3$$$ on the vertices of given graph so it becomes beautiful. Since answers may be large, print them modulo $$$998244353$$$.
standard output
PASSED
7309b76a232c2ab68707054a6d1cbfed
train_000.jsonl
1544884500
You are given an undirected unweighted graph consisting of $$$n$$$ vertices and $$$m$$$ edges.You have to write a number on each vertex of the graph. Each number should be $$$1$$$, $$$2$$$ or $$$3$$$. The graph becomes beautiful if for each edge the sum of numbers on vertices connected by this edge is odd.Calculate the number of possible ways to write numbers $$$1$$$, $$$2$$$ and $$$3$$$ on vertices so the graph becomes beautiful. Since this number may be large, print it modulo $$$998244353$$$.Note that you have to write exactly one number on each vertex.The graph does not have any self-loops or multiple edges.
256 megabytes
// Author @ BlackRise :) // // Birla Institute of Technology, Mesra// import java.io.*; import java.util.*; public class beautifulGraph { static int b=0,sz=0; static int mod=998244353; static long power[]=new long[4*100005]; static long ans = 1; static void Blackrise() { //The name Blackrise is my pen name... you can change the name according to your wish int t = ni(); tsc(); //calculates the starting time of execution power[0]=1; for(int i=1;i<4*100005;i++) power[i]=(power[i-1]*2)%mod; while (t-- > 0) {ans=1; int n = ni(); int m = ni(); ArrayList<Integer> ar[] = new ArrayList[n + 1]; int color[] = new int[n + 1]; Arrays.fill(color, -1); for (int i = 0; i <= n; i++) ar[i] = new ArrayList<>(); for (int i = 0; i < m; i++) { int x = ni(); int y = ni(); ar[x].add(y); ar[y].add(x); } for (int i = 1; i < n + 1; i++) { if (color[i] == -1) { b = sz = 0; color[i] = 0; dfs(i,color,ar); ans = ans * (power[b] + power[sz - b]) % mod; } } pl(ans); } tec(); //calculates the ending time of execution //pwt(); //prints the time taken to execute the program } static void dfs(int i,int color[],ArrayList<Integer> ar[]) { sz++;b+=color[i]; for(int x:ar[i]) { if(color[x]==-1) { color[x]=color[i]^1; dfs(x,color,ar); } else if(color[i]==color[x])ans=0; } } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// static Calendar ts, te; //For time calculation static int mod9 = (int) 1e9 + 7; static Lelo input = new Lelo(System.in); static PrintWriter pw = new PrintWriter(System.out, true); public static void main(String[] args) { //threading has been used to increase the stack size. new Thread(null, null, "BlackRise", 1<<25) //the last parameter is stack size which is desired, { public void run() { try { Blackrise(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } }.start(); } static class Lelo { //Lelo class for fast input private InputStream ayega; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public Lelo(InputStream ayega) { this.ayega = ayega; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = ayega.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public double nextDouble() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } double res = 0; while (!isSpaceChar(c) && c != '.') { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } if (c == '.') { c = read(); double m = 1; while (!isSpaceChar(c)) { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return readString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } // functions to take input// static int ni() { return input.nextInt(); } static long nl() { return input.nextLong(); } static double nd() { return input.nextDouble(); } static String ns() { return input.readString(); } //functions to give output static void pl() { pw.println(); } static void p(Object o) { pw.print(o + " "); } static void pws(Object o){ pw.print(o+""); } static void pl(Object o) { pw.println(o); } static void tsc() //calculates the starting time of execution { ts = Calendar.getInstance(); ts.setTime(new Date()); } static void tec() //calculates the ending time of execution { te = Calendar.getInstance(); te.setTime(new Date()); } static void pwt() //prints the time taken for execution { pw.printf("\nExecution time was :- %f s\n", (te.getTimeInMillis() - ts.getTimeInMillis()) / 1000.00); } }
Java
["2\n2 1\n1 2\n4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4"]
2 seconds
["4\n0"]
NotePossible ways to distribute numbers in the first test: the vertex $$$1$$$ should contain $$$1$$$, and $$$2$$$ should contain $$$2$$$; the vertex $$$1$$$ should contain $$$3$$$, and $$$2$$$ should contain $$$2$$$; the vertex $$$1$$$ should contain $$$2$$$, and $$$2$$$ should contain $$$1$$$; the vertex $$$1$$$ should contain $$$2$$$, and $$$2$$$ should contain $$$3$$$. In the second test there is no way to distribute numbers.
Java 8
standard input
[ "dfs and similar", "graphs" ]
332340a793eb3ec14131948e2b6bdf2f
The first line contains one integer $$$t$$$ ($$$1 \le t \le 3 \cdot 10^5$$$) β€” the number of tests in the input. The first line of each test contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5, 0 \le m \le 3 \cdot 10^5$$$) β€” the number of vertices and the number of edges, respectively. Next $$$m$$$ lines describe edges: $$$i$$$-th line contains two integers $$$u_i$$$, $$$ v_i$$$ ($$$1 \le u_i, v_i \le n; u_i \neq v_i$$$) β€” indices of vertices connected by $$$i$$$-th edge. It is guaranteed that $$$\sum\limits_{i=1}^{t} n \le 3 \cdot 10^5$$$ and $$$\sum\limits_{i=1}^{t} m \le 3 \cdot 10^5$$$.
1,700
For each test print one line, containing one integer β€” the number of possible ways to write numbers $$$1$$$, $$$2$$$, $$$3$$$ on the vertices of given graph so it becomes beautiful. Since answers may be large, print them modulo $$$998244353$$$.
standard output
PASSED
d026dc24f80d51afc54a93b58bf105ac
train_000.jsonl
1544884500
You are given an undirected unweighted graph consisting of $$$n$$$ vertices and $$$m$$$ edges.You have to write a number on each vertex of the graph. Each number should be $$$1$$$, $$$2$$$ or $$$3$$$. The graph becomes beautiful if for each edge the sum of numbers on vertices connected by this edge is odd.Calculate the number of possible ways to write numbers $$$1$$$, $$$2$$$ and $$$3$$$ on vertices so the graph becomes beautiful. Since this number may be large, print it modulo $$$998244353$$$.Note that you have to write exactly one number on each vertex.The graph does not have any self-loops or multiple edges.
256 megabytes
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.math.BigInteger; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import static java.util.Collections.list; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.PriorityQueue; import java.util.Random; import java.util.Stack; import java.util.stream.IntStream; import java.util.stream.Stream; public class Main { private static int[] solve() { int[] dp = new int[101]; for(int i=2;i<=7;i++) dp[i]=1; for(int i=8;i<=100;i++) { for(int j=i-1;j>=0;j--) { if(dp[j]>0 && dp[i-j]>0) { dp[i]=dp[j]+dp[i-j]; break; } } } return dp; } private static long[] solve2(int n, long[] b) throws Exception { long[] a = new long[n+1]; a[1]=0; a[n]=b[1]; for(int i=2;i<=n/2;i++) { long x = a[i-1]; long y = b[i]-x; if(b[i] > a[n-i+2] && y > a[n-i+2]) { x += y-a[n-i+2]; y = b[i]-x; } a[i]=x; a[n-i+1]=y; } return a; } public static void main(String[] args) throws IOException, Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); int T = Integer.parseInt(br.readLine()); final int MOD = 998244353 ; while(T-->0) { String[] in = br.readLine().split(" "); int n = Integer.parseInt(in[0]); int m = Integer.parseInt(in[1]); //if m is zero append 0- and continue List<List<Integer>> G = new ArrayList<>(n); // a static graph of size n for(int i=0;i<n;i++) G.add(new ArrayList<>()); for(int i=0;i<m;i++) { in=br.readLine().split(" "); int x = Integer.parseInt(in[0]); int y = Integer.parseInt(in[1]); x--;y--; G.get(x).add(y); G.get(y).add(x); //undirected graph } if( m == 0) { bw.append(binpow(3, n, MOD)+"\n"); continue; } long val = solve3(G, n, m); bw.append(val+"\n"); } bw.close(); } private static int solve3(List<List<Integer>> G, int n, int m) throws Exception { final int MOD = 998244353 ; long ret = 1; int[] v = new int[n]; int[] d = new int[n]; Arrays.fill(d, -1); boolean ans = true; for(int i=0;i<n;i++) { if(v[i]==0) { d[i]=0; List<Integer> A = new ArrayList<>(); ans = dfs(G, v, d, A, i); if(!ans) break; int r = 0; for(Integer g : A) { if(d[g]==1) r++; } long cur = (binpow(2, r, MOD) + binpow(2, A.size()-r,MOD))%MOD; ret*=cur; ret%=MOD; } } if(!ans) return 0; return (int) (ret%MOD); } private static long mult(long a, long b, int MOD) { if(a==1) return b%MOD; if(b==1) return a%MOD; if(a%2==0) return 2l*mult(a/2,b,MOD)%MOD; return (2l*mult((a-1)/2, b,MOD)%MOD + b)%MOD; } private static long binpow(int a, int n, int MOD) { if (n == 0) return 1; if (n == 1) return a % MOD; long half = binpow(a, n / 2, MOD); if (n % 2 == 0) { return half * half % MOD; } half = (half * half) % MOD; return (a * half) % MOD; } private static boolean dfs(List<List<Integer>> G, int[] v, int[] d, List<Integer> A, int u) { v[u]=1; A.add(u); for(Integer g : G.get(u)){ if(v[g]==0) { d[g]=d[u]==0?1:0; boolean ans = dfs(G,v,d,A,g); if(!ans) return false; } else if(d[u]==d[g]) return false; } return true; } }
Java
["2\n2 1\n1 2\n4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4"]
2 seconds
["4\n0"]
NotePossible ways to distribute numbers in the first test: the vertex $$$1$$$ should contain $$$1$$$, and $$$2$$$ should contain $$$2$$$; the vertex $$$1$$$ should contain $$$3$$$, and $$$2$$$ should contain $$$2$$$; the vertex $$$1$$$ should contain $$$2$$$, and $$$2$$$ should contain $$$1$$$; the vertex $$$1$$$ should contain $$$2$$$, and $$$2$$$ should contain $$$3$$$. In the second test there is no way to distribute numbers.
Java 8
standard input
[ "dfs and similar", "graphs" ]
332340a793eb3ec14131948e2b6bdf2f
The first line contains one integer $$$t$$$ ($$$1 \le t \le 3 \cdot 10^5$$$) β€” the number of tests in the input. The first line of each test contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5, 0 \le m \le 3 \cdot 10^5$$$) β€” the number of vertices and the number of edges, respectively. Next $$$m$$$ lines describe edges: $$$i$$$-th line contains two integers $$$u_i$$$, $$$ v_i$$$ ($$$1 \le u_i, v_i \le n; u_i \neq v_i$$$) β€” indices of vertices connected by $$$i$$$-th edge. It is guaranteed that $$$\sum\limits_{i=1}^{t} n \le 3 \cdot 10^5$$$ and $$$\sum\limits_{i=1}^{t} m \le 3 \cdot 10^5$$$.
1,700
For each test print one line, containing one integer β€” the number of possible ways to write numbers $$$1$$$, $$$2$$$, $$$3$$$ on the vertices of given graph so it becomes beautiful. Since answers may be large, print them modulo $$$998244353$$$.
standard output
PASSED
a9bef1da8ab795629bd2a6a930288e43
train_000.jsonl
1544884500
You are given an undirected unweighted graph consisting of $$$n$$$ vertices and $$$m$$$ edges.You have to write a number on each vertex of the graph. Each number should be $$$1$$$, $$$2$$$ or $$$3$$$. The graph becomes beautiful if for each edge the sum of numbers on vertices connected by this edge is odd.Calculate the number of possible ways to write numbers $$$1$$$, $$$2$$$ and $$$3$$$ on vertices so the graph becomes beautiful. Since this number may be large, print it modulo $$$998244353$$$.Note that you have to write exactly one number on each vertex.The graph does not have any self-loops or multiple edges.
256 megabytes
import java.io.*; import java.util.*; public class BeautifulGraph { public static void main (String[] args) throws IOException{ BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); int T = Integer.parseInt(in.readLine()); StringBuilder sb = new StringBuilder(); for (int t = 0; t < T; t++) { StringTokenizer st = new StringTokenizer(in.readLine()); int n = Integer.parseInt(st.nextToken()); int m = Integer.parseInt(st.nextToken()); Node graph [] = new Node [n]; long pow2 [] = new long [n + 1]; pow2[0] = 1; for (int i = 0; i < n; i++) { graph[i] = new Node(); pow2[i+1] = (pow2[i] * 2) % 998244353; } for (int i = 0; i < m; i++) { st = new StringTokenizer(in.readLine()); int a = Integer.parseInt(st.nextToken()) -1; int b = Integer.parseInt(st.nextToken()) -1; graph[b].con.add(graph[a]); graph[a].con.add(graph[b]); } long ans = 1; for (int i = 0; i < n; i++) { if (graph[i].parity == -1) { int cnt [] = new int [2]; if (!dfs(graph[i], 0, cnt)) {ans = 0; break;} ans = (ans * ((pow2[cnt[0]] + pow2[cnt[1]]) % 998244353)) % 998244353; } } sb.append(ans + "\n"); } System.out.println(sb); } public static boolean dfs (Node j, int par, int cnt []) { j.parity = par; cnt[par]++; for (Node n: j.con) { if (n.parity == -1 && !dfs(n, (par + 1) % 2, cnt)) return false; else if (n.parity == par) return false; } return true; } static class Node { int parity = -1; ArrayList<Node> con = new ArrayList<Node>(); } }
Java
["2\n2 1\n1 2\n4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4"]
2 seconds
["4\n0"]
NotePossible ways to distribute numbers in the first test: the vertex $$$1$$$ should contain $$$1$$$, and $$$2$$$ should contain $$$2$$$; the vertex $$$1$$$ should contain $$$3$$$, and $$$2$$$ should contain $$$2$$$; the vertex $$$1$$$ should contain $$$2$$$, and $$$2$$$ should contain $$$1$$$; the vertex $$$1$$$ should contain $$$2$$$, and $$$2$$$ should contain $$$3$$$. In the second test there is no way to distribute numbers.
Java 8
standard input
[ "dfs and similar", "graphs" ]
332340a793eb3ec14131948e2b6bdf2f
The first line contains one integer $$$t$$$ ($$$1 \le t \le 3 \cdot 10^5$$$) β€” the number of tests in the input. The first line of each test contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5, 0 \le m \le 3 \cdot 10^5$$$) β€” the number of vertices and the number of edges, respectively. Next $$$m$$$ lines describe edges: $$$i$$$-th line contains two integers $$$u_i$$$, $$$ v_i$$$ ($$$1 \le u_i, v_i \le n; u_i \neq v_i$$$) β€” indices of vertices connected by $$$i$$$-th edge. It is guaranteed that $$$\sum\limits_{i=1}^{t} n \le 3 \cdot 10^5$$$ and $$$\sum\limits_{i=1}^{t} m \le 3 \cdot 10^5$$$.
1,700
For each test print one line, containing one integer β€” the number of possible ways to write numbers $$$1$$$, $$$2$$$, $$$3$$$ on the vertices of given graph so it becomes beautiful. Since answers may be large, print them modulo $$$998244353$$$.
standard output
PASSED
530071640603f1880d24ee298ba19867
train_000.jsonl
1544884500
You are given an undirected unweighted graph consisting of $$$n$$$ vertices and $$$m$$$ edges.You have to write a number on each vertex of the graph. Each number should be $$$1$$$, $$$2$$$ or $$$3$$$. The graph becomes beautiful if for each edge the sum of numbers on vertices connected by this edge is odd.Calculate the number of possible ways to write numbers $$$1$$$, $$$2$$$ and $$$3$$$ on vertices so the graph becomes beautiful. Since this number may be large, print it modulo $$$998244353$$$.Note that you have to write exactly one number on each vertex.The graph does not have any self-loops or multiple edges.
256 megabytes
import java.util.*; import java.io.*; //import javafx.util.Pair; public class Main implements Runnable { static class Pair implements Comparable <Pair> { int x,y,wt; Pair(int x,int y,int wt) { this.x=x; this.y=y; this.wt=wt; } /*public boolean equals(Object obj) { if(obj==null) return false; if(obj==this) return true; if(!(obj instanceof Pair)) return false; Pair o=(Pair) obj; return o.x==this.x && o.y==this.y; } public int hashCode() { return this.x+this.y; }*/ public int compareTo(Pair p) { return Integer.compare(wt,p.wt); } } public static void main(String[] args) { new Thread(null, new Main(), "rev", 1 << 29).start(); } public void run() { InputStream inputStream=System.in; OutputStream outputStream=System.out; InputReader in=new InputReader(inputStream); PrintWriter out=new PrintWriter(outputStream); Task solver=new Task(); solver.solve(1,in,out); out.close(); } static class Task { ArrayList <Integer>adj[]; boolean []vis; int mod=998244353,n; int []col; Queue <Integer> q=new LinkedList<>(); long pow(long x,long y) { long l=1; while(y>0) { if(y%2==1) l=(l*x)%mod; y>>=1; x=(x*x)%mod; } return l; } boolean check() { for(int i=1;i<=n;i++) if(!vis[i]) if(!dfs(i,1)) return false; return true; } boolean dfs(int s,int c) { vis[s]=true; col[s]=c; for(int i:adj[s]) { if(!vis[i]) { if(!dfs(i,1^c)) return false; } else if(col[i]==col[s]) return false; } return true; } long bfs(int i) { vis[i]=true; q.add(i); q.add(-1); int ct1=0,ct2=0,x; long sum1=1,sum2=1; while(!q.isEmpty()) { x=q.poll(); if(x!=-1) ct1++; if(x==-1) { ct2++; if(ct2%2==1) sum1=(sum1*pow(2,ct1))%mod; else sum2=(sum2*pow(2,ct1))%mod; ct1=0; if(q.isEmpty()) break; q.add(-1); continue; } for(int y:adj[x]) if(!vis[y]) { vis[y]=true; q.add(y); } } return (sum1+sum2)%mod; } void solve(int testNumber, InputReader in, PrintWriter out) { int t=in.nextInt(),m,x,y; long ans; while(t-->0) { n=in.nextInt(); m=in.nextInt(); adj=new ArrayList[n+1]; for(int i=1;i<=n;i++) adj[i]=new ArrayList<>(); vis=new boolean[n+1]; col=new int[n+1]; while(m-->0) { x=in.nextInt(); y=in.nextInt(); adj[x].add(y); adj[y].add(x); } if(!check()) { out.println("0"); continue; } Arrays.fill(vis,false); ans=1; for(int i=1;i<=n;i++) if(!vis[i]) ans=(ans*bfs(i))%mod; out.println(ans); } } } static class InputReader { private InputStream stream; private byte[] buf=new byte[8192]; private int curChar,snumChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream=stream; } public int snext() { if(snumChars==-1) throw new InputMismatchException(); if(curChar>=snumChars) { curChar=0; try { snumChars=stream.read(buf); } catch(IOException e) { throw new InputMismatchException(); } if(snumChars<=0) return -1; } return buf[curChar++]; } public int nextInt() { int c=snext(); while(isSpaceChar(c)) c=snext(); int sgn=1; if(c=='-') { sgn=-1; c=snext(); } int res=0; do { if(c<'0'||c>'9') throw new InputMismatchException(); res*=10; res+=c-'0'; c=snext(); }while(!isSpaceChar(c)); return res*sgn; } public long nextLong() { int c=snext(); while(isSpaceChar(c)) c=snext(); int sgn=1; if(c=='-') { sgn=-1; c=snext(); } long res=0; do{ if (c<'0' || c>'9') throw new InputMismatchException(); res*=10; res+=c-'0'; c=snext(); }while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int a[]=new int[n]; for(int i=0;i<n;i++) a[i]=nextInt(); return a; } public long[] nextLongArray(int n) { long a[]=new long[n]; for(int i=0;i<n;i++) a[i]=nextLong(); return a; } public String nextString() { 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 boolean isSpaceChar(int c) { if(filter != null) return filter.isSpaceChar(c); return c==' ' || c=='\n' || c=='\r' || c=='\t' || c==-1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["2\n2 1\n1 2\n4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4"]
2 seconds
["4\n0"]
NotePossible ways to distribute numbers in the first test: the vertex $$$1$$$ should contain $$$1$$$, and $$$2$$$ should contain $$$2$$$; the vertex $$$1$$$ should contain $$$3$$$, and $$$2$$$ should contain $$$2$$$; the vertex $$$1$$$ should contain $$$2$$$, and $$$2$$$ should contain $$$1$$$; the vertex $$$1$$$ should contain $$$2$$$, and $$$2$$$ should contain $$$3$$$. In the second test there is no way to distribute numbers.
Java 8
standard input
[ "dfs and similar", "graphs" ]
332340a793eb3ec14131948e2b6bdf2f
The first line contains one integer $$$t$$$ ($$$1 \le t \le 3 \cdot 10^5$$$) β€” the number of tests in the input. The first line of each test contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5, 0 \le m \le 3 \cdot 10^5$$$) β€” the number of vertices and the number of edges, respectively. Next $$$m$$$ lines describe edges: $$$i$$$-th line contains two integers $$$u_i$$$, $$$ v_i$$$ ($$$1 \le u_i, v_i \le n; u_i \neq v_i$$$) β€” indices of vertices connected by $$$i$$$-th edge. It is guaranteed that $$$\sum\limits_{i=1}^{t} n \le 3 \cdot 10^5$$$ and $$$\sum\limits_{i=1}^{t} m \le 3 \cdot 10^5$$$.
1,700
For each test print one line, containing one integer β€” the number of possible ways to write numbers $$$1$$$, $$$2$$$, $$$3$$$ on the vertices of given graph so it becomes beautiful. Since answers may be large, print them modulo $$$998244353$$$.
standard output
PASSED
4ba82f71f179400eafa07fab1b378988
train_000.jsonl
1544884500
You are given an undirected unweighted graph consisting of $$$n$$$ vertices and $$$m$$$ edges.You have to write a number on each vertex of the graph. Each number should be $$$1$$$, $$$2$$$ or $$$3$$$. The graph becomes beautiful if for each edge the sum of numbers on vertices connected by this edge is odd.Calculate the number of possible ways to write numbers $$$1$$$, $$$2$$$ and $$$3$$$ on vertices so the graph becomes beautiful. Since this number may be large, print it modulo $$$998244353$$$.Note that you have to write exactly one number on each vertex.The graph does not have any self-loops or multiple edges.
256 megabytes
import java.util.*; import java.math.*; import java.io.*; public class CF1093D { class Graph { int n, ones, zeros; List<Integer>[] adj; public Graph(int nn) { adj = new ArrayList[n = nn]; for(int i = 0 ; i < n ; i++) adj[i] = new ArrayList<>(); } void add(int u, int v) { adj[u].add(v); adj[v].add(u); } long solve() { long res = 1; Deque<Integer> q = new ArrayDeque<>(); int[] color = new int[n]; Arrays.fill(color, -1); for(int i = 0 ; i < n ; i++) { if(color[i] == -1) { ones = 0; zeros = 0; q.add(i); q.add(0); color[i] = 0; while(!q.isEmpty()) { int u = q.pop(), c = q.pop(); if(c == 1) ones++; else zeros++; for(int v : adj[u]) { if(color[v] == -1) { color[v] = c ^ 1; q.add(v); q.add(c ^ 1); } else if(color[v] == color[u]) return 0; } } res = (res * (pow2[ones] + pow2[zeros])) % MOD; } } return res; } } final long[] pow2 = new long[500000]; final int MOD = 998244353; public CF1093D() { FS scan = new FS(); PrintWriter out = new PrintWriter(System.out); pow2[0] = 1; for(int i = 1 ; i < 500000 ; i++) pow2[i] = (pow2[i - 1] << 1) % MOD; int t = scan.nextInt(); for(int tt = 0 ; tt < t ; tt++) { int n = scan.nextInt(), e = scan.nextInt(); Graph g = new Graph(n); for(int i = 0 ; i < e ; i++) { int u = scan.nextInt() - 1, v = scan.nextInt() - 1; g.add(u, v); } out.println(g.solve()); } out.close(); } class FS { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); public String next() { while(!st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch(Exception e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } public static void main(String[] args) { new CF1093D(); } }
Java
["2\n2 1\n1 2\n4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4"]
2 seconds
["4\n0"]
NotePossible ways to distribute numbers in the first test: the vertex $$$1$$$ should contain $$$1$$$, and $$$2$$$ should contain $$$2$$$; the vertex $$$1$$$ should contain $$$3$$$, and $$$2$$$ should contain $$$2$$$; the vertex $$$1$$$ should contain $$$2$$$, and $$$2$$$ should contain $$$1$$$; the vertex $$$1$$$ should contain $$$2$$$, and $$$2$$$ should contain $$$3$$$. In the second test there is no way to distribute numbers.
Java 8
standard input
[ "dfs and similar", "graphs" ]
332340a793eb3ec14131948e2b6bdf2f
The first line contains one integer $$$t$$$ ($$$1 \le t \le 3 \cdot 10^5$$$) β€” the number of tests in the input. The first line of each test contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5, 0 \le m \le 3 \cdot 10^5$$$) β€” the number of vertices and the number of edges, respectively. Next $$$m$$$ lines describe edges: $$$i$$$-th line contains two integers $$$u_i$$$, $$$ v_i$$$ ($$$1 \le u_i, v_i \le n; u_i \neq v_i$$$) β€” indices of vertices connected by $$$i$$$-th edge. It is guaranteed that $$$\sum\limits_{i=1}^{t} n \le 3 \cdot 10^5$$$ and $$$\sum\limits_{i=1}^{t} m \le 3 \cdot 10^5$$$.
1,700
For each test print one line, containing one integer β€” the number of possible ways to write numbers $$$1$$$, $$$2$$$, $$$3$$$ on the vertices of given graph so it becomes beautiful. Since answers may be large, print them modulo $$$998244353$$$.
standard output
PASSED
c9c7c048c1321cd9e4343cc6ffb9c3d6
train_000.jsonl
1544884500
You are given an undirected unweighted graph consisting of $$$n$$$ vertices and $$$m$$$ edges.You have to write a number on each vertex of the graph. Each number should be $$$1$$$, $$$2$$$ or $$$3$$$. The graph becomes beautiful if for each edge the sum of numbers on vertices connected by this edge is odd.Calculate the number of possible ways to write numbers $$$1$$$, $$$2$$$ and $$$3$$$ on vertices so the graph becomes beautiful. Since this number may be large, print it modulo $$$998244353$$$.Note that you have to write exactly one number on each vertex.The graph does not have any self-loops or multiple edges.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.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 real */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } static class TaskD { ArrayList<ArrayList<Integer>> list; long mod = 998244353; int[][] ar; int[] vis; int done = 1; int l1; int l2; public void solve(int testNumber, InputReader in, PrintWriter out) { long pow[] = new long[300000 + 1]; pow[0] = 1; for (int i = 1; i < pow.length; i++) { pow[i] = pow[i - 1] * 2; pow[i] %= mod; } int t = in.nextInt(); while (t > 0) { int n = in.nextInt(); int m = in.nextInt(); list = in.initlist(n); for (int i = 0; i < m; i++) { int u = in.nextInt(); int v = in.nextInt(); list.get(u).add(v); list.get(v).add(u); } done = 1; vis = in.memset(n + 1, -1); ar = in.convertList(list); long ans = 1; for (int i = 1; i <= n; i++) { // done = 1; l1 = 0; l2 = 0; if (vis[i] == -1) { solve(i, 0); // System.out.println(l1+" "+l2); ans = ans * (pow[l1] + pow[l2]); ans = ans % mod; } } if (done == 0) ans = 0; out.println(ans); t--; } } void solve(int curr, int level) { if (vis[curr] != -1) { if (vis[curr] == level) { return; } done = 0; return; } if (level % 2 == 0) l1++; else l2++; if (vis[curr] == -1) vis[curr] = level; for (int x : ar[curr]) { solve(x, (level + 1) % 2); } } } static class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar; private int snumChars; public InputReader(InputStream st) { this.stream = st; } public int read() { //*-*------clare------ //remeber while comparing 2 non primitive data type not to use == //remember Arrays.sort for primitive data has worst time case complexity of 0(n^2) bcoz it uses quick sort //again silly mistakes ,yr kb tk krta rhega ye mistakes //try to write simple codes ,break it into simple things // for test cases make sure println(); ;) //knowledge>rating /* public class Main implements Runnable{ public static void main(String[] args) { new Thread(null,new Main(),"Main",1<<26).start(); } public void run() { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC();//chenge the name of task solver.solve(1, in, out); out.close(); } */ 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 ArrayList<ArrayList<Integer>> initlist(int n) { ArrayList<ArrayList<Integer>> list = new ArrayList<>(); for (int i = 0; i <= n; i++) { list.add(new ArrayList<Integer>()); } return list; } public int[] memset(int n, int val) { int ar[] = new int[n]; Arrays.fill(ar, val); return ar; } public int[][] convertList(ArrayList<ArrayList<Integer>> list) { int arr[][] = new int[list.size()][]; for (int i = 0; i < list.size(); i++) { arr[i] = new int[list.get(i).size()]; for (int j = 0; j < list.get(i).size(); j++) { arr[i][j] = list.get(i).get(j); } } return arr; } public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } }
Java
["2\n2 1\n1 2\n4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4"]
2 seconds
["4\n0"]
NotePossible ways to distribute numbers in the first test: the vertex $$$1$$$ should contain $$$1$$$, and $$$2$$$ should contain $$$2$$$; the vertex $$$1$$$ should contain $$$3$$$, and $$$2$$$ should contain $$$2$$$; the vertex $$$1$$$ should contain $$$2$$$, and $$$2$$$ should contain $$$1$$$; the vertex $$$1$$$ should contain $$$2$$$, and $$$2$$$ should contain $$$3$$$. In the second test there is no way to distribute numbers.
Java 8
standard input
[ "dfs and similar", "graphs" ]
332340a793eb3ec14131948e2b6bdf2f
The first line contains one integer $$$t$$$ ($$$1 \le t \le 3 \cdot 10^5$$$) β€” the number of tests in the input. The first line of each test contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5, 0 \le m \le 3 \cdot 10^5$$$) β€” the number of vertices and the number of edges, respectively. Next $$$m$$$ lines describe edges: $$$i$$$-th line contains two integers $$$u_i$$$, $$$ v_i$$$ ($$$1 \le u_i, v_i \le n; u_i \neq v_i$$$) β€” indices of vertices connected by $$$i$$$-th edge. It is guaranteed that $$$\sum\limits_{i=1}^{t} n \le 3 \cdot 10^5$$$ and $$$\sum\limits_{i=1}^{t} m \le 3 \cdot 10^5$$$.
1,700
For each test print one line, containing one integer β€” the number of possible ways to write numbers $$$1$$$, $$$2$$$, $$$3$$$ on the vertices of given graph so it becomes beautiful. Since answers may be large, print them modulo $$$998244353$$$.
standard output
PASSED
49b9ca7442df4117a9ced84e8a0f97e5
train_000.jsonl
1544884500
You are given an undirected unweighted graph consisting of $$$n$$$ vertices and $$$m$$$ edges.You have to write a number on each vertex of the graph. Each number should be $$$1$$$, $$$2$$$ or $$$3$$$. The graph becomes beautiful if for each edge the sum of numbers on vertices connected by this edge is odd.Calculate the number of possible ways to write numbers $$$1$$$, $$$2$$$ and $$$3$$$ on vertices so the graph becomes beautiful. Since this number may be large, print it modulo $$$998244353$$$.Note that you have to write exactly one number on each vertex.The graph does not have any self-loops or multiple edges.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class Main { private FastScanner scanner = new FastScanner(); public static void main(String[] args) { new Main().solve(); } List<List<Integer>> gr = new ArrayList<>(); private void solve() { int t = scanner.nextInt(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < t; i++) { sb.append(solve1()).append("\n"); } System.out.println(sb.toString()); } int color[], cntc[]; private long solve1() { int n = scanner.nextInt(), m = scanner.nextInt(); gr = new ArrayList<>(); for (int i = 0; i < n; i++) { gr.add(new ArrayList<>()); } color = new int[n]; cntc = new int[3]; for (int i = 0; i < m; i++) { int u = scanner.nextInt() - 1, v = scanner.nextInt() - 1; gr.get(u).add(v); gr.get(v).add(u); } boolean ok = true; long ans = 1; long p[] = new long[n + 1]; p[0] = 1; for (int i = 1; i < n + 1; i++) { p[i] = (p[i - 1] * 2) % 998244353; } StringBuilder sb = new StringBuilder(); for (int i = 0; i < n; i++) { if (color[i] != 0) { continue; } Arrays.fill(cntc, 0); ok &= dfs(i, 1); int a = cntc[1], b = cntc[2]; ans = ans * (p[a] + p[b]) % 998244353; } if (!ok) { return 0; } return ans; } boolean dfs(int v, int c) { if (color[v] != 0) { return color[v] == c; } color[v] = c; cntc[c] ++; boolean ans = true; for (int next: gr.get(v)) { ans &= dfs(next, c == 1? 2: 1); } return ans; } public static final <T> void swap(T[] a, int i, int j) { T t = a[i]; a[i] = a[j]; a[j] = t; } class Pair implements Comparable<Pair> { int a, i; public Pair(int a, int i) { this.a = a; this.i = i; } @Override public int compareTo(Pair o) { return this.a - o.a; } } long gcd(long a, long b) { if (b != 0) { return gcd(b, a % b); } return a; } class FastScanner { public BufferedReader reader; public StringTokenizer tokenizer; public FastScanner() { reader = new BufferedReader(new InputStreamReader(System.in), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String nextLine() { try { return reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } } } }
Java
["2\n2 1\n1 2\n4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4"]
2 seconds
["4\n0"]
NotePossible ways to distribute numbers in the first test: the vertex $$$1$$$ should contain $$$1$$$, and $$$2$$$ should contain $$$2$$$; the vertex $$$1$$$ should contain $$$3$$$, and $$$2$$$ should contain $$$2$$$; the vertex $$$1$$$ should contain $$$2$$$, and $$$2$$$ should contain $$$1$$$; the vertex $$$1$$$ should contain $$$2$$$, and $$$2$$$ should contain $$$3$$$. In the second test there is no way to distribute numbers.
Java 8
standard input
[ "dfs and similar", "graphs" ]
332340a793eb3ec14131948e2b6bdf2f
The first line contains one integer $$$t$$$ ($$$1 \le t \le 3 \cdot 10^5$$$) β€” the number of tests in the input. The first line of each test contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5, 0 \le m \le 3 \cdot 10^5$$$) β€” the number of vertices and the number of edges, respectively. Next $$$m$$$ lines describe edges: $$$i$$$-th line contains two integers $$$u_i$$$, $$$ v_i$$$ ($$$1 \le u_i, v_i \le n; u_i \neq v_i$$$) β€” indices of vertices connected by $$$i$$$-th edge. It is guaranteed that $$$\sum\limits_{i=1}^{t} n \le 3 \cdot 10^5$$$ and $$$\sum\limits_{i=1}^{t} m \le 3 \cdot 10^5$$$.
1,700
For each test print one line, containing one integer β€” the number of possible ways to write numbers $$$1$$$, $$$2$$$, $$$3$$$ on the vertices of given graph so it becomes beautiful. Since answers may be large, print them modulo $$$998244353$$$.
standard output
PASSED
6d0fb69c98c278f093606195f2e28e2a
train_000.jsonl
1544884500
You are given an undirected unweighted graph consisting of $$$n$$$ vertices and $$$m$$$ edges.You have to write a number on each vertex of the graph. Each number should be $$$1$$$, $$$2$$$ or $$$3$$$. The graph becomes beautiful if for each edge the sum of numbers on vertices connected by this edge is odd.Calculate the number of possible ways to write numbers $$$1$$$, $$$2$$$ and $$$3$$$ on vertices so the graph becomes beautiful. Since this number may be large, print it modulo $$$998244353$$$.Note that you have to write exactly one number on each vertex.The graph does not have any self-loops or multiple edges.
256 megabytes
import java.io.*; import java.util.*; import static java.lang.Math.*; public class Main { FastScanner in; PrintWriter out; void run() { in = new FastScanner(); out = new PrintWriter(System.out); problem(); 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) { 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 Main().run(); } void build (int a[], int v, int tl, int tr) { if (tl == tr) t[v] = a[tl]; else { int tm = (tl + tr) / 2; build(a, v * 2, tl, tm); build(a, v * 2 + 1, tm + 1, tr); t[v] = t[v * 2] + t[v * 2 + 1]; } } int sum (int v, int tl, int tr, int l, int r) { if (l > r) return 0; if (l == tl && r == tr) return t[v]; int tm = (tl + tr) / 2; return sum (v*2, tl, tm, l, min(r,tm)) + sum (v*2+1, tm+1, tr, max(l,tm+1), r); } public static long modPower(int x, int y) { if(y==0) return 1; long z = modPower(x, y/2); if ((y % 2) == 0) return (z*z)%N; else return (x*z*z)%N; } int [] t; // static int N = (int)pow(10, 9) + 7; static int N = 998244353; class Node { boolean visited = false; int c = 0; List<Node> sos = new ArrayList<>(); void dfs() { if (result) { visited = true; if (sos.size() != 0) { if (c == 0) { c = 1; c1++; } if (c == 1) { for (Node so : sos) { if (so.c == 1) { result = false; return; } else { if (!so.visited) { so.c = 2; c2++; so.dfs(); } } } } else { for (Node so : sos) { if (so.c == 2) { result = false; return; } else { if (!so.visited) { so.c = 1; c1++; so.dfs(); } } } } } } } } boolean result; int c1; int c2; void problem() { int t = in.nextInt(); for (int asd = 0; asd < t; asd++) { result = true; int n = in.nextInt(); int m = in.nextInt(); Node[] nodes = new Node[n]; for (int i = 0; i < n; i++) { nodes[i] = new Node(); } for (int i = 0; i < m; i++) { int x = in.nextInt() - 1; int y = in.nextInt() - 1; nodes[x].sos.add(nodes[y]); nodes[y].sos.add(nodes[x]); } long res = 1; for (int i = 0; i < n; i++) { if(!nodes[i].visited) { nodes[i].dfs(); if (nodes[i].c == 0) { res = (res * 3) % N; } else { res = (res * (modPower(2, c1) + modPower(2, c2))) % N; c1 = 0; c2 = 0; } } } if (result) { out.println(res % N); } else { out.println(0); } } } } /* 1 7 4 1 2 2 3 6 4 4 5 3 5 6 2 1 1 3 3 4 4 5 5 1 2 4 5 5 2 1 1 3 3 4 4 5 5 1 5 4 2 1 1 3 3 4 4 5 */
Java
["2\n2 1\n1 2\n4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4"]
2 seconds
["4\n0"]
NotePossible ways to distribute numbers in the first test: the vertex $$$1$$$ should contain $$$1$$$, and $$$2$$$ should contain $$$2$$$; the vertex $$$1$$$ should contain $$$3$$$, and $$$2$$$ should contain $$$2$$$; the vertex $$$1$$$ should contain $$$2$$$, and $$$2$$$ should contain $$$1$$$; the vertex $$$1$$$ should contain $$$2$$$, and $$$2$$$ should contain $$$3$$$. In the second test there is no way to distribute numbers.
Java 8
standard input
[ "dfs and similar", "graphs" ]
332340a793eb3ec14131948e2b6bdf2f
The first line contains one integer $$$t$$$ ($$$1 \le t \le 3 \cdot 10^5$$$) β€” the number of tests in the input. The first line of each test contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5, 0 \le m \le 3 \cdot 10^5$$$) β€” the number of vertices and the number of edges, respectively. Next $$$m$$$ lines describe edges: $$$i$$$-th line contains two integers $$$u_i$$$, $$$ v_i$$$ ($$$1 \le u_i, v_i \le n; u_i \neq v_i$$$) β€” indices of vertices connected by $$$i$$$-th edge. It is guaranteed that $$$\sum\limits_{i=1}^{t} n \le 3 \cdot 10^5$$$ and $$$\sum\limits_{i=1}^{t} m \le 3 \cdot 10^5$$$.
1,700
For each test print one line, containing one integer β€” the number of possible ways to write numbers $$$1$$$, $$$2$$$, $$$3$$$ on the vertices of given graph so it becomes beautiful. Since answers may be large, print them modulo $$$998244353$$$.
standard output
PASSED
b7d2bea3dc70e57587016915f829a539
train_000.jsonl
1544884500
You are given an undirected unweighted graph consisting of $$$n$$$ vertices and $$$m$$$ edges.You have to write a number on each vertex of the graph. Each number should be $$$1$$$, $$$2$$$ or $$$3$$$. The graph becomes beautiful if for each edge the sum of numbers on vertices connected by this edge is odd.Calculate the number of possible ways to write numbers $$$1$$$, $$$2$$$ and $$$3$$$ on vertices so the graph becomes beautiful. Since this number may be large, print it modulo $$$998244353$$$.Note that you have to write exactly one number on each vertex.The graph does not have any self-loops or multiple edges.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.UncheckedIOException; 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 * * @author mikit */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; LightScanner in = new LightScanner(inputStream); PrintWriter out = new PrintWriter(outputStream); DBeautifulGraph solver = new DBeautifulGraph(); solver.solve(1, in, out); out.close(); } static class DBeautifulGraph { private static final int MOD = 998244353; private static long[] c = new long[2]; public void solve(int testNumber, LightScanner in, PrintWriter out) { int t = in.ints(); ModMath mod = new ModMath(MOD); outer: for (int testCase = 0; testCase < t; testCase++) { int n = in.ints(), m = in.ints(); DBeautifulGraph.N[] ns = new DBeautifulGraph.N[n]; for (int i = 0; i < n; i++) { ns[i] = new DBeautifulGraph.N(); } for (int i = 0; i < m; i++) { int x = in.ints() - 1, y = in.ints() - 1; ns[x].list.add(ns[y]); ns[y].list.add(ns[x]); } long ans = 1; for (int i = 0; i < n; i++) { if (ns[i].w == 0) { c[0] = 0; c[1] = 0; if (!dfs(ns[i], true)) { out.println(0); continue outer; } else { long ws = c[0]; long nws = c[1]; ans *= (mod.pow(2, ws) + mod.pow(2, nws)) % MOD; ans %= MOD; } } } out.println(ans); } } public static boolean dfs(DBeautifulGraph.N n, boolean even) { if (n.w > 0) { return (n.w == 2) == even; } n.w = even ? 2 : 1; c[even ? 0 : 1]++; for (DBeautifulGraph.N t : n.list) { if (!dfs(t, !even)) { return false; } } return true; } private static class N { private List<DBeautifulGraph.N> list = new ArrayList<>(); private int w = 0; } } static class ModMath { private static final int DEFAULT_MOD = 1_000_000_007; private final long mod; public ModMath(long mod) { this.mod = mod; } public ModMath() { this(DEFAULT_MOD); } public long pow(long x, long y) { if (y == 0) { return 1; } else if (y % 2 == 0) { long z = pow(x, y / 2); return (z * z) % mod; } else { return (x % mod) * pow(x, y - 1) % mod; } } } static class LightScanner { private BufferedReader reader = null; private StringTokenizer tokenizer = null; public LightScanner(InputStream in) { reader = new BufferedReader(new InputStreamReader(in)); } public String string() { if (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new UncheckedIOException(e); } } return tokenizer.nextToken(); } public int ints() { return Integer.parseInt(string()); } } }
Java
["2\n2 1\n1 2\n4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4"]
2 seconds
["4\n0"]
NotePossible ways to distribute numbers in the first test: the vertex $$$1$$$ should contain $$$1$$$, and $$$2$$$ should contain $$$2$$$; the vertex $$$1$$$ should contain $$$3$$$, and $$$2$$$ should contain $$$2$$$; the vertex $$$1$$$ should contain $$$2$$$, and $$$2$$$ should contain $$$1$$$; the vertex $$$1$$$ should contain $$$2$$$, and $$$2$$$ should contain $$$3$$$. In the second test there is no way to distribute numbers.
Java 8
standard input
[ "dfs and similar", "graphs" ]
332340a793eb3ec14131948e2b6bdf2f
The first line contains one integer $$$t$$$ ($$$1 \le t \le 3 \cdot 10^5$$$) β€” the number of tests in the input. The first line of each test contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5, 0 \le m \le 3 \cdot 10^5$$$) β€” the number of vertices and the number of edges, respectively. Next $$$m$$$ lines describe edges: $$$i$$$-th line contains two integers $$$u_i$$$, $$$ v_i$$$ ($$$1 \le u_i, v_i \le n; u_i \neq v_i$$$) β€” indices of vertices connected by $$$i$$$-th edge. It is guaranteed that $$$\sum\limits_{i=1}^{t} n \le 3 \cdot 10^5$$$ and $$$\sum\limits_{i=1}^{t} m \le 3 \cdot 10^5$$$.
1,700
For each test print one line, containing one integer β€” the number of possible ways to write numbers $$$1$$$, $$$2$$$, $$$3$$$ on the vertices of given graph so it becomes beautiful. Since answers may be large, print them modulo $$$998244353$$$.
standard output
PASSED
578b054d889b55fc1f54fc1fecb87b96
train_000.jsonl
1544884500
You are given an undirected unweighted graph consisting of $$$n$$$ vertices and $$$m$$$ edges.You have to write a number on each vertex of the graph. Each number should be $$$1$$$, $$$2$$$ or $$$3$$$. The graph becomes beautiful if for each edge the sum of numbers on vertices connected by this edge is odd.Calculate the number of possible ways to write numbers $$$1$$$, $$$2$$$ and $$$3$$$ on vertices so the graph becomes beautiful. Since this number may be large, print it modulo $$$998244353$$$.Note that you have to write exactly one number on each vertex.The graph does not have any self-loops or multiple edges.
256 megabytes
import java.util.*; import java.io.*; public class Solution{ public static void main (String[] args) throws IOException{ BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); PrintWriter out=new PrintWriter(System.out); String[] temp=br.readLine().trim().split(" "); int numTestCases=Integer.parseInt(temp[0]); while(numTestCases-->0){ temp=br.readLine().trim().split(" "); int n=Integer.parseInt(temp[0]); int m=Integer.parseInt(temp[1]); ArrayList<ArrayList<Integer>> graph=new ArrayList<>(); for(int i=0;i<=n;i++){ graph.add(new ArrayList<>()); } for(int i=0;i<m;i++){ temp=br.readLine().trim().split(" "); int u=Integer.parseInt(temp[0]); int v=Integer.parseInt(temp[1]); graph.get(u).add(v); graph.get(v).add(u); } out.println(numWays(graph)); } out.flush(); out.close(); } public static long numWays(ArrayList<ArrayList<Integer>> graph) { int V=graph.size()-1; boolean[] visited=new boolean[V+1]; int[] color=new int[V+1]; for(int i=1;i<=V;i++){ if(visited[i]==false){ bfs(graph,i,visited,color); } } visited=new boolean[V+1]; for(int i=1;i<=V;i++){ if(visited[i]==false){ if(isComponentBipartite(graph,i,visited,color)==false){ return 0; } } } int ans=1; int mod=998244353; visited=new boolean[V+1]; for(int i=1;i<=V;i++){ if(visited[i]==false){ Pair p=numNodes(graph,i,visited,color); int numOdd=p.numOdd; int numEven=p.numEven; int temp=(power(2,numEven,mod) + power(2,numOdd,mod) % mod); ans=(int)(( 1L * (ans%mod) * (temp%mod) ) % mod); } } return ans; } public static int power(int a,int b,int c){ if(b==0){ return 1; } int smallAns=power(a,b/2,c); int ans=(int)((1L*(smallAns%c)*(smallAns%c))%c); if(b%2==0){ return ans; } else{ ans=(int)((1L*(ans%c)*(a%c))%c); return ans; } } public static void bfs(ArrayList<ArrayList<Integer>> graph,int start,boolean[] visited,int[] color){ int V=graph.size()-1; Queue<Integer> pendingNodes=new LinkedList<>(); pendingNodes.add(start); color[start]=2; visited[start]=true; while(pendingNodes.isEmpty()==false){ int front=pendingNodes.remove(); for(int i=0;i<graph.get(front).size();i++){ if(visited[graph.get(front).get(i)]==false){ visited[graph.get(front).get(i)]=true; pendingNodes.add(graph.get(front).get(i)); if(color[front]==1){ color[graph.get(front).get(i)]=2; } else{ color[graph.get(front).get(i)]=1; } } } } } public static boolean isComponentBipartite(ArrayList<ArrayList<Integer>> graph,int start,boolean[] visited,int[] color) { Queue<Integer> pendingNodes=new LinkedList<>(); pendingNodes.add(start); visited[start]=true; while(pendingNodes.size()!=0){ int front=pendingNodes.remove(); for(int i=0;i<graph.get(front).size();i++){ if(color[front]==color[graph.get(front).get(i)]){ return false; } if(visited[graph.get(front).get(i)]==false){ visited[graph.get(front).get(i)]=true; pendingNodes.add(graph.get(front).get(i)); } } } return true; } public static Pair numNodes(ArrayList<ArrayList<Integer>> graph,int start,boolean[] visited,int[] color) { int numOdd=0,numEven=0; Queue<Integer> pendingNodes=new LinkedList<>(); pendingNodes.add(start); visited[start]=true; while(pendingNodes.size()!=0){ int front=pendingNodes.remove(); if(color[front]%2==0){ numEven++; } else{ numOdd++; } for(int i=0;i<graph.get(front).size();i++){ if(visited[graph.get(front).get(i)]==false){ visited[graph.get(front).get(i)]=true; pendingNodes.add(graph.get(front).get(i)); } } } Pair ans=new Pair(); ans.numOdd=numOdd; ans.numEven=numEven; return ans; } } class Pair{ int numOdd; int numEven; }
Java
["2\n2 1\n1 2\n4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4"]
2 seconds
["4\n0"]
NotePossible ways to distribute numbers in the first test: the vertex $$$1$$$ should contain $$$1$$$, and $$$2$$$ should contain $$$2$$$; the vertex $$$1$$$ should contain $$$3$$$, and $$$2$$$ should contain $$$2$$$; the vertex $$$1$$$ should contain $$$2$$$, and $$$2$$$ should contain $$$1$$$; the vertex $$$1$$$ should contain $$$2$$$, and $$$2$$$ should contain $$$3$$$. In the second test there is no way to distribute numbers.
Java 8
standard input
[ "dfs and similar", "graphs" ]
332340a793eb3ec14131948e2b6bdf2f
The first line contains one integer $$$t$$$ ($$$1 \le t \le 3 \cdot 10^5$$$) β€” the number of tests in the input. The first line of each test contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5, 0 \le m \le 3 \cdot 10^5$$$) β€” the number of vertices and the number of edges, respectively. Next $$$m$$$ lines describe edges: $$$i$$$-th line contains two integers $$$u_i$$$, $$$ v_i$$$ ($$$1 \le u_i, v_i \le n; u_i \neq v_i$$$) β€” indices of vertices connected by $$$i$$$-th edge. It is guaranteed that $$$\sum\limits_{i=1}^{t} n \le 3 \cdot 10^5$$$ and $$$\sum\limits_{i=1}^{t} m \le 3 \cdot 10^5$$$.
1,700
For each test print one line, containing one integer β€” the number of possible ways to write numbers $$$1$$$, $$$2$$$, $$$3$$$ on the vertices of given graph so it becomes beautiful. Since answers may be large, print them modulo $$$998244353$$$.
standard output
PASSED
dd54e94a54d1e9d7d8e85172f762f635
train_000.jsonl
1566311700
The main characters have been omitted to be short.You are given a directed unweighted graph without loops with $$$n$$$ vertexes and a path in it (that path is not necessary simple) given by a sequence $$$p_1, p_2, \ldots, p_m$$$ of $$$m$$$ vertexes; for each $$$1 \leq i &lt; m$$$ there is an arc from $$$p_i$$$ to $$$p_{i+1}$$$.Define the sequence $$$v_1, v_2, \ldots, v_k$$$ of $$$k$$$ vertexes as good, if $$$v$$$ is a subsequence of $$$p$$$, $$$v_1 = p_1$$$, $$$v_k = p_m$$$, and $$$p$$$ is one of the shortest paths passing through the vertexes $$$v_1$$$, $$$\ldots$$$, $$$v_k$$$ in that order.A sequence $$$a$$$ is a subsequence of a sequence $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) elements. It is obvious that the sequence $$$p$$$ is good but your task is to find the shortest good subsequence.If there are multiple shortest good subsequences, output any of them.
256 megabytes
import java.util.*; import java.io.*; public class Main { static class Scan { private byte[] buf=new byte[1024]; private int index; private InputStream in; private int total; public Scan() { in=System.in; } public int scan()throws IOException { if(total<0) throw new InputMismatchException(); if(index>=total) { index=0; total=in.read(buf); if(total<=0) return -1; } return buf[index++]; } public int scanInt()throws IOException { 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(); } else throw new InputMismatchException(); } return neg*integer; } public double scanDouble()throws IOException { double doub=0; int n=scan(); while(isWhiteSpace(n)) n=scan(); int neg=1; if(n=='-') { neg=-1; n=scan(); } while(!isWhiteSpace(n)&&n!='.') { if(n>='0'&&n<='9') { doub*=10; doub+=n-'0'; n=scan(); } else throw new InputMismatchException(); } if(n=='.') { n=scan(); double temp=1; while(!isWhiteSpace(n)) { if(n>='0'&&n<='9') { temp/=10; doub+=(n-'0')*temp; n=scan(); } else throw new InputMismatchException(); } } return doub*neg; } public String scanString()throws IOException { StringBuilder sb=new StringBuilder(); int n=scan(); while(isWhiteSpace(n)) n=scan(); while(!isWhiteSpace(n)) { sb.append((char)n); n=scan(); } return sb.toString(); } private boolean isWhiteSpace(int n) { if(n==' '||n=='\n'||n=='\r'||n=='\t'||n==-1) return true; return false; } } public static void sort(int arr[],int l,int r) { //sort(arr,0,n-1); if(l==r) { return; } int mid=(l+r)/2; sort(arr,l,mid); sort(arr,mid+1,r); merge(arr,l,mid,mid+1,r); } public static void merge(int arr[],int l1,int r1,int l2,int r2) { int tmp[]=new int[r2-l1+1]; int indx1=l1,indx2=l2; //sorting the two halves using a tmp array for(int i=0;i<tmp.length;i++) { if(indx1>r1) { tmp[i]=arr[indx2]; indx2++; continue; } if(indx2>r2) { tmp[i]=arr[indx1]; indx1++; continue; } if(arr[indx1]<arr[indx2]) { tmp[i]=arr[indx1]; indx1++; continue; } tmp[i]=arr[indx2]; indx2++; } //Copying the elements of tmp into the main array for(int i=0,j=l1;i<tmp.length;i++,j++) { arr[j]=tmp[i]; } } public static void sort(long arr[],int l,int r) { //sort(arr,0,n-1); if(l==r) { return; } int mid=(l+r)/2; sort(arr,l,mid); sort(arr,mid+1,r); merge(arr,l,mid,mid+1,r); } public static void merge(long arr[],int l1,int r1,int l2,int r2) { long tmp[]=new long[r2-l1+1]; int indx1=l1,indx2=l2; //sorting the two halves using a tmp array for(int i=0;i<tmp.length;i++) { if(indx1>r1) { tmp[i]=arr[indx2]; indx2++; continue; } if(indx2>r2) { tmp[i]=arr[indx1]; indx1++; continue; } if(arr[indx1]<arr[indx2]) { tmp[i]=arr[indx1]; indx1++; continue; } tmp[i]=arr[indx2]; indx2++; } //Copying the elements of tmp into the main array for(int i=0,j=l1;i<tmp.length;i++,j++) { arr[j]=tmp[i]; } } static ArrayList<Integer> adj_lst[]; static int dist[][]; public static void main(String args[]) throws IOException { Scan input=new Scan(); StringBuilder ans=new StringBuilder(""); int n=input.scanInt(); adj_lst=new ArrayList[n]; for(int i=0;i<n;i++) { adj_lst[i]=new ArrayList<>(); } for(int i=0;i<n;i++) { String str=input.scanString(); for(int j=0;j<n;j++) { if(str.charAt(j)=='1') { adj_lst[i].add(j); } } } int m=input.scanInt(); int path[]=new int[m]; for(int i=0;i<m;i++) { path[i]=input.scanInt()-1; } dist=new int[n][n]; for(int i=0;i<n;i++) { BFS(i); } int prev[]=new int[n]; Arrays.fill(prev, -1); int dp[]=new int[m]; Arrays.fill(dp, Integer.MAX_VALUE); dp[0]=1; prev[path[0]]=0; for(int i=1;i<m;i++) { for(int j=0;j<n;j++) { if(j==path[i]) { continue; } int indx=prev[j]; if(indx==-1) { continue; } if(dist[j][path[i]]==(i-indx)) { dp[i]=Math.min(dp[i], dp[indx]+1); } } prev[path[i]]=i; } // for(int i=0;i<m;i++) { // System.out.print(dp[i]+" "); // } // System.out.println(); ArrayList<Integer> arrli=new ArrayList<>(); int indx=m-1; while(indx>=0) { // System.out.println(indx); arrli.add((path[indx]+1)); if(indx==0) { break; } for(int j=indx-1;j>=0;j--) { if(dp[j]==dp[indx]-1 && dist[path[j]][path[indx]]==indx-j) { indx=j; break; } } } ans.append(dp[m-1]+"\n"); for(int i=arrli.size()-1;i>=0;i--) { ans.append(arrli.get(i)+" "); } System.out.println(ans); } static void BFS(int src) { boolean vis[]=new boolean[adj_lst.length]; int depth[]=new int[adj_lst.length]; Arrays.fill(depth, Integer.MAX_VALUE); Queue<Integer> que = new LinkedList<>(); que.add(src); depth[src]=0; vis[src]=true; while(!que.isEmpty()) { for(int i=0;i<adj_lst[que.peek()].size();i++) { if(!vis[adj_lst[que.peek()].get(i)]) { que.add(adj_lst[que.peek()].get(i)); vis[adj_lst[que.peek()].get(i)]=true; depth[adj_lst[que.peek()].get(i)]=depth[que.peek()]+1; } } que.poll(); } dist[src]=depth; } }
Java
["4\n0110\n0010\n0001\n1000\n4\n1 2 3 4", "4\n0110\n0010\n1001\n1000\n20\n1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4", "3\n011\n101\n110\n7\n1 2 3 1 3 2 1", "4\n0110\n0001\n0001\n1000\n3\n1 2 4"]
2 seconds
["3\n1 2 4", "11\n1 2 4 2 4 2 4 2 4 2 4", "7\n1 2 3 1 3 2 1", "2\n1 4"]
NoteBelow you can see the graph from the first example:The given path is passing through vertexes $$$1$$$, $$$2$$$, $$$3$$$, $$$4$$$. The sequence $$$1-2-4$$$ is good because it is the subsequence of the given path, its first and the last elements are equal to the first and the last elements of the given path respectively, and the shortest path passing through vertexes $$$1$$$, $$$2$$$ and $$$4$$$ in that order is $$$1-2-3-4$$$. Note that subsequences $$$1-4$$$ and $$$1-3-4$$$ aren't good because in both cases the shortest path passing through the vertexes of these sequences is $$$1-3-4$$$.In the third example, the graph is full so any sequence of vertexes in which any two consecutive elements are distinct defines a path consisting of the same number of vertexes.In the fourth example, the paths $$$1-2-4$$$ and $$$1-3-4$$$ are the shortest paths passing through the vertexes $$$1$$$ and $$$4$$$.
Java 11
standard input
[ "dp", "graphs", "greedy", "shortest paths" ]
c9d07fdf0d3293d5564275ebbabbcf12
The first line contains a single integer $$$n$$$ ($$$2 \le n \le 100$$$)Β β€” the number of vertexes in a graph. The next $$$n$$$ lines define the graph by an adjacency matrix: the $$$j$$$-th character in the $$$i$$$-st line is equal to $$$1$$$ if there is an arc from vertex $$$i$$$ to the vertex $$$j$$$ else it is equal to $$$0$$$. It is guaranteed that the graph doesn't contain loops. The next line contains a single integer $$$m$$$ ($$$2 \le m \le 10^6$$$)Β β€” the number of vertexes in the path. The next line contains $$$m$$$ integers $$$p_1, p_2, \ldots, p_m$$$ ($$$1 \le p_i \le n$$$)Β β€” the sequence of vertexes in the path. It is guaranteed that for any $$$1 \leq i &lt; m$$$ there is an arc from $$$p_i$$$ to $$$p_{i+1}$$$.
1,700
In the first line output a single integer $$$k$$$ ($$$2 \leq k \leq m$$$)Β β€” the length of the shortest good subsequence. In the second line output $$$k$$$ integers $$$v_1$$$, $$$\ldots$$$, $$$v_k$$$ ($$$1 \leq v_i \leq n$$$)Β β€” the vertexes in the subsequence. If there are multiple shortest subsequences, print any. Any two consecutive numbers should be distinct.
standard output
PASSED
ed852a0aca2104073d6fcf1671d5243c
train_000.jsonl
1566311700
The main characters have been omitted to be short.You are given a directed unweighted graph without loops with $$$n$$$ vertexes and a path in it (that path is not necessary simple) given by a sequence $$$p_1, p_2, \ldots, p_m$$$ of $$$m$$$ vertexes; for each $$$1 \leq i &lt; m$$$ there is an arc from $$$p_i$$$ to $$$p_{i+1}$$$.Define the sequence $$$v_1, v_2, \ldots, v_k$$$ of $$$k$$$ vertexes as good, if $$$v$$$ is a subsequence of $$$p$$$, $$$v_1 = p_1$$$, $$$v_k = p_m$$$, and $$$p$$$ is one of the shortest paths passing through the vertexes $$$v_1$$$, $$$\ldots$$$, $$$v_k$$$ in that order.A sequence $$$a$$$ is a subsequence of a sequence $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) elements. It is obvious that the sequence $$$p$$$ is good but your task is to find the shortest good subsequence.If there are multiple shortest good subsequences, output any of them.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.Scanner; import java.util.ArrayList; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Kraken7 */ 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 { private final int INF = (int) 1e7; public void solve(int testNumber, Scanner in, PrintWriter out) { int n = in.nextInt(); int[][] d = new int[n][n]; for (int[] i : d) { Arrays.fill(i, INF); } for (int i = 0; i < n; i++) { String s = in.next(); for (int j = 0; j < n; j++) { int v = s.charAt(j) - '0'; if (v > 0) d[i][j] = v; if (i == j) d[i][j] = 0; } } for (int k = 0; k < n; k++) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { d[i][j] = Math.min(d[i][j], d[i][k] + d[k][j]); } } } int m = in.nextInt(); int[] p = new int[m]; for (int i = 0; i < m; i++) p[i] = in.nextInt() - 1; ArrayList<Integer> res = new ArrayList<>(); int l = 0, r = 1; res.add(p[0]); int cnt = 1; while (r < m) { if (cnt > d[p[l]][p[r]]) { res.add(p[r - 1]); r -= 1; l = r; cnt = 0; } r++; cnt++; } res.add(p[m - 1]); out.println(res.size()); for (int i : res) out.print((i + 1) + " "); } } }
Java
["4\n0110\n0010\n0001\n1000\n4\n1 2 3 4", "4\n0110\n0010\n1001\n1000\n20\n1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4", "3\n011\n101\n110\n7\n1 2 3 1 3 2 1", "4\n0110\n0001\n0001\n1000\n3\n1 2 4"]
2 seconds
["3\n1 2 4", "11\n1 2 4 2 4 2 4 2 4 2 4", "7\n1 2 3 1 3 2 1", "2\n1 4"]
NoteBelow you can see the graph from the first example:The given path is passing through vertexes $$$1$$$, $$$2$$$, $$$3$$$, $$$4$$$. The sequence $$$1-2-4$$$ is good because it is the subsequence of the given path, its first and the last elements are equal to the first and the last elements of the given path respectively, and the shortest path passing through vertexes $$$1$$$, $$$2$$$ and $$$4$$$ in that order is $$$1-2-3-4$$$. Note that subsequences $$$1-4$$$ and $$$1-3-4$$$ aren't good because in both cases the shortest path passing through the vertexes of these sequences is $$$1-3-4$$$.In the third example, the graph is full so any sequence of vertexes in which any two consecutive elements are distinct defines a path consisting of the same number of vertexes.In the fourth example, the paths $$$1-2-4$$$ and $$$1-3-4$$$ are the shortest paths passing through the vertexes $$$1$$$ and $$$4$$$.
Java 11
standard input
[ "dp", "graphs", "greedy", "shortest paths" ]
c9d07fdf0d3293d5564275ebbabbcf12
The first line contains a single integer $$$n$$$ ($$$2 \le n \le 100$$$)Β β€” the number of vertexes in a graph. The next $$$n$$$ lines define the graph by an adjacency matrix: the $$$j$$$-th character in the $$$i$$$-st line is equal to $$$1$$$ if there is an arc from vertex $$$i$$$ to the vertex $$$j$$$ else it is equal to $$$0$$$. It is guaranteed that the graph doesn't contain loops. The next line contains a single integer $$$m$$$ ($$$2 \le m \le 10^6$$$)Β β€” the number of vertexes in the path. The next line contains $$$m$$$ integers $$$p_1, p_2, \ldots, p_m$$$ ($$$1 \le p_i \le n$$$)Β β€” the sequence of vertexes in the path. It is guaranteed that for any $$$1 \leq i &lt; m$$$ there is an arc from $$$p_i$$$ to $$$p_{i+1}$$$.
1,700
In the first line output a single integer $$$k$$$ ($$$2 \leq k \leq m$$$)Β β€” the length of the shortest good subsequence. In the second line output $$$k$$$ integers $$$v_1$$$, $$$\ldots$$$, $$$v_k$$$ ($$$1 \leq v_i \leq n$$$)Β β€” the vertexes in the subsequence. If there are multiple shortest subsequences, print any. Any two consecutive numbers should be distinct.
standard output
PASSED
ede584000a7adef05a124f4ea86a7148
train_000.jsonl
1566311700
The main characters have been omitted to be short.You are given a directed unweighted graph without loops with $$$n$$$ vertexes and a path in it (that path is not necessary simple) given by a sequence $$$p_1, p_2, \ldots, p_m$$$ of $$$m$$$ vertexes; for each $$$1 \leq i &lt; m$$$ there is an arc from $$$p_i$$$ to $$$p_{i+1}$$$.Define the sequence $$$v_1, v_2, \ldots, v_k$$$ of $$$k$$$ vertexes as good, if $$$v$$$ is a subsequence of $$$p$$$, $$$v_1 = p_1$$$, $$$v_k = p_m$$$, and $$$p$$$ is one of the shortest paths passing through the vertexes $$$v_1$$$, $$$\ldots$$$, $$$v_k$$$ in that order.A sequence $$$a$$$ is a subsequence of a sequence $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) elements. It is obvious that the sequence $$$p$$$ is good but your task is to find the shortest good subsequence.If there are multiple shortest good subsequences, output any of them.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.Objects; import java.util.Random; import java.util.StringTokenizer; public class Solution{ static ArrayList<Integer>[] adjList; public static void main(String[] args) { FastScanner fs = new FastScanner(); PrintWriter out = new PrintWriter(System.out); int tt = 1; while(tt-->0) { int n = fs.nextInt(); adjList = new ArrayList[n]; for(int i=0;i<n;i++) adjList[i] = new ArrayList<Integer>(); for(int i=0;i<n;i++) { char[] arr = fs.next().toCharArray(); for(int j=0;j<n;j++) { if(arr[j]=='1') adjList[i].add(j); } } int[][] dist = new int[n][n]; boolean[] visited = new boolean[n]; int m = fs.nextInt(); int[] arr = fs.readArray(m); for(int i=0;i<n;i++) { for(int j=0;j<n;j++) visited[j] = false; ArrayDeque<Integer> queue = new ArrayDeque<Integer>(); queue.add(i); visited[i] = true; while(!queue.isEmpty()) { int v = queue.poll(); for(int node: adjList[v]) { if(!visited[node]) { queue.add(node); visited[node] = true; dist[i][node] = dist[i][v] + 1; } } } } ArrayList<Integer> list = new ArrayList<Integer>(); list.add(arr[0]-1); int pre = 0; for(int i=1;i<m-1;i++) { if(dist[list.get(list.size()-1)][arr[i+1]-1]<i+1-pre){ list.add(arr[i]-1); pre = i; } } list.add(arr[m-1]-1); out.println(list.size()); for(int num: list) out.print((num+1)+" "); out.println(""); } out.close(); } static final Random random=new Random(); static void ruffleSort(int[] a) { int n=a.length;//shuffle, then sort for (int i=0; i<n; i++) { int oi=random.nextInt(n), temp=a[oi]; a[oi]=a[i]; a[i]=temp; } Arrays.sort(a); } static class FastScanner{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); public String next(){ while(!st.hasMoreElements()){ try{ st = new StringTokenizer(br.readLine()); } catch(IOException e){ e.printStackTrace(); } } return st.nextToken(); } public String nextLine() throws IOException { return br.readLine(); } public int nextInt(){ return Integer.parseInt(next()); } public int[] readArray(int n){ int[] a = new int[n]; for(int i=0;i<n;i++) a[i] = nextInt(); return a; } public long nextLong() { return Long.parseLong(next()); } public char nextChar() { return next().toCharArray()[0]; } } }
Java
["4\n0110\n0010\n0001\n1000\n4\n1 2 3 4", "4\n0110\n0010\n1001\n1000\n20\n1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4", "3\n011\n101\n110\n7\n1 2 3 1 3 2 1", "4\n0110\n0001\n0001\n1000\n3\n1 2 4"]
2 seconds
["3\n1 2 4", "11\n1 2 4 2 4 2 4 2 4 2 4", "7\n1 2 3 1 3 2 1", "2\n1 4"]
NoteBelow you can see the graph from the first example:The given path is passing through vertexes $$$1$$$, $$$2$$$, $$$3$$$, $$$4$$$. The sequence $$$1-2-4$$$ is good because it is the subsequence of the given path, its first and the last elements are equal to the first and the last elements of the given path respectively, and the shortest path passing through vertexes $$$1$$$, $$$2$$$ and $$$4$$$ in that order is $$$1-2-3-4$$$. Note that subsequences $$$1-4$$$ and $$$1-3-4$$$ aren't good because in both cases the shortest path passing through the vertexes of these sequences is $$$1-3-4$$$.In the third example, the graph is full so any sequence of vertexes in which any two consecutive elements are distinct defines a path consisting of the same number of vertexes.In the fourth example, the paths $$$1-2-4$$$ and $$$1-3-4$$$ are the shortest paths passing through the vertexes $$$1$$$ and $$$4$$$.
Java 11
standard input
[ "dp", "graphs", "greedy", "shortest paths" ]
c9d07fdf0d3293d5564275ebbabbcf12
The first line contains a single integer $$$n$$$ ($$$2 \le n \le 100$$$)Β β€” the number of vertexes in a graph. The next $$$n$$$ lines define the graph by an adjacency matrix: the $$$j$$$-th character in the $$$i$$$-st line is equal to $$$1$$$ if there is an arc from vertex $$$i$$$ to the vertex $$$j$$$ else it is equal to $$$0$$$. It is guaranteed that the graph doesn't contain loops. The next line contains a single integer $$$m$$$ ($$$2 \le m \le 10^6$$$)Β β€” the number of vertexes in the path. The next line contains $$$m$$$ integers $$$p_1, p_2, \ldots, p_m$$$ ($$$1 \le p_i \le n$$$)Β β€” the sequence of vertexes in the path. It is guaranteed that for any $$$1 \leq i &lt; m$$$ there is an arc from $$$p_i$$$ to $$$p_{i+1}$$$.
1,700
In the first line output a single integer $$$k$$$ ($$$2 \leq k \leq m$$$)Β β€” the length of the shortest good subsequence. In the second line output $$$k$$$ integers $$$v_1$$$, $$$\ldots$$$, $$$v_k$$$ ($$$1 \leq v_i \leq n$$$)Β β€” the vertexes in the subsequence. If there are multiple shortest subsequences, print any. Any two consecutive numbers should be distinct.
standard output
PASSED
9a7d0c4d20834a42626d7b506a9aad51
train_000.jsonl
1566311700
The main characters have been omitted to be short.You are given a directed unweighted graph without loops with $$$n$$$ vertexes and a path in it (that path is not necessary simple) given by a sequence $$$p_1, p_2, \ldots, p_m$$$ of $$$m$$$ vertexes; for each $$$1 \leq i &lt; m$$$ there is an arc from $$$p_i$$$ to $$$p_{i+1}$$$.Define the sequence $$$v_1, v_2, \ldots, v_k$$$ of $$$k$$$ vertexes as good, if $$$v$$$ is a subsequence of $$$p$$$, $$$v_1 = p_1$$$, $$$v_k = p_m$$$, and $$$p$$$ is one of the shortest paths passing through the vertexes $$$v_1$$$, $$$\ldots$$$, $$$v_k$$$ in that order.A sequence $$$a$$$ is a subsequence of a sequence $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) elements. It is obvious that the sequence $$$p$$$ is good but your task is to find the shortest good subsequence.If there are multiple shortest good subsequences, output any of them.
256 megabytes
import java.util.*; import java.io.*; import java.math.*; public class codechef { public static class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar, snumChars; public InputReader(InputStream st) { this.stream = st; } public int read() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int 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; } } static class pair { public long x1; public long x2; pair(long x, long y) { this.x1 = x; this.x2 = y; } } public static long[][] floydWarshall(long[][] g) { int n = g.length; for (int k = 0; k < n; k++) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (g[i][j] > g[i][k] + g[k][j]) { g[i][j] = g[i][k] + g[k][j]; } } } } return g; } public static void main(String[] args) throws IOException { InputReader in = new InputReader(System.in); PrintWriter out = new PrintWriter(System.out); int n = in.nextInt(); int inf = (int) 1e9; long g[][] = new long[n + 1][n + 1]; for (long a[] : g) Arrays.fill(a, inf); for (int i = 1; i <= n; i++) { char s[] = in.nextLine().toCharArray(); for (int j = 1; j <= n; j++) { g[i][j] = (s[j - 1] - '0'); if (g[i][j] == 0) g[i][j] = inf; } g[i][i] = 0; } g = floydWarshall(g); int m = in.nextInt(); int a[] = new int[m]; for (int i = 0; i < m; i++) { a[i] = in.nextInt(); } int src = a[0], dst = a[m - 1], sid = 0, tmpID = 0; ArrayDeque<Integer> dq = new ArrayDeque<>(); dq.addLast(src); for (int i = 1; i < m; i++) { int d = i - sid; long f = g[src][a[i]]; if (d == f) { tmpID = i; } else { src = a[tmpID]; sid = tmpID; tmpID = i; dq.addLast(src); } if (i == m - 1) { dq.addLast(a[i]); } } out.println(dq.size()); for (int i : dq) out.print(i + " "); out.println(); out.flush(); } }
Java
["4\n0110\n0010\n0001\n1000\n4\n1 2 3 4", "4\n0110\n0010\n1001\n1000\n20\n1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4", "3\n011\n101\n110\n7\n1 2 3 1 3 2 1", "4\n0110\n0001\n0001\n1000\n3\n1 2 4"]
2 seconds
["3\n1 2 4", "11\n1 2 4 2 4 2 4 2 4 2 4", "7\n1 2 3 1 3 2 1", "2\n1 4"]
NoteBelow you can see the graph from the first example:The given path is passing through vertexes $$$1$$$, $$$2$$$, $$$3$$$, $$$4$$$. The sequence $$$1-2-4$$$ is good because it is the subsequence of the given path, its first and the last elements are equal to the first and the last elements of the given path respectively, and the shortest path passing through vertexes $$$1$$$, $$$2$$$ and $$$4$$$ in that order is $$$1-2-3-4$$$. Note that subsequences $$$1-4$$$ and $$$1-3-4$$$ aren't good because in both cases the shortest path passing through the vertexes of these sequences is $$$1-3-4$$$.In the third example, the graph is full so any sequence of vertexes in which any two consecutive elements are distinct defines a path consisting of the same number of vertexes.In the fourth example, the paths $$$1-2-4$$$ and $$$1-3-4$$$ are the shortest paths passing through the vertexes $$$1$$$ and $$$4$$$.
Java 11
standard input
[ "dp", "graphs", "greedy", "shortest paths" ]
c9d07fdf0d3293d5564275ebbabbcf12
The first line contains a single integer $$$n$$$ ($$$2 \le n \le 100$$$)Β β€” the number of vertexes in a graph. The next $$$n$$$ lines define the graph by an adjacency matrix: the $$$j$$$-th character in the $$$i$$$-st line is equal to $$$1$$$ if there is an arc from vertex $$$i$$$ to the vertex $$$j$$$ else it is equal to $$$0$$$. It is guaranteed that the graph doesn't contain loops. The next line contains a single integer $$$m$$$ ($$$2 \le m \le 10^6$$$)Β β€” the number of vertexes in the path. The next line contains $$$m$$$ integers $$$p_1, p_2, \ldots, p_m$$$ ($$$1 \le p_i \le n$$$)Β β€” the sequence of vertexes in the path. It is guaranteed that for any $$$1 \leq i &lt; m$$$ there is an arc from $$$p_i$$$ to $$$p_{i+1}$$$.
1,700
In the first line output a single integer $$$k$$$ ($$$2 \leq k \leq m$$$)Β β€” the length of the shortest good subsequence. In the second line output $$$k$$$ integers $$$v_1$$$, $$$\ldots$$$, $$$v_k$$$ ($$$1 \leq v_i \leq n$$$)Β β€” the vertexes in the subsequence. If there are multiple shortest subsequences, print any. Any two consecutive numbers should be distinct.
standard output
PASSED
d35789e2f79873df1bdb8a46f077d786
train_000.jsonl
1566311700
The main characters have been omitted to be short.You are given a directed unweighted graph without loops with $$$n$$$ vertexes and a path in it (that path is not necessary simple) given by a sequence $$$p_1, p_2, \ldots, p_m$$$ of $$$m$$$ vertexes; for each $$$1 \leq i &lt; m$$$ there is an arc from $$$p_i$$$ to $$$p_{i+1}$$$.Define the sequence $$$v_1, v_2, \ldots, v_k$$$ of $$$k$$$ vertexes as good, if $$$v$$$ is a subsequence of $$$p$$$, $$$v_1 = p_1$$$, $$$v_k = p_m$$$, and $$$p$$$ is one of the shortest paths passing through the vertexes $$$v_1$$$, $$$\ldots$$$, $$$v_k$$$ in that order.A sequence $$$a$$$ is a subsequence of a sequence $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) elements. It is obvious that the sequence $$$p$$$ is good but your task is to find the shortest good subsequence.If there are multiple shortest good subsequences, output any of them.
256 megabytes
import java.util.*; import java.io.*; public class File { public static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } } public static void main(String[] args) { FastScanner sc = new FastScanner(); PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); // # vertexes in graph. int n = sc.nextInt(); // Get the directed graph. Map<Integer, List<Integer>> graph = new HashMap<>(); for (int i = 1; i <= n; i++) { graph.put(i, new ArrayList<>()); String s = sc.next(); for (int j = 1; j <= n; j++) { if (s.charAt(j-1) == '1') { graph.get(i).add(j); } } } // The path p1, p2, ..., pm int m = sc.nextInt(); int[] path = new int[m]; for (int i = 0; i < m; i++) { path[i] = sc.nextInt(); } int[][] dist = new int[n+1][n+1]; for (int i = 0; i <= n; i++) { Arrays.fill(dist[i], 1000000); } for (int i = 1; i <= n; i++) { dist[i][i] = 0; for (int j : graph.get(i)) { dist[i][j] = 1; } } for (int k = 1; k <= n; k++) { for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { if (dist[i][k] + dist[k][j] < dist[i][j]) { dist[i][j] = dist[i][k] + dist[k][j]; } } } } StringBuilder res = new StringBuilder(); int prevIndex = 0; res.append(path[prevIndex]); int index = 1; // out.println("Added: " + path[prevIndex]); int totalLength = 1; while (index < m) { int end = index; while (end + 1 < m && (dist[path[prevIndex]][path[end+1]] == (end + 1 - prevIndex))) { end++; } if (end < m) { if (res.length() > 0) { res.append(" "); } res.append(path[end]); totalLength++; prevIndex = end; // out.println("Added: " + path[end]); } index = end + 1; } out.println(totalLength); out.println(res.toString()); out.close(); } }
Java
["4\n0110\n0010\n0001\n1000\n4\n1 2 3 4", "4\n0110\n0010\n1001\n1000\n20\n1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4", "3\n011\n101\n110\n7\n1 2 3 1 3 2 1", "4\n0110\n0001\n0001\n1000\n3\n1 2 4"]
2 seconds
["3\n1 2 4", "11\n1 2 4 2 4 2 4 2 4 2 4", "7\n1 2 3 1 3 2 1", "2\n1 4"]
NoteBelow you can see the graph from the first example:The given path is passing through vertexes $$$1$$$, $$$2$$$, $$$3$$$, $$$4$$$. The sequence $$$1-2-4$$$ is good because it is the subsequence of the given path, its first and the last elements are equal to the first and the last elements of the given path respectively, and the shortest path passing through vertexes $$$1$$$, $$$2$$$ and $$$4$$$ in that order is $$$1-2-3-4$$$. Note that subsequences $$$1-4$$$ and $$$1-3-4$$$ aren't good because in both cases the shortest path passing through the vertexes of these sequences is $$$1-3-4$$$.In the third example, the graph is full so any sequence of vertexes in which any two consecutive elements are distinct defines a path consisting of the same number of vertexes.In the fourth example, the paths $$$1-2-4$$$ and $$$1-3-4$$$ are the shortest paths passing through the vertexes $$$1$$$ and $$$4$$$.
Java 11
standard input
[ "dp", "graphs", "greedy", "shortest paths" ]
c9d07fdf0d3293d5564275ebbabbcf12
The first line contains a single integer $$$n$$$ ($$$2 \le n \le 100$$$)Β β€” the number of vertexes in a graph. The next $$$n$$$ lines define the graph by an adjacency matrix: the $$$j$$$-th character in the $$$i$$$-st line is equal to $$$1$$$ if there is an arc from vertex $$$i$$$ to the vertex $$$j$$$ else it is equal to $$$0$$$. It is guaranteed that the graph doesn't contain loops. The next line contains a single integer $$$m$$$ ($$$2 \le m \le 10^6$$$)Β β€” the number of vertexes in the path. The next line contains $$$m$$$ integers $$$p_1, p_2, \ldots, p_m$$$ ($$$1 \le p_i \le n$$$)Β β€” the sequence of vertexes in the path. It is guaranteed that for any $$$1 \leq i &lt; m$$$ there is an arc from $$$p_i$$$ to $$$p_{i+1}$$$.
1,700
In the first line output a single integer $$$k$$$ ($$$2 \leq k \leq m$$$)Β β€” the length of the shortest good subsequence. In the second line output $$$k$$$ integers $$$v_1$$$, $$$\ldots$$$, $$$v_k$$$ ($$$1 \leq v_i \leq n$$$)Β β€” the vertexes in the subsequence. If there are multiple shortest subsequences, print any. Any two consecutive numbers should be distinct.
standard output
PASSED
0be78e7d149d96121271c36a894befd5
train_000.jsonl
1566311700
The main characters have been omitted to be short.You are given a directed unweighted graph without loops with $$$n$$$ vertexes and a path in it (that path is not necessary simple) given by a sequence $$$p_1, p_2, \ldots, p_m$$$ of $$$m$$$ vertexes; for each $$$1 \leq i &lt; m$$$ there is an arc from $$$p_i$$$ to $$$p_{i+1}$$$.Define the sequence $$$v_1, v_2, \ldots, v_k$$$ of $$$k$$$ vertexes as good, if $$$v$$$ is a subsequence of $$$p$$$, $$$v_1 = p_1$$$, $$$v_k = p_m$$$, and $$$p$$$ is one of the shortest paths passing through the vertexes $$$v_1$$$, $$$\ldots$$$, $$$v_k$$$ in that order.A sequence $$$a$$$ is a subsequence of a sequence $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) elements. It is obvious that the sequence $$$p$$$ is good but your task is to find the shortest good subsequence.If there are multiple shortest good subsequences, output any of them.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.Queue; import java.util.StringTokenizer; import java.util.*; public class c { static long mod = 1000000009L; public static void main(String[] args) throws Exception { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); sc = new FastScanner(in); int t =1; while (t-- > 0) { int n = sc.nextInt(); int[][] arr = new int[n][n]; int[][] min = new int[n][n]; for(int i = 0 ;i < n;i++) { String tt = sc.nextToken(); for(int j = 0 ; j< n;j++) { arr[i][j] =tt.charAt(j)-'0'; } } for(int i = 0 ; i< n;i++) { Arrays.fill(min[i] , -1); min_path(min , arr , i ,i ); } int m =sc.nextInt(); int[] temp = new int[m]; for(int i = 0 ; i < m ;i++) { temp[i] = sc.nextInt()-1; } int i = 0 ; ArrayList<Integer> ans = new ArrayList<Integer>(); while(i<m ) { if(i==m) { ans.add(temp[m-1]); break; } int j = i+2 ; int cur = temp[i]; while(j<m && min[cur][temp[j]]==j-i) { j++; } ans.add(cur); if(i==m-1) { break; } i = j-1; } out.println(ans.size()); for(int val : ans) { out.print(val+1+" "); } } out.flush(); } private static void min_path(int[][] min, int[][] arr, int i, int cur) { // TODO Auto-generated method stub Queue<Integer> q = new LinkedList<>(); q.add(i); q.add(-1); int level = 0; while(!q.isEmpty()) { int rv = q.remove(); if(rv ==-1) { if(q.size()>0) { q.add(-1); } level++; continue; } if(min[i][rv]!=-1)continue; min[i][rv]=level; for(int j = 0 ; j < arr.length ;j++) { if(arr[rv][j]==0)continue; if(min[cur][j]==-1) { q.add(j); } } } } static BufferedReader in; static FastScanner sc; static PrintWriter out; static class FastScanner { BufferedReader in; StringTokenizer st; public FastScanner(BufferedReader in) { this.in = in; } public String nextToken() throws Exception { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(in.readLine()); } return st.nextToken(); } public int nextInt() throws Exception { return Integer.parseInt(nextToken()); } public long nextLong() throws Exception { return Long.parseLong(nextToken()); } public double nextDouble() throws Exception { return Double.parseDouble(nextToken()); } } }
Java
["4\n0110\n0010\n0001\n1000\n4\n1 2 3 4", "4\n0110\n0010\n1001\n1000\n20\n1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4", "3\n011\n101\n110\n7\n1 2 3 1 3 2 1", "4\n0110\n0001\n0001\n1000\n3\n1 2 4"]
2 seconds
["3\n1 2 4", "11\n1 2 4 2 4 2 4 2 4 2 4", "7\n1 2 3 1 3 2 1", "2\n1 4"]
NoteBelow you can see the graph from the first example:The given path is passing through vertexes $$$1$$$, $$$2$$$, $$$3$$$, $$$4$$$. The sequence $$$1-2-4$$$ is good because it is the subsequence of the given path, its first and the last elements are equal to the first and the last elements of the given path respectively, and the shortest path passing through vertexes $$$1$$$, $$$2$$$ and $$$4$$$ in that order is $$$1-2-3-4$$$. Note that subsequences $$$1-4$$$ and $$$1-3-4$$$ aren't good because in both cases the shortest path passing through the vertexes of these sequences is $$$1-3-4$$$.In the third example, the graph is full so any sequence of vertexes in which any two consecutive elements are distinct defines a path consisting of the same number of vertexes.In the fourth example, the paths $$$1-2-4$$$ and $$$1-3-4$$$ are the shortest paths passing through the vertexes $$$1$$$ and $$$4$$$.
Java 11
standard input
[ "dp", "graphs", "greedy", "shortest paths" ]
c9d07fdf0d3293d5564275ebbabbcf12
The first line contains a single integer $$$n$$$ ($$$2 \le n \le 100$$$)Β β€” the number of vertexes in a graph. The next $$$n$$$ lines define the graph by an adjacency matrix: the $$$j$$$-th character in the $$$i$$$-st line is equal to $$$1$$$ if there is an arc from vertex $$$i$$$ to the vertex $$$j$$$ else it is equal to $$$0$$$. It is guaranteed that the graph doesn't contain loops. The next line contains a single integer $$$m$$$ ($$$2 \le m \le 10^6$$$)Β β€” the number of vertexes in the path. The next line contains $$$m$$$ integers $$$p_1, p_2, \ldots, p_m$$$ ($$$1 \le p_i \le n$$$)Β β€” the sequence of vertexes in the path. It is guaranteed that for any $$$1 \leq i &lt; m$$$ there is an arc from $$$p_i$$$ to $$$p_{i+1}$$$.
1,700
In the first line output a single integer $$$k$$$ ($$$2 \leq k \leq m$$$)Β β€” the length of the shortest good subsequence. In the second line output $$$k$$$ integers $$$v_1$$$, $$$\ldots$$$, $$$v_k$$$ ($$$1 \leq v_i \leq n$$$)Β β€” the vertexes in the subsequence. If there are multiple shortest subsequences, print any. Any two consecutive numbers should be distinct.
standard output
PASSED
8c37793b552f38f3ce96c2e1359a9212
train_000.jsonl
1443430800
The capital of Berland has n multifloor buildings. The architect who built up the capital was very creative, so all the houses were built in one row.Let's enumerate all the houses from left to right, starting with one. A house is considered to be luxurious if the number of floors in it is strictly greater than in all the houses with larger numbers. In other words, a house is luxurious if the number of floors in it is strictly greater than in all the houses, which are located to the right from it. In this task it is assumed that the heights of floors in the houses are the same.The new architect is interested in n questions, i-th of them is about the following: "how many floors should be added to the i-th house to make it luxurious?" (for all i from 1 to n, inclusive). You need to help him cope with this task.Note that all these questions are independent from each other β€” the answer to the question for house i does not affect other answers (i.e., the floors to the houses are not actually added).
256 megabytes
import java.util.Scanner; public class TT { public static void main(String args[]) { Scanner get=new Scanner(System.in); int n=get.nextInt(); int a[]=new int[n]; int ans[]=new int[n]; for(int i=0;i<n;i++) a[i]=get.nextInt(); int max=a[n-1]; int maxi=n-1; for(int i=a.length-1;i>=0;i--) { if(maxi==i) ans[i]=0; else if(a[i]>max) { max=a[i]; maxi=i; ans[i]=0; } else { ans[i]=max+1-a[i]; } } for(int i=0;i<ans.length;i++) System.out.print(ans[i]+" "); } }
Java
["5\n1 2 3 1 2", "4\n3 2 1 4"]
1 second
["3 2 0 2 0", "2 3 4 0"]
null
Java 7
standard input
[ "implementation", "math" ]
e544ed0904e2def0c1b2d91f94acbc56
The first line of the input contains a single number n (1 ≀ n ≀ 105) β€” the number of houses in the capital of Berland. The second line contains n space-separated positive integers hi (1 ≀ hi ≀ 109), where hi equals the number of floors in the i-th house.
1,100
Print n integers a1, a2, ..., an, where number ai is the number of floors that need to be added to the house number i to make it luxurious. If the house is already luxurious and nothing needs to be added to it, then ai should be equal to zero. All houses are numbered from left to right, starting from one.
standard output
PASSED
086abad4a9630e0792e79479b89de44c
train_000.jsonl
1443430800
The capital of Berland has n multifloor buildings. The architect who built up the capital was very creative, so all the houses were built in one row.Let's enumerate all the houses from left to right, starting with one. A house is considered to be luxurious if the number of floors in it is strictly greater than in all the houses with larger numbers. In other words, a house is luxurious if the number of floors in it is strictly greater than in all the houses, which are located to the right from it. In this task it is assumed that the heights of floors in the houses are the same.The new architect is interested in n questions, i-th of them is about the following: "how many floors should be added to the i-th house to make it luxurious?" (for all i from 1 to n, inclusive). You need to help him cope with this task.Note that all these questions are independent from each other β€” the answer to the question for house i does not affect other answers (i.e., the floors to the houses are not actually added).
256 megabytes
import java.util.Scanner; public class PB { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Communication S=new Communication(); int n=S.i(); int[] a=S.is(); int M=0; for(int i=n-1;i>-1;i--){ if(a[i]>M){ M=a[i]; a[i]=0; }else{ a[i]=M+1-a[i]; } } for(int i=0;i<n;i++){ S.sendw(a[i]+" "); } } ///////////////////////////////////// static class Communication { Scanner sc; public static void send(Object x){ System.out.println(x); } public static void sendw(Object x){ System.out.print(x); } public Communication(){ sc=new Scanner(System.in); } public int i(){ return Integer.valueOf(sc.nextLine()); } public int[] is(){ String s=sc.nextLine(); String[] s2=s.split(" "); int[] j=new int[s2.length]; for(int i=0;i<s2.length;i++){ j[i]=Integer.valueOf(s2[i]); } return j; } public String s(){ return sc.nextLine(); } public String[] ss(){ return sc.nextLine().split(" "); } public char c(){ return sc.nextLine().charAt(0); } public char[] cs(){ return sc.nextLine().toCharArray(); } public long l(){ return Long.valueOf(sc.nextLine()); } } }
Java
["5\n1 2 3 1 2", "4\n3 2 1 4"]
1 second
["3 2 0 2 0", "2 3 4 0"]
null
Java 7
standard input
[ "implementation", "math" ]
e544ed0904e2def0c1b2d91f94acbc56
The first line of the input contains a single number n (1 ≀ n ≀ 105) β€” the number of houses in the capital of Berland. The second line contains n space-separated positive integers hi (1 ≀ hi ≀ 109), where hi equals the number of floors in the i-th house.
1,100
Print n integers a1, a2, ..., an, where number ai is the number of floors that need to be added to the house number i to make it luxurious. If the house is already luxurious and nothing needs to be added to it, then ai should be equal to zero. All houses are numbered from left to right, starting from one.
standard output
PASSED
bd30d9a3571bbc10e29ee8acb8e00155
train_000.jsonl
1443430800
The capital of Berland has n multifloor buildings. The architect who built up the capital was very creative, so all the houses were built in one row.Let's enumerate all the houses from left to right, starting with one. A house is considered to be luxurious if the number of floors in it is strictly greater than in all the houses with larger numbers. In other words, a house is luxurious if the number of floors in it is strictly greater than in all the houses, which are located to the right from it. In this task it is assumed that the heights of floors in the houses are the same.The new architect is interested in n questions, i-th of them is about the following: "how many floors should be added to the i-th house to make it luxurious?" (for all i from 1 to n, inclusive). You need to help him cope with this task.Note that all these questions are independent from each other β€” the answer to the question for house i does not affect other answers (i.e., the floors to the houses are not actually added).
256 megabytes
import java.util.Scanner; public class LuxHourses { public static void main(String[] args) { Scanner s = new Scanner(System.in); int n = s.nextInt(); int[] hs = new int[n]; for(int i = 0; i < n; i++) { hs[i] = s.nextInt(); } int[] lux = new int[n]; int max = 0; for(int i = n-1; i >= 0; i--) { if(hs[i] > max) { lux[i] = 0; max = hs[i]; } else { lux[i] = (max - hs[i]) +1; } } for(int i = 0; i < n ; i++) { System.out.print(lux[i]+" "); } } }
Java
["5\n1 2 3 1 2", "4\n3 2 1 4"]
1 second
["3 2 0 2 0", "2 3 4 0"]
null
Java 7
standard input
[ "implementation", "math" ]
e544ed0904e2def0c1b2d91f94acbc56
The first line of the input contains a single number n (1 ≀ n ≀ 105) β€” the number of houses in the capital of Berland. The second line contains n space-separated positive integers hi (1 ≀ hi ≀ 109), where hi equals the number of floors in the i-th house.
1,100
Print n integers a1, a2, ..., an, where number ai is the number of floors that need to be added to the house number i to make it luxurious. If the house is already luxurious and nothing needs to be added to it, then ai should be equal to zero. All houses are numbered from left to right, starting from one.
standard output
PASSED
80b99755076246c5e0ea4030f28967fc
train_000.jsonl
1443430800
The capital of Berland has n multifloor buildings. The architect who built up the capital was very creative, so all the houses were built in one row.Let's enumerate all the houses from left to right, starting with one. A house is considered to be luxurious if the number of floors in it is strictly greater than in all the houses with larger numbers. In other words, a house is luxurious if the number of floors in it is strictly greater than in all the houses, which are located to the right from it. In this task it is assumed that the heights of floors in the houses are the same.The new architect is interested in n questions, i-th of them is about the following: "how many floors should be added to the i-th house to make it luxurious?" (for all i from 1 to n, inclusive). You need to help him cope with this task.Note that all these questions are independent from each other β€” the answer to the question for house i does not affect other answers (i.e., the floors to the houses are not actually added).
256 megabytes
import java.io.*; import java.util.*; public class Solver{ public static void main(String args[]){ try{ Scanner sc = new Scanner(System.in); int T = sc.nextInt(); int values[] = new int[T]; int floors[] = new int[T]; for (int i = 0; i < T; i++) values[i] = sc.nextInt(); int max = values[T - 1]; floors[T-1] = 0; for (int i = T - 2; i >= 0; i--) { if (values[i] > max){ max = values[i]; floors[i] = 0; } else floors[i] = max - values[i] + 1; } for (int i = 0; i < floors.length; i++) System.out.println(floors[i]); sc.close(); } catch(Exception e){ System.out.println(e); } } }
Java
["5\n1 2 3 1 2", "4\n3 2 1 4"]
1 second
["3 2 0 2 0", "2 3 4 0"]
null
Java 7
standard input
[ "implementation", "math" ]
e544ed0904e2def0c1b2d91f94acbc56
The first line of the input contains a single number n (1 ≀ n ≀ 105) β€” the number of houses in the capital of Berland. The second line contains n space-separated positive integers hi (1 ≀ hi ≀ 109), where hi equals the number of floors in the i-th house.
1,100
Print n integers a1, a2, ..., an, where number ai is the number of floors that need to be added to the house number i to make it luxurious. If the house is already luxurious and nothing needs to be added to it, then ai should be equal to zero. All houses are numbered from left to right, starting from one.
standard output
PASSED
ca1b206e11d82449c54e7d7f757024d1
train_000.jsonl
1443430800
The capital of Berland has n multifloor buildings. The architect who built up the capital was very creative, so all the houses were built in one row.Let's enumerate all the houses from left to right, starting with one. A house is considered to be luxurious if the number of floors in it is strictly greater than in all the houses with larger numbers. In other words, a house is luxurious if the number of floors in it is strictly greater than in all the houses, which are located to the right from it. In this task it is assumed that the heights of floors in the houses are the same.The new architect is interested in n questions, i-th of them is about the following: "how many floors should be added to the i-th house to make it luxurious?" (for all i from 1 to n, inclusive). You need to help him cope with this task.Note that all these questions are independent from each other β€” the answer to the question for house i does not affect other answers (i.e., the floors to the houses are not actually added).
256 megabytes
import java.lang.*; import java.io.*; import java.util.*; public class Houses { public static void main(String[] args) throws java.lang.Exception { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskA solver = new TaskA(); solver.solve(in, out); out.close(); } } class TaskA { public void solve(InputReader in, PrintWriter out) { int n = in.nextInt(); int[] a = new int[n]; int[] ans = new int[n]; int mx = 0; int i, j, k; for (i=0; i<n; ++i) a[i] = in.nextInt(); for (i=n-1; i>=0; --i) { ans[i] = mx<a[i] ? 0:mx-a[i]+1; mx = mx>a[i] ? mx:a[i]; } for (i=0; i<n; ++i) out.print(ans[i] + " "); out.println(); } } 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
["5\n1 2 3 1 2", "4\n3 2 1 4"]
1 second
["3 2 0 2 0", "2 3 4 0"]
null
Java 7
standard input
[ "implementation", "math" ]
e544ed0904e2def0c1b2d91f94acbc56
The first line of the input contains a single number n (1 ≀ n ≀ 105) β€” the number of houses in the capital of Berland. The second line contains n space-separated positive integers hi (1 ≀ hi ≀ 109), where hi equals the number of floors in the i-th house.
1,100
Print n integers a1, a2, ..., an, where number ai is the number of floors that need to be added to the house number i to make it luxurious. If the house is already luxurious and nothing needs to be added to it, then ai should be equal to zero. All houses are numbered from left to right, starting from one.
standard output
PASSED
c70476ebfbf2e42d2a6c85413bec0e41
train_000.jsonl
1443430800
The capital of Berland has n multifloor buildings. The architect who built up the capital was very creative, so all the houses were built in one row.Let's enumerate all the houses from left to right, starting with one. A house is considered to be luxurious if the number of floors in it is strictly greater than in all the houses with larger numbers. In other words, a house is luxurious if the number of floors in it is strictly greater than in all the houses, which are located to the right from it. In this task it is assumed that the heights of floors in the houses are the same.The new architect is interested in n questions, i-th of them is about the following: "how many floors should be added to the i-th house to make it luxurious?" (for all i from 1 to n, inclusive). You need to help him cope with this task.Note that all these questions are independent from each other β€” the answer to the question for house i does not affect other answers (i.e., the floors to the houses are not actually added).
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Scanner; public class B { int n; long h[]; void readInput() throws NumberFormatException, IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); //Scanner sc = new Scanner(System.in); n = Integer.parseInt(br.readLine()); String s = br.readLine(); String ss[] = s.split(" "); h = new long[n]; for(int i=0; i<n; i++) h[i] = Integer.parseInt(ss[i]); } void solve(){ long a[] = new long[n]; long mm = h[n-1]; for(int i=n-2;i>=0;i--){ if (h[i]<=mm) a[i] = mm-h[i]+1; if (h[i]>mm) mm = h[i]; } for(int i=0; i<n; i++) System.out.print(a[i]+" "); } public static void main(String[] args) throws NumberFormatException, IOException { B a = new B(); a.readInput(); a.solve(); } }
Java
["5\n1 2 3 1 2", "4\n3 2 1 4"]
1 second
["3 2 0 2 0", "2 3 4 0"]
null
Java 7
standard input
[ "implementation", "math" ]
e544ed0904e2def0c1b2d91f94acbc56
The first line of the input contains a single number n (1 ≀ n ≀ 105) β€” the number of houses in the capital of Berland. The second line contains n space-separated positive integers hi (1 ≀ hi ≀ 109), where hi equals the number of floors in the i-th house.
1,100
Print n integers a1, a2, ..., an, where number ai is the number of floors that need to be added to the house number i to make it luxurious. If the house is already luxurious and nothing needs to be added to it, then ai should be equal to zero. All houses are numbered from left to right, starting from one.
standard output
PASSED
439889153a8d8bd828c2a230f951ad4d
train_000.jsonl
1443430800
The capital of Berland has n multifloor buildings. The architect who built up the capital was very creative, so all the houses were built in one row.Let's enumerate all the houses from left to right, starting with one. A house is considered to be luxurious if the number of floors in it is strictly greater than in all the houses with larger numbers. In other words, a house is luxurious if the number of floors in it is strictly greater than in all the houses, which are located to the right from it. In this task it is assumed that the heights of floors in the houses are the same.The new architect is interested in n questions, i-th of them is about the following: "how many floors should be added to the i-th house to make it luxurious?" (for all i from 1 to n, inclusive). You need to help him cope with this task.Note that all these questions are independent from each other β€” the answer to the question for house i does not affect other answers (i.e., the floors to the houses are not actually added).
256 megabytes
import static java.lang.System.in; import java.io.IOException; public class B { public static void main(String[] args) throws IOException { InputReader in = new InputReader(); int n = in.readInt(); int[] arr = new int[n]; for(int i =0;i<n;i++) { arr[i]=in.readInt(); } int maxi[] = new int[n+1]; for(int i =n-1 ;i>=0;i--) { maxi[i] = Math.max(maxi[i+1] , arr[i]); } for(int i=0;i<n;i++){ int ans = Math.max(0, ((maxi[i+1] + 1) - arr[i])); System.out.print(ans); System.out.print(" "); } System.out.println(); } final static class InputReader { byte[] buffer = new byte[8192]; int offset = 0; int bufferSize = 0; public int readInt() throws IOException { int number = 0; int s = 1; if (offset == bufferSize) { offset = 0; bufferSize = in.read(buffer); } if (bufferSize == -1) throw new IOException("No new bytes"); for (; buffer[offset] < 0x30 || buffer[offset] == '-'; ++offset) { if (buffer[offset] == '-') s = -1; if (offset == bufferSize - 1) { offset = -1; bufferSize = in.read(buffer); } } for (; offset < bufferSize && buffer[offset] > 0x2f; ++offset) { number = (number << 3) + (number << 1) + buffer[offset] - 0x30; if (offset == bufferSize - 1) { offset = -1; bufferSize = in.read(buffer); } } ++offset; return number * s; } public int[] readIntArray(int n) throws IOException { int[] ar = new int[n]; for (int i = 0; i < n; i++) ar[i] = readInt(); return ar; } public int[][] readMatrix(int n) throws IOException { int[][] ar = new int[n][n]; for (int i = 0; i < n; i++) ar[i] = readIntArray(n); return ar; } } }
Java
["5\n1 2 3 1 2", "4\n3 2 1 4"]
1 second
["3 2 0 2 0", "2 3 4 0"]
null
Java 7
standard input
[ "implementation", "math" ]
e544ed0904e2def0c1b2d91f94acbc56
The first line of the input contains a single number n (1 ≀ n ≀ 105) β€” the number of houses in the capital of Berland. The second line contains n space-separated positive integers hi (1 ≀ hi ≀ 109), where hi equals the number of floors in the i-th house.
1,100
Print n integers a1, a2, ..., an, where number ai is the number of floors that need to be added to the house number i to make it luxurious. If the house is already luxurious and nothing needs to be added to it, then ai should be equal to zero. All houses are numbered from left to right, starting from one.
standard output
PASSED
362ad9166b22914e59fc93ea9cf950a0
train_000.jsonl
1443430800
The capital of Berland has n multifloor buildings. The architect who built up the capital was very creative, so all the houses were built in one row.Let's enumerate all the houses from left to right, starting with one. A house is considered to be luxurious if the number of floors in it is strictly greater than in all the houses with larger numbers. In other words, a house is luxurious if the number of floors in it is strictly greater than in all the houses, which are located to the right from it. In this task it is assumed that the heights of floors in the houses are the same.The new architect is interested in n questions, i-th of them is about the following: "how many floors should be added to the i-th house to make it luxurious?" (for all i from 1 to n, inclusive). You need to help him cope with this task.Note that all these questions are independent from each other β€” the answer to the question for house i does not affect other answers (i.e., the floors to the houses are not actually added).
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Scanner; public class DevelopingSkill { public static void main(String args[]) throws IOException { @SuppressWarnings("resource") Scanner sc=new Scanner(System.in); int totalHouses = sc.nextInt(); int inparr[] = new int[totalHouses]; ArrayList<Integer> inparray = new ArrayList<Integer>(totalHouses); for(int i=0;i<totalHouses;i++){ inparr[i]=sc.nextInt(); } int maxHt=inparr[totalHouses-1]; int out[] = new int[totalHouses]; out[totalHouses-1]=0; for(int j=totalHouses-2;j>=0;j--) { if(inparr[j] > maxHt) { maxHt=inparr[j]; out[j]=0; } else { out[j]=maxHt-inparr[j]+1; } } for(int output=0;output<totalHouses;output++) { System.out.print(out[output] + " "); } } }
Java
["5\n1 2 3 1 2", "4\n3 2 1 4"]
1 second
["3 2 0 2 0", "2 3 4 0"]
null
Java 7
standard input
[ "implementation", "math" ]
e544ed0904e2def0c1b2d91f94acbc56
The first line of the input contains a single number n (1 ≀ n ≀ 105) β€” the number of houses in the capital of Berland. The second line contains n space-separated positive integers hi (1 ≀ hi ≀ 109), where hi equals the number of floors in the i-th house.
1,100
Print n integers a1, a2, ..., an, where number ai is the number of floors that need to be added to the house number i to make it luxurious. If the house is already luxurious and nothing needs to be added to it, then ai should be equal to zero. All houses are numbered from left to right, starting from one.
standard output
PASSED
fbc927a31bf8eb2ba4f49a45c69d83be
train_000.jsonl
1443430800
The capital of Berland has n multifloor buildings. The architect who built up the capital was very creative, so all the houses were built in one row.Let's enumerate all the houses from left to right, starting with one. A house is considered to be luxurious if the number of floors in it is strictly greater than in all the houses with larger numbers. In other words, a house is luxurious if the number of floors in it is strictly greater than in all the houses, which are located to the right from it. In this task it is assumed that the heights of floors in the houses are the same.The new architect is interested in n questions, i-th of them is about the following: "how many floors should be added to the i-th house to make it luxurious?" (for all i from 1 to n, inclusive). You need to help him cope with this task.Note that all these questions are independent from each other β€” the answer to the question for house i does not affect other answers (i.e., the floors to the houses are not actually added).
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Scanner; public class DevelopingSkill { public static void main(String args[]) throws IOException { @SuppressWarnings("resource") Scanner sc=new Scanner(System.in); //System.out.println("Enter the number in 1 to 10^5"); int totalHouses = sc.nextInt(); //InputStreamReader ir = new InputStreamReader(System.in); //BufferedReader br = new BufferedReader(ir); //String floorsperhouse = br.readLine().trim(); //StringTokenizer st = new StringTokenizer(floorsperhouse); //if(st.countTokens() == totalHouses) //{ //int inparr[] = new int[totalHouses]; ArrayList<Integer> inparray = new ArrayList<Integer>(totalHouses); for(int i=0;i<totalHouses;i++){ inparray.add(sc.nextInt()); } //int outarr[] = new int[totalHouses]; int maxHt=inparray.get(totalHouses-1); //ArrayList<Integer> outarray = new ArrayList<Integer>(totalHouses); int out[] = new int[totalHouses]; out[totalHouses-1]=0; for(int j=totalHouses-2;j>=0;j--) { int inp=inparray.get(j); if(inp > maxHt) { maxHt=inp; out[j]=0; //out[j]=maxHt-inp+1; } else { out[j]=maxHt-inp+1; } } for(int output=0;output<totalHouses;output++) { System.out.print(out[output] + " "); } } }
Java
["5\n1 2 3 1 2", "4\n3 2 1 4"]
1 second
["3 2 0 2 0", "2 3 4 0"]
null
Java 7
standard input
[ "implementation", "math" ]
e544ed0904e2def0c1b2d91f94acbc56
The first line of the input contains a single number n (1 ≀ n ≀ 105) β€” the number of houses in the capital of Berland. The second line contains n space-separated positive integers hi (1 ≀ hi ≀ 109), where hi equals the number of floors in the i-th house.
1,100
Print n integers a1, a2, ..., an, where number ai is the number of floors that need to be added to the house number i to make it luxurious. If the house is already luxurious and nothing needs to be added to it, then ai should be equal to zero. All houses are numbered from left to right, starting from one.
standard output
PASSED
d2fcc3e15ff22aaa1835853b69ac0639
train_000.jsonl
1443430800
The capital of Berland has n multifloor buildings. The architect who built up the capital was very creative, so all the houses were built in one row.Let's enumerate all the houses from left to right, starting with one. A house is considered to be luxurious if the number of floors in it is strictly greater than in all the houses with larger numbers. In other words, a house is luxurious if the number of floors in it is strictly greater than in all the houses, which are located to the right from it. In this task it is assumed that the heights of floors in the houses are the same.The new architect is interested in n questions, i-th of them is about the following: "how many floors should be added to the i-th house to make it luxurious?" (for all i from 1 to n, inclusive). You need to help him cope with this task.Note that all these questions are independent from each other β€” the answer to the question for house i does not affect other answers (i.e., the floors to the houses are not actually added).
256 megabytes
import java.io.PrintWriter; import java.util.*; public class Solution { public static void main(String[] args) { new Solution().run(); } private void run() { Scanner in = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int n = in.nextInt(); int[] h = new int[n]; Map<Integer, Integer> counts = new HashMap<Integer, Integer>(); List<Integer> kinds = new ArrayList<Integer>(); for (int i = 0; i < n; i++) { h[i] = in.nextInt(); if (counts.containsKey(h[i])) counts.put(h[i], counts.get(h[i]) + 1); else { kinds.add(h[i]); counts.put(h[i], 1); } } Collections.sort(kinds); int kindsIndex = kinds.size() - 1; for (int i = 0; i < n; i++) if (h[i] == kinds.get(kindsIndex)) { if (counts.get(h[i]) > 1) out.print("1 "); else out.print("0 "); counts.put(h[i], counts.get(h[i]) - 1); while (kindsIndex >= 0 && counts.get(kinds.get(kindsIndex)) == 0) kindsIndex--; } else { out.print((kinds.get(kindsIndex) - h[i] + 1) + " "); counts.put(h[i], counts.get(h[i]) - 1); } in.close(); out.close(); } }
Java
["5\n1 2 3 1 2", "4\n3 2 1 4"]
1 second
["3 2 0 2 0", "2 3 4 0"]
null
Java 7
standard input
[ "implementation", "math" ]
e544ed0904e2def0c1b2d91f94acbc56
The first line of the input contains a single number n (1 ≀ n ≀ 105) β€” the number of houses in the capital of Berland. The second line contains n space-separated positive integers hi (1 ≀ hi ≀ 109), where hi equals the number of floors in the i-th house.
1,100
Print n integers a1, a2, ..., an, where number ai is the number of floors that need to be added to the house number i to make it luxurious. If the house is already luxurious and nothing needs to be added to it, then ai should be equal to zero. All houses are numbered from left to right, starting from one.
standard output
PASSED
472d449073a131dbbc2501bab7abcacd
train_000.jsonl
1443430800
The capital of Berland has n multifloor buildings. The architect who built up the capital was very creative, so all the houses were built in one row.Let's enumerate all the houses from left to right, starting with one. A house is considered to be luxurious if the number of floors in it is strictly greater than in all the houses with larger numbers. In other words, a house is luxurious if the number of floors in it is strictly greater than in all the houses, which are located to the right from it. In this task it is assumed that the heights of floors in the houses are the same.The new architect is interested in n questions, i-th of them is about the following: "how many floors should be added to the i-th house to make it luxurious?" (for all i from 1 to n, inclusive). You need to help him cope with this task.Note that all these questions are independent from each other β€” the answer to the question for house i does not affect other answers (i.e., the floors to the houses are not actually added).
256 megabytes
import java.io.*; import java.util.Scanner; public class Solution2{ public static void main(String[] args) { Scanner sc = new Scanner(System.in); final int MAXN = 100003; int n; n = sc.nextInt(); int[] rmax = new int[MAXN]; int[] arr = new int[MAXN]; int[] result = new int[MAXN]; for(int i = 0; i < n; i++){ arr[i] = sc.nextInt(); } for(int i = n-1; i > -1; i--){ rmax[i] = Math.max(rmax[i+1], arr[i]); } for(int i = 0; i < n; i++){ result[i] = rmax[i+1] >= arr[i]?rmax[i+1]-arr[i]+1: 0; } for(int i = 0; i < n; i++){ System.out.print(result[i]+" "); } System.out.println(); } }
Java
["5\n1 2 3 1 2", "4\n3 2 1 4"]
1 second
["3 2 0 2 0", "2 3 4 0"]
null
Java 7
standard input
[ "implementation", "math" ]
e544ed0904e2def0c1b2d91f94acbc56
The first line of the input contains a single number n (1 ≀ n ≀ 105) β€” the number of houses in the capital of Berland. The second line contains n space-separated positive integers hi (1 ≀ hi ≀ 109), where hi equals the number of floors in the i-th house.
1,100
Print n integers a1, a2, ..., an, where number ai is the number of floors that need to be added to the house number i to make it luxurious. If the house is already luxurious and nothing needs to be added to it, then ai should be equal to zero. All houses are numbered from left to right, starting from one.
standard output
PASSED
dcc4476ebc5065e50e38f6d6f0e79540
train_000.jsonl
1443430800
The capital of Berland has n multifloor buildings. The architect who built up the capital was very creative, so all the houses were built in one row.Let's enumerate all the houses from left to right, starting with one. A house is considered to be luxurious if the number of floors in it is strictly greater than in all the houses with larger numbers. In other words, a house is luxurious if the number of floors in it is strictly greater than in all the houses, which are located to the right from it. In this task it is assumed that the heights of floors in the houses are the same.The new architect is interested in n questions, i-th of them is about the following: "how many floors should be added to the i-th house to make it luxurious?" (for all i from 1 to n, inclusive). You need to help him cope with this task.Note that all these questions are independent from each other β€” the answer to the question for house i does not affect other answers (i.e., the floors to the houses are not actually added).
256 megabytes
import java.io.*; import java.util.Locale; import java.util.StringTokenizer; public class Main implements Runnable { final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null; BufferedReader in; PrintWriter out; StringTokenizer tok = new StringTokenizer(""); public static void main(String[] args) { new Thread(null, new Main(), "", 128 * (1L << 20)).start(); } void init() throws FileNotFoundException { Locale.setDefault(Locale.US); /*if(!ONLINE_JUDGE){ in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); }else { in = new BufferedReader(new FileReader("gazmyas.in")); out = new PrintWriter("gazmyas.out"); }*/ in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } long timeBegin, timeEnd; void time() { timeEnd = System.currentTimeMillis(); System.err.println("Time = " + (timeEnd - timeBegin)); } public void run() { try { timeBegin = System.currentTimeMillis(); init(); solve(); out.close(); time(); } catch (Exception e) { e.printStackTrace(System.err); System.exit(-1); } } String readString() throws IOException { while (!tok.hasMoreTokens()) { try { tok = new StringTokenizer(in.readLine()); } catch (Exception e) { return null; } } return tok.nextToken(); } String readString(String s) throws IOException { while (!tok.hasMoreTokens()) { try { tok = new StringTokenizer(in.readLine(), s + "\n \t"); } catch (Exception e) { return null; } } return tok.nextToken(); } double readDouble() throws IOException { return Double.parseDouble(readString()); } int readInt() throws IOException { return Integer.parseInt(readString()); } long readLong() throws IOException { return Long.parseLong(readString()); } int readInt(String s) throws IOException { return Integer.parseInt(readString(s)); } boolean isPrime(int a) throws IOException { int del = 0; if (a == 2) { return true; } for (int i = 2; i < Math.sqrt(a) + 1; i++) { if (a % i == 0) { del = i; break; } } if (del > 0) { return false; } else return true; } public long factorial(int num) throws IOException { long res = 1; for (int i = 2; i <= num; i++) { res *= i; } return res; } public int[] readIntArr(int n) throws IOException { int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = readInt(); } return a; } class pair implements Comparable<pair>{ int val, count; @Override public int compareTo(pair pair) { return Integer.compare(val, pair.val); } } void solve() throws Exception{ int n=readInt(); int[] max = new int[n]; int[] indmax = new int[n]; int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i]=readInt(); } max[n-1]=a[n-1]; indmax[n-1]=n-1; for(int i=n-2;i>=0;i--){ if(a[i]>max[i+1]){ max[i]=a[i]; indmax[i]=i; }else{ max[i]=max[i+1]; indmax[i]=indmax[i+1]; } } for (int i = 0; i < n; i++) { if(a[i]==max[i] && indmax[i]==i){ out.print(0+" "); }else{ out.print(max[i]-a[i]+1+" "); } } } }
Java
["5\n1 2 3 1 2", "4\n3 2 1 4"]
1 second
["3 2 0 2 0", "2 3 4 0"]
null
Java 7
standard input
[ "implementation", "math" ]
e544ed0904e2def0c1b2d91f94acbc56
The first line of the input contains a single number n (1 ≀ n ≀ 105) β€” the number of houses in the capital of Berland. The second line contains n space-separated positive integers hi (1 ≀ hi ≀ 109), where hi equals the number of floors in the i-th house.
1,100
Print n integers a1, a2, ..., an, where number ai is the number of floors that need to be added to the house number i to make it luxurious. If the house is already luxurious and nothing needs to be added to it, then ai should be equal to zero. All houses are numbered from left to right, starting from one.
standard output
PASSED
ecb033109587ead6831e1c11974bd895
train_000.jsonl
1443430800
The capital of Berland has n multifloor buildings. The architect who built up the capital was very creative, so all the houses were built in one row.Let's enumerate all the houses from left to right, starting with one. A house is considered to be luxurious if the number of floors in it is strictly greater than in all the houses with larger numbers. In other words, a house is luxurious if the number of floors in it is strictly greater than in all the houses, which are located to the right from it. In this task it is assumed that the heights of floors in the houses are the same.The new architect is interested in n questions, i-th of them is about the following: "how many floors should be added to the i-th house to make it luxurious?" (for all i from 1 to n, inclusive). You need to help him cope with this task.Note that all these questions are independent from each other β€” the answer to the question for house i does not affect other answers (i.e., the floors to the houses are not actually added).
256 megabytes
import java.util.*; import java.io.*; public class Main { public static void main(String [] args)throws Exception{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(br.readLine()); int array[] = new int[n]; StringTokenizer st = new StringTokenizer(br.readLine()); for(int i = 0;i < n;i++){ array[i] = Integer.parseInt(st.nextToken()); } int ans [] = new int[n]; int max = array[n - 1]; for(int i = n - 2;i >= 0;i--){ if(array[i] <= max) ans[i] = max - array[i] + 1; max = Math.max(array[i],max); } StringBuilder sb = new StringBuilder(); for(int i = 0;i < n;i++){ sb.append(ans[i]); sb.append(' '); } System.out.print(sb); } }
Java
["5\n1 2 3 1 2", "4\n3 2 1 4"]
1 second
["3 2 0 2 0", "2 3 4 0"]
null
Java 7
standard input
[ "implementation", "math" ]
e544ed0904e2def0c1b2d91f94acbc56
The first line of the input contains a single number n (1 ≀ n ≀ 105) β€” the number of houses in the capital of Berland. The second line contains n space-separated positive integers hi (1 ≀ hi ≀ 109), where hi equals the number of floors in the i-th house.
1,100
Print n integers a1, a2, ..., an, where number ai is the number of floors that need to be added to the house number i to make it luxurious. If the house is already luxurious and nothing needs to be added to it, then ai should be equal to zero. All houses are numbered from left to right, starting from one.
standard output
PASSED
e637b5b4c0250b83280bb9112598f0e5
train_000.jsonl
1443430800
The capital of Berland has n multifloor buildings. The architect who built up the capital was very creative, so all the houses were built in one row.Let's enumerate all the houses from left to right, starting with one. A house is considered to be luxurious if the number of floors in it is strictly greater than in all the houses with larger numbers. In other words, a house is luxurious if the number of floors in it is strictly greater than in all the houses, which are located to the right from it. In this task it is assumed that the heights of floors in the houses are the same.The new architect is interested in n questions, i-th of them is about the following: "how many floors should be added to the i-th house to make it luxurious?" (for all i from 1 to n, inclusive). You need to help him cope with this task.Note that all these questions are independent from each other β€” the answer to the question for house i does not affect other answers (i.e., the floors to the houses are not actually added).
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.BufferedWriter; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.*; public class B581 { 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.readInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = in.readInt(); } int max = a[n-1]; int[] ans = new int[n]; ans[n-1] = 0; for (int i = n-2; i >=0; i--) { if (a[i] > max) { ans[i] = 0; max = a[i]; } else { ans[i] = max - a[i] +1; } } for (int i:ans) { System.out.print(i + " "); } } } static class IOUtils { public static int[] readIntArray(InputReader in, int size) { int[] array = new int[size]; for (int i = 0; i < size; i++) { array[i] = in.readInt(); } return array; } } 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; 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 char readCharacter() { int c = read(); while (isSpaceChar(c)) { c = read(); } return (char) c; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["5\n1 2 3 1 2", "4\n3 2 1 4"]
1 second
["3 2 0 2 0", "2 3 4 0"]
null
Java 7
standard input
[ "implementation", "math" ]
e544ed0904e2def0c1b2d91f94acbc56
The first line of the input contains a single number n (1 ≀ n ≀ 105) β€” the number of houses in the capital of Berland. The second line contains n space-separated positive integers hi (1 ≀ hi ≀ 109), where hi equals the number of floors in the i-th house.
1,100
Print n integers a1, a2, ..., an, where number ai is the number of floors that need to be added to the house number i to make it luxurious. If the house is already luxurious and nothing needs to be added to it, then ai should be equal to zero. All houses are numbered from left to right, starting from one.
standard output
PASSED
ee77a38f88c46e76e765acb6da4ebdca
train_000.jsonl
1443430800
The capital of Berland has n multifloor buildings. The architect who built up the capital was very creative, so all the houses were built in one row.Let's enumerate all the houses from left to right, starting with one. A house is considered to be luxurious if the number of floors in it is strictly greater than in all the houses with larger numbers. In other words, a house is luxurious if the number of floors in it is strictly greater than in all the houses, which are located to the right from it. In this task it is assumed that the heights of floors in the houses are the same.The new architect is interested in n questions, i-th of them is about the following: "how many floors should be added to the i-th house to make it luxurious?" (for all i from 1 to n, inclusive). You need to help him cope with this task.Note that all these questions are independent from each other β€” the answer to the question for house i does not affect other answers (i.e., the floors to the houses are not actually added).
256 megabytes
import java.util.Scanner; public class mainClass { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n= in.nextInt(); int [] floors =new int[100000]; for(int i=0;i<n;i++) { floors[i]=in.nextInt(); } int[] out = new int[100000]; out[n-1]=0; int max1 =floors[n-1]; for(int i=n-2;i>=0;i--){ max1=Math.max(max1,floors[i+1]); out[i]=(max1<floors[i])?0:(max1-floors[i]+1); } for(int i=0; i<n;i++){ System.out.print(out[i]+" "); } } }
Java
["5\n1 2 3 1 2", "4\n3 2 1 4"]
1 second
["3 2 0 2 0", "2 3 4 0"]
null
Java 7
standard input
[ "implementation", "math" ]
e544ed0904e2def0c1b2d91f94acbc56
The first line of the input contains a single number n (1 ≀ n ≀ 105) β€” the number of houses in the capital of Berland. The second line contains n space-separated positive integers hi (1 ≀ hi ≀ 109), where hi equals the number of floors in the i-th house.
1,100
Print n integers a1, a2, ..., an, where number ai is the number of floors that need to be added to the house number i to make it luxurious. If the house is already luxurious and nothing needs to be added to it, then ai should be equal to zero. All houses are numbered from left to right, starting from one.
standard output
PASSED
6b294ce17c5652c04932f5107ada1fd5
train_000.jsonl
1443430800
The capital of Berland has n multifloor buildings. The architect who built up the capital was very creative, so all the houses were built in one row.Let's enumerate all the houses from left to right, starting with one. A house is considered to be luxurious if the number of floors in it is strictly greater than in all the houses with larger numbers. In other words, a house is luxurious if the number of floors in it is strictly greater than in all the houses, which are located to the right from it. In this task it is assumed that the heights of floors in the houses are the same.The new architect is interested in n questions, i-th of them is about the following: "how many floors should be added to the i-th house to make it luxurious?" (for all i from 1 to n, inclusive). You need to help him cope with this task.Note that all these questions are independent from each other β€” the answer to the question for house i does not affect other answers (i.e., the floors to the houses are not actually added).
256 megabytes
import java.util.Arrays; import java.util.Scanner; public class floors { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int n=sc.nextInt(); int a[]=new int[n]; int b[]=new int[n]; int c[]=new int[n]; for(int i=0;i<n;i++) { a[i]=sc.nextInt(); } int max=0; //max=a[n-1]; for(int i=n-1;i>=0;i--) { if(max<a[i]) { b[i]=0; } else { b[i]=max+1-a[i]; } max=Math.max(a[i],max); } for (int i = 0; i < b.length; i++) { System.out.print(b[i]+" "); } sc.close(); } }
Java
["5\n1 2 3 1 2", "4\n3 2 1 4"]
1 second
["3 2 0 2 0", "2 3 4 0"]
null
Java 7
standard input
[ "implementation", "math" ]
e544ed0904e2def0c1b2d91f94acbc56
The first line of the input contains a single number n (1 ≀ n ≀ 105) β€” the number of houses in the capital of Berland. The second line contains n space-separated positive integers hi (1 ≀ hi ≀ 109), where hi equals the number of floors in the i-th house.
1,100
Print n integers a1, a2, ..., an, where number ai is the number of floors that need to be added to the house number i to make it luxurious. If the house is already luxurious and nothing needs to be added to it, then ai should be equal to zero. All houses are numbered from left to right, starting from one.
standard output
PASSED
cc7619fd257f57a0b1add2bc72842526
train_000.jsonl
1443430800
The capital of Berland has n multifloor buildings. The architect who built up the capital was very creative, so all the houses were built in one row.Let's enumerate all the houses from left to right, starting with one. A house is considered to be luxurious if the number of floors in it is strictly greater than in all the houses with larger numbers. In other words, a house is luxurious if the number of floors in it is strictly greater than in all the houses, which are located to the right from it. In this task it is assumed that the heights of floors in the houses are the same.The new architect is interested in n questions, i-th of them is about the following: "how many floors should be added to the i-th house to make it luxurious?" (for all i from 1 to n, inclusive). You need to help him cope with this task.Note that all these questions are independent from each other β€” the answer to the question for house i does not affect other answers (i.e., the floors to the houses are not actually added).
256 megabytes
import java.io.*; import java.util.*; public class main { static BufferedReader in; static PrintWriter out; static StringTokenizer tok; static String next() throws IOException{ while ( tok == null || !tok.hasMoreTokens()){ tok = new StringTokenizer(in.readLine()); } return tok.nextToken(); } static String nextLine() throws IOException{ tok = new StringTokenizer(""); return in.readLine(); } static int nextInt() throws IOException{ return Integer.parseInt(next()); } public static void main(String[] args) throws IOException { // TODO Auto-generated method stub in = new BufferedReader(new InputStreamReader(System.in)); int n = nextInt(); int ar[] = new int[100000]; int MAXar[] = new int[100000]; for (int i = 0; i<n; i++) ar[i] = nextInt(); int max = 0; for (int i = n-1; i>=0;i--){ if (ar[i]>max) { max = ar[i]; MAXar[i]=0; } else{ MAXar[i]= max - ar[i]+1; } } for (int i = 0; i<n; i++){ System.out.print(MAXar[i]); System.out.print(' '); } } }
Java
["5\n1 2 3 1 2", "4\n3 2 1 4"]
1 second
["3 2 0 2 0", "2 3 4 0"]
null
Java 7
standard input
[ "implementation", "math" ]
e544ed0904e2def0c1b2d91f94acbc56
The first line of the input contains a single number n (1 ≀ n ≀ 105) β€” the number of houses in the capital of Berland. The second line contains n space-separated positive integers hi (1 ≀ hi ≀ 109), where hi equals the number of floors in the i-th house.
1,100
Print n integers a1, a2, ..., an, where number ai is the number of floors that need to be added to the house number i to make it luxurious. If the house is already luxurious and nothing needs to be added to it, then ai should be equal to zero. All houses are numbered from left to right, starting from one.
standard output
PASSED
d4f44158fd5f243634d829c14b32ca58
train_000.jsonl
1443430800
The capital of Berland has n multifloor buildings. The architect who built up the capital was very creative, so all the houses were built in one row.Let's enumerate all the houses from left to right, starting with one. A house is considered to be luxurious if the number of floors in it is strictly greater than in all the houses with larger numbers. In other words, a house is luxurious if the number of floors in it is strictly greater than in all the houses, which are located to the right from it. In this task it is assumed that the heights of floors in the houses are the same.The new architect is interested in n questions, i-th of them is about the following: "how many floors should be added to the i-th house to make it luxurious?" (for all i from 1 to n, inclusive). You need to help him cope with this task.Note that all these questions are independent from each other β€” the answer to the question for house i does not affect other answers (i.e., the floors to the houses are not actually added).
256 megabytes
import java.util.Scanner; public class LuxuriousHouses { public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc = new Scanner(System.in); int numOfHouse = sc.nextInt(); int[] floors = new int[numOfHouse]; for(int i=0; i<numOfHouse; i++){ floors[i] = sc.nextInt(); } int[] max = new int[numOfHouse]; int maxval = floors[numOfHouse-1]; for(int i=numOfHouse-2; i>=0; i--){ if(maxval < floors[i]){ max[i] = floors[i]; maxval = floors[i]; } else if(maxval == floors[i]){ max[i] = -1; } else { max[i] = maxval; } } /* for(int i=0; i<max.length; i++) System.out.print(max[i]+" "); */ int[] result = new int[numOfHouse]; for(int i=0; i<numOfHouse; i++){ if(max[i] < 0){ result[i] = 1; } else if(floors[i] < max[i]){ result[i] = (max[i]-floors[i])+1; } else if(floors[i] == max[i]){ result[i] = 0; } } for(int i=0; i<numOfHouse; i++) System.out.print(result[i]+" "); } /* static int getMax(int index, int[] floors){ int max = floors[index]; int val = index; for(int i=index; i<floors.length; i++){ if(floors[i] > max){ max = floors[i]; val = i; } } return val; } */ }
Java
["5\n1 2 3 1 2", "4\n3 2 1 4"]
1 second
["3 2 0 2 0", "2 3 4 0"]
null
Java 7
standard input
[ "implementation", "math" ]
e544ed0904e2def0c1b2d91f94acbc56
The first line of the input contains a single number n (1 ≀ n ≀ 105) β€” the number of houses in the capital of Berland. The second line contains n space-separated positive integers hi (1 ≀ hi ≀ 109), where hi equals the number of floors in the i-th house.
1,100
Print n integers a1, a2, ..., an, where number ai is the number of floors that need to be added to the house number i to make it luxurious. If the house is already luxurious and nothing needs to be added to it, then ai should be equal to zero. All houses are numbered from left to right, starting from one.
standard output
PASSED
27768c6700bd3917cb6254e7a79bca92
train_000.jsonl
1443430800
The capital of Berland has n multifloor buildings. The architect who built up the capital was very creative, so all the houses were built in one row.Let's enumerate all the houses from left to right, starting with one. A house is considered to be luxurious if the number of floors in it is strictly greater than in all the houses with larger numbers. In other words, a house is luxurious if the number of floors in it is strictly greater than in all the houses, which are located to the right from it. In this task it is assumed that the heights of floors in the houses are the same.The new architect is interested in n questions, i-th of them is about the following: "how many floors should be added to the i-th house to make it luxurious?" (for all i from 1 to n, inclusive). You need to help him cope with this task.Note that all these questions are independent from each other β€” the answer to the question for house i does not affect other answers (i.e., the floors to the houses are not actually added).
256 megabytes
import java.util.Scanner; import java.util.TreeMap; import java.util.TreeSet; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Hashtable; import java.util.InputMismatchException; import java.util.LinkedList; import java.util.Map; import java.util.PriorityQueue; public class R3221{ public static void main(String args[]){ FasterScanner s=new FasterScanner(); PrintWriter out=new PrintWriter(System.out); n=s.nextInt(); for(int i=n;i<2*n;i++){ t[i]=s.nextInt(); } build(); //System.out.println(query(3,4)); for(int i=0;i<n;i++){ int k=query(i+1,n); //System.out.println(t[i]); if(t[i+n]>k) out.print(0+" "); else out.print((k-t[n+i]+1)+" "); } out.close(); } static int N = (int) 1e5; // limit for array size static int n; // array size static int t[]=new int[2*N]; static void build() { // build the tree for (int i = n - 1; i > 0; --i) t[i] = Math.max(t[i<<1] , t[i<<1|1]); } void modify(int p, int value) { // set value at position p for (t[p += n] = value; p > 1; p >>= 1) t[p>>1] = t[p] + t[p^1]; } static int query(int l, int r) { // sum on interval [l, r) int res = 0; for (l += n, r += n; l < r; l >>= 1, r >>= 1) { if ((l&1)!=0) res = Math.max(res,t[l++]); if ((r&1)!=0) res = Math.max(res, t[--r]); } return res; } public static class FasterScanner { private byte[] buf = new byte[1024]; private int curChar; private int numChars; public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = System.in.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public String nextString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = nextInt(); } return arr; } public long[] nextLongArray(int n) { long[] arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = nextLong(); } return arr; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } } }
Java
["5\n1 2 3 1 2", "4\n3 2 1 4"]
1 second
["3 2 0 2 0", "2 3 4 0"]
null
Java 7
standard input
[ "implementation", "math" ]
e544ed0904e2def0c1b2d91f94acbc56
The first line of the input contains a single number n (1 ≀ n ≀ 105) β€” the number of houses in the capital of Berland. The second line contains n space-separated positive integers hi (1 ≀ hi ≀ 109), where hi equals the number of floors in the i-th house.
1,100
Print n integers a1, a2, ..., an, where number ai is the number of floors that need to be added to the house number i to make it luxurious. If the house is already luxurious and nothing needs to be added to it, then ai should be equal to zero. All houses are numbered from left to right, starting from one.
standard output
PASSED
df2ee48180ab7250c7b7adfc45234a3d
train_000.jsonl
1443430800
The capital of Berland has n multifloor buildings. The architect who built up the capital was very creative, so all the houses were built in one row.Let's enumerate all the houses from left to right, starting with one. A house is considered to be luxurious if the number of floors in it is strictly greater than in all the houses with larger numbers. In other words, a house is luxurious if the number of floors in it is strictly greater than in all the houses, which are located to the right from it. In this task it is assumed that the heights of floors in the houses are the same.The new architect is interested in n questions, i-th of them is about the following: "how many floors should be added to the i-th house to make it luxurious?" (for all i from 1 to n, inclusive). You need to help him cope with this task.Note that all these questions are independent from each other β€” the answer to the question for house i does not affect other answers (i.e., the floors to the houses are not actually added).
256 megabytes
import java.util.*; public class CF581B { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int[] a = new int[n]; for(int i = 0; i < n; i ++) a[i] = in.nextInt(); int max = a[n -1] - 1; for(int i = n - 1; i > -1; i --) { int t = a[i]; a[i] = Math.max(max - a[i] + 1, 0); max = Math.max(max, t); } for(int i = 0; i < n; i ++) System.out.print(a[i] + " "); } }
Java
["5\n1 2 3 1 2", "4\n3 2 1 4"]
1 second
["3 2 0 2 0", "2 3 4 0"]
null
Java 7
standard input
[ "implementation", "math" ]
e544ed0904e2def0c1b2d91f94acbc56
The first line of the input contains a single number n (1 ≀ n ≀ 105) β€” the number of houses in the capital of Berland. The second line contains n space-separated positive integers hi (1 ≀ hi ≀ 109), where hi equals the number of floors in the i-th house.
1,100
Print n integers a1, a2, ..., an, where number ai is the number of floors that need to be added to the house number i to make it luxurious. If the house is already luxurious and nothing needs to be added to it, then ai should be equal to zero. All houses are numbered from left to right, starting from one.
standard output
PASSED
7bc913785b91a5c0fe3ff91c28ccc1af
train_000.jsonl
1443430800
The capital of Berland has n multifloor buildings. The architect who built up the capital was very creative, so all the houses were built in one row.Let's enumerate all the houses from left to right, starting with one. A house is considered to be luxurious if the number of floors in it is strictly greater than in all the houses with larger numbers. In other words, a house is luxurious if the number of floors in it is strictly greater than in all the houses, which are located to the right from it. In this task it is assumed that the heights of floors in the houses are the same.The new architect is interested in n questions, i-th of them is about the following: "how many floors should be added to the i-th house to make it luxurious?" (for all i from 1 to n, inclusive). You need to help him cope with this task.Note that all these questions are independent from each other β€” the answer to the question for house i does not affect other answers (i.e., the floors to the houses are not actually added).
256 megabytes
import java.io.*; import java.util.*; public class b1 { public static void main(String[] args) throws FileNotFoundException { Scanner in = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int n = in.nextInt(); int h[] = new int[n]; for (int i = 0; i < n; i++) { h[i] = in.nextInt(); } int ans[] = new int[n]; int max = 0; for (int i = n - 1; i > -1; i--) { ans[i] = Math.max(max - h[i] + 1, 0); max = Math.max(max, h[i]); } for (int i = 0; i < n; i++) { out.print(ans[i] + " "); } out.close(); } }
Java
["5\n1 2 3 1 2", "4\n3 2 1 4"]
1 second
["3 2 0 2 0", "2 3 4 0"]
null
Java 7
standard input
[ "implementation", "math" ]
e544ed0904e2def0c1b2d91f94acbc56
The first line of the input contains a single number n (1 ≀ n ≀ 105) β€” the number of houses in the capital of Berland. The second line contains n space-separated positive integers hi (1 ≀ hi ≀ 109), where hi equals the number of floors in the i-th house.
1,100
Print n integers a1, a2, ..., an, where number ai is the number of floors that need to be added to the house number i to make it luxurious. If the house is already luxurious and nothing needs to be added to it, then ai should be equal to zero. All houses are numbered from left to right, starting from one.
standard output
PASSED
4c90e7ad7ec4b68c92ed5ab48f072ef7
train_000.jsonl
1443430800
The capital of Berland has n multifloor buildings. The architect who built up the capital was very creative, so all the houses were built in one row.Let's enumerate all the houses from left to right, starting with one. A house is considered to be luxurious if the number of floors in it is strictly greater than in all the houses with larger numbers. In other words, a house is luxurious if the number of floors in it is strictly greater than in all the houses, which are located to the right from it. In this task it is assumed that the heights of floors in the houses are the same.The new architect is interested in n questions, i-th of them is about the following: "how many floors should be added to the i-th house to make it luxurious?" (for all i from 1 to n, inclusive). You need to help him cope with this task.Note that all these questions are independent from each other β€” the answer to the question for house i does not affect other answers (i.e., the floors to the houses are not actually added).
256 megabytes
import java.io.BufferedReader; import java.io.FileReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; public class Codeforces { StringTokenizer tok; BufferedReader in; PrintWriter out; final boolean OJ = System.getProperty("ONLINE_JUDGE") != null; String filename = null; void init() { try { if (OJ) { if (filename == null) { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } else { in = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter("output.txt"); } } else { in = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter("output.txt"); } } catch (Exception e) { throw new RuntimeException(e); } } String readString() { try { while (tok == null || !tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); } return tok.nextToken(); } catch (Throwable t) { throw new RuntimeException(t); } } int readInt() { return Integer.parseInt(readString()); } long readLong() { return Long.parseLong(readString()); } public static void main(String[] args) { new Codeforces().run(); } void run() { init(); long time = System.currentTimeMillis(); solve(); System.err.println(System.currentTimeMillis() - time); out.close(); } void solve() { int n = readInt(); int[] a = new int[n]; for (int i=0;i<n;i++) { a[i] = readInt(); } int max = 0; int[] ans = new int[n]; ans[n - 1] = 0; max = a[n - 1]; for (int i=n-2;i>=0;i--) { ans[i] = Math.max(0, max + 1 - a[i]); max = Math.max(max,a[i]); } for (int i=0;i<n;i++) out.print(ans[i] + " "); } }
Java
["5\n1 2 3 1 2", "4\n3 2 1 4"]
1 second
["3 2 0 2 0", "2 3 4 0"]
null
Java 7
standard input
[ "implementation", "math" ]
e544ed0904e2def0c1b2d91f94acbc56
The first line of the input contains a single number n (1 ≀ n ≀ 105) β€” the number of houses in the capital of Berland. The second line contains n space-separated positive integers hi (1 ≀ hi ≀ 109), where hi equals the number of floors in the i-th house.
1,100
Print n integers a1, a2, ..., an, where number ai is the number of floors that need to be added to the house number i to make it luxurious. If the house is already luxurious and nothing needs to be added to it, then ai should be equal to zero. All houses are numbered from left to right, starting from one.
standard output
PASSED
0b4c1b20aad7b3bea052a614fa2fba31
train_000.jsonl
1443430800
The capital of Berland has n multifloor buildings. The architect who built up the capital was very creative, so all the houses were built in one row.Let's enumerate all the houses from left to right, starting with one. A house is considered to be luxurious if the number of floors in it is strictly greater than in all the houses with larger numbers. In other words, a house is luxurious if the number of floors in it is strictly greater than in all the houses, which are located to the right from it. In this task it is assumed that the heights of floors in the houses are the same.The new architect is interested in n questions, i-th of them is about the following: "how many floors should be added to the i-th house to make it luxurious?" (for all i from 1 to n, inclusive). You need to help him cope with this task.Note that all these questions are independent from each other β€” the answer to the question for house i does not affect other answers (i.e., the floors to the houses are not actually added).
256 megabytes
import java.util.*; import java.lang.Math; public class Sample1 { public static void main(String args[]){ int n; long h[], maxr; h = new long[100000]; Scanner sc = new Scanner(System.in); n = sc.nextInt(); for(int i = 0; i < n; i++){ h[i] = sc.nextInt(); } maxr = h[n-1]; h[n - 1] = 0; for(int i = (n - 2); i >= 0; i--){ if(h[i] <= maxr){ h[i] = (maxr - h[i]) + 1; } else{ maxr = h[i]; h[i] = 0; } } for(int i = 0; i < n; i++){ System.out.println(h[i] + " "); } } }
Java
["5\n1 2 3 1 2", "4\n3 2 1 4"]
1 second
["3 2 0 2 0", "2 3 4 0"]
null
Java 7
standard input
[ "implementation", "math" ]
e544ed0904e2def0c1b2d91f94acbc56
The first line of the input contains a single number n (1 ≀ n ≀ 105) β€” the number of houses in the capital of Berland. The second line contains n space-separated positive integers hi (1 ≀ hi ≀ 109), where hi equals the number of floors in the i-th house.
1,100
Print n integers a1, a2, ..., an, where number ai is the number of floors that need to be added to the house number i to make it luxurious. If the house is already luxurious and nothing needs to be added to it, then ai should be equal to zero. All houses are numbered from left to right, starting from one.
standard output
PASSED
a26389d3ec1b2257e023f5754add2d16
train_000.jsonl
1443430800
The capital of Berland has n multifloor buildings. The architect who built up the capital was very creative, so all the houses were built in one row.Let's enumerate all the houses from left to right, starting with one. A house is considered to be luxurious if the number of floors in it is strictly greater than in all the houses with larger numbers. In other words, a house is luxurious if the number of floors in it is strictly greater than in all the houses, which are located to the right from it. In this task it is assumed that the heights of floors in the houses are the same.The new architect is interested in n questions, i-th of them is about the following: "how many floors should be added to the i-th house to make it luxurious?" (for all i from 1 to n, inclusive). You need to help him cope with this task.Note that all these questions are independent from each other β€” the answer to the question for house i does not affect other answers (i.e., the floors to the houses are not actually added).
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.StringTokenizer; public class Codeforces581B { public static void main(String[] args) { try { BufferedReader f = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(f.readLine()); int[] heights = new int[n]; StringTokenizer st = new StringTokenizer(f.readLine()); f.close(); for(int i = 0; i < n; i++) heights[i] = Integer.parseInt(st.nextToken()); int[] maxHeights = new int[n]; maxHeights[n - 1] = heights[n - 1]; StringBuffer s = new StringBuffer(""); for(int i = n - 2; i >= 0; i--) { if(heights[i] > maxHeights[i + 1]) maxHeights[i] = heights[i]; else maxHeights[i] = maxHeights[i + 1]; } //System.out.println(Arrays.toString(maxHeights)); for(int i = 0; i < n - 1; i++) { if(heights[i] > maxHeights[i + 1]) s.append("0 "); else { int diff = maxHeights[i + 1] - heights[i] + 1; s.append(diff + " "); } } s.append("0"); System.out.println(s.toString()); } catch(IOException e) { System.out.println(e); } } }
Java
["5\n1 2 3 1 2", "4\n3 2 1 4"]
1 second
["3 2 0 2 0", "2 3 4 0"]
null
Java 7
standard input
[ "implementation", "math" ]
e544ed0904e2def0c1b2d91f94acbc56
The first line of the input contains a single number n (1 ≀ n ≀ 105) β€” the number of houses in the capital of Berland. The second line contains n space-separated positive integers hi (1 ≀ hi ≀ 109), where hi equals the number of floors in the i-th house.
1,100
Print n integers a1, a2, ..., an, where number ai is the number of floors that need to be added to the house number i to make it luxurious. If the house is already luxurious and nothing needs to be added to it, then ai should be equal to zero. All houses are numbered from left to right, starting from one.
standard output