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
5b99523e5e50329eb9c99d658c0526dd
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.lang.reflect.Array; import java.math.BigInteger; import java.util.*; import java.io.*; public class taskB { private static final int mx =1000000; private static final long l=1000000000; private static boolean primes[]=new boolean[mx+1]; private static void Eratos() { Arrays.fill(primes,true); primes[0]=primes[1]=false; for(int i=2;i*i<=mx;++i) { if(primes[i]) { for(int j=i*i;j<=mx;j+=i) primes[j]=false; } } } public void solve() { int n=cin.nextInt(); int m=cin.nextInt(); int a[][]=new int [n][m]; for(int i=0;i<n;i++) for(int j=0;j<m;j++) a[i][j]=cin.nextInt(); for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { if(!primes[a[i][j]]) { int x=a[i][j]; while(!primes[a[i][j]]) { ++a[i][j]; } a[i][j]-=x; } else a[i][j]=0; } } long res=l; for(int i=0;i<n;i++) { long sum=0; for(int j=0;j<m;j++) sum+=a[i][j]; res=Math.min(sum,res); } for(int j=0;j<m;j++) { long sum=0; for(int i=0;i<n;i++) sum+=a[i][j]; res=Math.min(res,sum); } out.println(res); } public static void main(String[] args) throws IOException { taskB solved = new taskB(); solved.Eratos(); solved.solve(); solved.out.close(); } Scanner cin = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); }
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 8
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
0618de1c2fb168ae2ad2a0232a992677
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.ArrayList; import java.util.Arrays; import java.util.Scanner; import java.util.TreeSet; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int m = sc.nextInt(); boolean init = false; int x = 0; int[][] matr = new int[n][m]; int[] ops = new int[n+m]; int f = 150000; boolean[] arr = new boolean[f]; Arrays.fill(arr, true); TreeSet<Integer> primes = new TreeSet<Integer>(); arr[0] = false; arr[1] = false; for(int i = 2; i < f; i++) { if(arr[i] == true) { primes.add(i); for(int j = (2*i); j < f; j += i) { arr[j] = false; } } } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { matr[i][j] = sc.nextInt(); } } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { int num = matr[i][j]; ops[i] += primes.ceiling(num) - num; } } for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { int num = matr[j][i]; ops[i+n] += primes.ceiling(num) - num; } } for (int i = (n+m)-1; i >= 0; i--) { if (init) { if (ops[i] < x) x = ops[i]; } else { init = true; x = ops[i]; } } System.out.print(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 8
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
8591294048bd0409a2ea2d9c35eed126
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.*;import java.io.*;import java.math.*; public class Main { public static void process()throws IOException { boolean[] sieve=new boolean[200001]; Arrays.fill(sieve,false); TreeSet<Integer>set=new TreeSet<Integer>(); for(int i=2;i<sieve.length;i++) { if(sieve[i]==true) continue; set.add(i); for(int j=2*i;j<sieve.length;j+=i) sieve[j]=true; } int n=ni(); int m=ni(); int[][]A=new int[n][m]; long ans=Long.MAX_VALUE;; for(int i=0;i<n;i++) { long sum=0; for(int j=0;j<m;j++) { A[i][j]=ni(); if(set.ceiling(A[i][j])!=null) sum+=set.ceiling(A[i][j])-A[i][j]; } ans=Math.min(ans,sum); } for(int i=0;i<m;i++) { long sum=0; for(int j=0;j<n;j++) { if(set.ceiling(A[j][i])!=null) sum+=set.ceiling(A[j][i])-A[j][i]; } ans=Math.min(ans,sum); } pn(ans); } static AnotherReader sc; static PrintWriter out; public static void main(String[]args)throws IOException { boolean oj = System.getProperty("ONLINE_JUDGE") != null; if(oj){sc=new AnotherReader();out=new PrintWriter(System.out);} else{sc=new AnotherReader(100);out=new PrintWriter("output.txt");} int t=1; // t=ni(); while(t-->0) {process();} out.flush();out.close(); } static void pn(Object o){out.println(o);} static void p(Object o){out.print(o);} static void pni(Object o){out.println(o);out.flush();} static int ni()throws IOException{return sc.nextInt();} static long nl()throws IOException{return sc.nextLong();} static double nd()throws IOException{return sc.nextDouble();} static String nln()throws IOException{return sc.nextLine();} static int[] nai(int N)throws IOException{int[]A=new int[N];for(int i=0;i!=N;i++){A[i]=ni();}return A;} static long[] nal(int N)throws IOException{long[]A=new long[N];for(int i=0;i!=N;i++){A[i]=nl();}return A;} static long gcd(long a, long b)throws IOException{return (b==0)?a:gcd(b,a%b);} static int gcd(int a, int b)throws IOException{return (b==0)?a:gcd(b,a%b);} static int bit(long n)throws IOException{return (n==0)?0:(1+bit(n&(n-1)));} ///////////////////////////////////////////////////////////////////////////////////////////////////////// static class AnotherReader{BufferedReader br; StringTokenizer st; AnotherReader()throws FileNotFoundException{ br=new BufferedReader(new InputStreamReader(System.in));} AnotherReader(int a)throws FileNotFoundException{ br = new BufferedReader(new FileReader("input.txt"));} String next()throws IOException{ while (st == null || !st.hasMoreElements()) {try{ st = new StringTokenizer(br.readLine());} catch (IOException e){ e.printStackTrace(); }} return st.nextToken(); } int nextInt() throws IOException{ return Integer.parseInt(next());} long nextLong() throws IOException {return Long.parseLong(next());} double nextDouble()throws IOException { return Double.parseDouble(next()); } String nextLine() throws IOException{ String str = ""; try{ str = br.readLine();} catch (IOException e){ e.printStackTrace();} return str;}} ///////////////////////////////////////////////////////////////////////////////////////////////////////////// }
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 8
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
a0b67f41c3d045357174003e5891363e
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 javafx.util.*; import java.io.*; import java.io.InputStreamReader; import java.util.Scanner; import java.util.StringTokenizer; import java.util.*; import java.math.*; public class Main { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } public static void main (String[] args) throws java.lang.Exception { FastReader sc=new FastReader(); PrintWriter pw=new PrintWriter(System.out); int prime[]=new int[200000]; List<Integer> l=new ArrayList<>(); Arrays.fill(prime,1); prime[0] = 0; prime[1] = 0; for(int i = 2 ; i <= Math.sqrt(200000) ; i++) { if(prime[i] == 1) { for(int j = i*i ; j < 200000 ; j+=i) prime[j] = 0; } }int k=0; for(int i=2;i<200000;i++) { if(prime[i]==1) l.add(i); }int b[]=new int[l.size()]; for(int i=0;i<l.size();i++) b[i]=l.get(i); int t=1;//sc.nextInt(); while(t-->0){ int n=sc.nextInt(),m=sc.nextInt(); int a[][]=new int[n][m],min=Integer.MAX_VALUE; for(int i=0;i<n;i++) { int sum=0; for(int j=0;j<m;j++) { a[i][j]=sc.nextInt(); int index=Arrays.binarySearch(b,a[i][j]); if(index>=0) a[i][j]=0; else a[i][j]=b[Math.abs(index)-1]-a[i][j]; sum+=a[i][j]; } min=Math.min(min,sum); } for(int i=0;i<m;i++) { int sum=0; for(int j=0;j<n;j++) sum+=a[j][i]; min=Math.min(min,sum); } pw.println(min); } pw.close(); } }
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 8
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
8fdc7de576a5f61fe4cd8bcb9aa556ac
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 javafx.util.*; import java.io.*; import java.io.InputStreamReader; import java.util.Scanner; import java.util.StringTokenizer; import java.util.*; import java.math.*; public class Main { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } public static void main (String[] args) throws java.lang.Exception { FastReader sc=new FastReader(); PrintWriter pw=new PrintWriter(System.out); int prime[]=new int[200000]; List<Integer> l=new ArrayList<>(); Arrays.fill(prime,1); prime[0] = 0; prime[1] = 0; for(int i = 2 ; i <= Math.sqrt(200000) ; i++) { if(prime[i] == 1) { for(int j = i*i ; j < 200000 ; j+=i) prime[j] = 0; } }int k=0; for(int i=2;i<200000;i++) { if(prime[i]==1) l.add(i); }Integer b[]=new Integer[l.size()]; l.toArray(b); int t=1;//sc.nextInt(); while(t-->0){ int n=sc.nextInt(),m=sc.nextInt(); int a[][]=new int[n][m],min=Integer.MAX_VALUE; for(int i=0;i<n;i++) { int sum=0; for(int j=0;j<m;j++) { a[i][j]=sc.nextInt(); int index=Arrays.binarySearch(b,a[i][j]); if(index>=0) a[i][j]=0; else a[i][j]=b[Math.abs(index)-1]-a[i][j]; sum+=a[i][j]; } min=Math.min(min,sum); } for(int i=0;i<m;i++) { int sum=0; for(int j=0;j<n;j++) sum+=a[j][i]; min=Math.min(min,sum); } pw.println(min); } pw.close(); } }
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 8
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
0f1d14ef19841e36580af00ff85455f2
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 PrimeMatrix { static BufferedReader br; static StringTokenizer st; static int n, m, pn; static int[][] a; static int[] p = new int[222222]; static boolean[] prime; static final int maxn = 150000; static String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } static int nextInt() throws IOException { return Integer.parseInt(next()); } public static void main(String[] args) throws Exception { br = new BufferedReader(new InputStreamReader(System.in)); n = nextInt(); m = nextInt(); a = new int[n][m]; prime = new boolean[maxn + 1]; Arrays.fill(prime, true); for (int i = 2; i <= maxn; ++i) if (prime[i]) { p[pn++] = i; for (int j = i + i; j <= maxn; j += i) prime[j] = false; } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { int x = nextInt(); int l = -1, r = pn; while (r - l > 1) { int mid = (l + r) / 2; if (p[mid] >= x) r = mid; else l = mid; } a[i][j] = p[r] - x; //System.out.print(a[i][j] + " "); } //System.out.println(); } int res = 1000 * 1000 * 1000; for (int i = 0; i < n; ++i) { int sum = 0; for (int j = 0; j < m; ++j) { sum += a[i][j]; } res = Math.min(res, sum); } for (int j = 0; j < m; ++j) { int sum = 0; for (int i = 0; i < n; ++i) { sum += a[i][j]; } res = Math.min(res, sum); } System.out.println(res); } }
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 8
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
b08c59221343f7641d0385ccb2e109d5
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 javax.naming.PartialResultException; import java.util.*; import java.io.*; public class PrimeMatrix { InputStream is; PrintWriter out; String INPUT = ""; ArrayList<Integer> primes; void solve() throws IOException { int n= ni(), m= ni(); int[][] arr= new int[n][m]; for(int i=0;i<n;i++) { for(int j=0;j<m;j++) arr[i][j]= ni(); } sieve(); for(int i=0;i<n;i++) { for(int j=0;j<m;j++) arr[i][j]= binarySearch(arr[i][j], 0, primes.size()-1)- arr[i][j]; } int ans= Integer.MAX_VALUE; for(int i=0;i<n;i++) { int sum=0; for(int j=0;j<m;j++) { if(sum> ans) break; else sum+= arr[i][j]; } ans= Math.min(ans, sum); } for(int i=0;i<m;i++) { int sum=0; for(int j=0;j<n;j++) { if(sum> ans) break; else sum+= arr[j][i]; } ans= Math.min(ans, sum); } out.println(ans); } private int binarySearch(int find, int start, int last) { while(start<= last) { int mid= start+ (last- start)/2; if(primes.get(mid)== find) return find; else if(primes.get(mid)> find) last= mid-1; else start= mid+1; } return primes.get(start); } private void sieve() { boolean[] composite= new boolean[100000]; for(int i=2;i*i<= composite.length;i++) { if(composite[i]) continue; for(int j=i*i;j< composite.length;j+=i) composite[j]= true; } primes= new ArrayList<>(); for(int i=2;i<composite.length;i++) if(!composite[i]) primes.add(i); primes.add(100003); } void run() throws Exception { is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes()); out = new PrintWriter(System.out); solve(); out.flush(); } public static void main(String[] args) throws Exception { new PrimeMatrix().run(); } private byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; private int readByte() { if (lenbuf == -1) throw new InputMismatchException(); if (ptrbuf >= lenbuf) { ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if (lenbuf <= 0) return -1; } return inbuf[ptrbuf++]; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while ((b = readByte()) != -1 && isSpaceChar(b)) ; return b; } private double nd() { return Double.parseDouble(ns()); } private char nc() { return (char) skip(); } private String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private char[] ns(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while (p < n && !(isSpaceChar(b))) { buf[p++] = (char) b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private char[][] nm(int n, int m) { char[][] map = new char[n][]; for (int i = 0; i < n; i++) map[i] = ns(m); return map; } private int[] na(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = ni(); return a; } private int ni() { int num = 0, b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } private long nl() { long num = 0; int b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } private void tr(Object... o) { if (INPUT.length() > 0) System.out.println(Arrays.deepToString(o)); } }
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 8
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
4711701db816bf438c23d5f9c65969bd
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.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.*; import java.io.*; public class Contest1 { static Scanner sc=new Scanner(System.in); static PrintWriter out=new PrintWriter(System.out); public static void main(String[] args) throws IOException { int n=sc.nextInt(); int m=sc.nextInt(); int cost=0; int a[][]=new int[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { a[i][j]=sc.nextInt(); } } primes(1000000); int min=Integer.MAX_VALUE; for (int i = 0; i < n; i++) { cost=0; for (int j = 0; j < m; j++) { cost+=set.ceiling(a[i][j])-a[i][j]; } min=Math.min(cost, min); } for (int i = 0; i < m; i++) { cost=0; for (int j = 0; j < n; j++) { cost+=set.ceiling(a[j][i])-a[j][i]; } min=Math.min(cost, min); } System.out.println(min); } static TreeSet<Integer> set=new TreeSet<Integer>(); public static void primes(int n) { boolean[] primes = new boolean[n + 1]; for (int i = 2; i < primes.length; i++) { primes[i] = true; } int num = 2; while (true) { for (int i = 2;; i++) { int multiple = num * i; if (multiple > n) { break; } else { primes[multiple] = false; } } boolean nextNumFound = false; for (int i = num + 1; i < n + 1; i++) { if (primes[i]) { num = i; nextNumFound = true; break; } } if (!nextNumFound) { break; } } for (int i = 0; i < primes.length; i++) { if (primes[i]) { set.add(i); } } } } class Scanner{ StringTokenizer st; BufferedReader br; public Scanner(InputStream system){ br=new BufferedReader(new InputStreamReader(system)); } public Scanner (String file) throws IOException{ br=new BufferedReader(new FileReader(file)); } public String next() throws IOException{ while (st==null || !st.hasMoreTokens()) st=new StringTokenizer(br.readLine()); return st.nextToken(); } public String nextLine() throws IOException{ return br.readLine(); } public int nextInt() throws IOException{ return Integer.parseInt(next()); } public long nextLong() throws IOException{ return Long.parseLong(next()); } public Double nextDouble() throws IOException{ 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 8
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
78389d1982e06e146eff423373e2d324
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 PrimeMatrix { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader inp = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); Solver solver = new Solver(); solver.solve(inp, out); out.close(); } static class Solver { private static boolean[] primes; private static LinkedList<Integer> prime; private static int[] nextPrime = new int[100001]; private static void setPrime(int n) { primes = new boolean[n+1]; prime = new LinkedList<>(); for (int i = 2; i <= n; i++) primes[i] = true; for (int i = 2; i <= Math.sqrt(n); i++) { if(primes[i]) { for (int j = i + i; j <= n; j += i) primes[j] = false; } } for (int i = 2; i <= n; i++) if (primes[i]) prime.addLast(i); } private static void setNextPrime() { int i = 0; int highestPrime = prime.get(i); for (int j = 0; j <= 100000; j++) { if (!(j <= highestPrime)) highestPrime = prime.get(++i); nextPrime[j] = highestPrime; } } private void solve(InputReader inp, PrintWriter out) { setPrime(101000); setNextPrime(); int n = inp.nextInt(); int m = inp.nextInt(); int[][] matrix = new int[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { matrix[i][j] = inp.nextInt(); } } int min = Integer.MAX_VALUE; for (int i = 0; i < n; i++) { int sum = 0; for (int j = 0; j < m; j++) { sum += nextPrime[matrix[i][j]] - matrix[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 += nextPrime[matrix[i][j]] - matrix[i][j]; } min = Math.min(min, sum); } out.print(min); } } static class InputReader { BufferedReader reader; StringTokenizer tokenizer; InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } }
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 8
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
04df0887fb1338f995c4713fd7fa93fa
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.*; // author @mdazmat9 public class codeforces{ static ArrayList<Integer> primes=new ArrayList<>(); static HashSet set=new HashSet(); public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int test = 1; for (int ind = 0; ind < test; ind++) { int n=sc.nextInt(); int m=sc.nextInt(); sieveOfEratosthenes(1000000); int a[][]=new int[n][m]; int check[][]=new int[n][m]; int min=Integer.MAX_VALUE; for(int i=0;i<n;i++){ int diff=0; for(int j=0;j<m;j++){ a[i][j]=sc.nextInt(); if(set.contains(a[i][j])){ check[i][j]=a[i][j]; } else{ int index=leastgreater(0,primes.size()-1,a[i][j]); check[i][j]=primes.get(index); diff+=(check[i][j]-a[i][j]); } } if(diff<min) min=diff; } for(int i=0;i<m;i++){ int diff=0; for(int j=0;j<n;j++){ int num=check[j][i]; diff+=(num-a[j][i]); } if(diff<min) min=diff; } out.println(min); } out.flush(); } static int leastgreater(int low, int high, int key) { int ans = -1; while (low <= high) { int mid = low + (high - low + 1) / 2; int midVal = primes.get(mid); if (midVal < key) { // if mid is less than key, all elements // in range [low, mid - 1] are <= key // then we search in right side of mid // so we now search in [mid + 1, high] low = mid + 1; } else if (midVal > key) { // if mid is greater than key, all elements // in range [mid + 1, high] are >= key // we note down the last found index, then // we search in left side of mid // so we now search in [low, mid - 1] ans = mid; high = mid - 1; } else if (midVal == key) { // if mid is equal to key, all elements in // range [low, mid] are <= key // so we now search in [mid + 1, high] low = mid + 1; } } return ans; } static void sieveOfEratosthenes(int n) { // Create a boolean array "prime[0..n]" and initialize // all entries it as true. A value in prime[i] will // finally be false if i is Not a prime, else true. boolean prime[] = new boolean[n+1]; for(int i=0;i<n;i++) prime[i] = true; for(int p = 2; p*p <=n; p++) { // If prime[p] is not changed, then it is a prime if(prime[p] == true) { // Update all multiples of p for(int i = p*p; i <= n; i += p) prime[i] = false; } } // Print all prime numbers for(int i = 2; i <= n; i++) { if(prime[i] == true) { primes.add(i); set.add(i); } } } static void shuffle(int[] a) { int n = a.length; for(int i = 0; i < n; i++) { int r = i + (int) (Math.random() * (n - i)); int tmp = a[i]; a[i] = a[r]; a[r] = tmp; } } static long gcd(long a , long b) { if(b == 0) return a; return gcd(b , a % b); } } class Scanner { public BufferedReader reader; public StringTokenizer st; public Scanner(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); st = null; } public String next() { while (st == null || !st.hasMoreTokens()) { try { String line = reader.readLine(); if (line == null) return null; st = new StringTokenizer(line); } catch (Exception e) { throw (new RuntimeException()); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } } class OutputWriter { BufferedWriter writer; public OutputWriter(OutputStream stream) { writer = new BufferedWriter(new OutputStreamWriter(stream)); } public void print(int i) throws IOException { writer.write(i); } public void print(String s) throws IOException { writer.write(s); } public void print(char[] c) throws IOException { writer.write(c); } public void close() throws IOException { writer.close(); } }
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 8
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
49703f184b2abef240a6a853c351b9ab
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.PrintWriter; import java.util.ArrayList; import java.util.StringTokenizer; import java.util.*; public class CF271B { public static void main(String[] args) { FastReader input = new FastReader(); PrintWriter pw = new PrintWriter(System.out); boolean[] prime = new boolean[1000000+1]; Arrays.fill(prime,true); prime[0] = false; prime[1] = false; for(int i = 2;i * i <= 1000000;i++){ if(prime[i]){ for(int j = i * i;j <= 1000000; j+=i){ prime[j] = false; } } } ArrayList<Integer> primes = new ArrayList<>(); for(int i = 0;i < prime.length;i++){ if(prime[i]) primes.add(i); } int n = input.nextInt(); int m = input.nextInt(); int[][] matrix = new int[n+1][m+1]; for(int i = 1;i <= n;i++){ for(int j = 1;j <= m;j++){ matrix[i][j] = input.nextInt(); } } int rowMin = Integer.MAX_VALUE; for(int i = 1;i <= n;i++){ int sum = 0; for(int j = 1;j <= m;j++){ int val = matrix[i][j]; if(prime[val]){ } else{ int up = -1; int low = 0; int high = primes.size()-1; int ans1 = -1; while (low <= high){ int mid = (low + high) / 2; if(primes.get(mid) >= val){ ans1 = primes.get(mid); high = mid - 1; } else{ low = mid + 1; } } up = ans1 - val; sum += up; } } rowMin = Math.min(rowMin,sum); } // pw.println(rowMin); int colMin = Integer.MAX_VALUE; for(int col = 1;col <= m;col++){ int sum = 0; for(int row = 1;row <= n;row++){ int val = matrix[row][col]; if(prime[val]){ } else{ int up = -1; int low = 0; int high = primes.size()-1; int ans1 = -1; while (low <= high){ int mid = (low + high) / 2; if(primes.get(mid) >= val){ ans1 = primes.get(mid); high = mid - 1; } else{ low = mid + 1; } } up = ans1 - val; sum += up; } } colMin = Math.min(colMin,sum); } // pw.println(rowMin + " " + colMin); pw.println(Math.min(rowMin,colMin)); // ****If sorting is required, use ArrayList pw.flush(); pw.close(); } static void sort(int[] arr){ ArrayList<Integer> list = new ArrayList<Integer>(); for(int i : arr) list.add(i); Collections.sort(list); for(int i = 0;i < list.size();i++){ arr[i] = list.get(i); } return; } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["3 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 8
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
b16ac7c8aab2f1c96de844cf9db0e424
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 Solution { public static void main(String[] args) { /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */ Scanner sc=new Scanner(System.in); int n=sc.nextInt(); int m=sc.nextInt(); int a[][]=new int[n][m]; for(int i=0;i<n;i++) for(int j=0;j<m;j++) a[i][j]=sc.nextInt(); int pr[]=new int[1000005]; pr[1]=1; pr[0]=1; for(int i=2;i*i<=1000000;i++) if(pr[i]==0) for(int j=2*i;j<=1000000;j+=i) pr[j]=1; int next[]=new int[10000005]; int prime=-1; for(int i=1000000;i>=1;i--) { next[i]=prime; if(pr[i]==0) prime=i; } int min=Integer.MAX_VALUE; for(int i=0;i<n;i++) { int ans=0; for(int j=0;j<m;j++) { if(pr[a[i][j]]==0) continue; ans+=(next[a[i][j]]-a[i][j]); } if(min>ans) min=ans; } for(int i=0;i<m;i++) { int ans=0; for(int j=0;j<n;j++) { if(pr[a[j][i]]==0) continue; ans+=(next[a[j][i]]-a[j][i]); } if(min>ans) min=ans; } System.out.print(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 8
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
2fc5e5ab05cbada7ac0665ea70112bda
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; import java.util.TreeSet; import java.util.stream.IntStream; public class primematrix { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Scanner input = new Scanner(System.in); TreeSet<Integer> primes= new TreeSet<Integer>(); for(int i=2; i<200000;i++){ if(isPrime(i))primes.add(i); } int n = input.nextInt(); int m = input.nextInt(); int[]rows = new int[n]; int[] col = new int[m]; for(int i=0; i<n;i++){ for(int j=0; j<m;j++){ int x = input.nextInt(); int diff = primes.ceiling(x)-x; rows[i]+=diff; col[j]+=diff; } } System.out.println(IntStream.concat(IntStream.of(rows),IntStream.of(col)).min().getAsInt()); } private static boolean isPrime(int x){ for(int i=2; i*i<=x;i++){ if(x%i==0)return false; } return true; } }
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 8
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
2cf90c921f637c575acab5ef6419e380
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 Main { // n levels and 4 vertex public static void main(String[] args){ Scanner sc= new Scanner(System.in); ArrayList<Integer> p= new ArrayList<>(); for (int i = 2; i <= 100000+10; i++) { boolean prime=true; for (int j= 2; j <= Math.sqrt(i); j++) { if(i%j==0){prime=false;break;} } if(prime)p.add(i); } int n=sc.nextInt(); int m=sc.nextInt(); int [][] sumx=new int[n+1][m+1]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { int temp= sc.nextInt(); int idx= Collections.binarySearch(p, temp); int hp = idx<0?-(idx+1):idx; sumx[i][j]=p.get(hp)-temp; sumx[n][j]+=sumx[i][j]; sumx[i][m]+=sumx[i][j]; } } int min=Integer.MAX_VALUE; for (int i = 0; i < n; i++) min=sumx[i][m]<min?sumx[i][m]:min; for (int i = 0; i < m; i++) min=sumx[n][i]<min?sumx[n][i]:min; 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 8
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
835b2689e1716a0f25bd9651b31957b3
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.nio.charset.StandardCharsets; // import java.math.BigInteger; public class B { static Writer wr; public static void main(String[] args) throws Exception { // long startTime = System.nanoTime(); // String testString = ""; // InputStream stream = new ByteArrayInputStream(testString.getBytes(StandardCharsets.UTF_8)); // Reader in = new Reader(stream); Reader in = new Reader(); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out)); wr = new Writer(); /* Precomputation */ int max = 200000; boolean[] is_not_prime = new boolean[max+1]; for(int i=2;i*i<=max;i+=2) { if(!is_not_prime[i]) { for(int j=2;j*i<=max;j++) { is_not_prime[j*i] = true; } } if(i==2) i--; } int idx=0; int[] primes = new int[17984]; for(int i=2;i<=max;i++) { if(!is_not_prime[i]) { primes[idx++] = i; } } // wr.writeRedLn(Arrays.toString(Arrays.copyOfRange(primes, 9585, primes.length))); // wr.writeRedLn(idx); // long elapsedTime = System.nanoTime() - startTime; // double seconds = (double)elapsedTime / 1000000000.0; // wr.writeRedLn(seconds); /* Input */ 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(); } } ArrayList<Integer> count = new ArrayList<>(); for(int i=0;i<N;i++) { int cc=0; for(int j=0;j<M;j++) { int check = Arrays.binarySearch(primes, a[i][j]); if(check<0) { check = -check-1; int best = 1000000; for(int k=check; k<=check+2;k++) { if((k>=0) && (k<primes.length)) { best = Math.min(best, Math.abs(a[i][j]-primes[k])); // wr.writeRedLn(a[i][j] + " " + best +" "+primes[k]); } } cc += best; // wr.writeRedLn(a[i][j] + " " + best +" "+check); } } // wr.writeGreenLn(cc+""); count.add(cc); } for(int j=0;j<M;j++) { int cc=0; for(int i=0;i<N;i++) { int check = Arrays.binarySearch(primes, a[i][j]); if(check<0) { check = -check-1; int best = 1000000; for(int k=check; k<=check+2;k++) { if((k>=0) && (k<primes.length)) { best = Math.min(best, Math.abs(a[i][j]-primes[k])); // wr.writeRedLn(a[i][j] + " " + best +" "+primes[k]); } } cc += best; // wr.writeRedLn(a[i][j] + " " + best +" "+check); } } // wr.writeGreenLn(cc+""); count.add(cc); } Collections.sort(count); out.write(count.get(0) + "\n"); out.flush(); } } class Writer { public void writeRedLn(Object x) { writeRedLn(x+""); } public void writeBlueLn(Object x) { writeBlueLn(x+""); } public void writeGreenLn(Object x) { writeGreenLn(x+""); } public void writePinkLn(Object x) { writePinkLn(x+""); } public void writeRedLn(String x) { System.out.println((char)27 + "[31m" + (char)27 + "[40m" + x + (char)27 + "[0m"); } public void writeBlueLn(String x) { System.out.println((char)27 + "[34m" + (char)27 + "[3m" + x + (char)27 + "[0m"); } public void writeGreenLn(String x) { System.out.println((char)27 + "[32m" + (char)27 + "[3m" + x + (char)27 + "[0m"); } public void writePinkLn(String x) { System.out.println((char)27 + "[30m" + (char)27 + "[45m" + x + (char)27 + "[0m"); } public void writeRed(String x) { System.out.print((char)27 + "[31m" + (char)27 + "[40m" + x + (char)27 + "[0m"); } public void writeBlue(String x) { System.out.print((char)27 + "[34m" + (char)27 + "[3m" + x + (char)27 + "[0m"); } public void writeGreen(String x) { System.out.print((char)27 + "[32m" + (char)27 + "[3m" + x + (char)27 + "[0m"); } public void writePink(String x) { System.out.print((char)27 + "[30m" + (char)27 + "[45m" + x + (char)27 + "[0m"); } } class Reader { final private int BUFFER_SIZE = 1 << 16;private DataInputStream din;private byte[] buffer;private int bufferPointer, bytesRead; public Reader(){din=new DataInputStream(System.in);buffer=new byte[BUFFER_SIZE];bufferPointer=bytesRead=0;} public Reader(InputStream stream){din=new DataInputStream(stream);buffer=new byte[BUFFER_SIZE];bufferPointer=bytesRead=0;} public String readLine()throws IOException{byte[] buf=new byte[1024];int cnt=0,c; while((c=read())!=-1){if(c=='\n')break;buf[cnt++]=(byte)c;}return new String(buf,0,cnt);} public char nextChar()throws IOException{byte c=read();while(c<=' ')c=read();return (char)c;} public int nextInt()throws IOException{int ret=0;byte c=read();while(c<=' ')c=read();boolean neg=(c=='-'); if(neg)c=read();do{ret=ret*10+c-'0';}while((c=read())>='0'&&c<='9');if(neg)return -ret;return ret;} public long nextLong()throws IOException{long ret=0;byte c=read();while(c<=' ')c=read();boolean neg=(c=='-'); if(neg)c=read();do{ret=ret*10+c-'0';}while((c=read())>='0'&&c<='9');if(neg)return -ret;return ret;} public double nextDouble()throws IOException{double ret=0,div=1;byte c=read();while(c<=' ')c=read();boolean neg=(c=='-');if(neg)c = read();do {ret=ret*10+c-'0';}while((c=read())>='0'&&c<='9'); if(c=='.')while((c=read())>='0'&&c<='9')ret+=(c-'0')/(div*=10);if(neg)return -ret;return ret;} private void fillBuffer()throws IOException{bytesRead=din.read(buffer,bufferPointer=0,BUFFER_SIZE);if(bytesRead==-1)buffer[0]=-1;} private byte read()throws IOException{if(bufferPointer==bytesRead)fillBuffer();return buffer[bufferPointer++];} public void close()throws IOException{if(din==null) return;din.close();} }
Java
["3 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 8
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
07e7fd8ce2bc9fc6478b01d8c897c52f
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.*; import java.io.*; public class PA { /* Tyger! Tyger! burning bright In the forests of the night, What immortal hand or eye Could frame thy fearful symmetry? In what distant deeps or skies Burnt the fire of thine eyes? On what wings dare he aspire? What the hand, dare sieze the fire? And what shoulder, & what art, Could twist the sinews of thy heart? And when thy heart began to beat, What dread hand? & what dread feet? What the hammer? what the chain? In what furnace was thy brain? What the anvil? what dread grasp Dare its deadly terrors clasp? When the stars threw down their spears, And water’d heaven with their tears, Did he smile his work to see? Did he who made the Lamb make thee? Tyger! Tyger! burning bright In the forests of the night, What immortal hand or eye Dare frame thy fearful symmetry? */ public static boolean isPrime(int x) { for(int i = 2 ; i * i <= x ; i++) { if(x % i == 0) return false; } return true; } public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); // StringTokenizer st1 = new StringTokenizer(br.readLine()); Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int m = sc.nextInt(); TreeSet<Integer> primes = new TreeSet<>(); for(int i = 2 ; i <= 1000000 ; i++) { if(isPrime(i)) primes.add(i); } int arr[][] = new int [n][m]; for(int i = 0 ; i < n ; i++) { for(int j = 0 ; j < m ; j++) { arr[i][j] = sc.nextInt(); } } int min = Integer.MAX_VALUE; for(int i = 0 ; i < n ; i++) { int sum = 0; for(int j = 0 ; j < m ; j++) { sum += primes.ceiling(arr[i][j])-arr[i][j]; } min = Math.min(min , sum); } for(int i = 0 ; i < m ; i++) { int sum = 0; for(int j = 0 ; j < n ; j++) { sum += primes.ceiling(arr[j][i])-arr[j][i]; } min = Math.min(min , sum); } out.println(min); out.flush(); out.close(); } }
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 8
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
55c2b17a160089d536f16af3c4be60b7
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.*; import java.io.*; public class PA { /* Tyger! Tyger! burning bright In the forests of the night, What immortal hand or eye Could frame thy fearful symmetry? In what distant deeps or skies Burnt the fire of thine eyes? On what wings dare he aspire? What the hand, dare sieze the fire? And what shoulder, & what art, Could twist the sinews of thy heart? And when thy heart began to beat, What dread hand? & what dread feet? What the hammer? what the chain? In what furnace was thy brain? What the anvil? what dread grasp Dare its deadly terrors clasp? When the stars threw down their spears, And water’d heaven with their tears, Did he smile his work to see? Did he who made the Lamb make thee? Tyger! Tyger! burning bright In the forests of the night, What immortal hand or eye Dare frame thy fearful symmetry? */ public static boolean isPrime(int x) { for(int i = 2 ; i * i <= x ; i++) { if(x % i == 0) return false; } return true; } public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); // StringTokenizer st1 = new StringTokenizer(br.readLine()); Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int m = sc.nextInt(); TreeSet<Integer> primes = new TreeSet<>(); for(int i = 2 ; i <= 1000000 ; i++) { if(isPrime(i)) primes.add(i); } int arr[][] = new int [n][m]; for(int i = 0 ; i < n ; i++) { for(int j = 0 ; j < m ; j++) { arr[i][j] = sc.nextInt(); } } int min = Integer.MAX_VALUE; for(int i = 0 ; i < n ; i++) { int sum = 0; for(int j = 0 ; j < m ; j++) { sum += primes.ceiling(arr[i][j])-arr[i][j]; } min = Math.min(min , sum); } for(int i = 0 ; i < m ; i++) { int sum = 0; for(int j = 0 ; j < n ; j++) { sum += primes.ceiling(arr[j][i])-arr[j][i]; } min = Math.min(min , sum); } out.println(min); out.flush(); out.close(); } }
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 8
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
fa4921907eabb2d22bbd142fa9211c78
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.*; import java.io.*; public class PA { /* Tyger! Tyger! burning bright In the forests of the night, What immortal hand or eye Could frame thy fearful symmetry? In what distant deeps or skies Burnt the fire of thine eyes? On what wings dare he aspire? What the hand, dare sieze the fire? And what shoulder, & what art, Could twist the sinews of thy heart? And when thy heart began to beat, What dread hand? & what dread feet? What the hammer? what the chain? In what furnace was thy brain? What the anvil? what dread grasp Dare its deadly terrors clasp? When the stars threw down their spears, And water’d heaven with their tears, Did he smile his work to see? Did he who made the Lamb make thee? Tyger! Tyger! burning bright In the forests of the night, What immortal hand or eye Dare frame thy fearful symmetry? */ public static boolean isPrime(int x) { for(int i = 2 ; i * i <= x ; i++) { if(x % i == 0) return false; } return true; } public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); // StringTokenizer st1 = new StringTokenizer(br.readLine()); Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int m = sc.nextInt(); TreeSet<Integer> primes = new TreeSet<>(); for(int i = 2 ; i <= 1000000 ; i++) { if(isPrime(i)) primes.add(i); } int arr[][] = new int [n][m]; for(int i = 0 ; i < n ; i++) { for(int j = 0 ; j < m ; j++) { arr[i][j] = sc.nextInt(); } } int min = Integer.MAX_VALUE; for(int i = 0 ; i < n ; i++) { int sum = 0; for(int j = 0 ; j < m ; j++) { sum += primes.ceiling(arr[i][j])-arr[i][j]; } min = Math.min(min , sum); } for(int i = 0 ; i < m ; i++) { int sum = 0; for(int j = 0 ; j < n ; j++) { sum += primes.ceiling(arr[j][i])-arr[j][i]; } min = Math.min(min , sum); } out.println(min); out.flush(); out.close(); } }
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 8
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
e4d142db49af12b92d4958ec99a4eb05
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.math.*; public class Main{ static class Solver{ Vector<Integer> primes; void sieve(int n){ primes = new Vector<Integer>((int)(n / (Math.log(n) - 1))); BitSet isp = new BitSet(n); isp.set(2, n); for(int i = 2; i < n; ++i){ if(isp.get(i)){ primes.add(i); for(int j = 2 * i; j < n; j += i){ isp.clear(j); } } } } int getPrime(int x){ int i = 0, j = primes.size() - 1; while(i < j){ int m = (i + j) / 2; if(primes.get(m).compareTo(x) < 0){ i = m + 1; } else{ j = m; } } return primes.get(i); } void main(){ // freopen("in"); sieve(100010); int n = nextInt(); int m = nextInt(); // int n = 500; // int m = 500; int[] cr = new int[n]; int[] cc = new int[m]; for(int i = 0; i < n; ++i){ for(int j = 0; j < m; ++j){ int x = nextInt(); // int x = rand() % 100000 + 1; int c = getPrime(x) - x; cr[i] += c; cc[j] += c; } } int ans = inf; for(int x : cr){ ans = min(ans, x); } for(int x : cc){ ans = min(ans, x); } printf("%d\n", ans); } final int maxn = 100010; final int inf = 0x3f3f3f3f; Random rnd = new Random(); int rand(){ return rnd.nextInt(); } <T extends Comparable<T>> T max(T x, T y){ return (x.compareTo(y) > 0 ? x : y); } <T extends Comparable<T>> T min(T x, T y){ return (x.compareTo(y) < 0 ? x : y); } /** io **/ PrintWriter out; BufferedReader reader; StringTokenizer tokens; Solver(){ tokens = new StringTokenizer(""); reader = new BufferedReader(new InputStreamReader(System.in), 1 << 15); out = new PrintWriter(System.out); main(); // solução out.close(); // flush output } void freopen(String s){ try{ reader = new BufferedReader(new InputStreamReader(new FileInputStream(s)), 1 << 15); } catch(FileNotFoundException e){ throw new RuntimeException(e); } } /** input -- supõe que não chegou no EOF **/ int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String next(){ readTokens(); return tokens.nextToken(); } String nextLine(){ readTokens(); return tokens.nextToken("\n"); } boolean readTokens(){ while(!tokens.hasMoreTokens()){ // lê os dados, ignorando linhas vazias try{ String line = reader.readLine(); if(line == null) return false; // EOF tokens = new StringTokenizer(line); } catch(IOException e){ throw new RuntimeException(e); } } return true; } /** output **/ void printf(String s, Object... o) { out.printf(s, o); } void debug(String s, Object... o) { System.err.printf((char)27 + "[91m" + s + (char)27 + "[0m", o); } } public static void main(String[] args){ new Solver(); } }
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 8
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
25072eac095a7ea59f34441379770f21
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.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.StringTokenizer; public class Main { static int Max = 1000000; static boolean [] arr = new boolean[Max]; public static void main(String[] args) throws IOException { // write your code here steive(); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); int row = Integer.parseInt(st.nextToken()); int col = Integer.parseInt(st.nextToken()); int [][] differenceInPrime = new int[row][col]; //int [][] matrix = new int[row][col]; for (int i=0;i<row;i++){ st = new StringTokenizer(br.readLine()); for (int j=0;j<col;j++){ int n = Integer.parseInt(st.nextToken()); differenceInPrime[i][j] = nesrestDiffereencePrime(n); } } //this method find the min difference I need to achieve a col or row ful of prime int globalMin = Integer.MAX_VALUE; //try all the row to chekc if t have row full of prime for (int i=0;i<row;i++){ int sum =0; for (int j=0;j<col;j++){ sum+=differenceInPrime[i][j]; } globalMin = Math.min(globalMin,sum); } //try all downward col for (int i=0;i<col;i++){ int sum =0; for (int j=0;j<row;j++){ sum+=differenceInPrime[j][i]; } globalMin = Math.min(globalMin,sum); } System.out.println(globalMin); } static public void steive(){ Arrays.fill(arr,true); arr[0] = false; arr[1] = false; for (long i=2;i<Max;i++) if(arr[(int)i]) for (long j=i*i;j<Max;j+=i) arr[(int)j] = false; } //this will get an int and return the difference to the nearest prime static public int nesrestDiffereencePrime(int n){ int i=n; if(arr[n]) return 0; else while (i<Max&&!arr[i]) { i++; } return i-n; } }
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 8
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
4bdc315f622f388a8e6047d0d34b7661
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.StringTokenizer; public class PrimeMatrix { static boolean esPrimo[] = new boolean[100000 + 100]; public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); criba(100090); StringTokenizer st = new StringTokenizer(br.readLine()); int n1 = Integer.parseInt(st.nextToken()); int n2 = Integer.parseInt(st.nextToken()); //int mat[][] = new int[n1][n2]; int columns[] = new int[n2]; int menor = Integer.MAX_VALUE; for (int i = 0; i < n1; i++) { st = new StringTokenizer(br.readLine()); int mov = 0; for (int j = 0; j < n2; j++) { int n = Integer.parseInt(st.nextToken()); if (!esPrimo[n]) { int aux = primCercano(n); mov += aux; columns[j] += aux; } } if (mov < menor) { menor = mov; } } for (int i = 0; i < columns.length; i++) { if (columns[i] < menor) { menor = columns[i]; } } System.out.println(menor); } static int primCercano(int n) { int cont = 0; for (int i = n; i < esPrimo.length; i++) { if (esPrimo[i]) { break; } cont++; } return cont; } static void criba(int tam) { for (int i = 2; i <= tam; ++i) { esPrimo[i] = true; } esPrimo[0] = false; esPrimo[1] = false; for (int i = 2; i * i <= tam; ++i) { if (esPrimo[i]) { for (int h = 2; i * h <= tam; ++h) { esPrimo[i * h] = false; } } } } }
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 8
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
f12511d818a5777347d69825f7fae76f
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.*; import java.io.*; public class Main { int[] primes ; boolean[] numbers; int index ; public static void main(String[] args) { new Main().start(); } void start(){ primes = new int[10000]; index = 0 ; numbers = new boolean[100004]; loadPrimes(); numbers[100003] = true ; Scanner reader = new Scanner(System.in); int n ,m ; int[][] arr , counter; int[] row , column ; while(reader.hasNext()){ n = reader.nextInt(); m = reader.nextInt(); arr = new int[n][m] ; counter = new int[n][m] ; row = new int[n]; column = new int[m]; for(int i=0 ; i<n ; i++){ for(int j=0 ;j<m ; j++){ arr[i][j] = reader.nextInt(); while( numbers[arr[i][j]]==false ){ arr[i][j]++; counter[i][j]++; } } } for(int i=0 ; i<n ; i++){ for(int j=0 ;j<m ; j++){ row[i] += counter[i][j]; } } for(int i=0 ; i<m ; i++){ for(int j=0 ;j<n ; j++){ column[i] += counter[j][i]; } } Arrays.sort(row); Arrays.sort(column); if(row[0]<=column[0]) System.out.println(row[0]); else System.out.println(column[0]); } } void loadPrimes(){ primes[0] = 2 ; primes[1] = 3 ; primes[2] = 5 ; primes[3] = 7 ; numbers[2] = true ; numbers[3] = true ; numbers[5] = true ; numbers[7] = true ; index = 4 ; for(int i=11 ; i<=100000 ; i++){ if(isPrime(i)){ primes[index] = i ; index++; numbers[i] = true ; } } } private boolean isPrime(int num) { for(int i=0 ; i<index ; i++){ if(num%primes[i]==0) return false; } return true; } }
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 8
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
5a2ec6554f677c616d2a3d1154a91bd1
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.*; import java.math.BigInteger; import java.util.*; import java.text.*; public class cf271b { static BufferedReader br; static Scanner sc; static PrintWriter out; public static void initA() { try { br = new BufferedReader(new InputStreamReader(System.in)); //br = new BufferedReader(new FileReader("input.txt")); sc = new Scanner(System.in); //out = new PrintWriter("output.txt"); out = new PrintWriter(System.out); } catch (Exception e) { } } public static void initB() { try { br = new BufferedReader(new FileReader("input.txt")); sc = new Scanner(new FileReader("input.txt")); out = new PrintWriter("output.txt"); } catch (Exception e) { } } public static String getString() { try { return br.readLine(); } catch (Exception e) { } return ""; } public static Integer getInt() { try { return Integer.parseInt(br.readLine()); } catch (Exception e) { } return 0; } public static Integer[] getIntArr() { try { StringTokenizer temp = new StringTokenizer(br.readLine()); int n = temp.countTokens(); Integer temp2[] = new Integer[n]; for (int i = 0; i < n; i++) { temp2[i] = Integer.parseInt(temp.nextToken()); } return temp2; } catch (Exception e) { } return null; } public static Long[] getLongArr() { try { StringTokenizer temp = new StringTokenizer(br.readLine()); int n = temp.countTokens(); Long temp2[] = new Long[n]; for (int i = 0; i < n; i++) { temp2[i] = Long.parseLong(temp.nextToken()); } return temp2; } catch (Exception e) { } return null; } public static String[] getStringArr() { try { StringTokenizer temp = new StringTokenizer(br.readLine()); int n = temp.countTokens(); String temp2[] = new String[n]; for (int i = 0; i < n; i++) { temp2[i] = (temp.nextToken()); } return temp2; } catch (Exception e) { } return null; } public static int getMax(Integer[] ar) { int t = ar[0]; for (int i = 0; i < ar.length; i++) { if (ar[i] > t) { t = ar[i]; } } return t; } public static void print(Object a) { out.println(a); } public static int nextInt() { return sc.nextInt(); } public static double nextDouble() { return sc.nextDouble(); } public static void main(String[] ar) { initA(); solve(); out.flush(); } public static void solve() { int max = 110000; boolean notprime[] = new boolean[110000]; for (int i = 2; i < max; i++) { for (int j = 2; j * i < max; j++) { notprime[i * j] = true; } } ArrayList<Integer> prime = new ArrayList<Integer>(110000); for (int i = 2; i < max; i++) { if (!notprime[i]) { prime.add(i); } } final int last = prime.size(); int dp[] = new int[110000]; //Arrays.fill(dp, -1); for (int i = 0; i < 110000; i++) { int s = 0; int num = i; while (!isPrime(num)) { num++; s++; } dp[i] = s; } Integer x[] = getIntArr(); int n = x[0], m = x[1]; int min[][] = new int[n][m]; for (int i = 0; i < n; i++) { Integer temp[] = getIntArr(); for (int ii = 0; ii < m; ii++) { int num = temp[ii]; min[i][ii] = dp[num]; /* int l =0, r= last-1; while(l!=r){ int mid = (l+r)/2; int te = prime.get(mid); if(te >= num){ r=mid; }else{ l=mid+1; } } min[i][ii] = prime.get(l)-num; */ } } int out = Integer.MAX_VALUE; for (int i = 0; i < n; i++) { int sum = 0; for (int ii = 0; ii < m; ii++) { sum += min[i][ii]; } out = Math.min(sum, out); } for (int i = 0; i < m; i++) { int sum = 0; for (int ii = 0; ii < n; ii++) { sum += min[ii][i]; } out = Math.min(sum, out); } print(out); } static boolean isPrime(int n) { if (n == 2 || n == 3) { return true; } if (n < 2 || n % 2 == 0) { return false; } for (int i = 3; i <= Math.sqrt(n) + 1; i += 2) { if (n % i == 0) { return false; } } return true; } }
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
4d7086fb734497f811e8c83157975568
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.*; import java.math.BigInteger; import java.util.*; import java.text.*; public class cf271b { static BufferedReader br; static Scanner sc; static PrintWriter out; public static void initA() { try { br = new BufferedReader(new InputStreamReader(System.in)); //br = new BufferedReader(new FileReader("input.txt")); sc = new Scanner(System.in); //out = new PrintWriter("output.txt"); out = new PrintWriter(System.out); } catch (Exception e) { } } public static void initB() { try { br = new BufferedReader(new FileReader("input.txt")); sc = new Scanner(new FileReader("input.txt")); out = new PrintWriter("output.txt"); } catch (Exception e) { } } public static String getString() { try { return br.readLine(); } catch (Exception e) { } return ""; } public static Integer getInt() { try { return Integer.parseInt(br.readLine()); } catch (Exception e) { } return 0; } public static Integer[] getIntArr() { try { StringTokenizer temp = new StringTokenizer(br.readLine()); int n = temp.countTokens(); Integer temp2[] = new Integer[n]; for (int i = 0; i < n; i++) { temp2[i] = Integer.parseInt(temp.nextToken()); } return temp2; } catch (Exception e) { } return null; } public static Long[] getLongArr() { try { StringTokenizer temp = new StringTokenizer(br.readLine()); int n = temp.countTokens(); Long temp2[] = new Long[n]; for (int i = 0; i < n; i++) { temp2[i] = Long.parseLong(temp.nextToken()); } return temp2; } catch (Exception e) { } return null; } public static String[] getStringArr() { try { StringTokenizer temp = new StringTokenizer(br.readLine()); int n = temp.countTokens(); String temp2[] = new String[n]; for (int i = 0; i < n; i++) { temp2[i] = (temp.nextToken()); } return temp2; } catch (Exception e) { } return null; } public static int getMax(Integer[] ar) { int t = ar[0]; for (int i = 0; i < ar.length; i++) { if (ar[i] > t) { t = ar[i]; } } return t; } public static void print(Object a) { out.println(a); } public static int nextInt() { return sc.nextInt(); } public static double nextDouble() { return sc.nextDouble(); } public static void main(String[] ar) { initA(); solve(); out.flush(); } public static void solve() { int max = 110000; boolean notprime[] = new boolean[110000]; for (int i = 2; i < max; i++) { for (int j = 2; j * i < max; j++) { notprime[i * j] = true; } } ArrayList<Integer> prime = new ArrayList<Integer>(110000); for (int i = 2; i < max; i++) { if (!notprime[i]) { prime.add(i); } } final int last = prime.size(); Integer x[] = getIntArr(); int n = x[0], m = x[1]; int min[][] = new int[n][m]; for (int i = 0; i < n; i++) { Integer temp[] = getIntArr(); for (int ii = 0; ii < m; ii++) { int num = temp[ii]; int l =0, r= last-1; while(l!=r){ int mid = (l+r)/2; int te = prime.get(mid); if(te >= num){ r=mid; }else{ l=mid+1; } } min[i][ii] = prime.get(l)-num; } } int out = Integer.MAX_VALUE; for (int i = 0; i < n; i++) { int sum = 0; for (int ii = 0; ii < m; ii++) { sum += min[i][ii]; } out = Math.min(sum, out); } for (int i = 0; i < m; i++) { int sum = 0; for (int ii = 0; ii < n; ii++) { sum += min[ii][i]; } out = Math.min(sum, out); } print(out); } static boolean isPrime(int n) { if (n == 2 || n == 3) { return true; } if (n < 2 || n % 2 == 0) { return false; } for (int i = 3; i <= Math.sqrt(n) + 1; i += 2) { if (n % i == 0) { return false; } } return true; } }
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
525e956845a20cc62b6932d1a655a1e6
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.*; import java.math.BigInteger; import java.util.*; import java.text.*; public class cf271b { static BufferedReader br; static Scanner sc; static PrintWriter out; public static void initA() { try { br = new BufferedReader(new InputStreamReader(System.in)); //br = new BufferedReader(new FileReader("input.txt")); sc = new Scanner(System.in); //out = new PrintWriter("output.txt"); out = new PrintWriter(System.out); } catch (Exception e) { } } public static void initB() { try { br = new BufferedReader(new FileReader("input.txt")); sc = new Scanner(new FileReader("input.txt")); out = new PrintWriter("output.txt"); } catch (Exception e) { } } public static String getString() { try { return br.readLine(); } catch (Exception e) { } return ""; } public static Integer getInt() { try { return Integer.parseInt(br.readLine()); } catch (Exception e) { } return 0; } public static Integer[] getIntArr() { try { StringTokenizer temp = new StringTokenizer(br.readLine()); int n = temp.countTokens(); Integer temp2[] = new Integer[n]; for (int i = 0; i < n; i++) { temp2[i] = Integer.parseInt(temp.nextToken()); } return temp2; } catch (Exception e) { } return null; } public static Long[] getLongArr() { try { StringTokenizer temp = new StringTokenizer(br.readLine()); int n = temp.countTokens(); Long temp2[] = new Long[n]; for (int i = 0; i < n; i++) { temp2[i] = Long.parseLong(temp.nextToken()); } return temp2; } catch (Exception e) { } return null; } public static String[] getStringArr() { try { StringTokenizer temp = new StringTokenizer(br.readLine()); int n = temp.countTokens(); String temp2[] = new String[n]; for (int i = 0; i < n; i++) { temp2[i] = (temp.nextToken()); } return temp2; } catch (Exception e) { } return null; } public static int getMax(Integer[] ar) { int t = ar[0]; for (int i = 0; i < ar.length; i++) { if (ar[i] > t) { t = ar[i]; } } return t; } public static void print(Object a) { out.println(a); } public static int nextInt() { return sc.nextInt(); } public static double nextDouble() { return sc.nextDouble(); } public static void main(String[] ar) { initA(); solve(); out.flush(); } public static void solve() { int max = 110000; boolean notprime[] = new boolean[110000]; for (int i = 2; i < max; i++) { for (int j = 2; j * i < max; j++) { notprime[i * j] = true; } } ArrayList<Integer> prime = new ArrayList<Integer>(110000); for (int i = 2; i < max; i++) { if (!notprime[i]) { prime.add(i); } } final int last = prime.size(); int dp[] = new int[110000]; Arrays.fill(dp, -1); /* for (int i = 0; i < 110000; i++) { int s = 0; int num = i; while (!isPrime(num)) { num++; s++; } dp[i] = s; } * */ Integer x[] = getIntArr(); int n = x[0], m = x[1]; int min[][] = new int[n][m]; for (int i = 0; i < n; i++) { Integer temp[] = getIntArr(); for (int ii = 0; ii < m; ii++) { int num = temp[ii]; if (dp[num] == -1) { int l = 0, r = last - 1; while (l != r) { int mid = (l + r) / 2; int te = prime.get(mid); if (te >= num) { r = mid; } else { l = mid + 1; } } min[i][ii] = prime.get(l) - num; dp[num]=prime.get(l) - num; }else{ min[i][ii]=dp[num]; } } } int out = Integer.MAX_VALUE; for (int i = 0; i < n; i++) { int sum = 0; for (int ii = 0; ii < m; ii++) { sum += min[i][ii]; } out = Math.min(sum, out); } for (int i = 0; i < m; i++) { int sum = 0; for (int ii = 0; ii < n; ii++) { sum += min[ii][i]; } out = Math.min(sum, out); } print(out); } static boolean isPrime(int n) { if (n == 2 || n == 3) { return true; } if (n < 2 || n % 2 == 0) { return false; } for (int i = 3; i <= Math.sqrt(n) + 1; i += 2) { if (n % i == 0) { return false; } } return true; } }
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
830f04b3d13cec886dd0ad78057f4674
train_000.jsonl
1549546500
You are given an integer $$$n$$$ ($$$n \ge 0$$$) represented with $$$k$$$ digits in base (radix) $$$b$$$. So,$$$$$$n = a_1 \cdot b^{k-1} + a_2 \cdot b^{k-2} + \ldots a_{k-1} \cdot b + a_k.$$$$$$For example, if $$$b=17, k=3$$$ and $$$a=[11, 15, 7]$$$ then $$$n=11\cdot17^2+15\cdot17+7=3179+255+7=3441$$$.Determine whether $$$n$$$ is even or odd.
256 megabytes
/* package codechef; // don't place package name! */ import java.util.*; import java.lang.*; import java.io.*; /* Name of the class has to be "Main" only if the class is public. */ public class Codechef { public static void main (String[] args) throws java.lang.Exception { // your code goes here BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); String s1[]=br.readLine().trim().split("\\ "); String s2[]=br.readLine().trim().split("\\ "); int flag=0; long b=Long.parseLong(s1[0]); long k=Long.parseLong(s1[1]); int q=0; k--; while(k>=0){ long z=Long.parseLong(s2[q])*b; if(k==0) z=Long.parseLong(s2[q]); q++; k--; z=z%2; flag+=z; flag%=2; } if(flag==1) System.out.println("odd"); else System.out.println("even"); } }
Java
["13 3\n3 2 7", "10 9\n1 2 3 4 5 6 7 8 9", "99 5\n32 92 85 74 4", "2 2\n1 0"]
1 second
["even", "odd", "odd", "even"]
NoteIn the first example, $$$n = 3 \cdot 13^2 + 2 \cdot 13 + 7 = 540$$$, which is even.In the second example, $$$n = 123456789$$$ is odd.In the third example, $$$n = 32 \cdot 99^4 + 92 \cdot 99^3 + 85 \cdot 99^2 + 74 \cdot 99 + 4 = 3164015155$$$ is odd.In the fourth example $$$n = 2$$$.
Java 8
standard input
[ "math" ]
ee105b664099808143a94a374d6d5daa
The first line contains two integers $$$b$$$ and $$$k$$$ ($$$2\le b\le 100$$$, $$$1\le k\le 10^5$$$) — the base of the number and the number of digits. The second line contains $$$k$$$ integers $$$a_1, a_2, \ldots, a_k$$$ ($$$0\le a_i &lt; b$$$) — the digits of $$$n$$$. The representation of $$$n$$$ contains no unnecessary leading zero. That is, $$$a_1$$$ can be equal to $$$0$$$ only if $$$k = 1$$$.
900
Print "even" if $$$n$$$ is even, otherwise print "odd". You can print each letter in any case (upper or lower).
standard output
PASSED
1d2a770c01d0ee7f8a55f49813fca883
train_000.jsonl
1549546500
You are given an integer $$$n$$$ ($$$n \ge 0$$$) represented with $$$k$$$ digits in base (radix) $$$b$$$. So,$$$$$$n = a_1 \cdot b^{k-1} + a_2 \cdot b^{k-2} + \ldots a_{k-1} \cdot b + a_k.$$$$$$For example, if $$$b=17, k=3$$$ and $$$a=[11, 15, 7]$$$ then $$$n=11\cdot17^2+15\cdot17+7=3179+255+7=3441$$$.Determine whether $$$n$$$ is even or odd.
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 @Ziklon */ 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); AParity solver = new AParity(); solver.solve(1, in, out); out.close(); } static class AParity { public void solve(int testNumber, InputReader in, OutputWriter out) { int b = in.readInt(), k = in.readInt(); int ans = 0; for (int i = 0; i < k; ++i) { ans += in.readInt() * IntegerUtils.power(b, k - i - 1,2); } out.printLine(ans % 2 == 0 ? "even" : "odd"); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } static class IntegerUtils { public static long power(long base, long exponent, long mod) { if (base >= mod) { base %= mod; } if (exponent == 0) { return 1 % mod; } long result = power(base, exponent >> 1, mod); result = result * result % mod; if ((exponent & 1) != 0) { result = result * base % mod; } return result; } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) { writer.print(' '); } writer.print(objects[i]); } } public void printLine(Object... objects) { print(objects); writer.println(); } public void close() { writer.close(); } } }
Java
["13 3\n3 2 7", "10 9\n1 2 3 4 5 6 7 8 9", "99 5\n32 92 85 74 4", "2 2\n1 0"]
1 second
["even", "odd", "odd", "even"]
NoteIn the first example, $$$n = 3 \cdot 13^2 + 2 \cdot 13 + 7 = 540$$$, which is even.In the second example, $$$n = 123456789$$$ is odd.In the third example, $$$n = 32 \cdot 99^4 + 92 \cdot 99^3 + 85 \cdot 99^2 + 74 \cdot 99 + 4 = 3164015155$$$ is odd.In the fourth example $$$n = 2$$$.
Java 8
standard input
[ "math" ]
ee105b664099808143a94a374d6d5daa
The first line contains two integers $$$b$$$ and $$$k$$$ ($$$2\le b\le 100$$$, $$$1\le k\le 10^5$$$) — the base of the number and the number of digits. The second line contains $$$k$$$ integers $$$a_1, a_2, \ldots, a_k$$$ ($$$0\le a_i &lt; b$$$) — the digits of $$$n$$$. The representation of $$$n$$$ contains no unnecessary leading zero. That is, $$$a_1$$$ can be equal to $$$0$$$ only if $$$k = 1$$$.
900
Print "even" if $$$n$$$ is even, otherwise print "odd". You can print each letter in any case (upper or lower).
standard output
PASSED
d317f2e8e30694b88da64e0547bf1f65
train_000.jsonl
1549546500
You are given an integer $$$n$$$ ($$$n \ge 0$$$) represented with $$$k$$$ digits in base (radix) $$$b$$$. So,$$$$$$n = a_1 \cdot b^{k-1} + a_2 \cdot b^{k-2} + \ldots a_{k-1} \cdot b + a_k.$$$$$$For example, if $$$b=17, k=3$$$ and $$$a=[11, 15, 7]$$$ then $$$n=11\cdot17^2+15\cdot17+7=3179+255+7=3441$$$.Determine whether $$$n$$$ is even or odd.
256 megabytes
//Hack it if you can !! import java.util.*; import java.io.*; import java.math.*; public class Main { static class FastReader { private InputStream mIs;private byte[] buf = new byte[1024];private int curChar,numChars;public FastReader() { this(System.in); }public FastReader(InputStream is) { mIs = is;} public int read() {if (numChars == -1) throw new InputMismatchException();if (curChar >= numChars) {curChar = 0;try { numChars = mIs.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 next(){int c = read();while (isSpaceChar(c)) c = read();StringBuilder res = new StringBuilder();do {res.appendCodePoint(c);c = read();}while (!isSpaceChar(c));return res.toString();} public long l(){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 i(){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 double d() throws IOException {return Double.parseDouble(next()) ;} 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; } public void scanIntArr(int [] arr){ for(int li=0;li<arr.length;++li){ arr[li]=i();}} public void scanLongArr(long [] arr){for (int i=0;i<arr.length;++i){arr[i]=l();}} public void shuffle(int [] arr){ for(int i=arr.length;i>0;--i) { int r=(int)(Math.random()*i); int temp=arr[i-1]; arr[i-1]=arr[r]; arr[r]=temp; } } } public static void main(String[] args)throws IOException { /* inputCopy 13 3 3 2 7 outputCopy even inputCopy 10 9 1 2 3 4 5 6 7 8 9 outputCopy odd inputCopy 99 5 32 92 85 74 4 outputCopy odd inputCopy 2 2 1 0 outputCopy even Note In the first example, 𝑛=3⋅132+2⋅13+7=540, which is even. */ PrintWriter pw = new PrintWriter(System.out); FastReader fr = new FastReader(); long b=fr.l(); long k=fr.l(); BigInteger num=BigInteger.ZERO; BigInteger curMul=BigInteger.ONE; BigInteger base=new BigInteger(b+""); long [] arr=new long[(int)k]; fr.scanLongArr(arr); for(int ki=arr.length-1;ki>=0;--ki) { // num=num.multiply(curMul).add(new BigInteger(arr[ki]+"")); num=new BigInteger(arr[ki]+"").multiply(curMul).add(num).mod(new BigInteger("2")); curMul=curMul.multiply(base).mod(new BigInteger("2")); //pw.println(num.toString()); } if(num.mod(new BigInteger("2")).compareTo(BigInteger.ZERO)==0) { pw.println("even"); } else { pw.println("odd"); } pw.flush(); pw.close(); } }
Java
["13 3\n3 2 7", "10 9\n1 2 3 4 5 6 7 8 9", "99 5\n32 92 85 74 4", "2 2\n1 0"]
1 second
["even", "odd", "odd", "even"]
NoteIn the first example, $$$n = 3 \cdot 13^2 + 2 \cdot 13 + 7 = 540$$$, which is even.In the second example, $$$n = 123456789$$$ is odd.In the third example, $$$n = 32 \cdot 99^4 + 92 \cdot 99^3 + 85 \cdot 99^2 + 74 \cdot 99 + 4 = 3164015155$$$ is odd.In the fourth example $$$n = 2$$$.
Java 8
standard input
[ "math" ]
ee105b664099808143a94a374d6d5daa
The first line contains two integers $$$b$$$ and $$$k$$$ ($$$2\le b\le 100$$$, $$$1\le k\le 10^5$$$) — the base of the number and the number of digits. The second line contains $$$k$$$ integers $$$a_1, a_2, \ldots, a_k$$$ ($$$0\le a_i &lt; b$$$) — the digits of $$$n$$$. The representation of $$$n$$$ contains no unnecessary leading zero. That is, $$$a_1$$$ can be equal to $$$0$$$ only if $$$k = 1$$$.
900
Print "even" if $$$n$$$ is even, otherwise print "odd". You can print each letter in any case (upper or lower).
standard output
PASSED
8ef1fc0ebe01d5977fc90e4573f3c1ce
train_000.jsonl
1549546500
You are given an integer $$$n$$$ ($$$n \ge 0$$$) represented with $$$k$$$ digits in base (radix) $$$b$$$. So,$$$$$$n = a_1 \cdot b^{k-1} + a_2 \cdot b^{k-2} + \ldots a_{k-1} \cdot b + a_k.$$$$$$For example, if $$$b=17, k=3$$$ and $$$a=[11, 15, 7]$$$ then $$$n=11\cdot17^2+15\cdot17+7=3179+255+7=3441$$$.Determine whether $$$n$$$ is even or odd.
256 megabytes
import java.util.Scanner; public class A { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int n=sc.nextInt(),m=sc.nextInt(); int o=0; for (int i=0;i<m;i++){ long j= sc.nextLong(); if(i==m-1){ if (j%2!=0){ o++; break; } } if ((j*n)%2!=0){ o++; } } System.out.println(o%2==0?"even":"odd"); } }
Java
["13 3\n3 2 7", "10 9\n1 2 3 4 5 6 7 8 9", "99 5\n32 92 85 74 4", "2 2\n1 0"]
1 second
["even", "odd", "odd", "even"]
NoteIn the first example, $$$n = 3 \cdot 13^2 + 2 \cdot 13 + 7 = 540$$$, which is even.In the second example, $$$n = 123456789$$$ is odd.In the third example, $$$n = 32 \cdot 99^4 + 92 \cdot 99^3 + 85 \cdot 99^2 + 74 \cdot 99 + 4 = 3164015155$$$ is odd.In the fourth example $$$n = 2$$$.
Java 8
standard input
[ "math" ]
ee105b664099808143a94a374d6d5daa
The first line contains two integers $$$b$$$ and $$$k$$$ ($$$2\le b\le 100$$$, $$$1\le k\le 10^5$$$) — the base of the number and the number of digits. The second line contains $$$k$$$ integers $$$a_1, a_2, \ldots, a_k$$$ ($$$0\le a_i &lt; b$$$) — the digits of $$$n$$$. The representation of $$$n$$$ contains no unnecessary leading zero. That is, $$$a_1$$$ can be equal to $$$0$$$ only if $$$k = 1$$$.
900
Print "even" if $$$n$$$ is even, otherwise print "odd". You can print each letter in any case (upper or lower).
standard output
PASSED
3e1d96ee106d892dc56ec226e599b249
train_000.jsonl
1549546500
You are given an integer $$$n$$$ ($$$n \ge 0$$$) represented with $$$k$$$ digits in base (radix) $$$b$$$. So,$$$$$$n = a_1 \cdot b^{k-1} + a_2 \cdot b^{k-2} + \ldots a_{k-1} \cdot b + a_k.$$$$$$For example, if $$$b=17, k=3$$$ and $$$a=[11, 15, 7]$$$ then $$$n=11\cdot17^2+15\cdot17+7=3179+255+7=3441$$$.Determine whether $$$n$$$ is even or odd.
256 megabytes
import java.util.*; public class Test { public static void main(String[] args) { Scanner in = new Scanner(System.in); int b = in.nextInt(); int k = in.nextInt(); int n = 0; for(int i = k-1; i > 0; i--){ int a = in.nextInt(); n += (a * b) % 2; } n += in.nextInt(); System.out.println(n%2 == 0? "even" : "odd"); } }
Java
["13 3\n3 2 7", "10 9\n1 2 3 4 5 6 7 8 9", "99 5\n32 92 85 74 4", "2 2\n1 0"]
1 second
["even", "odd", "odd", "even"]
NoteIn the first example, $$$n = 3 \cdot 13^2 + 2 \cdot 13 + 7 = 540$$$, which is even.In the second example, $$$n = 123456789$$$ is odd.In the third example, $$$n = 32 \cdot 99^4 + 92 \cdot 99^3 + 85 \cdot 99^2 + 74 \cdot 99 + 4 = 3164015155$$$ is odd.In the fourth example $$$n = 2$$$.
Java 8
standard input
[ "math" ]
ee105b664099808143a94a374d6d5daa
The first line contains two integers $$$b$$$ and $$$k$$$ ($$$2\le b\le 100$$$, $$$1\le k\le 10^5$$$) — the base of the number and the number of digits. The second line contains $$$k$$$ integers $$$a_1, a_2, \ldots, a_k$$$ ($$$0\le a_i &lt; b$$$) — the digits of $$$n$$$. The representation of $$$n$$$ contains no unnecessary leading zero. That is, $$$a_1$$$ can be equal to $$$0$$$ only if $$$k = 1$$$.
900
Print "even" if $$$n$$$ is even, otherwise print "odd". You can print each letter in any case (upper or lower).
standard output
PASSED
1c21e3a236218409802807603388bde0
train_000.jsonl
1549546500
You are given an integer $$$n$$$ ($$$n \ge 0$$$) represented with $$$k$$$ digits in base (radix) $$$b$$$. So,$$$$$$n = a_1 \cdot b^{k-1} + a_2 \cdot b^{k-2} + \ldots a_{k-1} \cdot b + a_k.$$$$$$For example, if $$$b=17, k=3$$$ and $$$a=[11, 15, 7]$$$ then $$$n=11\cdot17^2+15\cdot17+7=3179+255+7=3441$$$.Determine whether $$$n$$$ is even or odd.
256 megabytes
import java.util.Scanner; /* * 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. */ /** * * @author MANAV PATEL */ public class NewClass111 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n1; int n2; int k=0; long sum = 0; n1 = sc.nextInt(); n2 = sc.nextInt(); int j=n2-1; int arr[] = new int[n2]; for(int i=0; i<n2; i++) { arr[i]=sc.nextInt(); if(i!=j && (arr[i]*n1)%2==1) { k++; } } if((k%2==1 && arr[j]%2==0) || (k%2==0 && arr[j]%2==1)) { System.out.println("odd"); } else { System.out.println("even"); } } }
Java
["13 3\n3 2 7", "10 9\n1 2 3 4 5 6 7 8 9", "99 5\n32 92 85 74 4", "2 2\n1 0"]
1 second
["even", "odd", "odd", "even"]
NoteIn the first example, $$$n = 3 \cdot 13^2 + 2 \cdot 13 + 7 = 540$$$, which is even.In the second example, $$$n = 123456789$$$ is odd.In the third example, $$$n = 32 \cdot 99^4 + 92 \cdot 99^3 + 85 \cdot 99^2 + 74 \cdot 99 + 4 = 3164015155$$$ is odd.In the fourth example $$$n = 2$$$.
Java 8
standard input
[ "math" ]
ee105b664099808143a94a374d6d5daa
The first line contains two integers $$$b$$$ and $$$k$$$ ($$$2\le b\le 100$$$, $$$1\le k\le 10^5$$$) — the base of the number and the number of digits. The second line contains $$$k$$$ integers $$$a_1, a_2, \ldots, a_k$$$ ($$$0\le a_i &lt; b$$$) — the digits of $$$n$$$. The representation of $$$n$$$ contains no unnecessary leading zero. That is, $$$a_1$$$ can be equal to $$$0$$$ only if $$$k = 1$$$.
900
Print "even" if $$$n$$$ is even, otherwise print "odd". You can print each letter in any case (upper or lower).
standard output
PASSED
a536b4a3dede64361dee79eabd88b601
train_000.jsonl
1549546500
You are given an integer $$$n$$$ ($$$n \ge 0$$$) represented with $$$k$$$ digits in base (radix) $$$b$$$. So,$$$$$$n = a_1 \cdot b^{k-1} + a_2 \cdot b^{k-2} + \ldots a_{k-1} \cdot b + a_k.$$$$$$For example, if $$$b=17, k=3$$$ and $$$a=[11, 15, 7]$$$ then $$$n=11\cdot17^2+15\cdot17+7=3179+255+7=3441$$$.Determine whether $$$n$$$ is even or odd.
256 megabytes
import java.io.InputStreamReader; import java.io.BufferedReader; public class cdfgr1a { public static void main(String args[])throws Exception { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); String s=br.readLine(); String ss[]=s.split(" "); int n=Integer.parseInt(ss[0]); int k=Integer.parseInt(ss[1]); n%=2; s=br.readLine(); String str[]=s.split(" "); int arr[]=new int[k]; for(int i=0;i<k;i++) arr[i]=Integer.parseInt(str[i]); int sum=0; for(int i=0;i<k;i++) { if(i==k-1) { if(arr[i]%2==1) sum+=1; break; } sum=sum+arr[i]%2*n; } if(sum%2==0) System.out.println("even"); else System.out.println("odd"); } }
Java
["13 3\n3 2 7", "10 9\n1 2 3 4 5 6 7 8 9", "99 5\n32 92 85 74 4", "2 2\n1 0"]
1 second
["even", "odd", "odd", "even"]
NoteIn the first example, $$$n = 3 \cdot 13^2 + 2 \cdot 13 + 7 = 540$$$, which is even.In the second example, $$$n = 123456789$$$ is odd.In the third example, $$$n = 32 \cdot 99^4 + 92 \cdot 99^3 + 85 \cdot 99^2 + 74 \cdot 99 + 4 = 3164015155$$$ is odd.In the fourth example $$$n = 2$$$.
Java 8
standard input
[ "math" ]
ee105b664099808143a94a374d6d5daa
The first line contains two integers $$$b$$$ and $$$k$$$ ($$$2\le b\le 100$$$, $$$1\le k\le 10^5$$$) — the base of the number and the number of digits. The second line contains $$$k$$$ integers $$$a_1, a_2, \ldots, a_k$$$ ($$$0\le a_i &lt; b$$$) — the digits of $$$n$$$. The representation of $$$n$$$ contains no unnecessary leading zero. That is, $$$a_1$$$ can be equal to $$$0$$$ only if $$$k = 1$$$.
900
Print "even" if $$$n$$$ is even, otherwise print "odd". You can print each letter in any case (upper or lower).
standard output
PASSED
58ec87a3bb7036c9761786dde9011e22
train_000.jsonl
1549546500
You are given an integer $$$n$$$ ($$$n \ge 0$$$) represented with $$$k$$$ digits in base (radix) $$$b$$$. So,$$$$$$n = a_1 \cdot b^{k-1} + a_2 \cdot b^{k-2} + \ldots a_{k-1} \cdot b + a_k.$$$$$$For example, if $$$b=17, k=3$$$ and $$$a=[11, 15, 7]$$$ then $$$n=11\cdot17^2+15\cdot17+7=3179+255+7=3441$$$.Determine whether $$$n$$$ is even or odd.
256 megabytes
import java.util.*; public class helloworld { public static int solve(int a[],int b,int k) { int ans = 0; // 1 代表奇数 boolean flag = (b % 2 == 0); // flag = 1 代表 b 是偶数 int coun = 0; if(flag == true) { if(a[k] % 2 == 1) { ans = 1 - ans; } } else { for(int i = 1;i <= k;i ++) { if(a[i] % 2 == 1) ++ coun; } if(coun % 2 == 1) ans = 1; } return ans; } public static void main(String[] args) { Scanner input = new Scanner(System.in); int a[] = new int[100100]; int b,k; b = input.nextInt(); k = input.nextInt(); for(int i = 1;i <= k;i ++) a[i] = input.nextInt(); if(solve(a,b,k) == 1) System.out.println("odd"); else System.out.println("even"); } }
Java
["13 3\n3 2 7", "10 9\n1 2 3 4 5 6 7 8 9", "99 5\n32 92 85 74 4", "2 2\n1 0"]
1 second
["even", "odd", "odd", "even"]
NoteIn the first example, $$$n = 3 \cdot 13^2 + 2 \cdot 13 + 7 = 540$$$, which is even.In the second example, $$$n = 123456789$$$ is odd.In the third example, $$$n = 32 \cdot 99^4 + 92 \cdot 99^3 + 85 \cdot 99^2 + 74 \cdot 99 + 4 = 3164015155$$$ is odd.In the fourth example $$$n = 2$$$.
Java 8
standard input
[ "math" ]
ee105b664099808143a94a374d6d5daa
The first line contains two integers $$$b$$$ and $$$k$$$ ($$$2\le b\le 100$$$, $$$1\le k\le 10^5$$$) — the base of the number and the number of digits. The second line contains $$$k$$$ integers $$$a_1, a_2, \ldots, a_k$$$ ($$$0\le a_i &lt; b$$$) — the digits of $$$n$$$. The representation of $$$n$$$ contains no unnecessary leading zero. That is, $$$a_1$$$ can be equal to $$$0$$$ only if $$$k = 1$$$.
900
Print "even" if $$$n$$$ is even, otherwise print "odd". You can print each letter in any case (upper or lower).
standard output
PASSED
e21327351644d249d3484cbc4597cbfe
train_000.jsonl
1549546500
You are given an integer $$$n$$$ ($$$n \ge 0$$$) represented with $$$k$$$ digits in base (radix) $$$b$$$. So,$$$$$$n = a_1 \cdot b^{k-1} + a_2 \cdot b^{k-2} + \ldots a_{k-1} \cdot b + a_k.$$$$$$For example, if $$$b=17, k=3$$$ and $$$a=[11, 15, 7]$$$ then $$$n=11\cdot17^2+15\cdot17+7=3179+255+7=3441$$$.Determine whether $$$n$$$ is even or odd.
256 megabytes
import java.util.*; public class helloworld { public static void main(String[] args) { Scanner input = new Scanner(System.in); int a[] = new int[100100]; int b,k; b = input.nextInt(); k = input.nextInt(); for(int i = 1;i <= k;i ++) a[i] = input.nextInt(); int ans = 0; // 1 代表奇数 boolean flag = (b % 2 == 0); // flag = 1 代表 b 是偶数 int coun = 0; if(flag == true) { if(a[k] % 2 == 1) { ans = 1 - ans; } } else { for(int i = 1;i <= k;i ++) { if(a[i] % 2 == 1) ++ coun; } if(coun % 2 == 1) ans = 1; } if(ans == 1) System.out.println("odd"); else System.out.println("even"); } }
Java
["13 3\n3 2 7", "10 9\n1 2 3 4 5 6 7 8 9", "99 5\n32 92 85 74 4", "2 2\n1 0"]
1 second
["even", "odd", "odd", "even"]
NoteIn the first example, $$$n = 3 \cdot 13^2 + 2 \cdot 13 + 7 = 540$$$, which is even.In the second example, $$$n = 123456789$$$ is odd.In the third example, $$$n = 32 \cdot 99^4 + 92 \cdot 99^3 + 85 \cdot 99^2 + 74 \cdot 99 + 4 = 3164015155$$$ is odd.In the fourth example $$$n = 2$$$.
Java 8
standard input
[ "math" ]
ee105b664099808143a94a374d6d5daa
The first line contains two integers $$$b$$$ and $$$k$$$ ($$$2\le b\le 100$$$, $$$1\le k\le 10^5$$$) — the base of the number and the number of digits. The second line contains $$$k$$$ integers $$$a_1, a_2, \ldots, a_k$$$ ($$$0\le a_i &lt; b$$$) — the digits of $$$n$$$. The representation of $$$n$$$ contains no unnecessary leading zero. That is, $$$a_1$$$ can be equal to $$$0$$$ only if $$$k = 1$$$.
900
Print "even" if $$$n$$$ is even, otherwise print "odd". You can print each letter in any case (upper or lower).
standard output
PASSED
78f9453a6c650338e4e8ecf5a74b0952
train_000.jsonl
1549546500
You are given an integer $$$n$$$ ($$$n \ge 0$$$) represented with $$$k$$$ digits in base (radix) $$$b$$$. So,$$$$$$n = a_1 \cdot b^{k-1} + a_2 \cdot b^{k-2} + \ldots a_{k-1} \cdot b + a_k.$$$$$$For example, if $$$b=17, k=3$$$ and $$$a=[11, 15, 7]$$$ then $$$n=11\cdot17^2+15\cdot17+7=3179+255+7=3441$$$.Determine whether $$$n$$$ is even or odd.
256 megabytes
import java.util.*; import java.io.*; public class Main{ public static void main(String[]args) throws IOException{ Scanner scan=new Scanner(System.in); BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); PrintWriter pr=new PrintWriter(System.out); int b=scan.nextInt(); int k=scan.nextInt(); int numOdd=0,a=0; for(int i=0;i<k;i++){ a=scan.nextInt(); if(a%2==1) numOdd++; } if(b%2==0){ if(a%2==0) System.out.print("even"); else System.out.print("odd"); } else{ if(numOdd%2==0) System.out.print("even"); else System.out.print("odd"); } } }
Java
["13 3\n3 2 7", "10 9\n1 2 3 4 5 6 7 8 9", "99 5\n32 92 85 74 4", "2 2\n1 0"]
1 second
["even", "odd", "odd", "even"]
NoteIn the first example, $$$n = 3 \cdot 13^2 + 2 \cdot 13 + 7 = 540$$$, which is even.In the second example, $$$n = 123456789$$$ is odd.In the third example, $$$n = 32 \cdot 99^4 + 92 \cdot 99^3 + 85 \cdot 99^2 + 74 \cdot 99 + 4 = 3164015155$$$ is odd.In the fourth example $$$n = 2$$$.
Java 8
standard input
[ "math" ]
ee105b664099808143a94a374d6d5daa
The first line contains two integers $$$b$$$ and $$$k$$$ ($$$2\le b\le 100$$$, $$$1\le k\le 10^5$$$) — the base of the number and the number of digits. The second line contains $$$k$$$ integers $$$a_1, a_2, \ldots, a_k$$$ ($$$0\le a_i &lt; b$$$) — the digits of $$$n$$$. The representation of $$$n$$$ contains no unnecessary leading zero. That is, $$$a_1$$$ can be equal to $$$0$$$ only if $$$k = 1$$$.
900
Print "even" if $$$n$$$ is even, otherwise print "odd". You can print each letter in any case (upper or lower).
standard output
PASSED
e38fce2c9beca63e812363cbc302e635
train_000.jsonl
1549546500
You are given an integer $$$n$$$ ($$$n \ge 0$$$) represented with $$$k$$$ digits in base (radix) $$$b$$$. So,$$$$$$n = a_1 \cdot b^{k-1} + a_2 \cdot b^{k-2} + \ldots a_{k-1} \cdot b + a_k.$$$$$$For example, if $$$b=17, k=3$$$ and $$$a=[11, 15, 7]$$$ then $$$n=11\cdot17^2+15\cdot17+7=3179+255+7=3441$$$.Determine whether $$$n$$$ is even or odd.
256 megabytes
// package CF1110; import java.io.*; import java.util.*; public class CF1110A { static FastReader s; static PrintWriter out; static String INPUT = "13 1\n" + "7\n"; public static void main(String[] args) { long time = System.currentTimeMillis(); boolean oj = System.getProperty("ONLINE_JUDGE") != null; out = new PrintWriter(System.out); s = new FastReader(oj); int b = s.nextInt(); int k = s.nextInt(); int[] arr = s.nextIntArray(k); boolean even = true; for (int i = 0; i < k; i++) { int num = (k - i - 1); if(num != 0) { num %= 4; if(num == 0) { num++; } } long num1= (long) ((long)arr[i] * (long)(Math.pow(b, num))); if(num1 % 2 != 0){ if(!even) { even = true; } else { even = false; } } } out.println(even ? "even\n" : "odd"); if (!oj) { System.out.println(Arrays.deepToString(new Object[]{System.currentTimeMillis() - time + " ms"})); } out.flush(); } private static class Maths { static ArrayList<Long> printDivisors(long n) { // Note that this loop runs till square root ArrayList<Long> list = new ArrayList<>(); for (long i = 1; i <= Math.sqrt(n); i++) { if (n % i == 0) { if (n / i == i) { list.add(i); } else { list.add(i); list.add(n / i); } } } return list; } // GCD - Using Euclid theorem. private static long gcd(long a, long b) { if (b == 0) { return a; } return gcd(b, a % b); } // Extended euclidean algorithm // Used to solve equations of the form ax + by = gcd(a,b) // return array [d, a, b] such that d = gcd(p, q), ap + bq = d static long[] extendedEuclidean(long p, long q) { if (q == 0) return new long[]{p, 1, 0}; long[] vals = extendedEuclidean(q, p % q); long d = vals[0]; long a = vals[2]; long b = vals[1] - (p / q) * vals[2]; return new long[]{d, a, b}; } // X ^ y mod p static long power(long x, long y, long p) { long res = 1; x = x % p; while (y > 0) { if ((y & 1) == 1) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return res; } // Returns modulo inverse of a // with respect to m using extended // Euclid Algorithm. Refer below post for details: // https://www.geeksforgeeks.org/multiplicative-inverse-under-modulo-m/ static long inv(long a, long m) { long m0 = m, t, q; long x0 = 0, x1 = 1; if (m == 1) return 0; // Apply extended Euclid Algorithm while (a > 1) { q = a / m; t = m; m = a % m; a = t; t = x0; x0 = x1 - q * x0; x1 = t; } // Make x1 positive if (x1 < 0) x1 += m0; return x1; } // k is size of num[] and rem[]. // Returns the smallest number // x such that: // x % num[0] = rem[0], // x % num[1] = rem[1], // .................. // x % num[k-2] = rem[k-1] // Assumption: Numbers in num[] are pairwise // coprime (gcd for every pair is 1) static long findMinX(long num[], long rem[], long k) { int prod = 1; for (int i = 0; i < k; i++) prod *= num[i]; int result = 0; for (int i = 0; i < k; i++) { long pp = prod / num[i]; result += rem[i] * inv(pp, num[i]) * pp; } return result % prod; } } private static class BS { // Binary search private static int binarySearch(int[] arr, int ele) { int low = 0; int high = arr.length - 1; while (low <= high) { int mid = (low + high) / 2; if (arr[mid] == ele) { return mid; } else if (ele < arr[mid]) { high = mid - 1; } else { low = mid + 1; } } return -1; } // First occurence using binary search private static int binarySearchFirstOccurence(int[] arr, int ele) { int low = 0; int high = arr.length - 1; int ans = -1; while (low <= high) { int mid = (low + high) / 2; if (arr[mid] == ele) { ans = mid; high = mid - 1; } else if (ele < arr[mid]) { high = mid - 1; } else { low = mid + 1; } } return ans; } // Last occurenece using binary search private static int binarySearchLastOccurence(int[] arr, int ele) { int low = 0; int high = arr.length - 1; int ans = -1; while (low <= high) { int mid = (low + high) / 2; if (arr[mid] == ele) { ans = mid; low = mid + 1; } else if (ele < arr[mid]) { high = mid - 1; } else { low = mid + 1; } } return ans; } } private static class arrays { // Merge sort static void merge(int arr[], int l, int m, int r) { int n1 = m - l + 1; int n2 = r - m; int L[] = new int[n1]; int R[] = new int[n2]; for (int i = 0; i < n1; ++i) L[i] = arr[l + i]; for (int j = 0; j < n2; ++j) R[j] = arr[m + 1 + j]; int i = 0, j = 0; int k = l; while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } while (i < n1) { arr[k] = L[i]; i++; k++; } while (j < n2) { arr[k] = R[j]; j++; k++; } } static void sort(int arr[], int l, int r) { if (l < r) { int m = (l + r) / 2; sort(arr, l, m); sort(arr, m + 1, r); merge(arr, l, m, r); } } static void sort(int[] arr) { sort(arr, 0, arr.length - 1); } } private static class UnionFindDisjointSet { int[] parent; int[] size; int n; int size1; public UnionFindDisjointSet(int n) { this.n = n; this.parent = new int[n]; this.size = new int[n]; for (int i = 0; i < n; i++) { parent[i] = i; } for (int i = 0; i < n; i++) { size[i] = 1; } this.size1 = n; } private int numDisjointSets() { System.out.println(size1); return size1; } private boolean find(int a, int b) { int rootA = root(a); int rootB = root(b); if (rootA == rootB) { return true; } return false; } private int root(int b) { while (parent[b] != b) { parent[b] = parent[parent[b]]; b = parent[b]; } return b; } private void union(int a, int b) { int rootA = root(a); int rootB = root(b); if (rootA == rootB) { return; } if (size[rootA] < size[rootB]) { parent[rootA] = parent[rootB]; size[rootB] += size[rootA]; } else { parent[rootB] = parent[rootA]; size[rootA] += size[rootB]; } size1--; System.out.println(Arrays.toString(parent)); } } private static class SegTree { int[] st; int[] arr; public SegTree(int[] arr) { this.arr = arr; int size = (int) Math.ceil(Math.log(arr.length) / Math.log(2)); st = new int[(int) ((2 * Math.pow(2, size)) - 1)]; buildSegmentTree(1, 0, arr.length - 1); } //**********JUST CALL THE CONSTRUCTOR, THIS FUNCTION WILL BE CALLED AUTOMATICALLY****** private void buildSegmentTree(int index, int L, int R) { if (L == R) { st[index] = arr[L]; return; } buildSegmentTree(index * 2, L, (L + R) / 2); buildSegmentTree(index * 2 + 1, (L + R) / 2 + 1, R); // Replace this line if you want to change the function of the Segment tree. st[index] = Math.min(st[index * 2], st[index * 2 + 1]); } //***********We have to use this function ************** private int Query(int queL, int queR) { return Query1(1, 0, arr.length - 1, queL, queR); } //This is a helper function. //************* DO NOT USE THIS **************** private int Query1(int index, int segL, int segR, int queL, int queR) { if (queL > segR || queR < segL) { return -1; } if (queL <= segL && queR >= segR) { return st[index]; } int ans1 = Query1(index * 2, segL, (segL + segR) / 2, queL, queR); int ans2 = Query1(index * 2 + 1, (segL + segR) / 2 + 1, segR, queL, queR); if (ans1 == -1) { return ans2; } if (ans2 == -1) { return ans1; } // Segment tree implemented for range minimum query. Change the below line to change the function. return Math.min(ans1, ans2); } private void update(int idx, int val) { update1(1, 0, arr.length - 1, idx, val); } private void update1(int node, int queL, int queR, int idx, int val) { // idx - index to be updated in the array // node - index to be updated in the seg tree if (queL == queR) { // Leaf node arr[idx] += val; st[node] += val; } else { int mid = (queL + queR) / 2; if (queL <= idx && idx <= mid) { // If idx is in the left child, recurse on the left child update1(2 * node, queL, mid, idx, val); } else { // if idx is in the right child, recurse on the right child update1(2 * node + 1, mid + 1, queR, idx, val); } // Internal node will have the min of both of its children st[node] = Math.min(st[2 * node], st[2 * node + 1]); } } } private static class FastReader { InputStream is; public FastReader(boolean onlineJudge) { is = onlineJudge ? System.in : new ByteArrayInputStream(INPUT.getBytes()); } byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; 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++]; } boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } int skip() { int b; while ((b = readByte()) != -1 && isSpaceChar(b)) ; return b; } double nextDouble() { return Double.parseDouble(next()); } char nextChar() { return (char) skip(); } String next() { int b = skip(); StringBuilder sb = new StringBuilder(); while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } String nextLine() { int b = skip(); StringBuilder sb = new StringBuilder(); while ((!isSpaceChar(b) || b == ' ')) { // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } char[] next(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); } int nextInt() { int num = 0, b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } long nextLong() { 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(); } } char[][] nextMatrix(int n, int m) { char[][] map = new char[n][]; for (int i = 0; i < n; i++) map[i] = next(m); return map; } int[] nextIntArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } long[] nextLongArray(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } int[][] next2DInt(int n, int m) { int[][] arr = new int[n][]; for (int i = 0; i < n; i++) { arr[i] = nextIntArray(m); } return arr; } long[][] next2DLong(int n, int m) { long[][] arr = new long[n][]; for (int i = 0; i < n; i++) { arr[i] = nextLongArray(m); } return arr; } int[] shuffle(int[] arr) { Random r = new Random(); for (int i = 1, j; i < arr.length; i++) { j = r.nextInt(i); arr[i] = arr[i] ^ arr[j]; arr[j] = arr[i] ^ arr[j]; arr[i] = arr[i] ^ arr[j]; } return arr; } int[] uniq(int[] arr) { Arrays.sort(arr); int[] rv = new int[arr.length]; int pos = 0; rv[pos++] = arr[0]; for (int i = 1; i < arr.length; i++) { if (arr[i] != arr[i - 1]) { rv[pos++] = arr[i]; } } return Arrays.copyOf(rv, pos); } } }
Java
["13 3\n3 2 7", "10 9\n1 2 3 4 5 6 7 8 9", "99 5\n32 92 85 74 4", "2 2\n1 0"]
1 second
["even", "odd", "odd", "even"]
NoteIn the first example, $$$n = 3 \cdot 13^2 + 2 \cdot 13 + 7 = 540$$$, which is even.In the second example, $$$n = 123456789$$$ is odd.In the third example, $$$n = 32 \cdot 99^4 + 92 \cdot 99^3 + 85 \cdot 99^2 + 74 \cdot 99 + 4 = 3164015155$$$ is odd.In the fourth example $$$n = 2$$$.
Java 8
standard input
[ "math" ]
ee105b664099808143a94a374d6d5daa
The first line contains two integers $$$b$$$ and $$$k$$$ ($$$2\le b\le 100$$$, $$$1\le k\le 10^5$$$) — the base of the number and the number of digits. The second line contains $$$k$$$ integers $$$a_1, a_2, \ldots, a_k$$$ ($$$0\le a_i &lt; b$$$) — the digits of $$$n$$$. The representation of $$$n$$$ contains no unnecessary leading zero. That is, $$$a_1$$$ can be equal to $$$0$$$ only if $$$k = 1$$$.
900
Print "even" if $$$n$$$ is even, otherwise print "odd". You can print each letter in any case (upper or lower).
standard output
PASSED
acb8cd1c1c5e989435b07b276819705d
train_000.jsonl
1384443000
A boy Petya loves chess very much. He even came up with a chess piece of his own, a semiknight. The semiknight can move in any of these four directions: 2 squares forward and 2 squares to the right, 2 squares forward and 2 squares to the left, 2 squares backward and 2 to the right and 2 squares backward and 2 to the left. Naturally, the semiknight cannot move beyond the limits of the chessboard.Petya put two semiknights on a standard chessboard. Petya simultaneously moves with both semiknights. The squares are rather large, so after some move the semiknights can meet, that is, they can end up in the same square. After the meeting the semiknights can move on, so it is possible that they meet again. Petya wonders if there is such sequence of moves when the semiknights meet. Petya considers some squares bad. That is, they do not suit for the meeting. The semiknights can move through these squares but their meetings in these squares don't count.Petya prepared multiple chess boards. Help Petya find out whether the semiknights can meet on some good square for each board.Please see the test case analysis.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; public class knightMoves { public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw = new PrintWriter(new OutputStreamWriter(System.out)); int t = Integer.parseInt(br.readLine()); for(int i=0;i<t;++i) { int k1x=0,k1y=0,k2x=0,k2y=0; boolean k1 = false,k2=false; for(int j=0;j<8;++j) { String row = br.readLine(); for(int k=0;k<8;++k) { if(row.charAt(k)=='K') { if(!k1) { k1x=j; k1y=k; k1=true; } else if(!k2) { k2x=j; k2y=k; k2=true; } } } } int v1 = Math.abs(k1x-k2x); int v2 = Math.abs(k1y-k2y); if(v1%4==0 && v2%4==0) { pw.println("YES"); } else { pw.println("NO"); } if(i<(t-1)) { br.readLine(); } } pw.flush(); pw.close(); } }
Java
["2\n........\n........\n......#.\nK..##..#\n.......#\n...##..#\n......#.\nK.......\n\n........\n........\n..#.....\n..#..#..\n..####..\n...##...\n........\n....K#K#"]
1 second
["YES\nNO"]
NoteConsider the first board from the sample. We will assume the rows and columns of the matrix to be numbered 1 through 8 from top to bottom and from left to right, correspondingly. The knights can meet, for example, in square (2, 7). The semiknight from square (4, 1) goes to square (2, 3) and the semiknight goes from square (8, 1) to square (6, 3). Then both semiknights go to (4, 5) but this square is bad, so they move together to square (2, 7).On the second board the semiknights will never meet.
Java 6
standard input
[ "greedy", "math" ]
4f3bec9c36d0ac2fdb8041469133458c
The first line contains number t (1 ≤ t ≤ 50) — the number of boards. Each board is described by a matrix of characters, consisting of 8 rows and 8 columns. The matrix consists of characters ".", "#", "K", representing an empty good square, a bad square and the semiknight's position, correspondingly. It is guaranteed that matrix contains exactly 2 semiknights. The semiknight's squares are considered good for the meeting. The tests are separated by empty line.
1,500
For each test, print on a single line the answer to the problem: "YES", if the semiknights can meet and "NO" otherwise.
standard output
PASSED
7cb07126579cb1995ed6211089c5ead7
train_000.jsonl
1384443000
A boy Petya loves chess very much. He even came up with a chess piece of his own, a semiknight. The semiknight can move in any of these four directions: 2 squares forward and 2 squares to the right, 2 squares forward and 2 squares to the left, 2 squares backward and 2 to the right and 2 squares backward and 2 to the left. Naturally, the semiknight cannot move beyond the limits of the chessboard.Petya put two semiknights on a standard chessboard. Petya simultaneously moves with both semiknights. The squares are rather large, so after some move the semiknights can meet, that is, they can end up in the same square. After the meeting the semiknights can move on, so it is possible that they meet again. Petya wonders if there is such sequence of moves when the semiknights meet. Petya considers some squares bad. That is, they do not suit for the meeting. The semiknights can move through these squares but their meetings in these squares don't count.Petya prepared multiple chess boards. Help Petya find out whether the semiknights can meet on some good square for each board.Please see the test case analysis.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; public class knightMoves { public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw = new PrintWriter(new OutputStreamWriter(System.out)); int t = Integer.parseInt(br.readLine()); for(int i=0;i<t;++i) { int k1x=0,k1y=0,k2x=0,k2y=0; boolean k1 = false,k2=false; char[][] values = new char[8][8]; for(int j=0;j<8;++j) { String row = br.readLine(); for(int k=0;k<8;++k) { values[j][k] = row.charAt(k); if(values[j][k]=='K') { if(!k1) { k1x=j; k1y=k; k1=true; } else if(!k2) { k2x=j; k2y=k; k2=true; } } } } // if(k1x==k2x) // { // pw.println("NO"); // } // else // { int v1 = Math.abs(k1x-k2x); int v2 = Math.abs(k1y-k2y); if(v1%4==0 && v2%4==0) { // System.out.println(v1+" "+v2); pw.println("YES"); } else { pw.println("NO"); } // } if(i<(t-1)) { br.readLine(); } } pw.flush(); pw.close(); } }
Java
["2\n........\n........\n......#.\nK..##..#\n.......#\n...##..#\n......#.\nK.......\n\n........\n........\n..#.....\n..#..#..\n..####..\n...##...\n........\n....K#K#"]
1 second
["YES\nNO"]
NoteConsider the first board from the sample. We will assume the rows and columns of the matrix to be numbered 1 through 8 from top to bottom and from left to right, correspondingly. The knights can meet, for example, in square (2, 7). The semiknight from square (4, 1) goes to square (2, 3) and the semiknight goes from square (8, 1) to square (6, 3). Then both semiknights go to (4, 5) but this square is bad, so they move together to square (2, 7).On the second board the semiknights will never meet.
Java 6
standard input
[ "greedy", "math" ]
4f3bec9c36d0ac2fdb8041469133458c
The first line contains number t (1 ≤ t ≤ 50) — the number of boards. Each board is described by a matrix of characters, consisting of 8 rows and 8 columns. The matrix consists of characters ".", "#", "K", representing an empty good square, a bad square and the semiknight's position, correspondingly. It is guaranteed that matrix contains exactly 2 semiknights. The semiknight's squares are considered good for the meeting. The tests are separated by empty line.
1,500
For each test, print on a single line the answer to the problem: "YES", if the semiknights can meet and "NO" otherwise.
standard output
PASSED
32714060e02c05d53219c759674fef92
train_000.jsonl
1384443000
A boy Petya loves chess very much. He even came up with a chess piece of his own, a semiknight. The semiknight can move in any of these four directions: 2 squares forward and 2 squares to the right, 2 squares forward and 2 squares to the left, 2 squares backward and 2 to the right and 2 squares backward and 2 to the left. Naturally, the semiknight cannot move beyond the limits of the chessboard.Petya put two semiknights on a standard chessboard. Petya simultaneously moves with both semiknights. The squares are rather large, so after some move the semiknights can meet, that is, they can end up in the same square. After the meeting the semiknights can move on, so it is possible that they meet again. Petya wonders if there is such sequence of moves when the semiknights meet. Petya considers some squares bad. That is, they do not suit for the meeting. The semiknights can move through these squares but their meetings in these squares don't count.Petya prepared multiple chess boards. Help Petya find out whether the semiknights can meet on some good square for each board.Please see the test case analysis.
256 megabytes
import java.util.Scanner; public class SemiKnight { public static void main (String[] args) { new SemiKnight().solve(); } public void solve () { Scanner in = new Scanner(System.in); int n = in.nextInt(); in.nextLine(); for (int j = 0; j < n; j++) { int k1X = 0; int k1Y = 0; int k2X = 0; int k2Y = 0; boolean firstKnight = false; for (int i = 0; i < 8; i++) { String line = in.nextLine(); // System.out.println(line+"__"+i); int ind = line.indexOf("K"); if (ind != -1) { if (!firstKnight) { k1X = line.indexOf("K"); k1Y = i; firstKnight = true; } else { k2X = line.indexOf("K"); k2Y = i; } if (ind + 1 <= 8) { line = line.substring(ind + 1); int ind2 = line.indexOf("K"); if (ind2 != -1) { if (!firstKnight) { k1X = ind2 + ind+1; k1Y = i; firstKnight = true; } else { k2X = ind2 + ind+1; k2Y = i; } } } } } if(j!=n-1){ in.nextLine(); } // System.out.println(k1X + " " + k1Y); // System.out.println(k2X + " " + k2Y); int xDiff = Math.abs(k1X - k2X); int yDiff = Math.abs(k1Y - k2Y); if (xDiff%4==0 && yDiff % 4 == 0) { System.out.println("YES"); } else { System.out.println("NO"); } } } }
Java
["2\n........\n........\n......#.\nK..##..#\n.......#\n...##..#\n......#.\nK.......\n\n........\n........\n..#.....\n..#..#..\n..####..\n...##...\n........\n....K#K#"]
1 second
["YES\nNO"]
NoteConsider the first board from the sample. We will assume the rows and columns of the matrix to be numbered 1 through 8 from top to bottom and from left to right, correspondingly. The knights can meet, for example, in square (2, 7). The semiknight from square (4, 1) goes to square (2, 3) and the semiknight goes from square (8, 1) to square (6, 3). Then both semiknights go to (4, 5) but this square is bad, so they move together to square (2, 7).On the second board the semiknights will never meet.
Java 6
standard input
[ "greedy", "math" ]
4f3bec9c36d0ac2fdb8041469133458c
The first line contains number t (1 ≤ t ≤ 50) — the number of boards. Each board is described by a matrix of characters, consisting of 8 rows and 8 columns. The matrix consists of characters ".", "#", "K", representing an empty good square, a bad square and the semiknight's position, correspondingly. It is guaranteed that matrix contains exactly 2 semiknights. The semiknight's squares are considered good for the meeting. The tests are separated by empty line.
1,500
For each test, print on a single line the answer to the problem: "YES", if the semiknights can meet and "NO" otherwise.
standard output
PASSED
16b08553c40d4f2c1166c90748bfd347
train_000.jsonl
1384443000
A boy Petya loves chess very much. He even came up with a chess piece of his own, a semiknight. The semiknight can move in any of these four directions: 2 squares forward and 2 squares to the right, 2 squares forward and 2 squares to the left, 2 squares backward and 2 to the right and 2 squares backward and 2 to the left. Naturally, the semiknight cannot move beyond the limits of the chessboard.Petya put two semiknights on a standard chessboard. Petya simultaneously moves with both semiknights. The squares are rather large, so after some move the semiknights can meet, that is, they can end up in the same square. After the meeting the semiknights can move on, so it is possible that they meet again. Petya wonders if there is such sequence of moves when the semiknights meet. Petya considers some squares bad. That is, they do not suit for the meeting. The semiknights can move through these squares but their meetings in these squares don't count.Petya prepared multiple chess boards. Help Petya find out whether the semiknights can meet on some good square for each board.Please see the test case analysis.
256 megabytes
import java.util.*; public class cf362A{ public static void main(String args[]) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); for(int i=0; i<t; i++) { int[][] matrix = new int[8][8]; int[][] knights = new int[2][2]; int kcount = 0; for(int j=0; j<8; j++) { String inp = sc.next(); for(int k=0; k<8; k++) { if(inp.charAt(k) == '#' ) { matrix[j][k] = 1; } if(inp.charAt(k) == 'K') { matrix[j][k] = 2; knights[kcount][0] = j; knights[kcount][1] = k; kcount++; } } } boolean[][][][] visited = new boolean[8][8][8][8]; if(ifPossible(matrix, knights,visited)) System.out.println("YES"); else System.out.println("NO"); } } public static boolean ifPossible(int[][] matrix, int[][] knights, boolean[][][][] visited) { if(knights[0][0] == knights[1][0] && knights[0][1] == knights[1][1] && matrix[knights[0][0]][knights[0][1]] != 1) { return true; } visited[knights[0][0]][knights[0][1]][knights[1][0]][knights[1][1]] = true; if(knights[0][0] + 2 < 8 && knights[0][1]+2 < 8) { if(knights[1][0] + 2 < 8 && knights[1][1]+2 < 8) { int[][] temp = new int[2][2]; temp[0][0] = knights[0][0] + 2; temp[0][1] = knights[0][1] + 2; temp[1][0] = knights[1][0] + 2; temp[1][1] = knights[1][1] + 2; if(!visited[temp[0][0]][temp[0][1]][temp[1][0]][temp[1][1]]) if(ifPossible(matrix,temp,visited)) return true; } if(knights[1][0] + 2 < 8 && knights[1][1]-2 >=0) { int[][] temp = new int[2][2]; temp[0][0] = knights[0][0] + 2; temp[0][1] = knights[0][1] + 2; temp[1][0] = knights[1][0] + 2; temp[1][1] = knights[1][1] - 2; if(!visited[temp[0][0]][temp[0][1]][temp[1][0]][temp[1][1]]) if(ifPossible(matrix,temp,visited)) return true; } if(knights[1][0] - 2 >=0 && knights[1][1]+2 < 8) { int[][] temp = new int[2][2]; temp[0][0] = knights[0][0] + 2; temp[0][1] = knights[0][1] + 2; temp[1][0] = knights[1][0] - 2; temp[1][1] = knights[1][1] + 2; if(!visited[temp[0][0]][temp[0][1]][temp[1][0]][temp[1][1]]) if(ifPossible(matrix,temp,visited)) return true; } if(knights[1][0] - 2 >= 0 && knights[1][1]-2 >=0) { int[][] temp = new int[2][2]; temp[0][0] = knights[0][0] + 2; temp[0][1] = knights[0][1] + 2; temp[1][0] = knights[1][0] - 2; temp[1][1] = knights[1][1] - 2; if(!visited[temp[0][0]][temp[0][1]][temp[1][0]][temp[1][1]]) if(ifPossible(matrix,temp,visited)) return true; } } if(knights[0][0] + 2 < 8 && knights[0][1]-2 >=0) { if(knights[1][0] + 2 < 8 && knights[1][1]+2 < 8) { int[][] temp = new int[2][2]; temp[0][0] = knights[0][0] + 2; temp[0][1] = knights[0][1] - 2; temp[1][0] = knights[1][0] + 2; temp[1][1] = knights[1][1] + 2; if(!visited[temp[0][0]][temp[0][1]][temp[1][0]][temp[1][1]]) if(ifPossible(matrix,temp,visited)) return true; } if(knights[1][0] + 2 < 8 && knights[1][1]-2 >=0) { int[][] temp = new int[2][2]; temp[0][0] = knights[0][0] + 2; temp[0][1] = knights[0][1] - 2; temp[1][0] = knights[1][0] + 2; temp[1][1] = knights[1][1] - 2; if(!visited[temp[0][0]][temp[0][1]][temp[1][0]][temp[1][1]]) if(ifPossible(matrix,temp,visited)) return true; } if(knights[1][0] - 2 >=0 && knights[1][1]+2 < 8) { int[][] temp = new int[2][2]; temp[0][0] = knights[0][0] + 2; temp[0][1] = knights[0][1] - 2; temp[1][0] = knights[1][0] - 2; temp[1][1] = knights[1][1] + 2; if(!visited[temp[0][0]][temp[0][1]][temp[1][0]][temp[1][1]]) if(ifPossible(matrix,temp,visited)) return true; } if(knights[1][0] - 2 >= 0 && knights[1][1]-2 >=0) { int[][] temp = new int[2][2]; temp[0][0] = knights[0][0] + 2; temp[0][1] = knights[0][1] - 2; temp[1][0] = knights[1][0] - 2; temp[1][1] = knights[1][1] - 2; if(!visited[temp[0][0]][temp[0][1]][temp[1][0]][temp[1][1]]) if(ifPossible(matrix,temp,visited)) return true; } } if(knights[0][0] - 2 >=0 && knights[0][1]+2 < 8) { if(knights[1][0] + 2 < 8 && knights[1][1]+2 < 8) { int[][] temp = new int[2][2]; temp[0][0] = knights[0][0] - 2; temp[0][1] = knights[0][1] + 2; temp[1][0] = knights[1][0] + 2; temp[1][1] = knights[1][1] + 2; if(!visited[temp[0][0]][temp[0][1]][temp[1][0]][temp[1][1]]) if(ifPossible(matrix,temp,visited)) return true; } if(knights[1][0] + 2 < 8 && knights[1][1]-2 >=0) { int[][] temp = new int[2][2]; temp[0][0] = knights[0][0] - 2; temp[0][1] = knights[0][1] + 2; temp[1][0] = knights[1][0] + 2; temp[1][1] = knights[1][1] - 2; if(!visited[temp[0][0]][temp[0][1]][temp[1][0]][temp[1][1]]) if(ifPossible(matrix,temp,visited)) return true; } if(knights[1][0] - 2 >=0 && knights[1][1]+2 < 8) { int[][] temp = new int[2][2]; temp[0][0] = knights[0][0] - 2; temp[0][1] = knights[0][1] + 2; temp[1][0] = knights[1][0] - 2; temp[1][1] = knights[1][1] + 2; if(!visited[temp[0][0]][temp[0][1]][temp[1][0]][temp[1][1]]) if(ifPossible(matrix,temp,visited)) return true; } if(knights[1][0] - 2 >= 0 && knights[1][1]-2 >=0) { int[][] temp = new int[2][2]; temp[0][0] = knights[0][0] - 2; temp[0][1] = knights[0][1] + 2; temp[1][0] = knights[1][0] - 2; temp[1][1] = knights[1][1] - 2; if(!visited[temp[0][0]][temp[0][1]][temp[1][0]][temp[1][1]]) if(ifPossible(matrix,temp,visited)) return true; } } if(knights[0][0] - 2 >= 0 && knights[0][1]-2 >=0) { if(knights[1][0] + 2 < 8 && knights[1][1]+2 < 8) { int[][] temp = new int[2][2]; temp[0][0] = knights[0][0] - 2; temp[0][1] = knights[0][1] - 2; temp[1][0] = knights[1][0] + 2; temp[1][1] = knights[1][1] + 2; if(!visited[temp[0][0]][temp[0][1]][temp[1][0]][temp[1][1]]) if(ifPossible(matrix,temp,visited)) return true; } if(knights[1][0] + 2 < 8 && knights[1][1]-2 >=0) { int[][] temp = new int[2][2]; temp[0][0] = knights[0][0] - 2; temp[0][1] = knights[0][1] - 2; temp[1][0] = knights[1][0] + 2; temp[1][1] = knights[1][1] - 2; if(!visited[temp[0][0]][temp[0][1]][temp[1][0]][temp[1][1]]) if(ifPossible(matrix,temp,visited)) return true; } if(knights[1][0] - 2 >=0 && knights[1][1]+2 < 8) { int[][] temp = new int[2][2]; temp[0][0] = knights[0][0] - 2; temp[0][1] = knights[0][1] - 2; temp[1][0] = knights[1][0] - 2; temp[1][1] = knights[1][1] + 2; if(!visited[temp[0][0]][temp[0][1]][temp[1][0]][temp[1][1]]) if(ifPossible(matrix,temp,visited)) return true; } if(knights[1][0] - 2 >= 0 && knights[1][1]-2 >=0) { int[][] temp = new int[2][2]; temp[0][0] = knights[0][0] - 2; temp[0][1] = knights[0][1] - 2; temp[1][0] = knights[1][0] - 2; temp[1][1] = knights[1][1] - 2; if(!visited[temp[0][0]][temp[0][1]][temp[1][0]][temp[1][1]]) if(ifPossible(matrix,temp,visited)) return true; } } return false; } }
Java
["2\n........\n........\n......#.\nK..##..#\n.......#\n...##..#\n......#.\nK.......\n\n........\n........\n..#.....\n..#..#..\n..####..\n...##...\n........\n....K#K#"]
1 second
["YES\nNO"]
NoteConsider the first board from the sample. We will assume the rows and columns of the matrix to be numbered 1 through 8 from top to bottom and from left to right, correspondingly. The knights can meet, for example, in square (2, 7). The semiknight from square (4, 1) goes to square (2, 3) and the semiknight goes from square (8, 1) to square (6, 3). Then both semiknights go to (4, 5) but this square is bad, so they move together to square (2, 7).On the second board the semiknights will never meet.
Java 6
standard input
[ "greedy", "math" ]
4f3bec9c36d0ac2fdb8041469133458c
The first line contains number t (1 ≤ t ≤ 50) — the number of boards. Each board is described by a matrix of characters, consisting of 8 rows and 8 columns. The matrix consists of characters ".", "#", "K", representing an empty good square, a bad square and the semiknight's position, correspondingly. It is guaranteed that matrix contains exactly 2 semiknights. The semiknight's squares are considered good for the meeting. The tests are separated by empty line.
1,500
For each test, print on a single line the answer to the problem: "YES", if the semiknights can meet and "NO" otherwise.
standard output
PASSED
426d9666b00048dfb52ba0a7b98b8643
train_000.jsonl
1384443000
A boy Petya loves chess very much. He even came up with a chess piece of his own, a semiknight. The semiknight can move in any of these four directions: 2 squares forward and 2 squares to the right, 2 squares forward and 2 squares to the left, 2 squares backward and 2 to the right and 2 squares backward and 2 to the left. Naturally, the semiknight cannot move beyond the limits of the chessboard.Petya put two semiknights on a standard chessboard. Petya simultaneously moves with both semiknights. The squares are rather large, so after some move the semiknights can meet, that is, they can end up in the same square. After the meeting the semiknights can move on, so it is possible that they meet again. Petya wonders if there is such sequence of moves when the semiknights meet. Petya considers some squares bad. That is, they do not suit for the meeting. The semiknights can move through these squares but their meetings in these squares don't count.Petya prepared multiple chess boards. Help Petya find out whether the semiknights can meet on some good square for each board.Please see the test case analysis.
256 megabytes
import java.util.*; import static java.lang.Math.*; public class A { void run() { Scanner sc = new Scanner(System.in); int N = sc.nextInt(); for (int t = 0; t < N; ++t) { sc.nextLine(); int[][] pos = new int[][] {null, null}; for (int i = 0; i < 8; ++i) { char[] c = sc.nextLine().toCharArray(); for (int j = 0; j < 8; ++j) { if (c[j] == 'K') { int[] k = new int[] {i, j}; if (pos[0] == null) { pos[0] = k; } else { pos[1] = k; } } } } int dx = pos[0][0] - pos[1][0]; int dy = pos[0][1] - pos[1][1]; if (dx % 4 == 0 && dy % 4 == 0) { p("YES\n"); } else { p("NO\n"); } } } void p(String f,Object...p) { System.out.printf(f, p); } public A() {} public static void main(String[] args) { new A().run(); } }
Java
["2\n........\n........\n......#.\nK..##..#\n.......#\n...##..#\n......#.\nK.......\n\n........\n........\n..#.....\n..#..#..\n..####..\n...##...\n........\n....K#K#"]
1 second
["YES\nNO"]
NoteConsider the first board from the sample. We will assume the rows and columns of the matrix to be numbered 1 through 8 from top to bottom and from left to right, correspondingly. The knights can meet, for example, in square (2, 7). The semiknight from square (4, 1) goes to square (2, 3) and the semiknight goes from square (8, 1) to square (6, 3). Then both semiknights go to (4, 5) but this square is bad, so they move together to square (2, 7).On the second board the semiknights will never meet.
Java 6
standard input
[ "greedy", "math" ]
4f3bec9c36d0ac2fdb8041469133458c
The first line contains number t (1 ≤ t ≤ 50) — the number of boards. Each board is described by a matrix of characters, consisting of 8 rows and 8 columns. The matrix consists of characters ".", "#", "K", representing an empty good square, a bad square and the semiknight's position, correspondingly. It is guaranteed that matrix contains exactly 2 semiknights. The semiknight's squares are considered good for the meeting. The tests are separated by empty line.
1,500
For each test, print on a single line the answer to the problem: "YES", if the semiknights can meet and "NO" otherwise.
standard output
PASSED
475c906d927e203e6e9561a505128618
train_000.jsonl
1384443000
A boy Petya loves chess very much. He even came up with a chess piece of his own, a semiknight. The semiknight can move in any of these four directions: 2 squares forward and 2 squares to the right, 2 squares forward and 2 squares to the left, 2 squares backward and 2 to the right and 2 squares backward and 2 to the left. Naturally, the semiknight cannot move beyond the limits of the chessboard.Petya put two semiknights on a standard chessboard. Petya simultaneously moves with both semiknights. The squares are rather large, so after some move the semiknights can meet, that is, they can end up in the same square. After the meeting the semiknights can move on, so it is possible that they meet again. Petya wonders if there is such sequence of moves when the semiknights meet. Petya considers some squares bad. That is, they do not suit for the meeting. The semiknights can move through these squares but their meetings in these squares don't count.Petya prepared multiple chess boards. Help Petya find out whether the semiknights can meet on some good square for each board.Please see the test case analysis.
256 megabytes
import java.util.Scanner; public class JavaApplication1 { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here int t; Scanner sc = new Scanner(System.in); t = sc.nextInt(); for(int yyyy = 1; yyyy <= t; yyyy++) { char s; int kf1=0,kf2=0,ks1=0,ks2=0; boolean flag = false; boolean Mass[][]; Mass = new boolean[2][4]; String str = new String(); for(int i = 0; i <= 7; i++) { str = sc.next(); for(int j = 0; j <= 7; j++) { s = str.charAt(j); if(s == 'K') { if(!flag) { flag = true; kf1 = i%4; ks1 = j%4; } else { kf2 = i%4; ks2 = j%4; } } if(s == '.') { Mass[i%2][(i+j)%4] = true; } } } if((ks1 == ks2)&&(kf1 == kf2)) { System.out.println("YES"); } else { System.out.println("NO"); } } } }
Java
["2\n........\n........\n......#.\nK..##..#\n.......#\n...##..#\n......#.\nK.......\n\n........\n........\n..#.....\n..#..#..\n..####..\n...##...\n........\n....K#K#"]
1 second
["YES\nNO"]
NoteConsider the first board from the sample. We will assume the rows and columns of the matrix to be numbered 1 through 8 from top to bottom and from left to right, correspondingly. The knights can meet, for example, in square (2, 7). The semiknight from square (4, 1) goes to square (2, 3) and the semiknight goes from square (8, 1) to square (6, 3). Then both semiknights go to (4, 5) but this square is bad, so they move together to square (2, 7).On the second board the semiknights will never meet.
Java 6
standard input
[ "greedy", "math" ]
4f3bec9c36d0ac2fdb8041469133458c
The first line contains number t (1 ≤ t ≤ 50) — the number of boards. Each board is described by a matrix of characters, consisting of 8 rows and 8 columns. The matrix consists of characters ".", "#", "K", representing an empty good square, a bad square and the semiknight's position, correspondingly. It is guaranteed that matrix contains exactly 2 semiknights. The semiknight's squares are considered good for the meeting. The tests are separated by empty line.
1,500
For each test, print on a single line the answer to the problem: "YES", if the semiknights can meet and "NO" otherwise.
standard output
PASSED
6a5163d454d4128b3dc174ca8689e7d0
train_000.jsonl
1384443000
A boy Petya loves chess very much. He even came up with a chess piece of his own, a semiknight. The semiknight can move in any of these four directions: 2 squares forward and 2 squares to the right, 2 squares forward and 2 squares to the left, 2 squares backward and 2 to the right and 2 squares backward and 2 to the left. Naturally, the semiknight cannot move beyond the limits of the chessboard.Petya put two semiknights on a standard chessboard. Petya simultaneously moves with both semiknights. The squares are rather large, so after some move the semiknights can meet, that is, they can end up in the same square. After the meeting the semiknights can move on, so it is possible that they meet again. Petya wonders if there is such sequence of moves when the semiknights meet. Petya considers some squares bad. That is, they do not suit for the meeting. The semiknights can move through these squares but their meetings in these squares don't count.Petya prepared multiple chess boards. Help Petya find out whether the semiknights can meet on some good square for each board.Please see the test case analysis.
256 megabytes
import java.io.*; import java.util.*; public class A { public static void main(String[] args) throws IOException { A solver = new A(); solver.solve(); } private void solve() throws IOException { FastScanner sc = new FastScanner(System.in); // sc = new FastScanner("2\n" + // "........\n" + // "........\n" + // "......#.\n" + // "K..##..#\n" + // ".......#\n" + // "...##..#\n" + // "......#.\n" + // "K.......\n" + // "\n" + // "........\n" + // "........\n" + // "..#.....\n" + // "..#..#..\n" + // "..####..\n" + // "...##...\n" + // "........\n" + // "....K#K#\n"); int n = sc.nextInt(); for (int t = 0; t < n; t++) { int x = -1; int y = -1; int xx = -1; int yy = -1; for (int i = 0; i < 8; i++) { String line = sc.next(); for (int j = 0; j < line.length(); j++) { if (line.charAt(j) == 'K') { if (x == -1 || y == -1) { x = i; y = j; } else { xx = i; yy = j; } } } } boolean[][] m = new boolean[8][8]; boolean r = dfs(x, y, xx, yy, 0, m); System.out.println(r ? "YES" : "NO"); } } private boolean dfs(int x, int y, int xx, int yy, int i, boolean[][] m) { if (x < 0 || y < 0 || x >= 8 || y >= 8) return false; if (m[x][y]) return false; m[x][y] = true; if (x == xx && y == yy && i % 2 == 0) return true; if (dfs(x + 2, y + 2, xx, yy, i + 1, m)) return true; if (dfs(x - 2, y - 2, xx, yy, i + 1, m)) return true; if (dfs(x + 2, y - 2, xx, yy, i + 1, m)) return true; if (dfs(x - 2, y + 2, xx, yy, i + 1, m)) return true; return false; } private static class FastScanner { private BufferedReader br; private StringTokenizer st; public FastScanner(InputStream in) throws IOException { br = new BufferedReader(new InputStreamReader(in)); } public FastScanner(File file) throws IOException { br = new BufferedReader(new FileReader(file)); } public FastScanner(String s) { br = new BufferedReader(new StringReader(s)); } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); return ""; } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } }
Java
["2\n........\n........\n......#.\nK..##..#\n.......#\n...##..#\n......#.\nK.......\n\n........\n........\n..#.....\n..#..#..\n..####..\n...##...\n........\n....K#K#"]
1 second
["YES\nNO"]
NoteConsider the first board from the sample. We will assume the rows and columns of the matrix to be numbered 1 through 8 from top to bottom and from left to right, correspondingly. The knights can meet, for example, in square (2, 7). The semiknight from square (4, 1) goes to square (2, 3) and the semiknight goes from square (8, 1) to square (6, 3). Then both semiknights go to (4, 5) but this square is bad, so they move together to square (2, 7).On the second board the semiknights will never meet.
Java 6
standard input
[ "greedy", "math" ]
4f3bec9c36d0ac2fdb8041469133458c
The first line contains number t (1 ≤ t ≤ 50) — the number of boards. Each board is described by a matrix of characters, consisting of 8 rows and 8 columns. The matrix consists of characters ".", "#", "K", representing an empty good square, a bad square and the semiknight's position, correspondingly. It is guaranteed that matrix contains exactly 2 semiknights. The semiknight's squares are considered good for the meeting. The tests are separated by empty line.
1,500
For each test, print on a single line the answer to the problem: "YES", if the semiknights can meet and "NO" otherwise.
standard output
PASSED
fc2dd7cbe309a0b144ae40f87e34c42d
train_000.jsonl
1384443000
A boy Petya loves chess very much. He even came up with a chess piece of his own, a semiknight. The semiknight can move in any of these four directions: 2 squares forward and 2 squares to the right, 2 squares forward and 2 squares to the left, 2 squares backward and 2 to the right and 2 squares backward and 2 to the left. Naturally, the semiknight cannot move beyond the limits of the chessboard.Petya put two semiknights on a standard chessboard. Petya simultaneously moves with both semiknights. The squares are rather large, so after some move the semiknights can meet, that is, they can end up in the same square. After the meeting the semiknights can move on, so it is possible that they meet again. Petya wonders if there is such sequence of moves when the semiknights meet. Petya considers some squares bad. That is, they do not suit for the meeting. The semiknights can move through these squares but their meetings in these squares don't count.Petya prepared multiple chess boards. Help Petya find out whether the semiknights can meet on some good square for each board.Please see the test case analysis.
256 megabytes
import java.util.*; public class SemiKnights362A { public static void main(String[] args) { // Set up scanner Scanner sc = new Scanner(System.in); // System.out.println("Enter n"); int n = sc.nextInt(); for (int i=0; i<n; i++) { int k1r = -1; int k2r = -1; int k1c = -1; int k2c = -1; for (int r=0; r<8; r++) { // System.out.println("Enter next row"); String st = sc.next(); for (int c=0; c<8; c++) { String ch = st.substring(c,c+1); if (ch.equals("K")) { if (k1r == -1) // The first one { k1r = r; k1c = c; } else // The second one { k2r = r; k2c = c; } } } } if (k1r%4 != k2r%4) { System.out.println("NO"); } else if (k1c%4 != k2c%4) { System.out.println("NO"); } else if ((k1r+k1c)%4 != (k2r+k2c)%4) { System.out.println("NO"); } else { System.out.println("YES"); } } } }
Java
["2\n........\n........\n......#.\nK..##..#\n.......#\n...##..#\n......#.\nK.......\n\n........\n........\n..#.....\n..#..#..\n..####..\n...##...\n........\n....K#K#"]
1 second
["YES\nNO"]
NoteConsider the first board from the sample. We will assume the rows and columns of the matrix to be numbered 1 through 8 from top to bottom and from left to right, correspondingly. The knights can meet, for example, in square (2, 7). The semiknight from square (4, 1) goes to square (2, 3) and the semiknight goes from square (8, 1) to square (6, 3). Then both semiknights go to (4, 5) but this square is bad, so they move together to square (2, 7).On the second board the semiknights will never meet.
Java 6
standard input
[ "greedy", "math" ]
4f3bec9c36d0ac2fdb8041469133458c
The first line contains number t (1 ≤ t ≤ 50) — the number of boards. Each board is described by a matrix of characters, consisting of 8 rows and 8 columns. The matrix consists of characters ".", "#", "K", representing an empty good square, a bad square and the semiknight's position, correspondingly. It is guaranteed that matrix contains exactly 2 semiknights. The semiknight's squares are considered good for the meeting. The tests are separated by empty line.
1,500
For each test, print on a single line the answer to the problem: "YES", if the semiknights can meet and "NO" otherwise.
standard output
PASSED
82e1e81b085acf10b1b89a1437088eaf
train_000.jsonl
1585233300
You are given two positive integers $$$a$$$ and $$$b$$$. In one move you can increase $$$a$$$ by $$$1$$$ (replace $$$a$$$ with $$$a+1$$$). Your task is to find the minimum number of moves you need to do in order to make $$$a$$$ divisible by $$$b$$$. It is possible, that you have to make $$$0$$$ moves, as $$$a$$$ is already divisible by $$$b$$$. You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.io.*; import java.math.*; import java.security.*; import java.text.*; import java.lang.*; import java.util.*; import java.util.concurrent.*; public class Result{ public static void main(String[] args) { Scanner s=new Scanner(System.in); int t=s.nextInt(); while(t-->0){ int a=s.nextInt(); int b=s.nextInt(); int k=a/b; if(k==0){ System.out.println(b-a); } else{ if(a%b==0){ System.out.println(0); } else{ System.out.println(((k+1)*b)-a); } } } } }
Java
["5\n10 4\n13 9\n100 13\n123 456\n92 46"]
1 second
["2\n5\n4\n333\n0"]
null
Java 8
standard input
[ "math" ]
d9fd10700cb122b148202a664e7f7689
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains two integers $$$a$$$ and $$$b$$$ ($$$1 \le a, b \le 10^9$$$).
800
For each test case print the answer — the minimum number of moves you need to do in order to make $$$a$$$ divisible by $$$b$$$.
standard output
PASSED
18980078faf84e7317ee4f74d2f075c9
train_000.jsonl
1585233300
You are given two positive integers $$$a$$$ and $$$b$$$. In one move you can increase $$$a$$$ by $$$1$$$ (replace $$$a$$$ with $$$a+1$$$). Your task is to find the minimum number of moves you need to do in order to make $$$a$$$ divisible by $$$b$$$. It is possible, that you have to make $$$0$$$ moves, as $$$a$$$ is already divisible by $$$b$$$. You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.util.Scanner; import java.util.*; public class Divisible { public static void main(String args[]){ Scanner sc=new Scanner(System.in); int t=sc.nextInt(); int res[]=new int[t]; for(int i=0;i<t;i++){ int a=sc.nextInt(); int b=sc.nextInt(); res[i]=getCount(a,b); } for(int i:res){ System.out.println(i); } } public static int getCount(int a,int b){ int count=0; int rem=a%b; // while(rem!=0){ // a=a+1; // count++; // rem=a%b; // } if(a%b==0) return 0; return (b-(a%b)); } }
Java
["5\n10 4\n13 9\n100 13\n123 456\n92 46"]
1 second
["2\n5\n4\n333\n0"]
null
Java 8
standard input
[ "math" ]
d9fd10700cb122b148202a664e7f7689
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains two integers $$$a$$$ and $$$b$$$ ($$$1 \le a, b \le 10^9$$$).
800
For each test case print the answer — the minimum number of moves you need to do in order to make $$$a$$$ divisible by $$$b$$$.
standard output
PASSED
8095cbbe2b9ce4a727de826ed284c63f
train_000.jsonl
1585233300
You are given two positive integers $$$a$$$ and $$$b$$$. In one move you can increase $$$a$$$ by $$$1$$$ (replace $$$a$$$ with $$$a+1$$$). Your task is to find the minimum number of moves you need to do in order to make $$$a$$$ divisible by $$$b$$$. It is possible, that you have to make $$$0$$$ moves, as $$$a$$$ is already divisible by $$$b$$$. You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.util.*; public class Problem1 { public static void main(String[] args) { Scanner read=new Scanner(System.in); int t=read.nextInt(); for(int i=0;i<t;i++) { int a=read.nextInt(); int b=read.nextInt(); if(a%b==0) System.out.println(0); else { double divide=a*1.0/b; int result=((int)Math.ceil(divide))*b-a; System.out.println(result); } } } }
Java
["5\n10 4\n13 9\n100 13\n123 456\n92 46"]
1 second
["2\n5\n4\n333\n0"]
null
Java 8
standard input
[ "math" ]
d9fd10700cb122b148202a664e7f7689
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains two integers $$$a$$$ and $$$b$$$ ($$$1 \le a, b \le 10^9$$$).
800
For each test case print the answer — the minimum number of moves you need to do in order to make $$$a$$$ divisible by $$$b$$$.
standard output
PASSED
9f88da3252d40e486d2aa859962495b7
train_000.jsonl
1585233300
You are given two positive integers $$$a$$$ and $$$b$$$. In one move you can increase $$$a$$$ by $$$1$$$ (replace $$$a$$$ with $$$a+1$$$). Your task is to find the minimum number of moves you need to do in order to make $$$a$$$ divisible by $$$b$$$. It is possible, that you have to make $$$0$$$ moves, as $$$a$$$ is already divisible by $$$b$$$. You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.util.Scanner; public class Main{ public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); long[] out = new long[n]; for(int i=0; i<n; i++){ long a = scanner.nextLong(); long b = scanner.nextLong(); int count = 0; // while(a % b != 0){ // a++; // count++; // } long c = a % b; if(c != 0) out[i] = b - c; else out[i] = c; } for(int i=0; i<n; i++){ System.out.println(out[i]); } } }
Java
["5\n10 4\n13 9\n100 13\n123 456\n92 46"]
1 second
["2\n5\n4\n333\n0"]
null
Java 8
standard input
[ "math" ]
d9fd10700cb122b148202a664e7f7689
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains two integers $$$a$$$ and $$$b$$$ ($$$1 \le a, b \le 10^9$$$).
800
For each test case print the answer — the minimum number of moves you need to do in order to make $$$a$$$ divisible by $$$b$$$.
standard output
PASSED
5ded8aedccb8bfbe42a602fae5512fd1
train_000.jsonl
1585233300
You are given two positive integers $$$a$$$ and $$$b$$$. In one move you can increase $$$a$$$ by $$$1$$$ (replace $$$a$$$ with $$$a+1$$$). Your task is to find the minimum number of moves you need to do in order to make $$$a$$$ divisible by $$$b$$$. It is possible, that you have to make $$$0$$$ moves, as $$$a$$$ is already divisible by $$$b$$$. You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.util.*; public class div{ public static void main(String[] args){ Scanner sc=new Scanner(System.in); int n=sc.nextInt(); int t=n; int[] ans=new int[n]; int i=0; while( (n--) > 0 ) { double a = sc.nextDouble(); double b = sc.nextDouble(); int count=0; if((a%b)!=0){ if(b>a){ count=(int)(b-a); } else{ double div=Math.ceil(a/b); div=(int)div; count=(int)(div*b-a); } } ans[i]=count; i++; } for(int j=0;j<t;j++) System.out.println(ans[j]); } }
Java
["5\n10 4\n13 9\n100 13\n123 456\n92 46"]
1 second
["2\n5\n4\n333\n0"]
null
Java 8
standard input
[ "math" ]
d9fd10700cb122b148202a664e7f7689
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains two integers $$$a$$$ and $$$b$$$ ($$$1 \le a, b \le 10^9$$$).
800
For each test case print the answer — the minimum number of moves you need to do in order to make $$$a$$$ divisible by $$$b$$$.
standard output
PASSED
01a7f53ed29760a95372215418953204
train_000.jsonl
1585233300
You are given two positive integers $$$a$$$ and $$$b$$$. In one move you can increase $$$a$$$ by $$$1$$$ (replace $$$a$$$ with $$$a+1$$$). Your task is to find the minimum number of moves you need to do in order to make $$$a$$$ divisible by $$$b$$$. It is possible, that you have to make $$$0$$$ moves, as $$$a$$$ is already divisible by $$$b$$$. You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.util.Scanner; import java.lang.*; public class Test { public void check(long a,long b) { if(a%b==0) System.out.println("0"); else { System.out.println(b-(a%b)); } } public static void main(String [] args) { Test t1=new Test(); Scanner sc=new Scanner(System.in); int t=sc.nextInt(); while(t!=0) { long a,b; a=sc.nextInt(); b=sc.nextInt(); t1.check(a,b); t--; } } }
Java
["5\n10 4\n13 9\n100 13\n123 456\n92 46"]
1 second
["2\n5\n4\n333\n0"]
null
Java 8
standard input
[ "math" ]
d9fd10700cb122b148202a664e7f7689
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains two integers $$$a$$$ and $$$b$$$ ($$$1 \le a, b \le 10^9$$$).
800
For each test case print the answer — the minimum number of moves you need to do in order to make $$$a$$$ divisible by $$$b$$$.
standard output
PASSED
cfa72e0ac2849db1bb700c29d2e7aa6d
train_000.jsonl
1585233300
You are given two positive integers $$$a$$$ and $$$b$$$. In one move you can increase $$$a$$$ by $$$1$$$ (replace $$$a$$$ with $$$a+1$$$). Your task is to find the minimum number of moves you need to do in order to make $$$a$$$ divisible by $$$b$$$. It is possible, that you have to make $$$0$$$ moves, as $$$a$$$ is already divisible by $$$b$$$. You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.io.*; import java.util.*; public class Divisibility { public static void main(String[] args) throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(br.readLine()); for (int i = 0; i < t; i++) { StringTokenizer st = new StringTokenizer(br.readLine()); int a = Integer.parseInt(st.nextToken()); int b = Integer.parseInt(st.nextToken()); System.out.println((int)Math.ceil((double)a / b) * b - a); } br.close(); } }
Java
["5\n10 4\n13 9\n100 13\n123 456\n92 46"]
1 second
["2\n5\n4\n333\n0"]
null
Java 8
standard input
[ "math" ]
d9fd10700cb122b148202a664e7f7689
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains two integers $$$a$$$ and $$$b$$$ ($$$1 \le a, b \le 10^9$$$).
800
For each test case print the answer — the minimum number of moves you need to do in order to make $$$a$$$ divisible by $$$b$$$.
standard output
PASSED
83ef119454ff6da6049c50aa7c48f0e7
train_000.jsonl
1585233300
You are given two positive integers $$$a$$$ and $$$b$$$. In one move you can increase $$$a$$$ by $$$1$$$ (replace $$$a$$$ with $$$a+1$$$). Your task is to find the minimum number of moves you need to do in order to make $$$a$$$ divisible by $$$b$$$. It is possible, that you have to make $$$0$$$ moves, as $$$a$$$ is already divisible by $$$b$$$. You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.util.Scanner; /** * * @author Perry */ public class DivisibilityProblem { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here Scanner input=new Scanner(System.in); int []A; A=new int[200000]; int n1=0; int n2=0; int moves=0; // System.out.println("Insert input:"); int numop=input.nextInt(); for(int i=0;i<numop;i++) { n1=input.nextInt(); n2=input.nextInt(); if(n1%n2==0) { moves=0; } else{ moves=n2-(n1%n2); } A[i]=moves; } for(int x=0;x<numop;x++) { System.out.println(" "+A[x]); } } }
Java
["5\n10 4\n13 9\n100 13\n123 456\n92 46"]
1 second
["2\n5\n4\n333\n0"]
null
Java 8
standard input
[ "math" ]
d9fd10700cb122b148202a664e7f7689
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains two integers $$$a$$$ and $$$b$$$ ($$$1 \le a, b \le 10^9$$$).
800
For each test case print the answer — the minimum number of moves you need to do in order to make $$$a$$$ divisible by $$$b$$$.
standard output
PASSED
e9cedbdb5d0de777ad968536793bd3ae
train_000.jsonl
1585233300
You are given two positive integers $$$a$$$ and $$$b$$$. In one move you can increase $$$a$$$ by $$$1$$$ (replace $$$a$$$ with $$$a+1$$$). Your task is to find the minimum number of moves you need to do in order to make $$$a$$$ divisible by $$$b$$$. It is possible, that you have to make $$$0$$$ moves, as $$$a$$$ is already divisible by $$$b$$$. You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.io.*; import java.util.*; import java.math.*; public class Main { static boolean GET = true; static void solve(int t, int w) throws IOException { long a = nl(); long b = nl(); if(a % b == 0) { println("0"); return; } long q = 0; try { q = a / b; }catch(Exception e) {} ++q; b = b * q; println(b - a); } //default java template to get started quickly... public static void main(String[] string) throws IOException { int t = 1; if(GET) t = ni(); for(int i = 1; i <= t; ++i) solve(t, i); out.flush(); } static int ni() { return sc.nextInt(); } static long nl() { return sc.nextLong(); } static String str() { return sc.next(); } static void print(Object... o) { int len = o.length; if(String.valueOf(o[len - 1]).equals(" ")) { for(int i = 0; i < len; ++i) out.print(String.valueOf(o[i]) + " "); return; } for(int i = 0; i < len; ++i) out.print(String.valueOf(o[i])); } static void println(Object... o) { int len = o.length; if(len == 0) { out.println(); return; } for(int i = 0; i < len; ++i) out.println(String.valueOf(o[i])); } static Scanner sc = new Scanner(System.in); static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); static PrintWriter out = new PrintWriter(System.out); }
Java
["5\n10 4\n13 9\n100 13\n123 456\n92 46"]
1 second
["2\n5\n4\n333\n0"]
null
Java 8
standard input
[ "math" ]
d9fd10700cb122b148202a664e7f7689
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains two integers $$$a$$$ and $$$b$$$ ($$$1 \le a, b \le 10^9$$$).
800
For each test case print the answer — the minimum number of moves you need to do in order to make $$$a$$$ divisible by $$$b$$$.
standard output
PASSED
8a513fad460e51a1fa88e299115387d0
train_000.jsonl
1585233300
You are given two positive integers $$$a$$$ and $$$b$$$. In one move you can increase $$$a$$$ by $$$1$$$ (replace $$$a$$$ with $$$a+1$$$). Your task is to find the minimum number of moves you need to do in order to make $$$a$$$ divisible by $$$b$$$. It is possible, that you have to make $$$0$$$ moves, as $$$a$$$ is already divisible by $$$b$$$. You have to answer $$$t$$$ independent test cases.
256 megabytes
//package com.company; import java.util.Scanner; public class Main { private static Scanner input = new Scanner(System.in); public static void main(String[] args) { int n = input.nextInt(); for(int i = 0; i < n; i++){ int a = input.nextInt(); int b = input.nextInt(); System.out.println(a%b==0 ? 0 : b-(a%b)); } } }
Java
["5\n10 4\n13 9\n100 13\n123 456\n92 46"]
1 second
["2\n5\n4\n333\n0"]
null
Java 8
standard input
[ "math" ]
d9fd10700cb122b148202a664e7f7689
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains two integers $$$a$$$ and $$$b$$$ ($$$1 \le a, b \le 10^9$$$).
800
For each test case print the answer — the minimum number of moves you need to do in order to make $$$a$$$ divisible by $$$b$$$.
standard output
PASSED
3502b27e49206fc9c067345c55b4ce77
train_000.jsonl
1585233300
You are given two positive integers $$$a$$$ and $$$b$$$. In one move you can increase $$$a$$$ by $$$1$$$ (replace $$$a$$$ with $$$a+1$$$). Your task is to find the minimum number of moves you need to do in order to make $$$a$$$ divisible by $$$b$$$. It is possible, that you have to make $$$0$$$ moves, as $$$a$$$ is already divisible by $$$b$$$. You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; public class Main { public static void main(String[] args) { FastReader in = new FastReader(); PrintWriter out = new PrintWriter(System.out); int t=in.nextInt(); while (t-->0) { int a = in.nextInt(); int b = in.nextInt(); int cont = 0; if (a%b!=0) { if (a < b) { cont = b - a; } else { cont = b - a % b; } } out.println(cont); } out.close(); } /* public static long factorial(int m) { if (m == 0) return 1; return (m * factorial(m - 1)); } public static long GCD(long a, long b) { if (b == 0) return a; return GCD(b, a % b); } */ } class FastReader { private BufferedReader br; private StringTokenizer st; public FastReader() { InputStreamReader inr = new InputStreamReader(System.in); br = new BufferedReader(inr); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } double nextDouble() { return Double.parseDouble(next()); } long nextLong() { return Long.parseLong(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } }
Java
["5\n10 4\n13 9\n100 13\n123 456\n92 46"]
1 second
["2\n5\n4\n333\n0"]
null
Java 8
standard input
[ "math" ]
d9fd10700cb122b148202a664e7f7689
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains two integers $$$a$$$ and $$$b$$$ ($$$1 \le a, b \le 10^9$$$).
800
For each test case print the answer — the minimum number of moves you need to do in order to make $$$a$$$ divisible by $$$b$$$.
standard output
PASSED
bd62e5f96213464029b19140affd90a7
train_000.jsonl
1585233300
You are given two positive integers $$$a$$$ and $$$b$$$. In one move you can increase $$$a$$$ by $$$1$$$ (replace $$$a$$$ with $$$a+1$$$). Your task is to find the minimum number of moves you need to do in order to make $$$a$$$ divisible by $$$b$$$. It is possible, that you have to make $$$0$$$ moves, as $$$a$$$ is already divisible by $$$b$$$. You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.util.Arrays; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int T = sc.nextInt(); while(T-->0) { int a = sc.nextInt(); int b = sc.nextInt(); if(a%b!=0) System.out.println(b-a%b); else System.out.println(0); } } }
Java
["5\n10 4\n13 9\n100 13\n123 456\n92 46"]
1 second
["2\n5\n4\n333\n0"]
null
Java 8
standard input
[ "math" ]
d9fd10700cb122b148202a664e7f7689
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains two integers $$$a$$$ and $$$b$$$ ($$$1 \le a, b \le 10^9$$$).
800
For each test case print the answer — the minimum number of moves you need to do in order to make $$$a$$$ divisible by $$$b$$$.
standard output
PASSED
54213f8b188f4a4a32a3ec89a7ad10a8
train_000.jsonl
1585233300
You are given two positive integers $$$a$$$ and $$$b$$$. In one move you can increase $$$a$$$ by $$$1$$$ (replace $$$a$$$ with $$$a+1$$$). Your task is to find the minimum number of moves you need to do in order to make $$$a$$$ divisible by $$$b$$$. It is possible, that you have to make $$$0$$$ moves, as $$$a$$$ is already divisible by $$$b$$$. You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int T = sc.nextInt(); while(T-->0) { int a = sc.nextInt(); int b = sc.nextInt(); if(a%b == 0) System.out.println(0); else System.out.println(b-a%b); } } }
Java
["5\n10 4\n13 9\n100 13\n123 456\n92 46"]
1 second
["2\n5\n4\n333\n0"]
null
Java 8
standard input
[ "math" ]
d9fd10700cb122b148202a664e7f7689
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains two integers $$$a$$$ and $$$b$$$ ($$$1 \le a, b \le 10^9$$$).
800
For each test case print the answer — the minimum number of moves you need to do in order to make $$$a$$$ divisible by $$$b$$$.
standard output
PASSED
86e9f325c765578816b222080d502d74
train_000.jsonl
1585233300
You are given two positive integers $$$a$$$ and $$$b$$$. In one move you can increase $$$a$$$ by $$$1$$$ (replace $$$a$$$ with $$$a+1$$$). Your task is to find the minimum number of moves you need to do in order to make $$$a$$$ divisible by $$$b$$$. It is possible, that you have to make $$$0$$$ moves, as $$$a$$$ is already divisible by $$$b$$$. You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.util.Scanner; public class Main { static boolean[][] arr; public static void main(String[] args) { Scanner sc = new Scanner(System.in); int T = sc.nextInt(); while(T-->0) { int a = sc.nextInt(); int b = sc.nextInt(); if(a<b) { System.out.println(b-a); } else if(a%b==0) { System.out.println(0); } else { System.out.println(b-a%b); } } } }
Java
["5\n10 4\n13 9\n100 13\n123 456\n92 46"]
1 second
["2\n5\n4\n333\n0"]
null
Java 8
standard input
[ "math" ]
d9fd10700cb122b148202a664e7f7689
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains two integers $$$a$$$ and $$$b$$$ ($$$1 \le a, b \le 10^9$$$).
800
For each test case print the answer — the minimum number of moves you need to do in order to make $$$a$$$ divisible by $$$b$$$.
standard output
PASSED
28b1c61317820280b0062948e0247d9a
train_000.jsonl
1585233300
You are given two positive integers $$$a$$$ and $$$b$$$. In one move you can increase $$$a$$$ by $$$1$$$ (replace $$$a$$$ with $$$a+1$$$). Your task is to find the minimum number of moves you need to do in order to make $$$a$$$ divisible by $$$b$$$. It is possible, that you have to make $$$0$$$ moves, as $$$a$$$ is already divisible by $$$b$$$. You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.util.*; public class Main { public static void main(String at[]) { Scanner in=new Scanner(System.in); int t=in.nextInt(); while(t-->0) { int a=in.nextInt(),b=in.nextInt(); if(a%b==0) System.out.println(0); else { int x=(a/b +1)*b; System.out.println(x-a); } } } }
Java
["5\n10 4\n13 9\n100 13\n123 456\n92 46"]
1 second
["2\n5\n4\n333\n0"]
null
Java 8
standard input
[ "math" ]
d9fd10700cb122b148202a664e7f7689
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains two integers $$$a$$$ and $$$b$$$ ($$$1 \le a, b \le 10^9$$$).
800
For each test case print the answer — the minimum number of moves you need to do in order to make $$$a$$$ divisible by $$$b$$$.
standard output
PASSED
2ddc5d9bccf0d02c34bafc1a64d9c805
train_000.jsonl
1585233300
You are given two positive integers $$$a$$$ and $$$b$$$. In one move you can increase $$$a$$$ by $$$1$$$ (replace $$$a$$$ with $$$a+1$$$). Your task is to find the minimum number of moves you need to do in order to make $$$a$$$ divisible by $$$b$$$. It is possible, that you have to make $$$0$$$ moves, as $$$a$$$ is already divisible by $$$b$$$. You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.util.*; public class class1 { public static void main (String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); for(int i =0;i<n;i++) { int n2 = sc.nextInt(); int n3 = sc.nextInt(); System.out.println((n3 - n2%n3)%n3); } sc.close(); } /*if(n2<n3) { System.out.println(n3-n2); } else { while(n2%n3!=0) { k++; n2++; } System.out.println(k); } }*/ } /* //Way Too Long Words Scanner sc = new Scanner(System.in); double length = sc.nextInt(); String in = null; for(int i = 0; i <= length; i++) { in = sc.nextLine(); if(in.length() > 10) { System.out.print(in.charAt(0)); System.out.print(in.length() -2); System.out.println(in.charAt(in.length() -1)); }else System.out.println(in); } }*/ /*//Telephone Number Scanner sc1 = new Scanner(System.in); int n = sc1.nextInt(); int i =0; sc1.nextLine(); while(i!=n) { i++; int tel = sc1.nextInt(); sc1.nextLine(); String s2 = sc1.nextLine(); char [] tab = s2.toCharArray(); String x="NO"; for(int j=0;j<tab.length;j++) { if((tab[j]=='8' && (j+11) <=tel)) { x="YES"; } } System.out.println(x); } sc1.close(); }}*/ /*//Anton and Danik Scanner sc = new Scanner(System.in); int x = sc.nextInt(); sc.nextLine(); String s = sc.nextLine(); int ka=0; int kd=0; char [] temp = s.toCharArray(); for(int i=0;i<temp.length;i++) { if(temp[i]=='A') { ka++; }else { kd++; } } if(ka>kd) { System.out.println("Anton"); } else if(ka ==kd) { System.out.println("Friendship"); } else { System.out.println("Danik"); } } }*/ /* //Elephant * Scanner sc = new Scanner(System.in); int x = sc.nextInt(); int k=0; while(x>=5) { x=x-5; k++; } while(x>=4) { x=x-4; k++; } while(x>=3) { x=x-3; k++; } while(x>=2) { x=x-2; k++; } while(x>0) { x=x-1; k++; } System.out.println(k); sc.close(); }}*/ /* //Love "A" * Scanner sc = new Scanner(System.in); String mo = sc.nextLine(); char [] mot = mo.toCharArray(); int c=0; for(int i=0;i<mot.length;i++) { if(mot[i]=='a') { c++; } } int tot = mot.length; while(c<=Math.floor(tot/2)) { tot--; } System.out.println(tot); sc.close(); }}*/ /* //In Search of an Easy Problem * Scanner sc = new Scanner(System.in); int n = sc.nextInt(); sc.nextLine(); String mo = sc.nextLine(); if(mo.contains("1")) { System.out.println("HARD"); } else { System.out.println("EASY"); } sc.close(); }}*/ /* //Beautiful Matrix * Scanner sc = new Scanner(System.in); int i = 1; int j = 1; for (i = 1; i <= 5; i++) { if (sc.nextInt() == 1) { break; } // Increment; if (i == 5) { j++; i = 0; } } System.out.println(Math.abs(i-3)+Math.abs(j-3)); } } */ /* //Suffix Three Scanner sc1 = new Scanner(System.in) ; int k = sc1.nextInt(); int i=0; while (i<=k) { i++; String str = sc1.nextLine(); if(str.length()>=2 && str.length() <4) { if(str.charAt(str.length()-2)=='p' && str.charAt(str.length()-1)=='o') { System.out.println("FILIPINO"); } } if(str.length()==4) { if((str.charAt((str.length()-4))=='d' && str.charAt(str.length()-3)=='e' && str.charAt(str.length()-2)=='s' && str.charAt(str.length()-1)=='u') || (str.charAt((str.length()-4))=='m' && str.charAt(str.length()-3)=='a' && str.charAt(str.length()-2)=='s' && str.charAt(str.length()-1)=='u')){ System.out.println("JAPANESE"); } if(str.charAt(str.length()-2)=='p' && str.charAt(str.length()-1)=='o') { System.out.println("FILIPINO"); } } if(str.length()>=5) { if(str.charAt(str.length()-2)=='p' && str.charAt(str.length()-1)=='o') { System.out.println("FILIPINO"); } if((str.charAt((str.length()-4))=='d' && str.charAt(str.length()-3)=='e' && str.charAt(str.length()-2)=='s' && str.charAt(str.length()-1)=='u') || (str.charAt((str.length()-4))=='m' && str.charAt(str.length()-3)=='a' && str.charAt(str.length()-2)=='s' && str.charAt(str.length()-1)=='u')){ System.out.println("JAPANESE"); } if((str.charAt((str.length()-5))=='m' && str.charAt(str.length()-4)=='n' && str.charAt(str.length()-3)=='i' && str.charAt(str.length()-2)=='d' && str.charAt(str.length()-1)=='a')){ System.out.println("KOREAN"); } } } sc1.close(); }} */
Java
["5\n10 4\n13 9\n100 13\n123 456\n92 46"]
1 second
["2\n5\n4\n333\n0"]
null
Java 8
standard input
[ "math" ]
d9fd10700cb122b148202a664e7f7689
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains two integers $$$a$$$ and $$$b$$$ ($$$1 \le a, b \le 10^9$$$).
800
For each test case print the answer — the minimum number of moves you need to do in order to make $$$a$$$ divisible by $$$b$$$.
standard output
PASSED
8397a7b8baa4fdde8f5adf84560d647f
train_000.jsonl
1589707200
Polycarp plays a computer game. In this game, the players summon armies of magical minions, which then fight each other.Polycarp can summon $$$n$$$ different minions. The initial power level of the $$$i$$$-th minion is $$$a_i$$$, and when it is summoned, all previously summoned minions' power levels are increased by $$$b_i$$$. The minions can be summoned in any order.Unfortunately, Polycarp cannot have more than $$$k$$$ minions under his control. To get rid of unwanted minions after summoning them, he may destroy them. Each minion can be summoned (and destroyed) only once.Polycarp's goal is to summon the strongest possible army. Formally, he wants to maximize the sum of power levels of all minions under his control (those which are summoned and not destroyed).Help Polycarp to make up a plan of actions to summon the strongest possible army!
512 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.StringTokenizer; import java.io.BufferedReader; import java.util.Comparator; import java.util.ArrayDeque; 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); SummoningMinions solver = new SummoningMinions(); solver.solve(1, in, out); out.close(); } static class SummoningMinions { public void solve(int testNumber, InputReader in, PrintWriter out) { int T = in.nextInt(); while (T-- > 0) { int N = in.nextInt(); int K = in.nextInt(); int[][] arr = new int[N][3]; for (int i = 0; i < N; i++) { arr[i][0] = in.nextInt(); arr[i][1] = in.nextInt(); arr[i][2] = i + 1; } Arrays.sort(arr, new Comparator<int[]>() { public int compare(int[] ints, int[] t1) { return Integer.compare(ints[1], t1[1]); } }); long[][] dp = new long[N][K + 1]; boolean[][] add = new boolean[N][K + 1]; Arrays.fill(dp[0], Long.MIN_VALUE); dp[0][0] = (K - 1) * arr[0][1]; dp[0][1] = (arr[0][0]); add[0][1] = true; for (int i = 1; i < N; i++) { for (int j = 0; j <= K; j++) { dp[i][j] = dp[i - 1][j] + (K - 1) * arr[i][1]; if (j > 0) { if (dp[i - 1][j - 1] + arr[i][0] + arr[i][1] * (j - 1) > dp[i][j]) { add[i][j] = true; dp[i][j] = dp[i - 1][j - 1] + arr[i][0] + arr[i][1] * (j - 1); } } } } int u = K; ArrayDeque<Integer> order = new ArrayDeque<>(); ArrayList<Integer> not_added = new ArrayList<>(); for (int i = N - 1; i >= 0; i--) { if (add[i][u]) { order.addFirst(arr[i][2]); u--; } else { not_added.add(arr[i][2]); } } StringBuilder str = new StringBuilder(); str.append((2 * N - K) + "\n"); // assert false; while (order.size() > 1) { str.append(order.removeFirst() + " "); } for (int i : not_added) { str.append(i + " "); str.append((-i) + " "); } str.append(order.removeFirst() + " "); out.println(str.toString()); } } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["3\n5 2\n5 3\n7 0\n5 0\n4 0\n10 0\n2 1\n10 100\n50 10\n5 5\n1 5\n2 4\n3 3\n4 2\n5 1"]
6 seconds
["4\n2 1 -1 5\n1\n2\n5\n5 4 3 2 1"]
NoteConsider the example test.In the first test case, Polycarp can summon the minion $$$2$$$ with power level $$$7$$$, then summon the minion $$$1$$$, which will increase the power level of the previous minion by $$$3$$$, then destroy the minion $$$1$$$, and finally, summon the minion $$$5$$$. After this, Polycarp will have two minions with power levels of $$$10$$$.In the second test case, Polycarp can control only one minion, so he should choose the strongest of them and summon it.In the third test case, Polycarp is able to summon and control all five minions.
Java 8
standard input
[ "dp", "greedy", "constructive algorithms", "flows", "graph matchings", "sortings" ]
e764c6437ce11b6b0cee015bc8b8e0b5
The first line contains one integer $$$T$$$ ($$$1 \le T \le 75$$$) — the number of test cases. Each test case begins with a line containing two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 75$$$) — the number of minions availible for summoning, and the maximum number of minions that can be controlled by Polycarp, respectively. Then $$$n$$$ lines follow, the $$$i$$$-th line contains $$$2$$$ integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \le a_i \le 10^5$$$, $$$0 \le b_i \le 10^5$$$) — the parameters of the $$$i$$$-th minion.
2,500
For each test case print the optimal sequence of actions as follows: Firstly, print $$$m$$$ — the number of actions which Polycarp has to perform ($$$0 \le m \le 2n$$$). Then print $$$m$$$ integers $$$o_1$$$, $$$o_2$$$, ..., $$$o_m$$$, where $$$o_i$$$ denotes the $$$i$$$-th action as follows: if the $$$i$$$-th action is to summon the minion $$$x$$$, then $$$o_i = x$$$, and if the $$$i$$$-th action is to destroy the minion $$$x$$$, then $$$o_i = -x$$$. Each minion can be summoned at most once and cannot be destroyed before being summoned (and, obviously, cannot be destroyed more than once). The number of minions in Polycarp's army should be not greater than $$$k$$$ after every action. If there are multiple optimal sequences, print any of them.
standard output
PASSED
785aebb0375b4a91604705e4755ad466
train_000.jsonl
1589707200
Polycarp plays a computer game. In this game, the players summon armies of magical minions, which then fight each other.Polycarp can summon $$$n$$$ different minions. The initial power level of the $$$i$$$-th minion is $$$a_i$$$, and when it is summoned, all previously summoned minions' power levels are increased by $$$b_i$$$. The minions can be summoned in any order.Unfortunately, Polycarp cannot have more than $$$k$$$ minions under his control. To get rid of unwanted minions after summoning them, he may destroy them. Each minion can be summoned (and destroyed) only once.Polycarp's goal is to summon the strongest possible army. Formally, he wants to maximize the sum of power levels of all minions under his control (those which are summoned and not destroyed).Help Polycarp to make up a plan of actions to summon the strongest possible army!
512 megabytes
/****************************************************************************** Online Java Compiler. Code, Compile, Run and Debug java program online. Write your code in this editor and press "Run" button to execute it. *******************************************************************************/ 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)); StringTokenizer st = new StringTokenizer(br.readLine()); PrintWriter out = new PrintWriter(System.out); int trials = Integer.parseInt(st.nextToken()); for(int trial = 0; trial < trials; trial++){ st = new StringTokenizer(br.readLine()); int n = Integer.parseInt(st.nextToken()); int k = Integer.parseInt(st.nextToken()); int[][] minion = new int[n][3]; for(int i = 0; i < n; i++){ st = new StringTokenizer(br.readLine()); int a = Integer.parseInt(st.nextToken()); int b = Integer.parseInt(st.nextToken()); minion[i][0] = a; minion[i][1] = b; minion[i][2] = i+1; } sort(minion, 0, n-1); int[][] dp = new int[n+1][k+1]; for(int i = 1; i <= n; i++){ dp[i][0] = dp[i-1][0] + (k-1)*minion[i-1][1]; for(int j = 1; j <= k; j++){ if(j < i) dp[i][j] = Math.max(dp[i-1][j] + (k-1)*minion[i-1][1], dp[i-1][j-1] + (j-1)*minion[i-1][1] + minion[i-1][0]); else if(j == i) dp[i][j] = dp[i-1][j-1] + (j-1)*minion[i-1][1] + minion[i-1][0]; } } int i = n; int j = k; Stack<Integer> stay = new Stack<Integer>(); HashSet<Integer> remove = new HashSet<Integer>(); while(j > 0){ if(dp[i][j] == dp[i-1][j-1] + (j-1)*minion[i-1][1] + minion[i-1][0]){ stay.push(minion[i-1][2]); j--; } else remove.add(minion[i-1][2]); i--; } while(i > 0){ remove.add(minion[i-1][2]); i--; } StringJoiner sj = new StringJoiner(" "); for(i = 0; i < k-1; i++) sj.add(Integer.toString(stay.pop())); for(int l:remove){ sj.add(Integer.toString(l)); sj.add(Integer.toString(-l)); } sj.add(Integer.toString(stay.pop())); out.println(2*n-k); out.println(sj); } out.close(); } static void sort(int[][] arr, int l, int r){ if (l < r) { // Find the middle point int m = (l+r)/2; // Sort first and second halves sort(arr, l, m); sort(arr , m+1, r); // Merge the sorted halves merge(arr, l, m, r); } } static void merge(int[][] arr, int l, int m, int r) { // Find sizes of two subarrays to be merged int n1 = m - l + 1; int n2 = r - m; /* Create temp arrays */ int L[][] = new int [n1][3]; int R[][] = new int [n2][3]; /*Copy data to temp arrays*/ for (int i=0; i<n1; ++i){ L[i][0] = arr[l + i][0]; L[i][1] = arr[l+i][1]; L[i][2] = arr[l+i][2]; } for (int j=0; j<n2; ++j){ R[j][0] = arr[m + 1+ j][0]; R[j][1] = arr[m+1+j][1]; R[j][2] = arr[m+1+j][2]; } /* Merge the temp arrays */ // Initial indexes of first and second subarrays int i = 0, j = 0; // Initial index of merged subarry array int k = l; while (i < n1 && j < n2) { if (L[i][1] < R[j][1] || (L[i][1] == R[j][1] && L[i][0] < R[j][0])) { arr[k][0] = L[i][0]; arr[k][1] = L[i][1]; arr[k][2] = L[i][2]; i++; } else { arr[k][0] = R[j][0]; arr[k][1] = R[j][1]; arr[k][2] = R[j][2]; j++; } k++; } /* Copy remaining elements of L[] if any */ while (i < n1) { arr[k][0] = L[i][0]; arr[k][1] = L[i][1]; arr[k][2] = L[i][2]; i++; k++; } /* Copy remaining elements of R[] if any */ while (j < n2) { arr[k][0] = R[j][0]; arr[k][1] = R[j][1]; arr[k][2] = R[j][2]; j++; k++; } } }
Java
["3\n5 2\n5 3\n7 0\n5 0\n4 0\n10 0\n2 1\n10 100\n50 10\n5 5\n1 5\n2 4\n3 3\n4 2\n5 1"]
6 seconds
["4\n2 1 -1 5\n1\n2\n5\n5 4 3 2 1"]
NoteConsider the example test.In the first test case, Polycarp can summon the minion $$$2$$$ with power level $$$7$$$, then summon the minion $$$1$$$, which will increase the power level of the previous minion by $$$3$$$, then destroy the minion $$$1$$$, and finally, summon the minion $$$5$$$. After this, Polycarp will have two minions with power levels of $$$10$$$.In the second test case, Polycarp can control only one minion, so he should choose the strongest of them and summon it.In the third test case, Polycarp is able to summon and control all five minions.
Java 8
standard input
[ "dp", "greedy", "constructive algorithms", "flows", "graph matchings", "sortings" ]
e764c6437ce11b6b0cee015bc8b8e0b5
The first line contains one integer $$$T$$$ ($$$1 \le T \le 75$$$) — the number of test cases. Each test case begins with a line containing two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 75$$$) — the number of minions availible for summoning, and the maximum number of minions that can be controlled by Polycarp, respectively. Then $$$n$$$ lines follow, the $$$i$$$-th line contains $$$2$$$ integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \le a_i \le 10^5$$$, $$$0 \le b_i \le 10^5$$$) — the parameters of the $$$i$$$-th minion.
2,500
For each test case print the optimal sequence of actions as follows: Firstly, print $$$m$$$ — the number of actions which Polycarp has to perform ($$$0 \le m \le 2n$$$). Then print $$$m$$$ integers $$$o_1$$$, $$$o_2$$$, ..., $$$o_m$$$, where $$$o_i$$$ denotes the $$$i$$$-th action as follows: if the $$$i$$$-th action is to summon the minion $$$x$$$, then $$$o_i = x$$$, and if the $$$i$$$-th action is to destroy the minion $$$x$$$, then $$$o_i = -x$$$. Each minion can be summoned at most once and cannot be destroyed before being summoned (and, obviously, cannot be destroyed more than once). The number of minions in Polycarp's army should be not greater than $$$k$$$ after every action. If there are multiple optimal sequences, print any of them.
standard output
PASSED
bfd059da541815208bae24a5252c2f61
train_000.jsonl
1589707200
Polycarp plays a computer game. In this game, the players summon armies of magical minions, which then fight each other.Polycarp can summon $$$n$$$ different minions. The initial power level of the $$$i$$$-th minion is $$$a_i$$$, and when it is summoned, all previously summoned minions' power levels are increased by $$$b_i$$$. The minions can be summoned in any order.Unfortunately, Polycarp cannot have more than $$$k$$$ minions under his control. To get rid of unwanted minions after summoning them, he may destroy them. Each minion can be summoned (and destroyed) only once.Polycarp's goal is to summon the strongest possible army. Formally, he wants to maximize the sum of power levels of all minions under his control (those which are summoned and not destroyed).Help Polycarp to make up a plan of actions to summon the strongest possible army!
512 megabytes
import java.io.*; import java.util.*; import java.math.*; public class F { static final boolean RUN_TIMING = false; static PushbackReader in = new PushbackReader(new BufferedReader(new InputStreamReader(System.in)), 1024); static PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); public void go() throws IOException { // in = new PushbackReader(new BufferedReader(new FileReader(new File("test.txt"))), 1024); // out = new PrintWriter(new FileWriter(new File("output.txt"))); int zzz = ipar(); for (int zz = 0; zz < zzz; zz++) { int n = ipar(); int k = ipar(); Minion[] arr = new Minion[n]; for (int i = 0; i < n; i++) { int a = ipar(); int b = ipar(); arr[i] = new Minion(a, b, i); } Arrays.sort(arr, (a, b) -> a.b - b.b); int[][] dp = new int[n+1][k+1]; int[][] index = new int[n+1][k+1]; for (int i = 0; i < k; i++) { dp[n][i] = Integer.MIN_VALUE; } for (int i = n-1; i >= 0; i--) { for (int e = 0; e <= k; e++) { dp[i][e] = dp[i+1][e] + arr[i].getDestroy(k-1); index[i][e] = -arr[i].i-1; } for (int e = 0; e < k; e++) { if (dp[i+1][e+1] + arr[i].getAdd(e) > dp[i][e]) { dp[i][e] = dp[i+1][e+1] + arr[i].getAdd(e); index[i][e] = arr[i].i+1; } } } ArrayList<Integer> adds = new ArrayList<>(); ArrayList<Integer> destroys = new ArrayList<>(); for (int i = 0; i < n; i++) { if (index[i][adds.size()] > 0) { adds.add(index[i][adds.size()]); } else { destroys.add(-index[i][adds.size()]); } } // for (int[] a : dp) { // out.println(Arrays.toString(a)); // } out.println(adds.size() + destroys.size()*2); for (int i = 0; i < k-1; i++) { out.print(adds.get(i)); out.print(" "); } for (int i = 0; i < n-k; i++) { out.print(destroys.get(i)); out.print(" "); out.print(-destroys.get(i)); out.print(" "); } out.println(adds.get(k-1)); } out.flush(); in.close(); } private class Minion { int a, b, i; public Minion(int a, int b, int i) { this.a = a; this.b = b; this.i = i; } public int getAdd(int t) { return a + b*t; } public int getDestroy(int t) { return b*t; } public String toString() { return String.format("%d=(%d,%d)", i, a, b); } } public int ipar() throws IOException { return Integer.parseInt(spar()); } public int[] iapar(int n) throws IOException { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = ipar(); } return arr; } public long lpar() throws IOException { return Long.parseLong(spar()); } public long[] lapar(int n) throws IOException { long[] arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = lpar(); } return arr; } public double dpar() throws IOException { return Double.parseDouble(spar()); } public String spar() throws IOException { StringBuilder sb = new StringBuilder(1024); int c; do { c = in.read(); } while (Character.isWhitespace(c) && c != -1); if (c == -1) { throw new NoSuchElementException("Reached EOF"); } do { sb.append((char)c); c = in.read(); } while (!Character.isWhitespace(c) && c != -1); while (c != '\n' && Character.isWhitespace(c) && c != -1) { c = in.read(); } if (c != -1 && c != '\n') { in.unread(c); } return sb.toString(); } public String linepar() throws IOException { StringBuilder sb = new StringBuilder(1024); int c; while ((c = in.read()) != '\n' && c != -1) { if (c == '\r') { continue; } sb.append((char)c); } return sb.toString(); } public boolean haspar() throws IOException { String line = linepar(); if (line.isEmpty()) { return false; } in.unread('\n'); in.unread(line.toCharArray()); return true; } public static void main(String[] args) throws IOException { long time = 0; time -= System.nanoTime(); new F().go(); time += System.nanoTime(); if (RUN_TIMING) { System.out.printf("%.3f ms%n", time/1000000.0); } out.flush(); in.close(); } }
Java
["3\n5 2\n5 3\n7 0\n5 0\n4 0\n10 0\n2 1\n10 100\n50 10\n5 5\n1 5\n2 4\n3 3\n4 2\n5 1"]
6 seconds
["4\n2 1 -1 5\n1\n2\n5\n5 4 3 2 1"]
NoteConsider the example test.In the first test case, Polycarp can summon the minion $$$2$$$ with power level $$$7$$$, then summon the minion $$$1$$$, which will increase the power level of the previous minion by $$$3$$$, then destroy the minion $$$1$$$, and finally, summon the minion $$$5$$$. After this, Polycarp will have two minions with power levels of $$$10$$$.In the second test case, Polycarp can control only one minion, so he should choose the strongest of them and summon it.In the third test case, Polycarp is able to summon and control all five minions.
Java 8
standard input
[ "dp", "greedy", "constructive algorithms", "flows", "graph matchings", "sortings" ]
e764c6437ce11b6b0cee015bc8b8e0b5
The first line contains one integer $$$T$$$ ($$$1 \le T \le 75$$$) — the number of test cases. Each test case begins with a line containing two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 75$$$) — the number of minions availible for summoning, and the maximum number of minions that can be controlled by Polycarp, respectively. Then $$$n$$$ lines follow, the $$$i$$$-th line contains $$$2$$$ integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \le a_i \le 10^5$$$, $$$0 \le b_i \le 10^5$$$) — the parameters of the $$$i$$$-th minion.
2,500
For each test case print the optimal sequence of actions as follows: Firstly, print $$$m$$$ — the number of actions which Polycarp has to perform ($$$0 \le m \le 2n$$$). Then print $$$m$$$ integers $$$o_1$$$, $$$o_2$$$, ..., $$$o_m$$$, where $$$o_i$$$ denotes the $$$i$$$-th action as follows: if the $$$i$$$-th action is to summon the minion $$$x$$$, then $$$o_i = x$$$, and if the $$$i$$$-th action is to destroy the minion $$$x$$$, then $$$o_i = -x$$$. Each minion can be summoned at most once and cannot be destroyed before being summoned (and, obviously, cannot be destroyed more than once). The number of minions in Polycarp's army should be not greater than $$$k$$$ after every action. If there are multiple optimal sequences, print any of them.
standard output
PASSED
e42effcd1090e3581afb3575a27e5188
train_000.jsonl
1589707200
Polycarp plays a computer game. In this game, the players summon armies of magical minions, which then fight each other.Polycarp can summon $$$n$$$ different minions. The initial power level of the $$$i$$$-th minion is $$$a_i$$$, and when it is summoned, all previously summoned minions' power levels are increased by $$$b_i$$$. The minions can be summoned in any order.Unfortunately, Polycarp cannot have more than $$$k$$$ minions under his control. To get rid of unwanted minions after summoning them, he may destroy them. Each minion can be summoned (and destroyed) only once.Polycarp's goal is to summon the strongest possible army. Formally, he wants to maximize the sum of power levels of all minions under his control (those which are summoned and not destroyed).Help Polycarp to make up a plan of actions to summon the strongest possible army!
512 megabytes
import java.util.Arrays; import java.util.Scanner; /* 1 5 2 5 3 7 0 5 0 4 0 10 0 */ public class SummoningMinions2 { public static void main(String[] args) { Scanner fs=new Scanner(System.in); int T=fs.nextInt(); for (int tt=0; tt<T; tt++) { int n=fs.nextInt(), k=fs.nextInt(); long ans=0; int[][] cost=new int[k][n]; for (int i=0; i<n; i++) { int a=fs.nextInt(), b=fs.nextInt(); ans+=(k-1)*(long)b; for (int spot=0; spot<k; spot++) cost[spot][i]=-(-(k-1)*b+spot*b+a); } // for (int spot=0; spot<k; spot++) { // for (int i=0; i<n; i++) { // System.out.print(cost[spot][i]+" "); // } // System.out.println(); // } hungarian(cost); // for (int spot=0; spot<k; spot++) { // System.out.println("Matched spot "+spot+" with "+rowMatchesWith[spot]); // } boolean[] chosen=new boolean[n]; for (int i=0; i<k; i++) chosen[rowMatchesWith[i]]=true; System.out.println(k-1 + 2*(n-k) + 1); for (int i=0; i+1<k; i++) { System.out.print(1+rowMatchesWith[i]+" "); } for (int i=0; i<n; i++) if (!chosen[i]) System.out.print((1+i)+" -"+(1+i)+" "); System.out.println(rowMatchesWith[k-1]+1); } } // finds MINIMUM total matching cost of // each row to some column, using each col at most once // **nRows must be <= nCols** //rowMatchWith[i] = the column that row i matched with static int[] rowMatchesWith; static int hungarian(int[][] a) { int n=a.length, m=a[0].length; if (n>m) throw null; int[] u=new int[n], v=new int[m+1]; //edge (i->j) >= u[i]+v[j] int[] p=new int[m+1]; //p[j] = left match for right node j Arrays.fill(p, -1); for (int i=0; i<n; i++) {//find alternating path for node i int j0=m; p[j0]=i; int[] dist=new int[m+1], from=new int[m+1]; boolean[] seen=new boolean[m+1]; Arrays.fill(dist, Integer.MAX_VALUE); Arrays.fill(from, -1); while (p[j0]!=-1) { seen[j0]=true; int i0=p[j0], delta=Integer.MAX_VALUE, j1=-1; for (int j=0; j<m; j++) {//consider edges i0 -> everything if (seen[j]) continue; int candDist=a[i0][j]-u[i0]-v[j]; if (candDist<dist[j]) {dist[j]=candDist; from[j]=j0;} if (dist[j]<delta) {delta=dist[j]; j1=j;} } //it costs at least delta to get somewhere else, //subtract that from all distances and add cost to u, v, arrays //from all done -> not done edges for (int j=0; j<=m; j++) { if (seen[j]) {u[p[j]]+=delta; v[j]-=delta;} else dist[j]-=delta; } j0=j1; } //flip alternating path while (j0!=m) { int j1=from[j0]; p[j0]=p[j1]; j0=j1; } } //sum of deltas is stored at v[m] coincidentally int ans=-v[m]; rowMatchesWith=new int[n]; for (int j=0; j<m; j++) if (p[j]!=-1) rowMatchesWith[p[j]]=j; return ans; } }
Java
["3\n5 2\n5 3\n7 0\n5 0\n4 0\n10 0\n2 1\n10 100\n50 10\n5 5\n1 5\n2 4\n3 3\n4 2\n5 1"]
6 seconds
["4\n2 1 -1 5\n1\n2\n5\n5 4 3 2 1"]
NoteConsider the example test.In the first test case, Polycarp can summon the minion $$$2$$$ with power level $$$7$$$, then summon the minion $$$1$$$, which will increase the power level of the previous minion by $$$3$$$, then destroy the minion $$$1$$$, and finally, summon the minion $$$5$$$. After this, Polycarp will have two minions with power levels of $$$10$$$.In the second test case, Polycarp can control only one minion, so he should choose the strongest of them and summon it.In the third test case, Polycarp is able to summon and control all five minions.
Java 8
standard input
[ "dp", "greedy", "constructive algorithms", "flows", "graph matchings", "sortings" ]
e764c6437ce11b6b0cee015bc8b8e0b5
The first line contains one integer $$$T$$$ ($$$1 \le T \le 75$$$) — the number of test cases. Each test case begins with a line containing two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 75$$$) — the number of minions availible for summoning, and the maximum number of minions that can be controlled by Polycarp, respectively. Then $$$n$$$ lines follow, the $$$i$$$-th line contains $$$2$$$ integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \le a_i \le 10^5$$$, $$$0 \le b_i \le 10^5$$$) — the parameters of the $$$i$$$-th minion.
2,500
For each test case print the optimal sequence of actions as follows: Firstly, print $$$m$$$ — the number of actions which Polycarp has to perform ($$$0 \le m \le 2n$$$). Then print $$$m$$$ integers $$$o_1$$$, $$$o_2$$$, ..., $$$o_m$$$, where $$$o_i$$$ denotes the $$$i$$$-th action as follows: if the $$$i$$$-th action is to summon the minion $$$x$$$, then $$$o_i = x$$$, and if the $$$i$$$-th action is to destroy the minion $$$x$$$, then $$$o_i = -x$$$. Each minion can be summoned at most once and cannot be destroyed before being summoned (and, obviously, cannot be destroyed more than once). The number of minions in Polycarp's army should be not greater than $$$k$$$ after every action. If there are multiple optimal sequences, print any of them.
standard output
PASSED
92f6b1e72d3a9c64ad15cd572d057aa0
train_000.jsonl
1589707200
Polycarp plays a computer game. In this game, the players summon armies of magical minions, which then fight each other.Polycarp can summon $$$n$$$ different minions. The initial power level of the $$$i$$$-th minion is $$$a_i$$$, and when it is summoned, all previously summoned minions' power levels are increased by $$$b_i$$$. The minions can be summoned in any order.Unfortunately, Polycarp cannot have more than $$$k$$$ minions under his control. To get rid of unwanted minions after summoning them, he may destroy them. Each minion can be summoned (and destroyed) only once.Polycarp's goal is to summon the strongest possible army. Formally, he wants to maximize the sum of power levels of all minions under his control (those which are summoned and not destroyed).Help Polycarp to make up a plan of actions to summon the strongest possible army!
512 megabytes
import java.util.Arrays; import java.util.Scanner; public class SummoningMinions { public static void main(String[] args) { Scanner fs=new Scanner(System.in); int T=fs.nextInt(); for (int tt=0; tt<T; tt++) { int n=fs.nextInt(), k=fs.nextInt(); long ans=0; int[][] cost=new int[k][n]; for (int i=0; i<n; i++) { int a=fs.nextInt(), b=fs.nextInt(); ans+=(k-1)*(long)b; for (int spot=0; spot<k; spot++) cost[spot][i]=-(k-1)*b+spot*b+a; } Hungarian h=new Hungarian(cost); h.run(); boolean[] chosen=new boolean[n]; for (int i=0; i<k; i++) chosen[h.xy[i]]=true; System.out.println(k-1 + 2*(n-k) + 1); for (int i=0; i+1<k; i++) { System.out.print(1+h.xy[i]+" "); } for (int i=0; i<n; i++) if (!chosen[i]) System.out.print((1+i)+" -"+(1+i)+" "); System.out.println(h.xy[k-1]+1); } } // #rows of cost matrix MUST be <= #columns // xy[i] tells you what item i from the left matched with // Given a cost matrix, matches each row with a column that MAXIMIZES // total of selected edges. static class Hungarian { static int inf=100000000; int[][] c; int[] lx, ly, xy, yx, s, sx, p, q; int n, m; boolean[] S, T; public Hungarian(int[][] cost) { c=cost; n=c.length; m=c[0].length; // INIT: lx[n],xy[n],prev[n],q[n],ly[m],yx[m],s[m],sx[m] S=new boolean[n]; T=new boolean[m]; // # // Array initialization lx=new int[n]; ly=new int[m]; xy=new int[n]; yx=new int[m]; s=new int[m]; sx=new int[m]; p=new int[n]; q=new int[n]; // $ } void augment() { int x, y, root=-1, wr=0, rd=0; Arrays.fill(p, -1); Arrays.fill(S, false); Arrays.fill(T, false); for (x=0; x<n; x++) { if (xy[x]==-1) { q[wr++]=root=x; p[x]=-2; S[x]=true; break; } } for (y=0; y<m; y++) { s[y]=lx[root]+ly[y]-c[root][y]; sx[y]=root; } while (y>=m) { while (rd<wr&&y>=m) { x=q[rd++]; for (y=0; y<m; y++) { if (c[x][y]==lx[x]+ly[y]&&!T[y]) { if (yx[y]==-1) break; T[y]=true; q[wr++]=yx[y]; addToTree(yx[y], x); } } } if (y<m) break; updateLabels(); wr=rd=0; for (y=0; y<m; y++) { if (!T[y]&&s[y]==0) { if (yx[y]==-1) { x=sx[y]; break; } else { T[y]=true; if (!S[yx[y]]) { q[wr++]=yx[y]; addToTree(yx[y], sx[y]); } } } } } for (int cx=x, cy=y, ty; cx!=-2; cx=p[cx], cy=ty) { ty=xy[cx]; yx[cy]=cx; xy[cx]=cy; } } void updateLabels() { int x, y, delta=inf; for (y=0; y<m; y++) delta=Math.min(delta, !T[y]?s[y]:inf); for (x=0; x<n; x++) lx[x]-=S[x]?delta:0; for (y=0; y<m; y++) { ly[y]+=T[y]?delta:0; s[y]-=!T[y]?delta:0; } } void addToTree(int x, int prevX) { S[x]=true; p[x]=prevX; for (int y=0; y<m; y++) { if (lx[x]+ly[y]-c[x][y]<s[y]) { s[y]=lx[x]+ly[y]-c[x][y]; sx[y]=x; } } } int run() { Arrays.fill(xy, -1); Arrays.fill(yx, -1); for (int x=0; x<n; x++) for (int y=0; y<m; y++) lx[x]=Math.max(lx[x], c[x][y]); for (int i=0; i<n; i++) augment(); int ret=0; for (int x=0; x<n; x++) ret+=c[x][xy[x]]; return ret; } } }
Java
["3\n5 2\n5 3\n7 0\n5 0\n4 0\n10 0\n2 1\n10 100\n50 10\n5 5\n1 5\n2 4\n3 3\n4 2\n5 1"]
6 seconds
["4\n2 1 -1 5\n1\n2\n5\n5 4 3 2 1"]
NoteConsider the example test.In the first test case, Polycarp can summon the minion $$$2$$$ with power level $$$7$$$, then summon the minion $$$1$$$, which will increase the power level of the previous minion by $$$3$$$, then destroy the minion $$$1$$$, and finally, summon the minion $$$5$$$. After this, Polycarp will have two minions with power levels of $$$10$$$.In the second test case, Polycarp can control only one minion, so he should choose the strongest of them and summon it.In the third test case, Polycarp is able to summon and control all five minions.
Java 8
standard input
[ "dp", "greedy", "constructive algorithms", "flows", "graph matchings", "sortings" ]
e764c6437ce11b6b0cee015bc8b8e0b5
The first line contains one integer $$$T$$$ ($$$1 \le T \le 75$$$) — the number of test cases. Each test case begins with a line containing two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 75$$$) — the number of minions availible for summoning, and the maximum number of minions that can be controlled by Polycarp, respectively. Then $$$n$$$ lines follow, the $$$i$$$-th line contains $$$2$$$ integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \le a_i \le 10^5$$$, $$$0 \le b_i \le 10^5$$$) — the parameters of the $$$i$$$-th minion.
2,500
For each test case print the optimal sequence of actions as follows: Firstly, print $$$m$$$ — the number of actions which Polycarp has to perform ($$$0 \le m \le 2n$$$). Then print $$$m$$$ integers $$$o_1$$$, $$$o_2$$$, ..., $$$o_m$$$, where $$$o_i$$$ denotes the $$$i$$$-th action as follows: if the $$$i$$$-th action is to summon the minion $$$x$$$, then $$$o_i = x$$$, and if the $$$i$$$-th action is to destroy the minion $$$x$$$, then $$$o_i = -x$$$. Each minion can be summoned at most once and cannot be destroyed before being summoned (and, obviously, cannot be destroyed more than once). The number of minions in Polycarp's army should be not greater than $$$k$$$ after every action. If there are multiple optimal sequences, print any of them.
standard output
PASSED
2f10de90e62d506bb896efb859eb13df
train_000.jsonl
1589707200
Polycarp plays a computer game. In this game, the players summon armies of magical minions, which then fight each other.Polycarp can summon $$$n$$$ different minions. The initial power level of the $$$i$$$-th minion is $$$a_i$$$, and when it is summoned, all previously summoned minions' power levels are increased by $$$b_i$$$. The minions can be summoned in any order.Unfortunately, Polycarp cannot have more than $$$k$$$ minions under his control. To get rid of unwanted minions after summoning them, he may destroy them. Each minion can be summoned (and destroyed) only once.Polycarp's goal is to summon the strongest possible army. Formally, he wants to maximize the sum of power levels of all minions under his control (those which are summoned and not destroyed).Help Polycarp to make up a plan of actions to summon the strongest possible army!
512 megabytes
import java.util.Arrays; import java.util.Scanner; public class SummoningMinions2 { public static void main(String[] args) { Scanner fs=new Scanner(System.in); int T=fs.nextInt(); for (int tt=0; tt<T; tt++) { int n=fs.nextInt(), k=fs.nextInt(); int[][] cost=new int[k][n]; for (int i=0; i<n; i++) { int a=fs.nextInt(), b=fs.nextInt(); for (int spot=0; spot<k; spot++) cost[spot][i]=-(-(k-1)*b+spot*b+a); } hungarian(cost); boolean[] chosen=new boolean[n]; for (int i=0; i<k; i++) chosen[rowMatchesWith[i]]=true; System.out.println(k-1 + 2*(n-k) + 1); for (int i=0; i+1<k; i++) { System.out.print(1+rowMatchesWith[i]+" "); } for (int i=0; i<n; i++) if (!chosen[i]) System.out.print((1+i)+" -"+(1+i)+" "); System.out.println(rowMatchesWith[k-1]+1); } } // finds MINIMUM total matching cost of // each row to some column, using each col at most once // **nRows must be <= nCols** //rowMatchWith[i] = the column that row i matched with static int[] rowMatchesWith; static int hungarian(int[][] a) { int n=a.length, m=a[0].length; if (n>m) throw null; int[] u=new int[n], v=new int[m+1]; //edge (i->j) >= u[i]+v[j] int[] p=new int[m+1]; //p[j] = left match for right node j Arrays.fill(p, -1); for (int i=0; i<n; i++) {//find alternating path for node i int j0=m; p[j0]=i; int[] dist=new int[m+1], from=new int[m+1]; boolean[] seen=new boolean[m+1]; Arrays.fill(dist, Integer.MAX_VALUE); Arrays.fill(from, -1); while (p[j0]!=-1) { seen[j0]=true; int i0=p[j0], delta=Integer.MAX_VALUE, j1=-1; for (int j=0; j<m; j++) {//consider edges i0 -> everything if (seen[j]) continue; int candDist=a[i0][j]-u[i0]-v[j]; if (candDist<dist[j]) {dist[j]=candDist; from[j]=j0;} if (dist[j]<delta) {delta=dist[j]; j1=j;} } //it costs at least delta to get somewhere else, //subtract that from all distances and add cost to u, v, arrays //from all done -> not done edges for (int j=0; j<=m; j++) { if (seen[j]) {u[p[j]]+=delta; v[j]-=delta;} else dist[j]-=delta; } j0=j1; } //flip alternating path while (j0!=m) { int j1=from[j0]; p[j0]=p[j1]; j0=j1; } } //sum of deltas is stored at v[m] coincidentally int ans=-v[m]; rowMatchesWith=new int[n]; for (int j=0; j<m; j++) if (p[j]!=-1) rowMatchesWith[p[j]]=j; return ans; } }
Java
["3\n5 2\n5 3\n7 0\n5 0\n4 0\n10 0\n2 1\n10 100\n50 10\n5 5\n1 5\n2 4\n3 3\n4 2\n5 1"]
6 seconds
["4\n2 1 -1 5\n1\n2\n5\n5 4 3 2 1"]
NoteConsider the example test.In the first test case, Polycarp can summon the minion $$$2$$$ with power level $$$7$$$, then summon the minion $$$1$$$, which will increase the power level of the previous minion by $$$3$$$, then destroy the minion $$$1$$$, and finally, summon the minion $$$5$$$. After this, Polycarp will have two minions with power levels of $$$10$$$.In the second test case, Polycarp can control only one minion, so he should choose the strongest of them and summon it.In the third test case, Polycarp is able to summon and control all five minions.
Java 8
standard input
[ "dp", "greedy", "constructive algorithms", "flows", "graph matchings", "sortings" ]
e764c6437ce11b6b0cee015bc8b8e0b5
The first line contains one integer $$$T$$$ ($$$1 \le T \le 75$$$) — the number of test cases. Each test case begins with a line containing two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 75$$$) — the number of minions availible for summoning, and the maximum number of minions that can be controlled by Polycarp, respectively. Then $$$n$$$ lines follow, the $$$i$$$-th line contains $$$2$$$ integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \le a_i \le 10^5$$$, $$$0 \le b_i \le 10^5$$$) — the parameters of the $$$i$$$-th minion.
2,500
For each test case print the optimal sequence of actions as follows: Firstly, print $$$m$$$ — the number of actions which Polycarp has to perform ($$$0 \le m \le 2n$$$). Then print $$$m$$$ integers $$$o_1$$$, $$$o_2$$$, ..., $$$o_m$$$, where $$$o_i$$$ denotes the $$$i$$$-th action as follows: if the $$$i$$$-th action is to summon the minion $$$x$$$, then $$$o_i = x$$$, and if the $$$i$$$-th action is to destroy the minion $$$x$$$, then $$$o_i = -x$$$. Each minion can be summoned at most once and cannot be destroyed before being summoned (and, obviously, cannot be destroyed more than once). The number of minions in Polycarp's army should be not greater than $$$k$$$ after every action. If there are multiple optimal sequences, print any of them.
standard output
PASSED
7eb843eaae455c2f066cca59392f1415
train_000.jsonl
1589707200
Polycarp plays a computer game. In this game, the players summon armies of magical minions, which then fight each other.Polycarp can summon $$$n$$$ different minions. The initial power level of the $$$i$$$-th minion is $$$a_i$$$, and when it is summoned, all previously summoned minions' power levels are increased by $$$b_i$$$. The minions can be summoned in any order.Unfortunately, Polycarp cannot have more than $$$k$$$ minions under his control. To get rid of unwanted minions after summoning them, he may destroy them. Each minion can be summoned (and destroyed) only once.Polycarp's goal is to summon the strongest possible army. Formally, he wants to maximize the sum of power levels of all minions under his control (those which are summoned and not destroyed).Help Polycarp to make up a plan of actions to summon the strongest possible army!
512 megabytes
/* ID: tommatt1 LANG: JAVA TASK: */ import java.util.*; import java.io.*; public class cf1354f{ public static void main(String[] args)throws IOException { PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); BufferedReader bf=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(bf.readLine()); int tt=Integer.parseInt(st.nextToken()); while(tt-->0) { st=new StringTokenizer(bf.readLine()); int n=Integer.parseInt(st.nextToken()); int k=Integer.parseInt(st.nextToken()); pair[] mnn=new pair[n+1]; boolean[] inc=new boolean[n+1]; boolean[][] poss=new boolean[n+1][k+1]; int[][] dp=new int[n+1][k+1]; for(int i=1;i<=n;i++) { st=new StringTokenizer(bf.readLine()); int a=Integer.parseInt(st.nextToken()); int b=Integer.parseInt(st.nextToken()); mnn[i]=new pair(a,b,i); } for(int i=0;i<=n;i++) { Arrays.fill(dp[i], 1, k+1, Integer.MIN_VALUE/2); } Arrays.sort(mnn,1,n+1); for(int i=1;i<=n;i++) { for(int j=k;j>0;j--) { dp[i][j]=Math.max(dp[i-1][j], dp[i-1][j-1]+mnn[i].a-mnn[i].b*(k-j)); poss[i][j]=(dp[i][j]^dp[i-1][j])==0?false:true; } } for(int i=n,j=k;i>0;i--) { if(poss[i][j]) { inc[i]=true; j--; } } out.println(k+2*(n-k)); for(int i=1,j=0;i<=n;i++) { if(j==k-1) { for(int z=1;z<=n;z++) { if(!inc[z]) { out.print(mnn[z].c+" "+(-mnn[z].c)+" "); } } j++; } if(inc[i]) { out.print(mnn[i].c+" "); j++; } } out.println(); } out.close(); } static class pair implements Comparable<pair>{ int a,b,c; public pair(int x,int y,int z) { a=x;b=y;c=z; } public int compareTo(pair p) { return b-p.b; //if(a>p.a) return 1; } } }
Java
["3\n5 2\n5 3\n7 0\n5 0\n4 0\n10 0\n2 1\n10 100\n50 10\n5 5\n1 5\n2 4\n3 3\n4 2\n5 1"]
6 seconds
["4\n2 1 -1 5\n1\n2\n5\n5 4 3 2 1"]
NoteConsider the example test.In the first test case, Polycarp can summon the minion $$$2$$$ with power level $$$7$$$, then summon the minion $$$1$$$, which will increase the power level of the previous minion by $$$3$$$, then destroy the minion $$$1$$$, and finally, summon the minion $$$5$$$. After this, Polycarp will have two minions with power levels of $$$10$$$.In the second test case, Polycarp can control only one minion, so he should choose the strongest of them and summon it.In the third test case, Polycarp is able to summon and control all five minions.
Java 8
standard input
[ "dp", "greedy", "constructive algorithms", "flows", "graph matchings", "sortings" ]
e764c6437ce11b6b0cee015bc8b8e0b5
The first line contains one integer $$$T$$$ ($$$1 \le T \le 75$$$) — the number of test cases. Each test case begins with a line containing two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 75$$$) — the number of minions availible for summoning, and the maximum number of minions that can be controlled by Polycarp, respectively. Then $$$n$$$ lines follow, the $$$i$$$-th line contains $$$2$$$ integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \le a_i \le 10^5$$$, $$$0 \le b_i \le 10^5$$$) — the parameters of the $$$i$$$-th minion.
2,500
For each test case print the optimal sequence of actions as follows: Firstly, print $$$m$$$ — the number of actions which Polycarp has to perform ($$$0 \le m \le 2n$$$). Then print $$$m$$$ integers $$$o_1$$$, $$$o_2$$$, ..., $$$o_m$$$, where $$$o_i$$$ denotes the $$$i$$$-th action as follows: if the $$$i$$$-th action is to summon the minion $$$x$$$, then $$$o_i = x$$$, and if the $$$i$$$-th action is to destroy the minion $$$x$$$, then $$$o_i = -x$$$. Each minion can be summoned at most once and cannot be destroyed before being summoned (and, obviously, cannot be destroyed more than once). The number of minions in Polycarp's army should be not greater than $$$k$$$ after every action. If there are multiple optimal sequences, print any of them.
standard output
PASSED
4c39cf2fa2627aed43d0c72f204ff825
train_000.jsonl
1589707200
Polycarp plays a computer game. In this game, the players summon armies of magical minions, which then fight each other.Polycarp can summon $$$n$$$ different minions. The initial power level of the $$$i$$$-th minion is $$$a_i$$$, and when it is summoned, all previously summoned minions' power levels are increased by $$$b_i$$$. The minions can be summoned in any order.Unfortunately, Polycarp cannot have more than $$$k$$$ minions under his control. To get rid of unwanted minions after summoning them, he may destroy them. Each minion can be summoned (and destroyed) only once.Polycarp's goal is to summon the strongest possible army. Formally, he wants to maximize the sum of power levels of all minions under his control (those which are summoned and not destroyed).Help Polycarp to make up a plan of actions to summon the strongest possible army!
512 megabytes
import java.io.*; import java.util.*; public class Sol{ static class specInt { int restore[]; int val; public specInt(int val) { this.val = val; restore = new int[n+1]; } } public static int mxN = 76; public static specInt dp[][] = new specInt[mxN][mxN]; public static int arr[][]; public static int n, k; public static int restore[]; public static void main(String[] args) throws IOException{ FastIO sc = new FastIO(System.in); PrintWriter out = new PrintWriter(System.out); int t = sc.nextInt(); while(t-->0) { n = sc.nextInt(); k = sc.nextInt(); arr = new int[n+1][3]; restore = new int[n+1]; for(int i=0; i<mxN; ++i) { for(int j=0; j<mxN; ++j) { dp[i][j] = new specInt(Integer.MIN_VALUE); } } for(int i=1; i<=n; ++i) { arr[i][0] = sc.nextInt(); arr[i][1] = sc.nextInt(); arr[i][2] = i; } ColumnSort(arr, 1); dp[0][0].val = 0; for(int i=1; i<=n; ++i) { for(int j=0; j<=k; ++j) { //if(dp[i-1][j].val!=Integer.MIN_VALUE) { if(arr[i][1]*(k-1)+dp[i-1][j].val>dp[i][j].val) { dp[i][j].val = arr[i][1]*(k-1)+dp[i-1][j].val; for(int b=1; b<=n; ++b) { dp[i][j].restore[b] = dp[i-1][j].restore[b]; } dp[i][j].restore[i] = 0; } if(j<k&&arr[i][0] + arr[i][1]*j+dp[i-1][j].val>dp[i][j+1].val) { dp[i][j+1].val = arr[i][0] + arr[i][1]*j+dp[i-1][j].val; for(int b=1; b<=n; ++b) { dp[i][j+1].restore[b] = dp[i-1][j].restore[b]; } dp[i][j+1].restore[i] = 1; } //} } } int idx = 0; int num = 0; for(int i=1; i<=n; ++i) { if(dp[n][k].restore[i]==1) num++; else num+=2; } out.println(num); for(int i=1; i<=n; ++i) { if(idx<k-1&&dp[n][k].restore[i]==1) { out.print(arr[i][2] + " "); idx++; } } for(int i=1; i<=n; ++i) { if(dp[n][k].restore[i]==0) { out.print(arr[i][2] + " " + (-arr[i][2]) + " "); } } for(int i=n; i>=0; --i) { if(dp[n][k].restore[i]==1) { out.println(arr[i][2]); break; } } out.println(); } out.close(); } public static void ColumnSort(int arr[][], int col) { Arrays.sort(arr, new Comparator<int[]>() { @Override public int compare(int[] entry1, int[] entry2) { Integer a = entry1[col]; Integer b = entry2[col]; return a.compareTo(b); } }); } static class FastIO { // Is your Fast I/O being bad? InputStream dis; byte[] buffer = new byte[1 << 17]; int pointer = 0; public FastIO(String fileName) throws IOException { dis = new FileInputStream(fileName); } public FastIO(InputStream is) throws IOException { dis = is; } int nextInt() throws IOException { int ret = 0; byte b; do { b = nextByte(); } while (b <= ' '); boolean negative = false; if (b == '-') { negative = true; b = nextByte(); } while (b >= '0' && b <= '9') { ret = 10 * ret + b - '0'; b = nextByte(); } return (negative) ? -ret : ret; } long nextLong() throws IOException { long ret = 0; byte b; do { b = nextByte(); } while (b <= ' '); boolean negative = false; if (b == '-') { negative = true; b = nextByte(); } while (b >= '0' && b <= '9') { ret = 10 * ret + b - '0'; b = nextByte(); } return (negative) ? -ret : ret; } byte nextByte() throws IOException { if (pointer == buffer.length) { dis.read(buffer, 0, buffer.length); pointer = 0; } return buffer[pointer++]; } String next() throws IOException { StringBuffer ret = new StringBuffer(); byte b; do { b = nextByte(); } while (b <= ' '); while (b > ' ') { ret.appendCodePoint(b); b = nextByte(); } return ret.toString(); } } }
Java
["3\n5 2\n5 3\n7 0\n5 0\n4 0\n10 0\n2 1\n10 100\n50 10\n5 5\n1 5\n2 4\n3 3\n4 2\n5 1"]
6 seconds
["4\n2 1 -1 5\n1\n2\n5\n5 4 3 2 1"]
NoteConsider the example test.In the first test case, Polycarp can summon the minion $$$2$$$ with power level $$$7$$$, then summon the minion $$$1$$$, which will increase the power level of the previous minion by $$$3$$$, then destroy the minion $$$1$$$, and finally, summon the minion $$$5$$$. After this, Polycarp will have two minions with power levels of $$$10$$$.In the second test case, Polycarp can control only one minion, so he should choose the strongest of them and summon it.In the third test case, Polycarp is able to summon and control all five minions.
Java 8
standard input
[ "dp", "greedy", "constructive algorithms", "flows", "graph matchings", "sortings" ]
e764c6437ce11b6b0cee015bc8b8e0b5
The first line contains one integer $$$T$$$ ($$$1 \le T \le 75$$$) — the number of test cases. Each test case begins with a line containing two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 75$$$) — the number of minions availible for summoning, and the maximum number of minions that can be controlled by Polycarp, respectively. Then $$$n$$$ lines follow, the $$$i$$$-th line contains $$$2$$$ integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \le a_i \le 10^5$$$, $$$0 \le b_i \le 10^5$$$) — the parameters of the $$$i$$$-th minion.
2,500
For each test case print the optimal sequence of actions as follows: Firstly, print $$$m$$$ — the number of actions which Polycarp has to perform ($$$0 \le m \le 2n$$$). Then print $$$m$$$ integers $$$o_1$$$, $$$o_2$$$, ..., $$$o_m$$$, where $$$o_i$$$ denotes the $$$i$$$-th action as follows: if the $$$i$$$-th action is to summon the minion $$$x$$$, then $$$o_i = x$$$, and if the $$$i$$$-th action is to destroy the minion $$$x$$$, then $$$o_i = -x$$$. Each minion can be summoned at most once and cannot be destroyed before being summoned (and, obviously, cannot be destroyed more than once). The number of minions in Polycarp's army should be not greater than $$$k$$$ after every action. If there are multiple optimal sequences, print any of them.
standard output
PASSED
0e8786d08b4807490078fcad43033412
train_000.jsonl
1589707200
Polycarp plays a computer game. In this game, the players summon armies of magical minions, which then fight each other.Polycarp can summon $$$n$$$ different minions. The initial power level of the $$$i$$$-th minion is $$$a_i$$$, and when it is summoned, all previously summoned minions' power levels are increased by $$$b_i$$$. The minions can be summoned in any order.Unfortunately, Polycarp cannot have more than $$$k$$$ minions under his control. To get rid of unwanted minions after summoning them, he may destroy them. Each minion can be summoned (and destroyed) only once.Polycarp's goal is to summon the strongest possible army. Formally, he wants to maximize the sum of power levels of all minions under his control (those which are summoned and not destroyed).Help Polycarp to make up a plan of actions to summon the strongest possible army!
512 megabytes
import java.io.*; import java.util.*; public class Main { static final long MOD = 1000000007L; static final int INF = 50000000; static final int NINF = -500000000; static ArrayDeque<int[]>[] graph; public static void main(String[] args) { FastScanner sc = new FastScanner(); PrintWriter pw = new PrintWriter(System.out); int Q = sc.ni(); for (int q = 0; q < Q; q++) { int N = sc.ni(); int K = sc.ni(); int[][] nums = new int[N+1][3]; //A,B,i Arrays.fill(nums[0],-1); for (int i = 1; i <= N; i++) nums[i] = new int[] {sc.ni(),sc.ni(),i}; sort(nums); int[][] dp = new int[N+1][K+1]; //put minion i in position j for (int i = 0; i <= N; i++) Arrays.fill(dp[i], NINF); dp[0][0] = 0; int[][] from = new int[N+1][K+1]; //equal to k or k-1 for (int i = 1; i <= N; i++) { for (int j = 0; j <= Math.min(i, K); j++) { int v1 = 0; if (j > 0) v1 = dp[i-1][j-1]+nums[i][0]+(j-1)*nums[i][1]; //put this minion in the final roster int v2 = dp[i-1][j]+(K-1)*nums[i][1]; //this is a throwaway minion if (v1 > v2) { dp[i][j] = v1; from[i][j] = j-1; } else { dp[i][j] = v2; from[i][j] = j; } } } //pw.println(Arrays.deepToString(nums)); //pw.println(Arrays.deepToString(dp)); //pw.println(Arrays.deepToString(from)); ArrayList<Integer> survived = new ArrayList<Integer>(); ArrayList<Integer> killed = new ArrayList<Integer>(); int pos = K; for (int i = N; i >= 1; i--) { if (from[i][pos]==pos) { killed.add(nums[i][2]); } else { survived.add(nums[i][2]); } pos = from[i][pos]; } Collections.reverse(survived); ArrayList<Integer> ans = new ArrayList<Integer>(); for (int i = 0; i < survived.size()-1; i++) { ans.add(survived.get(i)); } for (int i = 0; i < killed.size(); i++) { int idx = killed.get(i); ans.add(idx); ans.add(0-idx); } ans.add(survived.get(survived.size()-1)); pw.println(ans.size()); for (int a: ans) pw.print(a + " "); pw.println(); } pw.close(); } public static void sort(int[][] arr) { //Sort an array (immune to quicksort TLE) Random rgen = new Random(); for (int i = 0; i < arr.length; i++) { int randomPosition = rgen.nextInt(arr.length); int[] temp = arr[i]; arr[i] = arr[randomPosition]; arr[randomPosition] = temp; } Arrays.sort(arr, new Comparator<int[]>() { @Override public int compare(int[] arr1, int[] arr2) { return arr1[1]-arr2[1]; //Ascending order. } }); } 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 ni() { return Integer.parseInt(next()); } long nl() { return Long.parseLong(next()); } double nd() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["3\n5 2\n5 3\n7 0\n5 0\n4 0\n10 0\n2 1\n10 100\n50 10\n5 5\n1 5\n2 4\n3 3\n4 2\n5 1"]
6 seconds
["4\n2 1 -1 5\n1\n2\n5\n5 4 3 2 1"]
NoteConsider the example test.In the first test case, Polycarp can summon the minion $$$2$$$ with power level $$$7$$$, then summon the minion $$$1$$$, which will increase the power level of the previous minion by $$$3$$$, then destroy the minion $$$1$$$, and finally, summon the minion $$$5$$$. After this, Polycarp will have two minions with power levels of $$$10$$$.In the second test case, Polycarp can control only one minion, so he should choose the strongest of them and summon it.In the third test case, Polycarp is able to summon and control all five minions.
Java 8
standard input
[ "dp", "greedy", "constructive algorithms", "flows", "graph matchings", "sortings" ]
e764c6437ce11b6b0cee015bc8b8e0b5
The first line contains one integer $$$T$$$ ($$$1 \le T \le 75$$$) — the number of test cases. Each test case begins with a line containing two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 75$$$) — the number of minions availible for summoning, and the maximum number of minions that can be controlled by Polycarp, respectively. Then $$$n$$$ lines follow, the $$$i$$$-th line contains $$$2$$$ integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \le a_i \le 10^5$$$, $$$0 \le b_i \le 10^5$$$) — the parameters of the $$$i$$$-th minion.
2,500
For each test case print the optimal sequence of actions as follows: Firstly, print $$$m$$$ — the number of actions which Polycarp has to perform ($$$0 \le m \le 2n$$$). Then print $$$m$$$ integers $$$o_1$$$, $$$o_2$$$, ..., $$$o_m$$$, where $$$o_i$$$ denotes the $$$i$$$-th action as follows: if the $$$i$$$-th action is to summon the minion $$$x$$$, then $$$o_i = x$$$, and if the $$$i$$$-th action is to destroy the minion $$$x$$$, then $$$o_i = -x$$$. Each minion can be summoned at most once and cannot be destroyed before being summoned (and, obviously, cannot be destroyed more than once). The number of minions in Polycarp's army should be not greater than $$$k$$$ after every action. If there are multiple optimal sequences, print any of them.
standard output
PASSED
1cf3fe9378dd20929a90fd41b01e6e4e
train_000.jsonl
1589707200
Polycarp plays a computer game. In this game, the players summon armies of magical minions, which then fight each other.Polycarp can summon $$$n$$$ different minions. The initial power level of the $$$i$$$-th minion is $$$a_i$$$, and when it is summoned, all previously summoned minions' power levels are increased by $$$b_i$$$. The minions can be summoned in any order.Unfortunately, Polycarp cannot have more than $$$k$$$ minions under his control. To get rid of unwanted minions after summoning them, he may destroy them. Each minion can be summoned (and destroyed) only once.Polycarp's goal is to summon the strongest possible army. Formally, he wants to maximize the sum of power levels of all minions under his control (those which are summoned and not destroyed).Help Polycarp to make up a plan of actions to summon the strongest possible army!
512 megabytes
/* If you want to aim high, aim high Don't let that studying and grades consume you Just live life young ****************************** If I'm the sun, you're the moon Because when I go up, you go down ******************************* I'm working for the day I will surpass you https://www.a2oj.com/Ladder16.html */ import java.util.*; import java.io.*; import java.math.*; public class x1354F2 { public static void main(String omkar[]) throws Exception { BufferedReader infile = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(infile.readLine()); int T = Integer.parseInt(st.nextToken()); StringBuilder sb = new StringBuilder(); while(T-->0) { st = new StringTokenizer(infile.readLine()); int N = Integer.parseInt(st.nextToken()); int K = Integer.parseInt(st.nextToken()); Minion[] arr = new Minion[N]; for(int i=0; i < N; i++) { st = new StringTokenizer(infile.readLine()); int a = Integer.parseInt(st.nextToken()); int b = Integer.parseInt(st.nextToken()); arr[i] = new Minion(a, b, i); } Arrays.sort(arr); Node[][] par = new Node[N][K+1]; long[][] dp = new long[N][K+1]; for(int i=0; i < N; i++) Arrays.fill(dp[i], -1); dp[0][1] = arr[0].a; par[0][1] = new Node(-1, 420); if(N != K) { dp[0][0] = arr[0].b*(K-1); par[0][0] = new Node(-1, 420); } for(int i=1; i < N; i++) for(int k=0; k <= K; k++) { if(i+1 < k) break; int boof = i-k+1; long max = -1L; if(i >= k && dp[i-1][k] != -1) max = dp[i-1][k]+arr[i].b*(K-1); if(k > 0 && dp[i-1][k-1] != -1) max = Math.max(max, dp[i-1][k-1]+arr[i].a+arr[i].b*(k-1)); dp[i][k] = max; if(max == dp[i-1][k]+arr[i].b*(K-1) && dp[i-1][k] != -1) par[i][k] = new Node(i-1, k); else if(max != -1) par[i][k] = new Node(i-1, k-1); } //restore ArrayList<Integer> ls = new ArrayList<Integer>(); HashSet<Integer> set = new HashSet<Integer>(); for(int i=0; i < N; i++) set.add(i); Node curr = new Node(N-1, K); while(curr.dex > 0) { int i = curr.dex; int k = curr.cnt; Node next = par[i][k]; if(k == next.cnt+1) { ls.add(arr[i].dex); set.remove(arr[i].dex); } curr = next; } if(curr.cnt == 1) { ls.add(arr[0].dex); set.remove(arr[0].dex); } Collections.reverse(ls); ArrayList<Integer> res = new ArrayList<Integer>(); for(int i=0; i < ls.size()-1; i++) res.add(ls.get(i)+1); for(int x: set) { res.add(x+1); res.add(-x-1); } res.add(ls.get(ls.size()-1)+1); sb.append(res.size()+"\n"); for(int x: res) sb.append(x+" "); sb.append("\n"); } System.out.print(sb); } } class Minion implements Comparable<Minion> { public long a; public long b; public int dex; public Minion(long x, long y, int d) { a = x; b = y; dex = d; } public int compareTo(Minion oth) { if(b == oth.b) return (int)(oth.a-a); return (int)(b-oth.b); } } class Node { public int dex; public int cnt; public Node(int a, int c) { dex = a; cnt = c; } }
Java
["3\n5 2\n5 3\n7 0\n5 0\n4 0\n10 0\n2 1\n10 100\n50 10\n5 5\n1 5\n2 4\n3 3\n4 2\n5 1"]
6 seconds
["4\n2 1 -1 5\n1\n2\n5\n5 4 3 2 1"]
NoteConsider the example test.In the first test case, Polycarp can summon the minion $$$2$$$ with power level $$$7$$$, then summon the minion $$$1$$$, which will increase the power level of the previous minion by $$$3$$$, then destroy the minion $$$1$$$, and finally, summon the minion $$$5$$$. After this, Polycarp will have two minions with power levels of $$$10$$$.In the second test case, Polycarp can control only one minion, so he should choose the strongest of them and summon it.In the third test case, Polycarp is able to summon and control all five minions.
Java 8
standard input
[ "dp", "greedy", "constructive algorithms", "flows", "graph matchings", "sortings" ]
e764c6437ce11b6b0cee015bc8b8e0b5
The first line contains one integer $$$T$$$ ($$$1 \le T \le 75$$$) — the number of test cases. Each test case begins with a line containing two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 75$$$) — the number of minions availible for summoning, and the maximum number of minions that can be controlled by Polycarp, respectively. Then $$$n$$$ lines follow, the $$$i$$$-th line contains $$$2$$$ integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \le a_i \le 10^5$$$, $$$0 \le b_i \le 10^5$$$) — the parameters of the $$$i$$$-th minion.
2,500
For each test case print the optimal sequence of actions as follows: Firstly, print $$$m$$$ — the number of actions which Polycarp has to perform ($$$0 \le m \le 2n$$$). Then print $$$m$$$ integers $$$o_1$$$, $$$o_2$$$, ..., $$$o_m$$$, where $$$o_i$$$ denotes the $$$i$$$-th action as follows: if the $$$i$$$-th action is to summon the minion $$$x$$$, then $$$o_i = x$$$, and if the $$$i$$$-th action is to destroy the minion $$$x$$$, then $$$o_i = -x$$$. Each minion can be summoned at most once and cannot be destroyed before being summoned (and, obviously, cannot be destroyed more than once). The number of minions in Polycarp's army should be not greater than $$$k$$$ after every action. If there are multiple optimal sequences, print any of them.
standard output
PASSED
032e7050bac3b599d1e62d55ded33be6
train_000.jsonl
1589707200
Polycarp plays a computer game. In this game, the players summon armies of magical minions, which then fight each other.Polycarp can summon $$$n$$$ different minions. The initial power level of the $$$i$$$-th minion is $$$a_i$$$, and when it is summoned, all previously summoned minions' power levels are increased by $$$b_i$$$. The minions can be summoned in any order.Unfortunately, Polycarp cannot have more than $$$k$$$ minions under his control. To get rid of unwanted minions after summoning them, he may destroy them. Each minion can be summoned (and destroyed) only once.Polycarp's goal is to summon the strongest possible army. Formally, he wants to maximize the sum of power levels of all minions under his control (those which are summoned and not destroyed).Help Polycarp to make up a plan of actions to summon the strongest possible army!
512 megabytes
import java.io.*; import java.text.*; import java.util.*; import java.math.*; public class template { public static void main(String[] args) throws Exception { new template().run(); } public void run() throws Exception { FastScanner f = new FastScanner(); PrintWriter out = new PrintWriter(System.out); int asdf = f.nextInt(); while(asdf-->0) { int n = f.nextInt(), k = f.nextInt(); Pair[] arr = new Pair[n]; for(int i = 0; i < n; i++) arr[i] = new Pair(f.nextInt(), f.nextInt(),i); Arrays.sort(arr); boolean[][] use = new boolean[n+1][k+1]; int[][] dp = new int[n+1][k+1]; for(int[] i : dp) Arrays.fill(i, -2147483648); dp[0][0] = 0; for(int i = 0; i < n; i++) for(int j = 0; j <= k; j++) { if(dp[i+1][j] < dp[i][j]+(k-1)*(arr[i].b)) { dp[i+1][j] = dp[i][j]+(k-1)*(arr[i].b); use[i+1][j] = false; } if(j != k && dp[i+1][j+1] < dp[i][j]+j*arr[i].b+arr[i].a) { dp[i+1][j+1] = dp[i][j]+j*arr[i].b+arr[i].a; use[i+1][j+1] = true; } } int j = k; boolean[] del = new boolean[n]; for(int i = n; i > 0; i--) { if(use[i][j]) j--; else del[i-1] = true; } out.println(2*n-k); int last = -1; for(int i = 0; i < n; i++) if(!del[i]) { if(last != -1) out.print(last + " "); last = arr[i].i+1; } for(int i = 0; i < n; i++) if(del[i]) out.print(arr[i].i+1+" " + -(arr[i].i+1) + " "); out.println(last); } out.flush(); } class Pair implements Comparable<Pair> { int a, b, i; public Pair(int a, int b, int i) { this.a = a; this.b = b; this.i = i; } public int compareTo(Pair p) { return Integer.compare(b, p.b); } public String toString() { return a + "," + b; } } static 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
["3\n5 2\n5 3\n7 0\n5 0\n4 0\n10 0\n2 1\n10 100\n50 10\n5 5\n1 5\n2 4\n3 3\n4 2\n5 1"]
6 seconds
["4\n2 1 -1 5\n1\n2\n5\n5 4 3 2 1"]
NoteConsider the example test.In the first test case, Polycarp can summon the minion $$$2$$$ with power level $$$7$$$, then summon the minion $$$1$$$, which will increase the power level of the previous minion by $$$3$$$, then destroy the minion $$$1$$$, and finally, summon the minion $$$5$$$. After this, Polycarp will have two minions with power levels of $$$10$$$.In the second test case, Polycarp can control only one minion, so he should choose the strongest of them and summon it.In the third test case, Polycarp is able to summon and control all five minions.
Java 8
standard input
[ "dp", "greedy", "constructive algorithms", "flows", "graph matchings", "sortings" ]
e764c6437ce11b6b0cee015bc8b8e0b5
The first line contains one integer $$$T$$$ ($$$1 \le T \le 75$$$) — the number of test cases. Each test case begins with a line containing two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 75$$$) — the number of minions availible for summoning, and the maximum number of minions that can be controlled by Polycarp, respectively. Then $$$n$$$ lines follow, the $$$i$$$-th line contains $$$2$$$ integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \le a_i \le 10^5$$$, $$$0 \le b_i \le 10^5$$$) — the parameters of the $$$i$$$-th minion.
2,500
For each test case print the optimal sequence of actions as follows: Firstly, print $$$m$$$ — the number of actions which Polycarp has to perform ($$$0 \le m \le 2n$$$). Then print $$$m$$$ integers $$$o_1$$$, $$$o_2$$$, ..., $$$o_m$$$, where $$$o_i$$$ denotes the $$$i$$$-th action as follows: if the $$$i$$$-th action is to summon the minion $$$x$$$, then $$$o_i = x$$$, and if the $$$i$$$-th action is to destroy the minion $$$x$$$, then $$$o_i = -x$$$. Each minion can be summoned at most once and cannot be destroyed before being summoned (and, obviously, cannot be destroyed more than once). The number of minions in Polycarp's army should be not greater than $$$k$$$ after every action. If there are multiple optimal sequences, print any of them.
standard output
PASSED
81533ecb9e3f3530f78bf371bb4c5810
train_000.jsonl
1589707200
Polycarp plays a computer game. In this game, the players summon armies of magical minions, which then fight each other.Polycarp can summon $$$n$$$ different minions. The initial power level of the $$$i$$$-th minion is $$$a_i$$$, and when it is summoned, all previously summoned minions' power levels are increased by $$$b_i$$$. The minions can be summoned in any order.Unfortunately, Polycarp cannot have more than $$$k$$$ minions under his control. To get rid of unwanted minions after summoning them, he may destroy them. Each minion can be summoned (and destroyed) only once.Polycarp's goal is to summon the strongest possible army. Formally, he wants to maximize the sum of power levels of all minions under his control (those which are summoned and not destroyed).Help Polycarp to make up a plan of actions to summon the strongest possible army!
512 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.util.stream.IntStream; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Arrays; import java.io.BufferedWriter; import java.util.InputMismatchException; import java.io.IOException; import java.util.stream.Collectors; import java.util.ArrayList; import java.util.List; import java.util.stream.Stream; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.Comparator; import java.util.Collections; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author out_of_the_box */ 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); FSummoningMinions solver = new FSummoningMinions(); int testCount = Integer.parseInt(in.next()); for (int i = 1; i <= testCount; i++) solver.solve(i, in, out); out.close(); } static class FSummoningMinions { public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.nextInt(); int k = in.nextInt(); int[] a = new int[n]; int[] b = new int[n]; for (int i = 0; i < n; i++) { a[i] = in.nextInt(); b[i] = in.nextInt(); } int[][] dp = new int[n][k + 1]; int[] indexes = new int[n]; for (int i = 0; i < n; i++) { indexes[i] = i; } indexes = Arrays.stream(indexes).boxed().sorted(Comparator.comparingInt(ind -> b[ind])).mapToInt(i -> i) .toArray(); boolean[][] select = new boolean[n][k + 1]; dp[0][0] = (k - 1) * b[indexes[0]]; dp[0][1] = a[indexes[0]]; select[0][1] = true; for (int i = 1; i < n; i++) { dp[i][0] = dp[i - 1][0] + (k - 1) * (b[indexes[i]]); } for (int i = 1; i < n; i++) { int maxJ = Math.min(i + 1, k); for (int j = 1; j <= maxJ; j++) { int first = dp[i - 1][j - 1] + a[indexes[i]] + (j - 1) * b[indexes[i]]; int second = (j <= i) ? dp[i - 1][j] + (k - 1) * b[indexes[i]] : (-1); if (first >= second) { dp[i][j] = first; select[i][j] = true; } else { dp[i][j] = second; } } } List<Integer> selected = new ArrayList<>(); boolean[] selectedFlag = new boolean[n]; int tbs = k; for (int i = n - 1; i >= 0; i--) { if (tbs == 0) break; if (select[i][tbs]) { selected.add(indexes[i]); selectedFlag[indexes[i]] = true; tbs--; } } List<Integer> listA = Arrays.stream(a).boxed().collect(Collectors.toList()); List<Integer> listB = Arrays.stream(b).boxed().collect(Collectors.toList()); String message = String.format("Selected size mismatch. size = %d, k = %d, n = %d, a = %s, b = %s", selected.size(), k, n, listA, listB); MiscUtility.assertion(selected.size() == k, message); Collections.reverse(selected); int m = k + (n - k) * 2; out.println(m); for (int i = 0; i < (k - 1); i++) { out.print((selected.get(i) + 1) + " "); } for (int i = 0; i < n; i++) { if (!selectedFlag[i]) { out.print((i + 1) + " "); out.print(-(i + 1) + " "); } } out.print(selected.get(k - 1) + 1); 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 print(int i) { writer.print(i); } public void println(int i) { writer.println(i); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String nextString() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { if (Character.isValidCodePoint(c)) { res.appendCodePoint(c); } c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return nextString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } static class MiscUtility { public static void assertion(boolean condition, String message) { if (!condition) { throw new RuntimeException("Assertion failed. " + message); } } } }
Java
["3\n5 2\n5 3\n7 0\n5 0\n4 0\n10 0\n2 1\n10 100\n50 10\n5 5\n1 5\n2 4\n3 3\n4 2\n5 1"]
6 seconds
["4\n2 1 -1 5\n1\n2\n5\n5 4 3 2 1"]
NoteConsider the example test.In the first test case, Polycarp can summon the minion $$$2$$$ with power level $$$7$$$, then summon the minion $$$1$$$, which will increase the power level of the previous minion by $$$3$$$, then destroy the minion $$$1$$$, and finally, summon the minion $$$5$$$. After this, Polycarp will have two minions with power levels of $$$10$$$.In the second test case, Polycarp can control only one minion, so he should choose the strongest of them and summon it.In the third test case, Polycarp is able to summon and control all five minions.
Java 8
standard input
[ "dp", "greedy", "constructive algorithms", "flows", "graph matchings", "sortings" ]
e764c6437ce11b6b0cee015bc8b8e0b5
The first line contains one integer $$$T$$$ ($$$1 \le T \le 75$$$) — the number of test cases. Each test case begins with a line containing two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 75$$$) — the number of minions availible for summoning, and the maximum number of minions that can be controlled by Polycarp, respectively. Then $$$n$$$ lines follow, the $$$i$$$-th line contains $$$2$$$ integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \le a_i \le 10^5$$$, $$$0 \le b_i \le 10^5$$$) — the parameters of the $$$i$$$-th minion.
2,500
For each test case print the optimal sequence of actions as follows: Firstly, print $$$m$$$ — the number of actions which Polycarp has to perform ($$$0 \le m \le 2n$$$). Then print $$$m$$$ integers $$$o_1$$$, $$$o_2$$$, ..., $$$o_m$$$, where $$$o_i$$$ denotes the $$$i$$$-th action as follows: if the $$$i$$$-th action is to summon the minion $$$x$$$, then $$$o_i = x$$$, and if the $$$i$$$-th action is to destroy the minion $$$x$$$, then $$$o_i = -x$$$. Each minion can be summoned at most once and cannot be destroyed before being summoned (and, obviously, cannot be destroyed more than once). The number of minions in Polycarp's army should be not greater than $$$k$$$ after every action. If there are multiple optimal sequences, print any of them.
standard output
PASSED
986ed672e3c2aee1b11e95a6176321dc
train_000.jsonl
1573914900
You're given two arrays $$$a[1 \dots n]$$$ and $$$b[1 \dots n]$$$, both of the same length $$$n$$$.In order to perform a push operation, you have to choose three integers $$$l, r, k$$$ satisfying $$$1 \le l \le r \le n$$$ and $$$k &gt; 0$$$. Then, you will add $$$k$$$ to elements $$$a_l, a_{l+1}, \ldots, a_r$$$.For example, if $$$a = [3, 7, 1, 4, 1, 2]$$$ and you choose $$$(l = 3, r = 5, k = 2)$$$, the array $$$a$$$ will become $$$[3, 7, \underline{3, 6, 3}, 2]$$$.You can do this operation at most once. Can you make array $$$a$$$ equal to array $$$b$$$?(We consider that $$$a = b$$$ if and only if, for every $$$1 \le i \le n$$$, $$$a_i = b_i$$$)
256 megabytes
import java.io.*; import java.util.*; public class Main{ static int mod = (int)(Math.pow(10, 9) + 7); public static void main(String[] args) { MyScanner sc = new MyScanner(); out = new PrintWriter(new BufferedOutputStream(System.out)); int t= sc.nextInt(); while (t-->0) { int n = sc.nextInt(); int[] a = new int[n]; int[] b = new int[n]; int[] d = new int[n]; for (int i= 0 ; i < n; i++){ a[i] = sc.nextInt(); } for (int i= 0 ; i < n; i++){ b[i] = sc.nextInt(); } Set<Integer> nums = new HashSet<Integer>(); boolean works = true; for (int i= 0 ; i < n; i++){ d[i] = b[i] - a[i]; // out.println(d[i] + " " + t); if (d[i] == 0) { continue; } else if (d[i] < 0){ works = false; break; } else{ // out.println(d[i] + " " + t); nums.add(d[i]); } } // for (int i: nums){ // out.print(i + " "); // } // out.println(); if (nums.size() >= 2) works = false; if (works && nums.size() == 1){ //out.println(t); List<Integer> nu = new ArrayList<Integer>(); nu.addAll(nums); int k = nu.get(0); int streak = 0; int total = 0; int maxStreak = 0; for (int i = 0; i < n; i++){ if (d[i] == k){ streak++; total++; } else{ maxStreak = Integer.max(streak, maxStreak); streak = 0; } } maxStreak = Integer.max(streak, maxStreak); //out.println(maxStreak + " " +total + " " + t); if (maxStreak != total) works = false; } if (!works){ out.println("nO"); } else out.println("yEs"); } out.close(); } static long pow(long a, long N) { if (N == 0) return 1; else if (N == 1) return a; else { long R = pow(a,N/2); if (N % 2 == 0) { return R*R; } else { return R*R*a; } } } static long powMod(long a, long N) { if (N == 0) return 1; else if (N == 1) return a % mod; else { long R = powMod(a,N/2) % mod; R *= R % mod; if (N % 2 == 0) { R *= a % mod; } return R % mod; } } static void mergeSort(int[] A){ // low to hi sort, single array only int n = A.length; if (n < 2) return; int[] l = new int[n/2]; int[] r = new int[n - n/2]; for (int i = 0; i < n/2; i++){ l[i] = A[i]; } for (int j = n/2; j < n; j++){ r[j-n/2] = A[j]; } mergeSort(l); mergeSort(r); merge(l, r, A); } static void merge(int[] l, int[] r, int[] a){ int i = 0, j = 0, k = 0; while (i < l.length && j < r.length && k < a.length){ if (l[i] < r[j]){ a[k] = l[i]; i++; } else{ a[k] = r[j]; j++; } k++; } while (i < l.length){ a[k] = l[i]; i++; k++; } while (j < r.length){ a[k] = r[j]; j++; k++; } } //-----------PrintWriter for faster output--------------------------------- public static PrintWriter out; //-----------MyScanner class for faster input---------- public static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine(){ String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } //-------------------------------------------------------- }
Java
["4\n6\n3 7 1 4 1 2\n3 7 3 6 3 2\n5\n1 1 1 1 1\n1 2 1 3 1\n2\n42 42\n42 42\n1\n7\n6"]
1 second
["YES\nNO\nYES\nNO"]
NoteThe first test case is described in the statement: we can perform a push operation with parameters $$$(l=3, r=5, k=2)$$$ to make $$$a$$$ equal to $$$b$$$.In the second test case, we would need at least two operations to make $$$a$$$ equal to $$$b$$$.In the third test case, arrays $$$a$$$ and $$$b$$$ are already equal.In the fourth test case, it's impossible to make $$$a$$$ equal to $$$b$$$, because the integer $$$k$$$ has to be positive.
Java 8
standard input
[ "implementation" ]
0e0ef011ebe7198b7189fce562b7d6c1
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 20$$$) — the number of test cases in the input. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 100\ 000$$$) — the number of elements in each array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 1000$$$). The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le 1000$$$). It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.
1,000
For each test case, output one line containing "YES" if it's possible to make arrays $$$a$$$ and $$$b$$$ equal by performing at most once the described operation or "NO" if it's impossible. You can print each letter in any case (upper or lower).
standard output
PASSED
f588ffde6907de66c7fabda53692b587
train_000.jsonl
1573914900
You're given two arrays $$$a[1 \dots n]$$$ and $$$b[1 \dots n]$$$, both of the same length $$$n$$$.In order to perform a push operation, you have to choose three integers $$$l, r, k$$$ satisfying $$$1 \le l \le r \le n$$$ and $$$k &gt; 0$$$. Then, you will add $$$k$$$ to elements $$$a_l, a_{l+1}, \ldots, a_r$$$.For example, if $$$a = [3, 7, 1, 4, 1, 2]$$$ and you choose $$$(l = 3, r = 5, k = 2)$$$, the array $$$a$$$ will become $$$[3, 7, \underline{3, 6, 3}, 2]$$$.You can do this operation at most once. Can you make array $$$a$$$ equal to array $$$b$$$?(We consider that $$$a = b$$$ if and only if, for every $$$1 \le i \le n$$$, $$$a_i = b_i$$$)
256 megabytes
import java.io.*; import java.util.*; public class A { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); //StringBuilder sb=new StringBuilder(); //StringTokenizer st=new StringTokenizer(br.readLine()); int q = Integer.parseInt(br.readLine()); int k =1; w:while (q-- > 0) { int n = Integer.parseInt(br.readLine()); int a[] =new int[n]; int b[] =new int[n]; StringTokenizer st=new StringTokenizer(br.readLine()); for(int i=0 ;i<n;i++){ a[i]=Integer.parseInt(st.nextToken()); } st=new StringTokenizer(br.readLine()); for(int i=0 ;i<n;i++){ b[i]=Integer.parseInt(st.nextToken()); } int c[]=new int[n]; for(int i=0 ;i<n;i++){ c[i]=b[i]-a[i]; } //out.println(Arrays.toString(c)); for(int i=0 ;i<n;i++){ if(c[i]<0){out.println("NO");continue w;} } int g=0; HashSet<Integer> hs=new HashSet<>(); for(int i=0 ;i<c.length;i++){ if(c[i]>0){hs.add(c[i]);} } if(hs.size()>1){out.println("NO");continue;} for(int i=0 ;i<c.length-1;i++){ if(c[i]!=c[i+1]){g++;} } if(g==0){out.println("YES");continue;} if(b[0]!=a[0]||(b[c.length-1]!=a[c.length-1])){ if(g==1){out.println("YES");continue;} else { out.println("NO");continue; } } if(g==2){out.println("YES");continue;} else { out.println("NO");continue; } //out.println(Arrays.toString(c)); }//out.println(); out.close(); } }
Java
["4\n6\n3 7 1 4 1 2\n3 7 3 6 3 2\n5\n1 1 1 1 1\n1 2 1 3 1\n2\n42 42\n42 42\n1\n7\n6"]
1 second
["YES\nNO\nYES\nNO"]
NoteThe first test case is described in the statement: we can perform a push operation with parameters $$$(l=3, r=5, k=2)$$$ to make $$$a$$$ equal to $$$b$$$.In the second test case, we would need at least two operations to make $$$a$$$ equal to $$$b$$$.In the third test case, arrays $$$a$$$ and $$$b$$$ are already equal.In the fourth test case, it's impossible to make $$$a$$$ equal to $$$b$$$, because the integer $$$k$$$ has to be positive.
Java 8
standard input
[ "implementation" ]
0e0ef011ebe7198b7189fce562b7d6c1
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 20$$$) — the number of test cases in the input. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 100\ 000$$$) — the number of elements in each array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 1000$$$). The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le 1000$$$). It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.
1,000
For each test case, output one line containing "YES" if it's possible to make arrays $$$a$$$ and $$$b$$$ equal by performing at most once the described operation or "NO" if it's impossible. You can print each letter in any case (upper or lower).
standard output
PASSED
35be249d299803fd2cef5d64876e6b86
train_000.jsonl
1573914900
You're given two arrays $$$a[1 \dots n]$$$ and $$$b[1 \dots n]$$$, both of the same length $$$n$$$.In order to perform a push operation, you have to choose three integers $$$l, r, k$$$ satisfying $$$1 \le l \le r \le n$$$ and $$$k &gt; 0$$$. Then, you will add $$$k$$$ to elements $$$a_l, a_{l+1}, \ldots, a_r$$$.For example, if $$$a = [3, 7, 1, 4, 1, 2]$$$ and you choose $$$(l = 3, r = 5, k = 2)$$$, the array $$$a$$$ will become $$$[3, 7, \underline{3, 6, 3}, 2]$$$.You can do this operation at most once. Can you make array $$$a$$$ equal to array $$$b$$$?(We consider that $$$a = b$$$ if and only if, for every $$$1 \le i \le n$$$, $$$a_i = b_i$$$)
256 megabytes
import java.util.*; public class Main{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while(t-->0){ int n = sc.nextInt(); int[] a = new int[n]; int[] b = new int[n]; for(int i=0;i<n;i++)a[i]=sc.nextInt(); for(int i=0;i<n;i++)b[i]=sc.nextInt(); int[] c = new int[n]; boolean flag = true; int last = 0; int l = 0; int r = n-1; for(int i=0;i<n;i++){ c[i]=b[i]-a[i]; if(c[i]<0)flag = false; } for(int i=0;i<n;i++){ if(c[i]>0){ l=i; break; } } for(int i=n-1;i>=0;i--){ if(c[i]>0){ r=i; break; } } int mi = c[l]; for(int i=l;i<=r;i++){ c[i]-=mi; if(c[i]!=0)flag = false; } System.out.println((flag)?"YES":"NO"); } } public static int lcm(int x, int y){ return x*y/gcd(x,y); } public static int gcd(int x, int y){ if(x < y)return gcd(y,x); if(y==0)return x; return gcd(y,x%y); } } class Pair{ int a,b; Pair(int a, int b){ this.a = a; this.b = b; } }
Java
["4\n6\n3 7 1 4 1 2\n3 7 3 6 3 2\n5\n1 1 1 1 1\n1 2 1 3 1\n2\n42 42\n42 42\n1\n7\n6"]
1 second
["YES\nNO\nYES\nNO"]
NoteThe first test case is described in the statement: we can perform a push operation with parameters $$$(l=3, r=5, k=2)$$$ to make $$$a$$$ equal to $$$b$$$.In the second test case, we would need at least two operations to make $$$a$$$ equal to $$$b$$$.In the third test case, arrays $$$a$$$ and $$$b$$$ are already equal.In the fourth test case, it's impossible to make $$$a$$$ equal to $$$b$$$, because the integer $$$k$$$ has to be positive.
Java 8
standard input
[ "implementation" ]
0e0ef011ebe7198b7189fce562b7d6c1
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 20$$$) — the number of test cases in the input. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 100\ 000$$$) — the number of elements in each array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 1000$$$). The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le 1000$$$). It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.
1,000
For each test case, output one line containing "YES" if it's possible to make arrays $$$a$$$ and $$$b$$$ equal by performing at most once the described operation or "NO" if it's impossible. You can print each letter in any case (upper or lower).
standard output
PASSED
c8f6b230ca9b248383542ec02b0ca917
train_000.jsonl
1573914900
You're given two arrays $$$a[1 \dots n]$$$ and $$$b[1 \dots n]$$$, both of the same length $$$n$$$.In order to perform a push operation, you have to choose three integers $$$l, r, k$$$ satisfying $$$1 \le l \le r \le n$$$ and $$$k &gt; 0$$$. Then, you will add $$$k$$$ to elements $$$a_l, a_{l+1}, \ldots, a_r$$$.For example, if $$$a = [3, 7, 1, 4, 1, 2]$$$ and you choose $$$(l = 3, r = 5, k = 2)$$$, the array $$$a$$$ will become $$$[3, 7, \underline{3, 6, 3}, 2]$$$.You can do this operation at most once. Can you make array $$$a$$$ equal to array $$$b$$$?(We consider that $$$a = b$$$ if and only if, for every $$$1 \le i \le n$$$, $$$a_i = b_i$$$)
256 megabytes
import java.util.Scanner; public class TaskA { private static boolean solve(int N, int[] a, int[] b) { boolean diffStarted = false; boolean diffEnded = false; int diff = Integer.MIN_VALUE; for (int i = 0; i < N; i++) { if (a[i] == b[i]) { if (diffStarted) diffEnded = true; continue; } if (a[i] > b[i]) return false; if (diffEnded) return false; if (!diffStarted) { diff = b[i] - a[i]; diffStarted = true; continue; } if (diff != b[i] - a[i]) return false; } return true; } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int T = scanner.nextInt(); for (int t = 0; t < T; t++) { int N = scanner.nextInt(); int[] a = new int[N]; int[] b = new int[N]; for (int i = 0; i < N; i++) a[i] = scanner.nextInt(); for (int i = 0; i < N; i++) b[i] = scanner.nextInt(); System.out.println(solve(N, a, b) ? "YES" : "NO"); } } }
Java
["4\n6\n3 7 1 4 1 2\n3 7 3 6 3 2\n5\n1 1 1 1 1\n1 2 1 3 1\n2\n42 42\n42 42\n1\n7\n6"]
1 second
["YES\nNO\nYES\nNO"]
NoteThe first test case is described in the statement: we can perform a push operation with parameters $$$(l=3, r=5, k=2)$$$ to make $$$a$$$ equal to $$$b$$$.In the second test case, we would need at least two operations to make $$$a$$$ equal to $$$b$$$.In the third test case, arrays $$$a$$$ and $$$b$$$ are already equal.In the fourth test case, it's impossible to make $$$a$$$ equal to $$$b$$$, because the integer $$$k$$$ has to be positive.
Java 8
standard input
[ "implementation" ]
0e0ef011ebe7198b7189fce562b7d6c1
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 20$$$) — the number of test cases in the input. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 100\ 000$$$) — the number of elements in each array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 1000$$$). The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le 1000$$$). It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.
1,000
For each test case, output one line containing "YES" if it's possible to make arrays $$$a$$$ and $$$b$$$ equal by performing at most once the described operation or "NO" if it's impossible. You can print each letter in any case (upper or lower).
standard output
PASSED
9fbe90ac295f482498e9308f84268fa3
train_000.jsonl
1369582200
SmallR is an archer. SmallR is taking a match of archer with Zanoes. They try to shoot in the target in turns, and SmallR shoots first. The probability of shooting the target each time is for SmallR while for Zanoes. The one who shoots in the target first should be the winner.Output the probability that SmallR will win the match.
256 megabytes
import java.util.*; public class Archer{ public static void main(String[] Args){ Scanner sc = new Scanner(System.in); double a = sc.nextInt(); double b = sc.nextInt(); double c = sc.nextInt(); double d = sc.nextInt(); double ans = (a*d)/ (b*d - (b-a)*(d-c)); System.out.println(ans); } }
Java
["1 2 1 2"]
2 seconds
["0.666666666667"]
null
Java 7
standard input
[ "probabilities", "math" ]
7b932b2d3ab65a353b18d81cf533a54e
A single line contains four integers .
1,300
Print a single real number, the probability that SmallR will win the match. The answer will be considered correct if the absolute or relative error doesn't exceed 10 - 6.
standard output
PASSED
490b5e41210c1ab7e9bf9c3415c93735
train_000.jsonl
1369582200
SmallR is an archer. SmallR is taking a match of archer with Zanoes. They try to shoot in the target in turns, and SmallR shoots first. The probability of shooting the target each time is for SmallR while for Zanoes. The one who shoots in the target first should be the winner.Output the probability that SmallR will win the match.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.IOException; import java.util.StringTokenizer; public class Archer { public static void main(String[] args) { MyScanner sc = new MyScanner(); int A = sc.nextInt(); int B = sc.nextInt(); int C = sc.nextInt(); int D = sc.nextInt(); double r = (double)A / B; double z = (double)C / D; System.out.println(r / (1 - (1 - r) * (1 - z))); } public static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } int nextInt() { return Integer.parseInt(next()); } int[] nextIntArray(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = nextInt(); } return arr; } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["1 2 1 2"]
2 seconds
["0.666666666667"]
null
Java 7
standard input
[ "probabilities", "math" ]
7b932b2d3ab65a353b18d81cf533a54e
A single line contains four integers .
1,300
Print a single real number, the probability that SmallR will win the match. The answer will be considered correct if the absolute or relative error doesn't exceed 10 - 6.
standard output
PASSED
db6edcafb9a6792b76de6747b7518a34
train_000.jsonl
1369582200
SmallR is an archer. SmallR is taking a match of archer with Zanoes. They try to shoot in the target in turns, and SmallR shoots first. The probability of shooting the target each time is for SmallR while for Zanoes. The one who shoots in the target first should be the winner.Output the probability that SmallR will win the match.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.math.BigDecimal; import java.math.MathContext; import java.math.RoundingMode; import java.util.Arrays; import java.util.Scanner; public class Main { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringBuilder out = new StringBuilder(); int a = sc.nextInt(); int b = sc.nextInt(); int c = sc.nextInt(); int d = sc.nextInt(); double ans = 0; double res = (a *1.0)/b; double se = (c *1.0)/d; double fe = (a *1.0)/b; double th = (1-res) * (1 - se); while(Math.abs(ans - res) > 10e-10 ){ ans = res; res += th * (a *1.0)/b; th *= (1-fe) * (1 - se); } System.out.println(res); } }
Java
["1 2 1 2"]
2 seconds
["0.666666666667"]
null
Java 7
standard input
[ "probabilities", "math" ]
7b932b2d3ab65a353b18d81cf533a54e
A single line contains four integers .
1,300
Print a single real number, the probability that SmallR will win the match. The answer will be considered correct if the absolute or relative error doesn't exceed 10 - 6.
standard output
PASSED
4536ca4018a0181c9584175865a15027
train_000.jsonl
1369582200
SmallR is an archer. SmallR is taking a match of archer with Zanoes. They try to shoot in the target in turns, and SmallR shoots first. The probability of shooting the target each time is for SmallR while for Zanoes. The one who shoots in the target first should be the winner.Output the probability that SmallR will win the match.
256 megabytes
import java.io.*; import java.util.*; public final class archery { static BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); static FastScanner sc=new FastScanner(br); static PrintWriter out=new PrintWriter(System.out); public static void main(String args[]) throws Exception { double a=sc.nextDouble(),b=sc.nextDouble(),c=sc.nextDouble(),d=sc.nextDouble(),res=0; for(int i=1;i<=10000;i++) { double val1=(Math.pow(1-(a/b),i-1))*Math.pow(1-(c/d),i-1)*(a/b); res+=val1; } out.printf("%.12f\n",res); out.close(); } } 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 String next() throws Exception { return nextToken().toString(); } 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
["1 2 1 2"]
2 seconds
["0.666666666667"]
null
Java 7
standard input
[ "probabilities", "math" ]
7b932b2d3ab65a353b18d81cf533a54e
A single line contains four integers .
1,300
Print a single real number, the probability that SmallR will win the match. The answer will be considered correct if the absolute or relative error doesn't exceed 10 - 6.
standard output
PASSED
5aeffc9ecc9f9675d097837ff2a575a0
train_000.jsonl
1369582200
SmallR is an archer. SmallR is taking a match of archer with Zanoes. They try to shoot in the target in turns, and SmallR shoots first. The probability of shooting the target each time is for SmallR while for Zanoes. The one who shoots in the target first should be the winner.Output the probability that SmallR will win the match.
256 megabytes
import java.math.*; import java.util.*; public class CF { public static void main(String[] args) { Scanner in = new Scanner(System.in); double SmallR = (double)in.nextInt()/in.nextInt(); double Zanoes = (double)in.nextInt()/in.nextInt(); System.out.print((SmallR) / (1 - (1- SmallR)*(1 - Zanoes))); } }
Java
["1 2 1 2"]
2 seconds
["0.666666666667"]
null
Java 7
standard input
[ "probabilities", "math" ]
7b932b2d3ab65a353b18d81cf533a54e
A single line contains four integers .
1,300
Print a single real number, the probability that SmallR will win the match. The answer will be considered correct if the absolute or relative error doesn't exceed 10 - 6.
standard output
PASSED
4bded0ed566e27ee7b37c0801f2b6eec
train_000.jsonl
1369582200
SmallR is an archer. SmallR is taking a match of archer with Zanoes. They try to shoot in the target in turns, and SmallR shoots first. The probability of shooting the target each time is for SmallR while for Zanoes. The one who shoots in the target first should be the winner.Output the probability that SmallR will win the match.
256 megabytes
import java.io.*; import java.util.*; public class cf185B { public static void main(String[] args) throws Exception { // BufferedReader in = new BufferedReader(new FileReader("cf185B.in")); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String[] arr = in.readLine().split(" "); int[] nums = new int[arr.length]; for(int i = 0; i < nums.length; i++) { nums[i] = Integer.parseInt(arr[i]); } double p1 = (double) nums[0] / nums[1]; double p2 = (double) nums[2] / nums[3]; System.out.printf("%.11f%n", p1 / (1 - (1 - p1) * (1 - p2))); } }
Java
["1 2 1 2"]
2 seconds
["0.666666666667"]
null
Java 7
standard input
[ "probabilities", "math" ]
7b932b2d3ab65a353b18d81cf533a54e
A single line contains four integers .
1,300
Print a single real number, the probability that SmallR will win the match. The answer will be considered correct if the absolute or relative error doesn't exceed 10 - 6.
standard output
PASSED
f2fb16cfd0cc88e5e5e83abfa2e50921
train_000.jsonl
1369582200
SmallR is an archer. SmallR is taking a match of archer with Zanoes. They try to shoot in the target in turns, and SmallR shoots first. The probability of shooting the target each time is for SmallR while for Zanoes. The one who shoots in the target first should be the winner.Output the probability that SmallR will win the match.
256 megabytes
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); double a, b, c, d; a = sc.nextInt(); b = sc.nextInt(); c = sc.nextInt(); d = sc.nextInt(); System.out.print(a/b * (1/(a/b + c/d - a*c/b/d))); } }
Java
["1 2 1 2"]
2 seconds
["0.666666666667"]
null
Java 7
standard input
[ "probabilities", "math" ]
7b932b2d3ab65a353b18d81cf533a54e
A single line contains four integers .
1,300
Print a single real number, the probability that SmallR will win the match. The answer will be considered correct if the absolute or relative error doesn't exceed 10 - 6.
standard output
PASSED
8d5b4e50dccad73971b43992f2f4e567
train_000.jsonl
1369582200
SmallR is an archer. SmallR is taking a match of archer with Zanoes. They try to shoot in the target in turns, and SmallR shoots first. The probability of shooting the target each time is for SmallR while for Zanoes. The one who shoots in the target first should be the winner.Output the probability that SmallR will win the match.
256 megabytes
import java.util.*; public class temp { //static {System.out.println("hello");} public static void main(String args[]) { Scanner scn=new Scanner(System.in); int a=scn.nextInt(); int b=scn.nextInt(); int c=scn.nextInt(); int d=scn.nextInt(); double x=(a*1.0)/b; double y=(c*1.0)/d; System.out.println(x/(1-((1-x)*(1-y)))); } }
Java
["1 2 1 2"]
2 seconds
["0.666666666667"]
null
Java 7
standard input
[ "probabilities", "math" ]
7b932b2d3ab65a353b18d81cf533a54e
A single line contains four integers .
1,300
Print a single real number, the probability that SmallR will win the match. The answer will be considered correct if the absolute or relative error doesn't exceed 10 - 6.
standard output
PASSED
f9767ef58352d123b22fa5fa134d6570
train_000.jsonl
1369582200
SmallR is an archer. SmallR is taking a match of archer with Zanoes. They try to shoot in the target in turns, and SmallR shoots first. The probability of shooting the target each time is for SmallR while for Zanoes. The one who shoots in the target first should be the winner.Output the probability that SmallR will win the match.
256 megabytes
import static java.lang.System.*; import static java.lang.Math.*; import java.lang.reflect.Array; import java.util.*; import java.util.Map.Entry; public class B311 { public static Scanner sc=new Scanner(in); //public static Random sc=new Random(); final int mod=1000000007; void run() throws RuntimeException{ double a=sc.nextInt(),b=sc.nextInt(),c=sc.nextInt(),d=sc.nextInt(); ln((a*d)/(b*c+a*d-a*c)); } public static void main(String[] args) { new B311().run(); } //output lib static final String br=System.getProperty("line.separator"); static final String[] asep=new String[]{""," ",br,br+br}; static String str(boolean o){ return o?"YES":"NO"; } static <K,V> String str(Map<K, V> map){ StringBuilder sb=new StringBuilder(); boolean isFirst=true; for(Entry<K,V> set:map.entrySet()){ if(!isFirst)sb.append(br); sb.append(str(set.getKey())).append(":").append(str(set.getValue())); isFirst=false; } return sb.toString(); } static <E> String str(Collection<E> list){ StringBuilder sb=new StringBuilder(); boolean isFirst=true; for(E e:list){ if(!isFirst)sb.append(" "); sb.append(str(e)); isFirst=false; } return sb.toString(); } static String str(Object o){ int depth=_getArrayDepth(o); if(depth>0)return _strArray(o,depth); return o.toString(); } static int _getArrayDepth(Object o){ if(!o.getClass().isArray() || Array.getLength(o)==0) return 0; return 1+_getArrayDepth(Array.get(o,0)); } //depth ex A[10]…1 A[10][10]…2 exception A[0]…0 A[10][0]…1 A[0][0]…0 static String _strArray(Object o,int depth){ if(depth==0) return str(o); StringBuilder sb=new StringBuilder(); for(int i=0,len=Array.getLength(o);i<len;i++){ if(i!=0)sb.append(asep[depth]); sb.append(_strArray(Array.get(o,i),depth-1)); } return sb.toString(); } static void pr(Object... os){ boolean isFirst=true; for(Object o:os){ if(!isFirst)out.print(" "); out.print(o); isFirst=false; } } static void ln(){ out.println(); } static void ln(Object... os){ for(Object o:os){ pr(o);ln(); } } }
Java
["1 2 1 2"]
2 seconds
["0.666666666667"]
null
Java 7
standard input
[ "probabilities", "math" ]
7b932b2d3ab65a353b18d81cf533a54e
A single line contains four integers .
1,300
Print a single real number, the probability that SmallR will win the match. The answer will be considered correct if the absolute or relative error doesn't exceed 10 - 6.
standard output
PASSED
e1f05f3d7599d499b6c2d0ef2702512e
train_000.jsonl
1369582200
SmallR is an archer. SmallR is taking a match of archer with Zanoes. They try to shoot in the target in turns, and SmallR shoots first. The probability of shooting the target each time is for SmallR while for Zanoes. The one who shoots in the target first should be the winner.Output the probability that SmallR will win the match.
256 megabytes
import java.util.*; import java.io.*; import java.awt.Point; import java.math.BigDecimal; import java.math.BigInteger; import static java.lang.Math.*; // Solution is at the bottom of code public class B implements Runnable{ final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null; BufferedReader in; OutputWriter out; StringTokenizer tok = new StringTokenizer(""); public static void main(String[] args){ new Thread(null, new B(), "", 128 * (1L << 20)).start(); } ///////////////////////////////////////////////////////////////////// void init() throws FileNotFoundException{ Locale.setDefault(Locale.US); if (ONLINE_JUDGE){ in = new BufferedReader(new InputStreamReader(System.in)); out = new OutputWriter(System.out); }else{ in = new BufferedReader(new FileReader("input.txt")); out = new OutputWriter("output.txt"); } } //////////////////////////////////////////////////////////////// long timeBegin, timeEnd; void time(){ timeEnd = System.currentTimeMillis(); System.err.println("Time = " + (timeEnd - timeBegin)); } void debug(Object... objects){ if (ONLINE_JUDGE){ for (Object o: objects){ System.err.println(o.toString()); } } } ///////////////////////////////////////////////////////////////////// public void run(){ try{ timeBegin = System.currentTimeMillis(); Locale.setDefault(Locale.US); init(); solve(); out.close(); time(); }catch (Exception e){ e.printStackTrace(System.err); System.exit(-1); } } ///////////////////////////////////////////////////////////////////// String delim = " "; String readString() throws IOException{ while(!tok.hasMoreTokens()){ try{ tok = new StringTokenizer(in.readLine()); }catch (Exception e){ return null; } } return tok.nextToken(delim); } String readLine() throws IOException{ return in.readLine(); } ///////////////////////////////////////////////////////////////// final char NOT_A_SYMBOL = '\0'; char readChar() throws IOException{ int intValue = in.read(); if (intValue == -1){ return NOT_A_SYMBOL; } return (char) intValue; } char[] readCharArray() throws IOException{ return readLine().toCharArray(); } ///////////////////////////////////////////////////////////////// int readInt() throws IOException { return Integer.parseInt(readString()); } int[] readIntArray(int size) throws IOException { int[] array = new int[size]; for (int index = 0; index < size; ++index){ array[index] = readInt(); } return array; } int[] readIntArrayWithDecrease(int size) throws IOException { int[] array = readIntArray(size); for (int i = 0; i < size; ++i) { array[i]--; } return array; } /////////////////////////////////////////////////////////////////// long readLong() throws IOException{ return Long.parseLong(readString()); } long[] readLongArray(int size) throws IOException{ long[] array = new long[size]; for (int index = 0; index < size; ++index){ array[index] = readLong(); } return array; } //////////////////////////////////////////////////////////////////// double readDouble() throws IOException{ return Double.parseDouble(readString()); } double[] readDoubleArray(int size) throws IOException{ double[] array = new double[size]; for (int index = 0; index < size; ++index){ array[index] = readDouble(); } return array; } //////////////////////////////////////////////////////////////////// BigInteger readBigInteger() throws IOException { return new BigInteger(readString()); } BigDecimal readBigDecimal() throws IOException { return new BigDecimal(readString()); } ///////////////////////////////////////////////////////////////////// Point readPoint() throws IOException{ int x = readInt(); int y = readInt(); return new Point(x, y); } Point[] readPointArray(int size) throws IOException{ Point[] array = new Point[size]; for (int index = 0; index < size; ++index){ array[index] = readPoint(); } return array; } ///////////////////////////////////////////////////////////////////// List<Integer>[] readGraph(int vertexNumber, int edgeNumber) throws IOException{ @SuppressWarnings("unchecked") List<Integer>[] graph = new List[vertexNumber]; for (int index = 0; index < vertexNumber; ++index){ graph[index] = new ArrayList<Integer>(); } while (edgeNumber-- > 0){ int from = readInt() - 1; int to = readInt() - 1; graph[from].add(to); graph[to].add(from); } return graph; } ///////////////////////////////////////////////////////////////////// static class IntIndexPair { static Comparator<IntIndexPair> increaseComparator = new Comparator<B.IntIndexPair>() { @Override public int compare(IntIndexPair indexPair1, IntIndexPair indexPair2) { int value1 = indexPair1.value; int value2 = indexPair2.value; if (value1 != value2) return value1 - value2; int index1 = indexPair1.index; int index2 = indexPair2.index; return index1 - index2; } }; static Comparator<IntIndexPair> decreaseComparator = new Comparator<B.IntIndexPair>() { @Override public int compare(IntIndexPair indexPair1, IntIndexPair indexPair2) { int value1 = indexPair1.value; int value2 = indexPair2.value; if (value1 != value2) return -(value1 - value2); int index1 = indexPair1.index; int index2 = indexPair2.index; return index1 - index2; } }; int value, index; public IntIndexPair(int value, int index) { super(); this.value = value; this.index = index; } public int getRealIndex() { return index + 1; } } IntIndexPair[] readIntIndexArray(int size) throws IOException { IntIndexPair[] array = new IntIndexPair[size]; for (int index = 0; index < size; ++index) { array[index] = new IntIndexPair(readInt(), index); } return array; } ///////////////////////////////////////////////////////////////////// static class OutputWriter extends PrintWriter{ final int DEFAULT_PRECISION = 12; int precision; String format, formatWithSpace; { precision = DEFAULT_PRECISION; format = createFormat(precision); formatWithSpace = format + " "; } public OutputWriter(OutputStream out) { super(out); } public OutputWriter(String fileName) throws FileNotFoundException { super(fileName); } public int getPrecision() { return precision; } public void setPrecision(int precision) { precision = max(0, precision); this.precision = precision; format = createFormat(precision); formatWithSpace = format + " "; } private String createFormat(int precision){ return "%." + precision + "f"; } @Override public void print(double d){ printf(format, d); } public void printWithSpace(double d){ printf(formatWithSpace, d); } public void printAll(double...d){ for (int i = 0; i < d.length - 1; ++i){ printWithSpace(d[i]); } print(d[d.length - 1]); } @Override public void println(double d){ printlnAll(d); } public void printlnAll(double... d){ printAll(d); println(); } } ///////////////////////////////////////////////////////////////////// int[][] steps = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; int[][] steps8 = { {-1, 0}, {1, 0}, {0, -1}, {0, 1}, {-1, -1}, {1, 1}, {1, -1}, {-1, 1} }; boolean check(int index, int lim){ return (0 <= index && index < lim); } ///////////////////////////////////////////////////////////////////// boolean checkBit(int mask, int bitNumber){ return (mask & (1 << bitNumber)) != 0; } ///////////////////////////////////////////////////////////////////// void solve() throws IOException { int a = readInt(); int b = readInt(); int c = readInt(); int d = readInt(); double ans = a * d; ans /= (a * d + b * c - a * c); out.println(ans); } }
Java
["1 2 1 2"]
2 seconds
["0.666666666667"]
null
Java 7
standard input
[ "probabilities", "math" ]
7b932b2d3ab65a353b18d81cf533a54e
A single line contains four integers .
1,300
Print a single real number, the probability that SmallR will win the match. The answer will be considered correct if the absolute or relative error doesn't exceed 10 - 6.
standard output
PASSED
23c4ecc77bdd95a559a057eb102b54cc
train_000.jsonl
1369582200
SmallR is an archer. SmallR is taking a match of archer with Zanoes. They try to shoot in the target in turns, and SmallR shoots first. The probability of shooting the target each time is for SmallR while for Zanoes. The one who shoots in the target first should be the winner.Output the probability that SmallR will win the match.
256 megabytes
import java.util.Scanner; public class Main2 { public static void main(String args[]){ Scanner input = new Scanner(System.in); double a = input.nextInt(); double b = input.nextInt(); double c = input.nextInt(); double d = input.nextInt(); System.out.println(sentence(a,b,c,d)); } public static double sentence(double a,double b,double c,double d){ int turn = 0; double sump = 0; double probable = 1; while(turn != 10000){ sump += probable*(a/b); probable *= (1-a/b); probable *= (1-c/d); turn++; } return sump; } }
Java
["1 2 1 2"]
2 seconds
["0.666666666667"]
null
Java 7
standard input
[ "probabilities", "math" ]
7b932b2d3ab65a353b18d81cf533a54e
A single line contains four integers .
1,300
Print a single real number, the probability that SmallR will win the match. The answer will be considered correct if the absolute or relative error doesn't exceed 10 - 6.
standard output
PASSED
f4941a16e5ffdaf64d23475e3a04bdd5
train_000.jsonl
1369582200
SmallR is an archer. SmallR is taking a match of archer with Zanoes. They try to shoot in the target in turns, and SmallR shoots first. The probability of shooting the target each time is for SmallR while for Zanoes. The one who shoots in the target first should be the winner.Output the probability that SmallR will win the match.
256 megabytes
import java.util.Scanner; public class Main { private static Scanner sc = new Scanner(System.in); public static void main(String[] args) { double a = sc.nextDouble(), b = sc.nextDouble(), c = sc.nextDouble(), d = sc.nextDouble(); double ab = a/b; double cd = c/d; System.out.println(ab/(1-(1-ab)*(1-cd))); } }
Java
["1 2 1 2"]
2 seconds
["0.666666666667"]
null
Java 7
standard input
[ "probabilities", "math" ]
7b932b2d3ab65a353b18d81cf533a54e
A single line contains four integers .
1,300
Print a single real number, the probability that SmallR will win the match. The answer will be considered correct if the absolute or relative error doesn't exceed 10 - 6.
standard output
PASSED
8ea513cf2142169996d59187a83d8644
train_000.jsonl
1369582200
SmallR is an archer. SmallR is taking a match of archer with Zanoes. They try to shoot in the target in turns, and SmallR shoots first. The probability of shooting the target each time is for SmallR while for Zanoes. The one who shoots in the target first should be the winner.Output the probability that SmallR will win the match.
256 megabytes
import java.util.Locale; import java.util.Scanner; public class ArchersSolver { private int a; private int b; private int c; private int d; public static void main(String[] args) { ArchersSolver solver = new ArchersSolver(); solver.readData(); double solution = solver.solve(); solver.print(solution); } private void print(double value) { System.out.printf(Locale.ENGLISH, "%.10f", value); } private void readData() { Scanner scanner = new Scanner(System.in); a = scanner.nextInt(); b = scanner.nextInt(); c = scanner.nextInt(); d = scanner.nextInt(); } private double solve() { return a * d / ((double) a * d + b * c - a * c); } }
Java
["1 2 1 2"]
2 seconds
["0.666666666667"]
null
Java 7
standard input
[ "probabilities", "math" ]
7b932b2d3ab65a353b18d81cf533a54e
A single line contains four integers .
1,300
Print a single real number, the probability that SmallR will win the match. The answer will be considered correct if the absolute or relative error doesn't exceed 10 - 6.
standard output
PASSED
73aa64b0085fc4961004506da96d79f0
train_000.jsonl
1369582200
SmallR is an archer. SmallR is taking a match of archer with Zanoes. They try to shoot in the target in turns, and SmallR shoots first. The probability of shooting the target each time is for SmallR while for Zanoes. The one who shoots in the target first should be the winner.Output the probability that SmallR will win the match.
256 megabytes
import static java.lang.Double.parseDouble; import static java.lang.Integer.parseInt; import static java.lang.Long.parseLong; import static java.lang.System.exit; import static java.util.Arrays.fill; import java.io.*; import java.util.*; import java.math.*; import java.lang.*; import java.text.*; public class Main { static BufferedReader in; static PrintWriter out; static StringTokenizer tok; final static double EPS = 1e-12; final static int MOD = 1000000009; static void solve() throws Exception { int a = nextInt(); int b = nextInt(); int c = nextInt(); int d = nextInt(); double p1 = a/(double)b; double q1 = 1 - p1; double p2 = c/(double)d; double q2 = 1 - p2; double sum = p1; double res = 0; while (Math.abs(sum) > EPS) { res += sum; sum *= q1*q2; } out.println(res); } static long sqr(long x) { return x*x; } static int nextInt() throws IOException { return parseInt(next()); } static long nextLong() throws IOException { return parseLong(next()); } static double nextDouble() throws IOException { return parseDouble(next()); } static BigInteger nextBigInteger() throws IOException { return new BigInteger(next()); } static String next() throws IOException { while (tok == null || !tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); } return tok.nextToken(); } public static void main(String args[]) { try { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(new OutputStreamWriter(System.out)); solve(); in.close(); out.close(); } catch (Throwable e) { e.printStackTrace(); exit(1); } } }
Java
["1 2 1 2"]
2 seconds
["0.666666666667"]
null
Java 7
standard input
[ "probabilities", "math" ]
7b932b2d3ab65a353b18d81cf533a54e
A single line contains four integers .
1,300
Print a single real number, the probability that SmallR will win the match. The answer will be considered correct if the absolute or relative error doesn't exceed 10 - 6.
standard output
PASSED
3f8bae68ae97364ab72c3990bb328712
train_000.jsonl
1369582200
SmallR is an archer. SmallR is taking a match of archer with Zanoes. They try to shoot in the target in turns, and SmallR shoots first. The probability of shooting the target each time is for SmallR while for Zanoes. The one who shoots in the target first should be the winner.Output the probability that SmallR will win the match.
256 megabytes
import java.util.Scanner; public class Probability { public static void main(String args[]) { Scanner scanner = new Scanner(System.in); int a = scanner.nextInt(); int b = scanner.nextInt(); int c = scanner.nextInt(); int d = scanner.nextInt(); double r = (1.0 - ((a * 1.0) / b)) * (1.0 - ((c * 1.0) / d)); System.out.printf("%.12f", ((a * 1.0) / (b)) * (1.0 / (1.0 - r))); } }
Java
["1 2 1 2"]
2 seconds
["0.666666666667"]
null
Java 7
standard input
[ "probabilities", "math" ]
7b932b2d3ab65a353b18d81cf533a54e
A single line contains four integers .
1,300
Print a single real number, the probability that SmallR will win the match. The answer will be considered correct if the absolute or relative error doesn't exceed 10 - 6.
standard output
PASSED
ad6f395bb45ca53e2581420bab1715d1
train_000.jsonl
1369582200
SmallR is an archer. SmallR is taking a match of archer with Zanoes. They try to shoot in the target in turns, and SmallR shoots first. The probability of shooting the target each time is for SmallR while for Zanoes. The one who shoots in the target first should be the winner.Output the probability that SmallR will win the match.
256 megabytes
import java.io.*; import java.util.*; import javax.swing.plaf.multi.MultiSeparatorUI; public class Main{ static BufferedReader in; static StringTokenizer stk; static PrintWriter out; static void initio() throws Exception{ in=new BufferedReader(new InputStreamReader(System.in)); out=new PrintWriter(System.out); } static void initiot() throws Exception{ in=new BufferedReader(new FileReader("test")); out=new PrintWriter(new File("outtest")); // out=new PrintWriter(System.out); } static int Int() throws Exception{ int ch,x,s=1; for(ch=in.read();ch<'0'&&ch!=-1&&ch!='-'||ch>'9';ch=in.read()); if(ch==-1) return -1; else if(ch=='-'){ s=-1; ch=in.read(); } for(x=0,ch-='0';ch>=0&&ch<=9;x=x*10+ch,ch=in.read()-'0'); return x*s; } static String next() throws Exception{ while(stk==null||!stk.hasMoreTokens()) stk=new StringTokenizer(in.readLine()); return stk.nextToken(); } static int nextInt() throws Exception{ return Integer.parseInt(next()); } public static void main(String[] args) throws Exception{ initio(); double a=Int(),b=Int(),c=Int(),d=Int(); out.println(a*d/(b*d-(b-a)*(d-c))); out.close(); } }
Java
["1 2 1 2"]
2 seconds
["0.666666666667"]
null
Java 7
standard input
[ "probabilities", "math" ]
7b932b2d3ab65a353b18d81cf533a54e
A single line contains four integers .
1,300
Print a single real number, the probability that SmallR will win the match. The answer will be considered correct if the absolute or relative error doesn't exceed 10 - 6.
standard output
PASSED
fcff374ba070710ac2f24653d7551fd0
train_000.jsonl
1369582200
SmallR is an archer. SmallR is taking a match of archer with Zanoes. They try to shoot in the target in turns, and SmallR shoots first. The probability of shooting the target each time is for SmallR while for Zanoes. The one who shoots in the target first should be the winner.Output the probability that SmallR will win the match.
256 megabytes
import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.math.BigDecimal; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.Scanner; public class template { public static ArrayList<Integer> strToInts(String str, String token) { ArrayList<Integer> result = new ArrayList<>(); ArrayList<String> strs = new ArrayList<>(Arrays.asList(str.split(token))); for (String string : strs) { result.add(Integer.parseInt(string)); } return result; } public static void main(String[] args) throws IOException { // The input and output streams BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); // system //BufferedReader in = new BufferedReader(new FileReader("input.txt")); // File BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out)); ArrayList<Integer> params = strToInts(in.readLine(), " "); double hitA = (double)params.get(0) / params.get(1); double hitB = (double) params.get(2) / params.get(3); double win = hitA; double newRound = (1 - hitA) * (1-hitB); int i = 0; while (true) { double newWin = newRound* (hitA); double newNewRound = newRound * (1 - hitA) * (1-hitB); newRound = newNewRound; if (newWin < 0.000000000001) { break; } else i++; win += newWin; } System.out.println(win); } }
Java
["1 2 1 2"]
2 seconds
["0.666666666667"]
null
Java 7
standard input
[ "probabilities", "math" ]
7b932b2d3ab65a353b18d81cf533a54e
A single line contains four integers .
1,300
Print a single real number, the probability that SmallR will win the match. The answer will be considered correct if the absolute or relative error doesn't exceed 10 - 6.
standard output
PASSED
16e0016fbabc359a0793f2b58b33e34f
train_000.jsonl
1369582200
SmallR is an archer. SmallR is taking a match of archer with Zanoes. They try to shoot in the target in turns, and SmallR shoots first. The probability of shooting the target each time is for SmallR while for Zanoes. The one who shoots in the target first should be the winner.Output the probability that SmallR will win the match.
256 megabytes
import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.math.BigDecimal; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.Scanner; public class template { public static ArrayList<Integer> strToInts(String str, String token) { ArrayList<Integer> result = new ArrayList<>(); ArrayList<String> strs = new ArrayList<>(Arrays.asList(str.split(token))); for (String string : strs) { result.add(Integer.parseInt(string)); } return result; } public static void main(String[] args) throws IOException { // The input and output streams BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); // system //BufferedReader in = new BufferedReader(new FileReader("input.txt")); // File BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out)); ArrayList<Integer> params = strToInts(in.readLine(), " "); double hitA = (double)params.get(0) / params.get(1); double hitB = (double) params.get(2) / params.get(3); double win = hitA; double newRound = (1 - hitA) * (1-hitB); int i = 0; while (true) { double newWin = newRound* (hitA); double newNewRound = newRound * (1 - hitA) * (1-hitB); newRound = newNewRound; if (newWin < 0.0000000001) { break; } else i++; win += newWin; } System.out.println(win); } }
Java
["1 2 1 2"]
2 seconds
["0.666666666667"]
null
Java 7
standard input
[ "probabilities", "math" ]
7b932b2d3ab65a353b18d81cf533a54e
A single line contains four integers .
1,300
Print a single real number, the probability that SmallR will win the match. The answer will be considered correct if the absolute or relative error doesn't exceed 10 - 6.
standard output
PASSED
00edf8a10cd7b7e5050a2e5ed684fec2
train_000.jsonl
1369582200
SmallR is an archer. SmallR is taking a match of archer with Zanoes. They try to shoot in the target in turns, and SmallR shoots first. The probability of shooting the target each time is for SmallR while for Zanoes. The one who shoots in the target first should be the winner.Output the probability that SmallR will win the match.
256 megabytes
import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.math.BigDecimal; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.Scanner; public class template { public static ArrayList<Integer> strToInts(String str, String token) { ArrayList<Integer> result = new ArrayList<>(); ArrayList<String> strs = new ArrayList<>(Arrays.asList(str.split(token))); for (String string : strs) { result.add(Integer.parseInt(string)); } return result; } public static void main(String[] args) throws IOException { // The input and output streams BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); // system //BufferedReader in = new BufferedReader(new FileReader("input.txt")); // File BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out)); ArrayList<Integer> params = strToInts(in.readLine(), " "); double hitA = (double)params.get(0) / params.get(1); double hitB = (double) params.get(2) / params.get(3); double win = hitA; double newRound = (1 - hitA) * (1-hitB); int i = 0; while (true) { double newWin = newRound* (hitA); double newNewRound = newRound * (1 - hitA) * (1-hitB); newRound = newNewRound; if (i > 10000) { break; } else i++; win += newWin; } System.out.println(win); } }
Java
["1 2 1 2"]
2 seconds
["0.666666666667"]
null
Java 7
standard input
[ "probabilities", "math" ]
7b932b2d3ab65a353b18d81cf533a54e
A single line contains four integers .
1,300
Print a single real number, the probability that SmallR will win the match. The answer will be considered correct if the absolute or relative error doesn't exceed 10 - 6.
standard output
PASSED
caa8872934779935973337544d9f6996
train_000.jsonl
1369582200
SmallR is an archer. SmallR is taking a match of archer with Zanoes. They try to shoot in the target in turns, and SmallR shoots first. The probability of shooting the target each time is for SmallR while for Zanoes. The one who shoots in the target first should be the winner.Output the probability that SmallR will win the match.
256 megabytes
import java.io.*; import java.util.*; public class B { void run() throws IOException { double s = (double) ni() / (double) ni(), z = (double) ni() / (double) ni(); double p = 1; double ns = 1 - s; double nz = 1 - z; double tns = ns, tnz = nz; for (int i = 0; i < 100000; i++) { p += ns * nz; ns *= tns; nz *= tnz; } pw.print(p * s); } int[] na(int a_len) throws IOException { int[] _a = new int[a_len]; for (int i = 0; i < a_len; i++) _a[i] = ni(); return _a; } int[][] nm(int a_len, int a_hei) throws IOException { int[][] _a = new int[a_len][a_hei]; for (int i = 0; i < a_len; i++) for (int j = 0; j < a_hei; j++) _a[i][j] = ni(); return _a; } String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } int ni() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } String nl() throws IOException { return br.readLine(); } void tr(String debug) { if (!OJ) pw.println(" " + debug); } static PrintWriter pw; static BufferedReader br; static StringTokenizer st; static boolean OJ; public static void main(String[] args) throws IOException { long timeout = System.currentTimeMillis(); OJ = System.getProperty("ONLINE_JUDGE") != null; pw = new PrintWriter(System.out); br = new BufferedReader(OJ ? new InputStreamReader(System.in) : new FileReader(new File("B.txt"))); while (br.ready()) new B().run(); if (!OJ) { pw.println(); pw.println(System.currentTimeMillis() - timeout); } br.close(); pw.close(); } }
Java
["1 2 1 2"]
2 seconds
["0.666666666667"]
null
Java 7
standard input
[ "probabilities", "math" ]
7b932b2d3ab65a353b18d81cf533a54e
A single line contains four integers .
1,300
Print a single real number, the probability that SmallR will win the match. The answer will be considered correct if the absolute or relative error doesn't exceed 10 - 6.
standard output
PASSED
30fab3d74a34c5c34772aa32aee0230a
train_000.jsonl
1369582200
SmallR is an archer. SmallR is taking a match of archer with Zanoes. They try to shoot in the target in turns, and SmallR shoots first. The probability of shooting the target each time is for SmallR while for Zanoes. The one who shoots in the target first should be the winner.Output the probability that SmallR will win the match.
256 megabytes
import java.util.Scanner; public class BArcher { public static void main(String[] args) { Scanner k = new Scanner(System.in); double a,b,c,d,r1,r2; a=k.nextDouble(); b=k.nextDouble(); c=k.nextDouble(); d=k.nextDouble(); r1=a/b; r2=c/d; r1/=(1-((1-r1)*(1-r2))); System.out.println(r1); } }
Java
["1 2 1 2"]
2 seconds
["0.666666666667"]
null
Java 7
standard input
[ "probabilities", "math" ]
7b932b2d3ab65a353b18d81cf533a54e
A single line contains four integers .
1,300
Print a single real number, the probability that SmallR will win the match. The answer will be considered correct if the absolute or relative error doesn't exceed 10 - 6.
standard output
PASSED
c1d4ad1d595bde58ddeacd9bf11b57d6
train_000.jsonl
1369582200
SmallR is an archer. SmallR is taking a match of archer with Zanoes. They try to shoot in the target in turns, and SmallR shoots first. The probability of shooting the target each time is for SmallR while for Zanoes. The one who shoots in the target first should be the winner.Output the probability that SmallR will win the match.
256 megabytes
import java.io.IOException; import java.io.OutputStreamWriter; import java.util.Arrays; import java.io.BufferedWriter; import java.util.InputMismatchException; import java.io.OutputStream; import java.io.PrintWriter; import java.io.Writer; import java.util.StringTokenizer; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author saket */ 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); Archer solver = new Archer(); solver.solve(1, in, out); out.close(); } } class Archer { public void solve(int testNumber, InputReader in, OutputWriter out) { double a=in.readDouble(); double b=in.readDouble(); double c=in.readDouble(); double d=in.readDouble(); double small=a/b; double za=(1-a/b)*(1-c/d); double ans=small/(1-za); out.printLine(ans); } } class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public double readDouble() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } double res = 0; while (!isSpaceChar(c) && c != '.') { if (c == 'e' || c == 'E') return res * Math.pow(10, readInt()); if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } if (c == '.') { c = read(); double m = 1; while (!isSpaceChar(c)) { if (c == 'e' || c == 'E') return res * Math.pow(10, readInt()); if (c < '0' || c > '9') throw new InputMismatchException(); m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } public boolean 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); } } class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.print(objects[i]); } } public void printLine(Object... objects) { print(objects); writer.println(); } public void close() { writer.close(); } }
Java
["1 2 1 2"]
2 seconds
["0.666666666667"]
null
Java 7
standard input
[ "probabilities", "math" ]
7b932b2d3ab65a353b18d81cf533a54e
A single line contains four integers .
1,300
Print a single real number, the probability that SmallR will win the match. The answer will be considered correct if the absolute or relative error doesn't exceed 10 - 6.
standard output
PASSED
3f9e99f05b5cc8da0fb34d103e9ee774
train_000.jsonl
1369582200
SmallR is an archer. SmallR is taking a match of archer with Zanoes. They try to shoot in the target in turns, and SmallR shoots first. The probability of shooting the target each time is for SmallR while for Zanoes. The one who shoots in the target first should be the winner.Output the probability that SmallR will win the match.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class archer { public static void main(String[] args) throws Exception { BufferedReader r = new BufferedReader(new InputStreamReader(System.in)); PrintWriter w = new PrintWriter(System.out); StringTokenizer st = new StringTokenizer(r.readLine()); double smallr = (double) Integer.parseInt(st.nextToken()) / Integer.parseInt(st.nextToken()); double zanoes = (double) Integer.parseInt(st.nextToken()) / Integer.parseInt(st.nextToken()); //answer is infinite sum of smallr + (1 - smallr) * (1 - zanoes) * smallr + smallr * (1 - zanoes) * smallr * (1 - zanoes) * smallr ..... double q = (1 - smallr) * (1 - zanoes); //q is the ratio between terms //smallr = a, start term double answer = smallr/(1 - q); System.out.println(answer); } }
Java
["1 2 1 2"]
2 seconds
["0.666666666667"]
null
Java 7
standard input
[ "probabilities", "math" ]
7b932b2d3ab65a353b18d81cf533a54e
A single line contains four integers .
1,300
Print a single real number, the probability that SmallR will win the match. The answer will be considered correct if the absolute or relative error doesn't exceed 10 - 6.
standard output
PASSED
79cb2aea2300cf1457a23e0d07fbd156
train_000.jsonl
1369582200
SmallR is an archer. SmallR is taking a match of archer with Zanoes. They try to shoot in the target in turns, and SmallR shoots first. The probability of shooting the target each time is for SmallR while for Zanoes. The one who shoots in the target first should be the winner.Output the probability that SmallR will win the match.
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; import java.util.Map.Entry; 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); //Scanner in = new Scanner(new FileReader("input.txt")); //PrintWriter out = new PrintWriter("output.txt"); double a = in.nextInt(); double b = in.nextInt(); double c = in.nextInt(); double d = in.nextInt(); double res = a * d / (b * d - (b - a) * (d - c)); out.println(res); out.close(); } class Unit { public int num; public int type; public Unit(int num, int type) { super(); this.num = num; this.type = type; } @Override public boolean equals(Object obj) { Unit u = (Unit) obj; return num == u.num && type == u.type; } } 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
["1 2 1 2"]
2 seconds
["0.666666666667"]
null
Java 7
standard input
[ "probabilities", "math" ]
7b932b2d3ab65a353b18d81cf533a54e
A single line contains four integers .
1,300
Print a single real number, the probability that SmallR will win the match. The answer will be considered correct if the absolute or relative error doesn't exceed 10 - 6.
standard output