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
e59f5d44fab594968cc57a4158d59487
train_108.jsonl
1650722700
There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times: Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l < r \le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times.
256 megabytes
import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; public class D1672 { public static void main(String[] args) throws IOException { InputReader ir = new InputReader(System.in); PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); for (int t = ir.nextInt(); t-- > 0; ) { int n = ir.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = ir.nextInt(); } int[] b = new int[n]; for (int i = 0; i < n; i++) { b[i] = ir.nextInt(); } int[] count = new int[n + 1]; int ap = n - 1; int bp = n - 1; while (ap >= 0) { while (bp > 0 && b[bp - 1] == b[bp]) { count[b[bp]]++; bp--; } if (bp >= 0 && a[ap] == b[bp]) { ap--; bp--; } else if (count[a[ap]] > 0) { count[a[ap]]--; ap--; } else { break; } } if (ap >=0 || bp >= 0) { out.println("NO"); } else { out.println("YES"); } } ir.close(); out.close(); } private static final class InputReader { private int index; private String[] line; private final BufferedReader br; private InputReader(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); index = 0; line = new String[0]; } private int nextInt() { updateIndex(); return Integer.parseInt(line[index++]); } private void updateIndex() { try { if (index == line.length) { line = br.readLine().split(" "); index = 0; } } catch (IOException ioException) { } } private long nextLong() { updateIndex(); return Long.parseLong(line[index++]); } private float nextFloat() { updateIndex(); return Float.parseFloat(line[index++]); } private double nextDouble() { updateIndex(); return Double.parseDouble(line[index++]); } private char nextChar() { updateIndex(); return line[index++].charAt(0); } private String nextString() { updateIndex(); return line[index++]; } private void close() { try { br.close(); } catch (IOException ioException) { } } } }
Java
["5\n\n5\n\n1 2 3 3 2\n\n1 3 3 2 2\n\n5\n\n1 2 4 2 1\n\n4 2 2 1 1\n\n5\n\n2 4 5 5 2\n\n2 2 4 5 5\n\n3\n\n1 2 3\n\n1 2 3\n\n3\n\n1 1 2\n\n2 1 1"]
1 second
["YES\nYES\nNO\nYES\nNO"]
NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation.
Java 8
standard input
[ "constructive algorithms", "greedy", "implementation", "two pointers" ]
158bd0ab8f4319f5fd1e6062caddad4e
Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$)  — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$)  — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$)  — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$)  — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$
1,700
For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response).
standard output
PASSED
6e788896b84fc71d8debe3f6af474af0
train_108.jsonl
1650722700
There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times: Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l &lt; r \le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times.
256 megabytes
import java.util.*; import java.io.*; // cd C:\Users\Lenovo\Desktop\New //ArrayList<Integer> a=new ArrayList<>(); //List<Integer> lis=new ArrayList<>(); //StringBuilder ans = new StringBuilder(); //HashMap<Integer,Integer> map=new HashMap<>(); public class cf { static FastReader in=new FastReader(); static final Random random=new Random(); static long mod=1000000007l; //static long dp[]=new long[200002]; public static void main(String args[]) throws IOException { FastReader sc=new FastReader(); //Scanner s=new Scanner(System.in); int tt=sc.nextInt(); //int tt=1; while(tt-->0){ int n=sc.nextInt(); int arr[]=new int[n]; int brr[]=new int[n]; for(int i=0;i<n;i++){ arr[i]=sc.nextInt(); } for(int i=0;i<n;i++){ brr[i]=sc.nextInt(); } HashMap<Integer,Integer> map=new HashMap<>(); int i=n-1; int j=n-1; boolean check=true; while(i>=0){ if(j>0 && brr[j]==brr[j-1]){ map.put(brr[j],map.getOrDefault(brr[j],0)+1); j--; continue; } if(j>=0 && arr[i]==brr[j]){ i--; j--; continue; } if(map.getOrDefault(arr[i],0)>0){ map.put(arr[i],map.getOrDefault(arr[i],0)-1); i--; } else{ check=false; break; } } if(check){ System.out.println("YES"); } else{ System.out.println("NO"); } } } /*static void bfs(){ dist[1]=0; for(int i=2;i<dist.length;i++){ dist[i]=-1; } Queue<Integer> q=new LinkedList<>(); q.add(1); while(q.size()!=0){ int cur=q.peek(); q.remove(); for(int i=1;i<dist.length;i++ ){ int next=cur+cur/i; int ndis=dist[cur]+1; if(next<dist.length && dist[next]==-1){ dist[next]=ndis; q.add(next); } } } }*/ static long comb(int n,int k){ return factorial(n) * pow(factorial(k), mod-2) % mod * pow(factorial(n-k), mod-2) % mod; } static long pow(long a, long b) { // long mod=1000000007; long res = 1; while (b != 0) { if ((b & 1) != 0) { res = (res * a) % mod; } a = (a * a) % mod; b /= 2; } return res; } static boolean powOfTwo(long n){ while(n%2==0){ n=n/2; } if(n!=1){ return false; } return true; } static int upper_bound(long arr[], long key) { int mid, N = arr.length; int low = 0; int high = N; // Till low is less than high while (low < high && low != N) { mid = low + (high - low) / 2; if (key >= arr[mid]) { low = mid + 1; } else { high = mid; } } return low; } static boolean prime(int n){ for(int i=2;i<=Math.sqrt(n);i++){ if(n%i==0){ return false; } } return true; } static long factorial(int n){ long ret = 1; while(n > 0){ ret = ret * n % mod; n--; } return ret; } static long find(ArrayList<Long> arr,long n){ int l=0; int r=arr.size(); while(l+1<r){ int mid=(l+r)/2; if(arr.get(mid)<n){ l=mid; } else{ r=mid; } } return arr.get(l); } static void rotate(int ans[]){ int last=ans[0]; for(int i=0;i<ans.length-1;i++){ ans[i]=ans[i+1]; } ans[ans.length-1]=last; } static int countprimefactors(int n){ int ans=0; int z=(int)Math.sqrt(n); for(int i=2;i<=z;i++){ while(n%i==0){ ans++; n=n/i; } } if(n>1){ ans++; } return ans; } static String reverse_String(String s){ String ans=""; for(int i=s.length()-1;i>=0;i--){ ans+=s.charAt(i); } return ans; } static void reverse_array(int arr[]){ int l=0; int r=arr.length-1; while(l<r){ int temp=arr[l]; arr[l]=arr[r]; arr[r]=temp; l++; r--; } } static int msb(int x){ int ans=0; while(x!=0){ x=x/2; ans++; } return ans; } 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 long gcd(long a,long b) { if(b==0) { return a; } return gcd(b,a%b); } /* Iterator<Map.Entry<Integer, Integer>> iterator = map.entrySet().iterator(); while(iterator.hasNext()){ Map.Entry<Integer, Integer> entry = iterator.next(); int value = entry.getValue(); if(value==1){ iterator.remove(); } else{ entry.setValue(value-1); } } */ static class Pair implements Comparable { int a; int b; public String toString() { return a+" " + b; } public Pair(int x , int y) { a=x;b=y; } @Override public int compareTo(Object o) { Pair p = (Pair)o; if(a!=p.a){ return a-p.a; } else{ return b-p.b; } /*if(p.a!=a){ return a-p.a;//in } else{ return b-p.b;// }*/ } } public static boolean checkAP(List<Integer> lis){ for(int i=1;i<lis.size()-1;i++){ if(2*lis.get(i)!=lis.get(i-1)+lis.get(i+1)){ return false; } } return true; } /* public static int minBS(int[]arr,int val){ int l=-1; int r=arr.length; while(r>l+1){ int mid=(l+r)/2; if(arr[mid]>=val){ r=mid; } else{ l=mid; } } return r; } public static int maxBS(int[]arr,int val){ int l=-1; int r=arr.length; while(r>l+1){ int mid=(l+r)/2; if(arr[mid]<=val){ l=mid; } else{ r=mid; } } return l; } */ static long lcm(long a, long b) { return (a / gcd(a, b)) * b; } 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
["5\n\n5\n\n1 2 3 3 2\n\n1 3 3 2 2\n\n5\n\n1 2 4 2 1\n\n4 2 2 1 1\n\n5\n\n2 4 5 5 2\n\n2 2 4 5 5\n\n3\n\n1 2 3\n\n1 2 3\n\n3\n\n1 1 2\n\n2 1 1"]
1 second
["YES\nYES\nNO\nYES\nNO"]
NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation.
Java 8
standard input
[ "constructive algorithms", "greedy", "implementation", "two pointers" ]
158bd0ab8f4319f5fd1e6062caddad4e
Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$)  — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$)  — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$)  — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$)  — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$
1,700
For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response).
standard output
PASSED
9b2dba15a1ee7f136d19c4b4c850284a
train_108.jsonl
1650722700
There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times: Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l &lt; r \le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times.
256 megabytes
import java.util.*; import java.io.*; public class E{ static FastScanner fs = null; public static void main(String[] args) { fs = new FastScanner(); PrintWriter out = new PrintWriter(System.out); int t = fs.nextInt(); while (t-->0) { int n = fs.nextInt(); int a[] = new int[n]; int b[] = new int[n]; for(int i=0;i<n;i++){ a[i] = fs.nextInt(); } for(int i=0;i<n;i++){ b[i] = fs.nextInt(); } int cnt[] = new int[n+1]; boolean res = true; int i = 0; int j = 0; while (j<n) { if(i<n && j<n && a[i]==b[j]){ i+=1; j+=1; continue; } if(cnt[b[j]]>0 && b[j]==b[j-1]){ cnt[b[j++]]-=1; } else if(i<n){ cnt[a[i++]]+=1; } else{ res = false; break; } } if(res) out.println("YES"); else out.println("NO"); } out.close(); } static void sort(int[] a) { ArrayList<Integer> l=new ArrayList<>(); for (int i:a) l.add(i); Collections.sort(l); for (int i=0; i<a.length; i++) a[i]=l.get(i); } static 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()); } double nextDouble() { return Double.parseDouble(next()); } } }
Java
["5\n\n5\n\n1 2 3 3 2\n\n1 3 3 2 2\n\n5\n\n1 2 4 2 1\n\n4 2 2 1 1\n\n5\n\n2 4 5 5 2\n\n2 2 4 5 5\n\n3\n\n1 2 3\n\n1 2 3\n\n3\n\n1 1 2\n\n2 1 1"]
1 second
["YES\nYES\nNO\nYES\nNO"]
NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation.
Java 8
standard input
[ "constructive algorithms", "greedy", "implementation", "two pointers" ]
158bd0ab8f4319f5fd1e6062caddad4e
Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$)  — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$)  — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$)  — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$)  — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$
1,700
For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response).
standard output
PASSED
874c3f105ade4a84dee930fdc223de80
train_108.jsonl
1650722700
There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times: Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l &lt; r \le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times.
256 megabytes
import java.util.*; import java.io.*; public class Main { static final int MOD = 1000000007; static InputReader in = new InputReader(System.in); static BufferOutput out = new BufferOutput(); public static void main(String[] args) { for(int i = in.nextInt();i>0;i--) { int n = in.nextInt(); int[] a = in.nextIntArray(n); int[] b = in.nextIntArray(n); Map<Integer, Integer> MultiMap = new HashMap<Integer, Integer>(); int j, l; j = l = n-1; boolean ans = true; while((l >= 0 & j >= 0)) { if(l>0) { while(b[l] == b[l-1]) { if(MultiMap.containsKey(b[l])) { MultiMap.put(b[l], MultiMap.get(b[l])+1); } else { MultiMap.put(b[l], 1); } l--; if(l==0)break; } } if(a[j]==b[l]) { l--; j--; } else { if(MultiMap.containsKey(a[j])) { if(MultiMap.get(a[j])<=0) { ans = false; break; } else { MultiMap.put(a[j], MultiMap.get(a[j])-1); j--; } } else { ans = false; break; } } } if(ans)System.out.println("YES"); else System.out.println("NO"); } } static class BufferOutput { private DataOutputStream dout; final private int BUFFER_SIZE = 1 << 16; private byte[] buffer; private int pointer = 0; public BufferOutput() { buffer = new byte[BUFFER_SIZE]; dout = new DataOutputStream(System.out); } public BufferOutput(OutputStream out) { buffer = new byte[BUFFER_SIZE]; dout = new DataOutputStream(out); } public void writeBytes(byte arr[]) throws IOException { int bytesToWrite = arr.length; if (pointer + bytesToWrite >= BUFFER_SIZE) { flush(); } for (int i = 0; i < bytesToWrite; i++) { buffer[pointer++] = arr[i]; } } public void writeString(String str) throws IOException { writeBytes(str.getBytes()); } public void flush() throws IOException { dout.write(buffer, 0, pointer); dout.flush(); pointer = 0; } public void close() throws IOException{ dout.close(); } } 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 String nextLine() { StringBuilder sb = new StringBuilder(); int b = readByte(); while (b != 10) { sb.appendCodePoint(b); b = readByte(); } if (sb.length() == 0) return ""; return sb.toString().substring(0, sb.length() - 1); } 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 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; } } }
Java
["5\n\n5\n\n1 2 3 3 2\n\n1 3 3 2 2\n\n5\n\n1 2 4 2 1\n\n4 2 2 1 1\n\n5\n\n2 4 5 5 2\n\n2 2 4 5 5\n\n3\n\n1 2 3\n\n1 2 3\n\n3\n\n1 1 2\n\n2 1 1"]
1 second
["YES\nYES\nNO\nYES\nNO"]
NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation.
Java 8
standard input
[ "constructive algorithms", "greedy", "implementation", "two pointers" ]
158bd0ab8f4319f5fd1e6062caddad4e
Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$)  — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$)  — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$)  — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$)  — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$
1,700
For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response).
standard output
PASSED
cd5be54a4109cc3a2e7de4e99cf123b9
train_108.jsonl
1650722700
There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times: Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l &lt; r \le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times.
256 megabytes
import static java.lang.Math.max; import static java.lang.Math.min; import static java.lang.Math.abs; import java.util.*; import java.io.*; import java.math.*; /** * * @Har_Har_Mahadev */ /** * Main , Solution , Remove Public */ public class Solution { public static void process() throws IOException { int n = sc.nextInt(); int arr[] = sc.readArray(n), b[] = sc.readArray(n); int count[] = new int[n+1]; int i = n-1, j = n-1; while(i>=0 && j>=0) { if(arr[i] == b[j]) { i--; j--; continue; } if(j+1<n && b[j] == b[j+1]) { count[b[j]]++; j--; continue; } if(count[arr[i]] == 0) { System.out.println("NO"); return; } count[arr[i]]--; i--; } System.out.println("YES"); } //============================================================================= //--------------------------The End--------------------------------- //============================================================================= private static long INF = 2000000000000000000L, M = 1000000007, MM = 998244353; private static int N = 0; private static void google(int tt) { System.out.print("Case #" + (tt) + ": "); } static FastScanner sc; static FastWriter out; public static void main(String[] args) throws IOException { boolean oj = true; if (oj) { sc = new FastScanner(); out = new FastWriter(System.out); } else { sc = new FastScanner("input.txt"); out = new FastWriter("output.txt"); } long s = System.currentTimeMillis(); int t = 1; t = sc.nextInt(); int TTT = 1; while (t-- > 0) { // google(TTT++); process(); } out.flush(); // tr(System.currentTimeMillis()-s+"ms"); } private static boolean oj = System.getProperty("ONLINE_JUDGE") != null; private static void tr(Object... o) { if (!oj) System.err.println(Arrays.deepToString(o)); } static class Pair implements Comparable<Pair> { int x, y; Pair(int x, int y) { this.x = x; this.y = y; } @Override public int compareTo(Pair o) { return Integer.compare(this.x, o.x); } /* @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Pair)) return false; Pair key = (Pair) o; return x == key.x && y == key.y; } @Override public int hashCode() { int result = x; result = 31 * result + y; return result; } */ } ///////////////////////////////////////////////////////////////////////////////////////////////////////// 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)); } static long sqrt(long z) { long sqz = (long) Math.sqrt(z); while (sqz * 1L * sqz < z) { sqz++; } while (sqz * 1L * sqz > z) { sqz--; } return sqz; } static int log2(int N) { int result = (int) (Math.log(N) / Math.log(2)); return result; } public static long gcd(long a, long b) { if (a > b) a = (a + b) - (b = a); if (a == 0L) return b; return gcd(b % a, a); } public static long lcm(long a, long b) { return (a * b) / gcd(a, b); } public static int lower_bound(int[] arr, int x) { int low = 0, high = arr.length - 1, mid = -1; int ans = -1; while (low <= high) { mid = (low + high) / 2; if (arr[mid] > x) { high = mid - 1; } else { ans = mid; low = mid + 1; } } return ans; } public static int upper_bound(int[] arr, int x) { int low = 0, high = arr.length - 1, mid = -1; int ans = arr.length; while (low < high) { mid = (low + high) / 2; if (arr[mid] >= x) { ans = mid; high = mid - 1; } else { low = mid + 1; } } return ans; } static void ruffleSort(int[] a) { Random get = new Random(); for (int i = 0; i < a.length; i++) { int r = get.nextInt(a.length); int temp = a[i]; a[i] = a[r]; a[r] = temp; } Arrays.sort(a); } static void ruffleSort(long[] a) { Random get = new Random(); for (int i = 0; i < a.length; i++) { int r = get.nextInt(a.length); long temp = a[i]; a[i] = a[r]; a[r] = temp; } Arrays.sort(a); } static void reverseArray(int[] a) { int n = a.length; int arr[] = new int[n]; for (int i = 0; i < n; i++) arr[i] = a[n - i - 1]; for (int i = 0; i < n; i++) a[i] = arr[i]; } static void reverseArray(long[] a) { int n = a.length; long arr[] = new long[n]; for (int i = 0; i < n; i++) arr[i] = a[n - i - 1]; for (int i = 0; i < n; i++) a[i] = arr[i]; } //custom multiset (replace with HashMap if needed) public static void push(TreeMap<Integer, Integer> map, int k, int v) { //map[k] += v; if (!map.containsKey(k)) map.put(k, v); else map.put(k, map.get(k) + v); } public static void pull(TreeMap<Integer, Integer> map, int k, int v) { //assumes map[k] >= v //map[k] -= v int lol = map.get(k); if (lol == v) map.remove(k); else map.put(k, lol - v); } // compress Big value to Time Limit public static int[] compress(int[] arr) { ArrayList<Integer> ls = new ArrayList<Integer>(); for (int x : arr) ls.add(x); Collections.sort(ls); HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); int boof = 1; //min value for (int x : ls) if (!map.containsKey(x)) map.put(x, boof++); int[] brr = new int[arr.length]; for (int i = 0; i < arr.length; i++) brr[i] = map.get(arr[i]); return brr; } // Fast Writer public static class FastWriter { private static final int BUF_SIZE = 1 << 13; private final byte[] buf = new byte[BUF_SIZE]; private final OutputStream out; private int ptr = 0; private FastWriter() { out = null; } public FastWriter(OutputStream os) { this.out = os; } public FastWriter(String path) { try { this.out = new FileOutputStream(path); } catch (FileNotFoundException e) { throw new RuntimeException("FastWriter"); } } public FastWriter write(byte b) { buf[ptr++] = b; if (ptr == BUF_SIZE) innerflush(); return this; } public FastWriter write(char c) { return write((byte) c); } public FastWriter write(char[] s) { for (char c : s) { buf[ptr++] = (byte) c; if (ptr == BUF_SIZE) innerflush(); } return this; } public FastWriter write(String s) { s.chars().forEach(c -> { buf[ptr++] = (byte) c; 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 FastWriter write(int x) { if (x == Integer.MIN_VALUE) { return write((long) x); } if (ptr + 12 >= BUF_SIZE) innerflush(); if (x < 0) { write((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 FastWriter write(long x) { if (x == Long.MIN_VALUE) { return write("" + x); } if (ptr + 21 >= BUF_SIZE) innerflush(); if (x < 0) { write((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 FastWriter write(double x, int precision) { if (x < 0) { write('-'); x = -x; } x += Math.pow(10, -precision) / 2; // if(x < 0){ x = 0; } write((long) x).write("."); x -= (long) x; for (int i = 0; i < precision; i++) { x *= 10; write((char) ('0' + (int) x)); x -= (int) x; } return this; } public FastWriter writeln(char c) { return write(c).writeln(); } public FastWriter writeln(int x) { return write(x).writeln(); } public FastWriter writeln(long x) { return write(x).writeln(); } public FastWriter writeln(double x, int precision) { return write(x, precision).writeln(); } public FastWriter write(int... xs) { boolean first = true; for (int x : xs) { if (!first) write(' '); first = false; write(x); } return this; } public FastWriter write(long... xs) { boolean first = true; for (long x : xs) { if (!first) write(' '); first = false; write(x); } return this; } public FastWriter writeln() { return write((byte) '\n'); } public FastWriter writeln(int... xs) { return write(xs).writeln(); } public FastWriter writeln(long... xs) { return write(xs).writeln(); } public FastWriter writeln(char[] line) { return write(line).writeln(); } public FastWriter writeln(char[]... map) { for (char[] line : map) write(line).writeln(); return this; } public FastWriter writeln(String s) { return write(s).writeln(); } 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"); } } public FastWriter print(byte b) { return write(b); } public FastWriter print(char c) { return write(c); } public FastWriter print(char[] s) { return write(s); } public FastWriter print(String s) { return write(s); } public FastWriter print(int x) { return write(x); } public FastWriter print(long x) { return write(x); } public FastWriter print(double x, int precision) { return write(x, precision); } public FastWriter println(char c) { return writeln(c); } public FastWriter println(int x) { return writeln(x); } public FastWriter println(long x) { return writeln(x); } public FastWriter println(double x, int precision) { return writeln(x, precision); } public FastWriter print(int... xs) { return write(xs); } public FastWriter print(long... xs) { return write(xs); } public FastWriter println(int... xs) { return writeln(xs); } public FastWriter println(long... xs) { return writeln(xs); } public FastWriter println(char[] line) { return writeln(line); } public FastWriter println(char[]... map) { return writeln(map); } public FastWriter println(String s) { return writeln(s); } public FastWriter println() { return writeln(); } } // Fast Inputs static 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[] readArray(int N) { int[] res = new int[N]; for (int i = 0; i < N; i++) { res[i] = (int) nextLong(); } return res; } public long[] readArrayLong(int N) { long[] res = new long[N]; for (int i = 0; i < N; i++) { res[i] = nextLong(); } return res; } public int[][] readArrayMatrix(int N, int M, int Index) { if (Index == 0) { int[][] res = new int[N][M]; for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) res[i][j] = (int) nextLong(); } return res; } int[][] res = new int[N][M]; for (int i = 1; i <= N; i++) { for (int j = 1; j <= M; j++) res[i][j] = (int) nextLong(); } return res; } public long[][] readArrayMatrixLong(int N, int M, int Index) { if (Index == 0) { long[][] res = new long[N][M]; for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) res[i][j] = nextLong(); } return res; } long[][] res = new long[N][M]; for (int i = 1; i <= N; i++) { for (int j = 1; j <= M; j++) res[i][j] = 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[] readArrayDouble(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
["5\n\n5\n\n1 2 3 3 2\n\n1 3 3 2 2\n\n5\n\n1 2 4 2 1\n\n4 2 2 1 1\n\n5\n\n2 4 5 5 2\n\n2 2 4 5 5\n\n3\n\n1 2 3\n\n1 2 3\n\n3\n\n1 1 2\n\n2 1 1"]
1 second
["YES\nYES\nNO\nYES\nNO"]
NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation.
Java 8
standard input
[ "constructive algorithms", "greedy", "implementation", "two pointers" ]
158bd0ab8f4319f5fd1e6062caddad4e
Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$)  — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$)  — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$)  — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$)  — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$
1,700
For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response).
standard output
PASSED
eef531c1931b2efd97da5c129386ecbb
train_108.jsonl
1650722700
There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times: Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l &lt; r \le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times.
256 megabytes
import java.util.Scanner; public class MyClass { static Scanner in = new Scanner(System.in); static int testCases, n; static int a[], b[]; static void solve() { int next[] = new int[n + 1]; int count[] = new int[n + 1]; int map[] = new int[n + 1]; for(int i = 0; i < n; ++i) { count[i] = 1; next[i] = -1; } for(int i = n - 1; i >= 0; --i) { if(map[a[i]] > 0) { next[i] = map[a[i]] - 1; } else { next[i] = -1; } map[a[i]] = i + 1; } int i = 0, j = 0; while(j < n && i < n) { if( a[i] == b[j] ) { if(count[i] == 1) { ++i; } else { --count[i]; } ++j; } else { if(next[i] == -1) { break; } //else { count[ next[i] ] += count[i]; ++i; //} } } if(j >= n) { System.out.println("YES"); } else { System.out.println("NO"); } } public static void main(String args[]) { testCases = in.nextInt(); for(int t = 0; t < testCases; ++t) { n = in.nextInt(); a = new int[n]; b = new int[n]; for(int i = 0; i < n; ++i) { a[i] = in.nextInt(); } for(int i = 0; i < n; ++i) { b[i] = in.nextInt(); } solve(); } } }
Java
["5\n\n5\n\n1 2 3 3 2\n\n1 3 3 2 2\n\n5\n\n1 2 4 2 1\n\n4 2 2 1 1\n\n5\n\n2 4 5 5 2\n\n2 2 4 5 5\n\n3\n\n1 2 3\n\n1 2 3\n\n3\n\n1 1 2\n\n2 1 1"]
1 second
["YES\nYES\nNO\nYES\nNO"]
NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation.
Java 8
standard input
[ "constructive algorithms", "greedy", "implementation", "two pointers" ]
158bd0ab8f4319f5fd1e6062caddad4e
Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$)  — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$)  — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$)  — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$)  — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$
1,700
For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response).
standard output
PASSED
7ad0d438b9ceb8bcc2b8c1d0dc0990cd
train_108.jsonl
1650722700
There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times: Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l &lt; r \le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times.
256 megabytes
import java.util.Scanner; import java.util.Map; import java.util.HashMap; public class MyClass { static Scanner in = new Scanner(System.in); static int testCases, n; static int a[], b[]; static void solve() { Map<Integer, Integer> map = new HashMap<>(); int next[] = new int[n]; int count[] = new int[n]; for(int i = 0; i < n; ++i) { next[i] = -1; count[i] = 1; } for(int i = n - 1; i >= 0; --i) { if(map.containsKey(a[i])) { next[i] = map.get(a[i]); } else { next[i] = -1; } map.put(a[i], i); } int i = 0, j = 0; while (j < n) { if(a[i] == b[j]) { if(count[i] == 1) { ++i; } else { --count[i]; } ++j; } else { if(next[i] == -1) { break; } count[next[i]] += count[i]; ++i; } } System.out.println(j == n ? "YES" : "NO"); } public static void main(String priya[]) { testCases = in.nextInt(); for(int t = 0; t < testCases; ++t) { n = in.nextInt(); a = new int[n]; b = new int[n]; for(int i = 0; i < n; ++i) { a[i] = in.nextInt(); } for(int i = 0; i < n; ++i) { b[i] = in.nextInt(); } solve(); } } }
Java
["5\n\n5\n\n1 2 3 3 2\n\n1 3 3 2 2\n\n5\n\n1 2 4 2 1\n\n4 2 2 1 1\n\n5\n\n2 4 5 5 2\n\n2 2 4 5 5\n\n3\n\n1 2 3\n\n1 2 3\n\n3\n\n1 1 2\n\n2 1 1"]
1 second
["YES\nYES\nNO\nYES\nNO"]
NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation.
Java 8
standard input
[ "constructive algorithms", "greedy", "implementation", "two pointers" ]
158bd0ab8f4319f5fd1e6062caddad4e
Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$)  — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$)  — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$)  — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$)  — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$
1,700
For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response).
standard output
PASSED
83f2c936a2247be102ea01831b9db942
train_108.jsonl
1650722700
There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times: Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l &lt; r \le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times.
256 megabytes
import java.util.*; import java.io.*; public class Main { public static void main(String[] args)throws Exception { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw=new PrintWriter(System.out); int t=Integer.parseInt(br.readLine()); while(t-->0) { int n=Integer.parseInt(br.readLine()); String s[]=(br.readLine()).split(" "); String s1[]=(br.readLine()).split(" "); int a[]=new int[n]; int b[]=new int[n]; for(int i=0;i<n;i++) { a[i]=Integer.parseInt(s[i]); b[i]=Integer.parseInt(s1[i]); } HashMap<Integer,Integer> hm=new HashMap<Integer,Integer>(); int a1=0; int b1=0; boolean flag=true; while(a1<n || b1<n) { if(a1<n) { if(a[a1]==b[b1]) { a1++; b1++; continue; } else if(hm.containsKey(b[b1]) && hm.get(b[b1])>0) { if(b[b1-1]==b[b1]) { hm.replace(b[b1],hm.get(b[b1])-1); b1++; } else { if(hm.containsKey(a[a1])) { hm.replace(a[a1],hm.get(a[a1])+1); } else { hm.put(a[a1],1); } a1++; } } else { if(hm.containsKey(a[a1])) { hm.replace(a[a1],hm.get(a[a1])+1); } else { hm.put(a[a1],1); } a1++; } } else { if(hm.containsKey(b[b1]) && hm.get(b[b1])>0 && b[b1-1]==b[b1]) { hm.replace(b[b1],hm.get(b[b1])-1); b1++; } else { flag=false; break; } } } if(flag) { pw.println("yes"); } else { pw.println("NO"); } } pw.flush(); } }
Java
["5\n\n5\n\n1 2 3 3 2\n\n1 3 3 2 2\n\n5\n\n1 2 4 2 1\n\n4 2 2 1 1\n\n5\n\n2 4 5 5 2\n\n2 2 4 5 5\n\n3\n\n1 2 3\n\n1 2 3\n\n3\n\n1 1 2\n\n2 1 1"]
1 second
["YES\nYES\nNO\nYES\nNO"]
NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation.
Java 8
standard input
[ "constructive algorithms", "greedy", "implementation", "two pointers" ]
158bd0ab8f4319f5fd1e6062caddad4e
Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$)  — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$)  — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$)  — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$)  — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$
1,700
For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response).
standard output
PASSED
17054701acf43afdf6d60c4fda2c5d76
train_108.jsonl
1650722700
There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times: Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l &lt; r \le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times.
256 megabytes
import java.io.*; import java.util.*; import java.lang.*; import static java.lang.Math.*; public class Codeforces { static int MAX = Integer.MAX_VALUE,MIN = Integer.MIN_VALUE; static long MAXL = Long.MAX_VALUE,MINL = Long.MIN_VALUE,MOD = (int)1e9+7; static void solve() { int n = fs.nInt(); int[]ar = new int[n]; int[]br = new int[n]; for(int i=0;i<n;i++)ar[i] = fs.nInt(); for(int i=0;i<n;i++)br[i] = fs.nInt(); int[]cnt = new int[n+1]; int i=0,j=0; boolean possible = true; while( j < n ){ if( i < n && ar[i] == br[j]){ i++;j++;continue; } if( cnt[br[j]] > 0 && br[j] == br[j-1]){ cnt[br[j++]]--; }else if( i < n ){ cnt[ar[i++]]++; }else{ possible = false; break; } } if(possible){ if( i < n-1)possible=false; for(i=0;i<n;i++){ if(cnt[ar[i]]>0)possible = false; } } if(possible)out.println("YES"); else out.println("NO"); } static class Triplet<T,U,V>{ T a; U b; V c; Triplet(T a,U b,V c){ this.a = a; this.b = b; this.c = c; } } static class Pair<A, B>{ A fst; B snd; Pair(A fst,B snd){ this.fst = fst; this.snd = snd; } } 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 extends PrintWriter { private InputStream stream; private byte[] buf = new byte[1<<16]; private int curChar, numChars; public FastScanner() { this(System.in,System.out); } public FastScanner(InputStream i, OutputStream o) { super(o); stream = i; } // file input public FastScanner(String i, String o) throws IOException { super(new FileWriter(o)); stream = new FileInputStream(i); } // throws InputMismatchException() if previously detected end of file private int nextByte() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars == -1) return -1; // end of file } return buf[curChar++]; } // to read in entire lines, replace c <= ' ' // with a function that checks whether c is a line break public String next() { int c; do { c = nextByte(); } while (c <= ' '); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = nextByte(); } while (c > ' '); return res.toString(); } public int nInt() { // nextLong() would be implemented similarly int c; do { c = nextByte(); } while (c <= ' '); int sgn = 1; if (c == '-') { sgn = -1; c = nextByte(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res = 10*res+c-'0'; c = nextByte(); } while (c > ' '); return res * sgn; } public long nLong(){return Long.parseLong(next());} public double nextDouble() { return Double.parseDouble(next()); } } public static void sort(int[] arr){ ArrayList<Integer> ls = new ArrayList<>(); 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 sortR(int[] arr){ ArrayList<Integer> ls = new ArrayList<>(); for(int x: arr) ls.add(x); Collections.sort(ls,Collections.reverseOrder()); 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); } public static void sortR(long[] arr){ ArrayList<Long> ls = new ArrayList<>(); for(long x: arr) ls.add(x); Collections.sort(ls,Collections.reverseOrder()); for(int i=0; i < arr.length; i++) arr[i] = ls.get(i); } }
Java
["5\n\n5\n\n1 2 3 3 2\n\n1 3 3 2 2\n\n5\n\n1 2 4 2 1\n\n4 2 2 1 1\n\n5\n\n2 4 5 5 2\n\n2 2 4 5 5\n\n3\n\n1 2 3\n\n1 2 3\n\n3\n\n1 1 2\n\n2 1 1"]
1 second
["YES\nYES\nNO\nYES\nNO"]
NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation.
Java 8
standard input
[ "constructive algorithms", "greedy", "implementation", "two pointers" ]
158bd0ab8f4319f5fd1e6062caddad4e
Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$)  — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$)  — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$)  — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$)  — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$
1,700
For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response).
standard output
PASSED
58b70056428ae6ab0d324a19cfbb8c89
train_108.jsonl
1650722700
There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times: Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l &lt; r \le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times.
256 megabytes
import java.io.*; import java.util.*; public class D { public static void main(String[] args) { new D().run(); } BufferedReader br; PrintWriter out; int mod = (int) (1e9 + 7), inf = (int) (1e9); class pair { int F, S; pair(int f, int s) { F = f; S = s; } } // ---------------------- solve -------------------------- void solve() { int t=1; t = ni(); // comment for no test cases while(t-- > 0) { //TODO: int n= ni(); int[] a= new int[n+1]; int[] b= new int[n+1]; for(int i=1; i<=n; i++){ a[i]= ni(); } for(int i=1; i<=n; i++){ b[i]=ni(); } b[0]=-inf; a[0]=-1; HashMap<Integer, Integer> map= new HashMap<>(); int prev=inf, p1=n, p2=n; boolean pos=true; while(p1!=0 || p2!=0){ if(a[p1]==b[p2]){ prev=a[p1]; p1--; p2--; } else{ if(prev==b[p2]){ map.put(b[p2], map.getOrDefault(b[p2], 0)+1); p2--; } else{ if(map.containsKey(a[p1])){ map.put(a[p1], map.get(a[p1])-1); if(map.get(a[p1])==0){ map.remove(a[p1]); } p1--; } else{ pos=false; break; } } } } if(pos){ out.println("YES"); } else{ out.println("NO"); } } } // -------- I/O Template ------------- public long pow(long A, long B, long C) { if(A==0) return 0; if(B==0) return 1; long n=pow(A, B/2, C); if(B%2==0){ return (long)((n*n)%C + C )%C; } else{ return (long)(((n*n)%C * A)%C +C)%C; } } char nc() { return ns().charAt(0); } String nLine() { try { return br.readLine(); } catch(IOException e) { return "-1"; } } double nd() { return Double.parseDouble(ns()); } long nl() { return Long.parseLong(ns()); } int ni() { return Integer.parseInt(ns()); } int[] na(int n) { int a[] = new int[n]; for(int i = 0; i < n; i++) a[i] = ni(); return a; } long[] nal(int n) { long a[] = new long[n]; for(int i = 0; i < n; i++) a[i] = nl(); return a; } StringTokenizer ip; String ns() { if(ip == null || !ip.hasMoreTokens()) { try { ip = new StringTokenizer(br.readLine()); if(ip == null || !ip.hasMoreTokens()) ip = new StringTokenizer(br.readLine()); } catch(IOException e) { throw new InputMismatchException(); } } return ip.nextToken(); } void run() { try { if (System.getProperty("ONLINE_JUDGE") == null) { br = new BufferedReader(new FileReader("/media/ankanchanda/Data1/WORKPLACE/DS and CP/Competitive Programming/VSCODE/IO/input.txt")); out = new PrintWriter("/media/ankanchanda/Data1/WORKPLACE/DS and CP/Competitive Programming/VSCODE/IO/output.txt"); } else { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } } catch (FileNotFoundException e) { System.out.println(e); } solve(); out.flush(); } }
Java
["5\n\n5\n\n1 2 3 3 2\n\n1 3 3 2 2\n\n5\n\n1 2 4 2 1\n\n4 2 2 1 1\n\n5\n\n2 4 5 5 2\n\n2 2 4 5 5\n\n3\n\n1 2 3\n\n1 2 3\n\n3\n\n1 1 2\n\n2 1 1"]
1 second
["YES\nYES\nNO\nYES\nNO"]
NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation.
Java 8
standard input
[ "constructive algorithms", "greedy", "implementation", "two pointers" ]
158bd0ab8f4319f5fd1e6062caddad4e
Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$)  — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$)  — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$)  — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$)  — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$
1,700
For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response).
standard output
PASSED
749889a1a3dc404dda747c52821e9268
train_108.jsonl
1650722700
There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times: Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l &lt; r \le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times.
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; public class Codechef { public static void main (String[] args) throws java.lang.Exception { try{ FastReader read=new FastReader(); StringBuilder sb = new StringBuilder(); int t=read.nextInt(); while(t>0) { int n = read.nextInt(); int a[] = new int[n]; int b[] = new int[n]; for(int i=0;i<n;i++) { a[i] = read.nextInt(); } for(int i=0;i<n;i++) { b[i] = read.nextInt(); } int i = 0,j=0; Hashtable<Integer,Integer> ht = new Hashtable<>(); boolean flag = true; while(i<n && j<n) { if(a[i]!=b[j]) { if(ht.containsKey(b[j])) { if(b[j-1]==b[j]) { int val = ht.get(b[j]); val--; if(val==0) { ht.remove(b[j]); } else { ht.put(b[j],val); } j++; } else { while(i<n && a[i]!=b[j]) { if(ht.containsKey(a[i])) { int val = ht.get(a[i]); val++; ht.put(a[i],val); } else { ht.put(a[i],1); } i++; } if(i==n) { flag = false; break; } else { i++; j++; } } } else { while(i<n && a[i]!=b[j]) { if(ht.containsKey(a[i])) { int val = ht.get(a[i]); val++; ht.put(a[i],val); } else { ht.put(a[i],1); } i++; } if(i==n) { flag = false; break; } else { i++; j++; } } } else { i++; j++; } } //System.out.println(i+" "+j+" "+ht.size()); if(!flag) { sb.append("NO"); } else { flag = true; i=j; for(int k = i;k<n;k++) { if(ht.containsKey(b[k])) { if(b[k-1]==b[k]) { int val = ht.get(b[k]); val--; if(val==0) { ht.remove(b[k]); } else { ht.put(b[k],val); } } else { flag = false; break; } } else { flag = false; break; } } if(flag) sb.append("YES"); else sb.append("NO"); } sb.append('\n'); t--; } System.out.println(sb); } catch(Exception e) {return; } } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader( new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } 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); } 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); } static void sort(ArrayList<Long> A,char ch) { int n = A.size(); Random rnd = new Random(); for (int i = 0; i < n; ++i) { long tmp = A.get(i); int randomPos = i + rnd.nextInt(n - i); A.set(i,A.get(randomPos)); A.set(randomPos,tmp); } Collections.sort(A); } static void sort(ArrayList<Integer> A) { int n = A.size(); Random rnd = new Random(); for (int i = 0; i < n; ++i) { int tmp = A.get(i); int randomPos = i + rnd.nextInt(n - i); A.set(i,A.get(randomPos)); A.set(randomPos,tmp); } Collections.sort(A); } static String sort(String s) { Character ch[] = new Character[s.length()]; for (int i = 0; i < s.length(); i++) { ch[i] = s.charAt(i); } Arrays.sort(ch); StringBuffer st = new StringBuffer(""); for (int i = 0; i < s.length(); i++) { st.append(ch[i]); } return st.toString(); } } class pair implements Comparable<pair> { int X,Y,C; pair(int s,int e,int c) { X=s; Y=e; C=c; } public int compareTo(pair p ) { return this.C-p.C; } }
Java
["5\n\n5\n\n1 2 3 3 2\n\n1 3 3 2 2\n\n5\n\n1 2 4 2 1\n\n4 2 2 1 1\n\n5\n\n2 4 5 5 2\n\n2 2 4 5 5\n\n3\n\n1 2 3\n\n1 2 3\n\n3\n\n1 1 2\n\n2 1 1"]
1 second
["YES\nYES\nNO\nYES\nNO"]
NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation.
Java 8
standard input
[ "constructive algorithms", "greedy", "implementation", "two pointers" ]
158bd0ab8f4319f5fd1e6062caddad4e
Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$)  — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$)  — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$)  — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$)  — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$
1,700
For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response).
standard output
PASSED
a26cef55b9b3555a6c5d4cea88723c9c
train_108.jsonl
1650722700
There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times: Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l &lt; r \le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times.
256 megabytes
import java.awt.datatransfer.StringSelection; import java.util.*; import javax.management.Query; import java.io.*; public class practice { static String s; static HashMap<Long,Integer>hm; public static void main(String[] args) throws Exception { Scanner sc=new Scanner(System.in); int t=sc.nextInt(); while(t-->0) { int n=sc.nextInt(); int[] a=sc.nextIntArray(n); int[] b=sc.nextIntArray(n); int ptr=n-1; boolean f=true; int[] freq=new int[n+5]; for (int i =n-1; i >=0 ; i--) { if(b[i]!=a[ptr]){ // pw.println("not as ptr"); if(i==n-1){ f=false; break; } if(b[i]!=b[i+1]){ if(freq[a[ptr]]>0) { freq[a[ptr]]--; ptr--; i++; } else f=false; } else{ freq[b[i]]++; } } else{//pw.println("as ptr"); ptr--; } //pw.println(Arrays.toString(freq)); } pw.println(f?"Yes":"No"); } pw.close(); } public static int next(long[] arr, int target,int days) { // pw.println("days="+days); int start = 0, end = arr.length-1; // Minimum size of the array should be 1 // If target lies beyond the max element, than the index of strictly smaller // value than target should be (end - 1) if (target >= 0l+arr[end]+1l*(end+1)*days) return end; int ans = -1; while (start <= end) { int mid = (start + end) / 2; // Move to the left side if the target is smaller if (0l+arr[mid]+1l*(mid+1)*days > target) { end = mid - 1; } // Move right side else { ans = mid; start = mid + 1; } } return ans; } public static long factorial(int n){ int y=1; for (int i = 2; i <=n ; i++) { y*=i; } return y; } public static void sort(int[] in) { shuffle(in); Arrays.sort(in); } public static void shuffle(int[] in) { for (int i = 0; i < in.length; i++) { int idx = (int) (Math.random() * in.length); int tmp = in[i]; in[i] = in[idx]; in[idx] = tmp; } } static LinkedList getfact(int n){ LinkedList<Integer>ll=new LinkedList<>(); LinkedList<Integer>ll2=new LinkedList<>(); for (int i = 1; i <= Math.sqrt(n); i++) { if(n%i==0) { ll.add(i); if(i!=n/i) ll2.addLast(n/i); } } while (!ll2.isEmpty()){ ll.add(ll2.removeLast()); } return ll; } static void rev(int n){ String s1=s.substring(0,n); s=s.substring(n); for (int i = 0; i <n ; i++) { s=s1.charAt(i)+s; } } static class SegmentTree { // 1-based DS, OOP int N; //the number of elements in the array as a power of 2 (i.e. after padding) long[] array, sTree; Long[]lazy; SegmentTree(long[] in) { array = in; N = in.length - 1; sTree = new long[N<<1]; //no. of nodes = 2*N - 1, we add one to cross out index zero lazy = new Long[N<<1]; build(1,1,N); } void build(int node, int b, int e) // O(n) { if(b == e) sTree[node] = array[b]; else { int mid = b + e >> 1; build(node<<1,b,mid); build(node<<1|1,mid+1,e); sTree[node] = sTree[node<<1]+sTree[node<<1|1]; } } void update_point(int index, int val) // O(log n) { index += N - 1; sTree[index] += val; while(index>1) { index >>= 1; sTree[index] = sTree[index<<1] + sTree[index<<1|1]; } } void update_range(int i, int j, int val) // O(log n) { update_range(1,1,N,i,j,val); } void update_range(int node, int b, int e, int i, int j, int val) { if(i > e || j < b) return; if(b >= i && e <= j) { sTree[node] = (e-b+1)*val; lazy[node] = val*1l; } else { int mid = b + e >> 1; propagate(node, b, mid, e); update_range(node<<1,b,mid,i,j,val); update_range(node<<1|1,mid+1,e,i,j,val); sTree[node] = sTree[node<<1] + sTree[node<<1|1]; } } void propagate(int node, int b, int mid, int e) { if(lazy[node]!=null) { lazy[node << 1] = lazy[node]; lazy[node << 1 | 1] = lazy[node]; sTree[node << 1] = (mid - b + 1) * lazy[node]; sTree[node << 1 | 1] = (e - mid) * lazy[node]; } lazy[node] = null; } long query(int i, int j) { return query(1,1,N,i,j); } long query(int node, int b, int e, int i, int j) // O(log n) { if(i>e || j <b) return 0; if(b>= i && e <= j) return sTree[node]; int mid = b + e >> 1; propagate(node, b, mid, e); long q1 = query(node<<1,b,mid,i,j); long q2 = query(node<<1|1,mid+1,e,i,j); return q1 + q2; } } // public static long dp(int idx) { // if (idx >= n) // return Long.MAX_VALUE/2; // return Math.min(dp(idx+1),memo[idx]+dp(idx+k)); // } // if(num==k) // return dp(0,idx+1); // if(memo[num][idx]!=-1) // return memo[num][idx]; // long ret=0; // if(num==0) { // if(s.charAt(idx)=='a') // ret= dp(1,idx+1); // else if(s.charAt(idx)=='?') { // ret=Math.max(1+dp(1,idx+1),dp(0,idx+1) ); // } // } // else { // if(num%2==0) { // if(s.charAt(idx)=='a') // ret=dp(num+1,idx+1); // else if(s.charAt(idx)=='?') // ret=Math.max(1+dp(num+1,idx+1),dp(0,idx+1)); // } // else { // if(s.charAt(idx)=='b') // ret=dp(num+1,idx+1); // else if(s.charAt(idx)=='?') // ret=Math.max(1+dp(num+1,idx+1),dp(0,idx+1)); // } // } // } static void putorrem(long x){ if(hm.getOrDefault(x,0)==1){ hm.remove(x); } else hm.put(x,hm.getOrDefault(x,0)-1); } public static int max4(int a,int b, int c,int d) { int [] s= {a,b,c,d}; Arrays.sort(s); return s[3]; } public static double logbase2(int k) { return( (Math.log(k)+0.0)/Math.log(2)); } 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 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(); } } static class pair implements Comparable<pair> { long x; long y; public pair(long x, long y) { this.x = x; this.y = y; } public String toString() { return x + " " + y; } public boolean equals(Object o) { if (o instanceof pair) { pair p = (pair) o; return p.x == x && p.y == y; } return false; } public int hashCode() { return new Long(x).hashCode() * 31 + new Long(y).hashCode(); } public int compareTo(pair other) { if (this.x == other.x) { return Long.compare(this.y, other.y); } return Long.compare(this.x, other.x); } } static class tuble implements Comparable<tuble> { int x; int y; int z; public tuble(int x, int y, int z) { this.x = x; this.y = y; this.z = z; } public String toString() { return x + " " + y + " " + z; } public int compareTo(tuble other) { if (this.x == other.x) { if (this.y == other.y) { return this.z - other.z; } return this.y - other.y; } else { return this.x - other.x; } } public tuble add(tuble t){ return new tuble(this.x+t.x,this.y+t.y,this.z+t.z); } } static long mod = 1000000007; static Random rn = new Random(); static Scanner sc = new Scanner(System.in); static PrintWriter pw = new PrintWriter(System.out); }
Java
["5\n\n5\n\n1 2 3 3 2\n\n1 3 3 2 2\n\n5\n\n1 2 4 2 1\n\n4 2 2 1 1\n\n5\n\n2 4 5 5 2\n\n2 2 4 5 5\n\n3\n\n1 2 3\n\n1 2 3\n\n3\n\n1 1 2\n\n2 1 1"]
1 second
["YES\nYES\nNO\nYES\nNO"]
NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation.
Java 8
standard input
[ "constructive algorithms", "greedy", "implementation", "two pointers" ]
158bd0ab8f4319f5fd1e6062caddad4e
Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$)  — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$)  — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$)  — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$)  — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$
1,700
For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response).
standard output
PASSED
678d292c1eb63dc47f023208d012b9fc
train_108.jsonl
1650722700
There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times: Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l &lt; r \le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times.
256 megabytes
import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintStream; import java.util.Locale; import java.util.StringTokenizer; public class Solution implements Runnable { private PrintStream out; private BufferedReader in; private StringTokenizer st; public void solve() throws IOException { long time0 = System.currentTimeMillis(); int t = nextInt(); for (int test = 1; test <= t; test++) { int n = nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } int[] b = new int[n]; for (int i = 0; i < n; i++) { b[i] = nextInt(); } boolean answer = solve(n, a, b); if (answer) { out.println("YES"); } else { out.println("NO"); } } System.err.println("time: " + (System.currentTimeMillis() - time0)); } private boolean solve(int n, int[] a, int[] b) { int i = n - 1; int j = n - 1; int[] hang = new int[n + 1]; while (j >= 0) { if (a[i] == b[j]) { i--; j--; continue; } if (j + 1 < n && b[j] == b[j + 1]) { hang[b[j]]++; j--; continue; } if (hang[a[i]] > 0) { hang[a[i]]--; i--; continue; } return false; } return true; } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public String next() throws IOException { while (!st.hasMoreTokens()) { String line = in.readLine(); if (line == null) { return null; } st = new StringTokenizer(line); } return st.nextToken(); } @Override public void run() { try { solve(); out.close(); } catch (Throwable e) { throw new RuntimeException(e); } } public Solution(String name) throws IOException { Locale.setDefault(Locale.US); if (name == null) { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintStream(new BufferedOutputStream(System.out)); } else { in = new BufferedReader(new InputStreamReader(new FileInputStream(name + ".in"))); out = new PrintStream(new BufferedOutputStream(new FileOutputStream(name + ".out"))); } st = new StringTokenizer(""); } public static void main(String[] args) throws IOException { new Thread(new Solution(null)).start(); } }
Java
["5\n\n5\n\n1 2 3 3 2\n\n1 3 3 2 2\n\n5\n\n1 2 4 2 1\n\n4 2 2 1 1\n\n5\n\n2 4 5 5 2\n\n2 2 4 5 5\n\n3\n\n1 2 3\n\n1 2 3\n\n3\n\n1 1 2\n\n2 1 1"]
1 second
["YES\nYES\nNO\nYES\nNO"]
NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation.
Java 8
standard input
[ "constructive algorithms", "greedy", "implementation", "two pointers" ]
158bd0ab8f4319f5fd1e6062caddad4e
Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$)  — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$)  — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$)  — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$)  — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$
1,700
For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response).
standard output
PASSED
1dc53210b8aea97fa3beb7ecf6b9d4ca
train_108.jsonl
1650722700
There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times: Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l &lt; r \le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times.
256 megabytes
import java.util.*; import java.io.*; public class myclass { public static void main(String args[]) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while(t-->0) { int n = sc.nextInt(); int a[] = new int[n]; int b[] = new int[n]; for(int i=0 ;i<n ; i++) a[i] = sc.nextInt(); for(int i=0 ; i<n ; i++) b[i] = sc.nextInt(); int count[] = new int[n]; Arrays.fill(count , 1); int next[] = new int[n]; HashMap<Integer, Integer> map = new HashMap<>(); for(int i=n-1; i>=0 ; i--) { if(map.containsKey(a[i])) next[i] = map.get(a[i]); else next[i] = -1; map.put(a[i] , i); } int i =0 , j = 0; while(j<n) { if(a[i]==b[j]) { if(count[i]==1) i++; else count[i]--; j++; } else { if(next[i]==-1) break; count[next[i]] += count[i]; i++; } } System.out.println(j==n?"YES":"NO"); } } }
Java
["5\n\n5\n\n1 2 3 3 2\n\n1 3 3 2 2\n\n5\n\n1 2 4 2 1\n\n4 2 2 1 1\n\n5\n\n2 4 5 5 2\n\n2 2 4 5 5\n\n3\n\n1 2 3\n\n1 2 3\n\n3\n\n1 1 2\n\n2 1 1"]
1 second
["YES\nYES\nNO\nYES\nNO"]
NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation.
Java 8
standard input
[ "constructive algorithms", "greedy", "implementation", "two pointers" ]
158bd0ab8f4319f5fd1e6062caddad4e
Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$)  — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$)  — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$)  — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$)  — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$
1,700
For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response).
standard output
PASSED
43351c2123f442a7eb852115ef89fd35
train_108.jsonl
1650722700
There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times: Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l &lt; r \le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; public class AACFCC { // public static long mod = (long) Math.pow(10, 9) + 7; public static long mod2 = 998244353; public int oo = 0; // public static HashMap<Integer, Integer> primenom; // public static HashMap<Integer, Integer> primeden; // public static HashMap<Integer, Integer> fin; public static String zz; public static long ttt = -1; static HashMap<Integer, Integer>[] factors; public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw = new PrintWriter(System.out); int t = Integer.parseInt(br.readLine()); while (t-- > 0) { String[] s2 = (br.readLine()).split(" "); int n = Integer.valueOf(s2[0]); // int q = Integer.valueOf(s2[1]); int[] arr = new int[n]; String[] s1 = br.readLine().split(" "); for (int i = 0; i < n; i++) { arr[i] = Integer.valueOf(s1[i]); } int[] b = new int[n]; s1 = br.readLine().split(" "); for (int i = 0; i < n; i++) { b[i] = Integer.valueOf(s1[i]); } int w=n-1; int ans=1; HashMap<Integer,Integer> map=new HashMap<>(); for(int i=n-1;i>=0;i--) { if(i==n-1&&arr[w]!=b[i]) { ans=0; break; } if(arr[w]==b[i]) { w--; } else if(arr[w+1]==b[i]) { map.put(arr[w+1], map.getOrDefault(arr[w+1], 0)+1); } else if(map.containsKey(arr[w])) { map.put(arr[w], map.getOrDefault(arr[w], 0)-1); if(map.get(arr[w])==0) { map.remove(arr[w]); } w--; i++; }else { ans=0; break; } //System.out.println(i+" "+w+" "+ans+" "+map); } while(w>=0) { if(map.containsKey(arr[w])) { map.put(arr[w], map.getOrDefault(arr[w], 0)-1); if(map.get(arr[w])==0) { map.remove(arr[w]); } w--; }else { ans=0; break; } } if(!map.isEmpty()) { ans=0; } if(ans==0) { pw.println("NO"); }else{ pw.println("YES"); } } pw.close(); } } // private static void putBit(int ind, int val, int[] bit) { // // TODO Auto-generated method stub // for (int i = ind; i < bit.length; i += (i & -i)) { // bit[i] += val; // } // } // // private static int getSum(int ind, int[] bit) { // // TODO Auto-generated method stub // int ans = 0; // for (int i = ind; i > 0; i -= (i & -i)) { // ans += bit[i]; // } // return ans; // } // private static void product(long[] bin, int ind, int currIt, long[] power) { // // TODO Auto-generated method stub // long pre = 1; // if (ind > 1) { // pre = power(power[ind - 1] - 1, mod2 - 1); // } // long cc = power[ind] - 1; // // System.out.println(pre + " " + cc); // for (int i = ind; i < bin.length; i += (i & (-i))) { // bin[i] = (bin[i] * pre) % mod2; // bin[i] = (bin[i] * cc) % mod2; // } // } // // private static void add(long[] bin, int ind, int val) { // // TODO Auto-generated method stub // for (int i = ind; i < bin.length; i += (i & (-i))) { // bin[i] += val; // } // } // // private static long sum(long[] bin, int ind) { // // TODO Auto-generated method stub // long ans = 0; // for (int i = ind; i > 0; i -= (i & (-i))) { // ans += bin[i]; // } // return ans; // } // // private static long power(long a, long p) { // TODO Auto-generated method stub // long res = 1;while(p>0) // { // if (p % 2 == 1) { // res = (res * a) % mod; // } // p = p / 2; // a = (a * a) % mod; // }return res; // }} // private static void getFac(long n, PrintWriter pw) { // // TODO Auto-generated method stub // int a = 0; // while (n % 2 == 0) { // a++; // n = n / 2; // } // if (n == 1) { // a--; // } // for (int i = 3; i <= Math.sqrt(n); i += 2) { // while (n % i == 0) { // n = n / i; // a++; // } // } // if (n > 1) { // a++; // } // if (a % 2 == 0) { // pw.println("Bob"); // } else { // pw.println("Alice"); // } // //System.out.println(a); // return; // } // private static long power(long a, long p) { // // TODO Auto-generated method stub // long res = 1; // while (p > 0) { // if (p % 2 == 1) { // res = (res * a) % mod; // } // p = p / 2; // a = (a * a) % mod; // } // return res; // } // // private static void fac() { // fac[0] = 1; // // TODO Auto-generated method stub // for (int i = 1; i < fac.length; i++) { // if (i == 1) { // fac[i] = 1; // } else { // fac[i] = i * fac[i - 1]; // } // if (fac[i] > mod) { // fac[i] = fac[i] % mod; // } // } // } // // private static int getLower(Long long1, Long[] st) { // // TODO Auto-generated method stub // int left = 0, right = st.length - 1; // int ans = -1; // while (left <= right) { // int mid = (left + right) / 2; // if (st[mid] <= long1) { // ans = mid; // left = mid + 1; // } else { // right = mid - 1; // } // } // return ans; // } // private static long getGCD(long l, long m) { // // long t1 = Math.min(l, m); // long t2 = Math.max(l, m); // while (true) { // long temp = t2 % t1; // if (temp == 0) { // return t1; // } // t2 = t1; // t1 = temp; // } // } // private static int kmp(String str) { // // TODO Auto-generated method stub // // System.out.println(str); // int[] pi = new int[str.length()]; // pi[0] = 0; // for (int i = 1; i < str.length(); i++) { // int j = pi[i - 1]; // while (j > 0 && str.charAt(i) != str.charAt(j)) { // j = pi[j - 1]; // } // if (str.charAt(j) == str.charAt(i)) { // j++; // } // pi[i] = j; // System.out.print(pi[i]); // } // System.out.println(); // return pi[str.length() - 1]; // } // private static void getFac(long n, PrintWriter pw) { // // TODO Auto-generated method stub // int a = 0; // while (n % 2 == 0) { // a++; // n = n / 2; // } // if (n == 1) { // a--; // } // for (int i = 3; i <= Math.sqrt(n); i += 2) { // while (n % i == 0) { // n = n / i; // a++; // } // } // if (n > 1) { // a++; // } // if (a % 2 == 0) { // pw.println("Bob"); // } else { // pw.println("Alice"); // } // //System.out.println(a); // return; // } // private static long power(long a, long p) { // // TODO Auto-generated method stub // long res = 1; // while (p > 0) { // if (p % 2 == 1) { // res = (res * a) % mod; // } // p = p / 2; // a = (a * a) % mod; // } // return res; // } // // private static void fac() { // fac[0] = 1; // // TODO Auto-generated method stub // for (int i = 1; i < fac.length; i++) { // if (i == 1) { // fac[i] = 1; // } else { // fac[i] = i * fac[i - 1]; // } // if (fac[i] > mod) { // fac[i] = fac[i] % mod; // } // } // } // // private static int getLower(Long long1, Long[] st) { // // TODO Auto-generated method stub // int left = 0, right = st.length - 1; // int ans = -1; // while (left <= right) { // int mid = (left + right) / 2; // if (st[mid] <= long1) { // ans = mid; // left = mid + 1; // } else { // right = mid - 1; // } // } // return ans; // } // private static long getGCD(long l, long m) { // // long t1 = Math.min(l, m); // long t2 = Math.max(l, m); // while (true) { // long temp = t2 % t1; // if (temp == 0) { // return t1; // } // t2 = t1; // t1 = temp; // } // }
Java
["5\n\n5\n\n1 2 3 3 2\n\n1 3 3 2 2\n\n5\n\n1 2 4 2 1\n\n4 2 2 1 1\n\n5\n\n2 4 5 5 2\n\n2 2 4 5 5\n\n3\n\n1 2 3\n\n1 2 3\n\n3\n\n1 1 2\n\n2 1 1"]
1 second
["YES\nYES\nNO\nYES\nNO"]
NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation.
Java 8
standard input
[ "constructive algorithms", "greedy", "implementation", "two pointers" ]
158bd0ab8f4319f5fd1e6062caddad4e
Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$)  — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$)  — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$)  — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$)  — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$
1,700
For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response).
standard output
PASSED
7b5a4d6ae892ca8d3bd0b9bab1ce0e38
train_108.jsonl
1650722700
There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times: Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l &lt; r \le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times.
256 megabytes
import java.io.*; import java.util.*; import java.math.*; public class D { static byte[] buf = new byte[1<<26]; static int bp = -1; public static void main(String[] args) throws IOException { /**/ DataInputStream in = new DataInputStream(System.in); /*/ DataInputStream in = new DataInputStream(new FileInputStream("src/d.in")); /**/ in.read(buf, 0, 1<<26); int t = nni(); for (int z = 0; z < t; ++z) { int n = nni(); int[] a = new int[n]; for (int i = 0; i < n; ++i) a[i] = nni(); int[] b = new int[n]; for (int i = 0; i < n; ++i) b[i] = nni(); int[] cts = new int[n+1]; int pa = 0; int pb = 0; int lb = -1; while (pa<n&&pb<n) { if (a[pa]==b[pb]) { lb = b[pb]; ++pa; ++pb; continue; } else if (b[pb]==lb&&cts[lb]>0) { --cts[lb]; ++pb; continue; } else { ++cts[a[pa]]; ++pa; continue; } } while (pb<n) { if (b[pb]==lb&&cts[lb]>0) { --cts[lb]; ++pb; continue; } else { break; } } if (pa==n&&pb==n) { System.out.println("YES"); } else { System.out.println("NO"); } } } public static int nni() { int ret = 0; byte b = buf[++bp]; while (true) { ret = ret*10+b-'0'; b = buf[++bp]; if (b<'0'||b>'9') { while (buf[bp+1]=='\r'||buf[bp+1]=='\n'||buf[bp+1]==' ') {++bp;} break; } } return ret; } }
Java
["5\n\n5\n\n1 2 3 3 2\n\n1 3 3 2 2\n\n5\n\n1 2 4 2 1\n\n4 2 2 1 1\n\n5\n\n2 4 5 5 2\n\n2 2 4 5 5\n\n3\n\n1 2 3\n\n1 2 3\n\n3\n\n1 1 2\n\n2 1 1"]
1 second
["YES\nYES\nNO\nYES\nNO"]
NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation.
Java 8
standard input
[ "constructive algorithms", "greedy", "implementation", "two pointers" ]
158bd0ab8f4319f5fd1e6062caddad4e
Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$)  — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$)  — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$)  — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$)  — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$
1,700
For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response).
standard output
PASSED
f524faa9030766bb9eded20031964384
train_108.jsonl
1650722700
You have a binary string $$$a$$$ of length $$$n$$$ consisting only of digits $$$0$$$ and $$$1$$$. You are given $$$q$$$ queries. In the $$$i$$$-th query, you are given two indices $$$l$$$ and $$$r$$$ such that $$$1 \le l \le r \le n$$$. Let $$$s=a[l,r]$$$. You are allowed to do the following operation on $$$s$$$: Choose two indices $$$x$$$ and $$$y$$$ such that $$$1 \le x \le y \le |s|$$$. Let $$$t$$$ be the substring $$$t = s[x, y]$$$. Then for all $$$1 \le i \le |t| - 1$$$, the condition $$$t_i \neq t_{i+1}$$$ has to hold. Note that $$$x = y$$$ is always a valid substring. Delete the substring $$$s[x, y]$$$ from $$$s$$$. For each of the $$$q$$$ queries, find the minimum number of operations needed to make $$$s$$$ an empty string.Note that for a string $$$s$$$, $$$s[l,r]$$$ denotes the subsegment $$$s_l,s_{l+1},\ldots,s_r$$$.
256 megabytes
import java.util.*; import java.io.*; // you can compare with output.txt and expected out public class RoundGlobal20H { 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))); RoundGlobal20H sol = new RoundGlobal20H(); 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) { n = in.nextInt(); int q = in.nextInt(); a = in.next(); preprocess(a); for(int j=0; j<q; j++) { int l = in.nextInt()-1; int r = in.nextInt()-1; int ans = query(l, r); out.println(ans); } if(isDebug) out.flush(); } in.close(); out.close(); } String a; int n; private int query(int l, int r) { if(nexts[l] > r) return 1; int n00 = t00[prevs[r]] - t00[starts[l]]; int n01 = t01[prevs[r]] - t01[starts[l]]; int n10 = t10[prevs[r]] - t10[starts[l]]; int n11 = t11[prevs[r]] - t11[starts[l]]; if(a.charAt(l) == '0') { if(a.charAt(nexts[l]-1) == '0') n00++; else n01++; } else { if(a.charAt(nexts[l]-1) == '0') n10++; else n11++; } if(a.charAt(starts[r]) == '0') { if(a.charAt(r) == '0') n00++; else n01++; } else { if(a.charAt(r) == '0') n10++; else n11++; } if(a.charAt(l) == '0') { if(a.charAt(r) == '0') n00--; else n01--; } else { if(a.charAt(r) == '0') n10--; else n11--; } int ans = 1; ans += n10; int k = Math.min(n00, n11); ans += k; n00 -= k; n11 -= k; ans += n00 + n11; return ans; } private void preprocess(String a) { // case 1: xxx1 + 101010101 + 1xxxx // can be handled separately // case 2: xxx1 + 10101010 + 0xxxx // extra save 1 comes in // actually, whenever we have 10101010 or (symmetrically) 01010101 _in the middle_, // a save happens // t00 t01 t10 t11 // a) 0..1 + 1..0 + 0..0 1 1 1 // -> 0..0 1 // b) 0..1 + 1..0 + 0..1 2 1 // -> 0..1 1 // c) 1..1 + 1..0 + 0..0 1 1 1 // -> 1..0 1 // d) 1..1 + 1..0 + 0..1 1 1 1 // -> 1..1 1 // should be symmetrical w.r.t. flipping (0 <-> 1) as well // t00 - t11 remains unchanged // t01 - t10 remains unchanged t00 = new int[n]; t01 = new int[n]; t10 = new int[n]; t11 = new int[n]; nexts = new int[n]; prevs = new int[n]; starts = new int[n]; int prev = -1; int start = 0; while(start < n) { int end = start+1; while(end < n && a.charAt(end) != a.charAt(end-1)) end++; int[] t; if(a.charAt(start) == '0') { if(a.charAt(end-1) == '0') t = t00; else t = t01; } else { if(a.charAt(end-1) == '0') t = t10; else t = t11; } if(prev >= 0){ t00[start] = t00[prev]; t01[start] = t01[prev]; t10[start] = t10[prev]; t11[start] = t11[prev]; } t[start]++; for(int i=start; i<end; i++) { prevs[i] = prev; nexts[i] = end; starts[i] = start; } prev = start; start = end; } } int[] t00, t01, t10, t11, nexts, prevs, starts; 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(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(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 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 3\n11011\n2 4\n1 5\n3 5", "10 3\n1001110110\n1 10\n2 5\n5 10"]
1 second
["1\n3\n2", "4\n2\n3"]
NoteIn the first test case, The substring is $$$\texttt{101}$$$, so we can do one operation to make the substring empty. The substring is $$$\texttt{11011}$$$, so we can do one operation on $$$s[2, 4]$$$ to make $$$\texttt{11}$$$, then use two more operations to make the substring empty. The substring is $$$\texttt{011}$$$, so we can do one operation on $$$s[1, 2]$$$ to make $$$\texttt{1}$$$, then use one more operation to make the substring empty.
Java 17
standard input
[ "constructive algorithms", "data structures", "greedy" ]
d1c3b8985d0c17e0806117bef30d7ff2
The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n, q \le 2 \cdot 10 ^ 5$$$)  — the length of the binary string $$$a$$$ and the number of queries respectively. The second line contains a binary string $$$a$$$ of length $$$n$$$ ($$$a_i \in \{0, 1\}$$$). Each of the next $$$q$$$ lines contains two integers $$$l$$$ and $$$r$$$ ($$$1 \le l \le r \le n$$$)  — representing the substring of each query.
2,700
Print $$$q$$$ lines, the $$$i$$$-th line representing the minimum number of operations needed for the $$$i$$$-th query.
standard output
PASSED
76004ac7b6b3076ddb0bf3a6427bc1b4
train_108.jsonl
1650722700
You have a binary string $$$a$$$ of length $$$n$$$ consisting only of digits $$$0$$$ and $$$1$$$. You are given $$$q$$$ queries. In the $$$i$$$-th query, you are given two indices $$$l$$$ and $$$r$$$ such that $$$1 \le l \le r \le n$$$. Let $$$s=a[l,r]$$$. You are allowed to do the following operation on $$$s$$$: Choose two indices $$$x$$$ and $$$y$$$ such that $$$1 \le x \le y \le |s|$$$. Let $$$t$$$ be the substring $$$t = s[x, y]$$$. Then for all $$$1 \le i \le |t| - 1$$$, the condition $$$t_i \neq t_{i+1}$$$ has to hold. Note that $$$x = y$$$ is always a valid substring. Delete the substring $$$s[x, y]$$$ from $$$s$$$. For each of the $$$q$$$ queries, find the minimum number of operations needed to make $$$s$$$ an empty string.Note that for a string $$$s$$$, $$$s[l,r]$$$ denotes the subsegment $$$s_l,s_{l+1},\ldots,s_r$$$.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author lucasr */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; MyScanner in = new MyScanner(inputStream); PrintWriter out = new PrintWriter(outputStream); HZiguZagu solver = new HZiguZagu(); solver.solve(1, in, out); out.close(); } static class HZiguZagu { public static MyScanner sc; public static PrintWriter out; public void solve(int testNumber, MyScanner sc, PrintWriter out) { HZiguZagu.sc = sc; HZiguZagu.out = out; int n = sc.nextInt(); int q = sc.nextInt(); char[] vals = sc.next().toCharArray(); int[][] acum = new int[2][n]; for (int i = 0; i < 2; i++) { for (int j = 1; j < n; j++) { acum[i][j] = acum[i][j - 1]; if (vals[j] == '0' + i && vals[j] == vals[j - 1]) { acum[i][j]++; } } } for (int i = 0; i < q; i++) { int l = sc.nextInt() - 1; int r = sc.nextInt() - 1; int zeroes = acum[0][r] - acum[0][l]; int ones = acum[1][r] - acum[1][l]; out.println(Math.max(zeroes, ones) + 1); } } } static class MyScanner { private BufferedReader br; private StringTokenizer tokenizer; public MyScanner(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(br.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["5 3\n11011\n2 4\n1 5\n3 5", "10 3\n1001110110\n1 10\n2 5\n5 10"]
1 second
["1\n3\n2", "4\n2\n3"]
NoteIn the first test case, The substring is $$$\texttt{101}$$$, so we can do one operation to make the substring empty. The substring is $$$\texttt{11011}$$$, so we can do one operation on $$$s[2, 4]$$$ to make $$$\texttt{11}$$$, then use two more operations to make the substring empty. The substring is $$$\texttt{011}$$$, so we can do one operation on $$$s[1, 2]$$$ to make $$$\texttt{1}$$$, then use one more operation to make the substring empty.
Java 11
standard input
[ "constructive algorithms", "data structures", "greedy" ]
d1c3b8985d0c17e0806117bef30d7ff2
The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n, q \le 2 \cdot 10 ^ 5$$$)  — the length of the binary string $$$a$$$ and the number of queries respectively. The second line contains a binary string $$$a$$$ of length $$$n$$$ ($$$a_i \in \{0, 1\}$$$). Each of the next $$$q$$$ lines contains two integers $$$l$$$ and $$$r$$$ ($$$1 \le l \le r \le n$$$)  — representing the substring of each query.
2,700
Print $$$q$$$ lines, the $$$i$$$-th line representing the minimum number of operations needed for the $$$i$$$-th query.
standard output
PASSED
aea82d2887f5276776ccc0f5fd755a57
train_108.jsonl
1650722700
You have a binary string $$$a$$$ of length $$$n$$$ consisting only of digits $$$0$$$ and $$$1$$$. You are given $$$q$$$ queries. In the $$$i$$$-th query, you are given two indices $$$l$$$ and $$$r$$$ such that $$$1 \le l \le r \le n$$$. Let $$$s=a[l,r]$$$. You are allowed to do the following operation on $$$s$$$: Choose two indices $$$x$$$ and $$$y$$$ such that $$$1 \le x \le y \le |s|$$$. Let $$$t$$$ be the substring $$$t = s[x, y]$$$. Then for all $$$1 \le i \le |t| - 1$$$, the condition $$$t_i \neq t_{i+1}$$$ has to hold. Note that $$$x = y$$$ is always a valid substring. Delete the substring $$$s[x, y]$$$ from $$$s$$$. For each of the $$$q$$$ queries, find the minimum number of operations needed to make $$$s$$$ an empty string.Note that for a string $$$s$$$, $$$s[l,r]$$$ denotes the subsegment $$$s_l,s_{l+1},\ldots,s_r$$$.
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; public class H { FastScanner in; PrintWriter out; boolean systemIO = true; public class DSU { int[] sz; int[] p; public DSU(int n) { sz = new int[n]; p = new int[n]; for (int i = 0; i < p.length; i++) { p[i] = i; sz[i] = 1; } } public int get(int x) { if (x == p[x]) { return x; } int par = get(p[x]); p[x] = par; return par; } public boolean unite(int a, int b) { int pa = get(a); int pb = get(b); if (pa == pb) { return false; } if (sz[pa] < sz[pb]) { p[pa] = pb; sz[pb] += sz[pa]; } else { p[pb] = pa; sz[pa] += sz[pb]; } return true; } } public class SegmentTreeAdd { int pow; long[] max; long[] delta; boolean[] flag; public SegmentTreeAdd(long[] a) { pow = 1; while (pow < a.length) { pow *= 2; } flag = new boolean[2 * pow]; max = new long[2 * pow]; delta = new long[2 * pow]; for (int i = 0; i < max.length; i++) { max[i] = Long.MIN_VALUE / 2; } for (int i = 0; i < a.length; i++) { max[pow + i] = a[i]; } for (int i = pow - 1; i > 0; i--) { max[i] = f(max[2 * i], max[2 * i + 1]); } } public long get(int v, int tl, int tr, int l, int r) { push(v, tl, tr); if (l > r) { return Long.MIN_VALUE / 2; } if (l == tl && r == tr) { return max[v]; } int tm = (tl + tr) / 2; return f(get(2 * v, tl, tm, l, Math.min(r, tm)), get(2 * v + 1, tm + 1, tr, Math.max(l, tm + 1), r)); } public void set(int v, int tl, int tr, int l, int r, long x) { push(v, tl, tr); if (l > tr || r < tl) { return; } if (l <= tl && r >= tr) { delta[v] += x; flag[v] = true; push(v, tl, tr); return; } int tm = (tl + tr) / 2; set(2 * v, tl, tm, l, r, x); set(2 * v + 1, tm + 1, tr, l, r, x); max[v] = f(max[2 * v], max[2 * v + 1]); } public void push(int v, int tl, int tr) { if (flag[v]) { if (v < pow) { flag[2 * v] = true; flag[2 * v + 1] = true; delta[2 * v] += delta[v]; delta[2 * v + 1] += delta[v]; } flag[v] = false; max[v] += delta[v]; delta[v] = 0; } } public long f(long a, long b) { return Math.max(a, b); } } public class SegmentTreeSet { int pow; int[] sum; int[] delta; boolean[] flag; public SegmentTreeSet(int[] a) { pow = 1; while (pow < a.length) { pow *= 2; } flag = new boolean[2 * pow]; sum = new int[2 * pow]; delta = new int[2 * pow]; for (int i = 0; i < a.length; i++) { sum[pow + i] = a[i]; } for (int i = pow - 1; i > 0; i--) { sum[i] = f(sum[2 * i], sum[2 * i + 1]); } } public int get(int v, int tl, int tr, int l, int r) { push(v, tl, tr); if (l > r) { return 0; } if (l == tl && r == tr) { return sum[v]; } int tm = (tl + tr) / 2; return f(get(2 * v, tl, tm, l, Math.min(r, tm)), get(2 * v + 1, tm + 1, tr, Math.max(l, tm + 1), r)); } public void set(int v, int tl, int tr, int l, int r, int x) { push(v, tl, tr); if (l > tr || r < tl) { return; } if (l <= tl && r >= tr) { delta[v] = x; flag[v] = true; push(v, tl, tr); return; } int tm = (tl + tr) / 2; set(2 * v, tl, tm, l, r, x); set(2 * v + 1, tm + 1, tr, l, r, x); sum[v] = f(sum[2 * v], sum[2 * v + 1]); } public void push(int v, int tl, int tr) { if (flag[v]) { if (v < pow) { flag[2 * v] = true; flag[2 * v + 1] = true; delta[2 * v] = delta[v]; delta[2 * v + 1] = delta[v]; } flag[v] = false; sum[v] = delta[v] * (tr - tl + 1); } } public int f(int a, int b) { return a + b; } } public class Pair implements Comparable<Pair> { int x; int y; public Pair(int x, int y) { this.x = x; this.y = y; } public Pair clone() { return new Pair(x, y); } public String toString() { return x + " " + y; } @Override public int compareTo(Pair o) { if (x > o.x) { return 1; } if (x < o.x) { return -1; } if (y > o.y) { return 1; } if (y < o.y) { return -1; } return 0; } } long mod = 1000000007; Random random = new Random(566); public void shuffle(Pair[] a) { for (int i = 0; i < a.length; i++) { int x = random.nextInt(i + 1); Pair t = a[x]; a[x] = a[i]; a[i] = t; } } public void sort(int[][] a) { for (int i = 0; i < a.length; i++) { Arrays.sort(a[i]); } } public void add(Map<Long, Integer> map, long l) { if (map.containsKey(l)) { map.put(l, map.get(l) + 1); } else { map.put(l, 1); } } public void remove(Map<Integer, Integer> map, Integer s) { if (map.get(s) > 1) { map.put(s, map.get(s) - 1); } else { map.remove(s); } } long max = Long.MAX_VALUE / 2; double eps = 1e-10; public int signum(double x) { if (x > eps) { return 1; } if (x < -eps) { return -1; } return 0; } public long abs(long x) { return x < 0 ? -x : x; } public long min(long x, long y) { return x < y ? x : y; } public long max(long x, long y) { return x > y ? x : y; } public long gcd(long x, long y) { while (y > 0) { long c = y; y = x % y; x = c; } return x; } public final Vector ZERO = new Vector(0, 0); // public class Vector implements Comparable<Vector> { // long x; // long y; // int type; // int number; // // public Vector() { // x = 0; // y = 0; // } // // public Vector(long x, long y, int type, int number) { // this.x = x; // this.y = y; // this.type = type; // this.number = number; // } // // public Vector(long x, long y) { // // } // // public Vector(Point begin, Point end) { // this(end.x - begin.x, end.y - begin.y); // } // // public void orient() { // if (x < 0) { // x = -x; // y = -y; // } // if (x == 0 && y < 0) { // y = -y; // } // } // // public void normalize() { // long gcd = gcd(abs(x), abs(y)); // x /= gcd; // y /= gcd; // } // // public String toString() { // return x + " " + y; // } // // public boolean equals(Vector v) { // return x == v.x && y == v.y; // } // // public boolean collinear(Vector v) { // return cp(this, v) == 0; // } // // public boolean orthogonal(Vector v) { // return dp(this, v) == 0; // } // // public Vector ort(Vector v) { // return new Vector(-y, x); // } // // public Vector add(Vector v) { // return new Vector(x + v.x, y + v.y); // } // // public Vector multiply(long c) { // return new Vector(c * x, c * y); // } // // public int quater() { // if (x > 0 && y >= 0) { // return 1; // } // if (x <= 0 && y > 0) { // return 2; // } // if (x < 0) { // return 3; // } // return 0; // } // // public long len2() { // return x * x + y * y; // } // // @Override // public int compareTo(Vector o) { // if (quater() != o.quater()) { // return quater() - o.quater(); // } // return signum(cp(o, this)); // } // } // public long dp(Vector v1, Vector v2) { // return v1.x * v2.x + v1.y * v2.y; // } // // public long cp(Vector v1, Vector v2) { // return v1.x * v2.y - v1.y * v2.x; // } // public class Line implements Comparable<Line> { // Point p; // Vector v; // // public Line(Point p, Vector v) { // this.p = p; // this.v = v; // } // // public Line(Point p1, Point p2) { // if (p1.compareTo(p2) < 0) { // p = p1; // v = new Vector(p1, p2); // } else { // p = p2; // v = new Vector(); // } // } // // public boolean collinear(Line l) { // return v.collinear(l.v); // } // // public boolean inLine(Point p) { // return hv(p) == 0; // } // // public boolean inSegment(Point p) { // if (!inLine(p)) { // return false; // } // Point p1 = p; // Point p2 = p.add(v); // return p1.x <= p.x && p.x <= p2.x && min(p1.y, p2.y) <= p.y && p.y <= // max(p1.y, p2.y); // } // // public boolean equalsSegment(Line l) { // return p.equals(l.p) && v.equals(l.v); // } // // public boolean equalsLine(Line l) { // return collinear(l) && inLine(l.p); // } // // public long hv(Point p) { // Vector v1 = new Vector(this.p, p); // return cp(v, v1); // } // // public double h(Point p) { // Vector v1 = new Vector(this.p, p); // return cp(v, v1) / Math.sqrt(v.len2()); // } // // public long[] intersectLines(Line l) { // if (collinear(l)) { // return null; // } // long[] ans = new long[4]; // // return ans; // } // // public long[] intersectSegment(Line l) { // long[] ans = intersectLines(l); // if (ans == null) { // return null; // } // Point p1 = p; // Point p2 = p.add(v); // boolean f1 = p1.x * ans[1] <= ans[0] && ans[0] <= p2.x * ans[1] && min(p1.y, // p2.y) * ans[3] <= ans[2] // && ans[2] <= max(p1.y, p2.y) * ans[3]; // p1 = l.p; // p2 = l.p.add(v); // boolean f2 = p1.x * ans[1] <= ans[0] && ans[0] <= p2.x * ans[1] && min(p1.y, // p2.y) * ans[3] <= ans[2] // && ans[2] <= max(p1.y, p2.y) * ans[3]; // if (!f1 || !f2) { // return null; // } // return ans; // } // // @Override // public int compareTo(Line o) { // return v.compareTo(o.v); // } // } public class Rect { long x1; long x2; long y1; long y2; int number; public Rect(long x1, long x2, long y1, long y2, int number) { this.x1 = x1; this.x2 = x2; this.y1 = y1; this.y2 = y2; this.number = number; } } public static class Fenvik { int[] t; public Fenvik(int n) { t = new int[n]; } public void add(int x, int delta) { for (int i = x; i < t.length; i = (i | (i + 1))) { t[i] += delta; } } private int sum(int r) { int ans = 0; int x = r; while (x >= 0) { ans += t[x]; x = (x & (x + 1)) - 1; } return ans; } public int sum(int l, int r) { return sum(r) - sum(l - 1); } } public class SegmentTreeMaxSum { int pow; int[] sum; int[] maxPrefSum; int[] maxSufSum; int[] maxSum; public SegmentTreeMaxSum(int[] a) { pow = 1; while (pow < a.length) { pow *= 2; } sum = new int[2 * pow]; maxPrefSum = new int[2 * pow]; maxSum = new int[2 * pow]; maxSufSum = new int[2 * pow]; for (int i = 0; i < a.length; i++) { sum[pow + i] = a[i]; maxSum[pow + i] = Math.max(a[i], 0); maxPrefSum[pow + i] = maxSum[pow + i]; maxSufSum[pow + i] = maxSum[pow + i]; } for (int i = pow - 1; i > 0; i--) { update(i); } } public int[] get(int v, int tl, int tr, int l, int r) { if (r <= tl || l >= tr) { int[] ans = { 0, 0, 0, 0 }; return ans; } if (l <= tl && r >= tr) { int[] ans = { maxPrefSum[v], maxSum[v], maxSufSum[v], sum[v] }; return ans; } int tm = (tl + tr) / 2; int[] left = get(2 * v, tl, tm, l, r); int[] right = get(2 * v + 1, tm, tr, l, r); int[] ans = { Math.max(left[0], right[0] + left[3]), Math.max(left[1], Math.max(right[1], left[2] + right[0])), Math.max(right[2], left[2] + right[3]), left[3] + right[3] }; return ans; } public void set(int v, int tl, int tr, int x, int value) { if (v >= pow) { sum[v] = value; maxSum[v] = Math.max(value, 0); maxPrefSum[v] = maxSum[v]; maxSufSum[v] = maxSum[v]; return; } int tm = (tl + tr) / 2; if (x < tm) { set(2 * v, tl, tm, x, value); } else { set(2 * v + 1, tm, tr, x, value); } update(v); } public void update(int i) { sum[i] = f(sum[2 * i], sum[2 * i + 1]); maxSum[i] = Math.max(maxSum[2 * i], Math.max(maxSum[2 * i + 1], maxSufSum[2 * i] + maxPrefSum[2 * i + 1])); maxPrefSum[i] = Math.max(maxPrefSum[2 * i], maxPrefSum[2 * i + 1] + sum[2 * i]); maxSufSum[i] = Math.max(maxSufSum[2 * i + 1], maxSufSum[2 * i] + sum[2 * i + 1]); } public int f(int a, int b) { return a + b; } } public class Circle implements Comparable<Circle> { Point p; int r; public Circle(Point p, int r) { this.p = p; this.r = r; } public Point angle() { double z = r / sq2; z -= z % 1e-5; return new Point(p.x - z, p.y - z); } public boolean inside(Point p) { return hypot2(p.x - this.p.x, p.y - this.p.y) <= sq(r); } @Override public int compareTo(Circle o) { Point a = angle(); Point oa = o.angle(); int z = signum(a.x + a.y - oa.x - oa.y); if (z != 0) { return z; } return signum(a.y - oa.y); } } public class Fraction implements Comparable<Fraction> { long x; long y; public Fraction(long x, long y, boolean needNorm) { this.x = x; this.y = y; if (y < 0) { this.x *= -1; this.y *= -1; } if (needNorm) { long gcd = gcd(this.x, this.y); this.x /= gcd; this.y /= gcd; } } public Fraction clone() { return new Fraction(x, y, false); } public String toString() { return x + "/" + y; } @Override public int compareTo(Fraction o) { long res = x * o.y - y * o.x; if (res > 0) { return 1; } if (res < 0) { return -1; } return 0; } } public double sq(double x) { return x * x; } public long sq(long x) { return x * x; } public double hypot2(double x, double y) { return sq(x) + sq(y); } public long hypot2(long x, long y) { return sq(x) + sq(y); } public boolean kuhn(int v, int[][] edge, boolean[] used, int[] mt) { used[v] = true; for (int u : edge[v]) { if (mt[u] < 0 || (!used[mt[u]] && kuhn(mt[u], edge, used, mt))) { mt[u] = v; return true; } } return false; } public int matching(int[][] edge) { int n = edge.length; int[] mt = new int[n]; Arrays.fill(mt, -1); boolean[] used = new boolean[n]; int ans = 0; for (int i = 0; i < n; i++) { if (!used[i] && kuhn(i, edge, used, mt)) { Arrays.fill(used, false); ans++; } } return ans; } double sq2 = Math.sqrt(2); int small = 20; public class MyStack { int[] st; int sz; public MyStack(int n) { this.st = new int[n]; sz = 0; } public boolean isEmpty() { return sz == 0; } public int peek() { return st[sz - 1]; } public int pop() { sz--; return st[sz]; } public void clear() { sz = 0; } public void add(int x) { st[sz++] = x; } public int get(int x) { return st[x]; } } public int[][] readGraph(int n, int m) { int[][] to = new int[n][]; int[] sz = new int[n]; int[] x = new int[m]; int[] y = new int[m]; for (int i = 0; i < m; i++) { x[i] = in.nextInt() - 1; y[i] = in.nextInt() - 1; sz[x[i]]++; sz[y[i]]++; } for (int i = 0; i < to.length; i++) { to[i] = new int[sz[i]]; sz[i] = 0; } for (int i = 0; i < x.length; i++) { to[x[i]][sz[x[i]]++] = y[i]; to[y[i]][sz[y[i]]++] = x[i]; } return to; } public class Pol { double[] coeff; public Pol(double[] coeff) { this.coeff = coeff; } public Pol mult(Pol p) { double[] ans = new double[coeff.length + p.coeff.length - 1]; for (int i = 0; i < ans.length; i++) { for (int j = Math.max(0, i - p.coeff.length + 1); j < coeff.length && j <= i; j++) { ans[i] += coeff[j] * p.coeff[i - j]; } } return new Pol(ans); } public String toString() { String ans = ""; for (int i = 0; i < coeff.length; i++) { ans += coeff[i] + " "; } return ans; } public double value(double x) { double ans = 0; double p = 1; for (int i = 0; i < coeff.length; i++) { ans += coeff[i] * p; p *= x; } return ans; } public double integrate(double r) { Pol p = new Pol(new double[coeff.length + 1]); for (int i = 0; i < coeff.length; i++) { p.coeff[i + 1] = coeff[i] / fact[i + 1]; } return p.value(r); } public double integrate(double l, double r) { return integrate(r) - integrate(l); } } double[] fact = new double[100]; public class SparseTable { int pow; int[] lessPow; int[][] min; public SparseTable(int[] a) { pow = 0; while ((1 << pow) <= a.length) { pow++; } min = new int[pow][a.length]; for (int i = 0; i < a.length; i++) { min[0][i] = a[i]; } for (int i = 1; i < pow; i++) { for (int j = 0; j < a.length; j++) { min[i][j] = min[i - 1][j]; if (j + (1 << (i - 1)) < a.length) { min[i][j] = func(min[i][j], min[i - 1][j + (1 << (i - 1))]); } } } lessPow = new int[a.length + 1]; for (int i = 1; i < lessPow.length; i++) { if (i < (1 << (lessPow[i - 1]) + 1)) { lessPow[i] = lessPow[i - 1]; } else { lessPow[i] = lessPow[i - 1] + 1; } } } public int get(int l, int r) { // [l, r) int p = lessPow[r - l]; return func(min[p][l], min[p][r - (1 << p)]); } public int func(int a, int b) { if (a < b) { return a; } return b; } } public double check(int n, ArrayList<Integer> masks) { int good = 0; for (int colorMask = 0; colorMask < (1 << n); ++colorMask) { int best = 2 << n; int cnt = 0; for (int curMask : masks) { int curScore = 0; for (int i = 0; i < n; ++i) { if (((curMask >> i) & 1) == 1) { if (((colorMask >> i) & 1) == 0) { curScore += 1; } else { curScore += 2; } } } if (curScore < best) { best = curScore; cnt = 1; } else if (curScore == best) { ++cnt; } } if (cnt == 1) { ++good; } } return (double) good / (double) (1 << n); } public int builtin_popcount(int x) { int ans = 0; for (int i = 0; i < 14; i++) { if (((x >> i) & 1) > 0) { ans++; } } return ans; } public int number(int[] x) { int ans = 0; for (int i = 0; i < x.length; i++) { ans *= 3; ans += x[i]; } return ans; } public int[] rotate(int[] x) { int[] ans = { x[2], x[0], x[3], x[1] }; return ans; } int MAX = 100000; boolean[] b = new boolean[MAX]; int[][] max0 = new int[MAX][2]; int[][] max1 = new int[MAX][2]; int[][] max2 = new int[MAX][2]; int[] index0 = new int[MAX]; int[] index1 = new int[MAX]; int[] p = new int[MAX]; public int place(String s) { if (s.charAt(s.length() - 1) == '1') { return 1; } int number = 16; boolean w = true; boolean a = true; for (int i = 0; i < s.length(); i++) { if (number == 1) { return 2; } if (s.charAt(i) == '1') { if (w) { number /= 2; } else { if (a) { a = false; } else { number /= 2; a = true; } } } else { if (w) { if (number == 16) { w = false; number /= 2; } else { w = false; a = false; } } else { if (number == 8) { if (a) { return 13; } else { return 9; } } else if (number == 4) { if (a) { return 7; } else { return 5; } } else if (a) { return 4; } else { return 3; } } } } return 0; } public class P implements Comparable<P> { Integer x; String s; public P(Integer x, String s) { this.x = x; this.s = s; } @Override public String toString() { return x + " " + s; } @Override public int compareTo(P o) { if (x != o.x) { return x - o.x; } return s.compareTo(o.s); } } public BigInteger prod(int l, int r) { if (l + 1 == r) { return BigInteger.valueOf(l); } int m = (l + r) >> 1; return prod(l, m).multiply(prod(m, r)); } public class Frac { BigInteger p; BigInteger q; public Frac(BigInteger p, BigInteger q) { BigInteger gcd = p.gcd(q); this.p = p.divide(gcd); this.q = q.divide(gcd); } public String toString() { return p + "\n" + q; } public Frac(long p, long q) { this(BigInteger.valueOf(p), BigInteger.valueOf(q)); } public Frac mul(Frac o) { return new Frac(p.multiply(o.p), q.multiply(o.q)); } public Frac sum(Frac o) { return new Frac(p.multiply(o.q).add(q.multiply(o.p)), q.multiply(o.q)); } public Frac diff(Frac o) { return new Frac(p.multiply(o.q).subtract(q.multiply(o.p)), q.multiply(o.q)); } } public int[] transform(int[] x, int k, int step) { int n = x.length; int[] a = new int[n]; int[][] prefsum = new int[n][]; int[] elements = new int[n]; int[] start = new int[n]; int[] id = new int[n]; for (int i = 0; i < n; i++) { if (elements[i] > 0) { continue; } int cur = i; do { elements[i]++; cur += step; cur %= n; } while (cur != i); for (int j = 0; j < elements[i]; j++) { start[cur] = i; id[cur] = j; elements[cur] = elements[i]; cur += step; cur %= n; } prefsum[i] = new int[3 * elements[i] + 1]; for (int j = 0; j < 3 * elements[i]; j++) { prefsum[i][j + 1] = prefsum[i][j] ^ x[cur]; cur += step; cur %= n; } } for (int i = 0; i < x.length; i++) { int curlen = k % (2 * elements[i]); a[i] = prefsum[start[i]][id[i] + curlen] ^ prefsum[start[i]][id[i]]; } return a; } public long edge(long i, long j, long t) { return i * j + t * (i + j); } public long prim(long[] a, long t) { long res = 0; int maxUsed = 0; int firstFree = 1; int lastFree = a.length - 1; while (firstFree <= lastFree) { long res11 = edge(a[0], a[firstFree], t); long res12 = edge(a[0], a[lastFree], t); long res21 = edge(a[maxUsed], a[firstFree], t); long res22 = edge(a[maxUsed], a[lastFree], t); if (res11 <= res12 && res11 <= res21 && res11 <= res22) { res += res11; if (firstFree > maxUsed) { maxUsed = firstFree; } firstFree++; } else if (res12 <= res21 && res12 <= res22) { res += res12; if (lastFree > maxUsed) { maxUsed = lastFree; } lastFree--; } else if (res21 <= res22) { res += res21; if (firstFree > maxUsed) { maxUsed = firstFree; } firstFree++; } else { res += res22; if (lastFree > maxUsed) { maxUsed = lastFree; } lastFree--; } } return res; } public int squares(int p) { int[] number = new int[p]; for (int i = 1; i < number.length; i++) { int x = (int) ((i * 1L * i) % p); number[x]++; if (number[p - x] > 0) { return 0; } } int dif = 0; for (int i = 0; i < number.length; i++) { if (number[i] > 0) { dif++; if (number[i] == 1) { System.out.println(p); } } } return dif; } public class Point implements Comparable<Point> { double x; double y; public Point() { x = 0; y = 0; } public Point(double x, double y) { this.x = x; this.y = y; } public Point(double angle) { x = Math.cos(angle * Math.PI / 180); y = Math.sin(angle * Math.PI / 180); } public String toString() { return x + " " + y; } public boolean equals(Point p) { return x == p.x && y == p.y; } public double dist2() { return x * x + y * y; } public Point add(Point v) { return new Point(x + v.x, y + v.y); } @Override public int compareTo(Point o) { int z = signum(x + y - o.x - o.y); if (z != 0) { return z; } return signum(x - o.x) != 0 ? signum(x - o.x) : signum(y - o.y); } } HashMap<String, Integer> map = new HashMap<>(); public void precalc(int n) { map.put("", 0); for (int len = 1; len <= n; len++) { for (int mask = 0; mask < 1 << len; mask++) { String s = ""; for (int i = 0; i < len; i++) { if (((mask >> i) & 1) > 0) { s += "1"; } else { s += "0"; } } for (int l = 0; l < len; l++) { f: for (int r = l; r < len; r++) { for (int x = l + 1; x <= r; x++) { if (s.charAt(x) == s.charAt(x - 1)) { continue f; } } String prev = s.substring(0, l) + s.substring(r + 1); if (!map.containsKey(s) || map.get(s) > map.get(prev) + 1) { map.put(s, map.get(prev) + 1); } } } } } } public void solve() { int n = in.nextInt(); int q = in.nextInt(); String s = in.next(); // long time = System.currentTimeMillis(); // int n = 10; // precalc(n); // String s = ""; // for (int i = 0; i < n; i++) { // if (random.nextBoolean()) { // s += "1"; // } else { // s += "0"; // } // } // System.err.println(System.currentTimeMillis() - time); int[] pref0 = new int[n]; int[] pref1 = new int[n]; for (int i = 1; i < s.length(); i++) { if (s.charAt(i) == s.charAt(i - 1)) { if (s.charAt(i) == '0') { pref0[i] = pref0[i - 1] + 1; pref1[i] = pref1[i - 1]; } else { pref0[i] = pref0[i - 1]; pref1[i] = pref1[i - 1] + 1; } } else { pref0[i] = pref0[i - 1]; pref1[i] = pref1[i - 1]; } } for (int i = 0; i < q; i++) { int l = in.nextInt() - 1; int r = in.nextInt() - 1; // for (int l = 0; l < n; l++) { // for (int r = l; r < n; r++) { int n0 = pref0[r] - pref0[l]; int n1 = pref1[r] - pref1[l]; // if (Math.max(n0, n1) + 1 != map.get(s.substring(l, r + 1))) { // System.out.println(s + " " + l + " " + r + " " + (Math.max(n0, n1) + 1) + " " + n0 + " " + n1 + " " + map.get(s.substring(l, r + 1))); // return; // } out.println(Math.max(n0, n1) + 1); // } } } public void add(HashMap<Integer, Integer> map, int x) { if (map.containsKey(x)) { map.put(x, map.get(x) + 1); } else { map.put(x, 1); } } public void run() { try { if (systemIO) { in = new FastScanner(System.in); out = new PrintWriter(System.out); } else { in = new FastScanner(new File("input.txt")); out = new PrintWriter(new File("output.txt")); } solve(); out.close(); } catch (IOException e) { e.printStackTrace(); } } class FastScanner { BufferedReader br; StringTokenizer st; FastScanner(File f) { try { br = new BufferedReader(new FileReader(f)); } catch (FileNotFoundException e) { e.printStackTrace(); } } FastScanner(InputStream f) { br = new BufferedReader(new InputStreamReader(f)); } String nextLine() { try { return br.readLine(); } catch (IOException e) { return null; } } 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()); } } // AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA public static void main(String[] arg) { new H().run(); } }
Java
["5 3\n11011\n2 4\n1 5\n3 5", "10 3\n1001110110\n1 10\n2 5\n5 10"]
1 second
["1\n3\n2", "4\n2\n3"]
NoteIn the first test case, The substring is $$$\texttt{101}$$$, so we can do one operation to make the substring empty. The substring is $$$\texttt{11011}$$$, so we can do one operation on $$$s[2, 4]$$$ to make $$$\texttt{11}$$$, then use two more operations to make the substring empty. The substring is $$$\texttt{011}$$$, so we can do one operation on $$$s[1, 2]$$$ to make $$$\texttt{1}$$$, then use one more operation to make the substring empty.
Java 8
standard input
[ "constructive algorithms", "data structures", "greedy" ]
d1c3b8985d0c17e0806117bef30d7ff2
The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n, q \le 2 \cdot 10 ^ 5$$$)  — the length of the binary string $$$a$$$ and the number of queries respectively. The second line contains a binary string $$$a$$$ of length $$$n$$$ ($$$a_i \in \{0, 1\}$$$). Each of the next $$$q$$$ lines contains two integers $$$l$$$ and $$$r$$$ ($$$1 \le l \le r \le n$$$)  — representing the substring of each query.
2,700
Print $$$q$$$ lines, the $$$i$$$-th line representing the minimum number of operations needed for the $$$i$$$-th query.
standard output
PASSED
697b18a2ea306b9ee9a5ab5667c7d30f
train_108.jsonl
1650722700
You have a binary string $$$a$$$ of length $$$n$$$ consisting only of digits $$$0$$$ and $$$1$$$. You are given $$$q$$$ queries. In the $$$i$$$-th query, you are given two indices $$$l$$$ and $$$r$$$ such that $$$1 \le l \le r \le n$$$. Let $$$s=a[l,r]$$$. You are allowed to do the following operation on $$$s$$$: Choose two indices $$$x$$$ and $$$y$$$ such that $$$1 \le x \le y \le |s|$$$. Let $$$t$$$ be the substring $$$t = s[x, y]$$$. Then for all $$$1 \le i \le |t| - 1$$$, the condition $$$t_i \neq t_{i+1}$$$ has to hold. Note that $$$x = y$$$ is always a valid substring. Delete the substring $$$s[x, y]$$$ from $$$s$$$. For each of the $$$q$$$ queries, find the minimum number of operations needed to make $$$s$$$ an empty string.Note that for a string $$$s$$$, $$$s[l,r]$$$ denotes the subsegment $$$s_l,s_{l+1},\ldots,s_r$$$.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Random; import java.util.StringTokenizer; /* */ public class H { public static void main(String[] args) { FastScanner fs=new FastScanner(); PrintWriter out=new PrintWriter(System.out); int n=fs.nextInt(); int nQ=fs.nextInt(); char[] line=fs.next().toCharArray(); BIT zeroBlocks=new BIT(n-1); BIT oneBlocks=new BIT(n-1); for (int i=0; i+1<n; i++) { if (line[i]==line[i+1]) { if (line[i]=='0') { zeroBlocks.update(i, 1); } else { oneBlocks.update(i, 1); } } } for (int qq=0; qq<nQ; qq++) { int l=fs.nextInt()-1, r=fs.nextInt()-1; int zeros=zeroBlocks.query(l, r-1); int ones=oneBlocks.query(l, r-1); int ans=1+Math.max(zeros, ones); out.println(ans); } out.close(); } static class BIT { int n, tree[]; public BIT(int N) { n = N; tree = new int[N + 1]; } void update(int i, int val) { for (i++; i <= n; i += i & -i) tree[i] += val; } int read(int i) { int sum = 0; for (i++; i > 0; i -= i & -i) sum += tree[i]; return sum; } // query sum of [l, r] inclusive int query(int l, int r) { return read(r) - read(l - 1); } // if the BIT is a freq array, returns the index of the // kth item (0-indexed), or n if there are <= k items. int getKth(int k) { if (k < 0) return -1; int i = 0; for (int pw = Integer.highestOneBit(n); pw > 0; pw >>= 1) if (i + pw <= n && tree[i + pw] <= k) k -= tree[i += pw]; return i; } } static final Random random=new Random(); static final int mod=1_000_000_007; static void ruffleSort(int[] a) { int n=a.length;//shuffle, then sort for (int i=0; i<n; i++) { int oi=random.nextInt(n), temp=a[oi]; a[oi]=a[i]; a[i]=temp; } Arrays.sort(a); } static long add(long a, long b) { return (a+b)%mod; } static long sub(long a, long b) { return ((a-b)%mod+mod)%mod; } static long mul(long a, long b) { return (a*b)%mod; } static long exp(long base, long exp) { if (exp==0) return 1; long half=exp(base, exp/2); if (exp%2==0) return mul(half, half); return mul(half, mul(half, base)); } static long[] factorials=new long[2_000_001]; static long[] invFactorials=new long[2_000_001]; static void precompFacts() { factorials[0]=invFactorials[0]=1; for (int i=1; i<factorials.length; i++) factorials[i]=mul(factorials[i-1], i); invFactorials[factorials.length-1]=exp(factorials[factorials.length-1], mod-2); for (int i=invFactorials.length-2; i>=0; i--) invFactorials[i]=mul(invFactorials[i+1], i+1); } static long nCk(int n, int k) { return mul(factorials[n], mul(invFactorials[k], invFactorials[n-k])); } static void sort(int[] a) { ArrayList<Integer> l=new ArrayList<>(); for (int i:a) l.add(i); Collections.sort(l); for (int i=0; i<a.length; i++) a[i]=l.get(i); } static 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
["5 3\n11011\n2 4\n1 5\n3 5", "10 3\n1001110110\n1 10\n2 5\n5 10"]
1 second
["1\n3\n2", "4\n2\n3"]
NoteIn the first test case, The substring is $$$\texttt{101}$$$, so we can do one operation to make the substring empty. The substring is $$$\texttt{11011}$$$, so we can do one operation on $$$s[2, 4]$$$ to make $$$\texttt{11}$$$, then use two more operations to make the substring empty. The substring is $$$\texttt{011}$$$, so we can do one operation on $$$s[1, 2]$$$ to make $$$\texttt{1}$$$, then use one more operation to make the substring empty.
Java 8
standard input
[ "constructive algorithms", "data structures", "greedy" ]
d1c3b8985d0c17e0806117bef30d7ff2
The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n, q \le 2 \cdot 10 ^ 5$$$)  — the length of the binary string $$$a$$$ and the number of queries respectively. The second line contains a binary string $$$a$$$ of length $$$n$$$ ($$$a_i \in \{0, 1\}$$$). Each of the next $$$q$$$ lines contains two integers $$$l$$$ and $$$r$$$ ($$$1 \le l \le r \le n$$$)  — representing the substring of each query.
2,700
Print $$$q$$$ lines, the $$$i$$$-th line representing the minimum number of operations needed for the $$$i$$$-th query.
standard output
PASSED
9a593097a6936cdce96cfeac90fe32a9
train_108.jsonl
1650722700
oolimry has an array $$$a$$$ of length $$$n$$$ which he really likes. Today, you have changed his array to $$$b$$$, a permutation of $$$a$$$, to make him sad.Because oolimry is only a duck, he can only perform the following operation to restore his array: Choose two integers $$$i,j$$$ such that $$$1 \leq i,j \leq n$$$. Swap $$$b_i$$$ and $$$b_j$$$. The sadness of the array $$$b$$$ is the minimum number of operations needed to transform $$$b$$$ into $$$a$$$.Given the array $$$a$$$, find any array $$$b$$$ which is a permutation of $$$a$$$ that has the maximum sadness over all permutations of the array $$$a$$$.
256 megabytes
import javax.swing.*; import java.lang.reflect.Array; import java.text.DecimalFormat; import java.util.*; import java.lang.*; import java.io.*; import java.math.*; import java.util.stream.Stream; // Please name your class Main public class Main { static FastScanner fs=new FastScanner(); 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 Int() { return Integer.parseInt(next()); } long Long() { return Long.parseLong(next()); } String Str(){ return next(); } } public static void main (String[] args) throws java.lang.Exception { PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); //reading /writing file //Scanner in=new Scanner(System.in); //Scanner in=new Scanner(new File("input.txt")); //PrintWriter pr=new PrintWriter("output.txt") int T=Int(); for(int t=0;t<T;t++){ Solution sol1=new Solution(out,fs); sol1.solution(T,t); } out.flush(); } public static int[] Arr(int n){ int A[]=new int[n]; for(int i=0;i<n;i++)A[i]=Int(); return A; } public static int Int(){ return fs.Int(); } public static long Long(){ return fs.Long(); } public static String Str(){ return fs.Str(); } } class Solution { PrintWriter out; int INF = Integer.MAX_VALUE; int NINF = Integer.MIN_VALUE; int MOD = 998244353; int mod = 998244353; Main.FastScanner fs; public Solution(PrintWriter out, Main.FastScanner fs) { this.out = out; this.fs = fs; } public void add(Map<Integer, Integer> f, int key) { Integer cnt = f.get(key); if(cnt == null) { f.put(key, 1); } else { f.put(key, cnt + 1); } } public void del(Map<Integer, Integer> f, int key) { Integer cnt = f.get(key); if(cnt == 1) { f.remove(key); } else { f.put(key, cnt - 1); } } public void msg(String s) { System.out.println(s); } public void solution(int all, int testcase) { int n = fs.Int(); //sadness : minimum operation b -> a //given a int a[] = new int[n]; int b[] = new int[n]; Map<Integer, Queue<Integer>> f = new HashMap<>(); for(int i = 0; i < n; i++) { a[i] = fs.Int(); if(!f.containsKey(a[i])) { f.put(a[i], new LinkedList<>()); } f.get(a[i]).add(i); } PriorityQueue<Queue<Integer>> pq = new PriorityQueue<>((x,y) -> { return y.size() - x.size(); }); for(Integer k:f.keySet())pq.add(f.get(k)); while(pq.size() > 0) { int size = pq.size(); List<Integer> list = new ArrayList<>(); List<Queue<Integer>> llist = new ArrayList<>(); for(int i = 0; i < size; i++) { Queue<Integer> q = pq.poll(); int index = q.poll(); if(q.size() > 0) llist.add(q); list.add(index); } Collections.sort(list,(x, y)->{ return a[x] - a[y]; }); for(Queue<Integer> q : llist) pq.add(q); // System.out.println(pq); for(int i = 0; i < list.size(); i++) { int cur = list.get(i); int val = a[cur]; int nxt = list.get((i + 1) % list.size()); b[nxt] = val; } } print(b); } public void print(int a[]) { StringBuilder str = new StringBuilder(); for(int i : a) str.append(i).append(" "); out.println(str.toString()); } }
Java
["2\n\n2\n\n2 1\n\n4\n\n1 2 3 3"]
1 second
["1 2\n3 3 2 1"]
NoteIn the first test case, the array $$$[1,2]$$$ has sadness $$$1$$$. We can transform $$$[1,2]$$$ into $$$[2,1]$$$ using one operation with $$$(i,j)=(1,2)$$$.In the second test case, the array $$$[3,3,2,1]$$$ has sadness $$$2$$$. We can transform $$$[3,3,2,1]$$$ into $$$[1,2,3,3]$$$ with two operations with $$$(i,j)=(1,4)$$$ and $$$(i,j)=(2,3)$$$ respectively.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy" ]
01703877719e19dd8551e4599c3e1c85
Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$)  — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$)  — the length of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$)  — elements of the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
2,000
For each test case, print $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ — describing the array $$$b$$$. If there are multiple answers, you may print any.
standard output
PASSED
76adefde61139091c018e011dc215c9e
train_108.jsonl
1650722700
oolimry has an array $$$a$$$ of length $$$n$$$ which he really likes. Today, you have changed his array to $$$b$$$, a permutation of $$$a$$$, to make him sad.Because oolimry is only a duck, he can only perform the following operation to restore his array: Choose two integers $$$i,j$$$ such that $$$1 \leq i,j \leq n$$$. Swap $$$b_i$$$ and $$$b_j$$$. The sadness of the array $$$b$$$ is the minimum number of operations needed to transform $$$b$$$ into $$$a$$$.Given the array $$$a$$$, find any array $$$b$$$ which is a permutation of $$$a$$$ that has the maximum sadness over all permutations of the array $$$a$$$.
256 megabytes
import java.io.*; import java.util.*; public class ArrayShuffling { private static final int START_TEST_CASE = 1; public static void solveCase(FastIO io, int testCase) { final int N = io.nextInt(); final int[] A = io.nextIntArray(N); IntQueue[] queues = new IntQueue[N + 1]; for (int i = 0; i <= N; ++i) { queues[i] = new IntQueue(); } for (int i = 0; i < N; ++i) { queues[A[i]].offer(i); } BucketSort.sortReversed(queues, new BucketSort.IntConverter<IntQueue>() { @Override public int toInt(IntQueue item) { return item.size(); } }); // Arrays.sort(queues, Collections.reverseOrder(new Comparator<IntQueue>() { // @Override // public int compare(IntQueue a, IntQueue b) { // return Integer.compare(a.size(), b.size()); // } // })); int[] ans = new int[N]; while (!queues[0].isEmpty()) { ArrayList<Integer> idxs = new ArrayList<>(); for (IntQueue q : queues) { if (q.isEmpty()) { break; } idxs.add(q.poll()); } for (int i = 0; i < idxs.size(); ++i) { int j = i + 1; if (j >= idxs.size()) { j -= idxs.size(); } int x = idxs.get(i); int y = idxs.get(j); ans[y] = A[x]; } } io.printlnArray(ans); } private static class BucketSort { private static <T> T[] sortReversed(T[] items, IntConverter<T> converter) { sort(items, converter); for (int i = 0, j = items.length - 1; i < j; ++i, --j) { T tmp = items[i]; items[i] = items[j]; items[j] = tmp; } return items; } private static <T> T[] sort(T[] items, IntConverter<T> converter) { final int N = items.length; int[] values = new int[N]; int minVal = Integer.MAX_VALUE; int maxVal = Integer.MIN_VALUE; for (int i = 0; i < items.length; ++i) { values[i] = converter.toInt(items[i]); minVal = Math.min(minVal, values[i]); maxVal = Math.max(maxVal, values[i]); } int capacity = maxVal - minVal + 1; ArrayList<ArrayList<T>> buckets = new ArrayList<>(capacity); for (int i = 0; i < capacity; ++i) { buckets.add(null); } for (int i = 0; i < items.length; ++i) { int bucketIndex = values[i] - minVal; ArrayList<T> lst = buckets.get(bucketIndex); if (lst == null) { lst = new ArrayList<>(); buckets.set(bucketIndex, lst); } lst.add(items[i]); } int p = 0; for (ArrayList<T> lst : buckets) { if (lst == null) { continue; } for (T item : lst) { items[p++] = item; } } return items; } public static interface IntConverter<T> { public int toInt(T item); } } private static class IntQueue extends ArrayDeque<Integer> { private static final long serialVersionUID = -8362259169868340852L; } public static void solve(FastIO io) { final int T = io.nextInt(); for (int t = 0; t < T; ++t) { solveCase(io, START_TEST_CASE + t); } } public static class FastIO { private InputStream reader; private PrintWriter writer; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public FastIO(InputStream r, OutputStream w) { reader = r; writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(w))); } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = reader.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public String nextString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } // TODO: read this byte-by-byte like the other read functions. public double nextDouble() { return Double.parseDouble(nextString()); } public int[] nextIntArray(int n) { return nextIntArray(n, 0); } public int[] nextIntArray(int n, int off) { int[] arr = new int[n + off]; for (int i = 0; i < n; i++) { arr[i + off] = nextInt(); } return arr; } public long[] nextLongArray(int n) { return nextLongArray(n, 0); } public long[] nextLongArray(int n, int off) { long[] arr = new long[n + off]; for (int i = 0; i < n; i++) { arr[i + off] = nextLong(); } return arr; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) { writer.print(' '); } writer.print(objects[i]); } } public void println(Object... objects) { print(objects); writer.println(); } public void printArray(int[] arr) { for (int i = 0; i < arr.length; i++) { if (i != 0) { writer.print(' '); } writer.print(arr[i]); } } public void printArray(long[] arr) { for (int i = 0; i < arr.length; i++) { if (i != 0) { writer.print(' '); } writer.print(arr[i]); } } public void printlnArray(int[] arr) { printArray(arr); writer.println(); } public void printlnArray(long[] arr) { printArray(arr); writer.println(); } public void printf(String format, Object... args) { print(String.format(format, args)); } public void flush() { writer.flush(); } } public static void main(String[] args) { FastIO io = new FastIO(System.in, System.out); solve(io); io.flush(); } }
Java
["2\n\n2\n\n2 1\n\n4\n\n1 2 3 3"]
1 second
["1 2\n3 3 2 1"]
NoteIn the first test case, the array $$$[1,2]$$$ has sadness $$$1$$$. We can transform $$$[1,2]$$$ into $$$[2,1]$$$ using one operation with $$$(i,j)=(1,2)$$$.In the second test case, the array $$$[3,3,2,1]$$$ has sadness $$$2$$$. We can transform $$$[3,3,2,1]$$$ into $$$[1,2,3,3]$$$ with two operations with $$$(i,j)=(1,4)$$$ and $$$(i,j)=(2,3)$$$ respectively.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy" ]
01703877719e19dd8551e4599c3e1c85
Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$)  — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$)  — the length of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$)  — elements of the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
2,000
For each test case, print $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ — describing the array $$$b$$$. If there are multiple answers, you may print any.
standard output
PASSED
051cdb8efef508662ab185424e1a9b92
train_108.jsonl
1650722700
oolimry has an array $$$a$$$ of length $$$n$$$ which he really likes. Today, you have changed his array to $$$b$$$, a permutation of $$$a$$$, to make him sad.Because oolimry is only a duck, he can only perform the following operation to restore his array: Choose two integers $$$i,j$$$ such that $$$1 \leq i,j \leq n$$$. Swap $$$b_i$$$ and $$$b_j$$$. The sadness of the array $$$b$$$ is the minimum number of operations needed to transform $$$b$$$ into $$$a$$$.Given the array $$$a$$$, find any array $$$b$$$ which is a permutation of $$$a$$$ that has the maximum sadness over all permutations of the array $$$a$$$.
256 megabytes
import java.io.*; import java.util.*; public class ArrayShuffling { private static final int START_TEST_CASE = 1; public static void solveCase(FastIO io, int testCase) { final int N = io.nextInt(); final int[] A = io.nextIntArray(N); IntQueue[] queues = new IntQueue[N + 1]; for (int i = 0; i <= N; ++i) { queues[i] = new IntQueue(); } for (int i = 0; i < N; ++i) { queues[A[i]].offer(i); } Arrays.sort(queues, Collections.reverseOrder(new Comparator<IntQueue>() { @Override public int compare(IntQueue a, IntQueue b) { return Integer.compare(a.size(), b.size()); } })); int[] ans = new int[N]; while (!queues[0].isEmpty()) { ArrayList<Integer> idxs = new ArrayList<>(); for (IntQueue q : queues) { if (q.isEmpty()) { break; } idxs.add(q.poll()); } for (int i = 0; i < idxs.size(); ++i) { int j = i + 1; if (j >= idxs.size()) { j -= idxs.size(); } int x = idxs.get(i); int y = idxs.get(j); ans[y] = A[x]; } } io.printlnArray(ans); } private static class BucketSort { private static <T> T[] sort(T[] items, IntConverter<T> converter) { final int N = items.length; int[] values = new int[N]; int minVal = Integer.MAX_VALUE; int maxVal = Integer.MIN_VALUE; for (int i = 0; i < items.length; ++i) { values[i] = converter.toInt(items[i]); minVal = Math.min(minVal, values[i]); maxVal = Math.max(maxVal, values[i]); } int capacity = maxVal - minVal + 1; ArrayList<ArrayList<T>> buckets = new ArrayList<>(capacity); for (int i = 0; i < capacity; ++i) { buckets.add(null); } for (int i = 0; i < items.length; ++i) { int bucketIndex = values[i] - minVal; ArrayList<T> lst = buckets.get(bucketIndex); if (lst == null) { lst = new ArrayList<>(); buckets.set(bucketIndex, lst); } lst.add(items[i]); } int p = 0; for (ArrayList<T> lst : buckets) { if (lst == null) { continue; } for (T item : lst) { items[p++] = item; } } return items; } public static interface IntConverter<T> { public int toInt(T item); } } private static class IntQueue extends ArrayDeque<Integer> { private static final long serialVersionUID = -8362259169868340852L; } public static void solve(FastIO io) { final int T = io.nextInt(); for (int t = 0; t < T; ++t) { solveCase(io, START_TEST_CASE + t); } } public static class FastIO { private InputStream reader; private PrintWriter writer; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public FastIO(InputStream r, OutputStream w) { reader = r; writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(w))); } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = reader.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public String nextString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } // TODO: read this byte-by-byte like the other read functions. public double nextDouble() { return Double.parseDouble(nextString()); } public int[] nextIntArray(int n) { return nextIntArray(n, 0); } public int[] nextIntArray(int n, int off) { int[] arr = new int[n + off]; for (int i = 0; i < n; i++) { arr[i + off] = nextInt(); } return arr; } public long[] nextLongArray(int n) { return nextLongArray(n, 0); } public long[] nextLongArray(int n, int off) { long[] arr = new long[n + off]; for (int i = 0; i < n; i++) { arr[i + off] = nextLong(); } return arr; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) { writer.print(' '); } writer.print(objects[i]); } } public void println(Object... objects) { print(objects); writer.println(); } public void printArray(int[] arr) { for (int i = 0; i < arr.length; i++) { if (i != 0) { writer.print(' '); } writer.print(arr[i]); } } public void printArray(long[] arr) { for (int i = 0; i < arr.length; i++) { if (i != 0) { writer.print(' '); } writer.print(arr[i]); } } public void printlnArray(int[] arr) { printArray(arr); writer.println(); } public void printlnArray(long[] arr) { printArray(arr); writer.println(); } public void printf(String format, Object... args) { print(String.format(format, args)); } public void flush() { writer.flush(); } } public static void main(String[] args) { FastIO io = new FastIO(System.in, System.out); solve(io); io.flush(); } }
Java
["2\n\n2\n\n2 1\n\n4\n\n1 2 3 3"]
1 second
["1 2\n3 3 2 1"]
NoteIn the first test case, the array $$$[1,2]$$$ has sadness $$$1$$$. We can transform $$$[1,2]$$$ into $$$[2,1]$$$ using one operation with $$$(i,j)=(1,2)$$$.In the second test case, the array $$$[3,3,2,1]$$$ has sadness $$$2$$$. We can transform $$$[3,3,2,1]$$$ into $$$[1,2,3,3]$$$ with two operations with $$$(i,j)=(1,4)$$$ and $$$(i,j)=(2,3)$$$ respectively.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy" ]
01703877719e19dd8551e4599c3e1c85
Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$)  — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$)  — the length of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$)  — elements of the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
2,000
For each test case, print $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ — describing the array $$$b$$$. If there are multiple answers, you may print any.
standard output
PASSED
558b06d439dc3df26fc2ea5a61135b4a
train_108.jsonl
1650722700
oolimry has an array $$$a$$$ of length $$$n$$$ which he really likes. Today, you have changed his array to $$$b$$$, a permutation of $$$a$$$, to make him sad.Because oolimry is only a duck, he can only perform the following operation to restore his array: Choose two integers $$$i,j$$$ such that $$$1 \leq i,j \leq n$$$. Swap $$$b_i$$$ and $$$b_j$$$. The sadness of the array $$$b$$$ is the minimum number of operations needed to transform $$$b$$$ into $$$a$$$.Given the array $$$a$$$, find any array $$$b$$$ which is a permutation of $$$a$$$ that has the maximum sadness over all permutations of the array $$$a$$$.
256 megabytes
import java.io.*; import java.util.*; public class ArrayShuffling { private static final int START_TEST_CASE = 1; public static void solveCase(FastIO io, int testCase) { final int N = io.nextInt(); final int[] A = io.nextIntArray(N); IntQueue[] queues = new IntQueue[N + 1]; for (int i = 0; i <= N; ++i) { queues[i] = new IntQueue(); } for (int i = 0; i < N; ++i) { queues[A[i]].offer(i); } Arrays.parallelSort(queues, Collections.reverseOrder(new Comparator<IntQueue>() { @Override public int compare(IntQueue a, IntQueue b) { return Integer.compare(a.size(), b.size()); } })); int[] ans = new int[N]; while (!queues[0].isEmpty()) { ArrayList<Integer> idxs = new ArrayList<>(); for (IntQueue q : queues) { if (q.isEmpty()) { break; } idxs.add(q.poll()); } for (int i = 0; i < idxs.size(); ++i) { int j = i + 1; if (j >= idxs.size()) { j -= idxs.size(); } int x = idxs.get(i); int y = idxs.get(j); ans[y] = A[x]; } } io.printlnArray(ans); } private static class IntQueue extends ArrayDeque<Integer> { private static final long serialVersionUID = -8362259169868340852L; } public static void solve(FastIO io) { final int T = io.nextInt(); for (int t = 0; t < T; ++t) { solveCase(io, START_TEST_CASE + t); } } public static class FastIO { private InputStream reader; private PrintWriter writer; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public FastIO(InputStream r, OutputStream w) { reader = r; writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(w))); } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = reader.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public String nextString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } // TODO: read this byte-by-byte like the other read functions. public double nextDouble() { return Double.parseDouble(nextString()); } public int[] nextIntArray(int n) { return nextIntArray(n, 0); } public int[] nextIntArray(int n, int off) { int[] arr = new int[n + off]; for (int i = 0; i < n; i++) { arr[i + off] = nextInt(); } return arr; } public long[] nextLongArray(int n) { return nextLongArray(n, 0); } public long[] nextLongArray(int n, int off) { long[] arr = new long[n + off]; for (int i = 0; i < n; i++) { arr[i + off] = nextLong(); } return arr; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) { writer.print(' '); } writer.print(objects[i]); } } public void println(Object... objects) { print(objects); writer.println(); } public void printArray(int[] arr) { for (int i = 0; i < arr.length; i++) { if (i != 0) { writer.print(' '); } writer.print(arr[i]); } } public void printArray(long[] arr) { for (int i = 0; i < arr.length; i++) { if (i != 0) { writer.print(' '); } writer.print(arr[i]); } } public void printlnArray(int[] arr) { printArray(arr); writer.println(); } public void printlnArray(long[] arr) { printArray(arr); writer.println(); } public void printf(String format, Object... args) { print(String.format(format, args)); } public void flush() { writer.flush(); } } public static void main(String[] args) { FastIO io = new FastIO(System.in, System.out); solve(io); io.flush(); } }
Java
["2\n\n2\n\n2 1\n\n4\n\n1 2 3 3"]
1 second
["1 2\n3 3 2 1"]
NoteIn the first test case, the array $$$[1,2]$$$ has sadness $$$1$$$. We can transform $$$[1,2]$$$ into $$$[2,1]$$$ using one operation with $$$(i,j)=(1,2)$$$.In the second test case, the array $$$[3,3,2,1]$$$ has sadness $$$2$$$. We can transform $$$[3,3,2,1]$$$ into $$$[1,2,3,3]$$$ with two operations with $$$(i,j)=(1,4)$$$ and $$$(i,j)=(2,3)$$$ respectively.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy" ]
01703877719e19dd8551e4599c3e1c85
Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$)  — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$)  — the length of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$)  — elements of the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
2,000
For each test case, print $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ — describing the array $$$b$$$. If there are multiple answers, you may print any.
standard output
PASSED
ba8b6b1e6cd9d89e2977a1d8cb72bd4c
train_108.jsonl
1650722700
oolimry has an array $$$a$$$ of length $$$n$$$ which he really likes. Today, you have changed his array to $$$b$$$, a permutation of $$$a$$$, to make him sad.Because oolimry is only a duck, he can only perform the following operation to restore his array: Choose two integers $$$i,j$$$ such that $$$1 \leq i,j \leq n$$$. Swap $$$b_i$$$ and $$$b_j$$$. The sadness of the array $$$b$$$ is the minimum number of operations needed to transform $$$b$$$ into $$$a$$$.Given the array $$$a$$$, find any array $$$b$$$ which is a permutation of $$$a$$$ that has the maximum sadness over all permutations of the array $$$a$$$.
256 megabytes
import java.io.*; import java.math.*; import java.util.*; public class ArrayShuffling { private static final int START_TEST_CASE = 1; public static void solveCase(FastIO io, int testCase) { final int N = io.nextInt(); final int[] A = io.nextIntArray(N); // int[] freq = new int[N + 1]; // for (int x : A) { // ++freq[x]; // } // // ArrayList<FreqNum> freqs = new ArrayList<>(); // for (int i = 1; i <= N; ++i) { // if (freq[i] > 0) { // freqs.add(new FreqNum(i, freq[i])); // } // } // Collections.sort(freqs, Collections.reverseOrder(new Comparator<FreqNum>() { // @Override // public int compare(FreqNum a, FreqNum b) { // return Integer.compare(a.count, b.count); // } // })); // // if (freqs.size() == 1) { // io.printlnArray(A); // return; // } // // int largestFreq = freqs.get(0).count; // if (freqs.get(0).count < N) { // io.printlnArray(applyOffset(A, largestFreq)); // return; // } IntQueue[] queues = new IntQueue[N + 1]; for (int i = 0; i <= N; ++i) { queues[i] = new IntQueue(); } for (int i = 0; i < N; ++i) { queues[A[i]].offer(i); } Arrays.parallelSort(queues, Collections.reverseOrder(new Comparator<IntQueue>() { @Override public int compare(IntQueue a, IntQueue b) { return Integer.compare(a.size(), b.size()); } })); int[] ans = new int[N]; while (!queues[0].isEmpty()) { ArrayList<Integer> idxs = new ArrayList<>(); for (IntQueue q : queues) { if (q.isEmpty()) { break; } idxs.add(q.poll()); } // System.out.println(idxs); for (int i = 0; i < idxs.size(); ++i) { int j = i + 1; if (j >= idxs.size()) { j -= idxs.size(); } int x = idxs.get(i); int y = idxs.get(j); ans[y] = A[x]; } } io.printlnArray(ans); } private static class IntQueue extends ArrayDeque<Integer> { } private static int[] applyOffset(int[] A, int offset) { final int N = A.length; IndexNum[] vals = new IndexNum[N]; for (int i = 0; i < N; ++i) { vals[i] = new IndexNum(i, A[i]); } Arrays.parallelSort(vals, new Comparator<IndexNum>() { @Override public int compare(IndexNum a, IndexNum b) { return Integer.compare(a.value, b.value); } }); int[] ans = new int[N]; for (int i = 0; i < N; ++i) { int j = i + offset; if (j >= N) { j -= N; } ans[vals[j].index] = vals[i].value; } return ans; } private static class FreqNum { public int value; public int count; public FreqNum(int value, int count) { this.value = value; this.count = count; } } private static class IndexNum { public int index; public int value; public IndexNum(int index, int value) { this.index = index; this.value = value; } } public static void solve(FastIO io) { final int T = io.nextInt(); for (int t = 0; t < T; ++t) { solveCase(io, START_TEST_CASE + t); } } public static class FastIO { private InputStream reader; private PrintWriter writer; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public FastIO(InputStream r, OutputStream w) { reader = r; writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(w))); } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = reader.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public String nextString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } // TODO: read this byte-by-byte like the other read functions. public double nextDouble() { return Double.parseDouble(nextString()); } public int[] nextIntArray(int n) { return nextIntArray(n, 0); } public int[] nextIntArray(int n, int off) { int[] arr = new int[n + off]; for (int i = 0; i < n; i++) { arr[i + off] = nextInt(); } return arr; } public long[] nextLongArray(int n) { return nextLongArray(n, 0); } public long[] nextLongArray(int n, int off) { long[] arr = new long[n + off]; for (int i = 0; i < n; i++) { arr[i + off] = nextLong(); } return arr; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) { writer.print(' '); } writer.print(objects[i]); } } public void println(Object... objects) { print(objects); writer.println(); } public void printArray(int[] arr) { for (int i = 0; i < arr.length; i++) { if (i != 0) { writer.print(' '); } writer.print(arr[i]); } } public void printArray(long[] arr) { for (int i = 0; i < arr.length; i++) { if (i != 0) { writer.print(' '); } writer.print(arr[i]); } } public void printlnArray(int[] arr) { printArray(arr); writer.println(); } public void printlnArray(long[] arr) { printArray(arr); writer.println(); } public void printf(String format, Object... args) { print(String.format(format, args)); } public void flush() { writer.flush(); } } public static void main(String[] args) { FastIO io = new FastIO(System.in, System.out); solve(io); io.flush(); } }
Java
["2\n\n2\n\n2 1\n\n4\n\n1 2 3 3"]
1 second
["1 2\n3 3 2 1"]
NoteIn the first test case, the array $$$[1,2]$$$ has sadness $$$1$$$. We can transform $$$[1,2]$$$ into $$$[2,1]$$$ using one operation with $$$(i,j)=(1,2)$$$.In the second test case, the array $$$[3,3,2,1]$$$ has sadness $$$2$$$. We can transform $$$[3,3,2,1]$$$ into $$$[1,2,3,3]$$$ with two operations with $$$(i,j)=(1,4)$$$ and $$$(i,j)=(2,3)$$$ respectively.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy" ]
01703877719e19dd8551e4599c3e1c85
Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$)  — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$)  — the length of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$)  — elements of the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
2,000
For each test case, print $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ — describing the array $$$b$$$. If there are multiple answers, you may print any.
standard output
PASSED
8f0a50e7fe70f702807a15babd882b0a
train_108.jsonl
1650722700
oolimry has an array $$$a$$$ of length $$$n$$$ which he really likes. Today, you have changed his array to $$$b$$$, a permutation of $$$a$$$, to make him sad.Because oolimry is only a duck, he can only perform the following operation to restore his array: Choose two integers $$$i,j$$$ such that $$$1 \leq i,j \leq n$$$. Swap $$$b_i$$$ and $$$b_j$$$. The sadness of the array $$$b$$$ is the minimum number of operations needed to transform $$$b$$$ into $$$a$$$.Given the array $$$a$$$, find any array $$$b$$$ which is a permutation of $$$a$$$ that has the maximum sadness over all permutations of the array $$$a$$$.
256 megabytes
/* I am dead inside Do you like NCT, sKz, BTS? 5 4 3 2 1 Moonwalk Imma knock it down like domino Is this what you want? Is this what you want? Let's ttalkbocky about that */ import static java.lang.Math.*; import java.util.*; import java.io.*; public class ArrayShuffling { public static void main(String omkar[]) throws Exception { BufferedReader infile = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(infile.readLine()); int T = Integer.parseInt(st.nextToken()); StringBuilder sb = new StringBuilder(); while(T-->0) { st = new StringTokenizer(infile.readLine()); int N = Integer.parseInt(st.nextToken()); int[] arr = readArr(N, infile, st); ArrayDeque<Integer>[] locs = new ArrayDeque[N+1]; for(int i=1; i <= N; i++) locs[i] = new ArrayDeque<Integer>(); for(int i=0; i < N; i++) locs[arr[i]].add(i); ArrayList<Integer> ids = new ArrayList<Integer>(); int[] size = new int[N+1]; for(int v=1; v <= N; v++) if(locs[v].size() > 0) { size[v] = locs[v].size(); ids.add(v); } Collections.sort(ids, (x, y) -> { return locs[y].size()-locs[x].size(); }); if(ids.size() == 1) { for(int x: arr) sb.append(x+" "); sb.append("\n"); continue; } int[] res = new int[N]; int curr = 1; int destination = 0; while(destination < ids.size()) { int c = ids.get(curr); int d = ids.get(destination); while(size[c] > 0 && locs[d].size() > 0) { res[locs[d].poll()] = c; size[c]--; } if(locs[d].size() == 0) destination++; if(size[c] == 0) { curr++; if(curr == ids.size()) curr = 0; } } for(int x: res) sb.append(x+" "); sb.append("\n"); } System.out.print(sb); } public static int[] readArr(int N, BufferedReader infile, StringTokenizer st) throws Exception { int[] arr = new int[N]; st = new StringTokenizer(infile.readLine()); for(int i=0; i < N; i++) arr[i] = Integer.parseInt(st.nextToken()); return arr; } }
Java
["2\n\n2\n\n2 1\n\n4\n\n1 2 3 3"]
1 second
["1 2\n3 3 2 1"]
NoteIn the first test case, the array $$$[1,2]$$$ has sadness $$$1$$$. We can transform $$$[1,2]$$$ into $$$[2,1]$$$ using one operation with $$$(i,j)=(1,2)$$$.In the second test case, the array $$$[3,3,2,1]$$$ has sadness $$$2$$$. We can transform $$$[3,3,2,1]$$$ into $$$[1,2,3,3]$$$ with two operations with $$$(i,j)=(1,4)$$$ and $$$(i,j)=(2,3)$$$ respectively.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy" ]
01703877719e19dd8551e4599c3e1c85
Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$)  — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$)  — the length of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$)  — elements of the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
2,000
For each test case, print $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ — describing the array $$$b$$$. If there are multiple answers, you may print any.
standard output
PASSED
6d64f65f31449c000829643627db2a27
train_108.jsonl
1650722700
oolimry has an array $$$a$$$ of length $$$n$$$ which he really likes. Today, you have changed his array to $$$b$$$, a permutation of $$$a$$$, to make him sad.Because oolimry is only a duck, he can only perform the following operation to restore his array: Choose two integers $$$i,j$$$ such that $$$1 \leq i,j \leq n$$$. Swap $$$b_i$$$ and $$$b_j$$$. The sadness of the array $$$b$$$ is the minimum number of operations needed to transform $$$b$$$ into $$$a$$$.Given the array $$$a$$$, find any array $$$b$$$ which is a permutation of $$$a$$$ that has the maximum sadness over all permutations of the array $$$a$$$.
256 megabytes
import java.io.*; import java.util.*; public class Main { //--------------------------INPUT READER---------------------------------// static class fs { public BufferedReader br; StringTokenizer st = new StringTokenizer(""); public fs() { this(System.in); } public fs(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); } String next() { while (!st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int ni() { return Integer.parseInt(next()); } long nl() { return Long.parseLong(next()); } double nd() { return Double.parseDouble(next()); } String ns() { return next(); } int[] na(long nn) { int n = (int) nn; int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = ni(); return a; } long[] nal(long nn) { int n = (int) nn; long[] l = new long[n]; for(int i = 0; i < n; i++) l[i] = nl(); return l; } } //-----------------------------------------------------------------------// //---------------------------PRINTER-------------------------------------// static class Printer { static PrintWriter w; public Printer() {this(System.out);} public Printer(OutputStream os) { w = new PrintWriter(os); } public void p(int i) {w.println(i);} public void p(long l) {w.println(l);} public void p(double d) {w.println(d);} public void p(String s) { w.println(s);} public void pr(int i) {w.print(i);} public void pr(long l) {w.print(l);} public void pr(double d) {w.print(d);} public void pr(String s) { w.print(s);} public void pl() {w.println();} public void close() {w.close();} } //-----------------------------------------------------------------------// //--------------------------VARIABLES------------------------------------// static fs sc = new fs(); static OutputStream outputStream = System.out; static Printer w = new Printer(outputStream); static long lma = Long.MAX_VALUE, lmi = Long.MIN_VALUE; static int ima = Integer.MAX_VALUE, imi = Integer.MIN_VALUE; static long mod = 1000000007; //-----------------------------------------------------------------------// //--------------------------ADMIN_MODE-----------------------------------// private static void ADMIN_MODE() throws IOException { if (System.getProperty("ONLINE_JUDGE") == null) { w = new Printer(new FileOutputStream("output.txt")); sc = new fs(new FileInputStream("input.txt")); } } //-----------------------------------------------------------------------// //----------------------------START--------------------------------------// public static void main(String[] args) throws IOException { ADMIN_MODE(); int t = sc.ni();while(t-->0) solve(); w.close(); } static void solve() throws IOException { int n = sc.ni(); int[] arr = sc.na(n); HashMap<Integer, HashSet<Integer>> posMap = new HashMap<>(); for(int i = 0; i < n; i++) { int curr = arr[i]; HashSet<Integer> pos = posMap.getOrDefault(curr, new HashSet<>()); pos.add(i); posMap.put(curr, pos); } List<Integer> li = new ArrayList<>(posMap.keySet()); li.sort((a, b)-> Integer.compare(posMap.get(a).size(), posMap.get(b).size())); List<Integer> pos = new ArrayList<>(); for(int i = li.size()-1; i >= 0; i--) { int currElem = li.get(i); pos.addAll(posMap.get(currElem)); } int pt = 0; int[] res = new int[n]; for(int i = li.size()-2; i >= 0; i--) { int curr = li.get(i); int freq = posMap.get(curr).size(); for(int j = 0; j < freq; j++) { res[pos.get(pt)] = curr; pt++; } } for(int i = 0; i < n; i++) { if(res[i] == 0) res[i] = li.get(li.size()-1); } for(int i: res) w.pr(i+" "); w.pl(); } static class obj { int val, freq; public obj(int val, int freq) { this.val = val; this.freq = freq; } } }
Java
["2\n\n2\n\n2 1\n\n4\n\n1 2 3 3"]
1 second
["1 2\n3 3 2 1"]
NoteIn the first test case, the array $$$[1,2]$$$ has sadness $$$1$$$. We can transform $$$[1,2]$$$ into $$$[2,1]$$$ using one operation with $$$(i,j)=(1,2)$$$.In the second test case, the array $$$[3,3,2,1]$$$ has sadness $$$2$$$. We can transform $$$[3,3,2,1]$$$ into $$$[1,2,3,3]$$$ with two operations with $$$(i,j)=(1,4)$$$ and $$$(i,j)=(2,3)$$$ respectively.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy" ]
01703877719e19dd8551e4599c3e1c85
Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$)  — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$)  — the length of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$)  — elements of the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
2,000
For each test case, print $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ — describing the array $$$b$$$. If there are multiple answers, you may print any.
standard output
PASSED
058b0ac0223d8f96d36d6276c535fe90
train_108.jsonl
1650722700
oolimry has an array $$$a$$$ of length $$$n$$$ which he really likes. Today, you have changed his array to $$$b$$$, a permutation of $$$a$$$, to make him sad.Because oolimry is only a duck, he can only perform the following operation to restore his array: Choose two integers $$$i,j$$$ such that $$$1 \leq i,j \leq n$$$. Swap $$$b_i$$$ and $$$b_j$$$. The sadness of the array $$$b$$$ is the minimum number of operations needed to transform $$$b$$$ into $$$a$$$.Given the array $$$a$$$, find any array $$$b$$$ which is a permutation of $$$a$$$ that has the maximum sadness over all permutations of the array $$$a$$$.
256 megabytes
import java.util.*; import java.io.*; // cd C:\Users\Lenovo\Desktop\New //ArrayList<Integer> a=new ArrayList<>(); //List<Integer> lis=new ArrayList<>(); //StringBuilder ans = new StringBuilder(); //HashMap<Integer,Integer> map=new HashMap<>(); public class cf { static FastReader in=new FastReader(); static final Random random=new Random(); //static long m=1000000007l; static long mod=1000000007l; //static long dp[]=new long[200002]; //static ArrayList<Integer> ans; //static ArrayList<ArrayList<String>> ans; static long ans; public static void main(String args[]) throws IOException { FastReader sc=new FastReader(); //Scanner s=new Scanner(System.in); int tt=sc.nextInt(); //int tt=1; while(tt-->0){ int n=sc.nextInt(); int arr[]=new int[n]; for(int i=0;i<n;i++){ arr[i]=sc.nextInt(); } HashMap<Integer,HashSet<Integer>> map=new HashMap<>(); for(int i=0;i<n;i++){ if(map.containsKey(arr[i])){ HashSet<Integer> set=map.get(arr[i]); set.add(i); map.put(arr[i],set); } else{ HashSet<Integer> set=new HashSet<>(); set.add(i); map.put(arr[i],set); } } ArrayList<Integer> list=new ArrayList<>(map.keySet()); Collections.sort(list,(o1,o2)->Integer.compare(map.get(o1).size(),map.get(o2).size())); ArrayList<Integer> pos=new ArrayList<>(); for(int i=list.size()-1;i>=0;i--){ int x=list.get(i); pos.addAll(map.get(x)); } int res[]=new int[n]; int point=0; for(int i=list.size()-2;i>=0;i--){ int freq=map.get(list.get(i)).size(); for(int j=0;j<freq;j++){ res[pos.get(point)]=list.get(i); point++; } } for(int i=0;i<n;i++){ if(res[i]==0){ res[i]=list.get(list.size()-1); } } StringBuilder ans=new StringBuilder(); for(int i=0;i<n;i++){ ans.append(res[i]+" "); } System.out.println(ans); } } public static boolean isPal(String temp){ for(int i=0;i<temp.length();i++){ if(temp.charAt(i)!=temp.charAt(temp.length()-1-i)){ return false; } } return true; } /*static void bfs(){ dist[1]=0; for(int i=2;i<dist.length;i++){ dist[i]=-1; } Queue<Integer> q=new LinkedList<>(); q.add(1); while(q.size()!=0){ int cur=q.peek(); q.remove(); for(int i=1;i<dist.length;i++ ){ int next=cur+cur/i; int ndis=dist[cur]+1; if(next<dist.length && dist[next]==-1){ dist[next]=ndis; q.add(next); } } } }*/ static long comb(int n,int k){ return factorial(n) * pow(factorial(k), mod-2) % mod * pow(factorial(n-k), mod-2) % mod; } static long pow(long a, long b) { // long mod=1000000007; long res = 1; while (b != 0) { if ((b & 1) != 0) { res = (res * a) % mod; } a = (a * a) % mod; b /= 2; } return res; } static boolean powOfTwo(long n){ while(n%2==0){ n=n/2; } if(n!=1){ return false; } return true; } static int upper_bound(long arr[], long key) { int mid, N = arr.length; int low = 0; int high = N; // Till low is less than high while (low < high && low != N) { mid = low + (high - low) / 2; if (key >= arr[mid]) { low = mid + 1; } else { high = mid; } } return low; } static boolean prime(int n){ for(int i=2;i<=Math.sqrt(n);i++){ if(n%i==0){ return false; } } return true; } static long factorial(int n){ long ret = 1; while(n > 0){ ret = ret * n % mod; n--; } return ret; } static long find(ArrayList<Long> arr,long n){ int l=0; int r=arr.size(); while(l+1<r){ int mid=(l+r)/2; if(arr.get(mid)<n){ l=mid; } else{ r=mid; } } return arr.get(l); } static void rotate(int ans[]){ int last=ans[0]; for(int i=0;i<ans.length-1;i++){ ans[i]=ans[i+1]; } ans[ans.length-1]=last; } static int countprimefactors(int n){ int ans=0; int z=(int)Math.sqrt(n); for(int i=2;i<=z;i++){ while(n%i==0){ ans++; n=n/i; } } if(n>1){ ans++; } return ans; } static String reverse_String(String s){ String ans=""; for(int i=s.length()-1;i>=0;i--){ ans+=s.charAt(i); } return ans; } static void reverse_array(int arr[]){ int l=0; int r=arr.length-1; while(l<r){ int temp=arr[l]; arr[l]=arr[r]; arr[r]=temp; l++; r--; } } static int msb(int x){ int ans=0; while(x!=0){ x=x/2; ans++; } return ans; } static void ruffleSort(int[] a) { int n=a.length; for (int i=0; i<n; i++) { int oi=random.nextInt(n); int temp=a[oi]; a[oi]=a[i]; a[i]=temp; } Arrays.sort(a); } static long gcd(long a,long b) { if(b==0) { return a; } return gcd(b,a%b); } /* Iterator<Map.Entry<Integer, Integer>> iterator = map.entrySet().iterator(); while(iterator.hasNext()){ Map.Entry<Integer, Integer> entry = iterator.next(); int value = entry.getValue(); if(value==1){ iterator.remove(); } else{ entry.setValue(value-1); } } */ static class Pair implements Comparable { int a; int b; public String toString() { return a+" " + b; } public Pair(int x , int y) { a=x;b=y; } @Override public int compareTo(Object o) { Pair p = (Pair)o; if(b!=p.b){ return b-p.b; } else{ return a-p.a; } /*if(p.a!=a){ return a-p.a;//in } else{ return b-p.b;// }*/ } } public static boolean checkAP(List<Integer> lis){ for(int i=1;i<lis.size()-1;i++){ if(2*lis.get(i)!=lis.get(i-1)+lis.get(i+1)){ return false; } } return true; } /* public static int minBS(int[]arr,int val){ int l=-1; int r=arr.length; while(r>l+1){ int mid=(l+r)/2; if(arr[mid]>=val){ r=mid; } else{ l=mid; } } return r; } public static int maxBS(int[]arr,int val){ int l=-1; int r=arr.length; while(r>l+1){ int mid=(l+r)/2; if(arr[mid]<=val){ l=mid; } else{ r=mid; } } return l; } */ static long lcm(long a, long b) { return (a / gcd(a, b)) * b; } 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
["2\n\n2\n\n2 1\n\n4\n\n1 2 3 3"]
1 second
["1 2\n3 3 2 1"]
NoteIn the first test case, the array $$$[1,2]$$$ has sadness $$$1$$$. We can transform $$$[1,2]$$$ into $$$[2,1]$$$ using one operation with $$$(i,j)=(1,2)$$$.In the second test case, the array $$$[3,3,2,1]$$$ has sadness $$$2$$$. We can transform $$$[3,3,2,1]$$$ into $$$[1,2,3,3]$$$ with two operations with $$$(i,j)=(1,4)$$$ and $$$(i,j)=(2,3)$$$ respectively.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy" ]
01703877719e19dd8551e4599c3e1c85
Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$)  — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$)  — the length of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$)  — elements of the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
2,000
For each test case, print $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ — describing the array $$$b$$$. If there are multiple answers, you may print any.
standard output
PASSED
1fa226cc1d8cbe1c44b3e1537e35e43b
train_108.jsonl
1650722700
oolimry has an array $$$a$$$ of length $$$n$$$ which he really likes. Today, you have changed his array to $$$b$$$, a permutation of $$$a$$$, to make him sad.Because oolimry is only a duck, he can only perform the following operation to restore his array: Choose two integers $$$i,j$$$ such that $$$1 \leq i,j \leq n$$$. Swap $$$b_i$$$ and $$$b_j$$$. The sadness of the array $$$b$$$ is the minimum number of operations needed to transform $$$b$$$ into $$$a$$$.Given the array $$$a$$$, find any array $$$b$$$ which is a permutation of $$$a$$$ that has the maximum sadness over all permutations of the array $$$a$$$.
256 megabytes
import java.io.*; import java.util.*; public final class Main { //int 2e9 - long 9e18 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[][] a = inputWithIdx(n); int mx = 1; int[] c = new int[n + 1]; for (int i = 0; i < n; i++) { c[a[i][1]]++; mx = Math.max(mx, c[a[i][1]]); } Arrays.sort(a, new Comparator<int[]>() { @Override public int compare(int[] o1, int[] o2) { return o1[1] - o2[1]; } }); int[] b = new int[n]; for (int i = 0; i < n; i++) { int pos = (i + mx) % n; b[a[pos][0]] = a[i][1]; } print(b); } // (10,5) = 2 ,(11,5) = 3 static long upperDiv(long a, long b) { return (a / b) + ((a % b == 0) ? 0 : 1); } static long sum(int[] a) { long sum = 0; for (int x : a) { sum += x; } return sum; } static int[] preint(int[] a) { int[] pre = new int[a.length + 1]; pre[0] = 0; for (int i = 0; i < a.length; i++) { pre[i + 1] = pre[i] + a[i]; } return pre; } 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 long[] post(int[] a) { long[] post = new long[a.length + 1]; post[0] = 0; for (int i = 0; i < a.length; i++) { post[i + 1] = post[i] + a[a.length - 1 - i]; } return post; } static long[] pre(long[] 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 String c() { return in.next(); } 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; } // find highest i which satisfy a[i]<=x static int lowerbound(int[] a, int x) { int l = 0; int r = a.length - 1; while (l < r) { int m = (l + r + 1) / 2; if (a[m] <= x) { l = m; } else { r = m - 1; } } return l; } static void shuffle(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; } } 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 void swap(char A[], int a, int b) { char 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 void reverse(int[] arr) { int l = 0; int r = arr.length - 1; while (l < r) { swap(arr, l, r); l++; r--; } } 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; int 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 ThreePair { int i; int j; int k; ThreePair(int i, int j, int k) { this.i = i; this.j = j; this.k = k; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ThreePair pair = (ThreePair) o; return i == pair.i && j == pair.j && k == pair.k; } @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 val; public Node(int val) { this.val = val; } } 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(0); } 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; } return new Node(GCD(a.val, b.val)); } static int GCD(int a, int b) { if (b == 0) { return a; } else { return GCD(b, a % b); } } }
Java
["2\n\n2\n\n2 1\n\n4\n\n1 2 3 3"]
1 second
["1 2\n3 3 2 1"]
NoteIn the first test case, the array $$$[1,2]$$$ has sadness $$$1$$$. We can transform $$$[1,2]$$$ into $$$[2,1]$$$ using one operation with $$$(i,j)=(1,2)$$$.In the second test case, the array $$$[3,3,2,1]$$$ has sadness $$$2$$$. We can transform $$$[3,3,2,1]$$$ into $$$[1,2,3,3]$$$ with two operations with $$$(i,j)=(1,4)$$$ and $$$(i,j)=(2,3)$$$ respectively.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy" ]
01703877719e19dd8551e4599c3e1c85
Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$)  — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$)  — the length of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$)  — elements of the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
2,000
For each test case, print $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ — describing the array $$$b$$$. If there are multiple answers, you may print any.
standard output
PASSED
f63fd0d7de5451d41bb6503c50d2277a
train_108.jsonl
1650722700
oolimry has an array $$$a$$$ of length $$$n$$$ which he really likes. Today, you have changed his array to $$$b$$$, a permutation of $$$a$$$, to make him sad.Because oolimry is only a duck, he can only perform the following operation to restore his array: Choose two integers $$$i,j$$$ such that $$$1 \leq i,j \leq n$$$. Swap $$$b_i$$$ and $$$b_j$$$. The sadness of the array $$$b$$$ is the minimum number of operations needed to transform $$$b$$$ into $$$a$$$.Given the array $$$a$$$, find any array $$$b$$$ which is a permutation of $$$a$$$ that has the maximum sadness over all permutations of the array $$$a$$$.
256 megabytes
import java.io.*; import java.util.*; public class problemF1 { public static void main(String[] args)throws IOException { // TODO Auto-generated method stub BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out)); int t = Integer.parseInt(br.readLine()); for(int i=0; i<t; i++) { int n = Integer.parseInt(br.readLine()); int[][] joyce_qu = new int[n][2]; int max = 0; StringTokenizer st = new StringTokenizer(br.readLine()); HashMap<Integer,Integer> map = new HashMap<>(); for(int j=0; j<n; j++) { joyce_qu[j][0] = Integer.parseInt(st.nextToken()); joyce_qu[j][1] = j; if(map.containsKey(joyce_qu[j][0]))map.put(joyce_qu[j][0],map.get(joyce_qu[j][0])+1); else map.put(joyce_qu[j][0], 1); max = Math.max(max, map.get(joyce_qu[j][0])); } Arrays.sort(joyce_qu, (a,b)->a[0]-b[0]); int[] next = new int[n]; int[] ans = new int[n]; for(int j=0; j<n; j++) next[j] = joyce_qu[(j+max)%n][0]; for(int j=0; j<n; j++) ans[joyce_qu[j][1]] = next[j]; for(int j=0; j<n; j++) out.write(ans[j] +" "); out.write("\n"); /* LinkedList<Integer>[] joyce_qu = new LinkedList[n+1]; for(int j=1; j<=n; j++)joyce_qu[j] = new LinkedList<>(); for(int j=0; j<n; j++) { arr[j] = Integer.parseInt(st.nextToken()); joyce_qu[arr[j]].add(j); } int[] next = new int[n+1]; for(int j=1; j<=n; j++) { if(joyce_qu[j].isEmpty())next[i] = -1; else next[j] = joyce_qu[j].removeFirst(); } */ } out.flush(); out.close(); } }
Java
["2\n\n2\n\n2 1\n\n4\n\n1 2 3 3"]
1 second
["1 2\n3 3 2 1"]
NoteIn the first test case, the array $$$[1,2]$$$ has sadness $$$1$$$. We can transform $$$[1,2]$$$ into $$$[2,1]$$$ using one operation with $$$(i,j)=(1,2)$$$.In the second test case, the array $$$[3,3,2,1]$$$ has sadness $$$2$$$. We can transform $$$[3,3,2,1]$$$ into $$$[1,2,3,3]$$$ with two operations with $$$(i,j)=(1,4)$$$ and $$$(i,j)=(2,3)$$$ respectively.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy" ]
01703877719e19dd8551e4599c3e1c85
Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$)  — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$)  — the length of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$)  — elements of the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
2,000
For each test case, print $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ — describing the array $$$b$$$. If there are multiple answers, you may print any.
standard output
PASSED
56a2e843763866c15f2e6420c55f285f
train_108.jsonl
1650722700
oolimry has an array $$$a$$$ of length $$$n$$$ which he really likes. Today, you have changed his array to $$$b$$$, a permutation of $$$a$$$, to make him sad.Because oolimry is only a duck, he can only perform the following operation to restore his array: Choose two integers $$$i,j$$$ such that $$$1 \leq i,j \leq n$$$. Swap $$$b_i$$$ and $$$b_j$$$. The sadness of the array $$$b$$$ is the minimum number of operations needed to transform $$$b$$$ into $$$a$$$.Given the array $$$a$$$, find any array $$$b$$$ which is a permutation of $$$a$$$ that has the maximum sadness over all permutations of the array $$$a$$$.
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 F_1_Array_Shuffling{ 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> unique = new ArrayList<Long>(n+3); HashMap<Long,Stack<Long>> map = new HashMap<Long,Stack<Long>>(); for(int i=0;i<n;i++){ array[i]=s.nextLong(); if(map.containsKey(array[i])){ map.get(array[i]).push((long)i); } else{ Stack<Long> obj = new Stack<Long>(); obj.push((long)i); map.put(array[i],obj); unique.add(array[i]); } } //creating my linear graph of nodes long first=-1;//stores the number of the first node in list long last=-1;// stores the number of the last node in the list pair prev=null; pair start=null; pair end=null; for(int i=0;i<unique.size();i++){ long num=unique.get(i); if(prev==null){ pair obj = new pair(num,null); start=obj; prev=obj; first=num; last= num; end=obj; } else{ pair obj = new pair(num,null); prev.next=obj; last=num; prev=obj; end=obj; } } long ans[]= new long[n]; while(true){ if(first==last){ break; } pair yoyo=start; long number=end.val; pair previous=null; while(yoyo!=null){ long alpha=yoyo.val; long index=map.get(alpha).pop(); ans[(int)index]=number; long nextnumber=alpha; pair nextnode=yoyo.next; if(map.get(alpha).size()==0){ //no indexes left of alpha if(previous!=null){ if(nextnode!=null){ previous.next=nextnode; } else{ previous.next=null; last=previous.val; end=previous; } } else{ if(nextnode!=null){ first=nextnode.val; start=nextnode; } else{ } } yoyo=nextnode; number=nextnumber; } else{ previous=yoyo; yoyo=nextnode; number=nextnumber; } } } long number=first; Stack<Long> well= map.get(number); while(well.size()>0){ long index=well.pop(); ans[(int)index]=number; } for(int i=0;i<n;i++){ res.append(ans[i]+" "); } res.append(" \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; } static class pair{ long val; pair next; pair(long val, pair next){ this.val=val; this.next=next; } } }
Java
["2\n\n2\n\n2 1\n\n4\n\n1 2 3 3"]
1 second
["1 2\n3 3 2 1"]
NoteIn the first test case, the array $$$[1,2]$$$ has sadness $$$1$$$. We can transform $$$[1,2]$$$ into $$$[2,1]$$$ using one operation with $$$(i,j)=(1,2)$$$.In the second test case, the array $$$[3,3,2,1]$$$ has sadness $$$2$$$. We can transform $$$[3,3,2,1]$$$ into $$$[1,2,3,3]$$$ with two operations with $$$(i,j)=(1,4)$$$ and $$$(i,j)=(2,3)$$$ respectively.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy" ]
01703877719e19dd8551e4599c3e1c85
Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$)  — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$)  — the length of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$)  — elements of the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
2,000
For each test case, print $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ — describing the array $$$b$$$. If there are multiple answers, you may print any.
standard output
PASSED
72c9d4700479981c386465641d2eac17
train_108.jsonl
1650722700
oolimry has an array $$$a$$$ of length $$$n$$$ which he really likes. Today, you have changed his array to $$$b$$$, a permutation of $$$a$$$, to make him sad.Because oolimry is only a duck, he can only perform the following operation to restore his array: Choose two integers $$$i,j$$$ such that $$$1 \leq i,j \leq n$$$. Swap $$$b_i$$$ and $$$b_j$$$. The sadness of the array $$$b$$$ is the minimum number of operations needed to transform $$$b$$$ into $$$a$$$.Given the array $$$a$$$, find any array $$$b$$$ which is a permutation of $$$a$$$ that has the maximum sadness over all permutations of the array $$$a$$$.
256 megabytes
import java.io.*; import java.util.*; //import javafx.util.*; public class Main { static PrintWriter out = new PrintWriter(System.out); static FastReader in = new FastReader(); static int INF = Integer.MAX_VALUE; static int NINF = Integer.MIN_VALUE; public static StringBuilder str = new StringBuilder(); public static boolean flag = true; public static ArrayList<Integer> arr = new ArrayList<>(); public static void main (String[] args) throws java.lang.Exception { //check if you have to take product or the constraints are big int t = i(); while(t-- > 0){ int n = i(); int[] arr = input(n); ArrayList<Queue<Integer>> indices = new ArrayList<>(); for(int i = 0;i < n + 1;i++){ indices.add(new LinkedList<>()); } PriorityQueue<pair> pq = new PriorityQueue<>(Collections.reverseOrder()); HashMap<Integer,Integer> map = new HashMap<>(); for(int i = 0;i < n;i++){ map.put(arr[i],map.getOrDefault(arr[i],0) + 1); indices.get(arr[i]).add(i); } for(int i : map.keySet()){ pq.add(new pair(map.get(i),i)); } pair initial = pq.poll(); int previous = initial.y; int count_previous = initial.x; Queue<Integer> main_queue = indices.get(previous); int[] res = new int[n]; while(!pq.isEmpty()){ pair p = pq.poll(); int count = p.x; int element = p.y; while(count-- > 0){ res[main_queue.poll()] = element; } Queue<Integer> queue = indices.get(element); while(!queue.isEmpty()){ main_queue.add(queue.poll()); } } for(int i = 0;i < n;i++){ if(res[i] == 0){ res[i] = initial.y; } } for(int i = 0;i < n;i++){ out.print(res[i] + " "); } out.println(); } out.close(); } public static void sort(int[] arr){ ArrayList<Integer> ls = new ArrayList<>(); 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 reverse(int[] arr){ int n = arr.length; for(int i = 0;i < n/2;i++){ int temp = arr[i]; arr[i] = arr[n-1-i]; arr[n-1-i] = temp; } } static int i() { return in.nextInt(); } static long l() { return in.nextLong(); } 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; } } class pair implements Comparable<pair> { int x; int y; public pair(int x, int y) { this.x = x; this.y = y; } public String toString() { return x + " " + y; } public boolean equals(Object o) { if (o instanceof pair) { pair p = (pair) o; return p.x == x && p.y == y; } return false; } // public int hashCode() { // return new Integer(x).hashCode() * 31 + new Integer(y).hashCode(); // } public int compareTo(pair other) { if (this.x == other.x) { return Integer.compare(this.y, other.y); } return Integer.compare(this.x, other.x); } } 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
["2\n\n2\n\n2 1\n\n4\n\n1 2 3 3"]
1 second
["1 2\n3 3 2 1"]
NoteIn the first test case, the array $$$[1,2]$$$ has sadness $$$1$$$. We can transform $$$[1,2]$$$ into $$$[2,1]$$$ using one operation with $$$(i,j)=(1,2)$$$.In the second test case, the array $$$[3,3,2,1]$$$ has sadness $$$2$$$. We can transform $$$[3,3,2,1]$$$ into $$$[1,2,3,3]$$$ with two operations with $$$(i,j)=(1,4)$$$ and $$$(i,j)=(2,3)$$$ respectively.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy" ]
01703877719e19dd8551e4599c3e1c85
Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$)  — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$)  — the length of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$)  — elements of the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
2,000
For each test case, print $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ — describing the array $$$b$$$. If there are multiple answers, you may print any.
standard output
PASSED
e1a064f1dad817a3127c025d963ca8b1
train_108.jsonl
1650722700
oolimry has an array $$$a$$$ of length $$$n$$$ which he really likes. Today, you have changed his array to $$$b$$$, a permutation of $$$a$$$, to make him sad.Because oolimry is only a duck, he can only perform the following operation to restore his array: Choose two integers $$$i,j$$$ such that $$$1 \leq i,j \leq n$$$. Swap $$$b_i$$$ and $$$b_j$$$. The sadness of the array $$$b$$$ is the minimum number of operations needed to transform $$$b$$$ into $$$a$$$.Given the array $$$a$$$, find any array $$$b$$$ which is a permutation of $$$a$$$ that has the maximum sadness over all permutations of the array $$$a$$$.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; public class AACFCC { // public static long mod = (long) Math.pow(10, 9) + 7; public static long mod2 = 998244353; public int oo = 0; // public static HashMap<Integer, Integer> primenom; // public static HashMap<Integer, Integer> primeden; // public static HashMap<Integer, Integer> fin; public static String zz; public static long ttt = -1; static HashMap<Integer, Integer>[] factors; public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw = new PrintWriter(System.out); int t = Integer.parseInt(br.readLine()); while (t-- > 0) { String[] s2 = (br.readLine()).split(" "); int n = Integer.valueOf(s2[0]); int[]arr=new int[n]; String[]s1=br.readLine().split(" "); for(int i=0;i<n;i++) { arr[i]=Integer.valueOf(s1[i]); } HashMap<Integer,Integer> map=new HashMap<>(); for(int i=0;i<n;i++) { map.put(arr[i],map.getOrDefault(arr[i], 0)+ 1); } HashMap<Integer,ArrayList<Integer>> mm=new HashMap<>(); while(!map.isEmpty()) { int op=-1; int pp=-1; ArrayList<Integer> list=new ArrayList<>(map.keySet()); for(int a:list) { if(op==-1) { op=a; pp=a; }else { if(mm.containsKey(a)) { mm.get(a).add(pp); }else { ArrayList<Integer> l=new ArrayList<>(); l.add(pp); mm.put(a, l); } pp=a; } map.put(a, map.get(a)-1); if(map.get(a)==0) { map.remove(a); } } if(mm.containsKey(op)) { mm.get(op).add(pp); }else { ArrayList<Integer> l=new ArrayList<>(); l.add(pp); mm.put(op, l); } } // System.out.println(mm); map=new HashMap<>(); for(int a:mm.keySet()) { map.put(a, 0); } StringBuilder ans=new StringBuilder(); for(int i=0;i<n;i++) { int op=arr[i]; //System.out.println(mm.get(arr[i])+" "+map.get(arr[i])+" "+map); arr[i]=mm.get(arr[i]).get(map.get(arr[i])); map.put(op, map.get(op)+1); ans.append(arr[i]+" "); } pw.println(ans.toString()); // System.out.flush(); // long lh = 0, rh = 1; // long l = 0, r = n * 2000 + 2500; // r = getAns(r, 1l, l, r, br); // System.out.println(r); // long ans = Long.MAX_VALUE; // while (l <= r) { // long mid = (l + r) / 2; // System.out.println("? " + mid); // System.out.flush(); // long hi = Integer.valueOf(br.readLine()); // if (hi == lh) { // l = mid + 1; // continue; // } else if (hi == rh) { // r = mid - 1; // continue; // } // long no=getAns(mid, hi, l, mid, br); // ans = Math.min(ans, hi * no); // if (rh * (r) > hi * no) { // // r = no - 1; // } else { // // l = no + 1; // } // // } // System.out.println("! " + ans); } pw.close(); } private static long getAns(long curr, long no, long l, long r, BufferedReader br) throws Exception { // TODO Auto-generated method stub long ans = curr; while (l <= r) { long mid = (l + r) / 2; System.out.println("? " + mid); System.out.flush(); long hi = Integer.valueOf(br.readLine()); if (hi == no) { ans = r; r = mid - 1; } else if (hi > no) { l = mid + 1; } else { r = mid - 1; } } return ans; } } // private static void putBit(int ind, int val, int[] bit) { // // TODO Auto-generated method stub // for (int i = ind; i < bit.length; i += (i & -i)) { // bit[i] += val; // } // } // // private static int getSum(int ind, int[] bit) { // // TODO Auto-generated method stub // int ans = 0; // for (int i = ind; i > 0; i -= (i & -i)) { // ans += bit[i]; // } // return ans; // } // private static void product(long[] bin, int ind, int currIt, long[] power) { // // TODO Auto-generated method stub // long pre = 1; // if (ind > 1) { // pre = power(power[ind - 1] - 1, mod2 - 1); // } // long cc = power[ind] - 1; // // System.out.println(pre + " " + cc); // for (int i = ind; i < bin.length; i += (i & (-i))) { // bin[i] = (bin[i] * pre) % mod2; // bin[i] = (bin[i] * cc) % mod2; // } // } // // private static void add(long[] bin, int ind, int val) { // // TODO Auto-generated method stub // for (int i = ind; i < bin.length; i += (i & (-i))) { // bin[i] += val; // } // } // // private static long sum(long[] bin, int ind) { // // TODO Auto-generated method stub // long ans = 0; // for (int i = ind; i > 0; i -= (i & (-i))) { // ans += bin[i]; // } // return ans; // } // // private static long power(long a, long p) { // TODO Auto-generated method stub // long res = 1;while(p>0) // { // if (p % 2 == 1) { // res = (res * a) % mod; // } // p = p / 2; // a = (a * a) % mod; // }return res; // }} // private static void getFac(long n, PrintWriter pw) { // // TODO Auto-generated method stub // int a = 0; // while (n % 2 == 0) { // a++; // n = n / 2; // } // if (n == 1) { // a--; // } // for (int i = 3; i <= Math.sqrt(n); i += 2) { // while (n % i == 0) { // n = n / i; // a++; // } // } // if (n > 1) { // a++; // } // if (a % 2 == 0) { // pw.println("Bob"); // } else { // pw.println("Alice"); // } // //System.out.println(a); // return; // } // private static long power(long a, long p) { // // TODO Auto-generated method stub // long res = 1; // while (p > 0) { // if (p % 2 == 1) { // res = (res * a) % mod; // } // p = p / 2; // a = (a * a) % mod; // } // return res; // } // // private static void fac() { // fac[0] = 1; // // TODO Auto-generated method stub // for (int i = 1; i < fac.length; i++) { // if (i == 1) { // fac[i] = 1; // } else { // fac[i] = i * fac[i - 1]; // } // if (fac[i] > mod) { // fac[i] = fac[i] % mod; // } // } // } // // private static int getLower(Long long1, Long[] st) { // // TODO Auto-generated method stub // int left = 0, right = st.length - 1; // int ans = -1; // while (left <= right) { // int mid = (left + right) / 2; // if (st[mid] <= long1) { // ans = mid; // left = mid + 1; // } else { // right = mid - 1; // } // } // return ans; // } // private static long getGCD(long l, long m) { // // long t1 = Math.min(l, m); // long t2 = Math.max(l, m); // while (true) { // long temp = t2 % t1; // if (temp == 0) { // return t1; // } // t2 = t1; // t1 = temp; // } // } // private static int kmp(String str) { // // TODO Auto-generated method stub // // System.out.println(str); // int[] pi = new int[str.length()]; // pi[0] = 0; // for (int i = 1; i < str.length(); i++) { // int j = pi[i - 1]; // while (j > 0 && str.charAt(i) != str.charAt(j)) { // j = pi[j - 1]; // } // if (str.charAt(j) == str.charAt(i)) { // j++; // } // pi[i] = j; // System.out.print(pi[i]); // } // System.out.println(); // return pi[str.length() - 1]; // } // private static void getFac(long n, PrintWriter pw) { // // TODO Auto-generated method stub // int a = 0; // while (n % 2 == 0) { // a++; // n = n / 2; // } // if (n == 1) { // a--; // } // for (int i = 3; i <= Math.sqrt(n); i += 2) { // while (n % i == 0) { // n = n / i; // a++; // } // } // if (n > 1) { // a++; // } // if (a % 2 == 0) { // pw.println("Bob"); // } else { // pw.println("Alice"); // } // //System.out.println(a); // return; // } // private static long power(long a, long p) { // // TODO Auto-generated method stub // long res = 1; // while (p > 0) { // if (p % 2 == 1) { // res = (res * a) % mod; // } // p = p / 2; // a = (a * a) % mod; // } // return res; // } // // private static void fac() { // fac[0] = 1; // // TODO Auto-generated method stub // for (int i = 1; i < fac.length; i++) { // if (i == 1) { // fac[i] = 1; // } else { // fac[i] = i * fac[i - 1]; // } // if (fac[i] > mod) { // fac[i] = fac[i] % mod; // } // } // } // // private static int getLower(Long long1, Long[] st) { // // TODO Auto-generated method stub // int left = 0, right = st.length - 1; // int ans = -1; // while (left <= right) { // int mid = (left + right) / 2; // if (st[mid] <= long1) { // ans = mid; // left = mid + 1; // } else { // right = mid - 1; // } // } // return ans; // } // private static long getGCD(long l, long m) { // // long t1 = Math.min(l, m); // long t2 = Math.max(l, m); // while (true) { // long temp = t2 % t1; // if (temp == 0) { // return t1; // } // t2 = t1; // t1 = temp; // } // }
Java
["2\n\n2\n\n2 1\n\n4\n\n1 2 3 3"]
1 second
["1 2\n3 3 2 1"]
NoteIn the first test case, the array $$$[1,2]$$$ has sadness $$$1$$$. We can transform $$$[1,2]$$$ into $$$[2,1]$$$ using one operation with $$$(i,j)=(1,2)$$$.In the second test case, the array $$$[3,3,2,1]$$$ has sadness $$$2$$$. We can transform $$$[3,3,2,1]$$$ into $$$[1,2,3,3]$$$ with two operations with $$$(i,j)=(1,4)$$$ and $$$(i,j)=(2,3)$$$ respectively.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy" ]
01703877719e19dd8551e4599c3e1c85
Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$)  — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$)  — the length of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$)  — elements of the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
2,000
For each test case, print $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ — describing the array $$$b$$$. If there are multiple answers, you may print any.
standard output
PASSED
dcaf33dc1e2970e8cccd20cd5b215515
train_108.jsonl
1650722700
oolimry has an array $$$a$$$ of length $$$n$$$ which he really likes. Today, you have changed his array to $$$b$$$, a permutation of $$$a$$$, to make him sad.Because oolimry is only a duck, he can only perform the following operation to restore his array: Choose two integers $$$i,j$$$ such that $$$1 \leq i,j \leq n$$$. Swap $$$b_i$$$ and $$$b_j$$$. The sadness of the array $$$b$$$ is the minimum number of operations needed to transform $$$b$$$ into $$$a$$$.Given the array $$$a$$$, find any array $$$b$$$ which is a permutation of $$$a$$$ that has the maximum sadness over all permutations of the array $$$a$$$.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Random; import java.util.StringTokenizer; /* */ public class F { public static void main(String[] args) { FastScanner fs=new FastScanner(); PrintWriter out=new PrintWriter(System.out); int T=fs.nextInt(); // int T=1; for (int tt=0; tt<T; tt++) { int n=fs.nextInt(); int[] a=fs.readArray(n); ArrayDeque<Integer>[] occsOf=new ArrayDeque[n+1]; for (int i=0; i<=n; i++) occsOf[i]=new ArrayDeque<>(); for (int i=0; i<n; i++) occsOf[a[i]].addLast(i); Arrays.sort(occsOf, (aa, bb) -> Integer.compare(bb.size(), aa.size())); int[] ans=a.clone(); while (!occsOf[1].isEmpty()) { ArrayList<Integer> loop=new ArrayList<>(); for (int i=0; !occsOf[i].isEmpty(); i++) loop.add(occsOf[i].removeFirst()); loop(ans, loop); } for (int i:ans) { out.print(i+" "); } out.println(); } out.close(); } static void loop(int[] a, ArrayList<Integer> loop) { int[] values=new int[loop.size()]; for (int i=0; i<values.length; i++) values[i]=a[loop.get(i)]; for (int i=0; i<values.length; i++) a[loop.get((i+1)%values.length)]=values[i]; } static final Random random=new Random(); static final int mod=1_000_000_007; static void ruffleSort(int[] a) { int n=a.length;//shuffle, then sort for (int i=0; i<n; i++) { int oi=random.nextInt(n), temp=a[oi]; a[oi]=a[i]; a[i]=temp; } Arrays.sort(a); } static long add(long a, long b) { return (a+b)%mod; } static long sub(long a, long b) { return ((a-b)%mod+mod)%mod; } static long mul(long a, long b) { return (a*b)%mod; } static long exp(long base, long exp) { if (exp==0) return 1; long half=exp(base, exp/2); if (exp%2==0) return mul(half, half); return mul(half, mul(half, base)); } static long[] factorials=new long[2_000_001]; static long[] invFactorials=new long[2_000_001]; static void precompFacts() { factorials[0]=invFactorials[0]=1; for (int i=1; i<factorials.length; i++) factorials[i]=mul(factorials[i-1], i); invFactorials[factorials.length-1]=exp(factorials[factorials.length-1], mod-2); for (int i=invFactorials.length-2; i>=0; i--) invFactorials[i]=mul(invFactorials[i+1], i+1); } static long nCk(int n, int k) { return mul(factorials[n], mul(invFactorials[k], invFactorials[n-k])); } static void sort(int[] a) { ArrayList<Integer> l=new ArrayList<>(); for (int i:a) l.add(i); Collections.sort(l); for (int i=0; i<a.length; i++) a[i]=l.get(i); } static 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
["2\n\n2\n\n2 1\n\n4\n\n1 2 3 3"]
1 second
["1 2\n3 3 2 1"]
NoteIn the first test case, the array $$$[1,2]$$$ has sadness $$$1$$$. We can transform $$$[1,2]$$$ into $$$[2,1]$$$ using one operation with $$$(i,j)=(1,2)$$$.In the second test case, the array $$$[3,3,2,1]$$$ has sadness $$$2$$$. We can transform $$$[3,3,2,1]$$$ into $$$[1,2,3,3]$$$ with two operations with $$$(i,j)=(1,4)$$$ and $$$(i,j)=(2,3)$$$ respectively.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy" ]
01703877719e19dd8551e4599c3e1c85
Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$)  — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$)  — the length of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$)  — elements of the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
2,000
For each test case, print $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ — describing the array $$$b$$$. If there are multiple answers, you may print any.
standard output
PASSED
477a244b162db29a0c8af39a410d92e2
train_108.jsonl
1650722700
oolimry has an array $$$a$$$ of length $$$n$$$ which he really likes. Today, you have changed his array to $$$b$$$, a permutation of $$$a$$$, to make him sad.Because oolimry is only a duck, he can only perform the following operation to restore his array: Choose two integers $$$i,j$$$ such that $$$1 \leq i,j \leq n$$$. Swap $$$b_i$$$ and $$$b_j$$$. The sadness of the array $$$b$$$ is the minimum number of operations needed to transform $$$b$$$ into $$$a$$$.Given the array $$$a$$$, find any array $$$b$$$ which is a permutation of $$$a$$$ that has the maximum sadness over all permutations of the array $$$a$$$.
256 megabytes
import java.io.*; import java.util.*; import java.math.*; public class F1 { public static void main(String[] args) throws IOException { /**/ Scanner sc = new Scanner(new BufferedReader(new InputStreamReader(System.in))); /*/ Scanner sc = new Scanner(new BufferedReader(new InputStreamReader(new FileInputStream("src/f1.in")))); /**/ int t = sc.nextInt(); for (int z = 0; z < t; ++z) { int n = sc.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; ++i) a[i] = sc.nextInt(); int[] b = new int[n]; int[] cts = new int[n+1]; ArrayList<ArrayList<Long>> rots = new ArrayList<>(); rots.add(new ArrayList<>()); for (int i = 0; i < n; ++i) { ++cts[a[i]]; if (rots.size()==cts[a[i]]) rots.add(new ArrayList<>()); long num = a[i]; num<<=32; num+=i; rots.get(cts[a[i]]).add(num); } for (int i = 0; i < rots.size(); ++i) { Collections.sort(rots.get(i)); for (int j = 0; j < rots.get(i).size(); ++j) { int src = (int)(0+rots.get(i).get(j)); int dest = (int)(0+rots.get(i).get((j+1)%rots.get(i).size())); b[dest] = a[src]; } } StringBuilder ans = new StringBuilder(); for (int x : b) { if (ans.length()>0) ans.append(" "); ans.append(x); } System.out.println(ans); } } }
Java
["2\n\n2\n\n2 1\n\n4\n\n1 2 3 3"]
1 second
["1 2\n3 3 2 1"]
NoteIn the first test case, the array $$$[1,2]$$$ has sadness $$$1$$$. We can transform $$$[1,2]$$$ into $$$[2,1]$$$ using one operation with $$$(i,j)=(1,2)$$$.In the second test case, the array $$$[3,3,2,1]$$$ has sadness $$$2$$$. We can transform $$$[3,3,2,1]$$$ into $$$[1,2,3,3]$$$ with two operations with $$$(i,j)=(1,4)$$$ and $$$(i,j)=(2,3)$$$ respectively.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy" ]
01703877719e19dd8551e4599c3e1c85
Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$)  — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$)  — the length of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$)  — elements of the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
2,000
For each test case, print $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ — describing the array $$$b$$$. If there are multiple answers, you may print any.
standard output
PASSED
e3edd1f8c831c42253368e95e23d5a78
train_108.jsonl
1650722700
oolimry has an array $$$a$$$ of length $$$n$$$ which he really likes. Today, you have changed his array to $$$b$$$, a permutation of $$$a$$$, to make him sad.Because oolimry is only a duck, he can only perform the following operation to restore his array: Choose two integers $$$i,j$$$ such that $$$1 \leq i,j \leq n$$$. Swap $$$b_i$$$ and $$$b_j$$$. The sadness of the array $$$b$$$ is the minimum number of operations needed to transform $$$b$$$ into $$$a$$$.Given the array $$$a$$$, find any array $$$b$$$ which is a permutation of $$$a$$$ that has the maximum sadness over all permutations of the array $$$a$$$.
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 = new int[n]; int[] b = new int[n]; for(int i = 0; i < n; i++){ a[i] = b[i] = sc.nextInt(); } ArrayList<Stack<Integer>> al = new ArrayList<>(); for(int i = 0; i <= n; i++) al.add(new Stack<Integer>()); int[] cnt = new int[n+1]; for(int v : a) cnt[v]++; int max = 0; Arrays.sort(b); for(int i = 1; i <= n; i++) max = Math.max(max,cnt[i]); for(int i = 0; i < n; i++){ al.get(b[i]).push(b[(i+max)%n]); } for(int i = 0; i < n; i++){ sb.append(al.get(a[i]).pop()).append(" "); } pw.println(sb.toString()); sb.setLength(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
["2\n\n2\n\n2 1\n\n4\n\n1 2 3 3"]
1 second
["1 2\n3 3 2 1"]
NoteIn the first test case, the array $$$[1,2]$$$ has sadness $$$1$$$. We can transform $$$[1,2]$$$ into $$$[2,1]$$$ using one operation with $$$(i,j)=(1,2)$$$.In the second test case, the array $$$[3,3,2,1]$$$ has sadness $$$2$$$. We can transform $$$[3,3,2,1]$$$ into $$$[1,2,3,3]$$$ with two operations with $$$(i,j)=(1,4)$$$ and $$$(i,j)=(2,3)$$$ respectively.
Java 11
standard input
[ "constructive algorithms", "graphs", "greedy" ]
01703877719e19dd8551e4599c3e1c85
Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$)  — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$)  — the length of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$)  — elements of the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
2,000
For each test case, print $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ — describing the array $$$b$$$. If there are multiple answers, you may print any.
standard output
PASSED
ce4d4af437fc5aba65d2cfe24e9cd3b0
train_108.jsonl
1650722700
oolimry has an array $$$a$$$ of length $$$n$$$ which he really likes. Today, you have changed his array to $$$b$$$, a permutation of $$$a$$$, to make him sad.Because oolimry is only a duck, he can only perform the following operation to restore his array: Choose two integers $$$i,j$$$ such that $$$1 \leq i,j \leq n$$$. Swap $$$b_i$$$ and $$$b_j$$$. The sadness of the array $$$b$$$ is the minimum number of operations needed to transform $$$b$$$ into $$$a$$$.Given the array $$$a$$$, find any array $$$b$$$ which is a permutation of $$$a$$$ that has the maximum sadness over all permutations of the array $$$a$$$.
256 megabytes
import java.io.*; import java.util.ArrayDeque; import java.util.Arrays; import java.util.InputMismatchException; public class E1672F1 { public static void main(String[] args) { FastIO io = new FastIO(); int t = io.nextInt(); while (t-- > 0) { int n = io.nextInt(); int[] count = new int[n + 1]; int[] arr = new int[n]; int[][] sorted = new int[n][2]; int maxCount = 0; for (int i = 0; i < n; i++) { arr[i] = io.nextInt(); sorted[i] = new int[]{arr[i], i}; count[arr[i]]++; maxCount = Math.max(maxCount, count[arr[i]]); } Arrays.sort(sorted, (a, b) -> a[0] == b[0] ? a[1] - b[1] : a[0] - b[0]); int[] ans = new int[n]; for (int i = 0; i < n; i++) { ans[sorted[i][1]] = arr[sorted[(i + maxCount) % n][1]]; } for (int v : ans) io.print(v + " "); io.println(); } io.close(); } private static class FastIO extends PrintWriter { private final InputStream stream; private final byte[] buf = new byte[1 << 16]; private int curChar, numChars; // standard input public FastIO() { this(System.in, System.out); } public FastIO(InputStream i, OutputStream o) { super(o); stream = i; } // file input public FastIO(String i, String o) throws IOException { super(new FileWriter(o)); stream = new FileInputStream(i); } // throws InputMismatchException() if previously detected end of file private int nextByte() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars == -1) return -1; // end of file } return buf[curChar++]; } // to read in entire lines, replace c <= ' ' // with a function that checks whether c is a line break public String next() { int c; do { c = nextByte(); } while (c <= ' '); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = nextByte(); } while (c > ' '); return res.toString(); } public int nextInt() { // nextLong() would be implemented similarly int c; do { c = nextByte(); } while (c <= ' '); int sgn = 1; if (c == '-') { sgn = -1; c = nextByte(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res = 10 * res + c - '0'; c = nextByte(); } while (c > ' '); return res * sgn; } public long nextLong() { // nextLong() would be implemented similarly int c; do { c = nextByte(); } while (c <= ' '); int sgn = 1; if (c == '-') { sgn = -1; c = nextByte(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res = 10 * res + c - '0'; c = nextByte(); } while (c > ' '); return res * sgn; } public double nextDouble() { return Double.parseDouble(next()); } } }
Java
["2\n\n2\n\n2 1\n\n4\n\n1 2 3 3"]
1 second
["1 2\n3 3 2 1"]
NoteIn the first test case, the array $$$[1,2]$$$ has sadness $$$1$$$. We can transform $$$[1,2]$$$ into $$$[2,1]$$$ using one operation with $$$(i,j)=(1,2)$$$.In the second test case, the array $$$[3,3,2,1]$$$ has sadness $$$2$$$. We can transform $$$[3,3,2,1]$$$ into $$$[1,2,3,3]$$$ with two operations with $$$(i,j)=(1,4)$$$ and $$$(i,j)=(2,3)$$$ respectively.
Java 11
standard input
[ "constructive algorithms", "graphs", "greedy" ]
01703877719e19dd8551e4599c3e1c85
Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$)  — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$)  — the length of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$)  — elements of the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
2,000
For each test case, print $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ — describing the array $$$b$$$. If there are multiple answers, you may print any.
standard output
PASSED
42e191faf75f758c62e25f1aaf486a34
train_108.jsonl
1650722700
oolimry has an array $$$a$$$ of length $$$n$$$ which he really likes. Today, you have changed his array to $$$b$$$, a permutation of $$$a$$$, to make him sad.Because oolimry is only a duck, he can only perform the following operation to restore his array: Choose two integers $$$i,j$$$ such that $$$1 \leq i,j \leq n$$$. Swap $$$b_i$$$ and $$$b_j$$$. The sadness of the array $$$b$$$ is the minimum number of operations needed to transform $$$b$$$ into $$$a$$$.Given the array $$$a$$$, find any array $$$b$$$ which is a permutation of $$$a$$$ that has the maximum sadness over all permutations of the array $$$a$$$.
256 megabytes
import java.util.*; import java.io.*; // you can compare with output.txt and expected out public class RoundGlobal20F1 { 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))); RoundGlobal20F1 sol = new RoundGlobal20F1(); 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) { 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 int[] solve(int[] a) { int n = a.length; Integer[] sortedIdx = new Integer[n]; for(int i=0; i<n; i++) sortedIdx[i] = i; Arrays.sort(sortedIdx, new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { return Integer.compare(a[o1], a[o2]); } }); ArrayList<Pair> cycles = new ArrayList<>(); int start = 0; while(start < n) { int end = start+1; while(end < n && a[sortedIdx[start]] == a[sortedIdx[end]]) end++; cycles.add(new Pair(a[sortedIdx[start]], end-start)); start = end; } if(cycles.size() == 1) return a; start = 0; for(int i=1; i<cycles.size(); i++) { if(cycles.get(i).len > cycles.get(start).len) start = i; } int[] b = new int[n]; int idx = 0; for(int i=0; i<start; i++) idx += cycles.get(i).len; int i = start+1; do { i = i==cycles.size()? 0: i; int val = cycles.get(i).val; int len = cycles.get(i).len; for(int j=0; j<len; j++) b[sortedIdx[j+idx<n? j+idx: j+idx-n]] = val; idx += len; idx = idx>=n? idx-n: idx; i++; }while(i != start+1); // 1 4 1 4 1 4 // 4 1 4 1 4 1 // 1 1 1 4 4 4 // 4 4 4 1 1 1 // 1 4 1 4 1 4 // sortedIdx[0] = 0 // sortedIdx[1] = 2 // sortedIdx[2] = 4 // 1 1 1 4 4 4 return b; } static class Pair{ int val; int len; public Pair(int val, int len) { this.val = val; this.len = len; } } 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(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(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 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
["2\n\n2\n\n2 1\n\n4\n\n1 2 3 3"]
1 second
["1 2\n3 3 2 1"]
NoteIn the first test case, the array $$$[1,2]$$$ has sadness $$$1$$$. We can transform $$$[1,2]$$$ into $$$[2,1]$$$ using one operation with $$$(i,j)=(1,2)$$$.In the second test case, the array $$$[3,3,2,1]$$$ has sadness $$$2$$$. We can transform $$$[3,3,2,1]$$$ into $$$[1,2,3,3]$$$ with two operations with $$$(i,j)=(1,4)$$$ and $$$(i,j)=(2,3)$$$ respectively.
Java 11
standard input
[ "constructive algorithms", "graphs", "greedy" ]
01703877719e19dd8551e4599c3e1c85
Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$)  — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$)  — the length of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$)  — elements of the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
2,000
For each test case, print $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ — describing the array $$$b$$$. If there are multiple answers, you may print any.
standard output
PASSED
8a0fce71e991dd8f0ec5f86b95676723
train_108.jsonl
1650722700
oolimry has an array $$$a$$$ of length $$$n$$$ which he really likes. Today, you have changed his array to $$$b$$$, a permutation of $$$a$$$, to make him sad.Because oolimry is only a duck, he can only perform the following operation to restore his array: Choose two integers $$$i,j$$$ such that $$$1 \leq i,j \leq n$$$. Swap $$$b_i$$$ and $$$b_j$$$. The sadness of the array $$$b$$$ is the minimum number of operations needed to transform $$$b$$$ into $$$a$$$.Given the array $$$a$$$, find any array $$$b$$$ which is a permutation of $$$a$$$ that has the maximum sadness over all permutations of the array $$$a$$$.
256 megabytes
/** * @description: 比赛 * @author: dzx * @date: 2022/4/20 */ import java.io.*; import java.util.*; public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastScanner in = new FastScanner(inputStream); FastPrinter out = new FastPrinter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { public void solve(int testNumber, FastScanner in, FastPrinter out) { int t = in.nextInt(); while (t-- > 0) { int n = in.nextInt(); int[][] a = new int[n][2]; Map<Integer, Integer> map = new HashMap<>(); for (int i = 0; i < n; i++) { a[i][0] = in.nextInt(); a[i][1] = i; map.put(a[i][0], map.getOrDefault(a[i][0], 0) + 1); } int max = 0, maxIdx = 0; for (Map.Entry<Integer, Integer> entry : map.entrySet()) { if (entry.getValue() > max) { maxIdx = entry.getKey(); max = entry.getValue(); } } Arrays.sort(a,(x,y)->{ if(x!=y) return x[0] - y[0]; return x[1] - y[1]; }); int[] ans = new int[n]; for (int i = 0; i < n; i++) { ans[a[(i+max)%n][1]] = a[i][0]; } StringBuffer sb = new StringBuffer(); for (int i = 0; i < n; i++) { sb.append(ans[i]).append(" "); } System.out.println(sb); } } } static class ru_ifmo_niyaz_arrayutils_ArrayUtils { static final long seed = System.nanoTime(); static final Random rand = new Random(seed); public static void sort(int[] a) { shuffle(a); Arrays.sort(a); } public static void shuffle(int[] a) { for (int i = 0; i < a.length; i++) { int j = rand.nextInt(i + 1); int t = a[i]; a[i] = a[j]; a[j] = t; } } } static class FastPrinter extends PrintWriter { public FastPrinter(OutputStream out) { super(out); } public FastPrinter(Writer out) { super(out); } } static class net_egork_misc_ArrayUtils { public static long sumArray(int[] array) { long result = 0; for (int element : array) result += element; return result; } } static class FastScanner extends BufferedReader { public FastScanner(InputStream is) { super(new InputStreamReader(is)); } public int read() { try { int ret = super.read(); // if (isEOF && ret < 0) { // throw new InputMismatchException(); // } // isEOF = ret == -1; return ret; } catch (IOException e) { throw new InputMismatchException(); } } public String next() { StringBuilder sb = new StringBuilder(); int c = read(); while (isWhiteSpace(c)) { c = read(); } if (c < 0) { return null; } while (c >= 0 && !isWhiteSpace(c)) { sb.appendCodePoint(c); c = read(); } return sb.toString(); } static boolean isWhiteSpace(int c) { return c >= 0 && c <= 32; } public int nextInt() { int c = read(); while (isWhiteSpace(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int ret = 0; while (c >= 0 && !isWhiteSpace(c)) { if (c < '0' || c > '9') { throw new NumberFormatException("digit expected " + (char) c + " found"); } ret = ret * 10 + c - '0'; c = read(); } return ret * sgn; } public long nextLong() { return Long.parseLong(next()); } public String readLine() { try { return super.readLine(); } catch (IOException e) { return null; } } public int[] readIntArray(int n) { int[] ret = new int[n]; for (int i = 0; i < n; i++) { ret[i] = nextInt(); } return ret; } } }
Java
["2\n\n2\n\n2 1\n\n4\n\n1 2 3 3"]
1 second
["1 2\n3 3 2 1"]
NoteIn the first test case, the array $$$[1,2]$$$ has sadness $$$1$$$. We can transform $$$[1,2]$$$ into $$$[2,1]$$$ using one operation with $$$(i,j)=(1,2)$$$.In the second test case, the array $$$[3,3,2,1]$$$ has sadness $$$2$$$. We can transform $$$[3,3,2,1]$$$ into $$$[1,2,3,3]$$$ with two operations with $$$(i,j)=(1,4)$$$ and $$$(i,j)=(2,3)$$$ respectively.
Java 11
standard input
[ "constructive algorithms", "graphs", "greedy" ]
01703877719e19dd8551e4599c3e1c85
Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$)  — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$)  — the length of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$)  — elements of the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
2,000
For each test case, print $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ — describing the array $$$b$$$. If there are multiple answers, you may print any.
standard output
PASSED
fba7127ba3286e0c6e4d887ef0826fa7
train_108.jsonl
1650722700
oolimry has an array $$$a$$$ of length $$$n$$$ which he really likes. Today, you have changed his array to $$$b$$$, a permutation of $$$a$$$, to make him sad.Because oolimry is only a duck, he can only perform the following operation to restore his array: Choose two integers $$$i,j$$$ such that $$$1 \leq i,j \leq n$$$. Swap $$$b_i$$$ and $$$b_j$$$. The sadness of the array $$$b$$$ is the minimum number of operations needed to transform $$$b$$$ into $$$a$$$.Given the array $$$a$$$, find any array $$$b$$$ which is a permutation of $$$a$$$ that has the maximum sadness over all permutations of the array $$$a$$$.
256 megabytes
//Utilities import java.io.*; import java.util.*; public class a { static int t; static int n; static int[] a, res; public static void main(String[] args) throws IOException { t = in.iscan(); while (t-- > 0) { n = in.iscan(); a = new int[n]; res = new int[n]; Stack<Integer>[] idxStack = new Stack[n+1]; for (int i = 0; i <= n; i++) { idxStack[i] = new Stack<Integer>(); } for (int i = 0; i < n; i++) { a[i] = in.iscan(); res[i] = a[i]; idxStack[a[i]].push(i); } ArrayList<Integer> arr = new ArrayList<Integer>(); for (int i = 1; i <= n; i++) { if (idxStack[i].size() >= 1) { arr.add(i); } } while (arr.size() > 1) { int sz = arr.size(); ArrayList<Integer> newArr = new ArrayList<Integer>(); for (int i = 0; i < sz; i++) { int cur = idxStack[arr.get(i)].pop(); if (i < sz-1) { res[cur] = arr.get(i+1); } else { res[cur] = arr.get(0); } if (!idxStack[arr.get(i)].isEmpty()) { newArr.add(arr.get(i)); } } arr = new ArrayList<Integer>(newArr); } for (int i = 0; i < n; i++) { out.print(res[i] + " "); } out.println(); } 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
["2\n\n2\n\n2 1\n\n4\n\n1 2 3 3"]
1 second
["1 2\n3 3 2 1"]
NoteIn the first test case, the array $$$[1,2]$$$ has sadness $$$1$$$. We can transform $$$[1,2]$$$ into $$$[2,1]$$$ using one operation with $$$(i,j)=(1,2)$$$.In the second test case, the array $$$[3,3,2,1]$$$ has sadness $$$2$$$. We can transform $$$[3,3,2,1]$$$ into $$$[1,2,3,3]$$$ with two operations with $$$(i,j)=(1,4)$$$ and $$$(i,j)=(2,3)$$$ respectively.
Java 11
standard input
[ "constructive algorithms", "graphs", "greedy" ]
01703877719e19dd8551e4599c3e1c85
Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$)  — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$)  — the length of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$)  — elements of the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
2,000
For each test case, print $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ — describing the array $$$b$$$. If there are multiple answers, you may print any.
standard output
PASSED
0196100b5d9911826227db21c0f1d84b
train_108.jsonl
1650722700
oolimry has an array $$$a$$$ of length $$$n$$$ which he really likes. Today, you have changed his array to $$$b$$$, a permutation of $$$a$$$, to make him sad.Because oolimry is only a duck, he can only perform the following operation to restore his array: Choose two integers $$$i,j$$$ such that $$$1 \leq i,j \leq n$$$. Swap $$$b_i$$$ and $$$b_j$$$. The sadness of the array $$$b$$$ is the minimum number of operations needed to transform $$$b$$$ into $$$a$$$.Given the array $$$a$$$, find any array $$$b$$$ which is a permutation of $$$a$$$ that has the maximum sadness over all permutations of the array $$$a$$$.
256 megabytes
//some updates in import stuff import static java.lang.Math.max; import static java.lang.Math.min; import static java.lang.Math.abs; import java.util.*; import java.io.*; import java.math.*; //key points learned //max space ever that could be alloted in a program to pass in cf //int[][] prefixSum = new int[201][200_005]; -> not a single array more!!! //never allocate memory again again to such bigg array, it will give memory exceeded for sure //believe in your fucking solution and keep improving it!!! (sometimes) //few things to figure around //getting better and faster at taking input/output with normal method (buffered reader and printwriter) //memorise all the key algos! a public class Main{ static int mod = (int) (Math.pow(10, 9)+7); static final int dx[] = { -1, 0, 1, 0 }, dy[] = { 0, -1, 0, 1 }; static final int[] dx8 = { -1, -1, -1, 0, 0, 1, 1, 1 }, dy8 = { -1, 0, 1, -1, 1, -1, 0, 1 }; static final int[] dx9 = { -1, -1, -1, 0, 0, 0, 1, 1, 1 }, dy9 = { -1, 0, 1, -1, 0, 1, -1, 0, 1 }; static final double eps = 1e-10; static List<Integer> primeNumbers = new ArrayList<>(); public static void main(String[] args) { MyScanner sc = new MyScanner(); //pretty important for sure - out = new PrintWriter(new BufferedOutputStream(System.out)); //dope shit output for sure //code here int test = sc.nextInt(); while(test--> 0){ int n = sc.nextInt(); //only further random practise should be left! (nothing more nothing less boi) int[] arr = new int[n]; int[] count = new int[n + 1]; Map<Integer, ArrayList<Integer>> map = new HashMap<>(); for(int i = 0; i < n;i ++){ arr[i] = sc.nextInt(); map.putIfAbsent(arr[i], new ArrayList<>()); map.get(arr[i]).add(i); //no worries keep coding bruh!! (not out main target for sure) count[arr[i]]++; } int val = -1; int size = -1; for(int i= 1; i <= n; i++){ if(count[i] > size){ val = i; size = count[i]; } } //study cause this is literally the last month! (you have for google!) //now make some arraylist and arraylist ArrayList<ArrayList<Integer>> storage = new ArrayList<>(); while(map.size() > 1){ ArrayList<Integer> list = new ArrayList<>(); //now move through all of them, pick one and remove one! //concurrent shit is happening, damn!! (think of some cool logic) ArrayList<Integer> rem = new ArrayList<>(); for(int value : map.keySet()){ ArrayList<Integer> temp = map.get(value); if(temp.size() == 0) { rem.add(value); continue; } list.add(temp.remove(temp.size() - 1)); } //simply remove them afterwards bois! - pretty dope for(int re : rem){ map.remove(re); } if(list.size() <= 1) break; storage.add(list); } //simplye output storage for now // out.println(storage); int[] ans = new int[n]; Arrays.fill(ans, -1); //pretty dope idea for sure! (think about it bois!) for(List<Integer> list : storage){ for(int i= 0; i < list.size()-1; i++){ int u = list.get(i); int v = list.get(i + 1); ans[u] = arr[v]; } ans[list.get(list.size() - 1)] = arr[list.get(0)]; } //after this fill the array whereever it is -1 for(int i = 0; i < n; i++){ if(ans[i] == -1){ ans[i] = arr[i]; } } for(int i : ans){ out.print(i + " "); } out.println(); } out.close(); } //new stuff to learn (whenever this is need for them, then only) //Lazy Segment Trees //Persistent Segment Trees //Square Root Decomposition //Geometry & Convex Hull //High Level DP -- yk yk //String Matching Algorithms //Heavy light Decomposition //Updation Required //Fenwick Tree - both are done (sum) //Segment Tree - both are done (min, max, sum) //-----CURRENTLY PRESENT-------// //Graph //DSU //powerMODe //power //Segment Tree (work on this one) //Prime Sieve //Count Divisors //Next Permutation //Get NCR //isVowel //Sort (int) //Sort (long) //Binomial Coefficient //Pair //Triplet //lcm (int & long) //gcd (int & long) //gcd (for binomial coefficient) //swap (int & char) //reverse //primeExponentCounts //Fast input and output //------------------------------------------------------------------- //------------------------------------------------------------------- //------------------------------------------------------------------- //------------------------------------------------------------------- //------------------------------------------------------------------- //GRAPH (basic structure) public static class Graph{ public int V; public ArrayList<ArrayList<Integer>> edges; //2 -> [0,1,2] (current) Graph(int V){ this.V = V; edges = new ArrayList<>(V+1); for(int i= 0; i <= V; i++){ edges.add(new ArrayList<>()); } } public void addEdge(int from , int to){ edges.get(from).add(to); edges.get(to).add(from); } } //DSU (path and rank optimised) public static class DisjointUnionSets { int[] rank, parent; int n; public DisjointUnionSets(int n) { rank = new int[n]; parent = new int[n]; Arrays.fill(rank, 1); Arrays.fill(parent,-1); this.n = n; } public int find(int curr){ if(parent[curr] == -1) return curr; //path compression optimisation return parent[curr] = find(parent[curr]); } public void union(int a, int b){ int s1 = find(a); int s2 = find(b); if(s1 != s2){ //union by size if(rank[s1] < rank[s2]){ parent[s1] = s2; rank[s2] += rank[s1]; }else{ parent[s2] = s1; rank[s1] += rank[s2]; } } } } //with mod public static long powerMOD(long x, long y) { long res = 1L; while (y > 0) { // If y is odd, multiply x with result if ((y & 1) != 0){ x %= mod; res %= mod; res = (res * x)%mod; } // y must be even now y = y >> 1; // y = y/2 x%= mod; x = (x * x)%mod; // Change x to x^2 } return res%mod; } //without mod public static long power(long x, long y) { long res = 1L; 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/ x = (x * x); } return res; } public static class segmentTree{ //so let's make a constructor function for this bad boi for sure!!! public long[] arr; public long[] tree; //COMPLEXITY (normal segment tree, stuff) //build -> O(n) //query -> O(logn) //update -> O(logn) //update-range -> O(n) (worst case) //simple iteration and stuff for sure public segmentTree(long[] arr){ int n = arr.length; this.arr = new long[n]; for(int i= 0; i < n; i++){ this.arr[i] = arr[i]; } tree = new long[4*n + 1]; } //pretty basic idea if you read the code once //first make child node once //then form the parent node using them public void buildTree(int s, int e, int index){ if(s == e){ tree[index] = arr[s]; return; } //recursive case int mid = (s + e)/2; buildTree(s, mid, 2 * index); buildTree(mid + 1, e, 2*index + 1); //the condition we want from children be like this tree[index] = min(tree[2 * index], tree[2 * index + 1]); return; } //definitely index based 0 query!!! //only int index = 1!! //baaki everything is simple as fuck public long query(int s, int e, int qs , int qe, int index){ //complete overlap if(s >= qs && e <= qe){ return tree[index]; } //no overlap if(qe < s || qs > e){ return Long.MAX_VALUE; } //partial overlap int mid = (s + e)/2; long left = query( s, mid , qs, qe, 2*index); long right = query( mid + 1, e, qs, qe, 2*index + 1); return min(left, right); } //gonna do range updates for sure now!! //let's do this bois!!! (solve this problem for sure) public void updateRange(int s, int e, int l, int r, long increment, int index){ //out of bounds if(l > e || r < s){ return; } //leaf node if(s == e){ tree[index] += increment; return; //behnchoda return tera baap krvayege? } //recursive case int mid = (s + e)/2; updateRange(s, mid, l, r, increment, 2 * index); updateRange(mid + 1, e, l, r, increment, 2 * index + 1); tree[index] = min(tree[2 * index], tree[2 * index + 1]); } } public static class segmentTreeLazy{ //so let's make a constructor function for this bad boi for sure!!! public long[] arr; public long[] tree; public long[] lazy; //COMPLEXITY (normal segment tree, stuff) //build -> O(n) //query-range -> O(logn) //lazy update-range -> O(logn) (imp) //simple iteration and stuff for sure public segmentTreeLazy(long[] arr){ int n = arr.length; this.arr = new long[n]; for(int i= 0; i < n; i++){ this.arr[i] = arr[i]; } tree = new long[4*n + 1]; lazy = new long[1000000]; //pretty big for no inconvenience (no?) NONONONOONON! NO fucker NO! } //pretty basic idea if you read the code once //first make child node once //then form the parent node using them public void buildTree(int s, int e, int index){ if(s == e){ tree[index] = arr[s]; return; } //recursive case int mid = (s + e)/2; buildTree(s, mid, 2 * index); buildTree(mid + 1, e, 2*index + 1); //the condition we want from children be like this tree[index] = min(tree[2 * index], tree[2 * index + 1]); return; } //definitely index based 0 query!!! //only int index = 1!! //baaki everything is simple as fuck public long queryLazy(int s, int e, int qs, int qe, int index){ //before going down resolve if it exist if(lazy[index] != 0){ tree[index] += lazy[index]; //non leaf node if(s != e){ lazy[2*index] += lazy[index]; lazy[2*index + 1] += lazy[index]; } lazy[index] = 0; //clear the lazy value at current node for sure } //no overlap if(s > qe || e < qs){ return Long.MAX_VALUE; } //complete overlap if(s >= qs && e <= qe){ return tree[index]; } //partial overlap int mid = (s + e)/2; long left = queryLazy(s, mid, qs, qe, 2 * index); long right = queryLazy(mid + 1, e, qs, qe, 2 * index + 1); return Math.min(left, right); } //update range in O(logn) -- using lazy array public void updateRangeLazy(int s, int e, int l, int r, int inc, int index){ //before going down resolve if it exist if(lazy[index] != 0){ tree[index] += lazy[index]; //non leaf node if(s != e){ lazy[2*index] += lazy[index]; lazy[2*index + 1] += lazy[index]; } lazy[index] = 0; //clear the lazy value at current node for sure } //no overlap if(s > r || l > e){ return; } //another case if(l <= s && e <= r){ tree[index] += inc; //create a new lazy value for children node if(s != e){ lazy[2*index] += inc; lazy[2*index + 1] += inc; } return; } //recursive case int mid = (s + e)/2; updateRangeLazy(s, mid, l, r, inc, 2*index); updateRangeLazy(mid + 1, e, l, r, inc, 2*index + 1); //update the tree index tree[index] = Math.min(tree[2*index], tree[2*index + 1]); return; } } //prime sieve public static void primeSieve(int n){ BitSet bitset = new BitSet(n+1); for(long i = 0; i < n ; i++){ if (i == 0 || i == 1) { bitset.set((int) i); continue; } if(bitset.get((int) i)) continue; primeNumbers.add((int)i); for(long j = i; j <= n ; j+= i) bitset.set((int)j); } } //number of divisors public static int countDivisors(long number){ if(number == 1) return 1; List<Integer> primeFactors = new ArrayList<>(); int index = 0; long curr = primeNumbers.get(index); while(curr * curr <= number){ while(number % curr == 0){ number = number/curr; primeFactors.add((int) curr); } index++; curr = primeNumbers.get(index); } if(number != 1) primeFactors.add((int) number); int current = primeFactors.get(0); int totalDivisors = 1; int currentCount = 2; for (int i = 1; i < primeFactors.size(); i++) { if (primeFactors.get(i) == current) { currentCount++; } else { totalDivisors *= currentCount; currentCount = 2; current = primeFactors.get(i); } } totalDivisors *= currentCount; return totalDivisors; } //primeExponentCounts public static int primeExponentsCount(int n) { if (n <= 1) return 0; int sqrt = (int) Math.sqrt(n); int remainingNumber = n; int result = 0; for (int i = 2; i <= sqrt; i++) { while (remainingNumber % i == 0) { result++; remainingNumber /= i; } } //in case of prime numbers this would happen if (remainingNumber > 1) { result++; } return result; } //now adding next permutation function to java hehe public static boolean next_permutation(int[] p) { for (int a = p.length - 2; a >= 0; --a) if (p[a] < p[a + 1]) for (int b = p.length - 1;; --b) if (p[b] > p[a]) { int t = p[a]; p[a] = p[b]; p[b] = t; for (++a, b = p.length - 1; a < b; ++a, --b) { t = p[a]; p[a] = p[b]; p[b] = t; } return true; } return false; } //finding the value of NCR in O(RlogN) time and O(1) space public static long getNcR(int n, int r) { long p = 1, k = 1; if (n - r < r) r = n - r; if (r != 0) { while (r > 0) { p *= n; k *= r; long m = __gcd(p, k); p /= m; k /= m; n--; r--; } } else { p = 1; } return p; } //is vowel function public static boolean isVowel(char c) { return (c=='a' || c=='A' || c=='e' || c=='E' || c=='i' || c=='I' || c=='o' || c=='O' || c=='u' || c=='U'); } //to sort the array with better method public static void sort(int[] a) { ArrayList<Integer> l=new ArrayList<>(); for (int i:a) l.add(i); Collections.sort(l); for (int i=0; i<a.length; i++) a[i]=l.get(i); } //sort long public static void sort(long[] a) { ArrayList<Long> l=new ArrayList<>(); for (long i:a) l.add(i); Collections.sort(l); for (int i=0; i<a.length; i++) a[i]=l.get(i); } //for calculating binomialCoeff public static int binomialCoeff(int n, int k) { int C[] = new int[k + 1]; // nC0 is 1 C[0] = 1; for (int i = 1; i <= n; i++) { // Compute next row of pascal // triangle using the previous row for (int j = Math.min(i, k); j > 0; j--) C[j] = C[j] + C[j - 1]; } return C[k]; } //Pair with int int public static class Pair{ public int a; public int b; public int hashCode; Pair(int a , int b){ this.a = a; this.b = b; this.hashCode = Objects.hash(a, b); } @Override public String toString(){ return a + " -> " + b; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Pair that = (Pair) o; return a == that.a && b == that.b; } @Override public int hashCode() { return this.hashCode; } } //Triplet with int int int public static class Triplet{ public int a; public int b; public int c; Triplet(int a , int b, int c){ this.a = a; this.b = b; this.c = c; } @Override public String toString(){ return a + " -> " + b; } } //Shortcut function public static long lcm(long a , long b){ return a * (b/gcd(a,b)); } //let's make one for calculating lcm basically public static int lcm(int a , int b){ return (a * b)/gcd(a,b); } //int version for gcd public static int gcd(int a, int b){ if(b == 0) return a; return gcd(b , a%b); } //long version for gcd public static long gcd(long a, long b){ if(b == 0) return a; return gcd(b , a%b); } //for ncr calculator(ignore this code) public static long __gcd(long n1, long n2) { long gcd = 1; for (int i = 1; i <= n1 && i <= n2; ++i) { // Checks if i is factor of both integers if (n1 % i == 0 && n2 % i == 0) { gcd = i; } } return gcd; } //swapping two elements in an array public static void swap(int[] arr, int left , int right){ int temp = arr[left]; arr[left] = arr[right]; arr[right] = temp; } //for char array public static void swap(char[] arr, int left , int right){ char temp = arr[left]; arr[left] = arr[right]; arr[right] = temp; } //reversing an array public static void reverse(int[] arr){ int left = 0; int right = arr.length-1; while(left <= right){ swap(arr, left,right); left++; right--; } } public static long expo(long a, long b, long mod) { long res = 1; while (b > 0) { if ((b & 1) == 1L) res = (res * a) % mod; //think about this one for a second a = (a * a) % mod; b = b >> 1; } return res; } //SOME EXTRA DOPE FUNCTIONS public static long mminvprime(long a, long b) { return expo(a, b - 2, b); } public static long mod_add(long a, long b, long m) { a = a % m; b = b % m; return (((a + b) % m) + m) % m; } public static long mod_sub(long a, long b, long m) { a = a % m; b = b % m; return (((a - b) % m) + m) % m; } public static long mod_mul(long a, long b, long m) { a = a % m; b = b % m; return (((a * b) % m) + m) % m; } public static long mod_div(long a, long b, long m) { a = a % m; b = b % m; return (mod_mul(a, mminvprime(b, m), m) + m) % m; } //O(n) every single time remember that public static long nCr(long N, long K , long mod){ long upper = 1L; long lower = 1L; long lowerr = 1L; for(long i = 1; i <= N; i++){ upper = mod_mul(upper, i, mod); } for(long i = 1; i <= K; i++){ lower = mod_mul(lower, i, mod); } for(long i = 1; i <= (N - K); i++){ lowerr = mod_mul(lowerr, i, mod); } // out.println(upper + " " + lower + " " + lowerr); long answer = mod_mul(lower, lowerr, mod); answer = mod_div(upper, answer, mod); return answer; } // long[] fact = new long[2 * n + 1]; // long[] ifact = new long[2 * n + 1]; // fact[0] = 1; // ifact[0] = 1; // for (long i = 1; i <= 2 * n; i++) // { // fact[(int)i] = mod_mul(fact[(int)i - 1], i, mod); // ifact[(int)i] = mminvprime(fact[(int)i], mod); // } //ifact is basically inverse factorial in here!!!!!(imp) public static long combination(long n, long r, long m, long[] fact, long[] ifact) { long val1 = fact[(int)n]; long val2 = ifact[(int)(n - r)]; long val3 = ifact[(int)r]; return (((val1 * val2) % m) * val3) % m; } //-----------PrintWriter for faster output--------------------------------- public static PrintWriter out; //-----------MyScanner class for faster input---------- public static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine(){ String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } //-------------------------------------------------------- }
Java
["2\n\n2\n\n2 1\n\n4\n\n1 2 3 3"]
1 second
["1 2\n3 3 2 1"]
NoteIn the first test case, the array $$$[1,2]$$$ has sadness $$$1$$$. We can transform $$$[1,2]$$$ into $$$[2,1]$$$ using one operation with $$$(i,j)=(1,2)$$$.In the second test case, the array $$$[3,3,2,1]$$$ has sadness $$$2$$$. We can transform $$$[3,3,2,1]$$$ into $$$[1,2,3,3]$$$ with two operations with $$$(i,j)=(1,4)$$$ and $$$(i,j)=(2,3)$$$ respectively.
Java 11
standard input
[ "constructive algorithms", "graphs", "greedy" ]
01703877719e19dd8551e4599c3e1c85
Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$)  — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$)  — the length of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$)  — elements of the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
2,000
For each test case, print $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ — describing the array $$$b$$$. If there are multiple answers, you may print any.
standard output
PASSED
af5e3d1cb87035cbf3d1396d576f456f
train_108.jsonl
1650722700
oolimry has an array $$$a$$$ of length $$$n$$$ which he really likes. Today, you have changed his array to $$$b$$$, a permutation of $$$a$$$, to make him sad.Because oolimry is only a duck, he can only perform the following operation to restore his array: Choose two integers $$$i,j$$$ such that $$$1 \leq i,j \leq n$$$. Swap $$$b_i$$$ and $$$b_j$$$. The sadness of the array $$$b$$$ is the minimum number of operations needed to transform $$$b$$$ into $$$a$$$.Given the array $$$a$$$, find any array $$$b$$$ which is a permutation of $$$a$$$ that has the maximum sadness over all permutations of the array $$$a$$$.
256 megabytes
import java.util.*; /* 6 4 3 4 3 6 6 */ public class F1 { static Scanner sc = new Scanner(System.in); public static void main(String[] args) { // TODO Auto-generated method stub int testCases = sc.nextInt(); for (int i = 1; i <= testCases; ++i) { solve(i); } } private static void solve(int t) { int n = sc.nextInt(); int [] arr = new int [n]; for (int i = 0; i < n; ++i) { arr[i] = sc.nextInt(); } int [][] arr2 = new int [arr.length][2]; Map<Integer, Integer> map = new HashMap<>(); for (int i = 0; i < arr.length; ++i) { arr2[i][0] = arr[i]; arr2[i][1] = i; map.put(arr[i], map.getOrDefault(arr[i],0 ) + 1); } int [][] arr3 = new int [arr.length][2]; Arrays.sort(arr2, (a , b) -> map.get(b[0]).intValue() == map.get(a[0]).intValue() ? a[0] - b[0] : map.get(b[0]) - map.get(a[0]) ); int idx = 0; while (idx < arr.length && arr2[0][0] == arr2[idx][0]) { ++idx; } for (int i = 0, j = idx; i < arr.length; ++i, ++j) { j %= arr.length; arr3[j][0] = arr2[i][0]; arr3[j][1] = arr2[j][1]; } int [] res = new int [arr.length]; for (int [] a : arr3) res[a[1]] = a[0]; StringBuilder sb = new StringBuilder(); for (int num : res) { sb.append(num); sb.append(' '); } System.out.println(sb); } public static void print(int test, long result) { System.out.println("Case #" + test + ": " + result); } }
Java
["2\n\n2\n\n2 1\n\n4\n\n1 2 3 3"]
1 second
["1 2\n3 3 2 1"]
NoteIn the first test case, the array $$$[1,2]$$$ has sadness $$$1$$$. We can transform $$$[1,2]$$$ into $$$[2,1]$$$ using one operation with $$$(i,j)=(1,2)$$$.In the second test case, the array $$$[3,3,2,1]$$$ has sadness $$$2$$$. We can transform $$$[3,3,2,1]$$$ into $$$[1,2,3,3]$$$ with two operations with $$$(i,j)=(1,4)$$$ and $$$(i,j)=(2,3)$$$ respectively.
Java 11
standard input
[ "constructive algorithms", "graphs", "greedy" ]
01703877719e19dd8551e4599c3e1c85
Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$)  — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$)  — the length of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$)  — elements of the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
2,000
For each test case, print $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ — describing the array $$$b$$$. If there are multiple answers, you may print any.
standard output
PASSED
91cfd7879de72e1bc92c71f516e374f9
train_108.jsonl
1650722700
oolimry has an array $$$a$$$ of length $$$n$$$ which he really likes. Today, you have changed his array to $$$b$$$, a permutation of $$$a$$$, to make him sad.Because oolimry is only a duck, he can only perform the following operation to restore his array: Choose two integers $$$i,j$$$ such that $$$1 \leq i,j \leq n$$$. Swap $$$b_i$$$ and $$$b_j$$$. The sadness of the array $$$b$$$ is the minimum number of operations needed to transform $$$b$$$ into $$$a$$$.Given the array $$$a$$$, find any array $$$b$$$ which is a permutation of $$$a$$$ that has the maximum sadness over all permutations of the array $$$a$$$.
256 megabytes
import java.io.*; import java.util.*; import java.util.concurrent.ThreadLocalRandom; import java.math.*; /** _ _ ( _) ( _) / / \\ / /\_\_ / / \\ / / | \ \ / / \\ / / |\ \ \ / / , \ , / / /| \ \ / / |\_ /| / / / \ \_\ / / |\/ _ '_| \ / / / \ \\ | / |/ 0 \0\ / | | \ \\ | |\| \_\_ / / | \ \\ | | |/ \.\ o\o) / \ | \\ \ | /\\`v-v / | | \\ | \/ /_| \\_| / | | \ \\ | | /__/_ - / ___ | | \ \\ \| [__] \_/ |_________ \ | \ () / [___] ( \ \ |\ | | // | [___] |\| \| / |/ /| [____] \ |/\ / / || ( \ [____ / ) _\ \ \ \| | || \ \ [_____| / / __/ \ / / // | \ [_____/ / / \ | \/ // | / '----| /=\____ _/ | / // __ / / | / ___/ _/\ \ | || (/-(/-\) / \ (/\/\)/ | / | / (/\/\) / / // _________/ / / \____________/ ( @author NTUDragons-Reborn */ public class C{ public static void main(String[] args) throws Exception { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); Task solver = new Task(); solver.solve(in, out); out.close(); } // main solver static class Task{ double eps= 0.00000001; static final int MAXN = 100005; static final int MOD= 998244353; // stores smallest prime factor for every number static int spf[] = new int[MAXN]; static boolean[] prime; Map<Integer,Set<Integer>> dp= new HashMap<>(); // Calculating SPF (Smallest Prime Factor) for every // number till MAXN. // Time Complexity : O(nloglogn) public 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; } } } void sieveOfEratosthenes(int n) { // Create a boolean array // "prime[0..n]" and // initialize all entries // it as true. A value in // prime[i] will finally be // false if i is Not a // prime, else true. prime= new boolean[n + 1]; for (int i = 0; i <= n; i++) prime[i] = true; for (int p = 2; p * p <= n; p++) { // If prime[p] is not changed, then it is a // prime if (prime[p] == true) { // Update all multiples of p for (int i = p * p; i <= n; i += p) prime[i] = false; } } } // A O(log n) function returning primefactorization // by dividing by smallest prime factor at every step public Set<Integer> getFactorization(int x) { if(dp.containsKey(x)) return dp.get(x); Set<Integer> ret = new HashSet<>(); while (x != 1) { if(spf[x]!=2) ret.add(spf[x]); x = x / spf[x]; } dp.put(x,ret); return ret; } // function to find first index >= x public int lowerIndex(List<Integer> arr, int n, int x) { int l = 0, h = n - 1; while (l <= h) { int mid = (l + h) / 2; if (arr.get(mid) >= x) h = mid - 1; else l = mid + 1; } return l; } public int lowerIndex(int[] arr, int n, int x) { int l = 0, h = n - 1; while (l <= h) { int mid = (l + h) / 2; if (arr[mid] >= x) h = mid - 1; else l = mid + 1; } return l; } // function to find last index <= y public int upperIndex(List<Integer> arr, int n, int y) { int l = 0, h = n - 1; while (l <= h) { int mid = (l + h) / 2; if (arr.get(mid) <= y) l = mid + 1; else h = mid - 1; } return h; } public int upperIndex(int[] arr, int n, int y) { int l = 0, h = n - 1; while (l <= h) { int mid = (l + h) / 2; if (arr[mid] <= y) l = mid + 1; else h = mid - 1; } return h; } // function to count elements within given range public int countInRange(List<Integer> arr, int n, int x, int y) { // initialize result int count = 0; count = upperIndex(arr, n, y) - lowerIndex(arr, n, x) + 1; return count; } public int add(int a, int b){ a+=b; while(a>=MOD) a-=MOD; while(a<0) a+=MOD; return a; } public int mul(int a, int b){ long res= (long)a*(long)b; return (int)(res%MOD); } public int power(int a, int b) { int ans=1; while(b>0){ if((b&1)!=0) ans= mul(ans,a); b>>=1; a= mul(a,a); } return ans; } int[] fact= new int[MAXN]; int[] inv= new int[MAXN]; public int Ckn(int n, int k){ if(k<0 || n<0) return 0; if(n<k) return 0; return mul(mul(fact[n],inv[k]),inv[n-k]); } public int inverse(int a){ return power(a,MOD-2); } public void preprocess() { fact[0]=1; for(int i=1;i<MAXN;i++) fact[i]= mul(fact[i-1],i); inv[MAXN-1]= inverse(fact[MAXN-1]); for(int i=MAXN-2;i>=0;i--){ inv[i]= mul(inv[i+1],i+1); } } /** * return VALUE of lower bound for unsorted array */ public int lowerBoundNormalArray(int[] arr, int x){ TreeSet<Integer> set= new TreeSet<>(); for(int num: arr) set.add(num); return set.lower(x); } /** * return VALUE of upper bound for unsorted array */ public int upperBoundNormalArray(int[] arr, int x){ TreeSet<Integer> set= new TreeSet<>(); for(int num: arr) set.add(num); return set.higher(x); } public void debugArr(int[] arr){ for(int i: arr) out.print(i+" "); out.println(); } public int rand(){ int min=0, max= MAXN; int random_int = (int)Math.floor(Math.random()*(max-min+1)+min); return random_int; } public void suffleSort(int[] arr){ shuffleArray(arr); Arrays.sort(arr); } public void shuffleArray(int[] ar) { // If running on Java 6 or older, use new Random() on RHS here Random rnd = ThreadLocalRandom.current(); for (int i = ar.length - 1; i > 0; i--) { int index = rnd.nextInt(i + 1); // Simple swap int a = ar[index]; ar[index] = ar[i]; ar[i] = a; } } InputReader in; PrintWriter out; Scanner sc= new Scanner(System.in); CustomFileReader cin; int[] xor= new int[3*100000+5]; int[] pow2= new int[1000000+1]; public void solve(InputReader in, PrintWriter out) throws Exception { this.in=in; this.out=out; // sieve(); // pow2[0]=1; // for(int i=1;i<pow2.length;i++){ // pow2[i]= mul(pow2[i-1],2); // } int t=in.nextInt(); // preprocess(); // int t=in.nextInt(); // int t= cin.nextIntArrLine()[0]; for(int i=1;i<=t;i++) solveF(i); } final double pi= Math.acos(-1); static Point base; void solveD(int test){ int n= in.nextInt(); int N= 2*100000+1; int[] a= in.nextIntArr(n); int[] b= in.nextIntArr(n); int[] cnt= new int[N]; int[] used= new int[N]; for(int i=0;i<n;i++) cnt[a[i]]++; int j= n-1; for(int i=n-1;i>=0;i--){ if(b[i]==a[j]){ cnt[b[i]]--; j--; } else{ if(j+1<n && a[j+1]==b[i] && cnt[b[i]]>0){ cnt[b[i]]--; used[b[i]]++; } else { if(used[a[j]]<=0) {out.println("NO"); return;} used[a[j]]--; j--; } } } out.println("YES"); } void solveF(int test) throws Exception{ int n= in.nextInt(); int[] a= in.nextIntArr(n); // Set<Integer> has= new HashSet<>(); // List<Integer> res= new ArrayList<>(); // List<Integer> temp= new ArrayList<>(); // for(int i=0;i<n;i++){ // if(has.contains(a[i])){ // has= new HashSet<>(); // if(temp.size()>0){ // for(int j=1;j<temp.size();++j){ // res.add(temp.get(j)); // } // res.add(temp.get(0)); // } // temp= new ArrayList<>(); // i--; // } // else{ // has.add(a[i]); // temp.add(a[i]); // } // } // if(temp.size()>0){ // for(int j=1;j<temp.size();++j){ // res.add(temp.get(j)); // } // res.add(temp.get(0)); // } // for(int i: res) out.print(i+" "); // if(res.size()!=n){ // throw new Exception(); // } // out.println(); Map<Integer,Queue<Integer>> idx= new HashMap<>(); Set<Integer> set= new HashSet<>(); for(int i=0;i<n;i++){ set.add(a[i]); if(!idx.containsKey(a[i])){ idx.put(a[i], new LinkedList<>()); } idx.get(a[i]).add(i); } List<Integer> vals= new ArrayList<>(); for(int i: set) vals.add(i); Collections.sort(vals); int[] res= new int[n]; boolean finish= true; do{ finish= true; List<Integer> index= new ArrayList<>(); for(Map.Entry<Integer,Queue<Integer>> entry: idx.entrySet()){ Queue<Integer> q= entry.getValue(); if(q.size()==0) continue; finish= false; index.add(q.poll()); } if(index.size()==0) break; int temp= a[index.get(0)]; for(int i=0;i<index.size()-1;i++){ res[index.get(i)]= a[index.get(i+1)]; } res[index.get(index.size()-1)]= temp; }while(!finish); for(int i: res) out.print(i+" "); out.println(); } static class ListNode{ int idx=-1; ListNode next= null; public ListNode(int idx){ this.idx= idx; } } public long _gcd(long a, long b) { if(b == 0) { return a; } else { return _gcd(b, a % b); } } public long _lcm(long a, long b){ return (a*b)/_gcd(a,b); } } // static class SEG { // Pair[] segtree; // public SEG(int n){ // segtree= new Pair[4*n]; // Arrays.fill(segtree, new Pair(-1,Long.MAX_VALUE)); // } // // void buildTree(int l, int r, int index) { // // if (l == r) { // // segtree[index].y = a[l]; // // return; // // } // // int mid = (l + r) / 2; // // buildTree(l, mid, 2 * index + 1); // // buildTree(mid + 1, r, 2 * index + 2); // // segtree[index].y = Math.min(segtree[2 * index + 1].y, segtree[2 * index + 2].y); // // } // void update(int l, int r, int index, int pos, Pair val) { // if (l == r) { // segtree[index] = val; // return; // } // int mid = (l + r) / 2; // if (pos <= mid) update(l, mid, 2 * index + 1, pos, val); // else update(mid + 1, r, 2 * index + 2, pos, val); // if(segtree[2 * index + 1].y < segtree[2 * index + 2].y){ // segtree[index]= segtree[2 * index + 1]; // } // else { // segtree[index]= segtree[2 * index + 2]; // } // } // // Pair query(int l, int r, int from, int to, int index) { // // if (from <= l && r <= to) // // return segtree[index]; // // if (r < from | to < l) // // return 0; // // int mid = (l + r) / 2; // // Pair left= query(l, mid, from, to, 2 * index + 1); // // Pair right= query(mid + 1, r, from, to, 2 * index + 2); // // if(left.y < right.y) return left; // // else return right; // // } // } static class Venice{ public Map<Long,Long> m= new HashMap<>(); public long base=0; public long totalValue=0; private int M= 1000000007; private long addMod(long a, long b){ a+=b; if(a>=M) a-=M; return a; } public void reset(){ m= new HashMap<>(); base=0; totalValue=0; } public void update(long add){ base= base+ add; } public void add(long key, long val){ long newKey= key-base; m.put(newKey, addMod(m.getOrDefault(newKey,(long)0),val)); } } static class Tuple implements Comparable<Tuple>{ int x, y, z; public Tuple(int x, int y, int z){ this.x= x; this.y= y; this.z=z; } @Override public int compareTo(Tuple o){ return this.z-o.z; } } static class Point implements Comparable<Point>{ public double x; public long y; public Point(double x, long y){ this.x= x; this.y= y; } @Override public int compareTo(Point o) { if(this.y!=o.y) return (int)(this.y-o.y); return (int)(this.x-o.x); } } // static class Vector { // public long x; // public long y; // // p1 -> p2 // public Vector(Point p1, Point p2){ // this.x= p2.x-p1.x; // this.y= p2.y-p1.y; // } // } 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 int compareTo(Pair o) { if(this.x!=o.x) return (int)(this.x-o.x); return (int)(this.y-o.y); } } // public static class compareL implements Comparator<Tuple>{ // @Override // public int compare(Tuple t1, Tuple t2) { // return t2.l - t1.l; // } // } // fast input reader class; static class InputReader { BufferedReader br; StringTokenizer st; public InputReader(InputStream stream) { br = new BufferedReader(new InputStreamReader(stream)); } public String nextToken() { while (st == null || !st.hasMoreTokens()) { String line = null; try { line = br.readLine(); } catch (IOException e) { throw new RuntimeException(e); } if (line == null) { return null; } st = new StringTokenizer(line); } return st.nextToken(); } public int nextInt() { return Integer.parseInt(nextToken()); } public double nextDouble(){ return Double.parseDouble(nextToken()); } public long nextLong(){ return Long.parseLong(nextToken()); } public int[] nextIntArr(int n){ int[] arr= new int[n]; for(int i=0;i<n;i++) arr[i]= nextInt(); return arr; } public long[] nextLongArr(int n){ long[] arr= new long[n]; for(int i=0;i<n;i++) arr[i]= nextLong(); return arr; } public List<Integer> nextIntList(int n){ List<Integer> arr= new ArrayList<>(); for(int i=0;i<n;i++) arr.add(nextInt()); return arr; } public int[][] nextIntMatArr(int n, int m){ int[][] mat= new int[n][m]; for(int i=0;i<n;i++) for(int j=0;j<m;j++) mat[i][j]= nextInt(); return mat; } public List<List<Integer>> nextIntMatList(int n, int m){ List<List<Integer>> mat= new ArrayList<>(); for(int i=0;i<n;i++){ List<Integer> temp= new ArrayList<>(); for(int j=0;j<m;j++) temp.add(nextInt()); mat.add(temp); } return mat; } public char[] nextStringCharArr(){ return nextToken().toCharArray(); } } static class CustomFileReader{ String path=""; Scanner sc; public CustomFileReader(String path){ this.path=path; try{ sc= new Scanner(new File(path)); } catch(Exception e){} } public String nextLine(){ return sc.nextLine(); } public int[] nextIntArrLine(){ String line= sc.nextLine(); String[] part= line.split("[\\s+]"); int[] res= new int[part.length]; for(int i=0;i<res.length;i++) res[i]= Integer.parseInt(part[i]); return res; } } }
Java
["2\n\n2\n\n2 1\n\n4\n\n1 2 3 3"]
1 second
["1 2\n3 3 2 1"]
NoteIn the first test case, the array $$$[1,2]$$$ has sadness $$$1$$$. We can transform $$$[1,2]$$$ into $$$[2,1]$$$ using one operation with $$$(i,j)=(1,2)$$$.In the second test case, the array $$$[3,3,2,1]$$$ has sadness $$$2$$$. We can transform $$$[3,3,2,1]$$$ into $$$[1,2,3,3]$$$ with two operations with $$$(i,j)=(1,4)$$$ and $$$(i,j)=(2,3)$$$ respectively.
Java 11
standard input
[ "constructive algorithms", "graphs", "greedy" ]
01703877719e19dd8551e4599c3e1c85
Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$)  — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$)  — the length of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$)  — elements of the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
2,000
For each test case, print $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ — describing the array $$$b$$$. If there are multiple answers, you may print any.
standard output
PASSED
2be29065606741f6c044bdf167574d8e
train_108.jsonl
1650722700
oolimry has an array $$$a$$$ of length $$$n$$$ which he really likes. Today, you have changed his array to $$$b$$$, a permutation of $$$a$$$, to make him sad.Because oolimry is only a duck, he can only perform the following operation to restore his array: Choose two integers $$$i,j$$$ such that $$$1 \leq i,j \leq n$$$. Swap $$$b_i$$$ and $$$b_j$$$. The sadness of the array $$$b$$$ is the minimum number of operations needed to transform $$$b$$$ into $$$a$$$.Given the array $$$a$$$, find any array $$$b$$$ which is a permutation of $$$a$$$ that has the maximum sadness over all permutations of the array $$$a$$$.
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 mod = (int) (1e9 + 7); final static int MAX = Integer.MAX_VALUE; final static int MIN = Integer.MIN_VALUE; final static long INF = Long.MAX_VALUE; final static long NEG_INF = Long.MIN_VALUE; 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(); Map<Integer, List<Integer>> map = new HashMap<>(); for (int i = 0; i < n; i++) { int x = readInt(); if (!map.containsKey(x)) map.put(x, new ArrayList<>()); map.get(x).add(i); } List<P> pq = new ArrayList<>(); for (int i : map.keySet()) pq.add(new P(i, map.get(i))); Collections.sort(pq); int[] arr = new int[n]; for (int p = 0; p < pq.size() - 1; p++) for (int i = 0; i < pq.get(p).idx.size(); i++) arr[pq.get(p + 1).idx.get(i)] = pq.get(p).val; int curr = 0; for (int i = 0; i < pq.get(pq.size() - 1).idx.size(); i++) { while (i == pq.get(curr).idx.size()) curr++; arr[pq.get(curr).idx.get(i)] = pq.get(pq.size() - 1).val; } printIArray(arr); } static class P implements Comparable<P> { int val; List<Integer> idx; P(int val, List<Integer> idx) { this.val = val; this.idx = idx; } public int compareTo(P o) { return this.idx.size() - o.idx.size(); } } private static void preprocess() throws IOException { } // cd C:\Users\Eshan Bhatt\Visual Studio Code\Competitive Programming\CodeForces // javac CodeForces.java // java CodeForces // javac CodeForces.java && java CodeForces // ==================== CUSTOM CLASSES ================================ static class 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(int n) 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(m); 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]); } // ====================== 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(int a, int 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 int multiply(int a, int b) { return (int) ((((1L * a) % mod) * ((1L * b) % mod)) % mod); } private static int divide(int a, int 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; } // ================== 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; } } // ==================== 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; } } // ==================== FENWICK TREE ================================ static class FT { long[] tree; int n; FT(int[] arr, int n) { this.n = n; this.tree = new long[n + 1]; for (int i = 1; i <= n; i++) { update(i, arr[i - 1]); } } void update(int idx, int val) { while (idx <= n) { tree[idx] += val; idx += idx & -idx; } } long query(int l, int r) { return getSum(r) - getSum(l - 1); } long getSum(int idx) { long ans = 0L; 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
["2\n\n2\n\n2 1\n\n4\n\n1 2 3 3"]
1 second
["1 2\n3 3 2 1"]
NoteIn the first test case, the array $$$[1,2]$$$ has sadness $$$1$$$. We can transform $$$[1,2]$$$ into $$$[2,1]$$$ using one operation with $$$(i,j)=(1,2)$$$.In the second test case, the array $$$[3,3,2,1]$$$ has sadness $$$2$$$. We can transform $$$[3,3,2,1]$$$ into $$$[1,2,3,3]$$$ with two operations with $$$(i,j)=(1,4)$$$ and $$$(i,j)=(2,3)$$$ respectively.
Java 11
standard input
[ "constructive algorithms", "graphs", "greedy" ]
01703877719e19dd8551e4599c3e1c85
Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$)  — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$)  — the length of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$)  — elements of the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
2,000
For each test case, print $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ — describing the array $$$b$$$. If there are multiple answers, you may print any.
standard output
PASSED
1e0150b57e9af17e14975f03483fa752
train_108.jsonl
1650722700
oolimry has an array $$$a$$$ of length $$$n$$$ which he really likes. Today, you have changed his array to $$$b$$$, a permutation of $$$a$$$, to make him sad.Because oolimry is only a duck, he can only perform the following operation to restore his array: Choose two integers $$$i,j$$$ such that $$$1 \leq i,j \leq n$$$. Swap $$$b_i$$$ and $$$b_j$$$. The sadness of the array $$$b$$$ is the minimum number of operations needed to transform $$$b$$$ into $$$a$$$.Given the array $$$a$$$, find any array $$$b$$$ which is a permutation of $$$a$$$ that has the maximum sadness over all permutations of the array $$$a$$$.
256 megabytes
import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.LinkedList; import java.util.Queue; import java.util.TreeMap; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; import java.util.Random; import java.io.FileWriter; import java.io.PrintWriter; /* Solution Created: 18:43:17 23/04/2022 Custom Competitive programming helper. */ public class Main { public static void solve() { int n = in.nextInt(); int[] a = in.na(n); TreeMap<Integer, Queue<Integer>> cyc = new TreeMap<>(); int[] ans = new int[n]; for(int i = 0; i<n; i++) { if(!cyc.containsKey(a[i])) cyc.put(a[i], new LinkedList<>()); cyc.get(a[i]).add(i); } while(!cyc.isEmpty()) { ArrayList<Integer> vals = new ArrayList<>(); ArrayList<Integer> idxs = new ArrayList<Integer>(); Integer i = cyc.firstKey(); vals.add(cyc.firstKey()); idxs.add(cyc.get(i).poll()); if(cyc.get(i).isEmpty()) cyc.remove(i); Integer nxt = cyc.higherKey(i); while(nxt != null) { vals.add(nxt); idxs.add(cyc.get(nxt).poll()); if(cyc.get(nxt).isEmpty()) cyc.remove(nxt); nxt = cyc.higherKey(nxt); } for(int j = 0; j<vals.size(); j++) { ans[idxs.get((j+1)%vals.size())] = vals.get(j); } } out.printlnArray(ans); } public static void main(String[] args) { in = new Reader(); out = new Writer(); int t = in.nextInt(); while (t-- > 0) solve(); out.exit(); } static Reader in; static Writer out; static class Reader { static BufferedReader br; static StringTokenizer st; public Reader() { this.br = new BufferedReader(new InputStreamReader(System.in)); } public Reader(String f){ try { this.br = new BufferedReader(new FileReader(f)); } catch (IOException e) { e.printStackTrace(); } } public int[] na(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public double[] nd(int n) { double[] a = new double[n]; for (int i = 0; i < n; i++) a[i] = nextDouble(); return a; } public long[] nl(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } public char[] nca() { return next().toCharArray(); } public String[] ns(int n) { String[] a = new String[n]; for (int i = 0; i < n; i++) a[i] = next(); return a; } public int nextInt() { ensureNext(); return Integer.parseInt(st.nextToken()); } public double nextDouble() { ensureNext(); return Double.parseDouble(st.nextToken()); } public Long nextLong() { ensureNext(); return Long.parseLong(st.nextToken()); } public String next() { ensureNext(); return st.nextToken(); } public String nextLine() { try { return br.readLine(); } catch (Exception e) { e.printStackTrace(); return null; } } private void ensureNext() { if (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } } } static class Util{ private static Random random = new Random(); static long[] fact; public static void initFactorial(int n, long mod) { fact = new long[n+1]; fact[0] = 1; for (int i = 1; i < n+1; i++) fact[i] = (fact[i - 1] * i) % mod; } public static long modInverse(long a, long MOD) { long[] gcdE = gcdExtended(a, MOD); if (gcdE[0] != 1) return -1; // Inverted doesn't exist long x = gcdE[1]; return (x % MOD + MOD) % MOD; } public static long[] gcdExtended(long p, long q) { if (q == 0) return new long[] { p, 1, 0 }; long[] vals = gcdExtended(q, p % q); long tmp = vals[2]; vals[2] = vals[1] - (p / q) * vals[2]; vals[1] = tmp; return vals; } public static long nCr(int n, int r, long MOD) { if (r == 0) return 1; return (fact[n] * modInverse(fact[r], MOD) % MOD * modInverse(fact[n - r], MOD) % MOD) % MOD; } public static long nCr(int n, int r) { return (fact[n]/fact[r])/fact[n-r]; } public static long nPr(int n, int r, long MOD) { if (r == 0) return 1; return (fact[n] * modInverse(fact[n - r], MOD) % MOD) % MOD; } public static long nPr(int n, int r) { return fact[n]/fact[n-r]; } public static boolean isPrime(int n) { if (n <= 1) return false; if (n <= 3) return true; if (n % 2 == 0 || n % 3 == 0) return false; for (int i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } public static boolean[] getSieve(int n) { boolean[] isPrime = new boolean[n+1]; for (int i = 2; i <= n; i++) isPrime[i] = true; for (int i = 2; i*i <= n; i++) if (isPrime[i]) for (int j = i; i*j <= n; j++) isPrime[i*j] = false; return isPrime; } static long pow(long x, long pow, long mod){ long res = 1; x = x % mod; if (x == 0) return 0; while (pow > 0){ if ((pow & 1) != 0) res = (res * x) % mod; pow >>= 1; x = (x * x) % mod; } return res; } public static int gcd(int a, int b) { int tmp = 0; while(b != 0) { tmp = b; b = a%b; a = tmp; } return a; } public static long gcd(long a, long b) { long tmp = 0; while(b != 0) { tmp = b; b = a%b; a = tmp; } return a; } public static int random(int min, int max) { return random.nextInt(max-min+1)+min; } public static void dbg(Object... o) { System.out.println(Arrays.deepToString(o)); } public static void reverse(int[] s, int l , int r) { for(int i = l; i<=(l+r)/2; i++) { int tmp = s[i]; s[i] = s[r+l-i]; s[r+l-i] = tmp; } } public static void reverse(int[] s) { reverse(s, 0, s.length-1); } public static void reverse(long[] s, int l , int r) { for(int i = l; i<=(l+r)/2; i++) { long tmp = s[i]; s[i] = s[r+l-i]; s[r+l-i] = tmp; } } public static void reverse(long[] s) { reverse(s, 0, s.length-1); } public static void reverse(float[] s, int l , int r) { for(int i = l; i<=(l+r)/2; i++) { float tmp = s[i]; s[i] = s[r+l-i]; s[r+l-i] = tmp; } } public static void reverse(float[] s) { reverse(s, 0, s.length-1); } public static void reverse(double[] s, int l , int r) { for(int i = l; i<=(l+r)/2; i++) { double tmp = s[i]; s[i] = s[r+l-i]; s[r+l-i] = tmp; } } public static void reverse(double[] s) { reverse(s, 0, s.length-1); } public static void reverse(char[] s, int l , int r) { for(int i = l; i<=(l+r)/2; i++) { char tmp = s[i]; s[i] = s[r+l-i]; s[r+l-i] = tmp; } } public static void reverse(char[] s) { reverse(s, 0, s.length-1); } public static <T> void reverse(T[] s, int l , int r) { for(int i = l; i<=(l+r)/2; i++) { T tmp = s[i]; s[i] = s[r+l-i]; s[r+l-i] = tmp; } } public static <T> void reverse(T[] s) { reverse(s, 0, s.length-1); } public static void shuffle(int[] s) { for (int i = 0; i < s.length; ++i) { int j = random.nextInt(i + 1); int t = s[i]; s[i] = s[j]; s[j] = t; } } public static void shuffle(long[] s) { for (int i = 0; i < s.length; ++i) { int j = random.nextInt(i + 1); long t = s[i]; s[i] = s[j]; s[j] = t; } } public static void shuffle(float[] s) { for (int i = 0; i < s.length; ++i) { int j = random.nextInt(i + 1); float t = s[i]; s[i] = s[j]; s[j] = t; } } public static void shuffle(double[] s) { for (int i = 0; i < s.length; ++i) { int j = random.nextInt(i + 1); double t = s[i]; s[i] = s[j]; s[j] = t; } } public static void shuffle(char[] s) { for (int i = 0; i < s.length; ++i) { int j = random.nextInt(i + 1); char t = s[i]; s[i] = s[j]; s[j] = t; } } public static <T> void shuffle(T[] s) { for (int i = 0; i < s.length; ++i) { int j = random.nextInt(i + 1); T t = s[i]; s[i] = s[j]; s[j] = t; } } public static void sortArray(int[] a) { shuffle(a); Arrays.sort(a); } public static void sortArray(long[] a) { shuffle(a); Arrays.sort(a); } public static void sortArray(float[] a) { shuffle(a); Arrays.sort(a); } public static void sortArray(double[] a) { shuffle(a); Arrays.sort(a); } public static void sortArray(char[] a) { shuffle(a); Arrays.sort(a); } public static <T extends Comparable<T>> void sortArray(T[] a) { Arrays.sort(a); } public static int[][] rotate90(int[][] a){ int n = a.length, m = a[0].length; int[][] ans = new int[m][n]; for(int i = 0; i<n; i++) for(int j = 0; j<m; j++) ans[m-j-1][i] = a[i][j]; return ans; } public static char[][] rotate90(char[][] a){ int n = a.length, m = a[0].length; char[][] ans = new char[m][n]; for(int i = 0; i<n; i++) for(int j = 0; j<m; j++) ans[m-j-1][i] = a[i][j]; return ans; } } static class Writer { private PrintWriter pw; public Writer(){ pw = new PrintWriter(System.out); } public Writer(String f){ try { pw = new PrintWriter(new FileWriter(f)); } catch (IOException e) { e.printStackTrace(); } } public void yesNo(boolean condition) { println(condition?"YES":"NO"); } public void printArray(int[] a) { for(int i = 0; i<a.length; i++) print(a[i]+" "); } public void printlnArray(int[] a) { for(int i = 0; i<a.length; i++) print(a[i]+" "); pw.println(); } public void printArray(long[] a) { for(int i = 0; i<a.length; i++) print(a[i]+" "); } public void printlnArray(long[] a) { for(int i = 0; i<a.length; i++) print(a[i]+" "); pw.println(); } public void print(Object o) { pw.print(o.toString()); } public void println(Object o) { pw.println(o.toString()); } public void println() { pw.println(); } public void flush() { pw.flush(); } public void exit() { pw.close(); } } }
Java
["2\n\n2\n\n2 1\n\n4\n\n1 2 3 3"]
1 second
["1 2\n3 3 2 1"]
NoteIn the first test case, the array $$$[1,2]$$$ has sadness $$$1$$$. We can transform $$$[1,2]$$$ into $$$[2,1]$$$ using one operation with $$$(i,j)=(1,2)$$$.In the second test case, the array $$$[3,3,2,1]$$$ has sadness $$$2$$$. We can transform $$$[3,3,2,1]$$$ into $$$[1,2,3,3]$$$ with two operations with $$$(i,j)=(1,4)$$$ and $$$(i,j)=(2,3)$$$ respectively.
Java 11
standard input
[ "constructive algorithms", "graphs", "greedy" ]
01703877719e19dd8551e4599c3e1c85
Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$)  — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$)  — the length of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$)  — elements of the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
2,000
For each test case, print $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ — describing the array $$$b$$$. If there are multiple answers, you may print any.
standard output
PASSED
b629267f8e92c9dd68d22caaaebfe575
train_108.jsonl
1650722700
oolimry has an array $$$a$$$ of length $$$n$$$ which he really likes. Today, you have changed his array to $$$b$$$, a permutation of $$$a$$$, to make him sad.Because oolimry is only a duck, he can only perform the following operation to restore his array: Choose two integers $$$i,j$$$ such that $$$1 \leq i,j \leq n$$$. Swap $$$b_i$$$ and $$$b_j$$$. The sadness of the array $$$b$$$ is the minimum number of operations needed to transform $$$b$$$ into $$$a$$$.Given the array $$$a$$$, find any array $$$b$$$ which is a permutation of $$$a$$$ that has the maximum sadness over all permutations of the array $$$a$$$.
256 megabytes
import java.io.*; import java.util.*; public class Codeforces { public static void main(String args[])throws Exception { BufferedReader bu=new BufferedReader(new InputStreamReader(System.in)); StringBuilder sb=new StringBuilder(); int t=Integer.parseInt(bu.readLine()); while(t-->0) { int n=Integer.parseInt(bu.readLine()); int i,a[]=new int[n]; String s[]=bu.readLine().split(" "); ArrayList<Integer> next[]=new ArrayList[n+1]; for(i=0;i<=n;i++) next[i]=new ArrayList<>(); for(i=0;i<n;i++) { a[i]=Integer.parseInt(s[i]); next[a[i]].add(i); } PriorityQueue<int[]> pq=new PriorityQueue<>(new Comparator<int[]>() { @Override public int compare(int[] o1, int[] o2) { if(o1[0]<o2[0]) return 1; else return -1; }}); for(i=1;i<=n;i++) if(next[i].size()>0) pq.add(new int[]{next[i].size(),i}); ArrayList<ArrayList<Integer>> cyc=new ArrayList<>(); int e[]=pq.poll(); for(int x:next[e[1]]) { ArrayList<Integer> te=new ArrayList<>(); te.add(x); cyc.add(te); } while(!pq.isEmpty()) { e=pq.poll(); int sz=next[e[1]].size(); for(i=0;i<sz;i++) cyc.get(i).add(next[e[1]].get(i)); } int ans[]=new int[n]; for(ArrayList<Integer> cy:cyc) { int sz=cy.size(); for(i=0;i<sz;i++) ans[cy.get(i)]=a[cy.get((i+1)%sz)]; } for(i=0;i<n;i++) sb.append(ans[i]+" "); sb.append("\n"); } System.out.print(sb); } }
Java
["2\n\n2\n\n2 1\n\n4\n\n1 2 3 3"]
1 second
["1 2\n3 3 2 1"]
NoteIn the first test case, the array $$$[1,2]$$$ has sadness $$$1$$$. We can transform $$$[1,2]$$$ into $$$[2,1]$$$ using one operation with $$$(i,j)=(1,2)$$$.In the second test case, the array $$$[3,3,2,1]$$$ has sadness $$$2$$$. We can transform $$$[3,3,2,1]$$$ into $$$[1,2,3,3]$$$ with two operations with $$$(i,j)=(1,4)$$$ and $$$(i,j)=(2,3)$$$ respectively.
Java 11
standard input
[ "constructive algorithms", "graphs", "greedy" ]
01703877719e19dd8551e4599c3e1c85
Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$)  — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$)  — the length of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$)  — elements of the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
2,000
For each test case, print $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ — describing the array $$$b$$$. If there are multiple answers, you may print any.
standard output
PASSED
aa6e3139b57230d69baf357781dda1bd
train_108.jsonl
1650722700
oolimry has an array $$$a$$$ of length $$$n$$$ which he really likes. Today, you have changed his array to $$$b$$$, a permutation of $$$a$$$, to make him sad.Because oolimry is only a duck, he can only perform the following operation to restore his array: Choose two integers $$$i,j$$$ such that $$$1 \leq i,j \leq n$$$. Swap $$$b_i$$$ and $$$b_j$$$. The sadness of the array $$$b$$$ is the minimum number of operations needed to transform $$$b$$$ into $$$a$$$.Given the array $$$a$$$, find any array $$$b$$$ which is a permutation of $$$a$$$ that has the maximum sadness over all permutations of the array $$$a$$$.
256 megabytes
import java.io.*; import java.util.*; import java.util.concurrent.ThreadLocalRandom; import java.math.*; /** _ _ ( _) ( _) / / \\ / /\_\_ / / \\ / / | \ \ / / \\ / / |\ \ \ / / , \ , / / /| \ \ / / |\_ /| / / / \ \_\ / / |\/ _ '_| \ / / / \ \\ | / |/ 0 \0\ / | | \ \\ | |\| \_\_ / / | \ \\ | | |/ \.\ o\o) / \ | \\ \ | /\\`v-v / | | \\ | \/ /_| \\_| / | | \ \\ | | /__/_ - / ___ | | \ \\ \| [__] \_/ |_________ \ | \ () / [___] ( \ \ |\ | | // | [___] |\| \| / |/ /| [____] \ |/\ / / || ( \ [____ / ) _\ \ \ \| | || \ \ [_____| / / __/ \ / / // | \ [_____/ / / \ | \/ // | / '----| /=\____ _/ | / // __ / / | / ___/ _/\ \ | || (/-(/-\) / \ (/\/\)/ | / | / (/\/\) / / // _________/ / / \____________/ ( @author NTUDragons-Reborn */ public class C{ public static void main(String[] args) throws Exception { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); Task solver = new Task(); solver.solve(in, out); out.close(); } // main solver static class Task{ double eps= 0.00000001; static final int MAXN = 100005; static final int MOD= 998244353; // stores smallest prime factor for every number static int spf[] = new int[MAXN]; static boolean[] prime; Map<Integer,Set<Integer>> dp= new HashMap<>(); // Calculating SPF (Smallest Prime Factor) for every // number till MAXN. // Time Complexity : O(nloglogn) public 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; } } } void sieveOfEratosthenes(int n) { // Create a boolean array // "prime[0..n]" and // initialize all entries // it as true. A value in // prime[i] will finally be // false if i is Not a // prime, else true. prime= new boolean[n + 1]; for (int i = 0; i <= n; i++) prime[i] = true; for (int p = 2; p * p <= n; p++) { // If prime[p] is not changed, then it is a // prime if (prime[p] == true) { // Update all multiples of p for (int i = p * p; i <= n; i += p) prime[i] = false; } } } // A O(log n) function returning primefactorization // by dividing by smallest prime factor at every step public Set<Integer> getFactorization(int x) { if(dp.containsKey(x)) return dp.get(x); Set<Integer> ret = new HashSet<>(); while (x != 1) { if(spf[x]!=2) ret.add(spf[x]); x = x / spf[x]; } dp.put(x,ret); return ret; } // function to find first index >= x public int lowerIndex(List<Integer> arr, int n, int x) { int l = 0, h = n - 1; while (l <= h) { int mid = (l + h) / 2; if (arr.get(mid) >= x) h = mid - 1; else l = mid + 1; } return l; } public int lowerIndex(int[] arr, int n, int x) { int l = 0, h = n - 1; while (l <= h) { int mid = (l + h) / 2; if (arr[mid] >= x) h = mid - 1; else l = mid + 1; } return l; } // function to find last index <= y public int upperIndex(List<Integer> arr, int n, int y) { int l = 0, h = n - 1; while (l <= h) { int mid = (l + h) / 2; if (arr.get(mid) <= y) l = mid + 1; else h = mid - 1; } return h; } public int upperIndex(int[] arr, int n, int y) { int l = 0, h = n - 1; while (l <= h) { int mid = (l + h) / 2; if (arr[mid] <= y) l = mid + 1; else h = mid - 1; } return h; } // function to count elements within given range public int countInRange(List<Integer> arr, int n, int x, int y) { // initialize result int count = 0; count = upperIndex(arr, n, y) - lowerIndex(arr, n, x) + 1; return count; } public int add(int a, int b){ a+=b; while(a>=MOD) a-=MOD; while(a<0) a+=MOD; return a; } public int mul(int a, int b){ long res= (long)a*(long)b; return (int)(res%MOD); } public int power(int a, int b) { int ans=1; while(b>0){ if((b&1)!=0) ans= mul(ans,a); b>>=1; a= mul(a,a); } return ans; } int[] fact= new int[MAXN]; int[] inv= new int[MAXN]; public int Ckn(int n, int k){ if(k<0 || n<0) return 0; if(n<k) return 0; return mul(mul(fact[n],inv[k]),inv[n-k]); } public int inverse(int a){ return power(a,MOD-2); } public void preprocess() { fact[0]=1; for(int i=1;i<MAXN;i++) fact[i]= mul(fact[i-1],i); inv[MAXN-1]= inverse(fact[MAXN-1]); for(int i=MAXN-2;i>=0;i--){ inv[i]= mul(inv[i+1],i+1); } } /** * return VALUE of lower bound for unsorted array */ public int lowerBoundNormalArray(int[] arr, int x){ TreeSet<Integer> set= new TreeSet<>(); for(int num: arr) set.add(num); return set.lower(x); } /** * return VALUE of upper bound for unsorted array */ public int upperBoundNormalArray(int[] arr, int x){ TreeSet<Integer> set= new TreeSet<>(); for(int num: arr) set.add(num); return set.higher(x); } public void debugArr(int[] arr){ for(int i: arr) out.print(i+" "); out.println(); } public int rand(){ int min=0, max= MAXN; int random_int = (int)Math.floor(Math.random()*(max-min+1)+min); return random_int; } public void suffleSort(int[] arr){ shuffleArray(arr); Arrays.sort(arr); } public void shuffleArray(int[] ar) { // If running on Java 6 or older, use new Random() on RHS here Random rnd = ThreadLocalRandom.current(); for (int i = ar.length - 1; i > 0; i--) { int index = rnd.nextInt(i + 1); // Simple swap int a = ar[index]; ar[index] = ar[i]; ar[i] = a; } } InputReader in; PrintWriter out; Scanner sc= new Scanner(System.in); CustomFileReader cin; int[] xor= new int[3*100000+5]; int[] pow2= new int[1000000+1]; public void solve(InputReader in, PrintWriter out) throws Exception { this.in=in; this.out=out; // sieve(); // pow2[0]=1; // for(int i=1;i<pow2.length;i++){ // pow2[i]= mul(pow2[i-1],2); // } int t=in.nextInt(); // preprocess(); // int t=in.nextInt(); // int t= cin.nextIntArrLine()[0]; for(int i=1;i<=t;i++) solveF(i); } final double pi= Math.acos(-1); static Point base; void solveD(int test){ int n= in.nextInt(); int N= 2*100000+1; int[] a= in.nextIntArr(n); int[] b= in.nextIntArr(n); int[] cnt= new int[N]; int[] used= new int[N]; for(int i=0;i<n;i++) cnt[a[i]]++; int j= n-1; for(int i=n-1;i>=0;i--){ if(b[i]==a[j]){ cnt[b[i]]--; j--; } else{ if(j+1<n && a[j+1]==b[i] && cnt[b[i]]>0){ cnt[b[i]]--; used[b[i]]++; } else { if(used[a[j]]<=0) {out.println("NO"); return;} used[a[j]]--; j--; } } } out.println("YES"); } void solveF(int test) throws Exception{ int n= in.nextInt(); int[] a= in.nextIntArr(n); // Set<Integer> has= new HashSet<>(); // List<Integer> res= new ArrayList<>(); // List<Integer> temp= new ArrayList<>(); // for(int i=0;i<n;i++){ // if(has.contains(a[i])){ // has= new HashSet<>(); // if(temp.size()>0){ // for(int j=1;j<temp.size();++j){ // res.add(temp.get(j)); // } // res.add(temp.get(0)); // } // temp= new ArrayList<>(); // i--; // } // else{ // has.add(a[i]); // temp.add(a[i]); // } // } // if(temp.size()>0){ // for(int j=1;j<temp.size();++j){ // res.add(temp.get(j)); // } // res.add(temp.get(0)); // } // for(int i: res) out.print(i+" "); // if(res.size()!=n){ // throw new Exception(); // } // out.println(); Map<Integer,Queue<Integer>> idx= new HashMap<>(); Set<Integer> set= new HashSet<>(); for(int i=0;i<n;i++){ set.add(a[i]); if(!idx.containsKey(a[i])){ idx.put(a[i], new LinkedList<>()); } idx.get(a[i]).add(i); } List<Integer> vals= new ArrayList<>(); for(int i: set) vals.add(i); Collections.sort(vals); int[] res= new int[n]; boolean finish= true; do{ finish= true; List<Integer> index= new ArrayList<>(); for(Map.Entry<Integer,Queue<Integer>> entry: idx.entrySet()){ Queue<Integer> q= entry.getValue(); if(q.size()==0) continue; finish= false; index.add(q.poll()); } if(index.size()==0) break; int temp= a[index.get(0)]; for(int i=0;i<index.size()-1;i++){ res[index.get(i)]= a[index.get(i+1)]; } res[index.get(index.size()-1)]= temp; }while(!finish); for(int i: res) out.print(i+" "); out.println(); } static class ListNode{ int idx=-1; ListNode next= null; public ListNode(int idx){ this.idx= idx; } } public long _gcd(long a, long b) { if(b == 0) { return a; } else { return _gcd(b, a % b); } } public long _lcm(long a, long b){ return (a*b)/_gcd(a,b); } } // static class SEG { // Pair[] segtree; // public SEG(int n){ // segtree= new Pair[4*n]; // Arrays.fill(segtree, new Pair(-1,Long.MAX_VALUE)); // } // // void buildTree(int l, int r, int index) { // // if (l == r) { // // segtree[index].y = a[l]; // // return; // // } // // int mid = (l + r) / 2; // // buildTree(l, mid, 2 * index + 1); // // buildTree(mid + 1, r, 2 * index + 2); // // segtree[index].y = Math.min(segtree[2 * index + 1].y, segtree[2 * index + 2].y); // // } // void update(int l, int r, int index, int pos, Pair val) { // if (l == r) { // segtree[index] = val; // return; // } // int mid = (l + r) / 2; // if (pos <= mid) update(l, mid, 2 * index + 1, pos, val); // else update(mid + 1, r, 2 * index + 2, pos, val); // if(segtree[2 * index + 1].y < segtree[2 * index + 2].y){ // segtree[index]= segtree[2 * index + 1]; // } // else { // segtree[index]= segtree[2 * index + 2]; // } // } // // Pair query(int l, int r, int from, int to, int index) { // // if (from <= l && r <= to) // // return segtree[index]; // // if (r < from | to < l) // // return 0; // // int mid = (l + r) / 2; // // Pair left= query(l, mid, from, to, 2 * index + 1); // // Pair right= query(mid + 1, r, from, to, 2 * index + 2); // // if(left.y < right.y) return left; // // else return right; // // } // } static class Venice{ public Map<Long,Long> m= new HashMap<>(); public long base=0; public long totalValue=0; private int M= 1000000007; private long addMod(long a, long b){ a+=b; if(a>=M) a-=M; return a; } public void reset(){ m= new HashMap<>(); base=0; totalValue=0; } public void update(long add){ base= base+ add; } public void add(long key, long val){ long newKey= key-base; m.put(newKey, addMod(m.getOrDefault(newKey,(long)0),val)); } } static class Tuple implements Comparable<Tuple>{ int x, y, z; public Tuple(int x, int y, int z){ this.x= x; this.y= y; this.z=z; } @Override public int compareTo(Tuple o){ return this.z-o.z; } } static class Point implements Comparable<Point>{ public double x; public long y; public Point(double x, long y){ this.x= x; this.y= y; } @Override public int compareTo(Point o) { if(this.y!=o.y) return (int)(this.y-o.y); return (int)(this.x-o.x); } } // static class Vector { // public long x; // public long y; // // p1 -> p2 // public Vector(Point p1, Point p2){ // this.x= p2.x-p1.x; // this.y= p2.y-p1.y; // } // } 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 int compareTo(Pair o) { if(this.x!=o.x) return (int)(this.x-o.x); return (int)(this.y-o.y); } } // public static class compareL implements Comparator<Tuple>{ // @Override // public int compare(Tuple t1, Tuple t2) { // return t2.l - t1.l; // } // } // fast input reader class; static class InputReader { BufferedReader br; StringTokenizer st; public InputReader(InputStream stream) { br = new BufferedReader(new InputStreamReader(stream)); } public String nextToken() { while (st == null || !st.hasMoreTokens()) { String line = null; try { line = br.readLine(); } catch (IOException e) { throw new RuntimeException(e); } if (line == null) { return null; } st = new StringTokenizer(line); } return st.nextToken(); } public int nextInt() { return Integer.parseInt(nextToken()); } public double nextDouble(){ return Double.parseDouble(nextToken()); } public long nextLong(){ return Long.parseLong(nextToken()); } public int[] nextIntArr(int n){ int[] arr= new int[n]; for(int i=0;i<n;i++) arr[i]= nextInt(); return arr; } public long[] nextLongArr(int n){ long[] arr= new long[n]; for(int i=0;i<n;i++) arr[i]= nextLong(); return arr; } public List<Integer> nextIntList(int n){ List<Integer> arr= new ArrayList<>(); for(int i=0;i<n;i++) arr.add(nextInt()); return arr; } public int[][] nextIntMatArr(int n, int m){ int[][] mat= new int[n][m]; for(int i=0;i<n;i++) for(int j=0;j<m;j++) mat[i][j]= nextInt(); return mat; } public List<List<Integer>> nextIntMatList(int n, int m){ List<List<Integer>> mat= new ArrayList<>(); for(int i=0;i<n;i++){ List<Integer> temp= new ArrayList<>(); for(int j=0;j<m;j++) temp.add(nextInt()); mat.add(temp); } return mat; } public char[] nextStringCharArr(){ return nextToken().toCharArray(); } } static class CustomFileReader{ String path=""; Scanner sc; public CustomFileReader(String path){ this.path=path; try{ sc= new Scanner(new File(path)); } catch(Exception e){} } public String nextLine(){ return sc.nextLine(); } public int[] nextIntArrLine(){ String line= sc.nextLine(); String[] part= line.split("[\\s+]"); int[] res= new int[part.length]; for(int i=0;i<res.length;i++) res[i]= Integer.parseInt(part[i]); return res; } } }
Java
["2\n\n2\n\n2 1\n\n4\n\n1 2 3 3"]
1 second
["1 2\n3 3 2 1"]
NoteIn the first test case, the array $$$[1,2]$$$ has sadness $$$1$$$. We can transform $$$[1,2]$$$ into $$$[2,1]$$$ using one operation with $$$(i,j)=(1,2)$$$.In the second test case, the array $$$[3,3,2,1]$$$ has sadness $$$2$$$. We can transform $$$[3,3,2,1]$$$ into $$$[1,2,3,3]$$$ with two operations with $$$(i,j)=(1,4)$$$ and $$$(i,j)=(2,3)$$$ respectively.
Java 11
standard input
[ "constructive algorithms", "graphs", "greedy" ]
01703877719e19dd8551e4599c3e1c85
Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$)  — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$)  — the length of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$)  — elements of the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
2,000
For each test case, print $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ — describing the array $$$b$$$. If there are multiple answers, you may print any.
standard output
PASSED
3184f7fa369d19b804d1e3b223e8892c
train_108.jsonl
1650722700
oolimry has an array $$$a$$$ of length $$$n$$$ which he really likes. Today, you have changed his array to $$$b$$$, a permutation of $$$a$$$, to make him sad.Because oolimry is only a duck, he can only perform the following operation to restore his array: Choose two integers $$$i,j$$$ such that $$$1 \leq i,j \leq n$$$. Swap $$$b_i$$$ and $$$b_j$$$. The sadness of the array $$$b$$$ is the minimum number of operations needed to transform $$$b$$$ into $$$a$$$.Given the array $$$a$$$, find any array $$$b$$$ which is a permutation of $$$a$$$ that has the maximum sadness over all permutations of the array $$$a$$$.
256 megabytes
import java.io.*; import java.util.*; public class Codeforces { public static void main(String args[])throws Exception { BufferedReader bu=new BufferedReader(new InputStreamReader(System.in)); StringBuilder sb=new StringBuilder(); int t=Integer.parseInt(bu.readLine()); while(t-->0) { int n=Integer.parseInt(bu.readLine()); int i,a[]=new int[n]; String s[]=bu.readLine().split(" "); ArrayList<Integer> next[]=new ArrayList[n+1]; for(i=0;i<=n;i++) next[i]=new ArrayList<>(); for(i=0;i<n;i++) { a[i]=Integer.parseInt(s[i]); next[a[i]].add(i); } PriorityQueue<int[]> pq=new PriorityQueue<>(new Comparator<int[]>() { @Override public int compare(int[] o1, int[] o2) { if(o1[0]<o2[0]) return 1; else return -1; }}); for(i=1;i<=n;i++) if(next[i].size()>0) pq.add(new int[]{next[i].size(),i}); ArrayList<ArrayList<Integer>> cyc=new ArrayList<>(); int e[]=pq.poll(); for(int x:next[e[1]]) { ArrayList<Integer> te=new ArrayList<>(); te.add(x); cyc.add(te); } while(!pq.isEmpty()) { e=pq.poll(); int sz=next[e[1]].size(); for(i=0;i<sz;i++) cyc.get(i).add(next[e[1]].get(i)); } int ans[]=new int[n]; for(ArrayList<Integer> cy:cyc) { int sz=cy.size(); for(i=0;i<sz;i++) ans[cy.get(i)]=a[cy.get((i+1)%sz)]; } for(i=0;i<n;i++) sb.append(ans[i]+" "); sb.append("\n"); } System.out.print(sb); } }
Java
["2\n\n2\n\n2 1\n\n4\n\n1 2 3 3"]
1 second
["1 2\n3 3 2 1"]
NoteIn the first test case, the array $$$[1,2]$$$ has sadness $$$1$$$. We can transform $$$[1,2]$$$ into $$$[2,1]$$$ using one operation with $$$(i,j)=(1,2)$$$.In the second test case, the array $$$[3,3,2,1]$$$ has sadness $$$2$$$. We can transform $$$[3,3,2,1]$$$ into $$$[1,2,3,3]$$$ with two operations with $$$(i,j)=(1,4)$$$ and $$$(i,j)=(2,3)$$$ respectively.
Java 11
standard input
[ "constructive algorithms", "graphs", "greedy" ]
01703877719e19dd8551e4599c3e1c85
Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$)  — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$)  — the length of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$)  — elements of the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
2,000
For each test case, print $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ — describing the array $$$b$$$. If there are multiple answers, you may print any.
standard output
PASSED
948c25c52a02c797c512303d847cd8a1
train_108.jsonl
1650722700
oolimry has an array $$$a$$$ of length $$$n$$$ which he really likes. Today, you have changed his array to $$$b$$$, a permutation of $$$a$$$, to make him sad.Because oolimry is only a duck, he can only perform the following operation to restore his array: Choose two integers $$$i,j$$$ such that $$$1 \leq i,j \leq n$$$. Swap $$$b_i$$$ and $$$b_j$$$. The sadness of the array $$$b$$$ is the minimum number of operations needed to transform $$$b$$$ into $$$a$$$.Given the array $$$a$$$, find any array $$$b$$$ which is a permutation of $$$a$$$ that has the maximum sadness over all permutations of the array $$$a$$$.
256 megabytes
// package c1672; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.InputStreamReader; import java.lang.invoke.MethodHandles; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Random; import java.util.StringTokenizer; // // Codeforces Global Round 20 2022-04-23 07:05 // F1. Array Shuffling // https://codeforces.com/contest/1672/problem/F1 // 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+).*' // // oolimry has an array a of length n which he really likes. Today, you have changed his array to b, // a permutation of a, to make him sad. // // Because oolimry is only a duck, he can only perform the following operation to restore his array: // * Choose two integers i,j such that 1 <= i,j <= n. // * Swap b_i and b_j. // // The of the array b is the minimum number of operations needed to transform b into a. // // Given the array a, find any array b which is a permutation of a that has the maximum sadness over // all permutations of the array a. // // Input // // Each test contains 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 a single integer n (1 <= n <= 2 * 10^5) -- the length // of the array. // // The second line of each test case contains n integers a_1, a_2, ..., a_n (1 <= a_i <= n) -- // elements of the array a. // // It is guaranteed that the sum of n over all test cases does not exceed 2 * 10^5. // // Output // // For each test case, print n integers b_1, b_2, ..., b_n -- describing the array b. If there are // multiple answers, you may print any. // // Example /* input: 2 2 2 1 4 1 2 3 3 output: 1 2 3 3 2 1 */ // Note // // In the first test case, the array [1,2] has sadness 1. We can transform [1,2] into [2,1] using // one operation with (i,j)=(1,2). // // In the second test case, the array [3,3,2,1] has sadness 2. We can transform [3,3,2,1] into // [1,2,3,3] with two operations with (i,j)=(1,4) and (i,j)=(2,3) respectively. // public class C1672F1 { static final int MOD = 998244353; static final Random RAND = new Random(); static int[] solve(int[] a) { int n = a.length; // Map from value to indexes Map<Integer, List<Integer>> vim = new HashMap<>(); for (int i = 0; i < n; i++) { vim.computeIfAbsent(a[i], v -> new ArrayList<>()).add(i); } List<Integer> va = new ArrayList<>(vim.keySet()); Collections.sort(va, (x,y) -> vim.get(y).size() - vim.get(x).size()); // System.out.format("va:%s\n", Utils.traceListInt(va)); List<Integer> idxes = new ArrayList<>(); int m = va.size(); for (int i = 1; i < m; i++) { idxes.addAll(vim.get(va.get(i))); } idxes.addAll(vim.get(va.get(0))); // System.out.format("idxes:%s\n", Utils.traceListInt(idxes)); int[] ans = new int[n]; int idx = 0; for (int v : va) { int k = vim.get(v).size(); for (int i = 0; i < k; i++) { ans[idxes.get(idx)] = v; idx++; } } return ans; } static boolean test = false; static void doTest() { if (!test) { return; } long t0 = System.currentTimeMillis(); output(solve(new int[] {2,1})); output(solve(new int[] {1,2,3,3})); output(solve(new int[] {1,2,3,4,5,6,4,4,2,2,2,1})); 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); output(ans); } } static void output(int[] a) { 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
["2\n\n2\n\n2 1\n\n4\n\n1 2 3 3"]
1 second
["1 2\n3 3 2 1"]
NoteIn the first test case, the array $$$[1,2]$$$ has sadness $$$1$$$. We can transform $$$[1,2]$$$ into $$$[2,1]$$$ using one operation with $$$(i,j)=(1,2)$$$.In the second test case, the array $$$[3,3,2,1]$$$ has sadness $$$2$$$. We can transform $$$[3,3,2,1]$$$ into $$$[1,2,3,3]$$$ with two operations with $$$(i,j)=(1,4)$$$ and $$$(i,j)=(2,3)$$$ respectively.
Java 11
standard input
[ "constructive algorithms", "graphs", "greedy" ]
01703877719e19dd8551e4599c3e1c85
Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$)  — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$)  — the length of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$)  — elements of the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
2,000
For each test case, print $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ — describing the array $$$b$$$. If there are multiple answers, you may print any.
standard output
PASSED
1f5cfbf4a38cec3596998c96d97a0bfa
train_108.jsonl
1650722700
oolimry has an array $$$a$$$ of length $$$n$$$ which he really likes. Today, you have changed his array to $$$b$$$, a permutation of $$$a$$$, to make him sad.Because oolimry is only a duck, he can only perform the following operation to restore his array: Choose two integers $$$i,j$$$ such that $$$1 \leq i,j \leq n$$$. Swap $$$b_i$$$ and $$$b_j$$$. The sadness of the array $$$b$$$ is the minimum number of operations needed to transform $$$b$$$ into $$$a$$$.Given the array $$$a$$$, find any array $$$b$$$ which is a permutation of $$$a$$$ that has the maximum sadness over all permutations of the array $$$a$$$.
256 megabytes
import static java.lang.Integer.parseInt; import static java.lang.Long.parseLong; import static java.lang.System.exit; import static java.util.Arrays.fill; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class F1 { static void solve() throws Exception { int tests = scanInt(); for (int test = 0; test < tests; test++) { int n = scanInt(), pos[] = new int[n + 1], prev[] = new int[n]; fill(pos, -1); for (int i = 0; i < n; i++) { int cur = scanInt(); prev[i] = pos[cur]; pos[cur] = i; } int last = -1, posPrev[] = new int[n + 1], b[] = new int[n], left = n; for (int i = 0; i <= n; i++) { if (pos[i] >= 0) { posPrev[i] = last; last = i; } } while (left > 0) { int newLast = -1, newCur = -1; for (int i = last; i >= 0; i = posPrev[i]) { b[pos[i]] = posPrev[i] >= 0 ? posPrev[i] : last; --left; pos[i] = prev[pos[i]]; if (pos[i] >= 0) { if (newLast < 0) { newLast = i; } else { posPrev[newCur] = i; } newCur = i; } } if (newCur >= 0) { posPrev[newCur] = -1; } last = newLast; } for (int i = 0; i < n; i++) { out.print(b[i] + " "); } out.println(); } } static int scanInt() throws IOException { return parseInt(scanString()); } static long scanLong() throws IOException { return parseLong(scanString()); } static String scanString() throws IOException { while (tok == null || !tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); } return tok.nextToken(); } static BufferedReader in; static PrintWriter out; static StringTokenizer tok; public static void main(String[] args) { try { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); in.close(); out.close(); } catch (Throwable e) { e.printStackTrace(); exit(1); } } }
Java
["2\n\n2\n\n2 1\n\n4\n\n1 2 3 3"]
1 second
["1 2\n3 3 2 1"]
NoteIn the first test case, the array $$$[1,2]$$$ has sadness $$$1$$$. We can transform $$$[1,2]$$$ into $$$[2,1]$$$ using one operation with $$$(i,j)=(1,2)$$$.In the second test case, the array $$$[3,3,2,1]$$$ has sadness $$$2$$$. We can transform $$$[3,3,2,1]$$$ into $$$[1,2,3,3]$$$ with two operations with $$$(i,j)=(1,4)$$$ and $$$(i,j)=(2,3)$$$ respectively.
Java 11
standard input
[ "constructive algorithms", "graphs", "greedy" ]
01703877719e19dd8551e4599c3e1c85
Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$)  — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$)  — the length of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$)  — elements of the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
2,000
For each test case, print $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ — describing the array $$$b$$$. If there are multiple answers, you may print any.
standard output
PASSED
7f8705ec63957767587fd4e18fc6ea7a
train_108.jsonl
1650722700
oolimry has an array $$$a$$$ of length $$$n$$$ which he really likes. Today, you have changed his array to $$$b$$$, a permutation of $$$a$$$, to make him sad.Because oolimry is only a duck, he can only perform the following operation to restore his array: Choose two integers $$$i,j$$$ such that $$$1 \leq i,j \leq n$$$. Swap $$$b_i$$$ and $$$b_j$$$. The sadness of the array $$$b$$$ is the minimum number of operations needed to transform $$$b$$$ into $$$a$$$.Given the array $$$a$$$, find any array $$$b$$$ which is a permutation of $$$a$$$ that has the maximum sadness over all permutations of the array $$$a$$$.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; import java.io.BufferedReader; import java.util.Comparator; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author lucasr */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; MyScanner in = new MyScanner(inputStream); PrintWriter out = new PrintWriter(outputStream); F1ArrayShuffling solver = new F1ArrayShuffling(); int testCount = Integer.parseInt(in.next()); for (int i = 1; i <= testCount; i++) solver.solve(i, in, out); out.close(); } static class F1ArrayShuffling { public static MyScanner sc; public static PrintWriter out; public void solve(int testNumber, MyScanner sc, PrintWriter out) { F1ArrayShuffling.sc = sc; F1ArrayShuffling.out = out; int n = sc.nextInt(); int[] vals = sc.nextIntArray(n); IntArray[] pos = new IntArray[n + 1]; for (int i = 0; i < n; i++) { if (pos[vals[i]] == null) pos[vals[i]] = new IntArray(); pos[vals[i]].add(i); } List<Group> all = new ArrayList<>(); for (int i = 1; i <= n; i++) { if (pos[i] != null) { all.add(new Group(i, pos[i])); } } all.sort(Comparator.comparingInt(g -> g.positions.size())); Group[] sorted = all.toArray(new Group[0]); int size = sorted.length; int from = 0; int[] ret = new int[n]; while (from < size) { for (int i = from; i < size; i++) { IntArray cur = sorted[i].positions; ret[cur.last()] = sorted[i + 1 == size ? from : i + 1].val; cur.removeLast(); } while (from < size && sorted[from].positions.isEmpty()) from++; } for (int i = 0; i < n; i++) { out.print(ret[i] + " "); } out.println(); } class Group { int val; IntArray positions; public Group(int val, IntArray positions) { this.val = val; this.positions = positions; } } } static class MyScanner { private BufferedReader br; private StringTokenizer tokenizer; public MyScanner(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(br.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public int[] nextIntArray(int n) { int[] ret = new int[n]; for (int i = 0; i < n; i++) { ret[i] = nextInt(); } return ret; } } static class IntArray { int[] arr; int size; public IntArray() { arr = new int[4]; } public void add(int val) { if (size == arr.length) { arr = Arrays.copyOf(arr, 2 * arr.length); } arr[size++] = val; } public int last() { return arr[size - 1]; } public void removeLast() { size--; } public int size() { return size; } public boolean isEmpty() { return size() == 0; } public int[] toArray() { return Arrays.copyOf(arr, size); } public String toString() { return "IntArray " + Arrays.toString(toArray()); } } }
Java
["2\n\n2\n\n2 1\n\n4\n\n1 2 3 3"]
1 second
["1 2\n3 3 2 1"]
NoteIn the first test case, the array $$$[1,2]$$$ has sadness $$$1$$$. We can transform $$$[1,2]$$$ into $$$[2,1]$$$ using one operation with $$$(i,j)=(1,2)$$$.In the second test case, the array $$$[3,3,2,1]$$$ has sadness $$$2$$$. We can transform $$$[3,3,2,1]$$$ into $$$[1,2,3,3]$$$ with two operations with $$$(i,j)=(1,4)$$$ and $$$(i,j)=(2,3)$$$ respectively.
Java 11
standard input
[ "constructive algorithms", "graphs", "greedy" ]
01703877719e19dd8551e4599c3e1c85
Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$)  — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$)  — the length of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$)  — elements of the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
2,000
For each test case, print $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ — describing the array $$$b$$$. If there are multiple answers, you may print any.
standard output
PASSED
045dbef44e5d59efb8db2ba8b951bb27
train_108.jsonl
1650722700
oolimry has an array $$$a$$$ of length $$$n$$$ which he really likes. Today, you have changed his array to $$$b$$$, a permutation of $$$a$$$, to make him sad.Because oolimry is only a duck, he can only perform the following operation to restore his array: Choose two integers $$$i,j$$$ such that $$$1 \leq i,j \leq n$$$. Swap $$$b_i$$$ and $$$b_j$$$. The sadness of the array $$$b$$$ is the minimum number of operations needed to transform $$$b$$$ into $$$a$$$.Given the array $$$a$$$, find any array $$$b$$$ which is a permutation of $$$a$$$ that has the maximum sadness over all permutations of the array $$$a$$$.
256 megabytes
import java.io.BufferedReader; import java.io.Closeable; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.time.Clock; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.Objects; import java.util.Set; import java.util.StringTokenizer; import java.util.function.Supplier; public class Solution { private void solve() throws IOException { int n = nextInt(); int[] a = nextIntArray(n); ArrayList<Integer>[] b = new ArrayList[n]; for (int i = 0; i < n; i++) { int aa = --a[i]; if (b[aa] == null) { b[aa] = new ArrayList<>(); } b[aa].add(i); } ArrayList<Integer>[] c = new ArrayList[n]; for (int i = 0; i < n; i++) { ArrayList<Integer> bi = b[i]; if (bi != null) { for (int j = bi.size() - 1; j >= 0; j--) { if (c[j] == null) { c[j] = new ArrayList<>(); } c[j].add(bi.get(j)); } } } int[] res = new int[n]; for (int i = 0; i < n; i++) { ArrayList<Integer> ci = c[i]; if (ci != null) { res[ci.get(0)] = a[ci.get(ci.size() - 1)]; for (int j = ci.size() - 1; j > 0; j--) { res[ci.get(j)] = a[ci.get(j - 1)]; } } } for (int i : res) { out.print((i + 1) + " "); } out.println(); } private static final boolean runNTestsInProd = true; private static final boolean printCaseNumber = false; private static final boolean assertInProd = false; private static final boolean logToFile = false; private static final boolean readFromConsoleInDebug = false; private static final boolean writeToConsoleInDebug = true; private static final boolean testTimer = false; private static Boolean isDebug = null; private BufferedReader in; private StringTokenizer line; private PrintWriter out; public static void main(String[] args) throws Exception { isDebug = Arrays.asList(args).contains("DEBUG_MODE"); if (isDebug) { log = logToFile ? new PrintWriter("logs/j_solution_" + System.currentTimeMillis() + ".log") : new PrintWriter(System.out); clock = Clock.systemDefaultZone(); } new Solution().run(); } private void run() throws Exception { in = new BufferedReader(new InputStreamReader(!isDebug || readFromConsoleInDebug ? System.in : new FileInputStream("input.txt"))); out = !isDebug || writeToConsoleInDebug ? new PrintWriter(System.out) : new PrintWriter("output.txt"); try (Timer totalTimer = new Timer("total")) { int t = runNTestsInProd || isDebug ? nextInt() : 1; for (int i = 0; i < t; i++) { if (printCaseNumber) { out.print("Case #" + (i + 1) + ": "); } if (testTimer) { try (Timer testTimer = new Timer("test #" + (i + 1))) { solve(); } } else { solve(); } if (isDebug) { out.flush(); } } } in.close(); out.flush(); out.close(); } private void println(Object... objects) { boolean isFirst = true; for (Object o : objects) { if (!isFirst) { out.print(" "); } else { isFirst = false; } out.print(o.toString()); } out.println(); } private int[] nextIntArray(int n) throws IOException { int[] res = new int[n]; for (int i = 0; i < n; i++) { res[i] = nextInt(); } return res; } private long[] nextLongArray(int n) throws IOException { long[] res = new long[n]; for (int i = 0; i < n; i++) { res[i] = nextLong(); } return res; } private int nextInt() throws IOException { return Integer.parseInt(nextToken()); } private long nextLong() throws IOException { return Long.parseLong(nextToken()); } private double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } private char[] nextTokenChars() throws IOException { return nextToken().toCharArray(); } private String nextToken() throws IOException { while (line == null || !line.hasMoreTokens()) { line = new StringTokenizer(in.readLine()); } return line.nextToken(); } private static void assertPredicate(boolean p) { if ((isDebug || assertInProd) && !p) { throw new RuntimeException(); } } private static void assertPredicate(boolean p, String message) { if ((isDebug || assertInProd) && !p) { throw new RuntimeException(message); } } private static <T> void assertNotEqual(T unexpected, T actual) { if ((isDebug || assertInProd) && Objects.equals(actual, unexpected)) { throw new RuntimeException("assertNotEqual: " + unexpected + " == " + actual); } } private static <T> void assertEqual(T expected, T actual) { if ((isDebug || assertInProd) && !Objects.equals(actual, expected)) { throw new RuntimeException("assertEqual: " + expected + " != " + actual); } } private static PrintWriter log = null; private static Clock clock = null; private static void log(Object... objects) { log(true, objects); } private static void logNoDelimiter(Object... objects) { log(false, objects); } private static void log(boolean printDelimiter, Object[] objects) { if (isDebug) { StringBuilder sb = new StringBuilder(); sb.append(LocalDateTime.now(clock)).append(" - "); boolean isFirst = true; for (Object o : objects) { if (!isFirst && printDelimiter) { sb.append(" "); } else { isFirst = false; } sb.append(o.toString()); } log.println(sb); log.flush(); } } private static class Timer implements Closeable { private final String label; private final long startTime = isDebug ? System.nanoTime() : 0; public Timer(String label) { this.label = label; } @Override public void close() throws IOException { if (isDebug) { long executionTime = System.nanoTime() - startTime; String fraction = Long.toString(executionTime / 1000 % 1_000_000); logNoDelimiter("Timer[", label, "]: ", executionTime / 1_000_000_000, '.', "00000".substring(0, 6 - fraction.length()), fraction, 's'); } } } private static <T> T timer(String label, Supplier<T> f) throws Exception { if (isDebug) { try (Timer timer = new Timer(label)) { return f.get(); } } else { return f.get(); } } }
Java
["2\n\n2\n\n2 1\n\n4\n\n1 2 3 3"]
1 second
["1 2\n3 3 2 1"]
NoteIn the first test case, the array $$$[1,2]$$$ has sadness $$$1$$$. We can transform $$$[1,2]$$$ into $$$[2,1]$$$ using one operation with $$$(i,j)=(1,2)$$$.In the second test case, the array $$$[3,3,2,1]$$$ has sadness $$$2$$$. We can transform $$$[3,3,2,1]$$$ into $$$[1,2,3,3]$$$ with two operations with $$$(i,j)=(1,4)$$$ and $$$(i,j)=(2,3)$$$ respectively.
Java 11
standard input
[ "constructive algorithms", "graphs", "greedy" ]
01703877719e19dd8551e4599c3e1c85
Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$)  — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$)  — the length of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$)  — elements of the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
2,000
For each test case, print $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ — describing the array $$$b$$$. If there are multiple answers, you may print any.
standard output
PASSED
38eb7e9518f93a98c325c8e5303d140b
train_108.jsonl
1650722700
oolimry has an array $$$a$$$ of length $$$n$$$ which he really likes. Today, you have changed his array to $$$b$$$, a permutation of $$$a$$$, to make him sad.Because oolimry is only a duck, he can only perform the following operation to restore his array: Choose two integers $$$i,j$$$ such that $$$1 \leq i,j \leq n$$$. Swap $$$b_i$$$ and $$$b_j$$$. The sadness of the array $$$b$$$ is the minimum number of operations needed to transform $$$b$$$ into $$$a$$$.Given the arrays $$$a$$$ and $$$b$$$, where $$$b$$$ is a permutation of $$$a$$$, determine if $$$b$$$ has the maximum sadness over all permutations of $$$a$$$.
256 megabytes
import java.util.*; import java.io.*; // you can compare with output.txt and expected out public class RoundGlobal20F2 { 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))); RoundGlobal20F2 sol = new RoundGlobal20F2(); 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) { int n = in.nextInt(); int[] a = in.nextIntArray(n); int[] b = in.nextIntArray(n); if(isDebug){ out.printf("Test %d\n", i); } boolean ans = solve(a, b); if(ans) out.println("AC"); else out.println("WA"); if(isDebug) out.flush(); } in.close(); out.close(); } private boolean solve(int[] a, int[] b) { // the representation was stupid // make vertices: a[i] // make edge: a[i] -> b[i] // decompose all edges into cycles int n = a.length; int[] outDeg = new int[n+1]; int[][] outNb = new int[n+1][]; for(int i=0; i<n; i++) { outDeg[a[i]]++; } int maxFrequentVal = 0; for(int i=1; i<=n; i++) { if(outDeg[i] > outDeg[maxFrequentVal]) maxFrequentVal = i; } for(int i=0; i<n; i++) { if(b[i] == maxFrequentVal) outDeg[a[i]]--; } outDeg[maxFrequentVal] = 0; for(int i=1; i<=n; i++) outNb[i] = new int[outDeg[i]]; int[] inDeg = new int[n+1]; int[] idx = new int[n+1]; for(int i=0; i<n; i++) { if(b[i] == maxFrequentVal || a[i] == maxFrequentVal) continue; outNb[a[i]][idx[a[i]]++] = b[i]; inDeg[b[i]]++; } ArrayDeque<Integer> queue = new ArrayDeque<Integer>(); for(int i=1; i<=n; i++) { if(inDeg[i] == 0) queue.add(i); } while(!queue.isEmpty()) { int curr = queue.pollFirst(); for(int next: outNb[curr]) { if(inDeg[next] == 0) return false; inDeg[next]--; if(inDeg[next] == 0) queue.addLast(next); } } for(int i=1; i<=n; i++) if(inDeg[i] != 0) return false; return true; } private boolean solve2(int[] a, int[] b) { // b[i] -> b[j] iff b[i] = a[j] // i.e., j is contained in invertedA[b[i]] // what kind of digraph is this? // for all edge i -> j, outDeg[i] = inDeg[j] // for all i, outDeg[i] >= 1 // it must be the case that these conditions guarantee the existence of a cycle decomposition // ___ the core observation is that // in an optimal cycle decomposition of worst b // each cycle contains exactly one vertex of max out degree // that means that the graph minus max out degree vertices contains no cycles. this.a = a; this.b = b; int n = a.length; invertedA = new HashSet[n+1]; invertedB = new HashSet[n+1]; for(int i=1; i<=n; i++) { invertedA[i] = new HashSet<Integer>(); invertedB[i] = new HashSet<Integer>(); } for(int i=0; i<n; i++) { invertedA[a[i]].add(i); invertedB[b[i]].add(i); } HashSet<Integer> maxInvertedA = invertedA[1]; maxFrequentVal = 1; for(int i=2; i<=n; i++) { if(invertedA[i].size() > maxInvertedA.size()) { maxInvertedA = invertedA[i]; maxFrequentVal = i; } } for(int i: invertedA[maxFrequentVal]) { // a[i] = maxfrequentVal } invertedA[maxFrequentVal].clear(); for(int i: invertedB[maxFrequentVal]) { // b[i] = maxFrequentVal // need to delete j -> i mapping s.t. b[j] = a[i] invertedA[a[i]].remove(i); } invertedB[maxFrequentVal].clear(); ArrayDeque<Integer> queue = new ArrayDeque<>(); visited = new boolean[n]; int[] inDeg = new int[n]; for(int i=0; i<n; i++) { if(b[i] == maxFrequentVal) continue; inDeg[i] = invertedB[a[i]].size(); if(inDeg[i] == 0) queue.add(i); } boolean[] used = new boolean[n+1]; while(!queue.isEmpty()) { int curr = queue.pollFirst(); for(int next: invertedA[b[curr]]) { if(b[next] == maxFrequentVal) continue; if(inDeg[next] == 0) return false; inDeg[next] --; if(inDeg[next] == 0) queue.addLast(next); } } used = used; for(int i=0; i<n; i++) if(b[i] != maxFrequentVal && inDeg[i] != 0) return false; return true; // for(int i=0; i<n; i++) { // if(visited[i] || b[i] == maxFrequentVal) // continue; // if(!dfs(i)) // return false; // } // return true; // int[] worst = computeWorst(a); // int correctSadness = computeSadness(a, worst); // int givenSadness = computeSadness(a, b); // out.println(correctSadness); // out.println(givenSadness); // return correctSadness == givenSadness; } HashSet<Integer>[] invertedA; HashSet<Integer>[] invertedB; int maxFrequentVal; int[] a; int[] b; boolean[] visited; private boolean dfs(int curr) { if(visited[curr]) return false; visited[curr] = true; for(int next: invertedA[b[curr]]) { if(b[next] == maxFrequentVal) continue; if(!dfs(next)) return false; } return true; } private int computeSadness(int[] a, int[] b) { int n = a.length; int sadness = 0; // this.a = a; // this.b = b; // 1 hour for an implementation for an incorrect idea // need to make a chain // b[i1] = a[i2] // b[i2] = a[i3] // ... // b[ik] = a[i1] // how to make a cycle decomposition of the maximum number k of cycles? // -> the sadness is n-k // 1 5 1 5 1 5 // 5 1 5 1 5 1 // this is a graph // something like the perfect matching algorithm? // (since the algorithm computes the augmenting cycles) // a bit different though // 1 1 ... 1 2 2 ... 2 .... m m ... m ... km ... km // m m+1 ... 2m-1 m m+1 ... 2m-1 .... 2m 2m+1 ... 3m-1 ... 1 ...m-1 // traverse zigzag, close a cycle when found a visited vertex // isn't this dfs? // invertedA = new HashSet[n+1]; // invertedB = new HashSet[n+1]; // for(int i=1; i<=n; i++) { // invertedA[i] = new HashSet<Integer>(); // invertedB[i] = new HashSet<Integer>(); // } // // for(int i=0; i<n; i++) { // invertedA[a[i]].add(i); // invertedB[b[i]].add(i); // } // // visitedA = new boolean[n]; // visitedB = new boolean[n]; // usedA = new boolean[n]; // usedB = new boolean[n]; // cycles = new ArrayList<ArrayList<Integer>>(); // for(int i=0; i<n; i++) { // dfs(i, true); // } // took another 90 mins to try above idea then convert the problem into a digraph problem // what kind of digraph is this? // for all edge i -> j, outDeg[i] = inDeg[j] // for all i, outDeg[i] >= 1 // it must be the case that these conditions guarantee the existence of a cycle decomposition // ___ the core observation is that // in an optimal cycle decomposition of worst b // each cycle contains exactly one vertex of max out degree // that means that the graph minus max out degree vertices contains no cycles. HashSet<Integer>[] invertedA = new HashSet[n+1]; for(int i=1; i<=n; i++) { invertedA[i] = new HashSet<Integer>(); } for(int i=0; i<n; i++) { invertedA[a[i]].add(i); } // b[i] -> b[j] iff b[i] = a[j] // i.e., j is contained in invertedA[b[i]] ArrayDeque<Integer> queue = new ArrayDeque<Integer>(); boolean[] visited = new boolean[n]; int[] prev = new int[n]; Arrays.fill(prev, -1); ArrayList<ArrayList<Integer>> cycles = new ArrayList<ArrayList<Integer>>(); for(int i=0; i<n; i++) { if(visited[i]) continue; queue.add(i); while(!queue.isEmpty()) { int curr = queue.pollFirst(); visited[curr] = true; for(int next: invertedA[b[i]]) { prev[next] = curr; if(visited[next]) { var cycle = new ArrayList<Integer>(); cycle.add(next); while(curr != next) { curr = prev[curr]; cycle.add(curr); } cycles.add(cycle); } else queue.add(next); } } } sadness = n-cycles.size(); return sadness; } // int[] a; // int[] b; // HashSet<Integer>[] invertedA; // HashSet<Integer>[] invertedB; // boolean[] visitedA; // boolean[] visitedB; // boolean[] usedA; // boolean[] usedB; // ArrayList<ArrayList<Integer>> cycles; // // private ArrayList<Integer> dfs(int curr, boolean isA) { // if(isA) { // if(visitedA[curr]) // return null; // visitedA[curr] = true; // var cycle = dfs(curr, false); // if(cycle != null) { // if(cycle.get(0) == curr) { // cycles.add(cycle); // for(int i=0; i<cycle.size(); i++) { // if( (i&1) == 0) // usedA[cycle.get(i)] = true; // else // usedB[cycle.get(i)] = true; // } // return null; // } // else { // cycle.add(curr); // return cycle; // } // } // // } // else { // if(visitedB[curr]) // return null; // visitedB[curr] = true; // for(int next: invertedA[b[curr]]) // if(visitedA[next] && !usedA[next]) { // var cycle = new ArrayList<Integer>(); // cycle.add(next); // cycle.add(curr); // return cycle; // } // for(int next: invertedA[b[curr]]) { // var cycle = dfs(next, true); // if(cycle != null) { // cycle.add(curr); // return cycle; // } // } // } // return null; // } private int computeSadness2(int[] a, int[] b) { int n = a.length; HashSet<Integer>[] invertedA = new HashSet[n+1]; HashSet<Integer>[] invertedB = new HashSet[n+1]; for(int i=1; i<=n; i++) { invertedA[i] = new HashSet<Integer>(); invertedB[i] = new HashSet<Integer>(); } for(int i=0; i<n; i++) { if(a[i] == b[i]) continue; invertedA[a[i]].add(i); invertedB[b[i]].add(i); } int sadness = 0; HashMap<Long, HashSet<Integer>> intersections = new HashMap<>(); for(int i=0; i<n; i++) { if(a[i] == b[i]) { } else { sadness++; // wants to find j s.t. // j in invertedA[b[i]] and invertedB[a[i]] HashSet<Integer> intersection = intersections.get(pack(a[i], b[i])); if(intersection == null) { intersection = new HashSet<>(invertedA[b[i]]); intersection.retainAll(invertedB[a[i]]); intersections.put(pack(a[i], b[i]), intersection); } if(!intersection.isEmpty()) { var iter = intersection.iterator(); int j = iter.next(); iter.remove(); swap(b, i, j); invertedB[a[i]].remove(j); invertedA[b[i]].remove(j); invertedA[a[i]].remove(i); invertedB[b[i]].remove(i); } } } return sadness; } private void swap(int[] arr, int i, int j) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } private long pack(int a, int b) { return (long)a << 32 + b; } private int[] computeWorst(int[] a) { int n = a.length; Integer[] sortedIdx = new Integer[n]; for(int i=0; i<n; i++) sortedIdx[i] = i; Arrays.sort(sortedIdx, new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { return Integer.compare(a[o1], a[o2]); } }); ArrayList<Pair> cycles = new ArrayList<>(); int start = 0; while(start < n) { int end = start+1; while(end < n && a[sortedIdx[start]] == a[sortedIdx[end]]) end++; cycles.add(new Pair(a[sortedIdx[start]], end-start)); start = end; } if(cycles.size() == 1) return a; start = 0; for(int i=1; i<cycles.size(); i++) { if(cycles.get(i).len > cycles.get(start).len) start = i; } int[] b = new int[n]; int idx = 0; for(int i=0; i<start; i++) idx += cycles.get(i).len; int i = start+1; do { i = i==cycles.size()? 0: i; int val = cycles.get(i).val; int len = cycles.get(i).len; for(int j=0; j<len; j++) b[sortedIdx[j+idx<n? j+idx: j+idx-n]] = val; idx += len; idx = idx>=n? idx-n: idx; i++; }while(i != start+1); // 1 4 1 4 1 4 // 4 1 4 1 4 1 // 1 1 1 4 4 4 // 4 4 4 1 1 1 // 1 4 1 4 1 4 // sortedIdx[0] = 0 // sortedIdx[1] = 2 // sortedIdx[2] = 4 // 1 1 1 4 4 4 return b; } static class Pair{ int val; int len; public Pair(int val, int len) { this.val = val; this.len = len; } } 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(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(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 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
["4\n\n2\n\n2 1\n\n1 2\n\n4\n\n1 2 3 3\n\n3 3 2 1\n\n2\n\n2 1\n\n2 1\n\n4\n\n1 2 3 3\n\n3 2 3 1"]
1 second
["AC\nAC\nWA\nWA"]
NoteIn the first test case, the array $$$[1,2]$$$ has sadness $$$1$$$. We can transform $$$[1,2]$$$ into $$$[2,1]$$$ using one operation with $$$(i,j)=(1,2)$$$.In the second test case, the array $$$[3,3,2,1]$$$ has sadness $$$2$$$. We can transform $$$[3,3,2,1]$$$ into $$$[1,2,3,3]$$$ with two operations with $$$(i,j)=(1,4)$$$ and $$$(i,j)=(2,3)$$$ respectively.In the third test case, the array $$$[2,1]$$$ has sadness $$$0$$$.In the fourth test case, the array $$$[3,2,3,1]$$$ has sadness $$$1$$$.
Java 11
standard input
[ "constructive algorithms", "dfs and similar", "graphs" ]
a8f7f64db8fdf42294909774884bec96
Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$)  — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$)  — the length of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$)  — the elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \leq b_i \leq n$$$)  — the elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
2,800
For each test case, print "AC" (without quotes) if $$$b$$$ has the maximum sadness over all permutations of $$$a$$$, and "WA" (without quotes) otherwise.
standard output
PASSED
b0bbaac88d6154ff1a2a826954936983
train_108.jsonl
1650722700
oolimry has an array $$$a$$$ of length $$$n$$$ which he really likes. Today, you have changed his array to $$$b$$$, a permutation of $$$a$$$, to make him sad.Because oolimry is only a duck, he can only perform the following operation to restore his array: Choose two integers $$$i,j$$$ such that $$$1 \leq i,j \leq n$$$. Swap $$$b_i$$$ and $$$b_j$$$. The sadness of the array $$$b$$$ is the minimum number of operations needed to transform $$$b$$$ into $$$a$$$.Given the arrays $$$a$$$ and $$$b$$$, where $$$b$$$ is a permutation of $$$a$$$, determine if $$$b$$$ has the maximum sadness over all permutations of $$$a$$$.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author lucasr */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; MyScanner in = new MyScanner(inputStream); PrintWriter out = new PrintWriter(outputStream); F2CheckerForArrayShuffling solver = new F2CheckerForArrayShuffling(); int testCount = Integer.parseInt(in.next()); for (int i = 1; i <= testCount; i++) solver.solve(i, in, out); out.close(); } static class F2CheckerForArrayShuffling { public static MyScanner sc; public static PrintWriter out; public void solve(int testNumber, MyScanner sc, PrintWriter out) { F2CheckerForArrayShuffling.sc = sc; F2CheckerForArrayShuffling.out = out; int n = sc.nextInt(); int[] a = sc.nextIntArray(n, true); int[] b = sc.nextIntArray(n, true); int big = mostCommon(a); IntArray[] adj = new IntArray[n]; for (int i = 0; i < n; i++) { adj[i] = new IntArray(); } for (int i = 0; i < n; i++) { if (a[i] != big && b[i] != big) { adj[a[i]].add(b[i]); } } out.println(new GraphLib.DirectedGraphCycleFinder(adj).findCycleIfExists() == null ? "AC" : "WA"); } static int mostCommon(int[] a) { int[] freq = new int[a.length]; for (int i : a) { freq[i]++; } int ret = 0; for (int i = 1; i < freq.length; i++) { if (freq[i] >= freq[ret]) ret = i; } return ret; } } static class GraphLib { public static class DirectedGraphCycleFinder { int n; IntArray[] adj; int[] color; int[] parent; int cycleStart; int cycleEnd; public DirectedGraphCycleFinder(IntArray[] adj) { this.adj = adj; this.n = adj.length; } private boolean dfs(int v) { color[v] = 1; for (int i = 0; i < adj[v].size(); i++) { int u = adj[v].get(i); if (color[u] == 0) { parent[u] = v; if (dfs(u)) return true; } else if (color[u] == 1) { cycleEnd = v; cycleStart = u; return true; } } color[v] = 2; return false; } public IntArray findCycleIfExists() { color = new int[n]; parent = new int[n]; Arrays.fill(parent, -1); cycleStart = -1; for (int v = 0; v < n; v++) if (color[v] == 0 && dfs(v)) { break; } if (cycleStart == -1) { return null; } IntArray cycle = new IntArray(); cycle.add(cycleStart); for (int v = cycleEnd; v != cycleStart; v = parent[v]) { cycle.add(v); } cycle.add(cycleStart); cycle.reverse(); return cycle; } } } static class ArrayUtils { public static void reverse(int[] array, int from, int to) { while (from < to) { int tmp = array[from]; array[from] = array[to]; array[to] = tmp; from++; to--; } } } static class MyScanner { private BufferedReader br; private StringTokenizer tokenizer; public MyScanner(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(br.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public int[] nextIntArray(int n, boolean subtractOne) { int add = subtractOne ? -1 : 0; int[] ret = new int[n]; for (int i = 0; i < n; i++) { ret[i] = nextInt() + add; } return ret; } } static class IntArray { int[] arr; int size; public IntArray() { arr = new int[4]; } public void add(int val) { if (size == arr.length) { arr = Arrays.copyOf(arr, 2 * arr.length); } arr[size++] = val; } public int get(int pos) { return arr[pos]; } public int size() { return size; } public void reverse() { ArrayUtils.reverse(arr, 0, size - 1); } public int[] toArray() { return Arrays.copyOf(arr, size); } public String toString() { return "IntArray " + Arrays.toString(toArray()); } } }
Java
["4\n\n2\n\n2 1\n\n1 2\n\n4\n\n1 2 3 3\n\n3 3 2 1\n\n2\n\n2 1\n\n2 1\n\n4\n\n1 2 3 3\n\n3 2 3 1"]
1 second
["AC\nAC\nWA\nWA"]
NoteIn the first test case, the array $$$[1,2]$$$ has sadness $$$1$$$. We can transform $$$[1,2]$$$ into $$$[2,1]$$$ using one operation with $$$(i,j)=(1,2)$$$.In the second test case, the array $$$[3,3,2,1]$$$ has sadness $$$2$$$. We can transform $$$[3,3,2,1]$$$ into $$$[1,2,3,3]$$$ with two operations with $$$(i,j)=(1,4)$$$ and $$$(i,j)=(2,3)$$$ respectively.In the third test case, the array $$$[2,1]$$$ has sadness $$$0$$$.In the fourth test case, the array $$$[3,2,3,1]$$$ has sadness $$$1$$$.
Java 11
standard input
[ "constructive algorithms", "dfs and similar", "graphs" ]
a8f7f64db8fdf42294909774884bec96
Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$)  — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$)  — the length of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$)  — the elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \leq b_i \leq n$$$)  — the elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
2,800
For each test case, print "AC" (without quotes) if $$$b$$$ has the maximum sadness over all permutations of $$$a$$$, and "WA" (without quotes) otherwise.
standard output
PASSED
58e07068fc83e6e6c577439b86c8c390
train_108.jsonl
1650722700
oolimry has an array $$$a$$$ of length $$$n$$$ which he really likes. Today, you have changed his array to $$$b$$$, a permutation of $$$a$$$, to make him sad.Because oolimry is only a duck, he can only perform the following operation to restore his array: Choose two integers $$$i,j$$$ such that $$$1 \leq i,j \leq n$$$. Swap $$$b_i$$$ and $$$b_j$$$. The sadness of the array $$$b$$$ is the minimum number of operations needed to transform $$$b$$$ into $$$a$$$.Given the arrays $$$a$$$ and $$$b$$$, where $$$b$$$ is a permutation of $$$a$$$, determine if $$$b$$$ has the maximum sadness over all permutations of $$$a$$$.
256 megabytes
import java.io.*; import java.util.*; import java.util.concurrent.ThreadLocalRandom; import java.math.*; /** _ _ ( _) ( _) / / \\ / /\_\_ / / \\ / / | \ \ / / \\ / / |\ \ \ / / , \ , / / /| \ \ / / |\_ /| / / / \ \_\ / / |\/ _ '_| \ / / / \ \\ | / |/ 0 \0\ / | | \ \\ | |\| \_\_ / / | \ \\ | | |/ \.\ o\o) / \ | \\ \ | /\\`v-v / | | \\ | \/ /_| \\_| / | | \ \\ | | /__/_ - / ___ | | \ \\ \| [__] \_/ |_________ \ | \ () / [___] ( \ \ |\ | | // | [___] |\| \| / |/ /| [____] \ |/\ / / || ( \ [____ / ) _\ \ \ \| | || \ \ [_____| / / __/ \ / / // | \ [_____/ / / \ | \/ // | / '----| /=\____ _/ | / // __ / / | / ___/ _/\ \ | || (/-(/-\) / \ (/\/\)/ | / | / (/\/\) / / // _________/ / / \____________/ ( @author NTUDragons-Reborn */ public class C{ public static void main(String[] args) throws Exception { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); Task solver = new Task(); solver.solve(in, out); out.close(); } // main solver static class Task{ double eps= 0.00000001; static final int MAXN = 100005; static final int MOD= 1000000007; // stores smallest prime factor for every number static int spf[] = new int[MAXN]; static boolean[] prime; Map<Integer,Set<Integer>> dp= new HashMap<>(); // Calculating SPF (Smallest Prime Factor) for every // number till MAXN. // Time Complexity : O(nloglogn) public 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; } } } void sieveOfEratosthenes(int n) { // Create a boolean array // "prime[0..n]" and // initialize all entries // it as true. A value in // prime[i] will finally be // false if i is Not a // prime, else true. prime= new boolean[n + 1]; for (int i = 0; i <= n; i++) prime[i] = true; for (int p = 2; p * p <= n; p++) { // If prime[p] is not changed, then it is a // prime if (prime[p] == true) { // Update all multiples of p for (int i = p * p; i <= n; i += p) prime[i] = false; } } } // A O(log n) function returning primefactorization // by dividing by smallest prime factor at every step public Set<Integer> getFactorization(int x) { if(dp.containsKey(x)) return dp.get(x); Set<Integer> ret = new HashSet<>(); while (x != 1) { if(spf[x]!=2) ret.add(spf[x]); x = x / spf[x]; } dp.put(x,ret); return ret; } public Map<Integer,Integer> getFactorizationPower(int x){ Map<Integer,Integer> map= new HashMap<>(); while(x!=1){ map.put(spf[x], map.getOrDefault(spf[x], 0)+1); x/= spf[x]; } return map; } // function to find first index >= x public int lowerIndex(List<Integer> arr, int n, int x) { int l = 0, h = n - 1; while (l <= h) { int mid = (l + h) / 2; if (arr.get(mid) >= x) h = mid - 1; else l = mid + 1; } return l; } public int lowerIndex(int[] arr, int n, int x) { int l = 0, h = n - 1; while (l <= h) { int mid = (l + h) / 2; if (arr[mid] >= x) h = mid - 1; else l = mid + 1; } return l; } // function to find last index <= y public int upperIndex(List<Integer> arr, int n, int y) { int l = 0, h = n - 1; while (l <= h) { int mid = (l + h) / 2; if (arr.get(mid) <= y) l = mid + 1; else h = mid - 1; } return h; } public int upperIndex(int[] arr, int n, int y) { int l = 0, h = n - 1; while (l <= h) { int mid = (l + h) / 2; if (arr[mid] <= y) l = mid + 1; else h = mid - 1; } return h; } // function to count elements within given range public int countInRange(List<Integer> arr, int n, int x, int y) { // initialize result int count = 0; count = upperIndex(arr, n, y) - lowerIndex(arr, n, x) + 1; return count; } public int add(int a, int b){ a+=b; while(a>=MOD) a-=MOD; while(a<0) a+=MOD; return a; } public int mul(int a, int b){ long res= (long)a*(long)b; return (int)(res%MOD); } public int power(int a, int b) { int ans=1; while(b>0){ if((b&1)!=0) ans= mul(ans,a); b>>=1; a= mul(a,a); } return ans; } int[] fact= new int[MAXN]; int[] inv= new int[MAXN]; public int Ckn(int n, int k){ if(k<0 || n<0) return 0; if(n<k) return 0; return mul(mul(fact[n],inv[k]),inv[n-k]); } public int inverse(int a){ return power(a,MOD-2); } public void preprocess() { fact[0]=1; for(int i=1;i<MAXN;i++) fact[i]= mul(fact[i-1],i); inv[MAXN-1]= inverse(fact[MAXN-1]); for(int i=MAXN-2;i>=0;i--){ inv[i]= mul(inv[i+1],i+1); } } /** * return VALUE of lower bound for unsorted array */ public int lowerBoundNormalArray(int[] arr, int x){ TreeSet<Integer> set= new TreeSet<>(); for(int num: arr) set.add(num); return set.lower(x); } /** * return VALUE of upper bound for unsorted array */ public int upperBoundNormalArray(int[] arr, int x){ TreeSet<Integer> set= new TreeSet<>(); for(int num: arr) set.add(num); return set.higher(x); } public void debugArr(int[] arr){ for(int i: arr) out.print(i+" "); out.println(); } public int rand(){ int min=0, max= MAXN; int random_int = (int)Math.floor(Math.random()*(max-min+1)+min); return random_int; } public void suffleSort(int[] arr){ shuffleArray(arr); Arrays.sort(arr); } public void shuffleArray(int[] ar) { // If running on Java 6 or older, use new Random() on RHS here Random rnd = ThreadLocalRandom.current(); for (int i = ar.length - 1; i > 0; i--) { int index = rnd.nextInt(i + 1); // Simple swap int a = ar[index]; ar[index] = ar[i]; ar[i] = a; } } InputReader in; PrintWriter out; Scanner sc= new Scanner(System.in); CustomFileReader cin; int[] xor= new int[3*100000+5]; int[] pow2= new int[1000000+1]; public void solve(InputReader in, PrintWriter out) throws Exception { this.in=in; this.out=out; // sieve(); // pow2[0]=1; // for(int i=1;i<pow2.length;i++){ // pow2[i]= mul(pow2[i-1],2); // } int t=in.nextInt(); // preprocess(); // int t=in.nextInt(); // int t= cin.nextIntArrLine()[0]; for(int i=1;i<=t;i++) solveF(i); } final double pi= Math.acos(-1); static Point base; boolean cycle= false; boolean[] vis, onWay; List[] adjs; void solveF(int test) throws Exception{ int n= in.nextInt(); int[] a= in.nextIntArr(n); int[] b= in.nextIntArr(n); cycle= false; vis= new boolean[n+1]; onWay= new boolean[n+1]; adjs= new List[n+1]; for(int i=0;i<=n;i++) adjs[i]= new ArrayList<>(); for(int i=0;i<n;i++) adjs[a[i]].add(b[i]); int mx=0; for(int i=1;i<=n;i++) { if(adjs[i].size()>=adjs[mx].size()) mx= i; } vis[mx] = true; // mark true to remove value of most occurence for(int i=1;i<=n;i++){ if(!vis[i]) { dfs(i); } } if(cycle) out.println("WA"); else out.println("AC"); } void dfs(int i){ vis[i]= true; onWay[i]= true; for(int j: (List<Integer>)adjs[i]){ if(onWay[j]) cycle= true; if(!vis[j]) dfs(j); } onWay[i]= false; } static class ListNode{ int idx=-1; ListNode next= null; public ListNode(int idx){ this.idx= idx; } } public long _gcd(long a, long b) { if(b == 0) { return a; } else { return _gcd(b, a % b); } } public long _lcm(long a, long b){ return (a*b)/_gcd(a,b); } } // static class SEG { // Pair[] segtree; // public SEG(int n){ // segtree= new Pair[4*n]; // Arrays.fill(segtree, new Pair(-1,Long.MAX_VALUE)); // } // // void buildTree(int l, int r, int index) { // // if (l == r) { // // segtree[index].y = a[l]; // // return; // // } // // int mid = (l + r) / 2; // // buildTree(l, mid, 2 * index + 1); // // buildTree(mid + 1, r, 2 * index + 2); // // segtree[index].y = Math.min(segtree[2 * index + 1].y, segtree[2 * index + 2].y); // // } // void update(int l, int r, int index, int pos, Pair val) { // if (l == r) { // segtree[index] = val; // return; // } // int mid = (l + r) / 2; // if (pos <= mid) update(l, mid, 2 * index + 1, pos, val); // else update(mid + 1, r, 2 * index + 2, pos, val); // if(segtree[2 * index + 1].y < segtree[2 * index + 2].y){ // segtree[index]= segtree[2 * index + 1]; // } // else { // segtree[index]= segtree[2 * index + 2]; // } // } // // Pair query(int l, int r, int from, int to, int index) { // // if (from <= l && r <= to) // // return segtree[index]; // // if (r < from | to < l) // // return 0; // // int mid = (l + r) / 2; // // Pair left= query(l, mid, from, to, 2 * index + 1); // // Pair right= query(mid + 1, r, from, to, 2 * index + 2); // // if(left.y < right.y) return left; // // else return right; // // } // } static class Venice{ public Map<Long,Long> m= new HashMap<>(); public long base=0; public long totalValue=0; private int M= 1000000007; private long addMod(long a, long b){ a+=b; if(a>=M) a-=M; return a; } public void reset(){ m= new HashMap<>(); base=0; totalValue=0; } public void update(long add){ base= base+ add; } public void add(long key, long val){ long newKey= key-base; m.put(newKey, addMod(m.getOrDefault(newKey,(long)0),val)); } } static class Tuple implements Comparable<Tuple>{ int x, y, z; public Tuple(int x, int y, int z){ this.x= x; this.y= y; this.z=z; } @Override public int compareTo(Tuple o){ return this.z-o.z; } } static class Point implements Comparable<Point>{ public double x; public long y; public Point(double x, long y){ this.x= x; this.y= y; } @Override public int compareTo(Point o) { if(this.y!=o.y) return (int)(this.y-o.y); return (int)(this.x-o.x); } } // static class Vector { // public long x; // public long y; // // p1 -> p2 // public Vector(Point p1, Point p2){ // this.x= p2.x-p1.x; // this.y= p2.y-p1.y; // } // } 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 int compareTo(Pair o) { if(this.x!=o.x) return (int)(this.x-o.x); return (int)(this.y-o.y); } } // public static class compareL implements Comparator<Tuple>{ // @Override // public int compare(Tuple t1, Tuple t2) { // return t2.l - t1.l; // } // } // fast input reader class; static class InputReader { BufferedReader br; StringTokenizer st; public InputReader(InputStream stream) { br = new BufferedReader(new InputStreamReader(stream)); } public String nextToken() { while (st == null || !st.hasMoreTokens()) { String line = null; try { line = br.readLine(); } catch (IOException e) { throw new RuntimeException(e); } if (line == null) { return null; } st = new StringTokenizer(line); } return st.nextToken(); } public int nextInt() { return Integer.parseInt(nextToken()); } public double nextDouble(){ return Double.parseDouble(nextToken()); } public long nextLong(){ return Long.parseLong(nextToken()); } public int[] nextIntArr(int n){ int[] arr= new int[n]; for(int i=0;i<n;i++) arr[i]= nextInt(); return arr; } public long[] nextLongArr(int n){ long[] arr= new long[n]; for(int i=0;i<n;i++) arr[i]= nextLong(); return arr; } public List<Integer> nextIntList(int n){ List<Integer> arr= new ArrayList<>(); for(int i=0;i<n;i++) arr.add(nextInt()); return arr; } public int[][] nextIntMatArr(int n, int m){ int[][] mat= new int[n][m]; for(int i=0;i<n;i++) for(int j=0;j<m;j++) mat[i][j]= nextInt(); return mat; } public List<List<Integer>> nextIntMatList(int n, int m){ List<List<Integer>> mat= new ArrayList<>(); for(int i=0;i<n;i++){ List<Integer> temp= new ArrayList<>(); for(int j=0;j<m;j++) temp.add(nextInt()); mat.add(temp); } return mat; } public char[] nextStringCharArr(){ return nextToken().toCharArray(); } } static class CustomFileReader{ String path=""; Scanner sc; public CustomFileReader(String path){ this.path=path; try{ sc= new Scanner(new File(path)); } catch(Exception e){} } public String nextLine(){ return sc.nextLine(); } public int[] nextIntArrLine(){ String line= sc.nextLine(); String[] part= line.split("[\\s+]"); int[] res= new int[part.length]; for(int i=0;i<res.length;i++) res[i]= Integer.parseInt(part[i]); return res; } } }
Java
["4\n\n2\n\n2 1\n\n1 2\n\n4\n\n1 2 3 3\n\n3 3 2 1\n\n2\n\n2 1\n\n2 1\n\n4\n\n1 2 3 3\n\n3 2 3 1"]
1 second
["AC\nAC\nWA\nWA"]
NoteIn the first test case, the array $$$[1,2]$$$ has sadness $$$1$$$. We can transform $$$[1,2]$$$ into $$$[2,1]$$$ using one operation with $$$(i,j)=(1,2)$$$.In the second test case, the array $$$[3,3,2,1]$$$ has sadness $$$2$$$. We can transform $$$[3,3,2,1]$$$ into $$$[1,2,3,3]$$$ with two operations with $$$(i,j)=(1,4)$$$ and $$$(i,j)=(2,3)$$$ respectively.In the third test case, the array $$$[2,1]$$$ has sadness $$$0$$$.In the fourth test case, the array $$$[3,2,3,1]$$$ has sadness $$$1$$$.
Java 11
standard input
[ "constructive algorithms", "dfs and similar", "graphs" ]
a8f7f64db8fdf42294909774884bec96
Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$)  — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$)  — the length of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$)  — the elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \leq b_i \leq n$$$)  — the elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
2,800
For each test case, print "AC" (without quotes) if $$$b$$$ has the maximum sadness over all permutations of $$$a$$$, and "WA" (without quotes) otherwise.
standard output
PASSED
97bb79587d2631dbfafd9bf1ba679be4
train_108.jsonl
1650722700
oolimry has an array $$$a$$$ of length $$$n$$$ which he really likes. Today, you have changed his array to $$$b$$$, a permutation of $$$a$$$, to make him sad.Because oolimry is only a duck, he can only perform the following operation to restore his array: Choose two integers $$$i,j$$$ such that $$$1 \leq i,j \leq n$$$. Swap $$$b_i$$$ and $$$b_j$$$. The sadness of the array $$$b$$$ is the minimum number of operations needed to transform $$$b$$$ into $$$a$$$.Given the arrays $$$a$$$ and $$$b$$$, where $$$b$$$ is a permutation of $$$a$$$, determine if $$$b$$$ has the maximum sadness over all permutations of $$$a$$$.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Random; import java.util.StringTokenizer; /* 1 6 1 2 3 4 4 4 4 4 4 1 2 3 5 1 2 4 4 4 4 4 1 2 4 5 1 2 3 4 4 4 4 1 2 3 1 3 2 3 1 1 2 3 1 5 1 3 2 5 4 2 5 1 4 3 6 [3, 5, 3, 5, 5, 2] [2, 3, 5, 3, 5, 5] 1 6 2 3 5 3 5 5 3 5 3 5 5 2 6 5 4 3 5 4 3 3 3 4 4 5 5 1 6 5 4 3 5 4 3 3 3 4 4 5 5 */ public class F4 { public static void main(String[] args) { FastScanner fs=new FastScanner(); int T=fs.nextInt(); outer: for (int tt=0; tt<T; tt++) { int n=fs.nextInt(); int[] a=fs.readArray(n); int[] b=fs.readArray(n); // Node[] nodes=new Node[n+1]; Node[] nodes2=new Node[n+1]; // for (int i=0; i<=n; i++) nodes[i]=new Node(i); for (int i=0; i<=n; i++) nodes2[i]=new Node(i); for (int i=0; i<n; i++) { // nodes[a[i]].adj.add(nodes[b[i]]); nodes2[a[i]].adj.add(nodes2[b[i]]); } // Node maxFreq=nodes[0]; // for (Node nn:nodes) // if (nn.adj.size()>maxFreq.adj.size()) // maxFreq=nn; Node maxFreq2=nodes2[0]; for (Node nn:nodes2) if (nn.adj.size()>maxFreq2.adj.size()) maxFreq2=nn; for (Node nn:nodes2) { if (nn==maxFreq2) continue; for (Node nnn:nn.adj) nnn.indegree++; } ArrayDeque<Node> bfs=new ArrayDeque<>(); for (Node nn:nodes2) { if (nn==maxFreq2) continue; if (nn.indegree==0) bfs.addLast(nn); } while (!bfs.isEmpty()) { Node next=bfs.remove(); for (Node nn:next.adj) { if (nn==maxFreq2) continue; nn.indegree--; if (nn.indegree==0) bfs.addLast(nn); } } boolean works=true; for (Node nn:nodes2) works&=nn.indegree==0 || nn==maxFreq2; System.out.println(works?"AC":"WA"); // maxFreq.isMax=true; // for (Node nn:nodes) { // if (nn.full()) continue; // nn.dfs(); // } // for (Node nn:nodes) { // if (nn.extraLoopStarts>0) { // System.out.println("WA"); // continue outer; // } // } // System.out.println("AC"); } } //every time you start at a node (except for the first time), you create a new loop static class Node { ArrayList<Node> adj=new ArrayList<>(); int edgeAt=0; int value; int extraLoopStarts=0; boolean isMax=false; int indegree=0; public Node(int value) { this.value=value; } public void dfs() { if (isMax) return; if (edgeAt!=0) extraLoopStarts++; while (!full()) { Node to=adj.get(edgeAt); edgeAt++; to.dfs(); } } boolean full() { return edgeAt==adj.size(); } } static final Random random=new Random(7); static final int mod=1_000_000_007; static void ruffleSort(int[] a) { int n=a.length;//shuffle, then sort for (int i=0; i<n; i++) { int oi=random.nextInt(n), temp=a[oi]; a[oi]=a[i]; a[i]=temp; } Arrays.sort(a); } static long add(long a, long b) { return (a+b)%mod; } static long sub(long a, long b) { return ((a-b)%mod+mod)%mod; } static long mul(long a, long b) { return (a*b)%mod; } static long exp(long base, long exp) { if (exp==0) return 1; long half=exp(base, exp/2); if (exp%2==0) return mul(half, half); return mul(half, mul(half, base)); } static long[] factorials=new long[2_000_001]; static long[] invFactorials=new long[2_000_001]; static void precompFacts() { factorials[0]=invFactorials[0]=1; for (int i=1; i<factorials.length; i++) factorials[i]=mul(factorials[i-1], i); invFactorials[factorials.length-1]=exp(factorials[factorials.length-1], mod-2); for (int i=invFactorials.length-2; i>=0; i--) invFactorials[i]=mul(invFactorials[i+1], i+1); } static long nCk(int n, int k) { return mul(factorials[n], mul(invFactorials[k], invFactorials[n-k])); } static void sort(int[] a) { ArrayList<Integer> l=new ArrayList<>(); for (int i:a) l.add(i); Collections.sort(l); for (int i=0; i<a.length; i++) a[i]=l.get(i); } static 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\n\n2\n\n2 1\n\n1 2\n\n4\n\n1 2 3 3\n\n3 3 2 1\n\n2\n\n2 1\n\n2 1\n\n4\n\n1 2 3 3\n\n3 2 3 1"]
1 second
["AC\nAC\nWA\nWA"]
NoteIn the first test case, the array $$$[1,2]$$$ has sadness $$$1$$$. We can transform $$$[1,2]$$$ into $$$[2,1]$$$ using one operation with $$$(i,j)=(1,2)$$$.In the second test case, the array $$$[3,3,2,1]$$$ has sadness $$$2$$$. We can transform $$$[3,3,2,1]$$$ into $$$[1,2,3,3]$$$ with two operations with $$$(i,j)=(1,4)$$$ and $$$(i,j)=(2,3)$$$ respectively.In the third test case, the array $$$[2,1]$$$ has sadness $$$0$$$.In the fourth test case, the array $$$[3,2,3,1]$$$ has sadness $$$1$$$.
Java 8
standard input
[ "constructive algorithms", "dfs and similar", "graphs" ]
a8f7f64db8fdf42294909774884bec96
Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$)  — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$)  — the length of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$)  — the elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \leq b_i \leq n$$$)  — the elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
2,800
For each test case, print "AC" (without quotes) if $$$b$$$ has the maximum sadness over all permutations of $$$a$$$, and "WA" (without quotes) otherwise.
standard output
PASSED
1d01fbd29b895166dd33d827672e8ef9
train_108.jsonl
1654266900
As for the technology in the outside world, it is really too advanced for Gensokyo to even look up to.—Yasaka Kanako, Symposium of Post-mysticismThis is an interactive problem.Under the direct supervision of Kanako and the Moriya Shrine, the railway system of Gensokyo is finally finished. GSKR (Gensokyo Railways) consists of $$$n$$$ stations with $$$m$$$ bidirectional tracks connecting them. The $$$i$$$-th track has length $$$l_i$$$ ($$$1\le l_i\le 10^6$$$). Due to budget limits, the railway system may not be connected, though there may be more than one track between two stations.The value of a railway system is defined as the total length of its all tracks. The maximum (or minimum) capacity of a railway system is defined as the maximum (or minimum) value among all of the currently functional system's full spanning forest.In brief, full spanning forest of a graph is a spanning forest with the same connectivity as the given graph.Kanako has a simulator only able to process no more than $$$2m$$$ queries. The input of the simulator is a string $$$s$$$ of length $$$m$$$, consisting of characters 0 and/or 1. The simulator will assume the $$$i$$$-th track functional if $$$s_i=$$$ 1. The device will then tell Kanako the maximum capacity of the system in the simulated state.Kanako wants to know the the minimum capacity of the system with all tracks functional with the help of the simulator.The structure of the railway system is fixed in advance. In other words, the interactor is not adaptive.
256 megabytes
import java.io.*; import java.util.*; public class RailwaySystem { public static void solve(FastIO io) { io.nextInt(); final int M = io.nextInt(); Edge[] edges = new Edge[M]; for (int i = 0; i < M; ++i) { int id = i + 1; final int L = query(io, M, id); edges[i] = new Edge(id, L); } BucketSort.sort(edges, new BucketSort.IntConverter<Edge>() { @Override public int toInt(Edge e) { return e.weight; } }); IntDeque used = new IntDeque(); int prev = 0; for (Edge e : edges) { used.push(e.id); int curr = query(io, M, used.toArray()); if (curr == prev + e.weight) { prev = curr; } else { used.pop(); } } answer(io, prev); } private static int query(FastIO io, int M, int... which) { char[] S = new char[M + 1]; Arrays.fill(S, '0'); for (int x : which) { S[x] = '1'; } io.println('?', new String(S, 1, M)); io.flush(); return io.nextInt(); } private static void answer(FastIO io, int ans) { io.println('!', ans); io.flush(); } private static class Edge { public int id; public int weight; public Edge(int id, int weight) { this.id = id; this.weight = weight; } } public static class BucketSort { public static <T> T[] sortReversed(T[] items, IntConverter<T> converter) { sort(items, converter); for (int i = 0, j = items.length - 1; i < j; ++i, --j) { T tmp = items[i]; items[i] = items[j]; items[j] = tmp; } return items; } public static <T> T[] sort(T[] items, IntConverter<T> converter) { final int N = items.length; int[] values = new int[N]; int minVal = Integer.MAX_VALUE; int maxVal = Integer.MIN_VALUE; for (int i = 0; i < items.length; ++i) { values[i] = converter.toInt(items[i]); minVal = Math.min(minVal, values[i]); maxVal = Math.max(maxVal, values[i]); } int capacity = maxVal - minVal + 1; ArrayList<ArrayList<T>> buckets = new ArrayList<>(capacity); for (int i = 0; i < capacity; ++i) { buckets.add(null); } for (int i = 0; i < items.length; ++i) { int bucketIndex = values[i] - minVal; ArrayList<T> lst = buckets.get(bucketIndex); if (lst == null) { lst = new ArrayList<>(); buckets.set(bucketIndex, lst); } lst.add(items[i]); } int p = 0; for (ArrayList<T> lst : buckets) { if (lst == null) { continue; } for (T item : lst) { items[p++] = item; } } return items; } public static int[] sortIntsReversed(int[] items) { sortInts(items); for (int i = 0, j = items.length - 1; i < j; ++i, --j) { int tmp = items[i]; items[i] = items[j]; items[j] = tmp; } return items; } public static int[] sortInts(int[] items) { final int N = items.length; int minVal = Integer.MAX_VALUE; int maxVal = Integer.MIN_VALUE; for (int i = 0; i < items.length; ++i) { minVal = Math.min(minVal, items[i]); maxVal = Math.max(maxVal, items[i]); } int capacity = maxVal - minVal + 1; int[] counts = new int[capacity]; for (int i = 0; i < N; ++i) { int bucketIndex = items[i] - minVal; ++counts[bucketIndex]; } int p = 0; for (int i = 0; i < capacity; ++i) { int origVal = i + minVal; for (int j = 0; j < counts[i]; ++j) { items[p++] = origVal; } } return items; } public static char[] sortCharsReversed(char[] items) { sortChars(items); for (int i = 0, j = items.length - 1; i < j; ++i, --j) { char tmp = items[i]; items[i] = items[j]; items[j] = tmp; } return items; } public static char[] sortChars(char[] items) { final int N = items.length; int minVal = Integer.MAX_VALUE; int maxVal = Integer.MIN_VALUE; for (int i = 0; i < items.length; ++i) { minVal = Math.min(minVal, items[i]); maxVal = Math.max(maxVal, items[i]); } int capacity = maxVal - minVal + 1; int[] counts = new int[capacity]; for (int i = 0; i < N; ++i) { int bucketIndex = items[i] - minVal; ++counts[bucketIndex]; } int p = 0; for (int i = 0; i < capacity; ++i) { char origVal = (char) (i + minVal); for (int j = 0; j < counts[i]; ++j) { items[p++] = origVal; } } return items; } public static interface IntConverter<T> { public int toInt(T item); } } /** * Circular buffer of int values, can be used as: * - ArrayList: values are added to end. * - Queue: values are added to end and removed from front. * - Stack: values are added to and removed from front. */ public static class IntDeque { private int[] arr; private int off; private int len; public IntDeque() { this(2); } public IntDeque(int capacity) { this.arr = new int[capacity]; } public void addFirst(int x) { if (len == arr.length) { increaseCapacity(); } if (off == 0) { off = arr.length; } arr[--off] = x; ++len; } public void addLast(int x) { if (len == arr.length) { increaseCapacity(); } int idx = index(off + len); arr[idx] = x; ++len; } public int peekFirst() { return arr[off]; } public int peekLast() { int idx = index(off + len - 1); return arr[idx]; } public int removeFirst() { int ans = peekFirst(); off = index(off + 1); --len; return ans; } public int removeLast() { int ans = peekLast(); --len; return ans; } public void add(int x) { addLast(x); } public void offer(int x) { addLast(x); } public int poll() { return removeFirst(); } public void push(int x) { addFirst(x); } public int pop() { return removeFirst(); } public int peek() { return peekFirst(); } public int get(int i) { if (i >= len) { throw new ArrayIndexOutOfBoundsException(String.format("index %d out of range [0, %d)", i, len)); } int idx = index(i + off); return arr[idx]; } public void set(int i, int x) { if (i >= len) { throw new ArrayIndexOutOfBoundsException(String.format("index %d out of range [0, %d)", i, len)); } int idx = index(i + off); arr[idx] = x; } public int size() { return len; } public boolean isEmpty() { return size() == 0; } public int[] toArray() { if (len == 0) { return new int[0]; } int idx = index(off + len); if (idx > off) { return Arrays.copyOfRange(arr, off, idx); } int[] A = new int[len]; int endLen = arr.length - off; int startLen = len - endLen; System.arraycopy(arr, off, A, 0, endLen); System.arraycopy(arr, 0, A, endLen, startLen); return A; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append('['); printToBuffer(sb, ", "); sb.append(']'); return sb.toString(); } private void increaseCapacity() { int[] next = new int[arr.length << 1]; int endLen = arr.length - off; System.arraycopy(arr, off, next, 0, endLen); System.arraycopy(arr, 0, next, endLen, off); arr = next; off = 0; } private int index(int i) { if (i >= arr.length) { i -= arr.length; } else if (i < 0) { i += arr.length; } return i; } private void printToBuffer(StringBuilder sb, CharSequence sep) { for (int i = 0; i < len; ++i) { if (i > 0) { sb.append(sep); } sb.append(get(i)); } } public static IntDeque of(int... arr) { IntDeque deq = new IntDeque(); for (int x : arr) { deq.add(x); } return deq; } } public static class FastIO { private InputStream reader; private PrintWriter writer; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public FastIO(InputStream r, OutputStream w) { reader = r; writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(w))); } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = reader.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public String nextString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } // TODO: read this byte-by-byte like the other read functions. public double nextDouble() { return Double.parseDouble(nextString()); } public int[] nextIntArray(int n) { return nextIntArray(n, 0); } public int[] nextIntArray(int n, int off) { int[] arr = new int[n + off]; for (int i = 0; i < n; i++) { arr[i + off] = nextInt(); } return arr; } public long[] nextLongArray(int n) { return nextLongArray(n, 0); } public long[] nextLongArray(int n, int off) { long[] arr = new long[n + off]; for (int i = 0; i < n; i++) { arr[i + off] = nextLong(); } return arr; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) { writer.print(' '); } writer.print(objects[i]); } } public void println(Object... objects) { print(objects); writer.println(); } public void printArray(int[] arr) { for (int i = 0; i < arr.length; i++) { if (i != 0) { writer.print(' '); } writer.print(arr[i]); } } public void printArray(long[] arr) { for (int i = 0; i < arr.length; i++) { if (i != 0) { writer.print(' '); } writer.print(arr[i]); } } public void printlnArray(int[] arr) { printArray(arr); writer.println(); } public void printlnArray(long[] arr) { printArray(arr); writer.println(); } public void printf(String format, Object... args) { print(String.format(format, args)); } public void flush() { writer.flush(); } } public static void main(String[] args) { FastIO io = new FastIO(System.in, System.out); solve(io); io.flush(); } }
Java
["5 4\n\n0\n\n5\n\n9\n\n7"]
1 second
["? 0000\n\n? 1110\n\n? 1111\n\n? 1101\n\n! 7"]
NoteHere is the graph of the example, satisfying $$$l_i=i$$$.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy", "interactive", "sortings" ]
003b7257b35416ec93f189cb29e458e6
The first and only line of input contains two integers $$$n,m$$$ ($$$2 \leq n \leq 200$$$, $$$1\le m \le 500$$$) — the number of stations and tracks.
1,700
null
standard output
PASSED
39e241f4f1044077d4b95f9170921e8d
train_108.jsonl
1654266900
As for the technology in the outside world, it is really too advanced for Gensokyo to even look up to.—Yasaka Kanako, Symposium of Post-mysticismThis is an interactive problem.Under the direct supervision of Kanako and the Moriya Shrine, the railway system of Gensokyo is finally finished. GSKR (Gensokyo Railways) consists of $$$n$$$ stations with $$$m$$$ bidirectional tracks connecting them. The $$$i$$$-th track has length $$$l_i$$$ ($$$1\le l_i\le 10^6$$$). Due to budget limits, the railway system may not be connected, though there may be more than one track between two stations.The value of a railway system is defined as the total length of its all tracks. The maximum (or minimum) capacity of a railway system is defined as the maximum (or minimum) value among all of the currently functional system's full spanning forest.In brief, full spanning forest of a graph is a spanning forest with the same connectivity as the given graph.Kanako has a simulator only able to process no more than $$$2m$$$ queries. The input of the simulator is a string $$$s$$$ of length $$$m$$$, consisting of characters 0 and/or 1. The simulator will assume the $$$i$$$-th track functional if $$$s_i=$$$ 1. The device will then tell Kanako the maximum capacity of the system in the simulated state.Kanako wants to know the the minimum capacity of the system with all tracks functional with the help of the simulator.The structure of the railway system is fixed in advance. In other words, the interactor is not adaptive.
256 megabytes
import java.io.*; import java.util.*; public class RailwaySystem { public static void solve(FastIO io) { io.nextInt(); final int M = io.nextInt(); Edge[] edges = new Edge[M]; for (int i = 0; i < M; ++i) { int id = i + 1; final int L = query(io, M, id); edges[i] = new Edge(id, L); } BucketSort.sort(edges, Edge::getWeight); IntDeque used = new IntDeque(); int prev = 0; for (Edge e : edges) { used.push(e.id); int curr = query(io, M, used.toArray()); if (curr == prev + e.weight) { prev = curr; } else { used.pop(); } } answer(io, prev); } private static int query(FastIO io, int M, int... which) { char[] S = new char[M + 1]; Arrays.fill(S, '0'); for (int x : which) { S[x] = '1'; } io.println('?', new String(S, 1, M)); io.flush(); return io.nextInt(); } private static void answer(FastIO io, int ans) { io.println('!', ans); io.flush(); } private static class Edge { public int id; public int weight; public Edge(int id, int weight) { this.id = id; this.weight = weight; } public int getWeight() { return weight; } public static final Comparator<Edge> BY_WEIGHT = new Comparator<Edge>() { public int compare(Edge a, Edge b) { return Integer.compare(a.weight, b.weight); } }; } public static class BucketSort { public static <T> T[] sortReversed(T[] items, IntConverter<T> converter) { sort(items, converter); for (int i = 0, j = items.length - 1; i < j; ++i, --j) { T tmp = items[i]; items[i] = items[j]; items[j] = tmp; } return items; } public static <T> T[] sort(T[] items, IntConverter<T> converter) { final int N = items.length; int[] values = new int[N]; int minVal = Integer.MAX_VALUE; int maxVal = Integer.MIN_VALUE; for (int i = 0; i < items.length; ++i) { values[i] = converter.toInt(items[i]); minVal = Math.min(minVal, values[i]); maxVal = Math.max(maxVal, values[i]); } int capacity = maxVal - minVal + 1; ArrayList<ArrayList<T>> buckets = new ArrayList<>(capacity); for (int i = 0; i < capacity; ++i) { buckets.add(null); } for (int i = 0; i < items.length; ++i) { int bucketIndex = values[i] - minVal; ArrayList<T> lst = buckets.get(bucketIndex); if (lst == null) { lst = new ArrayList<>(); buckets.set(bucketIndex, lst); } lst.add(items[i]); } int p = 0; for (ArrayList<T> lst : buckets) { if (lst == null) { continue; } for (T item : lst) { items[p++] = item; } } return items; } public static int[] sortIntsReversed(int[] items) { sortInts(items); for (int i = 0, j = items.length - 1; i < j; ++i, --j) { int tmp = items[i]; items[i] = items[j]; items[j] = tmp; } return items; } public static int[] sortInts(int[] items) { final int N = items.length; int minVal = Integer.MAX_VALUE; int maxVal = Integer.MIN_VALUE; for (int i = 0; i < items.length; ++i) { minVal = Math.min(minVal, items[i]); maxVal = Math.max(maxVal, items[i]); } int capacity = maxVal - minVal + 1; int[] counts = new int[capacity]; for (int i = 0; i < N; ++i) { int bucketIndex = items[i] - minVal; ++counts[bucketIndex]; } int p = 0; for (int i = 0; i < capacity; ++i) { int origVal = i + minVal; for (int j = 0; j < counts[i]; ++j) { items[p++] = origVal; } } return items; } public static char[] sortCharsReversed(char[] items) { sortChars(items); for (int i = 0, j = items.length - 1; i < j; ++i, --j) { char tmp = items[i]; items[i] = items[j]; items[j] = tmp; } return items; } public static char[] sortChars(char[] items) { final int N = items.length; int minVal = Integer.MAX_VALUE; int maxVal = Integer.MIN_VALUE; for (int i = 0; i < items.length; ++i) { minVal = Math.min(minVal, items[i]); maxVal = Math.max(maxVal, items[i]); } int capacity = maxVal - minVal + 1; int[] counts = new int[capacity]; for (int i = 0; i < N; ++i) { int bucketIndex = items[i] - minVal; ++counts[bucketIndex]; } int p = 0; for (int i = 0; i < capacity; ++i) { char origVal = (char)(i + minVal); for (int j = 0; j < counts[i]; ++j) { items[p++] = origVal; } } return items; } public static interface IntConverter<T> { public int toInt(T item); } } /** * Circular buffer of int values, can be used as: * - ArrayList: values are added to end. * - Queue: values are added to end and removed from front. * - Stack: values are added to and removed from front. */ public static class IntDeque { private int[] arr; private int off; private int len; public IntDeque() { this(2); } public IntDeque(int capacity) { this.arr = new int[capacity]; } public void addFirst(int x) { if (len == arr.length) { increaseCapacity(); } if (off == 0) { off = arr.length; } arr[--off] = x; ++len; } public void addLast(int x) { if (len == arr.length) { increaseCapacity(); } int idx = index(off + len); arr[idx] = x; ++len; } public int peekFirst() { return arr[off]; } public int peekLast() { int idx = index(off + len - 1); return arr[idx]; } public int removeFirst() { int ans = peekFirst(); off = index(off + 1); --len; return ans; } public int removeLast() { int ans = peekLast(); --len; return ans; } public void add(int x) { addLast(x); } public void offer(int x) { addLast(x); } public int poll() { return removeFirst(); } public void push(int x) { addFirst(x); } public int pop() { return removeFirst(); } public int peek() { return peekFirst(); } public int get(int i) { if (i >= len) { throw new ArrayIndexOutOfBoundsException(String.format("index %d out of range [0, %d)", i, len)); } int idx = index(i + off); return arr[idx]; } public void set(int i, int x) { if (i >= len) { throw new ArrayIndexOutOfBoundsException(String.format("index %d out of range [0, %d)", i, len)); } int idx = index(i + off); arr[idx] = x; } public int size() { return len; } public boolean isEmpty() { return size() == 0; } public int[] toArray() { if (len == 0) { return new int[0]; } int idx = index(off + len); if (idx > off) { return Arrays.copyOfRange(arr, off, idx); } int[] A = new int[len]; int endLen = arr.length - off; int startLen = len - endLen; System.arraycopy(arr, off, A, 0, endLen); System.arraycopy(arr, 0, A, endLen, startLen); return A; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append('['); printToBuffer(sb, ", "); sb.append(']'); return sb.toString(); } private void increaseCapacity() { int[] next = new int[arr.length << 1]; int endLen = arr.length - off; System.arraycopy(arr, off, next, 0, endLen); System.arraycopy(arr, 0, next, endLen, off); arr = next; off = 0; } private int index(int i) { if (i >= arr.length) { i -= arr.length; } else if (i < 0) { i += arr.length; } return i; } private void printToBuffer(StringBuilder sb, CharSequence sep) { for (int i = 0; i < len; ++i) { if (i > 0) { sb.append(sep); } sb.append(get(i)); } } public static IntDeque of(int... arr) { IntDeque deq = new IntDeque(); for (int x : arr) { deq.add(x); } return deq; } } public static class FastIO { private InputStream reader; private PrintWriter writer; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public FastIO(InputStream r, OutputStream w) { reader = r; writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(w))); } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = reader.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public String nextString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } // TODO: read this byte-by-byte like the other read functions. public double nextDouble() { return Double.parseDouble(nextString()); } public int[] nextIntArray(int n) { return nextIntArray(n, 0); } public int[] nextIntArray(int n, int off) { int[] arr = new int[n + off]; for (int i = 0; i < n; i++) { arr[i + off] = nextInt(); } return arr; } public long[] nextLongArray(int n) { return nextLongArray(n, 0); } public long[] nextLongArray(int n, int off) { long[] arr = new long[n + off]; for (int i = 0; i < n; i++) { arr[i + off] = nextLong(); } return arr; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) { writer.print(' '); } writer.print(objects[i]); } } public void println(Object... objects) { print(objects); writer.println(); } public void printArray(int[] arr) { for (int i = 0; i < arr.length; i++) { if (i != 0) { writer.print(' '); } writer.print(arr[i]); } } public void printArray(long[] arr) { for (int i = 0; i < arr.length; i++) { if (i != 0) { writer.print(' '); } writer.print(arr[i]); } } public void printlnArray(int[] arr) { printArray(arr); writer.println(); } public void printlnArray(long[] arr) { printArray(arr); writer.println(); } public void printf(String format, Object... args) { print(String.format(format, args)); } public void flush() { writer.flush(); } } public static void main(String[] args) { FastIO io = new FastIO(System.in, System.out); solve(io); io.flush(); } }
Java
["5 4\n\n0\n\n5\n\n9\n\n7"]
1 second
["? 0000\n\n? 1110\n\n? 1111\n\n? 1101\n\n! 7"]
NoteHere is the graph of the example, satisfying $$$l_i=i$$$.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy", "interactive", "sortings" ]
003b7257b35416ec93f189cb29e458e6
The first and only line of input contains two integers $$$n,m$$$ ($$$2 \leq n \leq 200$$$, $$$1\le m \le 500$$$) — the number of stations and tracks.
1,700
null
standard output
PASSED
14b75bdfce502a4b28718d21ddc429ef
train_108.jsonl
1654266900
As for the technology in the outside world, it is really too advanced for Gensokyo to even look up to.—Yasaka Kanako, Symposium of Post-mysticismThis is an interactive problem.Under the direct supervision of Kanako and the Moriya Shrine, the railway system of Gensokyo is finally finished. GSKR (Gensokyo Railways) consists of $$$n$$$ stations with $$$m$$$ bidirectional tracks connecting them. The $$$i$$$-th track has length $$$l_i$$$ ($$$1\le l_i\le 10^6$$$). Due to budget limits, the railway system may not be connected, though there may be more than one track between two stations.The value of a railway system is defined as the total length of its all tracks. The maximum (or minimum) capacity of a railway system is defined as the maximum (or minimum) value among all of the currently functional system's full spanning forest.In brief, full spanning forest of a graph is a spanning forest with the same connectivity as the given graph.Kanako has a simulator only able to process no more than $$$2m$$$ queries. The input of the simulator is a string $$$s$$$ of length $$$m$$$, consisting of characters 0 and/or 1. The simulator will assume the $$$i$$$-th track functional if $$$s_i=$$$ 1. The device will then tell Kanako the maximum capacity of the system in the simulated state.Kanako wants to know the the minimum capacity of the system with all tracks functional with the help of the simulator.The structure of the railway system is fixed in advance. In other words, the interactor is not adaptive.
256 megabytes
import java.io.*; import java.util.*; public class RailwaySystem { public static void solve(FastIO io) { io.nextInt(); final int M = io.nextInt(); Edge[] edges = new Edge[M]; for (int i = 0; i < M; ++i) { int id = i + 1; final int L = query(io, M, id); edges[i] = new Edge(id, L); } BucketSort.sort(edges, new BucketSort.IntConverter<Edge>() { @Override public int toInt(Edge e) { return e.weight; } }); IntDeque used = new IntDeque(); int prev = 0; for (Edge e : edges) { used.push(e.id); int curr = query(io, M, used.toArray()); if (curr == prev + e.weight) { prev = curr; } else { used.pop(); } } answer(io, prev); } private static int query(FastIO io, int M, int... which) { char[] S = new char[M + 1]; Arrays.fill(S, '0'); for (int x : which) { S[x] = '1'; } io.println('?', new String(S, 1, M)); io.flush(); return io.nextInt(); } private static void answer(FastIO io, int ans) { io.println('!', ans); io.flush(); } private static class Edge { public int id; public int weight; public Edge(int id, int weight) { this.id = id; this.weight = weight; } public static final Comparator<Edge> BY_WEIGHT = new Comparator<Edge>() { public int compare(Edge a, Edge b) { return Integer.compare(a.weight, b.weight); } }; } public static class BucketSort { public static <T> T[] sortReversed(T[] items, IntConverter<T> converter) { sort(items, converter); for (int i = 0, j = items.length - 1; i < j; ++i, --j) { T tmp = items[i]; items[i] = items[j]; items[j] = tmp; } return items; } public static <T> T[] sort(T[] items, IntConverter<T> converter) { final int N = items.length; int[] values = new int[N]; int minVal = Integer.MAX_VALUE; int maxVal = Integer.MIN_VALUE; for (int i = 0; i < items.length; ++i) { values[i] = converter.toInt(items[i]); minVal = Math.min(minVal, values[i]); maxVal = Math.max(maxVal, values[i]); } int capacity = maxVal - minVal + 1; ArrayList<ArrayList<T>> buckets = new ArrayList<>(capacity); for (int i = 0; i < capacity; ++i) { buckets.add(null); } for (int i = 0; i < items.length; ++i) { int bucketIndex = values[i] - minVal; ArrayList<T> lst = buckets.get(bucketIndex); if (lst == null) { lst = new ArrayList<>(); buckets.set(bucketIndex, lst); } lst.add(items[i]); } int p = 0; for (ArrayList<T> lst : buckets) { if (lst == null) { continue; } for (T item : lst) { items[p++] = item; } } return items; } public static int[] sortIntsReversed(int[] items) { sortInts(items); for (int i = 0, j = items.length - 1; i < j; ++i, --j) { int tmp = items[i]; items[i] = items[j]; items[j] = tmp; } return items; } public static int[] sortInts(int[] items) { final int N = items.length; int minVal = Integer.MAX_VALUE; int maxVal = Integer.MIN_VALUE; for (int i = 0; i < items.length; ++i) { minVal = Math.min(minVal, items[i]); maxVal = Math.max(maxVal, items[i]); } int capacity = maxVal - minVal + 1; int[] counts = new int[capacity]; for (int i = 0; i < N; ++i) { int bucketIndex = items[i] - minVal; ++counts[bucketIndex]; } int p = 0; for (int i = 0; i < capacity; ++i) { int origVal = i + minVal; for (int j = 0; j < counts[i]; ++j) { items[p++] = origVal; } } return items; } public static char[] sortCharsReversed(char[] items) { sortChars(items); for (int i = 0, j = items.length - 1; i < j; ++i, --j) { char tmp = items[i]; items[i] = items[j]; items[j] = tmp; } return items; } public static char[] sortChars(char[] items) { final int N = items.length; int minVal = Integer.MAX_VALUE; int maxVal = Integer.MIN_VALUE; for (int i = 0; i < items.length; ++i) { minVal = Math.min(minVal, items[i]); maxVal = Math.max(maxVal, items[i]); } int capacity = maxVal - minVal + 1; int[] counts = new int[capacity]; for (int i = 0; i < N; ++i) { int bucketIndex = items[i] - minVal; ++counts[bucketIndex]; } int p = 0; for (int i = 0; i < capacity; ++i) { char origVal = (char)(i + minVal); for (int j = 0; j < counts[i]; ++j) { items[p++] = origVal; } } return items; } public static interface IntConverter<T> { public int toInt(T item); } } /** * Circular buffer of int values, can be used as: * - ArrayList: values are added to end. * - Queue: values are added to end and removed from front. * - Stack: values are added to and removed from front. */ public static class IntDeque { private int[] arr; private int off; private int len; public IntDeque() { this(2); } public IntDeque(int capacity) { this.arr = new int[capacity]; } public void addFirst(int x) { if (len == arr.length) { increaseCapacity(); } if (off == 0) { off = arr.length; } arr[--off] = x; ++len; } public void addLast(int x) { if (len == arr.length) { increaseCapacity(); } int idx = index(off + len); arr[idx] = x; ++len; } public int peekFirst() { return arr[off]; } public int peekLast() { int idx = index(off + len - 1); return arr[idx]; } public int removeFirst() { int ans = peekFirst(); off = index(off + 1); --len; return ans; } public int removeLast() { int ans = peekLast(); --len; return ans; } public void add(int x) { addLast(x); } public void offer(int x) { addLast(x); } public int poll() { return removeFirst(); } public void push(int x) { addFirst(x); } public int pop() { return removeFirst(); } public int peek() { return peekFirst(); } public int get(int i) { if (i >= len) { throw new ArrayIndexOutOfBoundsException(String.format("index %d out of range [0, %d)", i, len)); } int idx = index(i + off); return arr[idx]; } public void set(int i, int x) { if (i >= len) { throw new ArrayIndexOutOfBoundsException(String.format("index %d out of range [0, %d)", i, len)); } int idx = index(i + off); arr[idx] = x; } public int size() { return len; } public boolean isEmpty() { return size() == 0; } public int[] toArray() { if (len == 0) { return new int[0]; } int idx = index(off + len); if (idx > off) { return Arrays.copyOfRange(arr, off, idx); } int[] A = new int[len]; int endLen = arr.length - off; int startLen = len - endLen; System.arraycopy(arr, off, A, 0, endLen); System.arraycopy(arr, 0, A, endLen, startLen); return A; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append('['); printToBuffer(sb, ", "); sb.append(']'); return sb.toString(); } private void increaseCapacity() { int[] next = new int[arr.length << 1]; int endLen = arr.length - off; System.arraycopy(arr, off, next, 0, endLen); System.arraycopy(arr, 0, next, endLen, off); arr = next; off = 0; } private int index(int i) { if (i >= arr.length) { i -= arr.length; } else if (i < 0) { i += arr.length; } return i; } private void printToBuffer(StringBuilder sb, CharSequence sep) { for (int i = 0; i < len; ++i) { if (i > 0) { sb.append(sep); } sb.append(get(i)); } } public static IntDeque of(int... arr) { IntDeque deq = new IntDeque(); for (int x : arr) { deq.add(x); } return deq; } } public static class FastIO { private InputStream reader; private PrintWriter writer; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public FastIO(InputStream r, OutputStream w) { reader = r; writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(w))); } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = reader.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public String nextString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } // TODO: read this byte-by-byte like the other read functions. public double nextDouble() { return Double.parseDouble(nextString()); } public int[] nextIntArray(int n) { return nextIntArray(n, 0); } public int[] nextIntArray(int n, int off) { int[] arr = new int[n + off]; for (int i = 0; i < n; i++) { arr[i + off] = nextInt(); } return arr; } public long[] nextLongArray(int n) { return nextLongArray(n, 0); } public long[] nextLongArray(int n, int off) { long[] arr = new long[n + off]; for (int i = 0; i < n; i++) { arr[i + off] = nextLong(); } return arr; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) { writer.print(' '); } writer.print(objects[i]); } } public void println(Object... objects) { print(objects); writer.println(); } public void printArray(int[] arr) { for (int i = 0; i < arr.length; i++) { if (i != 0) { writer.print(' '); } writer.print(arr[i]); } } public void printArray(long[] arr) { for (int i = 0; i < arr.length; i++) { if (i != 0) { writer.print(' '); } writer.print(arr[i]); } } public void printlnArray(int[] arr) { printArray(arr); writer.println(); } public void printlnArray(long[] arr) { printArray(arr); writer.println(); } public void printf(String format, Object... args) { print(String.format(format, args)); } public void flush() { writer.flush(); } } public static void main(String[] args) { FastIO io = new FastIO(System.in, System.out); solve(io); io.flush(); } }
Java
["5 4\n\n0\n\n5\n\n9\n\n7"]
1 second
["? 0000\n\n? 1110\n\n? 1111\n\n? 1101\n\n! 7"]
NoteHere is the graph of the example, satisfying $$$l_i=i$$$.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy", "interactive", "sortings" ]
003b7257b35416ec93f189cb29e458e6
The first and only line of input contains two integers $$$n,m$$$ ($$$2 \leq n \leq 200$$$, $$$1\le m \le 500$$$) — the number of stations and tracks.
1,700
null
standard output
PASSED
af0b0293e4df2f192eef5bae83f51424
train_108.jsonl
1654266900
As for the technology in the outside world, it is really too advanced for Gensokyo to even look up to.—Yasaka Kanako, Symposium of Post-mysticismThis is an interactive problem.Under the direct supervision of Kanako and the Moriya Shrine, the railway system of Gensokyo is finally finished. GSKR (Gensokyo Railways) consists of $$$n$$$ stations with $$$m$$$ bidirectional tracks connecting them. The $$$i$$$-th track has length $$$l_i$$$ ($$$1\le l_i\le 10^6$$$). Due to budget limits, the railway system may not be connected, though there may be more than one track between two stations.The value of a railway system is defined as the total length of its all tracks. The maximum (or minimum) capacity of a railway system is defined as the maximum (or minimum) value among all of the currently functional system's full spanning forest.In brief, full spanning forest of a graph is a spanning forest with the same connectivity as the given graph.Kanako has a simulator only able to process no more than $$$2m$$$ queries. The input of the simulator is a string $$$s$$$ of length $$$m$$$, consisting of characters 0 and/or 1. The simulator will assume the $$$i$$$-th track functional if $$$s_i=$$$ 1. The device will then tell Kanako the maximum capacity of the system in the simulated state.Kanako wants to know the the minimum capacity of the system with all tracks functional with the help of the simulator.The structure of the railway system is fixed in advance. In other words, the interactor is not adaptive.
256 megabytes
import java.io.*; import java.util.*; public class RailwaySystem { public static void solve(FastIO io) { io.nextInt(); final int M = io.nextInt(); Edge[] edges = new Edge[M]; for (int i = 0; i < M; ++i) { int id = i + 1; final int L = query(io, M, id); edges[i] = new Edge(id, L); } Arrays.sort(edges, Edge.BY_WEIGHT); IntDeque used = new IntDeque(); int prev = 0; for (Edge e : edges) { used.push(e.id); int curr = query(io, M, used.toArray()); if (curr == prev + e.weight) { prev = curr; } else { used.pop(); } } answer(io, prev); } private static int query(FastIO io, int M, int... which) { char[] S = new char[M + 1]; Arrays.fill(S, '0'); for (int x : which) { S[x] = '1'; } io.println('?', new String(S, 1, M)); io.flush(); return io.nextInt(); } private static void answer(FastIO io, int ans) { io.println('!', ans); io.flush(); } private static class Edge { public int id; public int weight; public Edge(int id, int weight) { this.id = id; this.weight = weight; } public static final Comparator<Edge> BY_WEIGHT = new Comparator<Edge>() { public int compare(Edge a, Edge b) { return Integer.compare(a.weight, b.weight); } }; } /** * Circular buffer of int values, can be used as: * - ArrayList: values are added to end. * - Queue: values are added to end and removed from front. * - Stack: values are added to and removed from front. */ public static class IntDeque { private int[] arr; private int off; private int len; public IntDeque() { this(2); } public IntDeque(int capacity) { this.arr = new int[capacity]; } public void addFirst(int x) { if (len == arr.length) { increaseCapacity(); } if (off == 0) { off = arr.length; } arr[--off] = x; ++len; } public void addLast(int x) { if (len == arr.length) { increaseCapacity(); } int idx = index(off + len); arr[idx] = x; ++len; } public int peekFirst() { return arr[off]; } public int peekLast() { int idx = index(off + len - 1); return arr[idx]; } public int removeFirst() { int ans = peekFirst(); off = index(off + 1); --len; return ans; } public int removeLast() { int ans = peekLast(); --len; return ans; } public void add(int x) { addLast(x); } public void offer(int x) { addLast(x); } public int poll() { return removeFirst(); } public void push(int x) { addFirst(x); } public int pop() { return removeFirst(); } public int peek() { return peekFirst(); } public int get(int i) { if (i >= len) { throw new ArrayIndexOutOfBoundsException(String.format("index %d out of range [0, %d)", i, len)); } int idx = index(i + off); return arr[idx]; } public void set(int i, int x) { if (i >= len) { throw new ArrayIndexOutOfBoundsException(String.format("index %d out of range [0, %d)", i, len)); } int idx = index(i + off); arr[idx] = x; } public int size() { return len; } public boolean isEmpty() { return size() == 0; } public int[] toArray() { if (len == 0) { return new int[0]; } int idx = index(off + len); if (idx > off) { return Arrays.copyOfRange(arr, off, idx); } int[] A = new int[len]; int endLen = arr.length - off; int startLen = len - endLen; System.arraycopy(arr, off, A, 0, endLen); System.arraycopy(arr, 0, A, endLen, startLen); return A; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append('['); printToBuffer(sb, ", "); sb.append(']'); return sb.toString(); } private void increaseCapacity() { int[] next = new int[arr.length << 1]; int endLen = arr.length - off; System.arraycopy(arr, off, next, 0, endLen); System.arraycopy(arr, 0, next, endLen, off); arr = next; off = 0; } private int index(int i) { if (i >= arr.length) { i -= arr.length; } else if (i < 0) { i += arr.length; } return i; } private void printToBuffer(StringBuilder sb, CharSequence sep) { for (int i = 0; i < len; ++i) { if (i > 0) { sb.append(sep); } sb.append(get(i)); } } public static IntDeque of(int... arr) { IntDeque deq = new IntDeque(); for (int x : arr) { deq.add(x); } return deq; } } public static class FastIO { private InputStream reader; private PrintWriter writer; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public FastIO(InputStream r, OutputStream w) { reader = r; writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(w))); } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = reader.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public String nextString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } // TODO: read this byte-by-byte like the other read functions. public double nextDouble() { return Double.parseDouble(nextString()); } public int[] nextIntArray(int n) { return nextIntArray(n, 0); } public int[] nextIntArray(int n, int off) { int[] arr = new int[n + off]; for (int i = 0; i < n; i++) { arr[i + off] = nextInt(); } return arr; } public long[] nextLongArray(int n) { return nextLongArray(n, 0); } public long[] nextLongArray(int n, int off) { long[] arr = new long[n + off]; for (int i = 0; i < n; i++) { arr[i + off] = nextLong(); } return arr; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) { writer.print(' '); } writer.print(objects[i]); } } public void println(Object... objects) { print(objects); writer.println(); } public void printArray(int[] arr) { for (int i = 0; i < arr.length; i++) { if (i != 0) { writer.print(' '); } writer.print(arr[i]); } } public void printArray(long[] arr) { for (int i = 0; i < arr.length; i++) { if (i != 0) { writer.print(' '); } writer.print(arr[i]); } } public void printlnArray(int[] arr) { printArray(arr); writer.println(); } public void printlnArray(long[] arr) { printArray(arr); writer.println(); } public void printf(String format, Object... args) { print(String.format(format, args)); } public void flush() { writer.flush(); } } public static void main(String[] args) { FastIO io = new FastIO(System.in, System.out); solve(io); io.flush(); } }
Java
["5 4\n\n0\n\n5\n\n9\n\n7"]
1 second
["? 0000\n\n? 1110\n\n? 1111\n\n? 1101\n\n! 7"]
NoteHere is the graph of the example, satisfying $$$l_i=i$$$.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy", "interactive", "sortings" ]
003b7257b35416ec93f189cb29e458e6
The first and only line of input contains two integers $$$n,m$$$ ($$$2 \leq n \leq 200$$$, $$$1\le m \le 500$$$) — the number of stations and tracks.
1,700
null
standard output
PASSED
6368b5063f5cf593b9f02f7c09000a9d
train_108.jsonl
1654266900
As for the technology in the outside world, it is really too advanced for Gensokyo to even look up to.—Yasaka Kanako, Symposium of Post-mysticismThis is an interactive problem.Under the direct supervision of Kanako and the Moriya Shrine, the railway system of Gensokyo is finally finished. GSKR (Gensokyo Railways) consists of $$$n$$$ stations with $$$m$$$ bidirectional tracks connecting them. The $$$i$$$-th track has length $$$l_i$$$ ($$$1\le l_i\le 10^6$$$). Due to budget limits, the railway system may not be connected, though there may be more than one track between two stations.The value of a railway system is defined as the total length of its all tracks. The maximum (or minimum) capacity of a railway system is defined as the maximum (or minimum) value among all of the currently functional system's full spanning forest.In brief, full spanning forest of a graph is a spanning forest with the same connectivity as the given graph.Kanako has a simulator only able to process no more than $$$2m$$$ queries. The input of the simulator is a string $$$s$$$ of length $$$m$$$, consisting of characters 0 and/or 1. The simulator will assume the $$$i$$$-th track functional if $$$s_i=$$$ 1. The device will then tell Kanako the maximum capacity of the system in the simulated state.Kanako wants to know the the minimum capacity of the system with all tracks functional with the help of the simulator.The structure of the railway system is fixed in advance. In other words, the interactor is not adaptive.
256 megabytes
import java.io.*; import java.util.*; public class RailwaySystem { public static void solve(FastIO io) { io.nextInt(); final int M = io.nextInt(); Edge[] edges = new Edge[M]; for (int i = 0; i < M; ++i) { int id = i + 1; final int L = query(io, M, id); edges[i] = new Edge(id, L); } Arrays.sort(edges, Edge.BY_WEIGHT); LongDeque used = new LongDeque(); int prev = 0; for (Edge e : edges) { used.push(e.id); int curr = query(io, M, used.toArray()); if (curr == prev + e.weight) { prev = curr; } else { used.pop(); } } answer(io, prev); } private static int query(FastIO io, int M, int... which) { char[] S = new char[M + 1]; Arrays.fill(S, '0'); for (int x : which) { S[x] = '1'; } io.println('?', new String(S, 1, M)); io.flush(); return io.nextInt(); } private static int query(FastIO io, int M, long... which) { char[] S = new char[M + 1]; Arrays.fill(S, '0'); for (long x : which) { int id = Math.toIntExact(x); S[id] = '1'; } io.println('?', new String(S, 1, M)); io.flush(); return io.nextInt(); } private static void answer(FastIO io, int ans) { io.println('!', ans); io.flush(); } private static class Edge { public int id; public int weight; public Edge(int id, int weight) { this.id = id; this.weight = weight; } public static final Comparator<Edge> BY_WEIGHT = new Comparator<Edge>() { public int compare(Edge a, Edge b) { return Integer.compare(a.weight, b.weight); } }; } /** * Circular buffer of int values, can be used as: * - ArrayList: values are added to end. * - Queue: values are added to end and removed from front. * - Stack: values are added to and removed from front. */ public static class IntDeque { private int[] arr; private int off; private int len; public IntDeque() { this(2); } public IntDeque(int capacity) { this.arr = new int[capacity]; } public void addFirst(int x) { if (len == arr.length) { increaseCapacity(); } if (off == 0) { off = arr.length; } arr[--off] = x; ++len; } public void addLast(int x) { if (len == arr.length) { increaseCapacity(); } int idx = index(off + len); arr[idx] = x; ++len; } public int peekFirst() { return arr[off]; } public int peekLast() { int idx = index(off + len - 1); return arr[idx]; } public int removeFirst() { int ans = peekFirst(); off = index(off + 1); --len; return ans; } public int removeLast() { int ans = peekLast(); --len; return ans; } public void add(int x) { addLast(x); } public void offer(int x) { addLast(x); } public int poll() { return removeFirst(); } public void push(int x) { addFirst(x); } public int pop() { return removeFirst(); } public int peek() { return peekFirst(); } public int get(int i) { if (i >= len) { throw new ArrayIndexOutOfBoundsException(String.format("index %d out of range [0, %d)", i, len)); } int idx = index(i + off); return arr[idx]; } public void set(int i, int x) { if (i >= len) { throw new ArrayIndexOutOfBoundsException(String.format("index %d out of range [0, %d)", i, len)); } int idx = index(i + off); arr[idx] = x; } public int size() { return len; } public boolean isEmpty() { return size() == 0; } public int[] toArray() { if (len == 0) { return new int[0]; } int idx = index(off + len); if (idx > off) { return Arrays.copyOfRange(arr, off, idx); } int[] A = new int[len]; int endLen = arr.length - off; int startLen = len - endLen; System.arraycopy(arr, off, A, 0, endLen); System.arraycopy(arr, 0, A, endLen, startLen); return A; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append('['); printToBuffer(sb, ", "); sb.append(']'); return sb.toString(); } private void increaseCapacity() { int[] next = new int[arr.length << 1]; int endLen = arr.length - off; System.arraycopy(arr, off, next, 0, endLen); System.arraycopy(arr, 0, next, endLen, off); arr = next; off = 0; } private int index(int i) { if (i >= arr.length) { i -= arr.length; } else if (i < 0) { i += arr.length; } return i; } private void printToBuffer(StringBuilder sb, CharSequence sep) { for (int i = 0; i < len; ++i) { if (i > 0) { sb.append(sep); } sb.append(get(i)); } } public static IntDeque of(int... arr) { IntDeque deq = new IntDeque(); for (int x : arr) { deq.add(x); } return deq; } } /** * Circular buffer of long values, can be used as: * - ArrayList: values are added to end. * - Queue: values are added to end and removed from front. * - Stack: values are added to and removed from front. */ public static class LongDeque { private long[] arr; private int off; private int len; public LongDeque() { this(2); } public LongDeque(int capacity) { this.arr = new long[capacity]; } public void addFirst(long x) { if (len == arr.length) { increaseCapacity(); } if (off == 0) { off = arr.length; } arr[--off] = x; ++len; } public void addLast(long x) { if (len == arr.length) { increaseCapacity(); } int idx = index(off + len); arr[idx] = x; ++len; } public long peekFirst() { return arr[off]; } public long peekLast() { int idx = index(off + len - 1); return arr[idx]; } public long removeFirst() { long ans = peekFirst(); off = index(off + 1); --len; return ans; } public long removeLast() { long ans = peekLast(); --len; return ans; } public void add(long x) { addLast(x); } public void offer(long x) { addLast(x); } public long poll() { return removeFirst(); } public void push(long x) { addFirst(x); } public long pop() { return removeFirst(); } public long peek() { return peekFirst(); } public long get(int i) { if (i >= len) { throw new ArrayIndexOutOfBoundsException(String.format("index %d out of range [0, %d)", i, len)); } int idx = index(i + off); return arr[idx]; } public void set(int i, long x) { if (i >= len) { throw new ArrayIndexOutOfBoundsException(String.format("index %d out of range [0, %d)", i, len)); } int idx = index(i + off); arr[idx] = x; } public int size() { return len; } public boolean isEmpty() { return size() == 0; } public long[] toArray() { if (len == 0) { return new long[0]; } int idx = index(off + len); if (idx > off) { return Arrays.copyOfRange(arr, off, idx); } long[] A = new long[len]; int endLen = arr.length - off; int startLen = len - endLen; System.arraycopy(arr, off, A, 0, endLen); System.arraycopy(arr, 0, A, endLen, startLen); return A; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append('['); printToBuffer(sb, ", "); sb.append(']'); return sb.toString(); } private void increaseCapacity() { long[] next = new long[arr.length << 1]; int endLen = arr.length - off; System.arraycopy(arr, off, next, 0, endLen); System.arraycopy(arr, 0, next, endLen, off); arr = next; off = 0; } private int index(int i) { if (i >= arr.length) { i -= arr.length; } else if (i < 0) { i += arr.length; } return i; } private void printToBuffer(StringBuilder sb, CharSequence sep) { for (int i = 0; i < len; ++i) { if (i > 0) { sb.append(sep); } sb.append(get(i)); } } public static LongDeque of(long... arr) { LongDeque deq = new LongDeque(); for (long x : arr) { deq.add(x); } return deq; } } public static class FastIO { private InputStream reader; private PrintWriter writer; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public FastIO(InputStream r, OutputStream w) { reader = r; writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(w))); } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = reader.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public String nextString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } // TODO: read this byte-by-byte like the other read functions. public double nextDouble() { return Double.parseDouble(nextString()); } public int[] nextIntArray(int n) { return nextIntArray(n, 0); } public int[] nextIntArray(int n, int off) { int[] arr = new int[n + off]; for (int i = 0; i < n; i++) { arr[i + off] = nextInt(); } return arr; } public long[] nextLongArray(int n) { return nextLongArray(n, 0); } public long[] nextLongArray(int n, int off) { long[] arr = new long[n + off]; for (int i = 0; i < n; i++) { arr[i + off] = nextLong(); } return arr; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) { writer.print(' '); } writer.print(objects[i]); } } public void println(Object... objects) { print(objects); writer.println(); } public void printArray(int[] arr) { for (int i = 0; i < arr.length; i++) { if (i != 0) { writer.print(' '); } writer.print(arr[i]); } } public void printArray(long[] arr) { for (int i = 0; i < arr.length; i++) { if (i != 0) { writer.print(' '); } writer.print(arr[i]); } } public void printlnArray(int[] arr) { printArray(arr); writer.println(); } public void printlnArray(long[] arr) { printArray(arr); writer.println(); } public void printf(String format, Object... args) { print(String.format(format, args)); } public void flush() { writer.flush(); } } public static void main(String[] args) { FastIO io = new FastIO(System.in, System.out); solve(io); io.flush(); } }
Java
["5 4\n\n0\n\n5\n\n9\n\n7"]
1 second
["? 0000\n\n? 1110\n\n? 1111\n\n? 1101\n\n! 7"]
NoteHere is the graph of the example, satisfying $$$l_i=i$$$.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy", "interactive", "sortings" ]
003b7257b35416ec93f189cb29e458e6
The first and only line of input contains two integers $$$n,m$$$ ($$$2 \leq n \leq 200$$$, $$$1\le m \le 500$$$) — the number of stations and tracks.
1,700
null
standard output
PASSED
96d5ad628a4e10ad1c3f900ecb3e6380
train_108.jsonl
1654266900
As for the technology in the outside world, it is really too advanced for Gensokyo to even look up to.—Yasaka Kanako, Symposium of Post-mysticismThis is an interactive problem.Under the direct supervision of Kanako and the Moriya Shrine, the railway system of Gensokyo is finally finished. GSKR (Gensokyo Railways) consists of $$$n$$$ stations with $$$m$$$ bidirectional tracks connecting them. The $$$i$$$-th track has length $$$l_i$$$ ($$$1\le l_i\le 10^6$$$). Due to budget limits, the railway system may not be connected, though there may be more than one track between two stations.The value of a railway system is defined as the total length of its all tracks. The maximum (or minimum) capacity of a railway system is defined as the maximum (or minimum) value among all of the currently functional system's full spanning forest.In brief, full spanning forest of a graph is a spanning forest with the same connectivity as the given graph.Kanako has a simulator only able to process no more than $$$2m$$$ queries. The input of the simulator is a string $$$s$$$ of length $$$m$$$, consisting of characters 0 and/or 1. The simulator will assume the $$$i$$$-th track functional if $$$s_i=$$$ 1. The device will then tell Kanako the maximum capacity of the system in the simulated state.Kanako wants to know the the minimum capacity of the system with all tracks functional with the help of the simulator.The structure of the railway system is fixed in advance. In other words, the interactor is not adaptive.
256 megabytes
// OM NAMAH SHIVAY //import jdk.jshell.execution.JdiDefaultExecutionControl; import java.math.BigInteger; import java.util.*; import java.io.*; //import java.util.logging.LogManager; public class Vaibhav { static long bit[]; static boolean prime[]; //static PrintWriter out = new PrintWriter(System.out); static class Pair implements Comparable<Pair>{ int a; int b; Pair(int p, int q) { a = p; b = q; } public int compareTo(Pair o){ return this.b - o.b; } // Pair with HashSet /* public boolean equals(Object o) { if (o instanceof Pair) { Pair p = (Pair) o; return p.a == a && p.b == b; } return false; } public int hashCode() { int hash = 5; hash = 17 * hash + this.a; return hash; }*/ } static long power(long x, long y, long p) { if (y == 0) return 1; if (x == 0) return 0; long res = 1l; 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 power(long x, long y) { if (y == 0) return 1; if (x == 0) return 0; long res = 1; while (y > 0) { if (y % 2 == 1) res = (res * x); y = y >> 1; x = (x * x); } return res; } static void sort(long[] a) { ArrayList<Long> l = new ArrayList<>(); for (long i : a) l.add(i); Collections.sort(l); for (int i = 0; i < a.length; i++) a[i] = l.get(i); } static class FastScanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } double nextDouble() { return Double.parseDouble(next()); } int[] readArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); 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()); } } static void sieveOfEratosthenes(int n) { 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; } } } public static int log2(int x) { return (int) (Math.log(x) / Math.log(2)); } static int binomialCoeff(int n, int r) { if (r > n) return 0; long m = 1000000007; long inv[] = new long[r + 1]; inv[0] = 1; if(r+1>=2) inv[1] = 1; for (int i = 2; i <= r; i++) { inv[i] = m - (m / i) * inv[(int) (m % i)] % m; } int ans = 1; for (int i = 2; i <= r; i++) { ans = (int) (((ans % m) * (inv[i] % m)) % m); } for (int i = n; i >= (n - r + 1); i--) { ans = (int) (((ans % m) * (i % m)) % m); } return ans; } public static int gcd(int a, int b) { if (b == 0) { return a; } return gcd(b, a % b); } static BigInteger bi(String str) { return new BigInteger(str); } // Author - vaibhav_1710 static FastScanner fs = null; static long mod=998244353; static int a[]; static int p[]; static int[][] dirs = { { 0, -1 }, { -1, 0 }, { 0, 1 }, { 1, 0 }, }; static int count=0; static ArrayList<Integer> al[]; static HashSet<Pair> h; static double len; public static void main(String[] args) { fs = new FastScanner(); PrintWriter out = new PrintWriter(System.out); int t = 1; outer: while (t-- > 0 ) { int n = fs.nextInt(); int m = fs.nextInt(); ArrayList<Pair> al = new ArrayList<>(); int c[] = new int[m]; for(int i=0;i<m;i++){ c[i]=1; out.print("? "); for(int x:c){ out.print(x); } out.println(); out.flush(); int v = fs.nextInt(); al.add(new Pair(i,v)); c[i]=0; } Collections.sort(al); int sum=0; for(int i=0;i<al.size();i++){ c[al.get(i).a]=1; out.print("? "); for(int x:c){ out.print(x); } out.println(); out.flush(); int s = fs.nextInt(); if((s-sum)==(al.get(i).b)){ sum=s; }else { c[al.get(i).a] = 0; } } out.println("! "+sum); out.flush(); } out.close(); } }
Java
["5 4\n\n0\n\n5\n\n9\n\n7"]
1 second
["? 0000\n\n? 1110\n\n? 1111\n\n? 1101\n\n! 7"]
NoteHere is the graph of the example, satisfying $$$l_i=i$$$.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy", "interactive", "sortings" ]
003b7257b35416ec93f189cb29e458e6
The first and only line of input contains two integers $$$n,m$$$ ($$$2 \leq n \leq 200$$$, $$$1\le m \le 500$$$) — the number of stations and tracks.
1,700
null
standard output
PASSED
019f8635a7b817c7e8a1795b3461c106
train_108.jsonl
1654266900
As for the technology in the outside world, it is really too advanced for Gensokyo to even look up to.—Yasaka Kanako, Symposium of Post-mysticismThis is an interactive problem.Under the direct supervision of Kanako and the Moriya Shrine, the railway system of Gensokyo is finally finished. GSKR (Gensokyo Railways) consists of $$$n$$$ stations with $$$m$$$ bidirectional tracks connecting them. The $$$i$$$-th track has length $$$l_i$$$ ($$$1\le l_i\le 10^6$$$). Due to budget limits, the railway system may not be connected, though there may be more than one track between two stations.The value of a railway system is defined as the total length of its all tracks. The maximum (or minimum) capacity of a railway system is defined as the maximum (or minimum) value among all of the currently functional system's full spanning forest.In brief, full spanning forest of a graph is a spanning forest with the same connectivity as the given graph.Kanako has a simulator only able to process no more than $$$2m$$$ queries. The input of the simulator is a string $$$s$$$ of length $$$m$$$, consisting of characters 0 and/or 1. The simulator will assume the $$$i$$$-th track functional if $$$s_i=$$$ 1. The device will then tell Kanako the maximum capacity of the system in the simulated state.Kanako wants to know the the minimum capacity of the system with all tracks functional with the help of the simulator.The structure of the railway system is fixed in advance. In other words, the interactor is not adaptive.
256 megabytes
import java.io.*; import java.util.*; import static java.util.Comparator.*; public class Solution { public static boolean useInFile = false; public static boolean useOutFile = false; public static void main(String args[]) throws IOException { InOut inout = new InOut(); Resolver resolver = new Resolver(inout); resolver.solve(); inout.flush(); } private static class Resolver { final long LONG_INF = (long) 1e18; final int INF = (int) (1e9 + 7); final int MOD = 998244353; long f[], inv[]; InOut inout; Resolver(InOut inout) { this.inout = inout; } void initF(int n, int mod) { f = new long[n + 1]; f[1] = 1; for (int i = 2; i <= n; i++) { f[i] = (f[i - 1] * i) % mod; } } void initInv(int n, int mod) { inv = new long[n + 1]; inv[n] = pow(f[n], mod - 2, mod); for (int i = inv.length - 2; i >= 0; i--) { inv[i] = inv[i + 1] * (i + 1) % mod; } } long cmn(int n, int m, int mod) { return f[n] * inv[m] % mod * inv[n - m] % mod; } int d[] = {0, -1, 0, 1, 0}; boolean legal(int r, int c, int n, int m) { return r >= 0 && r < n && c >= 0 && c < m; } int[] getBits(int n) { int b[] = new int[31]; for (int i = 0; i < 31; i++) { if ((n & (1 << i)) != 0) { b[i] = 1; } } return b; } private int ask(char ch[]) throws IOException { format("? %s\n", String.valueOf(ch)); flush(); return nextInt(); } void solve() throws IOException { int tt = 1; boolean hvt = false; if (hvt) { tt = nextInt(); // tt = Integer.parseInt(nextLine()); } // initF(300001, MOD); // initInv(300001, MOD); // boolean pri[] = generatePrime(40000); for (int cs = 1; cs <= tt; cs++) { long rs = 0; int n = nextInt(); int m = nextInt(); char ch[] = new char[m]; for (int i = 0; i < m; i++) { ch[i] = '0'; } int val[] = new int[m]; Integer order[] = new Integer[m]; for (int i = 0; i < m; i++) { order[i] = i; ch[i] = '1'; val[i] = ask(ch); ch[i] = '0'; } Arrays.sort(order, Comparator.comparingInt(o -> val[o])); int max[] = new int[m + 1]; for (int i = 0; i < m; i++) { int idx = order[i]; ch[idx] = '1'; max[i + 1] = ask(ch); if (max[i] + val[idx] == max[i + 1]) { rs += val[idx]; } } format("! %d", rs); if (cs < tt) { format("\n"); // format(" "); } // flush(); } } private void updateSegTree(int n, long l, SegmentTree lft) { long lazy; lazy = 1; for (int j = 1; j <= l; j++) { lazy = (lazy + cmn((int) l, j, INF)) % INF; lft.modify(1, j, j, lazy); } lft.modify(1, (int) (l + 1), n, lazy); } String next() throws IOException { return inout.next(); } String next(int n) throws IOException { return inout.next(n); } String nextLine() throws IOException { return inout.nextLine(); } int nextInt() throws IOException { return inout.nextInt(); } long nextLong(int n) throws IOException { return inout.nextLong(n); } int[] anInt(int i, int j) throws IOException { int a[] = new int[j + 1]; for (int k = i; k <= j; k++) { a[k] = nextInt(); } return a; } long[] anLong(int i, int j, int len) throws IOException { long a[] = new long[j + 1]; for (int k = i; k <= j; k++) { a[k] = nextLong(len); } return a; } void print(String s, boolean nextLine) { inout.print(s, nextLine); } void format(String format, Object... obj) { inout.format(format, obj); } void flush() { inout.flush(); } void swap(int a[], int i, int j) { a[i] ^= a[j]; a[j] ^= a[i]; a[i] ^= a[j]; } void swap(long a[], int i, int j) { a[i] ^= a[j]; a[j] ^= a[i]; a[i] ^= a[j]; } int getP(int x, int p[]) { if (p[x] == 0 || p[x] == x) { return x; } return p[x] = getP(p[x], p); } void union(int x, int y, int p[]) { if (x < y) { p[y] = x; } else { p[x] = y; } } boolean topSort() { int n = adj2.length - 1; int d[] = new int[n + 1]; for (int i = 1; i <= n; i++) { for (int j = 0; j < adj2[i].size(); j++) { d[adj2[i].get(j)[0]]++; } } List<Integer> list = new ArrayList<>(); for (int i = 1; i <= n; i++) { if (d[i] == 0) { list.add(i); } } for (int i = 0; i < list.size(); i++) { for (int j = 0; j < adj2[list.get(i)].size(); j++) { int t = adj2[list.get(i)].get(j)[0]; d[t]--; if (d[t] == 0) { list.add(t); } } } return list.size() == n; } class SegmentTreeNode { long defaultVal = 0; int l, r; long val = defaultVal, lazy = defaultVal; SegmentTreeNode(int l, int r) { this.l = l; this.r = r; } } class SegmentTree { SegmentTreeNode tree[]; long inf = Long.MIN_VALUE; long c[]; SegmentTree(int n) { assert n > 0; tree = new SegmentTreeNode[n * 3 + 1]; } void setAn(long cn[]) { c = cn; } SegmentTree build(int k, int l, int r) { if (l > r) { return this; } if (null == tree[k]) { tree[k] = new SegmentTreeNode(l, r); } if (l == r) { return this; } int mid = (l + r) >> 1; build(k << 1, l, mid); build(k << 1 | 1, mid + 1, r); return this; } void pushDown(int k) { if (tree[k].l == tree[k].r) { return; } long lazy = tree[k].lazy; tree[k << 1].val = ((c[tree[k << 1].l] - c[tree[k << 1].r + 1] + MOD) % MOD * lazy) % MOD; tree[k << 1].lazy = lazy; tree[k << 1 | 1].val = ((c[tree[k << 1 | 1].l] - c[tree[k << 1 | 1].r + 1] + MOD) % MOD * lazy) % MOD; tree[k << 1 | 1].lazy = lazy; tree[k].lazy = 0; } void modify(int k, int l, int r, long val) { if (tree[k].l >= l && tree[k].r <= r) { tree[k].val = ((c[tree[k].l] - c[tree[k].r + 1] + MOD) % MOD * val) % MOD; tree[k].lazy = val; return; } int mid = (tree[k].l + tree[k].r) >> 1; if (tree[k].lazy != 0) { pushDown(k); } if (mid >= l) { modify(k << 1, l, r, val); } if (mid + 1 <= r) { modify(k << 1 | 1, l, r, val); } tree[k].val = (tree[k << 1].val + tree[k << 1 | 1].val) % MOD; } long query(int k, int l, int r) { if (tree[k].l > r || tree[k].r < l) { return 0; } if (tree[k].lazy != 0) { pushDown(k); } if (tree[k].l >= l && tree[k].r <= r) { return tree[k].val; } long ans = (query(k << 1, l, r) + query(k << 1 | 1, l, r)) % MOD; if (tree[k].l < tree[k].r) { tree[k].val = (tree[k << 1].val + tree[k << 1 | 1].val) % MOD; } return ans; } } class BinaryIndexedTree { int n = 1; long C[]; BinaryIndexedTree(int sz) { while (n <= sz) { n <<= 1; } n = sz + 1; C = new long[n]; } int lowbit(int x) { return x & -x; } void add(int x, long val) { while (x < n) { C[x] += val; x += lowbit(x); } } long getSum(int x) { long res = 0; while (x > 0) { res += C[x]; x -= lowbit(x); } return res; } int binSearch(long sum) { if (sum == 0) { return 0; } int n = C.length; int mx = 1; while (mx < n) { mx <<= 1; } int res = 0; for (int i = mx / 2; i >= 1; i >>= 1) { if (C[res + i] < sum) { sum -= C[res + i]; res += i; } } return res + 1; } } static class TrieNode { int cnt = 0; TrieNode next[]; TrieNode() { next = new TrieNode[2]; } private void insert(TrieNode trie, int ch[], int i) { while (i < ch.length) { int idx = ch[i]; if (null == trie.next[idx]) { trie.next[idx] = new TrieNode(); } trie.cnt++; trie = trie.next[idx]; i++; } } private static int query(TrieNode trie) { if (null == trie) { return 0; } int ans[] = new int[2]; for (int i = 0; i < trie.next.length; i++) { if (null == trie.next[i]) { continue; } ans[i] = trie.next[i].cnt; } if (ans[0] == 0 && ans[0] == ans[1]) { return 0; } if (ans[0] == 0) { return query(trie.next[1]); } if (ans[1] == 0) { return query(trie.next[0]); } return Math.min(ans[0] - 1 + query(trie.next[1]), ans[1] - 1 + query(trie.next[0])); } } //Binary tree class TreeNode { int val; int tier = -1; TreeNode parent; TreeNode left; TreeNode right; TreeNode(int val) { this.val = val; } } //binary tree dfs void tierTree(TreeNode root) { if (null == root) { return; } if (null != root.parent) { root.tier = root.parent.tier + 1; } else { root.tier = 0; } tierTree(root.left); tierTree(root.right); } //LCA start TreeNode[][] lca; TreeNode[] tree; void lcaDfsTree(TreeNode root) { if (null == root) { return; } tree[root.val] = root; TreeNode nxt = root.parent; int idx = 0; while (null != nxt) { lca[root.val][idx] = nxt; nxt = lca[nxt.val][idx]; idx++; } lcaDfsTree(root.left); lcaDfsTree(root.right); } TreeNode lcaTree(TreeNode root, int n, TreeNode x, TreeNode y) throws IOException { if (null == root) { return null; } if (-1 == root.tier) { tree = new TreeNode[n + 1]; tierTree(root); } if (null == lca) { lca = new TreeNode[n + 1][31]; lcaDfsTree(root); } int z = Math.abs(x.tier - y.tier); int xx = x.tier > y.tier ? x.val : y.val; while (z > 0) { final int zz = z; int l = (int) BinSearch.bs(0, 31 , k -> zz < (1 << k)); xx = lca[xx][l].val; z -= 1 << l; } int yy = y.val; if (x.tier <= y.tier) { yy = x.val; } while (xx != yy) { final int xxx = xx; final int yyy = yy; int l = (int) BinSearch.bs(0, 31 , k -> (1 << k) <= tree[xxx].tier && lca[xxx][(int) k] != lca[yyy][(int) k]); xx = lca[xx][l].val; yy = lca[yy][l].val; } return tree[xx]; } //LCA end //graph List<Integer> adj[]; List<int[]> adj2[]; void initGraph(int n, int m, boolean hasW, boolean directed, int type) throws IOException { if (type == 1) { adj = new List[n + 1]; } else { adj2 = new List[n + 1]; } for (int i = 1; i <= n; i++) { if (type == 1) { adj[i] = new ArrayList<>(); } else { adj2[i] = new ArrayList<>(); } } for (int i = 0; i < m; i++) { int f = nextInt(); int t = nextInt(); if (type == 1) { adj[f].add(t); if (!directed) { adj[t].add(f); } } else { int w = hasW ? nextInt() : 0; adj2[f].add(new int[]{t, w}); if (!directed) { adj2[t].add(new int[]{f, w}); } } } } void getDiv(Map<Integer, Integer> map, long n) { int sqrt = (int) Math.sqrt(n); for (int i = 2; i <= sqrt; i++) { int cnt = 0; while (n % i == 0) { cnt++; n /= i; } if (cnt > 0) { map.put(i, cnt); } } if (n > 1) { map.put((int) n, 1); } } boolean[] generatePrime(int n) { boolean p[] = new boolean[n + 1]; p[2] = true; for (int i = 3; i <= n; i += 2) { p[i] = true; } for (int i = 3; i <= Math.sqrt(n); i += 2) { if (!p[i]) { continue; } for (int j = i * i; j <= n; j += i << 1) { p[j] = false; } } return p; } boolean isPrime(long n) { //determines if n is a prime number int p[] = {2, 3, 5, 233, 331}; int pn = p.length; long s = 0, t = n - 1;//n - 1 = 2^s * t while ((t & 1) == 0) { t >>= 1; ++s; } for (int i = 0; i < pn; ++i) { if (n == p[i]) { return true; } long pt = pow(p[i], t, n); for (int j = 0; j < s; ++j) { long cur = llMod(pt, pt, n); if (cur == 1 && pt != 1 && pt != n - 1) { return false; } pt = cur; } if (pt != 1) { return false; } } return true; } long[] llAdd2(long a[], long b[], long mod) { long c[] = new long[2]; c[1] = (a[1] + b[1]) % (mod * mod); c[0] = (a[1] + b[1]) / (mod * mod) + a[0] + b[0]; return c; } long[] llMod2(long a, long b, long mod) { long x1 = a / mod; long y1 = a % mod; long x2 = b / mod; long y2 = b % mod; long c = (x1 * y2 + x2 * y1) / mod; c += x1 * x2; long d = (x1 * y2 + x2 * y1) % mod * mod + y1 * y2; return new long[]{c, d}; } long llMod(long a, long b, long mod) { if (a > mod || b > mod) { return (a * b - (long) ((double) a / mod * b + 0.5) * mod + mod) % mod; } return a * b % mod; // long r = 0; // a %= mod; // b %= mod; // while (b > 0) { // if ((b & 1) == 1) { // r = (r + a) % mod; // } // b >>= 1; // a = (a << 1) % mod; // } // return r; } long pow(long a, long n) { long ans = 1; while (n > 0) { if ((n & 1) == 1) { ans = ans * a; } a = a * a; n >>= 1; } return ans; } long pow(long a, long n, long mod) { long ans = 1; while (n > 0) { if ((n & 1) == 1) { ans = llMod(ans, a, mod); } a = llMod(a, a, mod); n >>= 1; } return ans; } private long[][] initC(int n) { long c[][] = new long[n][n]; for (int i = 0; i < n; i++) { c[i][0] = 1; } for (int i = 1; i < n; i++) { for (int j = 1; j <= i; j++) { c[i][j] = c[i - 1][j - 1] + c[i - 1][j]; } } return c; } /** * ps: n >= m, choose m from n; */ // private int cmn(long n, long m) { // if (m > n) { // n ^= m; // m ^= n; // n ^= m; // } // m = Math.min(m, n - m); // // long top = 1; // long bot = 1; // for (long i = n - m + 1; i <= n; i++) { // top = (top * i) % MOD; // } // for (int i = 1; i <= m; i++) { // bot = (bot * i) % MOD; // } // // return (int) ((top * pow(bot, MOD - 2, MOD)) % MOD); // } long[] exGcd(long a, long b) { if (b == 0) { return new long[]{a, 1, 0}; } long[] ans = exGcd(b, a % b); long x = ans[2]; long y = ans[1] - a / b * ans[2]; ans[1] = x; ans[2] = y; return ans; } long gcd(long a, long b) { if (a < b) { return gcd(b, a); } while (b != 0) { long tmp = a % b; a = b; b = tmp; } return a; } int[] unique(int a[], Map<Integer, Integer> idx) { int tmp[] = a.clone(); Arrays.sort(tmp); int j = 0; for (int i = 0; i < tmp.length; i++) { if (i == 0 || tmp[i] > tmp[i - 1]) { idx.put(tmp[i], j++); } } int rs[] = new int[j]; j = 0; for (int key : idx.keySet()) { rs[j++] = key; } Arrays.sort(rs); return rs; } boolean isEven(long n) { return (n & 1) == 0; } static class BinSearch { static long bs(long l, long r, IBinSearch sort) throws IOException { while (l < r) { long m = l + (r - l) / 2; if (sort.binSearchCmp(m)) { l = m + 1; } else { r = m; } } return l; } interface IBinSearch { boolean binSearchCmp(long k) throws IOException; } } } private static class InOut { private BufferedReader br; private StreamTokenizer st; private PrintWriter pw; InOut() throws FileNotFoundException { if (useInFile) { System.setIn(new FileInputStream("resources/inout/in.text")); } if (useOutFile) { System.setOut(new PrintStream("resources/inout/out.text")); } br = new BufferedReader(new InputStreamReader(System.in)); st = new StreamTokenizer(br); pw = new PrintWriter(new OutputStreamWriter(System.out)); st.ordinaryChar('\''); st.ordinaryChar('\"'); st.ordinaryChar('/'); } private boolean hasNext() throws IOException { return st.nextToken() != StreamTokenizer.TT_EOF; } private long[] anLong(int n) throws IOException { long a[] = new long[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } private String next() throws IOException { if (st.nextToken() == StreamTokenizer.TT_EOF) { throw new IOException(); } return st.sval; } private String next(int len) throws IOException { char ch[] = new char[len]; int cur = 0; char c; while ((c = (char) br.read()) == '\n' || c == '\r' || c == ' ' || c == '\t') ; do { ch[cur++] = c; } while (!((c = (char) br.read()) == '\n' || c == '\r' || c == ' ' || c == '\t')); return String.valueOf(ch, 0, cur); } private int nextInt() throws IOException { if (st.nextToken() == StreamTokenizer.TT_EOF) { throw new IOException(); } return (int) st.nval; } private long nextLong(int n) throws IOException { return Long.parseLong(next(n)); } private double nextDouble() throws IOException { st.nextToken(); return st.nval; } private String[] nextSS(String reg) throws IOException { return br.readLine().split(reg); } private String nextLine() throws IOException { return br.readLine(); } private void print(String s, boolean newLine) { if (null != s) { pw.print(s); } if (newLine) { pw.println(); } } private void format(String format, Object... obj) { pw.format(format, obj); } private void flush() { pw.flush(); } } private static class FFT { double[] roots; int maxN; public FFT(int maxN) { this.maxN = maxN; initRoots(); } public long[] multiply(int[] a, int[] b) { int minSize = a.length + b.length - 1; int bits = 1; while (1 << bits < minSize) bits++; int N = 1 << bits; double[] aa = toComplex(a, N); double[] bb = toComplex(b, N); fftIterative(aa, false); fftIterative(bb, false); double[] c = new double[aa.length]; for (int i = 0; i < N; i++) { c[2 * i] = aa[2 * i] * bb[2 * i] - aa[2 * i + 1] * bb[2 * i + 1]; c[2 * i + 1] = aa[2 * i] * bb[2 * i + 1] + aa[2 * i + 1] * bb[2 * i]; } fftIterative(c, true); long[] ret = new long[minSize]; for (int i = 0; i < ret.length; i++) { ret[i] = Math.round(c[2 * i]); } return ret; } static double[] toComplex(int[] arr, int size) { double[] ret = new double[size * 2]; for (int i = 0; i < arr.length; i++) { ret[2 * i] = arr[i]; } return ret; } void initRoots() { roots = new double[2 * (maxN + 1)]; double ang = 2 * Math.PI / maxN; for (int i = 0; i <= maxN; i++) { roots[2 * i] = Math.cos(i * ang); roots[2 * i + 1] = Math.sin(i * ang); } } int bits(int N) { int ret = 0; while (1 << ret < N) ret++; if (1 << ret != N) throw new RuntimeException(); return ret; } void fftIterative(double[] array, boolean inv) { int bits = bits(array.length / 2); int N = 1 << bits; for (int from = 0; from < N; from++) { int to = Integer.reverse(from) >>> (32 - bits); if (from < to) { double tmpR = array[2 * from]; double tmpI = array[2 * from + 1]; array[2 * from] = array[2 * to]; array[2 * from + 1] = array[2 * to + 1]; array[2 * to] = tmpR; array[2 * to + 1] = tmpI; } } for (int n = 2; n <= N; n *= 2) { int delta = 2 * maxN / n; for (int from = 0; from < N; from += n) { int rootIdx = inv ? 2 * maxN : 0; double tmpR, tmpI; for (int arrIdx = 2 * from; arrIdx < 2 * from + n; arrIdx += 2) { tmpR = array[arrIdx + n] * roots[rootIdx] - array[arrIdx + n + 1] * roots[rootIdx + 1]; tmpI = array[arrIdx + n] * roots[rootIdx + 1] + array[arrIdx + n + 1] * roots[rootIdx]; array[arrIdx + n] = array[arrIdx] - tmpR; array[arrIdx + n + 1] = array[arrIdx + 1] - tmpI; array[arrIdx] += tmpR; array[arrIdx + 1] += tmpI; rootIdx += (inv ? -delta : delta); } } } if (inv) { for (int i = 0; i < array.length; i++) { array[i] /= N; } } } } }
Java
["5 4\n\n0\n\n5\n\n9\n\n7"]
1 second
["? 0000\n\n? 1110\n\n? 1111\n\n? 1101\n\n! 7"]
NoteHere is the graph of the example, satisfying $$$l_i=i$$$.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy", "interactive", "sortings" ]
003b7257b35416ec93f189cb29e458e6
The first and only line of input contains two integers $$$n,m$$$ ($$$2 \leq n \leq 200$$$, $$$1\le m \le 500$$$) — the number of stations and tracks.
1,700
null
standard output
PASSED
da1ceb7cac8ff6b854a9a4001b3a25df
train_108.jsonl
1654266900
As for the technology in the outside world, it is really too advanced for Gensokyo to even look up to.—Yasaka Kanako, Symposium of Post-mysticismThis is an interactive problem.Under the direct supervision of Kanako and the Moriya Shrine, the railway system of Gensokyo is finally finished. GSKR (Gensokyo Railways) consists of $$$n$$$ stations with $$$m$$$ bidirectional tracks connecting them. The $$$i$$$-th track has length $$$l_i$$$ ($$$1\le l_i\le 10^6$$$). Due to budget limits, the railway system may not be connected, though there may be more than one track between two stations.The value of a railway system is defined as the total length of its all tracks. The maximum (or minimum) capacity of a railway system is defined as the maximum (or minimum) value among all of the currently functional system's full spanning forest.In brief, full spanning forest of a graph is a spanning forest with the same connectivity as the given graph.Kanako has a simulator only able to process no more than $$$2m$$$ queries. The input of the simulator is a string $$$s$$$ of length $$$m$$$, consisting of characters 0 and/or 1. The simulator will assume the $$$i$$$-th track functional if $$$s_i=$$$ 1. The device will then tell Kanako the maximum capacity of the system in the simulated state.Kanako wants to know the the minimum capacity of the system with all tracks functional with the help of the simulator.The structure of the railway system is fixed in advance. In other words, the interactor is not adaptive.
256 megabytes
/* I am dead inside Do you like NCT, sKz, BTS? 5 4 3 2 1 Moonwalk Imma knock it down like domino Is this what you want? Is this what you want? Let's ttalkbocky about that :() */ import static java.lang.Math.*; import java.util.*; import java.io.*; public class x1687B { public static void main(String omkar[]) throws Exception { BufferedReader infile = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(infile.readLine()); int N = Integer.parseInt(st.nextToken()); int M = Integer.parseInt(st.nextToken()); int[] weights = new int[M]; for(int i=0; i < M; i++) { StringBuilder query = new StringBuilder("? "); for(int a=0; a < M; a++) { if(a == i) query.append(1); else query.append(0); } System.out.println(query); weights[i] = Integer.parseInt(infile.readLine()); } ArrayList<Integer> order = new ArrayList<Integer>(); for(int i=0; i < M; i++) order.add(i); Collections.sort(order, (x, y) -> { return weights[x]-weights[y]; }); boolean[] include = new boolean[M]; include[order.get(0)] = true; int[] sums = new int[M]; sums[0] = weights[order.get(0)]; for(int i=1; i < M; i++) { int curr = order.get(i); StringBuilder query = new StringBuilder("? "); for(int a=0; a < M; a++) { if(include[a] || a == curr) query.append(1); else query.append(0); } System.out.println(query); sums[i] = Integer.parseInt(infile.readLine()); if(sums[i-1]+weights[curr] == sums[i]) include[curr] = true; else sums[i] = sums[i-1]; } StringBuilder query = new StringBuilder("? "); for(int i=0; i < M; i++) { if(include[i]) query.append(1); else query.append(0); } System.out.println(query); int res = Integer.parseInt(infile.readLine()); System.out.println("! "+res); } public static int[] readArr(int N, BufferedReader infile, StringTokenizer st) throws Exception { int[] arr = new int[N]; st = new StringTokenizer(infile.readLine()); for(int i=0; i < N; i++) arr[i] = Integer.parseInt(st.nextToken()); return arr; } }
Java
["5 4\n\n0\n\n5\n\n9\n\n7"]
1 second
["? 0000\n\n? 1110\n\n? 1111\n\n? 1101\n\n! 7"]
NoteHere is the graph of the example, satisfying $$$l_i=i$$$.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy", "interactive", "sortings" ]
003b7257b35416ec93f189cb29e458e6
The first and only line of input contains two integers $$$n,m$$$ ($$$2 \leq n \leq 200$$$, $$$1\le m \le 500$$$) — the number of stations and tracks.
1,700
null
standard output
PASSED
9f3715569bb8574c91ae17eb41af6144
train_108.jsonl
1654266900
As for the technology in the outside world, it is really too advanced for Gensokyo to even look up to.—Yasaka Kanako, Symposium of Post-mysticismThis is an interactive problem.Under the direct supervision of Kanako and the Moriya Shrine, the railway system of Gensokyo is finally finished. GSKR (Gensokyo Railways) consists of $$$n$$$ stations with $$$m$$$ bidirectional tracks connecting them. The $$$i$$$-th track has length $$$l_i$$$ ($$$1\le l_i\le 10^6$$$). Due to budget limits, the railway system may not be connected, though there may be more than one track between two stations.The value of a railway system is defined as the total length of its all tracks. The maximum (or minimum) capacity of a railway system is defined as the maximum (or minimum) value among all of the currently functional system's full spanning forest.In brief, full spanning forest of a graph is a spanning forest with the same connectivity as the given graph.Kanako has a simulator only able to process no more than $$$2m$$$ queries. The input of the simulator is a string $$$s$$$ of length $$$m$$$, consisting of characters 0 and/or 1. The simulator will assume the $$$i$$$-th track functional if $$$s_i=$$$ 1. The device will then tell Kanako the maximum capacity of the system in the simulated state.Kanako wants to know the the minimum capacity of the system with all tracks functional with the help of the simulator.The structure of the railway system is fixed in advance. In other words, the interactor is not adaptive.
256 megabytes
import java.io.*; import java.util.Arrays; import java.util.StringTokenizer; public class Main { public static void main(String[] args) { InputReader in = new InputReader(System.in); PrintWriter out = new PrintWriter(System.out); Task solver = new Task(); solver.solve(1, in, out); out.close(); } static class Task { public void solve(int testNumber, InputReader in, PrintWriter out) { for (int i = 0; i < testNumber; i++) { int n = in.nextInt(); int m = in.nextInt(); int[][] a = new int[m][2]; for (int j = 0; j < m; j++) { int[] arr = new int[m]; arr[j] = 1; out.print("? "); for (int v : arr) { out.print(v); } out.println(); out.flush(); a[j] = new int[]{in.nextInt(), j}; } int[] arr = new int[m]; Arrays.fill(arr, 1); out.print("? "); for (int v : arr) { out.print(v); } out.println(); out.flush(); int cur = in.nextInt(); Arrays.sort(a, (o1, o2) -> o2[0] - o1[0]); for (int j = 0; j < a.length - 1; j++) { arr[a[j][1]] = 0; out.print("? "); for (int v : arr) { out.print(v); } out.println(); out.flush(); int next = in.nextInt(); if (cur - next != a[j][0]) { cur = next; } else { arr[a[j][1]] = 1; } } out.println("! " + cur); } } } 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()); } } }
Java
["5 4\n\n0\n\n5\n\n9\n\n7"]
1 second
["? 0000\n\n? 1110\n\n? 1111\n\n? 1101\n\n! 7"]
NoteHere is the graph of the example, satisfying $$$l_i=i$$$.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy", "interactive", "sortings" ]
003b7257b35416ec93f189cb29e458e6
The first and only line of input contains two integers $$$n,m$$$ ($$$2 \leq n \leq 200$$$, $$$1\le m \le 500$$$) — the number of stations and tracks.
1,700
null
standard output
PASSED
2468b04a8cc62a0ae0821c93088e12b9
train_108.jsonl
1654266900
As for the technology in the outside world, it is really too advanced for Gensokyo to even look up to.—Yasaka Kanako, Symposium of Post-mysticismThis is an interactive problem.Under the direct supervision of Kanako and the Moriya Shrine, the railway system of Gensokyo is finally finished. GSKR (Gensokyo Railways) consists of $$$n$$$ stations with $$$m$$$ bidirectional tracks connecting them. The $$$i$$$-th track has length $$$l_i$$$ ($$$1\le l_i\le 10^6$$$). Due to budget limits, the railway system may not be connected, though there may be more than one track between two stations.The value of a railway system is defined as the total length of its all tracks. The maximum (or minimum) capacity of a railway system is defined as the maximum (or minimum) value among all of the currently functional system's full spanning forest.In brief, full spanning forest of a graph is a spanning forest with the same connectivity as the given graph.Kanako has a simulator only able to process no more than $$$2m$$$ queries. The input of the simulator is a string $$$s$$$ of length $$$m$$$, consisting of characters 0 and/or 1. The simulator will assume the $$$i$$$-th track functional if $$$s_i=$$$ 1. The device will then tell Kanako the maximum capacity of the system in the simulated state.Kanako wants to know the the minimum capacity of the system with all tracks functional with the help of the simulator.The structure of the railway system is fixed in advance. In other words, the interactor is not adaptive.
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 B_Railway_System{ 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 n=s.nextInt(); int m=s.nextInt(); yoyo obj5 = new yoyo(); PriorityQueue<pair> well = new PriorityQueue<>(obj5); for(int i=0;i<m;i++){ StringBuilder res2 = new StringBuilder(); for(int j=0;j<m;j++){ if(i==j){ res2.append("1"); } else{ res2.append("0"); } } res2.append("\n"); System.out.println("? "+res2); System.out.println(); System.out.flush(); long hh=s.nextLong(); pair obj = new pair(hh,i); well.add(obj); } char array[]= new char[m]; for(int i=0;i<m;i++){ array[i]='0'; } long ans=0; while(well.size()>0){ pair obj = well.poll(); long a=obj.a;//value of that edge long b=obj.b;//index of that edge StringBuilder res2 = new StringBuilder(); for(int i=0;i<m;i++){ if(i==b){ res2.append("1"); } else{ res2.append(array[i]); } } res2.append("\n"); System.out.println("? "+res2); System.out.println(); System.out.flush(); long hh=s.nextLong(); if(hh==(ans+a)){ ans=hh; array[(int)b]='1'; } else{ } } res.append(ans+" \n"); System.out.println("! "+res); System.out.println(); System.out.flush(); } static class yoyo implements Comparator<pair>{ public int compare(pair o1, pair o2) { // TODO Auto-generated method stub if(o1.a<o2.a){ return -1; } else{ return 1; } } } static class pair{ long a; long b; pair(long a, long b){ this.a=a; this.b=b; } } 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 4\n\n0\n\n5\n\n9\n\n7"]
1 second
["? 0000\n\n? 1110\n\n? 1111\n\n? 1101\n\n! 7"]
NoteHere is the graph of the example, satisfying $$$l_i=i$$$.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy", "interactive", "sortings" ]
003b7257b35416ec93f189cb29e458e6
The first and only line of input contains two integers $$$n,m$$$ ($$$2 \leq n \leq 200$$$, $$$1\le m \le 500$$$) — the number of stations and tracks.
1,700
null
standard output
PASSED
a67ce933194fb9ff249f30ecde2a634c
train_108.jsonl
1654266900
As for the technology in the outside world, it is really too advanced for Gensokyo to even look up to.—Yasaka Kanako, Symposium of Post-mysticismThis is an interactive problem.Under the direct supervision of Kanako and the Moriya Shrine, the railway system of Gensokyo is finally finished. GSKR (Gensokyo Railways) consists of $$$n$$$ stations with $$$m$$$ bidirectional tracks connecting them. The $$$i$$$-th track has length $$$l_i$$$ ($$$1\le l_i\le 10^6$$$). Due to budget limits, the railway system may not be connected, though there may be more than one track between two stations.The value of a railway system is defined as the total length of its all tracks. The maximum (or minimum) capacity of a railway system is defined as the maximum (or minimum) value among all of the currently functional system's full spanning forest.In brief, full spanning forest of a graph is a spanning forest with the same connectivity as the given graph.Kanako has a simulator only able to process no more than $$$2m$$$ queries. The input of the simulator is a string $$$s$$$ of length $$$m$$$, consisting of characters 0 and/or 1. The simulator will assume the $$$i$$$-th track functional if $$$s_i=$$$ 1. The device will then tell Kanako the maximum capacity of the system in the simulated state.Kanako wants to know the the minimum capacity of the system with all tracks functional with the help of the simulator.The structure of the railway system is fixed in advance. In other words, the interactor is not adaptive.
256 megabytes
import java.io.*; import java.util.*; //import org.graalvm.compiler.core.common.Fields.ObjectTransformer; import java.math.*; import java.math.BigInteger; public final class A { static PrintWriter out = new PrintWriter(System.out); static StringBuilder ans=new StringBuilder(); static FastReader in=new FastReader(); static ArrayList<Integer> g[]; static long mod=998244353,INF=Long.MAX_VALUE; static boolean set[]; static int max=0; static int lca[][]; static int par[],col[],D[]; static long fact[]; static int size[],dp[][],countW[],countB[],N; static long sum[],f[]; static long t[],max_depth[],seg[]; static boolean sep[],isWhite[]; static boolean marked[],visited[],recStack[]; static int segR[],segC[]; static HashMap<Long,Integer> mp[]; public static void main(String args[])throws IOException { /* * star,rope,TPST * BS,LST,MS,MQ */ int N=i(),M=i(); int X[]=new int[M]; pair A[]=new pair[M]; for(int i=0; i<M; i++) { X[i]=1; A[i]=new pair(i,ask(X)); X[i]=0; } Arrays.sort(A); long s=0; for(pair x:A) { int a=x.size; int index=x.index; X[index]=1; long sum=ask(X); if(sum-s==a) { s+=a; } else X[index]=0; } out.print("! "+s); out.println(ans); out.close(); } static int ask(int X[]) { out.print("? "); for(int x:X)out.print(x); out.println(); out.flush(); return i(); } static int f(int cA,int cB, int mA,int mB) { int max=0; StringBuilder sb=new StringBuilder(); int a=0,b=0; boolean f=true; for(int i=0; a+b<cA+cB; i++) { if(f) { int run=a; for(int j=0; j<mA; j++) { a++; if(a==cA) break; } if(a==run)break; } else { int run=b; for(int j=0; j<mB; j++) { b++; if(b==cB) break; } if(b==run)break; } f^=true; } max=a+b; a=0;b=0; f=false; for(int i=0; a+b<cA+cB; i++) { if(f) { int run=a; for(int j=0; j<mA; j++) { a++; if(a==cA) break; } if(a==run)break; } else { int run=b; for(int j=0; j<mB; j++) { b++; if(b==cB) break; } if(b==run)break; } f^=true; } return Math.max(a+b,max); } static int dff(int n,int p,long L[],long R[]) { long s=0; int cnt=0; for(int c:g[n]) { if(c!=p) { cnt+=dff(c,n,L,R); s+=sum[c]; } } if(s<L[n]) { cnt++; sum[n]=R[n]; } else { sum[n]=Math.min(s, R[n]); } return cnt; } static void calculatePre(long A[][],int N,int M) { for(int i=1; i<=N; i++) { for(int j=1; j<=M; j++)A[i][j]+=A[i][j-1]; } for(int j=1; j<=M; j++) { for(int i=2; i<=N; i++)A[i][j]+=A[i-1][j]; } } static boolean equals(char X[],char Y[]) { for(int i=0; i<X.length; i++)if(X[i]!=Y[i])return false; return true; } static long nCr(long n,long r) { long s=0; long c=n-r; n=fact[(int)n]; r=fact[(int)r]; c=fact[(int)c]; r=pow(r,mod-2)%mod; c=pow(c,mod-2)%mod; s=(r*c)%mod; s=(s*n)%mod; return s%mod; } static boolean isValid(int x,int y,int N,int M) { if(x>=N || y>=M)return false; if(x<0 || y<0)return false; return true; } static int f2(int n,int p) { ArrayList<Integer> X=new ArrayList<>(); for(int c:g[n]) { if(c!=p) { X.add(c); } } // System.out.println("for--> "+n+" "+X); if(X.size()==0)return 0; if(X.size()==1)return size[n]-1; int a=X.get(0),b=X.get(1); // System.out.println("n--> "+n+" "+(size[a]+f2(b,n))+" "+(size[b]+f2(a,n))); return Math.max(size[a]+f2(b,n), size[b]+f2(a,n)); // return 0; } static void f(int n,int p) { for(int c:g[n]) { if(c!=p) { f(c,n); size[n]+=size[c]+1; } } // size[n]++; } static boolean isPower(long a,long b) { while(a%b==0) { } return a==1; } static String rotate(String X,int K) { StringBuilder sb=new StringBuilder(); int N=X.length(); int k=K%N; for(int i=N-k; i<N;i++) { sb.append(X.charAt(i)); } for(int i=0; i<N-k; i++) { sb.append(X.charAt(i)); } return sb.toString(); } static int rounds(String X,String Y) { int n=Y.length(); for(int i=1; i<Y.length(); i++) { if(X.charAt(0)==Y.charAt(0) && X.substring(i,i+n).equals(Y))return i; } return Y.length(); } static int index(ArrayList<Long> X,long x) { int l=-1,r=X.size(); while(r-l>1) { int m=(l+r)/2; if(X.get(m)<=x)l=m; else r=m; } return l+1; } static void swap(int i,int j,long A[][]) { for(int row=0; row<A.length; row++) { long t=A[row][i]; A[row][i]=A[row][j]; A[row][j]=t; } } static boolean isSorted(long A[]) { for(int i=1; i<A.length; i++)if(A[i]<A[i-1])return false; return true; } static void dfs(int node, int dp[], boolean visited[],long A[],long a) { // Mark as visited visited[node] = true; // Traverse for all its children for (int c:g[node]) { // If not visited if (A[c-1]<=a && !visited[c]) dfs(c, dp, visited,A,a); // Store the max of the paths dp[node] = Math.max(dp[node], 1 + dp[c]); } } static int findLongestPath( int n,long A[],long a) { // Dp array int[] dp = new int[n+1]; // Visited array to know if the node // has been visited previously or not boolean[] visited = new boolean[n + 1]; // Call DFS for every unvisited vertex for (int i = 1; i <= n; i++) { if (A[i-1]<=a && !visited[i]) dfs(i, dp, visited,A,a); } int ans = 0; // Traverse and find the maximum of all dp[i] for (int i = 1; i <= n; i++) { ans = Math.max(ans, dp[i]); } return ans; } static boolean isCyclicUtil(int n, boolean[] visited, boolean[] recStack,long A[],long a) { if (recStack[n]) return true; if (visited[n]) return false; visited[n] = true; recStack[n] = true; for (int c: g[n]) { if(A[c-1]<=a ) { if (isCyclicUtil(c, visited, recStack,A,a)) return true; } } recStack[n] = false; return false; } static void push(int v) { if (marked[v]) { t[v*2] = t[v*2+1] = t[v]; marked[v*2] = marked[v*2+1] = true; marked[v] = false; } } static void update1(int v, int tl, int tr, int l, int r, int new_val) { if (l > r) return; if (l == tl && tr == r) { t[v] = new_val; marked[v] = true; } else { push(v); int tm = (tl + tr) / 2; update1(v*2, tl, tm, l, Math.min(r, tm), new_val); update1(v*2+1, tm+1, tr, Math.max(l, tm+1), r, new_val); } } static long get1(int v, int tl, int tr, int pos) { if (tl == tr) { return t[v]; } push(v); int tm = (tl + tr) / 2; if (pos <= tm) return get1(v*2, tl, tm, pos); else return get1(v*2+1, tm+1, tr, pos); } static int cost=0; static void fmin(int i,int j,ArrayList<Integer> A,int cZ,int cO) { if(j-i>1) { int a=A.get(i),b=A.get(j); cO+=Math.min(a, b); if(a<b) { } else if(b>a) { } else { } } } static void fs(int n,int p) { if(isWhite[n])countW[n]=1; else countB[n]=1; for(int c:g[n]) { if(c!=p) { fs(c,n); countB[n]+=countB[c]; countW[n]+=countW[c]; } } } static int f(char X[],char Y[]) { int s=0; for(int i=0; i<Y.length; i++) { s+=Math.abs(X[i]-Y[i]); } return s; } public static long mergeSort(int A[],int l,int r) { long a=0; if(l<r) { int m=(l+r)/2; a+=mergeSort(A,l,m); a+=mergeSort(A,m+1,r); a+=merge(A,l,m,r); } return a; } public static long merge(int A[],int l,int m,int r) { long a=0; int i=l,j=m+1,index=0; long c=0; int B[]=new int[r-l+1]; while(i<=m && j<=r) { if(A[i]<=A[j]) { c++; B[index++]=A[i++]; } else { long s=(m-l)+1; a+=(s-c); B[index++]=A[j++]; } } while(i<=m)B[index++]=A[i++]; while(j<=r)B[index++]=A[j++]; index=0; for(; l<=r; l++)A[l]=B[index++]; return a; } static int f(int A[]) { int s=0; for(int i=1; i<4; i++) { s+=Math.abs(A[i]-A[i-1]); } return s; } static boolean f(int A[],int B[],int N) { for(int i=0; i<N; i++) { if(Math.abs(A[i]-B[i])>1)return false; } return true; } static int [] prefix(char s[],int N) { // int n = (int)s.length(); // vector<int> pi(n); N=s.length; int pi[]=new int[N]; for (int i = 1; i < N; i++) { int j = pi[i-1]; while (j > 0 && s[i] != s[j]) j = pi[j-1]; if (s[i] == s[j]) j++; pi[i] = j; } return pi; } static int count(long N) { int cnt=0; long p=1L; while(p<=N) { if((p&N)!=0)cnt++; p<<=1; } return cnt; } static long kadane(long A[]) { long lsum=A[0],gsum=0; gsum=Math.max(gsum, lsum); for(int i=1; i<A.length; i++) { lsum=Math.max(lsum+A[i],A[i]); gsum=Math.max(gsum,lsum); } return gsum; } public static void reverse(int i,int j,int A[]) { while(i<j) { int t=A[i]; A[i]=A[j]; A[j]=t; i++; j--; } } public static int ask(int a,int b,int c) { System.out.println("? "+a+" "+b+" "+c); return i(); } static int[] reverse(int A[],int N) { int B[]=new int[N]; for(int i=N-1; i>=0; i--) { B[N-i-1]=A[i]; } return B; } static boolean isPalin(char X[]) { int i=0,j=X.length-1; while(i<=j) { if(X[i]!=X[j])return false; i++; j--; } return true; } static int distance(int a,int b) { int d=D[a]+D[b]; int l=LCA(a,b); l=2*D[l]; return d-l; } static int LCA(int a,int b) { if(D[a]<D[b]) { int t=a; a=b; b=t; } int d=D[a]-D[b]; int p=1; for(int i=0; i>=0 && p<=d; i++) { if((p&d)!=0) { a=lca[a][i]; } p<<=1; } if(a==b)return a; for(int i=max-1; i>=0; i--) { if(lca[a][i]!=-1 && lca[a][i]!=lca[b][i]) { a=lca[a][i]; b=lca[b][i]; } } return lca[a][0]; } static void dfs(int n,int p) { lca[n][0]=p; if(p!=-1)D[n]=D[p]+1; for(int c:g[n]) { if(c!=p) { dfs(c,n); } } } static int[] prefix_function(char X[])//returns pi(i) array { int N=X.length; int pre[]=new int[N]; for(int i=1; i<N; i++) { int j=pre[i-1]; while(j>0 && X[i]!=X[j]) j=pre[j-1]; if(X[i]==X[j])j++; pre[i]=j; } return pre; } static int right(int A[],int Limit,int l,int r) { while(r-l>1) { int m=(l+r)/2; if(A[m]<Limit)l=m; else r=m; } return l; } static int left(int A[],int a,int l,int r) { while(r-l>1) { int m=(l+r)/2; if(A[m]<a)l=m; else r=m; } return l; } // static void build(int v,int tl,int tr,long A[]) // { // if(tl==tr) // { // long a=0; // if(A[tl]>0) // { // a=A[tl]; // // } // seg[v]=new node(a,a,a,A[tl],A[tl]); // return; // } // int tm=(tl+tr)/2; // build(v*2,tl,tm,A); // build(v*2+1,tm+1,tr,A); // seg[v]=combine(seg[v*2],seg[v*2+1]); // } // static node combine(node a,node b) // { // node temp=new node(0,0,0,0); // temp.pref=max(a.pref,a.sum+b.pref,a.sum+b.sum); // temp.suff=max(b.suff,b.sum+a.suff,b.sum+a.sum); // temp.max=max(a.max,b.max,a.suff+b.pref); // temp.sum=a.sum+b.sum; // temp.min=Math.max(a.min, b.min); // return temp; // } // static long max(long a,long b,long c) // { // return Math.max(a,Math.max(b, c)); // } // // static void update(int v,int tl,int tr,int index) // // { // // if(index==tl && index==tr) // // { // // segR[v]+=1; // // segR[v]%=2; // // } // // else // // { // // int tm=(tl+tr)/2; // // if(index<=tm)update(v*2,tl,tm,index); // // else update(v*2+1,tm+1,tr,index); // // segR[v]=segR[v*2]+segR[v*2+1]; // // } // // } // static long ask(int v,int tl,int tr,int l,int r) // { // // if(l>r)return 0; // if(tl==l && r==tr) // { // return seg[v].max; // } // int tm=(tl+tr)/2; // // return Math.max(ask(v*2,tl,tm,l,Math.min(tm, r)),ask(v*2+1,tm+1,tr,Math.max(tm+1, l),r)); // } static void build(int v,int tl,int tr,long A[]) { if(tl==tr) { seg[v]=A[tl]; return; } int tm=(tl+tr)/2; build(v*2,tl,tm,A); build(v*2+1,tm+1,tr,A); seg[v]=Math.max(seg[v*2],seg[v*2+1]); } static void update(int v,int tl,int tr,int index,int a) { if(index==tl && tl==tr) { seg[v]++; seg[v]%=2; } else { int tm=(tl+tr)/2; if(index<=tm)update(2*v,tl,tm,index,a); else update(2*v+1,tm+1,tr,index,a); seg[v]=seg[v*2]+seg[v*2+1]; } } static long ask(int v,int tl,int tr,int l,int r) { if(l>r)return 0; if(tl==l && tr==r)return seg[v]; int tm=(tl+tr)/2; return Math.max(ask(v*2,tl,tm,l,Math.min(tm,r)),ask(v*2+1,tm+1,tr,Math.max(l, tm+1),r)); } static void updateC(int v,int tl,int tr,int index) { if(index==tl && index==tr) { segC[v]+=1; segC[v]%=2; } else { int tm=(tl+tr)/2; if(index<=tm)updateC(v*2,tl,tm,index); else updateC(v*2+1,tm+1,tr,index); segC[v]=segC[v*2]+segC[v*2+1]; } } static int askC(int v,int tl,int tr,int l,int r) { if(l>r)return 0; if(tl==l && r==tr) { return segC[v]; } int tm=(tl+tr)/2; return askC(v*2,tl,tm,l,Math.min(tm, r))+askC(v*2+1,tm+1,tr,Math.max(tm+1, l),r); } static boolean f(long A[],long m,int N) { long B[]=new long[N]; for(int i=0; i<N; i++) { B[i]=A[i]; } for(int i=N-1; i>=0; i--) { if(B[i]<m)return false; if(i>=2) { long extra=Math.min(B[i]-m, A[i]); long x=extra/3L; B[i-2]+=2L*x; B[i-1]+=x; } } return true; } static int f(int l,int r,long A[],long x) { while(r-l>1) { int m=(l+r)/2; if(A[m]>=x)l=m; else r=m; } return r; } static boolean f(long m,long H,long A[],int N) { long s=m; for(int i=0; i<N-1;i++) { s+=Math.min(m, A[i+1]-A[i]); } return s>=H; } static long ask(long l,long r) { System.out.println("? "+l+" "+r); return l(); } static long f(long N,long M) { long s=0; if(N%3==0) { N/=3; s=N*M; } else { long b=N%3; N/=3; N++; s=N*M; N--; long a=N*M; if(M%3==0) { M/=3; a+=(b*M); } else { M/=3; M++; a+=(b*M); } s=Math.min(s, a); } return s; } static int ask(StringBuilder sb,int a) { System.out.println(sb+""+a); return i(); } static void swap(char X[],int i,int j) { char x=X[i]; X[i]=X[j]; X[j]=x; } static int min(int a,int b,int c) { return Math.min(Math.min(a, b), c); } static long and(int i,int j) { System.out.println("and "+i+" "+j); return l(); } static long or(int i,int j) { System.out.println("or "+i+" "+j); return l(); } static int len=0,number=0; static void f(char X[],int i,int num,int l) { if(i==X.length) { if(num==0)return; //update our num if(isPrime(num))return; if(l<len) { len=l; number=num; } return; } int a=X[i]-'0'; f(X,i+1,num*10+a,l+1); f(X,i+1,num,l); } static boolean is_Sorted(int A[]) { int N=A.length; for(int i=1; i<=N; i++)if(A[i-1]!=i)return false; return true; } static boolean f(StringBuilder sb,String Y,String order) { StringBuilder res=new StringBuilder(sb.toString()); HashSet<Character> set=new HashSet<>(); for(char ch:order.toCharArray()) { set.add(ch); for(int i=0; i<sb.length(); i++) { char x=sb.charAt(i); if(set.contains(x))continue; res.append(x); } } String str=res.toString(); return str.equals(Y); } static boolean all_Zero(int f[]) { for(int a:f)if(a!=0)return false; return true; } static long form(int a,int l) { long x=0; while(l-->0) { x*=10; x+=a; } return x; } static int count(String X) { HashSet<Integer> set=new HashSet<>(); for(char x:X.toCharArray())set.add(x-'0'); return set.size(); } static int f(long K) { long l=0,r=K; while(r-l>1) { long m=(l+r)/2; if(m*m<K)l=m; else r=m; } return (int)l; } static int [] sub(int A[],int B[]) { int N=A.length; int f[]=new int[N]; for(int i=N-1; i>=0; i--) { if(B[i]<A[i]) { B[i]+=26; B[i-1]-=1; } f[i]=B[i]-A[i]; } for(int i=0; i<N; i++) { if(f[i]%2!=0)f[i+1]+=26; f[i]/=2; } return f; } static int[] f(int N) { char X[]=in.next().toCharArray(); int A[]=new int[N]; for(int i=0; i<N; i++)A[i]=X[i]-'a'; return A; } static int max(int a ,int b,int c,int d) { a=Math.max(a, b); c=Math.max(c,d); return Math.max(a, c); } static int min(int a ,int b,int c,int d) { a=Math.min(a, b); c=Math.min(c,d); return Math.min(a, c); } static HashMap<Integer,Integer> Hash(int A[]) { HashMap<Integer,Integer> mp=new HashMap<>(); for(int a:A) { int f=mp.getOrDefault(a,0)+1; mp.put(a, f); } return mp; } static long mul(long a, long b) { return ( a %mod * 1L * b%mod )%mod; } static void swap(int A[],int a,int b) { int t=A[a]; A[a]=A[b]; A[b]=t; } static int find(int a) { if(par[a]<0)return a; return par[a]=find(par[a]); } static void union(int a,int b) { a=find(a); b=find(b); if(a!=b) { if(par[a]>par[b]) //this means size of a is less than that of b { int t=b; b=a; a=t; } par[a]+=par[b]; par[b]=a; } } static boolean isSorted(int A[]) { for(int i=1; i<A.length; i++) { if(A[i]<A[i-1])return false; } return true; } static boolean isDivisible(StringBuilder X,int i,long num) { long r=0; for(; i<X.length(); i++) { r=r*10+(X.charAt(i)-'0'); r=r%num; } return r==0; } static int lower_Bound(int A[],int low,int high, int x) { if (low > high) if (x >= A[high]) return A[high]; int mid = (low + high) / 2; if (A[mid] == x) return A[mid]; if (mid > 0 && A[mid - 1] <= x && x < A[mid]) return A[mid - 1]; if (x < A[mid]) return lower_Bound( A, low, mid - 1, x); return lower_Bound(A, mid + 1, high, x); } static String f(String A) { String X=""; for(int i=A.length()-1; i>=0; i--) { int c=A.charAt(i)-'0'; X+=(c+1)%2; } return X; } static void sortR(long[] a) //check for long { ArrayList<Long> l=new ArrayList<>(); for (long i:a) l.add(i); Collections.sort(l); int N=a.length; for (int i=0; i<a.length; i++) a[i]=l.get(N-i-1); } static void sort(long[] a) //check for long { ArrayList<Long> l=new ArrayList<>(); for (long i:a) l.add(i); Collections.sort(l); for (int i=0; i<a.length; i++) a[i]=l.get(i); } static String swap(String X,int i,int j) { char ch[]=X.toCharArray(); char a=ch[i]; ch[i]=ch[j]; ch[j]=a; return new String(ch); } static int sD(long n) { if (n % 2 == 0 ) return 2; for (int i = 3; i * i <= n; i += 2) { if (n % i == 0 ) return i; } return (int)n; } // static void setGraph(int N,int nodes) // { //// size=new int[N+1]; // par=new int[N+1]; // col=new int[N+1]; //// g=new int[N+1][]; // D=new int[N+1]; // int deg[]=new int[N+1]; // int A[][]=new int[nodes][2]; // for(int i=0; i<nodes; i++) // { // int a=i(),b=i(); // A[i][0]=a; // A[i][1]=b; // deg[a]++; // deg[b]++; // } // for(int i=0; i<=N; i++) // { // g[i]=new int[deg[i]]; // deg[i]=0; // } // for(int a[]:A) // { // int x=a[0],y=a[1]; // g[x][deg[x]++]=y; // g[y][deg[y]++]=x; // } // } static long pow(long a,long b) { //long mod=1000000007; 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 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; } static int countBits(long a) { return (int)(Math.log(a)/Math.log(2)+1); } static long fact(long N) { long n=2; if(N<=1)return 1; else { for(int i=3; i<=N; i++)n=(n*i)%mod; } return n; } static void sort(int[] a) { ArrayList<Integer> l=new ArrayList<>(); for (int i:a) l.add(i); Collections.sort(l); for (int i=0; i<a.length; i++) a[i]=l.get(i); } static 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; } static void print(char A[]) { for(char c:A)System.out.print(c+" "); System.out.println(); } static void print(boolean A[]) { for(boolean c:A)System.out.print(c+" "); System.out.println(); } static void print(int A[]) { for(int a:A)System.out.print(a+" "); System.out.println(); } static void print(long A[]) { for(long i:A)System.out.print(i+ " "); System.out.println(); } static void print(boolean A[][]) { for(boolean a[]:A)print(a); } static void print(long A[][]) { for(long a[]:A)print(a); } static void print(int A[][]) { for(int a[]:A)print(a); } static void print(ArrayList<Integer> A) { for(int a:A)System.out.print(a+" "); System.out.println(); } static int i() { return in.nextInt(); } static long l() { return in.nextLong(); } 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 long GCD(long a,long b) { if(b==0) { return a; } else return GCD(b,a%b ); } } class pair implements Comparable<pair> { int index,size; pair(int index,int size) { this.index=index; this.size=size; // size=i; } public int compareTo(pair x) { return this.size-x.size; } } //Code For FastReader //Code For FastReader //Code For FastReader //Code For FastReader 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
["5 4\n\n0\n\n5\n\n9\n\n7"]
1 second
["? 0000\n\n? 1110\n\n? 1111\n\n? 1101\n\n! 7"]
NoteHere is the graph of the example, satisfying $$$l_i=i$$$.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy", "interactive", "sortings" ]
003b7257b35416ec93f189cb29e458e6
The first and only line of input contains two integers $$$n,m$$$ ($$$2 \leq n \leq 200$$$, $$$1\le m \le 500$$$) — the number of stations and tracks.
1,700
null
standard output
PASSED
934ef4b6b96a1ef1c8d4071507aa36f5
train_108.jsonl
1654266900
As for the technology in the outside world, it is really too advanced for Gensokyo to even look up to.—Yasaka Kanako, Symposium of Post-mysticismThis is an interactive problem.Under the direct supervision of Kanako and the Moriya Shrine, the railway system of Gensokyo is finally finished. GSKR (Gensokyo Railways) consists of $$$n$$$ stations with $$$m$$$ bidirectional tracks connecting them. The $$$i$$$-th track has length $$$l_i$$$ ($$$1\le l_i\le 10^6$$$). Due to budget limits, the railway system may not be connected, though there may be more than one track between two stations.The value of a railway system is defined as the total length of its all tracks. The maximum (or minimum) capacity of a railway system is defined as the maximum (or minimum) value among all of the currently functional system's full spanning forest.In brief, full spanning forest of a graph is a spanning forest with the same connectivity as the given graph.Kanako has a simulator only able to process no more than $$$2m$$$ queries. The input of the simulator is a string $$$s$$$ of length $$$m$$$, consisting of characters 0 and/or 1. The simulator will assume the $$$i$$$-th track functional if $$$s_i=$$$ 1. The device will then tell Kanako the maximum capacity of the system in the simulated state.Kanako wants to know the the minimum capacity of the system with all tracks functional with the help of the simulator.The structure of the railway system is fixed in advance. In other words, the interactor is not adaptive.
256 megabytes
import java.lang.*; import java.util.*; import java.io.*; import java.math.*; public class Main { public static void deal(int n,int m,MyScanner sc) { char[] ch = new char[m]; Arrays.fill(ch,'0'); int[] a = new int[m]; Integer[] p = new Integer[m]; for(int i=0;i<m;i++) { p[i] = i; if(i>0) ch[i-1] = '0'; ch[i] = '1'; out.println(String.format("? %s",new String(ch))); out.flush(); a[i] = sc.nextInt(); } Arrays.sort(p,(o1,o2)->Integer.compare(a[o1],a[o2])); Arrays.fill(ch,'0'); int d = 0; for(int i=0;i<m;i++) { int t = p[i]; ch[t] = '1'; out.println(String.format("? %s",new String(ch))); out.flush(); int v = sc.nextInt(); if(v-d==a[t]) { d = v; } else { ch[t] = '0'; } } out.println(String.format("! %d",d)); } public static void main(String[] args) { MyScanner sc = new MyScanner(); out = new PrintWriter(new BufferedOutputStream(System.out)); int n = sc.nextInt(); int m = sc.nextInt(); deal(n,m,sc); out.close(); } //-----------PrintWriter for faster output--------------------------------- public static PrintWriter out; //-----------MyScanner class for faster input---------- public static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine(){ String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["5 4\n\n0\n\n5\n\n9\n\n7"]
1 second
["? 0000\n\n? 1110\n\n? 1111\n\n? 1101\n\n! 7"]
NoteHere is the graph of the example, satisfying $$$l_i=i$$$.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy", "interactive", "sortings" ]
003b7257b35416ec93f189cb29e458e6
The first and only line of input contains two integers $$$n,m$$$ ($$$2 \leq n \leq 200$$$, $$$1\le m \le 500$$$) — the number of stations and tracks.
1,700
null
standard output
PASSED
34dcffcdba1d184403f645a32c88ad8e
train_108.jsonl
1654266900
As for the technology in the outside world, it is really too advanced for Gensokyo to even look up to.—Yasaka Kanako, Symposium of Post-mysticismThis is an interactive problem.Under the direct supervision of Kanako and the Moriya Shrine, the railway system of Gensokyo is finally finished. GSKR (Gensokyo Railways) consists of $$$n$$$ stations with $$$m$$$ bidirectional tracks connecting them. The $$$i$$$-th track has length $$$l_i$$$ ($$$1\le l_i\le 10^6$$$). Due to budget limits, the railway system may not be connected, though there may be more than one track between two stations.The value of a railway system is defined as the total length of its all tracks. The maximum (or minimum) capacity of a railway system is defined as the maximum (or minimum) value among all of the currently functional system's full spanning forest.In brief, full spanning forest of a graph is a spanning forest with the same connectivity as the given graph.Kanako has a simulator only able to process no more than $$$2m$$$ queries. The input of the simulator is a string $$$s$$$ of length $$$m$$$, consisting of characters 0 and/or 1. The simulator will assume the $$$i$$$-th track functional if $$$s_i=$$$ 1. The device will then tell Kanako the maximum capacity of the system in the simulated state.Kanako wants to know the the minimum capacity of the system with all tracks functional with the help of the simulator.The structure of the railway system is fixed in advance. In other words, the interactor is not adaptive.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Arrays; import java.io.BufferedWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.Comparator; 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); BRailwaySystem solver = new BRailwaySystem(); solver.solve(1, in, out); out.close(); } static class BRailwaySystem { int ask(InputReader in, OutputWriter out, String s) { out.println("? " + s); out.flush(); return in.nextInt(); } public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.nextInt(), m = in.nextInt(); char[] c = new char[m]; int[] w = new int[m]; Integer[] p = new Integer[m]; for (int i = 0; i < m; i++) { p[i] = i; Arrays.fill(c, '0'); c[i] = '1'; w[i] = ask(in, out, new String(c)); } Arrays.sort(p, Comparator.comparingInt(i -> -w[i])); Arrays.fill(c, '1'); int answer = 0; int sum = ask(in, out, new String(c)); int l = 0; for (int i : p) { l++; if (l == m) { answer += w[i]; break; } c[i] = '0'; int u = ask(in, out, new String(c)); if (u == sum - w[i]) { answer += w[i]; } sum = u; } out.println("! " + answer); out.flush(); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } 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 flush() { writer.flush(); } public void println(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) { writer.print(' '); } writer.print(objects[i]); } writer.print('\n'); } public void close() { writer.close(); } } }
Java
["5 4\n\n0\n\n5\n\n9\n\n7"]
1 second
["? 0000\n\n? 1110\n\n? 1111\n\n? 1101\n\n! 7"]
NoteHere is the graph of the example, satisfying $$$l_i=i$$$.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy", "interactive", "sortings" ]
003b7257b35416ec93f189cb29e458e6
The first and only line of input contains two integers $$$n,m$$$ ($$$2 \leq n \leq 200$$$, $$$1\le m \le 500$$$) — the number of stations and tracks.
1,700
null
standard output
PASSED
161f61b571257a2526dcfff98f51cce4
train_108.jsonl
1654266900
As for the technology in the outside world, it is really too advanced for Gensokyo to even look up to.—Yasaka Kanako, Symposium of Post-mysticismThis is an interactive problem.Under the direct supervision of Kanako and the Moriya Shrine, the railway system of Gensokyo is finally finished. GSKR (Gensokyo Railways) consists of $$$n$$$ stations with $$$m$$$ bidirectional tracks connecting them. The $$$i$$$-th track has length $$$l_i$$$ ($$$1\le l_i\le 10^6$$$). Due to budget limits, the railway system may not be connected, though there may be more than one track between two stations.The value of a railway system is defined as the total length of its all tracks. The maximum (or minimum) capacity of a railway system is defined as the maximum (or minimum) value among all of the currently functional system's full spanning forest.In brief, full spanning forest of a graph is a spanning forest with the same connectivity as the given graph.Kanako has a simulator only able to process no more than $$$2m$$$ queries. The input of the simulator is a string $$$s$$$ of length $$$m$$$, consisting of characters 0 and/or 1. The simulator will assume the $$$i$$$-th track functional if $$$s_i=$$$ 1. The device will then tell Kanako the maximum capacity of the system in the simulated state.Kanako wants to know the the minimum capacity of the system with all tracks functional with the help of the simulator.The structure of the railway system is fixed in advance. In other words, the interactor is not adaptive.
256 megabytes
import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintStream; import java.util.Arrays; import java.util.Comparator; import java.util.Locale; import java.util.StringTokenizer; public class Solution implements Runnable { private PrintStream out; private BufferedReader in; private StringTokenizer st; public void solve() throws IOException { long time0 = System.currentTimeMillis(); /*int n = */nextInt(); int m = nextInt(); int[] l = new int[m]; boolean[] query = new boolean[m]; for (int i = 0; i < m; i++) { query[i] = true; l[i] = query(query); query[i] = false; } Integer[] id = new Integer[m]; for (int i = 0; i < m; i++) { id[i] = i; } Arrays.sort(id, new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { return Integer.compare(l[o1], l[o2]); } }); boolean[] good = new boolean[m]; query[id[0]] = true; int prevReply = l[id[0]]; good[id[0]] = true; for (int i = 1; i < m; i++) { query[id[i]] = true; int reply = query(query); if (reply == prevReply + l[id[i]]) { good[id[i]] = true; } prevReply = reply; } int answer = query(good); out.println("! " + answer); System.err.println("time: " + (System.currentTimeMillis() - time0)); } private int query(boolean[] query) throws IOException { out.print("? "); for (int i = 0; i < query.length; i++) { if (query[i]) { out.print('1'); } else { out.print('0'); } } out.println(); out.flush(); int result = nextInt(); return result; } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public String next() throws IOException { while (!st.hasMoreTokens()) { String line = in.readLine(); if (line == null) { return null; } st = new StringTokenizer(line); } return st.nextToken(); } @Override public void run() { try { solve(); out.close(); } catch (Throwable e) { throw new RuntimeException(e); } } public Solution(String name) throws IOException { Locale.setDefault(Locale.US); if (name == null) { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintStream(new BufferedOutputStream(System.out)); } else { in = new BufferedReader(new InputStreamReader(new FileInputStream(name + ".in"))); out = new PrintStream(new BufferedOutputStream(new FileOutputStream(name + ".out"))); } st = new StringTokenizer(""); } public static void main(String[] args) throws IOException { new Thread(new Solution(null)).start(); } }
Java
["5 4\n\n0\n\n5\n\n9\n\n7"]
1 second
["? 0000\n\n? 1110\n\n? 1111\n\n? 1101\n\n! 7"]
NoteHere is the graph of the example, satisfying $$$l_i=i$$$.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy", "interactive", "sortings" ]
003b7257b35416ec93f189cb29e458e6
The first and only line of input contains two integers $$$n,m$$$ ($$$2 \leq n \leq 200$$$, $$$1\le m \le 500$$$) — the number of stations and tracks.
1,700
null
standard output
PASSED
604932e2c4d7b364bfc1461d98020aaf
train_108.jsonl
1654266900
As for the technology in the outside world, it is really too advanced for Gensokyo to even look up to.—Yasaka Kanako, Symposium of Post-mysticismThis is an interactive problem.Under the direct supervision of Kanako and the Moriya Shrine, the railway system of Gensokyo is finally finished. GSKR (Gensokyo Railways) consists of $$$n$$$ stations with $$$m$$$ bidirectional tracks connecting them. The $$$i$$$-th track has length $$$l_i$$$ ($$$1\le l_i\le 10^6$$$). Due to budget limits, the railway system may not be connected, though there may be more than one track between two stations.The value of a railway system is defined as the total length of its all tracks. The maximum (or minimum) capacity of a railway system is defined as the maximum (or minimum) value among all of the currently functional system's full spanning forest.In brief, full spanning forest of a graph is a spanning forest with the same connectivity as the given graph.Kanako has a simulator only able to process no more than $$$2m$$$ queries. The input of the simulator is a string $$$s$$$ of length $$$m$$$, consisting of characters 0 and/or 1. The simulator will assume the $$$i$$$-th track functional if $$$s_i=$$$ 1. The device will then tell Kanako the maximum capacity of the system in the simulated state.Kanako wants to know the the minimum capacity of the system with all tracks functional with the help of the simulator.The structure of the railway system is fixed in advance. In other words, the interactor is not adaptive.
256 megabytes
import java.lang.*; import java.util.*; import java.io.*; import java.math.*; public class Main { public static void deal(int n,int m,MyScanner sc) { char[] ch = new char[m]; Arrays.fill(ch,'0'); int[] a = new int[m]; Integer[] p = new Integer[m]; for(int i=0;i<m;i++) { p[i] = i; if(i>0) ch[i-1] = '0'; ch[i] = '1'; out.println(String.format("? %s",new String(ch))); out.flush(); a[i] = sc.nextInt(); } Arrays.sort(p,(o1,o2)->Integer.compare(a[o1],a[o2])); Arrays.fill(ch,'0'); int d = 0; for(int i=0;i<m;i++) { int t = p[i]; ch[t] = '1'; out.println(String.format("? %s",new String(ch))); out.flush(); int v = sc.nextInt(); if(v-d==a[t]) { d = v; } else { ch[t] = '0'; } } out.println(String.format("! %d",d)); } public static void main(String[] args) { MyScanner sc = new MyScanner(); out = new PrintWriter(new BufferedOutputStream(System.out)); int n = sc.nextInt(); int m = sc.nextInt(); deal(n,m,sc); out.close(); } //-----------PrintWriter for faster output--------------------------------- public static PrintWriter out; //-----------MyScanner class for faster input---------- public static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine(){ String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["5 4\n\n0\n\n5\n\n9\n\n7"]
1 second
["? 0000\n\n? 1110\n\n? 1111\n\n? 1101\n\n! 7"]
NoteHere is the graph of the example, satisfying $$$l_i=i$$$.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy", "interactive", "sortings" ]
003b7257b35416ec93f189cb29e458e6
The first and only line of input contains two integers $$$n,m$$$ ($$$2 \leq n \leq 200$$$, $$$1\le m \le 500$$$) — the number of stations and tracks.
1,700
null
standard output
PASSED
2adea0a8cdf361367f5e48db79639122
train_108.jsonl
1654266900
As for the technology in the outside world, it is really too advanced for Gensokyo to even look up to.—Yasaka Kanako, Symposium of Post-mysticismThis is an interactive problem.Under the direct supervision of Kanako and the Moriya Shrine, the railway system of Gensokyo is finally finished. GSKR (Gensokyo Railways) consists of $$$n$$$ stations with $$$m$$$ bidirectional tracks connecting them. The $$$i$$$-th track has length $$$l_i$$$ ($$$1\le l_i\le 10^6$$$). Due to budget limits, the railway system may not be connected, though there may be more than one track between two stations.The value of a railway system is defined as the total length of its all tracks. The maximum (or minimum) capacity of a railway system is defined as the maximum (or minimum) value among all of the currently functional system's full spanning forest.In brief, full spanning forest of a graph is a spanning forest with the same connectivity as the given graph.Kanako has a simulator only able to process no more than $$$2m$$$ queries. The input of the simulator is a string $$$s$$$ of length $$$m$$$, consisting of characters 0 and/or 1. The simulator will assume the $$$i$$$-th track functional if $$$s_i=$$$ 1. The device will then tell Kanako the maximum capacity of the system in the simulated state.Kanako wants to know the the minimum capacity of the system with all tracks functional with the help of the simulator.The structure of the railway system is fixed in advance. In other words, the interactor is not adaptive.
256 megabytes
import java.io.BufferedReader; import java.io.Closeable; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigInteger; import java.time.Clock; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.Map; import java.util.Objects; import java.util.Random; import java.util.Set; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.TreeSet; import java.util.function.Supplier; public class Solution { private void solve() throws IOException { int n = nextInt(); int m = nextInt(); int[] a = new int[m]; boolean[] b = new boolean[m]; for (int i = 0; i < m; i++) { b[i] = true; a[i] = ask(b); b[i] = false; } Integer[] idx = new Integer[m]; for (int i = 0; i < m; i++) { idx[i] = i; } Arrays.sort(idx, new Comparator<Integer>() { @Override public int compare(Integer i, Integer j) { return Integer.compare(a[i], a[j]); } }); int lst = 0; for (int i = 0; i < m; i++) { int id = idx[i]; b[id] = true; int t = ask(b); if (lst + a[id] == t) { lst = t; } else { b[id] = false; } } out.println("! " + lst); } private int ask(boolean[] b) throws IOException { out.print("? "); for (boolean bb : b) { out.print(bb ? '1' : '0'); } out.println(); out.flush(); return nextInt(); } private static final boolean runNTestsInProd = false; private static final boolean printCaseNumber = false; private static final boolean assertInProd = false; private static final boolean logToFile = false; private static final boolean readFromConsoleInDebug = true; private static final boolean writeToConsoleInDebug = true; private static final boolean testTimer = false; private static Boolean isDebug = null; private BufferedReader in; private StringTokenizer line; private PrintWriter out; public static void main(String[] args) throws Exception { isDebug = Arrays.asList(args).contains("DEBUG_MODE"); if (isDebug) { log = logToFile ? new PrintWriter("logs/j_solution_" + System.currentTimeMillis() + ".log") : new PrintWriter(System.out); clock = Clock.systemDefaultZone(); } new Solution().run(); } private void run() throws Exception { in = new BufferedReader(new InputStreamReader(!isDebug || readFromConsoleInDebug ? System.in : new FileInputStream("input.txt"))); out = !isDebug || writeToConsoleInDebug ? new PrintWriter(System.out) : new PrintWriter("output.txt"); try (Timer totalTimer = new Timer("total")) { int t = runNTestsInProd || isDebug ? nextInt() : 1; for (int i = 0; i < t; i++) { if (printCaseNumber) { out.print("Case #" + (i + 1) + ": "); } if (testTimer) { try (Timer testTimer = new Timer("test #" + (i + 1))) { solve(); } } else { solve(); } if (isDebug) { out.flush(); } } } in.close(); out.flush(); out.close(); } private void println(Object... objects) { boolean isFirst = true; for (Object o : objects) { if (!isFirst) { out.print(" "); } else { isFirst = false; } out.print(o.toString()); } out.println(); } private int[] nextIntArray(int n) throws IOException { return nextIntArray(n, 0); } private int[] nextIntArray(int n, int delta) throws IOException { int[] res = new int[n]; for (int i = 0; i < n; i++) { res[i] = nextInt() + delta; } return res; } private long[] nextLongArray(int n) throws IOException { long[] res = new long[n]; for (int i = 0; i < n; i++) { res[i] = nextLong(); } return res; } private int nextInt() throws IOException { return Integer.parseInt(nextToken()); } private long nextLong() throws IOException { return Long.parseLong(nextToken()); } private double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } private char[] nextTokenChars() throws IOException { return nextToken().toCharArray(); } private String nextToken() throws IOException { while (line == null || !line.hasMoreTokens()) { line = new StringTokenizer(in.readLine()); } return line.nextToken(); } private static void assertPredicate(boolean p) { if ((isDebug || assertInProd) && !p) { throw new RuntimeException(); } } private static void assertPredicate(boolean p, String message) { if ((isDebug || assertInProd) && !p) { throw new RuntimeException(message); } } private static <T> void assertNotEqual(T unexpected, T actual) { if ((isDebug || assertInProd) && Objects.equals(actual, unexpected)) { throw new RuntimeException("assertNotEqual: " + unexpected + " == " + actual); } } private static <T> void assertEqual(T expected, T actual) { if ((isDebug || assertInProd) && !Objects.equals(actual, expected)) { throw new RuntimeException("assertEqual: " + expected + " != " + actual); } } private static PrintWriter log = null; private static Clock clock = null; private static void log(Object... objects) { log(true, objects); } private static void logNoDelimiter(Object... objects) { log(false, objects); } private static void log(boolean printDelimiter, Object[] objects) { if (isDebug) { StringBuilder sb = new StringBuilder(); sb.append(LocalDateTime.now(clock)).append(" - "); boolean isFirst = true; for (Object o : objects) { if (!isFirst && printDelimiter) { sb.append(" "); } else { isFirst = false; } sb.append(o.toString()); } log.println(sb); log.flush(); } } private static class Timer implements Closeable { private final String label; private final long startTime = isDebug ? System.nanoTime() : 0; public Timer(String label) { this.label = label; } @Override public void close() throws IOException { if (isDebug) { long executionTime = System.nanoTime() - startTime; String fraction = Long.toString(executionTime / 1000 % 1_000_000); logNoDelimiter("Timer[", label, "]: ", executionTime / 1_000_000_000, '.', "00000".substring(0, 6 - fraction.length()), fraction, 's'); } } } private static <T> T timer(String label, Supplier<T> f) throws Exception { if (isDebug) { try (Timer timer = new Timer(label)) { return f.get(); } } else { return f.get(); } } }
Java
["5 4\n\n0\n\n5\n\n9\n\n7"]
1 second
["? 0000\n\n? 1110\n\n? 1111\n\n? 1101\n\n! 7"]
NoteHere is the graph of the example, satisfying $$$l_i=i$$$.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy", "interactive", "sortings" ]
003b7257b35416ec93f189cb29e458e6
The first and only line of input contains two integers $$$n,m$$$ ($$$2 \leq n \leq 200$$$, $$$1\le m \le 500$$$) — the number of stations and tracks.
1,700
null
standard output
PASSED
85b3e92035eabea176ae591f6b2fd5ab
train_108.jsonl
1654266900
As for the technology in the outside world, it is really too advanced for Gensokyo to even look up to.—Yasaka Kanako, Symposium of Post-mysticismThis is an interactive problem.Under the direct supervision of Kanako and the Moriya Shrine, the railway system of Gensokyo is finally finished. GSKR (Gensokyo Railways) consists of $$$n$$$ stations with $$$m$$$ bidirectional tracks connecting them. The $$$i$$$-th track has length $$$l_i$$$ ($$$1\le l_i\le 10^6$$$). Due to budget limits, the railway system may not be connected, though there may be more than one track between two stations.The value of a railway system is defined as the total length of its all tracks. The maximum (or minimum) capacity of a railway system is defined as the maximum (or minimum) value among all of the currently functional system's full spanning forest.In brief, full spanning forest of a graph is a spanning forest with the same connectivity as the given graph.Kanako has a simulator only able to process no more than $$$2m$$$ queries. The input of the simulator is a string $$$s$$$ of length $$$m$$$, consisting of characters 0 and/or 1. The simulator will assume the $$$i$$$-th track functional if $$$s_i=$$$ 1. The device will then tell Kanako the maximum capacity of the system in the simulated state.Kanako wants to know the the minimum capacity of the system with all tracks functional with the help of the simulator.The structure of the railway system is fixed in advance. In other words, the interactor is not adaptive.
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; public class B { FastScanner in; PrintWriter out; boolean systemIO = true; int mod = 1000000007; public int mult(int x, int y) { return (int) (x * 1L * y % mod); } public int sum(int x, int y) { if (x + y >= mod) { return x + y - mod; } return x + y; } public int diff(int x, int y) { if (x >= y) { return x - y; } return x - y + mod; } // public int div(int x, int y) { // return mult(x, modInv(y)); // } public class Pair implements Comparable<Pair> { int x; int y; public Pair(int x, int y) { this.x = x; this.y = y; } @Override public int compareTo(Pair o) { if (x != o.x) { return x - o.x; } return y - o.y; } } public void solve() { int n = in.nextInt(); int m = in.nextInt(); int[] w = new int[m]; StringBuilder sb = new StringBuilder(m); for (int i = 0; i < m; i++) { sb.append("0"); } for (int i = 0; i < m; i++) { sb.setCharAt(i, '1'); System.out.println("? " + sb); sb.setCharAt(i, '0'); w[i] = in.nextInt(); } Pair[] p = new Pair[m]; for (int i = 0; i < p.length; i++) { p[i] = new Pair(w[i], i); } Random random = new Random(566); for (int i = 1; i < p.length; i++) { int id = random.nextInt(i); Pair p1 = p[id]; p[id] = p[i]; p[i] = p1; } Arrays.sort(p); long cur = 0; for (int i = 0; i < p.length; i++) { sb.setCharAt(p[i].y, '1'); System.out.println("? " + sb); if (in.nextInt() == cur + p[i].x) { cur += p[i].x; } else { sb.setCharAt(p[i].y, '0'); } } System.out.println("! " + cur); } public void print(int[] a) { for (int i = 0; i < a.length; i++) { if (a[i] < 2) { out.print(a[i]); } else if (a[i] == 2) { out.print("*"); } else { out.print("^"); } } out.println(); } public void add(HashMap<Integer, Integer> map, int x) { if (map.containsKey(x)) { map.put(x, map.get(x) + 1); } else { map.put(x, 1); } } public void run() { try { if (systemIO) { in = new FastScanner(System.in); out = new PrintWriter(System.out); } else { in = new FastScanner(new File("input.txt")); out = new PrintWriter(new File("output.txt")); } solve(); out.close(); } catch (IOException e) { e.printStackTrace(); } } class FastScanner { BufferedReader br; StringTokenizer st; FastScanner(File f) { try { br = new BufferedReader(new FileReader(f)); } catch (FileNotFoundException e) { e.printStackTrace(); } } FastScanner(InputStream f) { br = new BufferedReader(new InputStreamReader(f)); } String nextLine() { try { return br.readLine(); } catch (IOException e) { return null; } } 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()); } } // AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA public static void main(String[] arg) { new B().run(); } }
Java
["5 4\n\n0\n\n5\n\n9\n\n7"]
1 second
["? 0000\n\n? 1110\n\n? 1111\n\n? 1101\n\n! 7"]
NoteHere is the graph of the example, satisfying $$$l_i=i$$$.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy", "interactive", "sortings" ]
003b7257b35416ec93f189cb29e458e6
The first and only line of input contains two integers $$$n,m$$$ ($$$2 \leq n \leq 200$$$, $$$1\le m \le 500$$$) — the number of stations and tracks.
1,700
null
standard output
PASSED
3a4a59b035722fe5c6a7e7e4a7882372
train_108.jsonl
1654266900
As for the technology in the outside world, it is really too advanced for Gensokyo to even look up to.—Yasaka Kanako, Symposium of Post-mysticismThis is an interactive problem.Under the direct supervision of Kanako and the Moriya Shrine, the railway system of Gensokyo is finally finished. GSKR (Gensokyo Railways) consists of $$$n$$$ stations with $$$m$$$ bidirectional tracks connecting them. The $$$i$$$-th track has length $$$l_i$$$ ($$$1\le l_i\le 10^6$$$). Due to budget limits, the railway system may not be connected, though there may be more than one track between two stations.The value of a railway system is defined as the total length of its all tracks. The maximum (or minimum) capacity of a railway system is defined as the maximum (or minimum) value among all of the currently functional system's full spanning forest.In brief, full spanning forest of a graph is a spanning forest with the same connectivity as the given graph.Kanako has a simulator only able to process no more than $$$2m$$$ queries. The input of the simulator is a string $$$s$$$ of length $$$m$$$, consisting of characters 0 and/or 1. The simulator will assume the $$$i$$$-th track functional if $$$s_i=$$$ 1. The device will then tell Kanako the maximum capacity of the system in the simulated state.Kanako wants to know the the minimum capacity of the system with all tracks functional with the help of the simulator.The structure of the railway system is fixed in advance. In other words, the interactor is not adaptive.
256 megabytes
import java.util.*; import java.io.*; import java.text.*; public class Main{ //SOLUTION BEGIN void pre() throws Exception{} void solve(int TC) throws Exception { int N = ni(), M = ni(); BitSet b = new BitSet(M); PriorityQueue<int[]> pq = new PriorityQueue<>((int[] i1, int[] i2) -> Integer.compare(i1[1], i2[1])); for(int i = 0; i< M; i++){ b.set(i); pq.add(new int[]{i, query(b, M)}); b.flip(i); } long cur = 0; while (!pq.isEmpty()){ int[] p = pq.poll(); b.set(p[0]); int sum = query(b, M); if(sum != cur+p[1])b.flip(p[0]); else cur += p[1]; } pni("! "+cur); } int query(BitSet b, int M) throws Exception{ StringBuilder st = new StringBuilder(); for(int i = 0; i< M; i++)st.append(b.get(i)?"1":"0"); pni("? "+st.toString()); return ni(); } //SOLUTION END void hold(boolean b)throws Exception{if(!b)throw new Exception("Hold right there, Sparky!");} static void dbg(Object... o){System.err.println(Arrays.deepToString(o));} void exit(boolean b){if(!b)System.exit(0);} final long IINF = Long.MAX_VALUE/2; final int INF = Integer.MAX_VALUE/2; DecimalFormat df = new DecimalFormat("0.000000000"); double PI = 3.141592653589793238462643383279502884197169399, eps = 1e-9; static boolean multipleTC = false, memory = false, fileIO = false; FastReader in;PrintWriter out; void run() throws Exception{ long ct = System.currentTimeMillis(); if (fileIO) { in = new FastReader(""); out = new PrintWriter(""); } else { in = new FastReader(); out = new PrintWriter(System.out); } //Solution Credits: Taranpreet Singh int T = multipleTC? ni():1; pre(); for (int t = 1; t <= T; t++) solve(t); out.flush(); out.close(); System.err.println("Runtime: " + (System.currentTimeMillis() - ct)); } public static void main(String[] args) throws Exception{ if(memory)new Thread(null, new Runnable() {public void run(){try{new Main().run();}catch(Exception e){e.printStackTrace();System.exit(1);}}}, "1", 1 << 26).start(); else new Main().run(); } int[][] make(int n, int e, int[] from, int[] to, boolean f){ int[][] g = new int[n][];int[]cnt = new int[n]; for(int i = 0; i< e; i++){ cnt[from[i]]++; if(f)cnt[to[i]]++; } for(int i = 0; i< n; i++)g[i] = new int[cnt[i]]; for(int i = 0; i< e; i++){ g[from[i]][--cnt[from[i]]] = to[i]; if(f)g[to[i]][--cnt[to[i]]] = from[i]; } return g; } int[][][] makeS(int n, int e, int[] from, int[] to, boolean f){ int[][][] g = new int[n][][];int[]cnt = new int[n]; for(int i = 0; i< e; i++){ cnt[from[i]]++; if(f)cnt[to[i]]++; } for(int i = 0; i< n; i++)g[i] = new int[cnt[i]][]; for(int i = 0; i< e; i++){ g[from[i]][--cnt[from[i]]] = new int[]{to[i], i, 0}; if(f)g[to[i]][--cnt[to[i]]] = new int[]{from[i], i, 1}; } return g; } int[][] make(int n, int[] par, boolean f){ int[][] g = new int[n][]; int[] cnt = new int[n]; for(int x:par)cnt[x]++; if(f)for(int i = 1; i< n; i++)cnt[i]++; for(int i = 0; i< n; i++)g[i] = new int[cnt[i]]; for(int i = 1; i< n-1; i++){ g[par[i]][--cnt[par[i]]] = i; if(f)g[i][--cnt[i]] = par[i]; } return g; } int find(int[] set, int u){return set[u] = (set[u] == u?u:find(set, set[u]));} int digit(long s){int brute = 0;while(s>0){s/=10;brute++;}return brute;} long gcd(long a, long b){return (b==0)?a:gcd(b,a%b);} int gcd(int a, int b){return (b==0)?a:gcd(b,a%b);} int bit(long n){return (n==0)?0:(1+bit(n&(n-1)));} void p(Object... o){for(Object oo:o)out.print(oo+" ");} void pn(Object... o){ if(o.length == 0)out.println(""); for(int i = 0; i< o.length; i++){ out.print(o[i]); out.print((i+1 == o.length?"\n":" ")); } } void pni(Object... o){for(Object oo:o)out.print(oo+" ");out.println();out.flush();} String n()throws Exception{return in.next();} String nln()throws Exception{return in.nextLine();} 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());} 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 4\n\n0\n\n5\n\n9\n\n7"]
1 second
["? 0000\n\n? 1110\n\n? 1111\n\n? 1101\n\n! 7"]
NoteHere is the graph of the example, satisfying $$$l_i=i$$$.
Java 11
standard input
[ "constructive algorithms", "graphs", "greedy", "interactive", "sortings" ]
003b7257b35416ec93f189cb29e458e6
The first and only line of input contains two integers $$$n,m$$$ ($$$2 \leq n \leq 200$$$, $$$1\le m \le 500$$$) — the number of stations and tracks.
1,700
null
standard output
PASSED
fcfa10c8b8a70d40b6d5bccac30a6df4
train_108.jsonl
1654266900
As for the technology in the outside world, it is really too advanced for Gensokyo to even look up to.—Yasaka Kanako, Symposium of Post-mysticismThis is an interactive problem.Under the direct supervision of Kanako and the Moriya Shrine, the railway system of Gensokyo is finally finished. GSKR (Gensokyo Railways) consists of $$$n$$$ stations with $$$m$$$ bidirectional tracks connecting them. The $$$i$$$-th track has length $$$l_i$$$ ($$$1\le l_i\le 10^6$$$). Due to budget limits, the railway system may not be connected, though there may be more than one track between two stations.The value of a railway system is defined as the total length of its all tracks. The maximum (or minimum) capacity of a railway system is defined as the maximum (or minimum) value among all of the currently functional system's full spanning forest.In brief, full spanning forest of a graph is a spanning forest with the same connectivity as the given graph.Kanako has a simulator only able to process no more than $$$2m$$$ queries. The input of the simulator is a string $$$s$$$ of length $$$m$$$, consisting of characters 0 and/or 1. The simulator will assume the $$$i$$$-th track functional if $$$s_i=$$$ 1. The device will then tell Kanako the maximum capacity of the system in the simulated state.Kanako wants to know the the minimum capacity of the system with all tracks functional with the help of the simulator.The structure of the railway system is fixed in advance. In other words, the interactor is not adaptive.
256 megabytes
import java.io.*; import java.lang.Math; import java.util.*; import java.util.regex.Pattern; import javax.swing.text.DefaultStyledDocument.ElementSpec; public final class Solution { private static class FastScanner { private final int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; private FastScanner(boolean usingFile) throws IOException { if (usingFile) din = new DataInputStream(new FileInputStream("path")); else din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } private short nextShort() throws IOException { short ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do ret = (short) (ret * 10 + c - '0'); while ( (c = read()) >= '0' && c <= '9' ); if (neg) return (short) -ret; return ret; } private 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; } private char nextChar() throws IOException { byte c = read(); while (c <= ' ') c = read(); return (char) c; } private String nextString() throws IOException { StringBuilder ret = new StringBuilder(); byte c = read(); while (c <= ' ') c = read(); do { ret.append((char) c); } while ((c = read()) > ' '); return ret.toString(); } 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++]; } } static StringTokenizer st; static BufferedReader br = new BufferedReader( new InputStreamReader(System.in) ); static BufferedWriter bw = new BufferedWriter( new OutputStreamWriter(System.out) ); static int mod = 1000000007; static String is(int no) { return Integer.toString(no); } static String ls(long no) { return Long.toString(no); } static int pi(String s) { return Integer.parseInt(s); } static long pl(String s) { return Long.parseLong(s); } /*write your constructor and global variables here*/ static class Rec<f, s, t> { f a; s b; t c; Rec(f a, s b, t c) { this.a = a; this.b = b; this.c = c; } } static class Quad<f, s, t, fo> { f a; s b; t c; fo d; Quad(f a, s b, t c, fo d) { this.a = a; this.b = b; this.c = c; this.d = d; } } static class Pair<f, s> { f a; s b; Pair(f a, s b) { this.a = a; this.b = b; } } static int findPow(int a, int b, int mod) { int res = 1; while (b > 0) { if ((b & 1) != 0) { res = modMul.mod(res, a, mod); } a = modMul.mod(a, a, mod); b = b / 2; } return res; } interface modOperations { int mod(int a, int b, int mod); } static modOperations modAdd = (int a, int b, int mod) -> { return (a % mod + b % mod) % mod; }; static modOperations modSub = (int a, int b, int mod) -> { return ((a % mod - b % mod + mod) % mod); }; static modOperations modMul = (int a, int b, int mod) -> { return (int) ((1l * a % mod * b % mod)) % mod; }; static modOperations modDiv = (int a, int b, int mod) -> { return modMul.mod(a, findPow(b, mod - 2, mod), mod); }; static long gcd(long a, long b) { long div = b; long rem = a % b; while (rem != 0) { long temp = rem; rem = div % rem; div = temp; } return div; } static HashSet<Integer> primeList(int MAXI) { int[] prime = new int[MAXI + 1]; HashSet<Integer> list = new HashSet<>(); for (int i = 2; i <= (int) Math.sqrt(MAXI) + 1; i++) { if (prime[i] == 0) { list.add(i); for (int j = i * i; j <= MAXI; j += i) { prime[j] = 1; } } } for (int i = (int) Math.sqrt(MAXI) + 1; i <= MAXI; i++) { if (prime[i] == 0) { list.add(i); } } return list; } static int[] factorialList(int MAXI, int mod) { int[] factorial = new int[MAXI + 1]; factorial[0] = 1; for (int i = 1; i < MAXI + 1; i++) { factorial[i] = modMul.mod(factorial[i - 1], i, mod); } return factorial; } static void put(HashMap<Integer, Integer> cnt, int key) { if (cnt.containsKey(key)) { cnt.replace(key, cnt.get(key) + 1); } else { cnt.put(key, 1); } } static ArrayList<Integer> getKeys(HashMap<Integer, Integer> maps) { ArrayList<Integer> vals = new ArrayList<>(); for (Map.Entry<Integer, Integer> map : maps.entrySet()) { vals.add(map.getKey()); } return vals; } static ArrayList<Integer> getValues(HashMap<Integer, Integer> maps) { ArrayList<Integer> vals = new ArrayList<>(); for (Map.Entry<Integer, Integer> map : maps.entrySet()) { vals.add(map.getValue()); } return vals; } static int getMax(ArrayList<Integer> arr) { int max = arr.get(0); for (int i = 1; i < arr.size(); i++) { if (arr.get(i) > max) { max = arr.get(i); } } return max; } static int getMin(ArrayList<Integer> arr) { int max = arr.get(0); for (int i = 1; i < arr.size(); i++) { if (arr.get(i) < max) { max = arr.get(i); } } return max; } static int[][] fill_arr(int m, int n, int fill) { int arr[][] = new int[m][n]; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { arr[i][j] = fill; } } return arr; } static class sortCond implements Comparator<Pair<Integer, Long>> { @Override public int compare(Pair<Integer, Long> p1, Pair<Integer, Long> p2) { if (p1.b >= p2.b) { return 1; } else { return -1; } } } static class sortCondRec implements Comparator<Rec<Integer, Integer, Integer>> { @Override public int compare( Rec<Integer, Integer, Integer> p1, Rec<Integer, Integer, Integer> p2 ) { return p1.b - p2.b; } } /*write your methods and classes here*/ static int ret_ans(String s) { int n = s.length(); int ans = n; for (int i = 1; i <= n - 1; i++) { if ((s.substring(i, n) + s.substring(0, i)).equals(s)) { return i; } } return ans; } public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); st = new StringTokenizer(br.readLine()); int n = pi(st.nextToken()); int m = pi(st.nextToken()); int arr[] = new int[m]; for (int i = 0; i < m; i++) { bw.write("? "); for (int j = 0; j < m; j++) { if (j == i) { bw.write("1"); } else { bw.write("0"); } } bw.write("\n"); bw.flush(); arr[i] = pi(br.readLine()); } String ans[] = new String[m]; for (int i = 0; i < m; i++) { ans[i] = "0"; } int tot = 0; for (int i = 0; i < m; i++) { int x = 0; for (int j = 1; j < m; j++) { if (arr[x] > arr[j]) { x = j; } } ans[x] = "1"; bw.write("? "); for (int j = 0; j < m; j++) { bw.write(ans[j]); } bw.write("\n"); bw.flush(); int val = pi(br.readLine()); if (val - tot == arr[x]) { tot = val; } else { ans[x] = "0"; } arr[x] = 20000000; } bw.write("! " + is(tot) + "\n"); bw.flush(); } }
Java
["5 4\n\n0\n\n5\n\n9\n\n7"]
1 second
["? 0000\n\n? 1110\n\n? 1111\n\n? 1101\n\n! 7"]
NoteHere is the graph of the example, satisfying $$$l_i=i$$$.
Java 11
standard input
[ "constructive algorithms", "graphs", "greedy", "interactive", "sortings" ]
003b7257b35416ec93f189cb29e458e6
The first and only line of input contains two integers $$$n,m$$$ ($$$2 \leq n \leq 200$$$, $$$1\le m \le 500$$$) — the number of stations and tracks.
1,700
null
standard output
PASSED
6e3ba0fc074210b3d383e49115623da4
train_108.jsonl
1654266900
As for the technology in the outside world, it is really too advanced for Gensokyo to even look up to.—Yasaka Kanako, Symposium of Post-mysticismThis is an interactive problem.Under the direct supervision of Kanako and the Moriya Shrine, the railway system of Gensokyo is finally finished. GSKR (Gensokyo Railways) consists of $$$n$$$ stations with $$$m$$$ bidirectional tracks connecting them. The $$$i$$$-th track has length $$$l_i$$$ ($$$1\le l_i\le 10^6$$$). Due to budget limits, the railway system may not be connected, though there may be more than one track between two stations.The value of a railway system is defined as the total length of its all tracks. The maximum (or minimum) capacity of a railway system is defined as the maximum (or minimum) value among all of the currently functional system's full spanning forest.In brief, full spanning forest of a graph is a spanning forest with the same connectivity as the given graph.Kanako has a simulator only able to process no more than $$$2m$$$ queries. The input of the simulator is a string $$$s$$$ of length $$$m$$$, consisting of characters 0 and/or 1. The simulator will assume the $$$i$$$-th track functional if $$$s_i=$$$ 1. The device will then tell Kanako the maximum capacity of the system in the simulated state.Kanako wants to know the the minimum capacity of the system with all tracks functional with the help of the simulator.The structure of the railway system is fixed in advance. In other words, the interactor is not adaptive.
256 megabytes
import java.io.*; import java.util.Arrays; import java.util.Comparator; import java.util.stream.IntStream; public class RailwaySystem { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); String[] input = br.readLine().split(" "); int n = Integer.parseInt(input[0]); int m = Integer.parseInt(input[1]); int[] L = new int[m]; boolean[] func = new boolean[m]; for (int i = 0; i < m; i++) { func[i] = true; L[i] = query(func, br, bw); func[i] = false; } int[] indices = IntStream.range(0, m).boxed().sorted(Comparator.comparingInt(a -> L[a])).mapToInt(i -> i).toArray(); func[indices[0]] = true; int s = L[indices[0]]; for (int i = 1; i < m; i++) { func[indices[i]] = true; if (query(func, br, bw) == s + L[indices[i]]) { s += L[indices[i]]; } else { func[indices[i]] = false; } } bw.write("! " + s + "\n"); br.close(); bw.close(); } private static int query(boolean[] arr, BufferedReader br, BufferedWriter bw) throws IOException { StringBuilder sb = new StringBuilder(); sb.append("? "); for (boolean b : arr) { if (b) { sb.append("1"); } else { sb.append("0"); } } sb.append("\n"); bw.write(sb.toString()); bw.flush(); return Integer.parseInt(br.readLine()); } }
Java
["5 4\n\n0\n\n5\n\n9\n\n7"]
1 second
["? 0000\n\n? 1110\n\n? 1111\n\n? 1101\n\n! 7"]
NoteHere is the graph of the example, satisfying $$$l_i=i$$$.
Java 11
standard input
[ "constructive algorithms", "graphs", "greedy", "interactive", "sortings" ]
003b7257b35416ec93f189cb29e458e6
The first and only line of input contains two integers $$$n,m$$$ ($$$2 \leq n \leq 200$$$, $$$1\le m \le 500$$$) — the number of stations and tracks.
1,700
null
standard output
PASSED
ff23b869b1dd166851c9a4824fca78a5
train_108.jsonl
1654266900
As for the technology in the outside world, it is really too advanced for Gensokyo to even look up to.—Yasaka Kanako, Symposium of Post-mysticismThis is an interactive problem.Under the direct supervision of Kanako and the Moriya Shrine, the railway system of Gensokyo is finally finished. GSKR (Gensokyo Railways) consists of $$$n$$$ stations with $$$m$$$ bidirectional tracks connecting them. The $$$i$$$-th track has length $$$l_i$$$ ($$$1\le l_i\le 10^6$$$). Due to budget limits, the railway system may not be connected, though there may be more than one track between two stations.The value of a railway system is defined as the total length of its all tracks. The maximum (or minimum) capacity of a railway system is defined as the maximum (or minimum) value among all of the currently functional system's full spanning forest.In brief, full spanning forest of a graph is a spanning forest with the same connectivity as the given graph.Kanako has a simulator only able to process no more than $$$2m$$$ queries. The input of the simulator is a string $$$s$$$ of length $$$m$$$, consisting of characters 0 and/or 1. The simulator will assume the $$$i$$$-th track functional if $$$s_i=$$$ 1. The device will then tell Kanako the maximum capacity of the system in the simulated state.Kanako wants to know the the minimum capacity of the system with all tracks functional with the help of the simulator.The structure of the railway system is fixed in advance. In other words, the interactor is not adaptive.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Arrays; import java.io.BufferedWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.Comparator; 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); BRailwaySystem solver = new BRailwaySystem(); solver.solve(1, in, out); out.close(); } static class BRailwaySystem { int ask(InputReader in, OutputWriter out, String s) { out.println("? " + s); out.flush(); return in.nextInt(); } public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.nextInt(), m = in.nextInt(); char[] c = new char[m]; int[] w = new int[m]; Integer[] p = new Integer[m]; for (int i = 0; i < m; i++) { p[i] = i; Arrays.fill(c, '0'); c[i] = '1'; w[i] = ask(in, out, new String(c)); } Arrays.sort(p, Comparator.comparingInt(i -> -w[i])); Arrays.fill(c, '1'); int answer = 0; int sum = ask(in, out, new String(c)); int l = 0; for (int i : p) { l++; if (l == m) { answer += w[i]; break; } c[i] = '0'; int u = ask(in, out, new String(c)); if (u == sum - w[i]) { answer += w[i]; } sum = u; } out.println("! " + answer); out.flush(); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } 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 flush() { writer.flush(); } public void println(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) { writer.print(' '); } writer.print(objects[i]); } writer.print('\n'); } public void close() { writer.close(); } } }
Java
["5 4\n\n0\n\n5\n\n9\n\n7"]
1 second
["? 0000\n\n? 1110\n\n? 1111\n\n? 1101\n\n! 7"]
NoteHere is the graph of the example, satisfying $$$l_i=i$$$.
Java 11
standard input
[ "constructive algorithms", "graphs", "greedy", "interactive", "sortings" ]
003b7257b35416ec93f189cb29e458e6
The first and only line of input contains two integers $$$n,m$$$ ($$$2 \leq n \leq 200$$$, $$$1\le m \le 500$$$) — the number of stations and tracks.
1,700
null
standard output
PASSED
9beac3f4fad8aabcd4f980aa91d5f693
train_108.jsonl
1654266900
As for the technology in the outside world, it is really too advanced for Gensokyo to even look up to.—Yasaka Kanako, Symposium of Post-mysticismThis is an interactive problem.Under the direct supervision of Kanako and the Moriya Shrine, the railway system of Gensokyo is finally finished. GSKR (Gensokyo Railways) consists of $$$n$$$ stations with $$$m$$$ bidirectional tracks connecting them. The $$$i$$$-th track has length $$$l_i$$$ ($$$1\le l_i\le 10^6$$$). Due to budget limits, the railway system may not be connected, though there may be more than one track between two stations.The value of a railway system is defined as the total length of its all tracks. The maximum (or minimum) capacity of a railway system is defined as the maximum (or minimum) value among all of the currently functional system's full spanning forest.In brief, full spanning forest of a graph is a spanning forest with the same connectivity as the given graph.Kanako has a simulator only able to process no more than $$$2m$$$ queries. The input of the simulator is a string $$$s$$$ of length $$$m$$$, consisting of characters 0 and/or 1. The simulator will assume the $$$i$$$-th track functional if $$$s_i=$$$ 1. The device will then tell Kanako the maximum capacity of the system in the simulated state.Kanako wants to know the the minimum capacity of the system with all tracks functional with the help of the simulator.The structure of the railway system is fixed in advance. In other words, the interactor is not adaptive.
256 megabytes
//some updates in import stuff import static java.lang.Math.max; import static java.lang.Math.min; import static java.lang.Math.abs; import java.util.*; import java.io.*; import java.math.*; //key points learned //max space ever that could be alloted in a program to pass in cf //int[][] prefixSum = new int[201][200_005]; -> not a single array more!!! //never allocate memory again again to such bigg array, it will give memory exceeded for sure //believe in your fucking solution and keep improving it!!! (sometimes) ///common mistakes // didn't read the question properly public class Main{ static int mod = (int) (Math.pow(10, 9)+7); static final int dx[] = { -1, 0, 1, 0 }, dy[] = { 0, -1, 0, 1 }; static final int[] dx8 = { -1, -1, -1, 0, 0, 1, 1, 1 }, dy8 = { -1, 0, 1, -1, 1, -1, 0, 1 }; static final int[] dx9 = { -1, -1, -1, 0, 0, 0, 1, 1, 1 }, dy9 = { -1, 0, 1, -1, 0, 1, -1, 0, 1 }; static final double eps = 1e-10; static List<Integer> primeNumbers = new ArrayList<>(); public static void main(String[] args) { MyScanner sc = new MyScanner(); //pretty important for sure - out = new PrintWriter(new BufferedOutputStream(System.out)); //dope shit output for sure //code here int n = sc.nextInt(); int m = sc.nextInt(); //this is pretty simple for sure, now figure this out //ask for the values of all m queries ArrayList<Pair> valEdge = new ArrayList<>(); Map<Integer, Integer> values = new HashMap<>(); StringBuilder sb = new StringBuilder(); for(int i= 0; i < m; i++){ sb.append(0); } for(int i= 0; i < m; i++){ sb.setCharAt(i, '1'); String curr = sb.toString(); System.out.println("? " + curr); int val = sc.nextInt(); valEdge.add(new Pair(i, val)); values.put(i, val); sb.setCharAt(i, '0'); } //using the above code, I would have values for all the edges for sure Collections.sort(valEdge, (a,b) -> a.b - b.b); // System.out.println(valEdge);valEdge //now I have to see something imp int prev = 0; for(int i = 0; i < m; i++){ Pair p = valEdge.get(i); int val = p.b; int idx = p.a; sb.setCharAt(idx, '1'); String curr = sb.toString(); System.out.println("? " + curr); int cprev = sc.nextInt(); if(cprev - prev != val){ sb.setCharAt(idx, '0'); }else{ prev = cprev; } } System.out.println("! " + prev); out.close(); } //new stuff to learn (whenever this is need for them, then only) //Lazy Segment Trees //Persistent Segment Trees //Square Root Decomposition //Geometry & Convex Hull //High Level DP -- yk yk //String Matching Algorithms //Heavy light Decomposition //Updation Required //Fenwick Tree - both are done (sum) //Segment Tree - both are done (min, max, sum) //-----CURRENTLY PRESENT-------// //Graph //DSU //powerMODe //power //Segment Tree (work on this one) //Prime Sieve //Count Divisors //Next Permutation //Get NCR //isVowel //Sort (int) //Sort (long) //Binomial Coefficient //Pair //Triplet //lcm (int & long) //gcd (int & long) //gcd (for binomial coefficient) //swap (int & char) //reverse //primeExponentCounts //Fast input and output //------------------------------------------------------------------- //------------------------------------------------------------------- //------------------------------------------------------------------- //------------------------------------------------------------------- //------------------------------------------------------------------- //GRAPH (basic structure) public static class Graph{ public int V; public ArrayList<ArrayList<Integer>> edges; //2 -> [0,1,2] (current) Graph(int V){ this.V = V; edges = new ArrayList<>(V+1); for(int i= 0; i <= V; i++){ edges.add(new ArrayList<>()); } } public void addEdge(int from , int to){ edges.get(from).add(to); edges.get(to).add(from); } } //DSU (path and rank optimised) public static class DisjointUnionSets { int[] rank, parent; int n; public DisjointUnionSets(int n) { rank = new int[n]; parent = new int[n]; Arrays.fill(rank, 1); Arrays.fill(parent,-1); this.n = n; } public int find(int curr){ if(parent[curr] == -1) return curr; //path compression optimisation return parent[curr] = find(parent[curr]); } public void union(int a, int b){ int s1 = find(a); int s2 = find(b); if(s1 != s2){ //union by size if(rank[s1] < rank[s2]){ parent[s1] = s2; rank[s2] += rank[s1]; }else{ parent[s2] = s1; rank[s1] += rank[s2]; } } } } //with mod public static long powerMOD(long x, long y) { long res = 1L; while (y > 0) { // If y is odd, multiply x with result if ((y & 1) != 0){ x %= mod; res %= mod; res = (res * x)%mod; } // y must be even now y = y >> 1; // y = y/2 x%= mod; x = (x * x)%mod; // Change x to x^2 } return res%mod; } //without mod public static long power(long x, long y) { long res = 1L; 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/ x = (x * x); } return res; } public static class segmentTree{ //so let's make a constructor function for this bad boi for sure!!! public long[] arr; public long[] tree; //COMPLEXITY (normal segment tree, stuff) //build -> O(n) //query -> O(logn) //update -> O(logn) //update-range -> O(n) (worst case) //simple iteration and stuff for sure public segmentTree(long[] arr){ int n = arr.length; this.arr = new long[n]; for(int i= 0; i < n; i++){ this.arr[i] = arr[i]; } tree = new long[4*n + 1]; } //pretty basic idea if you read the code once //first make child node once //then form the parent node using them public void buildTree(int s, int e, int index){ if(s == e){ tree[index] = arr[s]; return; } //recursive case int mid = (s + e)/2; buildTree(s, mid, 2 * index); buildTree(mid + 1, e, 2*index + 1); //the condition we want from children be like this tree[index] = min(tree[2 * index], tree[2 * index + 1]); return; } //definitely index based 0 query!!! //only int index = 1!! //baaki everything is simple as fuck public long query(int s, int e, int qs , int qe, int index){ //complete overlap if(s >= qs && e <= qe){ return tree[index]; } //no overlap if(qe < s || qs > e){ return Long.MAX_VALUE; } //partial overlap int mid = (s + e)/2; long left = query( s, mid , qs, qe, 2*index); long right = query( mid + 1, e, qs, qe, 2*index + 1); return min(left, right); } //gonna do range updates for sure now!! //let's do this bois!!! (solve this problem for sure) public void updateRange(int s, int e, int l, int r, long increment, int index){ //out of bounds if(l > e || r < s){ return; } //leaf node if(s == e){ tree[index] += increment; return; //behnchoda return tera baap krvayege? } //recursive case int mid = (s + e)/2; updateRange(s, mid, l, r, increment, 2 * index); updateRange(mid + 1, e, l, r, increment, 2 * index + 1); tree[index] = min(tree[2 * index], tree[2 * index + 1]); } } public static class segmentTreeLazy{ //so let's make a constructor function for this bad boi for sure!!! public long[] arr; public long[] tree; public long[] lazy; //COMPLEXITY (normal segment tree, stuff) //build -> O(n) //query-range -> O(logn) //lazy update-range -> O(logn) (imp) //simple iteration and stuff for sure public segmentTreeLazy(long[] arr){ int n = arr.length; this.arr = new long[n]; for(int i= 0; i < n; i++){ this.arr[i] = arr[i]; } tree = new long[4*n + 1]; lazy = new long[1000000]; //pretty big for no inconvenience (no?) NONONONOONON! NO fucker NO! } //pretty basic idea if you read the code once //first make child node once //then form the parent node using them public void buildTree(int s, int e, int index){ if(s == e){ tree[index] = arr[s]; return; } //recursive case int mid = (s + e)/2; buildTree(s, mid, 2 * index); buildTree(mid + 1, e, 2*index + 1); //the condition we want from children be like this tree[index] = min(tree[2 * index], tree[2 * index + 1]); return; } //definitely index based 0 query!!! //only int index = 1!! //baaki everything is simple as fuck public long queryLazy(int s, int e, int qs, int qe, int index){ //before going down resolve if it exist if(lazy[index] != 0){ tree[index] += lazy[index]; //non leaf node if(s != e){ lazy[2*index] += lazy[index]; lazy[2*index + 1] += lazy[index]; } lazy[index] = 0; //clear the lazy value at current node for sure } //no overlap if(s > qe || e < qs){ return Long.MAX_VALUE; } //complete overlap if(s >= qs && e <= qe){ return tree[index]; } //partial overlap int mid = (s + e)/2; long left = queryLazy(s, mid, qs, qe, 2 * index); long right = queryLazy(mid + 1, e, qs, qe, 2 * index + 1); return Math.min(left, right); } //update range in O(logn) -- using lazy array public void updateRangeLazy(int s, int e, int l, int r, int inc, int index){ //before going down resolve if it exist if(lazy[index] != 0){ tree[index] += lazy[index]; //non leaf node if(s != e){ lazy[2*index] += lazy[index]; lazy[2*index + 1] += lazy[index]; } lazy[index] = 0; //clear the lazy value at current node for sure } //no overlap if(s > r || l > e){ return; } //another case if(l <= s && e <= r){ tree[index] += inc; //create a new lazy value for children node if(s != e){ lazy[2*index] += inc; lazy[2*index + 1] += inc; } return; } //recursive case int mid = (s + e)/2; updateRangeLazy(s, mid, l, r, inc, 2*index); updateRangeLazy(mid + 1, e, l, r, inc, 2*index + 1); //update the tree index tree[index] = Math.min(tree[2*index], tree[2*index + 1]); return; } } //prime sieve public static void primeSieve(int n){ BitSet bitset = new BitSet(n+1); for(long i = 0; i < n ; i++){ if (i == 0 || i == 1) { bitset.set((int) i); continue; } if(bitset.get((int) i)) continue; primeNumbers.add((int)i); for(long j = i; j <= n ; j+= i) bitset.set((int)j); } } //number of divisors public static int countDivisors(long number){ if(number == 1) return 1; List<Integer> primeFactors = new ArrayList<>(); int index = 0; long curr = primeNumbers.get(index); while(curr * curr <= number){ while(number % curr == 0){ number = number/curr; primeFactors.add((int) curr); } index++; curr = primeNumbers.get(index); } if(number != 1) primeFactors.add((int) number); int current = primeFactors.get(0); int totalDivisors = 1; int currentCount = 2; for (int i = 1; i < primeFactors.size(); i++) { if (primeFactors.get(i) == current) { currentCount++; } else { totalDivisors *= currentCount; currentCount = 2; current = primeFactors.get(i); } } totalDivisors *= currentCount; return totalDivisors; } //primeExponentCounts public static int primeExponentsCount(int n) { if (n <= 1) return 0; int sqrt = (int) Math.sqrt(n); int remainingNumber = n; int result = 0; for (int i = 2; i <= sqrt; i++) { while (remainingNumber % i == 0) { result++; remainingNumber /= i; } } //in case of prime numbers this would happen if (remainingNumber > 1) { result++; } return result; } //now adding next permutation function to java hehe public static boolean next_permutation(int[] p) { for (int a = p.length - 2; a >= 0; --a) if (p[a] < p[a + 1]) for (int b = p.length - 1;; --b) if (p[b] > p[a]) { int t = p[a]; p[a] = p[b]; p[b] = t; for (++a, b = p.length - 1; a < b; ++a, --b) { t = p[a]; p[a] = p[b]; p[b] = t; } return true; } return false; } //finding the value of NCR in O(RlogN) time and O(1) space public static long getNcR(int n, int r) { long p = 1, k = 1; if (n - r < r) r = n - r; if (r != 0) { while (r > 0) { p *= n; k *= r; long m = __gcd(p, k); p /= m; k /= m; n--; r--; } } else { p = 1; } return p; } //is vowel function public static boolean isVowel(char c) { return (c=='a' || c=='A' || c=='e' || c=='E' || c=='i' || c=='I' || c=='o' || c=='O' || c=='u' || c=='U'); } //to sort the array with better method public static void sort(int[] a) { ArrayList<Integer> l=new ArrayList<>(); for (int i:a) l.add(i); Collections.sort(l); for (int i=0; i<a.length; i++) a[i]=l.get(i); } //sort long public static void sort(long[] a) { ArrayList<Long> l=new ArrayList<>(); for (long i:a) l.add(i); Collections.sort(l); for (int i=0; i<a.length; i++) a[i]=l.get(i); } //for calculating binomialCoeff public static int binomialCoeff(int n, int k) { int C[] = new int[k + 1]; // nC0 is 1 C[0] = 1; for (int i = 1; i <= n; i++) { // Compute next row of pascal // triangle using the previous row for (int j = Math.min(i, k); j > 0; j--) C[j] = C[j] + C[j - 1]; } return C[k]; } //Pair with int int public static class Pair{ public int a; public int b; public int hashCode; Pair(int a , int b){ this.a = a; this.b = b; this.hashCode = Objects.hash(a, b); } @Override public String toString(){ return a + " -> " + b; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Pair that = (Pair) o; return a == that.a && b == that.b; } @Override public int hashCode() { return this.hashCode; } } //Triplet with int int int public static class Triplet{ public int a; public int b; public int c; Triplet(int a , int b, int c){ this.a = a; this.b = b; this.c = c; } @Override public String toString(){ return a + " -> " + b; } } //Shortcut function public static long lcm(long a , long b){ return a * (b/gcd(a,b)); } //let's make one for calculating lcm basically public static int lcm(int a , int b){ return (a * b)/gcd(a,b); } //int version for gcd public static int gcd(int a, int b){ if(b == 0) return a; return gcd(b , a%b); } //long version for gcd public static long gcd(long a, long b){ if(b == 0) return a; return gcd(b , a%b); } //for ncr calculator(ignore this code) public static long __gcd(long n1, long n2) { long gcd = 1; for (int i = 1; i <= n1 && i <= n2; ++i) { // Checks if i is factor of both integers if (n1 % i == 0 && n2 % i == 0) { gcd = i; } } return gcd; } //swapping two elements in an array public static void swap(int[] arr, int left , int right){ int temp = arr[left]; arr[left] = arr[right]; arr[right] = temp; } //for char array public static void swap(char[] arr, int left , int right){ char temp = arr[left]; arr[left] = arr[right]; arr[right] = temp; } //reversing an array public static void reverse(int[] arr){ int left = 0; int right = arr.length-1; while(left <= right){ swap(arr, left,right); left++; right--; } } public static long expo(long a, long b, long mod) { long res = 1; while (b > 0) { if ((b & 1) == 1L) res = (res * a) % mod; //think about this one for a second a = (a * a) % mod; b = b >> 1; } return res; } //SOME EXTRA DOPE FUNCTIONS public static long mminvprime(long a, long b) { return expo(a, b - 2, b); } public static long mod_add(long a, long b, long m) { a = a % m; b = b % m; return (((a + b) % m) + m) % m; } public static long mod_sub(long a, long b, long m) { a = a % m; b = b % m; return (((a - b) % m) + m) % m; } public static long mod_mul(long a, long b, long m) { a = a % m; b = b % m; return (((a * b) % m) + m) % m; } public static long mod_div(long a, long b, long m) { a = a % m; b = b % m; return (mod_mul(a, mminvprime(b, m), m) + m) % m; } //O(n) every single time remember that public static long nCr(long N, long K , long mod){ long upper = 1L; long lower = 1L; long lowerr = 1L; for(long i = 1; i <= N; i++){ upper = mod_mul(upper, i, mod); } for(long i = 1; i <= K; i++){ lower = mod_mul(lower, i, mod); } for(long i = 1; i <= (N - K); i++){ lowerr = mod_mul(lowerr, i, mod); } // out.println(upper + " " + lower + " " + lowerr); long answer = mod_mul(lower, lowerr, mod); answer = mod_div(upper, answer, mod); return answer; } // long[] fact = new long[2 * n + 1]; // long[] ifact = new long[2 * n + 1]; // fact[0] = 1; // ifact[0] = 1; // for (long i = 1; i <= 2 * n; i++) // { // fact[(int)i] = mod_mul(fact[(int)i - 1], i, mod); // ifact[(int)i] = mminvprime(fact[(int)i], mod); // } //ifact is basically inverse factorial in here!!!!!(imp) public static long combination(long n, long r, long m, long[] fact, long[] ifact) { long val1 = fact[(int)n]; long val2 = ifact[(int)(n - r)]; long val3 = ifact[(int)r]; return (((val1 * val2) % m) * val3) % m; } //-----------PrintWriter for faster output--------------------------------- public static PrintWriter out; //-----------MyScanner class for faster input---------- public static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine(){ String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } //-------------------------------------------------------- }
Java
["5 4\n\n0\n\n5\n\n9\n\n7"]
1 second
["? 0000\n\n? 1110\n\n? 1111\n\n? 1101\n\n! 7"]
NoteHere is the graph of the example, satisfying $$$l_i=i$$$.
Java 11
standard input
[ "constructive algorithms", "graphs", "greedy", "interactive", "sortings" ]
003b7257b35416ec93f189cb29e458e6
The first and only line of input contains two integers $$$n,m$$$ ($$$2 \leq n \leq 200$$$, $$$1\le m \le 500$$$) — the number of stations and tracks.
1,700
null
standard output
PASSED
0415fdd43466556d777d0a82d110479f
train_108.jsonl
1654266900
As for the technology in the outside world, it is really too advanced for Gensokyo to even look up to.—Yasaka Kanako, Symposium of Post-mysticismThis is an interactive problem.Under the direct supervision of Kanako and the Moriya Shrine, the railway system of Gensokyo is finally finished. GSKR (Gensokyo Railways) consists of $$$n$$$ stations with $$$m$$$ bidirectional tracks connecting them. The $$$i$$$-th track has length $$$l_i$$$ ($$$1\le l_i\le 10^6$$$). Due to budget limits, the railway system may not be connected, though there may be more than one track between two stations.The value of a railway system is defined as the total length of its all tracks. The maximum (or minimum) capacity of a railway system is defined as the maximum (or minimum) value among all of the currently functional system's full spanning forest.In brief, full spanning forest of a graph is a spanning forest with the same connectivity as the given graph.Kanako has a simulator only able to process no more than $$$2m$$$ queries. The input of the simulator is a string $$$s$$$ of length $$$m$$$, consisting of characters 0 and/or 1. The simulator will assume the $$$i$$$-th track functional if $$$s_i=$$$ 1. The device will then tell Kanako the maximum capacity of the system in the simulated state.Kanako wants to know the the minimum capacity of the system with all tracks functional with the help of the simulator.The structure of the railway system is fixed in advance. In other words, the interactor is not adaptive.
256 megabytes
import java.lang.*; import java.util.*; import java.io.*; import java.math.*; public class Main { public static void deal(int n,int m,MyScanner sc) { char[] ch = new char[m]; Arrays.fill(ch,'0'); int[] a = new int[m]; Integer[] p = new Integer[m]; for(int i=0;i<m;i++) { p[i] = i; if(i>0) ch[i-1] = '0'; ch[i] = '1'; out.println(String.format("? %s",new String(ch))); out.flush(); a[i] = sc.nextInt(); } Arrays.sort(p,(o1,o2)->Integer.compare(a[o1],a[o2])); Arrays.fill(ch,'0'); int d = 0; for(int i=0;i<m;i++) { int t = p[i]; ch[t] = '1'; out.println(String.format("? %s",new String(ch))); out.flush(); int v = sc.nextInt(); if(v-d==a[t]) { d = v; } else { ch[t] = '0'; } } out.println(String.format("! %d",d)); } public static void main(String[] args) { MyScanner sc = new MyScanner(); out = new PrintWriter(new BufferedOutputStream(System.out)); int n = sc.nextInt(); int m = sc.nextInt(); deal(n,m,sc); out.close(); } //-----------PrintWriter for faster output--------------------------------- public static PrintWriter out; //-----------MyScanner class for faster input---------- public static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine(){ String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["5 4\n\n0\n\n5\n\n9\n\n7"]
1 second
["? 0000\n\n? 1110\n\n? 1111\n\n? 1101\n\n! 7"]
NoteHere is the graph of the example, satisfying $$$l_i=i$$$.
Java 11
standard input
[ "constructive algorithms", "graphs", "greedy", "interactive", "sortings" ]
003b7257b35416ec93f189cb29e458e6
The first and only line of input contains two integers $$$n,m$$$ ($$$2 \leq n \leq 200$$$, $$$1\le m \le 500$$$) — the number of stations and tracks.
1,700
null
standard output
PASSED
772c11a8c3718c624a74f6b783dd26de
train_108.jsonl
1654266900
As for the technology in the outside world, it is really too advanced for Gensokyo to even look up to.—Yasaka Kanako, Symposium of Post-mysticismThis is an interactive problem.Under the direct supervision of Kanako and the Moriya Shrine, the railway system of Gensokyo is finally finished. GSKR (Gensokyo Railways) consists of $$$n$$$ stations with $$$m$$$ bidirectional tracks connecting them. The $$$i$$$-th track has length $$$l_i$$$ ($$$1\le l_i\le 10^6$$$). Due to budget limits, the railway system may not be connected, though there may be more than one track between two stations.The value of a railway system is defined as the total length of its all tracks. The maximum (or minimum) capacity of a railway system is defined as the maximum (or minimum) value among all of the currently functional system's full spanning forest.In brief, full spanning forest of a graph is a spanning forest with the same connectivity as the given graph.Kanako has a simulator only able to process no more than $$$2m$$$ queries. The input of the simulator is a string $$$s$$$ of length $$$m$$$, consisting of characters 0 and/or 1. The simulator will assume the $$$i$$$-th track functional if $$$s_i=$$$ 1. The device will then tell Kanako the maximum capacity of the system in the simulated state.Kanako wants to know the the minimum capacity of the system with all tracks functional with the help of the simulator.The structure of the railway system is fixed in advance. In other words, the interactor is not adaptive.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Arrays; import java.io.BufferedWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.Comparator; 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); BRailwaySystem solver = new BRailwaySystem(); solver.solve(1, in, out); out.close(); } static class BRailwaySystem { int ask(InputReader in, OutputWriter out, String s) { out.println("? " + s); out.flush(); return in.nextInt(); } public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.nextInt(), m = in.nextInt(); char[] c = new char[m]; int[] w = new int[m]; Integer[] p = new Integer[m]; for (int i = 0; i < m; i++) { p[i] = i; Arrays.fill(c, '0'); c[i] = '1'; w[i] = ask(in, out, new String(c)); } Arrays.sort(p, Comparator.comparingInt(i -> -w[i])); Arrays.fill(c, '1'); int answer = 0; int sum = ask(in, out, new String(c)); int l = 0; for (int i : p) { l++; if (l == m) { answer += w[i]; break; } c[i] = '0'; int u = ask(in, out, new String(c)); if (u == sum - w[i]) { answer += w[i]; } sum = u; } out.println("! " + answer); out.flush(); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } 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 flush() { writer.flush(); } public void println(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) { writer.print(' '); } writer.print(objects[i]); } writer.print('\n'); } public void close() { writer.close(); } } }
Java
["5 4\n\n0\n\n5\n\n9\n\n7"]
1 second
["? 0000\n\n? 1110\n\n? 1111\n\n? 1101\n\n! 7"]
NoteHere is the graph of the example, satisfying $$$l_i=i$$$.
Java 11
standard input
[ "constructive algorithms", "graphs", "greedy", "interactive", "sortings" ]
003b7257b35416ec93f189cb29e458e6
The first and only line of input contains two integers $$$n,m$$$ ($$$2 \leq n \leq 200$$$, $$$1\le m \le 500$$$) — the number of stations and tracks.
1,700
null
standard output
PASSED
2a2498d0b348e6759db9b308eaaebe1d
train_108.jsonl
1654266900
As for the technology in the outside world, it is really too advanced for Gensokyo to even look up to.—Yasaka Kanako, Symposium of Post-mysticismThis is an interactive problem.Under the direct supervision of Kanako and the Moriya Shrine, the railway system of Gensokyo is finally finished. GSKR (Gensokyo Railways) consists of $$$n$$$ stations with $$$m$$$ bidirectional tracks connecting them. The $$$i$$$-th track has length $$$l_i$$$ ($$$1\le l_i\le 10^6$$$). Due to budget limits, the railway system may not be connected, though there may be more than one track between two stations.The value of a railway system is defined as the total length of its all tracks. The maximum (or minimum) capacity of a railway system is defined as the maximum (or minimum) value among all of the currently functional system's full spanning forest.In brief, full spanning forest of a graph is a spanning forest with the same connectivity as the given graph.Kanako has a simulator only able to process no more than $$$2m$$$ queries. The input of the simulator is a string $$$s$$$ of length $$$m$$$, consisting of characters 0 and/or 1. The simulator will assume the $$$i$$$-th track functional if $$$s_i=$$$ 1. The device will then tell Kanako the maximum capacity of the system in the simulated state.Kanako wants to know the the minimum capacity of the system with all tracks functional with the help of the simulator.The structure of the railway system is fixed in advance. In other words, the interactor is not adaptive.
256 megabytes
import java.io.*; import java.util.Arrays; import java.util.Comparator; import java.util.stream.IntStream; public class RailwaySystem { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); String[] input = br.readLine().split(" "); int n = Integer.parseInt(input[0]); int m = Integer.parseInt(input[1]); int[] L = new int[m]; boolean[] func = new boolean[m]; for (int i = 0; i < m; i++) { func[i] = true; L[i] = query(func, br, bw); func[i] = false; } int[] indices = IntStream.range(0, m).boxed().sorted(Comparator.comparingInt(a -> L[a])).mapToInt(i -> i).toArray(); func[indices[0]] = true; int s = L[indices[0]]; for (int i = 1; i < m; i++) { func[indices[i]] = true; if (query(func, br, bw) == s + L[indices[i]]) { s += L[indices[i]]; } else { func[indices[i]] = false; } } bw.write("! " + s + "\n"); br.close(); bw.close(); } private static int query(boolean[] arr, BufferedReader br, BufferedWriter bw) throws IOException { StringBuilder sb = new StringBuilder(); sb.append("? "); for (boolean b : arr) { if (b) { sb.append("1"); } else { sb.append("0"); } } sb.append("\n"); bw.write(sb.toString()); bw.flush(); return Integer.parseInt(br.readLine()); } }
Java
["5 4\n\n0\n\n5\n\n9\n\n7"]
1 second
["? 0000\n\n? 1110\n\n? 1111\n\n? 1101\n\n! 7"]
NoteHere is the graph of the example, satisfying $$$l_i=i$$$.
Java 11
standard input
[ "constructive algorithms", "graphs", "greedy", "interactive", "sortings" ]
003b7257b35416ec93f189cb29e458e6
The first and only line of input contains two integers $$$n,m$$$ ($$$2 \leq n \leq 200$$$, $$$1\le m \le 500$$$) — the number of stations and tracks.
1,700
null
standard output
PASSED
c56aad5c24562d93a3eedaa71b09bce8
train_108.jsonl
1654266900
As for the technology in the outside world, it is really too advanced for Gensokyo to even look up to.—Yasaka Kanako, Symposium of Post-mysticismThis is an interactive problem.Under the direct supervision of Kanako and the Moriya Shrine, the railway system of Gensokyo is finally finished. GSKR (Gensokyo Railways) consists of $$$n$$$ stations with $$$m$$$ bidirectional tracks connecting them. The $$$i$$$-th track has length $$$l_i$$$ ($$$1\le l_i\le 10^6$$$). Due to budget limits, the railway system may not be connected, though there may be more than one track between two stations.The value of a railway system is defined as the total length of its all tracks. The maximum (or minimum) capacity of a railway system is defined as the maximum (or minimum) value among all of the currently functional system's full spanning forest.In brief, full spanning forest of a graph is a spanning forest with the same connectivity as the given graph.Kanako has a simulator only able to process no more than $$$2m$$$ queries. The input of the simulator is a string $$$s$$$ of length $$$m$$$, consisting of characters 0 and/or 1. The simulator will assume the $$$i$$$-th track functional if $$$s_i=$$$ 1. The device will then tell Kanako the maximum capacity of the system in the simulated state.Kanako wants to know the the minimum capacity of the system with all tracks functional with the help of the simulator.The structure of the railway system is fixed in advance. In other words, the interactor is not adaptive.
256 megabytes
import java.util.*; import java.io.*; // you can compare with output.txt and expected out public class Round796E { public static MyPrintWriter out; public static MyScanner in; final static String IMPOSSIBLE = "IMPOSSIBLE"; final static String POSSIBLE = "POSSIBLE"; final static String YES = "YES"; final static String NO = "NO"; private static void preferFileIO(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))); boolean isDebug = false; boolean isFileIO = false; preferFileIO(isFileIO); Round796E sol = new Round796E(); int n = in.nextInt(); int m = in.nextInt(); sol.init(n, m); for(int i=0; i<m*2; i++) { String s = sol.makeQuery(); out.print("? "); out.println(s); out.flush(); int capacity = in.nextInt(); sol.feed(capacity); } int ans = sol.getAnswer(); out.print("! "); out.println(ans); out.flush(); in.close(); out.close(); } private int getAnswer() { if(currCapacity < lastCapacity + weight[sortedWeight.get(m-1).index]) return lastCapacity; else return currCapacity; } private void feed(int capacity) { if(queryNum <= m) { weight[queryNum-1] = capacity; } else { currCapacity = capacity; } } int n; int m; private void init(int n, int m) { this.n = n; this.m = m; weight = new int[m]; state = new boolean[m]; lastCapacity = 0; } int[] weight; int queryNum = 0; boolean[] state; int lastCapacity; int currCapacity; private String makeQuery() { StringBuilder sb = new StringBuilder(); if(queryNum < m) { for(int i=0; i<m; i++) { if(i==queryNum) { sb.append("1"); } else { sb.append("0"); } } } else if(queryNum < 2*m){ if(queryNum == m) sort(); // we add edges as in kruskal int currIdx = sortedWeight.get(queryNum-m).index; state[currIdx] = true; if(queryNum > m) { int prevIdx = sortedWeight.get(queryNum-m-1).index; if(currCapacity < lastCapacity + weight[prevIdx]) { // we didn't need to pick the last edge // it wasn't necessary, since the adversary discarded another edge to pick the last edge state[prevIdx] = false; } else { // last edge is a critical one lastCapacity = currCapacity; } } for(int i=0; i<m; i++) { if(state[i]) { sb.append("1"); } else { sb.append("0"); } } } queryNum++; return sb.toString(); } ArrayList<Pair> sortedWeight; private void sort() { sortedWeight= new ArrayList<>() ; for(int i=0; i<m; i++) sortedWeight.add(new Pair(i, weight[i])); Collections.sort(sortedWeight, new Comparator<Pair>() { @Override public int compare(Round796E.Pair o1, Round796E.Pair o2) { // TODO Auto-generated method stub return Integer.compare(o1.weight, o2.weight); } }); } static class Pair{ int index; public Pair(int index, int weight) { this.index = index; this.weight = weight; } int weight; } long solve(){ 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) { // TODO Auto-generated catch block 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[][] 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] = in.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] = in.nextInt()+offset; return a; } } public static class MyPrintWriter extends PrintWriter{ public MyPrintWriter(OutputStream os) { super(os); } public void print(long[] arr){ if(arr != null){ print(arr[0]); for(int i=1; i<arr.length; i++){ print(" "); print(arr[i]); } } } public void println(long[] arr){ print(arr); println(); } public void print(int[] arr){ if(arr != null){ print(arr[0]); for(int i=1; i<arr.length; i++){ print(" "); print(arr[i]); } } } public void println(int[] arr){ print(arr); println(); } public <T> void print(ArrayList<T> arr){ if(arr != null){ print(arr.get(0)); for(int i=1; i<arr.size(); i++){ print(" "); print(arr.get(i)); } } } public <T> void println(ArrayList<T> arr){ print(arr); println(); } public void println(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 println(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(); } } } } 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(); } 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 4\n\n0\n\n5\n\n9\n\n7"]
1 second
["? 0000\n\n? 1110\n\n? 1111\n\n? 1101\n\n! 7"]
NoteHere is the graph of the example, satisfying $$$l_i=i$$$.
Java 11
standard input
[ "constructive algorithms", "graphs", "greedy", "interactive", "sortings" ]
003b7257b35416ec93f189cb29e458e6
The first and only line of input contains two integers $$$n,m$$$ ($$$2 \leq n \leq 200$$$, $$$1\le m \le 500$$$) — the number of stations and tracks.
1,700
null
standard output
PASSED
14cab0f84241e3c7a368fb6ce86e1b30
train_108.jsonl
1654266900
As for the technology in the outside world, it is really too advanced for Gensokyo to even look up to.—Yasaka Kanako, Symposium of Post-mysticismThis is an interactive problem.Under the direct supervision of Kanako and the Moriya Shrine, the railway system of Gensokyo is finally finished. GSKR (Gensokyo Railways) consists of $$$n$$$ stations with $$$m$$$ bidirectional tracks connecting them. The $$$i$$$-th track has length $$$l_i$$$ ($$$1\le l_i\le 10^6$$$). Due to budget limits, the railway system may not be connected, though there may be more than one track between two stations.The value of a railway system is defined as the total length of its all tracks. The maximum (or minimum) capacity of a railway system is defined as the maximum (or minimum) value among all of the currently functional system's full spanning forest.In brief, full spanning forest of a graph is a spanning forest with the same connectivity as the given graph.Kanako has a simulator only able to process no more than $$$2m$$$ queries. The input of the simulator is a string $$$s$$$ of length $$$m$$$, consisting of characters 0 and/or 1. The simulator will assume the $$$i$$$-th track functional if $$$s_i=$$$ 1. The device will then tell Kanako the maximum capacity of the system in the simulated state.Kanako wants to know the the minimum capacity of the system with all tracks functional with the help of the simulator.The structure of the railway system is fixed in advance. In other words, the interactor is not adaptive.
256 megabytes
import java.io.*; import java.util.*; public class B { static class Edge implements Comparable<Edge>{ int id; int val; Edge(int id, int val){ this.id = id; this.val = val; } public int compareTo(Edge e){ return Integer.compare(this.val, e.val); } } public static void main(String[] args) throws IOException { Soumit sc = new Soumit(); int n = sc.nextInt(); int m = sc.nextInt(); Edge[] edgeWeights = new Edge[m]; for(int i=0;i<m;i++){ StringBuilder sb = new StringBuilder(); for(int j=0;j<m;j++){ if(i==j){ sb.append("1"); } else{ sb.append("0"); } } System.out.println("? "+sb); System.out.flush(); edgeWeights[i] = new Edge(i, sc.nextInt()); } Arrays.sort(edgeWeights); int sum = 0; Set<Integer> set = new HashSet<>(); for(int i=0;i<m;i++){ set.add(edgeWeights[i].id); StringBuilder sb = new StringBuilder(); for(int j=0;j<m;j++){ if(set.contains(j)){ sb.append("1"); } else{ sb.append("0"); } } System.out.println("? "+sb); System.out.flush(); int newsum = sc.nextInt(); if(sum+edgeWeights[i].val == newsum){ sum += edgeWeights[i].val; } else{ set.remove(edgeWeights[i].id); } } System.out.println("! "+sum); System.out.flush(); sc.close(); } static class Soumit { final private int BUFFER_SIZE = 1 << 18; final private DataInputStream din; final private byte[] buffer; private PrintWriter pw; private int bufferPointer, bytesRead; StringTokenizer st; public Soumit() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Soumit(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public void streamOutput(String file) throws IOException { FileWriter fw = new FileWriter(file); BufferedWriter bw = new BufferedWriter(fw); pw = new PrintWriter(bw); } public void println(String a) { pw.println(a); } public void print(String a) { pw.print(a); } public String readLine() throws IOException { byte[] buf = new byte[3000064]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public void sort(int[] arr) { ArrayList<Integer> arlist = new ArrayList<>(); for (int i : arr) arlist.add(i); Collections.sort(arlist); for (int i = 0; i < arr.length; i++) arr[i] = arlist.get(i); } public void sort(long[] arr) { ArrayList<Long> arlist = new ArrayList<>(); for (long i : arr) arlist.add(i); Collections.sort(arlist); for (int i = 0; i < arr.length; i++) arr[i] = arlist.get(i); } public int[] nextIntArray(int n) throws IOException { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = nextInt(); } return arr; } public long[] nextLongArray(int n) throws IOException { long[] arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = nextLong(); } return arr; } public double[] nextDoubleArray(int n) throws IOException { double[] arr = new double[n]; for (int i = 0; i < n; i++) { arr[i] = nextDouble(); } return arr; } 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;*/ if (din != null) din.close(); if (pw != null) pw.close(); } } }
Java
["5 4\n\n0\n\n5\n\n9\n\n7"]
1 second
["? 0000\n\n? 1110\n\n? 1111\n\n? 1101\n\n! 7"]
NoteHere is the graph of the example, satisfying $$$l_i=i$$$.
Java 17
standard input
[ "constructive algorithms", "graphs", "greedy", "interactive", "sortings" ]
003b7257b35416ec93f189cb29e458e6
The first and only line of input contains two integers $$$n,m$$$ ($$$2 \leq n \leq 200$$$, $$$1\le m \le 500$$$) — the number of stations and tracks.
1,700
null
standard output
PASSED
4959b9ea2ced5daec99b7ba8f9fbb6a9
train_108.jsonl
1654266900
As for the technology in the outside world, it is really too advanced for Gensokyo to even look up to.—Yasaka Kanako, Symposium of Post-mysticismThis is an interactive problem.Under the direct supervision of Kanako and the Moriya Shrine, the railway system of Gensokyo is finally finished. GSKR (Gensokyo Railways) consists of $$$n$$$ stations with $$$m$$$ bidirectional tracks connecting them. The $$$i$$$-th track has length $$$l_i$$$ ($$$1\le l_i\le 10^6$$$). Due to budget limits, the railway system may not be connected, though there may be more than one track between two stations.The value of a railway system is defined as the total length of its all tracks. The maximum (or minimum) capacity of a railway system is defined as the maximum (or minimum) value among all of the currently functional system's full spanning forest.In brief, full spanning forest of a graph is a spanning forest with the same connectivity as the given graph.Kanako has a simulator only able to process no more than $$$2m$$$ queries. The input of the simulator is a string $$$s$$$ of length $$$m$$$, consisting of characters 0 and/or 1. The simulator will assume the $$$i$$$-th track functional if $$$s_i=$$$ 1. The device will then tell Kanako the maximum capacity of the system in the simulated state.Kanako wants to know the the minimum capacity of the system with all tracks functional with the help of the simulator.The structure of the railway system is fixed in advance. In other words, the interactor is not adaptive.
256 megabytes
import java.io.*; import java.util.*; public class B { static class Edge implements Comparable<Edge>{ int id; int val; Edge(int id, int val){ this.id = id; this.val = val; } public int compareTo(Edge e){ return Integer.compare(this.val, e.val); } } public static void main(String[] args) throws IOException { Soumit sc = new Soumit(); int n = sc.nextInt(); int m = sc.nextInt(); Edge[] edgeWeights = new Edge[m]; for(int i=0;i<m;i++){ StringBuilder sb = new StringBuilder(); for(int j=0;j<m;j++){ if(i==j){ sb.append("1"); } else{ sb.append("0"); } } System.out.println("? "+sb); System.out.flush(); edgeWeights[i] = new Edge(i, sc.nextInt()); } Arrays.sort(edgeWeights); int sum = 0; Set<Integer> set = new HashSet<>(); for(int i=0;i<m;i++){ set.add(edgeWeights[i].id); StringBuilder sb = new StringBuilder(); for(int j=0;j<m;j++){ if(set.contains(j)){ sb.append("1"); } else{ sb.append("0"); } } System.out.println("? "+sb); System.out.flush(); int newsum = sc.nextInt(); if(sum+edgeWeights[i].val == newsum){ sum += edgeWeights[i].val; } else{ set.remove(edgeWeights[i].id); } } System.out.println("! "+sum); System.out.flush(); sc.close(); } static class Soumit { final private int BUFFER_SIZE = 1 << 18; final private DataInputStream din; final private byte[] buffer; private PrintWriter pw; private int bufferPointer, bytesRead; StringTokenizer st; public Soumit() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Soumit(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public void streamOutput(String file) throws IOException { FileWriter fw = new FileWriter(file); BufferedWriter bw = new BufferedWriter(fw); pw = new PrintWriter(bw); } public void println(String a) { pw.println(a); } public void print(String a) { pw.print(a); } public String readLine() throws IOException { byte[] buf = new byte[3000064]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public void sort(int[] arr) { ArrayList<Integer> arlist = new ArrayList<>(); for (int i : arr) arlist.add(i); Collections.sort(arlist); for (int i = 0; i < arr.length; i++) arr[i] = arlist.get(i); } public void sort(long[] arr) { ArrayList<Long> arlist = new ArrayList<>(); for (long i : arr) arlist.add(i); Collections.sort(arlist); for (int i = 0; i < arr.length; i++) arr[i] = arlist.get(i); } public int[] nextIntArray(int n) throws IOException { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = nextInt(); } return arr; } public long[] nextLongArray(int n) throws IOException { long[] arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = nextLong(); } return arr; } public double[] nextDoubleArray(int n) throws IOException { double[] arr = new double[n]; for (int i = 0; i < n; i++) { arr[i] = nextDouble(); } return arr; } 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;*/ if (din != null) din.close(); if (pw != null) pw.close(); } } }
Java
["5 4\n\n0\n\n5\n\n9\n\n7"]
1 second
["? 0000\n\n? 1110\n\n? 1111\n\n? 1101\n\n! 7"]
NoteHere is the graph of the example, satisfying $$$l_i=i$$$.
Java 17
standard input
[ "constructive algorithms", "graphs", "greedy", "interactive", "sortings" ]
003b7257b35416ec93f189cb29e458e6
The first and only line of input contains two integers $$$n,m$$$ ($$$2 \leq n \leq 200$$$, $$$1\le m \le 500$$$) — the number of stations and tracks.
1,700
null
standard output
PASSED
b74a73d9da2d9ddd516f2bc87b0f1b9c
train_108.jsonl
1654266900
As for the technology in the outside world, it is really too advanced for Gensokyo to even look up to.—Yasaka Kanako, Symposium of Post-mysticismThis is an interactive problem.Under the direct supervision of Kanako and the Moriya Shrine, the railway system of Gensokyo is finally finished. GSKR (Gensokyo Railways) consists of $$$n$$$ stations with $$$m$$$ bidirectional tracks connecting them. The $$$i$$$-th track has length $$$l_i$$$ ($$$1\le l_i\le 10^6$$$). Due to budget limits, the railway system may not be connected, though there may be more than one track between two stations.The value of a railway system is defined as the total length of its all tracks. The maximum (or minimum) capacity of a railway system is defined as the maximum (or minimum) value among all of the currently functional system's full spanning forest.In brief, full spanning forest of a graph is a spanning forest with the same connectivity as the given graph.Kanako has a simulator only able to process no more than $$$2m$$$ queries. The input of the simulator is a string $$$s$$$ of length $$$m$$$, consisting of characters 0 and/or 1. The simulator will assume the $$$i$$$-th track functional if $$$s_i=$$$ 1. The device will then tell Kanako the maximum capacity of the system in the simulated state.Kanako wants to know the the minimum capacity of the system with all tracks functional with the help of the simulator.The structure of the railway system is fixed in advance. In other words, the interactor is not adaptive.
256 megabytes
import java.io.*; import java.util.*; public class B { static class Edge implements Comparable<Edge>{ int id; int val; Edge(int id, int val){ this.id = id; this.val = val; } public int compareTo(Edge e){ return Integer.compare(this.val, e.val); } } public static void main(String[] args) throws IOException { Soumit sc = new Soumit(); int n = sc.nextInt(); int m = sc.nextInt(); Edge[] edgeWeights = new Edge[m]; for(int i=0;i<m;i++){ StringBuilder sb = new StringBuilder(); for(int j=0;j<m;j++){ if(i==j){ sb.append("1"); } else{ sb.append("0"); } } System.out.println("? "+sb); System.out.flush(); edgeWeights[i] = new Edge(i, sc.nextInt()); } Arrays.sort(edgeWeights); int sum = 0; Set<Integer> set = new HashSet<>(); for(int i=0;i<m;i++){ set.add(edgeWeights[i].id); StringBuilder sb = new StringBuilder(); for(int j=0;j<m;j++){ if(set.contains(j)){ sb.append("1"); } else{ sb.append("0"); } } System.out.println("? "+sb); System.out.flush(); int newsum = sc.nextInt(); if(sum+edgeWeights[i].val == newsum){ sum += edgeWeights[i].val; } else{ set.remove(edgeWeights[i].id); } } System.out.println("! "+sum); System.out.flush(); sc.close(); } static class Soumit { final private int BUFFER_SIZE = 1 << 18; final private DataInputStream din; final private byte[] buffer; private PrintWriter pw; private int bufferPointer, bytesRead; StringTokenizer st; public Soumit() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Soumit(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public void streamOutput(String file) throws IOException { FileWriter fw = new FileWriter(file); BufferedWriter bw = new BufferedWriter(fw); pw = new PrintWriter(bw); } public void println(String a) { pw.println(a); } public void print(String a) { pw.print(a); } public String readLine() throws IOException { byte[] buf = new byte[3000064]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public void sort(int[] arr) { ArrayList<Integer> arlist = new ArrayList<>(); for (int i : arr) arlist.add(i); Collections.sort(arlist); for (int i = 0; i < arr.length; i++) arr[i] = arlist.get(i); } public void sort(long[] arr) { ArrayList<Long> arlist = new ArrayList<>(); for (long i : arr) arlist.add(i); Collections.sort(arlist); for (int i = 0; i < arr.length; i++) arr[i] = arlist.get(i); } public int[] nextIntArray(int n) throws IOException { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = nextInt(); } return arr; } public long[] nextLongArray(int n) throws IOException { long[] arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = nextLong(); } return arr; } public double[] nextDoubleArray(int n) throws IOException { double[] arr = new double[n]; for (int i = 0; i < n; i++) { arr[i] = nextDouble(); } return arr; } 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;*/ if (din != null) din.close(); if (pw != null) pw.close(); } } }
Java
["5 4\n\n0\n\n5\n\n9\n\n7"]
1 second
["? 0000\n\n? 1110\n\n? 1111\n\n? 1101\n\n! 7"]
NoteHere is the graph of the example, satisfying $$$l_i=i$$$.
Java 17
standard input
[ "constructive algorithms", "graphs", "greedy", "interactive", "sortings" ]
003b7257b35416ec93f189cb29e458e6
The first and only line of input contains two integers $$$n,m$$$ ($$$2 \leq n \leq 200$$$, $$$1\le m \le 500$$$) — the number of stations and tracks.
1,700
null
standard output
PASSED
f40ccd7ce7efdc4c01e3118a0d43cc4a
train_108.jsonl
1654266900
As for the technology in the outside world, it is really too advanced for Gensokyo to even look up to.—Yasaka Kanako, Symposium of Post-mysticismThis is an interactive problem.Under the direct supervision of Kanako and the Moriya Shrine, the railway system of Gensokyo is finally finished. GSKR (Gensokyo Railways) consists of $$$n$$$ stations with $$$m$$$ bidirectional tracks connecting them. The $$$i$$$-th track has length $$$l_i$$$ ($$$1\le l_i\le 10^6$$$). Due to budget limits, the railway system may not be connected, though there may be more than one track between two stations.The value of a railway system is defined as the total length of its all tracks. The maximum (or minimum) capacity of a railway system is defined as the maximum (or minimum) value among all of the currently functional system's full spanning forest.In brief, full spanning forest of a graph is a spanning forest with the same connectivity as the given graph.Kanako has a simulator only able to process no more than $$$2m$$$ queries. The input of the simulator is a string $$$s$$$ of length $$$m$$$, consisting of characters 0 and/or 1. The simulator will assume the $$$i$$$-th track functional if $$$s_i=$$$ 1. The device will then tell Kanako the maximum capacity of the system in the simulated state.Kanako wants to know the the minimum capacity of the system with all tracks functional with the help of the simulator.The structure of the railway system is fixed in advance. In other words, the interactor is not adaptive.
256 megabytes
import java.io.*; import java.util.*; public class B { static class Edge implements Comparable<Edge>{ int id; int val; Edge(int id, int val){ this.id = id; this.val = val; } public int compareTo(Edge e){ return Integer.compare(this.val, e.val); } } public static void main(String[] args) throws IOException { Soumit sc = new Soumit(); int n = sc.nextInt(); int m = sc.nextInt(); Edge[] edgeWeights = new Edge[m]; for(int i=0;i<m;i++){ StringBuilder sb = new StringBuilder(); for(int j=0;j<m;j++){ if(i==j){ sb.append("1"); } else{ sb.append("0"); } } System.out.println("? "+sb); System.out.flush(); edgeWeights[i] = new Edge(i, sc.nextInt()); } Arrays.sort(edgeWeights); int sum = 0; Set<Integer> set = new HashSet<>(); for(int i=0;i<m;i++){ set.add(edgeWeights[i].id); StringBuilder sb = new StringBuilder(); for(int j=0;j<m;j++){ if(set.contains(j)){ sb.append("1"); } else{ sb.append("0"); } } System.out.println("? "+sb); System.out.flush(); int newsum = sc.nextInt(); if(sum+edgeWeights[i].val == newsum){ sum += edgeWeights[i].val; } else{ set.remove(edgeWeights[i].id); } } System.out.println("! "+sum); System.out.flush(); sc.close(); } static class Soumit { final private int BUFFER_SIZE = 1 << 18; final private DataInputStream din; final private byte[] buffer; private PrintWriter pw; private int bufferPointer, bytesRead; StringTokenizer st; public Soumit() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Soumit(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public void streamOutput(String file) throws IOException { FileWriter fw = new FileWriter(file); BufferedWriter bw = new BufferedWriter(fw); pw = new PrintWriter(bw); } public void println(String a) { pw.println(a); } public void print(String a) { pw.print(a); } public String readLine() throws IOException { byte[] buf = new byte[3000064]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public void sort(int[] arr) { ArrayList<Integer> arlist = new ArrayList<>(); for (int i : arr) arlist.add(i); Collections.sort(arlist); for (int i = 0; i < arr.length; i++) arr[i] = arlist.get(i); } public void sort(long[] arr) { ArrayList<Long> arlist = new ArrayList<>(); for (long i : arr) arlist.add(i); Collections.sort(arlist); for (int i = 0; i < arr.length; i++) arr[i] = arlist.get(i); } public int[] nextIntArray(int n) throws IOException { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = nextInt(); } return arr; } public long[] nextLongArray(int n) throws IOException { long[] arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = nextLong(); } return arr; } public double[] nextDoubleArray(int n) throws IOException { double[] arr = new double[n]; for (int i = 0; i < n; i++) { arr[i] = nextDouble(); } return arr; } 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;*/ if (din != null) din.close(); if (pw != null) pw.close(); } } }
Java
["5 4\n\n0\n\n5\n\n9\n\n7"]
1 second
["? 0000\n\n? 1110\n\n? 1111\n\n? 1101\n\n! 7"]
NoteHere is the graph of the example, satisfying $$$l_i=i$$$.
Java 17
standard input
[ "constructive algorithms", "graphs", "greedy", "interactive", "sortings" ]
003b7257b35416ec93f189cb29e458e6
The first and only line of input contains two integers $$$n,m$$$ ($$$2 \leq n \leq 200$$$, $$$1\le m \le 500$$$) — the number of stations and tracks.
1,700
null
standard output
PASSED
711ecef046d62d80c45d6bb577b1c9b7
train_108.jsonl
1654266900
The enchanted forest got its name from the magical mushrooms growing here. They may cause illusions and generally should not be approached.—Perfect Memento in Strict SenseMarisa comes to pick mushrooms in the Enchanted Forest. The Enchanted forest can be represented by $$$n$$$ points on the $$$X$$$-axis numbered $$$1$$$ through $$$n$$$. Before Marisa started, her friend, Patchouli, used magic to detect the initial number of mushroom on each point, represented by $$$a_1,a_2,\ldots,a_n$$$.Marisa can start out at any point in the forest on minute $$$0$$$. Each minute, the followings happen in order: She moves from point $$$x$$$ to $$$y$$$ ($$$|x-y|\le 1$$$, possibly $$$y=x$$$). She collects all mushrooms on point $$$y$$$. A new mushroom appears on each point in the forest. Note that she cannot collect mushrooms on minute $$$0$$$.Now, Marisa wants to know the maximum number of mushrooms she can pick after $$$k$$$ minutes.
256 megabytes
import java.io.*; import java.util.*; import java.math.*; public class Practice{ public static void main(String[] args) { TaskA solver = new TaskA(); // initFac(2*100001); int t = in.nextInt(); for (int i = 1; i <= t ; i++) { solver.solve(i, in, out); } // solver.solve(1, in, out); out.flush(); out.close(); } static ArrayList<Integer>[] graph ; static int []children; static class TaskA { public void solve(int testNumber, InputReader in, PrintWriter out) { long n=in.nextInt();long k= in.nextInt(); long[]s=new long[(int)n+1]; for(long i=1;i<=n;i++)s[(int)i]=s[(int)(i-1)]+in.nextLong(); if(k>=n)println(s[(int)n]+(k-1L+k-n)*n/2); else { long max=s[(int)k]; for(long i= k+1;i<=n;i++)max=Math.max((s[(int)i]-s[(int)(i-k)]),max); println(max+k*(k-1L)/2); } } } static int dfs(int at,int pt) { if(graph[at].size()==0&&pt!=-1) { return 0; } else if(graph[at].size()==1) { return children[graph[at].get(0)]; } else { int max=0; return max(dfs(graph[at].get(0),at)+children[graph[at].get(1)],dfs(graph[at].get(1),at)+children[graph[at].get(0)]); } } static void dfsCh(int at,int pt) { if(graph[at].size()==0&&pt!=-1) { children[at]=0;return; } for(int x:graph[at]) { if(x==pt) {continue;} dfsCh(x,at); children[at]+=(1+children[x]); } } static void remdfs(int at,int pt) { if(graph[at].size()==1&&pt!=-1) { graph[at].remove(0);return; } for(int x:graph[at]) { if(x==pt) {continue;} remdfs(x,at); for(int i=0;i<graph[x].size();i++) { if(graph[x].get(i)==at) { graph[x].remove(i); } } } } static TreeMap<Integer,Integer>ctm(int[]arr){ TreeMap<Integer,Integer>tm=new TreeMap<>(); for(int i=0;i<arr.length;i++) { int x=arr[i]; if(tm.containsKey(x)){ tm.put(x, tm.get(x)+1); } else { tm.put(x, 1); } } return tm; } static HashMap<Integer,Integer>chm(int[]arr){ HashMap<Integer,Integer>tm=new HashMap<>(); for(int i=0;i<arr.length;i++) { int x=arr[i]; if(tm.containsKey(x)){ tm.put(x, tm.get(x)+1); } else { tm.put(x, 1); } } return tm; } static int min(int x,int y) { return Math.min(x, y); } static int max(int x,int y) { return Math.max(x, y); } static long min(long x,long y) { return Math.min(x, y); } static long max(long x,long y) { return Math.max(x, y); } static int abs(int x,int y) { return Math.abs(x-y); } static long abs(long x,long y) { return Math.abs(x-y); } static void Eularianbfs(int v,int[]cur,int k,ArrayList<Integer>path) { while (cur[v] < k) { int u = cur[v]++; Eularianbfs(u,cur,k,path); path.add(u); } } static long modExp(long x,long y,long mod) { long res = 1; while (y > 0) { if ((y & 1) != 0) res = (res * x)%mod; y = (y >> 1)%mod; x = (x * x)%mod; } return res % mod; } static long[] fac; static long mod = 1000000000+7; static void initFac(long n) { fac = new long[(int)n + 1]; fac[0] = 1; for (int i = 1; i <= n; i++) { fac[i] = (fac[i - 1] * i) % mod; } } static int count(char []arr,char x) { int c=0; for(int i=0;i<arr.length;i++) { if(arr[i]==x) { c++; } } return c; } static int count(int []arr,int x) { int c=0; for(int i=0;i<arr.length;i++) { if(arr[i]==x) { c++; } } return c; } static boolean[]seive(int n){ boolean[]b=new boolean[n+1]; for (int i = 2; i <= n; i++) b[i] = true; for(int i=2;i*i<=n;i++) { if(b[i]) { for(int j=i*i;j<=n;j+=i) { b[j]=false; } } } return b; } static int[] query(int l,int r) { System.out.println("? "+l+" "+r); System.out.print ("\n");System.out.flush(); int[]arr=new int[r-l+1]; for(int i=0;i<r-l+1;i++) { arr[i]=in.nextInt(); } return arr; } static long[]presum(int[]arr){ int n= arr.length; long[]pre=new long[n]; for(int i=0;i<n;i++) { if(i>0) { pre[i]=pre[i-1]; } pre[i]+=arr[i]; } return pre; } static int max(int[]arr) { int max=Integer.MIN_VALUE; for(int i=0;i<arr.length;i++) { max=Math.max(max, arr[i]); } return max; } static int min(int[]arr) { int min=Integer.MAX_VALUE; for(int i=0;i<arr.length;i++) { min=Math.min(min, arr[i]); } return min; } static int ceil(int a,int b) { int ans=a/b;if(a%b!=0) { ans++; } return ans; } static long sum(int[]arr) { long s=0; for(int x:arr) { s+=x; } return s; } static long sum(long[]arr) { long s=0; for(long x:arr) { s+=x; } return s; } static int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } 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); } static void println(int[][]arr) { for(int i=0;i<arr.length;i++) { for(int j=0;j<arr[0].length;j++) { print(arr[i][j]+" "); } print("\n"); } } static void println(long[][]arr) { for(int i=0;i<arr.length;i++) { for(int j=0;j<arr[0].length;j++) { print(arr[i][j]+" "); } print("\n"); } } static void println(int[]arr){ for(int i=0;i<arr.length;i++) { print(arr[i]+" "); } print("\n"); } static void println(long[]arr){ for(int i=0;i<arr.length;i++) { print(arr[i]+" "); } print("\n"); } static void println(char x) { out.println(x); } static long[]input(long n){ long[]arr=new long[(int)n]; for(int i=0;i<n;i++) { arr[i]=in.nextInt(); } return arr; } static int[]input(int n){ int[]arr=new int[n]; for(int i=0;i<n;i++) { arr[i]=in.nextInt(); } return arr; } static Character Char(int x) { return Character.toString((char)x).charAt(0); } static int[]input(){ int n= in.nextInt(); int[]arr=new int[(int)n]; for(int i=0;i<n;i++) { arr[i]=in.nextInt(); } return arr; } //////////////////////////////////////////////////////// static class Pair implements Comparable<Pair>{ int first; int second;int third; Pair(int x, int y) { this.first = x; this.second = y; } public int compareTo(Pair p) { return Integer.compare(second, p.second); } } static void sortS(Pair arr[]) { Arrays.sort(arr, new Comparator<Pair>() { @Override public int compare(Pair p1, Pair p2) { if(p1.second==p2.second) {return p1.first-p2.first;} return (p1.second - p2.second); } }); } static void sortF(Pair arr[]) { Arrays.sort(arr, new Comparator<Pair>() { @Override public int compare(Pair p1, Pair p2) { if(p1.first==p2.first) {return p1.second-p2.second;} return (p1.first - p2.first); } }); } ///////////////////////////////////////////////////////////// static InputStream inputStream = System.in; static OutputStream outputStream = System.out; static InputReader in = new InputReader(inputStream); static PrintWriter out = new PrintWriter(outputStream); static void println(long c) { out.println(c); } static void print(long c) { out.print(c); } static void print(int c) { out.print(c); } static void println(int x) { out.println(x); } static void print(String s) { out.print(s); } static void println(String s) { out.println(s); } static void println(boolean b) { out.println(b); } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } }
Java
["4\n\n5 2\n\n5 6 1 2 3\n\n5 7\n\n5 6 1 2 3\n\n1 2\n\n999999\n\n5 70000\n\n1000000000 1000000000 1000000000 1000000000 1000000000"]
2 seconds
["12\n37\n1000000\n5000349985"]
NoteTest case 1:Marisa can start at $$$x=2$$$. In the first minute, she moves to $$$x=1$$$ and collect $$$5$$$ mushrooms. The number of mushrooms will be $$$[1,7,2,3,4]$$$. In the second minute, she moves to $$$x=2$$$ and collects $$$7$$$ mushrooms. The numbers of mushrooms will be $$$[2,1,3,4,5]$$$. After $$$2$$$ minutes, Marisa collects $$$12$$$ mushrooms.It can be shown that it is impossible to collect more than $$$12$$$ mushrooms.Test case 2:This is one of her possible moving path:$$$2 \rightarrow 3 \rightarrow 2 \rightarrow 1 \rightarrow 2 \rightarrow 3 \rightarrow 4 \rightarrow 5$$$It can be shown that it is impossible to collect more than $$$37$$$ mushrooms.
Java 8
standard input
[ "brute force", "greedy" ]
e092d58ac58e1e41d17be946128234e5
Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains two integers $$$n$$$, $$$k$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$, $$$1\le k \le 10^9$$$) — the number of positions with mushrooms and the time Marisa has, respectively. The second line of each test case contains $$$n$$$ integers $$$a_1,a_2,\ldots,a_n$$$ ($$$1 \le a_i \le 10^9$$$) — the initial number of mushrooms on point $$$1,2,\ldots,n$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$.
1,600
For each test case, print the maximum number of mushrooms Marisa can pick after $$$k$$$ minutes.
standard output
PASSED
97995387e2a4cbe0ff27dae63df56f2a
train_108.jsonl
1654266900
The enchanted forest got its name from the magical mushrooms growing here. They may cause illusions and generally should not be approached.—Perfect Memento in Strict SenseMarisa comes to pick mushrooms in the Enchanted Forest. The Enchanted forest can be represented by $$$n$$$ points on the $$$X$$$-axis numbered $$$1$$$ through $$$n$$$. Before Marisa started, her friend, Patchouli, used magic to detect the initial number of mushroom on each point, represented by $$$a_1,a_2,\ldots,a_n$$$.Marisa can start out at any point in the forest on minute $$$0$$$. Each minute, the followings happen in order: She moves from point $$$x$$$ to $$$y$$$ ($$$|x-y|\le 1$$$, possibly $$$y=x$$$). She collects all mushrooms on point $$$y$$$. A new mushroom appears on each point in the forest. Note that she cannot collect mushrooms on minute $$$0$$$.Now, Marisa wants to know the maximum number of mushrooms she can pick after $$$k$$$ minutes.
256 megabytes
import java.util.*; import java.util.concurrent.LinkedBlockingDeque; import javax.print.attribute.IntegerSyntax; import javax.sql.rowset.spi.SyncResolver; import java.io.*; import java.nio.channels.NonReadableChannelException; import java.text.DateFormatSymbols; import static java.lang.System.*; public class CpTemp{ static FastScanner fs = null; static ArrayList<Integer> al[]; static HashMap<Long,Long> hm; static long fy; static long fx; static long ix; static long iy; static long prex[]; static long prey[]; public static void main(String[] args) { fs = new FastScanner(); PrintWriter out = new PrintWriter(System.out); int t= fs.nextInt(); outer: while (t-- > 0) { int n = fs.nextInt(); long k = fs.nextLong(); long pre[] = new long[n+1]; long a[] = fs.readlongArray(n); pre[1] = a[0]; for(int i=1;i<n;i++) pre[i+1] += a[i]+pre[i]; if(k<n){ long max = pre[(int)k]; for(long i= k+1;i<=n;i++){ max = Math.max(max,pre[(int)i]-pre[ (int)(i-k)]); } max += (k*(k-1))/2; out.println(max); }else{ long ans = pre[n]; ans += (n*k) - (long)((n*(n+1l))/2l); out.println(ans); } } out.close(); } public static void solve(long n, ArrayList<Long>al){ for(long d = 2; d*d<=(n);d++){ if(n%d==0){ al.add(d); if(d!=(n/d)){ al.add(-1l); return; } } } } // 0 6 1 3 2 m = 7 public static boolean check(long t,int a[],int m) { int prev = -1; for(int i=0;i<a.length;i++){ if(i==0){ if(a[i]+t >= m){ prev = 0; }else{ prev = a[i]; } }else{ if(a[i]==prev){ continue; }else if(a[i]<prev){ if(prev - a[i] <= t){ continue; }else{ return false; } }else{ if(a[i]+t >= m && (a[i]+t)%m < prev){ prev = a[i]; }else if(a[i]+t >=m && (a[i]+t)%m >= prev ){ continue; }else{ prev = a[i]; } } } } return true; } public static int CeilIndex(int A[], int l, int r, int key) { while (r - l > 1) { int m = l + (r - l) / 2; if (A[m] >= key) r = m; else l = m; } return r; } public static int LongestIncreasingSubsequenceLength(int A[], int size) { // Add boundary case, when array size is one int[] tailTable = new int[size]; int len; // always points empty slot tailTable[0] = A[0]; len = 1; for (int i = 1; i < size; i++) { if (A[i] < tailTable[0]) // new smallest value tailTable[0] = A[i]; else if (A[i] > tailTable[len - 1]) // A[i] wants to extend largest subsequence tailTable[len++] = A[i]; else // A[i] wants to be current end candidate of an existing // subsequence. It will replace ceil value in tailTable tailTable[CeilIndex(tailTable, -1, len - 1, A[i])] = A[i]; } return len; } public static int ask(int st,int end){ if(st>=end) { return -1; } out.println("? "+(st+1)+" "+(end+1)); int g = fs.nextInt(); out.flush(); return g-1; } static long bit[]; // '1' index based array public static void update(long bit[],int i,int x){ for(;i<bit.length;i+=(i&(-i))){ bit[i] += x; } } public static long sum(int i){ long sum=0; for(;i>0 ;i -= (i&(-i))){ sum += bit[i]; } return sum; } static class Pair implements Comparable<Pair> { int x; int y; Pair(int x, int y) { this.x = x; this.y = y; } public int compareTo(Pair o){ return this.y-o.y; } } static class Pair1 implements Comparable<Pair1> { int x; int y; int z; Pair1(int x, int y,int z) { this.x = x; this.y = y; this.z = z; } public int compareTo(Pair1 o){ return this.z-o.z; } } static int power(int x, int y, int p) { if (y == 0) return 1; if (x == 0) return 0; int 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 power(long x, long y) { if (y == 0) return 1; if (x == 0) return 0; long res = 1; while (y > 0) { if (y % 2 == 1) res = (res * x); y = y >> 1; x = (x * x); } return res; } static void sort(long[] a) { ArrayList<Long> l = new ArrayList<>(); for (long i : a) l.add(i); Collections.sort(l); for (int i = 0; i < a.length; i++) a[i] = l.get(i); } static class FastScanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } long[] 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()); } } static boolean prime[]; static void sieveOfEratosthenes(int n) { prime = new boolean[n + 1]; for (int i = 0; i <= n; i++) prime[i] = true; for (int p = 2; p * p <= n; p++) { // If prime[p] is not changed, then it is a // prime if (prime[p] == true) { // Update all multiples of p for (int i = p * p; i <= n; i += p) prime[i] = false; } } } public static int log2(int x) { return (int) (Math.log(x) / Math.log(2)); } public static long gcd(long a, long b) { if (b == 0) { return a; } return gcd(b, a % b); } static long nCk(int n, int k) { long res = 1; for (int i = n - k + 1; i <= n; ++i) res *= i; for (int i = 2; i <= k; ++i) res /= i; return res; } }
Java
["4\n\n5 2\n\n5 6 1 2 3\n\n5 7\n\n5 6 1 2 3\n\n1 2\n\n999999\n\n5 70000\n\n1000000000 1000000000 1000000000 1000000000 1000000000"]
2 seconds
["12\n37\n1000000\n5000349985"]
NoteTest case 1:Marisa can start at $$$x=2$$$. In the first minute, she moves to $$$x=1$$$ and collect $$$5$$$ mushrooms. The number of mushrooms will be $$$[1,7,2,3,4]$$$. In the second minute, she moves to $$$x=2$$$ and collects $$$7$$$ mushrooms. The numbers of mushrooms will be $$$[2,1,3,4,5]$$$. After $$$2$$$ minutes, Marisa collects $$$12$$$ mushrooms.It can be shown that it is impossible to collect more than $$$12$$$ mushrooms.Test case 2:This is one of her possible moving path:$$$2 \rightarrow 3 \rightarrow 2 \rightarrow 1 \rightarrow 2 \rightarrow 3 \rightarrow 4 \rightarrow 5$$$It can be shown that it is impossible to collect more than $$$37$$$ mushrooms.
Java 8
standard input
[ "brute force", "greedy" ]
e092d58ac58e1e41d17be946128234e5
Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains two integers $$$n$$$, $$$k$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$, $$$1\le k \le 10^9$$$) — the number of positions with mushrooms and the time Marisa has, respectively. The second line of each test case contains $$$n$$$ integers $$$a_1,a_2,\ldots,a_n$$$ ($$$1 \le a_i \le 10^9$$$) — the initial number of mushrooms on point $$$1,2,\ldots,n$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$.
1,600
For each test case, print the maximum number of mushrooms Marisa can pick after $$$k$$$ minutes.
standard output
PASSED
26fc7c4fbf84a34f2b2f3293aa09384b
train_108.jsonl
1654266900
The enchanted forest got its name from the magical mushrooms growing here. They may cause illusions and generally should not be approached.—Perfect Memento in Strict SenseMarisa comes to pick mushrooms in the Enchanted Forest. The Enchanted forest can be represented by $$$n$$$ points on the $$$X$$$-axis numbered $$$1$$$ through $$$n$$$. Before Marisa started, her friend, Patchouli, used magic to detect the initial number of mushroom on each point, represented by $$$a_1,a_2,\ldots,a_n$$$.Marisa can start out at any point in the forest on minute $$$0$$$. Each minute, the followings happen in order: She moves from point $$$x$$$ to $$$y$$$ ($$$|x-y|\le 1$$$, possibly $$$y=x$$$). She collects all mushrooms on point $$$y$$$. A new mushroom appears on each point in the forest. Note that she cannot collect mushrooms on minute $$$0$$$.Now, Marisa wants to know the maximum number of mushrooms she can pick after $$$k$$$ minutes.
256 megabytes
import java.util.Scanner; public class main { static long find_sum(long[] A,int k){ if (k>A.length){ long ans=0; for (int i=0;i<A.length;i++){ ans+=A[i]; } ans+=(((long) (A.length) *(k-1+k-A.length))/2); return ans; } long[] anss= new long[A.length]; long ans=0; for (int i=0;i<k;i++){ ans+=A[i]+i; anss[i]=0; } anss[k-1]=ans; for (int i=k;i<A.length;i++){ anss[i]=anss[i-1]+A[i]-A[i-k]; ans=Math.max(ans,anss[i]); } return ans; } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int t= scanner.nextInt(); for (int i=0;i<t;i++){ int n= scanner.nextInt(); int k=scanner.nextInt(); long[] A= new long[n]; for (int j=0;j<n;j++){ A[j]= scanner.nextInt(); } System.out.println(find_sum(A,k)); } } }
Java
["4\n\n5 2\n\n5 6 1 2 3\n\n5 7\n\n5 6 1 2 3\n\n1 2\n\n999999\n\n5 70000\n\n1000000000 1000000000 1000000000 1000000000 1000000000"]
2 seconds
["12\n37\n1000000\n5000349985"]
NoteTest case 1:Marisa can start at $$$x=2$$$. In the first minute, she moves to $$$x=1$$$ and collect $$$5$$$ mushrooms. The number of mushrooms will be $$$[1,7,2,3,4]$$$. In the second minute, she moves to $$$x=2$$$ and collects $$$7$$$ mushrooms. The numbers of mushrooms will be $$$[2,1,3,4,5]$$$. After $$$2$$$ minutes, Marisa collects $$$12$$$ mushrooms.It can be shown that it is impossible to collect more than $$$12$$$ mushrooms.Test case 2:This is one of her possible moving path:$$$2 \rightarrow 3 \rightarrow 2 \rightarrow 1 \rightarrow 2 \rightarrow 3 \rightarrow 4 \rightarrow 5$$$It can be shown that it is impossible to collect more than $$$37$$$ mushrooms.
Java 8
standard input
[ "brute force", "greedy" ]
e092d58ac58e1e41d17be946128234e5
Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains two integers $$$n$$$, $$$k$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$, $$$1\le k \le 10^9$$$) — the number of positions with mushrooms and the time Marisa has, respectively. The second line of each test case contains $$$n$$$ integers $$$a_1,a_2,\ldots,a_n$$$ ($$$1 \le a_i \le 10^9$$$) — the initial number of mushrooms on point $$$1,2,\ldots,n$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$.
1,600
For each test case, print the maximum number of mushrooms Marisa can pick after $$$k$$$ minutes.
standard output
PASSED
c43f10f7a3bb77d2de99a980e8b6cbfa
train_108.jsonl
1654266900
The enchanted forest got its name from the magical mushrooms growing here. They may cause illusions and generally should not be approached.—Perfect Memento in Strict SenseMarisa comes to pick mushrooms in the Enchanted Forest. The Enchanted forest can be represented by $$$n$$$ points on the $$$X$$$-axis numbered $$$1$$$ through $$$n$$$. Before Marisa started, her friend, Patchouli, used magic to detect the initial number of mushroom on each point, represented by $$$a_1,a_2,\ldots,a_n$$$.Marisa can start out at any point in the forest on minute $$$0$$$. Each minute, the followings happen in order: She moves from point $$$x$$$ to $$$y$$$ ($$$|x-y|\le 1$$$, possibly $$$y=x$$$). She collects all mushrooms on point $$$y$$$. A new mushroom appears on each point in the forest. Note that she cannot collect mushrooms on minute $$$0$$$.Now, Marisa wants to know the maximum number of mushrooms she can pick after $$$k$$$ minutes.
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; public class A { FastScanner in; PrintWriter out; boolean systemIO = true; int mod = 1000000007; public int mult(int x, int y) { return (int) (x * 1L * y % mod); } public int sum(int x, int y) { if (x + y >= mod) { return x + y - mod; } return x + y; } public int diff(int x, int y) { if (x >= y) { return x - y; } return x - y + mod; } public int div(int x, int y) { return mult(x, modInv(y)); } int[][] res = new int[2][2]; public void mult(int[][] a, int[][] b) { for (int i = 0; i < 2; i++) { for (int j = 0; j < 2; j++) { res[i][j] = 0; for (int k = 0; k < 2; k++) { res[i][j] = sum(res[i][j], mult(a[i][k], b[k][j])); } } } } public int pow(int x, long p) { if (p == 0) { return 1; } int ans = pow(x, p / 2); ans = mult(ans, ans); if ((p & 1) > 0) { ans = mult(ans, x); } return ans; } int[][] ans = { { 1, 0 }, { 0, 1 } }; public void pow(int[][] x, long p) { if (p == 0) { ans[0][0] = ans[1][1] = 1; ans[0][1] = ans[1][0] = 0; return; } pow(x, p / 2); mult(ans, ans); for (int i = 0; i < ans.length; i++) { for (int j = 0; j < ans.length; j++) { ans[i][j] = res[i][j]; } } if ((p & 1) > 0) { mult(ans, x); for (int i = 0; i < ans.length; i++) { for (int j = 0; j < ans.length; j++) { ans[i][j] = res[i][j]; } } } } public int modInv(int x) { return pow(x, mod - 2); } public long calc(int[] a, int x) { long ans = 0; long prev = 0; for (int i = x + 1; i < a.length; i++) { ans += (prev + a[i]) / a[i]; prev = (prev + a[i]) / a[i] * a[i]; } prev = 0; for (int i = x - 1; i >= 0; --i) { ans += (prev + a[i]) / a[i]; prev = (prev + a[i]) / a[i] * a[i]; } return ans; } public class Vertex implements Comparable<Vertex> { int r; int theta; public Vertex(int r, int theta) { this.r = r; this.theta = theta; } @Override public int compareTo(A.Vertex o) { if (r != o.r) { return r - o.r; } return theta - o.theta; } } public boolean dfs(int v) { if (v == 1) { return true; } used[v] = true; for (int i : to[v]) { if (!used[i] && dfs(i)) { return true; } } return false; } boolean[] used; ArrayList<Integer>[] to; public void solve() { f : for (int qwerty = in.nextInt(); qwerty > 0; --qwerty) { int n = in.nextInt(); int k = in.nextInt(); int[] a = new int[n]; for (int i = 0; i < a.length; i++) { a[i] = in.nextInt(); } long[] prefSum = new long[n + 1]; for (int i = 0; i < n; i++) { prefSum[i + 1] = prefSum[i] + a[i]; } int len = Math.min(n, k); long ans = len * (k - 1L) - len * (len - 1L) / 2; long max = 0; for (int i = 0; i + len <= n; i++) { max = Math.max(max, prefSum[i + len] - prefSum[i]); } out.println(ans + max); } } public void add(HashMap<Integer, Integer> map, int x) { if (map.containsKey(x)) { map.put(x, map.get(x) + 1); } else { map.put(x, 1); } } public void run() { try { if (systemIO) { in = new FastScanner(System.in); out = new PrintWriter(System.out); } else { in = new FastScanner(new File("input.txt")); out = new PrintWriter(new File("output.txt")); } solve(); out.close(); } catch (IOException e) { e.printStackTrace(); } } class FastScanner { BufferedReader br; StringTokenizer st; FastScanner(File f) { try { br = new BufferedReader(new FileReader(f)); } catch (FileNotFoundException e) { e.printStackTrace(); } } FastScanner(InputStream f) { br = new BufferedReader(new InputStreamReader(f)); } String nextLine() { try { return br.readLine(); } catch (IOException e) { return null; } } 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()); } } // AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA public static void main(String[] arg) { new A().run(); } }
Java
["4\n\n5 2\n\n5 6 1 2 3\n\n5 7\n\n5 6 1 2 3\n\n1 2\n\n999999\n\n5 70000\n\n1000000000 1000000000 1000000000 1000000000 1000000000"]
2 seconds
["12\n37\n1000000\n5000349985"]
NoteTest case 1:Marisa can start at $$$x=2$$$. In the first minute, she moves to $$$x=1$$$ and collect $$$5$$$ mushrooms. The number of mushrooms will be $$$[1,7,2,3,4]$$$. In the second minute, she moves to $$$x=2$$$ and collects $$$7$$$ mushrooms. The numbers of mushrooms will be $$$[2,1,3,4,5]$$$. After $$$2$$$ minutes, Marisa collects $$$12$$$ mushrooms.It can be shown that it is impossible to collect more than $$$12$$$ mushrooms.Test case 2:This is one of her possible moving path:$$$2 \rightarrow 3 \rightarrow 2 \rightarrow 1 \rightarrow 2 \rightarrow 3 \rightarrow 4 \rightarrow 5$$$It can be shown that it is impossible to collect more than $$$37$$$ mushrooms.
Java 8
standard input
[ "brute force", "greedy" ]
e092d58ac58e1e41d17be946128234e5
Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains two integers $$$n$$$, $$$k$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$, $$$1\le k \le 10^9$$$) — the number of positions with mushrooms and the time Marisa has, respectively. The second line of each test case contains $$$n$$$ integers $$$a_1,a_2,\ldots,a_n$$$ ($$$1 \le a_i \le 10^9$$$) — the initial number of mushrooms on point $$$1,2,\ldots,n$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$.
1,600
For each test case, print the maximum number of mushrooms Marisa can pick after $$$k$$$ minutes.
standard output
PASSED
4d5334f2dd4eed4dc23f676b3ba7a9f2
train_108.jsonl
1654266900
The enchanted forest got its name from the magical mushrooms growing here. They may cause illusions and generally should not be approached.—Perfect Memento in Strict SenseMarisa comes to pick mushrooms in the Enchanted Forest. The Enchanted forest can be represented by $$$n$$$ points on the $$$X$$$-axis numbered $$$1$$$ through $$$n$$$. Before Marisa started, her friend, Patchouli, used magic to detect the initial number of mushroom on each point, represented by $$$a_1,a_2,\ldots,a_n$$$.Marisa can start out at any point in the forest on minute $$$0$$$. Each minute, the followings happen in order: She moves from point $$$x$$$ to $$$y$$$ ($$$|x-y|\le 1$$$, possibly $$$y=x$$$). She collects all mushrooms on point $$$y$$$. A new mushroom appears on each point in the forest. Note that she cannot collect mushrooms on minute $$$0$$$.Now, Marisa wants to know the maximum number of mushrooms she can pick after $$$k$$$ minutes.
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 A { 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(),k=sc.nextInt(); int[]a=new int[n]; long s=0l; for(int i=0;i<n;i++) { a[i]=sc.nextInt(); s+=a[i]; } long ans=0l; if(k<=n) { long mxS=find(a,k); ans=mxS+1l*k*(k-1)/2; out.println(ans);continue; } ans=s+k-n+1l*(k-n+1)*(n-1); ans+=1l*(n-2)*(n-1)/2; out.println(ans); } out.close(); } private static long find(int[] a, int k) { long mxs=0; for(int i=0;i<k;i++) { mxs+=a[i]; } long cur=mxs; for(int i=k;i<a.length;i++) { cur+=a[i]; cur-=a[i-k]; mxs=Math.max(mxs, cur); } return mxs; } 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
["4\n\n5 2\n\n5 6 1 2 3\n\n5 7\n\n5 6 1 2 3\n\n1 2\n\n999999\n\n5 70000\n\n1000000000 1000000000 1000000000 1000000000 1000000000"]
2 seconds
["12\n37\n1000000\n5000349985"]
NoteTest case 1:Marisa can start at $$$x=2$$$. In the first minute, she moves to $$$x=1$$$ and collect $$$5$$$ mushrooms. The number of mushrooms will be $$$[1,7,2,3,4]$$$. In the second minute, she moves to $$$x=2$$$ and collects $$$7$$$ mushrooms. The numbers of mushrooms will be $$$[2,1,3,4,5]$$$. After $$$2$$$ minutes, Marisa collects $$$12$$$ mushrooms.It can be shown that it is impossible to collect more than $$$12$$$ mushrooms.Test case 2:This is one of her possible moving path:$$$2 \rightarrow 3 \rightarrow 2 \rightarrow 1 \rightarrow 2 \rightarrow 3 \rightarrow 4 \rightarrow 5$$$It can be shown that it is impossible to collect more than $$$37$$$ mushrooms.
Java 8
standard input
[ "brute force", "greedy" ]
e092d58ac58e1e41d17be946128234e5
Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains two integers $$$n$$$, $$$k$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$, $$$1\le k \le 10^9$$$) — the number of positions with mushrooms and the time Marisa has, respectively. The second line of each test case contains $$$n$$$ integers $$$a_1,a_2,\ldots,a_n$$$ ($$$1 \le a_i \le 10^9$$$) — the initial number of mushrooms on point $$$1,2,\ldots,n$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$.
1,600
For each test case, print the maximum number of mushrooms Marisa can pick after $$$k$$$ minutes.
standard output
PASSED
ede9a89b68cf32150cfbe2d5d70ccdb6
train_108.jsonl
1654266900
The enchanted forest got its name from the magical mushrooms growing here. They may cause illusions and generally should not be approached.—Perfect Memento in Strict SenseMarisa comes to pick mushrooms in the Enchanted Forest. The Enchanted forest can be represented by $$$n$$$ points on the $$$X$$$-axis numbered $$$1$$$ through $$$n$$$. Before Marisa started, her friend, Patchouli, used magic to detect the initial number of mushroom on each point, represented by $$$a_1,a_2,\ldots,a_n$$$.Marisa can start out at any point in the forest on minute $$$0$$$. Each minute, the followings happen in order: She moves from point $$$x$$$ to $$$y$$$ ($$$|x-y|\le 1$$$, possibly $$$y=x$$$). She collects all mushrooms on point $$$y$$$. A new mushroom appears on each point in the forest. Note that she cannot collect mushrooms on minute $$$0$$$.Now, Marisa wants to know the maximum number of mushrooms she can pick after $$$k$$$ minutes.
256 megabytes
import java.util.*; import java.io.*; import java.math.*; public class Main { static FastReader sc=new FastReader(); static PrintWriter out=new PrintWriter(System.out); 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 ArrayList<ArrayList<Integer>> graph; static long fact[]; static pair 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(); long k=L(); long a[]=IL(n); if(k<n){ int x=0,y=(int)k; long sum=0; for(int i=0;i<k;i++){ sum+=a[i]; } long temp=sum; while(y<n){ temp-=a[x]; temp+=a[y]; x++; y++; sum=max(sum,temp); } k--; long z=k*(k+1)/2; out.println(sum+z); }else{ long sum=suminA(a); long times=k-n; n--; sum+=times*(n+1)+(1L*n*(n+1)/2); out.println(sum); } } 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.a==p2.a) // return 0; // else if(p1.a<p2.a) // return 1; // else // return -1; // } } public static void setGraph(int n,int m) { 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); } } public static int dfs(int s,boolean v[],int cnt[]) { v[s]=true; for(int i:graph[s]){ if(!v[i]){ int p=dfs(i,v,cnt); cnt[s]+=p; } } return cnt[s]; } //LOWER_BOUND and UPPER_BOUND functions //It returns answer according to zero based indexing. public static int lower_bound(long arr[],long X,int start, int end) //start=0,end=n-1 { if(start>end)return -1; if(arr[arr.length-1]<X)return end; if(arr[0]>X)return -1; int left=start,right=end; while(left<right){ int mid=(left+right)/2; // if(arr[mid]==X){ //Returns last index of lower bound value. // if(mid<end && arr[mid+1]==X){ // left=mid+1; // }else{ // return mid; // } // } if(arr[mid]==X){ //Returns first index of lower bound value. if(mid>start && arr[mid-1]==X){ right=mid-1; }else{ return mid; } } else if(arr[mid]>X){ if(mid>start && arr[mid-1]<X){ return mid-1; }else{ right=mid-1; } }else{ if(mid<end && arr[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(int a[],int si,int ss,int se) { if(ss==se){ // seg[si]=new pair(a[ss],ss); seg[si].a=ss; seg[si].b=ss; return; } int mid=(ss+se)/2; buildTree(a,2*si+1,ss,mid); buildTree(a,2*si+2,mid+1,se); if(a[seg[2*si+1].a] <= a[seg[2*si+2].a]){ seg[si].a=seg[2*si+1].a; }else{ seg[si].a=seg[2*si+2].a; } if(a[seg[2*si+1].b] >= a[seg[2*si+2].b]){ seg[si].b=seg[2*si+1].b; }else{ seg[si].b=seg[2*si+2].b; } } 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 int query1(int a[],int si,int ss,int se,int qs,int qe)// return min { if(qs>se || qe<ss)return -1; if(ss>=qs && se<=qe)return seg[si].a; int mid=(ss+se)/2; int p1=query1(a,2*si+1,ss,mid,qs,qe); int p2=query1(a,2*si+2,mid+1,se,qs,qe); // return min(p1,p2); if(p1==-1 && p2==-1)return -1; else if(p1==-1)return p2; else if(p2==-1)return p1; else{ if(a[p1]<=a[p2]){ return p1; }else{ return p2; } } } public static int query2(int a[],int si,int ss,int se,int qs,int qe)//return max { if(qs>se || qe<ss)return -1; if(ss>=qs && se<=qe)return seg[si].b; int mid=(ss+se)/2; int p1=query2(a,2*si+1,ss,mid,qs,qe); int p2=query2(a,2*si+2,mid+1,se,qs,qe); if(p1==-1 && p2==-1)return -1; else if(p1==-1)return p2; else if(p2==-1)return p1; else{ if(a[p1]>=a[p2]){ return p1; }else{ return 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 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 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 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 HashMap<Integer,Integer> primeFact(int a) { // HashSet<Long> arr=new HashSet<>(); HashMap<Integer,Integer> hm=new HashMap<>(); int p=0; while(a%2==0){ // arr.add(2L); p++; a=a/2; } hm.put(2,hm.getOrDefault(2,0)+p); for(int i=3;i*i<=a;i+=2){ p=0; while(a%i==0){ // arr.add(i); p++; a=a/i; } hm.put(i,hm.getOrDefault(i,0)+p); } if(a>2){ // arr.add(a); hm.put(a,hm.getOrDefault(a,0)+1); } // return arr; return hm; } 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(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 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;} //end public static int[] I(int n){int a[]=new int[n];for(int i=0;i<n;i++){a[i]=I();}return a;} public static long[] IL(int n){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(){return sc.I();} public static long L(){return sc.L();} public static String S(){return sc.S();} public static double D(){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
["4\n\n5 2\n\n5 6 1 2 3\n\n5 7\n\n5 6 1 2 3\n\n1 2\n\n999999\n\n5 70000\n\n1000000000 1000000000 1000000000 1000000000 1000000000"]
2 seconds
["12\n37\n1000000\n5000349985"]
NoteTest case 1:Marisa can start at $$$x=2$$$. In the first minute, she moves to $$$x=1$$$ and collect $$$5$$$ mushrooms. The number of mushrooms will be $$$[1,7,2,3,4]$$$. In the second minute, she moves to $$$x=2$$$ and collects $$$7$$$ mushrooms. The numbers of mushrooms will be $$$[2,1,3,4,5]$$$. After $$$2$$$ minutes, Marisa collects $$$12$$$ mushrooms.It can be shown that it is impossible to collect more than $$$12$$$ mushrooms.Test case 2:This is one of her possible moving path:$$$2 \rightarrow 3 \rightarrow 2 \rightarrow 1 \rightarrow 2 \rightarrow 3 \rightarrow 4 \rightarrow 5$$$It can be shown that it is impossible to collect more than $$$37$$$ mushrooms.
Java 8
standard input
[ "brute force", "greedy" ]
e092d58ac58e1e41d17be946128234e5
Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains two integers $$$n$$$, $$$k$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$, $$$1\le k \le 10^9$$$) — the number of positions with mushrooms and the time Marisa has, respectively. The second line of each test case contains $$$n$$$ integers $$$a_1,a_2,\ldots,a_n$$$ ($$$1 \le a_i \le 10^9$$$) — the initial number of mushrooms on point $$$1,2,\ldots,n$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$.
1,600
For each test case, print the maximum number of mushrooms Marisa can pick after $$$k$$$ minutes.
standard output
PASSED
812a124c1e4ad772822fd21554cf416f
train_108.jsonl
1654266900
The enchanted forest got its name from the magical mushrooms growing here. They may cause illusions and generally should not be approached.—Perfect Memento in Strict SenseMarisa comes to pick mushrooms in the Enchanted Forest. The Enchanted forest can be represented by $$$n$$$ points on the $$$X$$$-axis numbered $$$1$$$ through $$$n$$$. Before Marisa started, her friend, Patchouli, used magic to detect the initial number of mushroom on each point, represented by $$$a_1,a_2,\ldots,a_n$$$.Marisa can start out at any point in the forest on minute $$$0$$$. Each minute, the followings happen in order: She moves from point $$$x$$$ to $$$y$$$ ($$$|x-y|\le 1$$$, possibly $$$y=x$$$). She collects all mushrooms on point $$$y$$$. A new mushroom appears on each point in the forest. Note that she cannot collect mushrooms on minute $$$0$$$.Now, Marisa wants to know the maximum number of mushrooms she can pick after $$$k$$$ minutes.
256 megabytes
import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.BitSet; import java.util.Calendar; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.PriorityQueue; import java.util.SortedSet; import java.util.Stack; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.TreeSet; /** * # * * @author pttrung */ public class A_Round_796_Div1 { public static long MOD = 1000000007; public static void main(String[] args) throws FileNotFoundException { // PrintWriter out = new PrintWriter(new FileOutputStream(new File( // "output.txt"))); PrintWriter out = new PrintWriter(System.out); Scanner in = new Scanner(); int T = in.nextInt(); for (int Z = 0; Z < T; Z++) { long n = in.nextInt(); long k = in.nextInt(); long[] data = new long[(int) n]; long total = 0; for (int i = 0; i < n; i++) { data[i] = in.nextInt(); total += data[i]; } if (k > n) { long re = 0; if (k % n != 0) { long tmp = k % n; long left = n - tmp; re += tmp * (tmp - 1) / 2 + tmp * (tmp + 1) / 2; total += tmp * left; k -= tmp; } re += total + (n * (n - 1) / 2) + ((k / n) - 1) * cal(n); out.println(re); continue; } long[] dp = new long[(int) n]; dp[0] = data[0]; for (int i = 1; i < n; i++) { dp[i] = data[i] + dp[i - 1]; } long re = 0; for (int i = (int) k - 1; i < n; i++) { re = Long.max(re, dp[i] - (i >= k ? dp[i - (int) k] : 0) + k * (k - 1L) / 2L); } out.println(re); } out.close(); } static long cal(long n) { return n * (n + 1) / 2 + n * (n - 1) / 2; } static int find(int index, int[] u) { if (u[index] != index) { return u[index] = find(u[index], u); } return index; } static int abs(int a) { return a < 0 ? -a : a; } public static int[] KMP(String val) { int i = 0; int j = -1; int[] result = new int[val.length() + 1]; result[0] = -1; while (i < val.length()) { while (j >= 0 && val.charAt(j) != val.charAt(i)) { j = result[j]; } j++; i++; result[i] = j; } return result; } public static boolean nextPer(int[] data) { int i = data.length - 1; while (i > 0 && data[i] < data[i - 1]) { i--; } if (i == 0) { return false; } int j = data.length - 1; while (data[j] < data[i - 1]) { j--; } int temp = data[i - 1]; data[i - 1] = data[j]; data[j] = temp; Arrays.sort(data, i, data.length); return true; } public static int digit(long n) { int result = 0; while (n > 0) { n /= 10; result++; } return result; } public static double dist(long a, long b, long x, long y) { double val = (b - a) * (b - a) + (x - y) * (x - y); val = Math.sqrt(val); double other = x * x + a * a; other = Math.sqrt(other); return val + other; } public static class Point { int x; int y; public Point(int start, int end) { this.x = start; this.y = end; } public String toString() { return x + " " + y; } } public static class FT { long[] data; FT(int n) { data = new long[n]; } public void update(int index, long value) { while (index < data.length) { data[index] += value; index += (index & (-index)); } } public long get(int index) { long result = 0; while (index > 0) { result += data[index]; index -= (index & (-index)); } return result; } } public static long gcd(long a, long b) { if (b == 0) { return a; } return gcd(b, a % b); } public static long pow(long a, int b) { if (b == 0) { return 1; } if (b == 1) { return a; } long val = pow(a, b / 2); if (b % 2 == 0) { return val * val; } else { return val * (val * a); } } static class Scanner { BufferedReader br; StringTokenizer st; public Scanner() throws FileNotFoundException { // System.setOut(new PrintStream(new BufferedOutputStream(System.out), true)); br = new BufferedReader(new InputStreamReader(System.in)); //br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("input.txt")))); } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { throw new RuntimeException(); } } return st.nextToken(); } public long nextLong() { return Long.parseLong(next()); } public int nextInt() { return Integer.parseInt(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String nextLine() { st = null; try { return br.readLine(); } catch (Exception e) { throw new RuntimeException(); } } public boolean endLine() { try { String next = br.readLine(); while (next != null && next.trim().isEmpty()) { next = br.readLine(); } if (next == null) { return true; } st = new StringTokenizer(next); return st.hasMoreTokens(); } catch (Exception e) { throw new RuntimeException(); } } } }
Java
["4\n\n5 2\n\n5 6 1 2 3\n\n5 7\n\n5 6 1 2 3\n\n1 2\n\n999999\n\n5 70000\n\n1000000000 1000000000 1000000000 1000000000 1000000000"]
2 seconds
["12\n37\n1000000\n5000349985"]
NoteTest case 1:Marisa can start at $$$x=2$$$. In the first minute, she moves to $$$x=1$$$ and collect $$$5$$$ mushrooms. The number of mushrooms will be $$$[1,7,2,3,4]$$$. In the second minute, she moves to $$$x=2$$$ and collects $$$7$$$ mushrooms. The numbers of mushrooms will be $$$[2,1,3,4,5]$$$. After $$$2$$$ minutes, Marisa collects $$$12$$$ mushrooms.It can be shown that it is impossible to collect more than $$$12$$$ mushrooms.Test case 2:This is one of her possible moving path:$$$2 \rightarrow 3 \rightarrow 2 \rightarrow 1 \rightarrow 2 \rightarrow 3 \rightarrow 4 \rightarrow 5$$$It can be shown that it is impossible to collect more than $$$37$$$ mushrooms.
Java 8
standard input
[ "brute force", "greedy" ]
e092d58ac58e1e41d17be946128234e5
Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains two integers $$$n$$$, $$$k$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$, $$$1\le k \le 10^9$$$) — the number of positions with mushrooms and the time Marisa has, respectively. The second line of each test case contains $$$n$$$ integers $$$a_1,a_2,\ldots,a_n$$$ ($$$1 \le a_i \le 10^9$$$) — the initial number of mushrooms on point $$$1,2,\ldots,n$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$.
1,600
For each test case, print the maximum number of mushrooms Marisa can pick after $$$k$$$ minutes.
standard output
PASSED
be25aa2c409612d8b5b60bd3ea24f15d
train_108.jsonl
1654266900
The enchanted forest got its name from the magical mushrooms growing here. They may cause illusions and generally should not be approached.—Perfect Memento in Strict SenseMarisa comes to pick mushrooms in the Enchanted Forest. The Enchanted forest can be represented by $$$n$$$ points on the $$$X$$$-axis numbered $$$1$$$ through $$$n$$$. Before Marisa started, her friend, Patchouli, used magic to detect the initial number of mushroom on each point, represented by $$$a_1,a_2,\ldots,a_n$$$.Marisa can start out at any point in the forest on minute $$$0$$$. Each minute, the followings happen in order: She moves from point $$$x$$$ to $$$y$$$ ($$$|x-y|\le 1$$$, possibly $$$y=x$$$). She collects all mushrooms on point $$$y$$$. A new mushroom appears on each point in the forest. Note that she cannot collect mushrooms on minute $$$0$$$.Now, Marisa wants to know the maximum number of mushrooms she can pick after $$$k$$$ minutes.
256 megabytes
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.math.BigInteger; import java.util.*; import java.util.concurrent.ThreadLocalRandom; public class c731{ public static void main(String[] args) throws IOException{ BufferedWriter out = new BufferedWriter( new OutputStreamWriter(System.out)); BufferedReader br = new BufferedReader( new InputStreamReader(System.in)); PrintWriter pt = new PrintWriter(System.out); FastReader sc = new FastReader(); int o1 = sc.nextInt(); for(int t1 = 0 ; t1<o1;t1++) { int n = sc.nextInt(); int k = sc.nextInt(); long[] arr = new long[n]; for(int i = 0 ; i<n;i++) { arr[i] = sc.nextLong(); } long[] psum = new long[n+1]; for(int i = 1 ; i<=n;i++) { psum[i] = psum[i-1] + arr[i-1]; } if(k<=n) { long max = 0; for(int i= 0 ; i<=n-k;i++) { max = Math.max(psum[i+k] - psum[i],max); } long v = (long)k*(k-1)/2; System.out.println(max + v); }else { int r = k - n; long ans = psum[n] + (long)k*(k-1)/2 - (long)r*(r+1)/2 + r; System.out.println(ans); } } } //------------------------------------------------------------------------------------------------------------------------------------------------ public static ArrayList<Long> printDivisors(long n) { ArrayList<Long> al = new ArrayList<>(); for (long i=1; i<=Math.sqrt(n); i++) { if (n%i==0) { if (n/i == i)al.add(i); else { al.add(i); al.add(n/i); } } } return al; } public static boolean palin(String s) { int n = s.length(); int i = 0; int j = n-1; while(i<=j) { if(s.charAt(i)!=s.charAt(j)) { return false; } i++; j--; } return true; } public static boolean check(int[] arr , int n , int v , int l ) { int x = v/2; int y = v/2; // System.out.println(x + " " + y); if(v%2 == 1 ) { x++; } for(int i = 0 ; i<n;i++) { int d = l - arr[i]; int c = Math.min(d/2, y); y -= c; arr[i] -= c*2; if(arr[i] > x) { return false; } x -= arr[i]; } return true; } public static int cnt_set(long x) { long v = 1l; int c =0; int f = 0; while(v<=x) { if((v&x)!=0) { c++; } v = v<<1; } return c; } public static int lis(int[] arr,int[] dp) { int n = arr.length; ArrayList<Integer> al = new ArrayList<Integer>(); al.add(arr[0]); dp[0]= 1; for(int i = 1 ; i<n;i++) { int x = al.get(al.size()-1); if(arr[i]>x) { al.add(arr[i]); }else { int v = lower_bound(al, 0, al.size(), arr[i]); // System.out.println(v); al.set(v, arr[i]); } dp[i] = al.size(); } //return al.size(); return al.size(); } public static int lis2(int[] arr,int[] dp) { int n = arr.length; ArrayList<Integer> al = new ArrayList<Integer>(); al.add(-arr[n-1]); dp[n-1] = 1; // System.out.println(al); for(int i = n-2 ; i>=0;i--) { int x = al.get(al.size()-1); // System.out.println(-arr[i] + " " + i + " " + x); if((-arr[i])>x) { al.add(-arr[i]); }else { int v = lower_bound(al, 0, al.size(), -arr[i]); // System.out.println(v); al.set(v, -arr[i]); } dp[i] = al.size(); } //return al.size(); return al.size(); } static int cntDivisors(int n){ int cnt = 0; for (int i=1; i<=Math.sqrt(n); i++) { if (n%i==0) { if (n/i == i) cnt++; else cnt+=2; } } return cnt; } public static long power(long x, long y, long p){ long res = 1; x = x % p; if (x == 0) return 0; while (y > 0){ if ((y & 1) != 0) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return res; } public static long ncr(long[] fac, int n , int r , long m) { if(r>n) { return 0; } return fac[n]*(modInverse(fac[r], m))%m *(modInverse(fac[n-r], m))%m; } public static int lower_bound(ArrayList<Integer> arr,int lo , int hi, int k) { int s=lo; int e=hi; while (s !=e) { int mid = s+e>>1; if (arr.get(mid) <k) { s=mid+1; } else { e=mid; } } if(s==arr.size()) { return -1; } return s; } public static int upper_bound(ArrayList<Integer> arr,int lo , int hi, int k) { int s=lo; int e=hi; while (s !=e) { int mid = s+e>>1; if (arr.get(mid) <=k) { s=mid+1; } else { e=mid; } } if(s==arr.size()) { return -1; } return s; } // ----------------------------------------------------------------------------------------------------------------------------------------------- public static long gcd(long a, long b){ if (a == 0) return b; return gcd(b % a, a); } //-------------------------------------------------------------------------------------------------------------------------------------------------------- public static long modInverse(long a, long m){ long m0 = m; long y = 0, x = 1; if (m == 1) return 0; while (a > 1) { // q is quotient long q = a / m; long t = m; // m is remainder now, process // same as Euclid's algo m = a % m; a = t; t = y; // Update x and y y = x - q * y; x = t; } // Make x positive if (x < 0) x += m0; return x; } //_________________________________________________________________________________________________________________________________________________________________ // private static int[] parent; // private static int[] size; public static int find(int[] parent, int u) { while(u != parent[u]) { parent[u] = parent[parent[u]]; u = parent[u]; } return u; } private static void union(int[] parent,int[] size,int u, int v) { int rootU = find(parent,u); int rootV = find(parent,v); if(rootU == rootV) { return; } if(size[rootU] < size[rootV]) { parent[rootU] = rootV; size[rootV] += size[rootU]; } else { parent[rootV] = rootU; size[rootU] += size[rootV]; } } //----------------------------------------------------------------------------------------------------------------------------------- //segment tree //for finding minimum in range public static void build(long [] seg,long []arr,int idx, int lo , int hi) { if(lo == hi) { seg[idx] = arr[lo]; return; } int mid = (lo + hi)/2; build(seg,arr,2*idx+1, lo, mid); build(seg,arr,idx*2+2, mid +1, hi); seg[idx] = seg[idx*2+1] + seg[idx*2+2]; } //for finding minimum in range public static long query(long[]seg,int idx , int lo , int hi , int l , int r) { if(lo>=l && hi<=r) { return seg[idx]; } if(hi<l || lo>r) { return 0; } int mid = (lo + hi)/2; long left = query(seg,idx*2 +1, lo, mid, l, r); long right = query(seg,idx*2 + 2, mid + 1, hi, l, r); return left + right; } public static void build2(long [] seg,long []arr,int idx, int lo , int hi) { if(lo == hi) { seg[idx] = arr[lo]; return; } int mid = (lo + hi)/2; build2(seg,arr,2*idx+1, lo, mid); build2(seg,arr,idx*2+2, mid +1, hi); seg[idx] = Math.max(seg[idx*2+1],seg[idx*2+2]); } //for finding minimum in range public static long query2(long[]seg,int idx , int lo , int hi , int l , int r) { if(lo>=l && hi<=r) { return seg[idx]; } if(hi<l || lo>r) { return Long.MIN_VALUE; } int mid = (lo + hi)/2; long left = query(seg,idx*2 +1, lo, mid, l, r); long right = query(seg,idx*2 + 2, mid + 1, hi, l, r); return Math.max(left, right); } public static void update(boolean[]seg,int idx, int lo , int hi , int node , boolean val) { if(lo == hi) { seg[idx] = val; }else { int mid = (lo + hi )/2; if(node<=mid && node>=lo) { update(seg, idx * 2 +1, lo, mid, node, val); }else { update(seg, idx*2 + 2, mid + 1, hi, node, val); } seg[idx] = seg[idx*2 + 1] & seg[idx*2 + 2]; } // } //--------------------------------------------------------------------------------------------------------------------------------------- // //static void shuffleArray(int[] ar) //{ // // If running on Java 6 or older, use `new Random()` on RHS here // Random rnd = ThreadLocalRandom.current(); // for (int i = ar.length - 1; i > 0; i--) // { // int index = rnd.nextInt(i + 1); // // Simple swap // int a = ar[index]; // ar[index] = ar[i]; // ar[i] = a; // } //} // static void shuffleArray(coup[] ar) // { // // If running on Java 6 or older, use `new Random()` on RHS here // Random rnd = ThreadLocalRandom.current(); // for (int i = ar.length - 1; i > 0; i--) // { // int index = rnd.nextInt(i + 1); // // Simple swap // coup a = ar[index]; // ar[index] = ar[i]; // ar[i] = a; // } // } //----------------------------------------------------------------------------------------------------------------------------------------------------------- } 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 coup{ int a; int b; public coup(int a , int b) { this.a = a; this.b = b; } } class dob{ int a; double b; public dob(int a , double b) { this.a = a; this.b = b; } } class trip{ int a; int b; int c; public trip(int a , int b, int c) { this.a = a; this.b = b; this.c = c; } }
Java
["4\n\n5 2\n\n5 6 1 2 3\n\n5 7\n\n5 6 1 2 3\n\n1 2\n\n999999\n\n5 70000\n\n1000000000 1000000000 1000000000 1000000000 1000000000"]
2 seconds
["12\n37\n1000000\n5000349985"]
NoteTest case 1:Marisa can start at $$$x=2$$$. In the first minute, she moves to $$$x=1$$$ and collect $$$5$$$ mushrooms. The number of mushrooms will be $$$[1,7,2,3,4]$$$. In the second minute, she moves to $$$x=2$$$ and collects $$$7$$$ mushrooms. The numbers of mushrooms will be $$$[2,1,3,4,5]$$$. After $$$2$$$ minutes, Marisa collects $$$12$$$ mushrooms.It can be shown that it is impossible to collect more than $$$12$$$ mushrooms.Test case 2:This is one of her possible moving path:$$$2 \rightarrow 3 \rightarrow 2 \rightarrow 1 \rightarrow 2 \rightarrow 3 \rightarrow 4 \rightarrow 5$$$It can be shown that it is impossible to collect more than $$$37$$$ mushrooms.
Java 8
standard input
[ "brute force", "greedy" ]
e092d58ac58e1e41d17be946128234e5
Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains two integers $$$n$$$, $$$k$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$, $$$1\le k \le 10^9$$$) — the number of positions with mushrooms and the time Marisa has, respectively. The second line of each test case contains $$$n$$$ integers $$$a_1,a_2,\ldots,a_n$$$ ($$$1 \le a_i \le 10^9$$$) — the initial number of mushrooms on point $$$1,2,\ldots,n$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$.
1,600
For each test case, print the maximum number of mushrooms Marisa can pick after $$$k$$$ minutes.
standard output
PASSED
5216ba1c4c691d63dc7b1eab84d5668a
train_108.jsonl
1654266900
The enchanted forest got its name from the magical mushrooms growing here. They may cause illusions and generally should not be approached.—Perfect Memento in Strict SenseMarisa comes to pick mushrooms in the Enchanted Forest. The Enchanted forest can be represented by $$$n$$$ points on the $$$X$$$-axis numbered $$$1$$$ through $$$n$$$. Before Marisa started, her friend, Patchouli, used magic to detect the initial number of mushroom on each point, represented by $$$a_1,a_2,\ldots,a_n$$$.Marisa can start out at any point in the forest on minute $$$0$$$. Each minute, the followings happen in order: She moves from point $$$x$$$ to $$$y$$$ ($$$|x-y|\le 1$$$, possibly $$$y=x$$$). She collects all mushrooms on point $$$y$$$. A new mushroom appears on each point in the forest. Note that she cannot collect mushrooms on minute $$$0$$$.Now, Marisa wants to know the maximum number of mushrooms she can pick after $$$k$$$ minutes.
256 megabytes
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.math.BigInteger; import java.util.*; import java.util.concurrent.ThreadLocalRandom; public class c731{ public static void main(String[] args) throws IOException{ BufferedWriter out = new BufferedWriter( new OutputStreamWriter(System.out)); BufferedReader br = new BufferedReader( new InputStreamReader(System.in)); PrintWriter pt = new PrintWriter(System.out); FastReader sc = new FastReader(); int o1 = sc.nextInt(); for(int t1 = 0 ; t1<o1;t1++) { int n = sc.nextInt(); int k = sc.nextInt(); long[] arr = new long[n]; for(int i = 0 ; i<n;i++) { arr[i] = sc.nextLong(); } long[] psum = new long[n+1]; for(int i = 1 ; i<=n;i++) { psum[i] = psum[i-1] + arr[i-1]; } if(k<=n) { long max = 0; for(int i= 0 ; i<=n-k;i++) { max = Math.max(psum[i+k] - psum[i],max); } long v = (long)k*(k-1)/2; System.out.println(max + v); }else { long ans = psum[n] + (long)n*k - (long)n*(n+1)/2; System.out.println(ans); } } } //------------------------------------------------------------------------------------------------------------------------------------------------ public static ArrayList<Long> printDivisors(long n) { ArrayList<Long> al = new ArrayList<>(); for (long i=1; i<=Math.sqrt(n); i++) { if (n%i==0) { if (n/i == i)al.add(i); else { al.add(i); al.add(n/i); } } } return al; } public static boolean palin(String s) { int n = s.length(); int i = 0; int j = n-1; while(i<=j) { if(s.charAt(i)!=s.charAt(j)) { return false; } i++; j--; } return true; } public static boolean check(int[] arr , int n , int v , int l ) { int x = v/2; int y = v/2; // System.out.println(x + " " + y); if(v%2 == 1 ) { x++; } for(int i = 0 ; i<n;i++) { int d = l - arr[i]; int c = Math.min(d/2, y); y -= c; arr[i] -= c*2; if(arr[i] > x) { return false; } x -= arr[i]; } return true; } public static int cnt_set(long x) { long v = 1l; int c =0; int f = 0; while(v<=x) { if((v&x)!=0) { c++; } v = v<<1; } return c; } public static int lis(int[] arr,int[] dp) { int n = arr.length; ArrayList<Integer> al = new ArrayList<Integer>(); al.add(arr[0]); dp[0]= 1; for(int i = 1 ; i<n;i++) { int x = al.get(al.size()-1); if(arr[i]>x) { al.add(arr[i]); }else { int v = lower_bound(al, 0, al.size(), arr[i]); // System.out.println(v); al.set(v, arr[i]); } dp[i] = al.size(); } //return al.size(); return al.size(); } public static int lis2(int[] arr,int[] dp) { int n = arr.length; ArrayList<Integer> al = new ArrayList<Integer>(); al.add(-arr[n-1]); dp[n-1] = 1; // System.out.println(al); for(int i = n-2 ; i>=0;i--) { int x = al.get(al.size()-1); // System.out.println(-arr[i] + " " + i + " " + x); if((-arr[i])>x) { al.add(-arr[i]); }else { int v = lower_bound(al, 0, al.size(), -arr[i]); // System.out.println(v); al.set(v, -arr[i]); } dp[i] = al.size(); } //return al.size(); return al.size(); } static int cntDivisors(int n){ int cnt = 0; for (int i=1; i<=Math.sqrt(n); i++) { if (n%i==0) { if (n/i == i) cnt++; else cnt+=2; } } return cnt; } public static long power(long x, long y, long p){ long res = 1; x = x % p; if (x == 0) return 0; while (y > 0){ if ((y & 1) != 0) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return res; } public static long ncr(long[] fac, int n , int r , long m) { if(r>n) { return 0; } return fac[n]*(modInverse(fac[r], m))%m *(modInverse(fac[n-r], m))%m; } public static int lower_bound(ArrayList<Integer> arr,int lo , int hi, int k) { int s=lo; int e=hi; while (s !=e) { int mid = s+e>>1; if (arr.get(mid) <k) { s=mid+1; } else { e=mid; } } if(s==arr.size()) { return -1; } return s; } public static int upper_bound(ArrayList<Integer> arr,int lo , int hi, int k) { int s=lo; int e=hi; while (s !=e) { int mid = s+e>>1; if (arr.get(mid) <=k) { s=mid+1; } else { e=mid; } } if(s==arr.size()) { return -1; } return s; } // ----------------------------------------------------------------------------------------------------------------------------------------------- public static long gcd(long a, long b){ if (a == 0) return b; return gcd(b % a, a); } //-------------------------------------------------------------------------------------------------------------------------------------------------------- public static long modInverse(long a, long m){ long m0 = m; long y = 0, x = 1; if (m == 1) return 0; while (a > 1) { // q is quotient long q = a / m; long t = m; // m is remainder now, process // same as Euclid's algo m = a % m; a = t; t = y; // Update x and y y = x - q * y; x = t; } // Make x positive if (x < 0) x += m0; return x; } //_________________________________________________________________________________________________________________________________________________________________ // private static int[] parent; // private static int[] size; public static int find(int[] parent, int u) { while(u != parent[u]) { parent[u] = parent[parent[u]]; u = parent[u]; } return u; } private static void union(int[] parent,int[] size,int u, int v) { int rootU = find(parent,u); int rootV = find(parent,v); if(rootU == rootV) { return; } if(size[rootU] < size[rootV]) { parent[rootU] = rootV; size[rootV] += size[rootU]; } else { parent[rootV] = rootU; size[rootU] += size[rootV]; } } //----------------------------------------------------------------------------------------------------------------------------------- //segment tree //for finding minimum in range public static void build(long [] seg,long []arr,int idx, int lo , int hi) { if(lo == hi) { seg[idx] = arr[lo]; return; } int mid = (lo + hi)/2; build(seg,arr,2*idx+1, lo, mid); build(seg,arr,idx*2+2, mid +1, hi); seg[idx] = seg[idx*2+1] + seg[idx*2+2]; } //for finding minimum in range public static long query(long[]seg,int idx , int lo , int hi , int l , int r) { if(lo>=l && hi<=r) { return seg[idx]; } if(hi<l || lo>r) { return 0; } int mid = (lo + hi)/2; long left = query(seg,idx*2 +1, lo, mid, l, r); long right = query(seg,idx*2 + 2, mid + 1, hi, l, r); return left + right; } public static void build2(long [] seg,long []arr,int idx, int lo , int hi) { if(lo == hi) { seg[idx] = arr[lo]; return; } int mid = (lo + hi)/2; build2(seg,arr,2*idx+1, lo, mid); build2(seg,arr,idx*2+2, mid +1, hi); seg[idx] = Math.max(seg[idx*2+1],seg[idx*2+2]); } //for finding minimum in range public static long query2(long[]seg,int idx , int lo , int hi , int l , int r) { if(lo>=l && hi<=r) { return seg[idx]; } if(hi<l || lo>r) { return Long.MIN_VALUE; } int mid = (lo + hi)/2; long left = query(seg,idx*2 +1, lo, mid, l, r); long right = query(seg,idx*2 + 2, mid + 1, hi, l, r); return Math.max(left, right); } public static void update(boolean[]seg,int idx, int lo , int hi , int node , boolean val) { if(lo == hi) { seg[idx] = val; }else { int mid = (lo + hi )/2; if(node<=mid && node>=lo) { update(seg, idx * 2 +1, lo, mid, node, val); }else { update(seg, idx*2 + 2, mid + 1, hi, node, val); } seg[idx] = seg[idx*2 + 1] & seg[idx*2 + 2]; } // } //--------------------------------------------------------------------------------------------------------------------------------------- // //static void shuffleArray(int[] ar) //{ // // If running on Java 6 or older, use `new Random()` on RHS here // Random rnd = ThreadLocalRandom.current(); // for (int i = ar.length - 1; i > 0; i--) // { // int index = rnd.nextInt(i + 1); // // Simple swap // int a = ar[index]; // ar[index] = ar[i]; // ar[i] = a; // } //} // static void shuffleArray(coup[] ar) // { // // If running on Java 6 or older, use `new Random()` on RHS here // Random rnd = ThreadLocalRandom.current(); // for (int i = ar.length - 1; i > 0; i--) // { // int index = rnd.nextInt(i + 1); // // Simple swap // coup a = ar[index]; // ar[index] = ar[i]; // ar[i] = a; // } // } //----------------------------------------------------------------------------------------------------------------------------------------------------------- } 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 coup{ int a; int b; public coup(int a , int b) { this.a = a; this.b = b; } } class dob{ int a; double b; public dob(int a , double b) { this.a = a; this.b = b; } } class trip{ int a; int b; int c; public trip(int a , int b, int c) { this.a = a; this.b = b; this.c = c; } }
Java
["4\n\n5 2\n\n5 6 1 2 3\n\n5 7\n\n5 6 1 2 3\n\n1 2\n\n999999\n\n5 70000\n\n1000000000 1000000000 1000000000 1000000000 1000000000"]
2 seconds
["12\n37\n1000000\n5000349985"]
NoteTest case 1:Marisa can start at $$$x=2$$$. In the first minute, she moves to $$$x=1$$$ and collect $$$5$$$ mushrooms. The number of mushrooms will be $$$[1,7,2,3,4]$$$. In the second minute, she moves to $$$x=2$$$ and collects $$$7$$$ mushrooms. The numbers of mushrooms will be $$$[2,1,3,4,5]$$$. After $$$2$$$ minutes, Marisa collects $$$12$$$ mushrooms.It can be shown that it is impossible to collect more than $$$12$$$ mushrooms.Test case 2:This is one of her possible moving path:$$$2 \rightarrow 3 \rightarrow 2 \rightarrow 1 \rightarrow 2 \rightarrow 3 \rightarrow 4 \rightarrow 5$$$It can be shown that it is impossible to collect more than $$$37$$$ mushrooms.
Java 8
standard input
[ "brute force", "greedy" ]
e092d58ac58e1e41d17be946128234e5
Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains two integers $$$n$$$, $$$k$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$, $$$1\le k \le 10^9$$$) — the number of positions with mushrooms and the time Marisa has, respectively. The second line of each test case contains $$$n$$$ integers $$$a_1,a_2,\ldots,a_n$$$ ($$$1 \le a_i \le 10^9$$$) — the initial number of mushrooms on point $$$1,2,\ldots,n$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$.
1,600
For each test case, print the maximum number of mushrooms Marisa can pick after $$$k$$$ minutes.
standard output
PASSED
d20df309a247cc1b7252a4af712b7173
train_108.jsonl
1654266900
The enchanted forest got its name from the magical mushrooms growing here. They may cause illusions and generally should not be approached.—Perfect Memento in Strict SenseMarisa comes to pick mushrooms in the Enchanted Forest. The Enchanted forest can be represented by $$$n$$$ points on the $$$X$$$-axis numbered $$$1$$$ through $$$n$$$. Before Marisa started, her friend, Patchouli, used magic to detect the initial number of mushroom on each point, represented by $$$a_1,a_2,\ldots,a_n$$$.Marisa can start out at any point in the forest on minute $$$0$$$. Each minute, the followings happen in order: She moves from point $$$x$$$ to $$$y$$$ ($$$|x-y|\le 1$$$, possibly $$$y=x$$$). She collects all mushrooms on point $$$y$$$. A new mushroom appears on each point in the forest. Note that she cannot collect mushrooms on minute $$$0$$$.Now, Marisa wants to know the maximum number of mushrooms she can pick after $$$k$$$ minutes.
256 megabytes
import java.io.*; import java.util.*; public class Solution { static BufferedReader bf; static PrintWriter out; static Scanner sc; static StringTokenizer st; public static void main (String[] args)throws IOException { bf = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); sc = new Scanner(System.in); // solve(); int t = Integer.parseInt(bf.readLine()); while(t-->0){ solve(); } } public static void solve( ) throws IOException{ long n = nextLong(); long k = nextLong(); long[]arr = new long[(int)n]; for(int i =0;i<n;i++){ arr[i] = nextLong(); } long sum = 0; if (n == 1){ sum +=arr[0]; sum += (k-1); println(sum); } else if(k > n){ if(k%(n-1) == 1){ for(int i = 0;i<n;i++){ sum += (arr[i]); } sum += ((n-1) * n)/2; k -= n; sum += ((k/(n-1)) * (n-1) * n); println(sum); } else{ long mid = k%(n-1); if(mid == 0){ mid = n-1; } int count = 0; for(int i = (int)mid-1;i>=0;i--){ sum += (arr[i] + count); count++; } sum += ((mid-1) * (mid)); int deri = 1; // println(sum); for(int i = (int)mid;i<n;i++){ sum += (arr[i] + (2*(mid-1))+deri); deri++; } if(mid == n-1){ k -= n-1; } else{ k-= (k%(n-1)); } k -= n-1; // println(k); sum += ((k/(n-1)) * ((n-1) * n)); println(sum); } } else if(k <= n){ long innerSum = 0; long maxSum = 0; for(int i = 0;i<k;i++){ innerSum +=arr[i]; } maxSum = innerSum; int i = 0; int j = (int)k; while(j < n){ innerSum += arr[j]; innerSum -= arr[i]; i++; j++; maxSum = Math.max(maxSum,innerSum); } maxSum += (k-1)*k/2; println(maxSum); } } public static long findSum(int node,int low,int high,int tlow,int thigh,long[]tree){ if(low >= tlow && high <= thigh)return tree[node]; if(high < tlow || low > thigh)return 0; int mid = (low+high)/2; return findSum(node*2,low,mid,tlow,thigh,tree) + findSum(node*2 + 1, mid+1,high,tlow,thigh,tree); } public static int findIndex(int node,int low,int high,int[]tree,int group){ if(node*2 >= tree.length){ tree[node] -= group; return node; } int left = node*2; int right = node*2+1; int mid = (low+high)/2; if(tree[left]>=group){ int index = findIndex(left,low,mid,tree,group); tree[node] = Math.max(tree[left],tree[right]); return index; } int index = findIndex(right,mid+1,high,tree,group); tree[node] = Math.max(tree[left],tree[right]); return index; } public static void update(int node,int low,int high,int tlow,int thigh,long val,long[]tree){ if(low>=tlow && high <= thigh){ tree[node] += val; return; } if(low > thigh || high < tlow)return; int mid = (low+high)/2; update(node*2 , low,mid,tlow,thigh,val,tree); update(node*2+1,mid+1,high,tlow,thigh,val,tree); } public static int findN(int n){ int num = 1; while(num < n){ num*=2; } return num; } public static String calc(char[]arr,int i,int j){ StringBuilder sb = new StringBuilder(); for(int k = i;k<=j;k++){ sb.append(arr[k]); } return sb.toString(); } public static boolean isPalindrome(char[]arr,int i ,int j){ while(i<=j){ if(arr[i] != arr[j])return false; i++; j--; } return true; } // code for input public static void print(String s ){ System.out.print(s); } public static void print(int num ){ System.out.print(num); } public static void print(long num ){ System.out.print(num); } public static void println(String s){ System.out.println(s); } public static void println(int num){ System.out.println(num); } public static void println(long num){ System.out.println(num); } public static void println(){ System.out.println(); } public static int Int(String s){ return Integer.parseInt(s); } public static long Long(String s){ return Long.parseLong(s); } public static String[] nextStringArray()throws IOException{ return bf.readLine().split(" "); } public static String nextString()throws IOException{ return bf.readLine(); } public static long[] nextLongArray(int n)throws IOException{ String[]str = bf.readLine().split(" "); long[]arr = new long[n]; for(int i =0;i<n;i++){ arr[i] = Long.parseLong(str[i]); } return arr; } public static int[][] newIntMatrix(int r,int c)throws IOException{ int[][]arr = new int[r][c]; for(int i =0;i<r;i++){ String[]str = bf.readLine().split(" "); for(int j =0;j<c;j++){ arr[i][j] = Integer.parseInt(str[j]); } } return arr; } public static long[][] newLongMatrix(int r,int c)throws IOException{ long[][]arr = new long[r][c]; for(int i =0;i<r;i++){ String[]str = bf.readLine().split(" "); for(int j =0;j<c;j++){ arr[i][j] = Long.parseLong(str[j]); } } return arr; } static class pair{ int one; int two; pair(int one,int two){ this.one = one ; this.two =two; } } public static long gcd(long a,long b){ if(b == 0)return a; return gcd(b,a%b); } public static long lcm(long a,long b){ return (a*b)/(gcd(a,b)); } public static boolean isPalindrome(String s){ int i = 0; int j = s.length()-1; while(i<=j){ if(s.charAt(i) != s.charAt(j)){ return false; } i++; j--; } return true; } // these functions are to calculate the number of smaller elements after self public static void sort(int[]arr,int l,int r){ if(l < r){ int mid = (l+r)/2; sort(arr,l,mid); sort(arr,mid+1,r); smallerNumberAfterSelf(arr, l, mid, r); } } public static void smallerNumberAfterSelf(int[]arr,int l,int mid,int r){ int n1 = mid - l +1; int n2 = r - mid; int []a = new int[n1]; int[]b = new int[n2]; for(int i = 0;i<n1;i++){ a[i] = arr[l+i]; } for(int i =0;i<n2;i++){ b[i] = arr[mid+i+1]; } int i = 0; int j =0; int k = l; while(i<n1 && j < n2){ if(a[i] < b[j]){ arr[k++] = a[i++]; } else{ arr[k++] = b[j++]; } } while(i<n1){ arr[k++] = a[i++]; } while(j<n2){ arr[k++] = b[j++]; } } public static String next(){ while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(bf.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } static int nextInt() { return Integer.parseInt(next()); } static long nextLong() { return Long.parseLong(next()); } static double nextDouble() { return Double.parseDouble(next()); } static String nextLine(){ String str = ""; try { str = bf.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } // use some math tricks it might help // sometimes just try to think in straightforward plan in A and B problems don't always complecate the questions with thinking too much differently // always use long number to do 10^9+7 modulo // if a problem is related to binary string it could also be related to parenthesis // *****try to use binary search(it is a very beautiful thing it can work in some of the very unexpected problems ) in the question it might work****** // try sorting // try to think in opposite direction of question it might work in your way // if a problem is related to maths try to relate some of the continuous subarray with variables like - > a+b+c+d or a,b,c,d in general // if the question is to much related to left and/or right side of any element in an array then try monotonic stack it could work. // in range query sums try to do binary search it could work // analyse the time complexity of program thoroughly // anylyse the test cases properly // if we divide any number by 2 till it gets 1 then there will be (number - 1) operation required // try to do the opposite operation of what is given in the problem //think about the base cases properly //If a question is related to numbers try prime factorisation or something related to number theory // keep in mind unique strings //you can calculate the number of inversion in O(n log n) // in a matrix you could sometimes think about row and cols indenpendentaly. // Try to think in more constructive(means a way to look through various cases of a problem) way. // a grid problem could also be related to graph related algorithms. // when we have to take all the n element into consideration of the calculations then the bitmask dp could be used in that question and constraints are always less .
Java
["4\n\n5 2\n\n5 6 1 2 3\n\n5 7\n\n5 6 1 2 3\n\n1 2\n\n999999\n\n5 70000\n\n1000000000 1000000000 1000000000 1000000000 1000000000"]
2 seconds
["12\n37\n1000000\n5000349985"]
NoteTest case 1:Marisa can start at $$$x=2$$$. In the first minute, she moves to $$$x=1$$$ and collect $$$5$$$ mushrooms. The number of mushrooms will be $$$[1,7,2,3,4]$$$. In the second minute, she moves to $$$x=2$$$ and collects $$$7$$$ mushrooms. The numbers of mushrooms will be $$$[2,1,3,4,5]$$$. After $$$2$$$ minutes, Marisa collects $$$12$$$ mushrooms.It can be shown that it is impossible to collect more than $$$12$$$ mushrooms.Test case 2:This is one of her possible moving path:$$$2 \rightarrow 3 \rightarrow 2 \rightarrow 1 \rightarrow 2 \rightarrow 3 \rightarrow 4 \rightarrow 5$$$It can be shown that it is impossible to collect more than $$$37$$$ mushrooms.
Java 8
standard input
[ "brute force", "greedy" ]
e092d58ac58e1e41d17be946128234e5
Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains two integers $$$n$$$, $$$k$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$, $$$1\le k \le 10^9$$$) — the number of positions with mushrooms and the time Marisa has, respectively. The second line of each test case contains $$$n$$$ integers $$$a_1,a_2,\ldots,a_n$$$ ($$$1 \le a_i \le 10^9$$$) — the initial number of mushrooms on point $$$1,2,\ldots,n$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$.
1,600
For each test case, print the maximum number of mushrooms Marisa can pick after $$$k$$$ minutes.
standard output
PASSED
7e84cb3ecca613e94d8ae2231184860b
train_108.jsonl
1654266900
The enchanted forest got its name from the magical mushrooms growing here. They may cause illusions and generally should not be approached.—Perfect Memento in Strict SenseMarisa comes to pick mushrooms in the Enchanted Forest. The Enchanted forest can be represented by $$$n$$$ points on the $$$X$$$-axis numbered $$$1$$$ through $$$n$$$. Before Marisa started, her friend, Patchouli, used magic to detect the initial number of mushroom on each point, represented by $$$a_1,a_2,\ldots,a_n$$$.Marisa can start out at any point in the forest on minute $$$0$$$. Each minute, the followings happen in order: She moves from point $$$x$$$ to $$$y$$$ ($$$|x-y|\le 1$$$, possibly $$$y=x$$$). She collects all mushrooms on point $$$y$$$. A new mushroom appears on each point in the forest. Note that she cannot collect mushrooms on minute $$$0$$$.Now, Marisa wants to know the maximum number of mushrooms she can pick after $$$k$$$ minutes.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.math.BigInteger; import java.util.*; import javafx.util.Pair; public class Main { public static long sumofn(long n) { return (n*(n+1))/2l; } public static void main(String[] args) throws IOException { FastScanner input = new FastScanner(); int tc = input.nextInt(); work: while (tc-- > 0) { int n = input.nextInt(); long k = input.nextInt(); long a[] = new long[n]; long sum = 0; for (int i = 0; i <n; i++) { a[i] = input.nextLong(); sum+=a[i]; } if(k<n) { long ans = 0; int temp= 0; while(temp<k) { ans+=a[temp++]; } int j = 0; long max = ans; for (int i = (int)k; i <n; i++,j++) { ans+=a[i]; ans-=a[j]; max = Math.max(max, ans); } max+=sumofn(k-1); System.out.println(max); } else { long ans = 0; ans = sumofn(n-1)+sum; k-=n; long div = k/n; long mod = k%n; ///for div long perdiv = sumofn(n)+sumofn(n-1); if(div>0) { ans+=(div*perdiv); } long onlymod = sumofn(n)-sumofn(n-mod)+sumofn(mod-1); if(mod>0) { ans+=onlymod; } System.out.println(ans); } } } 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()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() throws IOException { return br.readLine(); } } }
Java
["4\n\n5 2\n\n5 6 1 2 3\n\n5 7\n\n5 6 1 2 3\n\n1 2\n\n999999\n\n5 70000\n\n1000000000 1000000000 1000000000 1000000000 1000000000"]
2 seconds
["12\n37\n1000000\n5000349985"]
NoteTest case 1:Marisa can start at $$$x=2$$$. In the first minute, she moves to $$$x=1$$$ and collect $$$5$$$ mushrooms. The number of mushrooms will be $$$[1,7,2,3,4]$$$. In the second minute, she moves to $$$x=2$$$ and collects $$$7$$$ mushrooms. The numbers of mushrooms will be $$$[2,1,3,4,5]$$$. After $$$2$$$ minutes, Marisa collects $$$12$$$ mushrooms.It can be shown that it is impossible to collect more than $$$12$$$ mushrooms.Test case 2:This is one of her possible moving path:$$$2 \rightarrow 3 \rightarrow 2 \rightarrow 1 \rightarrow 2 \rightarrow 3 \rightarrow 4 \rightarrow 5$$$It can be shown that it is impossible to collect more than $$$37$$$ mushrooms.
Java 8
standard input
[ "brute force", "greedy" ]
e092d58ac58e1e41d17be946128234e5
Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains two integers $$$n$$$, $$$k$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$, $$$1\le k \le 10^9$$$) — the number of positions with mushrooms and the time Marisa has, respectively. The second line of each test case contains $$$n$$$ integers $$$a_1,a_2,\ldots,a_n$$$ ($$$1 \le a_i \le 10^9$$$) — the initial number of mushrooms on point $$$1,2,\ldots,n$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$.
1,600
For each test case, print the maximum number of mushrooms Marisa can pick after $$$k$$$ minutes.
standard output
PASSED
a02375c5a2733f78425935f409edb31b
train_108.jsonl
1654266900
The enchanted forest got its name from the magical mushrooms growing here. They may cause illusions and generally should not be approached.—Perfect Memento in Strict SenseMarisa comes to pick mushrooms in the Enchanted Forest. The Enchanted forest can be represented by $$$n$$$ points on the $$$X$$$-axis numbered $$$1$$$ through $$$n$$$. Before Marisa started, her friend, Patchouli, used magic to detect the initial number of mushroom on each point, represented by $$$a_1,a_2,\ldots,a_n$$$.Marisa can start out at any point in the forest on minute $$$0$$$. Each minute, the followings happen in order: She moves from point $$$x$$$ to $$$y$$$ ($$$|x-y|\le 1$$$, possibly $$$y=x$$$). She collects all mushrooms on point $$$y$$$. A new mushroom appears on each point in the forest. Note that she cannot collect mushrooms on minute $$$0$$$.Now, Marisa wants to know the maximum number of mushrooms she can pick after $$$k$$$ minutes.
256 megabytes
import java.util.Scanner; public class A1687 { public static void main(String[] args) { Scanner in = new Scanner(System.in); int T = in.nextInt(); for (int t=0; t<T; t++) { int N = in.nextInt(); int K = in.nextInt(); int[] A = new int[N]; for (int n=0; n<N; n++) { A[n] = in.nextInt(); } long answer; if (K >= N) { answer = 0; for (int a : A) { answer += a; } answer += K*(long)N; answer -= ((N+1)*(long)N)/2; } else { long sum = 0; for (int k=0; k<K; k++) { sum += A[k]; } long max = sum; for (int n=K; n<N; n++) { sum -= A[n-K]; sum += A[n]; max = Math.max(max, sum); } max += (K-1)*(long)K/2; answer = max; } System.out.println(answer); } } }
Java
["4\n\n5 2\n\n5 6 1 2 3\n\n5 7\n\n5 6 1 2 3\n\n1 2\n\n999999\n\n5 70000\n\n1000000000 1000000000 1000000000 1000000000 1000000000"]
2 seconds
["12\n37\n1000000\n5000349985"]
NoteTest case 1:Marisa can start at $$$x=2$$$. In the first minute, she moves to $$$x=1$$$ and collect $$$5$$$ mushrooms. The number of mushrooms will be $$$[1,7,2,3,4]$$$. In the second minute, she moves to $$$x=2$$$ and collects $$$7$$$ mushrooms. The numbers of mushrooms will be $$$[2,1,3,4,5]$$$. After $$$2$$$ minutes, Marisa collects $$$12$$$ mushrooms.It can be shown that it is impossible to collect more than $$$12$$$ mushrooms.Test case 2:This is one of her possible moving path:$$$2 \rightarrow 3 \rightarrow 2 \rightarrow 1 \rightarrow 2 \rightarrow 3 \rightarrow 4 \rightarrow 5$$$It can be shown that it is impossible to collect more than $$$37$$$ mushrooms.
Java 8
standard input
[ "brute force", "greedy" ]
e092d58ac58e1e41d17be946128234e5
Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains two integers $$$n$$$, $$$k$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$, $$$1\le k \le 10^9$$$) — the number of positions with mushrooms and the time Marisa has, respectively. The second line of each test case contains $$$n$$$ integers $$$a_1,a_2,\ldots,a_n$$$ ($$$1 \le a_i \le 10^9$$$) — the initial number of mushrooms on point $$$1,2,\ldots,n$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$.
1,600
For each test case, print the maximum number of mushrooms Marisa can pick after $$$k$$$ minutes.
standard output
PASSED
d86b97fe1da168fe760bb4a224948181
train_108.jsonl
1654266900
The enchanted forest got its name from the magical mushrooms growing here. They may cause illusions and generally should not be approached.—Perfect Memento in Strict SenseMarisa comes to pick mushrooms in the Enchanted Forest. The Enchanted forest can be represented by $$$n$$$ points on the $$$X$$$-axis numbered $$$1$$$ through $$$n$$$. Before Marisa started, her friend, Patchouli, used magic to detect the initial number of mushroom on each point, represented by $$$a_1,a_2,\ldots,a_n$$$.Marisa can start out at any point in the forest on minute $$$0$$$. Each minute, the followings happen in order: She moves from point $$$x$$$ to $$$y$$$ ($$$|x-y|\le 1$$$, possibly $$$y=x$$$). She collects all mushrooms on point $$$y$$$. A new mushroom appears on each point in the forest. Note that she cannot collect mushrooms on minute $$$0$$$.Now, Marisa wants to know the maximum number of mushrooms she can pick after $$$k$$$ minutes.
256 megabytes
// package faltu; import java.util.*; import java.util.Map.Entry; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.math.BigInteger; public class Main { // ***********************MATHS--STARTS************************************************* // private static ArrayList<Long> get_divisor(long x) { ArrayList<Long>a=new ArrayList<Long>(); for(long i=1;i*i<=x;i++) { if(x%i==0) { a.add((long) i); if(x/i!=i)a.add(x/i); } } return a; } private static int CntOfFactor(long x) { ArrayList<Long>a=new ArrayList<Long>(); for(long i=1;i*i<=x;i++) { if(x%i==0) { a.add((long) i); if(x/i!=i)a.add(x/i); } } return a.size(); } static long[] sieve; static long[] smallestPrime; public static void sieve() { int n=4000000+1; sieve=new long[n]; smallestPrime=new long[n]; sieve[0]=1; sieve[1]=1; for(int i=2;i<n;i++){ sieve[i]=i; smallestPrime[i]=i; } for(int i=2;i*i<n;i++){ if(sieve[i]==i){ for(int j=i*i;j<n;j+=i){ if(sieve[j]==j)sieve[j]=1; if(smallestPrime[j]==j||smallestPrime[j]>i)smallestPrime[j]=i; } } } } static long nCr(long n,long r,long MOD) { computeFact(n, MOD); if(n<r)return 0; if(r==0)return 1; return fact[(int) n]*mod_inv(fact[(int) r],MOD)%MOD*mod_inv(fact[(int) (n-r)],MOD)%MOD; } static long[]fact; static void computeFact(long n,long MOD) { fact=new long[(int)n+1]; fact[0]=1; for(int i=1;i<=n;i++)fact[i]=(fact[i-1]*i%MOD)%MOD; } static long bin_expo(long a,long b,long MOD) { if(b == 0)return 1; long ans = bin_expo(a,b/2,MOD); ans = (ans*ans)%MOD; if(b % 2!=0){ ans = (ans*a)%MOD; } return ans%MOD; } 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));} static long mod_add(long a, long b, long m) {a = a % m; b = b % m; return (((a + b) % m) + m) % m;} static long mod_mul(long a, long b, long m) {a = a % m; b = b % m; return (((a * b) % m) + m) % m;} static long mod_sub(long a, long b, long m) {a = a % m; b = b % m; return (((a - b) % m) + m) % m;} static long mod_inv(long n,long p) {return bin_expo(n,p-2,p);} static long gcd(long a, long b){if (a == 0) {return b;}return gcd(b % a, a); } static int gcd(int a, int 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 min(long x,long y) {return Math.min(x, y);}static long max(long x,long y) {return Math.max(x, y);} static int min(int x,int y) {return Math.min(x, y);}static int max(int x,int y) {return Math.max(x, y);} static ArrayList<String>powof2s; static void powof2S() { long i=1; while(i<(long)2e18) { powof2s.add(String.valueOf(i)); i*=2; } } static long power(long a, long b){ a %=MOD;long out = 1; while (b > 0) { if((b&1)!=0)out = out * a % MOD; a = a * a % MOD; b >>= 1; a*=a; } return out; } static boolean coprime(long a, long b){return (gcd(a, b) == 1);} // ****************************MATHS-ENDS***************************************************** // ***********************BINARY-SEARCH STARTS*********************************************** public static int upperBound(long[] arr, long m, int l, int r) { while(l<=r) { int mid=(l+r)/2; if(arr[mid]<=m) l=mid+1; else r=mid-1; } return l; } public static int lowerBound(long[] a, long m, int l, int r) { while(l<=r) { int mid=(l+r)/2; if(a[mid]<m) l=mid+1; else r=mid-1; } return l; } public static int lowerBound(ArrayList<Integer> ar,int k){ int s=0,e=ar.size(); while (s!=e){ int mid = s+e>>1; if (ar.get(mid) <k)s=mid+1; else e=mid; } if(s==ar.size())return -1; return s; } public static int upperBound(ArrayList<Integer> ar,int k){ int s=0,e=ar.size(); while (s!=e){ int mid = s+e>>1; if (ar.get(mid) <=k)s=mid+1; else e=mid; } if(s==ar.size())return -1; return s; } public static long getClosest(long val1, long val2,long target){if (target - val1 >= val2 - target)return val2; else return val1;} static void ruffleSort(long[] a) { int n=a.length; Random r=new Random(); for (int i=0; i<a.length; i++) { long oi=r.nextInt(n), temp=a[i]; a[i]=a[(int)oi]; a[(int)oi]=temp; } Arrays.sort(a); } static void ruffleSort(int[] a){ int n=a.length; Random r=new Random(); for (int i=0; i<a.length; i++) { int oi=r.nextInt(n), temp=a[i]; a[i]=a[oi]; a[oi]=temp; } Arrays.sort(a); } int ceilIndex(int input[], int T[], int end, int s){ int start = 0; int middle; int len = end; while(start <= end){ middle = (start + end)/2; if(middle < len && input[T[middle]] < s && s <= input[T[middle+1]]){ return middle+1; }else if(input[T[middle]] < s){ start = middle+1; }else{ end = middle-1; } } return -1; } static int lowerLimitBinarySearch(ArrayList<Long> v,long k) { int n =v.size(); int first = 0,second = n; while(first <second) { int mid = first + (second-first)/2; if(v.get(mid) > k) { second = mid; }else { first = mid+1; } } if(first < n && v.get(first) < k) { first++; } return first; //1 index } public static int searchindex(long arr[], long t){int index = Arrays.binarySearch(arr, t);return (index < 0) ? -1 : index;} public static long[] sort(long[] a) {ArrayList<Long> al = new ArrayList<>();for(int i=0;i<a.length;i++) al.add(a[i]);Collections.sort(al);for(int i=0;i<a.length;i++) a[i]=al.get(i);return a;} public static int[] sort(int[] a) {ArrayList<Integer> al = new ArrayList<>();for(int i=0;i<a.length;i++) al.add(a[i]);Collections.sort(al);for(int i=0;i<a.length;i++) a[i]=al.get(i);return a;} // *******************************BINARY-SEARCH ENDS*********************************************** // *********************************GRAPHS-STARTS**************************************************** // *******----SEGMENT TREE IMPLEMENT---***** // -------------START--------------- void buildTree (int[] arr,int[] tree,int start,int end,int treeNode){ if(start==end){ tree[treeNode]=arr[start]; return; } buildTree(arr,tree,start,end,2*treeNode); buildTree(arr,tree,start,end,2*treeNode+1); tree[treeNode]=tree[treeNode*2]+tree[2*treeNode+1]; } void updateTree(int[] arr,int[] tree,int start,int end,int treeNode,int idx,int value){ if(start==end){ arr[idx]=value; tree[treeNode]=value; return; } int mid=(start+end)/2; if(idx>mid)updateTree(arr,tree,mid+1,end,2*treeNode+1,idx,value); else updateTree(arr,tree,start,mid,2*treeNode,idx,value); tree[treeNode]=tree[2*treeNode]+tree[2*treeNode+1]; } long query(int[]arr,int[]tree,int start,int end,int treeNode,int qleft,int qright) { if(start>=qleft&&end<=qright)return tree[treeNode]; if(start>qright||end<qleft)return 0; int mid=(start+end)/2; long valLeft=query(arr,tree,start,mid-1,treeNode*2,qleft,qright); long valRight=query(arr,tree,mid+1,end,treeNode*2+1,qleft,qright); return valLeft+valRight; } // -------------ENDS--------------- //***********************DSU IMPLEMENT START************************* static int parent[]; static int rank[]; static int[]Size; static void makeSet(int n){ parent=new int[n]; rank=new int[n]; Size=new int[n]; for(int i=0;i<n;i++){ parent[i]=i; rank[i]=0; Size[i]=1; } } static void union(int u,int v){ u=findpar(u); v=findpar(v); if(u==v)return; if(rank[u]<rank[v]) { parent[u]=v; Size[v]+=Size[u]; } else if(rank[v]<rank[u]) { parent[v]=u; Size[u]+=Size[v]; } else{ parent[v]=u; rank[u]++; Size[u]+=Size[v]; } } private static int findpar(int node){ if(node==parent[node])return node; return parent[node]=findpar(parent[node]); } // *********************DSU IMPLEMENT ENDS************************* // ****__________PRIMS ALGO______________________**** private static int prim(ArrayList<node>[] adj,int N,int node) { int key[] = new int[N+1]; int parent[] = new int[N+1]; boolean mstSet[] = new boolean[N+1]; for(int i = 0;i<N;i++) { key[i] = 100000000; mstSet[i] = false; } PriorityQueue<node> pq = new PriorityQueue<node>(N, new node()); key[node] = 0; parent[node] = -1; pq.add(new node( node,key[node])); for(int i = 0;i<N-1;i++) { int u = pq.poll().getV(); mstSet[u] = true; for(node it: adj[u]) { if(mstSet[it.getV()] == false && it.getW() < key[it.getV()]) { parent[it.getV()] = u; key[it.getV()] = (int) it.getW(); pq.add(new node(it.getV(), key[it.getV()])); } } } int sum=0; for(int i=1;i<N;i++) { System.out.println(key[i]); sum+=key[i]; } System.out.println(sum); return sum; } // ****____________DIJKSTRAS ALGO___________**** static int[]dist; static int dijkstra(int u,int n,ArrayList<node>adj[]) { long[]path=new long[n]; dist=new int[n]; Arrays.fill(dist,Integer.MAX_VALUE); dist[u]=0; path[0]=1; PriorityQueue<node>pq=new PriorityQueue<node>(new node()); pq.add(new node(u,0)); while(!pq.isEmpty()) { node v=pq.poll(); if(dist[v.getV()]<v.getW())continue; for(node it:adj[v.getV()]) { if(dist[it.getV()]>it.getW()+dist[v.getV()]) { dist[it.getV()]=(int) (it.getW()+dist[v.getV()]); pq.add(new node(it.getV(),dist[it.getV()])); path[it.getV()]=path[v.getV()]; } else if(dist[it.getV()]==it.getW()+dist[v.getV()]) { path[it.getV()]+=path[v.getV()]; } } } int sum=0; for(int i=1;i<n;i++){ System.out.println(dist[i]); sum+=dist[i]; } return sum; } private static void setGraph(int n,int m){ vis=new boolean[n+1]; indeg=new int[n+1]; // adj=new ArrayList<ArrayList<Integer>>(); // for(int i=0;i<=n;i++)adj.add(new ArrayList<>()); // for(int i=0;i<m;i++){ // int u=s.nextInt(),v=s.nextInt(); // adj.get(u).add(v); // adj.get(v).add(u); // } adj=new ArrayList[n+1]; // backadj=new ArrayList[n+1]; for(int i=0;i<=n;i++){ adj[i]=new ArrayList<Integer>(); // backadj[i]=new ArrayList<Integer>(); } for(int i=0;i<m;i++){ int u=s.nextInt(),v=s.nextInt(); adj[u].add(v); adj[v].add(u); // backadj[v].add(u); indeg[v]++; indeg[u]++; } // weighted adj // adj=new ArrayList[n+1]; // for(int i=0;i<=n;i++){ // adj[i]=new ArrayList<node>(); // } // for(int i=0;i<m;i++){ // int u=s.nextInt(),v=s.nextInt(); // long w=s.nextInt(); // adj[u].add(new node(v,w)); //// adj[v].add(new node(u,w)); // } } // *********************************GRAPHS-ENDS**************************************************** static int[][] dirs8 = {{1,0},{-1,0},{0,1},{0,-1},{1,1},{1,-1},{-1,1},{-1,-1}}; static int[][] dirs4 = {{1,0},{-1,0},{0,1},{0,-1}}; //d-u-r-l static long MOD=(long) (1e9+7); static int prebitsum[][]; static boolean[] vis; static int[]indeg; // static ArrayList<ArrayList<Integer>>adj; static ArrayList<Integer> adj[]; static ArrayList<Integer> backadj[]; static FastReader s = new FastReader(System.in); static PrintWriter out = new PrintWriter(System.out); public static void main(String[] args) throws IOException{ // sieve(); // computeFact((int)1e7+1,MOD); // prebitsum=new int[2147483648][31]; // presumbit(prebitsum); // powof2S(); // try { int tt = s.nextInt(); // int tt=1; for(int i=1;i<=tt;i++) { solver(); } out.close(); // catch(Exception e) {return;} } private static void solver() { int n=s.nextInt(); long k=s.nextLong(); long[]pre=new long[n+1]; for(int i=1;i<=n;i++) { long x=s.nextLong(); pre[i]+=pre[i-1]+x; } if(k<n) { long ans=pre[(int) k]; for(int i=(int) (k+1);i<=n;i++) { ans=max(ans,pre[i]-pre[(int) (i-k)]); } ans+=(k*(k-1L))/2L; // for last k-1 term out.println(ans);return; } else { long ans = pre[n]; ans += (n*k) - (long)((n*(n+1L))/2L); //for kterms- nterms out.println(ans);return; } } static int swaps; private static int mergeAndCount(char[] arr, int l,int m, int r){ char[] left = Arrays.copyOfRange(arr, l, m + 1); char[] right = Arrays.copyOfRange(arr, m + 1, r + 1); int i = 0, j = 0, k = l; boolean f=false; while (i < left.length && j < right.length) { if (left[i]-'0' <= right[j]-'0')arr[k++] = left[i++]; else { arr[k++] = right[j++]; f=true; } } if(f)swaps++; while (i < left.length)arr[k++] = left[i++]; while (j < right.length)arr[k++] = right[j++]; return swaps; } // Merge sort function private static int mergeSortAndCount(char[] arr, int l, int r) { int count = 0; if (l < r) { int m = (l + r) / 2; count += mergeSortAndCount(arr, l, m); count += mergeSortAndCount(arr, m + 1, r); count += mergeAndCount(arr, l, m, r); } return count; } private static long sqroot(long x) {long left = 0, right = 2000000123;while (right > left) {long mid = (left + right) / 2;if (mid * mid > x) right = mid;else left = mid + 1;}return left - 1;} /* *********************BITS && TOOLS &&DEBUG STARTS***********************************************/ static boolean issafe(int i, int j, int r,int c,boolean[][]vis){ if (i < 0 || j < 0 || i >= r || j >= c||vis[i][j]==true)return false; else return true; } static void presumbit(int[][]prebitsum) { for(int i=1;i<=200000;i++) { int z=i; int j=0; while(z>0) { if((z&1)==1) { prebitsum[i][j]+=(prebitsum[i-1][j]+1); }else { prebitsum[i][j]=prebitsum[i-1][j]; } z=z>>1; j++; } } } static void countOfSetBit(long[]a) { for(int j=30;j>=0;j--) { int cnt=0; for(long i:a) { if((i&1<<j)==1)cnt++; } // printing the current no set bit in all array element System.out.println(cnt); } } public static String revStr(String str){String input = str;StringBuilder input1 = new StringBuilder();input1.append(input);input1.reverse();return input1.toString();} static void pl1d(long[] x) {for(int i=0;i<x.length;i++)out.print(x[i]+" ");out.println();} static void pb1d(boolean[] x) {for(int i=0;i<x.length;i++)out.print(x[i]+" ");out.println();} static void pi1d(int[] x) {for(int i=0;i<x.length;i++)out.print(x[i]+" ");out.println();} static void pc1d(char[] x) {for(int i=0;i<x.length;i++)out.print(x[i]+" ");out.println();} static void pb2d(boolean[][] vis) {int n=vis.length;int m=vis[0].length;for(int i=0;i<n;i++) {for(int j=0;j<m;j++) {System.out.print(vis[i][j]+" ");}System.out.println();}} static void pc2d(char[][] vis) {int n=vis.length;int m=vis[0].length;for(int i=0;i<n;i++) {for(int j=0;j<m;j++) {System.out.print(vis[i][j]+" ");}System.out.println();}} static void pi2d(int[][] vis) {int n=vis.length;int m=vis[0].length;for(int i=0;i<n;i++) {for(int j=0;j<m;j++) {System.out.print(vis[i][j]+" ");}System.out.println();}} static void pl2d(long[][] vis) {int n=vis.length;int m=vis[0].length;for(int i=0;i<n;i++) {for(int j=0;j<m;j++) {System.out.print(vis[i][j]+" ");}System.out.println();}} // *****************BITS && TOOLS &&DEBUG ENDS*********************************************** } // **************************I/O************************* class FastReader { public BufferedReader reader; public StringTokenizer tokenizer; public FastReader(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());} public String nextLine() {String str = "";try {str = reader.readLine();}catch (IOException e) {e.printStackTrace();}return str;} public int[] rdia(int n) {int[] a = new int[n];for (int i = 0; i < n; i++) a[i] = nextInt();return a;} public long[] rdla(int n) {long[] a = new long[n];for (int i = 0; i < n; i++) a[i] = nextLong();return a;} public Integer[] rdIa(int n) {Integer[] a = new Integer[n];for (int i = 0; i < n; i++) a[i] =nextInt();return a;} public Long[] rdLa(int n) {Long[] a = new Long[n];for (int i = 0; i < n; i++) a[i] = nextLong();return a;} } class dsu{ int n; static int parent[]; static int rank[]; static int[]Size; public dsu(int n) {this.n=n;this.parent=new int[n];this.rank=new int[n];this.Size=new int[n]; for(int i=0;i<n;i++){parent[i]=i;rank[i]=0;Size[i]=1;} } static int findpar(int node) {if(node==parent[node])return node;return parent[node]=findpar(parent[node]);} static void union(int u,int v){ u=findpar(u);v=findpar(v); if(u!=v) { if(rank[u]<rank[v]) {parent[u]=v;Size[v]+=Size[u];} else if(rank[v]<rank[u]) {parent[v]=u;Size[u]+=Size[v];} else{parent[v]=u;rank[u]++;Size[u]+=Size[v];} } } } class pair{ int x;int y; long u,v; public pair(int x,int y){this.x=x;this.y=y;} public pair(long u,long v) {this.u=u;this.v=v;} } class Tuple{ String str;int x;int y; public Tuple(String str,int x,int y) { this.str=str; this.x=x; this.y=y; } } class node implements Comparator<node>{ private int v; private long w; node(int _v, long _w) { v = _v; w = _w; } node() {} int getV() { return v; } long getW() { return w; } @Override public int compare(node node1, node node2) { if (node1.w < node2.w) return -1; if (node1.w > node2.w) return 1; return 0; } }
Java
["4\n\n5 2\n\n5 6 1 2 3\n\n5 7\n\n5 6 1 2 3\n\n1 2\n\n999999\n\n5 70000\n\n1000000000 1000000000 1000000000 1000000000 1000000000"]
2 seconds
["12\n37\n1000000\n5000349985"]
NoteTest case 1:Marisa can start at $$$x=2$$$. In the first minute, she moves to $$$x=1$$$ and collect $$$5$$$ mushrooms. The number of mushrooms will be $$$[1,7,2,3,4]$$$. In the second minute, she moves to $$$x=2$$$ and collects $$$7$$$ mushrooms. The numbers of mushrooms will be $$$[2,1,3,4,5]$$$. After $$$2$$$ minutes, Marisa collects $$$12$$$ mushrooms.It can be shown that it is impossible to collect more than $$$12$$$ mushrooms.Test case 2:This is one of her possible moving path:$$$2 \rightarrow 3 \rightarrow 2 \rightarrow 1 \rightarrow 2 \rightarrow 3 \rightarrow 4 \rightarrow 5$$$It can be shown that it is impossible to collect more than $$$37$$$ mushrooms.
Java 8
standard input
[ "brute force", "greedy" ]
e092d58ac58e1e41d17be946128234e5
Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains two integers $$$n$$$, $$$k$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$, $$$1\le k \le 10^9$$$) — the number of positions with mushrooms and the time Marisa has, respectively. The second line of each test case contains $$$n$$$ integers $$$a_1,a_2,\ldots,a_n$$$ ($$$1 \le a_i \le 10^9$$$) — the initial number of mushrooms on point $$$1,2,\ldots,n$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$.
1,600
For each test case, print the maximum number of mushrooms Marisa can pick after $$$k$$$ minutes.
standard output
PASSED
411d246827ba7b5a9c72c55c3c6c01b4
train_108.jsonl
1654266900
The enchanted forest got its name from the magical mushrooms growing here. They may cause illusions and generally should not be approached.—Perfect Memento in Strict SenseMarisa comes to pick mushrooms in the Enchanted Forest. The Enchanted forest can be represented by $$$n$$$ points on the $$$X$$$-axis numbered $$$1$$$ through $$$n$$$. Before Marisa started, her friend, Patchouli, used magic to detect the initial number of mushroom on each point, represented by $$$a_1,a_2,\ldots,a_n$$$.Marisa can start out at any point in the forest on minute $$$0$$$. Each minute, the followings happen in order: She moves from point $$$x$$$ to $$$y$$$ ($$$|x-y|\le 1$$$, possibly $$$y=x$$$). She collects all mushrooms on point $$$y$$$. A new mushroom appears on each point in the forest. Note that she cannot collect mushrooms on minute $$$0$$$.Now, Marisa wants to know the maximum number of mushrooms she can pick after $$$k$$$ minutes.
256 megabytes
import java.io.*; import java.util.*; public class TheEnchantedForest { private static final int START_TEST_CASE = 1; public static void solveCase(FastIO io, int testCase) { final int N = io.nextInt(); final int K = io.nextInt(); final int[] A = io.nextIntArray(N); if (K >= N) { long aSum = 0; for (int x : A) { aSum += x; } long extra = sumBetween(K - N, K - 1); io.println(aSum + extra); return; } long windowSum = 0; for (int i = 0; i < K; ++i) { windowSum += A[i]; } long best = windowSum; for (int i = K; i < N; ++i) { windowSum += A[i] - A[i - K]; best = Math.max(best, windowSum); } long extra = sumBetween(0, K - 1); io.println(best + extra); } private static long sumBetween(long loIncl, long hiIncl) { return sumTriangular(hiIncl) - sumTriangular(loIncl - 1); } private static long sumTriangular(long x) { return (x * (x + 1)) >> 1; } public static void solve(FastIO io) { final int T = io.nextInt(); for (int t = 0; t < T; ++t) { solveCase(io, START_TEST_CASE + t); } } public static class FastIO { private InputStream reader; private PrintWriter writer; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public FastIO(InputStream r, OutputStream w) { reader = r; writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(w))); } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = reader.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public String nextString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } // TODO: read this byte-by-byte like the other read functions. public double nextDouble() { return Double.parseDouble(nextString()); } public int[] nextIntArray(int n) { return nextIntArray(n, 0); } public int[] nextIntArray(int n, int off) { int[] arr = new int[n + off]; for (int i = 0; i < n; i++) { arr[i + off] = nextInt(); } return arr; } public long[] nextLongArray(int n) { return nextLongArray(n, 0); } public long[] nextLongArray(int n, int off) { long[] arr = new long[n + off]; for (int i = 0; i < n; i++) { arr[i + off] = nextLong(); } return arr; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) { writer.print(' '); } writer.print(objects[i]); } } public void println(Object... objects) { print(objects); writer.println(); } public void printArray(int[] arr) { for (int i = 0; i < arr.length; i++) { if (i != 0) { writer.print(' '); } writer.print(arr[i]); } } public void printArray(long[] arr) { for (int i = 0; i < arr.length; i++) { if (i != 0) { writer.print(' '); } writer.print(arr[i]); } } public void printlnArray(int[] arr) { printArray(arr); writer.println(); } public void printlnArray(long[] arr) { printArray(arr); writer.println(); } public void printf(String format, Object... args) { print(String.format(format, args)); } public void flush() { writer.flush(); } } public static void main(String[] args) { FastIO io = new FastIO(System.in, System.out); solve(io); io.flush(); } }
Java
["4\n\n5 2\n\n5 6 1 2 3\n\n5 7\n\n5 6 1 2 3\n\n1 2\n\n999999\n\n5 70000\n\n1000000000 1000000000 1000000000 1000000000 1000000000"]
2 seconds
["12\n37\n1000000\n5000349985"]
NoteTest case 1:Marisa can start at $$$x=2$$$. In the first minute, she moves to $$$x=1$$$ and collect $$$5$$$ mushrooms. The number of mushrooms will be $$$[1,7,2,3,4]$$$. In the second minute, she moves to $$$x=2$$$ and collects $$$7$$$ mushrooms. The numbers of mushrooms will be $$$[2,1,3,4,5]$$$. After $$$2$$$ minutes, Marisa collects $$$12$$$ mushrooms.It can be shown that it is impossible to collect more than $$$12$$$ mushrooms.Test case 2:This is one of her possible moving path:$$$2 \rightarrow 3 \rightarrow 2 \rightarrow 1 \rightarrow 2 \rightarrow 3 \rightarrow 4 \rightarrow 5$$$It can be shown that it is impossible to collect more than $$$37$$$ mushrooms.
Java 8
standard input
[ "brute force", "greedy" ]
e092d58ac58e1e41d17be946128234e5
Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains two integers $$$n$$$, $$$k$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$, $$$1\le k \le 10^9$$$) — the number of positions with mushrooms and the time Marisa has, respectively. The second line of each test case contains $$$n$$$ integers $$$a_1,a_2,\ldots,a_n$$$ ($$$1 \le a_i \le 10^9$$$) — the initial number of mushrooms on point $$$1,2,\ldots,n$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$.
1,600
For each test case, print the maximum number of mushrooms Marisa can pick after $$$k$$$ minutes.
standard output