exec_outcome
stringclasses
1 value
code_uid
stringlengths
32
32
file_name
stringclasses
111 values
prob_desc_created_at
stringlengths
10
10
prob_desc_description
stringlengths
63
3.8k
prob_desc_memory_limit
stringclasses
18 values
source_code
stringlengths
117
65.5k
lang_cluster
stringclasses
1 value
prob_desc_sample_inputs
stringlengths
2
802
prob_desc_time_limit
stringclasses
27 values
prob_desc_sample_outputs
stringlengths
2
796
prob_desc_notes
stringlengths
4
3k
lang
stringclasses
5 values
prob_desc_input_from
stringclasses
3 values
tags
listlengths
0
11
src_uid
stringlengths
32
32
prob_desc_input_spec
stringlengths
28
2.37k
difficulty
int64
-1
3.5k
prob_desc_output_spec
stringlengths
17
1.47k
prob_desc_output_to
stringclasses
3 values
hidden_unit_tests
stringclasses
1 value
PASSED
159cf74be849e5abf38d419d6ac524e5
train_108.jsonl
1635518100
Berland State University has received a new update for the operating system. Initially it is installed only on the $$$1$$$-st computer.Update files should be copied to all $$$n$$$ computers. The computers are not connected to the internet, so the only way to transfer update files from one computer to another is to copy them using a patch cable (a cable connecting two computers directly). Only one patch cable can be connected to a computer at a time. Thus, from any computer where the update files are installed, they can be copied to some other computer in exactly one hour.Your task is to find the minimum number of hours required to copy the update files to all $$$n$$$ computers if there are only $$$k$$$ patch cables in Berland State University.
256 megabytes
import java.util.Scanner; public class codeforcesround<n> { public static Scanner read = new Scanner(System.in); public static void main(String[] args) { int t = Integer.parseInt(read.nextLine().trim()); while (t-- > 0) { solve(); } } private static void solve() { long n = read.nextLong(); n -= 1; long k = read.nextLong(); long c = 1; long moves = 0; while (c<= k) { moves++; n-=c; c*=2; if (n<=0) break; } moves = moves+(n+k-1)/k; System.out.println(moves); } }
Java
["4\n8 3\n6 6\n7 1\n1 1"]
2 seconds
["4\n3\n6\n0"]
NoteLet's consider the test cases of the example: $$$n=8$$$, $$$k=3$$$: during the first hour, we copy the update files from the computer $$$1$$$ to the computer $$$2$$$; during the second hour, we copy the update files from the computer $$$1$$$ to the computer $$$3$$$, and from the computer $$$2$$$ to the computer $$$4$$$; during the third hour, we copy the update files from the computer $$$1$$$ to the computer $$$5$$$, from the computer $$$2$$$ to the computer $$$6$$$, and from the computer $$$3$$$ to the computer $$$7$$$; during the fourth hour, we copy the update files from the computer $$$2$$$ to the computer $$$8$$$. $$$n=6$$$, $$$k=6$$$: during the first hour, we copy the update files from the computer $$$1$$$ to the computer $$$2$$$; during the second hour, we copy the update files from the computer $$$1$$$ to the computer $$$3$$$, and from the computer $$$2$$$ to the computer $$$4$$$; during the third hour, we copy the update files from the computer $$$1$$$ to the computer $$$5$$$, and from the computer $$$2$$$ to the computer $$$6$$$. $$$n=7$$$, $$$k=1$$$: during the first hour, we copy the update files from the computer $$$1$$$ to the computer $$$2$$$; during the second hour, we copy the update files from the computer $$$1$$$ to the computer $$$3$$$; during the third hour, we copy the update files from the computer $$$1$$$ to the computer $$$4$$$; during the fourth hour, we copy the update files from the computer $$$4$$$ to the computer $$$5$$$; during the fifth hour, we copy the update files from the computer $$$4$$$ to the computer $$$6$$$; during the sixth hour, we copy the update files from the computer $$$3$$$ to the computer $$$7$$$.
Java 11
standard input
[ "greedy", "implementation", "math" ]
5df6eb50ead22b498bea69bb84341c06
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^5$$$) — the number of test cases. Each test case consists of a single line that contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 10^{18}$$$) — the number of computers and the number of patch cables.
1,100
For each test case print one integer — the minimum number of hours required to copy the update files to all $$$n$$$ computers.
standard output
PASSED
99332b68b1b04397546d57ff837424b5
train_108.jsonl
1635518100
Berland State University has received a new update for the operating system. Initially it is installed only on the $$$1$$$-st computer.Update files should be copied to all $$$n$$$ computers. The computers are not connected to the internet, so the only way to transfer update files from one computer to another is to copy them using a patch cable (a cable connecting two computers directly). Only one patch cable can be connected to a computer at a time. Thus, from any computer where the update files are installed, they can be copied to some other computer in exactly one hour.Your task is to find the minimum number of hours required to copy the update files to all $$$n$$$ computers if there are only $$$k$$$ patch cables in Berland State University.
256 megabytes
import java.util.*; public class updateFiles { public static void main(String args[]) { Scanner scan = new Scanner(System.in); int t = scan.nextInt(); while(t-- > 0) { long ncm = scan.nextLong(); long ncb = scan.nextLong(); long cm = 1L, cb = 1L, h = 0L; while(cm < ncm) { h += 1; cm += cb; if(cb < ncb) cb = Math.min(cb + cb, ncb); else { long temp = (ncm - cm) / cb; h += temp; cm += (temp * cb); } } System.out.println(h); } } }
Java
["4\n8 3\n6 6\n7 1\n1 1"]
2 seconds
["4\n3\n6\n0"]
NoteLet's consider the test cases of the example: $$$n=8$$$, $$$k=3$$$: during the first hour, we copy the update files from the computer $$$1$$$ to the computer $$$2$$$; during the second hour, we copy the update files from the computer $$$1$$$ to the computer $$$3$$$, and from the computer $$$2$$$ to the computer $$$4$$$; during the third hour, we copy the update files from the computer $$$1$$$ to the computer $$$5$$$, from the computer $$$2$$$ to the computer $$$6$$$, and from the computer $$$3$$$ to the computer $$$7$$$; during the fourth hour, we copy the update files from the computer $$$2$$$ to the computer $$$8$$$. $$$n=6$$$, $$$k=6$$$: during the first hour, we copy the update files from the computer $$$1$$$ to the computer $$$2$$$; during the second hour, we copy the update files from the computer $$$1$$$ to the computer $$$3$$$, and from the computer $$$2$$$ to the computer $$$4$$$; during the third hour, we copy the update files from the computer $$$1$$$ to the computer $$$5$$$, and from the computer $$$2$$$ to the computer $$$6$$$. $$$n=7$$$, $$$k=1$$$: during the first hour, we copy the update files from the computer $$$1$$$ to the computer $$$2$$$; during the second hour, we copy the update files from the computer $$$1$$$ to the computer $$$3$$$; during the third hour, we copy the update files from the computer $$$1$$$ to the computer $$$4$$$; during the fourth hour, we copy the update files from the computer $$$4$$$ to the computer $$$5$$$; during the fifth hour, we copy the update files from the computer $$$4$$$ to the computer $$$6$$$; during the sixth hour, we copy the update files from the computer $$$3$$$ to the computer $$$7$$$.
Java 11
standard input
[ "greedy", "implementation", "math" ]
5df6eb50ead22b498bea69bb84341c06
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^5$$$) — the number of test cases. Each test case consists of a single line that contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 10^{18}$$$) — the number of computers and the number of patch cables.
1,100
For each test case print one integer — the minimum number of hours required to copy the update files to all $$$n$$$ computers.
standard output
PASSED
195ae3129cd464abc910e86bdbfe68a3
train_108.jsonl
1635518100
Berland State University has received a new update for the operating system. Initially it is installed only on the $$$1$$$-st computer.Update files should be copied to all $$$n$$$ computers. The computers are not connected to the internet, so the only way to transfer update files from one computer to another is to copy them using a patch cable (a cable connecting two computers directly). Only one patch cable can be connected to a computer at a time. Thus, from any computer where the update files are installed, they can be copied to some other computer in exactly one hour.Your task is to find the minimum number of hours required to copy the update files to all $$$n$$$ computers if there are only $$$k$$$ patch cables in Berland State University.
256 megabytes
import java.io.PrintWriter; import java.util.Scanner; public class UpdateFiles { public static void main(String[] args) { Scanner sc = new Scanner(System.in); PrintWriter pw = new PrintWriter(System.out); int t = sc.nextInt(); for (int x = 0; x < t; x++) { long n = sc.nextLong(); long k = sc.nextLong(); long downloaded = 1; long time = 0; while (downloaded < k) { downloaded *= 2; time++; } if (downloaded < n) { time += (n - downloaded + k - 1) / k; } pw.println(time); } pw.close(); } }
Java
["4\n8 3\n6 6\n7 1\n1 1"]
2 seconds
["4\n3\n6\n0"]
NoteLet's consider the test cases of the example: $$$n=8$$$, $$$k=3$$$: during the first hour, we copy the update files from the computer $$$1$$$ to the computer $$$2$$$; during the second hour, we copy the update files from the computer $$$1$$$ to the computer $$$3$$$, and from the computer $$$2$$$ to the computer $$$4$$$; during the third hour, we copy the update files from the computer $$$1$$$ to the computer $$$5$$$, from the computer $$$2$$$ to the computer $$$6$$$, and from the computer $$$3$$$ to the computer $$$7$$$; during the fourth hour, we copy the update files from the computer $$$2$$$ to the computer $$$8$$$. $$$n=6$$$, $$$k=6$$$: during the first hour, we copy the update files from the computer $$$1$$$ to the computer $$$2$$$; during the second hour, we copy the update files from the computer $$$1$$$ to the computer $$$3$$$, and from the computer $$$2$$$ to the computer $$$4$$$; during the third hour, we copy the update files from the computer $$$1$$$ to the computer $$$5$$$, and from the computer $$$2$$$ to the computer $$$6$$$. $$$n=7$$$, $$$k=1$$$: during the first hour, we copy the update files from the computer $$$1$$$ to the computer $$$2$$$; during the second hour, we copy the update files from the computer $$$1$$$ to the computer $$$3$$$; during the third hour, we copy the update files from the computer $$$1$$$ to the computer $$$4$$$; during the fourth hour, we copy the update files from the computer $$$4$$$ to the computer $$$5$$$; during the fifth hour, we copy the update files from the computer $$$4$$$ to the computer $$$6$$$; during the sixth hour, we copy the update files from the computer $$$3$$$ to the computer $$$7$$$.
Java 11
standard input
[ "greedy", "implementation", "math" ]
5df6eb50ead22b498bea69bb84341c06
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^5$$$) — the number of test cases. Each test case consists of a single line that contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 10^{18}$$$) — the number of computers and the number of patch cables.
1,100
For each test case print one integer — the minimum number of hours required to copy the update files to all $$$n$$$ computers.
standard output
PASSED
1882d09227c803e1a7bc258a8bb8329c
train_108.jsonl
1635518100
Berland State University has received a new update for the operating system. Initially it is installed only on the $$$1$$$-st computer.Update files should be copied to all $$$n$$$ computers. The computers are not connected to the internet, so the only way to transfer update files from one computer to another is to copy them using a patch cable (a cable connecting two computers directly). Only one patch cable can be connected to a computer at a time. Thus, from any computer where the update files are installed, they can be copied to some other computer in exactly one hour.Your task is to find the minimum number of hours required to copy the update files to all $$$n$$$ computers if there are only $$$k$$$ patch cables in Berland State University.
256 megabytes
import java.io.*; import java.util.*; public class Main { public static void main(String[] args) throws IOException { BufferedReader r = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter w = new BufferedWriter(new OutputStreamWriter(System.out)); Scanner sc = new Scanner(System.in); int t = Integer.parseInt(r.readLine()); while(t-- > 0) { String s[] = r.readLine().split(" "); long k = Long.parseLong(s[1]); long n = Long.parseLong(s[0]); if(k == 1) { System.out.println(n-1); } else { long arr[] = fun(k, n); if(arr[2] == 1) System.out.println(arr[1]); else { long ans = arr[1] + (n - arr[0]) / k; if ((n - arr[0]) % k != 0) ans++; System.out.println(ans); } } } } static long[] fun(long k, long n) { long temp = 2, index = 1; long arr[] = new long[3]; arr[2] = -1; while(true) { if(temp >= n) { arr[2] = 1; arr[0] = -1; arr[1] = index; return arr; } if(temp > k) { break; } temp *= 2; index++; } arr[0] = temp; arr[1] = index; return arr; } }
Java
["4\n8 3\n6 6\n7 1\n1 1"]
2 seconds
["4\n3\n6\n0"]
NoteLet's consider the test cases of the example: $$$n=8$$$, $$$k=3$$$: during the first hour, we copy the update files from the computer $$$1$$$ to the computer $$$2$$$; during the second hour, we copy the update files from the computer $$$1$$$ to the computer $$$3$$$, and from the computer $$$2$$$ to the computer $$$4$$$; during the third hour, we copy the update files from the computer $$$1$$$ to the computer $$$5$$$, from the computer $$$2$$$ to the computer $$$6$$$, and from the computer $$$3$$$ to the computer $$$7$$$; during the fourth hour, we copy the update files from the computer $$$2$$$ to the computer $$$8$$$. $$$n=6$$$, $$$k=6$$$: during the first hour, we copy the update files from the computer $$$1$$$ to the computer $$$2$$$; during the second hour, we copy the update files from the computer $$$1$$$ to the computer $$$3$$$, and from the computer $$$2$$$ to the computer $$$4$$$; during the third hour, we copy the update files from the computer $$$1$$$ to the computer $$$5$$$, and from the computer $$$2$$$ to the computer $$$6$$$. $$$n=7$$$, $$$k=1$$$: during the first hour, we copy the update files from the computer $$$1$$$ to the computer $$$2$$$; during the second hour, we copy the update files from the computer $$$1$$$ to the computer $$$3$$$; during the third hour, we copy the update files from the computer $$$1$$$ to the computer $$$4$$$; during the fourth hour, we copy the update files from the computer $$$4$$$ to the computer $$$5$$$; during the fifth hour, we copy the update files from the computer $$$4$$$ to the computer $$$6$$$; during the sixth hour, we copy the update files from the computer $$$3$$$ to the computer $$$7$$$.
Java 11
standard input
[ "greedy", "implementation", "math" ]
5df6eb50ead22b498bea69bb84341c06
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^5$$$) — the number of test cases. Each test case consists of a single line that contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 10^{18}$$$) — the number of computers and the number of patch cables.
1,100
For each test case print one integer — the minimum number of hours required to copy the update files to all $$$n$$$ computers.
standard output
PASSED
cb8f8b3df811927261d87b1641bc5803
train_108.jsonl
1635518100
Berland State University has received a new update for the operating system. Initially it is installed only on the $$$1$$$-st computer.Update files should be copied to all $$$n$$$ computers. The computers are not connected to the internet, so the only way to transfer update files from one computer to another is to copy them using a patch cable (a cable connecting two computers directly). Only one patch cable can be connected to a computer at a time. Thus, from any computer where the update files are installed, they can be copied to some other computer in exactly one hour.Your task is to find the minimum number of hours required to copy the update files to all $$$n$$$ computers if there are only $$$k$$$ patch cables in Berland State University.
256 megabytes
import java.io.*; import java.util.*; public class Main{ public static void main(String[] args) throws IOException{ Scanner sc=new Scanner(System.in); int t=sc.nextInt(); while(t-->0) { Long n=sc.nextLong(); Long k=sc.nextLong(); Long ans= Long.valueOf(0); Long curr= Long.valueOf(1); while(curr<k){ curr*=2; ++ans; } if(curr<n) ans+=(n-curr+k-1)/k; System.out.println(ans); } sc.close(); } }
Java
["4\n8 3\n6 6\n7 1\n1 1"]
2 seconds
["4\n3\n6\n0"]
NoteLet's consider the test cases of the example: $$$n=8$$$, $$$k=3$$$: during the first hour, we copy the update files from the computer $$$1$$$ to the computer $$$2$$$; during the second hour, we copy the update files from the computer $$$1$$$ to the computer $$$3$$$, and from the computer $$$2$$$ to the computer $$$4$$$; during the third hour, we copy the update files from the computer $$$1$$$ to the computer $$$5$$$, from the computer $$$2$$$ to the computer $$$6$$$, and from the computer $$$3$$$ to the computer $$$7$$$; during the fourth hour, we copy the update files from the computer $$$2$$$ to the computer $$$8$$$. $$$n=6$$$, $$$k=6$$$: during the first hour, we copy the update files from the computer $$$1$$$ to the computer $$$2$$$; during the second hour, we copy the update files from the computer $$$1$$$ to the computer $$$3$$$, and from the computer $$$2$$$ to the computer $$$4$$$; during the third hour, we copy the update files from the computer $$$1$$$ to the computer $$$5$$$, and from the computer $$$2$$$ to the computer $$$6$$$. $$$n=7$$$, $$$k=1$$$: during the first hour, we copy the update files from the computer $$$1$$$ to the computer $$$2$$$; during the second hour, we copy the update files from the computer $$$1$$$ to the computer $$$3$$$; during the third hour, we copy the update files from the computer $$$1$$$ to the computer $$$4$$$; during the fourth hour, we copy the update files from the computer $$$4$$$ to the computer $$$5$$$; during the fifth hour, we copy the update files from the computer $$$4$$$ to the computer $$$6$$$; during the sixth hour, we copy the update files from the computer $$$3$$$ to the computer $$$7$$$.
Java 11
standard input
[ "greedy", "implementation", "math" ]
5df6eb50ead22b498bea69bb84341c06
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^5$$$) — the number of test cases. Each test case consists of a single line that contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 10^{18}$$$) — the number of computers and the number of patch cables.
1,100
For each test case print one integer — the minimum number of hours required to copy the update files to all $$$n$$$ computers.
standard output
PASSED
fdcbeacef9c68c75997304765de7f677
train_108.jsonl
1635518100
Berland State University has received a new update for the operating system. Initially it is installed only on the $$$1$$$-st computer.Update files should be copied to all $$$n$$$ computers. The computers are not connected to the internet, so the only way to transfer update files from one computer to another is to copy them using a patch cable (a cable connecting two computers directly). Only one patch cable can be connected to a computer at a time. Thus, from any computer where the update files are installed, they can be copied to some other computer in exactly one hour.Your task is to find the minimum number of hours required to copy the update files to all $$$n$$$ computers if there are only $$$k$$$ patch cables in Berland State University.
256 megabytes
import java.io.*; import java.util.*; import static java.lang.Math.abs; import static java.lang.Math.max; import static java.lang.Math.min; import static java.lang.System.out; public class B { public static Scanner scan = new Scanner(System.in); public static void main(String[] args) { int t = 1; t = Integer.parseInt(scan.nextLine()); while (t > 0) { solve(); t--; } } public static void solve() { final int mod = 1000000007; long n = scan.nextLong(); long k = scan.nextLong(); scan.nextLine(); long installed = 1, hours = 0; while (installed < k) { installed *= 2; hours++; } if (installed < n) { // hours += (long) Math.ceil((double) (n - installed) / (double) k); hours += (n - installed + k - 1) / k; } out.println(hours); } static int nextPowerOf2(int n) { int count = 0; if (n > 0 && (n & (n - 1)) == 0) return n; while (n != 0) { n >>= 1; count += 1; } return 1 << count; } public static int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); } }
Java
["4\n8 3\n6 6\n7 1\n1 1"]
2 seconds
["4\n3\n6\n0"]
NoteLet's consider the test cases of the example: $$$n=8$$$, $$$k=3$$$: during the first hour, we copy the update files from the computer $$$1$$$ to the computer $$$2$$$; during the second hour, we copy the update files from the computer $$$1$$$ to the computer $$$3$$$, and from the computer $$$2$$$ to the computer $$$4$$$; during the third hour, we copy the update files from the computer $$$1$$$ to the computer $$$5$$$, from the computer $$$2$$$ to the computer $$$6$$$, and from the computer $$$3$$$ to the computer $$$7$$$; during the fourth hour, we copy the update files from the computer $$$2$$$ to the computer $$$8$$$. $$$n=6$$$, $$$k=6$$$: during the first hour, we copy the update files from the computer $$$1$$$ to the computer $$$2$$$; during the second hour, we copy the update files from the computer $$$1$$$ to the computer $$$3$$$, and from the computer $$$2$$$ to the computer $$$4$$$; during the third hour, we copy the update files from the computer $$$1$$$ to the computer $$$5$$$, and from the computer $$$2$$$ to the computer $$$6$$$. $$$n=7$$$, $$$k=1$$$: during the first hour, we copy the update files from the computer $$$1$$$ to the computer $$$2$$$; during the second hour, we copy the update files from the computer $$$1$$$ to the computer $$$3$$$; during the third hour, we copy the update files from the computer $$$1$$$ to the computer $$$4$$$; during the fourth hour, we copy the update files from the computer $$$4$$$ to the computer $$$5$$$; during the fifth hour, we copy the update files from the computer $$$4$$$ to the computer $$$6$$$; during the sixth hour, we copy the update files from the computer $$$3$$$ to the computer $$$7$$$.
Java 11
standard input
[ "greedy", "implementation", "math" ]
5df6eb50ead22b498bea69bb84341c06
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^5$$$) — the number of test cases. Each test case consists of a single line that contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 10^{18}$$$) — the number of computers and the number of patch cables.
1,100
For each test case print one integer — the minimum number of hours required to copy the update files to all $$$n$$$ computers.
standard output
PASSED
3e9e130580d106cf714b623301f33a6a
train_108.jsonl
1635518100
Berland State University has received a new update for the operating system. Initially it is installed only on the $$$1$$$-st computer.Update files should be copied to all $$$n$$$ computers. The computers are not connected to the internet, so the only way to transfer update files from one computer to another is to copy them using a patch cable (a cable connecting two computers directly). Only one patch cable can be connected to a computer at a time. Thus, from any computer where the update files are installed, they can be copied to some other computer in exactly one hour.Your task is to find the minimum number of hours required to copy the update files to all $$$n$$$ computers if there are only $$$k$$$ patch cables in Berland State University.
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; import java.lang.*; import static java.lang.Math.*; // Sachin_2961 submission // public class Codeforces { static void solve(){ long n = fs.nLong(), k = fs.nLong(); long ans = 0,cur = 1L; while( cur < k ){ cur *= 2L; ans++; } if( cur < n ){ ans += (n-cur+k-1)/k; } out.println(ans); } static class Pair{ int value,ind; Pair(int value,int ind){ this.value = value; this.ind = ind; } } static boolean multipleTestCase = true; static FastScanner fs; static PrintWriter out; public static void main(String[]args){ try{ out = new PrintWriter(System.out); fs = new FastScanner(); int tc = multipleTestCase?fs.nInt():1; while (tc-->0)solve(); out.flush(); out.close(); }catch (Exception e){ e.printStackTrace(); } } static class FastScanner { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); String n() { while (!st.hasMoreTokens()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } String Line() { String str = ""; try { str = br.readLine(); }catch (IOException e) { e.printStackTrace(); } return str; } int nInt() {return Integer.parseInt(n()); } long nLong() {return Long.parseLong(n());} double nDouble(){return Double.parseDouble(n());} int[]aI(int n){ int[]ar = new int[n]; for(int i=0;i<n;i++) ar[i] = nInt(); return ar; } } public static void sort(int[] arr){ ArrayList<Integer> ls = new ArrayList<Integer>(); for(int x: arr) ls.add(x); Collections.sort(ls); for(int i=0; i < arr.length; i++) arr[i] = ls.get(i); } public static void sort(long[] arr){ ArrayList<Long> ls = new ArrayList<>(); for(long x: arr) ls.add(x); Collections.sort(ls); for(int i=0; i < arr.length; i++) arr[i] = ls.get(i); } }
Java
["4\n8 3\n6 6\n7 1\n1 1"]
2 seconds
["4\n3\n6\n0"]
NoteLet's consider the test cases of the example: $$$n=8$$$, $$$k=3$$$: during the first hour, we copy the update files from the computer $$$1$$$ to the computer $$$2$$$; during the second hour, we copy the update files from the computer $$$1$$$ to the computer $$$3$$$, and from the computer $$$2$$$ to the computer $$$4$$$; during the third hour, we copy the update files from the computer $$$1$$$ to the computer $$$5$$$, from the computer $$$2$$$ to the computer $$$6$$$, and from the computer $$$3$$$ to the computer $$$7$$$; during the fourth hour, we copy the update files from the computer $$$2$$$ to the computer $$$8$$$. $$$n=6$$$, $$$k=6$$$: during the first hour, we copy the update files from the computer $$$1$$$ to the computer $$$2$$$; during the second hour, we copy the update files from the computer $$$1$$$ to the computer $$$3$$$, and from the computer $$$2$$$ to the computer $$$4$$$; during the third hour, we copy the update files from the computer $$$1$$$ to the computer $$$5$$$, and from the computer $$$2$$$ to the computer $$$6$$$. $$$n=7$$$, $$$k=1$$$: during the first hour, we copy the update files from the computer $$$1$$$ to the computer $$$2$$$; during the second hour, we copy the update files from the computer $$$1$$$ to the computer $$$3$$$; during the third hour, we copy the update files from the computer $$$1$$$ to the computer $$$4$$$; during the fourth hour, we copy the update files from the computer $$$4$$$ to the computer $$$5$$$; during the fifth hour, we copy the update files from the computer $$$4$$$ to the computer $$$6$$$; during the sixth hour, we copy the update files from the computer $$$3$$$ to the computer $$$7$$$.
Java 11
standard input
[ "greedy", "implementation", "math" ]
5df6eb50ead22b498bea69bb84341c06
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^5$$$) — the number of test cases. Each test case consists of a single line that contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 10^{18}$$$) — the number of computers and the number of patch cables.
1,100
For each test case print one integer — the minimum number of hours required to copy the update files to all $$$n$$$ computers.
standard output
PASSED
0bf0dfe342c75e355175f1c28c1699ee
train_108.jsonl
1635518100
Berland State University has received a new update for the operating system. Initially it is installed only on the $$$1$$$-st computer.Update files should be copied to all $$$n$$$ computers. The computers are not connected to the internet, so the only way to transfer update files from one computer to another is to copy them using a patch cable (a cable connecting two computers directly). Only one patch cable can be connected to a computer at a time. Thus, from any computer where the update files are installed, they can be copied to some other computer in exactly one hour.Your task is to find the minimum number of hours required to copy the update files to all $$$n$$$ computers if there are only $$$k$$$ patch cables in Berland State University.
256 megabytes
import java.util.*; import java.util.Map.Entry; import java.io.*; import static java.util.Map.Entry.*; /* Name of the class has to be "Main" only if the class is public. */ public class Main { static long mod=(long) (1e9+7); static ArrayList<Integer>[] itemsList; public static void main (String[] args) throws Exception { final long mod1=(long) 1e9+7; Reader s=new Reader(); PrintWriter pt=new PrintWriter(System.out); BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); // int T=Integer.parseInt(br.readLine()); int T=s.nextInt(); // System.out.println(T); // int T=1; ol:while(T-- > 0) { long n=s.nextLong(); long k=s.nextLong(); long h=0; long p=1; while(n>p&&p<=k) { p*=2; h++; } // pt.println((int)Math.ceil(1.0*(n-p)/k)); h+=((n-p)/k)+((n-p)%k>0?1:0); pt.println(h); } pt.close(); } static Array copy(Array arr) { int n=arr.arr.length; int a[]=new int[n]; for(int i=0;i<n;i++) { a[i]=arr.arr[i]; } return new Array(a); } static class Array implements Comparable<Array>{ int arr[]; int sum=0; Array(int arr[]){ this.arr=arr; } public int sum(){ if (sum>0) return sum; for(int i=0;i<this.arr.length;i++) { sum+=itemsList[i].get(this.arr[i]-1); } return sum; } @Override public int compareTo(Array arr){ return this.sum()-arr.sum(); } @Override public int hashCode(){ int hash=0; for(int i=0;i<this.arr.length;i++) { hash^=(i+1)*Integer.hashCode(this.arr[i]); } // System.out.println(hash); return hash; } @Override public boolean equals(Object obj) { if (getClass() != obj.getClass()) { return false; } Array arr = (Array)obj; if(this.arr.length!=arr.arr.length) return false; boolean e=true; for(int i=0;i<this.arr.length;i++) { if(arr.arr[i]!=this.arr[i]) { e=false; } } return e; } } static int next(long[] arr, long target) { int start = 0, end = arr.length - 1; int ans = -1; while (start <= end) { int mid = (start + end) / 2; // Move to right side if target is // greater. if (arr[mid] < target) { start = mid + 1; } // Move left side. else { ans = mid; end = mid - 1; } } return ans; } static int prev(long[] arr, long target) { int start = 0, end = arr.length - 1; int ans = -1; while (start <= end) { int mid = (start + end) / 2; // Move to left side if target is // lesser. if (arr[mid] > target) { end = mid - 1; } // Move right side. else { ans = mid; start = mid + 1; } } return ans; } static void f(int arr[], int i) { if(arr[i]>arr[i+1]) { int temp=arr[i]; arr[i]=arr[i+1]; arr[i+1]=temp; } } static boolean isSorted(int arr[]) { for(int i=0;i<arr.length-1;i++) { if(arr[i]>arr[i+1]) { return false; } } return true; } /** * Seive * * @param n length * @param factors factors[num] is smallest prime divisor of num * @param ar list of primes */ static void sieveOfEratosthenes(int n, int factors[], ArrayList<Integer> ar) { factors[1]=1; int p; for(p = 2; p*p <=n; p++) { if(factors[p] == 0) { ar.add(p); factors[p]=p; for(int i = p*p; i <= n; i += p) if(factors[i]==0) factors[i] = p; } } for(;p<=n;p++){ if(factors[p] == 0) { factors[p] = p; ar.add(p); } } } static int binarySearch(int arr[], int x) { int l = 0, r = arr.length - 1; while (l <= r) { int m = l + (r - l) / 2; // Check if x is present at mid if (arr[m] == x) return m; // If x greater, ignore left half if (arr[m] < x) l = m + 1; // If x is smaller, ignore right half else r = m - 1; } // if we reach here, then element was // not present return -1; } public static int getFreq(int arr[], int n) { int k=0; for(int i=0;i<arr.length;i++) { if(arr[i]==n) k++; } return k; } public static void primeFactors(int n) { // Print the number of 2s that divide n HashMap<Integer, Integer> hm=new HashMap<Integer, Integer>(); while (n%2==0) { hm.put(2, hm.getOrDefault(2, 0)+1); n/=2; } // n must be odd at this point. So we can // skip one element (Note i = i +2) for (int i = 3; i <= Math.sqrt(n); i+= 2) { // While i divides n, print i and divide n while (n%i == 0) { n /= i; hm.put(i, hm.getOrDefault(i, 0)+1); } } // This condition is to handle the case whien // n is a prime number greater than 2 if (n > 2) hm.put(n, hm.getOrDefault(n, 0)+1); } static boolean isPartition(int arr[], int n) { int sum = 0; int i, j; // Calculate sum of all elements for (i = 0; i < n; i++) sum += arr[i]; if (sum % 2 != 0) return false; boolean part[][]=new boolean[sum/2+1][n+1]; // initialize top row as true for (i = 0; i <= n; i++) part[0][i] = true; // initialize leftmost column, except part[0][0], as false for (i = 1; i <= sum / 2; i++) part[i][0] = false; // Fill the partition table in bottom up manner for (i = 1; i <= sum / 2; i++) { for (j = 1; j <= n; j++) { part[i][j] = part[i][j - 1]; if (i >= arr[j - 1]) part[i][j] = part[i][j] || part[i - arr[j - 1]][j - 1]; } } return part[sum / 2][n]; } static int setBit(int S, int j) { return S | 1 << j; } static int clearBit(int S, int j) { return S & ~(1 << j); } static int toggleBit(int S, int j) { return S ^ 1 << j; } static boolean isOn(int S, int j) { return (S & 1 << j) != 0; } static int turnOnLastZero(int S) { return S | S + 1; } static int turnOnLastConsecutiveZeroes(int S) { return S | S - 1; } static int turnOffLastBit(int S) { return S & S - 1; } static int turnOffLastConsecutiveBits(int S) { return S & S + 1; } static int lowBit(int S) { return S & -S; } static int setAll(int N) { return (1 << N) - 1; } static int modulo(int S, int N) { return (S & N - 1); } //S%N, N is a power of 2 static boolean isPowerOfTwo(int S) { return (S & S - 1) == 0; } static boolean isWithin(long x, long y, long d, long k) { return x*k*x*k + y*k*y*k <= d*d; } static long modFact(long n, long p) { if (n >= p) return 0; long result = 1; for (int i = 1; i <= n; i++) result = (result * i) % p; return result; } static int sum(int[] arr, int n) { int inc[]=new int[n+1]; int dec[]=new int[n+1]; inc[0] = arr[0]; dec[0] = arr[0]; for (int i = 1; i < n; i++) { for (int j = 0; j < i; j++) { if (arr[j] > arr[i]) { dec[i] = max(dec[i], inc[j] + arr[i]); } else if (arr[i] > arr[j]) { inc[i] = max(inc[i], dec[j] + arr[i]); } } } return max(inc[n - 1], dec[n - 1]); } static long nc2(long a) { return a*(a-1)/2; } public static int numberOfprimeFactors(int n) { // Print the number of 2s that divide n HashSet<Integer> hs = new HashSet<Integer>(); while (n%2==0) { hs.add(2); n /= 2; } // n must be odd at this point. So we can // skip one element (Note i = i +2) for (int i = 3; i <= Math.sqrt(n); i+= 2) { // While i divides n, print i and divide n while (n%i == 0) { hs.add(i); n /= i; } } // This condition is to handle the case whien // n is a prime number greater than 2 if (n > 2) hs.add(n); return hs.size(); } static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } static void reverse(int arr[],int start, int end) { int temp; while (start < end) { temp = arr[start]; arr[start] = arr[end]; arr[end] = temp; start++; end--; } } static void reverse(long arr[],int start, int end) { long temp; while (start < end) { temp = arr[start]; arr[start] = arr[end]; arr[end] = temp; start++; end--; } } static boolean isPrime(int n) { // Corner cases if (n <= 1) return false; if (n <= 3) return true; // This is checked so that we can skip // middle five numbers in below loop if (n % 2 == 0 || n % 3 == 0) return false; for (int i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } static int p2(int n) { int k=0; while(n>1) { if(n%2!=0) return k; n/=2; k++; } return k; } static boolean isp2(int n) { while(n>1) { if(n%2==1) return false; n/=2; } return true; } static int binarySearch(int arr[], int first, int last, int key){ int mid = (first + last)/2; while( first <= last ){ if ( arr[mid] < key ){ first = mid + 1; }else if ( arr[mid] == key ){ return mid; }else{ last = mid - 1; } mid = (first + last)/2; } return -1; } static void print(int a[][]) { for(int i=0;i<a.length;i++) { for(int j=0;j<a[0].length;j++) System.out.print(a[i][j]+" "); System.out.println(); } } static int max (int x, int y) { return (x > y)? x : y; } static int search(Pair[] p, Pair pair) { int l=0, r=p.length; while (l <= r) { int m = l + (r - l) / 2; if (p[m].compareTo(pair)==0) return m; if (p[m].compareTo(pair)<0) l = m + 1; else r = m - 1; } return -1; } static void pa(int a[]) { for(int i=0;i<a.length;i++) System.out.print(a[i]+" "); System.out.println(); } static void pa(long a[]) { for(int i=0;i<a.length;i++) System.out.print(a[i]+" "); System.out.println(); } static void reverseArray(int arr[], int start, int end) { int temp; while (start < end) { temp = arr[start]; arr[start] = arr[end]; arr[end] = temp; start++; end--; } } static boolean isPalindrome(String s) { int l=s.length(); for(int i=0;i<l/2;i++) { if(s.charAt(i)!=s.charAt(l-i-1)) return false; } return true; } static long nc2(long n, long m) { return (n*(n-1)/2)%m; } static long c(long a) { return a*(a+1)/2; } static int next(int[] arr, int target) { int start = 0, end = arr.length - 1; int ans = -1; while (start <= end) { int mid = (start + end) / 2; // Move to right side if target is // greater. if (arr[mid] < target) { start = mid + 1; } // Move left side. else { ans = mid; end = mid - 1; } } return ans; } static int prev(int[] arr, int target) { int start = 0, end = arr.length - 1; int ans = -1; while (start <= end) { int mid = (start + end) / 2; // Move to left side if target is // lesser. if (arr[mid] > target) { end = mid - 1; } // Move right side. else { ans = mid; start = mid + 1; } } return ans; } static long power(long x, long y, long p) { long res = 1; x = x % p; while (y > 0) { if (y % 2 == 1) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return res; } static long modInverse(long n, long p) { return power(n, p-2, p); } static long nCrModP(long n, long r, long p) { if(r>n) return 0; if (r == 0) return 1; long[] fac = new long[(int) (n+1)]; fac[0] = 1; for (int i = 1 ;i <= n; i++) fac[i] = fac[i-1] * i % p; return (fac[(int) n]* modInverse(fac[(int) r], p) % p * modInverse(fac[(int) (n-r)], p) % p) % p; } static String reverse(String str) { return new StringBuffer(str).reverse().toString(); } static long fastpow(long x, long y, long m) { if (y == 0) return 1; long p = fastpow(x, y / 2, m) % m; p = (p * p) % m; if (y % 2 == 0) return p; else return (x * p) % m; } static boolean isPerfectSquare(long l) { return Math.pow((long)Math.sqrt(l),2)==l; } static void merge(long[] arr, int l, int m, int r) { // Find sizes of two subarrays to be merged int n1 = m - l + 1; int n2 = r - m; /* Create temp arrays */ long L[] = new long [n1]; long R[] = new long [n2]; /*Copy data to temp arrays*/ for (int i=0; i<n1; ++i) L[i] = arr[l + i]; for (int j=0; j<n2; ++j) R[j] = arr[m + 1+ j]; /* Merge the temp arrays */ // Initial indexes of first and second subarrays int i = 0, j = 0; // Initial index of merged subarry array int k = l; while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } /* Copy remaining elements of L[] if any */ while (i < n1) { arr[k] = L[i]; i++; k++; } /* Copy remaining elements of R[] if any */ while (j < n2) { arr[k] = R[j]; j++; k++; } } // Main function that sorts arr[l..r] using // merge() static void sort(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]; int R[] = new int [n2]; /*Copy data to temp arrays*/ for (int i=0; i<n1; ++i) L[i] = arr[l + i]; for (int j=0; j<n2; ++j) R[j] = arr[m + 1+ j]; /* Merge the temp arrays */ // Initial indexes of first and second subarrays int i = 0, j = 0; // Initial index of merged subarry array int k = l; while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } /* Copy remaining elements of L[] if any */ while (i < n1) { arr[k] = L[i]; i++; k++; } /* Copy remaining elements of R[] if any */ while (j < n2) { arr[k] = R[j]; j++; k++; } } // Main function that sorts arr[l..r] using // merge() static void sort(long arr[], int l, int r) { if (l < r) { // Find the middle point int m = (l+r)/2; // Sort first and second halves sort(arr, l, m); sort(arr , m+1, r); // Merge the sorted halves merge(arr, l, m, r); } } static class Pair implements Comparable<Pair>{ int a; int b; Pair(int a,int b){ this.a=a; this.b=b; } public int compareTo(Pair p){ if(a>p.a) return 1; if(a==p.a) return (b-p.b); return -1; } } static class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[128]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } }
Java
["4\n8 3\n6 6\n7 1\n1 1"]
2 seconds
["4\n3\n6\n0"]
NoteLet's consider the test cases of the example: $$$n=8$$$, $$$k=3$$$: during the first hour, we copy the update files from the computer $$$1$$$ to the computer $$$2$$$; during the second hour, we copy the update files from the computer $$$1$$$ to the computer $$$3$$$, and from the computer $$$2$$$ to the computer $$$4$$$; during the third hour, we copy the update files from the computer $$$1$$$ to the computer $$$5$$$, from the computer $$$2$$$ to the computer $$$6$$$, and from the computer $$$3$$$ to the computer $$$7$$$; during the fourth hour, we copy the update files from the computer $$$2$$$ to the computer $$$8$$$. $$$n=6$$$, $$$k=6$$$: during the first hour, we copy the update files from the computer $$$1$$$ to the computer $$$2$$$; during the second hour, we copy the update files from the computer $$$1$$$ to the computer $$$3$$$, and from the computer $$$2$$$ to the computer $$$4$$$; during the third hour, we copy the update files from the computer $$$1$$$ to the computer $$$5$$$, and from the computer $$$2$$$ to the computer $$$6$$$. $$$n=7$$$, $$$k=1$$$: during the first hour, we copy the update files from the computer $$$1$$$ to the computer $$$2$$$; during the second hour, we copy the update files from the computer $$$1$$$ to the computer $$$3$$$; during the third hour, we copy the update files from the computer $$$1$$$ to the computer $$$4$$$; during the fourth hour, we copy the update files from the computer $$$4$$$ to the computer $$$5$$$; during the fifth hour, we copy the update files from the computer $$$4$$$ to the computer $$$6$$$; during the sixth hour, we copy the update files from the computer $$$3$$$ to the computer $$$7$$$.
Java 11
standard input
[ "greedy", "implementation", "math" ]
5df6eb50ead22b498bea69bb84341c06
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^5$$$) — the number of test cases. Each test case consists of a single line that contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 10^{18}$$$) — the number of computers and the number of patch cables.
1,100
For each test case print one integer — the minimum number of hours required to copy the update files to all $$$n$$$ computers.
standard output
PASSED
735eefc59bd8649a8f35398ca0948468
train_108.jsonl
1635518100
Berland State University has received a new update for the operating system. Initially it is installed only on the $$$1$$$-st computer.Update files should be copied to all $$$n$$$ computers. The computers are not connected to the internet, so the only way to transfer update files from one computer to another is to copy them using a patch cable (a cable connecting two computers directly). Only one patch cable can be connected to a computer at a time. Thus, from any computer where the update files are installed, they can be copied to some other computer in exactly one hour.Your task is to find the minimum number of hours required to copy the update files to all $$$n$$$ computers if there are only $$$k$$$ patch cables in Berland State University.
256 megabytes
import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException; import java.io.IOException;import java.io.InputStream;import java.io.PrintWriter; import java.security.AccessControlException;import java.util.List;public class _B { static public void main(final String[] args) throws IOException{B._main(args);} static class B extends Solver{public B(){}@Override public void solve()throws IOException {long n=sc.nextLong();long k=sc.nextLong();sc.nextLine();long res=0;long done=1; while(done<n){res++;if(done<k){if(done*2<=n){done*=2;}else{done=n;}}else{res+=(n -done)/k+((n-done)%k>0?0:-1);done=n;}}pw.println(res);}static public void _main(String[] args)throws IOException{new B().run();}}static class MyScanner{private StringBuilder cache=new StringBuilder();int cache_pos=0;private int first_linebreak=-1;private int second_linebreak=-1;private StringBuilder sb=new StringBuilder();private InputStream is=null;public MyScanner(final InputStream is){this.is=is;}public String charToString(final int c){return String.format("'%s'",c=='\n'?"\\n":(c=='\r'?"\\r":String.valueOf((char)c))); }public int get(){int res=-1;if(cache_pos<cache.length()){res=cache.charAt(cache_pos); cache_pos++;if(cache_pos==cache.length()){cache.delete(0,cache_pos);cache_pos=0; }}else{try{res=is.read();}catch(IOException ex){throw new RuntimeException(ex);} }return res;}private void unget(final int c){if(cache_pos==0){cache.insert(0,(char)c); }else{cache_pos--;}}public String nextLine(){sb.delete(0,sb.length());int c;boolean done=false;boolean end=false;while((c=get())!=-1){if(check_linebreak(c)){done=true; if(c==first_linebreak){if(!end){end=true;}else{cache.append((char)c);break;}}else if(second_linebreak!=-1 && c==second_linebreak){break;}}if(end && c!=first_linebreak && c!=second_linebreak){cache.append((char)c);break;}if(!done){sb.append((char)c); }}return!done && sb.length()==0?null:sb.toString();}private boolean check_linebreak(int c){if(c=='\n'|| c=='\r'){if(first_linebreak==-1){first_linebreak=c;}else if(c!=first_linebreak && second_linebreak==-1){second_linebreak=c;}return true;}return false;}public int nextInt(){return Integer.parseInt(next());}public long nextLong(){return Long.parseLong(next()); }public boolean hasNext(){boolean res=false;int c;while((c=get())!=-1){if(!check_linebreak(c) && c!=' '&& c!='\t'){res=true;unget(c);break;}}return res;}public String next(){ sb.delete(0,sb.length());boolean started=false;int c;while((c=get())!=-1){if(check_linebreak(c) || c==' '|| c=='\t'){if(started){unget(c);break;}}else{started=true;sb.append((char)c); }}return sb.toString();}public int nextChar(){return get();}public boolean eof() {int c=get();boolean res=false;if(c!=-1){unget(c);}else{res=true;}return res;}public double nextDouble(){return Double.parseDouble(next());}}static abstract class Solver {protected String nameIn=null;protected String nameOut=null;protected boolean singleTest =false;protected MyScanner sc=null;protected PrintWriter pw=null;private int current_test =0;private int count_tests=0;protected int currentTest(){return current_test;}protected int countTests(){return count_tests;}private void process()throws IOException{if(!singleTest) {count_tests=sc.nextInt();sc.nextLine();for(current_test=1;current_test<=count_tests; current_test++){solve();pw.flush();}}else{count_tests=1;current_test=1;solve();} }abstract protected void solve()throws IOException;public void run()throws IOException {boolean done=false;try{if(nameIn!=null){if(new File(nameIn).exists()){try(FileInputStream fis=new FileInputStream(nameIn);PrintWriter pw0=select_output();){select_output(); done=true;sc=new MyScanner(fis);pw=pw0;process();}}else{throw new RuntimeException("File " +new File(nameIn).getAbsolutePath()+" does not exist!");}}}catch(IOException | AccessControlException ex){}if(!done){try(PrintWriter pw0=select_output();){sc=new MyScanner(System.in); pw=pw0;process();}}}private PrintWriter select_output()throws FileNotFoundException {if(nameOut!=null){return new PrintWriter(nameOut);}return new PrintWriter(System.out); }}static abstract class Tester{static public int getRandomInt(final int min,final int max){return(min+(int)Math.floor(Math.random()*(max-min+1)));}static public long getRandomLong(final long min,final long max){return(min+(long)Math.floor(Math.random() *(max-min+1)));}static public double getRandomDouble(final double min,final double maxExclusive){return(min+Math.random()*(maxExclusive-min));}abstract protected void testOutput(final List<String>output_data);abstract protected void generateInput(); abstract protected String inputDataToString();private boolean break_tester=false; protected void beforeTesting(){}protected void breakTester(){break_tester=true;} public boolean broken(){return break_tester;}}}
Java
["4\n8 3\n6 6\n7 1\n1 1"]
2 seconds
["4\n3\n6\n0"]
NoteLet's consider the test cases of the example: $$$n=8$$$, $$$k=3$$$: during the first hour, we copy the update files from the computer $$$1$$$ to the computer $$$2$$$; during the second hour, we copy the update files from the computer $$$1$$$ to the computer $$$3$$$, and from the computer $$$2$$$ to the computer $$$4$$$; during the third hour, we copy the update files from the computer $$$1$$$ to the computer $$$5$$$, from the computer $$$2$$$ to the computer $$$6$$$, and from the computer $$$3$$$ to the computer $$$7$$$; during the fourth hour, we copy the update files from the computer $$$2$$$ to the computer $$$8$$$. $$$n=6$$$, $$$k=6$$$: during the first hour, we copy the update files from the computer $$$1$$$ to the computer $$$2$$$; during the second hour, we copy the update files from the computer $$$1$$$ to the computer $$$3$$$, and from the computer $$$2$$$ to the computer $$$4$$$; during the third hour, we copy the update files from the computer $$$1$$$ to the computer $$$5$$$, and from the computer $$$2$$$ to the computer $$$6$$$. $$$n=7$$$, $$$k=1$$$: during the first hour, we copy the update files from the computer $$$1$$$ to the computer $$$2$$$; during the second hour, we copy the update files from the computer $$$1$$$ to the computer $$$3$$$; during the third hour, we copy the update files from the computer $$$1$$$ to the computer $$$4$$$; during the fourth hour, we copy the update files from the computer $$$4$$$ to the computer $$$5$$$; during the fifth hour, we copy the update files from the computer $$$4$$$ to the computer $$$6$$$; during the sixth hour, we copy the update files from the computer $$$3$$$ to the computer $$$7$$$.
Java 11
standard input
[ "greedy", "implementation", "math" ]
5df6eb50ead22b498bea69bb84341c06
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^5$$$) — the number of test cases. Each test case consists of a single line that contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 10^{18}$$$) — the number of computers and the number of patch cables.
1,100
For each test case print one integer — the minimum number of hours required to copy the update files to all $$$n$$$ computers.
standard output
PASSED
239832f48ab0661845ceba13a1220ac0
train_108.jsonl
1635518100
Berland State University has received a new update for the operating system. Initially it is installed only on the $$$1$$$-st computer.Update files should be copied to all $$$n$$$ computers. The computers are not connected to the internet, so the only way to transfer update files from one computer to another is to copy them using a patch cable (a cable connecting two computers directly). Only one patch cable can be connected to a computer at a time. Thus, from any computer where the update files are installed, they can be copied to some other computer in exactly one hour.Your task is to find the minimum number of hours required to copy the update files to all $$$n$$$ computers if there are only $$$k$$$ patch cables in Berland State University.
256 megabytes
import java.io.DataInputStream; import java.io.FileInputStream; import java.io.IOException; public class EduB { private static long solve(long n, long k) { if (n == 1) return 0; if (k == 1) return n - 1l; long hours = 1l; long pow = 1l; long covered = 1l; // covered after 1st installation while (pow * 2l <= k && covered + (pow * 2l) < n) { hours++; pow <<= 1l; covered += pow; } if (covered < n) { long l = n - covered - 1l; long ans = (l%k==0)? l/k : (l+k)/k; return ans + hours; } return hours; } public static void main(String[] args) throws IOException { Scanner s = new Scanner(); int t = 1; t = s.nextInt(); StringBuilder ans = new StringBuilder(); int count = 0; while (t-- > 0) { long n = s.nextLong(); long m = s.nextLong(); ans.append(solve(n, m)).append("\n"); } System.out.println(ans.toString()); } static class Scanner { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Scanner() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Scanner(String file_name) throws IOException { din = new DataInputStream( new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') { if (cnt != 0) { break; } else { continue; } } buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') { c = read(); } boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } public static long norm(long a, long MOD) { return ((a % MOD) + MOD) % MOD; } public static long msub(long a, long b, long MOD) { return norm(norm(a, MOD) - norm(b, MOD), MOD); } public static long madd(long a, long b, long MOD) { return norm(norm(a, MOD) + norm(b, MOD), MOD); } public static long mMul(long a, long b, long MOD) { return norm(norm(a, MOD) * norm(b, MOD), MOD); } public static long mDiv(long a, long b, long MOD) { return norm(norm(a, MOD) / norm(b, MOD), MOD); } public static String formattedArray(int a[]) { StringBuilder res = new StringBuilder(""); for (int e : a) res.append(e).append(" "); return res.toString().trim(); } private static void getInputs(Scanner s, int[] a, int n) throws IOException { for (int i = 0; i < n; i++) { a[i] = s.nextInt(); } } }
Java
["4\n8 3\n6 6\n7 1\n1 1"]
2 seconds
["4\n3\n6\n0"]
NoteLet's consider the test cases of the example: $$$n=8$$$, $$$k=3$$$: during the first hour, we copy the update files from the computer $$$1$$$ to the computer $$$2$$$; during the second hour, we copy the update files from the computer $$$1$$$ to the computer $$$3$$$, and from the computer $$$2$$$ to the computer $$$4$$$; during the third hour, we copy the update files from the computer $$$1$$$ to the computer $$$5$$$, from the computer $$$2$$$ to the computer $$$6$$$, and from the computer $$$3$$$ to the computer $$$7$$$; during the fourth hour, we copy the update files from the computer $$$2$$$ to the computer $$$8$$$. $$$n=6$$$, $$$k=6$$$: during the first hour, we copy the update files from the computer $$$1$$$ to the computer $$$2$$$; during the second hour, we copy the update files from the computer $$$1$$$ to the computer $$$3$$$, and from the computer $$$2$$$ to the computer $$$4$$$; during the third hour, we copy the update files from the computer $$$1$$$ to the computer $$$5$$$, and from the computer $$$2$$$ to the computer $$$6$$$. $$$n=7$$$, $$$k=1$$$: during the first hour, we copy the update files from the computer $$$1$$$ to the computer $$$2$$$; during the second hour, we copy the update files from the computer $$$1$$$ to the computer $$$3$$$; during the third hour, we copy the update files from the computer $$$1$$$ to the computer $$$4$$$; during the fourth hour, we copy the update files from the computer $$$4$$$ to the computer $$$5$$$; during the fifth hour, we copy the update files from the computer $$$4$$$ to the computer $$$6$$$; during the sixth hour, we copy the update files from the computer $$$3$$$ to the computer $$$7$$$.
Java 11
standard input
[ "greedy", "implementation", "math" ]
5df6eb50ead22b498bea69bb84341c06
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^5$$$) — the number of test cases. Each test case consists of a single line that contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 10^{18}$$$) — the number of computers and the number of patch cables.
1,100
For each test case print one integer — the minimum number of hours required to copy the update files to all $$$n$$$ computers.
standard output
PASSED
396317c855e4a19110d41f97b5da367b
train_108.jsonl
1635518100
Berland State University has received a new update for the operating system. Initially it is installed only on the $$$1$$$-st computer.Update files should be copied to all $$$n$$$ computers. The computers are not connected to the internet, so the only way to transfer update files from one computer to another is to copy them using a patch cable (a cable connecting two computers directly). Only one patch cable can be connected to a computer at a time. Thus, from any computer where the update files are installed, they can be copied to some other computer in exactly one hour.Your task is to find the minimum number of hours required to copy the update files to all $$$n$$$ computers if there are only $$$k$$$ patch cables in Berland State University.
256 megabytes
// import java.util.StringTokenizer; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.StringTokenizer; public class Test { static BufferedReader br; static double pre = 1e-9; static long mod = (long) (1e+9 + 7); static boolean isPrime[]; public static void main(String[] args) throws IOException { // your code goes here br = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(br.readLine()); while (t-- > 0) { // int n = Integer.parseInt(br.readLine()); StringTokenizer st; st = new StringTokenizer(br.readLine()); long n = Long.parseLong(st.nextToken()); long k = Long.parseLong(st.nextToken()); if (n == 1) { System.out.println("0"); continue; } long count = 0, ktemp = k; while (ktemp > 1) { ktemp /= 2; count++; } long ans = count; long left = n - (long) Math.pow(2, count); if (left > 0) { left = n - (long) Math.pow(2, count + 1); ans++; } if (left > 0) { ans += left / k + (left % k == 0 ? 0 : 1); // System.out.println("count =" + count + "\t left =" + left); } System.out.println(ans); } } private static long max3(long a, long b, long c) { if (a > b) { if (a > c) { return a; } return c; } if (b > c) { return b; } return c; } private static long binStringToNumMod(String str, long n, long mod) { long ans = 0; for (int i = 0; i < str.length(); i++) { ans = ((ans * n) % mod + (Integer.parseInt(str.substring(i, i + 1))) % mod) % mod; } return ans; } private static String numToBinString(long num) { StringBuffer sb = new StringBuffer(""); while (num > 0) { sb.append(num % 2); num /= 2; } return sb.reverse().toString(); } public static boolean[] SieveOfEratosthenes() { int n = (int) 1e7 + 7; boolean[] ans = new boolean[n]; Arrays.fill(ans, true); ans[0] = false; ans[1] = false; for (int i = 2; i < n; i++) { if (ans[i]) { for (int j = i * i; j < n; j = j + i) { ans[j] = false; } } } return ans; } public static long powerMod(long num, long pow, long mod) { if (pow == 0 || num == 1) return 1; if (num == 0 || pow == 1) return num; long ans = powerMod(num, pow / 2, mod) % mod; ans = (ans * ans) % mod; if (pow % 2 != 0) { ans = (ans * num) % mod; } return ans; } public static long gcd(long a, long b) { if (b == 0 || a == b) return a; if (a == 1 || b == 1) return 1; return gcd(b, a % b); } static class Element implements Comparable<Element> { int num; int freq; Element(int num, int freq) { this.num = num; this.freq = freq; } public int compareTo(Element e) { if (this.freq > e.freq) { return 1; } if (this.freq == e.freq) { return 0; } return -1; } } }
Java
["4\n8 3\n6 6\n7 1\n1 1"]
2 seconds
["4\n3\n6\n0"]
NoteLet's consider the test cases of the example: $$$n=8$$$, $$$k=3$$$: during the first hour, we copy the update files from the computer $$$1$$$ to the computer $$$2$$$; during the second hour, we copy the update files from the computer $$$1$$$ to the computer $$$3$$$, and from the computer $$$2$$$ to the computer $$$4$$$; during the third hour, we copy the update files from the computer $$$1$$$ to the computer $$$5$$$, from the computer $$$2$$$ to the computer $$$6$$$, and from the computer $$$3$$$ to the computer $$$7$$$; during the fourth hour, we copy the update files from the computer $$$2$$$ to the computer $$$8$$$. $$$n=6$$$, $$$k=6$$$: during the first hour, we copy the update files from the computer $$$1$$$ to the computer $$$2$$$; during the second hour, we copy the update files from the computer $$$1$$$ to the computer $$$3$$$, and from the computer $$$2$$$ to the computer $$$4$$$; during the third hour, we copy the update files from the computer $$$1$$$ to the computer $$$5$$$, and from the computer $$$2$$$ to the computer $$$6$$$. $$$n=7$$$, $$$k=1$$$: during the first hour, we copy the update files from the computer $$$1$$$ to the computer $$$2$$$; during the second hour, we copy the update files from the computer $$$1$$$ to the computer $$$3$$$; during the third hour, we copy the update files from the computer $$$1$$$ to the computer $$$4$$$; during the fourth hour, we copy the update files from the computer $$$4$$$ to the computer $$$5$$$; during the fifth hour, we copy the update files from the computer $$$4$$$ to the computer $$$6$$$; during the sixth hour, we copy the update files from the computer $$$3$$$ to the computer $$$7$$$.
Java 11
standard input
[ "greedy", "implementation", "math" ]
5df6eb50ead22b498bea69bb84341c06
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^5$$$) — the number of test cases. Each test case consists of a single line that contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 10^{18}$$$) — the number of computers and the number of patch cables.
1,100
For each test case print one integer — the minimum number of hours required to copy the update files to all $$$n$$$ computers.
standard output
PASSED
f586afee9c73438dc28edcf724698cc4
train_108.jsonl
1635518100
Berland State University has received a new update for the operating system. Initially it is installed only on the $$$1$$$-st computer.Update files should be copied to all $$$n$$$ computers. The computers are not connected to the internet, so the only way to transfer update files from one computer to another is to copy them using a patch cable (a cable connecting two computers directly). Only one patch cable can be connected to a computer at a time. Thus, from any computer where the update files are installed, they can be copied to some other computer in exactly one hour.Your task is to find the minimum number of hours required to copy the update files to all $$$n$$$ computers if there are only $$$k$$$ patch cables in Berland State University.
256 megabytes
import java.util.Scanner; public class Simple{ public static void main(String args[]){ //System.out.println("Hello Java"); Scanner s = new Scanner(System.in); int t = s.nextInt(); while (t>0){ long n = s.nextLong(); long k = s.nextLong(); long computer = 1; long remaining = n-1; long ans =0; while(remaining > 0 && computer <=k ){ ans++; remaining -= computer; computer+=computer; //System.out.println("Hello "+ans); } if(remaining>0){ ans+= remaining/k ; //System.out.println("Hello "+ans); if(remaining%k!=0)ans++; } System.out.println(ans); t--; } } }
Java
["4\n8 3\n6 6\n7 1\n1 1"]
2 seconds
["4\n3\n6\n0"]
NoteLet's consider the test cases of the example: $$$n=8$$$, $$$k=3$$$: during the first hour, we copy the update files from the computer $$$1$$$ to the computer $$$2$$$; during the second hour, we copy the update files from the computer $$$1$$$ to the computer $$$3$$$, and from the computer $$$2$$$ to the computer $$$4$$$; during the third hour, we copy the update files from the computer $$$1$$$ to the computer $$$5$$$, from the computer $$$2$$$ to the computer $$$6$$$, and from the computer $$$3$$$ to the computer $$$7$$$; during the fourth hour, we copy the update files from the computer $$$2$$$ to the computer $$$8$$$. $$$n=6$$$, $$$k=6$$$: during the first hour, we copy the update files from the computer $$$1$$$ to the computer $$$2$$$; during the second hour, we copy the update files from the computer $$$1$$$ to the computer $$$3$$$, and from the computer $$$2$$$ to the computer $$$4$$$; during the third hour, we copy the update files from the computer $$$1$$$ to the computer $$$5$$$, and from the computer $$$2$$$ to the computer $$$6$$$. $$$n=7$$$, $$$k=1$$$: during the first hour, we copy the update files from the computer $$$1$$$ to the computer $$$2$$$; during the second hour, we copy the update files from the computer $$$1$$$ to the computer $$$3$$$; during the third hour, we copy the update files from the computer $$$1$$$ to the computer $$$4$$$; during the fourth hour, we copy the update files from the computer $$$4$$$ to the computer $$$5$$$; during the fifth hour, we copy the update files from the computer $$$4$$$ to the computer $$$6$$$; during the sixth hour, we copy the update files from the computer $$$3$$$ to the computer $$$7$$$.
Java 11
standard input
[ "greedy", "implementation", "math" ]
5df6eb50ead22b498bea69bb84341c06
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^5$$$) — the number of test cases. Each test case consists of a single line that contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 10^{18}$$$) — the number of computers and the number of patch cables.
1,100
For each test case print one integer — the minimum number of hours required to copy the update files to all $$$n$$$ computers.
standard output
PASSED
fb670e8393920e1c5e29d2bc0956d5b3
train_108.jsonl
1635518100
Berland State University has received a new update for the operating system. Initially it is installed only on the $$$1$$$-st computer.Update files should be copied to all $$$n$$$ computers. The computers are not connected to the internet, so the only way to transfer update files from one computer to another is to copy them using a patch cable (a cable connecting two computers directly). Only one patch cable can be connected to a computer at a time. Thus, from any computer where the update files are installed, they can be copied to some other computer in exactly one hour.Your task is to find the minimum number of hours required to copy the update files to all $$$n$$$ computers if there are only $$$k$$$ patch cables in Berland State University.
256 megabytes
import java.util.*; public class Main { public static void main(String[] args) throws Exception { // Your code here! Scanner sc=new Scanner(System.in); int t= sc.nextInt(); while(t-->0) { long n = sc.nextLong(); long k = sc.nextLong(); long c=1,ans=0; while(c<n && c<=k) { c*=2; ans++; } if(c<n) { ans+=(n-c)/k; if((n-c)%k!=0) ans++; } System.out.println(ans); } } }
Java
["4\n8 3\n6 6\n7 1\n1 1"]
2 seconds
["4\n3\n6\n0"]
NoteLet's consider the test cases of the example: $$$n=8$$$, $$$k=3$$$: during the first hour, we copy the update files from the computer $$$1$$$ to the computer $$$2$$$; during the second hour, we copy the update files from the computer $$$1$$$ to the computer $$$3$$$, and from the computer $$$2$$$ to the computer $$$4$$$; during the third hour, we copy the update files from the computer $$$1$$$ to the computer $$$5$$$, from the computer $$$2$$$ to the computer $$$6$$$, and from the computer $$$3$$$ to the computer $$$7$$$; during the fourth hour, we copy the update files from the computer $$$2$$$ to the computer $$$8$$$. $$$n=6$$$, $$$k=6$$$: during the first hour, we copy the update files from the computer $$$1$$$ to the computer $$$2$$$; during the second hour, we copy the update files from the computer $$$1$$$ to the computer $$$3$$$, and from the computer $$$2$$$ to the computer $$$4$$$; during the third hour, we copy the update files from the computer $$$1$$$ to the computer $$$5$$$, and from the computer $$$2$$$ to the computer $$$6$$$. $$$n=7$$$, $$$k=1$$$: during the first hour, we copy the update files from the computer $$$1$$$ to the computer $$$2$$$; during the second hour, we copy the update files from the computer $$$1$$$ to the computer $$$3$$$; during the third hour, we copy the update files from the computer $$$1$$$ to the computer $$$4$$$; during the fourth hour, we copy the update files from the computer $$$4$$$ to the computer $$$5$$$; during the fifth hour, we copy the update files from the computer $$$4$$$ to the computer $$$6$$$; during the sixth hour, we copy the update files from the computer $$$3$$$ to the computer $$$7$$$.
Java 11
standard input
[ "greedy", "implementation", "math" ]
5df6eb50ead22b498bea69bb84341c06
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^5$$$) — the number of test cases. Each test case consists of a single line that contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 10^{18}$$$) — the number of computers and the number of patch cables.
1,100
For each test case print one integer — the minimum number of hours required to copy the update files to all $$$n$$$ computers.
standard output
PASSED
4a9bb0e17ac59296651c70a0d486510e
train_108.jsonl
1635518100
You are given a matrix, consisting of $$$n$$$ rows and $$$m$$$ columns. The $$$j$$$-th cell of the $$$i$$$-th row contains an integer $$$a_{ij}$$$.First, you have to color each row of the matrix either red or blue in such a way that at least one row is colored red and at least one row is colored blue.Then, you have to choose an integer $$$k$$$ ($$$1 \le k &lt; m$$$) and cut the colored matrix in such a way that the first $$$k$$$ columns become a separate matrix (the left matrix) and the last $$$m-k$$$ columns become a separate matrix (the right matrix).The coloring and the cut are called perfect if two properties hold: every red cell in the left matrix contains an integer greater than every blue cell in the left matrix; every blue cell in the right matrix contains an integer greater than every red cell in the right matrix. Find any perfect coloring and cut, or report that there are none.
256 megabytes
import java.util.*; import java.util.function.*; import java.io.*; // you can compare with output.txt and expected out public class RoundEdu116D { MyPrintWriter out; MyScanner in; // final static long FIXED_RANDOM; // static { // FIXED_RANDOM = System.currentTimeMillis(); // } final static String IMPOSSIBLE = "IMPOSSIBLE"; final static String POSSIBLE = "POSSIBLE"; final static String YES = "YES"; final static String NO = "NO"; private void initIO(boolean isFileIO) { if (System.getProperty("ONLINE_JUDGE") == null && isFileIO) { try{ in = new MyScanner(new FileInputStream("input.txt")); out = new MyPrintWriter(new FileOutputStream("output.txt")); } catch(FileNotFoundException e){ e.printStackTrace(); } } else{ in = new MyScanner(System.in); out = new MyPrintWriter(new BufferedOutputStream(System.out)); } } public static void main(String[] args){ // Scanner in = new Scanner(new BufferedReader(new InputStreamReader(System.in))); // the code for the deep recursion (more than 100k or 3~400k or so) // Thread t = new Thread(null, new RoundEdu130F(), "threadName", 1<<28); // t.start(); // t.join(); RoundEdu116D sol = new RoundEdu116D(); sol.run(); } private void run() { boolean isDebug = false; boolean isFileIO = true; boolean hasMultipleTests = true; initIO(isFileIO); int t = hasMultipleTests? in.nextInt() : 1; for (int i = 1; i <= t; ++i) { if(isDebug){ out.printf("Test %d\n", i); } getInput(); solve(); printOutput(); } in.close(); out.close(); } // use suitable one between matrix(2, n), matrix(n, 2), transposedMatrix(2, n) for graph edges, pairs, ... int n, m; int[][] a; void getInput() { n = in.nextInt(); m = in.nextInt(); a = in.nextMatrix(n, m); } void printOutput() { if(ans == null) out.println(NO); else { out.println(YES); out.print(ans); out.print(' '); out.println(k); } } String ans; int k; void solve(){ // first column, we get an ordering of rows // second column, we get another ordering of rows Integer[] row = new Integer[n]; for(int i=0; i<n; i++) row[i] = i; Arrays.sort(row, (i, j) -> Integer.compare(a[i][0], a[j][0])); // Integer[] invRow = new Integer[n]; // for(int i=0; i<n; i++) // invRow[i] = i; // Arrays.sort(invRow, (i, j) -> Integer.compare(a[j][m-1], a[i][m-1])); // vi = true if row i is red // we have 2 initial vi's from first and last column // ui = true if column i is contained in the left matrix // now, for each column i, // if ui, then ... it's 3-sat // we have intervals in each column that consist of same elements // right matrix -> flip // for each i, // color first i rows by blue // and find max k for the left matrix and min k for the right matrix int[][] maxPrefix = new int[n][m]; int[][] minSuffix = new int[n][m]; for(int j=0; j<m; j++) { maxPrefix[0][j] = a[row[0]][j]; for(int i=1; i<n; i++) maxPrefix[i][j] = Math.max(a[row[i]][j], maxPrefix[i-1][j]); minSuffix[n-1][j] = a[row[n-1]][j]; for(int i=n-2; i>=0; i--) minSuffix[i][j] = Math.min(a[row[i]][j], minSuffix[i+1][j]); } for(int j=1; j<m; j++) { for(int i=0; i<n; i++) maxPrefix[i][j] = Math.max(maxPrefix[i][j], maxPrefix[i][j-1]); for(int i=0; i<n; i++) minSuffix[i][j] = Math.min(minSuffix[i][j], minSuffix[i][j-1]); } int[][] minPrefix = new int[n][m]; int[][] maxSuffix = new int[n][m]; for(int j=0; j<m; j++) { minPrefix[0][j] = a[row[0]][j]; for(int i=1; i<n; i++) minPrefix[i][j] = Math.min(a[row[i]][j], minPrefix[i-1][j]); maxSuffix[n-1][j] = a[row[n-1]][j]; for(int i=n-2; i>=0; i--) maxSuffix[i][j] = Math.max(a[row[i]][j], maxSuffix[i+1][j]); } for(int j=m-2; j>=0; j--) { for(int i=0; i<n; i++) minPrefix[i][j] = Math.min(minPrefix[i][j], minPrefix[i][j+1]); for(int i=0; i<n; i++) maxSuffix[i][j] = Math.max(maxSuffix[i][j], maxSuffix[i][j+1]); } ans = null; for(int i=0; i<n-1; i++) { int maxK, minK; for(maxK=0; maxK<m-1; maxK++) if(maxPrefix[i][maxK] >= minSuffix[i+1][maxK]) break; for(minK=m-1; minK>0; minK--) if(minPrefix[i][minK] <= maxSuffix[i+1][minK]) break; if(minK < maxK) { k = maxK; char[] sb = new char[n]; for(int ii=0; ii<=i; ii++) sb[row[ii]] = 'B'; for(int ii=i+1; ii<n; ii++) sb[row[ii]] = 'R'; ans = String.valueOf(sb); return; } } } // Optional<T> solve() // return Optional.empty(); static class Pair implements Comparable<Pair>{ final static long FIXED_RANDOM = System.currentTimeMillis(); int first, second; public Pair(int first, int second) { this.first = first; this.second = second; } @Override public int hashCode() { // http://xorshift.di.unimi.it/splitmix64.c long x = first; x <<= 32; x += second; x += FIXED_RANDOM; x += 0x9e3779b97f4a7c15l; x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9l; x = (x ^ (x >> 27)) * 0x94d049bb133111ebl; return (int)(x ^ (x >> 31)); } @Override public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; Pair other = (Pair) obj; return first == other.first && second == other.second; } @Override public String toString() { return "[" + first + "," + second + "]"; } @Override public int compareTo(Pair o) { int cmp = Integer.compare(first, o.first); return cmp != 0? cmp: Integer.compare(second, o.second); } } public static class MyScanner { BufferedReader br; StringTokenizer st; // 32768? public MyScanner(InputStream is, int bufferSize) { br = new BufferedReader(new InputStreamReader(is), bufferSize); } public MyScanner(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); // br = new BufferedReader(new InputStreamReader(System.in)); // br = new BufferedReader(new InputStreamReader(new FileInputStream("input.txt"))); } public void close() { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine(){ String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } int[][] nextMatrix(int n, int m) { return nextMatrix(n, m, 0); } int[][] nextMatrix(int n, int m, int offset) { int[][] mat = new int[n][m]; for(int i=0; i<n; i++) { for(int j=0; j<m; j++) { mat[i][j] = nextInt()+offset; } } return mat; } int[][] nextTransposedMatrix(int n, int m){ return nextTransposedMatrix(n, m, 0); } int[][] nextTransposedMatrix(int n, int m, int offset){ int[][] mat = new int[m][n]; for(int i=0; i<n; i++) { for(int j=0; j<m; j++) { mat[j][i] = nextInt()+offset; } } return mat; } int[] nextIntArray(int len) { return nextIntArray(len, 0); } int[] nextIntArray(int len, int offset){ int[] a = new int[len]; for(int j=0; j<len; j++) a[j] = nextInt()+offset; return a; } long[] nextLongArray(int len) { return nextLongArray(len, 0); } long[] nextLongArray(int len, int offset){ long[] a = new long[len]; for(int j=0; j<len; j++) a[j] = nextLong()+offset; return a; } String[] nextStringArray(int len) { String[] s = new String[len]; for(int i=0; i<len; i++) s[i] = next(); return s; } } public static class MyPrintWriter extends PrintWriter{ public MyPrintWriter(OutputStream os) { super(os); } // public <T> void printlnAns(Optional<T> ans) { // if(ans.isEmpty()) // println(-1); // else // printlnAns(ans.get()); // } public void printlnAns(OptionalInt ans) { println(ans.orElse(-1)); } public void printlnAns(long ans) { println(ans); } public void printlnAns(int ans) { println(ans); } public void printlnAns(boolean ans) { if(ans) println(YES); else println(NO); } public void printAns(long[] arr){ if(arr != null && arr.length > 0){ print(arr[0]); for(int i=1; i<arr.length; i++){ print(" "); print(arr[i]); } } } public void printlnAns(long[] arr){ printAns(arr); println(); } public void printAns(int[] arr){ if(arr != null && arr.length > 0){ print(arr[0]); for(int i=1; i<arr.length; i++){ print(" "); print(arr[i]); } } } public void printlnAns(int[] arr){ printAns(arr); println(); } public <T> void printAns(ArrayList<T> arr){ if(arr != null && arr.size() > 0){ print(arr.get(0)); for(int i=1; i<arr.size(); i++){ print(" "); print(arr.get(i)); } } } public <T> void printlnAns(ArrayList<T> arr){ printAns(arr); println(); } public void printAns(int[] arr, int add){ if(arr != null && arr.length > 0){ print(arr[0]+add); for(int i=1; i<arr.length; i++){ print(" "); print(arr[i]+add); } } } public void printlnAns(int[] arr, int add){ printAns(arr, add); println(); } public void printAns(ArrayList<Integer> arr, int add) { if(arr != null && arr.size() > 0){ print(arr.get(0)+add); for(int i=1; i<arr.size(); i++){ print(" "); print(arr.get(i)+add); } } } public void printlnAns(ArrayList<Integer> arr, int add){ printAns(arr, add); println(); } public void printlnAnsSplit(long[] arr, int split){ if(arr != null){ for(int i=0; i<arr.length; i+=split){ print(arr[i]); for(int j=i+1; j<i+split; j++){ print(" "); print(arr[j]); } println(); } } } public void printlnAnsSplit(int[] arr, int split){ if(arr != null){ for(int i=0; i<arr.length; i+=split){ print(arr[i]); for(int j=i+1; j<i+split; j++){ print(" "); print(arr[j]); } println(); } } } public <T> void printlnAnsSplit(ArrayList<T> arr, int split){ if(arr != null && !arr.isEmpty()){ for(int i=0; i<arr.size(); i+=split){ print(arr.get(i)); for(int j=i+1; j<i+split; j++){ print(" "); print(arr.get(j)); } println(); } } } } static private void permutateAndSort(long[] a) { int n = a.length; Random R = new Random(System.currentTimeMillis()); for(int i=0; i<n; i++) { int t = R.nextInt(n-i); long temp = a[n-1-i]; a[n-1-i] = a[t]; a[t] = temp; } Arrays.sort(a); } static private void permutateAndSort(int[] a) { int n = a.length; Random R = new Random(System.currentTimeMillis()); for(int i=0; i<n; i++) { int t = R.nextInt(n-i); int temp = a[n-1-i]; a[n-1-i] = a[t]; a[t] = temp; } Arrays.sort(a); } static private int[][] constructChildren(int n, int[] parent, int parentRoot){ int[][] childrens = new int[n][]; int[] numChildren = new int[n]; for(int i=0; i<parent.length; i++) { if(parent[i] != parentRoot) numChildren[parent[i]]++; } for(int i=0; i<n; i++) { childrens[i] = new int[numChildren[i]]; } int[] idx = new int[n]; for(int i=0; i<parent.length; i++) { if(parent[i] != parentRoot) childrens[parent[i]][idx[parent[i]]++] = i; } return childrens; } static private int[][][] constructDirectedNeighborhood(int n, int[][] e){ int[] inDegree = new int[n]; int[] outDegree = new int[n]; for(int i=0; i<e.length; i++) { int u = e[i][0]; int v = e[i][1]; outDegree[u]++; inDegree[v]++; } int[][] inNeighbors = new int[n][]; int[][] outNeighbors = new int[n][]; for(int i=0; i<n; i++) { inNeighbors[i] = new int[inDegree[i]]; outNeighbors[i] = new int[outDegree[i]]; } for(int i=0; i<e.length; i++) { int u = e[i][0]; int v = e[i][1]; outNeighbors[u][--outDegree[u]] = v; inNeighbors[v][--inDegree[v]] = u; } return new int[][][] {inNeighbors, outNeighbors}; } static private int[][] constructNeighborhood(int n, int[][] e) { int[] degree = new int[n]; for(int i=0; i<e.length; i++) { int u = e[i][0]; int v = e[i][1]; degree[u]++; degree[v]++; } int[][] neighbors = new int[n][]; for(int i=0; i<n; i++) neighbors[i] = new int[degree[i]]; for(int i=0; i<e.length; i++) { int u = e[i][0]; int v = e[i][1]; neighbors[u][--degree[u]] = v; neighbors[v][--degree[v]] = u; } return neighbors; } static private void drawGraph(int[][] e) { makeDotUndirected(e); try { final Process process = new ProcessBuilder("dot", "-Tpng", "graph.dot") .redirectOutput(new File("graph.png")) .start(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } static private void makeDotUndirected(int[][] e) { MyPrintWriter out2 = null; try { out2 = new MyPrintWriter(new FileOutputStream("graph.dot")); } catch (FileNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } out2.println("strict graph {"); for(int i=0; i<e.length; i++){ out2.println(e[i][0] + "--" + e[i][1] + ";"); } out2.println("}"); out2.close(); } static private void makeDotDirected(int[][] e) { MyPrintWriter out2 = null; try { out2 = new MyPrintWriter(new FileOutputStream("graph.dot")); } catch (FileNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } out2.println("strict digraph {"); for(int i=0; i<e.length; i++){ out2.println(e[i][0] + "->" + e[i][1] + ";"); } out2.println("}"); out2.close(); } }
Java
["3\n5 5\n1 5 8 8 7\n5 2 1 4 3\n1 6 9 7 5\n9 3 3 3 2\n1 7 9 9 8\n3 3\n8 9 8\n1 5 3\n7 5 7\n2 6\n3 3 3 2 2 2\n1 1 1 4 4 4"]
4 seconds
["YES\nBRBRB 1\nNO\nYES\nRB 3"]
NoteThe coloring and the cut for the first testcase:
Java 17
standard input
[ "brute force", "constructive algorithms", "implementation", "sortings" ]
10751c875f4d7667ba21685c57cddd9e
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n, m \le 5 \cdot 10^5$$$; $$$n \cdot m \le 10^6$$$) — the number of rows and the number of columns in the matrix, respectively. The $$$i$$$-th of the next $$$n$$$ lines contains $$$m$$$ integers $$$a_{i1}, a_{i2}, \dots, a_{im}$$$ ($$$1 \le a_{ij} \le 10^6$$$). The sum of $$$n \cdot m$$$ over all testcases doesn't exceed $$$10^6$$$.
2,400
For each testcase print an answer. If there are no perfect colorings and cuts in the matrix, then print "NO". Otherwise, first, print "YES". Then a string, consisting of $$$n$$$ characters: the $$$i$$$-th character should be 'R' if the $$$i$$$-th row is colored red and 'B' if it's colored blue. The string should contain at least one 'R' and at least one 'B'. Finally, print an integer $$$k$$$ ($$$1 \le k &lt; m$$$) — the number of columns from the left that are cut.
standard output
PASSED
b127ead70ef77fd3df87780c16539f8d
train_108.jsonl
1635518100
You are given a matrix, consisting of $$$n$$$ rows and $$$m$$$ columns. The $$$j$$$-th cell of the $$$i$$$-th row contains an integer $$$a_{ij}$$$.First, you have to color each row of the matrix either red or blue in such a way that at least one row is colored red and at least one row is colored blue.Then, you have to choose an integer $$$k$$$ ($$$1 \le k &lt; m$$$) and cut the colored matrix in such a way that the first $$$k$$$ columns become a separate matrix (the left matrix) and the last $$$m-k$$$ columns become a separate matrix (the right matrix).The coloring and the cut are called perfect if two properties hold: every red cell in the left matrix contains an integer greater than every blue cell in the left matrix; every blue cell in the right matrix contains an integer greater than every red cell in the right matrix. Find any perfect coloring and cut, or report that there are none.
256 megabytes
import java.util.*; import java.io.*; import java.lang.*; public class cf { static FastReader in = new FastReader(); public static void main(String[] args) throws IOException { int t = i(); while (t-- > 0) { int n = i(), m = i(); int[][] a = new int[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { a[i][j] = i(); } } int[][][] left = new int[n][m][2]; int[][][] right = new int[n][m][2]; for (int i = 0; i < n; i++) { int big = a[i][0], sml = a[i][0]; left[i][0][0] = sml; left[i][0][1] = big; for (int j = 1; j < m; j++) { big = Math.max(big, a[i][j]); sml = Math.min(sml, a[i][j]); left[i][j][0] = sml; left[i][j][1] = big; } } //System.out.print(Arrays.deepToString(left)); //System.out.print(Arrays.deepToString(right)); for (int i = 0; i < n; i++) { int big = a[i][m-1], sml = a[i][m - 1]; right[i][m-1][0] = sml; right[i][m-1][1] = big; for (int j = 1; j < m; j++) { big = Math.max(big, a[i][m - j - 1]); sml = Math.min(sml, a[i][m - j - 1]); right[i][m - j - 1][0] = sml; right[i][m - j - 1][1] = big; } } boolean found = false; for (int i = 1; i < m; i++) { List<Pair> lpairs = new ArrayList<>(); List<Pair> rpairs = new ArrayList<>(); for (int j = 0; j < n; j++) { lpairs.add(new Pair(left[j][i-1][0], j)); lpairs.add(new Pair(left[j][i-1][1], j)); rpairs.add(new Pair(right[j][i][0], j)); rpairs.add(new Pair(right[j][i][1], j)); } Collections.sort(rpairs); Collections.sort(lpairs, Collections.reverseOrder()); int[] llocs = new int[n]; int[] rlocs = new int[n]; for (int j = 0; j < 2 * n; j++) { llocs[lpairs.get(j).j] = j; rlocs[rpairs.get(j).j] = j; } int[] included = new int[2 * n]; int bigl = 0; int bigr = 0; int pairs = 0; found = false; for (int j = 0; j < 2 * n; j++) { if (included[j] == 0) { pairs++; if (pairs == n) { break; } included[j] = 1; int otherl = llocs[lpairs.get(j).j]; included[otherl] = 1; bigl = Math.max(bigl, otherl); bigr = Math.max(bigr, rlocs[lpairs.get(j).j]); if (bigl == bigr && bigl == 2 * pairs - 1) { if (rpairs.get(bigr).i != rpairs.get(bigr + 1).i && lpairs.get(bigl).i != lpairs.get(bigl + 1).i) { found = true; char[] colors = new char[n]; for (int k = 0; k < n; k++) { colors[k] = 'B'; } for (int k = 0; k < 2 * n; k++) { if (included[k] == 1) { colors[lpairs.get(k).j] = 'R'; } } System.out.println("YES"); for (int k = 0; k < n; k++) { System.out.print(colors[k]); } System.out.print(' '); System.out.print(i); System.out.print('\n'); break; } } } } if (found) { break; } } if (! found) { System.out.println("NO"); } } } static int i() { return in.nextInt(); } static long l() { return in.nextLong(); } static double d() { return in.nextDouble(); } static String s() { return in.nextLine(); } } class Pair implements Comparable<Pair> { public int i, j; Pair(int i, int j) { this.i = i; this.j = j; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Pair pair = (Pair) o; return i == pair.i && j == pair.j; } @Override public int hashCode() { return Objects.hash(i, j); } @Override public int compareTo(Pair p) { if (this.i == p.i) { return this.j - p.j; } return this.i - p.i; } } 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\n5 5\n1 5 8 8 7\n5 2 1 4 3\n1 6 9 7 5\n9 3 3 3 2\n1 7 9 9 8\n3 3\n8 9 8\n1 5 3\n7 5 7\n2 6\n3 3 3 2 2 2\n1 1 1 4 4 4"]
4 seconds
["YES\nBRBRB 1\nNO\nYES\nRB 3"]
NoteThe coloring and the cut for the first testcase:
Java 8
standard input
[ "brute force", "constructive algorithms", "implementation", "sortings" ]
10751c875f4d7667ba21685c57cddd9e
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n, m \le 5 \cdot 10^5$$$; $$$n \cdot m \le 10^6$$$) — the number of rows and the number of columns in the matrix, respectively. The $$$i$$$-th of the next $$$n$$$ lines contains $$$m$$$ integers $$$a_{i1}, a_{i2}, \dots, a_{im}$$$ ($$$1 \le a_{ij} \le 10^6$$$). The sum of $$$n \cdot m$$$ over all testcases doesn't exceed $$$10^6$$$.
2,400
For each testcase print an answer. If there are no perfect colorings and cuts in the matrix, then print "NO". Otherwise, first, print "YES". Then a string, consisting of $$$n$$$ characters: the $$$i$$$-th character should be 'R' if the $$$i$$$-th row is colored red and 'B' if it's colored blue. The string should contain at least one 'R' and at least one 'B'. Finally, print an integer $$$k$$$ ($$$1 \le k &lt; m$$$) — the number of columns from the left that are cut.
standard output
PASSED
0b021dafe6f3a0083351bc38c8090986
train_108.jsonl
1635518100
You are given a matrix, consisting of $$$n$$$ rows and $$$m$$$ columns. The $$$j$$$-th cell of the $$$i$$$-th row contains an integer $$$a_{ij}$$$.First, you have to color each row of the matrix either red or blue in such a way that at least one row is colored red and at least one row is colored blue.Then, you have to choose an integer $$$k$$$ ($$$1 \le k &lt; m$$$) and cut the colored matrix in such a way that the first $$$k$$$ columns become a separate matrix (the left matrix) and the last $$$m-k$$$ columns become a separate matrix (the right matrix).The coloring and the cut are called perfect if two properties hold: every red cell in the left matrix contains an integer greater than every blue cell in the left matrix; every blue cell in the right matrix contains an integer greater than every red cell in the right matrix. Find any perfect coloring and cut, or report that there are none.
256 megabytes
/* stream Butter! eggyHide eggyVengeance I need U xiao rerun when */ import static java.lang.Math.*; import java.util.*; import java.io.*; import java.math.*; public class x1606D { public static void main(String hi[]) throws Exception { FastScanner infile = new FastScanner(); int T = infile.nextInt(); StringBuilder sb = new StringBuilder(); tc:while(T-->0) { int N = infile.nextInt(); int M = infile.nextInt(); int[][] grid = new int[N][M]; for(int r=0; r < N; r++) grid[r] = infile.nextInts(M); int[][] prefixMax = new int[N][M]; int[][] prefixMin = new int[N][M]; for(int r=0; r < N; r++) { prefixMax[r][0] = prefixMin[r][0] = grid[r][0]; for(int c=1; c < M; c++) { prefixMax[r][c] = max(prefixMax[r][c-1], grid[r][c]); prefixMin[r][c] = min(prefixMin[r][c-1], grid[r][c]); } } int[][] suffixMax = new int[N][M]; int[][] suffixMin = new int[N][M]; for(int r=0; r < N; r++) { suffixMax[r][M-1] = suffixMin[r][M-1] = grid[r][M-1]; for(int c=M-2; c >= 0; c--) { suffixMax[r][c] = max(suffixMax[r][c+1], grid[r][c]); suffixMin[r][c] = min(suffixMin[r][c+1], grid[r][c]); } } for(int cut=0; cut < M-1; cut++) { ArrayList<Integer> ls = new ArrayList<Integer>(); for(int r=0; r < N; r++) ls.add(r); int lmaocut = cut; Collections.sort(ls, (x,y) -> { return prefixMax[x][lmaocut]-prefixMax[y][lmaocut]; }); int redMins = prefixMin[ls.get(N-1)][cut]; boolean[] isRed = new boolean[N]; isRed[ls.get(N-1)] = true; //precomp the right side stuff int[] rightRed = new int[N]; rightRed[N-1] = suffixMax[ls.get(N-1)][cut+1]; for(int i=N-2; i >= 0; i--) rightRed[i] = max(rightRed[i+1], suffixMax[ls.get(i)][cut+1]); int[] rightBlue = new int[N]; rightBlue[0] = suffixMin[ls.get(0)][cut+1]; for(int i=1; i < N; i++) rightBlue[i] = min(rightBlue[i-1], suffixMin[ls.get(i)][cut+1]); for(int blue=N-2; blue >= 0; blue--) { if(prefixMax[ls.get(blue)][cut] < redMins) { //check the right matrix int maxRed = rightRed[blue+1]; int minBlue = rightBlue[blue]; if(maxRed < minBlue) { sb.append("YES\n"); for(int i=0; i < N; i++) { if(isRed[i]) sb.append("R"); else sb.append("B"); } sb.append(" "+(cut+1)+"\n"); continue tc; } } redMins = min(redMins, prefixMin[ls.get(blue)][cut]); isRed[ls.get(blue)] = true; } } sb.append("NO\n"); } System.out.print(sb); } } /* think about the first column If row r is colored red, all r2 with grid[r2][0] > grid[r][0] will also be red prefix max? for each possible cut, there are only N possible colorings for red rows For each cut, figure out the prefix maxes for each row and sort them by it Then just check if the suffix mins work */ class FastScanner { //I don't understand how this works lmao private int BS = 1 << 16; private char NC = (char) 0; private byte[] buf = new byte[BS]; private int bId = 0, size = 0; private char c = NC; private double cnt = 1; private BufferedInputStream in; public FastScanner() { in = new BufferedInputStream(System.in, BS); } public FastScanner(String s) { try { in = new BufferedInputStream(new FileInputStream(new File(s)), BS); } catch (Exception e) { in = new BufferedInputStream(System.in, BS); } } private char getChar() { while (bId == size) { try { size = in.read(buf); } catch (Exception e) { return NC; } if (size == -1) return NC; bId = 0; } return (char) buf[bId++]; } public int nextInt() { return (int) nextLong(); } public int[] nextInts(int N) { int[] res = new int[N]; for (int i = 0; i < N; i++) { res[i] = (int) nextLong(); } return res; } public long[] nextLongs(int N) { long[] res = new long[N]; for (int i = 0; i < N; i++) { res[i] = nextLong(); } return res; } public long nextLong() { cnt = 1; boolean neg = false; if (c == NC) c = getChar(); for (; (c < '0' || c > '9'); c = getChar()) { if (c == '-') neg = true; } long res = 0; for (; c >= '0' && c <= '9'; c = getChar()) { res = (res << 3) + (res << 1) + c - '0'; cnt *= 10; } return neg ? -res : res; } public double nextDouble() { double cur = nextLong(); return c != '.' ? cur : cur + nextLong() / cnt; } public double[] nextDoubles(int N) { double[] res = new double[N]; for (int i = 0; i < N; i++) { res[i] = nextDouble(); } return res; } public String next() { StringBuilder res = new StringBuilder(); while (c <= 32) c = getChar(); while (c > 32) { res.append(c); c = getChar(); } return res.toString(); } public String nextLine() { StringBuilder res = new StringBuilder(); while (c <= 32) c = getChar(); while (c != '\n') { res.append(c); c = getChar(); } return res.toString(); } public boolean hasNext() { if (c > 32) return true; while (true) { c = getChar(); if (c == NC) return false; else if (c > 32) return true; } } }
Java
["3\n5 5\n1 5 8 8 7\n5 2 1 4 3\n1 6 9 7 5\n9 3 3 3 2\n1 7 9 9 8\n3 3\n8 9 8\n1 5 3\n7 5 7\n2 6\n3 3 3 2 2 2\n1 1 1 4 4 4"]
4 seconds
["YES\nBRBRB 1\nNO\nYES\nRB 3"]
NoteThe coloring and the cut for the first testcase:
Java 8
standard input
[ "brute force", "constructive algorithms", "implementation", "sortings" ]
10751c875f4d7667ba21685c57cddd9e
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n, m \le 5 \cdot 10^5$$$; $$$n \cdot m \le 10^6$$$) — the number of rows and the number of columns in the matrix, respectively. The $$$i$$$-th of the next $$$n$$$ lines contains $$$m$$$ integers $$$a_{i1}, a_{i2}, \dots, a_{im}$$$ ($$$1 \le a_{ij} \le 10^6$$$). The sum of $$$n \cdot m$$$ over all testcases doesn't exceed $$$10^6$$$.
2,400
For each testcase print an answer. If there are no perfect colorings and cuts in the matrix, then print "NO". Otherwise, first, print "YES". Then a string, consisting of $$$n$$$ characters: the $$$i$$$-th character should be 'R' if the $$$i$$$-th row is colored red and 'B' if it's colored blue. The string should contain at least one 'R' and at least one 'B'. Finally, print an integer $$$k$$$ ($$$1 \le k &lt; m$$$) — the number of columns from the left that are cut.
standard output
PASSED
220420e16b8c303c4ad8f2247095314f
train_108.jsonl
1635518100
You are given a matrix, consisting of $$$n$$$ rows and $$$m$$$ columns. The $$$j$$$-th cell of the $$$i$$$-th row contains an integer $$$a_{ij}$$$.First, you have to color each row of the matrix either red or blue in such a way that at least one row is colored red and at least one row is colored blue.Then, you have to choose an integer $$$k$$$ ($$$1 \le k &lt; m$$$) and cut the colored matrix in such a way that the first $$$k$$$ columns become a separate matrix (the left matrix) and the last $$$m-k$$$ columns become a separate matrix (the right matrix).The coloring and the cut are called perfect if two properties hold: every red cell in the left matrix contains an integer greater than every blue cell in the left matrix; every blue cell in the right matrix contains an integer greater than every red cell in the right matrix. Find any perfect coloring and cut, or report that there are none.
256 megabytes
// Problem: D. Red-Blue Matrix // Contest: Codeforces - Educational Codeforces Round 116 (Rated for Div. 2) // URL: https://codeforces.com/contest/1606/problem/D // Memory Limit: 256 MB // Time Limit: 4000 ms // // Powered by CP Editor (https://cpeditor.org) import java.io.*; import java.util.*; import static java.lang.Math.max; import static java.lang.Math.min; import static java.lang.Math.abs; /** * zxz * problem link: **/ public class Main { //put some data here /** * do some clean action before next testcase */ private void clear() { } private void solve() throws Exception { rf(); int n = ri(); int m = ri(); int [][] mp = new int[n+1][m+2]; for(int i = 1; i <= n; i++){ rf(); for(int j = 1; j <= m; j++){ mp[i][j] = ri(); } mp[i][m+1] = i-1; } Arrays.sort(mp, (int [] a, int [] b)->{ for(int i = 1; i <= m; i++){ if(a[i] != b[i]){ return a[i] - b[i]; } } return 0; }); // for(int i = 1; i <= n;i++){ // print(mp[i], m+2); // } int [][] maxpre = new int[n+2][m+2]; int [][] minpre = new int[n+2][m+2]; int [][] maxsuf = new int[n+2][m+2]; int [][] minsuf = new int[n+2][m+2]; // print("maxpre"); for(int i = 1; i <= n; i++){ for(int j = 1; j <= m; j++){ maxpre[i][j] = max(max(maxpre[i][j-1],maxpre[i-1][j]), mp[i][j]); } minpre[i][0] = Integer.MAX_VALUE; // print(maxpre[i], m + 2); } // print("minpre"); Arrays.fill(minpre[n+1], Integer.MAX_VALUE); for(int i = n; i > 0; i--){ for(int j = 1; j <= m; j++){ int t = min(minpre[i][j-1],minpre[i+1][j]); minpre[i][j] = min(t, mp[i][j]); } // print(minpre[i], m + 2); } // print("maxsuf"); for(int i = n; i > 0; i--){ for(int j = m; j > 0; j--){ maxsuf[i][j] = max(max(maxsuf[i][j+1], maxsuf[i+1][j]), mp[i][j]); } minsuf[i][m + 1] = Integer.MAX_VALUE; // print(maxsuf[i], m + 2); } // print("minsuf"); Arrays.fill(minsuf[0], Integer.MAX_VALUE); // print(minsuf[0], m+1); for(int i = 1; i <= n; i++){ for(int j = m; j > 0; j--){ int t = min(minsuf[i-1][j], minsuf[i][j+1]); minsuf[i][j] = min(t, mp[i][j]); } // print(minsuf[i], m + 2); } for(int k = 1; k < m; k++){ for(int i = 1; i < n; i++){ if(maxpre[i][k] < minpre[i + 1][k] && minsuf[i][k+1] > maxsuf[i+1][k+1]){ addAns("YES"); char [] ans = new char[n]; // print("k = %d", k); for(int j = 1; j <= i; j++){ // print("%d", mp[j][m+1]); ans[mp[j][m+1]] = 'B'; } for(int j = i + 1; j <= n; j++){ // print("%d", mp[j][m+1]); ans[mp[j][m+1]] = 'R'; } addAns((new String(ans)) + " " + k); return ; } } } addAns("NO"); } private void run() throws Exception { int T = 1; rf(); T = ri(); while (T-- > 0) { solve(); if (T != 0) { clear(); } } printAns(); } public static void main(String[] args) throws Exception { new Main().run(); } StringBuilder sb = new StringBuilder(); BufferedReader infile = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer strT; private void addAns(int a){ sb.append(a + "\n"); } private void addAns(long a){ sb.append(a + "\n"); } private void addAns(String s){ sb.append(s + "\n"); } private void rf() throws IOException { strT = new StringTokenizer(infile.readLine()); } private int ri() { return Integer.parseInt(strT.nextToken()); } private long rl() { return Long.parseLong(strT.nextToken()); } private char [] rs2c(){ return strT.nextToken().toCharArray(); } private String rs(){ return strT.nextToken(); } private void printAns() { System.out.println(sb); } private int[] readArr(int N) throws Exception { int[] arr = new int[N]; for (int i = 0; i < N; i++) { arr[i] = Integer.parseInt(strT.nextToken()); } return arr; } private long[] readArr2(int N) throws Exception { long[] arr = new long[N]; for (int i = 0; i < N; i++) { arr[i] = Long.parseLong(strT.nextToken()); } return arr; } private void print(String format, Object ... args){ System.out.println(String.format(format,args)); } private void print(int[] arr, int x) { //for debugging only for (int i = 0;i < min(arr.length, x); i++) { System.out.print(arr[i] + " "); } System.out.println(); } private void print(long[] arr, int x) { //for debugging only for (int i = 0;i < min(arr.length, x); i++) { System.out.print(arr[i] + " "); } System.out.println(); } }
Java
["3\n5 5\n1 5 8 8 7\n5 2 1 4 3\n1 6 9 7 5\n9 3 3 3 2\n1 7 9 9 8\n3 3\n8 9 8\n1 5 3\n7 5 7\n2 6\n3 3 3 2 2 2\n1 1 1 4 4 4"]
4 seconds
["YES\nBRBRB 1\nNO\nYES\nRB 3"]
NoteThe coloring and the cut for the first testcase:
Java 8
standard input
[ "brute force", "constructive algorithms", "implementation", "sortings" ]
10751c875f4d7667ba21685c57cddd9e
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n, m \le 5 \cdot 10^5$$$; $$$n \cdot m \le 10^6$$$) — the number of rows and the number of columns in the matrix, respectively. The $$$i$$$-th of the next $$$n$$$ lines contains $$$m$$$ integers $$$a_{i1}, a_{i2}, \dots, a_{im}$$$ ($$$1 \le a_{ij} \le 10^6$$$). The sum of $$$n \cdot m$$$ over all testcases doesn't exceed $$$10^6$$$.
2,400
For each testcase print an answer. If there are no perfect colorings and cuts in the matrix, then print "NO". Otherwise, first, print "YES". Then a string, consisting of $$$n$$$ characters: the $$$i$$$-th character should be 'R' if the $$$i$$$-th row is colored red and 'B' if it's colored blue. The string should contain at least one 'R' and at least one 'B'. Finally, print an integer $$$k$$$ ($$$1 \le k &lt; m$$$) — the number of columns from the left that are cut.
standard output
PASSED
9832fbeceb5baa9dba567125b35f367f
train_108.jsonl
1635518100
You are given a matrix, consisting of $$$n$$$ rows and $$$m$$$ columns. The $$$j$$$-th cell of the $$$i$$$-th row contains an integer $$$a_{ij}$$$.First, you have to color each row of the matrix either red or blue in such a way that at least one row is colored red and at least one row is colored blue.Then, you have to choose an integer $$$k$$$ ($$$1 \le k &lt; m$$$) and cut the colored matrix in such a way that the first $$$k$$$ columns become a separate matrix (the left matrix) and the last $$$m-k$$$ columns become a separate matrix (the right matrix).The coloring and the cut are called perfect if two properties hold: every red cell in the left matrix contains an integer greater than every blue cell in the left matrix; every blue cell in the right matrix contains an integer greater than every red cell in the right matrix. Find any perfect coloring and cut, or report that there are none.
256 megabytes
/* || श्री राम समर्थ || || जय जय रघुवीर समर्थ || */ import java.io.IOException; import java.io.InputStream; import java.io.PrintStream; import java.io.PrintWriter; import java.util.*; import static java.util.Arrays.sort; /* Think until you get Good idea And then Code Easily Try Hard And Pay Attention to details (be positive always possible) think smart */ public class CodeforcesTemp { static Reader scan = new Reader(); static FastPrinter out = new FastPrinter(); static class SortByFirstCell implements Comparator<int[]>{ @Override public int compare(int[] o1, int[] o2) { return o1[0]-o2[0]; } } public static void main(String[] args) throws IOException { int tt = scan.nextInt(); // int tt = 1; for (int tc = 1; tc <= tt; tc++) { int n= scan.nextInt(); int m= scan.nextInt(); int[][] dp=scan.nextIntMatrix(n,m); int[][] arr=dp.clone(); Arrays.sort(arr,new SortByFirstCell()); int[][] up_left=new int[n][m]; int[][] below_left=new int[n][m]; int[][] up_right=new int[n][m]; int[][] below_right=new int[n][m]; for (int i = 0; i < n ; i++) { for (int j = 0; j < m; j++) { up_left[i][j]=arr[i][j]; up_right[i][j]=arr[i][j]; if(i!=0){ up_left[i][j]=Math.max(up_left[i][j],up_left[i-1][j]); up_right[i][j]=Math.min(up_right[i][j],up_right[i-1][j]); } } } for (int i = n-1; i >=0 ; i--) { for (int j = 0; j < m; j++) { below_left[i][j]=arr[i][j]; below_right[i][j]=arr[i][j]; if(i!=n-1){ below_left[i][j]=Math.min(below_left[i][j],below_left[i+1][j]); below_right[i][j]=Math.max(below_right[i][j],below_right[i+1][j]); } } } for (int i = 0; i < n ; i++) { for (int j = 1; j < m; j++) { up_left[i][j]=Math.max(up_left[i][j],up_left[i][j-1]); below_left[i][j]=Math.min(below_left[i][j],below_left[i][j-1]); } for (int j = m-2; j >=0; j--) { up_right[i][j]=Math.min(up_right[i][j],up_right[i][j+1]); below_right[i][j]=Math.max(below_right[i][j],below_right[i][j+1]); } } int up_to=-1; int cut=-1; inner:for (int i = 0; i < n-1; i++) { for (int j = 0; j < m-1; j++) { if((up_left[i][j]<below_left[i+1][j]) && (up_right[i][j+1]>below_right[i+1][j+1])){ up_to=up_left[i][0]; cut=(j+1); break inner; } } } if(up_to!=-1){ out.println("YES"); StringBuilder sb=new StringBuilder(); for (int i = 0; i < n; i++) { if(dp[i][0]<=up_to){ sb.append("B"); }else sb.append("R"); } out.println(sb.toString()+" "+cut); }else{ out.println("NO"); } out.flush(); } out.close(); } static class Reader { private final InputStream in; private final byte[] buffer = new byte[1024]; private int ptr = 0; private int buflen = 0; private static final long LONG_MAX_TENTHS = 922337203685477580L; private static final int LONG_MAX_LAST_DIGIT = 7; private static final int LONG_MIN_LAST_DIGIT = 8; public Reader(InputStream in) { this.in = in; } public Reader() { this(System.in); } private boolean hasNextByte() { if (ptr < buflen) { return true; } else { ptr = 0; try { buflen = in.read(buffer); } catch (IOException e) { e.printStackTrace(); } if (buflen <= 0) { return false; } } return true; } private int readByte() { if (hasNextByte()) return buffer[ptr++]; else return -1; } private static boolean isPrintableChar(int c) { return 33 <= c && c <= 126; } public boolean hasNext() { while (hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++; return hasNextByte(); } public String next() { if (!hasNext()) throw new NoSuchElementException(); StringBuilder sb = new StringBuilder(); int b = readByte(); while (isPrintableChar(b)) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } public long nextLong() { if (!hasNext()) throw new NoSuchElementException(); long n = 0; boolean minus = false; int b = readByte(); if (b == '-') { minus = true; b = readByte(); } if (b < '0' || '9' < b) { throw new NumberFormatException(); } while (true) { if ('0' <= b && b <= '9') { int digit = b - '0'; if (n >= LONG_MAX_TENTHS) { if (n == LONG_MAX_TENTHS) { if (minus) { if (digit <= LONG_MIN_LAST_DIGIT) { n = -n * 10 - digit; b = readByte(); if (!isPrintableChar(b)) { return n; } else if (b < '0' || '9' < b) { throw new NumberFormatException( String.format("not number")); } } } else { if (digit <= LONG_MAX_LAST_DIGIT) { n = n * 10 + digit; b = readByte(); if (!isPrintableChar(b)) { return n; } else if (b < '0' || '9' < b) { throw new NumberFormatException( String.format("not number")); } } } } throw new ArithmeticException( String.format(" overflows long.")); } n = n * 10 + digit; } else if (b == -1 || !isPrintableChar(b)) { return minus ? -n : n; } else { throw new NumberFormatException(); } b = readByte(); } } public int nextInt() { long nl = nextLong(); if (nl < Integer.MIN_VALUE || nl > Integer.MAX_VALUE) throw new NumberFormatException(); return (int) nl; } public double nextDouble() { return Double.parseDouble(next()); } public long[] nextLongArray(long length) { long[] array = new long[(int) length]; for (int i = 0; i < length; i++) array[i] = this.nextLong(); return array; } public long[] nextLongArray(int length, java.util.function.LongUnaryOperator map) { long[] array = new long[length]; for (int i = 0; i < length; i++) array[i] = map.applyAsLong(this.nextLong()); return array; } public int[] nextIntArray(int length) { int[] array = new int[length]; for (int i = 0; i < length; i++) array[i] = this.nextInt(); return array; } public int[][] nextIntArrayMulti(int length, int width) { int[][] arrays = new int[width][length]; for (int i = 0; i < length; i++) { for (int j = 0; j < width; j++) arrays[j][i] = this.nextInt(); } return arrays; } public int[] nextIntArray(int length, java.util.function.IntUnaryOperator map) { int[] array = new int[length]; for (int i = 0; i < length; i++) array[i] = map.applyAsInt(this.nextInt()); return array; } public double[] nextDoubleArray(int length) { double[] array = new double[length]; for (int i = 0; i < length; i++) array[i] = this.nextDouble(); return array; } public double[] nextDoubleArray(int length, java.util.function.DoubleUnaryOperator map) { double[] array = new double[length]; for (int i = 0; i < length; i++) array[i] = map.applyAsDouble(this.nextDouble()); return array; } public long[][] nextLongMatrix(int height, int width) { long[][] mat = new long[height][width]; for (int h = 0; h < height; h++) for (int w = 0; w < width; w++) { mat[h][w] = this.nextLong(); } return mat; } public int[][] nextIntMatrix(int height, int width) { int[][] mat = new int[height][width]; for (int h = 0; h < height; h++) for (int w = 0; w < width; w++) { mat[h][w] = this.nextInt(); } return mat; } public double[][] nextDoubleMatrix(int height, int width) { double[][] mat = new double[height][width]; for (int h = 0; h < height; h++) for (int w = 0; w < width; w++) { mat[h][w] = this.nextDouble(); } return mat; } public char[][] nextCharMatrix(int height, int width) { char[][] mat = new char[height][width]; for (int h = 0; h < height; h++) { String s = this.next(); for (int w = 0; w < width; w++) { mat[h][w] = s.charAt(w); } } return mat; } } static class FastPrinter extends PrintWriter { public FastPrinter(PrintStream stream) { super(stream); } public FastPrinter() { super(System.out); } private static String dtos(double x, int n) { StringBuilder sb = new StringBuilder(); if (x < 0) { sb.append('-'); x = -x; } x += Math.pow(10, -n) / 2; sb.append((long) x); sb.append("."); x -= (long) x; for (int i = 0; i < n; i++) { x *= 10; sb.append((int) x); x -= (int) x; } return sb.toString(); } @Override public void print(float f) { super.print(dtos(f, 20)); } @Override public void println(float f) { super.println(dtos(f, 20)); } @Override public void print(double d) { super.print(dtos(d, 20)); } @Override public void println(double d) { super.println(dtos(d, 20)); } public void printArray(int[] array, String separator) { int n = array.length; for (int i = 0; i < n - 1; i++) { super.print(array[i]); super.print(separator); } super.println(array[n - 1]); } public void printArray(int[] array) { this.printArray(array, " "); } public void printArray(int[] array, String separator, java.util.function.IntUnaryOperator map) { int n = array.length; for (int i = 0; i < n - 1; i++) { super.print(map.applyAsInt(array[i])); super.print(separator); } super.println(map.applyAsInt(array[n - 1])); } public void printArray(int[] array, java.util.function.IntUnaryOperator map) { this.printArray(array, " ", map); } public void printArray(long[] array, String separator) { int n = array.length; for (int i = 0; i < n - 1; i++) { super.print(array[i]); super.print(separator); } super.println(array[n - 1]); } public void printArray(long[] array) { this.printArray(array, " "); } public void printArray(long[] array, String separator, java.util.function.LongUnaryOperator map) { int n = array.length; for (int i = 0; i < n - 1; i++) { super.print(map.applyAsLong(array[i])); super.print(separator); } super.println(map.applyAsLong(array[n - 1])); } public void printArray(long[] array, java.util.function.LongUnaryOperator map) { this.printArray(array, " ", map); } public void printMatrix(int[][] arr) { for (int i = 0; i < arr.length; i++) { this.printArray(arr[i]); } } public void printCharMatrix(char[][] arr, int n, int m) { for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { this.print(arr[i][j] + " "); } this.println(); } } } static Random __r = new Random(); static int randInt(int min, int max) { return __r.nextInt(max - min + 1) + min; } static void reverse(int[] a) { for (int i = 0, n = a.length, half = n / 2; i < half; ++i) { int swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap; } } static void reverse(long[] a) { for (int i = 0, n = a.length, half = n / 2; i < half; ++i) { long swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap; } } static void reverse(double[] a) { for (int i = 0, n = a.length, half = n / 2; i < half; ++i) { double swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap; } } static void reverse(char[] a) { for (int i = 0, n = a.length, half = n / 2; i < half; ++i) { char swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap; } } static void reverse(char[] arr, int i, int j) { while (i < j) { char temp = arr[j]; arr[j] = arr[i]; arr[i] = temp; i++; j--; } } static void reverse(int[] arr, int i, int j) { while (i < j) { int temp = arr[j]; arr[j] = arr[i]; arr[i] = temp; i++; j--; } } static void reverse(long[] arr, int i, int j) { while (i < j) { long temp = arr[j]; arr[j] = arr[i]; arr[i] = temp; i++; j--; } } static void shuffle(int[] a) { int n = a.length - 1; for (int i = 0; i < n; ++i) { int ind = randInt(i, n); int swap = a[i]; a[i] = a[ind]; a[ind] = swap; } } static void shuffle(long[] a) { int n = a.length - 1; for (int i = 0; i < n; ++i) { int ind = randInt(i, n); long swap = a[i]; a[i] = a[ind]; a[ind] = swap; } } static void shuffle(double[] a) { int n = a.length - 1; for (int i = 0; i < n; ++i) { int ind = randInt(i, n); double swap = a[i]; a[i] = a[ind]; a[ind] = swap; } } static void rsort(int[] a) { shuffle(a); sort(a); } static void rsort(long[] a) { shuffle(a); sort(a); } static void rsort(double[] a) { shuffle(a); sort(a); } static int[] copy(int[] a) { int[] ans = new int[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans; } static long[] copy(long[] a) { long[] ans = new long[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans; } static double[] copy(double[] a) { double[] ans = new double[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans; } static char[] copy(char[] a) { char[] ans = new char[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans; } }
Java
["3\n5 5\n1 5 8 8 7\n5 2 1 4 3\n1 6 9 7 5\n9 3 3 3 2\n1 7 9 9 8\n3 3\n8 9 8\n1 5 3\n7 5 7\n2 6\n3 3 3 2 2 2\n1 1 1 4 4 4"]
4 seconds
["YES\nBRBRB 1\nNO\nYES\nRB 3"]
NoteThe coloring and the cut for the first testcase:
Java 8
standard input
[ "brute force", "constructive algorithms", "implementation", "sortings" ]
10751c875f4d7667ba21685c57cddd9e
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n, m \le 5 \cdot 10^5$$$; $$$n \cdot m \le 10^6$$$) — the number of rows and the number of columns in the matrix, respectively. The $$$i$$$-th of the next $$$n$$$ lines contains $$$m$$$ integers $$$a_{i1}, a_{i2}, \dots, a_{im}$$$ ($$$1 \le a_{ij} \le 10^6$$$). The sum of $$$n \cdot m$$$ over all testcases doesn't exceed $$$10^6$$$.
2,400
For each testcase print an answer. If there are no perfect colorings and cuts in the matrix, then print "NO". Otherwise, first, print "YES". Then a string, consisting of $$$n$$$ characters: the $$$i$$$-th character should be 'R' if the $$$i$$$-th row is colored red and 'B' if it's colored blue. The string should contain at least one 'R' and at least one 'B'. Finally, print an integer $$$k$$$ ($$$1 \le k &lt; m$$$) — the number of columns from the left that are cut.
standard output
PASSED
d8018ee2ba2fb29123590afeb769077f
train_108.jsonl
1635518100
You are given a matrix, consisting of $$$n$$$ rows and $$$m$$$ columns. The $$$j$$$-th cell of the $$$i$$$-th row contains an integer $$$a_{ij}$$$.First, you have to color each row of the matrix either red or blue in such a way that at least one row is colored red and at least one row is colored blue.Then, you have to choose an integer $$$k$$$ ($$$1 \le k &lt; m$$$) and cut the colored matrix in such a way that the first $$$k$$$ columns become a separate matrix (the left matrix) and the last $$$m-k$$$ columns become a separate matrix (the right matrix).The coloring and the cut are called perfect if two properties hold: every red cell in the left matrix contains an integer greater than every blue cell in the left matrix; every blue cell in the right matrix contains an integer greater than every red cell in the right matrix. Find any perfect coloring and cut, or report that there are none.
256 megabytes
import java.util.*; import java.util.Map.Entry; import java.math.*; import java.io.*; public class Main { static final int INF = 1 << 30; static int n; static int m; static int[][] a; static int[][] leftMin; static int[][] leftMax; static int[][] rightMin; static int[][] rightMax; public static void main(String[] args) throws FileNotFoundException { InputReader in = new InputReader(System.in); // Scanner in = new Scanner(System.in); // Scanner in = new Scanner(new BufferedReader(new // InputStreamReader(System.in))); PrintWriter out = new PrintWriter(System.out); // InputReader in = new InputReader(new // File("ethan_traverses_a_tree.txt")); // PrintWriter out = new PrintWriter(new // File("ethan_traverses_a_tree-output.txt")); int pi = in.nextInt(); for (int qi = 0; qi < pi; qi++) { n = in.nextInt(); m = in.nextInt(); a = new int[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { a[i][j] = in.nextInt(); } } leftMin = new int[n][m]; leftMax = new int[n][m]; rightMin = new int[n][m]; rightMax = new int[n][m]; for (int i = 0; i < n; i++) { leftMin[i][0] = leftMax[i][0] = a[i][0]; for (int j = 1; j < m; j++) { leftMin[i][j] = Math.min(leftMin[i][j - 1], a[i][j]); leftMax[i][j] = Math.max(leftMax[i][j - 1], a[i][j]); } rightMin[i][m - 1] = rightMax[i][m - 1] = a[i][m - 1]; for (int j = m - 2; j >= 0; j--) { rightMin[i][j] = Math.min(rightMin[i][j + 1], a[i][j]); rightMax[i][j] = Math.max(rightMax[i][j + 1], a[i][j]); } } boolean ok = false; for (int split = 0; split < m - 1; split++) { char[] ans = check(split); if (ans != null) { out.printf("YES\n"); out.printf("%s %d\n", String.valueOf(ans), split + 1); ok = true; break; } } if (ok == false) { out.printf("NO\n"); } } out.close(); } public static char[] check(int split) { List<Node> leftList = new ArrayList<Node>(); for (int i = 0; i < n; i++) { Node node = new Node(i, leftMin[i][split], leftMax[i][split]); leftList.add(node); } Collections.sort(leftList, new Comparator<Node>() { @Override public int compare(Main.Node o1, Main.Node o2) { return o2.max - o1.max; } }); TreeMap<Integer, Integer> rightBlueMin = new TreeMap<Integer, Integer>(); for (int i = 0; i < n; i++) { mapadd(rightBlueMin, rightMin[i][split + 1]); } char[] result = new char[n]; for (int i = 0; i < n; i++) { result[i] = 'B'; } int nowindex = 0; int leftRedMin = INF; int rightRedMax = 0; while (nowindex < n - 1) { // a[nowindex] to red Node firstnode = leftList.get(nowindex); result[firstnode.index] = 'R'; leftRedMin = Math.min(leftRedMin, firstnode.min); rightRedMax = Math.max(rightRedMax, rightMax[firstnode.index][split + 1]); mapremove(rightBlueMin, rightMin[firstnode.index][split + 1]); nowindex++; while (nowindex < n - 1 && leftRedMin <= leftList.get(nowindex).max) { Node node = leftList.get(nowindex); leftRedMin = Math.min(leftRedMin, node.min); rightRedMax = Math.max(rightRedMax, rightMax[node.index][split + 1]); mapremove(rightBlueMin, rightMin[node.index][split + 1]); result[node.index] = 'R'; nowindex++; } if (leftRedMin > leftList.get(nowindex).max && rightBlueMin.firstKey() > rightRedMax) { return result; } } return null; } public static void mapadd(TreeMap<Integer, Integer> map, int key) { if (map.containsKey(key) == false) { map.put(key, 0); } map.put(key, map.get(key) + 1); } public static void mapremove(TreeMap<Integer, Integer> map, int key) { map.put(key, map.get(key) - 1); if (map.get(key) == 0) { map.remove(key); } } static class Node { int index; int min; int max; public Node(int index, int min, int max) { this.index = index; this.min = min; this.max = max; } } static class InputReader { BufferedReader br; StringTokenizer st; public InputReader(File f) { try { br = new BufferedReader(new FileReader(f)); } catch (FileNotFoundException e) { e.printStackTrace(); } } public InputReader(InputStream in) { br = new BufferedReader(new InputStreamReader(in)); } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public boolean hasNext() { while (st == null || !st.hasMoreTokens()) { String s = null; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } if (s == null) return false; st = new StringTokenizer(s); } return true; } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } } }
Java
["3\n5 5\n1 5 8 8 7\n5 2 1 4 3\n1 6 9 7 5\n9 3 3 3 2\n1 7 9 9 8\n3 3\n8 9 8\n1 5 3\n7 5 7\n2 6\n3 3 3 2 2 2\n1 1 1 4 4 4"]
4 seconds
["YES\nBRBRB 1\nNO\nYES\nRB 3"]
NoteThe coloring and the cut for the first testcase:
Java 8
standard input
[ "brute force", "constructive algorithms", "implementation", "sortings" ]
10751c875f4d7667ba21685c57cddd9e
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n, m \le 5 \cdot 10^5$$$; $$$n \cdot m \le 10^6$$$) — the number of rows and the number of columns in the matrix, respectively. The $$$i$$$-th of the next $$$n$$$ lines contains $$$m$$$ integers $$$a_{i1}, a_{i2}, \dots, a_{im}$$$ ($$$1 \le a_{ij} \le 10^6$$$). The sum of $$$n \cdot m$$$ over all testcases doesn't exceed $$$10^6$$$.
2,400
For each testcase print an answer. If there are no perfect colorings and cuts in the matrix, then print "NO". Otherwise, first, print "YES". Then a string, consisting of $$$n$$$ characters: the $$$i$$$-th character should be 'R' if the $$$i$$$-th row is colored red and 'B' if it's colored blue. The string should contain at least one 'R' and at least one 'B'. Finally, print an integer $$$k$$$ ($$$1 \le k &lt; m$$$) — the number of columns from the left that are cut.
standard output
PASSED
ee5ece4587f8264ddf1b88b4bfeec25d
train_108.jsonl
1635518100
You are given a matrix, consisting of $$$n$$$ rows and $$$m$$$ columns. The $$$j$$$-th cell of the $$$i$$$-th row contains an integer $$$a_{ij}$$$.First, you have to color each row of the matrix either red or blue in such a way that at least one row is colored red and at least one row is colored blue.Then, you have to choose an integer $$$k$$$ ($$$1 \le k &lt; m$$$) and cut the colored matrix in such a way that the first $$$k$$$ columns become a separate matrix (the left matrix) and the last $$$m-k$$$ columns become a separate matrix (the right matrix).The coloring and the cut are called perfect if two properties hold: every red cell in the left matrix contains an integer greater than every blue cell in the left matrix; every blue cell in the right matrix contains an integer greater than every red cell in the right matrix. Find any perfect coloring and cut, or report that there are none.
256 megabytes
import java.io.*; import java.util.*; public final class Main { static PrintWriter out = new PrintWriter(System.out); static FastReader in = new FastReader(); static Pair[] moves = new Pair[]{new Pair(-1, 0), new Pair(0, 1), new Pair(1, 0), new Pair(0, -1)}; static int mod = (int) (1e9 + 7); static int mod2 = 998244353; public static void main(String[] args) { int tt = i(); while (tt-- > 0) { solve(); } out.flush(); } public static void solve() { int n = i(); int m = i(); int[][] mat = new int[n][m + 1]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { mat[i][j] = i(); } mat[i][m] = i; } Arrays.sort(mat, new Comparator<int[]>() { @Override public int compare(int[] o1, int[] o2) { return o1[0] - o2[0]; } }); int[][] x1 = new int[n][m]; int[][] x2 = new int[n][m]; int[][] x3 = new int[n][m]; int[][] x4 = new int[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { x1[i][j] = mat[i][j]; x1[i][j] = Math.max(x1[i][j], (i - 1 >= 0) ? x1[i - 1][j] : 0); x1[i][j] = Math.max(x1[i][j], (j - 1 >= 0) ? x1[i][j - 1] : 0); } } for (int i = 0; i < n; i++) { for (int j = m - 1; j >= 0; j--) { x2[i][j] = mat[i][j]; x2[i][j] = Math.min(x2[i][j], (i - 1 >= 0) ? x2[i - 1][j] : Integer.MAX_VALUE); x2[i][j] = Math.min(x2[i][j], (j + 1 < m) ? x2[i][j + 1] : Integer.MAX_VALUE); } } for (int i = n - 1; i >= 0; i--) { for (int j = 0; j < m; j++) { x3[i][j] = mat[i][j]; x3[i][j] = Math.min(x3[i][j], (i + 1 < n) ? x3[i + 1][j] : Integer.MAX_VALUE); x3[i][j] = Math.min(x3[i][j], (j - 1 >= 0) ? x3[i][j - 1] : Integer.MAX_VALUE); } } for (int i = n - 1; i >= 0; i--) { for (int j = m - 1; j >= 0; j--) { x4[i][j] = mat[i][j]; x4[i][j] = Math.max(x4[i][j], (i + 1 < n) ? x4[i + 1][j] : 0); x4[i][j] = Math.max(x4[i][j], (j + 1 < m) ? x4[i][j + 1] : 0); } } char[] chars = new char[n]; Arrays.fill(chars, 'R'); for (int i = 0; i < n - 1; i++) { chars[mat[i][m]] = 'B'; for (int j = 0; j < m - 1; j++) { int ans1 = x1[i][j]; int ans2 = x2[i][j + 1]; int ans3 = x3[i + 1][j]; int ans4 = x4[i + 1][j + 1]; if (ans3 > ans1 && ans2 > ans4) { out.println("YES"); out.println(new String(chars) + " " + (j + 1)); return; } } } out.println("NO"); } static long[] pre(int[] a) { long[] pre = new long[a.length + 1]; pre[0] = 0; for (int i = 0; i < a.length; i++) { pre[i + 1] = pre[i] + a[i]; } return pre; } static void print(char A[]) { for (char c : A) { out.print(c); } out.println(); } static void print(boolean A[]) { for (boolean c : A) { out.print(c + " "); } out.println(); } static void print(int A[]) { for (int c : A) { out.print(c + " "); } out.println(); } static void print(long A[]) { for (long i : A) { out.print(i + " "); } out.println(); } static void print(List<Integer> A) { for (int a : A) { out.print(a + " "); } } static int i() { return in.nextInt(); } static long l() { return in.nextLong(); } static double d() { return in.nextDouble(); } static String s() { return in.nextLine(); } static int[][] inputWithIdx(int N) { int A[][] = new int[N][2]; for (int i = 0; i < N; i++) { A[i] = new int[]{i, in.nextInt()}; } return A; } static int[] input(int N) { int A[] = new int[N]; for (int i = 0; i < N; i++) { A[i] = in.nextInt(); } return A; } static long[] inputLong(int N) { long A[] = new long[N]; for (int i = 0; i < A.length; i++) { A[i] = in.nextLong(); } return A; } static int GCD(int a, int b) { if (b == 0) { return a; } else { return GCD(b, a % b); } } static long GCD(long a, long b) { if (b == 0) { return a; } else { return GCD(b, a % b); } } static long LCM(int a, int b) { return (long) a / GCD(a, b) * b; } static long LCM(long a, long b) { return a / GCD(a, b) * b; } static void shuffleAndSort(int[] arr) { for (int i = 0; i < arr.length; i++) { int rand = (int) (Math.random() * arr.length); int temp = arr[rand]; arr[rand] = arr[i]; arr[i] = temp; } Arrays.sort(arr); } static void shuffleAndSort(int[][] arr, Comparator<? super int[]> comparator) { for (int i = 0; i < arr.length; i++) { int rand = (int) (Math.random() * arr.length); int[] temp = arr[rand]; arr[rand] = arr[i]; arr[i] = temp; } Arrays.sort(arr, comparator); } static void shuffleAndSort(long[] arr) { for (int i = 0; i < arr.length; i++) { int rand = (int) (Math.random() * arr.length); long temp = arr[rand]; arr[rand] = arr[i]; arr[i] = temp; } Arrays.sort(arr); } static boolean isPerfectSquare(double number) { double sqrt = Math.sqrt(number); return ((sqrt - Math.floor(sqrt)) == 0); } static void swap(int A[], int a, int b) { int t = A[a]; A[a] = A[b]; A[b] = t; } static long pow(long a, long b, int mod) { long pow = 1; long x = a; while (b != 0) { if ((b & 1) != 0) { pow = (pow * x) % mod; } x = (x * x) % mod; b /= 2; } return pow; } static long pow(long a, long b) { long pow = 1; long x = a; while (b != 0) { if ((b & 1) != 0) { pow *= x; } x = x * x; b /= 2; } return pow; } static long modInverse(long x, int mod) { return pow(x, mod - 2, mod); } static boolean isPrime(long N) { if (N <= 1) { return false; } if (N <= 3) { return true; } if (N % 2 == 0 || N % 3 == 0) { return false; } for (int i = 5; i * i <= N; i = i + 6) { if (N % i == 0 || N % (i + 2) == 0) { return false; } } return true; } public static String reverse(String str) { if (str == null) { return null; } return new StringBuilder(str).reverse().toString(); } public static String repeat(char ch, int repeat) { if (repeat <= 0) { return ""; } final char[] buf = new char[repeat]; for (int i = repeat - 1; i >= 0; i--) { buf[i] = ch; } return new String(buf); } public static int[] manacher(String s) { char[] chars = s.toCharArray(); int n = s.length(); int[] d1 = new int[n]; for (int i = 0, l = 0, r = -1; i < n; i++) { int k = (i > r) ? 1 : Math.min(d1[l + r - i], r - i + 1); while (0 <= i - k && i + k < n && chars[i - k] == chars[i + k]) { k++; } d1[i] = k--; if (i + k > r) { l = i - k; r = i + k; } } return d1; } public static int[] kmp(String s) { int n = s.length(); int[] res = new int[n]; for (int i = 1; i < n; ++i) { int j = res[i - 1]; while (j > 0 && s.charAt(i) != s.charAt(j)) { j = res[j - 1]; } if (s.charAt(i) == s.charAt(j)) { ++j; } res[i] = j; } return res; } } class Pair { int i, j; Pair(int i, int j) { this.i = i; this.j = j; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Pair pair = (Pair) o; return i == pair.i && j == pair.j; } @Override public int hashCode() { return Objects.hash(i, j); } } class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } class Node { int data, open, close; Node() { this(0, 0, 0); } Node(int data, int open, int close) { this.data = data; this.open = open; this.close = close; } } class ST { int n; Node[] st; ST(int n) { this.n = n; st = new Node[4 * Integer.highestOneBit(n)]; } void build(Node[] nodes) { build(0, 0, n - 1, nodes); } private void build(int id, int l, int r, Node[] nodes) { if (l == r) { st[id] = nodes[l]; return; } int mid = (l + r) >> 1; build((id << 1) + 1, l, mid, nodes); build((id << 1) + 2, mid + 1, r, nodes); st[id] = comb(st[(id << 1) + 1], st[(id << 1) + 2]); } void update(int i, Node node) { update(0, 0, n - 1, i, node); } private void update(int id, int l, int r, int i, Node node) { if (i < l || r < i) { return; } if (l == r) { st[id] = node; return; } int mid = (l + r) >> 1; update((id << 1) + 1, l, mid, i, node); update((id << 1) + 2, mid + 1, r, i, node); st[id] = comb(st[(id << 1) + 1], st[(id << 1) + 2]); } Node get(int x, int y) { return get(0, 0, n - 1, x, y); } private Node get(int id, int l, int r, int x, int y) { if (x > r || y < l) { return new Node(); } if (x <= l && r <= y) { return st[id]; } int mid = (l + r) >> 1; return comb(get((id << 1) + 1, l, mid, x, y), get((id << 1) + 2, mid + 1, r, x, y)); } Node comb(Node a, Node b) { if (a == null) { return b; } if (b == null) { return a; } int min = Math.min(a.open, b.close); return new Node(a.data + b.data + min * 2, a.open + b.open - min, a.close + b.close - min); } }
Java
["3\n5 5\n1 5 8 8 7\n5 2 1 4 3\n1 6 9 7 5\n9 3 3 3 2\n1 7 9 9 8\n3 3\n8 9 8\n1 5 3\n7 5 7\n2 6\n3 3 3 2 2 2\n1 1 1 4 4 4"]
4 seconds
["YES\nBRBRB 1\nNO\nYES\nRB 3"]
NoteThe coloring and the cut for the first testcase:
Java 8
standard input
[ "brute force", "constructive algorithms", "implementation", "sortings" ]
10751c875f4d7667ba21685c57cddd9e
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n, m \le 5 \cdot 10^5$$$; $$$n \cdot m \le 10^6$$$) — the number of rows and the number of columns in the matrix, respectively. The $$$i$$$-th of the next $$$n$$$ lines contains $$$m$$$ integers $$$a_{i1}, a_{i2}, \dots, a_{im}$$$ ($$$1 \le a_{ij} \le 10^6$$$). The sum of $$$n \cdot m$$$ over all testcases doesn't exceed $$$10^6$$$.
2,400
For each testcase print an answer. If there are no perfect colorings and cuts in the matrix, then print "NO". Otherwise, first, print "YES". Then a string, consisting of $$$n$$$ characters: the $$$i$$$-th character should be 'R' if the $$$i$$$-th row is colored red and 'B' if it's colored blue. The string should contain at least one 'R' and at least one 'B'. Finally, print an integer $$$k$$$ ($$$1 \le k &lt; m$$$) — the number of columns from the left that are cut.
standard output
PASSED
1835af9f247e24f8a2c8360cddcace8a
train_108.jsonl
1635518100
You are given a matrix, consisting of $$$n$$$ rows and $$$m$$$ columns. The $$$j$$$-th cell of the $$$i$$$-th row contains an integer $$$a_{ij}$$$.First, you have to color each row of the matrix either red or blue in such a way that at least one row is colored red and at least one row is colored blue.Then, you have to choose an integer $$$k$$$ ($$$1 \le k &lt; m$$$) and cut the colored matrix in such a way that the first $$$k$$$ columns become a separate matrix (the left matrix) and the last $$$m-k$$$ columns become a separate matrix (the right matrix).The coloring and the cut are called perfect if two properties hold: every red cell in the left matrix contains an integer greater than every blue cell in the left matrix; every blue cell in the right matrix contains an integer greater than every red cell in the right matrix. Find any perfect coloring and cut, or report that there are none.
256 megabytes
// coached by rainboy import java.io.*; import java.util.*; public class CF1606D extends PrintWriter { CF1606D() { super(System.out); } Scanner sc = new Scanner(System.in); public static void main(String[] $) { CF1606D o = new CF1606D(); o.main(); o.flush(); } static final int INF = 1000001; void main() { int t = sc.nextInt(); out: while (t-- > 0) { int n = sc.nextInt(); int m = sc.nextInt(); int[][] aa = new int[n][m]; int[][] pmax = new int[n][m]; int[][] pmin = new int[n][m]; int[][] qmax = new int[n][m]; int[][] qmin = new int[n][m]; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) pmax[i][j] = pmin[i][j] = qmax[i][j] = qmin[i][j] = aa[i][j] = sc.nextInt(); for (int i = 0; i < n; i++) { for (int j = 1; j < m; j++) { pmax[i][j] = Math.max(pmax[i][j - 1], pmax[i][j]); pmin[i][j] = Math.min(pmin[i][j - 1], pmin[i][j]); } for (int j = m - 2; j >= 0; j--) { qmax[i][j] = Math.max(qmax[i][j + 1], qmax[i][j]); qmin[i][j] = Math.min(qmin[i][j + 1], qmin[i][j]); } } for (int j = 0; j + 1 < m; j++) { int a = 0, b = INF; for (int i = 0; i < n; i++) { a = Math.max(a, pmax[i][j]); b = Math.min(b, qmin[i][j + 1]); } boolean[] red = new boolean[n]; int[] ip = new int[n]; int kp = 0; int[] iq = new int[n]; int kq = 0; for (int i = 0; i < n; i++) if (pmax[i][j] == a || qmin[i][j + 1] == b) red[i] = true; else { ip[kp++] = i; iq[kq++] = i; } a = INF; b = 0; for (int i = 0; i < n; i++) if (red[i]) { a = Math.min(a, pmin[i][j]); b = Math.max(b, qmax[i][j + 1]); } int j_ = j; ip = Arrays.stream(ip, 0, kp).boxed().sorted((i1, i2) -> pmax[i1][j_] - pmax[i2][j_]).mapToInt($->$).toArray(); iq = Arrays.stream(iq, 0, kq).boxed().sorted((i1, i2) -> qmin[i2][j_ + 1] - qmin[i1][j_ + 1]).mapToInt($->$).toArray(); while (kp > 0 && kq > 0) { int i = ip[kp - 1]; if (red[i]) { kp--; continue; } if (pmax[i][j] >= a) { a = Math.min(a, pmin[i][j]); b = Math.max(b, qmax[i][j + 1]); red[i] = true; kp--; continue; } i = iq[kq - 1]; if (red[i]) { kq--; continue; } if (qmin[i][j + 1] <= b) { a = Math.min(a, pmin[i][j]); b = Math.max(b, qmax[i][j + 1]); red[i] = true; kq--; continue; } break; } if (kp == 0 || kq == 0) continue; println("YES"); byte[] cc = new byte[n]; for (int i = 0; i < n; i++) cc[i] = (byte) (red[i] ? 'R' : 'B'); println(new String(cc) + " " + (j + 1)); continue out; } println("NO"); } } }
Java
["3\n5 5\n1 5 8 8 7\n5 2 1 4 3\n1 6 9 7 5\n9 3 3 3 2\n1 7 9 9 8\n3 3\n8 9 8\n1 5 3\n7 5 7\n2 6\n3 3 3 2 2 2\n1 1 1 4 4 4"]
4 seconds
["YES\nBRBRB 1\nNO\nYES\nRB 3"]
NoteThe coloring and the cut for the first testcase:
Java 11
standard input
[ "brute force", "constructive algorithms", "implementation", "sortings" ]
10751c875f4d7667ba21685c57cddd9e
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n, m \le 5 \cdot 10^5$$$; $$$n \cdot m \le 10^6$$$) — the number of rows and the number of columns in the matrix, respectively. The $$$i$$$-th of the next $$$n$$$ lines contains $$$m$$$ integers $$$a_{i1}, a_{i2}, \dots, a_{im}$$$ ($$$1 \le a_{ij} \le 10^6$$$). The sum of $$$n \cdot m$$$ over all testcases doesn't exceed $$$10^6$$$.
2,400
For each testcase print an answer. If there are no perfect colorings and cuts in the matrix, then print "NO". Otherwise, first, print "YES". Then a string, consisting of $$$n$$$ characters: the $$$i$$$-th character should be 'R' if the $$$i$$$-th row is colored red and 'B' if it's colored blue. The string should contain at least one 'R' and at least one 'B'. Finally, print an integer $$$k$$$ ($$$1 \le k &lt; m$$$) — the number of columns from the left that are cut.
standard output
PASSED
a23c069c110bac9a7dfd65ca71549562
train_108.jsonl
1635518100
You are given a matrix, consisting of $$$n$$$ rows and $$$m$$$ columns. The $$$j$$$-th cell of the $$$i$$$-th row contains an integer $$$a_{ij}$$$.First, you have to color each row of the matrix either red or blue in such a way that at least one row is colored red and at least one row is colored blue.Then, you have to choose an integer $$$k$$$ ($$$1 \le k &lt; m$$$) and cut the colored matrix in such a way that the first $$$k$$$ columns become a separate matrix (the left matrix) and the last $$$m-k$$$ columns become a separate matrix (the right matrix).The coloring and the cut are called perfect if two properties hold: every red cell in the left matrix contains an integer greater than every blue cell in the left matrix; every blue cell in the right matrix contains an integer greater than every red cell in the right matrix. Find any perfect coloring and cut, or report that there are none.
256 megabytes
import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.math.BigDecimal; import java.math.RoundingMode; import java.util.*; public class Main { static final long MOD1=1000000007; static final long MOD=998244353; static int[] ans; public static void main(String[] args){ PrintWriter out = new PrintWriter(System.out); InputReader sc=new InputReader(System.in); int t = sc.nextInt(); for (int i = 0; i < t; i++) { int n = sc.nextInt(); int m = sc.nextInt(); int[][] a = new int[n][m]; for (int j = 0; j < a.length; j++) { a[j] = sc.nextIntArray(m); } out.println(solve(n, m, a)); } out.flush(); } static String solve(int n, int m, int[][] a) { ArrayList<Pair> list = new ArrayList<>(); for (int i = 0; i < a.length; i++) { list.add(new Pair(a[i][0], i)); } Collections.sort(list); int[][] b = new int[n][m]; for (int i = 0; i < n; i++) { int k = list.get(i).y; for (int j = 0; j < m; j++) { b[i][j] = a[k][j]; } } int[][][] min = new int[n][m][4]; int[][][] max = new int[n][m][4]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { min[i][j][0] = b[i][j]; max[i][j][0] = b[i][j]; if(i-1 >= 0) { min[i][j][0] = Math.min(min[i][j][0], min[i-1][j][0]); max[i][j][0] = Math.max(max[i][j][0], max[i-1][j][0]); } if(j-1 >= 0) { min[i][j][0] = Math.min(min[i][j][0], min[i][j-1][0]); max[i][j][0] = Math.max(max[i][j][0], max[i][j-1][0]); } } } for (int i = 0; i < n; i++) { for (int j = m-1; j >= 0; j--) { min[i][j][1] = b[i][j]; max[i][j][1] = b[i][j]; if(i-1 >= 0) { min[i][j][1] = Math.min(min[i][j][1], min[i-1][j][1]); max[i][j][1] = Math.max(max[i][j][1], max[i-1][j][1]); } if(j+1 < m) { min[i][j][1] = Math.min(min[i][j][1], min[i][j+1][1]); max[i][j][1] = Math.max(max[i][j][1], max[i][j+1][1]); } } } for (int i = n-1; i >= 0; i--) { for (int j = m-1; j >= 0; j--) { min[i][j][2] = b[i][j]; max[i][j][2] = b[i][j]; if(i+1 < n) { min[i][j][2] = Math.min(min[i][j][2], min[i+1][j][2]); max[i][j][2] = Math.max(max[i][j][2], max[i+1][j][2]); } if(j+1 < m) { min[i][j][2] = Math.min(min[i][j][2], min[i][j+1][2]); max[i][j][2] = Math.max(max[i][j][2], max[i][j+1][2]); } } } for (int i = n-1; i >= 0; i--) { for (int j = 0; j < m; j++) { min[i][j][3] = b[i][j]; max[i][j][3] = b[i][j]; if(i+1 < n) { min[i][j][3] = Math.min(min[i][j][3], min[i+1][j][3]); max[i][j][3] = Math.max(max[i][j][3], max[i+1][j][3]); } if(j-1 >= 0) { min[i][j][3] = Math.min(min[i][j][3], min[i][j-1][3]); max[i][j][3] = Math.max(max[i][j][3], max[i][j-1][3]); } } } for (int i = 0; i < n-1; i++) { for (int j = 0; j < m-1; j++) { int left_up = max[i][j][0]; int left_down = min[i+1][j][3]; int right_up = min[i][j+1][1]; int right_down = max[i+1][j+1][2]; if (left_up < left_down && right_up > right_down) { char[] ans = new char[n]; for (int k = 0; k <= i; k++) { ans[list.get(k).y] = 'B'; } for (int k = i+1; k < n; k++) { ans[list.get(k).y] = 'R'; } return "YES "+String.valueOf(ans)+" "+(j+1); } } } return "NO"; } static class Pair implements Comparable<Pair>{ public int x; public int y; public Pair(int x,int y) { this.x=x; this.y=y; } @Override public boolean equals(Object obj) { if(obj instanceof Pair) { Pair other = (Pair) obj; return other.x==this.x && other.y==this.y; } return false; }//同値の定義 @Override public int hashCode() { return Objects.hash(this.x,this.y); }//これ書かないと正しく動作しない(要 勉強) @Override public int compareTo( Pair p){ if (this.x>p.x) { return 1; } else if (this.x<p.x) { return -1; } else { return 0; } } } static class InputReader { private InputStream in; private byte[] buffer = new byte[1024]; private int curbuf; private int lenbuf; public InputReader(InputStream in) { this.in = in; this.curbuf = this.lenbuf = 0; } public boolean hasNextByte() { if (curbuf >= lenbuf) { curbuf = 0; try { lenbuf = in.read(buffer); } catch (IOException e) { throw new InputMismatchException(); } if (lenbuf <= 0) return false; } return true; } private int readByte() { if (hasNextByte()) return buffer[curbuf++]; else return -1; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private void skip() { while (hasNextByte() && isSpaceChar(buffer[curbuf])) curbuf++; } public boolean hasNext() { skip(); return hasNextByte(); } public String next() { if (!hasNext()) throw new NoSuchElementException(); StringBuilder sb = new StringBuilder(); int b = readByte(); while (!isSpaceChar(b)) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } public int nextInt() { if (!hasNext()) throw new NoSuchElementException(); int c = readByte(); while (isSpaceChar(c)) c = readByte(); boolean minus = false; if (c == '-') { minus = true; c = readByte(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res = res * 10 + c - '0'; c = readByte(); } while (!isSpaceChar(c)); return (minus) ? -res : res; } public long nextLong() { if (!hasNext()) throw new NoSuchElementException(); int c = readByte(); while (isSpaceChar(c)) c = readByte(); boolean minus = false; if (c == '-') { minus = true; c = readByte(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res = res * 10 + c - '0'; c = readByte(); } while (!isSpaceChar(c)); return (minus) ? -res : res; } public double nextDouble() { return Double.parseDouble(next()); } public int[] nextIntArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public double[] nextDoubleArray(int n) { double[] a = new double[n]; for (int i = 0; i < n; i++) a[i] = nextDouble(); return a; } public long[] nextLongArray(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } public char[][] nextCharMap(int n, int m) { char[][] map = new char[n][m]; for (int i = 0; i < n; i++) map[i] = next().toCharArray(); return map; } } static int c(char a) { return (int)a - (int)'a'; } }
Java
["3\n5 5\n1 5 8 8 7\n5 2 1 4 3\n1 6 9 7 5\n9 3 3 3 2\n1 7 9 9 8\n3 3\n8 9 8\n1 5 3\n7 5 7\n2 6\n3 3 3 2 2 2\n1 1 1 4 4 4"]
4 seconds
["YES\nBRBRB 1\nNO\nYES\nRB 3"]
NoteThe coloring and the cut for the first testcase:
Java 11
standard input
[ "brute force", "constructive algorithms", "implementation", "sortings" ]
10751c875f4d7667ba21685c57cddd9e
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n, m \le 5 \cdot 10^5$$$; $$$n \cdot m \le 10^6$$$) — the number of rows and the number of columns in the matrix, respectively. The $$$i$$$-th of the next $$$n$$$ lines contains $$$m$$$ integers $$$a_{i1}, a_{i2}, \dots, a_{im}$$$ ($$$1 \le a_{ij} \le 10^6$$$). The sum of $$$n \cdot m$$$ over all testcases doesn't exceed $$$10^6$$$.
2,400
For each testcase print an answer. If there are no perfect colorings and cuts in the matrix, then print "NO". Otherwise, first, print "YES". Then a string, consisting of $$$n$$$ characters: the $$$i$$$-th character should be 'R' if the $$$i$$$-th row is colored red and 'B' if it's colored blue. The string should contain at least one 'R' and at least one 'B'. Finally, print an integer $$$k$$$ ($$$1 \le k &lt; m$$$) — the number of columns from the left that are cut.
standard output
PASSED
f6ff01349a554b8205627dec04f01cee
train_108.jsonl
1635518100
You are given a matrix, consisting of $$$n$$$ rows and $$$m$$$ columns. The $$$j$$$-th cell of the $$$i$$$-th row contains an integer $$$a_{ij}$$$.First, you have to color each row of the matrix either red or blue in such a way that at least one row is colored red and at least one row is colored blue.Then, you have to choose an integer $$$k$$$ ($$$1 \le k &lt; m$$$) and cut the colored matrix in such a way that the first $$$k$$$ columns become a separate matrix (the left matrix) and the last $$$m-k$$$ columns become a separate matrix (the right matrix).The coloring and the cut are called perfect if two properties hold: every red cell in the left matrix contains an integer greater than every blue cell in the left matrix; every blue cell in the right matrix contains an integer greater than every red cell in the right matrix. Find any perfect coloring and cut, or report that there are none.
256 megabytes
import java.io.*; import java.util.*; public class Main { static PrintWriter out; static Reader in; public static void main(String[] args) throws Exception { input_output(); Main solver = new Main(); solver.solve(); out.close(); out.flush(); } static int INF = (int)1e9; static int MAXN = (int)1e6+5; static int MOD = 998244353; static int q, t, m, n, k; void solve() throws Exception { t = in.nextInt(); while (t --> 0) { n = in.nextInt(); m = in.nextInt(); int[][] arr = new int[n][m]; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) arr[i][j] = in.nextInt(); int[][] minLeft = new int[n][m], maxLeft = new int[n][m], minRight = new int[n][m], maxRight = new int[n][m]; for (int i = 0; i < n; i++) minLeft[i][0] = maxLeft[i][0] = arr[i][0]; for (int i = 0; i < n; i++) minRight[i][m-1] = maxRight[i][m-1] = arr[i][m-1]; for (int i = 0; i < n; i++) { for (int j = 1; j < m; j++) { minLeft[i][j] = Math.min(arr[i][j], minLeft[i][j-1]); maxLeft[i][j] = Math.max(arr[i][j], maxLeft[i][j-1]); } } for (int i = 0; i < n; i++) { for (int j = m-2; j >= 0; j--) { maxRight[i][j] = Math.max(arr[i][j], maxRight[i][j+1]); minRight[i][j] = Math.min(arr[i][j], minRight[i][j+1]); } } boolean ans = false; int divideIdx = 0; StringBuilder coloring = new StringBuilder(""); outerLoop:for (int j = 0; j < m-1; j++) { TreeSet<Element> outerSet = new TreeSet<>(); TreeSet<Element> innerSet = new TreeSet<>(); for (int i = 0; i < n; i++) { outerSet.add(new Element(minLeft[i][j], minRight[i][j+1], i)); innerSet.add(new Element(0, maxRight[i][j+1], i)); } int maxPre = 0, minSuf = MAXN; while (!outerSet.isEmpty()) { Element e = outerSet.pollFirst(); maxPre = Math.max(maxPre, maxLeft[e.id][j]); minSuf = Math.min(minSuf, e.max); innerSet.remove(new Element(0, maxRight[e.id][j+1], e.id)); while (!outerSet.isEmpty()) { Element next = outerSet.first(); if (maxPre >= next.min) { outerSet.pollFirst(); maxPre = Math.max(maxPre, maxLeft[next.id][j]); minSuf = Math.min(minSuf, next.max); innerSet.remove(new Element(0, maxRight[next.id][j+1], next.id)); } else break; } if (innerSet.isEmpty()) break; e = innerSet.first(); if (e.max < minSuf) { ans = true; int[] color = new int[n]; while (!innerSet.isEmpty()) { Element next = innerSet.pollFirst(); color[next.id] = 1; } divideIdx = j+1; for (int i = 0; i < n; i++) coloring.append(color[i] == 0 ? "B" : "R"); break outerLoop; } } } if (ans) { out.println("YES"); out.println(coloring+" "+divideIdx); } else out.println("NO"); } } static class Element implements Comparable<Element> { int min, max, id; Element (int min, int max, int id) { this.min = min; this.max = max; this.id = id; } public int compareTo(Element o) { if (this.min != o.min) return this.min - o.min; if (this.max != o.max) return o.max - this.max; return this.id - o.id; } } static class Reader { private InputStream mIs; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public Reader() { this(System.in); } public Reader(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(); } double nextDouble() { return Double.parseDouble(next()); } public long nextLong() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } } static void input_output() throws IOException { File f = new File("in.txt"); if (f.exists() && !f.isDirectory()) { in = new Reader(new FileInputStream("in.txt")); } else in = new Reader(); f = new File("out.txt"); if (f.exists() && !f.isDirectory()) { out = new PrintWriter(new File("out.txt")); } else out = new PrintWriter(System.out); } }
Java
["3\n5 5\n1 5 8 8 7\n5 2 1 4 3\n1 6 9 7 5\n9 3 3 3 2\n1 7 9 9 8\n3 3\n8 9 8\n1 5 3\n7 5 7\n2 6\n3 3 3 2 2 2\n1 1 1 4 4 4"]
4 seconds
["YES\nBRBRB 1\nNO\nYES\nRB 3"]
NoteThe coloring and the cut for the first testcase:
Java 11
standard input
[ "brute force", "constructive algorithms", "implementation", "sortings" ]
10751c875f4d7667ba21685c57cddd9e
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n, m \le 5 \cdot 10^5$$$; $$$n \cdot m \le 10^6$$$) — the number of rows and the number of columns in the matrix, respectively. The $$$i$$$-th of the next $$$n$$$ lines contains $$$m$$$ integers $$$a_{i1}, a_{i2}, \dots, a_{im}$$$ ($$$1 \le a_{ij} \le 10^6$$$). The sum of $$$n \cdot m$$$ over all testcases doesn't exceed $$$10^6$$$.
2,400
For each testcase print an answer. If there are no perfect colorings and cuts in the matrix, then print "NO". Otherwise, first, print "YES". Then a string, consisting of $$$n$$$ characters: the $$$i$$$-th character should be 'R' if the $$$i$$$-th row is colored red and 'B' if it's colored blue. The string should contain at least one 'R' and at least one 'B'. Finally, print an integer $$$k$$$ ($$$1 \le k &lt; m$$$) — the number of columns from the left that are cut.
standard output
PASSED
9c5cbeccb9ce4abfa2cf4035071555c2
train_108.jsonl
1635518100
You are given a matrix, consisting of $$$n$$$ rows and $$$m$$$ columns. The $$$j$$$-th cell of the $$$i$$$-th row contains an integer $$$a_{ij}$$$.First, you have to color each row of the matrix either red or blue in such a way that at least one row is colored red and at least one row is colored blue.Then, you have to choose an integer $$$k$$$ ($$$1 \le k &lt; m$$$) and cut the colored matrix in such a way that the first $$$k$$$ columns become a separate matrix (the left matrix) and the last $$$m-k$$$ columns become a separate matrix (the right matrix).The coloring and the cut are called perfect if two properties hold: every red cell in the left matrix contains an integer greater than every blue cell in the left matrix; every blue cell in the right matrix contains an integer greater than every red cell in the right matrix. Find any perfect coloring and cut, or report that there are none.
256 megabytes
import java.util.*; import java.io.*; public class _116 { public static void main(String[] args) { MyScanner sc = new MyScanner(); PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); int t = sc.nextInt(); outer: while (t-- > 0) { 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 [][] pmin = new int[n][m]; int [][] pmax = new int[n][m]; int [][] smin = new int[n][m]; int [][] smax = new int[n][m]; for (int i = 0; i < n; i++) { int mn = a[i][0]; int mx = a[i][0]; pmin[i][0] = mn; pmax[i][0] = mx; for (int j = 1; j < m; j++) { mn = Math.min(mn, a[i][j]); mx = Math.max(mx, a[i][j]); pmax[i][j] = mx; pmin[i][j] = mn; } mn = a[i][m - 1]; mx = a[i][m - 1]; smin[i][m - 1] = mn; smax[i][m - 1] = mx; for (int j = m - 2; j >= 0; j--) { mn = Math.min(mn, a[i][j]); mx = Math.max(mx, a[i][j]); smax[i][j] = mx; smin[i][j] = mn; } } for (int cut = 0; cut < m - 1; cut++) { ArrayList<Pair> b = new ArrayList<>(); for (int i = 0; i < n; i++) { b.add(new Pair(pmin[i][cut], pmax[i][cut], smin[i][cut + 1], smax[i][cut + 1], i)); } Collections.sort(b, Comparator.comparingInt(x -> x.rmax)); int sz = b.size(); int [] rmin = new int[sz]; int [] lmin = new int[sz]; int [] lmax = new int[sz]; int [] rmax = new int[sz]; rmin[sz - 1] = b.get(sz - 1).rmin; lmax[sz - 1] = b.get(sz - 1).lmax; for (int i = sz - 2; i >= 0; i--) { rmin[i] = Math.min(rmin[i + 1], b.get(i).rmin); lmax[i] = Math.max(lmax[i + 1], b.get(i).lmax); } lmin[0] = b.get(0).lmin; rmax[0] = b.get(0).rmax; for (int i = 1; i < sz; i++) { lmin[i] = Math.min(lmin[i - 1], b.get(i).lmin); rmax[i] = Math.max(rmax[i - 1], b.get(i).rmax); } for (int i = 0; i < n - 1; i++) { if (rmax[i] < rmin[i + 1] && lmin[i] > lmax[i + 1]) { out.println("YES"); int [] res = new int[n]; for (int j = 0; j <= i; j++) { res[b.get(j).i] = 1; } for (int j = 0; j < n; j++) { out.print(res[j] == 1 ? 'R' : 'B'); } out.print(" "); out.print(cut + 1); out.println(); continue outer; } } } out.println("NO"); } out.close(); } static class Pair { int lmin; int lmax; int rmin; int rmax; int i; Pair(int lmin, int lmax, int rmin, int rmax, int i) { this.lmin = lmin; this.rmin = rmin; this.rmax = rmax; this.lmax = lmax; this.i = i; } } static void sort(int[] a) { ArrayList<Integer> q = new ArrayList<>(); for (int i : a) q.add(i); Collections.sort(q); for (int i = 0; i < a.length; i++) a[i] = q.get(i); } static void sort(long[] a) { ArrayList<Long> q = new ArrayList<>(); for (long i : a) q.add(i); Collections.sort(q); for (int i = 0; i < a.length; i++) a[i] = q.get(i); } //-----------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
["3\n5 5\n1 5 8 8 7\n5 2 1 4 3\n1 6 9 7 5\n9 3 3 3 2\n1 7 9 9 8\n3 3\n8 9 8\n1 5 3\n7 5 7\n2 6\n3 3 3 2 2 2\n1 1 1 4 4 4"]
4 seconds
["YES\nBRBRB 1\nNO\nYES\nRB 3"]
NoteThe coloring and the cut for the first testcase:
Java 11
standard input
[ "brute force", "constructive algorithms", "implementation", "sortings" ]
10751c875f4d7667ba21685c57cddd9e
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n, m \le 5 \cdot 10^5$$$; $$$n \cdot m \le 10^6$$$) — the number of rows and the number of columns in the matrix, respectively. The $$$i$$$-th of the next $$$n$$$ lines contains $$$m$$$ integers $$$a_{i1}, a_{i2}, \dots, a_{im}$$$ ($$$1 \le a_{ij} \le 10^6$$$). The sum of $$$n \cdot m$$$ over all testcases doesn't exceed $$$10^6$$$.
2,400
For each testcase print an answer. If there are no perfect colorings and cuts in the matrix, then print "NO". Otherwise, first, print "YES". Then a string, consisting of $$$n$$$ characters: the $$$i$$$-th character should be 'R' if the $$$i$$$-th row is colored red and 'B' if it's colored blue. The string should contain at least one 'R' and at least one 'B'. Finally, print an integer $$$k$$$ ($$$1 \le k &lt; m$$$) — the number of columns from the left that are cut.
standard output
PASSED
f95248dd6f12024fd72d59605c82ac07
train_108.jsonl
1635518100
You are given a matrix, consisting of $$$n$$$ rows and $$$m$$$ columns. The $$$j$$$-th cell of the $$$i$$$-th row contains an integer $$$a_{ij}$$$.First, you have to color each row of the matrix either red or blue in such a way that at least one row is colored red and at least one row is colored blue.Then, you have to choose an integer $$$k$$$ ($$$1 \le k &lt; m$$$) and cut the colored matrix in such a way that the first $$$k$$$ columns become a separate matrix (the left matrix) and the last $$$m-k$$$ columns become a separate matrix (the right matrix).The coloring and the cut are called perfect if two properties hold: every red cell in the left matrix contains an integer greater than every blue cell in the left matrix; every blue cell in the right matrix contains an integer greater than every red cell in the right matrix. Find any perfect coloring and cut, or report that there are none.
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; public class Main { static int MOD = 1000000007; // After writing solution, quick scan for: // array out of bounds // special cases e.g. n=1? // npe, particularly in maps // // Big numbers arithmetic bugs: // int overflow // sorting, or taking max, after MOD void solve() throws IOException { int T = ri(); for (int Ti = 0; Ti < T; Ti++) { int[] nm = ril(2); int n = nm[0]; int m = nm[1]; int[][] a = new int[n][]; for (int i = 0; i < n; i++) a[i] = ril(m); int idxMin = 0; // blue int idxMax = 0; // red for (int i = 0; i < n; i++) { if (a[i][0] < a[idxMin][0]) idxMin = i; if (a[i][0] > a[idxMax][0]) idxMax = i; } if (idxMin == idxMax) { pw.println("NO"); continue; } boolean ok = true; int p = 0; // [0..p] and [p+1..m-1]. for (int j = 0; ok && j < m-1; j++) { if (a[idxMin][j] == a[idxMax][j]) ok = false; else if (a[idxMin][j] > a[idxMax][j]) break; p = j; } if (!ok) { pw.println("NO"); continue; } // For the left matrix, what is the min and max in each row. [idx, min, max]. int[][] leftRows = new int[n][3]; for (int i = 0; i < n; i++) { leftRows[i][0] = i; leftRows[i][1] = Integer.MAX_VALUE; leftRows[i][2] = Integer.MIN_VALUE; } for (int i = 0; i < n; i++) { for (int j = 0; j <= p; j++) { leftRows[i][1] = Math.min(leftRows[i][1], a[i][j]); leftRows[i][2] = Math.max(leftRows[i][2], a[i][j]); } } Arrays.sort(leftRows, (r1, r2) -> Integer.compare(r1[1], r2[1])); UnionFind ufLeft = new UnionFind(n); int f = leftRows[0][2]; for (int i = 1; i < n; i++) { if (leftRows[i][1] <= f) { ufLeft.union(leftRows[i][0], leftRows[i-1][0]); f = Math.max(f, leftRows[i][2]); } else { f = leftRows[i][2]; } } if (ufLeft.getNumComponents() == 1) { pw.println("NO"); continue; } // ufLeft now contains information to identify disjoint intervals. // map from component number to [min, max] Map<Integer, int[]> map = new HashMap<>(); Map<Integer, List<Integer>> componentToRow = new HashMap<>(); for (int i = 0; i < n; i++) { int c = ufLeft.find(leftRows[i][0]); if (!componentToRow.containsKey(c)) componentToRow.put(c, new ArrayList<>()); componentToRow.get(c).add(leftRows[i][0]); if (!map.containsKey(c)) map.put(c, new int[]{c, Integer.MAX_VALUE, Integer.MIN_VALUE}); int[] here = map.get(c); here[1] = Math.min(here[1], leftRows[i][1]); here[2] = Math.max(here[2], leftRows[i][2]); } List<int[]> intervals = new ArrayList<>(map.values()); Collections.sort(intervals, (i1, i2) -> Integer.compare(i1[1], i2[1])); // Detour: compute right min/max int[][] rightRows = new int[n][3]; for (int i = 0; i < n; i++) { rightRows[i][0] = i; rightRows[i][1] = Integer.MAX_VALUE; rightRows[i][2] = Integer.MIN_VALUE; } for (int i = 0; i < n; i++) { for (int j = p+1; j < m; j++) { rightRows[i][1] = Math.min(rightRows[i][1], a[i][j]); rightRows[i][2] = Math.max(rightRows[i][2], a[i][j]); } } // We can now brute force every max value (besides last) as upper bound for blues on left // Start off with everything red // Recall: on the right, we want blues bigger than reds char[] color = new char[n]; Arrays.fill(color, 'R'); Multiset<Integer> rightRed = new Multiset<>(); Multiset<Integer> rightBlu = new Multiset<>(); for (int[] row : rightRows) { rightRed.add(row[1]); rightRed.add(row[2]); } boolean found = false; for (int x = 0; !found && x < intervals.size() - 1; x++) { int[] here = intervals.get(x); for (int i : componentToRow.get(here[0])) { color[i] = 'B'; rightRed.remove(rightRows[i][1]); rightRed.remove(rightRows[i][2]); rightBlu.add(rightRows[i][1]); rightBlu.add(rightRows[i][2]); } if (rightRed.last() < rightBlu.first()) { found = true; pw.println("YES"); pw.println(new String(color) + " " + (p+1)); } } if (!found) pw.println("NO"); } } // IMPORTANT // DID YOU CHECK THE COMMON MISTAKES ABOVE? // Template code below BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw = new PrintWriter(System.out); public static void main(String[] args) throws IOException { Main m = new Main(); m.solve(); m.close(); } void close() throws IOException { pw.flush(); pw.close(); br.close(); } int ri() throws IOException { return Integer.parseInt(br.readLine().trim()); } long rl() throws IOException { return Long.parseLong(br.readLine().trim()); } int[] ril(int n) throws IOException { int[] nums = new int[n]; int c = 0; for (int i = 0; i < n; i++) { int sign = 1; c = br.read(); int x = 0; if (c == '-') { sign = -1; c = br.read(); } while (c >= '0' && c <= '9') { x = x * 10 + c - '0'; c = br.read(); } nums[i] = x * sign; } while (c != '\n' && c != -1) c = br.read(); return nums; } long[] rll(int n) throws IOException { long[] nums = new long[n]; int c = 0; for (int i = 0; i < n; i++) { int sign = 1; c = br.read(); long x = 0; if (c == '-') { sign = -1; c = br.read(); } while (c >= '0' && c <= '9') { x = x * 10 + c - '0'; c = br.read(); } nums[i] = x * sign; } while (c != '\n' && c != -1) c = br.read(); return nums; } int[] rkil() throws IOException { int sign = 1; int c = br.read(); int x = 0; if (c == '-') { sign = -1; c = br.read(); } while (c >= '0' && c <= '9') { x = x * 10 + c - '0'; c = br.read(); } return ril(x); } long[] rkll() throws IOException { int sign = 1; int c = br.read(); int x = 0; if (c == '-') { sign = -1; c = br.read(); } while (c >= '0' && c <= '9') { x = x * 10 + c - '0'; c = br.read(); } return rll(x); } char[] rs() throws IOException { return br.readLine().toCharArray(); } void sort(int[] A) { Random r = new Random(); for (int i = A.length-1; i > 0; i--) { int j = r.nextInt(i+1); int temp = A[i]; A[i] = A[j]; A[j] = temp; } Arrays.sort(A); } void printDouble(double d) { pw.printf("%.16f", d); } } class UnionFind { int n; int numComponents; int[] parent; int[] rank; UnionFind(int n) { this.n = numComponents = n; parent = new int[n]; rank = new int[n]; for (int i = 0; i < n; i++) parent[i] = i; } void union(int u, int v) { int x = find(u); int y = find(v); if (x == y) return; if (rank[x] < rank[y]) parent[x] = y; else if (rank[x] > rank[y]) parent[y] = x; else { parent[x] = y; rank[y]++; } numComponents--; } int find(int u) { int current = u; List<Integer> toUpdate = new ArrayList<>(); while (parent[current] != current) { toUpdate.add(current); current = parent[current]; } for (Integer node : toUpdate) parent[node] = current; return current; } int getNumComponents() { return numComponents; } } class Multiset<T extends Comparable<T>> { private TreeMap<T, Integer> map = new TreeMap<>(); private int size; Multiset() {} Multiset(Comparator<T> comp) { map = new TreeMap<>(comp); } boolean isEmpty() { return size == 0; } int size() { return size; } int count(T t) { return map.getOrDefault(t, 0); } boolean contains(T t) { return map.containsKey(t); } void add(T t) { add(t, 1); } void add(T t, int count) { map.put(t, map.getOrDefault(t, 0) + count); size += count; } void remove(T t) { remove(t, 1); } void remove(T t, int count) { int curr = map.get(t); if (count > curr) throw new RuntimeException(); if (curr == count) map.remove(t); else map.put(t, curr - count); size -= count; } T first() { return map.firstKey(); }; T last() { return map.lastKey(); }; T lower(T t) { return map.lowerKey(t); } T higher(T t) { return map.higherKey(t); } T floor(T t) { return map.floorKey(t); } T ceiling(T t) { return map.ceilingKey(t); } Set<Map.Entry<T, Integer>> entrySet() { return map.entrySet(); } }
Java
["3\n5 5\n1 5 8 8 7\n5 2 1 4 3\n1 6 9 7 5\n9 3 3 3 2\n1 7 9 9 8\n3 3\n8 9 8\n1 5 3\n7 5 7\n2 6\n3 3 3 2 2 2\n1 1 1 4 4 4"]
4 seconds
["YES\nBRBRB 1\nNO\nYES\nRB 3"]
NoteThe coloring and the cut for the first testcase:
Java 11
standard input
[ "brute force", "constructive algorithms", "implementation", "sortings" ]
10751c875f4d7667ba21685c57cddd9e
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n, m \le 5 \cdot 10^5$$$; $$$n \cdot m \le 10^6$$$) — the number of rows and the number of columns in the matrix, respectively. The $$$i$$$-th of the next $$$n$$$ lines contains $$$m$$$ integers $$$a_{i1}, a_{i2}, \dots, a_{im}$$$ ($$$1 \le a_{ij} \le 10^6$$$). The sum of $$$n \cdot m$$$ over all testcases doesn't exceed $$$10^6$$$.
2,400
For each testcase print an answer. If there are no perfect colorings and cuts in the matrix, then print "NO". Otherwise, first, print "YES". Then a string, consisting of $$$n$$$ characters: the $$$i$$$-th character should be 'R' if the $$$i$$$-th row is colored red and 'B' if it's colored blue. The string should contain at least one 'R' and at least one 'B'. Finally, print an integer $$$k$$$ ($$$1 \le k &lt; m$$$) — the number of columns from the left that are cut.
standard output
PASSED
8a75e7741d5bccd3033ccd549ba66c8d
train_108.jsonl
1635518100
You are given a matrix, consisting of $$$n$$$ rows and $$$m$$$ columns. The $$$j$$$-th cell of the $$$i$$$-th row contains an integer $$$a_{ij}$$$.First, you have to color each row of the matrix either red or blue in such a way that at least one row is colored red and at least one row is colored blue.Then, you have to choose an integer $$$k$$$ ($$$1 \le k &lt; m$$$) and cut the colored matrix in such a way that the first $$$k$$$ columns become a separate matrix (the left matrix) and the last $$$m-k$$$ columns become a separate matrix (the right matrix).The coloring and the cut are called perfect if two properties hold: every red cell in the left matrix contains an integer greater than every blue cell in the left matrix; every blue cell in the right matrix contains an integer greater than every red cell in the right matrix. Find any perfect coloring and cut, or report that there are none.
256 megabytes
import java.util.*; import java.io.*; public class _116 { public static void main(String[] args) { MyScanner sc = new MyScanner(); PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); int t = sc.nextInt(); outer: while (t-- > 0) { 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 [][] pmin = new int[n][m]; int [][] pmax = new int[n][m]; int [][] smin = new int[n][m]; int [][] smax = new int[n][m]; for (int i = 0; i < n; i++) { int mn = a[i][0]; int mx = a[i][0]; pmin[i][0] = mn; pmax[i][0] = mx; for (int j = 1; j < m; j++) { mn = Math.min(mn, a[i][j]); mx = Math.max(mx, a[i][j]); pmax[i][j] = mx; pmin[i][j] = mn; } mn = a[i][m - 1]; mx = a[i][m - 1]; smin[i][m - 1] = mn; smax[i][m - 1] = mx; for (int j = m - 2; j >= 0; j--) { mn = Math.min(mn, a[i][j]); mx = Math.max(mx, a[i][j]); smax[i][j] = mx; smin[i][j] = mn; } } for (int cut = 0; cut < m - 1; cut++) { ArrayList<Pair> b = new ArrayList<>(); for (int i = 0; i < n; i++) { b.add(new Pair(pmin[i][cut], pmax[i][cut], smin[i][cut + 1], smax[i][cut + 1], i)); } Collections.sort(b, Comparator.comparingInt(x -> x.rmax)); int sz = b.size(); int [] rmin = new int[sz]; int [] lmin = new int[sz]; int [] lmax = new int[sz]; int [] rmax = new int[sz]; rmin[sz - 1] = b.get(sz - 1).rmin; lmax[sz - 1] = b.get(sz - 1).lmax; for (int i = sz - 2; i >= 0; i--) { rmin[i] = Math.min(rmin[i + 1], b.get(i).rmin); lmax[i] = Math.max(lmax[i + 1], b.get(i).lmax); } lmin[0] = b.get(0).lmin; rmax[0] = b.get(0).rmax; for (int i = 1; i < sz; i++) { lmin[i] = Math.min(lmin[i - 1], b.get(i).lmin); rmax[i] = Math.max(rmax[i - 1], b.get(i).rmax); } for (int i = 0; i < n - 1; i++) { if (rmax[i] < rmin[i + 1] && lmin[i] > lmax[i + 1]) { out.println("YES"); int [] res = new int[n]; for (int j = 0; j <= i; j++) { res[b.get(j).i] = 1; } for (int j = 0; j < n; j++) { out.print(res[j] == 1 ? 'R' : 'B'); } out.print(" "); out.print(cut + 1); out.println(); continue outer; } } } out.println("NO"); } out.close(); } static class Pair { int lmin; int lmax; int rmin; int rmax; int i; Pair(int lmin, int lmax, int rmin, int rmax, int i) { this.lmin = lmin; this.rmin = rmin; this.rmax = rmax; this.lmax = lmax; this.i = i; } } static void sort(int[] a) { ArrayList<Integer> q = new ArrayList<>(); for (int i : a) q.add(i); Collections.sort(q); for (int i = 0; i < a.length; i++) a[i] = q.get(i); } static void sort(long[] a) { ArrayList<Long> q = new ArrayList<>(); for (long i : a) q.add(i); Collections.sort(q); for (int i = 0; i < a.length; i++) a[i] = q.get(i); } //-----------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
["3\n5 5\n1 5 8 8 7\n5 2 1 4 3\n1 6 9 7 5\n9 3 3 3 2\n1 7 9 9 8\n3 3\n8 9 8\n1 5 3\n7 5 7\n2 6\n3 3 3 2 2 2\n1 1 1 4 4 4"]
4 seconds
["YES\nBRBRB 1\nNO\nYES\nRB 3"]
NoteThe coloring and the cut for the first testcase:
Java 11
standard input
[ "brute force", "constructive algorithms", "implementation", "sortings" ]
10751c875f4d7667ba21685c57cddd9e
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n, m \le 5 \cdot 10^5$$$; $$$n \cdot m \le 10^6$$$) — the number of rows and the number of columns in the matrix, respectively. The $$$i$$$-th of the next $$$n$$$ lines contains $$$m$$$ integers $$$a_{i1}, a_{i2}, \dots, a_{im}$$$ ($$$1 \le a_{ij} \le 10^6$$$). The sum of $$$n \cdot m$$$ over all testcases doesn't exceed $$$10^6$$$.
2,400
For each testcase print an answer. If there are no perfect colorings and cuts in the matrix, then print "NO". Otherwise, first, print "YES". Then a string, consisting of $$$n$$$ characters: the $$$i$$$-th character should be 'R' if the $$$i$$$-th row is colored red and 'B' if it's colored blue. The string should contain at least one 'R' and at least one 'B'. Finally, print an integer $$$k$$$ ($$$1 \le k &lt; m$$$) — the number of columns from the left that are cut.
standard output
PASSED
1149da4a5f0fd65cc1d80206d8407bff
train_108.jsonl
1635518100
You are given a matrix, consisting of $$$n$$$ rows and $$$m$$$ columns. The $$$j$$$-th cell of the $$$i$$$-th row contains an integer $$$a_{ij}$$$.First, you have to color each row of the matrix either red or blue in such a way that at least one row is colored red and at least one row is colored blue.Then, you have to choose an integer $$$k$$$ ($$$1 \le k &lt; m$$$) and cut the colored matrix in such a way that the first $$$k$$$ columns become a separate matrix (the left matrix) and the last $$$m-k$$$ columns become a separate matrix (the right matrix).The coloring and the cut are called perfect if two properties hold: every red cell in the left matrix contains an integer greater than every blue cell in the left matrix; every blue cell in the right matrix contains an integer greater than every red cell in the right matrix. Find any perfect coloring and cut, or report that there are none.
256 megabytes
import java.util.*; public class D { public static final int MOD998 = 998244353; public static final int MOD100 = 1000000007; public static void main(String[] args) throws Exception { ContestScanner sc = new ContestScanner(); ContestPrinter cp = new ContestPrinter(); int T = sc.nextInt(); for (int t = 0; t < T; t++) { int N = sc.nextInt(); int M = sc.nextInt(); int[][] A = sc.nextIntMatrix(N, M); Integer[] order = new Integer[N]; for (int n = 0; n < N; n++) { order[n] = n; } Arrays.sort(order, Comparator.comparingInt(i -> A[i][0])); Arrays.sort(A, Comparator.comparingInt(a -> a[0])); // cp.println(Arrays.toString(order)); int[][] lu = new int[N][M];// max int[][] ru = new int[N][M];// min int[][] ld = new int[N][M];// min int[][] rd = new int[N][M];// max for (int n = 0; n < N; n++) { for (int m = 0; m < M; m++) { if (n == 0) { if (m == 0) { lu[n][m] = A[n][m]; } else { lu[n][m] = Math.max(lu[n][m - 1], A[n][m]); } } else { if (m == 0) { lu[n][m] = Math.max(lu[n - 1][m], A[n][m]); } else { lu[n][m] = Math.max(Math.max(lu[n - 1][m], lu[n][m - 1]), A[n][m]); } } } } for (int n = 0; n < N; n++) { for (int m = M - 1; m >= 0; m--) { if (n == 0) { if (m == M - 1) { ru[n][m] = A[n][m]; } else { ru[n][m] = Math.min(ru[n][m + 1], A[n][m]); } } else { if (m == M - 1) { ru[n][m] = Math.min(ru[n - 1][m], A[n][m]); } else { ru[n][m] = Math.min(Math.min(ru[n - 1][m], ru[n][m + 1]), A[n][m]); } } } } for (int n = N - 1; n >= 0; n--) { for (int m = 0; m < M; m++) { if (n == N - 1) { if (m == 0) { ld[n][m] = A[n][m]; } else { ld[n][m] = Math.min(ld[n][m - 1], A[n][m]); } } else { if (m == 0) { ld[n][m] = Math.min(ld[n + 1][m], A[n][m]); } else { ld[n][m] = Math.min(Math.min(ld[n + 1][m], ld[n][m - 1]), A[n][m]); } } } } for (int n = N - 1; n >= 0; n--) { for (int m = M - 1; m >= 0; m--) { if (n == N - 1) { if (m == M - 1) { rd[n][m] = A[n][m]; } else { rd[n][m] = Math.max(rd[n][m + 1], A[n][m]); } } else { if (m == M - 1) { rd[n][m] = Math.max(rd[n + 1][m], A[n][m]); } else { rd[n][m] = Math.max(Math.max(rd[n + 1][m], rd[n][m + 1]), A[n][m]); } } } } boolean found = false; int ansn = -1; int ansm = -1; for (int n = 0; n < N - 1; n++) { for (int m = 0; m < M - 1; m++) { if (lu[n][m] < ld[n + 1][m] && ru[n][m + 1] > rd[n + 1][m + 1]) { found = true; ansn = n; ansm = m; } } } if (found) { cp.println("YES"); boolean[] blue = new boolean[N]; for (int n = 0; n <= ansn; n++) { blue[order[n]] = true; } for (boolean b : blue) { cp.print(b ? "B" : "R"); } cp.println(" " + (ansm + 1)); } else { cp.println("NO"); } } cp.close(); } ////////////////// // My Library // ////////////////// public static int zeroOneBFS(int[][][] weighted_graph, int start, int goal) { int[] dist = new int[weighted_graph.length]; Arrays.fill(dist, Integer.MAX_VALUE); dist[start] = 0; LinkedList<Integer> queue = new LinkedList<>(); queue.add(start); while (!queue.isEmpty()) { int now = queue.poll(); if (now == goal) { return dist[goal]; } for (int[] info : weighted_graph[now]) { if (dist[info[0]] > dist[now] + info[1]) { dist[info[0]] = dist[now] + info[1]; if (info[1] == 0) { queue.addFirst(info[0]); } else { queue.addLast(info[0]); } } } } return -1; } public static int[] zeroOneBFSAll(int[][][] weighted_graph, int start) { int[] dist = new int[weighted_graph.length]; Arrays.fill(dist, Integer.MAX_VALUE); dist[start] = 0; LinkedList<Integer> queue = new LinkedList<>(); queue.add(start); while (!queue.isEmpty()) { int now = queue.poll(); for (int[] info : weighted_graph[now]) { if (dist[info[0]] > dist[now] + info[1]) { dist[info[0]] = dist[now] + info[1]; if (info[1] == 0) { queue.addFirst(info[0]); } else { queue.addLast(info[0]); } } } } return dist; } public static long dijkstra(int[][][] weighted_graph, int start, int goal) { long[] dist = new long[weighted_graph.length]; Arrays.fill(dist, 0, dist.length, Long.MAX_VALUE); dist[start] = 0; PriorityQueue<Pair<Integer, Long>> unsettled = new PriorityQueue<>((u, v) -> (int) (u.cdr - v.cdr)); unsettled.offer(new Pair<Integer, Long>(start, 0L)); while (!unsettled.isEmpty()) { Pair<Integer, Long> pair = unsettled.poll(); int now = pair.car; if (now == goal) { return dist[goal]; } if (dist[now] < pair.cdr) { continue; } for (int[] info : weighted_graph[now]) { if (dist[info[0]] > dist[now] + info[1]) { dist[info[0]] = dist[now] + info[1]; unsettled.offer(new Pair<Integer, Long>(info[0], dist[info[0]])); } } } return -1; } public static long[] dijkstraAll(int[][][] weighted_graph, int start) { long[] dist = new long[weighted_graph.length]; Arrays.fill(dist, 0, dist.length, Long.MAX_VALUE); dist[start] = 0; PriorityQueue<Pair<Integer, Long>> unsettled = new PriorityQueue<>((u, v) -> (int) (u.cdr - v.cdr)); unsettled.offer(new Pair<Integer, Long>(start, 0L)); while (!unsettled.isEmpty()) { Pair<Integer, Long> pair = unsettled.poll(); int now = pair.car; if (dist[now] < pair.cdr) { continue; } for (int[] info : weighted_graph[now]) { if (dist[info[0]] > dist[now] + info[1]) { dist[info[0]] = dist[now] + info[1]; unsettled.offer(new Pair<Integer, Long>(info[0], dist[info[0]])); } } } return dist; } public static class Pair<A, B> { public final A car; public final B cdr; public Pair(A car_, B cdr_) { car = car_; cdr = cdr_; } private static boolean eq(Object o1, Object o2) { return o1 == null ? o2 == null : o1.equals(o2); } private static int hc(Object o) { return o == null ? 0 : o.hashCode(); } @Override public boolean equals(Object o) { if (!(o instanceof Pair)) return false; Pair<?, ?> rhs = (Pair<?, ?>) o; return eq(car, rhs.car) && eq(cdr, rhs.cdr); } @Override public int hashCode() { return hc(car) ^ hc(cdr); } } public static class Tuple1<A> extends Pair<A, Object> { public Tuple1(A a) { super(a, null); } } public static class Tuple2<A, B> extends Pair<A, Tuple1<B>> { public Tuple2(A a, B b) { super(a, new Tuple1<>(b)); } } public static class Tuple3<A, B, C> extends Pair<A, Tuple2<B, C>> { public Tuple3(A a, B b, C c) { super(a, new Tuple2<>(b, c)); } } public static class Tuple4<A, B, C, D> extends Pair<A, Tuple3<B, C, D>> { public Tuple4(A a, B b, C c, D d) { super(a, new Tuple3<>(b, c, d)); } } public static class Tuple5<A, B, C, D, E> extends Pair<A, Tuple4<B, C, D, E>> { public Tuple5(A a, B b, C c, D d, E e) { super(a, new Tuple4<>(b, c, d, e)); } } public static class PriorityQueueLogTime<T> { private PriorityQueue<T> queue; private Multiset<T> total; private int size = 0; public PriorityQueueLogTime() { queue = new PriorityQueue<>(); total = new Multiset<>(); } public PriorityQueueLogTime(Comparator<T> c) { queue = new PriorityQueue<>(c); total = new Multiset<>(); } public void clear() { queue.clear(); total.clear(); size = 0; } public boolean contains(T e) { return total.count(e) > 0; } public boolean isEmpty() { return size == 0; } public boolean offer(T e) { total.addOne(e); size++; return queue.offer(e); } public T peek() { if (total.isEmpty()) { return null; } simplify(); return queue.peek(); } public T poll() { if (total.isEmpty()) { return null; } simplify(); size--; T res = queue.poll(); total.removeOne(res); return res; } public void remove(T e) { total.removeOne(e); size--; } public int size() { return size; } private void simplify() { while (total.count(queue.peek()) == 0) { queue.poll(); } } } static int[][] scanGraphOneIndexed(ContestScanner sc, int node, int edge, boolean undirected) { int[][] arr = sc.nextIntArrayMulti(edge, 2); for (int n = 0; n < edge; n++) { arr[0][n]--; arr[1][n]--; } return GraphBuilder.makeGraph(node, edge, arr[0], arr[1], undirected); } static int[][][] scanWeightedGraphOneIndexed(ContestScanner sc, int node, int edge, boolean undirected) { int[][] arr = sc.nextIntArrayMulti(edge, 3); for (int n = 0; n < edge; n++) { arr[0][n]--; arr[1][n]--; } return GraphBuilder.makeGraphWithWeight(node, edge, arr[0], arr[1], arr[2], undirected); } static class EdgeData { private int capacity; private int[] from, to, weight; private int p = 0; private boolean weighted; public EdgeData(boolean weighted) { this(weighted, 500000); } public EdgeData(boolean weighted, int initial_capacity) { capacity = initial_capacity; from = new int[capacity]; to = new int[capacity]; weight = new int[capacity]; this.weighted = weighted; } public void addEdge(int u, int v) { if (weighted) { System.err.println("The graph is weighted!"); return; } if (p == capacity) { int[] newfrom = new int[capacity * 2]; int[] newto = new int[capacity * 2]; System.arraycopy(from, 0, newfrom, 0, capacity); System.arraycopy(to, 0, newto, 0, capacity); capacity *= 2; } from[p] = u; to[p] = v; p++; } public void addEdge(int u, int v, int w) { if (!weighted) { System.err.println("The graph is NOT weighted!"); return; } if (p == capacity) { int[] newfrom = new int[capacity * 2]; int[] newto = new int[capacity * 2]; int[] newweight = new int[capacity * 2]; System.arraycopy(from, 0, newfrom, 0, capacity); System.arraycopy(to, 0, newto, 0, capacity); System.arraycopy(weight, 0, newweight, 0, capacity); capacity *= 2; } from[p] = u; to[p] = v; weight[p] = w; p++; } public int[] getFrom() { int[] result = new int[p]; System.arraycopy(from, 0, result, 0, p); return result; } public int[] getTo() { int[] result = new int[p]; System.arraycopy(to, 0, result, 0, p); return result; } public int[] getWeight() { int[] result = new int[p]; System.arraycopy(weight, 0, result, 0, p); return result; } public int size() { return p; } } //////////////////////////////// // Atcoder Library for Java // //////////////////////////////// static class MathLib { private static long safe_mod(long x, long m) { x %= m; if (x < 0) x += m; return x; } private static long[] inv_gcd(long a, long b) { a = safe_mod(a, b); if (a == 0) return new long[] { b, 0 }; long s = b, t = a; long m0 = 0, m1 = 1; while (t > 0) { long u = s / t; s -= t * u; m0 -= m1 * u; long tmp = s; s = t; t = tmp; tmp = m0; m0 = m1; m1 = tmp; } if (m0 < 0) m0 += b / s; return new long[] { s, m0 }; } public static long gcd(long a, long b) { a = java.lang.Math.abs(a); b = java.lang.Math.abs(b); return inv_gcd(a, b)[0]; } public static long lcm(long a, long b) { a = java.lang.Math.abs(a); b = java.lang.Math.abs(b); return a / gcd(a, b) * b; } public static long pow_mod(long x, long n, int m) { assert n >= 0; assert m >= 1; if (m == 1) return 0L; x = safe_mod(x, m); long ans = 1L; while (n > 0) { if ((n & 1) == 1) ans = (ans * x) % m; x = (x * x) % m; n >>>= 1; } return ans; } public static long[] crt(long[] r, long[] m) { assert (r.length == m.length); int n = r.length; long r0 = 0, m0 = 1; for (int i = 0; i < n; i++) { assert (1 <= m[i]); long r1 = safe_mod(r[i], m[i]), m1 = m[i]; if (m0 < m1) { long tmp = r0; r0 = r1; r1 = tmp; tmp = m0; m0 = m1; m1 = tmp; } if (m0 % m1 == 0) { if (r0 % m1 != r1) return new long[] { 0, 0 }; continue; } long[] ig = inv_gcd(m0, m1); long g = ig[0], im = ig[1]; long u1 = m1 / g; if ((r1 - r0) % g != 0) return new long[] { 0, 0 }; long x = (r1 - r0) / g % u1 * im % u1; r0 += x * m0; m0 *= u1; if (r0 < 0) r0 += m0; // System.err.printf("%d %d\n", r0, m0); } return new long[] { r0, m0 }; } public static long floor_sum(long n, long m, long a, long b) { long ans = 0; if (a >= m) { ans += (n - 1) * n * (a / m) / 2; a %= m; } if (b >= m) { ans += n * (b / m); b %= m; } long y_max = (a * n + b) / m; long x_max = y_max * m - b; if (y_max == 0) return ans; ans += (n - (x_max + a - 1) / a) * y_max; ans += floor_sum(y_max, a, m, (a - x_max % a) % a); return ans; } public static java.util.ArrayList<Long> divisors(long n) { java.util.ArrayList<Long> divisors = new ArrayList<>(); java.util.ArrayList<Long> large = new ArrayList<>(); for (long i = 1; i * i <= n; i++) if (n % i == 0) { divisors.add(i); if (i * i < n) large.add(n / i); } for (int p = large.size() - 1; p >= 0; p--) { divisors.add(large.get(p)); } return divisors; } } static class Multiset<T> extends java.util.TreeMap<T, Long> { public Multiset() { super(); } public Multiset(java.util.List<T> list) { super(); for (T e : list) this.addOne(e); } public long count(Object elm) { return getOrDefault(elm, 0L); } public void add(T elm, long amount) { if (!this.containsKey(elm)) put(elm, amount); else replace(elm, get(elm) + amount); if (this.count(elm) == 0) this.remove(elm); } public void addOne(T elm) { this.add(elm, 1); } public void removeOne(T elm) { this.add(elm, -1); } public void removeAll(T elm) { this.add(elm, -this.count(elm)); } public static <T> Multiset<T> merge(Multiset<T> a, Multiset<T> b) { Multiset<T> c = new Multiset<>(); for (T x : a.keySet()) c.add(x, a.count(x)); for (T y : b.keySet()) c.add(y, b.count(y)); return c; } } static class GraphBuilder { public static int[][] makeGraph(int NumberOfNodes, int NumberOfEdges, int[] from, int[] to, boolean undirected) { int[][] graph = new int[NumberOfNodes][]; int[] outdegree = new int[NumberOfNodes]; for (int i = 0; i < NumberOfEdges; i++) { outdegree[from[i]]++; if (undirected) outdegree[to[i]]++; } for (int i = 0; i < NumberOfNodes; i++) graph[i] = new int[outdegree[i]]; for (int i = 0; i < NumberOfEdges; i++) { graph[from[i]][--outdegree[from[i]]] = to[i]; if (undirected) graph[to[i]][--outdegree[to[i]]] = from[i]; } return graph; } public static int[][][] makeGraphWithWeight(int NumberOfNodes, int NumberOfEdges, int[] from, int[] to, int[] weight, boolean undirected) { int[][][] graph = new int[NumberOfNodes][][]; int[] outdegree = new int[NumberOfNodes]; for (int i = 0; i < NumberOfEdges; i++) { outdegree[from[i]]++; if (undirected) outdegree[to[i]]++; } for (int i = 0; i < NumberOfNodes; i++) graph[i] = new int[outdegree[i]][]; for (int i = 0; i < NumberOfEdges; i++) { graph[from[i]][--outdegree[from[i]]] = new int[] { to[i], weight[i] }; if (undirected) graph[to[i]][--outdegree[to[i]]] = new int[] { from[i], weight[i] }; } return graph; } public static int[][][] makeGraphWithEdgeInfo(int NumberOfNodes, int NumberOfEdges, int[] from, int[] to, boolean undirected) { int[][][] graph = new int[NumberOfNodes][][]; int[] outdegree = new int[NumberOfNodes]; for (int i = 0; i < NumberOfEdges; i++) { outdegree[from[i]]++; if (undirected) outdegree[to[i]]++; } for (int i = 0; i < NumberOfNodes; i++) graph[i] = new int[outdegree[i]][]; for (int i = 0; i < NumberOfEdges; i++) { graph[from[i]][--outdegree[from[i]]] = new int[] { to[i], i, 0 }; if (undirected) graph[to[i]][--outdegree[to[i]]] = new int[] { from[i], i, 1 }; } return graph; } public static int[][][] makeGraphWithWeightAndEdgeInfo(int NumberOfNodes, int NumberOfEdges, int[] from, int[] to, int[] weight, boolean undirected) { int[][][] graph = new int[NumberOfNodes][][]; int[] outdegree = new int[NumberOfNodes]; for (int i = 0; i < NumberOfEdges; i++) { outdegree[from[i]]++; if (undirected) outdegree[to[i]]++; } for (int i = 0; i < NumberOfNodes; i++) graph[i] = new int[outdegree[i]][]; for (int i = 0; i < NumberOfEdges; i++) { graph[from[i]][--outdegree[from[i]]] = new int[] { to[i], weight[i], i, 0 }; if (undirected) graph[to[i]][--outdegree[to[i]]] = new int[] { from[i], weight[i], i, 1 }; } return graph; } } static class DSU { private int n; private int[] parentOrSize; public DSU(int n) { this.n = n; this.parentOrSize = new int[n]; java.util.Arrays.fill(parentOrSize, -1); } int merge(int a, int b) { if (!(0 <= a && a < n)) throw new IndexOutOfBoundsException("a=" + a); if (!(0 <= b && b < n)) throw new IndexOutOfBoundsException("b=" + b); int x = leader(a); int y = leader(b); if (x == y) return x; if (-parentOrSize[x] < -parentOrSize[y]) { int tmp = x; x = y; y = tmp; } parentOrSize[x] += parentOrSize[y]; parentOrSize[y] = x; return x; } boolean same(int a, int b) { if (!(0 <= a && a < n)) throw new IndexOutOfBoundsException("a=" + a); if (!(0 <= b && b < n)) throw new IndexOutOfBoundsException("b=" + b); return leader(a) == leader(b); } int leader(int a) { if (parentOrSize[a] < 0) { return a; } else { parentOrSize[a] = leader(parentOrSize[a]); return parentOrSize[a]; } } int size(int a) { if (!(0 <= a && a < n)) throw new IndexOutOfBoundsException("" + a); return -parentOrSize[leader(a)]; } java.util.ArrayList<java.util.ArrayList<Integer>> groups() { int[] leaderBuf = new int[n]; int[] groupSize = new int[n]; for (int i = 0; i < n; i++) { leaderBuf[i] = leader(i); groupSize[leaderBuf[i]]++; } java.util.ArrayList<java.util.ArrayList<Integer>> result = new java.util.ArrayList<>(n); for (int i = 0; i < n; i++) { result.add(new java.util.ArrayList<>(groupSize[i])); } for (int i = 0; i < n; i++) { result.get(leaderBuf[i]).add(i); } result.removeIf(java.util.ArrayList::isEmpty); return result; } } static class ModIntFactory { private final ModArithmetic ma; private final int mod; private final boolean usesMontgomery; private final ModArithmetic.ModArithmeticMontgomery maMontgomery; private ArrayList<Integer> factorial; private ArrayList<Integer> factorial_inversion; public ModIntFactory(int mod) { this.ma = ModArithmetic.of(mod); this.usesMontgomery = ma instanceof ModArithmetic.ModArithmeticMontgomery; this.maMontgomery = usesMontgomery ? (ModArithmetic.ModArithmeticMontgomery) ma : null; this.mod = mod; this.factorial = new ArrayList<>(); this.factorial_inversion = new ArrayList<>(); } public ModInt create(long value) { if ((value %= mod) < 0) value += mod; if (usesMontgomery) { return new ModInt(maMontgomery.generate(value)); } else { return new ModInt((int) value); } } private void prepareFactorial(int max) { factorial.ensureCapacity(max + 1); if (factorial.size() == 0) factorial.add(1); for (int i = factorial.size(); i <= max; i++) { factorial.add(ma.mul(factorial.get(i - 1), i)); } } public ModInt factorial(int i) { prepareFactorial(i); return create(factorial.get(i)); } public ModInt permutation(int n, int r) { if (n < 0 || r < 0 || n < r) return create(0); prepareFactorial(n); if (factorial_inversion.size() > n) { return create(ma.mul(factorial.get(n), factorial_inversion.get(n - r))); } return create(ma.div(factorial.get(n), factorial.get(n - r))); } public ModInt combination(int n, int r) { if (n < 0 || r < 0 || n < r) return create(0); prepareFactorial(n); if (factorial_inversion.size() > n) { return create( ma.mul(factorial.get(n), ma.mul(factorial_inversion.get(n - r), factorial_inversion.get(r)))); } return create(ma.div(factorial.get(n), ma.mul(factorial.get(r), factorial.get(n - r)))); } public void prepareFactorialInv(int max) { prepareFactorial(max); factorial_inversion.ensureCapacity(max + 1); for (int i = factorial_inversion.size(); i <= max; i++) { factorial_inversion.add(ma.inv(factorial.get(i))); } } public int getMod() { return mod; } public class ModInt { private int value; private ModInt(int value) { this.value = value; } public int mod() { return mod; } public int value() { if (ma instanceof ModArithmetic.ModArithmeticMontgomery) { return ((ModArithmetic.ModArithmeticMontgomery) ma).reduce(value); } return value; } public ModInt add(ModInt mi) { return new ModInt(ma.add(value, mi.value)); } public ModInt add(ModInt mi1, ModInt mi2) { return new ModInt(ma.add(value, mi1.value)).addAsg(mi2); } public ModInt add(ModInt mi1, ModInt mi2, ModInt mi3) { return new ModInt(ma.add(value, mi1.value)).addAsg(mi2).addAsg(mi3); } public ModInt add(ModInt mi1, ModInt mi2, ModInt mi3, ModInt mi4) { return new ModInt(ma.add(value, mi1.value)).addAsg(mi2).addAsg(mi3).addAsg(mi4); } public ModInt add(ModInt mi1, ModInt... mis) { ModInt mi = add(mi1); for (ModInt m : mis) mi.addAsg(m); return mi; } public ModInt add(long mi) { return new ModInt(ma.add(value, ma.remainder(mi))); } public ModInt sub(ModInt mi) { return new ModInt(ma.sub(value, mi.value)); } public ModInt sub(long mi) { return new ModInt(ma.sub(value, ma.remainder(mi))); } public ModInt mul(ModInt mi) { return new ModInt(ma.mul(value, mi.value)); } public ModInt mul(ModInt mi1, ModInt mi2) { return new ModInt(ma.mul(value, mi1.value)).mulAsg(mi2); } public ModInt mul(ModInt mi1, ModInt mi2, ModInt mi3) { return new ModInt(ma.mul(value, mi1.value)).mulAsg(mi2).mulAsg(mi3); } public ModInt mul(ModInt mi1, ModInt mi2, ModInt mi3, ModInt mi4) { return new ModInt(ma.mul(value, mi1.value)).mulAsg(mi2).mulAsg(mi3).mulAsg(mi4); } public ModInt mul(ModInt mi1, ModInt... mis) { ModInt mi = mul(mi1); for (ModInt m : mis) mi.mulAsg(m); return mi; } public ModInt mul(long mi) { return new ModInt(ma.mul(value, ma.remainder(mi))); } public ModInt div(ModInt mi) { return new ModInt(ma.div(value, mi.value)); } public ModInt div(long mi) { return new ModInt(ma.div(value, ma.remainder(mi))); } public ModInt inv() { return new ModInt(ma.inv(value)); } public ModInt pow(long b) { return new ModInt(ma.pow(value, b)); } public ModInt addAsg(ModInt mi) { this.value = ma.add(value, mi.value); return this; } public ModInt addAsg(ModInt mi1, ModInt mi2) { return addAsg(mi1).addAsg(mi2); } public ModInt addAsg(ModInt mi1, ModInt mi2, ModInt mi3) { return addAsg(mi1).addAsg(mi2).addAsg(mi3); } public ModInt addAsg(ModInt mi1, ModInt mi2, ModInt mi3, ModInt mi4) { return addAsg(mi1).addAsg(mi2).addAsg(mi3).addAsg(mi4); } public ModInt addAsg(ModInt... mis) { for (ModInt m : mis) addAsg(m); return this; } public ModInt addAsg(long mi) { this.value = ma.add(value, ma.remainder(mi)); return this; } public ModInt subAsg(ModInt mi) { this.value = ma.sub(value, mi.value); return this; } public ModInt subAsg(long mi) { this.value = ma.sub(value, ma.remainder(mi)); return this; } public ModInt mulAsg(ModInt mi) { this.value = ma.mul(value, mi.value); return this; } public ModInt mulAsg(ModInt mi1, ModInt mi2) { return mulAsg(mi1).mulAsg(mi2); } public ModInt mulAsg(ModInt mi1, ModInt mi2, ModInt mi3) { return mulAsg(mi1).mulAsg(mi2).mulAsg(mi3); } public ModInt mulAsg(ModInt mi1, ModInt mi2, ModInt mi3, ModInt mi4) { return mulAsg(mi1).mulAsg(mi2).mulAsg(mi3).mulAsg(mi4); } public ModInt mulAsg(ModInt... mis) { for (ModInt m : mis) mulAsg(m); return this; } public ModInt mulAsg(long mi) { this.value = ma.mul(value, ma.remainder(mi)); return this; } public ModInt divAsg(ModInt mi) { this.value = ma.div(value, mi.value); return this; } public ModInt divAsg(long mi) { this.value = ma.div(value, ma.remainder(mi)); return this; } @Override public String toString() { return String.valueOf(value()); } @Override public boolean equals(Object o) { if (o instanceof ModInt) { ModInt mi = (ModInt) o; return mod() == mi.mod() && value() == mi.value(); } return false; } @Override public int hashCode() { return (1 * 37 + mod()) * 37 + value(); } } private static abstract class ModArithmetic { abstract int mod(); abstract int remainder(long value); abstract int add(int a, int b); abstract int sub(int a, int b); abstract int mul(int a, int b); int div(int a, int b) { return mul(a, inv(b)); } int inv(int a) { int b = mod(); if (b == 1) return 0; long u = 1, v = 0; while (b >= 1) { int t = a / b; a -= t * b; int tmp1 = a; a = b; b = tmp1; u -= t * v; long tmp2 = u; u = v; v = tmp2; } if (a != 1) { throw new ArithmeticException("divide by zero"); } return remainder(u); } int pow(int a, long b) { if (b < 0) throw new ArithmeticException("negative power"); int r = 1; int x = a; while (b > 0) { if ((b & 1) == 1) r = mul(r, x); x = mul(x, x); b >>= 1; } return r; } static ModArithmetic of(int mod) { if (mod <= 0) { throw new IllegalArgumentException(); } else if (mod == 1) { return new ModArithmetic1(); } else if (mod == 2) { return new ModArithmetic2(); } else if (mod == 998244353) { return new ModArithmetic998244353(); } else if (mod == 1000000007) { return new ModArithmetic1000000007(); } else if ((mod & 1) == 1) { return new ModArithmeticMontgomery(mod); } else { return new ModArithmeticBarrett(mod); } } private static final class ModArithmetic1 extends ModArithmetic { int mod() { return 1; } int remainder(long value) { return 0; } int add(int a, int b) { return 0; } int sub(int a, int b) { return 0; } int mul(int a, int b) { return 0; } int pow(int a, long b) { return 0; } } private static final class ModArithmetic2 extends ModArithmetic { int mod() { return 2; } int remainder(long value) { return (int) (value & 1); } int add(int a, int b) { return a ^ b; } int sub(int a, int b) { return a ^ b; } int mul(int a, int b) { return a & b; } } private static final class ModArithmetic998244353 extends ModArithmetic { private final int mod = 998244353; int mod() { return mod; } int remainder(long value) { return (int) ((value %= mod) < 0 ? value + mod : value); } int add(int a, int b) { int res = a + b; return res >= mod ? res - mod : res; } int sub(int a, int b) { int res = a - b; return res < 0 ? res + mod : res; } int mul(int a, int b) { return (int) (((long) a * b) % mod); } } private static final class ModArithmetic1000000007 extends ModArithmetic { private final int mod = 1000000007; int mod() { return mod; } int remainder(long value) { return (int) ((value %= mod) < 0 ? value + mod : value); } int add(int a, int b) { int res = a + b; return res >= mod ? res - mod : res; } int sub(int a, int b) { int res = a - b; return res < 0 ? res + mod : res; } int mul(int a, int b) { return (int) (((long) a * b) % mod); } } private static final class ModArithmeticMontgomery extends ModArithmeticDynamic { private final long negInv; private final long r2; private ModArithmeticMontgomery(int mod) { super(mod); long inv = 0; long s = 1, t = 0; for (int i = 0; i < 32; i++) { if ((t & 1) == 0) { t += mod; inv += s; } t >>= 1; s <<= 1; } long r = (1l << 32) % mod; this.negInv = inv; this.r2 = (r * r) % mod; } private int generate(long x) { return reduce(x * r2); } private int reduce(long x) { x = (x + ((x * negInv) & 0xffff_ffffl) * mod) >>> 32; return (int) (x < mod ? x : x - mod); } @Override int remainder(long value) { return generate((value %= mod) < 0 ? value + mod : value); } @Override int mul(int a, int b) { return reduce((long) a * b); } @Override int inv(int a) { return super.inv(reduce(a)); } @Override int pow(int a, long b) { return generate(super.pow(a, b)); } } private static final class ModArithmeticBarrett extends ModArithmeticDynamic { private static final long mask = 0xffff_ffffl; private final long mh; private final long ml; private ModArithmeticBarrett(int mod) { super(mod); /** * m = floor(2^64/mod) 2^64 = p*mod + q, 2^32 = a*mod + b => (a*mod + b)^2 = * p*mod + q => p = mod*a^2 + 2ab + floor(b^2/mod) */ long a = (1l << 32) / mod; long b = (1l << 32) % mod; long m = a * a * mod + 2 * a * b + (b * b) / mod; mh = m >>> 32; ml = m & mask; } private int reduce(long x) { long z = (x & mask) * ml; z = (x & mask) * mh + (x >>> 32) * ml + (z >>> 32); z = (x >>> 32) * mh + (z >>> 32); x -= z * mod; return (int) (x < mod ? x : x - mod); } @Override int remainder(long value) { return (int) ((value %= mod) < 0 ? value + mod : value); } @Override int mul(int a, int b) { return reduce((long) a * b); } } private static class ModArithmeticDynamic extends ModArithmetic { final int mod; ModArithmeticDynamic(int mod) { this.mod = mod; } int mod() { return mod; } int remainder(long value) { return (int) ((value %= mod) < 0 ? value + mod : value); } int add(int a, int b) { int sum = a + b; return sum >= mod ? sum - mod : sum; } int sub(int a, int b) { int sum = a - b; return sum < 0 ? sum + mod : sum; } int mul(int a, int b) { return (int) (((long) a * b) % mod); } } } } static class ContestScanner { private final java.io.InputStream in; private final byte[] buffer = new byte[1024]; private int ptr = 0; private int buflen = 0; private static final long LONG_MAX_TENTHS = 922337203685477580L; private static final int LONG_MAX_LAST_DIGIT = 7; private static final int LONG_MIN_LAST_DIGIT = 8; public ContestScanner(java.io.InputStream in) { this.in = in; } public ContestScanner() { this(System.in); } private boolean hasNextByte() { if (ptr < buflen) { return true; } else { ptr = 0; try { buflen = in.read(buffer); } catch (java.io.IOException e) { e.printStackTrace(); } if (buflen <= 0) { return false; } } return true; } private int readByte() { if (hasNextByte()) return buffer[ptr++]; else return -1; } private static boolean isPrintableChar(int c) { return 33 <= c && c <= 126; } public boolean hasNext() { while (hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++; return hasNextByte(); } public String next() { if (!hasNext()) throw new java.util.NoSuchElementException(); StringBuilder sb = new StringBuilder(); int b = readByte(); while (isPrintableChar(b)) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } public long nextLong() { if (!hasNext()) throw new java.util.NoSuchElementException(); long n = 0; boolean minus = false; int b = readByte(); if (b == '-') { minus = true; b = readByte(); } if (b < '0' || '9' < b) { throw new NumberFormatException(); } while (true) { if ('0' <= b && b <= '9') { int digit = b - '0'; if (n >= LONG_MAX_TENTHS) { if (n == LONG_MAX_TENTHS) { if (minus) { if (digit <= LONG_MIN_LAST_DIGIT) { n = -n * 10 - digit; b = readByte(); if (!isPrintableChar(b)) { return n; } else if (b < '0' || '9' < b) { throw new NumberFormatException( String.format("%d%s... is not number", n, Character.toString(b))); } } } else { if (digit <= LONG_MAX_LAST_DIGIT) { n = n * 10 + digit; b = readByte(); if (!isPrintableChar(b)) { return n; } else if (b < '0' || '9' < b) { throw new NumberFormatException( String.format("%d%s... is not number", n, Character.toString(b))); } } } } throw new ArithmeticException( String.format("%s%d%d... overflows long.", minus ? "-" : "", n, digit)); } n = n * 10 + digit; } else if (b == -1 || !isPrintableChar(b)) { return minus ? -n : n; } else { throw new NumberFormatException(); } b = readByte(); } } public int nextInt() { long nl = nextLong(); if (nl < Integer.MIN_VALUE || nl > Integer.MAX_VALUE) throw new NumberFormatException(); return (int) nl; } public double nextDouble() { return Double.parseDouble(next()); } public long[] nextLongArray(int length) { long[] array = new long[length]; for (int i = 0; i < length; i++) array[i] = this.nextLong(); return array; } public long[] nextLongArray(int length, java.util.function.LongUnaryOperator map) { long[] array = new long[length]; for (int i = 0; i < length; i++) array[i] = map.applyAsLong(this.nextLong()); return array; } public int[] nextIntArray(int length) { int[] array = new int[length]; for (int i = 0; i < length; i++) array[i] = this.nextInt(); return array; } public int[][] nextIntArrayMulti(int length, int width) { int[][] arrays = new int[width][length]; for (int i = 0; i < length; i++) { for (int j = 0; j < width; j++) arrays[j][i] = this.nextInt(); } return arrays; } public int[] nextIntArray(int length, java.util.function.IntUnaryOperator map) { int[] array = new int[length]; for (int i = 0; i < length; i++) array[i] = map.applyAsInt(this.nextInt()); return array; } public double[] nextDoubleArray(int length) { double[] array = new double[length]; for (int i = 0; i < length; i++) array[i] = this.nextDouble(); return array; } public double[] nextDoubleArray(int length, java.util.function.DoubleUnaryOperator map) { double[] array = new double[length]; for (int i = 0; i < length; i++) array[i] = map.applyAsDouble(this.nextDouble()); return array; } public long[][] nextLongMatrix(int height, int width) { long[][] mat = new long[height][width]; for (int h = 0; h < height; h++) for (int w = 0; w < width; w++) { mat[h][w] = this.nextLong(); } return mat; } public int[][] nextIntMatrix(int height, int width) { int[][] mat = new int[height][width]; for (int h = 0; h < height; h++) for (int w = 0; w < width; w++) { mat[h][w] = this.nextInt(); } return mat; } public double[][] nextDoubleMatrix(int height, int width) { double[][] mat = new double[height][width]; for (int h = 0; h < height; h++) for (int w = 0; w < width; w++) { mat[h][w] = this.nextDouble(); } return mat; } public char[][] nextCharMatrix(int height, int width) { char[][] mat = new char[height][width]; for (int h = 0; h < height; h++) { String s = this.next(); for (int w = 0; w < width; w++) { mat[h][w] = s.charAt(w); } } return mat; } } static class ContestPrinter extends java.io.PrintWriter { public ContestPrinter(java.io.PrintStream stream) { super(stream); } public ContestPrinter() { super(System.out); } private static String dtos(double x, int n) { StringBuilder sb = new StringBuilder(); if (x < 0) { sb.append('-'); x = -x; } x += Math.pow(10, -n) / 2; sb.append((long) x); sb.append("."); x -= (long) x; for (int i = 0; i < n; i++) { x *= 10; sb.append((int) x); x -= (int) x; } return sb.toString(); } @Override public void print(float f) { super.print(dtos(f, 20)); } @Override public void println(float f) { super.println(dtos(f, 20)); } @Override public void print(double d) { super.print(dtos(d, 20)); } @Override public void println(double d) { super.println(dtos(d, 20)); } public void printArray(int[] array, String separator) { int n = array.length; for (int i = 0; i < n - 1; i++) { super.print(array[i]); super.print(separator); } super.println(array[n - 1]); } public void printArray(int[] array) { this.printArray(array, " "); } public void printArray(int[] array, String separator, java.util.function.IntUnaryOperator map) { int n = array.length; for (int i = 0; i < n - 1; i++) { super.print(map.applyAsInt(array[i])); super.print(separator); } super.println(map.applyAsInt(array[n - 1])); } public void printArray(int[] array, java.util.function.IntUnaryOperator map) { this.printArray(array, " ", map); } public void printArray(long[] array, String separator) { int n = array.length; for (int i = 0; i < n - 1; i++) { super.print(array[i]); super.print(separator); } super.println(array[n - 1]); } public void printArray(long[] array) { this.printArray(array, " "); } public void printArray(long[] array, String separator, java.util.function.LongUnaryOperator map) { int n = array.length; for (int i = 0; i < n - 1; i++) { super.print(map.applyAsLong(array[i])); super.print(separator); } super.println(map.applyAsLong(array[n - 1])); } public void printArray(long[] array, java.util.function.LongUnaryOperator map) { this.printArray(array, " ", map); } } public static void safeSort(int[] array) { Integer[] temp = new Integer[array.length]; for (int n = 0; n < array.length; n++) { temp[n] = array[n]; } Arrays.sort(temp); for (int n = 0; n < array.length; n++) { array[n] = temp[n]; } } public static void safeSort(long[] array) { Long[] temp = new Long[array.length]; for (int n = 0; n < array.length; n++) { temp[n] = array[n]; } Arrays.sort(temp); for (int n = 0; n < array.length; n++) { array[n] = temp[n]; } } public static void safeSort(double[] array) { Double[] temp = new Double[array.length]; for (int n = 0; n < array.length; n++) { temp[n] = array[n]; } Arrays.sort(temp); for (int n = 0; n < array.length; n++) { array[n] = temp[n]; } } }
Java
["3\n5 5\n1 5 8 8 7\n5 2 1 4 3\n1 6 9 7 5\n9 3 3 3 2\n1 7 9 9 8\n3 3\n8 9 8\n1 5 3\n7 5 7\n2 6\n3 3 3 2 2 2\n1 1 1 4 4 4"]
4 seconds
["YES\nBRBRB 1\nNO\nYES\nRB 3"]
NoteThe coloring and the cut for the first testcase:
Java 11
standard input
[ "brute force", "constructive algorithms", "implementation", "sortings" ]
10751c875f4d7667ba21685c57cddd9e
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n, m \le 5 \cdot 10^5$$$; $$$n \cdot m \le 10^6$$$) — the number of rows and the number of columns in the matrix, respectively. The $$$i$$$-th of the next $$$n$$$ lines contains $$$m$$$ integers $$$a_{i1}, a_{i2}, \dots, a_{im}$$$ ($$$1 \le a_{ij} \le 10^6$$$). The sum of $$$n \cdot m$$$ over all testcases doesn't exceed $$$10^6$$$.
2,400
For each testcase print an answer. If there are no perfect colorings and cuts in the matrix, then print "NO". Otherwise, first, print "YES". Then a string, consisting of $$$n$$$ characters: the $$$i$$$-th character should be 'R' if the $$$i$$$-th row is colored red and 'B' if it's colored blue. The string should contain at least one 'R' and at least one 'B'. Finally, print an integer $$$k$$$ ($$$1 \le k &lt; m$$$) — the number of columns from the left that are cut.
standard output
PASSED
9a8f32505e9fc45db11f44179fec3f3a
train_108.jsonl
1657982100
You are given a connected undirected graph consisting of $$$n$$$ vertices and $$$m$$$ edges. The weight of the $$$i$$$-th edge is $$$i$$$.Here is a wrong algorithm of finding a minimum spanning tree (MST) of a graph:vis := an array of length ns := a set of edgesfunction dfs(u): vis[u] := true iterate through each edge (u, v) in the order from smallest to largest edge weight if vis[v] = false add edge (u, v) into the set (s) dfs(v)function findMST(u): reset all elements of (vis) to false reset the edge set (s) to empty dfs(u) return the edge set (s)Each of the calls findMST(1), findMST(2), ..., findMST(n) gives you a spanning tree of the graph. Determine which of these trees are minimum spanning trees.
256 megabytes
// upsolve with kaiboy, coached by rainboy import java.io.*; import java.util.*; public class CF1708E extends PrintWriter { CF1708E() { super(System.out); } Scanner sc = new Scanner(System.in); public static void main(String[] $) { CF1708E o = new CF1708E(); o.main(); o.flush(); } int[] ds; int find(int i) { return ds[i] < 0 ? i : (ds[i] = find(ds[i])); } boolean join(int i, int j) { i = find(i); j = find(j); if (i == j) return false; if (ds[i] > ds[j]) ds[i] = j; else { if (ds[i] == ds[j]) ds[i]--; ds[j] = i; } return true; } int[] eo; int[][] ej; void append(int i, int j) { int o = eo[i]++; if (o >= 2 && (o & o - 1) == 0) ej[i] = Arrays.copyOf(ej[i], o << 1); ej[i][o] = j; } int[] ta, tb; int t; void dfs(int p, int i) { ta[i] = t++; int cnt = 0; for (int o = 0; o < eo[i]; o++) { int j = ej[i][o]; if (j != p) { dfs(i, j); ej[i][cnt++] = j; } } eo[i] = cnt; tb[i] = t; } int search(int i, int j) { int lower = 0, upper = eo[i]; while (upper - lower > 1) { int o = (lower + upper) / 2; if (ta[ej[i][o]] <= ta[j]) lower = o; else upper = o; } return ej[i][lower]; } void main() { int n = sc.nextInt(); int m = sc.nextInt(); ds = new int[n]; Arrays.fill(ds, -1); eo = new int[n]; ej = new int[n][2]; int[] ii = new int[m]; int[] jj = new int[m]; int cnt = 0; while (m-- > 0) { int i = sc.nextInt() - 1; int j = sc.nextInt() - 1; if (join(i, j)) { append(i, j); append(j, i); } else { ii[cnt] = i; jj[cnt] = j; cnt++; } } ta = new int[n]; tb = new int[n]; dfs(-1, 0); int[] xx = new int[n + 1]; while (cnt-- > 0) { int i = ii[cnt]; int j = jj[cnt]; int a = ta[i]; int b = tb[i]; int c = ta[j]; int d = tb[j]; if (a <= c && d <= b) { i = search(i, j); a = ta[i]; b = tb[i]; xx[a]++; xx[c]--; xx[d]++; xx[b]--; } else if (c <= a && b <= d) { j = search(j, i); c = ta[j]; d = tb[j]; xx[c]++; xx[a]--; xx[b]++; xx[d]--; } else if (b <= c) { xx[0]++; xx[a]--; xx[b]++; xx[c]--; xx[d]++; xx[n]--; } else { xx[0]++; xx[c]--; xx[d]++; xx[a]--; xx[b]++; xx[n]--; } } for (int i = 1; i < n; i++) xx[i] += xx[i - 1]; char[] cc = new char[n]; for (int i = 0; i < n; i++) cc[i] = xx[ta[i]] == 0 ? '1' : '0'; println(cc); } }
Java
["5 5\n1 2\n3 5\n1 3\n3 2\n4 2", "10 11\n1 2\n2 5\n3 4\n4 2\n8 1\n4 5\n10 5\n9 5\n8 2\n5 7\n4 6"]
1 second
["01111", "0011111011"]
NoteHere is the graph given in the first example. There is only one minimum spanning tree in this graph. A minimum spanning tree is $$$(1,2),(3,5),(1,3),(2,4)$$$ which has weight $$$1+2+3+5=11$$$.Here is a part of the process of calling findMST(1): reset the array vis and the edge set s; calling dfs(1); vis[1] := true; iterate through each edge $$$(1,2),(1,3)$$$; add edge $$$(1,2)$$$ into the edge set s, calling dfs(2): vis[2] := true iterate through each edge $$$(2,1),(2,3),(2,4)$$$; because vis[1] = true, ignore the edge $$$(2,1)$$$; add edge $$$(2,3)$$$ into the edge set s, calling dfs(3): ... In the end, it will select edges $$$(1,2),(2,3),(3,5),(2,4)$$$ with total weight $$$1+4+2+5=12&gt;11$$$, so findMST(1) does not find a minimum spanning tree.It can be shown that the other trees are all MSTs, so the answer is 01111.
Java 11
standard input
[ "dfs and similar", "graphs", "greedy" ]
2bf41400fa51f472f1d3904baa06d6a8
The first line of the input contains two integers $$$n$$$, $$$m$$$ ($$$2\le n\le 10^5$$$, $$$n-1\le m\le 2\cdot 10^5$$$) — the number of vertices and the number of edges in the graph. Each of the following $$$m$$$ lines contains two integers $$$u_i$$$ and $$$v_i$$$ ($$$1\le u_i, v_i\le n$$$, $$$u_i\ne v_i$$$), describing an undirected edge $$$(u_i,v_i)$$$ in the graph. The $$$i$$$-th edge in the input has weight $$$i$$$. It is guaranteed that the graph is connected and there is at most one edge between any pair of vertices.
2,400
You need to output a binary string $$$s$$$, where $$$s_i=1$$$ if findMST(i) creates an MST, and $$$s_i = 0$$$ otherwise.
standard output
PASSED
497d3dc3b27d616320e1328101b000f0
train_108.jsonl
1657982100
You are given a connected undirected graph consisting of $$$n$$$ vertices and $$$m$$$ edges. The weight of the $$$i$$$-th edge is $$$i$$$.Here is a wrong algorithm of finding a minimum spanning tree (MST) of a graph:vis := an array of length ns := a set of edgesfunction dfs(u): vis[u] := true iterate through each edge (u, v) in the order from smallest to largest edge weight if vis[v] = false add edge (u, v) into the set (s) dfs(v)function findMST(u): reset all elements of (vis) to false reset the edge set (s) to empty dfs(u) return the edge set (s)Each of the calls findMST(1), findMST(2), ..., findMST(n) gives you a spanning tree of the graph. Determine which of these trees are minimum spanning trees.
256 megabytes
//package com.example.practice.codeforces.sc2400; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.StringTokenizer; //E. DFS Trees public class Solution2 { public static void main (String [] args) throws IOException { // Use BufferedReader rather than RandomAccessFile; it's much faster final BufferedReader input = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); // input file name goes above StringTokenizer st = new StringTokenizer(input.readLine()); int n = Integer.parseInt(st.nextToken()), m = Integer.parseInt(st.nextToken()); int[][] es = readArray2DInt(m, m, input); out.println(calc(n, m, es)); out.close(); // close the output file } private static String calc(final int n, final int m, final int[][] es) { boolean[] isInMST = new boolean[m+1]; ArrayList<int[]>[] als = new ArrayList[n+1]; int[] rd = new int[n+1], rg = new int[n+2], timeStampToIds = new int[n+1]; int[][] timeStamp = new int[2][n+1]; for (int i=1;i<=n;++i){ als[i] = new ArrayList<>(); rd[i] = i; } int p = 1; for (int[] e : es){ als[e[0]].add(new int[]{e[1], p}); als[e[1]].add(new int[]{e[0], p++}); int a = find(rd, e[0]), b = find(rd, e[1]); if (a != b){ isInMST[p-1] = true; rd[b] = a; } } addTimeStamp(als, 1, -1, new int[]{1}, timeStamp, timeStampToIds, isInMST); todo(als, timeStamp, new int[n+1], new int[n+1], rg, isInMST, 1, -1, 1); char[] res = new char[n]; int cur = 0; for (int i=1;i<=n;++i){ cur += rg[i]; if (cur == 0){ res[timeStampToIds[i] - 1] = '1'; }else { res[timeStampToIds[i] - 1] = '0'; } } return new String(res); } private static void todo(ArrayList<int[]>[] als, int[][] timeStamp, int[] path, int[] pathIds, int[] rg, boolean[] isInMST, final int idx, final int pre, final int pa){ path[idx] = pa; pathIds[pa] = idx; for (int[] kk : als[idx]){ if (kk[0] != pre && timeStamp[0][kk[0]] < timeStamp[0][idx]){ if (path[kk[0]] > 0){ int rt = pathIds[path[kk[0]] + 1]; rg[timeStamp[0][rt]] += 1; rg[timeStamp[0][idx]] -= 1; if (timeStamp[1][idx] < timeStamp[1][rt]){ rg[timeStamp[1][idx]] += 1; rg[timeStamp[1][rt]] -= 1; } }else { rg[1] += 1; rg[timeStamp[0][kk[0]]] -= 1; rg[timeStamp[1][kk[0]]] += 1; rg[timeStamp[0][idx]] -= 1; if (timeStamp[1][idx] < als.length){ rg[timeStamp[1][idx]] += 1; rg[als.length] -= 1; } } }else if (kk[0] != pre && isInMST[kk[1]]){ todo(als, timeStamp, path, pathIds, rg, isInMST, kk[0], idx, pa+1); } } path[idx] = 0; pathIds[pa] = 0; } private static void addTimeStamp(ArrayList<int[]>[] als, int idx, int pre, int[] time, int[][] timeStamp, int[] timeStampToIds, boolean[] isInMST){ timeStamp[0][idx] = time[0]++; timeStampToIds[timeStamp[0][idx]] = idx; for (int[] kk : als[idx]){ if (kk[0] != pre && isInMST[kk[1]]){ addTimeStamp(als, kk[0], idx, time, timeStamp, timeStampToIds, isInMST); } } timeStamp[1][idx] = time[0]; } private static int find(int[] rd, int idx){ while (idx != rd[idx]){ rd[idx] = rd[rd[idx]]; idx = rd[idx]; } return idx; } private static void printArray(long[] ns, final PrintWriter out){ for (int i=0;i<ns.length;++i){ out.print(ns[i]); if (i+1<ns.length)out.print(" "); else out.println(); } } private static void printArrayInt(int[] ns, final PrintWriter out){ for (int i=0;i<ns.length;++i){ out.print(ns[i]); if (i+1<ns.length)out.print(" "); else out.println(); } } private static void printArrayVertical(long[] ns, final PrintWriter out){ for (long a : ns){ out.println(a); } } private static void printArrayVerticalInt(int[] ns, final PrintWriter out){ for (int a : ns){ out.println(a); } } private static void printArray2D(long[][] ns, final int len, final PrintWriter out){ int cnt = 0; for (long[] kk : ns){ cnt++; if (cnt > len)break; for (int i=0;i<kk.length;++i){ out.print(kk[i]); if (i+1<kk.length)out.print(" "); else out.println(); } } } private static void printArray2DInt(int[][] ns, final int len, final PrintWriter out){ int cnt = 0; for (int[] kk : ns){ cnt++; if (cnt > len)break; for (int i=0;i<kk.length;++i){ out.print(kk[i]); if (i+1<kk.length)out.print(" "); else out.println(); } } } private static long[] readArray(final int n, final BufferedReader input) throws IOException{ long[] ns = new long[n]; StringTokenizer st = new StringTokenizer(input.readLine()); for (int i=0;i<n;++i){ ns[i] = Long.parseLong(st.nextToken()); } return ns; } private static int[] readArrayInt(final int n, final BufferedReader input) throws IOException{ int[] ns = new int[n]; StringTokenizer st = new StringTokenizer(input.readLine()); for (int i=0;i<n;++i){ ns[i] = Integer.parseInt(st.nextToken()); } return ns; } private static long[] readArrayVertical(final int n, final BufferedReader input) throws IOException{ long[] ns = new long[n]; for (int i=0;i<n;++i){ ns[i] = Long.parseLong(input.readLine()); } return ns; } private static int[] readArrayVerticalInt(final int n, final BufferedReader input) throws IOException{ int[] ns = new int[n]; for (int i=0;i<n;++i){ ns[i] = Integer.parseInt(input.readLine()); } return ns; } private static long[][] readArray2D(final int n, final int len, final BufferedReader input) throws IOException{ long[][] ns = new long[len][]; for (int i=0;i<n;++i){ StringTokenizer st = new StringTokenizer(input.readLine()); ArrayList<Long> al = new ArrayList<>(); while (st.hasMoreTokens()){ al.add(Long.parseLong(st.nextToken())); } long[] kk = new long[al.size()]; for (int j=0;j<kk.length;++j){ kk[j] = al.get(j); } ns[i] = kk; } return ns; } private static int[][] readArray2DInt(final int n, final int len, final BufferedReader input) throws IOException{ int[][] ns = new int[len][]; for (int i=0;i<n;++i){ StringTokenizer st = new StringTokenizer(input.readLine()); ArrayList<Integer> al = new ArrayList<>(); while (st.hasMoreTokens()){ al.add(Integer.parseInt(st.nextToken())); } int[] kk = new int[al.size()]; for (int j=0;j<kk.length;++j){ kk[j] = al.get(j); } ns[i] = kk; } return ns; } }
Java
["5 5\n1 2\n3 5\n1 3\n3 2\n4 2", "10 11\n1 2\n2 5\n3 4\n4 2\n8 1\n4 5\n10 5\n9 5\n8 2\n5 7\n4 6"]
1 second
["01111", "0011111011"]
NoteHere is the graph given in the first example. There is only one minimum spanning tree in this graph. A minimum spanning tree is $$$(1,2),(3,5),(1,3),(2,4)$$$ which has weight $$$1+2+3+5=11$$$.Here is a part of the process of calling findMST(1): reset the array vis and the edge set s; calling dfs(1); vis[1] := true; iterate through each edge $$$(1,2),(1,3)$$$; add edge $$$(1,2)$$$ into the edge set s, calling dfs(2): vis[2] := true iterate through each edge $$$(2,1),(2,3),(2,4)$$$; because vis[1] = true, ignore the edge $$$(2,1)$$$; add edge $$$(2,3)$$$ into the edge set s, calling dfs(3): ... In the end, it will select edges $$$(1,2),(2,3),(3,5),(2,4)$$$ with total weight $$$1+4+2+5=12&gt;11$$$, so findMST(1) does not find a minimum spanning tree.It can be shown that the other trees are all MSTs, so the answer is 01111.
Java 11
standard input
[ "dfs and similar", "graphs", "greedy" ]
2bf41400fa51f472f1d3904baa06d6a8
The first line of the input contains two integers $$$n$$$, $$$m$$$ ($$$2\le n\le 10^5$$$, $$$n-1\le m\le 2\cdot 10^5$$$) — the number of vertices and the number of edges in the graph. Each of the following $$$m$$$ lines contains two integers $$$u_i$$$ and $$$v_i$$$ ($$$1\le u_i, v_i\le n$$$, $$$u_i\ne v_i$$$), describing an undirected edge $$$(u_i,v_i)$$$ in the graph. The $$$i$$$-th edge in the input has weight $$$i$$$. It is guaranteed that the graph is connected and there is at most one edge between any pair of vertices.
2,400
You need to output a binary string $$$s$$$, where $$$s_i=1$$$ if findMST(i) creates an MST, and $$$s_i = 0$$$ otherwise.
standard output
PASSED
62b4a67a4e6db7a45e3ed470e34b4297
train_108.jsonl
1657982100
You are given a connected undirected graph consisting of $$$n$$$ vertices and $$$m$$$ edges. The weight of the $$$i$$$-th edge is $$$i$$$.Here is a wrong algorithm of finding a minimum spanning tree (MST) of a graph:vis := an array of length ns := a set of edgesfunction dfs(u): vis[u] := true iterate through each edge (u, v) in the order from smallest to largest edge weight if vis[v] = false add edge (u, v) into the set (s) dfs(v)function findMST(u): reset all elements of (vis) to false reset the edge set (s) to empty dfs(u) return the edge set (s)Each of the calls findMST(1), findMST(2), ..., findMST(n) gives you a spanning tree of the graph. Determine which of these trees are minimum spanning trees.
256 megabytes
//package com.example.practice.codeforces; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.StringTokenizer; public class Solution { public static void main (String [] args) throws IOException { // Use BufferedReader rather than RandomAccessFile; it's much faster final BufferedReader input = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); // input file name goes above StringTokenizer st = new StringTokenizer(input.readLine()); int n = Integer.parseInt(st.nextToken()), m = Integer.parseInt(st.nextToken()); int[][] es = readArray2DInt(m, m, input); out.println(calc(n, m, es)); out.close(); // close the output file } private static String calc(final int n, final int m, final int[][] es) { boolean[] isInMST = new boolean[m+1]; ArrayList<int[]>[] als = new ArrayList[n+1]; int[] rd = new int[n+1], rg = new int[n+2], timeStampToIds = new int[n+1]; int[][] timeStamp = new int[2][n+1]; for (int i=1;i<=n;++i){ als[i] = new ArrayList<>(); rd[i] = i; } int p = 1; for (int[] e : es){ als[e[0]].add(new int[]{e[1], p}); als[e[1]].add(new int[]{e[0], p++}); int a = find(rd, e[0]), b = find(rd, e[1]); if (a != b){ isInMST[p-1] = true; rd[b] = a; } } addTimeStamp(als, 1, -1, new int[]{1}, timeStamp, timeStampToIds, isInMST); todo(als, timeStamp, new int[n+1], new int[n+1], rg, isInMST, 1, -1, 1); char[] res = new char[n]; int cur = 0; for (int i=1;i<=n;++i){ cur += rg[i]; if (cur == 0){ res[timeStampToIds[i] - 1] = '1'; }else { res[timeStampToIds[i] - 1] = '0'; } } return new String(res); } private static void todo(ArrayList<int[]>[] als, int[][] timeStamp, int[] path, int[] pathIds, int[] rg, boolean[] isInMST, final int idx, final int pre, final int pa){ path[idx] = pa; pathIds[pa] = idx; for (int[] kk : als[idx]){ if (kk[0] != pre && timeStamp[0][kk[0]] < timeStamp[0][idx]){ if (path[kk[0]] > 0){ int rt = pathIds[path[kk[0]] + 1]; rg[timeStamp[0][rt]] += 1; rg[timeStamp[0][idx]] -= 1; if (timeStamp[1][idx] < timeStamp[1][rt]){ rg[timeStamp[1][idx]] += 1; rg[timeStamp[1][rt]] -= 1; } }else { rg[1] += 1; rg[timeStamp[0][kk[0]]] -= 1; rg[timeStamp[1][kk[0]]] += 1; rg[timeStamp[0][idx]] -= 1; if (timeStamp[1][idx] < als.length){ rg[timeStamp[1][idx]] += 1; rg[als.length] -= 1; } } }else if (kk[0] != pre && isInMST[kk[1]]){ todo(als, timeStamp, path, pathIds, rg, isInMST, kk[0], idx, pa+1); } } path[idx] = 0; pathIds[pa] = 0; } private static void addTimeStamp(ArrayList<int[]>[] als, int idx, int pre, int[] time, int[][] timeStamp, int[] timeStampToIds, boolean[] isInMST){ timeStamp[0][idx] = time[0]++; timeStampToIds[timeStamp[0][idx]] = idx; for (int[] kk : als[idx]){ if (kk[0] != pre && isInMST[kk[1]]){ addTimeStamp(als, kk[0], idx, time, timeStamp, timeStampToIds, isInMST); } } timeStamp[1][idx] = time[0]; } private static int find(int[] rd, int idx){ while (idx != rd[idx]){ rd[idx] = rd[rd[idx]]; idx = rd[idx]; } return idx; } private static void printArray(long[] ns, final PrintWriter out){ for (int i=0;i<ns.length;++i){ out.print(ns[i]); if (i+1<ns.length)out.print(" "); else out.println(); } } private static void printArrayInt(int[] ns, final PrintWriter out){ for (int i=0;i<ns.length;++i){ out.print(ns[i]); if (i+1<ns.length)out.print(" "); else out.println(); } } private static void printArrayVertical(long[] ns, final PrintWriter out){ for (long a : ns){ out.println(a); } } private static void printArrayVerticalInt(int[] ns, final PrintWriter out){ for (int a : ns){ out.println(a); } } private static void printArray2D(long[][] ns, final int len, final PrintWriter out){ int cnt = 0; for (long[] kk : ns){ cnt++; if (cnt > len)break; for (int i=0;i<kk.length;++i){ out.print(kk[i]); if (i+1<kk.length)out.print(" "); else out.println(); } } } private static void printArray2DInt(int[][] ns, final int len, final PrintWriter out){ int cnt = 0; for (int[] kk : ns){ cnt++; if (cnt > len)break; for (int i=0;i<kk.length;++i){ out.print(kk[i]); if (i+1<kk.length)out.print(" "); else out.println(); } } } private static long[] readArray(final int n, final BufferedReader input) throws IOException{ long[] ns = new long[n]; StringTokenizer st = new StringTokenizer(input.readLine()); for (int i=0;i<n;++i){ ns[i] = Long.parseLong(st.nextToken()); } return ns; } private static int[] readArrayInt(final int n, final BufferedReader input) throws IOException{ int[] ns = new int[n]; StringTokenizer st = new StringTokenizer(input.readLine()); for (int i=0;i<n;++i){ ns[i] = Integer.parseInt(st.nextToken()); } return ns; } private static long[] readArrayVertical(final int n, final BufferedReader input) throws IOException{ long[] ns = new long[n]; for (int i=0;i<n;++i){ ns[i] = Long.parseLong(input.readLine()); } return ns; } private static int[] readArrayVerticalInt(final int n, final BufferedReader input) throws IOException{ int[] ns = new int[n]; for (int i=0;i<n;++i){ ns[i] = Integer.parseInt(input.readLine()); } return ns; } private static long[][] readArray2D(final int n, final int len, final BufferedReader input) throws IOException{ long[][] ns = new long[len][]; for (int i=0;i<n;++i){ StringTokenizer st = new StringTokenizer(input.readLine()); ArrayList<Long> al = new ArrayList<>(); while (st.hasMoreTokens()){ al.add(Long.parseLong(st.nextToken())); } long[] kk = new long[al.size()]; for (int j=0;j<kk.length;++j){ kk[j] = al.get(j); } ns[i] = kk; } return ns; } private static int[][] readArray2DInt(final int n, final int len, final BufferedReader input) throws IOException{ int[][] ns = new int[len][]; for (int i=0;i<n;++i){ StringTokenizer st = new StringTokenizer(input.readLine()); ArrayList<Integer> al = new ArrayList<>(); while (st.hasMoreTokens()){ al.add(Integer.parseInt(st.nextToken())); } int[] kk = new int[al.size()]; for (int j=0;j<kk.length;++j){ kk[j] = al.get(j); } ns[i] = kk; } return ns; } static class SegTree{ int st; int en; int mid; int val1; int val2; SegTree left; SegTree right; public SegTree(int l, int r, int d){ st = l; en = r; mid = (st + en) >> 1; val1 = val2 = d; if (st<en){ left = new SegTree(st, mid, d); right = new SegTree(mid+1, en, d); }else { left = right = null; } } public SegTree(int l, int r, int[] ns){ st = l; en = r; mid = (st + en) >> 1; if (st==en){ val1 = val2 = ns[st]; }else { left = new SegTree(l, mid, ns); right = new SegTree(mid+1, r, ns); val1 = Math.min(left.val1, right.val1); val2 = Math.max(left.val2, right.val2); } } void update(int idx, int v){ if (st==en){ val1 = val2 = v; }else { if (idx <= mid){ left.update(idx, v); }else { right.update(idx, v); } val1 = Math.min(left.val1, right.val1); val2 = Math.max(left.val2, right.val2); } } int getMin(int l, int r){ if (st==en || (l==st && r==en))return val1; if (r<=mid){ return left.getMin(l, r); } if (l>mid){ return right.getMin(l, r); } return Math.min(left.getMin(l, mid), right.getMin(mid+1, r)); } int getMax(int l, int r){ if (st==en || (l==st && r==en))return val2; if (r<=mid){ return left.getMax(l, r); } if (l>mid){ return right.getMax(l, r); } return Math.max(left.getMax(l, mid), right.getMax(mid+1, r)); } } static class SparseTable{ int[][] minTable; int[][] maxTable; int[] log2; int n; public SparseTable(final int[] ns){ n = ns.length; int m = 0, pre = 0; while (1<<m < n){ m++; } m++; minTable = new int[n][m]; maxTable = new int[n][m]; log2 = new int[n+1]; for (int i=0;i<n;++i){ minTable[i][0] = ns[i]; maxTable[i][0] = ns[i]; if ((1<<(pre+1)) == i+1){ pre++; } log2[i+1] = pre; } for (int i=1;i<m;++i){ for (int j=0;j<n;++j){ int r = Math.min(n-1, j+(1<<i)-1); if (r-(1<<(i-1))+1 <= j){ minTable[j][i] = minTable[j][i-1]; maxTable[j][i] = maxTable[j][i-1]; }else { minTable[j][i] = Math.min(minTable[j][i-1], minTable[r-(1<<(i-1))+1][i-1]); maxTable[j][i] = Math.max(maxTable[j][i-1], maxTable[r-(1<<(i-1))+1][i-1]); } } } } int getMin(final int l, final int r){ int d = log2[r-l+1]; return Math.min(minTable[l][d], minTable[r-(1<<d)+1][d]); } int getMax(final int l, final int r){ int d = log2[r-l+1]; return Math.max(maxTable[l][d], maxTable[r-(1<<d)+1][d]); } } }
Java
["5 5\n1 2\n3 5\n1 3\n3 2\n4 2", "10 11\n1 2\n2 5\n3 4\n4 2\n8 1\n4 5\n10 5\n9 5\n8 2\n5 7\n4 6"]
1 second
["01111", "0011111011"]
NoteHere is the graph given in the first example. There is only one minimum spanning tree in this graph. A minimum spanning tree is $$$(1,2),(3,5),(1,3),(2,4)$$$ which has weight $$$1+2+3+5=11$$$.Here is a part of the process of calling findMST(1): reset the array vis and the edge set s; calling dfs(1); vis[1] := true; iterate through each edge $$$(1,2),(1,3)$$$; add edge $$$(1,2)$$$ into the edge set s, calling dfs(2): vis[2] := true iterate through each edge $$$(2,1),(2,3),(2,4)$$$; because vis[1] = true, ignore the edge $$$(2,1)$$$; add edge $$$(2,3)$$$ into the edge set s, calling dfs(3): ... In the end, it will select edges $$$(1,2),(2,3),(3,5),(2,4)$$$ with total weight $$$1+4+2+5=12&gt;11$$$, so findMST(1) does not find a minimum spanning tree.It can be shown that the other trees are all MSTs, so the answer is 01111.
Java 11
standard input
[ "dfs and similar", "graphs", "greedy" ]
2bf41400fa51f472f1d3904baa06d6a8
The first line of the input contains two integers $$$n$$$, $$$m$$$ ($$$2\le n\le 10^5$$$, $$$n-1\le m\le 2\cdot 10^5$$$) — the number of vertices and the number of edges in the graph. Each of the following $$$m$$$ lines contains two integers $$$u_i$$$ and $$$v_i$$$ ($$$1\le u_i, v_i\le n$$$, $$$u_i\ne v_i$$$), describing an undirected edge $$$(u_i,v_i)$$$ in the graph. The $$$i$$$-th edge in the input has weight $$$i$$$. It is guaranteed that the graph is connected and there is at most one edge between any pair of vertices.
2,400
You need to output a binary string $$$s$$$, where $$$s_i=1$$$ if findMST(i) creates an MST, and $$$s_i = 0$$$ otherwise.
standard output
PASSED
696e09106dbd64c96566217c80e79cb8
train_108.jsonl
1657982100
You are given a connected undirected graph consisting of $$$n$$$ vertices and $$$m$$$ edges. The weight of the $$$i$$$-th edge is $$$i$$$.Here is a wrong algorithm of finding a minimum spanning tree (MST) of a graph:vis := an array of length ns := a set of edgesfunction dfs(u): vis[u] := true iterate through each edge (u, v) in the order from smallest to largest edge weight if vis[v] = false add edge (u, v) into the set (s) dfs(v)function findMST(u): reset all elements of (vis) to false reset the edge set (s) to empty dfs(u) return the edge set (s)Each of the calls findMST(1), findMST(2), ..., findMST(n) gives you a spanning tree of the graph. Determine which of these trees are minimum spanning trees.
256 megabytes
import java.util.*; import java.util.function.*; import java.io.*; // you can compare with output.txt and expected out public class Round808E { MyPrintWriter out; MyScanner in; // final static long FIXED_RANDOM; // static { // FIXED_RANDOM = System.currentTimeMillis(); // } final static String IMPOSSIBLE = "IMPOSSIBLE"; final static String POSSIBLE = "POSSIBLE"; final static String YES = "YES"; final static String NO = "NO"; private void initIO(boolean isFileIO) { if (System.getProperty("ONLINE_JUDGE") == null && isFileIO) { try{ in = new MyScanner(new FileInputStream("input.txt")); out = new MyPrintWriter(new FileOutputStream("output.txt")); } catch(FileNotFoundException e){ e.printStackTrace(); } } else{ in = new MyScanner(System.in); out = new MyPrintWriter(new BufferedOutputStream(System.out)); } } public static void main(String[] args){ // Scanner in = new Scanner(new BufferedReader(new InputStreamReader(System.in))); Round808E sol = new Round808E(); sol.run(); } private void run() { boolean isDebug = false; boolean isFileIO = true; boolean hasMultipleTests = false; initIO(isFileIO); int t = hasMultipleTests? in.nextInt() : 1; for (int i = 1; i <= t; ++i) { if(isDebug){ out.printf("Test %d\n", i); } getInput(); solve(); printOutput(); } in.close(); out.close(); } // use suitable one between matrix(2, n) or matrix(n, 2) for graph edges, pairs, ... int n, m; int[][] e; void getInput() { n = in.nextInt(); m = in.nextInt(); e = in.nextMatrix(m, 2, -1); } void printOutput() { out.println(ans); } String ans; void solve(){ // fail at vk if v1 -> v2 -> ... -> vk // w (vi vk) < w (vk-1 vk) for i < k // success if smallest edge of vk is used // same as remove v1 // dfs on each cc // bad if v1 -> v2 // removing v1 from mst results in the same shape in the graph // -> good // mst is fixed as the main tree // for each bad edge e = (u, v) // good vertices are exactly // vertices in subtree of u, rooted at v // and vertices in subtree of v, rooted at u // since, for some other vertex w, // in a rooted tree at w, suppose findMST(w) didn't meet any bad edges until u or v // wlog it reached u before v // suppose it further didn't meet any bad edges in subtree of u (otherwise w is already bad) // then it will use uv to go to v, eventually making w bad // for each bad edge e = (u, v) // i) lca(u, v) = u // subtree of v is good // subtree of u - v is good // G - subtree of u is good // this can be expressed by // 1) root is good // 2) the prev of u in the path between u and v is bad // 3) v is good // ii) lca(u, v) = w // subtree of u and subtree of v are good // this can be expressed by // 1) u is good // 2) v is good // then we propagate the goodness // if a vertex is good if its goodness is exactly m-(n-1) DSU dsu = new DSU(n); treeNeighbors = new ArrayList[n]; for(int i=0; i<n; i++) treeNeighbors[i] = new ArrayList<Integer>(); boolean[] isBadEdge = new boolean[m]; for(int i=0; i<m; i++) { int u = e[i][0]; int v = e[i][1]; boolean isGood = dsu.union(u, v); if(isGood) { treeNeighbors[u].add(v); treeNeighbors[v].add(u); } else isBadEdge[i] = true; } final int root = 0; computeLifting(root); goodness = new int[n]; for(int i=0; i<m; i++) { if(isBadEdge[i]) { int u = e[i][0]; int v = e[i][1]; int w = lca(u, v); if(w == v) { int temp = u; u = v; v = temp; } if(w == u) { // i) lca(u, v) = u // subtree of v is good // subtree of u - v is good // G - subtree of u is good // so // 1) root is good // 2) the prev of u in the path between u and v is bad // 3) v is good goodness[root]++; int prev = prevChild(u, v); goodness[prev]--; goodness[v]++; } else { // ii) lca(u, v) = w // subtree of u and subtree of v are good // so // 1) u is good // 2) v is good goodness[u]++; goodness[v]++; } } } propagateDFS(root, -1); StringBuilder sb = new StringBuilder(); for(int i=0; i<n; i++) { if(goodness[i] == m-(n-1)) sb.append('1'); else sb.append('0'); } ans = sb.toString(); } int[] goodness; void propagateDFS(int curr, int parent) { for(int next: treeNeighbors[curr]) { if(next == parent) continue; goodness[next] += goodness[curr]; propagateDFS(next, curr); } } void computeLifting(final int root) { LOG = 31-Integer.numberOfLeadingZeros(n); lifting = new int[n][LOG+1]; depth = new int[n]; liftingDFS(root, root, 0); } void liftingDFS(int curr, int parent, int d) { depth[curr] = d; lifting[curr][0] = parent; for(int i=1; i<LOG; i++) { lifting[curr][i] = lifting[lifting[curr][i-1]][i-1]; } for(int next: treeNeighbors[curr]) { if(next == parent) continue; liftingDFS(next, curr, d+1); } } boolean isAncestor(int u, int v) { if(depth[u] > depth[v]) return false; // depth[u] <= depth[v] for(int i=LOG-1; i>=0 && depth[v] > depth[u]; i--){ if(depth[lifting[v][i]] >= depth[u]) v = lifting[v][i]; } return u == v; } // assumes u is an ancestor of v int prevChild(int u, int v) { for(int i=LOG-1; i>=0; i--){ if(depth[lifting[v][i]] > depth[u]) v = lifting[v][i]; } return v; } int lca(int u, int v) { if(depth[v] < depth[u]) return lca(v, u); // depth[u] <= depth[v] for(int i=LOG-1; i>=0 && depth[v] > depth[u]; i--){ if(depth[lifting[v][i]] >= depth[u]) v = lifting[v][i]; } if(u == v) return u; // depth[u] = depth[v] for(int i=LOG-1; i>=0; i--) { if(lifting[u][i] != lifting[v][i]) { u = lifting[u][i]; v = lifting[v][i]; } } return lifting[u][0]; } ArrayList<Integer>[] treeNeighbors; int[][] lifting; int[] depth; int LOG; class DSU{ int[] parent; int[] size; public DSU(int n) { parent = new int[n]; Arrays.fill(parent, -1); size = new int[n]; } public boolean union(int u, int v) { u = find(u); v = find(v); if(u == v) return false; int small, large; if(size[u] < size[v]) { small = u; large = v; } else { small = v; large = u; } size[large] += size[small]; parent[small] = large; return true; } public int find(int v) { if(parent[v] == -1) return v; int head = find(parent[v]); parent[v] = head; return head; } } public static class MyScanner { BufferedReader br; StringTokenizer st; // 32768? public MyScanner(InputStream is, int bufferSize) { br = new BufferedReader(new InputStreamReader(is), bufferSize); } public MyScanner(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); // br = new BufferedReader(new InputStreamReader(System.in)); // br = new BufferedReader(new InputStreamReader(new FileInputStream("input.txt"))); } public void close() { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine(){ String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } int[][] nextMatrix(int n, int m) { return nextMatrix(n, m, 0); } int[][] nextMatrix(int n, int m, int offset) { int[][] mat = new int[n][m]; for(int i=0; i<n; i++) { for(int j=0; j<m; j++) { mat[i][j] = nextInt()+offset; } } return mat; } int[] nextIntArray(int len) { return nextIntArray(len, 0); } int[] nextIntArray(int len, int offset){ int[] a = new int[len]; for(int j=0; j<len; j++) a[j] = nextInt()+offset; return a; } long[] nextLongArray(int len) { return nextLongArray(len, 0); } long[] nextLongArray(int len, int offset){ long[] a = new long[len]; for(int j=0; j<len; j++) a[j] = nextLong()+offset; return a; } } public static class MyPrintWriter extends PrintWriter{ public MyPrintWriter(OutputStream os) { super(os); } public void printlnAns(long ans) { println(ans); } public void printlnAns(int ans) { println(ans); } public void printlnAns(boolean ans) { if(ans) println(YES); else println(NO); } public void printAns(long[] arr){ if(arr != null && arr.length > 0){ print(arr[0]); for(int i=1; i<arr.length; i++){ print(" "); print(arr[i]); } } } public void printlnAns(long[] arr){ printAns(arr); println(); } public void printAns(int[] arr){ if(arr != null && arr.length > 0){ print(arr[0]); for(int i=1; i<arr.length; i++){ print(" "); print(arr[i]); } } } public void printlnAns(int[] arr){ printAns(arr); println(); } public <T> void printAns(ArrayList<T> arr){ if(arr != null && arr.size() > 0){ print(arr.get(0)); for(int i=1; i<arr.size(); i++){ print(" "); print(arr.get(i)); } } } public <T> void printlnAns(ArrayList<T> arr){ printAns(arr); println(); } public void printAns(int[] arr, int add){ if(arr != null && arr.length > 0){ print(arr[0]+add); for(int i=1; i<arr.length; i++){ print(" "); print(arr[i]+add); } } } public void printlnAns(int[] arr, int add){ printAns(arr, add); println(); } public void printAns(ArrayList<Integer> arr, int add) { if(arr != null && arr.size() > 0){ print(arr.get(0)+add); for(int i=1; i<arr.size(); i++){ print(" "); print(arr.get(i)+add); } } } public void printlnAns(ArrayList<Integer> arr, int add){ printAns(arr, add); println(); } public void printlnAnsSplit(long[] arr, int split){ if(arr != null){ for(int i=0; i<arr.length; i+=split){ print(arr[i]); for(int j=i+1; j<i+split; j++){ print(" "); print(arr[j]); } println(); } } } public void printlnAnsSplit(int[] arr, int split){ if(arr != null){ for(int i=0; i<arr.length; i+=split){ print(arr[i]); for(int j=i+1; j<i+split; j++){ print(" "); print(arr[j]); } println(); } } } public <T> void printlnAnsSplit(ArrayList<T> arr, int split){ if(arr != null && !arr.isEmpty()){ for(int i=0; i<arr.size(); i+=split){ print(arr.get(i)); for(int j=i+1; j<i+split; j++){ print(" "); print(arr.get(j)); } println(); } } } } static private void permutateAndSort(long[] a) { int n = a.length; Random R = new Random(System.currentTimeMillis()); for(int i=0; i<n; i++) { int t = R.nextInt(n-i); long temp = a[n-1-i]; a[n-1-i] = a[t]; a[t] = temp; } Arrays.sort(a); } static private void permutateAndSort(int[] a) { int n = a.length; Random R = new Random(System.currentTimeMillis()); for(int i=0; i<n; i++) { int t = R.nextInt(n-i); int temp = a[n-1-i]; a[n-1-i] = a[t]; a[t] = temp; } Arrays.sort(a); } static private int[][] constructChildren(int n, int[] parent, int parentRoot){ int[][] childrens = new int[n][]; int[] numChildren = new int[n]; for(int i=0; i<parent.length; i++) { if(parent[i] != parentRoot) numChildren[parent[i]]++; } for(int i=0; i<n; i++) { childrens[i] = new int[numChildren[i]]; } int[] idx = new int[n]; for(int i=0; i<parent.length; i++) { if(parent[i] != parentRoot) childrens[parent[i]][idx[parent[i]]++] = i; } return childrens; } static private int[][][] constructDirectedNeighborhood(int n, int[][] e){ int[] inDegree = new int[n]; int[] outDegree = new int[n]; for(int i=0; i<e.length; i++) { int u = e[i][0]; int v = e[i][1]; outDegree[u]++; inDegree[v]++; } int[][] inNeighbors = new int[n][]; int[][] outNeighbors = new int[n][]; for(int i=0; i<n; i++) { inNeighbors[i] = new int[inDegree[i]]; outNeighbors[i] = new int[outDegree[i]]; } for(int i=0; i<e.length; i++) { int u = e[i][0]; int v = e[i][1]; outNeighbors[u][--outDegree[u]] = v; inNeighbors[v][--inDegree[v]] = u; } return new int[][][] {inNeighbors, outNeighbors}; } static private int[][] constructNeighborhood(int n, int[][] e) { int[] degree = new int[n]; for(int i=0; i<e.length; i++) { int u = e[i][0]; int v = e[i][1]; degree[u]++; degree[v]++; } int[][] neighbors = new int[n][]; for(int i=0; i<n; i++) neighbors[i] = new int[degree[i]]; for(int i=0; i<e.length; i++) { int u = e[i][0]; int v = e[i][1]; neighbors[u][--degree[u]] = v; neighbors[v][--degree[v]] = u; } return neighbors; } static private void drawGraph(int[][] e) { makeDotUndirected(e); try { final Process process = new ProcessBuilder("dot", "-Tpng", "graph.dot") .redirectOutput(new File("graph.png")) .start(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } static private void makeDotUndirected(int[][] e) { MyPrintWriter out2 = null; try { out2 = new MyPrintWriter(new FileOutputStream("graph.dot")); } catch (FileNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } out2.println("strict graph {"); for(int i=0; i<e.length; i++){ out2.println(e[i][0] + "--" + e[i][1] + ";"); } out2.println("}"); out2.close(); } static private void makeDotDirected(int[][] e) { MyPrintWriter out2 = null; try { out2 = new MyPrintWriter(new FileOutputStream("graph.dot")); } catch (FileNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } out2.println("strict digraph {"); for(int i=0; i<e.length; i++){ out2.println(e[i][0] + "->" + e[i][1] + ";"); } out2.println("}"); out2.close(); } }
Java
["5 5\n1 2\n3 5\n1 3\n3 2\n4 2", "10 11\n1 2\n2 5\n3 4\n4 2\n8 1\n4 5\n10 5\n9 5\n8 2\n5 7\n4 6"]
1 second
["01111", "0011111011"]
NoteHere is the graph given in the first example. There is only one minimum spanning tree in this graph. A minimum spanning tree is $$$(1,2),(3,5),(1,3),(2,4)$$$ which has weight $$$1+2+3+5=11$$$.Here is a part of the process of calling findMST(1): reset the array vis and the edge set s; calling dfs(1); vis[1] := true; iterate through each edge $$$(1,2),(1,3)$$$; add edge $$$(1,2)$$$ into the edge set s, calling dfs(2): vis[2] := true iterate through each edge $$$(2,1),(2,3),(2,4)$$$; because vis[1] = true, ignore the edge $$$(2,1)$$$; add edge $$$(2,3)$$$ into the edge set s, calling dfs(3): ... In the end, it will select edges $$$(1,2),(2,3),(3,5),(2,4)$$$ with total weight $$$1+4+2+5=12&gt;11$$$, so findMST(1) does not find a minimum spanning tree.It can be shown that the other trees are all MSTs, so the answer is 01111.
Java 17
standard input
[ "dfs and similar", "graphs", "greedy" ]
2bf41400fa51f472f1d3904baa06d6a8
The first line of the input contains two integers $$$n$$$, $$$m$$$ ($$$2\le n\le 10^5$$$, $$$n-1\le m\le 2\cdot 10^5$$$) — the number of vertices and the number of edges in the graph. Each of the following $$$m$$$ lines contains two integers $$$u_i$$$ and $$$v_i$$$ ($$$1\le u_i, v_i\le n$$$, $$$u_i\ne v_i$$$), describing an undirected edge $$$(u_i,v_i)$$$ in the graph. The $$$i$$$-th edge in the input has weight $$$i$$$. It is guaranteed that the graph is connected and there is at most one edge between any pair of vertices.
2,400
You need to output a binary string $$$s$$$, where $$$s_i=1$$$ if findMST(i) creates an MST, and $$$s_i = 0$$$ otherwise.
standard output
PASSED
01363b84d3712abc3978597c6acbc423
train_108.jsonl
1657982100
You are given a connected undirected graph consisting of $$$n$$$ vertices and $$$m$$$ edges. The weight of the $$$i$$$-th edge is $$$i$$$.Here is a wrong algorithm of finding a minimum spanning tree (MST) of a graph:vis := an array of length ns := a set of edgesfunction dfs(u): vis[u] := true iterate through each edge (u, v) in the order from smallest to largest edge weight if vis[v] = false add edge (u, v) into the set (s) dfs(v)function findMST(u): reset all elements of (vis) to false reset the edge set (s) to empty dfs(u) return the edge set (s)Each of the calls findMST(1), findMST(2), ..., findMST(n) gives you a spanning tree of the graph. Determine which of these trees are minimum spanning trees.
256 megabytes
import java.util.*; import java.util.function.*; import java.io.*; // you can compare with output.txt and expected out public class Round808E { MyPrintWriter out; MyScanner in; // final static long FIXED_RANDOM; // static { // FIXED_RANDOM = System.currentTimeMillis(); // } final static String IMPOSSIBLE = "IMPOSSIBLE"; final static String POSSIBLE = "POSSIBLE"; final static String YES = "YES"; final static String NO = "NO"; private void initIO(boolean isFileIO) { if (System.getProperty("ONLINE_JUDGE") == null && isFileIO) { try{ in = new MyScanner(new FileInputStream("input.txt")); out = new MyPrintWriter(new FileOutputStream("output.txt")); } catch(FileNotFoundException e){ e.printStackTrace(); } } else{ in = new MyScanner(System.in); out = new MyPrintWriter(new BufferedOutputStream(System.out)); } } public static void main(String[] args){ // Scanner in = new Scanner(new BufferedReader(new InputStreamReader(System.in))); Round808E sol = new Round808E(); sol.run(); } private void run() { boolean isDebug = false; boolean isFileIO = true; boolean hasMultipleTests = false; initIO(isFileIO); int t = hasMultipleTests? in.nextInt() : 1; for (int i = 1; i <= t; ++i) { if(isDebug){ out.printf("Test %d\n", i); } getInput(); solve(); printOutput(); } in.close(); out.close(); } // use suitable one between matrix(2, n) or matrix(n, 2) for graph edges, pairs, ... int n, m; int[][] e; void getInput() { n = in.nextInt(); m = in.nextInt(); e = in.nextMatrix(m, 2, -1); } void printOutput() { out.println(ans); } String ans; void solve(){ // fail at vk if v1 -> v2 -> ... -> vk // w (vi vk) < w (vk-1 vk) for i < k // success if smallest edge of vk is used // same as remove v1 // dfs on each cc // bad if v1 -> v2 // removing v1 from mst results in the same shape in the graph // -> good // mst is fixed as the main tree // for each bad edge e = (u, v) // good vertices are exactly // vertices in subtree of u, rooted at v // and vertices in subtree of v, rooted at u // since, for some other vertex w, // in a rooted tree at w, suppose findMST(w) didn't meet any bad edges until u or v // wlog it reached u before v // suppose it further didn't meet any bad edges in subtree of u (otherwise w is already bad) // then it will use uv to go to v, eventually making w bad // for each bad edge e = (u, v) // i) lca(u, v) = u // subtree of v is good // subtree of u - v is good // G - subtree of u is good // this can be expressed by // 1) root is good // 2) the prev of u in the path between u and v is bad // 3) v is good // ii) lca(u, v) = w // subtree of u and subtree of v are good // this can be expressed by // 1) u is good // 2) v is good // then we propagate the goodness // if a vertex is good if its goodness is exactly m-(n-1) DSU dsu = new DSU(n); treeNeighbors = new ArrayList[n]; for(int i=0; i<n; i++) treeNeighbors[i] = new ArrayList<Integer>(); boolean[] isBadEdge = new boolean[m]; for(int i=0; i<m; i++) { int u = e[i][0]; int v = e[i][1]; boolean isGood = dsu.union(u, v); if(isGood) { treeNeighbors[u].add(v); treeNeighbors[v].add(u); } else isBadEdge[i] = true; } final int root = 0; computeLifting(root); goodness = new int[n]; for(int i=0; i<m; i++) { if(isBadEdge[i]) { int u = e[i][0]; int v = e[i][1]; int w = lca(u, v); if(w == v) { int temp = u; u = v; v = temp; } if(w == u) { // i) lca(u, v) = u // subtree of v is good // subtree of u - v is good // G - subtree of u is good // so // 1) root is good // 2) the prev of u in the path between u and v is bad // 3) v is good goodness[root]++; int prev = prevChild(u, v); goodness[prev]--; goodness[v]++; } else { // ii) lca(u, v) = w // subtree of u and subtree of v are good // so // 1) u is good // 2) v is good goodness[u]++; goodness[v]++; } } } propagateDFS(root, -1); StringBuilder sb = new StringBuilder(); for(int i=0; i<n; i++) { if(goodness[i] == m-(n-1)) sb.append('1'); else sb.append('0'); } ans = sb.toString(); } int[] goodness; void propagateDFS(int curr, int parent) { for(int next: treeNeighbors[curr]) { if(next == parent) continue; goodness[next] += goodness[curr]; propagateDFS(next, curr); } } void computeLifting(final int root) { int log = 31-Integer.numberOfLeadingZeros(n); lifting = new int[log+1][n]; depth = new int[n]; liftingDFS(root, root, 0); } void liftingDFS(int curr, int parent, int d) { depth[curr] = d; lifting[0][curr] = parent; for(int i=1; i<lifting.length; i++) { lifting[i][curr] = lifting[i-1][lifting[i-1][curr]]; } for(int next: treeNeighbors[curr]) { if(next == parent) continue; liftingDFS(next, curr, d+1); } } boolean isAncestor(int u, int v) { for(int i=lifting.length-1; i>=0 && depth[v] > depth[u]; i--){ if(depth[lifting[i][v]] >= depth[u]) v = lifting[i][v]; } return u == v; } // assumes u is an ancestor of v int prevChild(int u, int v) { for(int i=lifting.length-1; i>=0 && depth[v] > depth[u]; i--){ if(depth[lifting[i][v]] > depth[u]) v = lifting[i][v]; } return v; } int lca(int u, int v) { if(depth[v] < depth[u]) return lca(v, u); // depth[u] <= depth[v] for(int i=lifting.length-1; i>=0 && depth[v] > depth[u]; i--){ if(depth[lifting[i][v]] >= depth[u]) v = lifting[i][v]; } if(u == v) return u; // depth[u] = depth[v] for(int i=lifting.length-1; i>=0; i--) { if(lifting[i][u] != lifting[i][v]) { u = lifting[i][u]; v = lifting[i][v]; } } return lifting[0][u]; } ArrayList<Integer>[] treeNeighbors; int[][] lifting; int[] depth; class DSU{ int[] parent; int[] size; public DSU(int n) { parent = new int[n]; Arrays.fill(parent, -1); size = new int[n]; } public boolean union(int u, int v) { u = find(u); v = find(v); if(u == v) return false; int small, large; if(size[u] < size[v]) { small = u; large = v; } else { small = v; large = u; } size[large] += size[small]; parent[small] = large; return true; } public int find(int v) { if(parent[v] == -1) return v; int head = find(parent[v]); parent[v] = head; return head; } } public static class MyScanner { BufferedReader br; StringTokenizer st; // 32768? public MyScanner(InputStream is, int bufferSize) { br = new BufferedReader(new InputStreamReader(is), bufferSize); } public MyScanner(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); // br = new BufferedReader(new InputStreamReader(System.in)); // br = new BufferedReader(new InputStreamReader(new FileInputStream("input.txt"))); } public void close() { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine(){ String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } int[][] nextMatrix(int n, int m) { return nextMatrix(n, m, 0); } int[][] nextMatrix(int n, int m, int offset) { int[][] mat = new int[n][m]; for(int i=0; i<n; i++) { for(int j=0; j<m; j++) { mat[i][j] = nextInt()+offset; } } return mat; } int[] nextIntArray(int len) { return nextIntArray(len, 0); } int[] nextIntArray(int len, int offset){ int[] a = new int[len]; for(int j=0; j<len; j++) a[j] = nextInt()+offset; return a; } long[] nextLongArray(int len) { return nextLongArray(len, 0); } long[] nextLongArray(int len, int offset){ long[] a = new long[len]; for(int j=0; j<len; j++) a[j] = nextLong()+offset; return a; } } public static class MyPrintWriter extends PrintWriter{ public MyPrintWriter(OutputStream os) { super(os); } public void printlnAns(long ans) { println(ans); } public void printlnAns(int ans) { println(ans); } public void printlnAns(boolean ans) { if(ans) println(YES); else println(NO); } public void printAns(long[] arr){ if(arr != null && arr.length > 0){ print(arr[0]); for(int i=1; i<arr.length; i++){ print(" "); print(arr[i]); } } } public void printlnAns(long[] arr){ printAns(arr); println(); } public void printAns(int[] arr){ if(arr != null && arr.length > 0){ print(arr[0]); for(int i=1; i<arr.length; i++){ print(" "); print(arr[i]); } } } public void printlnAns(int[] arr){ printAns(arr); println(); } public <T> void printAns(ArrayList<T> arr){ if(arr != null && arr.size() > 0){ print(arr.get(0)); for(int i=1; i<arr.size(); i++){ print(" "); print(arr.get(i)); } } } public <T> void printlnAns(ArrayList<T> arr){ printAns(arr); println(); } public void printAns(int[] arr, int add){ if(arr != null && arr.length > 0){ print(arr[0]+add); for(int i=1; i<arr.length; i++){ print(" "); print(arr[i]+add); } } } public void printlnAns(int[] arr, int add){ printAns(arr, add); println(); } public void printAns(ArrayList<Integer> arr, int add) { if(arr != null && arr.size() > 0){ print(arr.get(0)+add); for(int i=1; i<arr.size(); i++){ print(" "); print(arr.get(i)+add); } } } public void printlnAns(ArrayList<Integer> arr, int add){ printAns(arr, add); println(); } public void printlnAnsSplit(long[] arr, int split){ if(arr != null){ for(int i=0; i<arr.length; i+=split){ print(arr[i]); for(int j=i+1; j<i+split; j++){ print(" "); print(arr[j]); } println(); } } } public void printlnAnsSplit(int[] arr, int split){ if(arr != null){ for(int i=0; i<arr.length; i+=split){ print(arr[i]); for(int j=i+1; j<i+split; j++){ print(" "); print(arr[j]); } println(); } } } public <T> void printlnAnsSplit(ArrayList<T> arr, int split){ if(arr != null && !arr.isEmpty()){ for(int i=0; i<arr.size(); i+=split){ print(arr.get(i)); for(int j=i+1; j<i+split; j++){ print(" "); print(arr.get(j)); } println(); } } } } static private void permutateAndSort(long[] a) { int n = a.length; Random R = new Random(System.currentTimeMillis()); for(int i=0; i<n; i++) { int t = R.nextInt(n-i); long temp = a[n-1-i]; a[n-1-i] = a[t]; a[t] = temp; } Arrays.sort(a); } static private void permutateAndSort(int[] a) { int n = a.length; Random R = new Random(System.currentTimeMillis()); for(int i=0; i<n; i++) { int t = R.nextInt(n-i); int temp = a[n-1-i]; a[n-1-i] = a[t]; a[t] = temp; } Arrays.sort(a); } static private int[][] constructChildren(int n, int[] parent, int parentRoot){ int[][] childrens = new int[n][]; int[] numChildren = new int[n]; for(int i=0; i<parent.length; i++) { if(parent[i] != parentRoot) numChildren[parent[i]]++; } for(int i=0; i<n; i++) { childrens[i] = new int[numChildren[i]]; } int[] idx = new int[n]; for(int i=0; i<parent.length; i++) { if(parent[i] != parentRoot) childrens[parent[i]][idx[parent[i]]++] = i; } return childrens; } static private int[][][] constructDirectedNeighborhood(int n, int[][] e){ int[] inDegree = new int[n]; int[] outDegree = new int[n]; for(int i=0; i<e.length; i++) { int u = e[i][0]; int v = e[i][1]; outDegree[u]++; inDegree[v]++; } int[][] inNeighbors = new int[n][]; int[][] outNeighbors = new int[n][]; for(int i=0; i<n; i++) { inNeighbors[i] = new int[inDegree[i]]; outNeighbors[i] = new int[outDegree[i]]; } for(int i=0; i<e.length; i++) { int u = e[i][0]; int v = e[i][1]; outNeighbors[u][--outDegree[u]] = v; inNeighbors[v][--inDegree[v]] = u; } return new int[][][] {inNeighbors, outNeighbors}; } static private int[][] constructNeighborhood(int n, int[][] e) { int[] degree = new int[n]; for(int i=0; i<e.length; i++) { int u = e[i][0]; int v = e[i][1]; degree[u]++; degree[v]++; } int[][] neighbors = new int[n][]; for(int i=0; i<n; i++) neighbors[i] = new int[degree[i]]; for(int i=0; i<e.length; i++) { int u = e[i][0]; int v = e[i][1]; neighbors[u][--degree[u]] = v; neighbors[v][--degree[v]] = u; } return neighbors; } static private void drawGraph(int[][] e) { makeDotUndirected(e); try { final Process process = new ProcessBuilder("dot", "-Tpng", "graph.dot") .redirectOutput(new File("graph.png")) .start(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } static private void makeDotUndirected(int[][] e) { MyPrintWriter out2 = null; try { out2 = new MyPrintWriter(new FileOutputStream("graph.dot")); } catch (FileNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } out2.println("strict graph {"); for(int i=0; i<e.length; i++){ out2.println(e[i][0] + "--" + e[i][1] + ";"); } out2.println("}"); out2.close(); } static private void makeDotDirected(int[][] e) { MyPrintWriter out2 = null; try { out2 = new MyPrintWriter(new FileOutputStream("graph.dot")); } catch (FileNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } out2.println("strict digraph {"); for(int i=0; i<e.length; i++){ out2.println(e[i][0] + "->" + e[i][1] + ";"); } out2.println("}"); out2.close(); } }
Java
["5 5\n1 2\n3 5\n1 3\n3 2\n4 2", "10 11\n1 2\n2 5\n3 4\n4 2\n8 1\n4 5\n10 5\n9 5\n8 2\n5 7\n4 6"]
1 second
["01111", "0011111011"]
NoteHere is the graph given in the first example. There is only one minimum spanning tree in this graph. A minimum spanning tree is $$$(1,2),(3,5),(1,3),(2,4)$$$ which has weight $$$1+2+3+5=11$$$.Here is a part of the process of calling findMST(1): reset the array vis and the edge set s; calling dfs(1); vis[1] := true; iterate through each edge $$$(1,2),(1,3)$$$; add edge $$$(1,2)$$$ into the edge set s, calling dfs(2): vis[2] := true iterate through each edge $$$(2,1),(2,3),(2,4)$$$; because vis[1] = true, ignore the edge $$$(2,1)$$$; add edge $$$(2,3)$$$ into the edge set s, calling dfs(3): ... In the end, it will select edges $$$(1,2),(2,3),(3,5),(2,4)$$$ with total weight $$$1+4+2+5=12&gt;11$$$, so findMST(1) does not find a minimum spanning tree.It can be shown that the other trees are all MSTs, so the answer is 01111.
Java 17
standard input
[ "dfs and similar", "graphs", "greedy" ]
2bf41400fa51f472f1d3904baa06d6a8
The first line of the input contains two integers $$$n$$$, $$$m$$$ ($$$2\le n\le 10^5$$$, $$$n-1\le m\le 2\cdot 10^5$$$) — the number of vertices and the number of edges in the graph. Each of the following $$$m$$$ lines contains two integers $$$u_i$$$ and $$$v_i$$$ ($$$1\le u_i, v_i\le n$$$, $$$u_i\ne v_i$$$), describing an undirected edge $$$(u_i,v_i)$$$ in the graph. The $$$i$$$-th edge in the input has weight $$$i$$$. It is guaranteed that the graph is connected and there is at most one edge between any pair of vertices.
2,400
You need to output a binary string $$$s$$$, where $$$s_i=1$$$ if findMST(i) creates an MST, and $$$s_i = 0$$$ otherwise.
standard output
PASSED
7896b589d1e05d4745669b5107aeae6b
train_108.jsonl
1657982100
You are given an array $$$a$$$ consisting of $$$n$$$ non-negative integers. It is guaranteed that $$$a$$$ is sorted from small to large.For each operation, we generate a new array $$$b_i=a_{i+1}-a_{i}$$$ for $$$1 \le i &lt; n$$$. Then we sort $$$b$$$ from small to large, replace $$$a$$$ with $$$b$$$, and decrease $$$n$$$ by $$$1$$$.After performing $$$n-1$$$ operations, $$$n$$$ becomes $$$1$$$. You need to output the only integer in array $$$a$$$ (that is to say, you need to output $$$a_1$$$).
256 megabytes
import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.security.cert.X509CRL; import java.util.*; import java.lang.*; import java.util.stream.Collector; import java.util.stream.Collectors; @SuppressWarnings("unused") public class Main { static InputStream is; static PrintWriter out; //static String INPUT = "in.txt"; static String INPUT = ""; static String OUTPUT = ""; //global const //private final static long BASE = 998244353L; private final static int ALPHABET = (int)('z') - (int)('a') + 1; private final static long BASE = 1000000007l; private final static int INF_I = 1000000000; private final static long INF_L = 10000000000000000l; private final static int MAXN = 1000100; private final static int MAXK = 30; private final static int[] DX = {-1,0,1,0}; private final static int[] DY = {0,1,0,-1}; //global static void solve() { //int ntest = 1; int ntest = readInt(); for (int test=0;test<ntest;test++) { int N = readInt(); int[] A = readIntArray(N); int pos0 = 0; for (int i=0;i<N;i++) if (A[i]==0) pos0++; for (int ti=N-2; ti>=0; ti--) { int npos0=Math.max(0,pos0-1); for (int i=Math.max(0,pos0-1); i<=ti; i++) { A[i] = A[i+1] - A[i]; if (A[i]==0) npos0++; } if (pos0 <= ti) Arrays.sort(A, Math.max(0,pos0-1), ti+1); pos0 = npos0; if (pos0 > ti) break; } out.println(A[0]); } } public static void main(String[] args) throws Exception { long S = System.currentTimeMillis(); if (INPUT=="") { is = System.in; } else { File file = new File(INPUT); is = new FileInputStream(file); } if (OUTPUT == "") out = new PrintWriter(System.out); else out = new PrintWriter(OUTPUT); solve(); out.flush(); long G = System.currentTimeMillis(); } private static class MultiSet<T extends Comparable<T>> { private TreeSet<T> set; private Map<T, Integer> count; public MultiSet() { this.set = new TreeSet<>(); this.count = new HashMap<>(); } public void add(T x) { this.set.add(x); int o = this.count.getOrDefault(x, 0); this.count.put(x, o+1); } public void remove(T x) { int o = this.count.getOrDefault(x, 0); if (o==0) return; this.count.put(x, o-1); if (o==1) this.set.remove(x); } public T first() { return this.set.first(); } public T last() { return this.set.last(); } public int size() { int res = 0; for (T x: this.set) res += this.count.get(x); return res; } } private static class Point<T extends Number & Comparable<T>> implements Comparable<Point<T>> { private T x; private T y; public Point(T x, T y) { this.x = x; this.y = y; } public T getX() {return x;} public T getY() {return y;} @Override public int compareTo(Point<T> o) { int cmp = x.compareTo(o.getX()); if (cmp==0) return y.compareTo(o.getY()); return cmp; } } private static class ClassComparator<T extends Comparable<T>> implements Comparator<T> { public ClassComparator() {} @Override public int compare(T a, T b) { return a.compareTo(b); } } private static class ListComparator<T extends Comparable<T>> implements Comparator<List<T>> { public ListComparator() {} @Override public int compare(List<T> o1, List<T> o2) { for (int i = 0; i < Math.min(o1.size(), o2.size()); i++) { int c = o1.get(i).compareTo(o2.get(i)); if (c != 0) { return c; } } return Integer.compare(o1.size(), o2.size()); } } private static boolean eof() { if(lenbuf == -1)return true; int lptr = ptrbuf; while(lptr < lenbuf)if(!isSpaceChar(inbuf[lptr++]))return false; try { is.mark(1000); while(true){ int b = is.read(); if(b == -1){ is.reset(); return true; }else if(!isSpaceChar(b)){ is.reset(); return false; } } } catch (IOException e) { return true; } } private static byte[] inbuf = new byte[1024]; static int lenbuf = 0, ptrbuf = 0; private static int readByte() { if(lenbuf == -1)throw new InputMismatchException(); if(ptrbuf >= lenbuf){ ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if(lenbuf <= 0)return -1; } return inbuf[ptrbuf++]; } private static boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } // private static boolean isSpaceChar(int c) { return !(c >= 32 && c <= 126); } private static int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; } private static double readDouble() { return Double.parseDouble(readString()); } private static char readChar() { return (char)skip(); } private static String readString() { int b = skip(); StringBuilder sb = new StringBuilder(); while(!(isSpaceChar(b))){ sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private static char[] readChar(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while(p < n && !(isSpaceChar(b))){ buf[p++] = (char)b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private static char[][] readTable(int n, int m) { char[][] map = new char[n][]; for(int i = 0;i < n;i++)map[i] = readChar(m); return map; } private static int[] readIntArray(int n) { int[] a = new int[n]; for(int i = 0;i < n;i++)a[i] = readInt(); return a; } private static long[] readLongArray(int n) { long[] a = new long[n]; for (int i=0;i<n;i++) a[i] = readLong(); return a; } private static int readInt() { int num = 0, b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private static long readLong() { 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 static void tr(Object... o) { if(INPUT.length() != 0)System.out.println(Arrays.deepToString(o)); } }
Java
["5\n\n3\n\n1 10 100\n\n4\n\n4 8 9 13\n\n5\n\n0 0 0 8 13\n\n6\n\n2 4 8 16 32 64\n\n7\n\n0 0 0 0 0 0 0"]
1 second
["81\n3\n1\n2\n0"]
NoteTo simplify the notes, let $$$\operatorname{sort}(a)$$$ denote the array you get by sorting $$$a$$$ from small to large.In the first test case, $$$a=[1,10,100]$$$ at first. After the first operation, $$$a=\operatorname{sort}([10-1,100-10])=[9,90]$$$. After the second operation, $$$a=\operatorname{sort}([90-9])=[81]$$$.In the second test case, $$$a=[4,8,9,13]$$$ at first. After the first operation, $$$a=\operatorname{sort}([8-4,9-8,13-9])=[1,4,4]$$$. After the second operation, $$$a=\operatorname{sort}([4-1,4-4])=[0,3]$$$. After the last operation, $$$a=\operatorname{sort}([3-0])=[3]$$$.
Java 8
standard input
[ "brute force", "sortings" ]
499b1440d8bb528d089724910e37e226
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1\le t\le 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2\le n\le 10^5$$$) — the length of the array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1,a_2,\dots,a_n$$$ ($$$0\le a_1\le \ldots\le a_n \le 5\cdot 10^5$$$) — the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2.5\cdot 10^5$$$, and the sum of $$$a_n$$$ over all test cases does not exceed $$$5\cdot 10^5$$$.
1,900
For each test case, output the answer on a new line.
standard output
PASSED
1fc3e267a79e130d5d49a5c9c9c4e3ee
train_108.jsonl
1657982100
You are given an array $$$a$$$ consisting of $$$n$$$ non-negative integers. It is guaranteed that $$$a$$$ is sorted from small to large.For each operation, we generate a new array $$$b_i=a_{i+1}-a_{i}$$$ for $$$1 \le i &lt; n$$$. Then we sort $$$b$$$ from small to large, replace $$$a$$$ with $$$b$$$, and decrease $$$n$$$ by $$$1$$$.After performing $$$n-1$$$ operations, $$$n$$$ becomes $$$1$$$. You need to output the only integer in array $$$a$$$ (that is to say, you need to output $$$a_1$$$).
256 megabytes
import java.util.*; import java.io.*; public class Main { static FastReader sc=new FastReader(); static PrintWriter out=new PrintWriter(System.out); static int dx[]={0,0,-1,1},dy[]={-1,1,0,0}; static final double pi=3.1415926536; static long mod=1000000007; // static long mod=998244353; static int MAX=Integer.MAX_VALUE; static int MIN=Integer.MIN_VALUE; static long MAXL=Long.MAX_VALUE; static long MINL=Long.MIN_VALUE; static ArrayList<Integer> graph[]; static long fact[]; static long seg[]; static int dp[]; // static long dp[][]; public static void main (String[] args) throws java.lang.Exception { // code goes here int t=I(); outer:while(t-->0) { int n=I(); int a[]=I(n); ArrayList<Integer> arr=new ArrayList<>(); int temp=0; boolean flag=false; for(int i:a){ if(i==0){ temp++; }else{ if(temp>0 && !flag){ flag=true; arr.add(0); } arr.add(i); } } if(arr.size()==0){ out.println("0"); continue; } // temp--; int qq=0; while(arr.size()>1){ if(temp>1){ while(temp-->1){ ArrayList<Integer> A=new ArrayList<>(); Collections.sort(arr); // System.out.print("temp->"+temp+":"); // for(int ii:arr){ // System.out.print(ii+" "); // }System.out.println(); // A.add(0); int temp1=0; for(int i=0;i<arr.size()-1;i++){ if(arr.get(i+1)-arr.get(i)==0){ temp1++; }else{ A.add(arr.get(i+1)-arr.get(i)); } } arr.clear(); if(temp1>0){ // arr.add(0); temp+=temp1; } if(temp>0){ arr.add(0); } for(int i:A){ arr.add(i); } } }else{ ArrayList<Integer> A=new ArrayList<>(); Collections.sort(arr); if(temp>0) temp--; // if(qq<4){ // System.out.print("temp->"+temp+":"); // for(int ii:arr){ // System.out.print(ii+" "); // }System.out.println(); // } int temp1=0; for(int i=0;i<arr.size()-1;i++){ if(arr.get(i+1)-arr.get(i)==0){ temp1++; }else{ A.add(arr.get(i+1)-arr.get(i)); } } arr.clear(); // temp--; if(temp1>0){ // arr.add(0); temp+=temp1; } // System.out.println(temp1); if(temp>0){ arr.add(0); } for(int i:A){ arr.add(i); } qq++; } } out.println(arr.get(0)); } out.close(); } public static class pair { int a; int b; public pair(int aa,int bb) { a=aa; b=bb; } } public static class myComp implements Comparator<pair> { //sort in ascending order. public int compare(pair p1,pair p2) { if(p1.a==p2.a) return 0; else if(p1.a<p2.a) return -1; else return 1; } // sort in descending order. // public int compare(pair p1,pair p2) // { // if(p1.b==p2.b) // return 0; // else if(p1.b<p2.b) // return 1; // else // return -1; // } } public static void setGraph(int n,int m)throws IOException { graph=new ArrayList[n+1]; for(int i=0;i<=n;i++){ graph[i]=new ArrayList<>(); } for(int i=0;i<m;i++){ int u=I(),v=I(); graph[u].add(v); graph[v].add(u); } } //LOWER_BOUND and UPPER_BOUND functions //It returns answer according to zero based indexing. public static int lower_bound(pair[] arr,int X,int start, int end) //start=0,end=n-1 { if(start>end)return -1; // if(arr.get(end)<X)return end; if(arr[end].a<X)return end; // if(arr.get(start)>X)return -1; if(arr[start].a>X)return -1; int left=start,right=end; while(left<right){ int mid=(left+right)/2; if(arr[mid].a==X){ // if(arr.get(mid)==X){ //Returns last index of lower bound value. if(mid<end && arr[mid+1].a==X){ // if(mid<end && arr.get(mid+1)==X){ left=mid+1; }else{ return mid; } } // if(arr.get(mid)==X){ //Returns first index of lower bound value. // if(arr[mid]==X){ // // if(mid>start && arr.get(mid-1)==X){ // if(mid>start && arr[mid-1]==X){ // right=mid-1; // }else{ // return mid; // } // } else if(arr[mid].a>X){ // else if(arr.get(mid)>X){ if(mid>start && arr[mid-1].a<X){ // if(mid>start && arr.get(mid-1)<X){ return mid-1; }else{ right=mid-1; } }else{ if(mid<end && arr[mid+1].a>X){ // if(mid<end && arr.get(mid+1)>X){ return mid; }else{ left=mid+1; } } } return left; } //It returns answer according to zero based indexing. public static int upper_bound(long arr[],long X,int start,int end) //start=0,end=n-1 { if(arr[0]>=X)return start; if(arr[arr.length-1]<X)return -1; int left=start,right=end; while(left<right){ int mid=(left+right)/2; if(arr[mid]==X){ //returns first index of upper bound value. if(mid>start && arr[mid-1]==X){ right=mid-1; }else{ return mid; } } // if(arr[mid]==X){ //returns last index of upper bound value. // if(mid<end && arr[mid+1]==X){ // left=mid+1; // }else{ // return mid; // } // } else if(arr[mid]>X){ if(mid>start && arr[mid-1]<X){ return mid; }else{ right=mid-1; } }else{ if(mid<end && arr[mid+1]>X){ return mid+1; }else{ left=mid+1; } } } return left; } //END //Segment Tree Code public static void buildTree(long a[],int si,int ss,int se) { if(ss==se){ seg[si]=a[ss]; return; } int mid=(ss+se)/2; buildTree(a,2*si+1,ss,mid); buildTree(a,2*si+2,mid+1,se); seg[si]=max(seg[2*si+1],seg[2*si+2]); } // public static void update(int si,int ss,int se,int pos,int val) // { // if(ss==se){ // // seg[si]=val; // return; // } // int mid=(ss+se)/2; // if(pos<=mid){ // update(2*si+1,ss,mid,pos,val); // }else{ // update(2*si+2,mid+1,se,pos,val); // } // // seg[si]=min(seg[2*si+1],seg[2*si+2]); // if(seg[2*si+1].a < seg[2*si+2].a){ // seg[si].a=seg[2*si+1].a; // seg[si].b=seg[2*si+1].b; // }else{ // seg[si].a=seg[2*si+2].a; // seg[si].b=seg[2*si+2].b; // } // } public static long query(int si,int ss,int se,int qs,int qe) { if(qs>se || qe<ss)return 0; if(ss>=qs && se<=qe)return seg[si]; int mid=(ss+se)/2; long p1=query(2*si+1,ss,mid,qs,qe); long p2=query(2*si+2,mid+1,se,qs,qe); return max(p1,p2); } public static void merge(ArrayList<Integer> f,ArrayList<Integer> a,ArrayList<Integer> b) { int i=0,j=0; while(i<a.size() && j<b.size()){ if(a.get(i)<=b.get(j)){ f.add(a.get(i)); i++; }else{ f.add(b.get(j)); j++; } } while(i<a.size()){ f.add(a.get(i)); i++; } while(j<b.size()){ f.add(b.get(j)); j++; } } //Segment Tree Code end //Prefix Function of KMP Algorithm public static int[] KMP(char c[],int n) { int pi[]=new int[n]; for(int i=1;i<n;i++){ int j=pi[i-1]; while(j>0 && c[i]!=c[j]){ j=pi[j-1]; } if(c[i]==c[j])j++; pi[i]=j; } return pi; } public static long kadane(long a[],int n) //largest sum subarray { long max_sum=Long.MIN_VALUE,max_end=0; for(int i=0;i<n;i++){ max_end+=a[i]; if(max_sum<max_end){max_sum=max_end;} if(max_end<0){max_end=0;} } return max_sum; } public static ArrayList<Long> primeFact(long x) { ArrayList<Long> arr=new ArrayList<>(); if(x%2==0){ arr.add(2L); while(x%2==0){ x/=2; } } for(long i=3;i*i<=x;i+=2){ if(x%i==0){ arr.add(i); while(x%i==0){ x/=i; } } } if(x>0){ arr.add(x); } return arr; } public static long nPr(int n,int r) { long ans=divide(fact(n),fact(n-r),mod); return ans; } public static long nCr(int n,int r) { long ans=divide(fact[n],mul(fact[n-r],fact[r]),mod); return ans; } public static boolean isSorted(int a[]) { int n=a.length; for(int i=0;i<n-1;i++){ if(a[i]>a[i+1])return false; } return true; } public static boolean isSorted(long a[]) { int n=a.length; for(int i=0;i<n-1;i++){ if(a[i]>a[i+1])return false; } return true; } public static long toggleBits(long x)//one's complement || Toggle bits { int n=(int)(Math.floor(Math.log(x)/Math.log(2)))+1; return ((1<<n)-1)^x; } public static int computeXOR(int n) //compute XOR of all numbers between 1 to n. { if (n % 4 == 0) return n; if (n % 4 == 1) return 1; if (n % 4 == 2) return n + 1; return 0; } public static int np2(int x) { x--; x |= x >> 1; x |= x >> 2; x |= x >> 4; x |= x >> 8; x |= x >> 16; x++; return x; } public static int hp2(int x) { x |= x >> 1; x |= x >> 2; x |= x >> 4; x |= x >> 8; x |= x >> 16; return x ^ (x >> 1); } public static long hp2(long x) { x |= x >> 1; x |= x >> 2; x |= x >> 4; x |= x >> 8; x |= x >> 16; return x ^ (x >> 1); } public static ArrayList<Integer> primeSieve(int n) { ArrayList<Integer> arr=new ArrayList<>(); 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] == true) { for (int i = p * p; i <= n; i += p) prime[i] = false; } } for (int i = 2; i <= n; i++) { if (prime[i] == true) arr.add(i); } return arr; } // Fenwick / BinaryIndexed Tree USE IT - FenwickTree ft1=new FenwickTree(n); public static class FenwickTree { int farr[]; int n; public FenwickTree(int c) { n=c+1; farr=new int[n]; } // public void update_range(int l,int r,long p) // { // update(l,p); // update(r+1,(-1)*p); // } public void update(int x,int p) { for(;x<n;x+=x&(-x)) { farr[x]+=p; } } public int get(int x) { int ans=0; for(;x>0;x-=x&(-x)) { ans=ans+farr[x]; } return ans; } } //Disjoint Set Union //NOTE: call find function for all the index in the par array at last, //in order to set parent of every index properly. public static class DSU { int par[],rank[]; public DSU(int c) { par=new int[c+1]; rank=new int[c+1]; for(int i=0;i<=c;i++) { par[i]=i; rank[i]=0; } } public int find(int a) { if(a==par[a]) return a; return par[a]=find(par[a]); } public void union(int a,int b) { int a_rep=find(a),b_rep=find(b); if(a_rep==b_rep) return; if(rank[a_rep]<rank[b_rep]) par[a_rep]=b_rep; else if(rank[a_rep]>rank[b_rep]) par[b_rep]=a_rep; else { par[b_rep]=a_rep; rank[a_rep]++; } } } public static boolean isVowel(char c) { if(c=='a' || c=='e' || c=='i' || c=='u' || c=='o')return true; return false; } public static boolean isInteger(double N) { int X = (int)N; double temp2 = N - X; if (temp2 > 0) { return false; } return true; } public static boolean isPalindrome(String s) { int n=s.length(); for(int i=0;i<=n/2;i++){ if(s.charAt(i)!=s.charAt(n-i-1)){ return false; } } return true; } public static int gcd(int a,int b) { if(b==0) return a; else return gcd(b,a%b); } public static long gcd(long a,long b) { if(b==0) return a; else return gcd(b,a%b); } public static long fact(long n) { long fact=1; for(long i=2;i<=n;i++){ fact=((fact%mod)*(i%mod))%mod; } return fact; } public static long fact(int n) { long fact=1; for(int i=2;i<=n;i++){ fact=((fact%mod)*(i%mod))%mod; } return fact; } public static boolean isPrime(int n) { if (n <= 1) return false; if (n <= 3) return true; if (n % 2 == 0 || n % 3 == 0) return false; double sq=Math.sqrt(n); for (int i = 5; i <= sq; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } public static boolean isPrime(long n) { if (n <= 1) return false; if (n <= 3) return true; if (n % 2 == 0 || n % 3 == 0) return false; double sq=Math.sqrt(n); for (int i = 5; i <= sq; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } public static void printArray(long a[]) { for(int i=0;i<a.length;i++){ out.print(a[i]+" "); } out.println(); } public static void printArray(int a[]) { for(int i=0;i<a.length;i++){ out.print(a[i]+" "); } out.println(); } public static void printArray(char a[]) { for(int i=0;i<a.length;i++){ out.print(a[i]); } out.println(); } public static void printArray(String a[]) { for(int i=0;i<a.length;i++){ out.print(a[i]+" "); } out.println(); } public static void printArray(boolean a[]) { for(int i=0;i<a.length;i++){ out.print(a[i]+" "); } out.println(); } public static void printArray(pair a[]) { for(pair p:a){ out.println(p.a+"->"+p.b); } } public static void printArray(int a[][]) { for(int i=0;i<a.length;i++){ for(int j=0;j<a[i].length;j++){ out.print(a[i][j]+" "); }out.println(); } } public static void printArray(String a[][]) { for(int i=0;i<a.length;i++){ for(int j=0;j<a[i].length;j++){ out.print(a[i][j]+" "); }out.println(); } } public static void printArray(boolean a[][]) { for(int i=0;i<a.length;i++){ for(int j=0;j<a[i].length;j++){ out.print(a[i][j]+" "); }out.println(); } } public static void printArray(long a[][]) { for(int i=0;i<a.length;i++){ for(int j=0;j<a[i].length;j++){ out.print(a[i][j]+" "); }out.println(); } } public static void printArray(char a[][]) { for(int i=0;i<a.length;i++){ for(int j=0;j<a[i].length;j++){ out.print(a[i][j]+" "); }out.println(); } } public static void printArray(ArrayList<?> arr) { for(int i=0;i<arr.size();i++){ out.print(arr.get(i)+" "); } out.println(); } public static void printMapI(HashMap<?,?> hm){ for(Map.Entry<?,?> e:hm.entrySet()){ out.println(e.getKey()+"->"+e.getValue()); }out.println(); } public static void printMap(HashMap<Long,ArrayList<Integer>> hm){ for(Map.Entry<Long,ArrayList<Integer>> e:hm.entrySet()){ out.print(e.getKey()+"->"); ArrayList<Integer> arr=e.getValue(); for(int i=0;i<arr.size();i++){ out.print(arr.get(i)+" "); }out.println(); } } public static void printGraph(ArrayList<Integer> graph[]) { int n=graph.length; for(int i=0;i<n;i++){ out.print(i+"->"); for(int j:graph[i]){ out.print(j+" "); }out.println(); } } //Modular Arithmetic public static long add(long a,long b) { a+=b; if(a>=mod)a-=mod; return a; } public static long sub(long a,long b) { a-=b; if(a<0)a+=mod; return a; } public static long mul(long a,long b) { return ((a%mod)*(b%mod))%mod; } public static long divide(long a,long b,long m) { a=mul(a,modInverse(b,m)); return a; } public static long modInverse(long a,long m) { int x=0,y=0; own p=new own(x,y); long g=gcdExt(a,m,p); if(g!=1){ out.println("inverse does not exists"); return -1; }else{ long res=((p.a%m)+m)%m; return res; } } public static long gcdExt(long a,long b,own p) { if(b==0){ p.a=1; p.b=0; return a; } int x1=0,y1=0; own p1=new own(x1,y1); long gcd=gcdExt(b,a%b,p1); p.b=p1.a - (a/b) * p1.b; p.a=p1.b; return gcd; } public static long pwr(long m,long n) { long res=1; if(m==0) return 0; while(n>0) { if((n&1)!=0) { res=(res*m); } n=n>>1; m=(m*m); } return res; } public static long modpwr(long m,long n) { long res=1; m=m%mod; if(m==0) return 0; while(n>0) { if((n&1)!=0) { res=(res*m)%mod; } n=n>>1; m=(m*m)%mod; } return res; } public static class own { long a; long b; public own(long val,long index) { a=val; b=index; } } //Modular Airthmetic public static void sort(int[] A) { int n = A.length; Random rnd = new Random(); for(int i=0; i<n; ++i) { int tmp = A[i]; int randomPos = i + rnd.nextInt(n-i); A[i] = A[randomPos]; A[randomPos] = tmp; } Arrays.sort(A); } public static void sort(char[] A) { int n = A.length; Random rnd = new Random(); for(int i=0; i<n; ++i) { char tmp = A[i]; int randomPos = i + rnd.nextInt(n-i); A[i] = A[randomPos]; A[randomPos] = tmp; } Arrays.sort(A); } public static void sort(long[] A) { int n = A.length; Random rnd = new Random(); for(int i=0; i<n; ++i) { long tmp = A[i]; int randomPos = i + rnd.nextInt(n-i); A[i] = A[randomPos]; A[randomPos] = tmp; } Arrays.sort(A); } //max,min,sum and sqrt public static int max(int a,int b){return Math.max(a,b);} public static int min(int a,int b){return Math.min(a,b);} public static int max(int a,int b,int c){return Math.max(a,Math.max(b,c));} public static int min(int a,int b,int c){return Math.min(a,Math.min(b,c));} public static long max(long a,long b){return Math.max(a,b);} public static long min(long a,long b){return Math.min(a,b);} public static long max(long a,long b,long c){return Math.max(a,Math.max(b,c));} public static long min(long a,long b,long c){return Math.min(a,Math.min(b,c));} public static int maxinA(int a[]){int n=a.length;int mx=a[0];for(int i=1;i<n;i++){mx=max(mx,a[i]);}return mx;} public static long maxinA(long a[]){int n=a.length;long mx=a[0];for(int i=1;i<n;i++){mx=max(mx,a[i]);}return mx;} public static int mininA(int a[]){int n=a.length;int mn=a[0];for(int i=1;i<n;i++){mn=min(mn,a[i]);}return mn;} public static long mininA(long a[]){int n=a.length;long mn=a[0];for(int i=1;i<n;i++){mn=min(mn,a[i]);}return mn;} public static long suminA(int a[]){int n=a.length;long sum=0;for(int i=0;i<n;i++){sum+=a[i];}return sum;} public static long suminA(long a[]){int n=a.length;long sum=0;for(int i=0;i<n;i++){sum+=a[i];}return sum;} public static int sqrt(int a){int p=(int)Math.sqrt(a);if(p*p>a)p--;return p;} public static long sqrt(long a){long p=(long)Math.sqrt(a);if(p*p>a)p--;return p;} //end public static int[] I(int n)throws IOException{int a[]=new int[n];for(int i=0;i<n;i++){a[i]=I();}return a;} public static long[] IL(int n)throws IOException{long a[]=new long[n];for(int i=0;i<n;i++){a[i]=L();}return a;} public static long[] prefix(int a[]){int n=a.length;long pre[]=new long[n];pre[0]=a[0];for(int i=1;i<n;i++){pre[i]=pre[i-1]+a[i];}return pre;} public static long[] prefix(long a[]){int n=a.length;long pre[]=new long[n];pre[0]=a[0];for(int i=1;i<n;i++){pre[i]=pre[i-1]+a[i];}return pre;} public static int I()throws IOException{return sc.I();} public static long L()throws IOException{return sc.L();} public static String S()throws IOException{return sc.S();} public static double D()throws IOException{return sc.D();} } 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 I(){ return Integer.parseInt(next());} long L(){ return Long.parseLong(next());} double D(){return Double.parseDouble(next());} String S(){ String str = ""; try { str = br.readLine(); } catch (IOException e){ e.printStackTrace(); } return str; } }
Java
["5\n\n3\n\n1 10 100\n\n4\n\n4 8 9 13\n\n5\n\n0 0 0 8 13\n\n6\n\n2 4 8 16 32 64\n\n7\n\n0 0 0 0 0 0 0"]
1 second
["81\n3\n1\n2\n0"]
NoteTo simplify the notes, let $$$\operatorname{sort}(a)$$$ denote the array you get by sorting $$$a$$$ from small to large.In the first test case, $$$a=[1,10,100]$$$ at first. After the first operation, $$$a=\operatorname{sort}([10-1,100-10])=[9,90]$$$. After the second operation, $$$a=\operatorname{sort}([90-9])=[81]$$$.In the second test case, $$$a=[4,8,9,13]$$$ at first. After the first operation, $$$a=\operatorname{sort}([8-4,9-8,13-9])=[1,4,4]$$$. After the second operation, $$$a=\operatorname{sort}([4-1,4-4])=[0,3]$$$. After the last operation, $$$a=\operatorname{sort}([3-0])=[3]$$$.
Java 8
standard input
[ "brute force", "sortings" ]
499b1440d8bb528d089724910e37e226
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1\le t\le 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2\le n\le 10^5$$$) — the length of the array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1,a_2,\dots,a_n$$$ ($$$0\le a_1\le \ldots\le a_n \le 5\cdot 10^5$$$) — the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2.5\cdot 10^5$$$, and the sum of $$$a_n$$$ over all test cases does not exceed $$$5\cdot 10^5$$$.
1,900
For each test case, output the answer on a new line.
standard output
PASSED
2c20808db67ef8cae130f316960dc73a
train_108.jsonl
1657982100
You are given an array $$$a$$$ consisting of $$$n$$$ non-negative integers. It is guaranteed that $$$a$$$ is sorted from small to large.For each operation, we generate a new array $$$b_i=a_{i+1}-a_{i}$$$ for $$$1 \le i &lt; n$$$. Then we sort $$$b$$$ from small to large, replace $$$a$$$ with $$$b$$$, and decrease $$$n$$$ by $$$1$$$.After performing $$$n-1$$$ operations, $$$n$$$ becomes $$$1$$$. You need to output the only integer in array $$$a$$$ (that is to say, you need to output $$$a_1$$$).
256 megabytes
import java.util.*; import java.io.*; // res.append("Case #"+(p+1)+": "+hh+" \n"); ////*************************************************************************** /* public class E_Gardener_and_Tree implements Runnable{ public static void main(String[] args) throws Exception { new Thread(null, new E_Gardener_and_Tree(), "E_Gardener_and_Tree", 1<<28).start(); } public void run(){ WRITE YOUR CODE HERE!!!! JUST WRITE EVERYTHING HERE WHICH YOU WRITE IN MAIN!!! } } */ /////************************************************************************** // public class D_Difference_Array{ public static void main(String[] args) { FastScanner s= new FastScanner(); //PrintWriter out=new PrintWriter(System.out); //end of program //out.println(answer); //out.close(); StringBuilder res = new StringBuilder(); int t=s.nextInt(); int p=0; while(p<t){ int n=s.nextInt(); long array[]= new long[n]; ArrayList<Long> list = new ArrayList<Long>(n+3); long zeroes=0; for(int i=0;i<n;i++){ array[i]=s.nextLong(); if(array[i]>0){ list.add(array[i]); } else{ zeroes++; } } long ans=-1; while(true){ int size=list.size(); if(size==0){ ans=0; break; } if(size==1){ ans=list.get(0); break; } ArrayList<Long> nice = new ArrayList<Long>(size+2); long yo=0; for(int i=0;i<size-1;i++){ long num1=list.get(i); long num2=list.get(i+1); long num3=num2-num1; if(num3>0){ nice.add(num3); } else{ yo++; } } if(zeroes>0){ zeroes--; nice.add(list.get(0)); } Collections.sort(nice); list=nice; zeroes+=yo; // } } res.append(ans+"\n"); p++;} System.out.println(res); } static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(String s) { try { br = new BufferedReader(new FileReader(s)); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String nextToken() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(nextToken()); } long nextLong() { return Long.parseLong(nextToken()); } double nextDouble() { return Double.parseDouble(nextToken()); } } static long modpower(long x, long y, long p) { long res = 1; // Initialize result x = x % p; // Update x if it is more than or // equal to p if (x == 0) return 0; // In case x is divisible by p; while (y > 0) { // If y is odd, multiply x with result if ((y & 1) != 0) res = (res * x) % p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return res; } // SIMPLE POWER FUNCTION=> static long power(long x, long y) { long res = 1; // Initialize result while (y > 0) { // If y is odd, multiply x with result if ((y & 1) != 0) res = res * x; // y must be even now y = y >> 1; // y = y/2 x = x * x; // Change x to x^2 } return res; } }
Java
["5\n\n3\n\n1 10 100\n\n4\n\n4 8 9 13\n\n5\n\n0 0 0 8 13\n\n6\n\n2 4 8 16 32 64\n\n7\n\n0 0 0 0 0 0 0"]
1 second
["81\n3\n1\n2\n0"]
NoteTo simplify the notes, let $$$\operatorname{sort}(a)$$$ denote the array you get by sorting $$$a$$$ from small to large.In the first test case, $$$a=[1,10,100]$$$ at first. After the first operation, $$$a=\operatorname{sort}([10-1,100-10])=[9,90]$$$. After the second operation, $$$a=\operatorname{sort}([90-9])=[81]$$$.In the second test case, $$$a=[4,8,9,13]$$$ at first. After the first operation, $$$a=\operatorname{sort}([8-4,9-8,13-9])=[1,4,4]$$$. After the second operation, $$$a=\operatorname{sort}([4-1,4-4])=[0,3]$$$. After the last operation, $$$a=\operatorname{sort}([3-0])=[3]$$$.
Java 8
standard input
[ "brute force", "sortings" ]
499b1440d8bb528d089724910e37e226
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1\le t\le 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2\le n\le 10^5$$$) — the length of the array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1,a_2,\dots,a_n$$$ ($$$0\le a_1\le \ldots\le a_n \le 5\cdot 10^5$$$) — the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2.5\cdot 10^5$$$, and the sum of $$$a_n$$$ over all test cases does not exceed $$$5\cdot 10^5$$$.
1,900
For each test case, output the answer on a new line.
standard output
PASSED
c89ab8fe56f6ecdafca2c6571ec3e4de
train_108.jsonl
1657982100
You are given an array $$$a$$$ consisting of $$$n$$$ non-negative integers. It is guaranteed that $$$a$$$ is sorted from small to large.For each operation, we generate a new array $$$b_i=a_{i+1}-a_{i}$$$ for $$$1 \le i &lt; n$$$. Then we sort $$$b$$$ from small to large, replace $$$a$$$ with $$$b$$$, and decrease $$$n$$$ by $$$1$$$.After performing $$$n-1$$$ operations, $$$n$$$ becomes $$$1$$$. You need to output the only integer in array $$$a$$$ (that is to say, you need to output $$$a_1$$$).
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class Main { public static void main(String[] args) throws IOException { Scanner in = new Scanner(System.in); StringBuffer out = new StringBuffer(); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int T = in.nextInt(); // int T = 1; String[] input; LABEL: while(T--!=0) { int n = in.nextInt(); TreeMap<Integer, Integer> map = new TreeMap<>(); for(int i=0; i<n; i++) { int item = in.nextInt(); map.put(item, map.getOrDefault(item, 0) + 1); } if(map.lastKey() == 0) { out.append(0).append("\n"); continue; } int nonZero, prev; do { nonZero = 0; prev = -1; TreeMap<Integer, Integer> temp = new TreeMap<>(); for(Map.Entry<Integer, Integer> entry: map.entrySet()) { int key = entry.getKey(); int value = entry.getValue(); if(value > 1) { temp.put(0, temp.getOrDefault(0, 0) + (value-1)); } if(prev!=-1) { int diff = key - prev; temp.put(diff, temp.getOrDefault(diff, 0) + 1); nonZero += 1; } prev = key; } // System.out.println(Arrays.toString(cnt) +" "+newMax); map = temp; } while (nonZero > 1); if (nonZero == 0) { out.append(0).append("\n"); } else { out.append(map.lastKey()).append("\n"); } } System.out.print(out); } private static long lcm(long a, long b) { return a * (b/gcd(a, b)); } private static long gcd(long a, long b) { if(a==0) { return b; } return gcd(b%a, a); } private static int toInt(String num) { return Integer.parseInt(num); } private static long toLong(String num) { return Long.parseLong(num); } }
Java
["5\n\n3\n\n1 10 100\n\n4\n\n4 8 9 13\n\n5\n\n0 0 0 8 13\n\n6\n\n2 4 8 16 32 64\n\n7\n\n0 0 0 0 0 0 0"]
1 second
["81\n3\n1\n2\n0"]
NoteTo simplify the notes, let $$$\operatorname{sort}(a)$$$ denote the array you get by sorting $$$a$$$ from small to large.In the first test case, $$$a=[1,10,100]$$$ at first. After the first operation, $$$a=\operatorname{sort}([10-1,100-10])=[9,90]$$$. After the second operation, $$$a=\operatorname{sort}([90-9])=[81]$$$.In the second test case, $$$a=[4,8,9,13]$$$ at first. After the first operation, $$$a=\operatorname{sort}([8-4,9-8,13-9])=[1,4,4]$$$. After the second operation, $$$a=\operatorname{sort}([4-1,4-4])=[0,3]$$$. After the last operation, $$$a=\operatorname{sort}([3-0])=[3]$$$.
Java 8
standard input
[ "brute force", "sortings" ]
499b1440d8bb528d089724910e37e226
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1\le t\le 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2\le n\le 10^5$$$) — the length of the array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1,a_2,\dots,a_n$$$ ($$$0\le a_1\le \ldots\le a_n \le 5\cdot 10^5$$$) — the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2.5\cdot 10^5$$$, and the sum of $$$a_n$$$ over all test cases does not exceed $$$5\cdot 10^5$$$.
1,900
For each test case, output the answer on a new line.
standard output
PASSED
54b93e1361ecabc16f3fa2b38627932a
train_108.jsonl
1657982100
You are given an array $$$a$$$ consisting of $$$n$$$ non-negative integers. It is guaranteed that $$$a$$$ is sorted from small to large.For each operation, we generate a new array $$$b_i=a_{i+1}-a_{i}$$$ for $$$1 \le i &lt; n$$$. Then we sort $$$b$$$ from small to large, replace $$$a$$$ with $$$b$$$, and decrease $$$n$$$ by $$$1$$$.After performing $$$n-1$$$ operations, $$$n$$$ becomes $$$1$$$. You need to output the only integer in array $$$a$$$ (that is to say, you need to output $$$a_1$$$).
256 megabytes
//package d; import java.util.*; import java.io.*; public class D { public static void main(String[] args) throws IOException{ BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw=new PrintWriter(System.out); int cases=Integer.parseInt(br.readLine()); for(int d=0;d<cases;d++){ int n=Integer.parseInt(br.readLine()); StringTokenizer st=new StringTokenizer(br.readLine()); int[] arr=new int[n]; for(int i=0;i<n;i++){ arr[i]=Integer.parseInt(st.nextToken()); } PriorityQueue<Integer> pq=new PriorityQueue<>(); int zero=0; for(int i=1;i<n;i++){ if(arr[i]-arr[i-1]!=0){ pq.add(arr[i]-arr[i-1]); }else{ zero++; } } while(pq.size()>1){ PriorityQueue<Integer> two=new PriorityQueue<>(); int size=pq.size(); if(zero>0){ two.add(pq.peek()); zero--; } for(int i=1;i<size;i++){ int a=pq.remove(); if(pq.peek()-a==0){ zero++; }else{ two.add(pq.peek()-a); } } pq=two; if(pq.size()==0&&zero>0){ pq.add(0); break; } } if(pq.isEmpty()){ pq.add(0); } pw.println(pq.peek()); } pw.close(); } }
Java
["5\n\n3\n\n1 10 100\n\n4\n\n4 8 9 13\n\n5\n\n0 0 0 8 13\n\n6\n\n2 4 8 16 32 64\n\n7\n\n0 0 0 0 0 0 0"]
1 second
["81\n3\n1\n2\n0"]
NoteTo simplify the notes, let $$$\operatorname{sort}(a)$$$ denote the array you get by sorting $$$a$$$ from small to large.In the first test case, $$$a=[1,10,100]$$$ at first. After the first operation, $$$a=\operatorname{sort}([10-1,100-10])=[9,90]$$$. After the second operation, $$$a=\operatorname{sort}([90-9])=[81]$$$.In the second test case, $$$a=[4,8,9,13]$$$ at first. After the first operation, $$$a=\operatorname{sort}([8-4,9-8,13-9])=[1,4,4]$$$. After the second operation, $$$a=\operatorname{sort}([4-1,4-4])=[0,3]$$$. After the last operation, $$$a=\operatorname{sort}([3-0])=[3]$$$.
Java 8
standard input
[ "brute force", "sortings" ]
499b1440d8bb528d089724910e37e226
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1\le t\le 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2\le n\le 10^5$$$) — the length of the array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1,a_2,\dots,a_n$$$ ($$$0\le a_1\le \ldots\le a_n \le 5\cdot 10^5$$$) — the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2.5\cdot 10^5$$$, and the sum of $$$a_n$$$ over all test cases does not exceed $$$5\cdot 10^5$$$.
1,900
For each test case, output the answer on a new line.
standard output
PASSED
ade4331e9d348b6fb3022589d21f1507
train_108.jsonl
1657982100
You are given an array $$$a$$$ consisting of $$$n$$$ non-negative integers. It is guaranteed that $$$a$$$ is sorted from small to large.For each operation, we generate a new array $$$b_i=a_{i+1}-a_{i}$$$ for $$$1 \le i &lt; n$$$. Then we sort $$$b$$$ from small to large, replace $$$a$$$ with $$$b$$$, and decrease $$$n$$$ by $$$1$$$.After performing $$$n-1$$$ operations, $$$n$$$ becomes $$$1$$$. You need to output the only integer in array $$$a$$$ (that is to say, you need to output $$$a_1$$$).
256 megabytes
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.security.KeyStore.Entry; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.PriorityQueue; import java.util.Queue; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.TreeSet; public class D { static ArrayList<Integer>adj[]; static int[]vis; static ArrayList<String>[]arr; static HashMap<String, Integer>dp; static HashSet<String>dat; static int c,n; public static void main(String[]args) throws IOException { // Scanner sc=new Scanner("files.in"); Scanner sc=new Scanner(System.in); PrintWriter out=new PrintWriter(System.out); int t=sc.nextInt(); while(t-->0) { int n=sc.nextInt(); TreeMap<Integer,Integer>tr=new TreeMap<Integer,Integer>(); // int[]a=new int[n]; for(int i=0;i<n;i++) { int x=sc.nextInt(); tr.put(x,tr.getOrDefault(x, 0)+1); } while(tr.size()>2) { TreeMap<Integer,Integer>tr2=new TreeMap<Integer,Integer>(); while(tr.size()>1) { int lst = tr.lastKey(); int x=tr.remove(lst); int nw=lst-tr.lastKey(); tr2.put(nw,tr2.getOrDefault(nw, 0)+1); if(x>1) tr2.put(0, tr2.getOrDefault(0, 0)+x-1); } int lst=tr.lastKey(); int x=tr.remove(lst); if(x>1) tr2.put(0, tr2.getOrDefault(0, 0)+x-1); // tr.clear(); tr.putAll(tr2); } int x=tr.lastKey();int v =tr.remove(x); if(tr.size()==1) {//2 elems out.println(x-tr.lastKey()); }else { out.println(v==1?x:0); } } out.close(); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));} public Scanner(String s) throws IOException{ br=new BufferedReader(new FileReader(new File(s))); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public boolean hasNext() {return st.hasMoreTokens();} public int nextInt() throws IOException {return Integer.parseInt(next());} public double nextDouble() throws IOException {return Double.parseDouble(next());} public long nextLong() throws IOException {return Long.parseLong(next());} public String nextLine() throws IOException {return br.readLine();} public boolean ready() throws IOException {return br.ready(); } } }
Java
["5\n\n3\n\n1 10 100\n\n4\n\n4 8 9 13\n\n5\n\n0 0 0 8 13\n\n6\n\n2 4 8 16 32 64\n\n7\n\n0 0 0 0 0 0 0"]
1 second
["81\n3\n1\n2\n0"]
NoteTo simplify the notes, let $$$\operatorname{sort}(a)$$$ denote the array you get by sorting $$$a$$$ from small to large.In the first test case, $$$a=[1,10,100]$$$ at first. After the first operation, $$$a=\operatorname{sort}([10-1,100-10])=[9,90]$$$. After the second operation, $$$a=\operatorname{sort}([90-9])=[81]$$$.In the second test case, $$$a=[4,8,9,13]$$$ at first. After the first operation, $$$a=\operatorname{sort}([8-4,9-8,13-9])=[1,4,4]$$$. After the second operation, $$$a=\operatorname{sort}([4-1,4-4])=[0,3]$$$. After the last operation, $$$a=\operatorname{sort}([3-0])=[3]$$$.
Java 8
standard input
[ "brute force", "sortings" ]
499b1440d8bb528d089724910e37e226
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1\le t\le 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2\le n\le 10^5$$$) — the length of the array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1,a_2,\dots,a_n$$$ ($$$0\le a_1\le \ldots\le a_n \le 5\cdot 10^5$$$) — the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2.5\cdot 10^5$$$, and the sum of $$$a_n$$$ over all test cases does not exceed $$$5\cdot 10^5$$$.
1,900
For each test case, output the answer on a new line.
standard output
PASSED
3d0595f036d985bd473716244aa17753
train_108.jsonl
1657982100
You are given an array $$$a$$$ consisting of $$$n$$$ non-negative integers. It is guaranteed that $$$a$$$ is sorted from small to large.For each operation, we generate a new array $$$b_i=a_{i+1}-a_{i}$$$ for $$$1 \le i &lt; n$$$. Then we sort $$$b$$$ from small to large, replace $$$a$$$ with $$$b$$$, and decrease $$$n$$$ by $$$1$$$.After performing $$$n-1$$$ operations, $$$n$$$ becomes $$$1$$$. You need to output the only integer in array $$$a$$$ (that is to say, you need to output $$$a_1$$$).
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.StringTokenizer; import java.util.stream.Collectors; public class D { static final long mod = (long) 1e9 + 7l; private static void solve(int t){ int n = fs.nextInt(); int zero =0; List<Integer> ls = new ArrayList<>(); for (int i = 0; i <n; i++) { int val = fs.nextInt(); if(val==0)zero++; else ls.add(val); } Collections.sort(ls); while(ls.size()>1) { List<Integer> ls2 = new ArrayList<>(); if(zero>0){ ls2.add(ls.get(0)); zero--; } for(int j =0; j<ls.size()-1; j++){ int val = ls.get(j+1)-ls.get(j); if(val==0)zero++; else ls2.add(val); } Collections.sort(ls2); ls = ls2; } if(ls.size()==1)out.println(ls.get(0)); else out.println(0); } private static int[] sortByCollections(int[] arr) { ArrayList<Integer> ls = new ArrayList<>(arr.length); for (int i = 0; i < arr.length; i++) { ls.add(arr[i]); } Collections.sort(ls); for (int i = 0; i < arr.length; i++) { arr[i] = ls.get(i); } return arr; } public static void main(String[] args) { fs = new FastScanner(); out = new PrintWriter(System.out); long s = System.currentTimeMillis(); int t = fs.nextInt(); for (int i = 1; i <= t; i++) solve(t); out.close(); // System.err.println( System.currentTimeMillis() - s + "ms" ); } static boolean DEBUG = true; static PrintWriter out; static FastScanner fs; static void trace(Object... o) { if (!DEBUG) return; System.err.println(Arrays.deepToString(o)); } static void pl(Object o) { out.println(o); } static void p(Object o) { out.print(o); } static long gcd(long a, long b) { return (b == 0) ? a : gcd(b, a % b); } static int gcd(int a, int b) { return (b == 0) ? a : gcd(b, a % b); } static void sieveOfEratosthenes(int n, int factors[]) { factors[1] = 1; for (int p = 2; p * p <= n; p++) { if (factors[p] == 0) { factors[p] = p; for (int i = p * p; i <= n; i += p) factors[i] = p; } } } static long mul(long a, long b) { return a * b % mod; } static long fact(int x) { long ans = 1; for (int i = 2; i <= x; i++) ans = mul(ans, i); return ans; } static long fastPow(long base, long exp) { if (exp == 0) return 1; long half = fastPow(base, exp / 2); if (exp % 2 == 0) return mul(half, half); return mul(half, mul(half, base)); } static long modInv(long x) { return fastPow(x, mod - 2); } static long nCk(int n, int k) { return mul(fact(n), mul(modInv(fact(k)), modInv(fact(n - k)))); } static class FastScanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); public String next() { while (!st.hasMoreElements()) try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } long nextLong() { return Long.parseLong(next()); } } static class _Scanner { InputStream is; _Scanner(InputStream is) { this.is = is; } byte[] bb = new byte[1 << 15]; int k, l; byte getc() throws IOException { if (k >= l) { k = 0; l = is.read(bb); if (l < 0) return -1; } return bb[k++]; } byte skip() throws IOException { byte b; while ((b = getc()) <= 32) ; return b; } int nextInt() throws IOException { int n = 0; for (byte b = skip(); b > 32; b = getc()) n = n * 10 + b - '0'; return n; } } }
Java
["5\n\n3\n\n1 10 100\n\n4\n\n4 8 9 13\n\n5\n\n0 0 0 8 13\n\n6\n\n2 4 8 16 32 64\n\n7\n\n0 0 0 0 0 0 0"]
1 second
["81\n3\n1\n2\n0"]
NoteTo simplify the notes, let $$$\operatorname{sort}(a)$$$ denote the array you get by sorting $$$a$$$ from small to large.In the first test case, $$$a=[1,10,100]$$$ at first. After the first operation, $$$a=\operatorname{sort}([10-1,100-10])=[9,90]$$$. After the second operation, $$$a=\operatorname{sort}([90-9])=[81]$$$.In the second test case, $$$a=[4,8,9,13]$$$ at first. After the first operation, $$$a=\operatorname{sort}([8-4,9-8,13-9])=[1,4,4]$$$. After the second operation, $$$a=\operatorname{sort}([4-1,4-4])=[0,3]$$$. After the last operation, $$$a=\operatorname{sort}([3-0])=[3]$$$.
Java 8
standard input
[ "brute force", "sortings" ]
499b1440d8bb528d089724910e37e226
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1\le t\le 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2\le n\le 10^5$$$) — the length of the array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1,a_2,\dots,a_n$$$ ($$$0\le a_1\le \ldots\le a_n \le 5\cdot 10^5$$$) — the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2.5\cdot 10^5$$$, and the sum of $$$a_n$$$ over all test cases does not exceed $$$5\cdot 10^5$$$.
1,900
For each test case, output the answer on a new line.
standard output
PASSED
fc1df46eed0f9fdb06d46cecb40cac28
train_108.jsonl
1657982100
You are given an array $$$a$$$ consisting of $$$n$$$ non-negative integers. It is guaranteed that $$$a$$$ is sorted from small to large.For each operation, we generate a new array $$$b_i=a_{i+1}-a_{i}$$$ for $$$1 \le i &lt; n$$$. Then we sort $$$b$$$ from small to large, replace $$$a$$$ with $$$b$$$, and decrease $$$n$$$ by $$$1$$$.After performing $$$n-1$$$ operations, $$$n$$$ becomes $$$1$$$. You need to output the only integer in array $$$a$$$ (that is to say, you need to output $$$a_1$$$).
256 megabytes
/* || श्री राम समर्थ || || जय जय रघुवीर समर्थ || */ import java.io.IOException; import java.io.InputStream; import java.io.PrintStream; import java.io.PrintWriter; import java.util.*; import static java.util.Arrays.sort; /* Think until you get Good idea And then Code Easily Try Hard And Pay Attention to details (be positive always possible) think smart */ public class CodeforcesTemp { static Reader scan = new Reader(); static FastPrinter out = new FastPrinter(); public static void main(String[] args) throws IOException { int tt = scan.nextInt(); // int tt = 1; for (int tc = 1; tc <= tt; tc++) { int n= scan.nextInt(); int[] arr= scan.nextIntArray(n); List<Integer> li=new ArrayList<>(); for (int i = 0; i < n; i++) { li.add(arr[i]); } int ans=0; int zero_cnt=0; while (true){ if(li.size()==1){ ans=li.get(0); break; } if(li.size()==0){ans=0;break;} Collections.sort(li); List<Integer> newli=new ArrayList<>(); if(zero_cnt>0){ newli.add(li.get(0)); zero_cnt--; } for (int i = 1; i < li.size(); i++) { int res=li.get(i)-li.get(i-1); if(res==0)++zero_cnt; if(res!=0){ newli.add(res); } } li=newli; } out.println(ans); out.flush(); } out.close(); } static class Reader { private final InputStream in; private final byte[] buffer = new byte[1024]; private int ptr = 0; private int buflen = 0; private static final long LONG_MAX_TENTHS = 922337203685477580L; private static final int LONG_MAX_LAST_DIGIT = 7; private static final int LONG_MIN_LAST_DIGIT = 8; public Reader(InputStream in) { this.in = in; } public Reader() { this(System.in); } private boolean hasNextByte() { if (ptr < buflen) { return true; } else { ptr = 0; try { buflen = in.read(buffer); } catch (IOException e) { e.printStackTrace(); } if (buflen <= 0) { return false; } } return true; } private int readByte() { if (hasNextByte()) return buffer[ptr++]; else return -1; } private static boolean isPrintableChar(int c) { return 33 <= c && c <= 126; } public boolean hasNext() { while (hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++; return hasNextByte(); } public String next() { if (!hasNext()) throw new NoSuchElementException(); StringBuilder sb = new StringBuilder(); int b = readByte(); while (isPrintableChar(b)) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } public long nextLong() { if (!hasNext()) throw new NoSuchElementException(); long n = 0; boolean minus = false; int b = readByte(); if (b == '-') { minus = true; b = readByte(); } if (b < '0' || '9' < b) { throw new NumberFormatException(); } while (true) { if ('0' <= b && b <= '9') { int digit = b - '0'; if (n >= LONG_MAX_TENTHS) { if (n == LONG_MAX_TENTHS) { if (minus) { if (digit <= LONG_MIN_LAST_DIGIT) { n = -n * 10 - digit; b = readByte(); if (!isPrintableChar(b)) { return n; } else if (b < '0' || '9' < b) { throw new NumberFormatException( String.format("not number")); } } } else { if (digit <= LONG_MAX_LAST_DIGIT) { n = n * 10 + digit; b = readByte(); if (!isPrintableChar(b)) { return n; } else if (b < '0' || '9' < b) { throw new NumberFormatException( String.format("not number")); } } } } throw new ArithmeticException( String.format(" overflows long.")); } n = n * 10 + digit; } else if (b == -1 || !isPrintableChar(b)) { return minus ? -n : n; } else { throw new NumberFormatException(); } b = readByte(); } } public int nextInt() { long nl = nextLong(); if (nl < Integer.MIN_VALUE || nl > Integer.MAX_VALUE) throw new NumberFormatException(); return (int) nl; } public double nextDouble() { return Double.parseDouble(next()); } public long[] nextLongArray(long length) { long[] array = new long[(int) length]; for (int i = 0; i < length; i++) array[i] = this.nextLong(); return array; } public long[] nextLongArray(int length, java.util.function.LongUnaryOperator map) { long[] array = new long[length]; for (int i = 0; i < length; i++) array[i] = map.applyAsLong(this.nextLong()); return array; } public int[] nextIntArray(int length) { int[] array = new int[length]; for (int i = 0; i < length; i++) array[i] = this.nextInt(); return array; } public int[][] nextIntArrayMulti(int length, int width) { int[][] arrays = new int[width][length]; for (int i = 0; i < length; i++) { for (int j = 0; j < width; j++) arrays[j][i] = this.nextInt(); } return arrays; } public int[] nextIntArray(int length, java.util.function.IntUnaryOperator map) { int[] array = new int[length]; for (int i = 0; i < length; i++) array[i] = map.applyAsInt(this.nextInt()); return array; } public double[] nextDoubleArray(int length) { double[] array = new double[length]; for (int i = 0; i < length; i++) array[i] = this.nextDouble(); return array; } public double[] nextDoubleArray(int length, java.util.function.DoubleUnaryOperator map) { double[] array = new double[length]; for (int i = 0; i < length; i++) array[i] = map.applyAsDouble(this.nextDouble()); return array; } public long[][] nextLongMatrix(int height, int width) { long[][] mat = new long[height][width]; for (int h = 0; h < height; h++) for (int w = 0; w < width; w++) { mat[h][w] = this.nextLong(); } return mat; } public int[][] nextIntMatrix(int height, int width) { int[][] mat = new int[height][width]; for (int h = 0; h < height; h++) for (int w = 0; w < width; w++) { mat[h][w] = this.nextInt(); } return mat; } public double[][] nextDoubleMatrix(int height, int width) { double[][] mat = new double[height][width]; for (int h = 0; h < height; h++) for (int w = 0; w < width; w++) { mat[h][w] = this.nextDouble(); } return mat; } public char[][] nextCharMatrix(int height, int width) { char[][] mat = new char[height][width]; for (int h = 0; h < height; h++) { String s = this.next(); for (int w = 0; w < width; w++) { mat[h][w] = s.charAt(w); } } return mat; } } static class FastPrinter extends PrintWriter { public FastPrinter(PrintStream stream) { super(stream); } public FastPrinter() { super(System.out); } private static String dtos(double x, int n) { StringBuilder sb = new StringBuilder(); if (x < 0) { sb.append('-'); x = -x; } x += Math.pow(10, -n) / 2; sb.append((long) x); sb.append("."); x -= (long) x; for (int i = 0; i < n; i++) { x *= 10; sb.append((int) x); x -= (int) x; } return sb.toString(); } @Override public void print(float f) { super.print(dtos(f, 20)); } @Override public void println(float f) { super.println(dtos(f, 20)); } @Override public void print(double d) { super.print(dtos(d, 20)); } @Override public void println(double d) { super.println(dtos(d, 20)); } public void printArray(int[] array, String separator) { int n = array.length; for (int i = 0; i < n - 1; i++) { super.print(array[i]); super.print(separator); } super.println(array[n - 1]); } public void printArray(int[] array) { this.printArray(array, " "); } public void printArray(int[] array, String separator, java.util.function.IntUnaryOperator map) { int n = array.length; for (int i = 0; i < n - 1; i++) { super.print(map.applyAsInt(array[i])); super.print(separator); } super.println(map.applyAsInt(array[n - 1])); } public void printArray(int[] array, java.util.function.IntUnaryOperator map) { this.printArray(array, " ", map); } public void printArray(long[] array, String separator) { int n = array.length; for (int i = 0; i < n - 1; i++) { super.print(array[i]); super.print(separator); } super.println(array[n - 1]); } public void printArray(long[] array) { this.printArray(array, " "); } public void printArray(long[] array, String separator, java.util.function.LongUnaryOperator map) { int n = array.length; for (int i = 0; i < n - 1; i++) { super.print(map.applyAsLong(array[i])); super.print(separator); } super.println(map.applyAsLong(array[n - 1])); } public void printArray(long[] array, java.util.function.LongUnaryOperator map) { this.printArray(array, " ", map); } public void printMatrix(int[][] arr) { for (int i = 0; i < arr.length; i++) { this.printArray(arr[i]); } } public void printCharMatrix(char[][] arr, int n, int m) { for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { this.print(arr[i][j] + " "); } this.println(); } } } static Random __r = new Random(); static int randInt(int min, int max) { return __r.nextInt(max - min + 1) + min; } static void reverse(int[] a) { for (int i = 0, n = a.length, half = n / 2; i < half; ++i) { int swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap; } } static void reverse(long[] a) { for (int i = 0, n = a.length, half = n / 2; i < half; ++i) { long swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap; } } static void reverse(double[] a) { for (int i = 0, n = a.length, half = n / 2; i < half; ++i) { double swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap; } } static void reverse(char[] a) { for (int i = 0, n = a.length, half = n / 2; i < half; ++i) { char swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap; } } static void reverse(char[] arr, int i, int j) { while (i < j) { char temp = arr[j]; arr[j] = arr[i]; arr[i] = temp; i++; j--; } } static void reverse(int[] arr, int i, int j) { while (i < j) { int temp = arr[j]; arr[j] = arr[i]; arr[i] = temp; i++; j--; } } static void reverse(long[] arr, int i, int j) { while (i < j) { long temp = arr[j]; arr[j] = arr[i]; arr[i] = temp; i++; j--; } } static void shuffle(int[] a) { int n = a.length - 1; for (int i = 0; i < n; ++i) { int ind = randInt(i, n); int swap = a[i]; a[i] = a[ind]; a[ind] = swap; } } static void shuffle(long[] a) { int n = a.length - 1; for (int i = 0; i < n; ++i) { int ind = randInt(i, n); long swap = a[i]; a[i] = a[ind]; a[ind] = swap; } } static void shuffle(double[] a) { int n = a.length - 1; for (int i = 0; i < n; ++i) { int ind = randInt(i, n); double swap = a[i]; a[i] = a[ind]; a[ind] = swap; } } static void rsort(int[] a) { shuffle(a); sort(a); } static void rsort(long[] a) { shuffle(a); sort(a); } static void rsort(double[] a) { shuffle(a); sort(a); } static int[] copy(int[] a) { int[] ans = new int[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans; } static long[] copy(long[] a) { long[] ans = new long[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans; } static double[] copy(double[] a) { double[] ans = new double[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans; } static char[] copy(char[] a) { char[] ans = new char[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans; } }
Java
["5\n\n3\n\n1 10 100\n\n4\n\n4 8 9 13\n\n5\n\n0 0 0 8 13\n\n6\n\n2 4 8 16 32 64\n\n7\n\n0 0 0 0 0 0 0"]
1 second
["81\n3\n1\n2\n0"]
NoteTo simplify the notes, let $$$\operatorname{sort}(a)$$$ denote the array you get by sorting $$$a$$$ from small to large.In the first test case, $$$a=[1,10,100]$$$ at first. After the first operation, $$$a=\operatorname{sort}([10-1,100-10])=[9,90]$$$. After the second operation, $$$a=\operatorname{sort}([90-9])=[81]$$$.In the second test case, $$$a=[4,8,9,13]$$$ at first. After the first operation, $$$a=\operatorname{sort}([8-4,9-8,13-9])=[1,4,4]$$$. After the second operation, $$$a=\operatorname{sort}([4-1,4-4])=[0,3]$$$. After the last operation, $$$a=\operatorname{sort}([3-0])=[3]$$$.
Java 8
standard input
[ "brute force", "sortings" ]
499b1440d8bb528d089724910e37e226
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1\le t\le 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2\le n\le 10^5$$$) — the length of the array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1,a_2,\dots,a_n$$$ ($$$0\le a_1\le \ldots\le a_n \le 5\cdot 10^5$$$) — the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2.5\cdot 10^5$$$, and the sum of $$$a_n$$$ over all test cases does not exceed $$$5\cdot 10^5$$$.
1,900
For each test case, output the answer on a new line.
standard output
PASSED
0e457c5937cfc1e1cc8f08fe92753920
train_108.jsonl
1657982100
You are given an array $$$a$$$ consisting of $$$n$$$ non-negative integers. It is guaranteed that $$$a$$$ is sorted from small to large.For each operation, we generate a new array $$$b_i=a_{i+1}-a_{i}$$$ for $$$1 \le i &lt; n$$$. Then we sort $$$b$$$ from small to large, replace $$$a$$$ with $$$b$$$, and decrease $$$n$$$ by $$$1$$$.After performing $$$n-1$$$ operations, $$$n$$$ becomes $$$1$$$. You need to output the only integer in array $$$a$$$ (that is to say, you need to output $$$a_1$$$).
256 megabytes
import java.util.*; import java.io.*; public class Main { static long startTime = System.currentTimeMillis(); // for global initializations and methods starts here // global initialisations and methods end here static void run() { boolean tc = true; AdityaFastIO r = new AdityaFastIO(); //FastReader r = new FastReader(); try (OutputStream out = new BufferedOutputStream(System.out)) { //long startTime = System.currentTimeMillis(); int testcases = tc ? r.ni() : 1; int tcCounter = 1; // Hold Here Sparky------------------->>> // Solution Starts Here start: while (testcases-- > 0) { int n = r.ni(); List<Integer> al = readIntList(n, r); for (int i = 0; i < n; i++) { int pos = n; for (int j = n - 1; j > i; j--) { if (al.get(j) == 0) { pos = j; break; } al.set(j, al.get(j) - al.get(j - 1)); pos = i + 1; } if (pos == i) pos++; Collections.sort(al.subList(pos, n)); } out.write((al.get(n - 1) + " ").getBytes()); out.write(("\n").getBytes()); } // Solution Ends Here } catch (IOException e) { e.printStackTrace(); } } static class AdityaFastIO { final private int BUFFER_SIZE = 1 << 16; private final DataInputStream din; private final byte[] buffer; private int bufferPointer, bytesRead; public BufferedReader br; public StringTokenizer st; public AdityaFastIO() { br = new BufferedReader(new InputStreamReader(System.in)); din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public AdityaFastIO(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String word() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public String line() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } public String readLine() throws IOException { byte[] buf = new byte[100000001]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int ni() 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 nl() 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 nd() 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(); } } public static void main(String[] args) throws Exception { run(); } static int[] readIntArr(int n, AdityaFastIO r) throws IOException { int[] arr = new int[n]; for (int i = 0; i < n; i++) arr[i] = r.ni(); return arr; } static long[] readLongArr(int n, AdityaFastIO r) throws IOException { long[] arr = new long[n]; for (int i = 0; i < n; i++) arr[i] = r.nl(); return arr; } static List<Integer> readIntList(int n, AdityaFastIO r) throws IOException { List<Integer> al = new ArrayList<>(); for (int i = 0; i < n; i++) al.add(r.ni()); return al; } static List<Long> readLongList(int n, AdityaFastIO r) throws IOException { List<Long> al = new ArrayList<>(); for (int i = 0; i < n; i++) al.add(r.nl()); return al; } static long mod = 998244353; static long modInv(long base, long e) { long result = 1; base %= mod; while (e > 0) { if ((e & 1) > 0) result = result * base % mod; base = base * base % mod; e >>= 1; } return result; } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String word() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } String line() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } int ni() { return Integer.parseInt(word()); } long nl() { return Long.parseLong(word()); } double nd() { return Double.parseDouble(word()); } } static int MOD = (int) (1e9 + 7); static long powerLL(long x, long n) { long result = 1; while (n > 0) { if (n % 2 == 1) result = result * x % MOD; n = n / 2; x = x * x % MOD; } return result; } static long powerStrings(int i1, int i2) { String sa = String.valueOf(i1); String sb = String.valueOf(i2); long a = 0, b = 0; for (int i = 0; i < sa.length(); i++) a = (a * 10 + (sa.charAt(i) - '0')) % MOD; for (int i = 0; i < sb.length(); i++) b = (b * 10 + (sb.charAt(i) - '0')) % (MOD - 1); return powerLL(a, b); } static long gcd(long a, long b) { if (a == 0) return b; else return gcd(b % a, a); } static long lcm(long a, long b) { return (a * b) / gcd(a, b); } static long lower_bound(int[] arr, int x) { int l = -1, r = arr.length; while (l + 1 < r) { int m = (l + r) >>> 1; if (arr[m] >= x) r = m; else l = m; } return r; } static int upper_bound(int[] arr, int x) { int l = -1, r = arr.length; while (l + 1 < r) { int m = (l + r) >>> 1; if (arr[m] <= x) l = m; else r = m; } return l + 1; } static void addEdge(ArrayList<ArrayList<Integer>> graph, int edge1, int edge2) { graph.get(edge1).add(edge2); graph.get(edge2).add(edge1); } public static class Pair implements Comparable<Pair> { int first; int second; public Pair(int first, int second) { this.first = first; this.second = second; } public String toString() { return "(" + first + "," + second + ")"; } public int compareTo(Pair o) { // TODO Auto-generated method stub if (this.first != o.first) return (int) (this.first - o.first); else return (int) (this.second - o.second); } @Override public int hashCode() { int hash = 5; hash = 17 * hash + this.first; return hash; } @Override public boolean equals(Object obj) { if (obj == null) return false; if (getClass() != obj.getClass()) return false; final Pair other = (Pair) obj; return this.first == other.first; } } public static class PairC<X, Y> implements Comparable<PairC> { X first; Y second; public PairC(X first, Y second) { this.first = first; this.second = second; } public String toString() { return "(" + first + "," + second + ")"; } public int compareTo(PairC o) { // TODO Auto-generated method stub return o.compareTo((PairC) first); } } static boolean isCollectionsSorted(List<Long> list) { if (list.size() == 0 || list.size() == 1) return true; for (int i = 1; i < list.size(); i++) if (list.get(i) <= list.get(i - 1)) return false; return true; } static boolean isCollectionsSortedReverseOrder(List<Long> list) { if (list.size() == 0 || list.size() == 1) return true; for (int i = 1; i < list.size(); i++) if (list.get(i) >= list.get(i - 1)) return false; return true; } }
Java
["5\n\n3\n\n1 10 100\n\n4\n\n4 8 9 13\n\n5\n\n0 0 0 8 13\n\n6\n\n2 4 8 16 32 64\n\n7\n\n0 0 0 0 0 0 0"]
1 second
["81\n3\n1\n2\n0"]
NoteTo simplify the notes, let $$$\operatorname{sort}(a)$$$ denote the array you get by sorting $$$a$$$ from small to large.In the first test case, $$$a=[1,10,100]$$$ at first. After the first operation, $$$a=\operatorname{sort}([10-1,100-10])=[9,90]$$$. After the second operation, $$$a=\operatorname{sort}([90-9])=[81]$$$.In the second test case, $$$a=[4,8,9,13]$$$ at first. After the first operation, $$$a=\operatorname{sort}([8-4,9-8,13-9])=[1,4,4]$$$. After the second operation, $$$a=\operatorname{sort}([4-1,4-4])=[0,3]$$$. After the last operation, $$$a=\operatorname{sort}([3-0])=[3]$$$.
Java 8
standard input
[ "brute force", "sortings" ]
499b1440d8bb528d089724910e37e226
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1\le t\le 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2\le n\le 10^5$$$) — the length of the array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1,a_2,\dots,a_n$$$ ($$$0\le a_1\le \ldots\le a_n \le 5\cdot 10^5$$$) — the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2.5\cdot 10^5$$$, and the sum of $$$a_n$$$ over all test cases does not exceed $$$5\cdot 10^5$$$.
1,900
For each test case, output the answer on a new line.
standard output
PASSED
e1093f72621c6759df5e809f06077d7a
train_108.jsonl
1657982100
You are given an array $$$a$$$ consisting of $$$n$$$ non-negative integers. It is guaranteed that $$$a$$$ is sorted from small to large.For each operation, we generate a new array $$$b_i=a_{i+1}-a_{i}$$$ for $$$1 \le i &lt; n$$$. Then we sort $$$b$$$ from small to large, replace $$$a$$$ with $$$b$$$, and decrease $$$n$$$ by $$$1$$$.After performing $$$n-1$$$ operations, $$$n$$$ becomes $$$1$$$. You need to output the only integer in array $$$a$$$ (that is to say, you need to output $$$a_1$$$).
256 megabytes
import java.util.Arrays; import java.util.Scanner; import java.util.TreeSet; public class D1708 { public static void main(String[] args){ Scanner scan = new Scanner(System.in); int tests = scan.nextInt(); for(int t = 0; t < tests; t ++){ int n = scan.nextInt(); // TreeSet<Integer> a = new TreeSet<>(); int[] a = new int[n+1]; for(int i =1; i <= n; i++){ a[i] = scan.nextInt(); } int pos = 0; for(int i = 0 ; i < n-1; i++){ for(;pos <= n && a[pos] == 0;pos++); if(pos > n) break; pos = Math.max(pos, i + 2); for(int j = n; j >= pos; j--){ a[j] = a[j] - a[j-1]; } // for(int j : a) System.out.print(j + " "); // System.out.println(); // System.out.println( pos ); Arrays.sort(a, pos , n+1); } System.out.println(a[n]); } } }
Java
["5\n\n3\n\n1 10 100\n\n4\n\n4 8 9 13\n\n5\n\n0 0 0 8 13\n\n6\n\n2 4 8 16 32 64\n\n7\n\n0 0 0 0 0 0 0"]
1 second
["81\n3\n1\n2\n0"]
NoteTo simplify the notes, let $$$\operatorname{sort}(a)$$$ denote the array you get by sorting $$$a$$$ from small to large.In the first test case, $$$a=[1,10,100]$$$ at first. After the first operation, $$$a=\operatorname{sort}([10-1,100-10])=[9,90]$$$. After the second operation, $$$a=\operatorname{sort}([90-9])=[81]$$$.In the second test case, $$$a=[4,8,9,13]$$$ at first. After the first operation, $$$a=\operatorname{sort}([8-4,9-8,13-9])=[1,4,4]$$$. After the second operation, $$$a=\operatorname{sort}([4-1,4-4])=[0,3]$$$. After the last operation, $$$a=\operatorname{sort}([3-0])=[3]$$$.
Java 8
standard input
[ "brute force", "sortings" ]
499b1440d8bb528d089724910e37e226
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1\le t\le 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2\le n\le 10^5$$$) — the length of the array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1,a_2,\dots,a_n$$$ ($$$0\le a_1\le \ldots\le a_n \le 5\cdot 10^5$$$) — the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2.5\cdot 10^5$$$, and the sum of $$$a_n$$$ over all test cases does not exceed $$$5\cdot 10^5$$$.
1,900
For each test case, output the answer on a new line.
standard output
PASSED
360bdf04d063f3171bc4cb7ad67f9a6f
train_108.jsonl
1657982100
You are given an array $$$a$$$ consisting of $$$n$$$ non-negative integers. It is guaranteed that $$$a$$$ is sorted from small to large.For each operation, we generate a new array $$$b_i=a_{i+1}-a_{i}$$$ for $$$1 \le i &lt; n$$$. Then we sort $$$b$$$ from small to large, replace $$$a$$$ with $$$b$$$, and decrease $$$n$$$ by $$$1$$$.After performing $$$n-1$$$ operations, $$$n$$$ becomes $$$1$$$. You need to output the only integer in array $$$a$$$ (that is to say, you need to output $$$a_1$$$).
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; import java.util.TreeMap; public class D { public static void main(String[] args) throws NumberFormatException, IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); int inputs = Integer.parseInt(in.readLine()); while(inputs-->0) { int n = Integer.parseInt(in.readLine()); TreeMap<Integer, Integer> map = new TreeMap<>(); StringTokenizer st = new StringTokenizer(in.readLine()); for(int i = 0; i < n; i++) { int num = Integer.parseInt(st.nextToken()); map.put(num, map.getOrDefault(num, 0)+1); } for(int i = 0; i < n-1; i++) { TreeMap<Integer, Integer> newMap = new TreeMap<>(); for(int key : map.keySet()) { int count = map.get(key); if(count > 1) { newMap.put(0, newMap.getOrDefault(0, 0)+count-1); } Integer next = map.ceilingKey(key+1); if(key != map.lastKey()) { newMap.put(next-key, newMap.getOrDefault(next-key, 0)+1); } } map = newMap; } System.out.println(map.firstKey()); } } }
Java
["5\n\n3\n\n1 10 100\n\n4\n\n4 8 9 13\n\n5\n\n0 0 0 8 13\n\n6\n\n2 4 8 16 32 64\n\n7\n\n0 0 0 0 0 0 0"]
1 second
["81\n3\n1\n2\n0"]
NoteTo simplify the notes, let $$$\operatorname{sort}(a)$$$ denote the array you get by sorting $$$a$$$ from small to large.In the first test case, $$$a=[1,10,100]$$$ at first. After the first operation, $$$a=\operatorname{sort}([10-1,100-10])=[9,90]$$$. After the second operation, $$$a=\operatorname{sort}([90-9])=[81]$$$.In the second test case, $$$a=[4,8,9,13]$$$ at first. After the first operation, $$$a=\operatorname{sort}([8-4,9-8,13-9])=[1,4,4]$$$. After the second operation, $$$a=\operatorname{sort}([4-1,4-4])=[0,3]$$$. After the last operation, $$$a=\operatorname{sort}([3-0])=[3]$$$.
Java 8
standard input
[ "brute force", "sortings" ]
499b1440d8bb528d089724910e37e226
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1\le t\le 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2\le n\le 10^5$$$) — the length of the array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1,a_2,\dots,a_n$$$ ($$$0\le a_1\le \ldots\le a_n \le 5\cdot 10^5$$$) — the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2.5\cdot 10^5$$$, and the sum of $$$a_n$$$ over all test cases does not exceed $$$5\cdot 10^5$$$.
1,900
For each test case, output the answer on a new line.
standard output
PASSED
8c38514da03d284a06bede6e57f5b3f8
train_108.jsonl
1657982100
You are given an array $$$a$$$ consisting of $$$n$$$ non-negative integers. It is guaranteed that $$$a$$$ is sorted from small to large.For each operation, we generate a new array $$$b_i=a_{i+1}-a_{i}$$$ for $$$1 \le i &lt; n$$$. Then we sort $$$b$$$ from small to large, replace $$$a$$$ with $$$b$$$, and decrease $$$n$$$ by $$$1$$$.After performing $$$n-1$$$ operations, $$$n$$$ becomes $$$1$$$. You need to output the only integer in array $$$a$$$ (that is to say, you need to output $$$a_1$$$).
256 megabytes
import java.io.*; import java.text.*; import java.util.*; import java.util.function.*; /** * Provide prove of correctness before implementation. Implementation can cost a lot of time. * Anti test that prove that it's wrong. * <p> * Do not confuse i j k g indexes, upTo and length. Do extra methods!!! Write more informative names to simulation * <p> * Will program ever exceed limit? * Try all approaches with prove of correctness if task is not obvious. * If you are given formula/rule: Try to play with it. * Analytic solution/Hardcoded solution/Constructive/Greedy/DP/Math/Brute force/Symmetric data * Number theory * Game theory (optimal play) that consider local and global strategy. * Start writing the hardest code first */ public class D { final boolean ONLINE_JUDGE = java.lang.System.getProperty("ONLINE_JUDGE") != null; final boolean ANTI_TEST_FINDER_MODE = false; final boolean SIMULATION = false; final Random random = new Random(420); private int solveOne(int testCase) { int n = nextInt(); int[] a = nextIntArr(n); int l = 0; int r = n; while (r - l > 1) { r--; for(int i = l; i < r; i++) { a[i] = a[i + 1] - a[i]; } sort(a, l, r); l = Math.max(0, lowerBound(-1, r, mid -> a[mid] > 0) - 1); } System.out.println(a[l]); return 0; } int lowerBound(int exclusiveLeft, int inclusiveRight, Predicate<Integer> predicate) { while (inclusiveRight - exclusiveLeft > 1) { int middle = exclusiveLeft + (inclusiveRight - exclusiveLeft) / 2; if (predicate.test(middle)) { inclusiveRight = middle; } else { exclusiveLeft = middle; } } return inclusiveRight; } void sort(int[] a, int from, int upTo) { for (int i = from; i < upTo; i++) { int j = from + random.nextInt(upTo - from); int temp = a[i]; a[i] = a[j]; a[j] = temp; } Arrays.sort(a, from, upTo); } public static int[] radixSort2(int[] a) { int n = a.length; int[] c0 = new int[0x101]; int[] c1 = new int[0x101]; int[] c2 = new int[0x101]; int[] c3 = new int[0x101]; for (int v : a) { c0[(v & 0xff) + 1]++; c1[(v >>> 8 & 0xff) + 1]++; c2[(v >>> 16 & 0xff) + 1]++; c3[(v >>> 24 ^ 0x80) + 1]++; } for (int i = 0; i < 0xff; i++) { c0[i + 1] += c0[i]; c1[i + 1] += c1[i]; c2[i + 1] += c2[i]; c3[i + 1] += c3[i]; } int[] t = new int[n]; for (int v : a) t[c0[v & 0xff]++] = v; for (int v : t) a[c1[v >>> 8 & 0xff]++] = v; for (int v : a) t[c2[v >>> 16 & 0xff]++] = v; for (int v : t) a[c3[v >>> 24 ^ 0x80]++] = v; return a; } private int solveOneNaive(int testCase) { return 0; } private void solve() { if (SIMULATION) { int t = 1; for (int testCase = 0; testCase < t; testCase++) { // int n = 3 + random.nextInt(200); // int[] a = new int[n]; // a[0] = random.nextInt(2000); // for (int i = 1; i < n; i++) { // a[i] = a[i - 1] + random.nextInt(1000); // } int n = (int) 200;//5e5; int[] a = new int[n]; a[0] = 0; for (int i = 1, diff = 0; i < n; i++, diff++) { a[i] = a[i - 1] + diff; if (a[i] > n) { java.lang.System.out.println("Val = " + a[i] + " Diff - " + diff); return; } } // int n = 70; // int[] a = {2, 5, 7, 10, 17, 19, 222, 333, 4000, 50000, // 60000, 60000, 60000, 60000, 60000, 60000, 60000, 60000, 60000, 60000, // 60000, 60000, 60000, 60000, 60000, 60000, 60000, 60000, 60000, 60000, // 60000, 60000, 60000, 60000, 60000, 60000, 60000, 60000, 60000, 60000, // 60000, 60000, 60000, 60000, 60000, 60000, 60000, 60000, 60000, 60000, // 60000, 60000, 60000, 60000, 60000, 60000, 60000, 60000, 60000, 60000, // 60000, 60000, 60000, 60000, 60000, 60000, 60000, 60000, 60000, 60000, // }; // 10 // 2 5 7 10 17 19 222 333 4000 50000 //[...................] // [..................] List<Merge> merges = new ArrayList<>(); for (int i = 0; i < n; i++) { Merge m = new Merge(-1, i, null, a); merges.add(m); } List<Merge> cur = merges; int p = 0; while (cur.size() > 1) { java.lang.System.out.println("Oper " + p++); List<Merge> local = new ArrayList<>(); for (int i = 1; i < cur.size(); i++) { Merge m = new Merge(i - 1, i, cur, a); java.lang.System.out.print(m.getVal()); java.lang.System.out.print(' '); local.add(m); } java.lang.System.out.println(); Collections.sort(local, Comparator.comparingInt(Merge::getVal)); for (Merge m : local) { java.lang.System.out.print(m.getVal()); java.lang.System.out.print(' '); } java.lang.System.out.println(); cur = local; } java.lang.System.out.println("Test: " + testCase); java.lang.System.out.println(Arrays.toString(a)); java.lang.System.out.println(cur.get(0).getVal()); int[] contribPlus = new int[n]; int[] contribMinus = new int[n]; dfs(cur.get(0).parent.get(cur.get(0).second), contribPlus, contribMinus); dfs(cur.get(0).parent.get(cur.get(0).first), contribMinus, contribPlus); java.lang.System.out.println(Arrays.toString(contribPlus)); java.lang.System.out.println(Arrays.toString(contribMinus)); ///Test: 0 //[0, 0, 2, 2, 3, 5, 7, 8, 10, 12] //1 //[0, 7, 29, 7, 63, 0, 70, 63, 2, 15] //[1, 21, 6, 15, 7, 126, 13, 1, 65, 1] // } } else if (ANTI_TEST_FINDER_MODE) { int t = 100_000; for (int testCase = 0; testCase < t; testCase++) { int expected = solveOneNaive(testCase); int actual = solveOne(testCase); if (expected != actual) { throw new AssertionRuntimeException( this.getClass().getSimpleName(), testCase, expected, actual); } } } else { int t = nextInt(); for (int testCase = 0; testCase < t; testCase++) { solveOne(testCase); } } } private void dfs(Merge merge, int[] plus, int[] minus) { if (merge.first == -1) { plus[merge.second]++; } else { dfs(merge.parent.get(merge.second), plus, minus); dfs(merge.parent.get(merge.first), minus, plus); } } class Merge { Merge(int l, int r, List<Merge> parent, int[] a) { first = l; second = r; this.parent = parent; this.a = a; } int getVal() { if (ans == -1) { if (first == -1) return ans = a[second]; else return ans = parent.get(second).getVal() - parent.get(first).getVal(); } else { return ans; } } int ans = -1; int[] a; int first; int second; List<Merge> parent; } class AssertionRuntimeException extends RuntimeException { AssertionRuntimeException(String testName, int testCase, Object expected, Object actual, Object... input) { super("Testcase: " + testCase + "\n expected = " + expected + ",\n actual = " + actual + ",\n " + Arrays.deepToString(input)); } } private void assertThat(boolean b) { if (!b) throw new RuntimeException(); } private void assertThat(boolean b, String s) { if (!b) throw new RuntimeException(s); } private int assertThatInt(long a) { assertThat(Integer.MIN_VALUE <= a && a <= Integer.MAX_VALUE, "Integer overflow long = [" + a + "]" + " int = [" + (int) a + "]"); return (int) a; } void _______debug(String str, Object... os) { if (!ONLINE_JUDGE) { System.out.println(MessageFormat.format(str, os)); System.out.flush(); } } void _______debug(Object o) { if (!ONLINE_JUDGE) { _______debug("{0}", String.valueOf(o)); } } private int nextInt() { return System.in.readInt(); } private long nextLong() { return System.in.readLong(); } private String nextString() { return System.in.readString(); } private int[] nextIntArr(int n) { return System.in.readIntArray(n); } private long[] nextLongArr(int n) { return System.in.readLongArray(n); } public static void main(String[] args) { new D().run(); } static class System { private static FastInputStream in; private static FastPrintStream out; } private void run() { // final long startTime = java.lang.System.currentTimeMillis(); final boolean USE_IO = ONLINE_JUDGE; if (USE_IO) { System.in = new FastInputStream(java.lang.System.in); System.out = new FastPrintStream(java.lang.System.out); solve(); System.out.flush(); } else { final String nameIn = "input.txt"; final String nameOut = "output.txt"; try { System.in = new FastInputStream(new FileInputStream(nameIn)); System.out = new FastPrintStream(new PrintStream(nameOut)); solve(); System.out.flush(); } catch (FileNotFoundException e) { e.printStackTrace(); } } // final long endTime = java.lang.System.currentTimeMillis(); // _______debug("Execution time: {0}", endTime - startTime); } private static class FastPrintStream { private static final int BUF_SIZE = 8192; private final byte[] buf = new byte[BUF_SIZE]; private final OutputStream out; private int ptr = 0; private FastPrintStream() { this(java.lang.System.out); } public FastPrintStream(OutputStream os) { this.out = os; } public FastPrintStream(String path) { try { this.out = new FileOutputStream(path); } catch (FileNotFoundException e) { throw new RuntimeException("FastWriter"); } } public FastPrintStream print(byte b) { buf[ptr++] = b; if (ptr == BUF_SIZE) innerFlush(); return this; } public FastPrintStream print(char c) { return print((byte) c); } public FastPrintStream print(char[] s) { for (char c : s) { buf[ptr++] = (byte) c; if (ptr == BUF_SIZE) innerFlush(); } return this; } public FastPrintStream print(String s) { s.chars().forEach(c -> { buf[ptr++] = (byte) c; if (ptr == BUF_SIZE) innerFlush(); }); return this; } //can be optimized public FastPrintStream print0(char[] s) { if (ptr + s.length < BUF_SIZE) { for (char c : s) { buf[ptr++] = (byte) c; } } else { for (char c : s) { buf[ptr++] = (byte) c; if (ptr == BUF_SIZE) innerFlush(); } } return this; } //can be optimized public FastPrintStream print0(String s) { if (ptr + s.length() < BUF_SIZE) { for (int i = 0; i < s.length(); i++) { buf[ptr++] = (byte) s.charAt(i); } } else { for (int i = 0; i < s.length(); i++) { buf[ptr++] = (byte) s.charAt(i); if (ptr == BUF_SIZE) innerFlush(); } } return this; } private static int countDigits(int l) { if (l >= 1000000000) return 10; if (l >= 100000000) return 9; if (l >= 10000000) return 8; if (l >= 1000000) return 7; if (l >= 100000) return 6; if (l >= 10000) return 5; if (l >= 1000) return 4; if (l >= 100) return 3; if (l >= 10) return 2; return 1; } public FastPrintStream print(int x) { if (x == Integer.MIN_VALUE) { return print((long) x); } if (ptr + 12 >= BUF_SIZE) innerFlush(); if (x < 0) { print((byte) '-'); x = -x; } int d = countDigits(x); for (int i = ptr + d - 1; i >= ptr; i--) { buf[i] = (byte) ('0' + x % 10); x /= 10; } ptr += d; return this; } private static int countDigits(long l) { if (l >= 1000000000000000000L) return 19; if (l >= 100000000000000000L) return 18; if (l >= 10000000000000000L) return 17; if (l >= 1000000000000000L) return 16; if (l >= 100000000000000L) return 15; if (l >= 10000000000000L) return 14; if (l >= 1000000000000L) return 13; if (l >= 100000000000L) return 12; if (l >= 10000000000L) return 11; if (l >= 1000000000L) return 10; if (l >= 100000000L) return 9; if (l >= 10000000L) return 8; if (l >= 1000000L) return 7; if (l >= 100000L) return 6; if (l >= 10000L) return 5; if (l >= 1000L) return 4; if (l >= 100L) return 3; if (l >= 10L) return 2; return 1; } public FastPrintStream print(long x) { if (x == Long.MIN_VALUE) { return print("" + x); } if (ptr + 21 >= BUF_SIZE) innerFlush(); if (x < 0) { print((byte) '-'); x = -x; } int d = countDigits(x); for (int i = ptr + d - 1; i >= ptr; i--) { buf[i] = (byte) ('0' + x % 10); x /= 10; } ptr += d; return this; } public FastPrintStream print(double x, int precision) { if (x < 0) { print('-'); x = -x; } x += Math.pow(10, -precision) / 2; print((long) x).print("."); x -= (long) x; for (int i = 0; i < precision; i++) { x *= 10; print((char) ('0' + (int) x)); x -= (int) x; } return this; } public FastPrintStream println(char c) { return print(c).println(); } public FastPrintStream println(int x) { return print(x).println(); } public FastPrintStream println(long x) { return print(x).println(); } public FastPrintStream println(String x) { return print(x).println(); } public FastPrintStream println(Object x) { return print(x.toString()).println(); } public FastPrintStream println(double x, int precision) { return print(x, precision).println(); } public FastPrintStream println() { return print((byte) '\n'); } public FastPrintStream printf(String format, Object... args) { return print(String.format(format, args)); } private void innerFlush() { try { out.write(buf, 0, ptr); ptr = 0; } catch (IOException e) { throw new RuntimeException("innerFlush"); } } public void flush() { innerFlush(); try { out.flush(); } catch (IOException e) { throw new RuntimeException("flush"); } } } private static class FastInputStream { private boolean finished = false; private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public FastInputStream(InputStream stream) { this.stream = stream; } public double[] readDoubleArray(int size) { double[] array = new double[size]; for (int i = 0; i < size; i++) { array[i] = readDouble(); } return array; } public String[] readStringArray(int size) { String[] array = new String[size]; for (int i = 0; i < size; i++) { array[i] = readString(); } return array; } public char[] readCharArray(int size) { char[] array = new char[size]; for (int i = 0; i < size; i++) { array[i] = readCharacter(); } return array; } public String readText() { StringBuilder result = new StringBuilder(); while (true) { int character = read(); if (character == '\r') { continue; } if (character == -1) { break; } result.append((char) character); } return result.toString(); } public long[] readLongArray(int size) { long[] array = new long[size]; for (int i = 0; i < size; i++) { array[i] = readLong(); } return array; } public int[] readIntArray(int size) { int[] array = new int[size]; for (int i = 0; i < size; i++) { array[i] = readInt(); } return array; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int peek() { if (numChars == -1) { return -1; } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { return -1; } if (numChars <= 0) { return -1; } } return buf[curChar]; } public int peekNonWhitespace() { while (isWhitespace(peek())) { read(); } return peek(); } public int readInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long readLong() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { if (Character.isValidCodePoint(c)) { res.appendCodePoint(c); } c = read(); } while (!isSpaceChar(c)); return res.toString(); } public char[] readStringAsCharArray() { 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)); char[] resArr = new char[res.length()]; res.getChars(0, res.length(), resArr, 0); return resArr; } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private String readLine0() { StringBuilder buf = new StringBuilder(); int c = read(); while (c != '\n' && c != -1) { if (c != '\r') { buf.appendCodePoint(c); } c = read(); } return buf.toString(); } public String readLine() { String s = readLine0(); while (s.trim().length() == 0) { s = readLine0(); } return s; } public String readLine(boolean ignoreEmptyLines) { if (ignoreEmptyLines) { return readLine(); } else { return readLine0(); } } public char readCharacter() { int c = read(); while (isSpaceChar(c)) { c = read(); } return (char) c; } public double readDouble() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } double res = 0; while (!isSpaceChar(c) && c != '.') { if (c == 'e' || c == 'E') { return res * Math.pow(10, readInt()); } if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } if (c == '.') { c = read(); double m = 1; while (!isSpaceChar(c)) { if (c == 'e' || c == 'E') { return res * Math.pow(10, readInt()); } if (c < '0' || c > '9') { throw new InputMismatchException(); } m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } public boolean isExhausted() { int value; while (isSpaceChar(value = peek()) && value != -1) { read(); } return value == -1; } public String next() { return readString(); } public SpaceCharFilter getFilter() { return filter; } public void setFilter(SpaceCharFilter filter) { this.filter = filter; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["5\n\n3\n\n1 10 100\n\n4\n\n4 8 9 13\n\n5\n\n0 0 0 8 13\n\n6\n\n2 4 8 16 32 64\n\n7\n\n0 0 0 0 0 0 0"]
1 second
["81\n3\n1\n2\n0"]
NoteTo simplify the notes, let $$$\operatorname{sort}(a)$$$ denote the array you get by sorting $$$a$$$ from small to large.In the first test case, $$$a=[1,10,100]$$$ at first. After the first operation, $$$a=\operatorname{sort}([10-1,100-10])=[9,90]$$$. After the second operation, $$$a=\operatorname{sort}([90-9])=[81]$$$.In the second test case, $$$a=[4,8,9,13]$$$ at first. After the first operation, $$$a=\operatorname{sort}([8-4,9-8,13-9])=[1,4,4]$$$. After the second operation, $$$a=\operatorname{sort}([4-1,4-4])=[0,3]$$$. After the last operation, $$$a=\operatorname{sort}([3-0])=[3]$$$.
Java 17
standard input
[ "brute force", "sortings" ]
499b1440d8bb528d089724910e37e226
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1\le t\le 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2\le n\le 10^5$$$) — the length of the array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1,a_2,\dots,a_n$$$ ($$$0\le a_1\le \ldots\le a_n \le 5\cdot 10^5$$$) — the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2.5\cdot 10^5$$$, and the sum of $$$a_n$$$ over all test cases does not exceed $$$5\cdot 10^5$$$.
1,900
For each test case, output the answer on a new line.
standard output
PASSED
0ef18595fbb00361c26c5dd3715a1475
train_108.jsonl
1657982100
You are given an array $$$a$$$ consisting of $$$n$$$ non-negative integers. It is guaranteed that $$$a$$$ is sorted from small to large.For each operation, we generate a new array $$$b_i=a_{i+1}-a_{i}$$$ for $$$1 \le i &lt; n$$$. Then we sort $$$b$$$ from small to large, replace $$$a$$$ with $$$b$$$, and decrease $$$n$$$ by $$$1$$$.After performing $$$n-1$$$ operations, $$$n$$$ becomes $$$1$$$. You need to output the only integer in array $$$a$$$ (that is to say, you need to output $$$a_1$$$).
256 megabytes
import java.util.*; import java.util.function.*; import java.io.*; // you can compare with output.txt and expected out public class Round808D { MyPrintWriter out; MyScanner in; // final static long FIXED_RANDOM; // static { // FIXED_RANDOM = System.currentTimeMillis(); // } final static String IMPOSSIBLE = "IMPOSSIBLE"; final static String POSSIBLE = "POSSIBLE"; final static String YES = "YES"; final static String NO = "NO"; private void initIO(boolean isFileIO) { if (System.getProperty("ONLINE_JUDGE") == null && isFileIO) { try{ in = new MyScanner(new FileInputStream("input.txt")); out = new MyPrintWriter(new FileOutputStream("output.txt")); } catch(FileNotFoundException e){ e.printStackTrace(); } } else{ in = new MyScanner(System.in); out = new MyPrintWriter(new BufferedOutputStream(System.out)); } } public static void main(String[] args){ // Scanner in = new Scanner(new BufferedReader(new InputStreamReader(System.in))); Round808D sol = new Round808D(); sol.run(); } private void run() { boolean isDebug = false; boolean isFileIO = true; boolean hasMultipleTests = true; initIO(isFileIO); //test(); // simulate(new int[]{5, 44, 126, 626, 845, 900, 929, 967, 990, 1277, 1366, 1467, 1524, 1551, 1736}); // simulate(new int[]{5, 44, 126, 626, 845}); // simulate(new int[]{900, 929, 967, 990, 1277, 1366, 1467, 1524, 1551, 1736}); int t = hasMultipleTests? in.nextInt() : 1; for (int i = 1; i <= t; ++i) { int n = in.nextInt(); int[] a = in.nextIntArray(n); if(isDebug){ out.printf("Test %d\n", i); } int ans = solve(a); out.printlnAns(ans); if(isDebug) out.flush(); } in.close(); out.close(); } private void test() { final int n = 100_000; final int MAX = 500_000; Random r = new Random(); int[] a = new int[n]; for(int i=0; i<n; i++) { a[i] = r.nextInt(MAX); } Arrays.sort(a); out.printlnAns(solve(a)); } private void simulate(int[] a) { int n = a.length; Arrays.sort(a); System.out.println(Arrays.toString(a)); for(int i=0; i<n-1; i++) { int[] b = new int[a.length-1]; for(int j=0; j<b.length; j++) b[j] = a[j+1] - a[j]; Arrays.sort(b); a = b; System.out.println(Arrays.toString(a)); } } private void simulate() { int n = 15; Random r = new Random(); int[] a = new int[n]; for(int i=0; i<n; i++) { a[i] = r.nextInt(2000); } Arrays.sort(a); System.out.println(Arrays.toString(a)); for(int i=0; i<n-1; i++) { int[] b = new int[a.length-1]; for(int j=0; j<b.length; j++) b[j] = a[j+1] - a[j]; Arrays.sort(b); a = b; System.out.println(Arrays.toString(a)); } } private int solve(int[] a) { // a_0 <= ... <= a_(n-1) // a1-a0, ....., an-1-an-2 --> sum = an-1 - a0 // --> sum = max(diff) - min(diff) // [0, 0, .....0, 0 , X] // -> X // [5, 44, 126, 626, 845, 900, 929, 967, 990, 1277, 1366, 1467, 1524, 1551, 1736] // [23, 27, 29, 38, 39, 55, 57, 82, 89, 101, 185, 219, 287, 500] // [1, 2, 2, 4, 7, 9, 12, 16, 25, 34, 68, 84, 213] // [0, 1, 2, 2, 3, 3, 4, 9, 9, 16, 34, 129] // [0, 0, 0, 1, 1, 1, 1, 5, 7, 18, 95] // [0, 0, 0, 0, 0, 1, 2, 4, 11, 77] // [0, 0, 0, 0, 1, 1, 2, 7, 66] // [0, 0, 0, 0, 1, 1, 5, 59] // [0, 0, 0, 0, 1, 4, 54] // [0, 0, 0, 1, 3, 50] // [0, 0, 1, 2, 47] // [0, 1, 1, 45] // [0, 1, 44] // [1, 43] // [42] // at some point, they kind of converge quickly (log) // once converged, easy? // take max, simulate by tree map from 2nd max // bruteforce until 2nd max <= 10? // 0 0 0 1 100 1000 10000 final int THRESHOLD = 300; //10; // gcd(a, b) ends in O(log n) while(a.length > 1) { int[] b = new int[a.length-1]; for(int j=0; j<b.length; j++) b[j] = a[j+1] - a[j]; permutateAndSort(b); a = b; // len > 1 if(a.length == 1) return a[0]; if(a[a.length-2] < THRESHOLD) break; } int len = a.length; // >= 2 int[] curr = new int[THRESHOLD]; for(int i=0; i<a.length-1; i++) curr[a[i]]++; int max = a[a.length-1]; if(max < THRESHOLD) { curr[max]++; max = -1; } while(len > 1) { int[] next = new int[THRESHOLD]; int last = THRESHOLD; int left = 0; while(left < THRESHOLD && curr[left] == 0) left++; last = left; while(left < THRESHOLD) { next[0] += curr[left]-1; int right = left+1; while(right < THRESHOLD && curr[right] == 0) right++; if(right < THRESHOLD) { next[right-left] += 1; last = right; } left = right; } if(max != -1) { max = max-last; if(max < THRESHOLD) { next[max]++; max = -1; } } curr = next; len--; } // while(a.length > 1) { // int[] b = new int[a.length-1]; // for(int j=0; j<b.length; j++) // b[j] = a[j+1] - a[j]; // Arrays.sort(b); // a = b; // } if(max != -1) return max; else { for(int i=THRESHOLD-1; i>=0; i--) if(curr[i] > 0) return i; return -1; } } public static class MyScanner { BufferedReader br; StringTokenizer st; // 32768? public MyScanner(InputStream is, int bufferSize) { br = new BufferedReader(new InputStreamReader(is), bufferSize); } public MyScanner(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); // br = new BufferedReader(new InputStreamReader(System.in)); // br = new BufferedReader(new InputStreamReader(new FileInputStream("input.txt"))); } public void close() { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine(){ String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } int[][] nextTreeEdges(int n, int offset){ int[][] e = new int[n-1][2]; for(int i=0; i<n-1; i++){ e[i][0] = nextInt()+offset; e[i][1] = nextInt()+offset; } return e; } int[][] nextMatrix(int n, int m) { return nextMatrix(n, m, 0); } int[][] nextMatrix(int n, int m, int offset) { int[][] mat = new int[n][m]; for(int i=0; i<n; i++) { for(int j=0; j<m; j++) { mat[i][j] = nextInt()+offset; } } return mat; } int[][] nextPairs(int n){ return nextPairs(n, 0); } int[][] nextPairs(int n, int offset) { int[][] xy = new int[2][n]; for(int i=0; i<n; i++) { xy[0][i] = nextInt() + offset; xy[1][i] = nextInt() + offset; } return xy; } int[][] nextGraphEdges(){ return nextGraphEdges(0); } int[][] nextGraphEdges(int offset) { int m = nextInt(); int[][] e = new int[m][2]; for(int i=0; i<m; i++){ e[i][0] = nextInt()+offset; e[i][1] = nextInt()+offset; } return e; } int[] nextIntArray(int len) { return nextIntArray(len, 0); } int[] nextIntArray(int len, int offset){ int[] a = new int[len]; for(int j=0; j<len; j++) a[j] = nextInt()+offset; return a; } long[] nextLongArray(int len) { return nextLongArray(len, 0); } long[] nextLongArray(int len, int offset){ long[] a = new long[len]; for(int j=0; j<len; j++) a[j] = nextLong()+offset; return a; } } public static class MyPrintWriter extends PrintWriter{ public MyPrintWriter(OutputStream os) { super(os); } public void printlnAns(long ans) { println(ans); } public void printlnAns(int ans) { println(ans); } public void printlnAns(boolean ans) { if(ans) println(YES); else println(NO); } public void printAns(long[] arr){ if(arr != null && arr.length > 0){ print(arr[0]); for(int i=1; i<arr.length; i++){ print(" "); print(arr[i]); } } } public void printlnAns(long[] arr){ printAns(arr); println(); } public void printAns(int[] arr){ if(arr != null && arr.length > 0){ print(arr[0]); for(int i=1; i<arr.length; i++){ print(" "); print(arr[i]); } } } public void printlnAns(int[] arr){ printAns(arr); println(); } public <T> void printAns(ArrayList<T> arr){ if(arr != null && arr.size() > 0){ print(arr.get(0)); for(int i=1; i<arr.size(); i++){ print(" "); print(arr.get(i)); } } } public <T> void printlnAns(ArrayList<T> arr){ printAns(arr); println(); } public void printAns(int[] arr, int add){ if(arr != null && arr.length > 0){ print(arr[0]+add); for(int i=1; i<arr.length; i++){ print(" "); print(arr[i]+add); } } } public void printlnAns(int[] arr, int add){ printAns(arr, add); println(); } public void printAns(ArrayList<Integer> arr, int add) { if(arr != null && arr.size() > 0){ print(arr.get(0)+add); for(int i=1; i<arr.size(); i++){ print(" "); print(arr.get(i)+add); } } } public void printlnAns(ArrayList<Integer> arr, int add){ printAns(arr, add); println(); } public void printlnAnsSplit(long[] arr, int split){ if(arr != null){ for(int i=0; i<arr.length; i+=split){ print(arr[i]); for(int j=i+1; j<i+split; j++){ print(" "); print(arr[j]); } println(); } } } public void printlnAnsSplit(int[] arr, int split){ if(arr != null){ for(int i=0; i<arr.length; i+=split){ print(arr[i]); for(int j=i+1; j<i+split; j++){ print(" "); print(arr[j]); } println(); } } } public <T> void printlnAnsSplit(ArrayList<T> arr, int split){ if(arr != null && !arr.isEmpty()){ for(int i=0; i<arr.size(); i+=split){ print(arr.get(i)); for(int j=i+1; j<i+split; j++){ print(" "); print(arr.get(j)); } println(); } } } } static private void permutateAndSort(long[] a) { int n = a.length; Random R = new Random(System.currentTimeMillis()); for(int i=0; i<n; i++) { int t = R.nextInt(n-i); long temp = a[n-1-i]; a[n-1-i] = a[t]; a[t] = temp; } Arrays.sort(a); } static private void permutateAndSort(int[] a) { int n = a.length; Random R = new Random(System.currentTimeMillis()); for(int i=0; i<n; i++) { int t = R.nextInt(n-i); int temp = a[n-1-i]; a[n-1-i] = a[t]; a[t] = temp; } Arrays.sort(a); } static private int[][] constructChildren(int n, int[] parent, int parentRoot){ int[][] childrens = new int[n][]; int[] numChildren = new int[n]; for(int i=0; i<parent.length; i++) { if(parent[i] != parentRoot) numChildren[parent[i]]++; } for(int i=0; i<n; i++) { childrens[i] = new int[numChildren[i]]; } int[] idx = new int[n]; for(int i=0; i<parent.length; i++) { if(parent[i] != parentRoot) childrens[parent[i]][idx[parent[i]]++] = i; } return childrens; } static private int[][][] constructDirectedNeighborhood(int n, int[][] e){ int[] inDegree = new int[n]; int[] outDegree = new int[n]; for(int i=0; i<e.length; i++) { int u = e[i][0]; int v = e[i][1]; outDegree[u]++; inDegree[v]++; } int[][] inNeighbors = new int[n][]; int[][] outNeighbors = new int[n][]; for(int i=0; i<n; i++) { inNeighbors[i] = new int[inDegree[i]]; outNeighbors[i] = new int[outDegree[i]]; } int[] inIdx = new int[n]; int[] outIdx = new int[n]; for(int i=0; i<e.length; i++) { int u = e[i][0]; int v = e[i][1]; outNeighbors[u][outIdx[u]++] = v; inNeighbors[v][inIdx[v]++] = u; } return new int[][][] {inNeighbors, outNeighbors}; } static private int[][] constructNeighborhood(int n, int[][] e) { int[] degree = new int[n]; for(int i=0; i<e.length; i++) { int u = e[i][0]; int v = e[i][1]; degree[u]++; degree[v]++; } int[][] neighbors = new int[n][]; for(int i=0; i<n; i++) neighbors[i] = new int[degree[i]]; int[] idx = new int[n]; for(int i=0; i<e.length; i++) { int u = e[i][0]; int v = e[i][1]; neighbors[u][idx[u]++] = v; neighbors[v][idx[v]++] = u; } return neighbors; } static private void drawGraph(int[][] e) { makeDotUndirected(e); try { final Process process = new ProcessBuilder("dot", "-Tpng", "graph.dot") .redirectOutput(new File("graph.png")) .start(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } static private void makeDotUndirected(int[][] e) { MyPrintWriter out2 = null; try { out2 = new MyPrintWriter(new FileOutputStream("graph.dot")); } catch (FileNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } out2.println("strict graph {"); for(int i=0; i<e.length; i++){ out2.println(e[i][0] + "--" + e[i][1] + ";"); } out2.println("}"); out2.close(); } static private void makeDotDirected(int[][] e) { MyPrintWriter out2 = null; try { out2 = new MyPrintWriter(new FileOutputStream("graph.dot")); } catch (FileNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } out2.println("strict digraph {"); for(int i=0; i<e.length; i++){ out2.println(e[i][0] + "->" + e[i][1] + ";"); } out2.println("}"); out2.close(); } }
Java
["5\n\n3\n\n1 10 100\n\n4\n\n4 8 9 13\n\n5\n\n0 0 0 8 13\n\n6\n\n2 4 8 16 32 64\n\n7\n\n0 0 0 0 0 0 0"]
1 second
["81\n3\n1\n2\n0"]
NoteTo simplify the notes, let $$$\operatorname{sort}(a)$$$ denote the array you get by sorting $$$a$$$ from small to large.In the first test case, $$$a=[1,10,100]$$$ at first. After the first operation, $$$a=\operatorname{sort}([10-1,100-10])=[9,90]$$$. After the second operation, $$$a=\operatorname{sort}([90-9])=[81]$$$.In the second test case, $$$a=[4,8,9,13]$$$ at first. After the first operation, $$$a=\operatorname{sort}([8-4,9-8,13-9])=[1,4,4]$$$. After the second operation, $$$a=\operatorname{sort}([4-1,4-4])=[0,3]$$$. After the last operation, $$$a=\operatorname{sort}([3-0])=[3]$$$.
Java 17
standard input
[ "brute force", "sortings" ]
499b1440d8bb528d089724910e37e226
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1\le t\le 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2\le n\le 10^5$$$) — the length of the array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1,a_2,\dots,a_n$$$ ($$$0\le a_1\le \ldots\le a_n \le 5\cdot 10^5$$$) — the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2.5\cdot 10^5$$$, and the sum of $$$a_n$$$ over all test cases does not exceed $$$5\cdot 10^5$$$.
1,900
For each test case, output the answer on a new line.
standard output
PASSED
ffd1209e3f5a013bb1ad7229a481d63c
train_108.jsonl
1657982100
You are given an array $$$a$$$ consisting of $$$n$$$ non-negative integers. It is guaranteed that $$$a$$$ is sorted from small to large.For each operation, we generate a new array $$$b_i=a_{i+1}-a_{i}$$$ for $$$1 \le i &lt; n$$$. Then we sort $$$b$$$ from small to large, replace $$$a$$$ with $$$b$$$, and decrease $$$n$$$ by $$$1$$$.After performing $$$n-1$$$ operations, $$$n$$$ becomes $$$1$$$. You need to output the only integer in array $$$a$$$ (that is to say, you need to output $$$a_1$$$).
256 megabytes
//package com.example.practice.codeforces; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.StringTokenizer; public class Solution { final static int[] map = new int[500001]; public static void main (String [] args) throws IOException { // Use BufferedReader rather than RandomAccessFile; it's much faster final BufferedReader input = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); // input file name goes above int Q = Integer.parseInt(input.readLine()); while (Q > 0) { StringTokenizer st = new StringTokenizer(input.readLine()); int n = Integer.parseInt(st.nextToken()); int[] ns = readArrayInt(n, input); out.println(calc(n, ns)); Q--; } out.close(); // close the output file } private static int calc(final int n, final int[] ns) { if (n>2)return calc2(n, ns); return ns[1]-ns[0]; } private static int calc2(final int n, final int[] ns) { int[][] al = new int[n][2], al2 = new int[n][2]; int p = 0; for (int i=0;i<n;++i){ if (p>0 && al[p-1][0]==ns[i]){ al[p-1][1]++; }else { al[p][0] = ns[i]; al[p++][1] = 1; } } while (p > 1){ int p2 = 0; for (int i=0;i<p;++i){ if (al[i][1] > 1){ if (map[0] > 0){ al2[map[0]-1][1] += al[i][1] - 1; }else { map[0] = p2+1; al2[p2][0] = 0; al2[p2++][1] = al[i][1] - 1; } } if (i+1<p){ int d = al[i+1][0] - al[i][0]; if (map[d] > 0){ al2[map[d]-1][1]++; }else { map[d] = p2+1; al2[p2][0] = d; al2[p2++][1] = 1; } } } Arrays.sort(al2, 0, p2, (a,b) -> (a[0]-b[0])); for (int i=0;i<p2;++i){ al[i][0] = al2[i][0]; al[i][1] = al2[i][1]; map[al2[i][0]] = 0; } p = p2; } if (al[0][1] > 1)return 0; return al[0][0]; } private static void printArray(long[] ns, final PrintWriter out){ for (int i=0;i<ns.length;++i){ out.print(ns[i]); if (i+1<ns.length)out.print(" "); else out.println(); } } private static void printArrayInt(int[] ns, final PrintWriter out){ for (int i=0;i<ns.length;++i){ out.print(ns[i]); if (i+1<ns.length)out.print(" "); else out.println(); } } private static void printArrayVertical(long[] ns, final PrintWriter out){ for (long a : ns){ out.println(a); } } private static void printArrayVerticalInt(int[] ns, final PrintWriter out){ for (int a : ns){ out.println(a); } } private static void printArray2D(long[][] ns, final int len, final PrintWriter out){ int cnt = 0; for (long[] kk : ns){ cnt++; if (cnt > len)break; for (int i=0;i<kk.length;++i){ out.print(kk[i]); if (i+1<kk.length)out.print(" "); else out.println(); } } } private static void printArray2DInt(int[][] ns, final int len, final PrintWriter out){ int cnt = 0; for (int[] kk : ns){ cnt++; if (cnt > len)break; for (int i=0;i<kk.length;++i){ out.print(kk[i]); if (i+1<kk.length)out.print(" "); else out.println(); } } } private static long[] readArray(final int n, final BufferedReader input) throws IOException{ long[] ns = new long[n]; StringTokenizer st = new StringTokenizer(input.readLine()); for (int i=0;i<n;++i){ ns[i] = Long.parseLong(st.nextToken()); } return ns; } private static int[] readArrayInt(final int n, final BufferedReader input) throws IOException{ int[] ns = new int[n]; StringTokenizer st = new StringTokenizer(input.readLine()); for (int i=0;i<n;++i){ ns[i] = Integer.parseInt(st.nextToken()); } return ns; } private static long[] readArrayVertical(final int n, final BufferedReader input) throws IOException{ long[] ns = new long[n]; for (int i=0;i<n;++i){ ns[i] = Long.parseLong(input.readLine()); } return ns; } private static int[] readArrayVerticalInt(final int n, final BufferedReader input) throws IOException{ int[] ns = new int[n]; for (int i=0;i<n;++i){ ns[i] = Integer.parseInt(input.readLine()); } return ns; } private static long[][] readArray2D(final int n, final int len, final BufferedReader input) throws IOException{ long[][] ns = new long[len][]; for (int i=0;i<n;++i){ StringTokenizer st = new StringTokenizer(input.readLine()); ArrayList<Long> al = new ArrayList<>(); while (st.hasMoreTokens()){ al.add(Long.parseLong(st.nextToken())); } long[] kk = new long[al.size()]; for (int j=0;j<kk.length;++j){ kk[j] = al.get(j); } ns[i] = kk; } return ns; } private static int[][] readArray2DInt(final int n, final int len, final BufferedReader input) throws IOException{ int[][] ns = new int[len][]; for (int i=0;i<n;++i){ StringTokenizer st = new StringTokenizer(input.readLine()); ArrayList<Integer> al = new ArrayList<>(); while (st.hasMoreTokens()){ al.add(Integer.parseInt(st.nextToken())); } int[] kk = new int[al.size()]; for (int j=0;j<kk.length;++j){ kk[j] = al.get(j); } ns[i] = kk; } return ns; } static class SegTree{ int st; int en; int mid; int val1; int val2; SegTree left; SegTree right; public SegTree(int l, int r, int d){ st = l; en = r; mid = (st + en) >> 1; val1 = val2 = d; if (st<en){ left = new SegTree(st, mid, d); right = new SegTree(mid+1, en, d); }else { left = right = null; } } public SegTree(int l, int r, int[] ns){ st = l; en = r; mid = (st + en) >> 1; if (st==en){ val1 = val2 = ns[st]; }else { left = new SegTree(l, mid, ns); right = new SegTree(mid+1, r, ns); val1 = Math.min(left.val1, right.val1); val2 = Math.max(left.val2, right.val2); } } void update(int idx, int v){ if (st==en){ val1 = val2 = v; }else { if (idx <= mid){ left.update(idx, v); }else { right.update(idx, v); } val1 = Math.min(left.val1, right.val1); val2 = Math.max(left.val2, right.val2); } } int getMin(int l, int r){ if (st==en || (l==st && r==en))return val1; if (r<=mid){ return left.getMin(l, r); } if (l>mid){ return right.getMin(l, r); } return Math.min(left.getMin(l, mid), right.getMin(mid+1, r)); } int getMax(int l, int r){ if (st==en || (l==st && r==en))return val2; if (r<=mid){ return left.getMax(l, r); } if (l>mid){ return right.getMax(l, r); } return Math.max(left.getMax(l, mid), right.getMax(mid+1, r)); } } static class SparseTable{ int[][] minTable; int[][] maxTable; int[] log2; int n; public SparseTable(final int[] ns){ n = ns.length; int m = 0, pre = 0; while (1<<m < n){ m++; } m++; minTable = new int[n][m]; maxTable = new int[n][m]; log2 = new int[n+1]; for (int i=0;i<n;++i){ minTable[i][0] = ns[i]; maxTable[i][0] = ns[i]; if ((1<<(pre+1)) == i+1){ pre++; } log2[i+1] = pre; } for (int i=1;i<m;++i){ for (int j=0;j<n;++j){ int r = Math.min(n-1, j+(1<<i)-1); if (r-(1<<(i-1))+1 <= j){ minTable[j][i] = minTable[j][i-1]; maxTable[j][i] = maxTable[j][i-1]; }else { minTable[j][i] = Math.min(minTable[j][i-1], minTable[r-(1<<(i-1))+1][i-1]); maxTable[j][i] = Math.max(maxTable[j][i-1], maxTable[r-(1<<(i-1))+1][i-1]); } } } } int getMin(final int l, final int r){ int d = log2[r-l+1]; return Math.min(minTable[l][d], minTable[r-(1<<d)+1][d]); } int getMax(final int l, final int r){ int d = log2[r-l+1]; return Math.max(maxTable[l][d], maxTable[r-(1<<d)+1][d]); } } }
Java
["5\n\n3\n\n1 10 100\n\n4\n\n4 8 9 13\n\n5\n\n0 0 0 8 13\n\n6\n\n2 4 8 16 32 64\n\n7\n\n0 0 0 0 0 0 0"]
1 second
["81\n3\n1\n2\n0"]
NoteTo simplify the notes, let $$$\operatorname{sort}(a)$$$ denote the array you get by sorting $$$a$$$ from small to large.In the first test case, $$$a=[1,10,100]$$$ at first. After the first operation, $$$a=\operatorname{sort}([10-1,100-10])=[9,90]$$$. After the second operation, $$$a=\operatorname{sort}([90-9])=[81]$$$.In the second test case, $$$a=[4,8,9,13]$$$ at first. After the first operation, $$$a=\operatorname{sort}([8-4,9-8,13-9])=[1,4,4]$$$. After the second operation, $$$a=\operatorname{sort}([4-1,4-4])=[0,3]$$$. After the last operation, $$$a=\operatorname{sort}([3-0])=[3]$$$.
Java 17
standard input
[ "brute force", "sortings" ]
499b1440d8bb528d089724910e37e226
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1\le t\le 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2\le n\le 10^5$$$) — the length of the array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1,a_2,\dots,a_n$$$ ($$$0\le a_1\le \ldots\le a_n \le 5\cdot 10^5$$$) — the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2.5\cdot 10^5$$$, and the sum of $$$a_n$$$ over all test cases does not exceed $$$5\cdot 10^5$$$.
1,900
For each test case, output the answer on a new line.
standard output
PASSED
ecb31e547370f57e900a9fd56fa212e2
train_108.jsonl
1657982100
You are given an array $$$a$$$ consisting of $$$n$$$ non-negative integers. It is guaranteed that $$$a$$$ is sorted from small to large.For each operation, we generate a new array $$$b_i=a_{i+1}-a_{i}$$$ for $$$1 \le i &lt; n$$$. Then we sort $$$b$$$ from small to large, replace $$$a$$$ with $$$b$$$, and decrease $$$n$$$ by $$$1$$$.After performing $$$n-1$$$ operations, $$$n$$$ becomes $$$1$$$. You need to output the only integer in array $$$a$$$ (that is to say, you need to output $$$a_1$$$).
256 megabytes
//package com.example.practice.codeforces; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.StringTokenizer; public class Solution { final static int[] map = new int[500001]; public static void main (String [] args) throws IOException { // Use BufferedReader rather than RandomAccessFile; it's much faster final BufferedReader input = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); // input file name goes above int Q = Integer.parseInt(input.readLine()); while (Q > 0) { StringTokenizer st = new StringTokenizer(input.readLine()); int n = Integer.parseInt(st.nextToken()); int[] ns = readArrayInt(n, input); out.println(calc(n, ns)); Q--; } out.close(); // close the output file } private static int calc(final int n, final int[] ns) { if (n>2)return calc2(n, ns); return ns[1]-ns[0]; } private static int calc2(final int n, final int[] ns) { int[][] al = new int[n][2], al2 = new int[n][2]; int p = 0; for (int i=0;i<n;++i){ if (p>0 && al[p-1][0]==ns[i]){ al[p-1][1]++; }else { al[p][0] = ns[i]; al[p++][1] = 1; } } while (p > 1){ int p2 = 0; for (int i=0;i<p;++i){ if (al[i][1] > 1){ if (map[0] > 0){ al2[map[0]-1][1] += al[i][1] - 1; }else { map[0] = p2+1; al2[p2][0] = 0; al2[p2++][1] = al[i][1] - 1; } } if (i+1<p){ int d = al[i+1][0] - al[i][0]; if (map[d] > 0){ al2[map[d]-1][1]++; }else { map[d] = p2+1; al2[p2][0] = d; al2[p2++][1] = 1; } } } Arrays.sort(al2, 0, p2, (a,b) -> (a[0]-b[0])); for (int i=0;i<p2;++i){ al[i][0] = al2[i][0]; al[i][1] = al2[i][1]; map[al2[i][0]] = 0; } p = p2; } if (al[0][1] > 1)return 0; return al[0][0]; } private static void printArray(long[] ns, final PrintWriter out){ for (int i=0;i<ns.length;++i){ out.print(ns[i]); if (i+1<ns.length)out.print(" "); else out.println(); } } private static void printArrayInt(int[] ns, final PrintWriter out){ for (int i=0;i<ns.length;++i){ out.print(ns[i]); if (i+1<ns.length)out.print(" "); else out.println(); } } private static void printArrayVertical(long[] ns, final PrintWriter out){ for (long a : ns){ out.println(a); } } private static void printArrayVerticalInt(int[] ns, final PrintWriter out){ for (int a : ns){ out.println(a); } } private static void printArray2D(long[][] ns, final int len, final PrintWriter out){ int cnt = 0; for (long[] kk : ns){ cnt++; if (cnt > len)break; for (int i=0;i<kk.length;++i){ out.print(kk[i]); if (i+1<kk.length)out.print(" "); else out.println(); } } } private static void printArray2DInt(int[][] ns, final int len, final PrintWriter out){ int cnt = 0; for (int[] kk : ns){ cnt++; if (cnt > len)break; for (int i=0;i<kk.length;++i){ out.print(kk[i]); if (i+1<kk.length)out.print(" "); else out.println(); } } } private static long[] readArray(final int n, final BufferedReader input) throws IOException{ long[] ns = new long[n]; StringTokenizer st = new StringTokenizer(input.readLine()); for (int i=0;i<n;++i){ ns[i] = Long.parseLong(st.nextToken()); } return ns; } private static int[] readArrayInt(final int n, final BufferedReader input) throws IOException{ int[] ns = new int[n]; StringTokenizer st = new StringTokenizer(input.readLine()); for (int i=0;i<n;++i){ ns[i] = Integer.parseInt(st.nextToken()); } return ns; } private static long[] readArrayVertical(final int n, final BufferedReader input) throws IOException{ long[] ns = new long[n]; for (int i=0;i<n;++i){ ns[i] = Long.parseLong(input.readLine()); } return ns; } private static int[] readArrayVerticalInt(final int n, final BufferedReader input) throws IOException{ int[] ns = new int[n]; for (int i=0;i<n;++i){ ns[i] = Integer.parseInt(input.readLine()); } return ns; } private static long[][] readArray2D(final int n, final int len, final BufferedReader input) throws IOException{ long[][] ns = new long[len][]; for (int i=0;i<n;++i){ StringTokenizer st = new StringTokenizer(input.readLine()); ArrayList<Long> al = new ArrayList<>(); while (st.hasMoreTokens()){ al.add(Long.parseLong(st.nextToken())); } long[] kk = new long[al.size()]; for (int j=0;j<kk.length;++j){ kk[j] = al.get(j); } ns[i] = kk; } return ns; } private static int[][] readArray2DInt(final int n, final int len, final BufferedReader input) throws IOException{ int[][] ns = new int[len][]; for (int i=0;i<n;++i){ StringTokenizer st = new StringTokenizer(input.readLine()); ArrayList<Integer> al = new ArrayList<>(); while (st.hasMoreTokens()){ al.add(Integer.parseInt(st.nextToken())); } int[] kk = new int[al.size()]; for (int j=0;j<kk.length;++j){ kk[j] = al.get(j); } ns[i] = kk; } return ns; } static class SegTree{ int st; int en; int mid; int val1; int val2; SegTree left; SegTree right; public SegTree(int l, int r, int d){ st = l; en = r; mid = (st + en) >> 1; val1 = val2 = d; if (st<en){ left = new SegTree(st, mid, d); right = new SegTree(mid+1, en, d); }else { left = right = null; } } public SegTree(int l, int r, int[] ns){ st = l; en = r; mid = (st + en) >> 1; if (st==en){ val1 = val2 = ns[st]; }else { left = new SegTree(l, mid, ns); right = new SegTree(mid+1, r, ns); val1 = Math.min(left.val1, right.val1); val2 = Math.max(left.val2, right.val2); } } void update(int idx, int v){ if (st==en){ val1 = val2 = v; }else { if (idx <= mid){ left.update(idx, v); }else { right.update(idx, v); } val1 = Math.min(left.val1, right.val1); val2 = Math.max(left.val2, right.val2); } } int getMin(int l, int r){ if (st==en || (l==st && r==en))return val1; if (r<=mid){ return left.getMin(l, r); } if (l>mid){ return right.getMin(l, r); } return Math.min(left.getMin(l, mid), right.getMin(mid+1, r)); } int getMax(int l, int r){ if (st==en || (l==st && r==en))return val2; if (r<=mid){ return left.getMax(l, r); } if (l>mid){ return right.getMax(l, r); } return Math.max(left.getMax(l, mid), right.getMax(mid+1, r)); } } static class SparseTable{ int[][] minTable; int[][] maxTable; int[] log2; int n; public SparseTable(final int[] ns){ n = ns.length; int m = 0, pre = 0; while (1<<m < n){ m++; } m++; minTable = new int[n][m]; maxTable = new int[n][m]; log2 = new int[n+1]; for (int i=0;i<n;++i){ minTable[i][0] = ns[i]; maxTable[i][0] = ns[i]; if ((1<<(pre+1)) == i+1){ pre++; } log2[i+1] = pre; } for (int i=1;i<m;++i){ for (int j=0;j<n;++j){ int r = Math.min(n-1, j+(1<<i)-1); if (r-(1<<(i-1))+1 <= j){ minTable[j][i] = minTable[j][i-1]; maxTable[j][i] = maxTable[j][i-1]; }else { minTable[j][i] = Math.min(minTable[j][i-1], minTable[r-(1<<(i-1))+1][i-1]); maxTable[j][i] = Math.max(maxTable[j][i-1], maxTable[r-(1<<(i-1))+1][i-1]); } } } } int getMin(final int l, final int r){ int d = log2[r-l+1]; return Math.min(minTable[l][d], minTable[r-(1<<d)+1][d]); } int getMax(final int l, final int r){ int d = log2[r-l+1]; return Math.max(maxTable[l][d], maxTable[r-(1<<d)+1][d]); } } }
Java
["5\n\n3\n\n1 10 100\n\n4\n\n4 8 9 13\n\n5\n\n0 0 0 8 13\n\n6\n\n2 4 8 16 32 64\n\n7\n\n0 0 0 0 0 0 0"]
1 second
["81\n3\n1\n2\n0"]
NoteTo simplify the notes, let $$$\operatorname{sort}(a)$$$ denote the array you get by sorting $$$a$$$ from small to large.In the first test case, $$$a=[1,10,100]$$$ at first. After the first operation, $$$a=\operatorname{sort}([10-1,100-10])=[9,90]$$$. After the second operation, $$$a=\operatorname{sort}([90-9])=[81]$$$.In the second test case, $$$a=[4,8,9,13]$$$ at first. After the first operation, $$$a=\operatorname{sort}([8-4,9-8,13-9])=[1,4,4]$$$. After the second operation, $$$a=\operatorname{sort}([4-1,4-4])=[0,3]$$$. After the last operation, $$$a=\operatorname{sort}([3-0])=[3]$$$.
Java 17
standard input
[ "brute force", "sortings" ]
499b1440d8bb528d089724910e37e226
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1\le t\le 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2\le n\le 10^5$$$) — the length of the array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1,a_2,\dots,a_n$$$ ($$$0\le a_1\le \ldots\le a_n \le 5\cdot 10^5$$$) — the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2.5\cdot 10^5$$$, and the sum of $$$a_n$$$ over all test cases does not exceed $$$5\cdot 10^5$$$.
1,900
For each test case, output the answer on a new line.
standard output
PASSED
27016e93bc4633fc58d72d2a7b873184
train_108.jsonl
1657982100
You are given an array $$$a$$$ consisting of $$$n$$$ non-negative integers. It is guaranteed that $$$a$$$ is sorted from small to large.For each operation, we generate a new array $$$b_i=a_{i+1}-a_{i}$$$ for $$$1 \le i &lt; n$$$. Then we sort $$$b$$$ from small to large, replace $$$a$$$ with $$$b$$$, and decrease $$$n$$$ by $$$1$$$.After performing $$$n-1$$$ operations, $$$n$$$ becomes $$$1$$$. You need to output the only integer in array $$$a$$$ (that is to say, you need to output $$$a_1$$$).
256 megabytes
import java.io.*; import java.util.*; public class D { Input in; PrintWriter out; public D() { in = new Input(System.in); out = new PrintWriter(System.out); } public static void main(String[] args) { D solution = new D(); for (int t = solution.in.nextInt(); t > 0; t--) { solution.solve(); } solution.out.close(); } void solve() { int n = in.nextInt(); List<Integer> list = new ArrayList<>(); for (int i=0; i<n; i++) { list.add(in.nextInt()); } int zero = 0; for (int j=0; j<n-1; j++) { if (list.size() == 0) { out.println(0); return; } List<Integer> diff = new ArrayList<>(); if (zero > 0) { diff.add(list.get(0)); zero--; } for (int i=1; i<list.size(); i++) { int temp = list.get(i) - list.get(i-1); if (temp > 0) diff.add(temp); else zero++; } if (list.size() == 1) diff.addAll(list); diff.sort(null); list = diff; } if (list.isEmpty()) out.println(0); else out.println(list.get(0)); } static class Input { BufferedReader br; StringTokenizer st; public Input(InputStream in) { br = new BufferedReader(new InputStreamReader(in)); st = new StringTokenizer(""); } String nextString() { while (!st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(nextString()); } long nextLong() { return Long.parseLong(nextString()); } int[] nextIntArray(int size) { int[] ans = new int[size]; for (int i = 0; i < size; i++) { ans[i] = nextInt(); } return ans; } } }
Java
["5\n\n3\n\n1 10 100\n\n4\n\n4 8 9 13\n\n5\n\n0 0 0 8 13\n\n6\n\n2 4 8 16 32 64\n\n7\n\n0 0 0 0 0 0 0"]
1 second
["81\n3\n1\n2\n0"]
NoteTo simplify the notes, let $$$\operatorname{sort}(a)$$$ denote the array you get by sorting $$$a$$$ from small to large.In the first test case, $$$a=[1,10,100]$$$ at first. After the first operation, $$$a=\operatorname{sort}([10-1,100-10])=[9,90]$$$. After the second operation, $$$a=\operatorname{sort}([90-9])=[81]$$$.In the second test case, $$$a=[4,8,9,13]$$$ at first. After the first operation, $$$a=\operatorname{sort}([8-4,9-8,13-9])=[1,4,4]$$$. After the second operation, $$$a=\operatorname{sort}([4-1,4-4])=[0,3]$$$. After the last operation, $$$a=\operatorname{sort}([3-0])=[3]$$$.
Java 17
standard input
[ "brute force", "sortings" ]
499b1440d8bb528d089724910e37e226
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1\le t\le 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2\le n\le 10^5$$$) — the length of the array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1,a_2,\dots,a_n$$$ ($$$0\le a_1\le \ldots\le a_n \le 5\cdot 10^5$$$) — the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2.5\cdot 10^5$$$, and the sum of $$$a_n$$$ over all test cases does not exceed $$$5\cdot 10^5$$$.
1,900
For each test case, output the answer on a new line.
standard output
PASSED
c1c1393f327204d9d1fc5e0785ea2317
train_108.jsonl
1657982100
You are given an array $$$a$$$ consisting of $$$n$$$ non-negative integers. It is guaranteed that $$$a$$$ is sorted from small to large.For each operation, we generate a new array $$$b_i=a_{i+1}-a_{i}$$$ for $$$1 \le i &lt; n$$$. Then we sort $$$b$$$ from small to large, replace $$$a$$$ with $$$b$$$, and decrease $$$n$$$ by $$$1$$$.After performing $$$n-1$$$ operations, $$$n$$$ becomes $$$1$$$. You need to output the only integer in array $$$a$$$ (that is to say, you need to output $$$a_1$$$).
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Arrays; import java.io.BufferedWriter; import java.util.InputMismatchException; import java.io.IOException; import java.util.Map; import java.io.Writer; import java.util.Map.Entry; import java.io.OutputStreamWriter; import java.util.NoSuchElementException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); DDifferenceArray solver = new DDifferenceArray(); solver.solve(1, in, out); out.close(); } static class DDifferenceArray { public void solve(int testNumber, InputReader in, OutputWriter out) { var tc = in.nextInt(); for (int i = 0; i < tc; i++) { solution(i, in, out); } } void solution(int testNumber, InputReader in, OutputWriter out) { // lets go through these sequences // 4 8 9 13 // 4 1 4 // 1 4 4 // that sort operation makes it extremely weird // what does the sort imply? that you want to always substract by the smallest. // you care about two things, the biggest, and the next biggest // hmm // we can't really subtract very easily, not for long at least // well, actually, how quickly do these things become 0? // if it's bucket sorted, and we have a bunch of them at the same value, can we quickly elinminated that? // if a bunch of them are the same value, can we just put that to a single one? since only the edge matters // yeah kinda // we care about distinct values! //int n = in.nextInt(); // int[] a = in.nextIntArray(n); // randomly generate arrays and compare basicsolution to fastsolution int n = in.nextInt(); int[] a = in.nextIntArray(n); int output = fastSolution(n, a); out.println(output); } private int fastSolution(int n, int[] a) { EzIntIntTreeMap map = new EzIntIntTreeMap(); for (int i = 0; i < n; i++) { map.put(a[i], map.get(a[i]) + 1); } int[] ka = map.keys(); while (ka.length > 1 && ka[ka.length - 2] != 0 || map.get(ka[ka.length - 1]) > 1) { int zeros = 0; for (int i = 0; i < ka.length; i++) { zeros += (map.get(ka[i]) - 1); } map.clear(); if (zeros > 0) { map.put(0, zeros); } for (int i = 0; i < ka.length - 1; i++) { int diff = ka[i + 1] - ka[i]; map.put(diff, map.get(diff) + 1); } ka = map.keys(); } int output = map.getLastKey(); return output; } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public int[] nextIntArray(int n) { int[] array = new int[n]; for (int i = 0; i < n; ++i) array[i] = nextInt(); return array; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void close() { writer.close(); } public void println(int i) { writer.println(i); } } static class EzIntIntTreeMap implements EzIntIntSortedMap { private static final int DEFAULT_CAPACITY = 10; private static final double ENLARGE_SCALE = 2.0; private static final int HASHCODE_INITIAL_VALUE = 0x811c9dc5; private static final int HASHCODE_MULTIPLIER = 0x01000193; private static final boolean BLACK = false; private static final boolean RED = true; private static final int NULL = 0; private static final int DEFAULT_NULL_KEY = (new int[1])[0]; private static final int DEFAULT_NULL_VALUE = (new int[1])[0]; private int[] keys; private int[] values; private int[] left; private int[] right; private int[] p; private boolean[] color; private int size; private int root; private boolean returnedNull; public EzIntIntTreeMap() { this(DEFAULT_CAPACITY); } public EzIntIntTreeMap(int capacity) { if (capacity < 0) { throw new IllegalArgumentException("Capacity must be non-negative"); } capacity++; keys = new int[capacity]; values = new int[capacity]; left = new int[capacity]; right = new int[capacity]; p = new int[capacity]; color = new boolean[capacity]; color[NULL] = BLACK; size = 0; root = NULL; returnedNull = false; } public EzIntIntTreeMap(EzIntIntMap map) { this(map.size()); for (EzIntIntMapIterator it = map.iterator(); it.hasNext(); it.next()) { put(it.getKey(), it.getValue()); } } public EzIntIntTreeMap(Map<Integer, Integer> javaMap) { this(javaMap.size()); for (Map.Entry<Integer, Integer> e : javaMap.entrySet()) { put(e.getKey(), e.getValue()); } } public int size() { return size; } public int get(int key) { int x = root; while (x != NULL) { if (key < keys[x]) { x = left[x]; } else if (key > keys[x]) { x = right[x]; } else { returnedNull = false; return values[x]; } } returnedNull = true; return DEFAULT_NULL_VALUE; } public int put(int key, int value) { int y = NULL; int x = root; while (x != NULL) { //noinspection SuspiciousNameCombination y = x; if (key < keys[x]) { x = left[x]; } else if (key > keys[x]) { x = right[x]; } else { final int oldValue = values[x]; values[x] = value; returnedNull = false; return oldValue; } } if (size == color.length - 1) { enlarge(); } int z = ++size; keys[z] = key; values[z] = value; p[z] = y; if (y == NULL) { root = z; } else { if (key < keys[y]) { left[y] = z; } else { right[y] = z; } } left[z] = NULL; right[z] = NULL; color[z] = RED; fixAfterAdd(z); returnedNull = true; return DEFAULT_NULL_VALUE; } private int successorNode(int x) { if (right[x] != NULL) { x = right[x]; while (left[x] != NULL) { x = left[x]; } return x; } else { int y = p[x]; while (y != NULL && x == right[y]) { //noinspection SuspiciousNameCombination x = y; y = p[y]; } return y; } } private void fixAfterAdd(int z) { while (color[p[z]] == RED) { if (p[z] == left[p[p[z]]]) { int y = right[p[p[z]]]; if (color[y] == RED) { color[p[z]] = BLACK; color[y] = BLACK; color[p[p[z]]] = RED; z = p[p[z]]; } else { if (z == right[p[z]]) { z = p[z]; rotateLeft(z); } color[p[z]] = BLACK; color[p[p[z]]] = RED; rotateRight(p[p[z]]); } } else { int y = left[p[p[z]]]; if (color[y] == RED) { color[p[z]] = BLACK; color[y] = BLACK; color[p[p[z]]] = RED; z = p[p[z]]; } else { if (z == left[p[z]]) { z = p[z]; rotateRight(z); } color[p[z]] = BLACK; color[p[p[z]]] = RED; rotateLeft(p[p[z]]); } } } color[root] = BLACK; } private void rotateLeft(int x) { int y = right[x]; right[x] = left[y]; if (left[y] != NULL) { p[left[y]] = x; } p[y] = p[x]; if (p[x] == NULL) { root = y; } else { if (x == left[p[x]]) { left[p[x]] = y; } else { right[p[x]] = y; } } left[y] = x; p[x] = y; } private void rotateRight(int x) { int y = left[x]; left[x] = right[y]; if (right[y] != NULL) { p[right[y]] = x; } p[y] = p[x]; if (p[x] == NULL) { root = y; } else { if (x == right[p[x]]) { right[p[x]] = y; } else { left[p[x]] = y; } } right[y] = x; p[x] = y; } public void clear() { color[NULL] = BLACK; size = 0; root = NULL; } public int[] keys() { int[] result = new int[size]; for (int i = 0, x = firstNode(); x != NULL; x = successorNode(x), i++) { result[i] = keys[x]; } return result; } public EzIntIntMapIterator iterator() { return new EzIntIntTreeMapIterator(); } private void enlarge() { int newLength = Math.max(color.length + 1, (int) (color.length * ENLARGE_SCALE)); keys = Arrays.copyOf(keys, newLength); values = Arrays.copyOf(values, newLength); left = Arrays.copyOf(left, newLength); right = Arrays.copyOf(right, newLength); p = Arrays.copyOf(p, newLength); color = Arrays.copyOf(color, newLength); } private int firstNode() { int x = root; while (left[x] != NULL) { x = left[x]; } return x; } private int lastNode() { int x = root; while (right[x] != NULL) { x = right[x]; } return x; } public int getLastKey() { if (root == NULL) { returnedNull = true; return DEFAULT_NULL_KEY; } final int x = lastNode(); returnedNull = false; return keys[x]; } public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; EzIntIntTreeMap that = (EzIntIntTreeMap) o; if (size != that.size) { return false; } for (int x = firstNode(), y = that.firstNode(); x != NULL; //noinspection SuspiciousNameCombination x = successorNode(x), y = that.successorNode(y) ) { if (keys[x] != that.keys[y] || values[x] != that.values[y]) { return false; } } return true; } public int hashCode() { int hash = HASHCODE_INITIAL_VALUE; for (int x = firstNode(); x != NULL; x = successorNode(x)) { hash = (hash ^ PrimitiveHashCalculator.getHash(keys[x])) * HASHCODE_MULTIPLIER; hash = (hash ^ PrimitiveHashCalculator.getHash(values[x])) * HASHCODE_MULTIPLIER; } return hash; } public String toString() { StringBuilder sb = new StringBuilder(); sb.append('{'); for (int x = firstNode(); x != NULL; x = successorNode(x)) { if (sb.length() > 1) { sb.append(", "); } sb.append(keys[x]); sb.append('='); sb.append(values[x]); } sb.append('}'); return sb.toString(); } private class EzIntIntTreeMapIterator implements EzIntIntMapIterator { private int x; private EzIntIntTreeMapIterator() { x = firstNode(); } public boolean hasNext() { return x != NULL; } public int getKey() { if (x == NULL) { throw new NoSuchElementException("Iterator doesn't have more entries"); } return keys[x]; } public int getValue() { if (x == NULL) { throw new NoSuchElementException("Iterator doesn't have more entries"); } return values[x]; } public void next() { if (x == NULL) { return; } x = successorNode(x); } } } static interface EzIntIntMapIterator { boolean hasNext(); int getKey(); int getValue(); void next(); } static final class PrimitiveHashCalculator { private PrimitiveHashCalculator() { } public static int getHash(int x) { return x; } } static interface EzIntIntSortedMap extends EzIntIntMap { int size(); EzIntIntMapIterator iterator(); boolean equals(Object object); int hashCode(); String toString(); } static class Arrays { private Arrays() { } public static int[] copyOf(int[] original, int newLength) { return java.util.Arrays.copyOf(original, newLength); } public static boolean[] copyOf(boolean[] original, int newLength) { return java.util.Arrays.copyOf(original, newLength); } } static interface EzIntIntMap { int size(); EzIntIntMapIterator iterator(); boolean equals(Object object); int hashCode(); String toString(); } }
Java
["5\n\n3\n\n1 10 100\n\n4\n\n4 8 9 13\n\n5\n\n0 0 0 8 13\n\n6\n\n2 4 8 16 32 64\n\n7\n\n0 0 0 0 0 0 0"]
1 second
["81\n3\n1\n2\n0"]
NoteTo simplify the notes, let $$$\operatorname{sort}(a)$$$ denote the array you get by sorting $$$a$$$ from small to large.In the first test case, $$$a=[1,10,100]$$$ at first. After the first operation, $$$a=\operatorname{sort}([10-1,100-10])=[9,90]$$$. After the second operation, $$$a=\operatorname{sort}([90-9])=[81]$$$.In the second test case, $$$a=[4,8,9,13]$$$ at first. After the first operation, $$$a=\operatorname{sort}([8-4,9-8,13-9])=[1,4,4]$$$. After the second operation, $$$a=\operatorname{sort}([4-1,4-4])=[0,3]$$$. After the last operation, $$$a=\operatorname{sort}([3-0])=[3]$$$.
Java 17
standard input
[ "brute force", "sortings" ]
499b1440d8bb528d089724910e37e226
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1\le t\le 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2\le n\le 10^5$$$) — the length of the array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1,a_2,\dots,a_n$$$ ($$$0\le a_1\le \ldots\le a_n \le 5\cdot 10^5$$$) — the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2.5\cdot 10^5$$$, and the sum of $$$a_n$$$ over all test cases does not exceed $$$5\cdot 10^5$$$.
1,900
For each test case, output the answer on a new line.
standard output
PASSED
a120fda905fcf0bdafe0aeaf4d0084e5
train_108.jsonl
1657982100
You are given an array $$$a$$$ consisting of $$$n$$$ non-negative integers. It is guaranteed that $$$a$$$ is sorted from small to large.For each operation, we generate a new array $$$b_i=a_{i+1}-a_{i}$$$ for $$$1 \le i &lt; n$$$. Then we sort $$$b$$$ from small to large, replace $$$a$$$ with $$$b$$$, and decrease $$$n$$$ by $$$1$$$.After performing $$$n-1$$$ operations, $$$n$$$ becomes $$$1$$$. You need to output the only integer in array $$$a$$$ (that is to say, you need to output $$$a_1$$$).
256 megabytes
import java.io.*; import java.util.*; public class Main { public static void main(String[] args) throws IOException { Scanner scanner = new Scanner(System.in); int t = scanner.nextInt(), cnt[] = new int[500001]; while (t-- > 0) { int n = scanner.nextInt(); ArrayList<Integer> a = new ArrayList<Integer>(); for (int i = 0; i < n; i++) { int x = scanner.nextInt(); if (cnt[x] == 0 && x != 0) a.add(x); cnt[x]++; } // System.out.println(a); // System.out.println(cnt[0]); while (a.size() > 1) { ArrayList<Integer> temp = new ArrayList<Integer>(); int z = cnt[0]; for (int i = 0; i < a.size(); i++) { cnt[0] += cnt[a.get(i)] - 1; cnt[a.get(i)] = 0; if (i == 0 && z > 0) { if (cnt[a.get(i)] == 0) temp.add(a.get(i)); cnt[a.get(i)]++; } else if (i > 0) { if (cnt[a.get(i) - a.get(i - 1)] == 0) temp.add(a.get(i) - a.get(i - 1)); cnt[a.get(i) - a.get(i - 1)]++; } } a = new ArrayList<Integer>(); for (int i = 0; i < temp.size(); i++) a.add(temp.get(i)); Collections.sort(a); if (z > 0) cnt[0]--; // System.out.println(a); } if (!a.isEmpty() && cnt[a.get(0)] > 1 && cnt[0] == 0) { cnt[a.get(0)] = 0; a.clear(); } System.out.println(!a.isEmpty() ? a.get(0) : 0); cnt[0] = 0; if (!a.isEmpty()) cnt[a.get(0)] = 0; } } }
Java
["5\n\n3\n\n1 10 100\n\n4\n\n4 8 9 13\n\n5\n\n0 0 0 8 13\n\n6\n\n2 4 8 16 32 64\n\n7\n\n0 0 0 0 0 0 0"]
1 second
["81\n3\n1\n2\n0"]
NoteTo simplify the notes, let $$$\operatorname{sort}(a)$$$ denote the array you get by sorting $$$a$$$ from small to large.In the first test case, $$$a=[1,10,100]$$$ at first. After the first operation, $$$a=\operatorname{sort}([10-1,100-10])=[9,90]$$$. After the second operation, $$$a=\operatorname{sort}([90-9])=[81]$$$.In the second test case, $$$a=[4,8,9,13]$$$ at first. After the first operation, $$$a=\operatorname{sort}([8-4,9-8,13-9])=[1,4,4]$$$. After the second operation, $$$a=\operatorname{sort}([4-1,4-4])=[0,3]$$$. After the last operation, $$$a=\operatorname{sort}([3-0])=[3]$$$.
Java 11
standard input
[ "brute force", "sortings" ]
499b1440d8bb528d089724910e37e226
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1\le t\le 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2\le n\le 10^5$$$) — the length of the array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1,a_2,\dots,a_n$$$ ($$$0\le a_1\le \ldots\le a_n \le 5\cdot 10^5$$$) — the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2.5\cdot 10^5$$$, and the sum of $$$a_n$$$ over all test cases does not exceed $$$5\cdot 10^5$$$.
1,900
For each test case, output the answer on a new line.
standard output
PASSED
ed28cd666e9418cc7a41a30bfe50aa68
train_108.jsonl
1657982100
You are given an array $$$a$$$ consisting of $$$n$$$ non-negative integers. It is guaranteed that $$$a$$$ is sorted from small to large.For each operation, we generate a new array $$$b_i=a_{i+1}-a_{i}$$$ for $$$1 \le i &lt; n$$$. Then we sort $$$b$$$ from small to large, replace $$$a$$$ with $$$b$$$, and decrease $$$n$$$ by $$$1$$$.After performing $$$n-1$$$ operations, $$$n$$$ becomes $$$1$$$. You need to output the only integer in array $$$a$$$ (that is to say, you need to output $$$a_1$$$).
256 megabytes
import java.io.*; import java.util.*; public class Main { public static void main(String[] args) throws IOException { Scanner scanner = new Scanner(System.in); int t = scanner.nextInt(), cnt[] = new int[500001]; while (t-- > 0) { int n = scanner.nextInt(); ArrayList<Integer> a = new ArrayList<Integer>(); for (int i = 0; i < n; i++) { int x = scanner.nextInt(); if (cnt[x] == 0 && x != 0) a.add(x); cnt[x]++; } // System.out.println(a); // System.out.println(cnt[0]); while (a.size() > 1) { ArrayList<Integer> temp = new ArrayList<Integer>(); HashSet<Integer> set = new HashSet<Integer>(); int z = cnt[0]; for (int i = 0; i < a.size(); i++) { cnt[0] += cnt[a.get(i)] - 1; cnt[a.get(i)] = 0; if (i == 0 && z > 0) { temp.add(a.get(i)); cnt[a.get(i)]++; set.add(a.get(i)); } else if (i > 0) { if (!set.contains(a.get(i) - a.get(i - 1))) { temp.add(a.get(i) - a.get(i - 1)); set.add(a.get(i) - a.get(i - 1)); } cnt[a.get(i) - a.get(i - 1)]++; } } a = new ArrayList<Integer>(); for (int i = 0; i < temp.size(); i++) a.add(temp.get(i)); Collections.sort(a); if (z > 0) cnt[0]--; // System.out.println(a); } if (!a.isEmpty() && cnt[a.get(0)] > 1 && cnt[0] == 0) { cnt[a.get(0)] = 0; a.clear(); } System.out.println(!a.isEmpty() ? a.get(0) : 0); cnt[0] = 0; if (!a.isEmpty()) cnt[a.get(0)] = 0; } } }
Java
["5\n\n3\n\n1 10 100\n\n4\n\n4 8 9 13\n\n5\n\n0 0 0 8 13\n\n6\n\n2 4 8 16 32 64\n\n7\n\n0 0 0 0 0 0 0"]
1 second
["81\n3\n1\n2\n0"]
NoteTo simplify the notes, let $$$\operatorname{sort}(a)$$$ denote the array you get by sorting $$$a$$$ from small to large.In the first test case, $$$a=[1,10,100]$$$ at first. After the first operation, $$$a=\operatorname{sort}([10-1,100-10])=[9,90]$$$. After the second operation, $$$a=\operatorname{sort}([90-9])=[81]$$$.In the second test case, $$$a=[4,8,9,13]$$$ at first. After the first operation, $$$a=\operatorname{sort}([8-4,9-8,13-9])=[1,4,4]$$$. After the second operation, $$$a=\operatorname{sort}([4-1,4-4])=[0,3]$$$. After the last operation, $$$a=\operatorname{sort}([3-0])=[3]$$$.
Java 11
standard input
[ "brute force", "sortings" ]
499b1440d8bb528d089724910e37e226
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1\le t\le 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2\le n\le 10^5$$$) — the length of the array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1,a_2,\dots,a_n$$$ ($$$0\le a_1\le \ldots\le a_n \le 5\cdot 10^5$$$) — the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2.5\cdot 10^5$$$, and the sum of $$$a_n$$$ over all test cases does not exceed $$$5\cdot 10^5$$$.
1,900
For each test case, output the answer on a new line.
standard output
PASSED
c6a0a5226e5cc584920cb263d5773911
train_108.jsonl
1657982100
You are given an array $$$a$$$ consisting of $$$n$$$ non-negative integers. It is guaranteed that $$$a$$$ is sorted from small to large.For each operation, we generate a new array $$$b_i=a_{i+1}-a_{i}$$$ for $$$1 \le i &lt; n$$$. Then we sort $$$b$$$ from small to large, replace $$$a$$$ with $$$b$$$, and decrease $$$n$$$ by $$$1$$$.After performing $$$n-1$$$ operations, $$$n$$$ becomes $$$1$$$. You need to output the only integer in array $$$a$$$ (that is to say, you need to output $$$a_1$$$).
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; /* Name of the class has to be "Main" only if the class is public. */ public class Codechef { public static void main (String[] args) throws java.lang.Exception { Scanner sc=new Scanner(System.in); int t=sc.nextInt(); while(t>0) { int n=sc.nextInt(); PriorityQueue<Integer> pq = new PriorityQueue<Integer>(); PriorityQueue<Integer> p = new PriorityQueue<Integer>(); int y=sc.nextInt(); pq.add(y); boolean alls=true; for(int i=1;i<n;i++) { int x=sc.nextInt(); pq.add(x); if(y!=x) { alls=false; } } if(alls) System.out.println(0); else { int k=0; boolean f=true; int ans=0; int c0=0,kk=0; while(f) { while(pq.size()>0 && pq.peek()==0) { int g=pq.poll(); c0++; } if(pq.size()==1) { f=false; ans=pq.poll(); break; } if(pq.size()>0) { k= pq.poll(); kk=k; } while(pq.size()>0) { int m=pq.poll()-k; p.add(m); k=m+k; } if(p.size()==0) { f=false; ans=0; break; } if(c0>0) { p.add(kk); c0--; } if(p.size()==1) { f=false; ans=p.poll(); break; } while(p.size()>0 && p.peek()==0) { int g=p.poll(); c0++; } if(p.size()==1) { f=false; ans=p.poll(); break; } if(p.size()>0) { k=p.poll(); kk=k; } while(p.size()>0) { int m=p.poll()-k; pq.add(m); k=m+k; } if(pq.size()==0) { f=false; ans=0; break; } if(c0>0) { pq.add(kk); c0--; } if(pq.size()==1) { f=false; ans=pq.poll(); break; } } System.out.println(ans); } t--; } } }
Java
["5\n\n3\n\n1 10 100\n\n4\n\n4 8 9 13\n\n5\n\n0 0 0 8 13\n\n6\n\n2 4 8 16 32 64\n\n7\n\n0 0 0 0 0 0 0"]
1 second
["81\n3\n1\n2\n0"]
NoteTo simplify the notes, let $$$\operatorname{sort}(a)$$$ denote the array you get by sorting $$$a$$$ from small to large.In the first test case, $$$a=[1,10,100]$$$ at first. After the first operation, $$$a=\operatorname{sort}([10-1,100-10])=[9,90]$$$. After the second operation, $$$a=\operatorname{sort}([90-9])=[81]$$$.In the second test case, $$$a=[4,8,9,13]$$$ at first. After the first operation, $$$a=\operatorname{sort}([8-4,9-8,13-9])=[1,4,4]$$$. After the second operation, $$$a=\operatorname{sort}([4-1,4-4])=[0,3]$$$. After the last operation, $$$a=\operatorname{sort}([3-0])=[3]$$$.
Java 11
standard input
[ "brute force", "sortings" ]
499b1440d8bb528d089724910e37e226
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1\le t\le 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2\le n\le 10^5$$$) — the length of the array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1,a_2,\dots,a_n$$$ ($$$0\le a_1\le \ldots\le a_n \le 5\cdot 10^5$$$) — the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2.5\cdot 10^5$$$, and the sum of $$$a_n$$$ over all test cases does not exceed $$$5\cdot 10^5$$$.
1,900
For each test case, output the answer on a new line.
standard output
PASSED
273a4ab3968afb4c2bd3e19585775dbd
train_108.jsonl
1657982100
You are given an array $$$a$$$ consisting of $$$n$$$ non-negative integers. It is guaranteed that $$$a$$$ is sorted from small to large.For each operation, we generate a new array $$$b_i=a_{i+1}-a_{i}$$$ for $$$1 \le i &lt; n$$$. Then we sort $$$b$$$ from small to large, replace $$$a$$$ with $$$b$$$, and decrease $$$n$$$ by $$$1$$$.After performing $$$n-1$$$ operations, $$$n$$$ becomes $$$1$$$. You need to output the only integer in array $$$a$$$ (that is to say, you need to output $$$a_1$$$).
256 megabytes
import java.io.*; import java.util.*; public class codeforces_808_D { private static void solve(FastIOAdapter in, PrintWriter out) { int n = in.nextInt(); int[] a = in.readArray(n); Map<Integer, Integer> map = new TreeMap<>(); for (int i = 1; i < n; i++) { int diff = a[i] - a[i - 1]; map.put(diff, map.getOrDefault(diff, 0) + 1); } while (map.size() > 1) { Map<Integer, Integer> newMap = new TreeMap<>(); var iter = map.keySet().iterator(); int prev = -1; while (iter.hasNext()) { int cur = iter.next(); if (map.get(cur) > 1) newMap.put(0, newMap.getOrDefault(0, 0) + map.get(cur) - 1); if (prev != -1) { int diff = cur - prev; newMap.put(diff, newMap.getOrDefault(diff, 0) + 1); } prev = cur; } map = newMap; } var entry = map.entrySet().iterator().next(); if (entry.getValue() > 1) out.println(0); else out.println(entry.getKey()); } public static void main(String[] args) throws Exception { try (FastIOAdapter ioAdapter = new FastIOAdapter()) { int count = 1; count = ioAdapter.nextInt(); while (count-- > 0) { solve(ioAdapter, ioAdapter.out); } } } static void ruffleSort(int[] arr) { int n = arr.length; Random rnd = new Random(); for (int i = 0; i < n; ++i) { int tmp = arr[i]; int randomPos = i + rnd.nextInt(n - i); arr[i] = arr[randomPos]; arr[randomPos] = tmp; } Arrays.sort(arr); } static class FastIOAdapter implements AutoCloseable { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); public PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter((System.out)))); StringTokenizer st = new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } String nextLine() { try { return br.readLine(); } catch (IOException e) { e.printStackTrace(); return null; } } int nextInt() { return Integer.parseInt(next()); } int[] readArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } long[] readArrayLong(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } long nextLong() { return Long.parseLong(next()); } @Override public void close() throws Exception { out.flush(); out.close(); br.close(); } } }
Java
["5\n\n3\n\n1 10 100\n\n4\n\n4 8 9 13\n\n5\n\n0 0 0 8 13\n\n6\n\n2 4 8 16 32 64\n\n7\n\n0 0 0 0 0 0 0"]
1 second
["81\n3\n1\n2\n0"]
NoteTo simplify the notes, let $$$\operatorname{sort}(a)$$$ denote the array you get by sorting $$$a$$$ from small to large.In the first test case, $$$a=[1,10,100]$$$ at first. After the first operation, $$$a=\operatorname{sort}([10-1,100-10])=[9,90]$$$. After the second operation, $$$a=\operatorname{sort}([90-9])=[81]$$$.In the second test case, $$$a=[4,8,9,13]$$$ at first. After the first operation, $$$a=\operatorname{sort}([8-4,9-8,13-9])=[1,4,4]$$$. After the second operation, $$$a=\operatorname{sort}([4-1,4-4])=[0,3]$$$. After the last operation, $$$a=\operatorname{sort}([3-0])=[3]$$$.
Java 11
standard input
[ "brute force", "sortings" ]
499b1440d8bb528d089724910e37e226
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1\le t\le 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2\le n\le 10^5$$$) — the length of the array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1,a_2,\dots,a_n$$$ ($$$0\le a_1\le \ldots\le a_n \le 5\cdot 10^5$$$) — the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2.5\cdot 10^5$$$, and the sum of $$$a_n$$$ over all test cases does not exceed $$$5\cdot 10^5$$$.
1,900
For each test case, output the answer on a new line.
standard output
PASSED
7df057b17fd510caa0311fafd78b4889
train_108.jsonl
1657982100
You are given an array $$$a$$$ consisting of $$$n$$$ non-negative integers. It is guaranteed that $$$a$$$ is sorted from small to large.For each operation, we generate a new array $$$b_i=a_{i+1}-a_{i}$$$ for $$$1 \le i &lt; n$$$. Then we sort $$$b$$$ from small to large, replace $$$a$$$ with $$$b$$$, and decrease $$$n$$$ by $$$1$$$.After performing $$$n-1$$$ operations, $$$n$$$ becomes $$$1$$$. You need to output the only integer in array $$$a$$$ (that is to say, you need to output $$$a_1$$$).
256 megabytes
import java.util.*; import java.io.*; public class Main { public static Scanner obj = new Scanner(System.in); public static PrintWriter out = new PrintWriter(System.out); public static void main(String[] args) { int len = obj.nextInt(); while (len-- != 0) { int n = obj.nextInt(); Vector<Integer> v=new Vector<>(); for(int i=0;i<n;i++)v.add(obj.nextInt()); int cnt=0; while(true) { Collections.sort(v,Collections.reverseOrder()); while(v.size()>0) { if(v.get(v.size()-1)!=0) break; v.remove(v.size()-1); cnt++; } if(v.size()==0) { out.println("0"); break; } else if(v.size()==1) { out.println(v.get(0)); break; } Vector<Integer> t=new Vector<>(); for(int i=1;i<v.size();i++)t.add(v.get(i-1)-v.get(i)); if(cnt>0) { t.add(v.get(v.size()-1)); cnt-=1; } Collections.sort(t); Vector<Integer> temp=t; t=v; v=temp; } } out.flush(); } }
Java
["5\n\n3\n\n1 10 100\n\n4\n\n4 8 9 13\n\n5\n\n0 0 0 8 13\n\n6\n\n2 4 8 16 32 64\n\n7\n\n0 0 0 0 0 0 0"]
1 second
["81\n3\n1\n2\n0"]
NoteTo simplify the notes, let $$$\operatorname{sort}(a)$$$ denote the array you get by sorting $$$a$$$ from small to large.In the first test case, $$$a=[1,10,100]$$$ at first. After the first operation, $$$a=\operatorname{sort}([10-1,100-10])=[9,90]$$$. After the second operation, $$$a=\operatorname{sort}([90-9])=[81]$$$.In the second test case, $$$a=[4,8,9,13]$$$ at first. After the first operation, $$$a=\operatorname{sort}([8-4,9-8,13-9])=[1,4,4]$$$. After the second operation, $$$a=\operatorname{sort}([4-1,4-4])=[0,3]$$$. After the last operation, $$$a=\operatorname{sort}([3-0])=[3]$$$.
Java 11
standard input
[ "brute force", "sortings" ]
499b1440d8bb528d089724910e37e226
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1\le t\le 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2\le n\le 10^5$$$) — the length of the array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1,a_2,\dots,a_n$$$ ($$$0\le a_1\le \ldots\le a_n \le 5\cdot 10^5$$$) — the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2.5\cdot 10^5$$$, and the sum of $$$a_n$$$ over all test cases does not exceed $$$5\cdot 10^5$$$.
1,900
For each test case, output the answer on a new line.
standard output
PASSED
0985d3252a1604bdb5ed92e9ab3adb3f
train_108.jsonl
1657982100
You are given an array $$$a$$$ consisting of $$$n$$$ non-negative integers. It is guaranteed that $$$a$$$ is sorted from small to large.For each operation, we generate a new array $$$b_i=a_{i+1}-a_{i}$$$ for $$$1 \le i &lt; n$$$. Then we sort $$$b$$$ from small to large, replace $$$a$$$ with $$$b$$$, and decrease $$$n$$$ by $$$1$$$.After performing $$$n-1$$$ operations, $$$n$$$ becomes $$$1$$$. You need to output the only integer in array $$$a$$$ (that is to say, you need to output $$$a_1$$$).
256 megabytes
import java.io.*; import java.util.*; public class new1{ static int mod = 998244353; public static long gcd(long a, long b) { if (a == 0) return b; return gcd(b%a, a); } public static void main(String[] args) throws IOException{ BufferedWriter output = new BufferedWriter(new OutputStreamWriter(System.out)); FastReader s = new FastReader(); int t = s.nextInt(); for(int z = 1; z <= t; z++) { int n = s.nextInt(); TreeSet<Integer> ts = new TreeSet<Integer>(); int[] arr = new int[n]; for(int i = 0; i < n; i++) { int val = s.nextInt(); arr[i] = val; } int same = 0; for(int i = 0; i < n - 1; i++) { if(ts.contains(arr[i + 1] - arr[i])) same++; ts.add(arr[i + 1] - arr[i]); } while(ts.size() > 1) { TreeSet<Integer> ts1 = new TreeSet<Integer>(); if(same > 0) { ts1.add(0); same--; } while(ts.size() > 1) { int a1 = ts.first(); ts.remove(a1); int a2 = ts.first(); if(ts1.contains(a2 - a1)) same++; ts1.add(a2 - a1); } ts = ts1; if(ts.size() == 2 && ts.first() == 0) { ts.remove(0); same = 0; } //System.out.println(ts.toString()); } if(same == 0) output.write(ts.first() + "\n"); else output.write(0 + "\n"); } output.flush(); } } 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(); } public int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; }}
Java
["5\n\n3\n\n1 10 100\n\n4\n\n4 8 9 13\n\n5\n\n0 0 0 8 13\n\n6\n\n2 4 8 16 32 64\n\n7\n\n0 0 0 0 0 0 0"]
1 second
["81\n3\n1\n2\n0"]
NoteTo simplify the notes, let $$$\operatorname{sort}(a)$$$ denote the array you get by sorting $$$a$$$ from small to large.In the first test case, $$$a=[1,10,100]$$$ at first. After the first operation, $$$a=\operatorname{sort}([10-1,100-10])=[9,90]$$$. After the second operation, $$$a=\operatorname{sort}([90-9])=[81]$$$.In the second test case, $$$a=[4,8,9,13]$$$ at first. After the first operation, $$$a=\operatorname{sort}([8-4,9-8,13-9])=[1,4,4]$$$. After the second operation, $$$a=\operatorname{sort}([4-1,4-4])=[0,3]$$$. After the last operation, $$$a=\operatorname{sort}([3-0])=[3]$$$.
Java 11
standard input
[ "brute force", "sortings" ]
499b1440d8bb528d089724910e37e226
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1\le t\le 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2\le n\le 10^5$$$) — the length of the array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1,a_2,\dots,a_n$$$ ($$$0\le a_1\le \ldots\le a_n \le 5\cdot 10^5$$$) — the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2.5\cdot 10^5$$$, and the sum of $$$a_n$$$ over all test cases does not exceed $$$5\cdot 10^5$$$.
1,900
For each test case, output the answer on a new line.
standard output
PASSED
af39bc297381912aa43d136b618f5e85
train_108.jsonl
1657982100
You are given an array $$$a$$$ consisting of $$$n$$$ non-negative integers. It is guaranteed that $$$a$$$ is sorted from small to large.For each operation, we generate a new array $$$b_i=a_{i+1}-a_{i}$$$ for $$$1 \le i &lt; n$$$. Then we sort $$$b$$$ from small to large, replace $$$a$$$ with $$$b$$$, and decrease $$$n$$$ by $$$1$$$.After performing $$$n-1$$$ operations, $$$n$$$ becomes $$$1$$$. You need to output the only integer in array $$$a$$$ (that is to say, you need to output $$$a_1$$$).
256 megabytes
import java.io.*; import java.util.*; // whole solution public class new1{ static int mod = 998244353; public static long gcd(long a, long b) { if (a == 0) return b; return gcd(b%a, a); } public static void main(String[] args) throws IOException{ BufferedWriter output = new BufferedWriter(new OutputStreamWriter(System.out)); FastReader s = new FastReader(); int t = s.nextInt(); for(int z = 1; z <= t; z++) { int n = s.nextInt(); TreeSet<Integer> ts = new TreeSet<Integer>(); int[] arr = new int[n]; for(int i = 0; i < n; i++) { int val = s.nextInt(); arr[i] = val; } int same = 0; for(int i = 0; i < n - 1; i++) { if(ts.contains(arr[i + 1] - arr[i])) same++; ts.add(arr[i + 1] - arr[i]); } while(ts.size() > 1) { TreeSet<Integer> ts1 = new TreeSet<Integer>(); if(same > 0) { ts1.add(0); same--; } while(ts.size() > 1) { int a1 = ts.first(); ts.remove(a1); int a2 = ts.first(); if(ts1.contains(a2 - a1)) same++; ts1.add(a2 - a1); } ts = ts1; if(ts.size() == 2 && ts.first() == 0) { ts.remove(0); same = 0; } //System.out.println(ts.toString()); } if(same == 0) output.write(ts.first() + "\n"); else output.write(0 + "\n"); } output.flush(); } } 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(); } public int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; }}
Java
["5\n\n3\n\n1 10 100\n\n4\n\n4 8 9 13\n\n5\n\n0 0 0 8 13\n\n6\n\n2 4 8 16 32 64\n\n7\n\n0 0 0 0 0 0 0"]
1 second
["81\n3\n1\n2\n0"]
NoteTo simplify the notes, let $$$\operatorname{sort}(a)$$$ denote the array you get by sorting $$$a$$$ from small to large.In the first test case, $$$a=[1,10,100]$$$ at first. After the first operation, $$$a=\operatorname{sort}([10-1,100-10])=[9,90]$$$. After the second operation, $$$a=\operatorname{sort}([90-9])=[81]$$$.In the second test case, $$$a=[4,8,9,13]$$$ at first. After the first operation, $$$a=\operatorname{sort}([8-4,9-8,13-9])=[1,4,4]$$$. After the second operation, $$$a=\operatorname{sort}([4-1,4-4])=[0,3]$$$. After the last operation, $$$a=\operatorname{sort}([3-0])=[3]$$$.
Java 11
standard input
[ "brute force", "sortings" ]
499b1440d8bb528d089724910e37e226
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1\le t\le 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2\le n\le 10^5$$$) — the length of the array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1,a_2,\dots,a_n$$$ ($$$0\le a_1\le \ldots\le a_n \le 5\cdot 10^5$$$) — the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2.5\cdot 10^5$$$, and the sum of $$$a_n$$$ over all test cases does not exceed $$$5\cdot 10^5$$$.
1,900
For each test case, output the answer on a new line.
standard output
PASSED
e2d9a1c5b8d27bec0b4af7957282da13
train_108.jsonl
1657982100
You are given an array $$$a$$$ consisting of $$$n$$$ non-negative integers. It is guaranteed that $$$a$$$ is sorted from small to large.For each operation, we generate a new array $$$b_i=a_{i+1}-a_{i}$$$ for $$$1 \le i &lt; n$$$. Then we sort $$$b$$$ from small to large, replace $$$a$$$ with $$$b$$$, and decrease $$$n$$$ by $$$1$$$.After performing $$$n-1$$$ operations, $$$n$$$ becomes $$$1$$$. You need to output the only integer in array $$$a$$$ (that is to say, you need to output $$$a_1$$$).
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.util.List; import java.util.TreeMap; import java.util.StringTokenizer; import java.util.Map; import java.io.Writer; import java.io.OutputStreamWriter; import java.io.BufferedReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ 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); DDifferenceArray solver = new DDifferenceArray(); int testCount = Integer.parseInt(in.next()); for (int i = 1; i <= testCount; i++) solver.solve(i, in, out); out.close(); } static class DDifferenceArray { public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.nextInt(); int[] arr = in.nextIntArray(n); Multiset<Integer> set = new Multiset<>(); for (int a : arr) set.add(a, 1); while (set.size() > 1) { Multiset<Integer> temp = new Multiset<>(); int last = -1; for (int a : set.keySet()) { int v = set.get(a).intValue(); temp.add(0, v - 1); if (last == -1) { last = a; continue; } temp.addOne(a - last); last = a; } set = temp; } int a = set.firstKey(); if (set.get(a) > 1) { out.println(0); } else { out.println(a); } // char[] arr= in.next().toCharArray(); // int n= arr.length; // int f=0; // int count=0,c1=0; // for(char c:arr){ // if(c=='G'){ // count++; // } // } // long ans=0; // for(char c:arr){ // if(count<2) break; // if(c=='G'){ // count--; // continue; // } // ans+= 1l*c1*(count)*(count-1)/2; // c1++; // } // count=0;c1=0; // for(char c:arr){ // if(c=='R'){ // count++; // } // } // for(char c:arr){ // if(count<2) break; // if(c=='R'){ // count--; // continue; // } // ans+= 1l*c1*(count)*(count-1)/2; // c1++; // } // out.println(ans); } class Multiset<T> extends TreeMap<T, Long> { public Multiset() { super(); } public Multiset(List<T> list) { super(); for (T e : list) this.addOne(e); } public long count(Object elm) { return getOrDefault(elm, 0L); } public void add(T elm, long amount) { if (!this.containsKey(elm)) put(elm, amount); else replace(elm, get(elm) + amount); if (this.count(elm) == 0) this.remove(elm); } public void addOne(T elm) { this.add(elm, 1); } } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void close() { writer.close(); } public void println(int i) { writer.println(i); } } static class InputReader { BufferedReader reader; 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[] nextIntArray(int n) { int[] array = new int[n]; for (int i = 0; i < n; ++i) array[i] = nextInt(); return array; } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["5\n\n3\n\n1 10 100\n\n4\n\n4 8 9 13\n\n5\n\n0 0 0 8 13\n\n6\n\n2 4 8 16 32 64\n\n7\n\n0 0 0 0 0 0 0"]
1 second
["81\n3\n1\n2\n0"]
NoteTo simplify the notes, let $$$\operatorname{sort}(a)$$$ denote the array you get by sorting $$$a$$$ from small to large.In the first test case, $$$a=[1,10,100]$$$ at first. After the first operation, $$$a=\operatorname{sort}([10-1,100-10])=[9,90]$$$. After the second operation, $$$a=\operatorname{sort}([90-9])=[81]$$$.In the second test case, $$$a=[4,8,9,13]$$$ at first. After the first operation, $$$a=\operatorname{sort}([8-4,9-8,13-9])=[1,4,4]$$$. After the second operation, $$$a=\operatorname{sort}([4-1,4-4])=[0,3]$$$. After the last operation, $$$a=\operatorname{sort}([3-0])=[3]$$$.
Java 11
standard input
[ "brute force", "sortings" ]
499b1440d8bb528d089724910e37e226
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1\le t\le 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2\le n\le 10^5$$$) — the length of the array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1,a_2,\dots,a_n$$$ ($$$0\le a_1\le \ldots\le a_n \le 5\cdot 10^5$$$) — the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2.5\cdot 10^5$$$, and the sum of $$$a_n$$$ over all test cases does not exceed $$$5\cdot 10^5$$$.
1,900
For each test case, output the answer on a new line.
standard output
PASSED
af28f1e6aa3435dd584cd485ad4ab541
train_108.jsonl
1657982100
You are given an array $$$a$$$ consisting of $$$n$$$ non-negative integers. It is guaranteed that $$$a$$$ is sorted from small to large.For each operation, we generate a new array $$$b_i=a_{i+1}-a_{i}$$$ for $$$1 \le i &lt; n$$$. Then we sort $$$b$$$ from small to large, replace $$$a$$$ with $$$b$$$, and decrease $$$n$$$ by $$$1$$$.After performing $$$n-1$$$ operations, $$$n$$$ becomes $$$1$$$. You need to output the only integer in array $$$a$$$ (that is to say, you need to output $$$a_1$$$).
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.util.List; import java.util.TreeMap; import java.util.StringTokenizer; import java.util.Map; import java.io.Writer; import java.io.OutputStreamWriter; import java.io.BufferedReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ 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); DDifferenceArray solver = new DDifferenceArray(); int testCount = Integer.parseInt(in.next()); for (int i = 1; i <= testCount; i++) solver.solve(i, in, out); out.close(); } static class DDifferenceArray { public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.nextInt(); int[] arr = in.nextIntArray(n); Multiset<Integer> set = new Multiset<>(); for (int a : arr) set.add(a, 1); while (set.size() > 1) { Multiset<Integer> temp = new Multiset<>(); int last = -1; for (int a : set.keySet()) { int v = set.get(a).intValue(); temp.add(0, v - 1); if (last == -1) { last = a; continue; } temp.addOne(a - last); last = a; } set = temp; } int a = set.firstKey(); if (set.get(a) > 1) { out.println(0); } else { out.println(a); } } class Multiset<T> extends TreeMap<T, Long> { public Multiset() { super(); } public Multiset(List<T> list) { super(); for (T e : list) this.addOne(e); } public long count(Object elm) { return getOrDefault(elm, 0L); } public void add(T elm, long amount) { if (!this.containsKey(elm)) put(elm, amount); else replace(elm, get(elm) + amount); if (this.count(elm) == 0) this.remove(elm); } public void addOne(T elm) { this.add(elm, 1); } } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void close() { writer.close(); } public void println(int i) { writer.println(i); } } static class InputReader { BufferedReader reader; 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[] nextIntArray(int n) { int[] array = new int[n]; for (int i = 0; i < n; ++i) array[i] = nextInt(); return array; } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["5\n\n3\n\n1 10 100\n\n4\n\n4 8 9 13\n\n5\n\n0 0 0 8 13\n\n6\n\n2 4 8 16 32 64\n\n7\n\n0 0 0 0 0 0 0"]
1 second
["81\n3\n1\n2\n0"]
NoteTo simplify the notes, let $$$\operatorname{sort}(a)$$$ denote the array you get by sorting $$$a$$$ from small to large.In the first test case, $$$a=[1,10,100]$$$ at first. After the first operation, $$$a=\operatorname{sort}([10-1,100-10])=[9,90]$$$. After the second operation, $$$a=\operatorname{sort}([90-9])=[81]$$$.In the second test case, $$$a=[4,8,9,13]$$$ at first. After the first operation, $$$a=\operatorname{sort}([8-4,9-8,13-9])=[1,4,4]$$$. After the second operation, $$$a=\operatorname{sort}([4-1,4-4])=[0,3]$$$. After the last operation, $$$a=\operatorname{sort}([3-0])=[3]$$$.
Java 11
standard input
[ "brute force", "sortings" ]
499b1440d8bb528d089724910e37e226
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1\le t\le 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2\le n\le 10^5$$$) — the length of the array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1,a_2,\dots,a_n$$$ ($$$0\le a_1\le \ldots\le a_n \le 5\cdot 10^5$$$) — the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2.5\cdot 10^5$$$, and the sum of $$$a_n$$$ over all test cases does not exceed $$$5\cdot 10^5$$$.
1,900
For each test case, output the answer on a new line.
standard output
PASSED
f7edc83e958402db07cd2007cf2d681b
train_108.jsonl
1657982100
You are given an array $$$a$$$ consisting of $$$n$$$ non-negative integers. It is guaranteed that $$$a$$$ is sorted from small to large.For each operation, we generate a new array $$$b_i=a_{i+1}-a_{i}$$$ for $$$1 \le i &lt; n$$$. Then we sort $$$b$$$ from small to large, replace $$$a$$$ with $$$b$$$, and decrease $$$n$$$ by $$$1$$$.After performing $$$n-1$$$ operations, $$$n$$$ becomes $$$1$$$. You need to output the only integer in array $$$a$$$ (that is to say, you need to output $$$a_1$$$).
256 megabytes
import java.util.*; import java.io.*; 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 boolean isPossible(int[] arr, int n, int x) { Arrays.sort(arr); if(arr[n]-arr[0]<x) return false; for(int i=0;i<n;i++) { if(arr[i+n]-arr[i]<x) return false; } return true; } public static long sweeper(int n, int[] arr) { long ans=0; int i=0; int temp = 0; int numZero = 0; boolean count = false; while(i<n-1) { if(arr[i]==0) { if(count) { numZero++; i++; } else { i++; } } else { if(count) { ans+=temp+numZero; temp=arr[i]; numZero=0; i++; } else { temp=arr[i]; numZero=0; count=true; i++; } } } ans+=temp+numZero; return ans; } public static int lastOccur(int[] arr, int n, int key){ int l=0; int h=n-1; int mid; while(l<=h){ mid = l + (h-l)/2; if(arr[mid]==key){ if(mid==n-1) return mid; else if(arr[mid+1]!=key) return mid; else{ l=mid+1; continue; } } else{ if(arr[mid]>key){ h=mid-1; continue; } else{ l=mid+1; continue; } } } return -1; } public static int bestPos(int[] arr, int n, int key){ int l=0; int h=n-1; int mid; while(l<=h){ mid=l+(h-l)/2; if(mid==0){ if(arr[mid]>=key) return mid; else{ l=mid+1; continue; } } else{ if(arr[mid]==key) return mid; else if(arr[mid-1]<key && arr[mid]>key) return mid; else if(arr[mid]>key){ h=mid-1; continue; } else{ l=mid+1; continue; } } } return l; } public static char[] findChar(int n, String str,int c, int[][] arr, int q, int[] queries) { int[] left = new int[c+1]; int[] right = new int[c+1]; int[] diff = new int[c+1]; left[0]=0; right[0]=n; for(int i=0;i<c;i++) { left[i+1]=right[i]; right[i+1]=left[i+1]+(arr[i][1]-arr[i][0]+1); diff[i+1]=left[i+1]-(arr[i][0]-1); } // for(int i=0;i<=c;i++) { // System.out.print(left[i]+" "); // } // System.out.println(); // for(int i=0;i<=c;i++) { // System.out.print(right[i]+" "); // } // System.out.println(); // for(int i=0;i<=c;i++) { // System.out.print(diff[i]+" "); // } // System.out.println(); char[] ans=new char[q]; for(int i=0;i<q;i++) { int k = queries[i]-1; int j = c; while(k>=n) { if(k<left[j]) { j--; continue; } else { k-=diff[j]; j--; } } ans[i]=str.charAt(k); } return ans; } public static int diffArray(int n, ArrayList<Integer> arr) { int countZero=0; for(int i=1;i<n;i++) { if(arr.size()==0) return 0; Collections.sort(arr); ArrayList<Integer> temp = new ArrayList<Integer>(); if(countZero>0) { countZero--; temp.add(arr.get(0)); } for(int j=1;j<arr.size();j++) { if(arr.get(j)-arr.get(j-1) == 0) { countZero++; } else { temp.add(arr.get(j)-arr.get(j-1)); } } arr=temp; } //System.out.println(countZero); if(countZero>0) return 0; else return arr.get(0); } public static boolean diff(int n, int[] arr) { while(true) { boolean minus = false; for(int i=n-1;i>0;i--) { if(arr[i]==0) continue; if(arr[i-1]==0) return false; arr[i]-=arr[i-1]; if(arr[i]<0) return false; minus=true; } if(!minus) break; } return true; } public static void diffGcd(int n, int l, int r) { int[] mul = new int[n]; for(int i=0;i<n;i++) { mul[i]=(int)l/(i+1); } int[] ans = new int[n]; for(int i=0;i<n;i++) { int j = mul[i]; int temp = j*(i+1); while(temp<l) { j++; temp=j*(i+1); } if(temp>r) { System.out.println("No"); return; } // if(hs.contains(temp)) { // while(hs.contains(temp)) { // j++; // temp=j*(i+1); // if(temp>r) { // System.out.println("No"); // return; // } // } // ans[i]=temp; // hs.add(temp); // ans[i]=temp; } System.out.println("Yes"); for(int a:ans) { System.out.print(a+" "); } System.out.println(); return; } public static String doremyIQ(int n, int q, int[] arr) { int[] num = new int[n]; int temp = 0; for(int i=n-1;i>=0;i--) { if(arr[i]>q) { temp++; num[i]=temp; } else { num[i]=temp; } } int x = 0; int Q=q; if(num[n-1]==0) Q--; for(int i=0;i<n;i++) { if(num[i]<=Q) { x=i; break; } } String ans=""; for(int i=0;i<n;i++) { if(i<x) { if(arr[i]<=q) { ans+="1"; } else ans+="0"; } else { ans+="1"; } } return ans; } public static void main(String[] args){ FastReader s = new FastReader(); int t=s.nextInt(); for(int i=0;i<t;i++){ int n=s.nextInt(); // int q=s.nextInt(); Integer[] arr=new Integer[n]; for(int j=0;j<n;j++) arr[j]=s.nextInt(); // System.out.println(diff(n, arr)?"Yes":"No"); System.out.println(diffArray(n, new ArrayList<Integer>(Arrays.asList(arr)))); } } } class Pair{ int val; int index; public Pair(int a, int b){ index=b; val=a; } } class sortPair implements Comparator<Pair>{ public int compare(Pair a,Pair b) { return a.val-b.val; } }
Java
["5\n\n3\n\n1 10 100\n\n4\n\n4 8 9 13\n\n5\n\n0 0 0 8 13\n\n6\n\n2 4 8 16 32 64\n\n7\n\n0 0 0 0 0 0 0"]
1 second
["81\n3\n1\n2\n0"]
NoteTo simplify the notes, let $$$\operatorname{sort}(a)$$$ denote the array you get by sorting $$$a$$$ from small to large.In the first test case, $$$a=[1,10,100]$$$ at first. After the first operation, $$$a=\operatorname{sort}([10-1,100-10])=[9,90]$$$. After the second operation, $$$a=\operatorname{sort}([90-9])=[81]$$$.In the second test case, $$$a=[4,8,9,13]$$$ at first. After the first operation, $$$a=\operatorname{sort}([8-4,9-8,13-9])=[1,4,4]$$$. After the second operation, $$$a=\operatorname{sort}([4-1,4-4])=[0,3]$$$. After the last operation, $$$a=\operatorname{sort}([3-0])=[3]$$$.
Java 11
standard input
[ "brute force", "sortings" ]
499b1440d8bb528d089724910e37e226
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1\le t\le 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2\le n\le 10^5$$$) — the length of the array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1,a_2,\dots,a_n$$$ ($$$0\le a_1\le \ldots\le a_n \le 5\cdot 10^5$$$) — the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2.5\cdot 10^5$$$, and the sum of $$$a_n$$$ over all test cases does not exceed $$$5\cdot 10^5$$$.
1,900
For each test case, output the answer on a new line.
standard output
PASSED
663bf8c55615c126e2795dd5cf557878
train_108.jsonl
1657982100
You are given an array $$$a$$$ consisting of $$$n$$$ non-negative integers. It is guaranteed that $$$a$$$ is sorted from small to large.For each operation, we generate a new array $$$b_i=a_{i+1}-a_{i}$$$ for $$$1 \le i &lt; n$$$. Then we sort $$$b$$$ from small to large, replace $$$a$$$ with $$$b$$$, and decrease $$$n$$$ by $$$1$$$.After performing $$$n-1$$$ operations, $$$n$$$ becomes $$$1$$$. You need to output the only integer in array $$$a$$$ (that is to say, you need to output $$$a_1$$$).
256 megabytes
import java.io.*; import java.util.*; public class Main { static PrintWriter pw; static Scanner sc; public static void main(String[] args) throws Exception { sc = new Scanner(System.in); pw = new PrintWriter(System.out); int t = sc.nextInt(); while (t-- > 0) { int n = sc.nextInt(); ArrayList<Integer> arr = new ArrayList<>(n); for (int i = 0; i < n; i++) { arr.add(sc.nextInt()); } int cnt = 0; while (arr.size() > 1) { ArrayList<Integer> temp = new ArrayList<>(); n = arr.size(); for (int i = 1; i < n; i++) { temp.add(arr.get(i) - arr.get(i - 1)); } temp.sort(null); arr = new ArrayList<>(); if (temp.get(0) != 0) { if (cnt > 0) { cnt--; arr.add(0); } } int dis = 0; for (int i = 0; i < n - 1;) { int val = temp.get(i); int j = i; while (i < n - 1 && temp.get(i) == val) { i++; } dis++; cnt += i - j - 1; arr.add(val); } // System.out.println(arr + " " + temp); if (dis == 1 && temp.size() > 1 && arr.get(0) != 0) { arr = new ArrayList<>(); arr.add(0); break; } if (arr.get(0) == 0 && arr.size() == 2) { arr.remove(0); } } pw.println(arr.get(0)); } pw.flush(); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public Scanner(FileReader r) { br = new BufferedReader(r); } public Scanner(String s) throws IOException { br = new BufferedReader(new FileReader(new File(s))); } public String readAllLines(BufferedReader reader) throws IOException { StringBuilder content = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { content.append(line); content.append(System.lineSeparator()); } return content.toString(); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public double nextDouble() throws IOException { String x = next(); StringBuilder sb = new StringBuilder("0"); double res = 0, f = 1; boolean dec = false, neg = false; int start = 0; if (x.charAt(0) == '-') { neg = true; start++; } for (int i = start; i < x.length(); i++) if (x.charAt(i) == '.') { res = Long.parseLong(sb.toString()); sb = new StringBuilder("0"); dec = true; } else { sb.append(x.charAt(i)); if (dec) f *= 10; } res += Long.parseLong(sb.toString()) / f; return res * (neg ? -1 : 1); } public long[] nextlongArray(int n) throws IOException { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } public Long[] nextLongArray(int n) throws IOException { Long[] a = new Long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } public int[] nextIntArray(int n) throws IOException { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public Integer[] nextIntegerArray(int n) throws IOException { Integer[] a = new Integer[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public boolean ready() throws IOException { return br.ready(); } } }
Java
["5\n\n3\n\n1 10 100\n\n4\n\n4 8 9 13\n\n5\n\n0 0 0 8 13\n\n6\n\n2 4 8 16 32 64\n\n7\n\n0 0 0 0 0 0 0"]
1 second
["81\n3\n1\n2\n0"]
NoteTo simplify the notes, let $$$\operatorname{sort}(a)$$$ denote the array you get by sorting $$$a$$$ from small to large.In the first test case, $$$a=[1,10,100]$$$ at first. After the first operation, $$$a=\operatorname{sort}([10-1,100-10])=[9,90]$$$. After the second operation, $$$a=\operatorname{sort}([90-9])=[81]$$$.In the second test case, $$$a=[4,8,9,13]$$$ at first. After the first operation, $$$a=\operatorname{sort}([8-4,9-8,13-9])=[1,4,4]$$$. After the second operation, $$$a=\operatorname{sort}([4-1,4-4])=[0,3]$$$. After the last operation, $$$a=\operatorname{sort}([3-0])=[3]$$$.
Java 11
standard input
[ "brute force", "sortings" ]
499b1440d8bb528d089724910e37e226
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1\le t\le 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2\le n\le 10^5$$$) — the length of the array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1,a_2,\dots,a_n$$$ ($$$0\le a_1\le \ldots\le a_n \le 5\cdot 10^5$$$) — the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2.5\cdot 10^5$$$, and the sum of $$$a_n$$$ over all test cases does not exceed $$$5\cdot 10^5$$$.
1,900
For each test case, output the answer on a new line.
standard output
PASSED
c3bfbe079b6e335a64fb62e3d0409b6e
train_108.jsonl
1657982100
You are given an array $$$a$$$ consisting of $$$n$$$ non-negative integers. It is guaranteed that $$$a$$$ is sorted from small to large.For each operation, we generate a new array $$$b_i=a_{i+1}-a_{i}$$$ for $$$1 \le i &lt; n$$$. Then we sort $$$b$$$ from small to large, replace $$$a$$$ with $$$b$$$, and decrease $$$n$$$ by $$$1$$$.After performing $$$n-1$$$ operations, $$$n$$$ becomes $$$1$$$. You need to output the only integer in array $$$a$$$ (that is to say, you need to output $$$a_1$$$).
256 megabytes
import java.io.*; import java.util.Arrays; public class DifferenceArray { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); int t = Integer.parseInt(br.readLine()); while (t-- > 0) { int n = Integer.parseInt(br.readLine()); int[] a = new int[n]; String[] input = br.readLine().split(" "); for (int i = 0; i < n; i++) { a[i] = Integer.parseInt(input[i]); } int s = 0; for (int i = 1; i < n; i++) { for (int j = s; j < n - i; j++) { a[j] = a[j + 1] - a[j]; } Arrays.sort(a, s, n - i); for (; s < n && a[s] == 0; s++) ; if (s > n - i) { break; } s--; s = Math.max(0, s); } bw.write(a[0] + "\n"); } br.close(); bw.close(); } }
Java
["5\n\n3\n\n1 10 100\n\n4\n\n4 8 9 13\n\n5\n\n0 0 0 8 13\n\n6\n\n2 4 8 16 32 64\n\n7\n\n0 0 0 0 0 0 0"]
1 second
["81\n3\n1\n2\n0"]
NoteTo simplify the notes, let $$$\operatorname{sort}(a)$$$ denote the array you get by sorting $$$a$$$ from small to large.In the first test case, $$$a=[1,10,100]$$$ at first. After the first operation, $$$a=\operatorname{sort}([10-1,100-10])=[9,90]$$$. After the second operation, $$$a=\operatorname{sort}([90-9])=[81]$$$.In the second test case, $$$a=[4,8,9,13]$$$ at first. After the first operation, $$$a=\operatorname{sort}([8-4,9-8,13-9])=[1,4,4]$$$. After the second operation, $$$a=\operatorname{sort}([4-1,4-4])=[0,3]$$$. After the last operation, $$$a=\operatorname{sort}([3-0])=[3]$$$.
Java 11
standard input
[ "brute force", "sortings" ]
499b1440d8bb528d089724910e37e226
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1\le t\le 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2\le n\le 10^5$$$) — the length of the array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1,a_2,\dots,a_n$$$ ($$$0\le a_1\le \ldots\le a_n \le 5\cdot 10^5$$$) — the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2.5\cdot 10^5$$$, and the sum of $$$a_n$$$ over all test cases does not exceed $$$5\cdot 10^5$$$.
1,900
For each test case, output the answer on a new line.
standard output
PASSED
812f466374583c529e411c105cdb4633
train_108.jsonl
1657982100
You are given an array $$$a$$$ consisting of $$$n$$$ non-negative integers. It is guaranteed that $$$a$$$ is sorted from small to large.For each operation, we generate a new array $$$b_i=a_{i+1}-a_{i}$$$ for $$$1 \le i &lt; n$$$. Then we sort $$$b$$$ from small to large, replace $$$a$$$ with $$$b$$$, and decrease $$$n$$$ by $$$1$$$.After performing $$$n-1$$$ operations, $$$n$$$ becomes $$$1$$$. You need to output the only integer in array $$$a$$$ (that is to say, you need to output $$$a_1$$$).
256 megabytes
import java.util.*; import java.io.*; public class practise { static boolean multipleTC = true; final static int Mod = 1000000007; final static int Mod2 = 998244353; final double PI = 3.14159265358979323846; int MAX = 1000000007; void pre() throws Exception { } void DFSUtil(int v, boolean[] visited, ArrayList<Integer> al, List<Integer> adj[]) { visited[v] = true; al.add(v); // System.out.print(v + " "); Iterator<Integer> it = adj[v].iterator(); while (it.hasNext()) { int n = it.next(); if (!visited[n]) DFSUtil(n, visited, al, adj); } } void DFS(List<Integer> adj[], ArrayList<ArrayList<Integer>> components, int V) { boolean[] visited = new boolean[V]; for (int i = 0; i < V; i++) { ArrayList<Integer> al = new ArrayList<>(); if (!visited[i]) { DFSUtil(i, visited, al, adj); components.add(al); } } } long gcd(long a, long b) { if(b == 0) return a; return gcd(b, a%b); } void solve(int t) throws Exception { int n = ni(); List<Integer> list = new ArrayList<>(); for(int i=1;i<=n;i++) list.add(ni()); Collections.sort(list, Collections.reverseOrder()); int cnt0 = 0; while(true) { while(list.size() > 0 && list.get(list.size()-1) == 0) { list.remove(list.size()-1); cnt0++; } if(list.size() == 0) { pn(0); return; } if(list.size() == 1) { pn(list.get(0)); return; } List<Integer> temp = new ArrayList<>(); for(int i=1;i<list.size();i++) { temp.add(list.get(i-1) - list.get(i)); } if(cnt0 > 0) { temp.add(list.get(list.size()-1)); cnt0--; } Collections.sort(temp, Collections.reverseOrder()); swap(list, temp); } } double dist(int x1, int y1, int x2, int y2) { double a = x1 - x2, b = y1 - y2; return Math.sqrt((a * a) + (b * b)); } void swap(List<Integer> list1, List<Integer> list2){ List<Integer> tmpList = new ArrayList<Integer>(list1); list1.clear(); list1.addAll(list2); list2.clear(); list2.addAll(tmpList); } long xor_sum_upton(long n) { if (n % 4 == 0) return n; if (n % 4 == 1) return 1; if (n % 4 == 2) return n + 1; return 0; } int[] readArr(int n) throws Exception { int arr[] = new int[n]; for (int i = 0; i < n; i++) { arr[i] = ni(); } return arr; } void sort(int arr[], int left, int right) { ArrayList<Integer> list = new ArrayList<>(); for (int i = left; i <= right; i++) list.add(arr[i]); Collections.sort(list); for (int i = left; i <= right; i++) arr[i] = list.get(i - left); } void sort(int arr[]) { ArrayList<Integer> list = new ArrayList<>(); for (int i = 0; i < arr.length; i++) list.add(arr[i]); Collections.sort(list); for (int i = 0; i < arr.length; i++) arr[i] = list.get(i); } public long max(long... arr) { long max = arr[0]; for (long itr : arr) max = Math.max(max, itr); return max; } public int max(int... arr) { int max = arr[0]; for (int itr : arr) max = Math.max(max, itr); return max; } public long min(long... arr) { long min = arr[0]; for (long itr : arr) min = Math.min(min, itr); return min; } public int min(int... arr) { int min = arr[0]; for (int itr : arr) min = Math.min(min, itr); return min; } public long sum(long... arr) { long sum = 0; for (long itr : arr) sum += itr; return sum; } public long sum(int... arr) { long sum = 0; for (int itr : arr) sum += itr; return sum; } String bin(long n) { return Long.toBinaryString(n); } String bin(int n) { return Integer.toBinaryString(n); } static int bitCount(int x) { return x == 0 ? 0 : (1 + bitCount(x & (x - 1))); } static void dbg(Object... o) { System.err.println(Arrays.deepToString(o)); } int bit(long n) { return (n == 0) ? 0 : (1 + bit(n & (n - 1))); } int abs(int a) { return (a < 0) ? -a : a; } long abs(long a) { return (a < 0) ? -a : a; } void p(Object o) { out.print(o); } void pn(Object o) { out.println(o); } void pni(Object o) { out.println(o); out.flush(); } void pn(int[] arr) { int n = arr.length; StringBuilder sb = new StringBuilder(); for (int i = 0; i < n; i++) { sb.append(arr[i] + " "); } pn(sb); } void pn(long[] arr) { int n = arr.length; StringBuilder sb = new StringBuilder(); for (int i = 0; i < n; i++) { sb.append(arr[i] + " "); } pn(sb); } String n() throws Exception { return in.next(); } String nln() throws Exception { return in.nextLine(); } char c() throws Exception { return in.next().charAt(0); } int ni() throws Exception { return Integer.parseInt(in.next()); } long nl() throws Exception { return Long.parseLong(in.next()); } double nd() throws Exception { return Double.parseDouble(in.next()); } public static void main(String[] args) throws Exception { new practise().run(); } FastReader in; PrintWriter out; void run() throws Exception { in = new FastReader(); out = new PrintWriter(System.out); int T = (multipleTC) ? ni() : 1; pre(); for (int t = 1; t <= T; t++) solve(t); out.flush(); out.close(); } class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } public FastReader(String s) throws Exception { br = new BufferedReader(new FileReader(s)); } String next() throws Exception { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { throw new Exception(e.toString()); } } return st.nextToken(); } String nextLine() throws Exception { String str = ""; try { str = br.readLine(); } catch (IOException e) { throw new Exception(e.toString()); } return str; } } }
Java
["5\n\n3\n\n1 10 100\n\n4\n\n4 8 9 13\n\n5\n\n0 0 0 8 13\n\n6\n\n2 4 8 16 32 64\n\n7\n\n0 0 0 0 0 0 0"]
1 second
["81\n3\n1\n2\n0"]
NoteTo simplify the notes, let $$$\operatorname{sort}(a)$$$ denote the array you get by sorting $$$a$$$ from small to large.In the first test case, $$$a=[1,10,100]$$$ at first. After the first operation, $$$a=\operatorname{sort}([10-1,100-10])=[9,90]$$$. After the second operation, $$$a=\operatorname{sort}([90-9])=[81]$$$.In the second test case, $$$a=[4,8,9,13]$$$ at first. After the first operation, $$$a=\operatorname{sort}([8-4,9-8,13-9])=[1,4,4]$$$. After the second operation, $$$a=\operatorname{sort}([4-1,4-4])=[0,3]$$$. After the last operation, $$$a=\operatorname{sort}([3-0])=[3]$$$.
Java 11
standard input
[ "brute force", "sortings" ]
499b1440d8bb528d089724910e37e226
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1\le t\le 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2\le n\le 10^5$$$) — the length of the array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1,a_2,\dots,a_n$$$ ($$$0\le a_1\le \ldots\le a_n \le 5\cdot 10^5$$$) — the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2.5\cdot 10^5$$$, and the sum of $$$a_n$$$ over all test cases does not exceed $$$5\cdot 10^5$$$.
1,900
For each test case, output the answer on a new line.
standard output
PASSED
129701570a1b3d4a88b2f233b3d6c1ef
train_108.jsonl
1657982100
You are given an array $$$a$$$ consisting of $$$n$$$ non-negative integers. It is guaranteed that $$$a$$$ is sorted from small to large.For each operation, we generate a new array $$$b_i=a_{i+1}-a_{i}$$$ for $$$1 \le i &lt; n$$$. Then we sort $$$b$$$ from small to large, replace $$$a$$$ with $$$b$$$, and decrease $$$n$$$ by $$$1$$$.After performing $$$n-1$$$ operations, $$$n$$$ becomes $$$1$$$. You need to output the only integer in array $$$a$$$ (that is to say, you need to output $$$a_1$$$).
256 megabytes
import java.io.*; import java.util.*; import java.math.*; import static java.lang.Math.max; import static java.lang.Math.min; import static java.lang.Math.abs; import static java.lang.System.out; public class D { public static void println (Object o) {System.out.println(o);} public static void print (Object o) {System.out.print(o);} public static void main(String[] args) { FScanner sc=new FScanner(); PrintWriter out=new PrintWriter(System.out); int T=sc.nextInt(); // int T=1; while(T-->0) { int n=sc.nextInt(); int[] a=sc.readArray(n); Map<Integer, Integer> map=new TreeMap<>(); for(int i=1; i<n; i++){ int diff=a[i]-a[i-1]; map.put(diff, map.getOrDefault(diff,0)+1); } while(map.size()>1){ Map<Integer, Integer> nMap=new TreeMap<>(); var it = map.keySet().iterator(); int prev=-1; while(it.hasNext()){ int curr=it.next(); if(map.get(curr)>1){ nMap.put(0, nMap.getOrDefault(0,0)+map.get(curr)-1); } if(prev!=-1){ int diff=curr-prev; nMap.put(diff, nMap.getOrDefault(diff, 0)+1); } prev=curr; } map=nMap; } var en=map.entrySet().iterator().next(); if(en.getValue()>1) println(0); else println(en.getKey()); } out.close(); } static void sort(int[] a) { // Arrays.sort() uses QuickSort // Collections.sort() uses MergeSort ArrayList<Integer> ls=new ArrayList<>(); for (int i:a) ls.add(i); Collections.sort(ls); for (int i=0; i<a.length; i++) a[i]=ls.get(i); } static class FScanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readArray(int n) { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } long nextLong() { return Long.parseLong(next()); } } }
Java
["5\n\n3\n\n1 10 100\n\n4\n\n4 8 9 13\n\n5\n\n0 0 0 8 13\n\n6\n\n2 4 8 16 32 64\n\n7\n\n0 0 0 0 0 0 0"]
1 second
["81\n3\n1\n2\n0"]
NoteTo simplify the notes, let $$$\operatorname{sort}(a)$$$ denote the array you get by sorting $$$a$$$ from small to large.In the first test case, $$$a=[1,10,100]$$$ at first. After the first operation, $$$a=\operatorname{sort}([10-1,100-10])=[9,90]$$$. After the second operation, $$$a=\operatorname{sort}([90-9])=[81]$$$.In the second test case, $$$a=[4,8,9,13]$$$ at first. After the first operation, $$$a=\operatorname{sort}([8-4,9-8,13-9])=[1,4,4]$$$. After the second operation, $$$a=\operatorname{sort}([4-1,4-4])=[0,3]$$$. After the last operation, $$$a=\operatorname{sort}([3-0])=[3]$$$.
Java 11
standard input
[ "brute force", "sortings" ]
499b1440d8bb528d089724910e37e226
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1\le t\le 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2\le n\le 10^5$$$) — the length of the array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1,a_2,\dots,a_n$$$ ($$$0\le a_1\le \ldots\le a_n \le 5\cdot 10^5$$$) — the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2.5\cdot 10^5$$$, and the sum of $$$a_n$$$ over all test cases does not exceed $$$5\cdot 10^5$$$.
1,900
For each test case, output the answer on a new line.
standard output
PASSED
cf2655438a9a4cbc365085716fcb2dbe
train_108.jsonl
1657982100
You are given an array $$$a$$$ consisting of $$$n$$$ non-negative integers. It is guaranteed that $$$a$$$ is sorted from small to large.For each operation, we generate a new array $$$b_i=a_{i+1}-a_{i}$$$ for $$$1 \le i &lt; n$$$. Then we sort $$$b$$$ from small to large, replace $$$a$$$ with $$$b$$$, and decrease $$$n$$$ by $$$1$$$.After performing $$$n-1$$$ operations, $$$n$$$ becomes $$$1$$$. You need to output the only integer in array $$$a$$$ (that is to say, you need to output $$$a_1$$$).
256 megabytes
// package c1708; // // Codeforces Round #808 (Div. 2) 2022-07-16 07:35 // D. Difference Array // https://codeforces.com/contest/1708/problem/D // time limit per test 1 second; memory limit per test 256 megabytes // public class Pseudo for 'Source should satisfy regex [^{}]*public\s+(final)?\s*class\s+(\w+).*' // // You are given an array a consisting of n non-negative integers. It is guaranteed that a is sorted // from small to large. // // For each operation, we generate a new array b_i=a_{i+1}-a_{i} for 1 <= i < n. Then we sort b from // small to large, replace a with b, and decrease n by 1. // // After performing n-1 operations, n becomes 1. You need to output the only integer in array a // (that is to say, you need to output a_1). // // Input // // The input consists of multiple test cases. The first line contains a single integer t (1<= t<= // 10^4)-- the number of test cases. The description of the test cases follows. // // The first line of each test case contains one integer n (2<= n<= 10^5)-- the length of the array // a. // // The second line contains n integers a_1,a_2,...,a_n (0<= a_1<= ...<= a_n <= 5* 10^5)-- the array // a. // // It is guaranteed that the sum of n over all test cases does not exceed 2.5* 10^5, and the sum of // a_n over all test cases does not exceed 5* 10^5. // // Output // // For each test case, output the answer on a new line. // // Example /* input: 5 3 1 10 100 4 4 8 9 13 5 0 0 0 8 13 6 2 4 8 16 32 64 7 0 0 0 0 0 0 0 output: 81 3 1 2 0 */ // Note // // To simplify the notes, let \operatorname{sort}(a) denote the array you get by sorting a from // small to large. // // In the first test case, a=[1,10,100] at first. After the first operation, // a=\operatorname{sort}([10-1,100-10])=[9,90]. After the second operation, // a=\operatorname{sort}([90-9])=[81]. // // In the second test case, a=[4,8,9,13] at first. After the first operation, // a=\operatorname{sort}([8-4,9-8,13-9])=[1,4,4]. After the second operation, // a=\operatorname{sort}([4-1,4-4])=[0,3]. After the last operation, // a=\operatorname{sort}([3-0])=[3]. // import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.InputStreamReader; import java.lang.invoke.MethodHandles; import java.util.Map; import java.util.Random; import java.util.StringTokenizer; import java.util.TreeMap; public class C1708D { static final int MOD = 998244353; static final Random RAND = new Random(); static int solve(int[] a) { int n = a.length; if (n == 2) { return a[1] - a[0]; } TreeMap<Integer, Integer> vcm = new TreeMap<>(); for (int v : a) { vcm.put(v, vcm.getOrDefault(v, 0) + 1); } while (vcm.size() > 1) { TreeMap<Integer, Integer> next = new TreeMap<>(); boolean first = true; int prev = 0; for (Map.Entry<Integer, Integer> e : vcm.entrySet()) { int v = e.getKey(); int k = e.getValue(); if (first) { first = false; } else { int w = v - prev; next.put(w, next.getOrDefault(w, 0) + 1); } if (k > 1) { next.put(0, next.getOrDefault(0, 0) + k - 1); } prev = e.getKey(); } vcm = next; } int k = vcm.firstEntry().getValue(); return k > 1 ? 0 : vcm.firstKey(); } static boolean test = false; static void doTest() { if (!test) { return; } long t0 = System.currentTimeMillis(); System.out.format("%d msec\n", System.currentTimeMillis() - t0); System.exit(0); } public static void main(String[] args) { doTest(); MyScanner in = new MyScanner(); int T = in.nextInt(); for (int t = 1; t <= T; t++) { int n = in.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = in.nextInt(); } int ans = solve(a); System.out.println(ans); } } static void output(int[] a) { if (a == null) { System.out.println("-1"); return; } StringBuilder sb = new StringBuilder(); for (int v : a) { sb.append(v); sb.append(' '); if (sb.length() > 500) { System.out.print(sb.toString()); sb.setLength(0); } } System.out.println(sb.toString()); } static void myAssert(boolean cond) { if (!cond) { throw new RuntimeException("Unexpected"); } } static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { try { final String USERDIR = System.getProperty("user.dir"); String cname = MethodHandles.lookup().lookupClass().getCanonicalName().replace(".MyScanner", ""); cname = cname.lastIndexOf('.') > 0 ? cname.substring(cname.lastIndexOf('.') + 1) : cname; final File fin = new File(USERDIR + "/io/c" + cname.substring(1,5) + "/" + cname + ".in"); br = new BufferedReader(new InputStreamReader(fin.exists() ? new FileInputStream(fin) : System.in)); } catch (Exception e) { br = new BufferedReader(new InputStreamReader(System.in)); } } public String next() { try { while (st == null || !st.hasMoreElements()) { st = new StringTokenizer(br.readLine()); } return st.nextToken(); } catch (Exception e) { throw new RuntimeException(e); } } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } }
Java
["5\n\n3\n\n1 10 100\n\n4\n\n4 8 9 13\n\n5\n\n0 0 0 8 13\n\n6\n\n2 4 8 16 32 64\n\n7\n\n0 0 0 0 0 0 0"]
1 second
["81\n3\n1\n2\n0"]
NoteTo simplify the notes, let $$$\operatorname{sort}(a)$$$ denote the array you get by sorting $$$a$$$ from small to large.In the first test case, $$$a=[1,10,100]$$$ at first. After the first operation, $$$a=\operatorname{sort}([10-1,100-10])=[9,90]$$$. After the second operation, $$$a=\operatorname{sort}([90-9])=[81]$$$.In the second test case, $$$a=[4,8,9,13]$$$ at first. After the first operation, $$$a=\operatorname{sort}([8-4,9-8,13-9])=[1,4,4]$$$. After the second operation, $$$a=\operatorname{sort}([4-1,4-4])=[0,3]$$$. After the last operation, $$$a=\operatorname{sort}([3-0])=[3]$$$.
Java 11
standard input
[ "brute force", "sortings" ]
499b1440d8bb528d089724910e37e226
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1\le t\le 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2\le n\le 10^5$$$) — the length of the array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1,a_2,\dots,a_n$$$ ($$$0\le a_1\le \ldots\le a_n \le 5\cdot 10^5$$$) — the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2.5\cdot 10^5$$$, and the sum of $$$a_n$$$ over all test cases does not exceed $$$5\cdot 10^5$$$.
1,900
For each test case, output the answer on a new line.
standard output
PASSED
41c63083e98f2e9b9ac3925ef5d933f7
train_108.jsonl
1657982100
You are given an array $$$a$$$ consisting of $$$n$$$ non-negative integers. It is guaranteed that $$$a$$$ is sorted from small to large.For each operation, we generate a new array $$$b_i=a_{i+1}-a_{i}$$$ for $$$1 \le i &lt; n$$$. Then we sort $$$b$$$ from small to large, replace $$$a$$$ with $$$b$$$, and decrease $$$n$$$ by $$$1$$$.After performing $$$n-1$$$ operations, $$$n$$$ becomes $$$1$$$. You need to output the only integer in array $$$a$$$ (that is to say, you need to output $$$a_1$$$).
256 megabytes
import java.io.*; import java.util.*; public class Main { public static void main(String[] args) throws IOException { //BufferedReader f = new BufferedReader(new FileReader("uva.in")); //PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("milkvisits.out"))); BufferedReader f = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); int t = Integer.parseInt(f.readLine()); while(t-- > 0) { int n = Integer.parseInt(f.readLine()); StringTokenizer st = new StringTokenizer(f.readLine()); TreeMap<Integer, Integer> a = new TreeMap<>(); for(int i = 0; i < n; i++) { int temp = Integer.parseInt(st.nextToken()); a.put(temp, a.getOrDefault(temp, 0)+1); } int total = n; while(total > 1) { int zeros = 0; TreeMap<Integer, Integer> b = new TreeMap<>(); int prev = -1; for(int i: a.keySet()) { zeros += a.get(i)-1; if(prev != -1) { b.put(i-prev, b.getOrDefault(i-prev, 0)+1); } prev = i; } if(zeros > 0) { b.put(0, zeros); } a = b; total = 0; for(int i: b.values()) { total += i; } } for(int i: a.keySet()) { out.println(i); } } f.close(); out.close(); } }
Java
["5\n\n3\n\n1 10 100\n\n4\n\n4 8 9 13\n\n5\n\n0 0 0 8 13\n\n6\n\n2 4 8 16 32 64\n\n7\n\n0 0 0 0 0 0 0"]
1 second
["81\n3\n1\n2\n0"]
NoteTo simplify the notes, let $$$\operatorname{sort}(a)$$$ denote the array you get by sorting $$$a$$$ from small to large.In the first test case, $$$a=[1,10,100]$$$ at first. After the first operation, $$$a=\operatorname{sort}([10-1,100-10])=[9,90]$$$. After the second operation, $$$a=\operatorname{sort}([90-9])=[81]$$$.In the second test case, $$$a=[4,8,9,13]$$$ at first. After the first operation, $$$a=\operatorname{sort}([8-4,9-8,13-9])=[1,4,4]$$$. After the second operation, $$$a=\operatorname{sort}([4-1,4-4])=[0,3]$$$. After the last operation, $$$a=\operatorname{sort}([3-0])=[3]$$$.
Java 11
standard input
[ "brute force", "sortings" ]
499b1440d8bb528d089724910e37e226
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1\le t\le 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2\le n\le 10^5$$$) — the length of the array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1,a_2,\dots,a_n$$$ ($$$0\le a_1\le \ldots\le a_n \le 5\cdot 10^5$$$) — the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2.5\cdot 10^5$$$, and the sum of $$$a_n$$$ over all test cases does not exceed $$$5\cdot 10^5$$$.
1,900
For each test case, output the answer on a new line.
standard output
PASSED
2d1544656b97605982d0b55e1cd9005c
train_108.jsonl
1657982100
You are given an array $$$a$$$ consisting of $$$n$$$ non-negative integers. It is guaranteed that $$$a$$$ is sorted from small to large.For each operation, we generate a new array $$$b_i=a_{i+1}-a_{i}$$$ for $$$1 \le i &lt; n$$$. Then we sort $$$b$$$ from small to large, replace $$$a$$$ with $$$b$$$, and decrease $$$n$$$ by $$$1$$$.After performing $$$n-1$$$ operations, $$$n$$$ becomes $$$1$$$. You need to output the only integer in array $$$a$$$ (that is to say, you need to output $$$a_1$$$).
256 megabytes
//Utilities import java.io.*; import java.util.*; public class a { static int t; static int n; static ArrayList<Integer> a; public static void main(String[] args) throws IOException { t = in.iscan(); while (t-- > 0) { n = in.iscan(); a = new ArrayList<Integer>(); int zeroCnt = 0; for (int i = 0; i < n; i++) { int x = in.iscan(); if (x > 0) a.add(x); else zeroCnt++; } while (a.size() > 1) { ArrayList<Integer> b = new ArrayList<Integer>(); int sz = a.size(); int min = a.get(0); int addZeroCnt = 0; for (int j = 0; j < sz-1; j++) { int dif = a.get(j+1) - a.get(j); if (dif > 0) { b.add(dif); } else { addZeroCnt++; } } if (zeroCnt > 0) { b.add(min); zeroCnt--; } Collections.sort(b); a = new ArrayList<Integer>(b); zeroCnt += addZeroCnt; // out.println(a); } if (!a.isEmpty()) out.println(a.get(0)); else out.println(0); } out.close(); } static INPUT in = new INPUT(System.in); static PrintWriter out = new PrintWriter(System.out); private static class INPUT { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar, numChars; public INPUT (InputStream stream) { this.stream = stream; } public INPUT (String file) throws IOException { this.stream = new FileInputStream (file); } public int cscan () throws IOException { if (curChar >= numChars) { curChar = 0; numChars = stream.read (buf); } if (numChars == -1) return numChars; return buf[curChar++]; } public int iscan () throws IOException { int c = cscan (), sgn = 1; while (space (c)) c = cscan (); if (c == '-') { sgn = -1; c = cscan (); } int res = 0; do { res = (res << 1) + (res << 3); res += c - '0'; c = cscan (); } while (!space (c)); return res * sgn; } public String sscan () throws IOException { int c = cscan (); while (space (c)) c = cscan (); StringBuilder res = new StringBuilder (); do { res.appendCodePoint (c); c = cscan (); } while (!space (c)); return res.toString (); } public double dscan () throws IOException { int c = cscan (), sgn = 1; while (space (c)) c = cscan (); if (c == '-') { sgn = -1; c = cscan (); } double res = 0; while (!space (c) && c != '.') { if (c == 'e' || c == 'E') return res * UTILITIES.fast_pow (10, iscan ()); res *= 10; res += c - '0'; c = cscan (); } if (c == '.') { c = cscan (); double m = 1; while (!space (c)) { if (c == 'e' || c == 'E') return res * UTILITIES.fast_pow (10, iscan ()); m /= 10; res += (c - '0') * m; c = cscan (); } } return res * sgn; } public long lscan () throws IOException { int c = cscan (), sgn = 1; while (space (c)) c = cscan (); if (c == '-') { sgn = -1; c = cscan (); } long res = 0; do { res = (res << 1) + (res << 3); res += c - '0'; c = cscan (); } while (!space (c)); return res * sgn; } public boolean space (int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } public static class UTILITIES { static final double EPS = 10e-6; public static void sort(int[] a, boolean increasing) { ArrayList<Integer> arr = new ArrayList<Integer>(); int n = a.length; for (int i = 0; i < n; i++) { arr.add(a[i]); } Collections.sort(arr); for (int i = 0; i < n; i++) { if (increasing) { a[i] = arr.get(i); } else { a[i] = arr.get(n-1-i); } } } public static void sort(long[] a, boolean increasing) { ArrayList<Long> arr = new ArrayList<Long>(); int n = a.length; for (int i = 0; i < n; i++) { arr.add(a[i]); } Collections.sort(arr); for (int i = 0; i < n; i++) { if (increasing) { a[i] = arr.get(i); } else { a[i] = arr.get(n-1-i); } } } public static void sort(double[] a, boolean increasing) { ArrayList<Double> arr = new ArrayList<Double>(); int n = a.length; for (int i = 0; i < n; i++) { arr.add(a[i]); } Collections.sort(arr); for (int i = 0; i < n; i++) { if (increasing) { a[i] = arr.get(i); } else { a[i] = arr.get(n-1-i); } } } public static int lower_bound (int[] arr, int x) { int low = 0, high = arr.length, mid = -1; while (low < high) { mid = (low + high) / 2; if (arr[mid] >= x) high = mid; else low = mid + 1; } return low; } public static int upper_bound (int[] arr, int x) { int low = 0, high = arr.length, mid = -1; while (low < high) { mid = (low + high) / 2; if (arr[mid] > x) high = mid; else low = mid + 1; } return low; } public static void updateMap(HashMap<Integer, Integer> map, int key, int v) { if (!map.containsKey(key)) { map.put(key, v); } else { map.put(key, map.get(key) + v); } if (map.get(key) == 0) { map.remove(key); } } public static long gcd (long a, long b) { return b == 0 ? a : gcd (b, a % b); } public static long lcm (long a, long b) { return a * b / gcd (a, b); } public static long fast_pow_mod (long b, long x, int mod) { if (x == 0) return 1; if (x == 1) return b; if (x % 2 == 0) return fast_pow_mod (b * b % mod, x / 2, mod) % mod; return b * fast_pow_mod (b * b % mod, x / 2, mod) % mod; } public static long fast_pow (long b, long x) { if (x == 0) return 1; if (x == 1) return b; if (x % 2 == 0) return fast_pow (b * b, x / 2); return b * fast_pow (b * b, x / 2); } public static long choose (long n, long k) { k = Math.min (k, n - k); long val = 1; for (int i = 0; i < k; ++i) val = val * (n - i) / (i + 1); return val; } public static long permute (int n, int k) { if (n < k) return 0; long val = 1; for (int i = 0; i < k; ++i) val = (val * (n - i)); return val; } // start of permutation and lower/upper bound template public static void nextPermutation(int[] nums) { //find first decreasing digit int mark = -1; for (int i = nums.length - 1; i > 0; i--) { if (nums[i] > nums[i - 1]) { mark = i - 1; break; } } if (mark == -1) { reverse(nums, 0, nums.length - 1); return; } int idx = nums.length-1; for (int i = nums.length-1; i >= mark+1; i--) { if (nums[i] > nums[mark]) { idx = i; break; } } swap(nums, mark, idx); reverse(nums, mark + 1, nums.length - 1); } public static void swap(int[] nums, int i, int j) { int t = nums[i]; nums[i] = nums[j]; nums[j] = t; } public static void reverse(int[] nums, int i, int j) { while (i < j) { swap(nums, i, j); i++; j--; } } static int lower_bound (int[] arr, int hi, int cmp) { int low = 0, high = hi, mid = -1; while (low < high) { mid = (low + high) / 2; if (arr[mid] >= cmp) high = mid; else low = mid + 1; } return low; } static int upper_bound (int[] arr, int hi, int cmp) { int low = 0, high = hi, mid = -1; while (low < high) { mid = (low + high) / 2; if (arr[mid] > cmp) high = mid; else low = mid + 1; } return low; } // end of permutation and lower/upper bound template } }
Java
["5\n\n3\n\n1 10 100\n\n4\n\n4 8 9 13\n\n5\n\n0 0 0 8 13\n\n6\n\n2 4 8 16 32 64\n\n7\n\n0 0 0 0 0 0 0"]
1 second
["81\n3\n1\n2\n0"]
NoteTo simplify the notes, let $$$\operatorname{sort}(a)$$$ denote the array you get by sorting $$$a$$$ from small to large.In the first test case, $$$a=[1,10,100]$$$ at first. After the first operation, $$$a=\operatorname{sort}([10-1,100-10])=[9,90]$$$. After the second operation, $$$a=\operatorname{sort}([90-9])=[81]$$$.In the second test case, $$$a=[4,8,9,13]$$$ at first. After the first operation, $$$a=\operatorname{sort}([8-4,9-8,13-9])=[1,4,4]$$$. After the second operation, $$$a=\operatorname{sort}([4-1,4-4])=[0,3]$$$. After the last operation, $$$a=\operatorname{sort}([3-0])=[3]$$$.
Java 11
standard input
[ "brute force", "sortings" ]
499b1440d8bb528d089724910e37e226
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1\le t\le 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2\le n\le 10^5$$$) — the length of the array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1,a_2,\dots,a_n$$$ ($$$0\le a_1\le \ldots\le a_n \le 5\cdot 10^5$$$) — the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2.5\cdot 10^5$$$, and the sum of $$$a_n$$$ over all test cases does not exceed $$$5\cdot 10^5$$$.
1,900
For each test case, output the answer on a new line.
standard output
PASSED
eed68d727561eb56572cad1bbb6efe70
train_108.jsonl
1657982100
You are given an array $$$a$$$ consisting of $$$n$$$ non-negative integers. It is guaranteed that $$$a$$$ is sorted from small to large.For each operation, we generate a new array $$$b_i=a_{i+1}-a_{i}$$$ for $$$1 \le i &lt; n$$$. Then we sort $$$b$$$ from small to large, replace $$$a$$$ with $$$b$$$, and decrease $$$n$$$ by $$$1$$$.After performing $$$n-1$$$ operations, $$$n$$$ becomes $$$1$$$. You need to output the only integer in array $$$a$$$ (that is to say, you need to output $$$a_1$$$).
256 megabytes
import java.util.*; import java.util.Map.Entry; import javax.swing.ToolTipManager; import org.xml.sax.HandlerBase; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.math.*; import java.sql.Array; public class Simple{ public static class Node{ int v; int val; public Node(int v,int val){ this.val = val; this.v = v; } } static final Random random=new Random(); static class FastReader{ BufferedReader br; StringTokenizer st; public FastReader(){ br=new BufferedReader(new InputStreamReader(System.in)); } String next(){ while(st==null || !st.hasMoreTokens()){ try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt(){ return Integer.parseInt(next()); } long nextLong(){ return Long.parseLong(next()); } double nextDouble(){ return Double.parseDouble(next()); } String nextLine(){ String str=""; try { str=br.readLine().trim(); } catch (Exception e) { e.printStackTrace(); } return str; } } static class FastWriter { private final BufferedWriter bw; public FastWriter() { this.bw = new BufferedWriter(new OutputStreamWriter(System.out)); } public void print(Object object) throws IOException { bw.append("" + object); } public void println(Object object) throws IOException { print(object); bw.append("\n"); } public void close() throws IOException { bw.close(); } } static void ruffleSort(int[] a) { int n=a.length; for (int i=0; i<n; i++) { int oi=random.nextInt(n), temp=a[oi]; a[oi]=a[i]; a[i]=temp; } Arrays.sort(a); } static void ruffleSort(long[] a) { int n=a.length; for (int i=0; i<n; i++) { long oi=random.nextInt(n), temp=a[(int)oi]; a[(int)oi]=a[i]; a[i]=temp; } Arrays.sort(a); } public static class Pair implements Comparable<Pair>{ int x; int y; public Pair(int x,int y){ this.x = x; this.y = y; } public int compareTo(Pair other){ return this.y - other.y; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + x; result = prime * result + y; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Pair other = (Pair) obj; if (x != other.x) return false; if (y != other.y) return false; return true; } // public boolean equals(Pair other){ // if(this.x == other.x && this.y == other.y)return true; // return false; // } // public int hashCode(){ // return 31*x + y; // } // @Override // public int compareTo(Simple.Pair o) { // // TODO Auto-generated method stub // return 0; // } } static long power(long x, long y, long p) { // Initialize result long res = 1; // Update x if it is more than or // equal to p x = x % p; while (y > 0) { // If y is odd, multiply x // with result if (y % 2 == 1) res = (res * x) % p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return res; } // Returns n^(-1) mod p static long modInverse(long n, long p) { return power(n, p - 2, p); } static long[] fac = new long[100000 + 1]; // Returns nCr % p using Fermat's // little theorem. static long nCrModPFermat(long n, long r, long p) { if (n<r) return 0; // Base case if (r == 0) return 1; // Fill factorial array so that we // can find all factorial of r, n // and n-r return (fac[(int)n] * modInverse(fac[(int)r], p) % p * modInverse(fac[(int)n - (int)r], p) % p) % p; } static int nCrModp(int n, int r, int p) { if (r > n - r) r = n - r; // The array C is going to store last // row of pascal triangle at the end. // And last entry of last row is nCr int C[] = new int[r + 1]; C[0] = 1; // Top row of Pascal Triangle // One by constructs remaining rows of Pascal // Triangle from top to bottom for (int i = 1; i <= n; i++) { // Fill entries of current row using previous // row values for (int j = Math.min(i, r); j > 0; j--) // nCj = (n-1)Cj + (n-1)C(j-1); C[j] = (C[j] + C[j - 1]) % p; } return C[r]; } static int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } static long gcd_long(long a, long b) { // Everything divides 0 if (a == 0) return b; if (b == 0) return a; // base case if (a == b) return a; // a is greater if (a > b) return gcd_long(a-b, b); return gcd_long(a, b-a); } // public static int helper(int arr[],int n ,int i,int j,int dp[][]){ // if(i==0 || j==0)return 0; // if(dp[i][j]!=-1){ // return dp[i][j]; // } // if(helper(arr, n, i-1, j-1, dp)>=0){ // return dp[i][j]=Math.max(helper(arr, n, i-1, j-1,dp)+arr[i-1], helper(arr, n, i-1, j,dp)); // } // return dp[i][j] = helper(arr, n, i-1, j,dp); // } // public static void dfs(ArrayList<ArrayList<Integer>> al,int levelcount[],int node,int count){ // levelcount[count]++; // for(Integer x : al.get(node)){ // dfs(al, levelcount, x, count+1); // } // } public static long __gcd(long a, long b) { if (b == 0) return a; return __gcd(b, a % b); } public static class DSU{ int n; int par[]; int rank[]; public DSU(int n){ this.n = n; par = new int[n+1]; rank = new int[n+1]; for(int i=1;i<=n;i++){ par[i] = i ; rank[i] = 0; } } public int findPar(int node){ if(node==par[node]){ return node; } return par[node] = findPar(par[node]);//path compression } public void union(int u,int v){ u = findPar(u); v = findPar(v); if(rank[u]<rank[v]){ par[u] = v; } else if(rank[u]>rank[v]){ par[v] = u; } else{ par[v] = u; rank[u]++; } } } public static boolean isPallindrome(char[] arr,int n,boolean vis[]){ int i=0; int j= n-1; while(i<j){ if(vis[i])i++; else if(vis[j])j--; else{ if(arr[i]!=arr[j])return false; i++; j--; } } return true; } public static List<List<Integer>> permute(int[] nums) { List<Integer> list = new ArrayList<>(); List<List<Integer>> ans = new ArrayList<>(); helper(ans,list,nums,nums.length); return ans; } public static void helper(List<List<Integer>> ans,List<Integer> list,int nums[],int n){ if(list.size()==n){ ans.add(new ArrayList<>(list)); return; } for(int i=0;i<n;i++){ if(!list.contains(nums[i])){ list.add(nums[i]); helper(ans,list,nums,n); list.remove(list.size()-1); } } } static int level = 0; static ArrayList<Integer> nodes; public static int printShortestPath(Map<Integer,Integer> par, int s, int d) { level = 0; // If we reached root of shortest path tree if (par.get(s) == -1) { System.out.printf("Shortest Path between"+ "%d and %d is %s ", s, d, s); return level; } printShortestPath(par, par.get(s), d); level++; // if (s < this.V) // System.out.printf("%d ", s); return level; } // finds shortest path from source vertex 's' to // destination vertex 'd'. // This function mainly does BFS and prints the // shortest path from src to dest. It is assumed // that weight of every edge is 1 public static void swap(char arr[],int i){ char c = arr[i]; arr[i] = arr[i+1]; arr[i+1] = c; } public static String mul(String str,int n){ int carry = 0; StringBuilder muli = new StringBuilder(); for(int i=n-1;i>=0;i--){ int val = str.charAt(i) - '0'; int ans = val*2 + carry; carry = ans/10; ans = ans%10; char c = (char)(ans + '0'); muli.append(c); } if(carry!=0){ muli.append((char)(carry + '0')); } muli.reverse(); return muli.toString(); } static boolean isSmaller(String str1, String str2) { // Calculate lengths of both string int n1 = str1.length(), n2 = str2.length(); if (n1 < n2) return true; if (n2 < n1) return false; for (int i = 0; i < n1; i++) if (str1.charAt(i) < str2.charAt(i)) return true; else if (str1.charAt(i) > str2.charAt(i)) return false; return false; } // Function for find difference of larger numbers static String findDiff(String str1, String str2) { // Before proceeding further, make sure str1 // is not smaller if (isSmaller(str1, str2)) { String t = str1; str1 = str2; str2 = t; } // Take an empty string for storing result String str = ""; // Calculate length of both string int n1 = str1.length(), n2 = str2.length(); // Reverse both of strings str1 = new StringBuilder(str1).reverse().toString(); str2 = new StringBuilder(str2).reverse().toString(); int carry = 0; // Run loop till small string length // and subtract digit of str1 to str2 for (int i = 0; i < n2; i++) { // Do school mathematics, compute difference of // current digits int sub = ((int)(str1.charAt(i) - '0') - (int)(str2.charAt(i) - '0') - carry); // If subtraction is less then zero // we add then we add 10 into sub and // take carry as 1 for calculating next step if (sub < 0) { sub = sub + 10; carry = 1; } else carry = 0; str += (char)(sub + '0'); } // subtract remaining digits of larger number for (int i = n2; i < n1; i++) { int sub = ((int)(str1.charAt(i) - '0') - carry); // if the sub value is -ve, then make it // positive if (sub < 0) { sub = sub + 10; carry = 1; } else carry = 0; str += (char)(sub + '0'); } // reverse resultant string return new StringBuilder(str).reverse().toString(); } public static double cal1(double x1,double x2,double y1,double y2){ double x = Math.abs(x1 - x2); double y = Math.abs(y1 - y2); double ans = x*x + y*y; return Math.sqrt(ans); } static final int MAXN = 100001; // stores smallest prime factor for every number static int spf[] = new int[MAXN]; // Calculating SPF (Smallest Prime Factor) for every // number till MAXN. // Time Complexity : O(nloglogn) static void sieve() { spf[1] = 1; for (int i=2; i<MAXN; i++) // marking smallest prime factor for every // number to be itself. spf[i] = i; // separately marking spf for every even // number as 2 for (int i=4; i<MAXN; i+=2) spf[i] = 2; for (int i=3; i*i<MAXN; i++) { // checking if i is prime if (spf[i] == i) { // marking SPF for all numbers divisible by i for (int j=i*i; j<MAXN; j+=i) // marking spf[j] if it is not // previously marked if (spf[j]==j) spf[j] = i; } } } // A O(log n) function returning primefactorization // by dividing by smallest prime factor at every step static Vector<Integer> getFactorization(int x) { Vector<Integer> ret = new Vector<>(); while (x != 1) { ret.add(spf[x]); x = x / spf[x]; } return ret; } public static long dfs(long index,int currIndex,long arr[][],int n){ if(currIndex==-1)return 1; if(index <=n){ return index; } if(index< arr[currIndex][3]){ return dfs(index, currIndex -1 , arr, n); } else{ long nindex = arr[currIndex][0] + index - arr[currIndex][3]; return dfs(nindex, currIndex-1, arr, n); } } public static void main(String args[]){ // try { // FastReader s=new FastReader(); // FastWriter out = new FastWriter(); Scanner s = new Scanner(System.in); int testCases=s.nextInt(); // int testCases = 1; // sieve(); // int something = 0; while(testCases-- > 0){ // counter++; int n = s.nextInt(); int arr[] = new int[n]; for(int i=0;i<n;i++){ arr[i] = s.nextInt(); } int size = n; PriorityQueue<Integer> pq = new PriorityQueue<>(); for(Integer x : arr)pq.add(x); // PriorityQueue<Integer> pq1 = new PriorityQueue<>(); int ans = 0; int countzero = 0; while(pq.size()!=0){ ArrayList<Integer> al = new ArrayList<>(); while(pq.isEmpty()==false){ al.add(pq.poll()); } int count = 0; if(countzero>0){ pq.add(al.get(0)); countzero--; } for(int i=0;i<al.size()-1;i++){ int dif = al.get(i+1) - al.get(i); if(dif!=0){ pq.add(dif); if(dif == 1)count++; } else{ countzero++; } } if(pq.size()==1){ ans = pq.poll(); break; } } System.out.println(ans); } // } // catch (Exception e) { // System.out.println(e.toString()); // // System.out.println("Eh"); // return; // } } } /* 1 3 4 5 2 2 4 3 5 1 */
Java
["5\n\n3\n\n1 10 100\n\n4\n\n4 8 9 13\n\n5\n\n0 0 0 8 13\n\n6\n\n2 4 8 16 32 64\n\n7\n\n0 0 0 0 0 0 0"]
1 second
["81\n3\n1\n2\n0"]
NoteTo simplify the notes, let $$$\operatorname{sort}(a)$$$ denote the array you get by sorting $$$a$$$ from small to large.In the first test case, $$$a=[1,10,100]$$$ at first. After the first operation, $$$a=\operatorname{sort}([10-1,100-10])=[9,90]$$$. After the second operation, $$$a=\operatorname{sort}([90-9])=[81]$$$.In the second test case, $$$a=[4,8,9,13]$$$ at first. After the first operation, $$$a=\operatorname{sort}([8-4,9-8,13-9])=[1,4,4]$$$. After the second operation, $$$a=\operatorname{sort}([4-1,4-4])=[0,3]$$$. After the last operation, $$$a=\operatorname{sort}([3-0])=[3]$$$.
Java 11
standard input
[ "brute force", "sortings" ]
499b1440d8bb528d089724910e37e226
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1\le t\le 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2\le n\le 10^5$$$) — the length of the array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1,a_2,\dots,a_n$$$ ($$$0\le a_1\le \ldots\le a_n \le 5\cdot 10^5$$$) — the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2.5\cdot 10^5$$$, and the sum of $$$a_n$$$ over all test cases does not exceed $$$5\cdot 10^5$$$.
1,900
For each test case, output the answer on a new line.
standard output
PASSED
422ae79d7d714871b210b4c4d856ad43
train_108.jsonl
1657982100
You are given an array $$$a$$$ consisting of $$$n$$$ non-negative integers. It is guaranteed that $$$a$$$ is sorted from small to large.For each operation, we generate a new array $$$b_i=a_{i+1}-a_{i}$$$ for $$$1 \le i &lt; n$$$. Then we sort $$$b$$$ from small to large, replace $$$a$$$ with $$$b$$$, and decrease $$$n$$$ by $$$1$$$.After performing $$$n-1$$$ operations, $$$n$$$ becomes $$$1$$$. You need to output the only integer in array $$$a$$$ (that is to say, you need to output $$$a_1$$$).
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Comparator; public class DifferenceArray { /* XqnbwZPKcYZgS6Dv43F1xCyaWzekaw7DAlE0lECn+9uoFKfCeFcSralYFcgaMLe157XJfdm5fP5lDd9ZDu5GhmKrCZasI2xq0h73lK6cLkvLaE2o+demx5UADQV08FafDNzQt5wR28cpsO3hu4RCPh5f5msSTMYf/jSP9W8v3KvZMhiuegOlPaW+DmQeRI2AsaP5P1xFRnxSUbA6AhWMjg== */ public static void main (String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(br.readLine()); while (t-- > 0) { String[] st = br.readLine().split(" "); int n = Integer.parseInt(st[0]); String[] str = br.readLine().split(" "); ArrayList<Long> a = new ArrayList<>(); for(int i = 0; i < n; i++) { a.add(Long.parseLong(str[i])); } a.sort(Comparator.reverseOrder()); long cnt0 = 0; while(true) { //cnt0 = 0; while(a.size() != 0 && a.get(a.size() - 1) == 0) { cnt0++; a.remove(a.size() - 1); } if(a.size() == 0) { System.out.println(0); break; } if(a.size() == 1) { System.out.println(a.get(0)); break; } ArrayList<Long> newList = new ArrayList<>(); for(int i = 1; i < a.size(); i++) { newList.add(a.get(i-1) - a.get(i)); } if(cnt0 != 0) { newList.add(a.get(a.size() - 1)); cnt0--; } newList.sort(Comparator.reverseOrder()); a = new ArrayList<>(newList); } } } }
Java
["5\n\n3\n\n1 10 100\n\n4\n\n4 8 9 13\n\n5\n\n0 0 0 8 13\n\n6\n\n2 4 8 16 32 64\n\n7\n\n0 0 0 0 0 0 0"]
1 second
["81\n3\n1\n2\n0"]
NoteTo simplify the notes, let $$$\operatorname{sort}(a)$$$ denote the array you get by sorting $$$a$$$ from small to large.In the first test case, $$$a=[1,10,100]$$$ at first. After the first operation, $$$a=\operatorname{sort}([10-1,100-10])=[9,90]$$$. After the second operation, $$$a=\operatorname{sort}([90-9])=[81]$$$.In the second test case, $$$a=[4,8,9,13]$$$ at first. After the first operation, $$$a=\operatorname{sort}([8-4,9-8,13-9])=[1,4,4]$$$. After the second operation, $$$a=\operatorname{sort}([4-1,4-4])=[0,3]$$$. After the last operation, $$$a=\operatorname{sort}([3-0])=[3]$$$.
Java 11
standard input
[ "brute force", "sortings" ]
499b1440d8bb528d089724910e37e226
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1\le t\le 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2\le n\le 10^5$$$) — the length of the array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1,a_2,\dots,a_n$$$ ($$$0\le a_1\le \ldots\le a_n \le 5\cdot 10^5$$$) — the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2.5\cdot 10^5$$$, and the sum of $$$a_n$$$ over all test cases does not exceed $$$5\cdot 10^5$$$.
1,900
For each test case, output the answer on a new line.
standard output
PASSED
cea12805dd856da0b72f6020d04c48eb
train_108.jsonl
1657982100
You are given an array $$$a$$$ consisting of $$$n$$$ non-negative integers. It is guaranteed that $$$a$$$ is sorted from small to large.For each operation, we generate a new array $$$b_i=a_{i+1}-a_{i}$$$ for $$$1 \le i &lt; n$$$. Then we sort $$$b$$$ from small to large, replace $$$a$$$ with $$$b$$$, and decrease $$$n$$$ by $$$1$$$.After performing $$$n-1$$$ operations, $$$n$$$ becomes $$$1$$$. You need to output the only integer in array $$$a$$$ (that is to say, you need to output $$$a_1$$$).
256 megabytes
// JAI SHREE RAM, HAR HAR MAHADEV, HARE KRISHNA import java.util.*; import java.util.Map.Entry; import java.util.stream.*; import java.lang.*; import java.math.BigInteger; import java.text.DecimalFormat; import java.io.*; public class CodeForces { static private final String INPUT = "input.txt"; static private final String OUTPUT = "output.txt"; static BufferedReader BR = new BufferedReader(new InputStreamReader(System.in)); static StringTokenizer ST; static PrintWriter out = new PrintWriter(System.out); static DecimalFormat df = new DecimalFormat("0.00000"); final static int MAX = Integer.MAX_VALUE, MIN = Integer.MIN_VALUE, mod = (int) (1e9 + 7); final static long LMAX = Long.MAX_VALUE, LMIN = Long.MIN_VALUE; final static long INF = (long) 1e18, Neg_INF = (long) -1e18; static Random rand = new Random(); // ======================= MAIN ================================== public static void main(String[] args) throws IOException { long time = System.currentTimeMillis(); boolean oj = System.getProperty("ONLINE_JUDGE") != null; // ==== start ==== input(); preprocess(); int t = 1; t = readInt(); while (t-- > 0) { solve(); } out.flush(); // ==== end ==== if (!oj) System.out.println(Arrays.deepToString(new Object[] { System.currentTimeMillis() - time + " ms" })); } private static void solve() throws IOException { int n = readInt(); int[] arr = readIntArray(n); for (int i = n - 2; i >= 0; i--) { boolean flag = false; int prev = arr[i + 1]; for (int j = i; j >= 0; j--) { flag = (arr[j] == 0); int tmp = arr[j]; arr[j] = prev - arr[j]; prev = tmp; if (flag) { Arrays.sort(arr, j, i + 1); break; } } if (!flag) Arrays.sort(arr, 0, i + 1); } out.println(arr[0]); } private static void preprocess() throws IOException { } // cd C:\Users\Eshan Bhatt\Visual Studio Code\Competitive Programming\CodeForces // javac CodeForces.java && java CodeForces // change Stack size -> java -Xss16M CodeForces.java // ==================== CUSTOM CLASSES ================================ static class Pair implements Comparable<Pair> { int first, second; Pair(int f, int s) { first = f; second = s; } public int compareTo(Pair o) { if (this.first == o.first) return this.second - o.second; return this.first - o.first; } @Override public boolean equals(Object obj) { if (obj == this) return true; if (obj == null) return false; if (this.getClass() != obj.getClass()) return false; Pair other = (Pair) (obj); if (this.first != other.first) return false; if (this.second != other.second) return false; return true; } @Override public int hashCode() { return this.first ^ this.second; } @Override public String toString() { return this.first + " " + this.second; } } static class DequeNode { DequeNode prev, next; int val; DequeNode(int val) { this.val = val; } DequeNode(int val, DequeNode prev, DequeNode next) { this.val = val; this.prev = prev; this.next = next; } } // ======================= FOR INPUT ================================== private static void input() { FileInputStream instream = null; PrintStream outstream = null; try { instream = new FileInputStream(INPUT); outstream = new PrintStream(new FileOutputStream(OUTPUT)); System.setIn(instream); System.setOut(outstream); } catch (Exception e) { System.err.println("Error Occurred."); } BR = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } static String next() throws IOException { while (ST == null || !ST.hasMoreTokens()) ST = new StringTokenizer(readLine()); return ST.nextToken(); } static long readLong() throws IOException { return Long.parseLong(next()); } static int readInt() throws IOException { return Integer.parseInt(next()); } static double readDouble() throws IOException { return Double.parseDouble(next()); } static char readCharacter() throws IOException { return next().charAt(0); } static String readString() throws IOException { return next(); } static String readLine() throws IOException { return BR.readLine().trim(); } static int[] readIntArray(int n) throws IOException { int[] arr = new int[n]; for (int i = 0; i < n; i++) arr[i] = readInt(); return arr; } static int[][] read2DIntArray(int n, int m) throws IOException { int[][] arr = new int[n][m]; for (int i = 0; i < n; i++) arr[i] = readIntArray(m); return arr; } static List<Integer> readIntList(int n) throws IOException { List<Integer> list = new ArrayList<>(n); for (int i = 0; i < n; i++) list.add(readInt()); return list; } static long[] readLongArray(int n) throws IOException { long[] arr = new long[n]; for (int i = 0; i < n; i++) arr[i] = readLong(); return arr; } static long[][] read2DLongArray(int n, int m) throws IOException { long[][] arr = new long[n][m]; for (int i = 0; i < n; i++) arr[i] = readLongArray(m); return arr; } static List<Long> readLongList(int n) throws IOException { List<Long> list = new ArrayList<>(n); for (int i = 0; i < n; i++) list.add(readLong()); return list; } static char[] readCharArray() throws IOException { return readString().toCharArray(); } static char[][] readMatrix(int n, int m) throws IOException { char[][] mat = new char[n][m]; for (int i = 0; i < n; i++) mat[i] = readCharArray(); return mat; } // ========================= FOR OUTPUT ================================== private static void printIList(List<Integer> list) { for (int i = 0; i < list.size(); i++) out.print(list.get(i) + " "); out.println(" "); } private static void printLList(List<Long> list) { for (int i = 0; i < list.size(); i++) out.print(list.get(i) + " "); out.println(" "); } private static void printIArray(int[] arr) { for (int i = 0; i < arr.length; i++) out.print(arr[i] + " "); out.println(" "); } private static void print2DIArray(int[][] arr) { for (int i = 0; i < arr.length; i++) printIArray(arr[i]); } private static void printLArray(long[] arr) { for (int i = 0; i < arr.length; i++) out.print(arr[i] + " "); out.println(" "); } private static void print2DLArray(long[][] arr) { for (int i = 0; i < arr.length; i++) printLArray(arr[i]); } private static void yes() { out.println("YES"); } private static void no() { out.println("NO"); } // ====================== TO CHECK IF STRING IS NUMBER ======================== private static boolean isInteger(String s) { try { Integer.parseInt(s); } catch (NumberFormatException e) { return false; } catch (NullPointerException e) { return false; } return true; } private static boolean isLong(String s) { try { Long.parseLong(s); } catch (NumberFormatException e) { return false; } catch (NullPointerException e) { return false; } return true; } // ==================== FASTER SORT ================================ private static void sort(int[] arr) { int n = arr.length; List<Integer> list = new ArrayList<>(n); for (int i = 0; i < n; i++) list.add(arr[i]); Collections.sort(list); for (int i = 0; i < n; i++) arr[i] = list.get(i); } private static void reverseSort(int[] arr) { int n = arr.length; List<Integer> list = new ArrayList<>(n); for (int i = 0; i < n; i++) list.add(arr[i]); Collections.sort(list, Collections.reverseOrder()); for (int i = 0; i < n; i++) arr[i] = list.get(i); } private static void sort(long[] arr) { int n = arr.length; List<Long> list = new ArrayList<>(n); for (int i = 0; i < n; i++) list.add(arr[i]); Collections.sort(list); for (int i = 0; i < n; i++) arr[i] = list.get(i); } private static void reverseSort(long[] arr) { int n = arr.length; List<Long> list = new ArrayList<>(n); for (int i = 0; i < n; i++) list.add(arr[i]); Collections.sort(list, Collections.reverseOrder()); for (int i = 0; i < n; i++) arr[i] = list.get(i); } // ==================== MATHEMATICAL FUNCTIONS =========================== private static int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } private static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } private static int lcm(int a, int b) { return (a / gcd(a, b)) * b; } private static long lcm(long a, long b) { return (a / gcd(a, b)) * b; } private static int mod_pow(long a, long b, int mod) { if (b == 0) return 1; int temp = mod_pow(a, b >> 1, mod); temp %= mod; temp = (int) ((1L * temp * temp) % mod); if ((b & 1) == 1) temp = (int) ((1L * temp * a) % mod); return temp; } private static long multiply(long a, long b) { return (((a % mod) * (b % mod)) % mod); } private static long divide(long a, long b) { return multiply(a, mod_pow(b, mod - 2, mod)); } private static boolean isPrime(long n) { for (long i = 2; i * i <= n; i++) if (n % i == 0) return false; return true; } private static long nCr(long n, long r) { if (n - r > r) r = n - r; long ans = 1L; for (long i = r + 1; i <= n; i++) ans *= i; for (long i = 2; i <= n - r; i++) ans /= i; return ans; } private static List<Integer> factors(int n) { List<Integer> list = new ArrayList<>(); for (int i = 1; 1L * i * i <= n; i++) if (n % i == 0) { list.add(i); if (i != n / i) list.add(n / i); } return list; } private static List<Long> factors(long n) { List<Long> list = new ArrayList<>(); for (long i = 1; i * i <= n; i++) if (n % i == 0) { list.add(i); if (i != n / i) list.add(n / i); } return list; } // ==================== Primes using Seive ===================== private static List<Integer> getPrimes(int n) { boolean[] prime = new boolean[n + 1]; Arrays.fill(prime, true); for (int i = 2; 1L * i * i <= n; i++) if (prime[i]) for (int j = i * i; j <= n; j += i) prime[j] = false; // return prime; List<Integer> list = new ArrayList<>(); for (int i = 2; i <= n; i++) if (prime[i]) list.add(i); return list; } private static int[] SeivePrime(int n) { int[] primes = new int[n]; for (int i = 0; i < n; i++) primes[i] = i; for (int i = 2; 1L * i * i < n; i++) { if (primes[i] != i) continue; for (int j = i * i; j < n; j += i) if (primes[j] == j) primes[j] = i; } return primes; } // ==================== STRING FUNCTIONS ================================ private static boolean isPalindrome(String str) { int i = 0, j = str.length() - 1; while (i < j) if (str.charAt(i++) != str.charAt(j--)) return false; return true; } // check if a is subsequence of b private static boolean isSubsequence(String a, String b) { int idx = 0; for (int i = 0; i < b.length() && idx < a.length(); i++) if (a.charAt(idx) == b.charAt(i)) idx++; return idx == a.length(); } private static String reverseString(String str) { StringBuilder sb = new StringBuilder(str); return sb.reverse().toString(); } private static String sortString(String str) { int[] arr = new int[256]; for (char ch : str.toCharArray()) arr[ch]++; StringBuilder sb = new StringBuilder(); for (int i = 0; i < 256; i++) while (arr[i]-- > 0) sb.append((char) i); return sb.toString(); } // ==================== LIS & LNDS ================================ private static int LIS(int arr[], int n) { List<Integer> list = new ArrayList<>(); for (int i = 0; i < n; i++) { int idx = find1(list, arr[i]); if (idx < list.size()) list.set(idx, arr[i]); else list.add(arr[i]); } return list.size(); } private static int find1(List<Integer> list, int val) { int ret = list.size(), i = 0, j = list.size() - 1; while (i <= j) { int mid = (i + j) / 2; if (list.get(mid) >= val) { ret = mid; j = mid - 1; } else { i = mid + 1; } } return ret; } private static int LNDS(int[] arr, int n) { List<Integer> list = new ArrayList<>(); for (int i = 0; i < n; i++) { int idx = find2(list, arr[i]); if (idx < list.size()) list.set(idx, arr[i]); else list.add(arr[i]); } return list.size(); } private static int find2(List<Integer> list, int val) { int ret = list.size(), i = 0, j = list.size() - 1; while (i <= j) { int mid = (i + j) / 2; if (list.get(mid) <= val) { i = mid + 1; } else { ret = mid; j = mid - 1; } } return ret; } // =============== Lower Bound & Upper Bound =========== // less than or equal private static int lower_bound(List<Integer> list, int val) { int ans = -1, lo = 0, hi = list.size() - 1; while (lo <= hi) { int mid = (lo + hi) / 2; if (list.get(mid) <= val) { ans = mid; lo = mid + 1; } else { hi = mid - 1; } } return ans; } private static int lower_bound(List<Long> list, long val) { int ans = -1, lo = 0, hi = list.size() - 1; while (lo <= hi) { int mid = (lo + hi) / 2; if (list.get(mid) <= val) { ans = mid; lo = mid + 1; } else { hi = mid - 1; } } return ans; } private static int lower_bound(int[] arr, int val) { int ans = -1, lo = 0, hi = arr.length - 1; while (lo <= hi) { int mid = (lo + hi) / 2; if (arr[mid] <= val) { ans = mid; lo = mid + 1; } else { hi = mid - 1; } } return ans; } private static int lower_bound(long[] arr, long val) { int ans = -1, lo = 0, hi = arr.length - 1; while (lo <= hi) { int mid = (lo + hi) / 2; if (arr[mid] <= val) { ans = mid; lo = mid + 1; } else { hi = mid - 1; } } return ans; } // greater than or equal private static int upper_bound(List<Integer> list, int val) { int ans = list.size(), lo = 0, hi = ans - 1; while (lo <= hi) { int mid = (lo + hi) / 2; if (list.get(mid) >= val) { ans = mid; hi = mid - 1; } else { lo = mid + 1; } } return ans; } private static int upper_bound(List<Long> list, long val) { int ans = list.size(), lo = 0, hi = ans - 1; while (lo <= hi) { int mid = (lo + hi) / 2; if (list.get(mid) >= val) { ans = mid; hi = mid - 1; } else { lo = mid + 1; } } return ans; } private static int upper_bound(int[] arr, int val) { int ans = arr.length, lo = 0, hi = ans - 1; while (lo <= hi) { int mid = (lo + hi) / 2; if (arr[mid] >= val) { ans = mid; hi = mid - 1; } else { lo = mid + 1; } } return ans; } private static int upper_bound(long[] arr, long val) { int ans = arr.length, lo = 0, hi = ans - 1; while (lo <= hi) { int mid = (lo + hi) / 2; if (arr[mid] >= val) { ans = mid; hi = mid - 1; } else { lo = mid + 1; } } return ans; } // ==================== UNION FIND ===================== private static int find(int x, int[] parent) { if (parent[x] == x) return x; return parent[x] = find(parent[x], parent); } private static boolean union(int x, int y, int[] parent, int[] rank) { int lx = find(x, parent), ly = find(y, parent); if (lx == ly) return false; if (rank[lx] > rank[ly]) parent[ly] = lx; else if (rank[lx] < rank[ly]) parent[lx] = ly; else { parent[lx] = ly; rank[ly]++; } return true; } // ==================== TRIE ================================ static class Trie { class Node { Node[] children; boolean isEnd; Node() { children = new Node[26]; } } Node root; Trie() { root = new Node(); } void insert(String word) { Node curr = root; for (char ch : word.toCharArray()) { if (curr.children[ch - 'a'] == null) curr.children[ch - 'a'] = new Node(); curr = curr.children[ch - 'a']; } curr.isEnd = true; } boolean find(String word) { Node curr = root; for (char ch : word.toCharArray()) { if (curr.children[ch - 'a'] == null) return false; curr = curr.children[ch - 'a']; } return curr.isEnd; } } // ================== SEGMENT TREE (RANGE SUM & RANGE UPDATE) ================== public static class SegmentTree { int n; long[] arr, tree, lazy; SegmentTree(long arr[]) { this.arr = arr; this.n = arr.length; this.tree = new long[(n << 2)]; this.lazy = new long[(n << 2)]; build(1, 0, n - 1); } void build(int id, int start, int end) { if (start == end) tree[id] = arr[start]; else { int mid = (start + end) / 2, left = (id << 1), right = left + 1; build(left, start, mid); build(right, mid + 1, end); tree[id] = tree[left] + tree[right]; } } void update(int l, int r, long val) { update(1, 0, n - 1, l, r, val); } void update(int id, int start, int end, int l, int r, long val) { distribute(id, start, end); if (end < l || r < start) return; if (start == end) tree[id] += val; else if (l <= start && end <= r) { lazy[id] += val; distribute(id, start, end); } else { int mid = (start + end) / 2, left = (id << 1), right = left + 1; update(left, start, mid, l, r, val); update(right, mid + 1, end, l, r, val); tree[id] = tree[left] + tree[right]; } } long query(int l, int r) { return query(1, 0, n - 1, l, r); } long query(int id, int start, int end, int l, int r) { if (end < l || r < start) return 0L; distribute(id, start, end); if (start == end) return tree[id]; else if (l <= start && end <= r) return tree[id]; else { int mid = (start + end) / 2, left = (id << 1), right = left + 1; return query(left, start, mid, l, r) + query(right, mid + 1, end, l, r); } } void distribute(int id, int start, int end) { if (start == end) tree[id] += lazy[id]; else { tree[id] += lazy[id] * (end - start + 1); lazy[(id << 1)] += lazy[id]; lazy[(id << 1) + 1] += lazy[id]; } lazy[id] = 0; } } // ==================== FENWICK TREE ================================ static class FT { int n; int[] arr; int[] tree; FT(int[] arr, int n) { this.arr = arr; this.n = n; this.tree = new int[n + 1]; for (int i = 1; i <= n; i++) { update(i, arr[i - 1]); } } FT(int n) { this.n = n; this.tree = new int[n + 1]; } // 1 based indexing void update(int idx, int val) { while (idx <= n) { tree[idx] += val; idx += idx & -idx; } } // 1 based indexing int query(int l, int r) { return getSum(r) - getSum(l - 1); } int getSum(int idx) { int ans = 0; while (idx > 0) { ans += tree[idx]; idx -= idx & -idx; } return ans; } } // ==================== BINARY INDEX TREE ================================ static class BIT { long[][] tree; int n, m; BIT(int[][] mat, int n, int m) { this.n = n; this.m = m; tree = new long[n + 1][m + 1]; for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { update(i, j, mat[i - 1][j - 1]); } } } void update(int x, int y, int val) { while (x <= n) { int t = y; while (t <= m) { tree[x][t] += val; t += t & -t; } x += x & -x; } } long query(int x1, int y1, int x2, int y2) { return getSum(x2, y2) - getSum(x1 - 1, y2) - getSum(x2, y1 - 1) + getSum(x1 - 1, y1 - 1); } long getSum(int x, int y) { long ans = 0L; while (x > 0) { int t = y; while (t > 0) { ans += tree[x][t]; t -= t & -t; } x -= x & -x; } return ans; } } }
Java
["5\n\n3\n\n1 10 100\n\n4\n\n4 8 9 13\n\n5\n\n0 0 0 8 13\n\n6\n\n2 4 8 16 32 64\n\n7\n\n0 0 0 0 0 0 0"]
1 second
["81\n3\n1\n2\n0"]
NoteTo simplify the notes, let $$$\operatorname{sort}(a)$$$ denote the array you get by sorting $$$a$$$ from small to large.In the first test case, $$$a=[1,10,100]$$$ at first. After the first operation, $$$a=\operatorname{sort}([10-1,100-10])=[9,90]$$$. After the second operation, $$$a=\operatorname{sort}([90-9])=[81]$$$.In the second test case, $$$a=[4,8,9,13]$$$ at first. After the first operation, $$$a=\operatorname{sort}([8-4,9-8,13-9])=[1,4,4]$$$. After the second operation, $$$a=\operatorname{sort}([4-1,4-4])=[0,3]$$$. After the last operation, $$$a=\operatorname{sort}([3-0])=[3]$$$.
Java 11
standard input
[ "brute force", "sortings" ]
499b1440d8bb528d089724910e37e226
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1\le t\le 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2\le n\le 10^5$$$) — the length of the array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1,a_2,\dots,a_n$$$ ($$$0\le a_1\le \ldots\le a_n \le 5\cdot 10^5$$$) — the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2.5\cdot 10^5$$$, and the sum of $$$a_n$$$ over all test cases does not exceed $$$5\cdot 10^5$$$.
1,900
For each test case, output the answer on a new line.
standard output
PASSED
0785631f7e6c096751bf1a6d56440fca
train_108.jsonl
1657982100
You are given an array $$$a$$$ consisting of $$$n$$$ non-negative integers. It is guaranteed that $$$a$$$ is sorted from small to large.For each operation, we generate a new array $$$b_i=a_{i+1}-a_{i}$$$ for $$$1 \le i &lt; n$$$. Then we sort $$$b$$$ from small to large, replace $$$a$$$ with $$$b$$$, and decrease $$$n$$$ by $$$1$$$.After performing $$$n-1$$$ operations, $$$n$$$ becomes $$$1$$$. You need to output the only integer in array $$$a$$$ (that is to say, you need to output $$$a_1$$$).
256 megabytes
import java.util.*; import java.io.*; public class Main { static ContestScanner sc = new ContestScanner(System.in); static PrintWriter pw = new PrintWriter(System.out); static StringBuilder sb = new StringBuilder(); static long mod = (long) 1e9 + 7; public static void main(String[] args) throws Exception { int T = sc.nextInt(); for(int i = 0; i < T; i++)solve(); //solve(); pw.flush(); } public static void solve() { int N = sc.nextInt(); int[] a = sc.nextIntArray(N); for(int i = N-2; i >= 0; --i){ int pre = a[i+1]; boolean ok = false; for(int j = i; j >= 0;--j){ ok = (a[j] == 0); a[j] = pre-a[j]; pre -= a[j]; if(ok){ Arrays.sort(a,j,i+1); break; } } if(!ok){ Arrays.sort(a,0,i+1); } } pw.println(a[0]); } static class GeekInteger { public static void save_sort(int[] array) { shuffle(array); Arrays.sort(array); } public static int[] shuffle(int[] array) { int n = array.length; Random random = new Random(); for (int i = 0, j; i < n; i++) { j = i + random.nextInt(n - i); int randomElement = array[j]; array[j] = array[i]; array[i] = randomElement; } return array; } public static void save_sort(long[] array) { shuffle(array); Arrays.sort(array); } public static long[] shuffle(long[] array) { int n = array.length; Random random = new Random(); for (int i = 0, j; i < n; i++) { j = i + random.nextInt(n - i); long randomElement = array[j]; array[j] = array[i]; array[i] = randomElement; } return array; } } } /** * refercence : https://github.com/NASU41/AtCoderLibraryForJava/blob/master/ContestIO/ContestScanner.java */ class ContestScanner { private final java.io.InputStream in; private final byte[] buffer = new byte[1024]; private int ptr = 0; private int buflen = 0; private static final long LONG_MAX_TENTHS = 922337203685477580L; private static final int LONG_MAX_LAST_DIGIT = 7; private static final int LONG_MIN_LAST_DIGIT = 8; public ContestScanner(java.io.InputStream in){ this.in = in; } public ContestScanner(java.io.File file) throws java.io.FileNotFoundException { this(new java.io.BufferedInputStream(new java.io.FileInputStream(file))); } public ContestScanner(){ this(System.in); } private boolean hasNextByte() { if (ptr < buflen) { return true; }else{ ptr = 0; try { buflen = in.read(buffer); } catch (java.io.IOException e) { e.printStackTrace(); } if (buflen <= 0) { return false; } } return true; } private int readByte() { if (hasNextByte()) return buffer[ptr++]; else return -1; } private static boolean isPrintableChar(int c) { return 33 <= c && c <= 126; } public boolean hasNext() { while(hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++; return hasNextByte(); } public String next() { if (!hasNext()) throw new java.util.NoSuchElementException(); StringBuilder sb = new StringBuilder(); int b = readByte(); while(isPrintableChar(b)) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } public long nextLong() { if (!hasNext()) throw new java.util.NoSuchElementException(); long n = 0; boolean minus = false; int b = readByte(); if (b == '-') { minus = true; b = readByte(); } if (b < '0' || '9' < b) { throw new NumberFormatException(); } while (true) { if ('0' <= b && b <= '9') { int digit = b - '0'; if (n >= LONG_MAX_TENTHS) { if (n == LONG_MAX_TENTHS) { if (minus) { if (digit <= LONG_MIN_LAST_DIGIT) { n = -n * 10 - digit; b = readByte(); if (!isPrintableChar(b)) { return n; } else if (b < '0' || '9' < b) { throw new NumberFormatException( String.format("%d%s... is not number", n, Character.toString(b)) ); } } } else { if (digit <= LONG_MAX_LAST_DIGIT) { n = n * 10 + digit; b = readByte(); if (!isPrintableChar(b)) { return n; } else if (b < '0' || '9' < b) { throw new NumberFormatException( String.format("%d%s... is not number", n, Character.toString(b)) ); } } } } throw new ArithmeticException( String.format("%s%d%d... overflows long.", minus ? "-" : "", n, digit) ); } n = n * 10 + digit; }else if(b == -1 || !isPrintableChar(b)){ return minus ? -n : n; }else{ throw new NumberFormatException(); } b = readByte(); } } public int nextInt() { long nl = nextLong(); if (nl < Integer.MIN_VALUE || nl > Integer.MAX_VALUE) throw new NumberFormatException(); return (int) nl; } public double nextDouble() { return Double.parseDouble(next()); } public long[] nextLongArray(int length){ long[] array = new long[length]; for(int i=0; i<length; i++) array[i] = this.nextLong(); return array; } public long[] nextLongArray(int length, java.util.function.LongUnaryOperator map){ long[] array = new long[length]; for(int i=0; i<length; i++) array[i] = map.applyAsLong(this.nextLong()); return array; } public int[] nextIntArray(int length){ int[] array = new int[length]; for(int i=0; i<length; i++) array[i] = this.nextInt(); return array; } public int[] nextIntArray(int length, java.util.function.IntUnaryOperator map){ int[] array = new int[length]; for(int i=0; i<length; i++) array[i] = map.applyAsInt(this.nextInt()); return array; } public double[] nextDoubleArray(int length){ double[] array = new double[length]; for(int i=0; i<length; i++) array[i] = this.nextDouble(); return array; } public double[] nextDoubleArray(int length, java.util.function.DoubleUnaryOperator map){ double[] array = new double[length]; for(int i=0; i<length; i++) array[i] = map.applyAsDouble(this.nextDouble()); return array; } public long[][] nextLongMatrix(int height, int width){ long[][] mat = new long[height][width]; for(int h=0; h<height; h++) for(int w=0; w<width; w++){ mat[h][w] = this.nextLong(); } return mat; } public int[][] nextIntMatrix(int height, int width){ int[][] mat = new int[height][width]; for(int h=0; h<height; h++) for(int w=0; w<width; w++){ mat[h][w] = this.nextInt(); } return mat; } public double[][] nextDoubleMatrix(int height, int width){ double[][] mat = new double[height][width]; for(int h=0; h<height; h++) for(int w=0; w<width; w++){ mat[h][w] = this.nextDouble(); } return mat; } public char[][] nextCharMatrix(int height, int width){ char[][] mat = new char[height][width]; for(int h=0; h<height; h++){ String s = this.next(); for(int w=0; w<width; w++){ mat[h][w] = s.charAt(w); } } return mat; } }
Java
["5\n\n3\n\n1 10 100\n\n4\n\n4 8 9 13\n\n5\n\n0 0 0 8 13\n\n6\n\n2 4 8 16 32 64\n\n7\n\n0 0 0 0 0 0 0"]
1 second
["81\n3\n1\n2\n0"]
NoteTo simplify the notes, let $$$\operatorname{sort}(a)$$$ denote the array you get by sorting $$$a$$$ from small to large.In the first test case, $$$a=[1,10,100]$$$ at first. After the first operation, $$$a=\operatorname{sort}([10-1,100-10])=[9,90]$$$. After the second operation, $$$a=\operatorname{sort}([90-9])=[81]$$$.In the second test case, $$$a=[4,8,9,13]$$$ at first. After the first operation, $$$a=\operatorname{sort}([8-4,9-8,13-9])=[1,4,4]$$$. After the second operation, $$$a=\operatorname{sort}([4-1,4-4])=[0,3]$$$. After the last operation, $$$a=\operatorname{sort}([3-0])=[3]$$$.
Java 11
standard input
[ "brute force", "sortings" ]
499b1440d8bb528d089724910e37e226
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1\le t\le 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2\le n\le 10^5$$$) — the length of the array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1,a_2,\dots,a_n$$$ ($$$0\le a_1\le \ldots\le a_n \le 5\cdot 10^5$$$) — the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2.5\cdot 10^5$$$, and the sum of $$$a_n$$$ over all test cases does not exceed $$$5\cdot 10^5$$$.
1,900
For each test case, output the answer on a new line.
standard output
PASSED
90f7a35ba7fe235f591dab3533636481
train_108.jsonl
1657982100
You are given an array $$$a$$$ consisting of $$$n$$$ non-negative integers. It is guaranteed that $$$a$$$ is sorted from small to large.For each operation, we generate a new array $$$b_i=a_{i+1}-a_{i}$$$ for $$$1 \le i &lt; n$$$. Then we sort $$$b$$$ from small to large, replace $$$a$$$ with $$$b$$$, and decrease $$$n$$$ by $$$1$$$.After performing $$$n-1$$$ operations, $$$n$$$ becomes $$$1$$$. You need to output the only integer in array $$$a$$$ (that is to say, you need to output $$$a_1$$$).
256 megabytes
import java.io.*; import java.util.*; public class CF1708D extends PrintWriter { CF1708D() { super(System.out); } Scanner sc = new Scanner(System.in); public static void main(String[] $) { CF1708D o = new CF1708D(); o.main(); o.flush(); } void main() { int t = sc.nextInt(); while (t-- > 0) { int n = sc.nextInt(); int[] aa = new int[n]; for (int i = 0; i < n; i++) aa[i] = sc.nextInt(); for (int h = 0; ; ) { while (h > 0 && aa[h] != 0) h--; while (h < n && aa[h] == 0) h++; if (h >= n - 1) break; for (int i = h; i < n; i++) if (i > 0) aa[i - 1] = aa[i] - aa[i - 1]; if (h > 0) h--; n--; Arrays.sort(aa, h, n); } println(aa[n - 1]); } } }
Java
["5\n\n3\n\n1 10 100\n\n4\n\n4 8 9 13\n\n5\n\n0 0 0 8 13\n\n6\n\n2 4 8 16 32 64\n\n7\n\n0 0 0 0 0 0 0"]
1 second
["81\n3\n1\n2\n0"]
NoteTo simplify the notes, let $$$\operatorname{sort}(a)$$$ denote the array you get by sorting $$$a$$$ from small to large.In the first test case, $$$a=[1,10,100]$$$ at first. After the first operation, $$$a=\operatorname{sort}([10-1,100-10])=[9,90]$$$. After the second operation, $$$a=\operatorname{sort}([90-9])=[81]$$$.In the second test case, $$$a=[4,8,9,13]$$$ at first. After the first operation, $$$a=\operatorname{sort}([8-4,9-8,13-9])=[1,4,4]$$$. After the second operation, $$$a=\operatorname{sort}([4-1,4-4])=[0,3]$$$. After the last operation, $$$a=\operatorname{sort}([3-0])=[3]$$$.
Java 11
standard input
[ "brute force", "sortings" ]
499b1440d8bb528d089724910e37e226
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1\le t\le 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2\le n\le 10^5$$$) — the length of the array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1,a_2,\dots,a_n$$$ ($$$0\le a_1\le \ldots\le a_n \le 5\cdot 10^5$$$) — the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2.5\cdot 10^5$$$, and the sum of $$$a_n$$$ over all test cases does not exceed $$$5\cdot 10^5$$$.
1,900
For each test case, output the answer on a new line.
standard output
PASSED
131c5376dd1fa580162791d6013916e9
train_108.jsonl
1657982100
You are given three integers $$$n$$$, $$$l$$$, and $$$r$$$. You need to construct an array $$$a_1,a_2,\dots,a_n$$$ ($$$l\le a_i\le r$$$) such that $$$\gcd(i,a_i)$$$ are all distinct or report there's no solution.Here $$$\gcd(x, y)$$$ denotes the greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.math.BigInteger; import java.util.*; import java.util.stream.Collectors; public class coding { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while(st == null || !st.hasMoreElements()) { try { String str = br.readLine(); if(str == null) throw new InputMismatchException(); st = new StringTokenizer(str); } 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(); } if(str == null) throw new InputMismatchException(); return str; } public BigInteger nextBigInteger() { // TODO Auto-generated method stub return null; } public void close() { // TODO Auto-generated method stub } } public static <K, V> K getKey(Map<K, V> map, V value) { for (Map.Entry<K, V> entry: map.entrySet()) { if (value.equals(entry.getValue())) { return entry.getKey(); } } return null; } public static int median(ArrayList<Integer> x) { int p=0; if(x.size()==1) { p=x.get(0); } else { p=x.get((x.size()-1)/2 ); } return p; } public static boolean palindrome(long x) { String s="",s1=""; while(x!=0) { s=s+x%10; x=x/10; } for(int i=0;i<s.length();i++) { s1=s1+s.charAt(s.length()-i-1); } if(s1.contentEquals(s)) { return true; } else { return false; } } static void reverse(String a[], int n) { String k="", t=""; for (int i = 0; i < n / 2; i++) { t = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = t; } } static int fact(int n) { int fact=1; int i=1; while(i<=n) { fact=fact*i; } return fact; } static int gcd(int y, int x) { while(x!=y) { if(x>y) { x=x-y; } else { y=y-x; } } return y; } public static void main(String args[] ) throws Exception { FastReader sc = new FastReader(); PrintWriter out = new PrintWriter(System.out); StringBuilder sb = new StringBuilder(); int t=sc.nextInt(); while(t-->0) { int n=sc.nextInt(); long l=sc.nextLong(); long r=sc.nextLong(); long l1=l,r1=r; long k1=l; long arr[]=new long[n]; boolean p=true; for(int i=0;i<n;i++) { long k=(long)i+1; if(l%k!=0) { l=l-l%k +k; } arr[i]=l; if(arr[i]>r) { p=false; break; } l=k1; } if(!p) { System.out.println("NO"); } else { System.out.println("YES"); for(int i=0;i<n;i++) { System.out.print(arr[i]+" "); } System.out.println(); } } } }
Java
["4\n5 1 5\n9 1000 2000\n10 30 35\n1 1000000000 1000000000"]
1 second
["YES\n1 2 3 4 5\nYES\n1145 1926 1440 1220 1230 1350 1001 1000 1233\nNO\nYES\n1000000000"]
NoteIn the first test case, $$$\gcd(1,a_1),\gcd(2,a_2),\ldots,\gcd(5,a_5)$$$ are equal to $$$1$$$, $$$2$$$, $$$3$$$, $$$4$$$, $$$5$$$, respectively.
Java 11
standard input
[ "constructive algorithms", "math" ]
d2cc6efe7173a64482659ba59efeec16
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1\le t\le 10^4$$$) — the number of test cases. The description of the test cases follows. The first line contains three integers $$$n$$$, $$$l$$$, $$$r$$$ ($$$1 \le n \le 10^5$$$, $$$1\le l\le r\le 10^9$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,100
For each test case, if there is no solution, print "NO" (without quotes). You can print letters in any case (upper or lower). Otherwise, print "YES" (without quotes). In the next line, print $$$n$$$ integers $$$a_1,a_2,\ldots,a_n$$$ — the array you construct. If there are multiple solutions, you may output any.
standard output
PASSED
cf5e2cd8e3b2ce1d089aee56355192d6
train_108.jsonl
1657982100
You are given three integers $$$n$$$, $$$l$$$, and $$$r$$$. You need to construct an array $$$a_1,a_2,\dots,a_n$$$ ($$$l\le a_i\le r$$$) such that $$$\gcd(i,a_i)$$$ are all distinct or report there's no solution.Here $$$\gcd(x, y)$$$ denotes the greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.math.BigInteger; import java.util.*; import java.util.stream.Collectors; public class coding { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while(st == null || !st.hasMoreElements()) { try { String str = br.readLine(); if(str == null) throw new InputMismatchException(); st = new StringTokenizer(str); } 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(); } if(str == null) throw new InputMismatchException(); return str; } public BigInteger nextBigInteger() { // TODO Auto-generated method stub return null; } public void close() { // TODO Auto-generated method stub } } public static <K, V> K getKey(Map<K, V> map, V value) { for (Map.Entry<K, V> entry: map.entrySet()) { if (value.equals(entry.getValue())) { return entry.getKey(); } } return null; } public static int median(ArrayList<Integer> x) { int p=0; if(x.size()==1) { p=x.get(0); } else { p=x.get((x.size()-1)/2 ); } return p; } public static boolean palindrome(long x) { String s="",s1=""; while(x!=0) { s=s+x%10; x=x/10; } for(int i=0;i<s.length();i++) { s1=s1+s.charAt(s.length()-i-1); } if(s1.contentEquals(s)) { return true; } else { return false; } } static void reverse(String a[], int n) { String k="", t=""; for (int i = 0; i < n / 2; i++) { t = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = t; } } static int fact(int n) { int fact=1; int i=1; while(i<=n) { fact=fact*i; } return fact; } static int gcd(int y, int x) { while(x!=y) { if(x>y) { x=x-y; } else { y=y-x; } } return y; } public static void main(String args[] ) throws Exception { FastReader sc = new FastReader(); PrintWriter out = new PrintWriter(System.out); StringBuilder sb = new StringBuilder(); int t=sc.nextInt(); while(t-->0) { int n=sc.nextInt(); long l=sc.nextLong(); long r=sc.nextLong(); long l1=l,r1=r; long k1=l; long arr[]=new long[n]; boolean p=true; for(int i=0;i<n;i++) { long k=(long)i+1; if(l%k!=0) { l=l-l%k +k; } arr[i]=l; if(arr[i]>r) { p=false; break; } l=k1; } if(!p) { System.out.println("NO"); } else { System.out.println("YES"); for(int i=0;i<n;i++) { System.out.print(arr[i]+" "); } System.out.println(); } } } }
Java
["4\n5 1 5\n9 1000 2000\n10 30 35\n1 1000000000 1000000000"]
1 second
["YES\n1 2 3 4 5\nYES\n1145 1926 1440 1220 1230 1350 1001 1000 1233\nNO\nYES\n1000000000"]
NoteIn the first test case, $$$\gcd(1,a_1),\gcd(2,a_2),\ldots,\gcd(5,a_5)$$$ are equal to $$$1$$$, $$$2$$$, $$$3$$$, $$$4$$$, $$$5$$$, respectively.
Java 11
standard input
[ "constructive algorithms", "math" ]
d2cc6efe7173a64482659ba59efeec16
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1\le t\le 10^4$$$) — the number of test cases. The description of the test cases follows. The first line contains three integers $$$n$$$, $$$l$$$, $$$r$$$ ($$$1 \le n \le 10^5$$$, $$$1\le l\le r\le 10^9$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,100
For each test case, if there is no solution, print "NO" (without quotes). You can print letters in any case (upper or lower). Otherwise, print "YES" (without quotes). In the next line, print $$$n$$$ integers $$$a_1,a_2,\ldots,a_n$$$ — the array you construct. If there are multiple solutions, you may output any.
standard output
PASSED
09e336aaeba34065cae038ca3863cc43
train_108.jsonl
1657982100
You are given three integers $$$n$$$, $$$l$$$, and $$$r$$$. You need to construct an array $$$a_1,a_2,\dots,a_n$$$ ($$$l\le a_i\le r$$$) such that $$$\gcd(i,a_i)$$$ are all distinct or report there's no solution.Here $$$\gcd(x, y)$$$ denotes the greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$.
256 megabytes
// Working program with FastReader import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Scanner; import java.util.StringTokenizer; import java.util.*; import java.lang.*; import java.util.stream.*; import java.util.stream.Collectors; 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 { if(st.hasMoreTokens()){ str = st.nextToken("\n"); } else{ str = br.readLine(); } } catch (IOException e) { e.printStackTrace(); } return str; } } public static int calcdiv2(int n) { int counter = 0; while( ( 1 & n) != 1) { n = n>>1; counter++; } return counter; } public static int highestPowerOfTwo(int n) { if((n & (n-1)) == 0) return n; return n & (n-1); } public static boolean isPowerOfTwo(int n) { return (n & (n-1)) == 0; } public static int valueOfRightMostSetBit(int n) { return (n & (-n)); } // public static HashMap<Integer, Integer> sortByValue(HashMap<Integer, Integer> hm) // { // HashMap<Integer, Integer> temp // = hm.entrySet() // .stream() // .sorted((i1, i2) // -> i1.getValue().compareTo( // i2.getValue())) // .collect(Collectors.toMap( // Map.Entry::getKey, // Map.Entry::getValue, // (e1, e2) -> e1, LinkedHashMap::new)); // return temp; // } // static int[] sortint(int a[]) { // ArrayList<Integer> al = new ArrayList<>(); // for (int i : a) { // al.add(i); // } // Collections.sort(al); // for (int i = 0; i < a.length; i++) { // a[i] = al.get(i); // } // return a; // } // static long[] sortlong(long a[]) { // ArrayList<Long> al = new ArrayList<>(); // for (long i : a) { // al.add(i); // } // Collections.sort(al); // for (int i = 0; i < al.size(); i++) { // a[i] = al.get(i); // } // return a; // } // static ArrayList<Integer> primesTilN(int n) { // boolean p[] = new boolean[n + 1]; // ArrayList<Integer> al = new ArrayList<>(); // Arrays.fill(p, true); // int i = 0; // for (i = 2; i * i <= n; i++) { // if (p[i] == true) { // al.add(i); // for (int j = i * i; j <= n; j += i) { // p[j] = false; // } // } // } // for (i = i; i <= n; i++) { // if (p[i] == true) { // al.add(i); // } // } // return al; // } // static int gcd(int a, int b) { // if (a == 0) { // return b; // } // return gcd(b % a, a); // } // static long gcd(long a, long b) { // if (a == 0) { // return b; // } // return gcd(b % a, a); // } // static long pow(long x, long y) { // long result = 1; // while (y > 0) { // if (y % 2 == 0) { // x = x * x; // y = y / 2; // } else { // result = result * x; // y = y - 1; // } // } // return result; // } // static boolean[] esieve(int n) { // boolean p[] = new boolean[n + 1]; // Arrays.fill(p, true); // for (int i = 2; i * i <= n; i++) { // if (p[i] == true) { // for (int j = i * i; j <= n; j += i) { // p[j] = false; // } // } // } // return p; // } // static int[] readarr(int n) { // int arr[] = new int[n]; // for (int i = 0; i < n; i++) { // arr[i] = x.nextInt(); // } // return arr; // } // static HashMap<Integer, Integer> mapCounter(int arr[]) { // for(int i : arr) { // if(map.containsKey(i)) map.put(arr[i], map.get(arr[i])+1); // else map.put(arr[i], 1); // } // } // static HashMap<Integer, Integer> mapCounter(int arr[]) { // for(int i : arr) { // if(map.containsKey(i)) map.put(arr[i], map.get(arr[i])+1); // else map.put(arr[i], 1); // } // } public static void main(String[] args) { FastReader sc = new FastReader(); int testcases = sc.nextInt(); int count = 0; while (count < testcases) { int n = sc.nextInt(); int l = sc.nextInt(); int r = sc.nextInt(); int arr[] = new int[n]; for(int i = 1; i<= n; i++) { if(l % i == 0) arr[i-1] = l; else { int res = l%i; int ans = l + (i- res); arr[i-1] = ans; } } int c=0; for(int x:arr){ if(x>=l && x<=r)c++; } if(c == n) { System.out.println("YES"); for(int i : arr) { System.out.print(i + " "); } System.out.println(); } else { System.out.println("NO"); } count++; } } }
Java
["4\n5 1 5\n9 1000 2000\n10 30 35\n1 1000000000 1000000000"]
1 second
["YES\n1 2 3 4 5\nYES\n1145 1926 1440 1220 1230 1350 1001 1000 1233\nNO\nYES\n1000000000"]
NoteIn the first test case, $$$\gcd(1,a_1),\gcd(2,a_2),\ldots,\gcd(5,a_5)$$$ are equal to $$$1$$$, $$$2$$$, $$$3$$$, $$$4$$$, $$$5$$$, respectively.
Java 11
standard input
[ "constructive algorithms", "math" ]
d2cc6efe7173a64482659ba59efeec16
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1\le t\le 10^4$$$) — the number of test cases. The description of the test cases follows. The first line contains three integers $$$n$$$, $$$l$$$, $$$r$$$ ($$$1 \le n \le 10^5$$$, $$$1\le l\le r\le 10^9$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,100
For each test case, if there is no solution, print "NO" (without quotes). You can print letters in any case (upper or lower). Otherwise, print "YES" (without quotes). In the next line, print $$$n$$$ integers $$$a_1,a_2,\ldots,a_n$$$ — the array you construct. If there are multiple solutions, you may output any.
standard output
PASSED
531ddce7adf1987923d9ba055ccb5fb0
train_108.jsonl
1657982100
You are given three integers $$$n$$$, $$$l$$$, and $$$r$$$. You need to construct an array $$$a_1,a_2,\dots,a_n$$$ ($$$l\le a_i\le r$$$) such that $$$\gcd(i,a_i)$$$ are all distinct or report there's no solution.Here $$$\gcd(x, y)$$$ denotes the greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$.
256 megabytes
import java.io.*; import java.util.*; public class cf { public static int gcd(int a, int b){ if(b == 0){ return a; } return gcd(b, a % b); } public static boolean isok(long x, long h, long k){ long sum = 0; if(h > k){ long t1 = h - k; long t = t1 * k; sum += (k * (k + 1)) / 2; sum += t - (t1 * (t1 + 1) / 2); }else{ sum += (h * (h + 1)) / 2; } if(sum < x){ return true; } return false; } public static boolean binary_search(long[] a, long k){ long low = 0; long high = a.length - 1; long mid = 0; while(low <= high){ mid = low + (high - low) / 2; if(a[(int)mid] == k){ return true; }else if(a[(int)mid] < k){ low = mid + 1; }else{ high = mid - 1; } } return false; } public static long lowerbound(long a[], long ddp){ long low = 0; long high = a.length; long mid = 0; while(low < high){ mid = low + (high - low)/2; if(a[(int)mid] == ddp){ return mid; } if(a[(int)mid] < ddp){ low = mid + 1; }else{ high = mid; } } // if(low + 1 < a.length && a[(int)low + 1] <= ddp){ // low++; // } if(low == a.length && low != 0){ low--; return low; } if(a[(int)low] > ddp && low != 0){ low--; } return low; } public static long upperbound(long a[], long ddp){ long low = 0; long high = a.length; long mid = 0; while(low < high){ mid = low + (high - low) / 2; if(a[(int)mid] < ddp){ low = mid + 1;; }else{ high = mid; } } if(low == a.length){ return a.length - 1; } return low; } public static class pair{ long w; long h; public pair(long w, long h){ this.w = w; this.h = h; } } public static class trinary{ long a; long b; long c; public trinary(long a, long b, long c){ this.a = a; this.b = b; this.c = c; } } public static long lowerboundforpairs(pair a[], long pr){ long low = 0; long high = a.length; long mid = 0; while(low < high){ mid = low + (high - low)/2; if(a[(int)mid].w <= pr){ low = mid + 1; }else{ high = mid; } } // if(low + 1 < a.length && a[(int)low + 1] <= ddp){ // low++; // } // if(low == a.length && low != 0){ // low--; // return low; // } // if(a[(int)low].w > pr && low != 0){ // low--; // } return low; } public static pair[] sortpair(pair[] a){ Arrays.sort(a, new Comparator<pair>() { public int compare(pair p1, pair p2){ return (int)p1.w - (int)p2.w; } }); return a; } public static boolean ispalindrome(String s){ long i = 0; long j = s.length() - 1; boolean is = false; while(i < j){ if(s.charAt((int)i) == s.charAt((int)j)){ is = true; i++; j--; }else{ is = false; return is; } } return is; } public static void sort(long[] arr) { ArrayList<Long> a = new ArrayList<>(); for (long i : arr) { a.add(i); } Collections.sort(a); for (int i = 0; i < a.size(); i++) { arr[i] = a.get(i); } } public static void sortForObjecttypes(Long[] arr) { ArrayList<Long> a = new ArrayList<>(); for (Long i : arr) { a.add(i); } Collections.sort(a); for (int i = 0; i < a.size(); i++) { arr[i] = a.get(i); } } 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()); } float nextFloat() { return Float.parseFloat(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } void readArr(int[] ar, int n) { for (int i = 0; i < n; i++) { ar[i] = nextInt(); } } } public static void solve(FastReader sc, PrintWriter w) throws Exception { int n = sc.nextInt(); int l = sc.nextInt(); int r = sc.nextInt(); ArrayList<Integer> al = new ArrayList<>(); al.add(l); for(int i = 2;i <= n;i++){ if(l % i == 0){ al.add(l); }else{ int k = l / i; k = (k + 1) * i; if(k > r){ break; } al.add(k); } } if(al.size() == n){ System.out.println("YES"); for(int i = 0;i < n;i++){ System.out.print(al.get(i) + " "); } System.out.println(); }else{ System.out.println("NO"); } } public static void main(String[] args) throws Exception { FastReader sc = new FastReader(); PrintWriter w = new PrintWriter(System.out); long o = sc.nextLong(); while(o > 0){ solve(sc, w); o--; } w.close(); } }
Java
["4\n5 1 5\n9 1000 2000\n10 30 35\n1 1000000000 1000000000"]
1 second
["YES\n1 2 3 4 5\nYES\n1145 1926 1440 1220 1230 1350 1001 1000 1233\nNO\nYES\n1000000000"]
NoteIn the first test case, $$$\gcd(1,a_1),\gcd(2,a_2),\ldots,\gcd(5,a_5)$$$ are equal to $$$1$$$, $$$2$$$, $$$3$$$, $$$4$$$, $$$5$$$, respectively.
Java 11
standard input
[ "constructive algorithms", "math" ]
d2cc6efe7173a64482659ba59efeec16
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1\le t\le 10^4$$$) — the number of test cases. The description of the test cases follows. The first line contains three integers $$$n$$$, $$$l$$$, $$$r$$$ ($$$1 \le n \le 10^5$$$, $$$1\le l\le r\le 10^9$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,100
For each test case, if there is no solution, print "NO" (without quotes). You can print letters in any case (upper or lower). Otherwise, print "YES" (without quotes). In the next line, print $$$n$$$ integers $$$a_1,a_2,\ldots,a_n$$$ — the array you construct. If there are multiple solutions, you may output any.
standard output
PASSED
335ead3be0c4562dedee7c307ddf460c
train_108.jsonl
1657982100
You are given three integers $$$n$$$, $$$l$$$, and $$$r$$$. You need to construct an array $$$a_1,a_2,\dots,a_n$$$ ($$$l\le a_i\le r$$$) such that $$$\gcd(i,a_i)$$$ are all distinct or report there's no solution.Here $$$\gcd(x, y)$$$ denotes the greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$.
256 megabytes
import java.lang.*; import java.io.*; import java.util.*; public class codeforces { static int max = Integer.MAX_VALUE, min = Integer.MIN_VALUE; long maxl = Long.MAX_VALUE, minl = Long.MIN_VALUE; static PrintWriter pw = new PrintWriter(System.out); static StringBuilder sb = new StringBuilder(); static int parent[] = new int[100001]; static int rank[] = new int[100001]; static int mod = 1000000007; static boolean b1 = true; // static int dp[][] = new int[10001][10001]; public static void main(String[] args) throws IOException { // if (System.getProperty("ONLINE_JUDGE") == null) { // PrintStream ps = new PrintStream(new File("output.txt")); // InputStream is = new FileInputStream("input.txt"); // System.setIn(is); // System.setOut(ps); FastScanner sc = new FastScanner(); int ttt = sc.nextInt(); for (int tt = 1; tt <= ttt; tt++) { int n = sc.nextInt(); int l = sc.nextInt(); int r = sc.nextInt(); b1 = true; int ar[] = new int[n]; ar[0] = l; // ar[1] = 0; for (int i = 2; i <= n; i++) { if (i > l) { if(i<=r) ar[i - 1] = i; else { b1 = false; break; } } else if (l % i != 0) { if ((l + (i-(l % i))) > r) { b1 = false; break; } else ar[i - 1] = (l + (i-(l % i))); } else ar[i - 1] = l; } if (b1) { System.out.println("YES"); for(int i=0;i<n;i++) System.out.print(ar[i] + " "); System.out.println(); } else System.out.println("NO"); } } // } // public static int countSubsetSum(int ar[], int sum, int n) { // // all numbers must be positive // if (sum == 0) // return 1; // if (n == 0) // return 0; // if (dp[n][sum] != -1) // return dp[n][sum]; // if (ar[n - 1] <= sum) { // dp[n][sum] = countSubsetSum(ar, sum - ar[n - 1], n - 1) + countSubsetSum(ar, sum, n - 1); // } else // dp[n][sum] = countSubsetSum(ar, sum, n - 1); // return dp[n][sum]; // } // finding subsequences using bit manupilation public static HashSet<String> allSubSequence(String s) { int n = s.length(); HashSet<String> hs = new HashSet<>(); for (int i = 0; i < (1 << n); i++) { String ss = ""; for (int j = 0; j < n; j++) { if ((i & (1 << j)) != 0) ss = ss + s.charAt(j); } hs.add(ss); } return hs; } // calculating nCr static long nCr(int n, int r) { long sum = 1; int max = Math.max(r, n - r); int min = Math.min(r, n - r); int st = 1; for (int i = n; i > max; i--) { sum = sum * i; sum /= st; st++; } return sum; } // finding subsequences using recurrsion public static HashSet<String> SubSequence(String input, String output, HashSet<String> a) { if (input.length() == 0) { a.add(output); return a; } String op1 = output; String op2 = output + input.charAt(0); input = input.substring(1); SubSequence(input, op1, a); SubSequence(input, op2, a); return a; } static int ceil(int x, int y) { return (x % y == 0 ? x / y : (x / y + 1)); } static long ceil(long x, long y) { return (x % y == 0 ? x / y : (x / y + 1)); } public static boolean checkPalindrome(int n) { int v = 0; int n1 = n; while (n > 0) { v = v * 10 + n % 10; n = n / 10; } if (n1 == v) return true; else return false; } public static int lis(int arr[], int n) { int lis[] = new int[n]; int i, j, max = 0; /* Initialize LIS values for all indexes */ for (i = 0; i < n; i++) lis[i] = 1; /* * Compute optimized LIS values in * bottom up manner */ for (i = 1; i < n; i++) for (j = 0; j < i; j++) if (arr[i] > arr[j] && lis[i] < lis[j] + 1) lis[i] = lis[j] + 1; /* Pick maximum of all LIS values */ for (i = 0; i < n; i++) if (max < lis[i]) max = lis[i]; return max; } public static void union(int a, int b) { a = find(a); b = find(b); if (a != b) { if (rank[a] < rank[b]) { parent[a] = b; rank[b] += rank[a]; } else { parent[b] = a; rank[a] += rank[b]; } } } public static int find(int a) { if (parent[a] < 0) return a; return (parent[a] = find(parent[a])); } public static Boolean[] primeNo() { Boolean[] is_prime = new Boolean[100001]; int max = 100000; for (int i = 2; i <= max; i++) is_prime[i] = true; is_prime[0] = is_prime[1] = false; for (int i = 2; (long) i * i <= max; i++) { if (is_prime[i] == true) { for (int j = (i * i); j <= max; j += i) is_prime[j] = false; } } return is_prime; } public static int binarySearch(int arr[], int x) { int l = 0, r = arr.length - 1; int result1 = -1; while (l <= r) { int mid = l + (r - l) / 2; if (arr[mid] == x) { return mid; } else if (arr[mid] > x) { r = mid - 1; } else { l = mid + 1; } } return result1; } public static class Pair { public int x; public int y; public Pair(int x, int y) { this.x = x; this.y = y; } } public static long gcd(long a, long b) { if (a == 0) return b; return gcd(b % a, a); } public static String reverseString(String s) { StringBuilder s1 = new StringBuilder(s); s1.reverse(); return s1.toString(); } public static class FastScanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } long nextLong() { return Long.parseLong(next()); } } }
Java
["4\n5 1 5\n9 1000 2000\n10 30 35\n1 1000000000 1000000000"]
1 second
["YES\n1 2 3 4 5\nYES\n1145 1926 1440 1220 1230 1350 1001 1000 1233\nNO\nYES\n1000000000"]
NoteIn the first test case, $$$\gcd(1,a_1),\gcd(2,a_2),\ldots,\gcd(5,a_5)$$$ are equal to $$$1$$$, $$$2$$$, $$$3$$$, $$$4$$$, $$$5$$$, respectively.
Java 11
standard input
[ "constructive algorithms", "math" ]
d2cc6efe7173a64482659ba59efeec16
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1\le t\le 10^4$$$) — the number of test cases. The description of the test cases follows. The first line contains three integers $$$n$$$, $$$l$$$, $$$r$$$ ($$$1 \le n \le 10^5$$$, $$$1\le l\le r\le 10^9$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,100
For each test case, if there is no solution, print "NO" (without quotes). You can print letters in any case (upper or lower). Otherwise, print "YES" (without quotes). In the next line, print $$$n$$$ integers $$$a_1,a_2,\ldots,a_n$$$ — the array you construct. If there are multiple solutions, you may output any.
standard output
PASSED
712b435aa879b0fdf95608443b930a2e
train_108.jsonl
1657982100
You are given three integers $$$n$$$, $$$l$$$, and $$$r$$$. You need to construct an array $$$a_1,a_2,\dots,a_n$$$ ($$$l\le a_i\le r$$$) such that $$$\gcd(i,a_i)$$$ are all distinct or report there's no solution.Here $$$\gcd(x, y)$$$ denotes the greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$.
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; import java.math.*; public class B { public static void main(String[] args) throws java.lang.Exception { Reader scan = new Reader(); int tc = scan.nextInt(); for (int i = 0; i < tc; i++) { int n = scan.nextInt(); long l = scan.nextLong(); long r = scan.nextLong(); solve(n, l, r); } } public static void solve(int n, long l, long r) { long arr[] = new long[n]; for (int i = 1; i <= n; i++){ long first = ((l-1)/i + 1)*i; if (first > r) continue; arr[i-1] = first; } for (int i = 0; i < arr.length; i++){ if (arr[i] == 0){ System.out.println("NO"); return; } } System.out.println("YES"); printarr(arr); } public static void printarr(long[] arr) { for (int i = 0; i < arr.length; i++) { System.out.print(arr[i] + " "); } System.out.println(); } public static void printarr(ArrayList<Long> arr) { for (int i = 0; i < arr.size(); i++) { System.out.print(arr.get(i) + " "); } System.out.println(); } static class Reader { final private int BUFFER_SIZE = 1 << 64; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream( new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[1000000]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') { if (cnt != 0) { break; } else { continue; } } buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') { c = read(); } boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } }
Java
["4\n5 1 5\n9 1000 2000\n10 30 35\n1 1000000000 1000000000"]
1 second
["YES\n1 2 3 4 5\nYES\n1145 1926 1440 1220 1230 1350 1001 1000 1233\nNO\nYES\n1000000000"]
NoteIn the first test case, $$$\gcd(1,a_1),\gcd(2,a_2),\ldots,\gcd(5,a_5)$$$ are equal to $$$1$$$, $$$2$$$, $$$3$$$, $$$4$$$, $$$5$$$, respectively.
Java 11
standard input
[ "constructive algorithms", "math" ]
d2cc6efe7173a64482659ba59efeec16
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1\le t\le 10^4$$$) — the number of test cases. The description of the test cases follows. The first line contains three integers $$$n$$$, $$$l$$$, $$$r$$$ ($$$1 \le n \le 10^5$$$, $$$1\le l\le r\le 10^9$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,100
For each test case, if there is no solution, print "NO" (without quotes). You can print letters in any case (upper or lower). Otherwise, print "YES" (without quotes). In the next line, print $$$n$$$ integers $$$a_1,a_2,\ldots,a_n$$$ — the array you construct. If there are multiple solutions, you may output any.
standard output
PASSED
6edfb2ecfc995fcece8e83e7ceccf492
train_108.jsonl
1657982100
You are given three integers $$$n$$$, $$$l$$$, and $$$r$$$. You need to construct an array $$$a_1,a_2,\dots,a_n$$$ ($$$l\le a_i\le r$$$) such that $$$\gcd(i,a_i)$$$ are all distinct or report there's no solution.Here $$$\gcd(x, y)$$$ denotes the greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$.
256 megabytes
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.*; public class weird_algrithm { static BufferedWriter output = new BufferedWriter( new OutputStreamWriter(System.out)); static BufferedReader sc = new BufferedReader(new InputStreamReader(System.in)); static int mod = 1000000007; static String toReturn = ""; static int steps = Integer.MAX_VALUE; static int maxlen = 1000005; /*MATHEMATICS FUNCTIONS START HERE MATHS MATHS MATHS MATHS*/ static long gcd(long a, long b) { if(b == 0) return a; else return gcd(b, a % b); } static long powerMod(long x, long y, int mod) { if(y == 0) return 1; long temp = powerMod(x, y / 2, mod); temp = ((temp % mod) * (temp % mod)) % mod; if(y % 2 == 0) return temp; else return ((x % mod) * (temp % mod)) % mod; } static long modInverse(long n, int p) { return powerMod(n, p - 2, p); } static long nCr(int n, int r, int mod, long [] fact, long [] ifact) { return ((fact[n] % mod) * ((ifact[r] * ifact[n - r]) % mod)) % mod; } static boolean isPrime(long a) { if(a == 1) return false; else if(a == 2 || a == 3 || a== 5) return true; else if(a % 2 == 0 || a % 3 == 0) return false; for(int i = 5; i * i <= a; i = i + 6) { if(a % i == 0 || a % (i + 2) == 0) return false; } return true; } static int [] seive(int a) { int [] toReturn = new int [a + 1]; for(int i = 0; i < a; i++) toReturn[i] = 1; toReturn[0] = 0; toReturn[1] = 0; toReturn[2] = 1; for(int i = 2; i * i <= a; i++) { if(toReturn[i] == 0) continue; for(int j = 2 * i; j <= a; j += i) toReturn[j] = 0; } return toReturn; } static long [] fact(int a) { long [] arr = new long[a + 1]; arr[0] = 1; for(int i = 1; i < a + 1; i++) { arr[i] = (arr[i - 1] * i) % mod; } return arr; } /*MATHS MATHS MATHS MATHS MATHEMATICS FUNCTIONS END HERE */ /*SWAP FUNCTION START HERE SWAP SWAP SWAP SWAP */ static void swap(int i, int j, long[] arr) { long temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } static void swap(int i, int j, int[] arr) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } static void swap(int i, int j, String [] arr) { String temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } static void swap(int i, int j, char [] arr) { char temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } /*SWAP SWAP SWAP SWAP SWAP FUNCTION END HERE*/ /*BINARY SEARCH METHODS START HERE * BINARY SEARCH * BINARY SEARCH * BINARY SEARCH * BINARY SEARCH */ static boolean BinaryCheck(long test, long [] arr, long health) { for(int i = 0; i <= arr.length - 1; i++) { if(i == arr.length - 1) health -= test; else if(arr[i + 1] - arr[i] > test) { health = health - test; }else { health = health - (arr[i + 1] - arr[i]); } if(health <= 0) return true; } return false; } static long binarySearchModified(long start1, long n, ArrayList<Long> arr, int a, long r) { long start = start1, end = n, ans = -1; while(start < end) { long mid = (start + end) / 2; //System.out.println(mid); if(arr.get((int)mid) + arr.get(a) <= r && mid != start1) { ans = mid; start = mid + 1; }else{ end = mid; } } //System.out.println(); return ans; } static int binarySearch(int start, int end, long [] arr, long val) { while(start < end) { int mid = (int)Math.ceil((start + end) / 2.0); //System.out.println(mid); if(arr[mid] > val) end = mid - 1; else start = mid; } return start; } /*BINARY SEARCH * BINARY SEARCH * BINARY SEARCH * BINARY SEARCH * BINARY SEARCH BINARY SEARCH METHODS END HERE*/ /*RECURSIVE FUNCTION START HERE * RECURSIVE * RECURSIVE * RECURSIVE * RECURSIVE */ static int recurse(int x, int y, int n, int steps1, Integer [][] dp) { if(x > n || y > n) return 0; if(dp[x][y] != null) { return dp[x][y]; } else if(x == n || y == n) { return steps1; } return dp[x][y] = Math.max(recurse(x + y, y, n, steps1 + 1, dp), recurse(x, x + y, n, steps1 + 1, dp)); } /*RECURSIVE * RECURSIVE * RECURSIVE * RECURSIVE * RECURSIVE RECURSIVE FUNCTION END HERE*/ /*GRAPH FUNCTIONS START HERE * GRAPH * GRAPH * GRAPH * GRAPH * */ static class edge{ int from, to; long weight; public edge(int x, int y, long weight2) { this.from = x; this.to = y; this.weight = weight2; } } static class sort implements Comparator<pair>{ @Override public int compare(pair o1, pair o2) { // TODO Auto-generated method stub return (int)o1.a - (int)o2.a; } } static void addEdge(ArrayList<ArrayList<edge>> graph, int from, int to, long weight) { edge temp = new edge(from, to, weight); edge temp1 = new edge(to, from, weight); graph.get(from).add(temp); //graph.get(to).add(temp1); } static int ans = 0; static int dfs(ArrayList<ArrayList<Integer>> graph, int vertex, boolean [] visited, int [] childs) { //System.out.println(graph.get(vertex).size()); if(visited[vertex]) return 0; visited[vertex] = true; int ans = 0; for(int i = 0; i < graph.get(vertex).size(); i++) { int temp = graph.get(vertex).get(i); if(!visited[temp]) { ans += dfs(graph, temp, visited, childs) + 1; } } childs[vertex] = ans; return ans; } static void topoSort(ArrayList<ArrayList<Integer>> graph, int vertex, boolean [] visited, ArrayList<Integer> toReturn) { if(visited[vertex]) return; visited[vertex] = true; for(int i = 0; i < graph.get(vertex).size(); i++) { if(!visited[graph.get(vertex).get(i)]) topoSort(graph, graph.get(vertex).get(i), visited, toReturn); } toReturn.add(vertex); } static boolean isCyclicDirected(ArrayList<ArrayList<Integer>> graph, int vertex, boolean [] visited, boolean [] reStack) { if(reStack[vertex]) return true; if(visited[vertex]) return false; reStack[vertex] = true; visited[vertex] = true; for(int i = 0; i < graph.get(vertex).size(); i++) { if(isCyclicDirected(graph, graph.get(vertex).get(i), visited, reStack)) return true; } reStack[vertex] = false; return false; } static int e = 0; static long mst(PriorityQueue<edge> pq, int nodes) { long weight = 0; while(!pq.isEmpty()) { edge temp = pq.poll(); int x = parent(parent, temp.to); int y = parent(parent, temp.from); if(x != y) { //System.out.println(temp.weight); union(x, y, rank, parent); weight += temp.weight; e++; } } return weight; } static void floyd(long [][] dist) { // to find min distance between two nodes for(int k = 0; k < dist.length; k++) { for(int i = 0; i < dist.length; i++) { for(int j = 0; j < dist.length; j++) { if(dist[i][j] > dist[i][k] + dist[k][j]) { dist[i][j] = dist[i][k] + dist[k][j]; } } } } } static void dijkstra(ArrayList<ArrayList<edge>> graph, long [] dist, int src) { for(int i = 0; i < dist.length; i++) dist[i] = Long.MAX_VALUE / 2; dist[src] = 0; boolean visited[] = new boolean[dist.length]; PriorityQueue<pair> pq = new PriorityQueue<>(new sort()); pq.add(new pair(src, 0)); while(!pq.isEmpty()) { pair temp = pq.poll(); int index = (int)temp.a; for(int i = 0; i < graph.get(index).size(); i++) { if(dist[graph.get(index).get(i).to] > dist[index] + graph.get(index).get(i).weight) { dist[graph.get(index).get(i).to] = dist[index] + graph.get(index).get(i).weight; pq.add(new pair(graph.get(index).get(i).to, graph.get(index).get(i).weight)); } } } } static int parent1 = -1; static boolean ford(ArrayList<ArrayList<edge>> graph1, ArrayList<edge> graph, long [] dist, int src, int [] parent) { for(int i = 0; i < dist.length; i++) dist[i] = Long.MIN_VALUE / 2; dist[src] = 0; boolean hasNeg = false; for(int i = 0; i < dist.length - 1; i++) { for(int j = 0; j < graph.size(); j++) { int from = graph.get(j).from; int to = graph.get(j).to; long weight = graph.get(j).weight; if(dist[to] < dist[from] + weight) { dist[to] = dist[from] + weight; parent[to] = from; } } } for(int i = 0; i < graph.size(); i++) { int from = graph.get(i).from; int to = graph.get(i).to; long weight = graph.get(i).weight; if(dist[to] < dist[from] + weight) { parent1 = from; hasNeg = true; /* * dfs(graph1, parent1, new boolean[dist.length], dist.length - 1); * //System.out.println(ans); dfs(graph1, 0, new boolean[dist.length], parent1); */ //System.out.println(ans); if(ans == 2) break; else ans = 0; } } return hasNeg; } /*GRAPH FUNCTIONS END HERE * GRAPH * GRAPH * GRAPH * GRAPH */ /*disjoint Set START HERE * disjoint Set * disjoint Set * disjoint Set * disjoint Set */ static int [] rank; static int [] parent; static int parent(int [] parent, int x) { if(parent[x] == x) return x; else return parent[x] = parent(parent, parent[x]); } static boolean union(int x, int y, int [] rank, int [] parent) { if(parent(parent, x) == parent(parent, y)) { return true; } if(rank[x] > rank[y]) { swap(x, y, rank); } rank[x] += rank[y]; parent[y] = x; return false; } /*disjoint Set END HERE * disjoint Set * disjoint Set * disjoint Set * disjoint Set */ /*INPUT START HERE * INPUT * INPUT * INPUT * INPUT * INPUT */ static int nextInt() throws NumberFormatException, IOException { return Integer.parseInt(sc.readLine()); } static long nextLong() throws NumberFormatException, IOException { return Long.parseLong(sc.readLine()); } static long [] inputLongArr() throws NumberFormatException, IOException{ String [] s = sc.readLine().split(" "); long [] toReturn = new long[s.length]; for(int i = 0; i < s.length; i++) { toReturn[i] = Long.parseLong(s[i]); } return toReturn; } static int max = 0; static int [] inputIntArr() throws NumberFormatException, IOException{ String [] s = sc.readLine().split(" "); //System.out.println(s.length); int [] toReturn = new int[s.length]; for(int i = 0; i < s.length; i++) { toReturn[i] = Integer.parseInt(s[i]); } return toReturn; } static void print(int n) throws IOException { output.write(Integer.toString(n)); output.flush(); } static void print(String s) throws IOException { output.write(s); output.flush(); } static void print(long n) throws IOException { output.write(Long.toString(n) + "\n"); output.flush(); } static void print(char n) throws IOException { output.write(n); output.flush(); } /*INPUT * INPUT * INPUT * INPUT * INPUT * INPUT END HERE */ static long [] preCompute(int level) { long [] toReturn = new long[level]; toReturn[0] = 1; toReturn[1] = 16; for(int i = 2; i < level; i++) { toReturn[i] = ((toReturn[i - 1] % mod) * (toReturn[i - 1] % mod)) % mod; } return toReturn; } static class pair{ long a; long b; long d; public pair(long in, long y) { this.a = in; this.b = y; this.d = 0; } } static long smallestFactor(long a) { for(long i = 2; i * i <= a; i++) { if(a % i == 0) { return i; } } return a; } static int recurseRow(int [][] mat, int i, int j, int prev, int ans) { if(j >= mat[0].length) return ans; if(mat[i][j] == prev) { return recurseRow(mat, i, j + 1, prev, ans + 1); } else return ans; } static int recurseCol(int [][] mat, int i, int j, int prev, int ans) { if(i >= mat.length) return ans; if(mat[i][j] == prev) { return recurseCol(mat, i + 1, j, prev, ans + 1); } else return ans; } static int diff(char [] a, char [] b) { int sum = 0; for(int i = 0; i < a.length; i++) { sum += Math.abs((int)a[i] - (int)b[i]); } return sum; } static int [] nextGreaterBack(char [] s) { Stack<Integer> stack = new Stack<>(); int [] toReturn = new int[s.length]; for(int i = 0; i < s.length; i++) { if(!stack.isEmpty() && s[stack.peek()] >= s[i]) { stack.pop(); } if(stack.isEmpty()) { stack.push(i); toReturn[i] = -1; }else { toReturn[i] = stack.peek(); stack.push(i); } } return toReturn; } static int [] nextGreaterFront(char [] s) { Stack<Integer> stack = new Stack<>(); int [] toReturn = new int[s.length]; for(int i = s.length - 1; i >= 0; i--) { if(!stack.isEmpty() && s[stack.peek()] >= s[i]) { stack.pop(); } if(stack.isEmpty()) { stack.push(i); toReturn[i] = -1; }else { toReturn[i] = stack.peek(); stack.push(i); } } return toReturn; } static int lps(String s) { int max = 0; int [] lps = new int[s.length()]; lps[0] = 0; int j = 0; for(int i = 1; i < lps.length; i++) { j = lps[i - 1]; while(j > 0 && s.charAt(i) != s.charAt(j)) j = lps[j - 1]; if(s.charAt(i) == s.charAt(j)) { lps[i] = j + 1; max = Math.max(max, lps[i]); } } return max; } static int [][] vectors = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}}; static String dir = "DRUL"; static boolean check(int i, int j, boolean [][] visited) { if(i >= visited.length || j >= visited[0].length) return false; if(i < 0 || j < 0) return false; return true; } static int count = 0; static void recurse(boolean [][] visited, int i, int j, String p, int z, Integer [][][] dp) throws IOException { if(p.length() == z) { //System.out.println(i + " " + j); if(i == visited.length - 1 && j == 0) { count++; return; }else return; } if(i == visited.length - 1 && j == 0) { return; } if(visited[i][j]) return; visited[i][j] = true; for(int k = 0; k < vectors.length; k++) { int x = i + vectors[k][0], y = j + vectors[k][1]; char toAdd = dir.charAt(k); if(p.charAt(z) == '?' || p.charAt(z) == toAdd) { if(check(x, y, visited) && !visited[x][y]) { //recurse(visited, x, y, p, z + 1); } } } visited[i][j] = false; } static boolean check1(int k, long [] arr, long minSum) { int subArrays = 0; long sum = 0; for(int i = 0; i < arr.length; i++) { if(sum + arr[i] > minSum) { sum = arr[i]; subArrays++; if(arr[i] > minSum) return false; }else sum += arr[i]; } if(subArrays < k) return true; return false; } static long bin(long start, long end, long [] arr, int k) { long ans = 0; while(start < end) { long mid = (start + end) / 2; //System.out.println(mid); if(check1(k, arr, mid)) { ans = mid; end = mid; }else { start = mid + 1; } } return ans; } static void selectionSort(long arr[], long [] arr1, ArrayList<ArrayList<Integer>> ans) { int n = arr.length; for (int i = 0; i < n-1; i++) { int min_idx = i; for (int j = i+1; j < n; j++) if (arr[j] < arr[min_idx]) min_idx = j; else if(arr[j] == arr[min_idx]) { if(arr1[j] < arr1[min_idx]) min_idx = j; } if(i == min_idx) { continue; } ArrayList<Integer> p = new ArrayList<Integer>(); p.add(min_idx + 1); p.add(i + 1); ans.add(new ArrayList<Integer>(p)); swap(i, min_idx, arr); swap(i, min_idx, arr1); } } static void solve1() throws IOException { /* * for(int i = 0; i < dp.length; i++) { for(int j = 0; j < dp[0].length; j++) { * System.out.print(dp[i][j] + " "); } System.out.println(); } */ //print(recurse1(n[0], n[1], new Long[Math.max(n[0], n[1]) + 1][Math.max(n[0], n[1]) + 1])); } static int saved = Integer.MAX_VALUE; static String ans1 = ""; public static boolean isValid(int x, int y, String [] mat) { if(x >= mat.length || x < 0) return false; if(y >= mat[0].length() || y < 0) return false; return true; } static boolean recurse1(int i, int j, int [][] arr, int sum, Boolean [][][] dp) { if(i == arr.length - 1 && j == arr[0].length - 1) { if(sum + arr[i][j] == 0) return true; return false; } if(i == arr.length) return false; else if(j == arr[0].length) return false; if(sum < 0 && dp[i][j][arr.length + arr[0].length + 1 + sum] != null) return dp[i][j][arr.length + arr[0].length + 1 + sum]; if(sum > 0 && dp[i][j][sum] != null) return dp[i][j][sum]; if(sum < 0) dp[i][j][arr.length + arr[0].length + 1 + sum] = recurse1(i + 1, j, arr, sum + arr[i][j], dp) || recurse1(i, j + 1, arr, sum + arr[i][j], dp); return dp[i][j][sum] = recurse1(i + 1, j, arr, sum + arr[i][j], dp) || recurse1(i, j + 1, arr, sum + arr[i][j], dp); } static void bfs(String [] grid, int [][] distance, Queue<pair> q) { boolean [][] visited = new boolean[grid.length][grid[0].length()]; while(!q.isEmpty()) { pair head = q.poll(); for(int i = 0; i < vectors.length; i++) { int x = (int)head.a + vectors[i][0], y = (int)head.b + vectors[i][1]; if(isValid(x, y, grid) && grid[x].charAt(y) != '#' && distance[x][y] == -1) { distance[x][y] = (int)head.d + 1; pair toAdd = new pair(x, y); toAdd.d = distance[x][y]; q.add(toAdd); } } } } static pair bfs1(String [] grid, int [][] distance, Queue<pair> q, char [][] path) { boolean [][] visited = new boolean[grid.length][grid[0].length()]; while(!q.isEmpty()) { pair head = q.poll(); if(head.a == grid.length - 1 || head.b == grid[0].length() - 1 || head.a == 0 || head.b == 0) { return head; } for(int i = 0; i < vectors.length; i++) { int x = (int)head.a + vectors[i][0], y = (int)head.b + vectors[i][1]; int dist = (int)head.d + 1; if(isValid(x, y, grid) && grid[x].charAt(y) != '#' && !visited[x][y] && (dist < distance[x][y] || distance[x][y] == -1)) { path[x][y] = dir.charAt(i); visited[x][y] = true; pair toAdd = new pair(x, y); toAdd.d = dist; q.add(toAdd); } } } return null; } static int search(ArrayList<Integer> arr, int target) { int start = 0; int end = arr.size() - 1; while(start <= end) { int mid = (start + end) / 2; if(arr.get(mid) < target) start = mid + 1; else if(arr.get(mid) > target) end = mid - 1; else if(arr.get(mid) == target) { if(mid + 1 < arr.size() && arr.get(mid + 1) == target) { start = mid + 1; }else return start; } } return start; } static int end = -1; static boolean dfs1(int src, ArrayList<ArrayList<Integer>> graph, boolean [] visited, int k, HashMap<Integer, Integer> map) { visited[src] = true; if(k == 0) return true; //System.out.println(src + " " + k); for(int x : graph.get(src)) { if(!visited[x]) { if(map.containsKey(x)) { end = x; if(dfs1(x, graph, visited, k - 1, map)) return true; }else { if(dfs1(x, graph, visited, k, map)) return true; } } } return false; } public static void recurse3(ArrayList<Character> arr, int index, String s, int max, ArrayList<String> toReturn) { if(s.length() == max) { toReturn.add(s); return; } if(index == arr.size()) return; recurse3(arr, index + 1, s + arr.get(index), max, toReturn); recurse3(arr, index + 1, s, max, toReturn); } static void solve() throws IOException { long [] n = inputLongArr(); ArrayList<Long> arr = new ArrayList<Long>(); for(int i = 0; i < n[0]; i++) { if(i == 0) { arr.add(n[1]); }else { long r = n[1] % (i + 1); long toAdd = (i + 1 - r); if(n[1] + toAdd > n[2]) { if(n[1] % (i + 1) == 0) { arr.add(n[1]); }else { print("NO\n"); return; } } else arr.add(n[1] + toAdd); } } print("YES\n"); for(int i = 0; i < arr.size(); i++) { print(arr.get(i) + " "); } print("\n"); } public static void main(String[] args) throws IOException { // TODO Auto-generated method stub int t = Integer.parseInt(sc.readLine()); for(int i = 0; i < t; i++) solve(); } } class TreeNode { int val; TreeNode next; public TreeNode(int x, TreeNode y) { this.val = x; this.next = y; } } /* 1 10 6 10 7 9 11 99 45 20 88 31 */
Java
["4\n5 1 5\n9 1000 2000\n10 30 35\n1 1000000000 1000000000"]
1 second
["YES\n1 2 3 4 5\nYES\n1145 1926 1440 1220 1230 1350 1001 1000 1233\nNO\nYES\n1000000000"]
NoteIn the first test case, $$$\gcd(1,a_1),\gcd(2,a_2),\ldots,\gcd(5,a_5)$$$ are equal to $$$1$$$, $$$2$$$, $$$3$$$, $$$4$$$, $$$5$$$, respectively.
Java 11
standard input
[ "constructive algorithms", "math" ]
d2cc6efe7173a64482659ba59efeec16
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1\le t\le 10^4$$$) — the number of test cases. The description of the test cases follows. The first line contains three integers $$$n$$$, $$$l$$$, $$$r$$$ ($$$1 \le n \le 10^5$$$, $$$1\le l\le r\le 10^9$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,100
For each test case, if there is no solution, print "NO" (without quotes). You can print letters in any case (upper or lower). Otherwise, print "YES" (without quotes). In the next line, print $$$n$$$ integers $$$a_1,a_2,\ldots,a_n$$$ — the array you construct. If there are multiple solutions, you may output any.
standard output
PASSED
91ec1c3454ef3e06d18e33d7421b3f0a
train_108.jsonl
1657982100
You are given three integers $$$n$$$, $$$l$$$, and $$$r$$$. You need to construct an array $$$a_1,a_2,\dots,a_n$$$ ($$$l\le a_i\le r$$$) such that $$$\gcd(i,a_i)$$$ are all distinct or report there's no solution.Here $$$\gcd(x, y)$$$ denotes the greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$.
256 megabytes
import java.util.*; public class Main{ static int total=0; public static void main(String[] args) { Scanner in=new Scanner(System.in); int t=in.nextInt(); for(int h=0;h<t;h++){ long n=in.nextInt(); long l=in.nextInt(); long r=in.nextInt(); boolean ans=true; ArrayList<Long> arr=new ArrayList<>(); for(int i=1;i<=n;i++){ int rem=0; if(l%i!=0) rem=1; long val=(l/i + rem)*i; if(val<=r) arr.add(val); else {ans=false;break;} } if(ans){ System.out.println("YES"); for(long i:arr) System.out.print(i+" "); System.out.println(); } else System.out.println("NO"); } } }
Java
["4\n5 1 5\n9 1000 2000\n10 30 35\n1 1000000000 1000000000"]
1 second
["YES\n1 2 3 4 5\nYES\n1145 1926 1440 1220 1230 1350 1001 1000 1233\nNO\nYES\n1000000000"]
NoteIn the first test case, $$$\gcd(1,a_1),\gcd(2,a_2),\ldots,\gcd(5,a_5)$$$ are equal to $$$1$$$, $$$2$$$, $$$3$$$, $$$4$$$, $$$5$$$, respectively.
Java 11
standard input
[ "constructive algorithms", "math" ]
d2cc6efe7173a64482659ba59efeec16
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1\le t\le 10^4$$$) — the number of test cases. The description of the test cases follows. The first line contains three integers $$$n$$$, $$$l$$$, $$$r$$$ ($$$1 \le n \le 10^5$$$, $$$1\le l\le r\le 10^9$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,100
For each test case, if there is no solution, print "NO" (without quotes). You can print letters in any case (upper or lower). Otherwise, print "YES" (without quotes). In the next line, print $$$n$$$ integers $$$a_1,a_2,\ldots,a_n$$$ — the array you construct. If there are multiple solutions, you may output any.
standard output
PASSED
21230b148307e7144b9b178b7c009d41
train_108.jsonl
1657982100
You are given three integers $$$n$$$, $$$l$$$, and $$$r$$$. You need to construct an array $$$a_1,a_2,\dots,a_n$$$ ($$$l\le a_i\le r$$$) such that $$$\gcd(i,a_i)$$$ are all distinct or report there's no solution.Here $$$\gcd(x, y)$$$ denotes the greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$.
256 megabytes
import java.util.*; public class Main{ static int total=0; public static void main(String[] args) { Scanner in=new Scanner(System.in); int t=in.nextInt(); for(int h=0;h<t;h++){ long n=in.nextInt(); long l=in.nextInt(); long r=in.nextInt(); boolean ans=true; ArrayList<Long> arr=new ArrayList<>(); HashSet<Long> check=new HashSet<>(); int count=0; for(int i=1;i<=n;i++){ int rem=0; if(l%i!=0) rem=1; long val=(l/i + rem)*i; // while(check.contains(val)) val+=i; if(val<=r) { // check.add(val); arr.add(val); count+=1; } else {ans=false;break;} } if(arr.size()==n){ System.out.println("YES"); for(long i:arr) System.out.print(i+" "); System.out.println(); } else System.out.println("NO"); } } }
Java
["4\n5 1 5\n9 1000 2000\n10 30 35\n1 1000000000 1000000000"]
1 second
["YES\n1 2 3 4 5\nYES\n1145 1926 1440 1220 1230 1350 1001 1000 1233\nNO\nYES\n1000000000"]
NoteIn the first test case, $$$\gcd(1,a_1),\gcd(2,a_2),\ldots,\gcd(5,a_5)$$$ are equal to $$$1$$$, $$$2$$$, $$$3$$$, $$$4$$$, $$$5$$$, respectively.
Java 11
standard input
[ "constructive algorithms", "math" ]
d2cc6efe7173a64482659ba59efeec16
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1\le t\le 10^4$$$) — the number of test cases. The description of the test cases follows. The first line contains three integers $$$n$$$, $$$l$$$, $$$r$$$ ($$$1 \le n \le 10^5$$$, $$$1\le l\le r\le 10^9$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,100
For each test case, if there is no solution, print "NO" (without quotes). You can print letters in any case (upper or lower). Otherwise, print "YES" (without quotes). In the next line, print $$$n$$$ integers $$$a_1,a_2,\ldots,a_n$$$ — the array you construct. If there are multiple solutions, you may output any.
standard output
PASSED
92f30175da817221637a7a69d901a7ab
train_108.jsonl
1657982100
You are given three integers $$$n$$$, $$$l$$$, and $$$r$$$. You need to construct an array $$$a_1,a_2,\dots,a_n$$$ ($$$l\le a_i\le r$$$) such that $$$\gcd(i,a_i)$$$ are all distinct or report there's no solution.Here $$$\gcd(x, y)$$$ denotes the greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$.
256 megabytes
import java.util.*; public class DifferenceOfGCDs { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int t=sc.nextInt(); outer: while(t-->0) { int n=sc.nextInt(); int l=sc.nextInt(); int k=l; int r=sc.nextInt(); // if(t==10000-4318) { // System.out.println(n+"/"+l+"/"+r); // } List<Integer> list=new ArrayList<>(); for(int i=1;i<=n;i++) { while(true) { if(((l/i)*i)>r) { break; } if(l/i>0 && ((l/i)*i)>=k) { // System.out.println(i+" i"); // System.out.println(((l/i)*i)); list.add(((l/i)*i)); break; } else { l+=i; } } l=k; } // System.out.println(list); if(list.size()!=n) { System.out.println("NO"); continue outer; } System.out.println("YES"); for(int j=0;j<list.size();j++) { System.out.print(list.get(j)+" "); } System.out.println(); } } }
Java
["4\n5 1 5\n9 1000 2000\n10 30 35\n1 1000000000 1000000000"]
1 second
["YES\n1 2 3 4 5\nYES\n1145 1926 1440 1220 1230 1350 1001 1000 1233\nNO\nYES\n1000000000"]
NoteIn the first test case, $$$\gcd(1,a_1),\gcd(2,a_2),\ldots,\gcd(5,a_5)$$$ are equal to $$$1$$$, $$$2$$$, $$$3$$$, $$$4$$$, $$$5$$$, respectively.
Java 11
standard input
[ "constructive algorithms", "math" ]
d2cc6efe7173a64482659ba59efeec16
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1\le t\le 10^4$$$) — the number of test cases. The description of the test cases follows. The first line contains three integers $$$n$$$, $$$l$$$, $$$r$$$ ($$$1 \le n \le 10^5$$$, $$$1\le l\le r\le 10^9$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,100
For each test case, if there is no solution, print "NO" (without quotes). You can print letters in any case (upper or lower). Otherwise, print "YES" (without quotes). In the next line, print $$$n$$$ integers $$$a_1,a_2,\ldots,a_n$$$ — the array you construct. If there are multiple solutions, you may output any.
standard output
PASSED
b9a1c9e7763e8b5de49b028012ccc289
train_108.jsonl
1657982100
You are given three integers $$$n$$$, $$$l$$$, and $$$r$$$. You need to construct an array $$$a_1,a_2,\dots,a_n$$$ ($$$l\le a_i\le r$$$) such that $$$\gcd(i,a_i)$$$ are all distinct or report there's no solution.Here $$$\gcd(x, y)$$$ denotes the greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$.
256 megabytes
import java.util.Scanner; public class DifferenceOfGCDs { public static void main(String[] args) { Scanner input=new Scanner (System.in); int t=input.nextInt(); for(int i=0;i<t;i++) { int n=input.nextInt(); long arr[]=new long[n];boolean flag=true; long mini=input.nextInt(); long max=input.nextInt(); int count=0; for(long m=1;m<=n;m++) { if ((((mini-1)/m)+1)*m<=max) { arr[count]=(((mini-1)/m)+1)*m; count++; } else {System.out.println("NO"); flag=false; break; } } if(flag) { System.out.println("YES"); for(int s=0;s<n;s++) { System.out.print(arr[s]+" "); } System.out.println(); }} }}
Java
["4\n5 1 5\n9 1000 2000\n10 30 35\n1 1000000000 1000000000"]
1 second
["YES\n1 2 3 4 5\nYES\n1145 1926 1440 1220 1230 1350 1001 1000 1233\nNO\nYES\n1000000000"]
NoteIn the first test case, $$$\gcd(1,a_1),\gcd(2,a_2),\ldots,\gcd(5,a_5)$$$ are equal to $$$1$$$, $$$2$$$, $$$3$$$, $$$4$$$, $$$5$$$, respectively.
Java 11
standard input
[ "constructive algorithms", "math" ]
d2cc6efe7173a64482659ba59efeec16
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1\le t\le 10^4$$$) — the number of test cases. The description of the test cases follows. The first line contains three integers $$$n$$$, $$$l$$$, $$$r$$$ ($$$1 \le n \le 10^5$$$, $$$1\le l\le r\le 10^9$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,100
For each test case, if there is no solution, print "NO" (without quotes). You can print letters in any case (upper or lower). Otherwise, print "YES" (without quotes). In the next line, print $$$n$$$ integers $$$a_1,a_2,\ldots,a_n$$$ — the array you construct. If there are multiple solutions, you may output any.
standard output
PASSED
6f33434ad5f26633dd8e90aca12a416d
train_108.jsonl
1657982100
You are given three integers $$$n$$$, $$$l$$$, and $$$r$$$. You need to construct an array $$$a_1,a_2,\dots,a_n$$$ ($$$l\le a_i\le r$$$) such that $$$\gcd(i,a_i)$$$ are all distinct or report there's no solution.Here $$$\gcd(x, y)$$$ denotes the greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$.
256 megabytes
import java.util.ArrayList; import java.util.Scanner; public class DifferenceOfGCDs { public static void main(String[] args) { Scanner input=new Scanner (System.in); long t=input.nextInt(); for(int i=0;i<t;i++) { long n=input.nextInt(); ArrayList<Long> arr=new ArrayList<>();boolean flag=true; long mini=input.nextInt(); long max=input.nextInt(); int count=0; for(long m=1;m<=n;m++) { if ((((mini-1)/m)+1)*m<=max) { arr.add(count, (((mini-1)/m)+1)*m); count++; } else {System.out.println("NO"); flag=false; break; } } if(flag) { System.out.println("YES"); for(int s=0;s<n;s++) { System.out.print(arr.get(s)+" "); } System.out.println(); }} }}
Java
["4\n5 1 5\n9 1000 2000\n10 30 35\n1 1000000000 1000000000"]
1 second
["YES\n1 2 3 4 5\nYES\n1145 1926 1440 1220 1230 1350 1001 1000 1233\nNO\nYES\n1000000000"]
NoteIn the first test case, $$$\gcd(1,a_1),\gcd(2,a_2),\ldots,\gcd(5,a_5)$$$ are equal to $$$1$$$, $$$2$$$, $$$3$$$, $$$4$$$, $$$5$$$, respectively.
Java 11
standard input
[ "constructive algorithms", "math" ]
d2cc6efe7173a64482659ba59efeec16
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1\le t\le 10^4$$$) — the number of test cases. The description of the test cases follows. The first line contains three integers $$$n$$$, $$$l$$$, $$$r$$$ ($$$1 \le n \le 10^5$$$, $$$1\le l\le r\le 10^9$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,100
For each test case, if there is no solution, print "NO" (without quotes). You can print letters in any case (upper or lower). Otherwise, print "YES" (without quotes). In the next line, print $$$n$$$ integers $$$a_1,a_2,\ldots,a_n$$$ — the array you construct. If there are multiple solutions, you may output any.
standard output
PASSED
78c9990e7a0063ae18eb3583b7430618
train_108.jsonl
1657982100
You are given three integers $$$n$$$, $$$l$$$, and $$$r$$$. You need to construct an array $$$a_1,a_2,\dots,a_n$$$ ($$$l\le a_i\le r$$$) such that $$$\gcd(i,a_i)$$$ are all distinct or report there's no solution.Here $$$\gcd(x, y)$$$ denotes the greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$.
256 megabytes
import java.util.*; public class DifferenceOfGCDs { public static void main(String[] args) { Scanner input=new Scanner (System.in); int t=input.nextInt(); for(int i=0;i<t;i++) { StringBuilder sb = new StringBuilder(); int n=input.nextInt(); // ArrayList<Long> arr=new ArrayList<Long>(); boolean flag=true; int mini=input.nextInt(); int max=input.nextInt(); for(long m=1;m<=n;m++) { if (((mini-1)/m+1)*m<=max) { sb.append(((mini-1)/m+1)*m+" "); } else {System.out.println("NO"); flag=false; break;} } if(flag) { System.out.println("YES"); System.out.println(sb.toString()); }} }}
Java
["4\n5 1 5\n9 1000 2000\n10 30 35\n1 1000000000 1000000000"]
1 second
["YES\n1 2 3 4 5\nYES\n1145 1926 1440 1220 1230 1350 1001 1000 1233\nNO\nYES\n1000000000"]
NoteIn the first test case, $$$\gcd(1,a_1),\gcd(2,a_2),\ldots,\gcd(5,a_5)$$$ are equal to $$$1$$$, $$$2$$$, $$$3$$$, $$$4$$$, $$$5$$$, respectively.
Java 11
standard input
[ "constructive algorithms", "math" ]
d2cc6efe7173a64482659ba59efeec16
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1\le t\le 10^4$$$) — the number of test cases. The description of the test cases follows. The first line contains three integers $$$n$$$, $$$l$$$, $$$r$$$ ($$$1 \le n \le 10^5$$$, $$$1\le l\le r\le 10^9$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,100
For each test case, if there is no solution, print "NO" (without quotes). You can print letters in any case (upper or lower). Otherwise, print "YES" (without quotes). In the next line, print $$$n$$$ integers $$$a_1,a_2,\ldots,a_n$$$ — the array you construct. If there are multiple solutions, you may output any.
standard output
PASSED
f9593134621faffefa680eb16aa83b3a
train_108.jsonl
1657982100
You are given three integers $$$n$$$, $$$l$$$, and $$$r$$$. You need to construct an array $$$a_1,a_2,\dots,a_n$$$ ($$$l\le a_i\le r$$$) such that $$$\gcd(i,a_i)$$$ are all distinct or report there's no solution.Here $$$\gcd(x, y)$$$ denotes the greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$.
256 megabytes
import java.util.Scanner; import java.util.Arrays; import java.util.stream.Collectors; import static java.lang.Math.max; import static java.lang.Math.min; public class B { public static void main(String[] args) { Scanner input = new Scanner(System.in); int t = input.nextInt(); while (t > 0) { solution(input); t--; } } public static void solution(Scanner input) { int n = input.nextInt(); int l = input.nextInt(); int r = input.nextInt(); String[] a = new String[n]; String result = "YES"; for (int i=n; i > 0; i--) { int temp = (((l - 1) / i) + 1) * i; if (temp > r) { result = "NO"; } a[i-1] = String.valueOf(temp); } System.out.println(result); if (result.equals("YES")) { System.out.println(Arrays.stream(a).collect(Collectors.joining(" "))); } } public static int gcd(int a, int b) { int d = max(a, b); int c = min(a, b); if (c == 0) { return d; } if (d == 0) { return c; } return gcd(c, d % c); } }
Java
["4\n5 1 5\n9 1000 2000\n10 30 35\n1 1000000000 1000000000"]
1 second
["YES\n1 2 3 4 5\nYES\n1145 1926 1440 1220 1230 1350 1001 1000 1233\nNO\nYES\n1000000000"]
NoteIn the first test case, $$$\gcd(1,a_1),\gcd(2,a_2),\ldots,\gcd(5,a_5)$$$ are equal to $$$1$$$, $$$2$$$, $$$3$$$, $$$4$$$, $$$5$$$, respectively.
Java 11
standard input
[ "constructive algorithms", "math" ]
d2cc6efe7173a64482659ba59efeec16
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1\le t\le 10^4$$$) — the number of test cases. The description of the test cases follows. The first line contains three integers $$$n$$$, $$$l$$$, $$$r$$$ ($$$1 \le n \le 10^5$$$, $$$1\le l\le r\le 10^9$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,100
For each test case, if there is no solution, print "NO" (without quotes). You can print letters in any case (upper or lower). Otherwise, print "YES" (without quotes). In the next line, print $$$n$$$ integers $$$a_1,a_2,\ldots,a_n$$$ — the array you construct. If there are multiple solutions, you may output any.
standard output
PASSED
135ef6e434a6ea12d3f40d1187f13861
train_108.jsonl
1657982100
You are given three integers $$$n$$$, $$$l$$$, and $$$r$$$. You need to construct an array $$$a_1,a_2,\dots,a_n$$$ ($$$l\le a_i\le r$$$) such that $$$\gcd(i,a_i)$$$ are all distinct or report there's no solution.Here $$$\gcd(x, y)$$$ denotes the greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$.
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; public class Codechef { public static void main(String[] args) throws java.lang.Exception { PrintWriter out = new PrintWriter(System.out); FastScanner sc = new FastScanner(); int t=sc.nextInt(); while(t-->0) { int n=sc.nextInt(); int l=sc.nextInt(); int r=sc.nextInt(); int arr[]=new int[n]; int flag=0; for(int i=0;i<n;i++) { if(l%(i+1)==0) arr[i]=l; else if(r%(i+1)==0) arr[i]=r; else { if(((l/(i+1))*(i+1)+(i+1))<=r) { arr[i]=((l/(i+1))*(i+1)+(i+1)); } else flag=1; } } if(flag==1) System.out.println("NO"); else { System.out.println("YES"); for(int i=0;i<n;i++) { System.out.print(arr[i]+" "); } System.out.println(); } } out.flush(); } static class FastScanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } long nextLong() { return Long.parseLong(next()); } } }
Java
["4\n5 1 5\n9 1000 2000\n10 30 35\n1 1000000000 1000000000"]
1 second
["YES\n1 2 3 4 5\nYES\n1145 1926 1440 1220 1230 1350 1001 1000 1233\nNO\nYES\n1000000000"]
NoteIn the first test case, $$$\gcd(1,a_1),\gcd(2,a_2),\ldots,\gcd(5,a_5)$$$ are equal to $$$1$$$, $$$2$$$, $$$3$$$, $$$4$$$, $$$5$$$, respectively.
Java 11
standard input
[ "constructive algorithms", "math" ]
d2cc6efe7173a64482659ba59efeec16
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1\le t\le 10^4$$$) — the number of test cases. The description of the test cases follows. The first line contains three integers $$$n$$$, $$$l$$$, $$$r$$$ ($$$1 \le n \le 10^5$$$, $$$1\le l\le r\le 10^9$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,100
For each test case, if there is no solution, print "NO" (without quotes). You can print letters in any case (upper or lower). Otherwise, print "YES" (without quotes). In the next line, print $$$n$$$ integers $$$a_1,a_2,\ldots,a_n$$$ — the array you construct. If there are multiple solutions, you may output any.
standard output
PASSED
458d885d68a8d95ddc99496ae86e2191
train_108.jsonl
1657982100
You are given three integers $$$n$$$, $$$l$$$, and $$$r$$$. You need to construct an array $$$a_1,a_2,\dots,a_n$$$ ($$$l\le a_i\le r$$$) such that $$$\gcd(i,a_i)$$$ are all distinct or report there's no solution.Here $$$\gcd(x, y)$$$ denotes the greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$.
256 megabytes
/* package codechef; // don't place package name! */ import java.util.*; import java.lang.*; import java.io.*; /* Name of the class has to be "Main" only if the class is public. */ public class Codechef { public static void main (String[] args) throws java.lang.Exception { Scanner sc=new Scanner(System.in); int t=sc.nextInt(); while(t-->0) { int n=sc.nextInt(); int l=sc.nextInt(); int r=sc.nextInt(); int arr[]=new int[n]; int flag=0; for(int i=0;i<n;i++) { if(l%(i+1)==0) arr[i]=l; else if(r%(i+1)==0) arr[i]=r; else { if(((l/(i+1))*(i+1)+(i+1))<=r) { arr[i]=((l/(i+1))*(i+1)+(i+1)); } else flag=1; } } if(flag==1) System.out.println("NO"); else { System.out.println("YES"); for(int i=0;i<n;i++) { System.out.print(arr[i]+" "); } System.out.println(); } } // your code goes here } }
Java
["4\n5 1 5\n9 1000 2000\n10 30 35\n1 1000000000 1000000000"]
1 second
["YES\n1 2 3 4 5\nYES\n1145 1926 1440 1220 1230 1350 1001 1000 1233\nNO\nYES\n1000000000"]
NoteIn the first test case, $$$\gcd(1,a_1),\gcd(2,a_2),\ldots,\gcd(5,a_5)$$$ are equal to $$$1$$$, $$$2$$$, $$$3$$$, $$$4$$$, $$$5$$$, respectively.
Java 11
standard input
[ "constructive algorithms", "math" ]
d2cc6efe7173a64482659ba59efeec16
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1\le t\le 10^4$$$) — the number of test cases. The description of the test cases follows. The first line contains three integers $$$n$$$, $$$l$$$, $$$r$$$ ($$$1 \le n \le 10^5$$$, $$$1\le l\le r\le 10^9$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,100
For each test case, if there is no solution, print "NO" (without quotes). You can print letters in any case (upper or lower). Otherwise, print "YES" (without quotes). In the next line, print $$$n$$$ integers $$$a_1,a_2,\ldots,a_n$$$ — the array you construct. If there are multiple solutions, you may output any.
standard output
PASSED
992759c3a5e9ee2d078e5d6879a50e48
train_108.jsonl
1657982100
You are given three integers $$$n$$$, $$$l$$$, and $$$r$$$. You need to construct an array $$$a_1,a_2,\dots,a_n$$$ ($$$l\le a_i\le r$$$) such that $$$\gcd(i,a_i)$$$ are all distinct or report there's no solution.Here $$$\gcd(x, y)$$$ denotes the greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$.
256 megabytes
import java.util.*; import java.io.*; public class Main { static long mod = 1000000007; static int[]parent; static int[]rank; static PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); public static void main(String[] args) throws IOException { FastReader sc = new FastReader(); int t = sc.nextInt(); while( t-- > 0) { int n=sc.nextInt(); int l=sc.nextInt(); int r=sc.nextInt(); // int[]temp=new int[n+1]; // if(r-l+1<n){ // out.println("No"); // continue; // } ArrayList<Integer>ans=new ArrayList<>(); ans.add(l); int c=1; for(int i=2;i<=n;i++){ if(l%i==0){ ans.add(l); c++; }else{ int mul=l/i; int val=i*mul+i; //int val=(mul+1)*i; if(val>=l && val<=r){ ans.add(val); c++; }else{ break; } } } if(c==n){ out.println("Yes"); for(int val:ans){ out.print(val+" "); } }else{ out.print("No"); } out.println(); } out.flush(); } public static int find(int x){ if(parent[x]==x){ return x; }else{ int px=parent[x]; int lead=find(px); parent[x]=lead; return lead; } } public static class Pair{ long first; long second; Pair(long first,long second){ this.first=first; this.second=second; } } public static void union(int l1,int l2){ if(rank[l1]>rank[l2]){ parent[l2]=l1; rank[l1]++; }else if(rank[l2]>rank[l1]){ parent[l1]=l2; rank[l2]++; }else{ parent[l1]=l2; rank[l2]++; } } public static void reverse(Long[]arr,int i,int j){ while(i<=j){ long temp=arr[i]; arr[i]=arr[j]; arr[j]=temp; i++; j--; } } public static int gcd(int n1,int n2){ while(n1%n2!=0){ int rem=n2%n1; n2=n1; n1=rem; } return n1; } // static class Pair{ // int val; // int bd; // Pair(int val,int bd){ // this.val=val; // this.bd=bd; // } // } public static int binarySearch(int[]arr,int data){ int left = 0; int right = arr.length - 1; int ceil = -1; int floor = 0; while(left <= right){ int mid = (left + right) / 2; if(data > arr[mid]){ left = mid + 1; floor = arr[mid]; } else if(data < arr[mid]){ right = mid - 1; ceil = mid+1; } else { floor = arr[mid]; ceil = mid+1; break; } } return ceil; } /* * WARNING -> DONT EVER USE ARRAYS.SORT() IN ANY WAY. * A B C are easy just dont give up , you can do it! * FIRST AND VERY IMP -> READ AND UNDERSTAND THE QUESTION VERY CAREFULLY. * WARNING -> DONT CODE BULLSHIT , ALWAYS CHECK THE LOGIC ON MULTIPLE TESTCASES AND EDGECASES BEFORE. * SECOND -> TRY TO FIND RELEVENT PATTERN SMARTLY. * WARNING -> IF YOU THINK YOUR SOLUION IS JUST DUMB DONT SUBMIT IT BEFORE RECHECKING ON YOUR END. */ public static boolean ifpowof2(long n ) { return ((n&(n-1)) == 0); } static boolean isprime(long x ) { if( x== 2) { return true; } if( x%2 == 0) { return false; } for( long i = 3 ;i*i <= x ;i+=2) { if( x%i == 0) { return false; } } return true; } static boolean[] sieveOfEratosthenes(long n) { boolean prime[] = new boolean[(int)n + 1]; for (int i = 0; i <= n; i++) { prime[i] = true; } for (long p = 2; p * p <= n; p++) { if (prime[(int)p] == true) { for (long i = p * p; i <= n; i += p) prime[(int)i] = false; } } return prime; } public static int[] nextLargerElement(int[] arr, int n) { Stack<Integer> stack = new Stack<>(); int rtrn[] = new int[n]; rtrn[n-1] = -1; stack.push( n-1); for( int i = n-2 ;i >= 0 ; i--){ int temp = arr[i]; int lol = -1; while( !stack.isEmpty() && arr[stack.peek()] <= temp){ if(arr[stack.peek()] == temp ) { lol = stack.peek(); } stack.pop(); } if( stack.isEmpty()){ if( lol != -1) { rtrn[i] = lol; } else { rtrn[i] = -1; } } else{ rtrn[i] = stack.peek(); } stack.push( i); } return rtrn; } static void mysort(int[] arr) { for(int i=0;i<arr.length;i++) { int rand = (int) (Math.random() * arr.length); int loc = arr[rand]; arr[rand] = arr[i]; arr[i] = loc; } Arrays.sort(arr); } static void mySort(Long[] arr) { for(int i=0;i<arr.length;i++) { int rand = (int) (Math.random() * arr.length); long loc = arr[rand]; arr[rand] = arr[i]; arr[i] = loc; } Arrays.sort(arr); } static long gcd(long a, long b) { if (a == 0) return b; return gcd(b % a, a); } static long lcm(long a, long b) { return (a / gcd(a, b)) * b; } static long rightmostsetbit(long n) { return n&-n; } static long leftmostsetbit(long n) { long k = (long)(Math.log(n) / Math.log(2)); return k; } static HashMap<Long,Long> primefactor( long n){ HashMap<Long ,Long> hm = new HashMap<>(); long temp = 0; while( n%2 == 0) { temp++; n/=2; } if( temp!= 0) { hm.put( 2L, temp); } long c = (long)Math.sqrt(n); for( long i = 3 ; i <= c ; i+=2) { temp = 0; while( n% i == 0) { temp++; n/=i; } if( temp!= 0) { hm.put( i, temp); } } if( n!= 1) { hm.put( n , 1L); } return hm; } static ArrayList<Integer> allfactors(int abs) { HashMap<Integer,Integer> hm = new HashMap<>(); ArrayList<Integer> rtrn = new ArrayList<>(); for( int i = 2 ;i*i <= abs; i++) { if( abs% i == 0) { hm.put( i , 0); hm.put(abs/i, 0); } } for( int x : hm.keySet()) { rtrn.add(x); } if( abs != 0) { rtrn.add(abs); } return rtrn; } public static int[][] prefixsum( int n , int m , int arr[][] ){ int prefixsum[][] = new int[n+1][m+1]; for( int i = 1 ;i <= n ;i++) { for( int j = 1 ; j<= m ; j++) { int toadd = 0; if( arr[i-1][j-1] == 1) { toadd = 1; } prefixsum[i][j] = toadd + prefixsum[i][j-1] + prefixsum[i-1][j] - prefixsum[i-1][j-1]; } } return prefixsum; } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["4\n5 1 5\n9 1000 2000\n10 30 35\n1 1000000000 1000000000"]
1 second
["YES\n1 2 3 4 5\nYES\n1145 1926 1440 1220 1230 1350 1001 1000 1233\nNO\nYES\n1000000000"]
NoteIn the first test case, $$$\gcd(1,a_1),\gcd(2,a_2),\ldots,\gcd(5,a_5)$$$ are equal to $$$1$$$, $$$2$$$, $$$3$$$, $$$4$$$, $$$5$$$, respectively.
Java 11
standard input
[ "constructive algorithms", "math" ]
d2cc6efe7173a64482659ba59efeec16
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1\le t\le 10^4$$$) — the number of test cases. The description of the test cases follows. The first line contains three integers $$$n$$$, $$$l$$$, $$$r$$$ ($$$1 \le n \le 10^5$$$, $$$1\le l\le r\le 10^9$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,100
For each test case, if there is no solution, print "NO" (without quotes). You can print letters in any case (upper or lower). Otherwise, print "YES" (without quotes). In the next line, print $$$n$$$ integers $$$a_1,a_2,\ldots,a_n$$$ — the array you construct. If there are multiple solutions, you may output any.
standard output
PASSED
ac5de6807c63e40ef33df935f48a13d7
train_108.jsonl
1657982100
You are given three integers $$$n$$$, $$$l$$$, and $$$r$$$. You need to construct an array $$$a_1,a_2,\dots,a_n$$$ ($$$l\le a_i\le r$$$) such that $$$\gcd(i,a_i)$$$ are all distinct or report there's no solution.Here $$$\gcd(x, y)$$$ denotes the greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$.
256 megabytes
import java.util.*; import java.io.*; public class Main { static long mod = 1000000007; static int[]parent; static int[]rank; static PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); public static void main(String[] args) throws IOException { FastReader sc = new FastReader(); int t = sc.nextInt(); while( t-- > 0) { int n=sc.nextInt(); int l=sc.nextInt(); int r=sc.nextInt(); // int[]temp=new int[n+1]; // if(r-l+1<n){ // out.println("No"); // continue; // } ArrayList<Integer>ans=new ArrayList<>(); ans.add(l); int c=1; for(int i=2;i<=n;i++){ if(l%i==0){ ans.add(l); c++; }else{ int mul=l/i; // int val=i*mul+i; int val=(mul+1)*i; if(val>=l && val<=r){ ans.add(val); c++; }else{ break; } } } if(c==n){ out.println("Yes"); for(int val:ans){ out.print(val+" "); } }else{ out.print("No"); } out.println(); } out.flush(); } public static int find(int x){ if(parent[x]==x){ return x; }else{ int px=parent[x]; int lead=find(px); parent[x]=lead; return lead; } } public static class Pair{ long first; long second; Pair(long first,long second){ this.first=first; this.second=second; } } public static void union(int l1,int l2){ if(rank[l1]>rank[l2]){ parent[l2]=l1; rank[l1]++; }else if(rank[l2]>rank[l1]){ parent[l1]=l2; rank[l2]++; }else{ parent[l1]=l2; rank[l2]++; } } public static void reverse(Long[]arr,int i,int j){ while(i<=j){ long temp=arr[i]; arr[i]=arr[j]; arr[j]=temp; i++; j--; } } public static int gcd(int n1,int n2){ while(n1%n2!=0){ int rem=n2%n1; n2=n1; n1=rem; } return n1; } // static class Pair{ // int val; // int bd; // Pair(int val,int bd){ // this.val=val; // this.bd=bd; // } // } public static int binarySearch(int[]arr,int data){ int left = 0; int right = arr.length - 1; int ceil = -1; int floor = 0; while(left <= right){ int mid = (left + right) / 2; if(data > arr[mid]){ left = mid + 1; floor = arr[mid]; } else if(data < arr[mid]){ right = mid - 1; ceil = mid+1; } else { floor = arr[mid]; ceil = mid+1; break; } } return ceil; } /* * WARNING -> DONT EVER USE ARRAYS.SORT() IN ANY WAY. * A B C are easy just dont give up , you can do it! * FIRST AND VERY IMP -> READ AND UNDERSTAND THE QUESTION VERY CAREFULLY. * WARNING -> DONT CODE BULLSHIT , ALWAYS CHECK THE LOGIC ON MULTIPLE TESTCASES AND EDGECASES BEFORE. * SECOND -> TRY TO FIND RELEVENT PATTERN SMARTLY. * WARNING -> IF YOU THINK YOUR SOLUION IS JUST DUMB DONT SUBMIT IT BEFORE RECHECKING ON YOUR END. */ public static boolean ifpowof2(long n ) { return ((n&(n-1)) == 0); } static boolean isprime(long x ) { if( x== 2) { return true; } if( x%2 == 0) { return false; } for( long i = 3 ;i*i <= x ;i+=2) { if( x%i == 0) { return false; } } return true; } static boolean[] sieveOfEratosthenes(long n) { boolean prime[] = new boolean[(int)n + 1]; for (int i = 0; i <= n; i++) { prime[i] = true; } for (long p = 2; p * p <= n; p++) { if (prime[(int)p] == true) { for (long i = p * p; i <= n; i += p) prime[(int)i] = false; } } return prime; } public static int[] nextLargerElement(int[] arr, int n) { Stack<Integer> stack = new Stack<>(); int rtrn[] = new int[n]; rtrn[n-1] = -1; stack.push( n-1); for( int i = n-2 ;i >= 0 ; i--){ int temp = arr[i]; int lol = -1; while( !stack.isEmpty() && arr[stack.peek()] <= temp){ if(arr[stack.peek()] == temp ) { lol = stack.peek(); } stack.pop(); } if( stack.isEmpty()){ if( lol != -1) { rtrn[i] = lol; } else { rtrn[i] = -1; } } else{ rtrn[i] = stack.peek(); } stack.push( i); } return rtrn; } static void mysort(int[] arr) { for(int i=0;i<arr.length;i++) { int rand = (int) (Math.random() * arr.length); int loc = arr[rand]; arr[rand] = arr[i]; arr[i] = loc; } Arrays.sort(arr); } static void mySort(Long[] arr) { for(int i=0;i<arr.length;i++) { int rand = (int) (Math.random() * arr.length); long loc = arr[rand]; arr[rand] = arr[i]; arr[i] = loc; } Arrays.sort(arr); } static long gcd(long a, long b) { if (a == 0) return b; return gcd(b % a, a); } static long lcm(long a, long b) { return (a / gcd(a, b)) * b; } static long rightmostsetbit(long n) { return n&-n; } static long leftmostsetbit(long n) { long k = (long)(Math.log(n) / Math.log(2)); return k; } static HashMap<Long,Long> primefactor( long n){ HashMap<Long ,Long> hm = new HashMap<>(); long temp = 0; while( n%2 == 0) { temp++; n/=2; } if( temp!= 0) { hm.put( 2L, temp); } long c = (long)Math.sqrt(n); for( long i = 3 ; i <= c ; i+=2) { temp = 0; while( n% i == 0) { temp++; n/=i; } if( temp!= 0) { hm.put( i, temp); } } if( n!= 1) { hm.put( n , 1L); } return hm; } static ArrayList<Integer> allfactors(int abs) { HashMap<Integer,Integer> hm = new HashMap<>(); ArrayList<Integer> rtrn = new ArrayList<>(); for( int i = 2 ;i*i <= abs; i++) { if( abs% i == 0) { hm.put( i , 0); hm.put(abs/i, 0); } } for( int x : hm.keySet()) { rtrn.add(x); } if( abs != 0) { rtrn.add(abs); } return rtrn; } public static int[][] prefixsum( int n , int m , int arr[][] ){ int prefixsum[][] = new int[n+1][m+1]; for( int i = 1 ;i <= n ;i++) { for( int j = 1 ; j<= m ; j++) { int toadd = 0; if( arr[i-1][j-1] == 1) { toadd = 1; } prefixsum[i][j] = toadd + prefixsum[i][j-1] + prefixsum[i-1][j] - prefixsum[i-1][j-1]; } } return prefixsum; } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["4\n5 1 5\n9 1000 2000\n10 30 35\n1 1000000000 1000000000"]
1 second
["YES\n1 2 3 4 5\nYES\n1145 1926 1440 1220 1230 1350 1001 1000 1233\nNO\nYES\n1000000000"]
NoteIn the first test case, $$$\gcd(1,a_1),\gcd(2,a_2),\ldots,\gcd(5,a_5)$$$ are equal to $$$1$$$, $$$2$$$, $$$3$$$, $$$4$$$, $$$5$$$, respectively.
Java 11
standard input
[ "constructive algorithms", "math" ]
d2cc6efe7173a64482659ba59efeec16
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1\le t\le 10^4$$$) — the number of test cases. The description of the test cases follows. The first line contains three integers $$$n$$$, $$$l$$$, $$$r$$$ ($$$1 \le n \le 10^5$$$, $$$1\le l\le r\le 10^9$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,100
For each test case, if there is no solution, print "NO" (without quotes). You can print letters in any case (upper or lower). Otherwise, print "YES" (without quotes). In the next line, print $$$n$$$ integers $$$a_1,a_2,\ldots,a_n$$$ — the array you construct. If there are multiple solutions, you may output any.
standard output
PASSED
8732c42ebccda5145edca84b27323470
train_108.jsonl
1657982100
You are given three integers $$$n$$$, $$$l$$$, and $$$r$$$. You need to construct an array $$$a_1,a_2,\dots,a_n$$$ ($$$l\le a_i\le r$$$) such that $$$\gcd(i,a_i)$$$ are all distinct or report there's no solution.Here $$$\gcd(x, y)$$$ denotes the greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$.
256 megabytes
import java.util.*; import java.io.*; public class mm { public static void main (String[] args) throws IOException { Scanner sc=new Scanner (System.in); int t=sc.nextInt(); while(t-->0){ long n=sc.nextLong(); long l=sc.nextLong(); long r=sc.nextLong(); long i=1; List<Long> ll=new ArrayList<>(); for( i=1;i<=n;i++){ long a=l%i; long b=l+(i-a); if(b<=r && a!=0) ll.add(b); else if(a==0) ll.add(l); } // System.out.println(ll); if(ll.size()==n){ System.out.println("YES"); for(long j:ll) System.out.print(j+" "); System.out.println(); } else System.out.println("NO"); } } }
Java
["4\n5 1 5\n9 1000 2000\n10 30 35\n1 1000000000 1000000000"]
1 second
["YES\n1 2 3 4 5\nYES\n1145 1926 1440 1220 1230 1350 1001 1000 1233\nNO\nYES\n1000000000"]
NoteIn the first test case, $$$\gcd(1,a_1),\gcd(2,a_2),\ldots,\gcd(5,a_5)$$$ are equal to $$$1$$$, $$$2$$$, $$$3$$$, $$$4$$$, $$$5$$$, respectively.
Java 11
standard input
[ "constructive algorithms", "math" ]
d2cc6efe7173a64482659ba59efeec16
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1\le t\le 10^4$$$) — the number of test cases. The description of the test cases follows. The first line contains three integers $$$n$$$, $$$l$$$, $$$r$$$ ($$$1 \le n \le 10^5$$$, $$$1\le l\le r\le 10^9$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,100
For each test case, if there is no solution, print "NO" (without quotes). You can print letters in any case (upper or lower). Otherwise, print "YES" (without quotes). In the next line, print $$$n$$$ integers $$$a_1,a_2,\ldots,a_n$$$ — the array you construct. If there are multiple solutions, you may output any.
standard output
PASSED
28864bcfcea34920c6d60fdd2faa3f6a
train_108.jsonl
1657982100
You are given three integers $$$n$$$, $$$l$$$, and $$$r$$$. You need to construct an array $$$a_1,a_2,\dots,a_n$$$ ($$$l\le a_i\le r$$$) such that $$$\gcd(i,a_i)$$$ are all distinct or report there's no solution.Here $$$\gcd(x, y)$$$ denotes the greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$.
256 megabytes
import java.util.*; public class Main { public static long gcd(long a,long b) { if(a==0)return b; return gcd(b%a,a); } public static void main(String[] args) { Scanner obj=new Scanner(System.in); int len=obj.nextInt(); while(len--!=0) { int n=obj.nextInt(); int l=obj.nextInt(); int r=obj.nextInt(); boolean ans=true; long[] a=new long[n+1]; a[1]=l; int d=l; for(int i=2;i<=n;i++) { int r1=l%i; int n1=l-r1; if(r1!=0)n1+=i; if(n1>r)ans=false; a[i]=n1; } if(ans) { System.out.println("YES"); for(int i=1;i<=n;i++)System.out.print(a[i]+" "); System.out.println(); } else System.out.println("NO"); } } }
Java
["4\n5 1 5\n9 1000 2000\n10 30 35\n1 1000000000 1000000000"]
1 second
["YES\n1 2 3 4 5\nYES\n1145 1926 1440 1220 1230 1350 1001 1000 1233\nNO\nYES\n1000000000"]
NoteIn the first test case, $$$\gcd(1,a_1),\gcd(2,a_2),\ldots,\gcd(5,a_5)$$$ are equal to $$$1$$$, $$$2$$$, $$$3$$$, $$$4$$$, $$$5$$$, respectively.
Java 11
standard input
[ "constructive algorithms", "math" ]
d2cc6efe7173a64482659ba59efeec16
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1\le t\le 10^4$$$) — the number of test cases. The description of the test cases follows. The first line contains three integers $$$n$$$, $$$l$$$, $$$r$$$ ($$$1 \le n \le 10^5$$$, $$$1\le l\le r\le 10^9$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,100
For each test case, if there is no solution, print "NO" (without quotes). You can print letters in any case (upper or lower). Otherwise, print "YES" (without quotes). In the next line, print $$$n$$$ integers $$$a_1,a_2,\ldots,a_n$$$ — the array you construct. If there are multiple solutions, you may output any.
standard output
PASSED
e49c67dbbc4013acb9cd7382de5c964e
train_108.jsonl
1657982100
You are given three integers $$$n$$$, $$$l$$$, and $$$r$$$. You need to construct an array $$$a_1,a_2,\dots,a_n$$$ ($$$l\le a_i\le r$$$) such that $$$\gcd(i,a_i)$$$ are all distinct or report there's no solution.Here $$$\gcd(x, y)$$$ denotes the greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$.
256 megabytes
import java.util.Scanner; public class div2B { public static void main(String[] args) { Scanner in = new Scanner(System.in); int k = in.nextInt(); for(int j =0; j<k ;j ++) { int n =in.nextInt(); long l =in.nextLong(); long q =in.nextLong(); long[] niz = new long[n]; niz[0] = l; int ok =0; for(int i = 1; i<n; i++) { if((l+i)%(i+1)==0 && l+i<=q) { niz[i] = (l+i); } else if((l+i)%(i+1)==0 && l+i>q) { System.out.println("NO"); ok=1; break;} else { niz[i] = (l+i)-((l+i)%(i+1)); if(niz[i]<l || niz[i]>q) { System.out.println("NO"); ok=1; break; } } } if(ok==0) { System.out.println("YES"); for(int i=0; i<n; i++) { System.out.print(niz[i]+" "); } System.out.println(); } } } }
Java
["4\n5 1 5\n9 1000 2000\n10 30 35\n1 1000000000 1000000000"]
1 second
["YES\n1 2 3 4 5\nYES\n1145 1926 1440 1220 1230 1350 1001 1000 1233\nNO\nYES\n1000000000"]
NoteIn the first test case, $$$\gcd(1,a_1),\gcd(2,a_2),\ldots,\gcd(5,a_5)$$$ are equal to $$$1$$$, $$$2$$$, $$$3$$$, $$$4$$$, $$$5$$$, respectively.
Java 11
standard input
[ "constructive algorithms", "math" ]
d2cc6efe7173a64482659ba59efeec16
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1\le t\le 10^4$$$) — the number of test cases. The description of the test cases follows. The first line contains three integers $$$n$$$, $$$l$$$, $$$r$$$ ($$$1 \le n \le 10^5$$$, $$$1\le l\le r\le 10^9$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,100
For each test case, if there is no solution, print "NO" (without quotes). You can print letters in any case (upper or lower). Otherwise, print "YES" (without quotes). In the next line, print $$$n$$$ integers $$$a_1,a_2,\ldots,a_n$$$ — the array you construct. If there are multiple solutions, you may output any.
standard output
PASSED
768f5049c6870c3b21f91fb44817836c
train_108.jsonl
1657982100
You are given three integers $$$n$$$, $$$l$$$, and $$$r$$$. You need to construct an array $$$a_1,a_2,\dots,a_n$$$ ($$$l\le a_i\le r$$$) such that $$$\gcd(i,a_i)$$$ are all distinct or report there's no solution.Here $$$\gcd(x, y)$$$ denotes the greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$.
256 megabytes
import java.util.*; import java.io.*; import static java.lang.Math.*; public class Main extends PrintWriter { Main() { super(System.out); } static boolean cases = true; // Solution void solve(int t) { int n = sc.nextInt(); int l = sc.nextInt(); int r = sc.nextInt(); int ans[] = new int[n]; for (int i = 0; i < n; i++) { if (l % (i + 1) == 0) { ans[i] = l; } else { ans[i] = (l + i + 1) - (l % (i + 1)); } if (ans[i] > r) { println("NO"); return; } } println("YES"); for (int i = 0; i < n; i++) { print(ans[i] + " "); } println(); } int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } void sort(int[] a) { ArrayList<Integer> l = new ArrayList<>(); for (int i : a) l.add(i); Collections.sort(l); for (int i = 0; i < a.length; i++) a[i] = l.get(i); } public static void main(String[] args) { Main obj = new Main(); int c = 1; for (int t = (cases ? sc.nextInt() : 0); t > 1; t--, c++) obj.solve(c); obj.solve(c); obj.flush(); } static class FastScanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readIntArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } char[] readCharArray(int n) { char a[] = new char[n]; String s = sc.next(); for (int i = 0; i < n; i++) { a[i] = s.charAt(i); } return a; } long[] readLongArray(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } long nextLong() { return Long.parseLong(next()); } } final int ima = Integer.MAX_VALUE; final int imi = Integer.MIN_VALUE; final long lma = Long.MAX_VALUE; final long lmi = Long.MIN_VALUE; static final long mod = (long) 1e9 + 7; private static final FastScanner sc = new FastScanner(); private PrintWriter out = new PrintWriter(System.out); }
Java
["4\n5 1 5\n9 1000 2000\n10 30 35\n1 1000000000 1000000000"]
1 second
["YES\n1 2 3 4 5\nYES\n1145 1926 1440 1220 1230 1350 1001 1000 1233\nNO\nYES\n1000000000"]
NoteIn the first test case, $$$\gcd(1,a_1),\gcd(2,a_2),\ldots,\gcd(5,a_5)$$$ are equal to $$$1$$$, $$$2$$$, $$$3$$$, $$$4$$$, $$$5$$$, respectively.
Java 11
standard input
[ "constructive algorithms", "math" ]
d2cc6efe7173a64482659ba59efeec16
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1\le t\le 10^4$$$) — the number of test cases. The description of the test cases follows. The first line contains three integers $$$n$$$, $$$l$$$, $$$r$$$ ($$$1 \le n \le 10^5$$$, $$$1\le l\le r\le 10^9$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,100
For each test case, if there is no solution, print "NO" (without quotes). You can print letters in any case (upper or lower). Otherwise, print "YES" (without quotes). In the next line, print $$$n$$$ integers $$$a_1,a_2,\ldots,a_n$$$ — the array you construct. If there are multiple solutions, you may output any.
standard output
PASSED
86c10a0ba0510df8f19725298fb901c6
train_108.jsonl
1657982100
You are given three integers $$$n$$$, $$$l$$$, and $$$r$$$. You need to construct an array $$$a_1,a_2,\dots,a_n$$$ ($$$l\le a_i\le r$$$) such that $$$\gcd(i,a_i)$$$ are all distinct or report there's no solution.Here $$$\gcd(x, y)$$$ denotes the greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$.
256 megabytes
import java.util.Scanner; public class B { static Scanner sc = new Scanner(System.in); public static void main(String[] args) { int t = sc.nextInt(); for (int i = 0; i < t; i++) { solve(); } } public static void solve(){ int n=sc.nextInt(); int l=sc.nextInt(); int r= sc.nextInt(); int[] ans=new int[n]; for (int j = 1; j <= n; j++) { int x=j*(r/j); if(x<l){ System.out.println("NO"); return; }else{ ans[j-1]=x; } } System.out.println("YES"); for (int j = 0; j < n; j++) { System.out.printf(ans[j]+" "); } System.out.println(); } }
Java
["4\n5 1 5\n9 1000 2000\n10 30 35\n1 1000000000 1000000000"]
1 second
["YES\n1 2 3 4 5\nYES\n1145 1926 1440 1220 1230 1350 1001 1000 1233\nNO\nYES\n1000000000"]
NoteIn the first test case, $$$\gcd(1,a_1),\gcd(2,a_2),\ldots,\gcd(5,a_5)$$$ are equal to $$$1$$$, $$$2$$$, $$$3$$$, $$$4$$$, $$$5$$$, respectively.
Java 11
standard input
[ "constructive algorithms", "math" ]
d2cc6efe7173a64482659ba59efeec16
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1\le t\le 10^4$$$) — the number of test cases. The description of the test cases follows. The first line contains three integers $$$n$$$, $$$l$$$, $$$r$$$ ($$$1 \le n \le 10^5$$$, $$$1\le l\le r\le 10^9$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,100
For each test case, if there is no solution, print "NO" (without quotes). You can print letters in any case (upper or lower). Otherwise, print "YES" (without quotes). In the next line, print $$$n$$$ integers $$$a_1,a_2,\ldots,a_n$$$ — the array you construct. If there are multiple solutions, you may output any.
standard output
PASSED
ed920a6a563761cd8916a9fd0a6b2402
train_108.jsonl
1657982100
You are given three integers $$$n$$$, $$$l$$$, and $$$r$$$. You need to construct an array $$$a_1,a_2,\dots,a_n$$$ ($$$l\le a_i\le r$$$) such that $$$\gcd(i,a_i)$$$ are all distinct or report there's no solution.Here $$$\gcd(x, y)$$$ denotes the greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$.
256 megabytes
import java.util.ArrayList; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.IOException; public class DifferenceOfGCSs { static class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream( new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') { if (cnt != 0) { break; } else { continue; } } buf[cnt++] = (byte)c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') { c = read(); } boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } public static void main(String[] args) throws IOException { Reader in = new Reader(); int t = in.nextInt(); for ( int p = 0; p < t; p++){ int n = in.nextInt(); int l = in.nextInt(); int r = in.nextInt(); ArrayList <Integer> list = new ArrayList<>(1); for ( int i = 1; i <= n; i++){ int k =(int)Math.ceil((1.0*l)/i) * i; if ( k <= r) list.add(k); else { System.out.println("NO"); break; } } if (list.size() == n && list.get(n-1) <= r) { System.out.println("YES"); for ( int i = 0; i < n; i++){ System.out.print(list.get(i) + " "); } System.out.println(); } } } }
Java
["4\n5 1 5\n9 1000 2000\n10 30 35\n1 1000000000 1000000000"]
1 second
["YES\n1 2 3 4 5\nYES\n1145 1926 1440 1220 1230 1350 1001 1000 1233\nNO\nYES\n1000000000"]
NoteIn the first test case, $$$\gcd(1,a_1),\gcd(2,a_2),\ldots,\gcd(5,a_5)$$$ are equal to $$$1$$$, $$$2$$$, $$$3$$$, $$$4$$$, $$$5$$$, respectively.
Java 11
standard input
[ "constructive algorithms", "math" ]
d2cc6efe7173a64482659ba59efeec16
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1\le t\le 10^4$$$) — the number of test cases. The description of the test cases follows. The first line contains three integers $$$n$$$, $$$l$$$, $$$r$$$ ($$$1 \le n \le 10^5$$$, $$$1\le l\le r\le 10^9$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,100
For each test case, if there is no solution, print "NO" (without quotes). You can print letters in any case (upper or lower). Otherwise, print "YES" (without quotes). In the next line, print $$$n$$$ integers $$$a_1,a_2,\ldots,a_n$$$ — the array you construct. If there are multiple solutions, you may output any.
standard output
PASSED
c3b3ecb273ea1010f47c8d68347887fc
train_108.jsonl
1657982100
You are given three integers $$$n$$$, $$$l$$$, and $$$r$$$. You need to construct an array $$$a_1,a_2,\dots,a_n$$$ ($$$l\le a_i\le r$$$) such that $$$\gcd(i,a_i)$$$ are all distinct or report there's no solution.Here $$$\gcd(x, y)$$$ denotes the greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$.
256 megabytes
import java.io.*; import java.util.*; import java.util.HashSet; import java.util.StringTokenizer; public class cf799 { static class FastReader{ BufferedReader br; StringTokenizer st; public FastReader(){ br=new BufferedReader(new InputStreamReader(System.in)); } String next(){ while(st==null || !st.hasMoreTokens()){ try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt(){ return Integer.parseInt(next()); } long nextLong(){ return Long.parseLong(next()); } double nextDouble(){ return Double.parseDouble(next()); } String nextLine(){ String str=""; try { str=br.readLine().trim(); } catch (Exception e) { e.printStackTrace(); } return str; } } static class FastWriter { private final BufferedWriter bw; public FastWriter() { this.bw = new BufferedWriter(new OutputStreamWriter(System.out)); } public void print(Object object) throws IOException { bw.append("" + object); } public void println(Object object) throws IOException { print(object); bw.append("\n"); } public void close() throws IOException { bw.close(); } } public static void main(String[] args) { try { FastReader sc = new FastReader(); FastWriter out = new FastWriter(); //Scanner sc=new Scanner(System.in); int t = sc.nextInt(); while (t-- > 0) { int n=sc.nextInt(); int l=sc.nextInt(); int r=sc.nextInt(); List<Integer> ll=new ArrayList<>(); ll.add(l); boolean check=false; for(int i=2;i<=n;i++){ int m=l/i; m=(m+1)*i; if(l%i==0){ ll.add(l); }else{ if(m<=r){ ll.add(m); }else{ check=true; break; } } } if(check){ System.out.println("NO"); }else{ System.out.println("YES"); for(int i:ll){ System.out.print(i+" "); } System.out.println(); } } }catch (Exception e) { return; } } private static void ff(ArrayList<Integer> ar , ArrayList<Integer> ar2) { for (Integer integer : ar2) { int count = 0; int num = integer; while (num % 2 == 0) { count++; num /= 2; } ar.add(count); } } }
Java
["4\n5 1 5\n9 1000 2000\n10 30 35\n1 1000000000 1000000000"]
1 second
["YES\n1 2 3 4 5\nYES\n1145 1926 1440 1220 1230 1350 1001 1000 1233\nNO\nYES\n1000000000"]
NoteIn the first test case, $$$\gcd(1,a_1),\gcd(2,a_2),\ldots,\gcd(5,a_5)$$$ are equal to $$$1$$$, $$$2$$$, $$$3$$$, $$$4$$$, $$$5$$$, respectively.
Java 11
standard input
[ "constructive algorithms", "math" ]
d2cc6efe7173a64482659ba59efeec16
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1\le t\le 10^4$$$) — the number of test cases. The description of the test cases follows. The first line contains three integers $$$n$$$, $$$l$$$, $$$r$$$ ($$$1 \le n \le 10^5$$$, $$$1\le l\le r\le 10^9$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,100
For each test case, if there is no solution, print "NO" (without quotes). You can print letters in any case (upper or lower). Otherwise, print "YES" (without quotes). In the next line, print $$$n$$$ integers $$$a_1,a_2,\ldots,a_n$$$ — the array you construct. If there are multiple solutions, you may output any.
standard output
PASSED
8ccfe21796669159672115cf40386202
train_108.jsonl
1657982100
You are given three integers $$$n$$$, $$$l$$$, and $$$r$$$. You need to construct an array $$$a_1,a_2,\dots,a_n$$$ ($$$l\le a_i\le r$$$) such that $$$\gcd(i,a_i)$$$ are all distinct or report there's no solution.Here $$$\gcd(x, y)$$$ denotes the greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$.
256 megabytes
import java.util.Scanner; /* gcd(a[i], i) = i Therefore, multiples of each i, bigger than the one just lesser than L should be less than R. */ public class B { public static void main(String[] args) { Scanner sc = new Scanner (System.in); int T = sc.nextInt(); while (T-- > 0) { int N = sc.nextInt(); int L = sc.nextInt(); long R = sc.nextInt(); boolean crossesR = false; long arr[] = new long[N]; for (int i = 1; i <= N; i++) { if (L % i == 0) { arr[i - 1] = L; continue; } long nextMultiple = i * ((L / i) + 1l); if (nextMultiple > R) { crossesR = true; break; } arr[i - 1] = nextMultiple; } if (crossesR == true) System.out.println("NO"); else { System.out.println("YES"); for (int i = 0; i < N; i++) System.out.print(arr[i] + " "); System.out.println(); } } sc.close(); } }
Java
["4\n5 1 5\n9 1000 2000\n10 30 35\n1 1000000000 1000000000"]
1 second
["YES\n1 2 3 4 5\nYES\n1145 1926 1440 1220 1230 1350 1001 1000 1233\nNO\nYES\n1000000000"]
NoteIn the first test case, $$$\gcd(1,a_1),\gcd(2,a_2),\ldots,\gcd(5,a_5)$$$ are equal to $$$1$$$, $$$2$$$, $$$3$$$, $$$4$$$, $$$5$$$, respectively.
Java 11
standard input
[ "constructive algorithms", "math" ]
d2cc6efe7173a64482659ba59efeec16
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1\le t\le 10^4$$$) — the number of test cases. The description of the test cases follows. The first line contains three integers $$$n$$$, $$$l$$$, $$$r$$$ ($$$1 \le n \le 10^5$$$, $$$1\le l\le r\le 10^9$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,100
For each test case, if there is no solution, print "NO" (without quotes). You can print letters in any case (upper or lower). Otherwise, print "YES" (without quotes). In the next line, print $$$n$$$ integers $$$a_1,a_2,\ldots,a_n$$$ — the array you construct. If there are multiple solutions, you may output any.
standard output
PASSED
56dee05e151ddb035103bde81c03c601
train_108.jsonl
1657982100
You are given three integers $$$n$$$, $$$l$$$, and $$$r$$$. You need to construct an array $$$a_1,a_2,\dots,a_n$$$ ($$$l\le a_i\le r$$$) such that $$$\gcd(i,a_i)$$$ are all distinct or report there's no solution.Here $$$\gcd(x, y)$$$ denotes the greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$.
256 megabytes
import java.io.*; import java.util.*; public class Qb { static int mod = (int) (1e9 + 7); static void solve() { long n = l(); long l = i(); long r = l(); long[] arr = new long[(int) (n+1)]; for (int i = 1; i <=n; i++) { long next=(( l+i-1)/i)*i; if(next>r){ System.out.println("NO"); return; } arr[i]=next; } System.out.println("YES"); for (int i = 1; i < arr.length; i++) { System.out.print(arr[i] + " "); } System.out.println(); } public static void main(String[] args) { int test = i(); while (test-- > 0) { solve(); } } // ----->segmentTree--> segTree as class // ----->lazy_Seg_tree --> lazy_Seg_tree as class // -----> Trie --->Trie as class // ----->fenwick_Tree ---> fenwick_Tree // -----> POWER ---> long power(long x, long y) <---- // -----> LCM ---> long lcm(long x, long y) <---- // -----> GCD ---> long gcd(long x, long y) <---- // -----> SIEVE --> ArrayList<Integer> sieve(int N) <----- // -----> NCR ---> long ncr(int n, int r) <---- // -----> BINARY_SEARCH ---> int binary_Search(long[]arr,long x) <---- // -----> (SORTING OF LONG, CHAR,INT) -->long[] sortLong(long[] a2)<-- // ----> DFS ---> void dfs(ArrayList<ArrayList<Integer>>edges,int child,int // parent)<--- // ---> NODETOROOT --> ArrayList<Integer> // node2Root(ArrayList<ArrayList<Integer>>edges,int child,int parent,int tofind) // <-- // ---> LEVELS_TREE -->levels_Trees(ArrayList<HashSet<Integer>> edges, int // child, int parent,int[]level,int currLevel) <-- // ---> K_THPARENT --> int k_thparent(int node,int[][]parent,int k) <--- // ---> TWOPOWERITHPARENTFILL --> void twoPowerIthParentFill(int[][]parent) <--- // -----> (INPUT OF INT,LONG ,STRING) -> int i() long l() String s()<- // tempstart static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int Int() { 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 String() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return String(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } static InputReader in = new InputReader(System.in); public static int i() { return in.Int(); } public static long l() { String s = in.String(); return Long.parseLong(s); } public static String s() { return in.String(); } }
Java
["4\n5 1 5\n9 1000 2000\n10 30 35\n1 1000000000 1000000000"]
1 second
["YES\n1 2 3 4 5\nYES\n1145 1926 1440 1220 1230 1350 1001 1000 1233\nNO\nYES\n1000000000"]
NoteIn the first test case, $$$\gcd(1,a_1),\gcd(2,a_2),\ldots,\gcd(5,a_5)$$$ are equal to $$$1$$$, $$$2$$$, $$$3$$$, $$$4$$$, $$$5$$$, respectively.
Java 11
standard input
[ "constructive algorithms", "math" ]
d2cc6efe7173a64482659ba59efeec16
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1\le t\le 10^4$$$) — the number of test cases. The description of the test cases follows. The first line contains three integers $$$n$$$, $$$l$$$, $$$r$$$ ($$$1 \le n \le 10^5$$$, $$$1\le l\le r\le 10^9$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,100
For each test case, if there is no solution, print "NO" (without quotes). You can print letters in any case (upper or lower). Otherwise, print "YES" (without quotes). In the next line, print $$$n$$$ integers $$$a_1,a_2,\ldots,a_n$$$ — the array you construct. If there are multiple solutions, you may output any.
standard output
PASSED
d32c8f3a314792ba61b0d33574dc582a
train_108.jsonl
1657982100
You are given three integers $$$n$$$, $$$l$$$, and $$$r$$$. You need to construct an array $$$a_1,a_2,\dots,a_n$$$ ($$$l\le a_i\le r$$$) such that $$$\gcd(i,a_i)$$$ are all distinct or report there's no solution.Here $$$\gcd(x, y)$$$ denotes the greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$.
256 megabytes
import java.util.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); for(int tc=0;tc<t;tc++){ int n = sc.nextInt(); int l = sc.nextInt(); int r = sc.nextInt(); int a[] = new int[n]; boolean flag = true; int s = 0; for(int i=1;i<=n;i++){ s = (r/i)*i; if(s<l){ flag = false; break; } else a[i-1] = s; } if(flag){ System.out.println("YES"); for(int i : a) System.out.print(i + " "); System.out.println(); } else System.out.println("NO"); } } }
Java
["4\n5 1 5\n9 1000 2000\n10 30 35\n1 1000000000 1000000000"]
1 second
["YES\n1 2 3 4 5\nYES\n1145 1926 1440 1220 1230 1350 1001 1000 1233\nNO\nYES\n1000000000"]
NoteIn the first test case, $$$\gcd(1,a_1),\gcd(2,a_2),\ldots,\gcd(5,a_5)$$$ are equal to $$$1$$$, $$$2$$$, $$$3$$$, $$$4$$$, $$$5$$$, respectively.
Java 11
standard input
[ "constructive algorithms", "math" ]
d2cc6efe7173a64482659ba59efeec16
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1\le t\le 10^4$$$) — the number of test cases. The description of the test cases follows. The first line contains three integers $$$n$$$, $$$l$$$, $$$r$$$ ($$$1 \le n \le 10^5$$$, $$$1\le l\le r\le 10^9$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,100
For each test case, if there is no solution, print "NO" (without quotes). You can print letters in any case (upper or lower). Otherwise, print "YES" (without quotes). In the next line, print $$$n$$$ integers $$$a_1,a_2,\ldots,a_n$$$ — the array you construct. If there are multiple solutions, you may output any.
standard output
PASSED
809a8e23330b4c84b4fd41aa39784f2e
train_108.jsonl
1657982100
You are given three integers $$$n$$$, $$$l$$$, and $$$r$$$. You need to construct an array $$$a_1,a_2,\dots,a_n$$$ ($$$l\le a_i\le r$$$) such that $$$\gcd(i,a_i)$$$ are all distinct or report there's no solution.Here $$$\gcd(x, y)$$$ denotes the greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$.
256 megabytes
import java.io.*; import java.util.*; public class Codeforces { static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } } static int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); int t = in.nextInt(); while(t-- > 0) { int n = in.nextInt(); int x = in.nextInt(); int y = in.nextInt(); Set<Integer> ans = new HashSet<>(); List<Integer> f = new ArrayList<>(); for (int i = 1; i <= n; i++) { int r = y % i; int temp = y - r; if (temp >= x) { f.add(temp); } } if (f.size() == n) { System.out.println("YES"); for (int i = 0; i < n; i++) System.out.print(f.get(i) + " "); System.out.println(); } else { System.out.println("NO"); } } out.close(); } }
Java
["4\n5 1 5\n9 1000 2000\n10 30 35\n1 1000000000 1000000000"]
1 second
["YES\n1 2 3 4 5\nYES\n1145 1926 1440 1220 1230 1350 1001 1000 1233\nNO\nYES\n1000000000"]
NoteIn the first test case, $$$\gcd(1,a_1),\gcd(2,a_2),\ldots,\gcd(5,a_5)$$$ are equal to $$$1$$$, $$$2$$$, $$$3$$$, $$$4$$$, $$$5$$$, respectively.
Java 11
standard input
[ "constructive algorithms", "math" ]
d2cc6efe7173a64482659ba59efeec16
The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1\le t\le 10^4$$$) — the number of test cases. The description of the test cases follows. The first line contains three integers $$$n$$$, $$$l$$$, $$$r$$$ ($$$1 \le n \le 10^5$$$, $$$1\le l\le r\le 10^9$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,100
For each test case, if there is no solution, print "NO" (without quotes). You can print letters in any case (upper or lower). Otherwise, print "YES" (without quotes). In the next line, print $$$n$$$ integers $$$a_1,a_2,\ldots,a_n$$$ — the array you construct. If there are multiple solutions, you may output any.
standard output