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
78e8695ba77d66fb68e4c51fa732f5a0
train_110.jsonl
1621152000
There are $$$n$$$ robots driving along an OX axis. There are also two walls: one is at coordinate $$$0$$$ and one is at coordinate $$$m$$$.The $$$i$$$-th robot starts at an integer coordinate $$$x_i~(0 < x_i < m)$$$ and moves either left (towards the $$$0$$$) or right with the speed of $$$1$$$ unit per second. No two robots start at the same coordinate.Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed.Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens.For each robot find out if it ever explodes and print the time of explosion if it happens and $$$-1$$$ otherwise.
256 megabytes
import java.io.*; import java.util.*; public class Codeforces { public static void main(String args[])throws Exception { BufferedReader bu=new BufferedReader(new InputStreamReader(System.in)); StringBuilder sb=new StringBuilder(); int t=Integer.parseInt(bu.readLine()); while(t-->0) { String s[]=bu.readLine().split(" "); int n=Integer.parseInt(s[0]),m=Integer.parseInt(s[1]); ArrayList<Robot> o=new ArrayList<>(),e=new ArrayList<>(); s=bu.readLine().split(" "); int i,a[]=new int[n]; for(i=0;i<n;i++) a[i]=Integer.parseInt(s[i]); s=bu.readLine().split(" "); for(i=0;i<n;i++) { int x=s[i].charAt(0); if(x=='L') x=1; else x=0; if(a[i]%2==0) e.add(new Robot(i,a[i],x)); else o.add(new Robot(i,a[i],x)); } long ans[]=new long[n]; fill(ans,e,m); fill(ans,o,m); for(i=0;i<n;i++) sb.append(ans[i]+" "); sb.append("\n"); } System.out.print(sb); } static void fill(long ans[],ArrayList<Robot> a,int m) { if(a.size()==0) return; Collections.sort(a, new Comparator<Robot>() { @Override public int compare(Robot o1, Robot o2) { if(o1.v>o2.v) return 1; else return -1; }}); Deque<Integer> dq=new LinkedList<>(),bad=new LinkedList<>(); int i; for(i=0;i<a.size();i++) if(a.get(i).t==0) dq.add(i); else { if(dq.isEmpty()) {bad.add(i); continue;} int x=dq.pollLast(); long d=a.get(i).v-a.get(x).v; d/=2; ans[a.get(i).i]=d; ans[a.get(x).i]=d; } int l=-1,r=-1; while(bad.size()>1) { int u=bad.removeFirst(),v=bad.removeFirst(); long d=a.get(v).v-a.get(u).v; d/=2; d+=a.get(u).v; ans[a.get(u).i]=d; ans[a.get(v).i]=d; } if(!bad.isEmpty()) l=bad.removeFirst(); while(dq.size()>1) { int u=dq.removeLast(),v=dq.removeLast(); long d=a.get(u).v-a.get(v).v; d/=2; d+=m-a.get(u).v; ans[a.get(u).i]=d; ans[a.get(v).i]=d; } if(!dq.isEmpty()) r=dq.removeFirst(); if(l!=-1 && r!=-1) { int max=Math.max(a.get(l).v,m-a.get(r).v); a.get(l).v-=max; a.get(r).v+=max; long d=max; a.get(l).v=Math.abs(a.get(l).v); if(a.get(r).v>m) a.get(r).v=2*m-a.get(r).v; d+=Math.abs(a.get(r).v-a.get(l).v)/2; ans[a.get(l).i]=d; ans[a.get(r).i]=d; } else { if(l!=-1) ans[a.get(l).i]=-1; if(r!=-1) ans[a.get(r).i]=-1; } } static class Robot { int i,v,t; Robot(int a,int b,int c) { i=a; v=b; t=c; } } }
Java
["5\n7 12\n1 2 3 4 9 10 11\nR R L L R R R\n2 10\n1 6\nR R\n2 10\n1 3\nL L\n1 10\n5\nR\n7 8\n6 1 7 2 3 5 4\nR L R L L L L"]
2 seconds
["1 1 1 1 2 -1 2 \n-1 -1 \n2 2 \n-1 \n-1 2 7 3 2 7 3"]
NoteHere is the picture for the seconds $$$0, 1, 2$$$ and $$$3$$$ of the first testcase: Notice that robots $$$2$$$ and $$$3$$$ don't collide because they meet at the same point $$$2.5$$$, which is not integer.After second $$$3$$$ robot $$$6$$$ just drive infinitely because there's no robot to collide with.
Java 11
standard input
[ "data structures", "greedy", "implementation", "sortings" ]
1a28b972e77966453cd8239cc5c8f59a
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5$$$; $$$2 \le m \le 10^8$$$) — the number of robots and the coordinate of the right wall. The second line of each testcase contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$0 &lt; x_i &lt; m$$$) — the starting coordinates of the robots. The third line of each testcase contains $$$n$$$ space-separated characters 'L' or 'R' — the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates $$$x_i$$$ in the testcase are distinct. The sum of $$$n$$$ over all testcases doesn't exceed $$$3 \cdot 10^5$$$.
2,000
For each testcase print $$$n$$$ integers — for the $$$i$$$-th robot output the time it explodes at if it does and $$$-1$$$ otherwise.
standard output
PASSED
858effb09d864b1ca317be053a6fa611
train_110.jsonl
1621152000
There are $$$n$$$ robots driving along an OX axis. There are also two walls: one is at coordinate $$$0$$$ and one is at coordinate $$$m$$$.The $$$i$$$-th robot starts at an integer coordinate $$$x_i~(0 &lt; x_i &lt; m)$$$ and moves either left (towards the $$$0$$$) or right with the speed of $$$1$$$ unit per second. No two robots start at the same coordinate.Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed.Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens.For each robot find out if it ever explodes and print the time of explosion if it happens and $$$-1$$$ otherwise.
256 megabytes
import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.InputMismatchException; import java.util.List; import java.util.Stack; public class Main { private static final String NO = "No"; private static final String YES = "Yes"; InputStream is; PrintWriter out; String INPUT = ""; private static final long MOD = 998244353L; void solve() { int T = ni(); for (int i = 0; i < T; i++) solve(i); } void solve(int p) { int n = ni(); int M = ni(); int[] a = na(n); int ans[] = new int[n]; char[] dir = nc(n); Arrays.fill(ans, -1); Integer ind[] = new Integer[n]; Arrays.setAll(ind, i -> i); Arrays.sort(ind, (x, y) -> a[x] - a[y]); for (int i = 0; i < 2; i++) { Stack<Integer> s = new Stack<Integer>(); for (int jj = 0; jj < n; jj++) { int j = ind[jj]; if (a[j] % 2 == i) { if (dir[j] == 'R' || s.isEmpty()) s.push(j); else { int k = s.pop(); int d = a[j] + (dir[k] == 'L' ? a[k] : -a[k]); ans[j] = ans[k] = d / 2; } } } while (s.size() >= 2) { int k = s.pop(); int j = s.pop(); int d = 2 * M - a[k] + (dir[j] == 'L' ? a[j] : -a[j]); ans[j] = ans[k] = d / 2; } } for (int i : ans) out.print(i + " "); out.println(); } // a^b long power(long a, long b) { long x = 1, y = a; while (b > 0) { if (b % 2 != 0) { x = (x * y) % MOD; } y = (y * y) % MOD; b /= 2; } return x % MOD; } private long gcd(long a, long b) { while (a != 0) { long tmp = b % a; b = a; a = tmp; } return b; } void run() throws Exception { is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes()); out = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); out.flush(); if (!INPUT.isEmpty()) tr(System.currentTimeMillis() - s + "ms"); } public static void main(String[] args) throws Exception { new Main().run(); } private byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; private int readByte() { if (lenbuf == -1) throw new InputMismatchException(); if (ptrbuf >= lenbuf) { ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if (lenbuf <= 0) return -1; } return inbuf[ptrbuf++]; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while ((b = readByte()) != -1 && isSpaceChar(b)) ; return b; } private double nd() { return Double.parseDouble(ns()); } private char nc() { return (char) skip(); } private char[] nc(int n) { char[] ret = new char[n]; for (int i = 0; i < n; i++) ret[i] = nc(); return ret; } private String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' // ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private char[] ns(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while (p < n) { if (!(isSpaceChar(b))) buf[p++] = (char) b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private char[][] nm(int n, int m) { char[][] map = new char[n][]; for (int i = 0; i < n; i++) map[i] = ns(m); return map; } private int[] na(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = ni(); return a; } private List<Integer> na2(int n) { List<Integer> a = new ArrayList<Integer>(); for (int i = 0; i < n; i++) a.add(ni()); return a; } private int[][] na(int n, int m) { int[][] a = new int[n][]; for (int i = 0; i < n; i++) a[i] = na(m); return a; } private int ni() { int num = 0, b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } private long[] nl(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nl(); return a; } private long[][] nl(int n, int m) { long[][] a = new long[n][]; for (int i = 0; i < n; i++) a[i] = nl(m); return a; } private long nl() { long num = 0; int b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } private static void tr(Object... o) { System.out.println(Arrays.deepToString(o)); } }
Java
["5\n7 12\n1 2 3 4 9 10 11\nR R L L R R R\n2 10\n1 6\nR R\n2 10\n1 3\nL L\n1 10\n5\nR\n7 8\n6 1 7 2 3 5 4\nR L R L L L L"]
2 seconds
["1 1 1 1 2 -1 2 \n-1 -1 \n2 2 \n-1 \n-1 2 7 3 2 7 3"]
NoteHere is the picture for the seconds $$$0, 1, 2$$$ and $$$3$$$ of the first testcase: Notice that robots $$$2$$$ and $$$3$$$ don't collide because they meet at the same point $$$2.5$$$, which is not integer.After second $$$3$$$ robot $$$6$$$ just drive infinitely because there's no robot to collide with.
Java 11
standard input
[ "data structures", "greedy", "implementation", "sortings" ]
1a28b972e77966453cd8239cc5c8f59a
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5$$$; $$$2 \le m \le 10^8$$$) — the number of robots and the coordinate of the right wall. The second line of each testcase contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$0 &lt; x_i &lt; m$$$) — the starting coordinates of the robots. The third line of each testcase contains $$$n$$$ space-separated characters 'L' or 'R' — the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates $$$x_i$$$ in the testcase are distinct. The sum of $$$n$$$ over all testcases doesn't exceed $$$3 \cdot 10^5$$$.
2,000
For each testcase print $$$n$$$ integers — for the $$$i$$$-th robot output the time it explodes at if it does and $$$-1$$$ otherwise.
standard output
PASSED
68286a98d471785bb90585148e62aae0
train_110.jsonl
1621152000
There are $$$n$$$ robots driving along an OX axis. There are also two walls: one is at coordinate $$$0$$$ and one is at coordinate $$$m$$$.The $$$i$$$-th robot starts at an integer coordinate $$$x_i~(0 &lt; x_i &lt; m)$$$ and moves either left (towards the $$$0$$$) or right with the speed of $$$1$$$ unit per second. No two robots start at the same coordinate.Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed.Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens.For each robot find out if it ever explodes and print the time of explosion if it happens and $$$-1$$$ otherwise.
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; public class Main { PrintWriter out = new PrintWriter(System.out); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer tok = new StringTokenizer(""); String next() throws IOException { if (!tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); } return tok.nextToken(); } int ni() throws IOException { return Integer.parseInt(next()); } long nl() throws IOException { return Long.parseLong(next()); } long mod=1000000007; void solve() throws IOException { for (int tc=ni();tc>0;tc--) { int n=ni(),m=ni(); int[]A=new int[n+1]; int[]B=new int[n+1]; int[]Z=new int[n+1]; for (int i=1;i<=n;i++) A[i]=ni(); for (int i=1;i<=n;i++) if (next().charAt(0)=='R') B[i]=1; for (int j=0;j<2;j++) { ArrayList<Integer>C=new ArrayList(); for (int i=1;i<=n;i++) if (A[i]%2==j) C.add(i); Collections.sort(C,(a,b)->Integer.compare(A[a],A[b])); //for (int u:C) out.println(u+" "+A[u]); //out.println(); Stack<Integer>S=new Stack(); for (int u:C) { if (B[u]==1) S.push(u); else { if (!S.empty()) { int v=S.pop(); int x=(A[u]-A[v])/2; Z[u]=x; Z[v]=x; } else { A[u]*=-1; S.push(u); } } } while (!S.empty()) { if (S.size()==1) Z[S.pop()]=-1; else { int u=S.pop(); A[u]=2*m-A[u]; int v=S.pop(); int x=(A[u]-A[v])/2; Z[u]=x; Z[v]=x; } } } for (int i=1;i<=n;i++) out.print(Z[i]+" "); out.println(); } out.flush(); } int gcd(int a,int b) { return(b==0?a:gcd(b,a%b)); } long gcd(long a,long b) { return(b==0?a:gcd(b,a%b)); } long mp(long a,long p) { long r=1; while(p>0) { if ((p&1)==1) r=(r*a)%mod; p>>=1; a=(a*a)%mod; } return r; } public static void main(String[] args) throws IOException { new Main().solve(); } }
Java
["5\n7 12\n1 2 3 4 9 10 11\nR R L L R R R\n2 10\n1 6\nR R\n2 10\n1 3\nL L\n1 10\n5\nR\n7 8\n6 1 7 2 3 5 4\nR L R L L L L"]
2 seconds
["1 1 1 1 2 -1 2 \n-1 -1 \n2 2 \n-1 \n-1 2 7 3 2 7 3"]
NoteHere is the picture for the seconds $$$0, 1, 2$$$ and $$$3$$$ of the first testcase: Notice that robots $$$2$$$ and $$$3$$$ don't collide because they meet at the same point $$$2.5$$$, which is not integer.After second $$$3$$$ robot $$$6$$$ just drive infinitely because there's no robot to collide with.
Java 11
standard input
[ "data structures", "greedy", "implementation", "sortings" ]
1a28b972e77966453cd8239cc5c8f59a
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5$$$; $$$2 \le m \le 10^8$$$) — the number of robots and the coordinate of the right wall. The second line of each testcase contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$0 &lt; x_i &lt; m$$$) — the starting coordinates of the robots. The third line of each testcase contains $$$n$$$ space-separated characters 'L' or 'R' — the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates $$$x_i$$$ in the testcase are distinct. The sum of $$$n$$$ over all testcases doesn't exceed $$$3 \cdot 10^5$$$.
2,000
For each testcase print $$$n$$$ integers — for the $$$i$$$-th robot output the time it explodes at if it does and $$$-1$$$ otherwise.
standard output
PASSED
a3a01e2599ffaa66d9ad3876a27d1ca5
train_110.jsonl
1621152000
There are $$$n$$$ robots driving along an OX axis. There are also two walls: one is at coordinate $$$0$$$ and one is at coordinate $$$m$$$.The $$$i$$$-th robot starts at an integer coordinate $$$x_i~(0 &lt; x_i &lt; m)$$$ and moves either left (towards the $$$0$$$) or right with the speed of $$$1$$$ unit per second. No two robots start at the same coordinate.Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed.Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens.For each robot find out if it ever explodes and print the time of explosion if it happens and $$$-1$$$ otherwise.
256 megabytes
/*========================================================================== * AUTHOR: RonWonWon * CREATED: 16.05.2021 13:49:41 * EMAIL: rachitpts.2454@gmail.com /*==========================================================================*/ import java.io.*; import java.util.*; public class C { public static void main(String[] args) { FastScanner in = new FastScanner(); PrintWriter out = new PrintWriter(System.out); int t = in.nextInt(), tt = 1; while(t-->0) { int n = in.nextInt(), m = in.nextInt(); int aa[] = in.readArray(n); int a[] = new int[n]; char ch[] = new char[n]; for(int i=0;i<n;i++) ch[i] = in.next().charAt(0); Pair sor[] = new Pair[n]; for(int i=0;i<n;i++) sor[i] = new Pair(ch[i],aa[i]); Arrays.sort(sor); for(int i=0;i<n;i++){ a[i] = sor[i].y; ch[i] = sor[i].x; } ArrayDeque<Integer> Rodd = new ArrayDeque<>(), Reven = new ArrayDeque<>(); ArrayDeque<Integer> Lodd = new ArrayDeque<>(), Leven = new ArrayDeque<>(); HashMap<Integer, Integer> map = new HashMap<>(); for(int i : a) map.put(i,-1); int ind = 0; for(int i : a){ if(i%2==0){ if(ch[ind]=='R') Reven.addLast(i); else{ if(Reven.isEmpty()==false){ int last = Reven.pollLast(); int x = (i-last)/2; map.put(last,x); map.put(i,x); } else Leven.addLast(i); } } else{ if(ch[ind]=='R') Rodd.addLast(i); else{ if(Rodd.isEmpty()==false){ int last = Rodd.pollLast(); int x = (i-last)/2; map.put(last,x); map.put(i,x); } else Lodd.addLast(i); } } ind++; } //Right int prev = -1; Iterator<Integer> it = Rodd.descendingIterator(); while(it.hasNext()){ int i = it.next(); if(prev==-1) prev = i; else{ int x = (m-prev) + (prev-i)/2; map.put(prev,x); map.put(i,x); prev = -1; } } prev = -1; it = Reven.descendingIterator(); while(it.hasNext()){ int i = it.next(); if(prev==-1) prev = i; else{ int x = (m-prev) + (prev-i)/2; map.put(prev,x); map.put(i,x); prev = -1; } } //Left prev = -1; for(int i : Lodd){ if(prev==-1) prev = i; else{ int x = (prev) + (i-prev)/2; map.put(prev,x); map.put(i,x); prev = -1; } } prev = -1; for(int i : Leven){ if(prev==-1) prev = i; else{ int x = (prev) + (i-prev)/2; map.put(prev,x); map.put(i,x); prev = -1; } } if(Lodd.size()%2==1&&Rodd.size()%2==1){ int x = Lodd.pollLast(), y = Rodd.pollFirst(); int max = Math.max(m-y,x); int xx = max; int curx = -1*(x-max), cury = m-(y+max-m); xx += (cury-curx)/2; map.put(x,xx); map.put(y,xx); } if(Leven.size()%2==1&&Reven.size()%2==1){ int x = Leven.pollLast(), y = Reven.pollFirst(); int max = Math.max(m-y,x); int xx = max; int curx = -1*(x-max), cury = m-(y+max-m); xx += (cury-curx)/2; map.put(x,xx); map.put(y,xx); } for(int i=0;i<n;i++){ out.print(map.get(aa[i])+" "); } out.println(); //out.println("Case #"+tt+": "+ans); tt++; } out.flush(); } static class Pair implements Comparable<Pair> { char x; int y; Pair(char a, int b){ x = a; y = b; } @Override public int compareTo(Pair o) { if(o.y - this.y>0) return -1; else if(o.y - this.y<0) return 1; else return 0; } } 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) {} return st.nextToken(); } String nextLine(){ try{ return br.readLine(); } catch(IOException e) { } return ""; } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } int[] readArray(int n) { int a[] = new int[n]; for(int i=0;i<n;i++) a[i] = nextInt(); return a; } } static final Random random = new Random(); static void ruffleSort(int[] a){ int n = a.length; for(int i=0;i<n;i++){ int j = random.nextInt(n), temp = a[j]; a[j] = a[i]; a[i] = temp; } Arrays.sort(a); } }
Java
["5\n7 12\n1 2 3 4 9 10 11\nR R L L R R R\n2 10\n1 6\nR R\n2 10\n1 3\nL L\n1 10\n5\nR\n7 8\n6 1 7 2 3 5 4\nR L R L L L L"]
2 seconds
["1 1 1 1 2 -1 2 \n-1 -1 \n2 2 \n-1 \n-1 2 7 3 2 7 3"]
NoteHere is the picture for the seconds $$$0, 1, 2$$$ and $$$3$$$ of the first testcase: Notice that robots $$$2$$$ and $$$3$$$ don't collide because they meet at the same point $$$2.5$$$, which is not integer.After second $$$3$$$ robot $$$6$$$ just drive infinitely because there's no robot to collide with.
Java 8
standard input
[ "data structures", "greedy", "implementation", "sortings" ]
1a28b972e77966453cd8239cc5c8f59a
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5$$$; $$$2 \le m \le 10^8$$$) — the number of robots and the coordinate of the right wall. The second line of each testcase contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$0 &lt; x_i &lt; m$$$) — the starting coordinates of the robots. The third line of each testcase contains $$$n$$$ space-separated characters 'L' or 'R' — the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates $$$x_i$$$ in the testcase are distinct. The sum of $$$n$$$ over all testcases doesn't exceed $$$3 \cdot 10^5$$$.
2,000
For each testcase print $$$n$$$ integers — for the $$$i$$$-th robot output the time it explodes at if it does and $$$-1$$$ otherwise.
standard output
PASSED
99ad19b8f8224b34c2dfe1f187304e9c
train_110.jsonl
1621152000
There are $$$n$$$ robots driving along an OX axis. There are also two walls: one is at coordinate $$$0$$$ and one is at coordinate $$$m$$$.The $$$i$$$-th robot starts at an integer coordinate $$$x_i~(0 &lt; x_i &lt; m)$$$ and moves either left (towards the $$$0$$$) or right with the speed of $$$1$$$ unit per second. No two robots start at the same coordinate.Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed.Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens.For each robot find out if it ever explodes and print the time of explosion if it happens and $$$-1$$$ otherwise.
256 megabytes
import java.io.*; import java.util.*; import java.math.*; import java.math.BigInteger; //import javafx.util.*; public final class B { static StringBuilder ans=new StringBuilder(); static FastReader in=new FastReader(); static ArrayList<ArrayList<Integer>> g; static long mod=(long)(1e9+7); static int D1[],D2[],par[]; static boolean set[]; static int value[]; static long INF=Long.MAX_VALUE; static int dp[][]; static int N,M; static int A[][],B[][]; static int s=1; public static void main(String args[])throws IOException { int T=i(); outer:while(T-->0) { int N=i(),M=i(); int B[]=input(N); char X[]=new char[N]; ArrayList<node> A=new ArrayList<node>(); for(int i=0; i<N; i++) { if(in.next().charAt(0)=='R') { X[i]='R'; A.add(new node(B[i],true,i)); } else { X[i]='L'; A.add(new node(B[i],false,i)); } } Collections.sort(A); int f[]=new int[N]; Arrays.fill(f, -1); ArrayList<Integer> odd=new ArrayList<Integer>(); ArrayList<Integer> even=new ArrayList<Integer>(); for(node x:A) { if(x.x%2==0)even.add(x.index); else odd.add(x.index); } ArrayList<Integer> last=new ArrayList<>(); for(int i:even) { if(X[i]=='R')last.add(i); else { if(last.size()>0) { int b=last.remove(last.size()-1); int d=B[i]-B[b]; d/=2; f[i]=d; f[b]=d; } } } //print(f); while(last.size()>1) { int n=last.size(); int a=last.remove(n-1),b=last.remove(n-2); int d=(M-B[a])+((B[a]-B[b])/2); //System.out.println(a+" "+b); f[a]=d;f[b]=d; } last=new ArrayList<>(); int lt=-1; for(int i:even) { if(f[i]==-1 && X[i]=='L') { if(lt==-1) { lt=i; } else { int a=lt,b=i; int d=B[a]+((B[b]-B[a])/2); f[a]=d; f[b]=d; lt=-1; } } } if(lt!=-1) { for(int i:even) { if(f[i]==-1 && X[i]=='R') { int a=lt,b=i; int d=B[a]+(M-B[b])+M; d/=2; f[a]=d; f[b]=d; } } } last=new ArrayList<>(); for(int i:odd) { if(X[i]=='R')last.add(i); else { if(last.size()>0) { int b=last.remove(last.size()-1); int d=B[i]-B[b]; d/=2; f[i]=d; f[b]=d; } } } while(last.size()>1) { int n=last.size(); int a=last.remove(n-1),b=last.remove(n-2); int d=(M-B[a])+((B[a]-B[b])/2); f[a]=d;f[b]=d; } last=new ArrayList<>(); lt=-1; for(int i:odd) { if(f[i]==-1 && X[i]=='L') { if(lt==-1) { lt=i; } else { int a=lt,b=i; int d=B[a]+((B[b]-B[a])/2); f[a]=d; f[b]=d; lt=-1; } } } if(lt!=-1) { for(int i:odd) { if(f[i]==-1 && X[i]=='R') { int a=lt,b=i; int d=B[a]+(M-B[b])+M; d/=2; f[a]=d; f[b]=d; } } } for(int a:f)ans.append(a+" "); ans.append("\n"); } System.out.println(ans); } static int f(int i,int j,ArrayList<Integer> one,ArrayList<Integer> zero, int s) { if(i==one.size())return s; if(j==zero.size())return Integer.MAX_VALUE; int a=one.get(i),b=zero.get(j); if(dp[a][b]==-1) { int min=Integer.MAX_VALUE; for(int t=j; t<zero.size(); t++) { min=Math.min(min, f(i+1,t+1,one,zero,s+Math.abs(b-a))); } dp[a][b]=min; } a=one.get(i);b=zero.get(j); return dp[a][b]; } 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; } static int f1(int x,ArrayList<Integer> A) { int l=-1,r=A.size(); while(r-l>1) { int m=(l+r)/2; int a=A.get(m); if(a<x)l=m; else r=m; } return l; } static int ask(int t,int i,int j,int x) { System.out.println("? "+t+" "+i+" "+j+" "+x); return i(); } static int ask(int a) { System.out.println("? 1 "+a); return i(); } static int f(int st,int end,int d) { if(st>end)return 0; int a=0,b=0,c=0; if(d>1)a=f(st+d-1,end,d-1); b=f(st+d,end,d); c=f(st+d+1,end,d+1); return value[st]+max(a,b,c); } static int max(int a,int b,int c) { return Math.max(a, Math.max(c, b)); } static int value(char X[],char Y[]) { int c=0; for(int i=0; i<7; i++) { if(Y[i]=='1' && X[i]=='0')return -1; if(X[i]=='1' && Y[i]=='0')c++; } return c; } static boolean isValid(int i,int j) { if(i<0 || i>=N)return false; if(j<0 || j>=M)return false; return true; } static long fact(long N) { long num=1L; while(N>=1) { num=((num%mod)*(N%mod))%mod; N--; } return num; } static boolean reverse(long A[],int l,int r) { while(l<r) { long t=A[l]; A[l]=A[r]; A[r]=t; l++; r--; } if(isSorted(A))return true; else return false; } static boolean isSorted(long A[]) { for(int i=1; i<A.length; i++)if(A[i]<A[i-1])return false; return true; } static boolean isPalindrome(char X[],int l,int r) { while(l<r) { if(X[l]!=X[r])return false; l++; r--; } return true; } static long min(long a,long b,long c) { return Math.min(a, Math.min(c, b)); } static void print(int a) { System.out.println("! "+a); } static int ask(int a,int b) { System.out.println("? "+a+" "+b); return i(); } 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) { par[a]+=par[b]; //transfers the size par[b]=a; //changes the parent } } static void swap(char A[],int a,int b) { char ch=A[a]; A[a]=A[b]; A[b]=ch; } 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 void setGraph(int N) { g=new ArrayList<ArrayList<Integer>>(); for(int i=0; i<=N; i++) { g.add(new ArrayList<Integer>()); } } 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 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 long GCD(long a,long b) { if(b==0) { return a; } else return GCD(b,a%b ); } //Debugging Functions Starts 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(ArrayList<Integer> A) { for(int a:A)System.out.print(a+" "); System.out.println(); } //Debugging Functions END //---------------------- //IO FUNCTIONS STARTS 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 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; } //IO FUNCTIONS END } class node implements Comparable<node> { int x,index; boolean right; node(int x,boolean right,int index) { this.x=x; this.right=right; this.index=index; } public int compareTo(node X) { return this.x-X.x; } } //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()); } //gey double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str=""; try { str=br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } }
Java
["5\n7 12\n1 2 3 4 9 10 11\nR R L L R R R\n2 10\n1 6\nR R\n2 10\n1 3\nL L\n1 10\n5\nR\n7 8\n6 1 7 2 3 5 4\nR L R L L L L"]
2 seconds
["1 1 1 1 2 -1 2 \n-1 -1 \n2 2 \n-1 \n-1 2 7 3 2 7 3"]
NoteHere is the picture for the seconds $$$0, 1, 2$$$ and $$$3$$$ of the first testcase: Notice that robots $$$2$$$ and $$$3$$$ don't collide because they meet at the same point $$$2.5$$$, which is not integer.After second $$$3$$$ robot $$$6$$$ just drive infinitely because there's no robot to collide with.
Java 8
standard input
[ "data structures", "greedy", "implementation", "sortings" ]
1a28b972e77966453cd8239cc5c8f59a
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5$$$; $$$2 \le m \le 10^8$$$) — the number of robots and the coordinate of the right wall. The second line of each testcase contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$0 &lt; x_i &lt; m$$$) — the starting coordinates of the robots. The third line of each testcase contains $$$n$$$ space-separated characters 'L' or 'R' — the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates $$$x_i$$$ in the testcase are distinct. The sum of $$$n$$$ over all testcases doesn't exceed $$$3 \cdot 10^5$$$.
2,000
For each testcase print $$$n$$$ integers — for the $$$i$$$-th robot output the time it explodes at if it does and $$$-1$$$ otherwise.
standard output
PASSED
89ec84b7058e24697fd4883cb5389f03
train_110.jsonl
1621152000
There are $$$n$$$ robots driving along an OX axis. There are also two walls: one is at coordinate $$$0$$$ and one is at coordinate $$$m$$$.The $$$i$$$-th robot starts at an integer coordinate $$$x_i~(0 &lt; x_i &lt; m)$$$ and moves either left (towards the $$$0$$$) or right with the speed of $$$1$$$ unit per second. No two robots start at the same coordinate.Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed.Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens.For each robot find out if it ever explodes and print the time of explosion if it happens and $$$-1$$$ otherwise.
256 megabytes
import java.lang.*; import java.util.*; import java.io.*; public class Main { static PrintWriter pw = new PrintWriter(System.out); static void deal(int[][] arr,int n,int m) { Arrays.sort(arr,(o1,o2)->Integer.compare(o1[0],o2[0])); LinkedList<Integer> pq0 = new LinkedList<>(); LinkedList<Integer> pq1 = new LinkedList<>(); int[] res = new int[n]; for(int i=0;i<n;i++) { LinkedList<Integer> pq; if((arr[i][0]&1) == 0) { pq = pq0; } else { pq = pq1; } if(arr[i][1] == 1) { pq.addLast(i); } else { if(pq.size()>0) { int index = pq.pollLast(); int time = (arr[i][0]-arr[index][0])/2; res[arr[i][2]] = time; res[arr[index][2]] = time; } else { arr[i][1] =1; arr[i][0] = -arr[i][0]; pq.addLast(i); } } } while(pq0.size()>0) { int index1 = pq0.pollLast(); if(pq0.size() == 0) { res[arr[index1][2]] = -1; } else { int index2 = pq0.pollLast(); int p = m+m-arr[index1][0]; int time = (p-arr[index2][0])/2; res[arr[index1][2]] = time; res[arr[index2][2]] = time; } } while(pq1.size()>0) { int index1 = pq1.pollLast(); if(pq1.size() == 0) { res[arr[index1][2]] = -1; } else { int index2 = pq1.pollLast(); int p = m+m-arr[index1][0]; int time = (p-arr[index2][0])/2; res[arr[index1][2]] = time; res[arr[index2][2]] = time; } } for(int i=0;i<n;i++) { pw.print(res[i]); pw.print(' '); } pw.println(); } public static void main(String[] args) { MyScanner scanner = new MyScanner(); int t = scanner.nextInt(); for(int i=0;i<t;i++) { int n = scanner.nextInt(); int m = scanner.nextInt(); int[][] arr = new int[n][3]; for(int j=0;j<n;j++) arr[j][0] = scanner.nextInt(); String str = scanner.nextLine(); String[] stArr = str.split(" "); for(int j=0;j<n;j++) { if("L".equals(stArr[j])) { arr[j][1] = -1; } else { arr[j][1] = 1; } arr[j][2] = j; } deal(arr,n,m); } pw.close(); } 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\n7 12\n1 2 3 4 9 10 11\nR R L L R R R\n2 10\n1 6\nR R\n2 10\n1 3\nL L\n1 10\n5\nR\n7 8\n6 1 7 2 3 5 4\nR L R L L L L"]
2 seconds
["1 1 1 1 2 -1 2 \n-1 -1 \n2 2 \n-1 \n-1 2 7 3 2 7 3"]
NoteHere is the picture for the seconds $$$0, 1, 2$$$ and $$$3$$$ of the first testcase: Notice that robots $$$2$$$ and $$$3$$$ don't collide because they meet at the same point $$$2.5$$$, which is not integer.After second $$$3$$$ robot $$$6$$$ just drive infinitely because there's no robot to collide with.
Java 8
standard input
[ "data structures", "greedy", "implementation", "sortings" ]
1a28b972e77966453cd8239cc5c8f59a
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5$$$; $$$2 \le m \le 10^8$$$) — the number of robots and the coordinate of the right wall. The second line of each testcase contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$0 &lt; x_i &lt; m$$$) — the starting coordinates of the robots. The third line of each testcase contains $$$n$$$ space-separated characters 'L' or 'R' — the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates $$$x_i$$$ in the testcase are distinct. The sum of $$$n$$$ over all testcases doesn't exceed $$$3 \cdot 10^5$$$.
2,000
For each testcase print $$$n$$$ integers — for the $$$i$$$-th robot output the time it explodes at if it does and $$$-1$$$ otherwise.
standard output
PASSED
33e3cb03345c88dbec00a289c561247c
train_110.jsonl
1621152000
There are $$$n$$$ robots driving along an OX axis. There are also two walls: one is at coordinate $$$0$$$ and one is at coordinate $$$m$$$.The $$$i$$$-th robot starts at an integer coordinate $$$x_i~(0 &lt; x_i &lt; m)$$$ and moves either left (towards the $$$0$$$) or right with the speed of $$$1$$$ unit per second. No two robots start at the same coordinate.Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed.Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens.For each robot find out if it ever explodes and print the time of explosion if it happens and $$$-1$$$ otherwise.
256 megabytes
import java.io.*; import java.util.*; public class C { static class Data{ int val; int Direction; int index; Data(int val, char c, int index) { this.val = val; this.Direction = c; this.index = index; } } static class comp implements Comparator<Data> { @Override public int compare(Data o1, Data o2) { return o1.val - o2.val; } } static class Reader{ private BufferedReader reader; private StringTokenizer tokenizer; Reader(InputStream input) { this.reader = new BufferedReader(new InputStreamReader(input)); this.tokenizer = new StringTokenizer(""); } public String next() throws IOException { while(!tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } 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 int[] nextIntArr(int n) throws IOException { int[] arr = new int[n]; for(int i=0;i<n;i++)arr[i]=nextInt(); return arr; } public char[] nextCharArr(int n) throws IOException { char[] arr = new char[n]; for(int i=0;i<n;i++)arr[i] = next().charAt(0); return arr; } } public static void main(String[] args) throws IOException { Reader scan = new Reader(System.in); int Test = scan.nextInt(); StringBuffer sb = new StringBuffer(); BufferedOutputStream b = new BufferedOutputStream(System.out); while(Test-->0) { int N = scan.nextInt(); int M = scan.nextInt(); int[] arr = scan.nextIntArr(N); char[] s = scan.nextCharArr(N); int[] ans = new int[N]; Arrays.fill(ans,-1); // System.out.print(s); // int j = 0; // for(int i=0;i<s.length();i++ ) // { // if(s.charAt(i)!=' '){s2[j] = s.charAt(i); j++;} // } ArrayList<Data> evenSet = new ArrayList<>(); ArrayList<Data> oddSet = new ArrayList<>(); for(int i=0;i<N;i++) { if(arr[i]%2==0) evenSet.add(new Data(arr[i],s[i],i)); } for(int i=0;i<N;i++)if(arr[i]%2!=0)oddSet.add(new Data(arr[i],s[i],i)); evenSet.sort(new comp()); oddSet.sort(new comp()); solve(evenSet,N,M,ans); solve(oddSet,N,M,ans); sb.append(getFinalAns(ans)); } b.write((sb.toString()).getBytes()); b.flush(); } private static String getFinalAns(int[] ans) { StringBuilder sb = new StringBuilder(); for(int i:ans)sb.append(i+" "); return sb.toString()+"\n"; } private static void solve(ArrayList<Data> a, int n, int m, int[] ans) { ArrayDeque<Data> Stack = new ArrayDeque<>(); for(Data d : a) { if(!Stack.isEmpty() && d.Direction=='L' && Stack.peekLast().Direction=='R') { Data d1 = Stack.peekLast(); Stack.pollLast(); int ct = calculateTime(d1,d,m); ans[d1.index]= ct; ans[d.index] = ct; continue; } Stack.addLast(d); } while(!Stack.isEmpty() && Stack.peekFirst().Direction=='L') { Data d = Stack.pollFirst(); if(!Stack.isEmpty() && Stack.peekFirst().Direction=='L') { Data d1 = Stack.pollFirst(); int ct = calculateTime(d1,d,m); ans[d.index] = ct; ans[d1.index] = ct; continue; } Stack.addFirst(d); break; } while(!Stack.isEmpty() && Stack.peekLast().Direction=='R') { Data d = Stack.pollLast(); if(!Stack.isEmpty() && Stack.peekLast().Direction=='R') { Data d1 = Stack.pollLast(); int ct = calculateTime(d1,d,m); ans[d.index] = ct; ans[d1.index] = ct; continue; } Stack.addLast(d); break; } if(Stack.size()==2) { Data d1 = Stack.pollLast(); Data d2 = Stack.pollLast(); int ct = calculateTime(d2,d1,m); ans[d1.index] = ct; ans[d2.index] = ct; } } // 0 1 2 3 4 5 6 7 8 // 3->4->5->6->7->8->7 // 5->6->7->8->7->6->5->4->3 // (m - ((m-pos2)+pos1))/2 + (m-pos2); private static int calculateTime(Data d1, Data d, int m) { if(d1.Direction == d.Direction && d1.Direction == 'L')return (d1.val+d.val)/2; else if(d1.Direction=='L' && d.Direction=='R') return (m+d1.val + m - d.val)/2; else if(d1.Direction=='R' && d.Direction=='L') return (d.val-d1.val)/2; return (m - d1.val + m - d.val)/2; } }
Java
["5\n7 12\n1 2 3 4 9 10 11\nR R L L R R R\n2 10\n1 6\nR R\n2 10\n1 3\nL L\n1 10\n5\nR\n7 8\n6 1 7 2 3 5 4\nR L R L L L L"]
2 seconds
["1 1 1 1 2 -1 2 \n-1 -1 \n2 2 \n-1 \n-1 2 7 3 2 7 3"]
NoteHere is the picture for the seconds $$$0, 1, 2$$$ and $$$3$$$ of the first testcase: Notice that robots $$$2$$$ and $$$3$$$ don't collide because they meet at the same point $$$2.5$$$, which is not integer.After second $$$3$$$ robot $$$6$$$ just drive infinitely because there's no robot to collide with.
Java 8
standard input
[ "data structures", "greedy", "implementation", "sortings" ]
1a28b972e77966453cd8239cc5c8f59a
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5$$$; $$$2 \le m \le 10^8$$$) — the number of robots and the coordinate of the right wall. The second line of each testcase contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$0 &lt; x_i &lt; m$$$) — the starting coordinates of the robots. The third line of each testcase contains $$$n$$$ space-separated characters 'L' or 'R' — the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates $$$x_i$$$ in the testcase are distinct. The sum of $$$n$$$ over all testcases doesn't exceed $$$3 \cdot 10^5$$$.
2,000
For each testcase print $$$n$$$ integers — for the $$$i$$$-th robot output the time it explodes at if it does and $$$-1$$$ otherwise.
standard output
PASSED
2c566e9462482517a37d012d3a7c6e68
train_110.jsonl
1621152000
There are $$$n$$$ robots driving along an OX axis. There are also two walls: one is at coordinate $$$0$$$ and one is at coordinate $$$m$$$.The $$$i$$$-th robot starts at an integer coordinate $$$x_i~(0 &lt; x_i &lt; m)$$$ and moves either left (towards the $$$0$$$) or right with the speed of $$$1$$$ unit per second. No two robots start at the same coordinate.Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed.Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens.For each robot find out if it ever explodes and print the time of explosion if it happens and $$$-1$$$ otherwise.
256 megabytes
import java.io.*; import java.util.*; import java.math.*; public class Main { InputStream is; PrintWriter out; String INPUT = ""; //class Declaration static class pair implements Comparable < pair > { int x; int y; pair(int i, int j) { x = i; y = j; } public int compareTo(pair p) { if (this.x != p.x) { return Integer.compare(this.x,p.x); } else { return Integer.compare(this.y,p.y); } } public int hashCode() { return (x + " " + y).hashCode(); } public String toString() { return x + " " + y; } public boolean equals(Object o) { pair x = (pair) o; return (x.x == this.x && x.y == this.y); } } // int[] dx = {0,0,1,-1}; // int[] dy = {1,-1,0,0}; // int[] ddx = {0,0,1,-1,1,-1,1,-1}; // int[] ddy = {1,-1,0,0,1,-1,-1,1}; final int inf = (int) 1e9 + 9; final long biginf = (long)1e18 + 7 ; //final long mod = (long)1e9+7; final long mod = 998244353; TreeMap<Integer,Integer> ans ; int m = 0; void solve() throws Exception { int T=ni(); while(T-->0){ int n=ni(); m=ni(); ans = new TreeMap<>(); ArrayList<pair> al = new ArrayList<>(); int[] arr = na(n); char[] moves =new char[n]; for(int i=0;i<n;++i) moves[i]=ns().toCharArray()[0]; for(int i=0;i<n;++i) al.add(new pair(arr[i],moves[i]=='L'?0:1)); Collections.sort(al); ArrayList<pair> odd = new ArrayList<>(); ArrayList<pair> even = new ArrayList<>(); for(pair p : al){ if(p.x %2 == 0){ even.add(p); } else odd.add(p); } getAns(even); getAns(odd); for(int x: arr){ p(ans.get(x)); } pn(""); } } void getAns(ArrayList<pair> positions){ LinkedList<pair> Lstack = new LinkedList<>(); LinkedList<pair> Rstack = new LinkedList<>(); for(pair p : positions){ if(p.y == 0){ if(Rstack.size() > 0){ pair lastR = Rstack.pollLast(); ans.put(p.x,(p.x - lastR.x)/2); ans.put(lastR.x,(p.x - lastR.x)/2); } else{ Lstack.add(p); } } else{ Rstack.add(p); } } pair Lremain= null; pair Rremain= null; if(Lstack.size()%2 == 0){ addAnsLeft(Lstack); } else{ Lremain = Lstack.pollLast(); addAnsLeft(Lstack); } if(Rstack.size()%2 == 0){ addAnsRight(Rstack); } else{ Rremain = Rstack.pollFirst(); addAnsRight(Rstack); } if(Lremain != null && Rremain != null){ int time = Math.max(Lremain.x,m-Rremain.x) + Math.abs(Lremain.x-Rremain.x)/2 + Math.min(Lremain.x,m-Rremain.x) ; ans.put(Lremain.x,time); ans.put(Rremain.x,time); } else{ if(Lremain != null){ ans.put(Lremain.x,-1); } else{ if(Rremain != null){ ans.put(Rremain.x,-1); } } } } void addAnsLeft(LinkedList<pair> evenList){ while(evenList.size()>0){ pair f = evenList.pollFirst(); pair s = evenList.pollFirst(); ans.put(f.x,(Math.abs(f.x-s.x)/2) + Math.min(f.x,s.x) ); ans.put(s.x,(Math.abs(f.x-s.x)/2) + Math.min(f.x,s.x) ); } } void addAnsRight(LinkedList<pair> evenList){ while(evenList.size()>0){ pair f = evenList.pollFirst(); pair s = evenList.pollFirst(); ans.put(f.x,(Math.abs(f.x-s.x)/2) + Math.min(m-f.x,m-s.x) ); ans.put(s.x,(Math.abs(f.x-s.x)/2) + Math.min(m-f.x,m-s.x) ); } } long pow(long a, long b){ long result = 1; while (b > 0) { if (b % 2 == 1) result = (result * a) % mod; b /= 2; a = (a * a) % mod; } return result; } long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } void run() throws Exception { is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes()); out = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); out.flush(); // System.err.println(System.currentTimeMillis() - s + "ms"); } public static void main(String[] args) throws Exception { boolean memory = false ; if(memory) new Thread(null, new Runnable() {public void run(){try{new Main().run();}catch(Exception e){e.printStackTrace();System.exit(1);}}}, "1", 1 << 28).start(); else new Main().run(); } //output methods private void dbg(Object... o){ System.err.println(Arrays.deepToString(o));} void p(Object o){out.print(o+" ");} void pn(Object o){out.println(o);} void pni(Object o){out.println(o); out.flush();} //input methods private int[][] ng(int n, int e, int[] from, int[] to, boolean f){ int[][] g = new int[n+1][];int[]cnt = new int[n+1]; 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; } private int[][][] nwg(int n, int e, int[] from, int[] to, boolean f){ int[][][] g = new int[n+1][][];int[]cnt = new int[n+1]; 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; } private byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; private int readByte() { if (lenbuf == -1) throw new InputMismatchException(); if (ptrbuf >= lenbuf) { ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if (lenbuf <= 0) return -1; } return inbuf[ptrbuf++]; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while ((b = readByte()) != -1 && isSpaceChar(b)); return b; } private double nd() { return Double.parseDouble(ns()); } private char nc() { return (char) skip(); } private String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private char[] ns(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while (p < n && !(isSpaceChar(b))) { buf[p++] = (char) b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private char[][] nm(int n, int m) { char[][] map = new char[n][]; for (int i = 0; i < n; i++) map[i] = ns(m); return map; } private int[] na(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = ni(); return a; } private int ni() { int num = 0, b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } private long nl() { long num = 0; int b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } }
Java
["5\n7 12\n1 2 3 4 9 10 11\nR R L L R R R\n2 10\n1 6\nR R\n2 10\n1 3\nL L\n1 10\n5\nR\n7 8\n6 1 7 2 3 5 4\nR L R L L L L"]
2 seconds
["1 1 1 1 2 -1 2 \n-1 -1 \n2 2 \n-1 \n-1 2 7 3 2 7 3"]
NoteHere is the picture for the seconds $$$0, 1, 2$$$ and $$$3$$$ of the first testcase: Notice that robots $$$2$$$ and $$$3$$$ don't collide because they meet at the same point $$$2.5$$$, which is not integer.After second $$$3$$$ robot $$$6$$$ just drive infinitely because there's no robot to collide with.
Java 8
standard input
[ "data structures", "greedy", "implementation", "sortings" ]
1a28b972e77966453cd8239cc5c8f59a
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5$$$; $$$2 \le m \le 10^8$$$) — the number of robots and the coordinate of the right wall. The second line of each testcase contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$0 &lt; x_i &lt; m$$$) — the starting coordinates of the robots. The third line of each testcase contains $$$n$$$ space-separated characters 'L' or 'R' — the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates $$$x_i$$$ in the testcase are distinct. The sum of $$$n$$$ over all testcases doesn't exceed $$$3 \cdot 10^5$$$.
2,000
For each testcase print $$$n$$$ integers — for the $$$i$$$-th robot output the time it explodes at if it does and $$$-1$$$ otherwise.
standard output
PASSED
fd1246b71a37d564862837903aeab6d2
train_110.jsonl
1621152000
There are $$$n$$$ robots driving along an OX axis. There are also two walls: one is at coordinate $$$0$$$ and one is at coordinate $$$m$$$.The $$$i$$$-th robot starts at an integer coordinate $$$x_i~(0 &lt; x_i &lt; m)$$$ and moves either left (towards the $$$0$$$) or right with the speed of $$$1$$$ unit per second. No two robots start at the same coordinate.Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed.Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens.For each robot find out if it ever explodes and print the time of explosion if it happens and $$$-1$$$ otherwise.
256 megabytes
import java.io.*; import java.util.*; public final class Solution { static PrintWriter out = new PrintWriter(System.out); static FastReader in = new FastReader(); static long mod = (long) 1e9 + 7; static Pair[] moves = new Pair[]{new Pair(-1, 0), new Pair(1, 0), new Pair(0, -1), new Pair(0, 1)}; //Input //1 //20 50 //4 6 8 9 10 13 14 16 18 20 23 25 30 32 33 38 42 43 45 46 //L L L L L L L L L L R R R L L R R L R R //Output //5 5 9 11 9 11 15 15 19 19 10 4 1 1 4 10 10 10 -1 -1 //Answer //5 5 9 11 9 11 15 15 19 19 10 4 1 1 4 -1 6 10 -1 6 public static void main(String[] args) { int tt = i(); out: while (tt-- > 0) { int n = i(); int m = i(); int[] x = input(n); String s = s(); PriorityQueue<int[]> op = new PriorityQueue<>(Comparator.comparingInt(o -> o[1])); PriorityQueue<int[]> ep = new PriorityQueue<>(Comparator.comparingInt(o -> o[1])); for (int i = 0; i < n; i++) { int d = s.charAt(2 * i) == 'L' ? -1 : 1; if (x[i] % 2 == 0) { ep.add(new int[]{i, x[i], d}); } else { op.add(new int[]{i, x[i], d}); } } int[] ans = new int[n]; solve(op, ans, m); solve(ep, ans, m); print(ans); } out.flush(); } private static void solve(PriorityQueue<int[]> p, int[] ans, int m) { Deque<int[]> leftQueue = new LinkedList<>(); Deque<int[]> rightQueue = new LinkedList<>(); while (!p.isEmpty()) { int[] poll = p.poll(); if (poll[2] == 1) { rightQueue.offer(poll); } else { if (rightQueue.size() > 0) { int[] right = rightQueue.pollLast(); int t = (poll[1] - right[1]) / 2; ans[poll[0]] = t; ans[right[0]] = t; } else { leftQueue.offer(poll); } } } while (rightQueue.size() >= 2) { int[] x = rightQueue.pollLast(); int[] y = rightQueue.pollLast(); int w = m - x[1]; int yw = (x[1] - y[1]) / 2; int t = w + yw; ans[x[0]] = t; ans[y[0]] = t; } while (leftQueue.size() >= 2) { int[] x = leftQueue.poll(); int[] y = leftQueue.poll(); int w = x[1]; int yw = (y[1] - x[1]) / 2; int t = w + yw; ans[x[0]] = t; ans[y[0]] = t; } if (leftQueue.size() == 1 && rightQueue.size() == 1) { int[] x = leftQueue.poll(); int[] y = rightQueue.poll(); int t = (m + x[1] + m - y[1]) / 2; ans[x[0]] = t; ans[y[0]] = t; } if (!leftQueue.isEmpty()) { ans[leftQueue.poll()[0]] = -1; } if (!rightQueue.isEmpty()) { ans[rightQueue.poll()[0]] = -1; } } static boolean isPS(double number) { double sqrt = Math.sqrt(number); return ((sqrt - Math.floor(sqrt)) == 0); } static int sd(long i) { int d = 0; while (i > 0) { d += i % 10; i = i / 10; } return d; } static int[] leastPrime; static void sieveLinear(int N) { int[] primes = new int[N]; int idx = 0; leastPrime = new int[N + 1]; for (int i = 2; i <= N; i++) { if (leastPrime[i] == 0) { primes[idx++] = i; leastPrime[i] = i; } int curLP = leastPrime[i]; for (int j = 0; j < idx; j++) { int p = primes[j]; if (p > curLP || (long) p * i > N) { break; } else { leastPrime[p * i] = p; } } } } static int lower(long A[], long x) { int l = -1, r = A.length; while (r - l > 1) { int m = (l + r) / 2; if (A[m] >= x) { r = m; } else { l = m; } } return r; } static int upper(long A[], long x) { int l = -1, r = A.length; while (r - l > 1) { int m = (l + r) / 2; if (A[m] <= x) { l = m; } else { r = m; } } return l; } static void swap(int A[], int a, int b) { int t = A[a]; A[a] = A[b]; A[b] = t; } static int lowerBound(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 lowerBound(A, low, mid - 1, x); } return lowerBound(A, mid + 1, high, x); } static long pow(long a, long b) { 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 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) { 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 void printYes() { out.println("YES"); } static void printNo() { out.println("NO"); } static int i() { return in.nextInt(); } static long l() { return in.nextLong(); } static String s() { return in.nextLine(); } 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); } } } class BIT { int n; int[] tree; public BIT(int n) { this.n = n; this.tree = new int[n + 1]; } public static int lowbit(int x) { return x & (-x); } public void update(int x) { while (x <= n) { ++tree[x]; x += lowbit(x); } } public int query(int x) { int ans = 0; while (x > 0) { ans += tree[x]; x -= lowbit(x); } return ans; } public int query(int x, int y) { return query(y) - query(x - 1); } } class SegmentTree { long[] t; public SegmentTree(int n) { t = new long[n + n]; Arrays.fill(t, Long.MIN_VALUE); } public long get(int i) { return t[i + t.length / 2]; } public void add(int i, long value) { i += t.length / 2; t[i] = value; for (; i > 1; i >>= 1) { t[i >> 1] = Math.max(t[i], t[i ^ 1]); } } // max[a, b] public long max(int a, int b) { long res = Long.MIN_VALUE; for (a += t.length / 2, b += t.length / 2; a <= b; a = (a + 1) >> 1, b = (b - 1) >> 1) { if ((a & 1) != 0) { res = Math.max(res, t[a]); } if ((b & 1) == 0) { res = Math.max(res, t[b]); } } return res; } } class Pair { int i, j; Pair(int i, int j) { this.i = i; this.j = 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; } }
Java
["5\n7 12\n1 2 3 4 9 10 11\nR R L L R R R\n2 10\n1 6\nR R\n2 10\n1 3\nL L\n1 10\n5\nR\n7 8\n6 1 7 2 3 5 4\nR L R L L L L"]
2 seconds
["1 1 1 1 2 -1 2 \n-1 -1 \n2 2 \n-1 \n-1 2 7 3 2 7 3"]
NoteHere is the picture for the seconds $$$0, 1, 2$$$ and $$$3$$$ of the first testcase: Notice that robots $$$2$$$ and $$$3$$$ don't collide because they meet at the same point $$$2.5$$$, which is not integer.After second $$$3$$$ robot $$$6$$$ just drive infinitely because there's no robot to collide with.
Java 8
standard input
[ "data structures", "greedy", "implementation", "sortings" ]
1a28b972e77966453cd8239cc5c8f59a
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5$$$; $$$2 \le m \le 10^8$$$) — the number of robots and the coordinate of the right wall. The second line of each testcase contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$0 &lt; x_i &lt; m$$$) — the starting coordinates of the robots. The third line of each testcase contains $$$n$$$ space-separated characters 'L' or 'R' — the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates $$$x_i$$$ in the testcase are distinct. The sum of $$$n$$$ over all testcases doesn't exceed $$$3 \cdot 10^5$$$.
2,000
For each testcase print $$$n$$$ integers — for the $$$i$$$-th robot output the time it explodes at if it does and $$$-1$$$ otherwise.
standard output
PASSED
461406b074916ddd7185472cd07f0fd0
train_110.jsonl
1621152000
There are $$$n$$$ robots driving along an OX axis. There are also two walls: one is at coordinate $$$0$$$ and one is at coordinate $$$m$$$.The $$$i$$$-th robot starts at an integer coordinate $$$x_i~(0 &lt; x_i &lt; m)$$$ and moves either left (towards the $$$0$$$) or right with the speed of $$$1$$$ unit per second. No two robots start at the same coordinate.Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed.Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens.For each robot find out if it ever explodes and print the time of explosion if it happens and $$$-1$$$ otherwise.
256 megabytes
import java.util.*; import java.util.Map.Entry; import java.io.*; import java.math.*; /** * * @Har_Har_Mahadev */ /** * Main , Solution , Remove Public */ public class C { public static void process() throws IOException { TreeMap<Integer, Integer> rightOdd = new TreeMap<Integer, Integer>(); TreeMap<Integer, Integer> leftOdd = new TreeMap<Integer, Integer>(); TreeMap<Integer, Integer> rightEven = new TreeMap<Integer, Integer>(); TreeMap<Integer, Integer> leftEven = new TreeMap<Integer, Integer>(); int n = sc.nextInt(),m = sc.nextInt(); int arr[] = sc.readArray(n); char[] cc = new char[n]; for(int i = 0; i<n; i++) { cc[i] = sc.next().charAt(0); if(cc[i] == 'R') { if(arr[i]%2 == 1)rightOdd.put(arr[i], i); else rightEven.put(arr[i], i); } else { if(arr[i]%2 == 1)leftOdd.put(arr[i], i); else leftEven.put(arr[i], i); } } int ans[] = new int[n]; Arrays.fill(ans, -1); HashMap<Integer, Integer> extra = new HashMap<Integer, Integer>(); while(!rightOdd.isEmpty()) { Entry<Integer, Integer> ff = rightOdd.pollLastEntry(); if(!leftOdd.isEmpty() && ff.getKey() <= leftOdd.lastKey()) { Entry<Integer, Integer> ss = leftOdd.ceilingEntry(ff.getKey()); leftOdd.remove(ss.getKey()); int diff = (ss.getKey() - ff.getKey()); ans[ff.getValue()] = diff/2; ans[ss.getValue()] = diff/2; continue; } extra.put(ff.getKey(), ff.getValue()); } for(Entry<Integer, Integer> e : extra.entrySet())rightOdd.put(e.getKey(), e.getValue()); extra.clear(); while(!rightEven.isEmpty()) { Entry<Integer, Integer> ff = rightEven.pollLastEntry(); if(!leftEven.isEmpty() && ff.getKey() <= leftEven.lastKey()) { Entry<Integer, Integer> ss = leftEven.ceilingEntry(ff.getKey()); leftEven.remove(ss.getKey()); int diff = (ss.getKey() - ff.getKey()); ans[ff.getValue()] = diff/2; ans[ss.getValue()] = diff/2; continue; } extra.put(ff.getKey(), ff.getValue()); } for(Entry<Integer, Integer> e : extra.entrySet())rightEven.put(e.getKey(), e.getValue()); while(leftEven.size() > 1) { Entry<Integer, Integer> ff = leftEven.pollFirstEntry(); Entry<Integer, Integer> ss = leftEven.pollFirstEntry(); int dis = (ss.getKey() - ff.getKey())/2; ans[ff.getValue()] = ff.getKey() + dis; ans[ss.getValue()] = ff.getKey()+dis; } while(leftOdd.size() > 1) { Entry<Integer, Integer> ff = leftOdd.pollFirstEntry(); Entry<Integer, Integer> ss = leftOdd.pollFirstEntry(); int dis = (ss.getKey() - ff.getKey())/2; ans[ff.getValue()] = ff.getKey()+dis; ans[ss.getValue()] = ff.getKey()+dis; } while(rightEven.size() > 1) { Entry<Integer, Integer> ff = rightEven.pollLastEntry(); Entry<Integer, Integer> ss = rightEven.pollLastEntry(); int dis = (ff.getKey() - ss.getKey())/2; ans[ff.getValue()] = m-ff.getKey()+ dis; ans[ss.getValue()] = m-ff.getKey()+ dis; } while(rightOdd.size() > 1) { Entry<Integer, Integer> ff = rightOdd.pollLastEntry(); Entry<Integer, Integer> ss = rightOdd.pollLastEntry(); int dis = (ff.getKey() - ss.getKey())/2; ans[ff.getValue()] = m-ff.getKey()+dis; ans[ss.getValue()] = m-ff.getKey()+dis; } while(!rightEven.isEmpty() && !leftEven.isEmpty()) { Entry<Integer, Integer> ff = rightEven.pollLastEntry(); Entry<Integer, Integer> ss = leftEven.pollFirstEntry(); int c1 = m-ff.getKey(),c2 = ss.getKey(); int aa = 0; if(c1 > c2) { aa += c1; c2 =(c1 - c2); c1 = m; aa+=(c1-c2)/2; } else { aa+=c2; c1 = (m-(c2-c1)); c2 = 0; aa+=(c1-c2)/2; } ans[ff.getValue()] = aa; ans[ss.getValue()] = aa; } while(!rightOdd.isEmpty() && !leftOdd.isEmpty()) { Entry<Integer, Integer> ff = rightOdd.pollLastEntry(); Entry<Integer, Integer> ss = leftOdd.pollFirstEntry(); int c1 = m-ff.getKey(),c2 = ss.getKey(); int aa = 0; if(c1 > c2) { aa +=c1; c2 =(c1 - c2); c1 = m; aa+=(c1-c2)/2; } else { aa+=c2; c1 = (m-(c2-c1)); c2 = 0; aa+=(c1-c2)/2; } ans[ff.getValue()] = aa; ans[ss.getValue()] = aa; } for(int e : ans)print(e+" "); println(); } //============================================================================= //--------------------------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 PrintWriter out; public static void main(String[] args) throws IOException { boolean oj = true; if (oj) { sc = new FastScanner(); out = new PrintWriter(System.out); } else { sc = new FastScanner(100); out = new PrintWriter("output.txt"); } int t = 1; t = sc.nextInt(); int TTT = 1; while (t-- > 0) { // google(TTT++); process(); } out.flush(); out.close(); } 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 void println(Object o) { out.println(o); } static void println() { out.println(); } static void print(Object o) { out.print(o); } static void pflush(Object o) { out.println(o); out.flush(); } 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 int max(int x, int y) { return Math.max(x, y); } static int min(int x, int y) { return Math.min(x, y); } static int abs(int x) { return Math.abs(x); } static long abs(long x) { return Math.abs(x); } 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; } static long max(long x, long y) { return Math.max(x, y); } static long min(long x, long y) { return Math.min(x, y); } public static int gcd(int a, int b) { BigInteger b1 = BigInteger.valueOf(a); BigInteger b2 = BigInteger.valueOf(b); BigInteger gcd = b1.gcd(b2); return gcd.intValue(); } public static long gcd(long a, long b) { BigInteger b1 = BigInteger.valueOf(a); BigInteger b2 = BigInteger.valueOf(b); BigInteger gcd = b1.gcd(b2); return gcd.longValue(); } public static long lcm(long a, long b) { return (a * b) / gcd(a, b); } public static int lcm(int a, int b) { return (a * b) / gcd(a, b); } public static int 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; } ///////////////////////////////////////////////////////////////////////////////////////////////////////// static class FastScanner { BufferedReader br; StringTokenizer st; FastScanner() throws FileNotFoundException { br = new BufferedReader(new InputStreamReader(System.in)); } FastScanner(int a) throws FileNotFoundException { br = new BufferedReader(new FileReader("input.txt")); } String next() throws IOException { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } String nextLine() throws IOException { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } int[] readArray(int n) throws IOException { int[] A = new int[n]; for (int i = 0; i != n; i++) { A[i] = sc.nextInt(); } return A; } long[] readArrayLong(int n) throws IOException { long[] A = new long[n]; for (int i = 0; i != n; i++) { A[i] = sc.nextLong(); } return A; } } 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); } }
Java
["5\n7 12\n1 2 3 4 9 10 11\nR R L L R R R\n2 10\n1 6\nR R\n2 10\n1 3\nL L\n1 10\n5\nR\n7 8\n6 1 7 2 3 5 4\nR L R L L L L"]
2 seconds
["1 1 1 1 2 -1 2 \n-1 -1 \n2 2 \n-1 \n-1 2 7 3 2 7 3"]
NoteHere is the picture for the seconds $$$0, 1, 2$$$ and $$$3$$$ of the first testcase: Notice that robots $$$2$$$ and $$$3$$$ don't collide because they meet at the same point $$$2.5$$$, which is not integer.After second $$$3$$$ robot $$$6$$$ just drive infinitely because there's no robot to collide with.
Java 8
standard input
[ "data structures", "greedy", "implementation", "sortings" ]
1a28b972e77966453cd8239cc5c8f59a
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5$$$; $$$2 \le m \le 10^8$$$) — the number of robots and the coordinate of the right wall. The second line of each testcase contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$0 &lt; x_i &lt; m$$$) — the starting coordinates of the robots. The third line of each testcase contains $$$n$$$ space-separated characters 'L' or 'R' — the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates $$$x_i$$$ in the testcase are distinct. The sum of $$$n$$$ over all testcases doesn't exceed $$$3 \cdot 10^5$$$.
2,000
For each testcase print $$$n$$$ integers — for the $$$i$$$-th robot output the time it explodes at if it does and $$$-1$$$ otherwise.
standard output
PASSED
a6eea341baa5029012ccf02718afeeb9
train_110.jsonl
1621152000
There are $$$n$$$ robots driving along an OX axis. There are also two walls: one is at coordinate $$$0$$$ and one is at coordinate $$$m$$$.The $$$i$$$-th robot starts at an integer coordinate $$$x_i~(0 &lt; x_i &lt; m)$$$ and moves either left (towards the $$$0$$$) or right with the speed of $$$1$$$ unit per second. No two robots start at the same coordinate.Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed.Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens.For each robot find out if it ever explodes and print the time of explosion if it happens and $$$-1$$$ otherwise.
256 megabytes
/* bts songs to dance to: I need U Run ON Filter I'm fine */ import static java.lang.Math.max; import static java.lang.Math.min; import static java.lang.Math.abs; import static java.lang.System.out; import java.util.*; import java.io.*; import java.math.*; public class x1525C { public static void main(String hi[]) 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()); M = Long.parseLong(st.nextToken()); int[] arr = readArr(N, infile, st); char[] directions = new char[N]; st = new StringTokenizer(infile.readLine()); for(int i=0; i < N; i++) directions[i] = st.nextToken().charAt(0); //get parities long[] res = new long[N]; ArrayList<Integer> odds = new ArrayList<Integer>(); ArrayList<Integer> evens = new ArrayList<Integer>(); for(int i=0; i < N; i++) { if(arr[i]%2 == 0) evens.add(i); else odds.add(i); } Arrays.fill(res, -1); solve(odds, N, res, arr, directions); solve(evens, N, res, arr, directions); for(long x: res) sb.append(x+" "); sb.append("\n"); } System.out.print(sb); } static boolean debug = false; static long M; public static void solve(ArrayList<Integer> ls, int N, long[] res, int[] arr, char[] dir) { Collections.sort(ls, (x,y) -> { return arr[x]-arr[y]; }); ArrayDeque<Integer> stack = new ArrayDeque<Integer>(); for(int curr: ls) { if(stack.size() == 0) stack.addLast(curr); else { char prev = dir[stack.peekLast()]; if(prev == 'R') { if(dir[curr] == 'L') { //RL case int other = stack.pollLast(); res[curr] = res[other] = (arr[curr]-arr[other])/2; } else stack.addLast(curr); } else { if(dir[curr] == 'L') { //LL case //kind of tricky int other = stack.pollLast(); int a = arr[other]; int b = arr[curr]; res[curr] = res[other] = (long)a+(b-a)/2; } else stack.addLast(curr); } } } if(stack.size() == 0) return; //at most 1 L, multiple R int head = -1; if(dir[stack.peekFirst()] == 'L') head = stack.pollFirst(); //RR case while(stack.size() >= 2) { //order is t1 < t2 int t2 = stack.pollLast(); int t1 = stack.pollLast(); int a = arr[t1]; int b = arr[t2]; long temp = M-a; long diff = M-b; res[t1] = res[t2] = diff+(temp-diff)/2; } int tail = -1; if(stack.size() == 1) tail = stack.poll(); //LR case if(min(head, tail) >= 0) { if(arr[head] <= M-arr[tail]) { long time = arr[head]; //a == 0 long b = arr[tail]+arr[head]; time += M-b; time += b/2; res[head] = res[tail] = time; } else { long time = M-arr[tail]; long a = arr[head]-time; //b == M time += a; time += (M-a)/2; res[head] = res[tail] = time; } } } 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; } } /* 1 7 12 1 2 3 4 9 10 11 R R L L R R R */ /* consider points with the same parity (necessary and sufficient condition for collision) use stack logic */
Java
["5\n7 12\n1 2 3 4 9 10 11\nR R L L R R R\n2 10\n1 6\nR R\n2 10\n1 3\nL L\n1 10\n5\nR\n7 8\n6 1 7 2 3 5 4\nR L R L L L L"]
2 seconds
["1 1 1 1 2 -1 2 \n-1 -1 \n2 2 \n-1 \n-1 2 7 3 2 7 3"]
NoteHere is the picture for the seconds $$$0, 1, 2$$$ and $$$3$$$ of the first testcase: Notice that robots $$$2$$$ and $$$3$$$ don't collide because they meet at the same point $$$2.5$$$, which is not integer.After second $$$3$$$ robot $$$6$$$ just drive infinitely because there's no robot to collide with.
Java 8
standard input
[ "data structures", "greedy", "implementation", "sortings" ]
1a28b972e77966453cd8239cc5c8f59a
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5$$$; $$$2 \le m \le 10^8$$$) — the number of robots and the coordinate of the right wall. The second line of each testcase contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$0 &lt; x_i &lt; m$$$) — the starting coordinates of the robots. The third line of each testcase contains $$$n$$$ space-separated characters 'L' or 'R' — the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates $$$x_i$$$ in the testcase are distinct. The sum of $$$n$$$ over all testcases doesn't exceed $$$3 \cdot 10^5$$$.
2,000
For each testcase print $$$n$$$ integers — for the $$$i$$$-th robot output the time it explodes at if it does and $$$-1$$$ otherwise.
standard output
PASSED
35f25a9f67398c61f2fd0fc7d9488b0c
train_110.jsonl
1621152000
There are $$$n$$$ robots driving along an OX axis. There are also two walls: one is at coordinate $$$0$$$ and one is at coordinate $$$m$$$.The $$$i$$$-th robot starts at an integer coordinate $$$x_i~(0 &lt; x_i &lt; m)$$$ and moves either left (towards the $$$0$$$) or right with the speed of $$$1$$$ unit per second. No two robots start at the same coordinate.Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed.Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens.For each robot find out if it ever explodes and print the time of explosion if it happens and $$$-1$$$ otherwise.
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; /*long startTime = System.currentTimeMillis(); //获取开始时间 * long endTime = System.currentTimeMillis(); //获取结束时间 * System.out.println("程序运行时间:" + (endTime - startTime) + "ms"); //输出程序运行时间 */ public class Main{ static final int n=998244353; public static void main(String[] args){ Read in=new Read(System.in); int t=in.nextInt(); while(t!=0) { t--; int n=in.nextInt(), m=in.nextInt(); int [][] rb=new int [n][3]; for(int i=0;i<n;i++) { rb[i][0]=in.nextInt(); rb[i][2]=i; } for(int i=0;i<n;i++) { if(in.next().charAt(0)=='R') { rb[i][1]=1; }else { rb[i][1]=0; } } Stack<int []> goR=new Stack<>(); Arrays.sort(rb,new Comparator<int []>(){ public int compare(int [] o1, int [] o2) { return o1[0]-o2[0]; } }); int [] ans=new int [n]; Arrays.fill(ans,-1); for(int i=0;i<n;i++) { if((rb[i][0]&1)==0) continue; if(rb[i][1]==1) { goR.add(rb[i]); }else { if(goR.isEmpty()) { rb[i][0]=-rb[i][0]; goR.add(rb[i]); }else { int [] temp=goR.pop(); int a=(rb[i][0]-temp[0])/2; ans[temp[2]]=a; ans[rb[i][2]]=a; } } } while(!goR.isEmpty()) { int [] t1=goR.pop(); if(!goR.isEmpty()) { int [] t2=goR.pop(); int a=(2*m-t1[0]-t2[0])/2; ans[t1[2]]=a; ans[t2[2]]=a; } } for(int i=0;i<n;i++) { if((rb[i][0]&1)!=0) continue; if(rb[i][1]==1) { goR.add(rb[i]); }else { if(goR.isEmpty()) { rb[i][0]=-rb[i][0]; goR.add(rb[i]); }else { int [] temp=goR.pop(); int a=(rb[i][0]-temp[0])/2; ans[temp[2]]=a; ans[rb[i][2]]=a; } } } while(!goR.isEmpty()) { int [] t1=goR.pop(); if(!goR.isEmpty()) { int [] t2=goR.pop(); int a=(2*m-t1[0]-t2[0])/2; ans[t1[2]]=a; ans[t2[2]]=a; } } for(int i=0;i<n;i++) { System.out.print(ans[i]+" "); } System.out.println(); } } static class Read {//自定义快读 Read public BufferedReader reader; public StringTokenizer tokenizer; public Read(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public String nextLine() { String str = null; try { str = reader.readLine(); } catch (IOException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } return str; } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public Double nextDouble() { return Double.parseDouble(next()); } public BigInteger nextBigInteger() { return new BigInteger(next()); } } }
Java
["5\n7 12\n1 2 3 4 9 10 11\nR R L L R R R\n2 10\n1 6\nR R\n2 10\n1 3\nL L\n1 10\n5\nR\n7 8\n6 1 7 2 3 5 4\nR L R L L L L"]
2 seconds
["1 1 1 1 2 -1 2 \n-1 -1 \n2 2 \n-1 \n-1 2 7 3 2 7 3"]
NoteHere is the picture for the seconds $$$0, 1, 2$$$ and $$$3$$$ of the first testcase: Notice that robots $$$2$$$ and $$$3$$$ don't collide because they meet at the same point $$$2.5$$$, which is not integer.After second $$$3$$$ robot $$$6$$$ just drive infinitely because there's no robot to collide with.
Java 8
standard input
[ "data structures", "greedy", "implementation", "sortings" ]
1a28b972e77966453cd8239cc5c8f59a
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5$$$; $$$2 \le m \le 10^8$$$) — the number of robots and the coordinate of the right wall. The second line of each testcase contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$0 &lt; x_i &lt; m$$$) — the starting coordinates of the robots. The third line of each testcase contains $$$n$$$ space-separated characters 'L' or 'R' — the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates $$$x_i$$$ in the testcase are distinct. The sum of $$$n$$$ over all testcases doesn't exceed $$$3 \cdot 10^5$$$.
2,000
For each testcase print $$$n$$$ integers — for the $$$i$$$-th robot output the time it explodes at if it does and $$$-1$$$ otherwise.
standard output
PASSED
0409dd05f82be3977d0ff011a5e433a5
train_110.jsonl
1621152000
There are $$$n$$$ robots driving along an OX axis. There are also two walls: one is at coordinate $$$0$$$ and one is at coordinate $$$m$$$.The $$$i$$$-th robot starts at an integer coordinate $$$x_i~(0 &lt; x_i &lt; m)$$$ and moves either left (towards the $$$0$$$) or right with the speed of $$$1$$$ unit per second. No two robots start at the same coordinate.Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed.Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens.For each robot find out if it ever explodes and print the time of explosion if it happens and $$$-1$$$ otherwise.
256 megabytes
// package FinalGrind; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.*; import java.util.ArrayList; import java.util.Collections; import java.util.Scanner; import java.util.Stack; public class Problem1 { static class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } public static void main(String[] args)throws IOException { // Reader s=new Reader(); Scanner s=new Scanner(System.in); StringBuilder print=new StringBuilder(); int test=s.nextInt(); while(test--!=0){ int n=s.nextInt(); int m=s.nextInt(); int x[]=new int[n]; for(int i=0;i<n;i++){ x[i]=s.nextInt(); } String str[]=new String[n]; ArrayList<Robot> odd=new ArrayList<>(); ArrayList<Robot> even=new ArrayList<>(); for(int i=0;i<n;i++){ str[i]=s.next(); if(x[i]%2!=0){ if(str[i].charAt(0)=='R'){ odd.add(new Robot(x[i],1,i)); } else{ odd.add(new Robot(x[i],0,i)); } } else{ if(str[i].charAt(0)=='R'){ even.add(new Robot(x[i],1,i)); } else{ even.add(new Robot(x[i],0,i)); } } } Collections.sort(odd); Collections.sort(even); solve(odd,m); solve(even,m); int ans[]=new int[n]; for(Robot robot:odd){ ans[robot.ind]=robot.time; } for(Robot robot:even){ ans[robot.ind]=robot.time; } for(int i=0;i<n;i++){ print.append(ans[i]).append(" "); } print.append("\n"); } System.out.print(print.toString()); } public static void solve(ArrayList<Robot> robots,int m){ Stack<Robot> stack=new Stack<>(); for(Robot robot:robots){ if(robot.direction==1){ stack.push(robot); } else{ if(!stack.isEmpty()){ Robot top=stack.pop(); int time=(robot.index-top.index)/2; top.time=robot.time=time; } else{ robot.index=-robot.index; robot.direction=1; stack.push(robot); } } } while(stack.size()>1){ Robot top1=stack.pop(); Robot top2=stack.pop(); int time=(top1.index-top2.index)/2+m-top1.index; top1.time=top2.time=time; } return; } } class Robot implements Comparable<Robot>{ int index,direction,time,ind; public Robot(int index,int direction,int ind){ this.index=index; this.direction=direction; this.time=-1; this.ind=ind; } @Override public int compareTo(Robot o) { return this.index-o.index; } }
Java
["5\n7 12\n1 2 3 4 9 10 11\nR R L L R R R\n2 10\n1 6\nR R\n2 10\n1 3\nL L\n1 10\n5\nR\n7 8\n6 1 7 2 3 5 4\nR L R L L L L"]
2 seconds
["1 1 1 1 2 -1 2 \n-1 -1 \n2 2 \n-1 \n-1 2 7 3 2 7 3"]
NoteHere is the picture for the seconds $$$0, 1, 2$$$ and $$$3$$$ of the first testcase: Notice that robots $$$2$$$ and $$$3$$$ don't collide because they meet at the same point $$$2.5$$$, which is not integer.After second $$$3$$$ robot $$$6$$$ just drive infinitely because there's no robot to collide with.
Java 8
standard input
[ "data structures", "greedy", "implementation", "sortings" ]
1a28b972e77966453cd8239cc5c8f59a
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5$$$; $$$2 \le m \le 10^8$$$) — the number of robots and the coordinate of the right wall. The second line of each testcase contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$0 &lt; x_i &lt; m$$$) — the starting coordinates of the robots. The third line of each testcase contains $$$n$$$ space-separated characters 'L' or 'R' — the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates $$$x_i$$$ in the testcase are distinct. The sum of $$$n$$$ over all testcases doesn't exceed $$$3 \cdot 10^5$$$.
2,000
For each testcase print $$$n$$$ integers — for the $$$i$$$-th robot output the time it explodes at if it does and $$$-1$$$ otherwise.
standard output
PASSED
a4dedc3d110282206ca357bd634cdea4
train_110.jsonl
1621152000
There are $$$n$$$ robots driving along an OX axis. There are also two walls: one is at coordinate $$$0$$$ and one is at coordinate $$$m$$$.The $$$i$$$-th robot starts at an integer coordinate $$$x_i~(0 &lt; x_i &lt; m)$$$ and moves either left (towards the $$$0$$$) or right with the speed of $$$1$$$ unit per second. No two robots start at the same coordinate.Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed.Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens.For each robot find out if it ever explodes and print the time of explosion if it happens and $$$-1$$$ otherwise.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Arrays; import java.util.HashMap; import java.util.Stack; import java.util.StringTokenizer; public class ProblemC { public static void main(String[] args) throws IOException { InputStream in = System.in; InputReader scan = new InputReader(in); int test = scan.nextInt(); StringBuilder sb = new StringBuilder(); for(int t=0;t<test;t++) { int n = scan.nextInt(); int m = scan.nextInt(); int[] coord = new int[n]; HashMap<Integer, Character> direction = new HashMap<>(); for(int i=0;i<n;i++) { coord[i] = scan.nextInt(); } for(int i=0;i<n;i++) { direction.put(coord[i], scan.nextChar()); } int[] sortedCoord = coord.clone(); Arrays.sort(sortedCoord); HashMap<Integer, Integer> destroyTime = new HashMap<>(); for(int i=0;i<n;i++) { destroyTime.put(sortedCoord[i], -1); } Stack<Integer> oddStack = new Stack<>(); Stack<Integer> evenStack = new Stack<>(); for(int i=0;i<n;i++) { if(sortedCoord[i]%2==0) { if(direction.get(sortedCoord[i])=='R') evenStack.push(sortedCoord[i]); else { if(evenStack.isEmpty()) { direction.remove(sortedCoord[i]); destroyTime.remove(sortedCoord[i]); int newCoord = -sortedCoord[i]; sortedCoord[i] = newCoord; direction.put(newCoord, 'R'); destroyTime.put(newCoord, -1); evenStack.push(newCoord); } else { int robot1 = evenStack.pop(); int robot2 = sortedCoord[i]; int time = (robot2-robot1)/2; destroyTime.put(robot1, time); destroyTime.put(robot2, time); } } } else { if(direction.get(sortedCoord[i])=='R') oddStack.push(sortedCoord[i]); else { if(oddStack.isEmpty()) { direction.remove(sortedCoord[i]); destroyTime.remove(sortedCoord[i]); int newCoord = -sortedCoord[i]; sortedCoord[i] = newCoord; direction.put(newCoord, 'R'); destroyTime.put(newCoord, -1); oddStack.push(newCoord); } else { int robot1 = oddStack.pop(); int robot2 = sortedCoord[i]; int time = (robot2-robot1)/2; destroyTime.put(robot1, time); destroyTime.put(robot2, time); } } } } //Now if the stack is not empty there is only 'R' moving robots in the stack while(evenStack.size()>1) { int robot1 = evenStack.pop(); int robot2 = evenStack.pop(); int time = m - (robot1+robot2)/2; destroyTime.put(robot1, time); destroyTime.put(robot2, time); } while(oddStack.size()>1) { int robot1 = oddStack.pop(); int robot2 = oddStack.pop(); int time = m - (robot1+robot2)/2; destroyTime.put(robot1, time); destroyTime.put(robot2, time); } for(int i=0;i<n;i++) { int time = (destroyTime.containsKey(coord[i])) ? destroyTime.get(coord[i]) : destroyTime.get(-coord[i]); sb.append(time).append(" "); } sb.append("\n"); } System.out.print(sb); } 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 char nextChar() { return next().charAt(0); } } }
Java
["5\n7 12\n1 2 3 4 9 10 11\nR R L L R R R\n2 10\n1 6\nR R\n2 10\n1 3\nL L\n1 10\n5\nR\n7 8\n6 1 7 2 3 5 4\nR L R L L L L"]
2 seconds
["1 1 1 1 2 -1 2 \n-1 -1 \n2 2 \n-1 \n-1 2 7 3 2 7 3"]
NoteHere is the picture for the seconds $$$0, 1, 2$$$ and $$$3$$$ of the first testcase: Notice that robots $$$2$$$ and $$$3$$$ don't collide because they meet at the same point $$$2.5$$$, which is not integer.After second $$$3$$$ robot $$$6$$$ just drive infinitely because there's no robot to collide with.
Java 8
standard input
[ "data structures", "greedy", "implementation", "sortings" ]
1a28b972e77966453cd8239cc5c8f59a
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5$$$; $$$2 \le m \le 10^8$$$) — the number of robots and the coordinate of the right wall. The second line of each testcase contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$0 &lt; x_i &lt; m$$$) — the starting coordinates of the robots. The third line of each testcase contains $$$n$$$ space-separated characters 'L' or 'R' — the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates $$$x_i$$$ in the testcase are distinct. The sum of $$$n$$$ over all testcases doesn't exceed $$$3 \cdot 10^5$$$.
2,000
For each testcase print $$$n$$$ integers — for the $$$i$$$-th robot output the time it explodes at if it does and $$$-1$$$ otherwise.
standard output
PASSED
680600dfabe58939773f76d03af14068
train_110.jsonl
1621152000
There are $$$n$$$ robots driving along an OX axis. There are also two walls: one is at coordinate $$$0$$$ and one is at coordinate $$$m$$$.The $$$i$$$-th robot starts at an integer coordinate $$$x_i~(0 &lt; x_i &lt; m)$$$ and moves either left (towards the $$$0$$$) or right with the speed of $$$1$$$ unit per second. No two robots start at the same coordinate.Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed.Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens.For each robot find out if it ever explodes and print the time of explosion if it happens and $$$-1$$$ otherwise.
256 megabytes
import java.util.*; import java.io.*; public class Pizza { public static void main(String[] args)throws IOException{ PrintWriter out = new PrintWriter(System.out); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); int t = Integer.parseInt(st.nextToken()); for(int z=0;z<t;z++){ st = new StringTokenizer(br.readLine()); int n = Integer.parseInt(st.nextToken()); int m = Integer.parseInt(st.nextToken()); Integer[] ind = new Integer[n]; int[] x = new int[n]; char[] d = new char[n]; st = new StringTokenizer(br.readLine()); for(int i=0;i<n;i++){ x[i] = Integer.parseInt(st.nextToken()); ind[i] = i; } st = new StringTokenizer(br.readLine()); for(int i=0;i<n;i++){ d[i] = st.nextToken().charAt(0); } Arrays.sort(ind,new Comparator<Integer>(){ public int compare(Integer i1,Integer i2){ return x[i1]-x[i2]; } }); //for(int i=0;i<n;i++) out.print(x[ind[i]]+" "); int[] score = new int[n]; LinkedList<Integer>[] s = new LinkedList[2]; for(int i=0;i<2;i++) s[i] = new LinkedList<Integer>(); for(int i=0;i<n;i++){ int indice = ind[i]; int pai = x[indice]%2; if(d[indice]=='L'){ if(s[pai].size()==0){ x[indice] *= -1; s[pai].addLast(indice); }else{ int in = s[pai].removeLast(); score[in] = (x[indice]-x[in])/2; score[indice] = (x[indice]-x[in])/2; } }else{ s[pai].addLast(indice); } } for(int pai=0;pai<2;pai++){ while(s[pai].size()>1){ int in1 = s[pai].removeLast(); int in2 = s[pai].removeLast(); x[in1] = m+m-x[in1]; score[in1] = (x[in1]-x[in2])/2; score[in2] = (x[in1]-x[in2])/2; } if(s[pai].size()==1){ int in = s[pai].removeLast(); score[in] = -1; } } for(int i=0;i<n;i++){ out.print(score[i]+" "); } out.println(""); } out.flush(); } }
Java
["5\n7 12\n1 2 3 4 9 10 11\nR R L L R R R\n2 10\n1 6\nR R\n2 10\n1 3\nL L\n1 10\n5\nR\n7 8\n6 1 7 2 3 5 4\nR L R L L L L"]
2 seconds
["1 1 1 1 2 -1 2 \n-1 -1 \n2 2 \n-1 \n-1 2 7 3 2 7 3"]
NoteHere is the picture for the seconds $$$0, 1, 2$$$ and $$$3$$$ of the first testcase: Notice that robots $$$2$$$ and $$$3$$$ don't collide because they meet at the same point $$$2.5$$$, which is not integer.After second $$$3$$$ robot $$$6$$$ just drive infinitely because there's no robot to collide with.
Java 8
standard input
[ "data structures", "greedy", "implementation", "sortings" ]
1a28b972e77966453cd8239cc5c8f59a
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5$$$; $$$2 \le m \le 10^8$$$) — the number of robots and the coordinate of the right wall. The second line of each testcase contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$0 &lt; x_i &lt; m$$$) — the starting coordinates of the robots. The third line of each testcase contains $$$n$$$ space-separated characters 'L' or 'R' — the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates $$$x_i$$$ in the testcase are distinct. The sum of $$$n$$$ over all testcases doesn't exceed $$$3 \cdot 10^5$$$.
2,000
For each testcase print $$$n$$$ integers — for the $$$i$$$-th robot output the time it explodes at if it does and $$$-1$$$ otherwise.
standard output
PASSED
fc7baa59bb05fa8209cb591f9c47f389
train_110.jsonl
1621152000
There are $$$n$$$ robots driving along an OX axis. There are also two walls: one is at coordinate $$$0$$$ and one is at coordinate $$$m$$$.The $$$i$$$-th robot starts at an integer coordinate $$$x_i~(0 &lt; x_i &lt; m)$$$ and moves either left (towards the $$$0$$$) or right with the speed of $$$1$$$ unit per second. No two robots start at the same coordinate.Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed.Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens.For each robot find out if it ever explodes and print the time of explosion if it happens and $$$-1$$$ otherwise.
256 megabytes
import java.io.*; import java.util.*; import java.math.*; import java.awt.Point; public class Main { //static final long MOD = 1000000007L; //static final long MOD2 = 1000000009L; static final long MOD = 998244353L; //static final long INF = 500000000000L; static final int INF = 1000000005; static final int NINF = -1000000005; //static final long INF = 1000000000000000000L; static FastScanner sc; static PrintWriter pw; //static final int[][] dirs = {{-1,0},{1,0},{0,-1},{0,1}}; static int[] ans; public static void main(String[] args) { sc = new FastScanner(); pw = new PrintWriter(System.out); int Q = sc.ni(); for (int q = 0; q < Q; q++) { int N = sc.ni(); int M = sc.ni(); ans = new int[N]; Arrays.fill(ans,-1); int[] nums = sc.intArray(N, 0); char[] dirs = sc.charArray(N); ArrayList<Pair> evens = new ArrayList<Pair>(); ArrayList<Pair> odds = new ArrayList<Pair>(); for (int i = 0; i < N; i++) { int n = nums[i]; int dirInt = 0; if (dirs[i]=='R') dirInt = 1; if (n%2==0) evens.add(new Pair(n,dirInt,i)); else odds.add(new Pair(n,dirInt,i)); } solve(N,M,evens); solve(N,M,odds); for (int a: ans) pw.print(a + " "); pw.println(); } pw.close(); } public static void solve(int N, int M, ArrayList<Pair> robots) { Collections.sort(robots); ArrayDeque<Pair> events = new ArrayDeque<Pair>(); for (Pair robot: robots) { if (!events.isEmpty()&&robot.y==0&&events.peekLast().y==1) { Pair last = events.pollLast(); int time = (robot.x-last.x)/2; ans[robot.i] = time; ans[last.i] = time; } else { events.add(robot); } } while (!events.isEmpty() && events.peekFirst().y==0) { Pair robot1 = events.pollFirst(); if (!events.isEmpty() && events.peekFirst().y==0) { Pair robot2 = events.pollFirst(); int time = (robot1.x+robot2.x)/2; ans[robot1.i] = time; ans[robot2.i] = time; } else { events.addFirst(robot1); break; } } while (!events.isEmpty() && events.peekLast().y==1) { Pair robot2 = events.pollLast(); if (!events.isEmpty() && events.peekLast().y==1) { Pair robot1 = events.pollLast(); int time = (M-robot1.x+M-robot2.x)/2; ans[robot1.i] = time; ans[robot2.i] = time; } else { events.addLast(robot2); break; } } if (events.size()==2) { Pair robot1 = events.pollFirst(); Pair robot2 = events.pollLast(); int time = M-(robot2.x-robot1.x)/2; ans[robot1.i] = time; ans[robot2.i] = time; } } static class Pair implements Comparable<Pair> { int x; int y; int i; public Pair(int x, int y, int i) { this.x=x; this.y=y; this.i=i; } public Pair(int x, int i) { this.x=x; this.y=0; this.i=i; } public int compareTo(Pair p) { return x-p.x; } public String toString() { return "("+x+","+y+")"; } } public static void sort(int[] arr) { Random rgen = new Random(); for (int i = 0; i < arr.length; i++) { int r = rgen.nextInt(arr.length); int temp = arr[i]; arr[i] = arr[r]; arr[r] = temp; } Arrays.sort(arr); } public static void sort(long[] arr) { Random rgen = new Random(); for (int i = 0; i < arr.length; i++) { int r = rgen.nextInt(arr.length); long temp = arr[i]; arr[i] = arr[r]; arr[r] = temp; } Arrays.sort(arr); } //Sort an array (immune to quicksort TLE) public static void sort(int[][] arr) { Random rgen = new Random(); for (int i = 0; i < arr.length; i++) { int r = rgen.nextInt(arr.length); int[] temp = arr[i]; arr[i] = arr[r]; arr[r] = temp; } Arrays.sort(arr, new Comparator<int[]>() { @Override public int compare(int[] a, int[] b) { return a[0]-b[0]; } }); } public static void sort(long[][] arr) { Random rgen = new Random(); for (int i = 0; i < arr.length; i++) { int r = rgen.nextInt(arr.length); long[] temp = arr[i]; arr[i] = arr[r]; arr[r] = temp; } Arrays.sort(arr, new Comparator<long[]>() { @Override public int compare(long[] a, long[] b) { if (a[0] > b[0]) return 1; else if (a[0] < b[0]) return -1; else return 0; //Ascending order. } }); } static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner() { br = new BufferedReader(new InputStreamReader(System.in), 32768); st = null; } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int ni() { return Integer.parseInt(next()); } int[][] graph(int N, int[][] edges) { int[][] graph = new int[N][]; int[] sz = new int[N]; for (int[] e: edges) { sz[e[0]] += 1; sz[e[1]] += 1; } for (int i = 0; i < N; i++) { graph[i] = new int[sz[i]]; } int[] cur = new int[N]; for (int[] e: edges) { graph[e[0]][cur[e[0]]] = e[1]; graph[e[1]][cur[e[1]]] = e[0]; cur[e[0]] += 1; cur[e[1]] += 1; } return graph; } int[] intArray(int N, int mod) { int[] ret = new int[N]; for (int i = 0; i < N; i++) ret[i] = ni()+mod; return ret; } char[] charArray(int N) { char[] ret = new char[N]; for (int i = 0; i < N; i++) ret[i] = next().charAt(0); return ret; } long nl() { return Long.parseLong(next()); } long[] longArray(int N, long mod) { long[] ret = new long[N]; for (int i = 0; i < N; i++) ret[i] = nl()+mod; return ret; } double nd() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["5\n7 12\n1 2 3 4 9 10 11\nR R L L R R R\n2 10\n1 6\nR R\n2 10\n1 3\nL L\n1 10\n5\nR\n7 8\n6 1 7 2 3 5 4\nR L R L L L L"]
2 seconds
["1 1 1 1 2 -1 2 \n-1 -1 \n2 2 \n-1 \n-1 2 7 3 2 7 3"]
NoteHere is the picture for the seconds $$$0, 1, 2$$$ and $$$3$$$ of the first testcase: Notice that robots $$$2$$$ and $$$3$$$ don't collide because they meet at the same point $$$2.5$$$, which is not integer.After second $$$3$$$ robot $$$6$$$ just drive infinitely because there's no robot to collide with.
Java 8
standard input
[ "data structures", "greedy", "implementation", "sortings" ]
1a28b972e77966453cd8239cc5c8f59a
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5$$$; $$$2 \le m \le 10^8$$$) — the number of robots and the coordinate of the right wall. The second line of each testcase contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$0 &lt; x_i &lt; m$$$) — the starting coordinates of the robots. The third line of each testcase contains $$$n$$$ space-separated characters 'L' or 'R' — the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates $$$x_i$$$ in the testcase are distinct. The sum of $$$n$$$ over all testcases doesn't exceed $$$3 \cdot 10^5$$$.
2,000
For each testcase print $$$n$$$ integers — for the $$$i$$$-th robot output the time it explodes at if it does and $$$-1$$$ otherwise.
standard output
PASSED
0d84dd2866ef13d58e84ac57bae404a5
train_110.jsonl
1621152000
There are $$$n$$$ robots driving along an OX axis. There are also two walls: one is at coordinate $$$0$$$ and one is at coordinate $$$m$$$.The $$$i$$$-th robot starts at an integer coordinate $$$x_i~(0 &lt; x_i &lt; m)$$$ and moves either left (towards the $$$0$$$) or right with the speed of $$$1$$$ unit per second. No two robots start at the same coordinate.Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed.Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens.For each robot find out if it ever explodes and print the time of explosion if it happens and $$$-1$$$ otherwise.
256 megabytes
import java.util.*; import java.io.*; public class Main2 { 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 long mod = (long)(1e9+7); // static Scanner sc = new Scanner(System.in); static FastReader sc = new FastReader(); static PrintWriter out = new PrintWriter(System.out); static long ans[]; public static void main (String[] args) { int t = 1; t = sc.nextInt(); z : while(t-->0) { int n = sc.nextInt(); long m = sc.nextLong(); ArrayList<point> a = new ArrayList<>(); for(int i=0;i<n;i++) { a.add(new point()); a.get(i).x = sc.nextInt(); a.get(i).pos = i; } for(int i=0;i<n;i++) { a.get(i).dir = sc.next().charAt(0); } ArrayList<point> odd = new ArrayList<>(); ArrayList<point> even = new ArrayList<>(); for(int i=0;i<n;i++) { if(a.get(i).x%2==0) even.add(a.get(i)); else odd.add(a.get(i)); } ans = new long[n]; Arrays.fill(ans, -1); helper(odd,m); helper(even,m); for(long val : ans) out.write(val+" "); out.write("\n"); } out.close(); } private static void helper(ArrayList<point> a, long m) { Collections.sort(a,new Comparator<point>() {public int compare(point o1, point o2) {return o1.x-o2.x;}}); ArrayList<point> l = new ArrayList<>(); ArrayList<point> r = new ArrayList<>(); for(int i=0;i<a.size();i++) { if(a.get(i).dir=='R') { r.add(a.get(i)); } else { if(r.size()>0) { point p1 = r.get(r.size()-1); r.remove(r.size()-1); point p2 = a.get(i); long ans1 = Math.abs(p1.x-p2.x)/2; ans[p1.pos] = ans1; ans[p2.pos] = ans1; } else if(l.size()>0) { point p1 = l.get(l.size()-1); l.remove(l.size()-1); point p2 = a.get(i); long ans1 = p1.x; p1.x -= ans1; p2.x -= ans1; long ans2 = p2.x/2; ans[p1.pos] = ans1 + ans2; ans[p2.pos] = ans1 + ans2; } else l.add(a.get(i)); } } while(r.size()>=2) { point p1 = r.get(r.size()-1); point p2 = r.get(r.size()-2); r.remove(r.size()-1); r.remove(r.size()-1); long ans1 = m - p1.x; p2.x += ans1; long ans2 = (m - p2.x)/2; // System.out.println(ans1+" "+ans2); ans[p1.pos] = ans1 + ans2; ans[p2.pos] = ans1 + ans2; } if(r.size()==1 && l.size()==1) { point p = r.get(0); point q = l.get(0); long t1 = Math.min(q.x,m-p.x); q.x -= t1; p.x += t1; long t2 = 0; if(q.x!=0) { t2 = q.x; q.x = 0; p.x = (int) (m - t2); } else if(p.x!=m) { t2 = m - p.x; p.x = (int) m; q.x += t2; } // System.out.println(t1+" "+t2); ans[p.pos] = Math.abs(p.x-q.x)/2 + t1 + t2; ans[q.pos] = Math.abs(p.x-q.x)/2 + t1 + t2; } } private static void ini(ArrayList<Integer>[] tre2){for(int i=0;i<tre2.length;i++){tre2[i] = new ArrayList<>();}} } class point{ int x; int pos; char dir; point(){ } point(int x,int pos,char dir){ this.x = x; this.pos = pos; this.dir = dir; } }
Java
["5\n7 12\n1 2 3 4 9 10 11\nR R L L R R R\n2 10\n1 6\nR R\n2 10\n1 3\nL L\n1 10\n5\nR\n7 8\n6 1 7 2 3 5 4\nR L R L L L L"]
2 seconds
["1 1 1 1 2 -1 2 \n-1 -1 \n2 2 \n-1 \n-1 2 7 3 2 7 3"]
NoteHere is the picture for the seconds $$$0, 1, 2$$$ and $$$3$$$ of the first testcase: Notice that robots $$$2$$$ and $$$3$$$ don't collide because they meet at the same point $$$2.5$$$, which is not integer.After second $$$3$$$ robot $$$6$$$ just drive infinitely because there's no robot to collide with.
Java 8
standard input
[ "data structures", "greedy", "implementation", "sortings" ]
1a28b972e77966453cd8239cc5c8f59a
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5$$$; $$$2 \le m \le 10^8$$$) — the number of robots and the coordinate of the right wall. The second line of each testcase contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$0 &lt; x_i &lt; m$$$) — the starting coordinates of the robots. The third line of each testcase contains $$$n$$$ space-separated characters 'L' or 'R' — the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates $$$x_i$$$ in the testcase are distinct. The sum of $$$n$$$ over all testcases doesn't exceed $$$3 \cdot 10^5$$$.
2,000
For each testcase print $$$n$$$ integers — for the $$$i$$$-th robot output the time it explodes at if it does and $$$-1$$$ otherwise.
standard output
PASSED
759ad6d858ac185b1cede9ece23c6660
train_110.jsonl
1621152000
There are $$$n$$$ robots driving along an OX axis. There are also two walls: one is at coordinate $$$0$$$ and one is at coordinate $$$m$$$.The $$$i$$$-th robot starts at an integer coordinate $$$x_i~(0 &lt; x_i &lt; m)$$$ and moves either left (towards the $$$0$$$) or right with the speed of $$$1$$$ unit per second. No two robots start at the same coordinate.Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed.Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens.For each robot find out if it ever explodes and print the time of explosion if it happens and $$$-1$$$ otherwise.
256 megabytes
import java.util.*; import java.io.*; //import java.math.*; public class Task{ // ..............code begins here.............. static long mod=(long)1e9+7,mod1=998244353l,inf=(long)1e17; static int[] res; static void go(List<int[]> l,int m){ Queue<int[]> q=new LinkedList<>(); Stack<int[]> s=new Stack<>(); for(int[] r:l){ if(r[1]==-1){ if(s.isEmpty())q.add(r); else{ res[s.peek()[2]]=res[r[2]]=(r[0]-s.pop()[0])/2; } } else s.push(r); } while(q.size()>1){ int[] p=q.poll(),r=q.poll(); res[p[2]]=res[r[2]]=p[0]+(r[0]-p[0])/2; } while(s.size()>1){ int[] p=s.pop(),r=s.pop(); res[p[2]]=res[r[2]]=m-r[0]+(r[0]-p[0])/2; } if(!s.isEmpty()&&!q.isEmpty()){ int[] p=q.poll(),r=s.pop(); res[p[2]]=res[r[2]]=(m-r[0]+p[0]+m)/2; } } static void solve() throws IOException { int[] x=int_arr(); int n=x[0],m=x[1]; res=new int[n]; Arrays.fill(res,-1); int[] a=int_arr(); String[] c=read().split(" "); List<int[]> e=new ArrayList<>(); List<int[]> o=new ArrayList<>(); for(int i=0;i<n;i++){ int d=c[i].charAt(0)=='L'?-1:1; if(a[i]%2==0) e.add(new int[]{a[i],d,i}); else o.add(new int[]{a[i],d,i}); } Collections.sort(e,(a1,b1)->a1[0]-b1[0]); Collections.sort(o,(a1,b1)->a1[0]-b1[0]); go(e,m); go(o,m); for(int i:res)out.write(i+" "); out.write("\n"); } // public static void main(String[] args) throws IOException{ assign(); int t=int_v(read()),cn=1; while(t--!=0){ //out.write("Case #"+cn+": "); solve(); //cn++; } out.flush(); } // taking inputs static BufferedReader s1; static BufferedWriter out; static String read() throws IOException{String line="";while(line.length()==0){line=s1.readLine();continue;}return line;} static int int_v (String s1){return Integer.parseInt(s1);} static long long_v(String s1){return Long.parseLong(s1);} static void sort(int[] a){List<Integer> l=new ArrayList<>();for(int x:a){l.add(x);}Collections.sort(l);for(int i=0;i<a.length;i++){a[i]=l.get(i);}} static int[] int_arr() throws IOException{String[] a=read().split(" ");int[] b=new int[a.length];for(int i=0;i<a.length;i++){b[i]=int_v(a[i]);}return b;} static long[] long_arr() throws IOException{String[] a=read().split(" ");long[] b=new long[a.length];for(int i=0;i<a.length;i++){b[i]=long_v(a[i]);}return b;} static void assign(){s1=new BufferedReader(new InputStreamReader(System.in));out=new BufferedWriter(new OutputStreamWriter(System.out));} //static String setpreciosion(double d,int k){BigDecimal d1 = new BigDecimal(Double.toString(d));return d1.setScale(k,RoundingMode.HALF_UP).toString();}//UP DOWN HALF_UP static int add(int a,int b){int z=a+b;if(z>=mod)z-=mod;return z;} static long gcd(long a,long b){if(b==0){return a;}return gcd(b,a%b);} static long Modpow(long a,long p,long m){long res=1;while(p>0){if((p&1)!=0){res=(res*a)%m;}p >>=1;a=(a*a)%m;}return res%m;} static long Modmul(long a,long b,long m){return ((a%m)*(b%m))%m;} static long ModInv(long a,long m){return Modpow(a,m-2,m);} //static long nck(int n,int r,long m){if(r>n){return 0l;}return Modmul(f[n],ModInv(Modmul(f[n-r],f[r],m),m),m);} //static long[] f; }
Java
["5\n7 12\n1 2 3 4 9 10 11\nR R L L R R R\n2 10\n1 6\nR R\n2 10\n1 3\nL L\n1 10\n5\nR\n7 8\n6 1 7 2 3 5 4\nR L R L L L L"]
2 seconds
["1 1 1 1 2 -1 2 \n-1 -1 \n2 2 \n-1 \n-1 2 7 3 2 7 3"]
NoteHere is the picture for the seconds $$$0, 1, 2$$$ and $$$3$$$ of the first testcase: Notice that robots $$$2$$$ and $$$3$$$ don't collide because they meet at the same point $$$2.5$$$, which is not integer.After second $$$3$$$ robot $$$6$$$ just drive infinitely because there's no robot to collide with.
Java 8
standard input
[ "data structures", "greedy", "implementation", "sortings" ]
1a28b972e77966453cd8239cc5c8f59a
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5$$$; $$$2 \le m \le 10^8$$$) — the number of robots and the coordinate of the right wall. The second line of each testcase contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$0 &lt; x_i &lt; m$$$) — the starting coordinates of the robots. The third line of each testcase contains $$$n$$$ space-separated characters 'L' or 'R' — the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates $$$x_i$$$ in the testcase are distinct. The sum of $$$n$$$ over all testcases doesn't exceed $$$3 \cdot 10^5$$$.
2,000
For each testcase print $$$n$$$ integers — for the $$$i$$$-th robot output the time it explodes at if it does and $$$-1$$$ otherwise.
standard output
PASSED
11071886c1f6597cd25157fed267ae03
train_110.jsonl
1621152000
There are $$$n$$$ robots driving along an OX axis. There are also two walls: one is at coordinate $$$0$$$ and one is at coordinate $$$m$$$.The $$$i$$$-th robot starts at an integer coordinate $$$x_i~(0 &lt; x_i &lt; m)$$$ and moves either left (towards the $$$0$$$) or right with the speed of $$$1$$$ unit per second. No two robots start at the same coordinate.Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed.Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens.For each robot find out if it ever explodes and print the time of explosion if it happens and $$$-1$$$ otherwise.
256 megabytes
import java.util.*; import java.io.*; //import java.math.*; public class Task{ // ..............code begins here.............. static long mod=(long)1e9+7,mod1=998244353l,inf=(long)1e17; static int[] res; static int f(int[] a,int[] b){ return a[0]-b[0]; } static void go(List<int[]> l,int m){ Queue<int[]> q=new LinkedList<>(); Stack<int[]> s=new Stack<>(); for(int[] r:l){ if(r[1]==-1){ if(s.isEmpty())q.add(r); else{ res[s.peek()[2]]=res[r[2]]=(r[0]-s.pop()[0])/2; } } else s.push(r); } while(q.size()>1){ int[] p=q.poll(),r=q.poll(); res[p[2]]=res[r[2]]=p[0]+(r[0]-p[0])/2; } while(s.size()>1){ int[] p=s.pop(),r=s.pop(); res[p[2]]=res[r[2]]=m-r[0]+(r[0]-p[0])/2; } if(!s.isEmpty()&&!q.isEmpty()){ int[] p=q.poll(),r=s.pop(); res[p[2]]=res[r[2]]=(m-r[0]+p[0]+m)/2; } } static void solve() throws IOException { int[] x=int_arr(); int n=x[0],m=x[1]; res=new int[n]; Arrays.fill(res,-1); int[] a=int_arr(); String[] c=read().split(" "); List<int[]> e=new ArrayList<>(); List<int[]> o=new ArrayList<>(); for(int i=0;i<n;i++){ int d=c[i].charAt(0)=='L'?-1:1; if(a[i]%2==0) e.add(new int[]{a[i],d,i}); else o.add(new int[]{a[i],d,i}); } Collections.sort(e,(a1,b1)->f(a1,b1)); Collections.sort(o,(a1,b1)->f(a1,b1)); go(e,m); go(o,m); for(int i:res)out.write(i+" "); out.write("\n"); } // public static void main(String[] args) throws IOException{ assign(); int t=int_v(read()),cn=1; while(t--!=0){ //out.write("Case #"+cn+": "); solve(); //cn++; } out.flush(); } // taking inputs static BufferedReader s1; static BufferedWriter out; static String read() throws IOException{String line="";while(line.length()==0){line=s1.readLine();continue;}return line;} static int int_v (String s1){return Integer.parseInt(s1);} static long long_v(String s1){return Long.parseLong(s1);} static void sort(int[] a){List<Integer> l=new ArrayList<>();for(int x:a){l.add(x);}Collections.sort(l);for(int i=0;i<a.length;i++){a[i]=l.get(i);}} static int[] int_arr() throws IOException{String[] a=read().split(" ");int[] b=new int[a.length];for(int i=0;i<a.length;i++){b[i]=int_v(a[i]);}return b;} static long[] long_arr() throws IOException{String[] a=read().split(" ");long[] b=new long[a.length];for(int i=0;i<a.length;i++){b[i]=long_v(a[i]);}return b;} static void assign(){s1=new BufferedReader(new InputStreamReader(System.in));out=new BufferedWriter(new OutputStreamWriter(System.out));} //static String setpreciosion(double d,int k){BigDecimal d1 = new BigDecimal(Double.toString(d));return d1.setScale(k,RoundingMode.HALF_UP).toString();}//UP DOWN HALF_UP static int add(int a,int b){int z=a+b;if(z>=mod)z-=mod;return z;} static long gcd(long a,long b){if(b==0){return a;}return gcd(b,a%b);} static long Modpow(long a,long p,long m){long res=1;while(p>0){if((p&1)!=0){res=(res*a)%m;}p >>=1;a=(a*a)%m;}return res%m;} static long Modmul(long a,long b,long m){return ((a%m)*(b%m))%m;} static long ModInv(long a,long m){return Modpow(a,m-2,m);} //static long nck(int n,int r,long m){if(r>n){return 0l;}return Modmul(f[n],ModInv(Modmul(f[n-r],f[r],m),m),m);} //static long[] f; }
Java
["5\n7 12\n1 2 3 4 9 10 11\nR R L L R R R\n2 10\n1 6\nR R\n2 10\n1 3\nL L\n1 10\n5\nR\n7 8\n6 1 7 2 3 5 4\nR L R L L L L"]
2 seconds
["1 1 1 1 2 -1 2 \n-1 -1 \n2 2 \n-1 \n-1 2 7 3 2 7 3"]
NoteHere is the picture for the seconds $$$0, 1, 2$$$ and $$$3$$$ of the first testcase: Notice that robots $$$2$$$ and $$$3$$$ don't collide because they meet at the same point $$$2.5$$$, which is not integer.After second $$$3$$$ robot $$$6$$$ just drive infinitely because there's no robot to collide with.
Java 8
standard input
[ "data structures", "greedy", "implementation", "sortings" ]
1a28b972e77966453cd8239cc5c8f59a
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5$$$; $$$2 \le m \le 10^8$$$) — the number of robots and the coordinate of the right wall. The second line of each testcase contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$0 &lt; x_i &lt; m$$$) — the starting coordinates of the robots. The third line of each testcase contains $$$n$$$ space-separated characters 'L' or 'R' — the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates $$$x_i$$$ in the testcase are distinct. The sum of $$$n$$$ over all testcases doesn't exceed $$$3 \cdot 10^5$$$.
2,000
For each testcase print $$$n$$$ integers — for the $$$i$$$-th robot output the time it explodes at if it does and $$$-1$$$ otherwise.
standard output
PASSED
77c9b6e9924b5ad5b76bf878608f9cad
train_110.jsonl
1621152000
There are $$$n$$$ robots driving along an OX axis. There are also two walls: one is at coordinate $$$0$$$ and one is at coordinate $$$m$$$.The $$$i$$$-th robot starts at an integer coordinate $$$x_i~(0 &lt; x_i &lt; m)$$$ and moves either left (towards the $$$0$$$) or right with the speed of $$$1$$$ unit per second. No two robots start at the same coordinate.Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed.Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens.For each robot find out if it ever explodes and print the time of explosion if it happens and $$$-1$$$ otherwise.
256 megabytes
import java.io.*; import java.util.*; public class Main{ static void main() throws Exception{ int n=sc.nextInt(),m=sc.nextInt(); int[]in=sc.intArr(n); TreeSet<int[]>[]left=new TreeSet[2]; TreeSet<int[]>[]right=new TreeSet[2]; for(int i=0;i<2;i++) { left[i]=new TreeSet<int[]>((x,y)->x[0]-y[0]); right[i]=new TreeSet<int[]>((x,y)->x[0]-y[0]); } for(int i=0;i<n;i++) { if(sc.nextChar()=='L') { left[in[i]&1].add(new int[] {in[i],i}); } else { right[in[i]&1].add(new int[] {in[i],i}); } } int[]ans=new int[n]; Arrays.fill(ans, -1); for(int i=0;i<2;i++) { TreeSet<int[]>l=new TreeSet<int[]>((x,y)->x[0]-y[0]); while(!left[i].isEmpty()) { int[]curL=left[i].pollFirst(); int[]lastR=right[i].floor(curL); if(lastR!=null) { right[i].remove(lastR); ans[curL[1]]=ans[lastR[1]]=(curL[0]-lastR[0])>>1; continue; } l.add(curL); continue; } left[i]=l; //L L L L .... R R R R R while(right[i].size()>=2) { int[]lastR=right[i].pollLast(),prevLastR=right[i].pollLast(); ans[prevLastR[1]]=ans[lastR[1]]=((lastR[0]-prevLastR[0])>>1)+(m-lastR[0]); } while(left[i].size()>=2) { int[]curL=left[i].pollFirst(); int[]nxtL=left[i].pollFirst(); ans[curL[1]]=ans[nxtL[1]]=((nxtL[0]-curL[0])>>1)+curL[0]; continue; } if(!left[i].isEmpty() && !right[i].isEmpty()) { int[]lastR=right[i].pollLast(); int[]curL=left[i].pollFirst(); int time=0,posi=curL[0],posj=lastR[0]; if(posi<=m-posj) { posj+=posi; time+=posi; posi=0; posi+=(m-posj); time+=(m-posj); posj=m; time+=((posj-posi)>>1); } else{ posi-=(m-posj); time+=(m-posj); posj=m; posj-=posi; time+=posi; posi=0; time+=((posj-posi)>>1); } ans[curL[1]]=ans[lastR[1]]=time; } } for(int i=0;i<n;i++)pw.print(ans[i]+" "); pw.println(); } //- _ - _ - - //1 3 //0 4 //1 5 //2 4 public static void main(String[] args) throws Exception{ sc=new MScanner(System.in); pw = new PrintWriter(System.out); int tc=1; tc=sc.nextInt(); for(int i=1;i<=tc;i++) { main(); } pw.flush(); } static PrintWriter pw; static MScanner sc; static class MScanner { StringTokenizer st; BufferedReader br; public MScanner(InputStream system) { br = new BufferedReader(new InputStreamReader(system)); } public MScanner(String file) throws Exception { br = new BufferedReader(new FileReader(file)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int[] intArr(int n) throws IOException { int[]in=new int[n];for(int i=0;i<n;i++)in[i]=nextInt(); return in; } public long[] longArr(int n) throws IOException { long[]in=new long[n];for(int i=0;i<n;i++)in[i]=nextLong(); return in; } public int[] intSortedArr(int n) throws IOException { int[]in=new int[n];for(int i=0;i<n;i++)in[i]=nextInt(); shuffle(in); Arrays.sort(in); return in; } public long[] longSortedArr(int n) throws IOException { long[]in=new long[n];for(int i=0;i<n;i++)in[i]=nextLong(); shuffle(in); Arrays.sort(in); return in; } public Integer[] IntegerArr(int n) throws IOException { Integer[]in=new Integer[n];for(int i=0;i<n;i++)in[i]=nextInt(); return in; } public Long[] LongArr(int n) throws IOException { Long[]in=new Long[n];for(int i=0;i<n;i++)in[i]=nextLong(); return in; } public String nextLine() throws IOException { return br.readLine(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public char nextChar() throws IOException { return next().charAt(0); } public long nextLong() throws IOException { return Long.parseLong(next()); } public boolean ready() throws IOException { return br.ready(); } public void waitForInput() throws InterruptedException { Thread.sleep(3000); } } 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 void shuffle(long[]in) { for(int i=0;i<in.length;i++) { int idx=(int)(Math.random()*in.length); long tmp=in[i]; in[i]=in[idx]; in[idx]=tmp; } } static void sort(int[]in) { shuffle(in); Arrays.sort(in); } static void sort(long[]in) { shuffle(in); Arrays.sort(in); } }
Java
["5\n7 12\n1 2 3 4 9 10 11\nR R L L R R R\n2 10\n1 6\nR R\n2 10\n1 3\nL L\n1 10\n5\nR\n7 8\n6 1 7 2 3 5 4\nR L R L L L L"]
2 seconds
["1 1 1 1 2 -1 2 \n-1 -1 \n2 2 \n-1 \n-1 2 7 3 2 7 3"]
NoteHere is the picture for the seconds $$$0, 1, 2$$$ and $$$3$$$ of the first testcase: Notice that robots $$$2$$$ and $$$3$$$ don't collide because they meet at the same point $$$2.5$$$, which is not integer.After second $$$3$$$ robot $$$6$$$ just drive infinitely because there's no robot to collide with.
Java 8
standard input
[ "data structures", "greedy", "implementation", "sortings" ]
1a28b972e77966453cd8239cc5c8f59a
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5$$$; $$$2 \le m \le 10^8$$$) — the number of robots and the coordinate of the right wall. The second line of each testcase contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$0 &lt; x_i &lt; m$$$) — the starting coordinates of the robots. The third line of each testcase contains $$$n$$$ space-separated characters 'L' or 'R' — the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates $$$x_i$$$ in the testcase are distinct. The sum of $$$n$$$ over all testcases doesn't exceed $$$3 \cdot 10^5$$$.
2,000
For each testcase print $$$n$$$ integers — for the $$$i$$$-th robot output the time it explodes at if it does and $$$-1$$$ otherwise.
standard output
PASSED
a305ba3fb25fea963f020989b3b64599
train_110.jsonl
1621152000
There are $$$n$$$ robots driving along an OX axis. There are also two walls: one is at coordinate $$$0$$$ and one is at coordinate $$$m$$$.The $$$i$$$-th robot starts at an integer coordinate $$$x_i~(0 &lt; x_i &lt; m)$$$ and moves either left (towards the $$$0$$$) or right with the speed of $$$1$$$ unit per second. No two robots start at the same coordinate.Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed.Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens.For each robot find out if it ever explodes and print the time of explosion if it happens and $$$-1$$$ otherwise.
256 megabytes
import java.util.*; import java.io.*; public class EdA { static long[] mods = {1000000007, 998244353, 1000000009}; static long mod = mods[0]; public static MyScanner sc; public static PrintWriter out; public static void main(String[] havish) throws Exception{ // TODO Auto-generated method stub sc = new MyScanner(); out = new PrintWriter(System.out); int t = sc.nextInt(); while(t-->0) { int n = sc.nextInt(); int m = sc.nextInt(); int[] arr = readArrayInt(n); char[] rl = new char[n]; for(int j = 0;j<n;j++){ rl[j] =sc.next().charAt(0); } Map<Integer, Character> mp = new HashMap<>(); Map<Integer, Integer> valToIndex = new HashMap<>(); Map<Integer, Integer> indexToIndex = new HashMap<>(); for(int j =0 ;j<n;j++){ mp.put(arr[j], rl[j]); valToIndex.put(arr[j], j); } sort(arr); for(int j = 0;j<n;j++){ rl[j] = mp.get(arr[j]); int index = valToIndex.get(arr[j]); indexToIndex.put(index, j); } TreeSet<Pair> right = new TreeSet<>(); TreeSet<Pair> left = new TreeSet<>(); int[] ans = new int[n]; Arrays.fill(ans, -1); for(int j = 0;j<n;j++){ if (arr[j]%2 == 1) { if (rl[j] == 'R') right.add(new Pair(arr[j], j)); else { if (right.size() == 0){ left.add(new Pair(arr[j], j)); } else{ Pair val = right.lower(new Pair(arr[j], j)); if (val == null) { left.add(new Pair(arr[j], j)); } else{ ans[val.index] = (arr[j] - val.x)/2; ans[j] = (arr[j] - val.x)/2; right.remove(val); } } } } } while(left.size() >=2){ Pair p1 = left.pollFirst(); Pair p2 = left.pollFirst(); ans[p1.index] = (p1.x + p2.x)/2; ans[p2.index] = (p1.x + p2.x)/2; } while(right.size() >=2){ Pair p1 = right.pollLast(); Pair p2 = right.pollLast(); ans[p1.index] = (2*m - p1.x - p2.x)/2; ans[p2.index] = (2*m - p1.x - p2.x)/2; } if (right.size() >=1 && left.size() >=1){ Pair p1 = right.pollFirst(); Pair p2 = left.pollFirst(); ans[p1.index] = (2*m - p1.x + p2.x)/2; ans[p2.index] = (2*m - p1.x + p2.x)/2; } right.clear(); left.clear(); for(int j = 0;j<n;j++){ if (arr[j]%2 == 0) { if (rl[j] == 'R') right.add(new Pair(arr[j], j)); else { if (right.size() == 0){ left.add(new Pair(arr[j], j)); } else{ Pair val = right.lower(new Pair(arr[j], j)); if (val == null) { left.add(new Pair(arr[j], j)); } else{ ans[val.index] = (arr[j] - val.x)/2; ans[j] = (arr[j] - val.x)/2; right.remove(val); } } } } } while(left.size() >=2){ Pair p1 = left.pollFirst(); Pair p2 = left.pollFirst(); ans[p1.index] = (p1.x + p2.x)/2; ans[p2.index] = (p1.x + p2.x)/2; } while(right.size() >=2){ Pair p1 = right.pollLast(); Pair p2 = right.pollLast(); ans[p1.index] = (2*m - p1.x - p2.x)/2; ans[p2.index] = (2*m - p1.x - p2.x)/2; } if (right.size() >=1 && left.size() >=1){ Pair p1 = right.pollFirst(); Pair p2 = left.pollFirst(); ans[p1.index] = (2*m - p1.x + p2.x)/2; ans[p2.index] = (2*m - p1.x + p2.x)/2; } for(int j = 0;j<n;j++){ out.print(ans[indexToIndex.get(j)] + " "); } out.println(); } out.close(); } static class Pair implements Comparable<Pair>{ private int x; private int index; public Pair(int x, int index) { this.x = x; this.index = index; } public int compareTo(Pair other) { return Integer.compare(x, other.x); } public boolean equals(Object o) { return x==((Pair)o).x; } public int hashCode() { return Objects.hash(this); } } public static int gcd(int a, int b){ if (b == 0) return a; return gcd(b, a % b); } public static void sort(int[] array){ ArrayList<Integer> copy = new ArrayList<>(); for (int i : array) copy.add(i); Collections.sort(copy); for(int i = 0;i<array.length;i++) array[i] = copy.get(i); } static String[] readArrayString(int n){ String[] array = new String[n]; for(int j =0 ;j<n;j++) array[j] = sc.next(); return array; } static int[] readArrayInt(int n){ int[] array = new int[n]; for(int j = 0;j<n;j++) array[j] = sc.nextInt(); return array; } static int[] readArrayInt1(int n){ int[] array = new int[n+1]; for(int j = 1;j<=n;j++){ array[j] = sc.nextInt(); } return array; } static long[] readArrayLong(int n){ long[] array = new long[n]; for(int j =0 ;j<n;j++) array[j] = sc.nextLong(); return array; } static double[] readArrayDouble(int n){ double[] array = new double[n]; for(int j =0 ;j<n;j++) array[j] = sc.nextDouble(); return array; } static int minIndex(int[] array){ int minValue = Integer.MAX_VALUE; int minIndex = -1; for(int j = 0;j<array.length;j++){ if (array[j] < minValue){ minValue = array[j]; minIndex = j; } } return minIndex; } static int minIndex(long[] array){ long minValue = Long.MAX_VALUE; int minIndex = -1; for(int j = 0;j<array.length;j++){ if (array[j] < minValue){ minValue = array[j]; minIndex = j; } } return minIndex; } static int minIndex(double[] array){ double minValue = Double.MAX_VALUE; int minIndex = -1; for(int j = 0;j<array.length;j++){ if (array[j] < minValue){ minValue = array[j]; minIndex = j; } } return minIndex; } static long power(long x, long y){ if (y == 0) return 1; if (y%2 == 1) return (x*power(x, y-1))%mod; return power((x*x)%mod, y/2)%mod; } static void verdict(boolean a){ out.println(a ? "YES" : "NO"); } 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; } } } //StringJoiner sj = new StringJoiner(" "); //sj.add(strings) //sj.toString() gives string of those stuff w spaces or whatever that sequence is
Java
["5\n7 12\n1 2 3 4 9 10 11\nR R L L R R R\n2 10\n1 6\nR R\n2 10\n1 3\nL L\n1 10\n5\nR\n7 8\n6 1 7 2 3 5 4\nR L R L L L L"]
2 seconds
["1 1 1 1 2 -1 2 \n-1 -1 \n2 2 \n-1 \n-1 2 7 3 2 7 3"]
NoteHere is the picture for the seconds $$$0, 1, 2$$$ and $$$3$$$ of the first testcase: Notice that robots $$$2$$$ and $$$3$$$ don't collide because they meet at the same point $$$2.5$$$, which is not integer.After second $$$3$$$ robot $$$6$$$ just drive infinitely because there's no robot to collide with.
Java 8
standard input
[ "data structures", "greedy", "implementation", "sortings" ]
1a28b972e77966453cd8239cc5c8f59a
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5$$$; $$$2 \le m \le 10^8$$$) — the number of robots and the coordinate of the right wall. The second line of each testcase contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$0 &lt; x_i &lt; m$$$) — the starting coordinates of the robots. The third line of each testcase contains $$$n$$$ space-separated characters 'L' or 'R' — the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates $$$x_i$$$ in the testcase are distinct. The sum of $$$n$$$ over all testcases doesn't exceed $$$3 \cdot 10^5$$$.
2,000
For each testcase print $$$n$$$ integers — for the $$$i$$$-th robot output the time it explodes at if it does and $$$-1$$$ otherwise.
standard output
PASSED
7bf964e95fa28946b80d4e72f764ad34
train_110.jsonl
1621152000
There are $$$n$$$ robots driving along an OX axis. There are also two walls: one is at coordinate $$$0$$$ and one is at coordinate $$$m$$$.The $$$i$$$-th robot starts at an integer coordinate $$$x_i~(0 &lt; x_i &lt; m)$$$ and moves either left (towards the $$$0$$$) or right with the speed of $$$1$$$ unit per second. No two robots start at the same coordinate.Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed.Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens.For each robot find out if it ever explodes and print the time of explosion if it happens and $$$-1$$$ otherwise.
256 megabytes
import java.io.*; import java.util.*; public class RobotCollisions_1525C { public static void main(String[] args) throws NumberFormatException, IOException { // TODO Auto-generated method stub BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(br.readLine()); while(t -- > 0) { StringTokenizer st = new StringTokenizer(br.readLine()); int n = Integer.parseInt(st.nextToken()); int m = Integer.parseInt(st.nextToken()); int[] x = new int[n]; st = new StringTokenizer(br.readLine()); for(int i = 0; i < n; i ++) x[i] = Integer.parseInt(st.nextToken()); String[] d = new String[n]; st = new StringTokenizer(br.readLine()); for(int i = 0; i < n; i ++) d[i] = st.nextToken(); List<Robot> odds = new ArrayList<>(), evens = new ArrayList<>(); for(int i = 0; i < n; i ++) { if(x[i] % 2 == 0) { evens.add(new Robot(x[i], i, d[i])); } else { odds.add(new Robot(x[i], i, d[i])); } } int[] res = new int[n]; Arrays.fill(res, -1); Collections.sort(evens, (a, b) -> a.x - b.x); helper(evens, res, m); Collections.sort(odds, (a, b) -> a.x - b.x); helper(odds, res, m); StringBuilder output = new StringBuilder(); for(int i : res) output.append(i + " "); System.out.println(output.toString()); } } private static void helper(List<Robot> list, int[] res, int m) { Stack<Robot> stack = new Stack<>(); for(Robot robot : list) { if(stack.isEmpty() || "R".equals(robot.d)) { stack.push(robot); } else { Robot prev = stack.pop(); if("R".equals(prev.d)) { int time = (robot.x - prev.x) / 2; res[prev.idx] = time; res[robot.idx] = time; } else { int time = (robot.x + prev.x) / 2; res[prev.idx] = time; res[robot.idx] = time; } } } while(stack.size() > 1) { Robot right = stack.pop(), left = stack.pop(); if("R".equals(left.d)) { int time = (2 * m - right.x - left.x) / 2; res[right.idx] = time; res[left.idx] = time; } else { int time = (2 * m - right.x + left.x) / 2; res[right.idx] = time; res[left.idx] = time; } } } } class Robot { int x, idx; String d; public Robot(int x, int idx, String d) { this.x = x; this.idx = idx; this.d = d; } }
Java
["5\n7 12\n1 2 3 4 9 10 11\nR R L L R R R\n2 10\n1 6\nR R\n2 10\n1 3\nL L\n1 10\n5\nR\n7 8\n6 1 7 2 3 5 4\nR L R L L L L"]
2 seconds
["1 1 1 1 2 -1 2 \n-1 -1 \n2 2 \n-1 \n-1 2 7 3 2 7 3"]
NoteHere is the picture for the seconds $$$0, 1, 2$$$ and $$$3$$$ of the first testcase: Notice that robots $$$2$$$ and $$$3$$$ don't collide because they meet at the same point $$$2.5$$$, which is not integer.After second $$$3$$$ robot $$$6$$$ just drive infinitely because there's no robot to collide with.
Java 8
standard input
[ "data structures", "greedy", "implementation", "sortings" ]
1a28b972e77966453cd8239cc5c8f59a
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5$$$; $$$2 \le m \le 10^8$$$) — the number of robots and the coordinate of the right wall. The second line of each testcase contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$0 &lt; x_i &lt; m$$$) — the starting coordinates of the robots. The third line of each testcase contains $$$n$$$ space-separated characters 'L' or 'R' — the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates $$$x_i$$$ in the testcase are distinct. The sum of $$$n$$$ over all testcases doesn't exceed $$$3 \cdot 10^5$$$.
2,000
For each testcase print $$$n$$$ integers — for the $$$i$$$-th robot output the time it explodes at if it does and $$$-1$$$ otherwise.
standard output
PASSED
8851af896ebbed910d344df24fe94c74
train_110.jsonl
1621152000
There are $$$n$$$ robots driving along an OX axis. There are also two walls: one is at coordinate $$$0$$$ and one is at coordinate $$$m$$$.The $$$i$$$-th robot starts at an integer coordinate $$$x_i~(0 &lt; x_i &lt; m)$$$ and moves either left (towards the $$$0$$$) or right with the speed of $$$1$$$ unit per second. No two robots start at the same coordinate.Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed.Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens.For each robot find out if it ever explodes and print the time of explosion if it happens and $$$-1$$$ otherwise.
256 megabytes
import java.net.Inet4Address; import java.util.*; import java.io.*; public class C { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader( new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { if (st.hasMoreTokens()) { str = st.nextToken("\n"); } else { str = br.readLine(); } } catch (IOException e) { e.printStackTrace(); } return str; } } private static void runWithStd() { FastReader scanner = new FastReader(); PrintWriter output = new PrintWriter(System.out); int t = scanner.nextInt(); while (t-- > 0) { int n = scanner.nextInt(),end = scanner.nextInt(); int[] nums = new int[n]; for (int i = 0; i < n; i++) { nums[i] = scanner.nextInt(); } int[] dirs = new int[n]; for (int i = 0; i < n; i++) { String s = scanner.next(); if(s.charAt(0) == 'L') dirs[i] = -1; else dirs[i] = 1; } int[] ret = solve(nums,dirs,end); StringBuilder stringBuilder = new StringBuilder(); for(long r : ret) stringBuilder.append(r + " "); output.println(stringBuilder); } output.close(); } private static void collapse(List<int[]> nums,int[] ret,int end){ Collections.sort(nums,(o1, o2) -> o1[0] - o2[0]); Stack<int[]> toR = new Stack<>(); List<int[]> toEnd = new ArrayList<>(),to0 = new ArrayList<>(); for (int[] ele : nums) { if(ele[1] > 0){ toR.push(ele); }else{ if(!toR.isEmpty()){ int[] oppo = toR.pop(); int time = (ele[0] - oppo[0]) / 2; ret[oppo[2]] = time; ret[ele[2]] = time; }else{ to0.add(ele); } } } while (!toR.isEmpty()){ toEnd.add(toR.pop()); } for(int i = 0;i<to0.size() - 1;i+=2){ int[] ori = to0.get(i), oppo = to0.get(i + 1); int time = ori[0] + (oppo[0] - ori[0]) / 2; ret[ori[2]] = time; ret[oppo[2]] = time; } for(int i = 0;i<toEnd.size() - 1;i+=2){ int[] ori = toEnd.get(i), oppo = toEnd.get(i + 1); int time = (end - ori[0]) + (ori[0] - oppo[0]) / 2; ret[ori[2]] = time; ret[oppo[2]] = time; } int[] reach0 = to0.size() % 2 == 0 ? null : to0.get(to0.size() - 1),reachEnd = toEnd.size() % 2 == 0 ? null : toEnd.get(toEnd.size() - 1); if(reach0 != null && reachEnd != null){ int ts0 = reach0[0],tsEnd = end - reachEnd[0]; int dis = end - (Math.max(ts0,tsEnd) - Math.min(ts0,tsEnd)); int time = Math.max(ts0,tsEnd) + dis / 2; ret[reach0[2]] = time; ret[reachEnd[2]] = time; } } private static int[] solve(int[] nums, int[] dirs, int end) { int[] ret = new int[nums.length]; Arrays.fill(ret,-1); List<int[]> evens = new ArrayList<>(),odds = new ArrayList<>(); for (int i = 0; i < nums.length; i++) { if(nums[i] % 2 == 0){ evens.add(new int[]{nums[i],dirs[i],i}); }else{ odds.add(new int[]{nums[i],dirs[i],i}); } } collapse(evens,ret,end); collapse(odds,ret,end); return ret; } private static void runWithDebug() { Random random = new Random(); int t = 100; while (t-- > 0) { long ts = System.currentTimeMillis(); long delta = System.currentTimeMillis() - ts; System.out.println("case t = " + t + " time = " + delta); } System.out.println("all passed"); } public static void main(String[] args) { runWithStd(); //runWithDebug(); } }
Java
["5\n7 12\n1 2 3 4 9 10 11\nR R L L R R R\n2 10\n1 6\nR R\n2 10\n1 3\nL L\n1 10\n5\nR\n7 8\n6 1 7 2 3 5 4\nR L R L L L L"]
2 seconds
["1 1 1 1 2 -1 2 \n-1 -1 \n2 2 \n-1 \n-1 2 7 3 2 7 3"]
NoteHere is the picture for the seconds $$$0, 1, 2$$$ and $$$3$$$ of the first testcase: Notice that robots $$$2$$$ and $$$3$$$ don't collide because they meet at the same point $$$2.5$$$, which is not integer.After second $$$3$$$ robot $$$6$$$ just drive infinitely because there's no robot to collide with.
Java 8
standard input
[ "data structures", "greedy", "implementation", "sortings" ]
1a28b972e77966453cd8239cc5c8f59a
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5$$$; $$$2 \le m \le 10^8$$$) — the number of robots and the coordinate of the right wall. The second line of each testcase contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$0 &lt; x_i &lt; m$$$) — the starting coordinates of the robots. The third line of each testcase contains $$$n$$$ space-separated characters 'L' or 'R' — the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates $$$x_i$$$ in the testcase are distinct. The sum of $$$n$$$ over all testcases doesn't exceed $$$3 \cdot 10^5$$$.
2,000
For each testcase print $$$n$$$ integers — for the $$$i$$$-th robot output the time it explodes at if it does and $$$-1$$$ otherwise.
standard output
PASSED
d41867fd9557934be8240228cc3bd07a
train_110.jsonl
1621152000
There are $$$n$$$ robots driving along an OX axis. There are also two walls: one is at coordinate $$$0$$$ and one is at coordinate $$$m$$$.The $$$i$$$-th robot starts at an integer coordinate $$$x_i~(0 &lt; x_i &lt; m)$$$ and moves either left (towards the $$$0$$$) or right with the speed of $$$1$$$ unit per second. No two robots start at the same coordinate.Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed.Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens.For each robot find out if it ever explodes and print the time of explosion if it happens and $$$-1$$$ otherwise.
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 C_Robot_Collisions{ 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 m=s.nextLong(); long array[]= new long[n]; yoyo obj5 = new yoyo(); PriorityQueue<pair> even = new PriorityQueue<pair>(obj5); PriorityQueue<pair> odd = new PriorityQueue<pair>(obj5); for(int i=0;i<n;i++){ array[i]=s.nextLong(); } for(int i=0;i<n;i++){ String str=s.nextToken(); char ch=str.charAt(0); if(ch=='R'){ pair obj = new pair(array[i],i,1); if(array[i]%2==0){ even.add(obj); } else{ odd.add(obj); } } else{ pair obj = new pair(array[i],i,0); if(array[i]%2==0){ even.add(obj); } else{ odd.add(obj); } } } ArrayList<pair> sortede = new ArrayList<pair>(); ArrayList<pair> sortedo = new ArrayList<pair>(); while(even.size()>0){ sortede.add(even.poll()); } while(odd.size()>0){ sortedo.add(odd.poll()); } long ans[]= new long[n]; solve(sortede,ans,m,n); solve(sortedo,ans,m,n); for(int i=0;i<n;i++){ res.append(ans[i]+" "); } res.append(" \n"); p++;} System.out.println(res); } private static void solve(ArrayList<pair> list, long[] ans, long m, int n) { int size=list.size(); Stack<pair> well = new Stack<pair>(); ArrayList<pair> left = new ArrayList<pair>(); ArrayList<pair> right = new ArrayList<pair>(); for(int i=0;i<size;i++){ pair obj1 =list.get(i); long a=obj1.a; long b=obj1.b; long c=obj1.c; if(c==1){ well.add(obj1); } else{ if(well.size()==0){ left.add(obj1); } else{ pair obj2 =well.pop(); long a2=obj2.a; long b2=obj2.b; long hh=Math.abs(a-a2); hh=hh/2L; ans[(int)b]=hh; ans[(int)b2]=hh; } } } while(well.size()>0){ right.add(well.pop()); } Collections.reverse(right); int checkl=0; pair alpha=null; { //for left for(int i=0;i<left.size();i+=2){ if(i==left.size()-1){ checkl=1; alpha=left.get(i); break; } pair obj1 = left.get(i); long a1=obj1.a; long b1=obj1.b; pair obj2 = left.get(i+1); long a2=obj2.a; long b2=obj2.b; long hh=a1; long hh2=(a2-a1)/2L; hh+=hh2; ans[(int)b1]=hh; ans[(int)b2]=hh; } } int checkr=0; pair beta=null; { //for right for(int i=right.size()-1;i>=0;i-=2){ if(i==0){ checkr=1; beta=right.get(i); break; } pair obj1=right.get(i); long a1=obj1.a; long b1=obj1.b; pair obj2 =right.get(i-1); long a2=obj2.a; long b2=obj2.b; long hh=m-a1; long hh2=(a1-a2)/2L; hh+=hh2; ans[(int)b1]=hh; ans[(int)b2]=hh; } } if(checkl==1 && checkr==1){ long a1=alpha.a; long b3=m-beta.a; long max=Math.max(a1,b3); long min=Math.min(a1,b3); long b1=alpha.b; long b2=beta.b; long hh=max; long yo=(m-(max-min))/2L; hh+=yo; ans[(int)b1]=hh; ans[(int)b2]=hh; } else if(checkl==1 && checkr==0){ long b1=alpha.b; ans[(int)b1]=-1; } else if(checkl==0 && checkr==1){ long b1=beta.b; ans[(int)b1]=-1; } else{ // } } 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; long c; pair(long a , long b,long c){ this.a=a; this.b=b; this.c=c; } } 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\n7 12\n1 2 3 4 9 10 11\nR R L L R R R\n2 10\n1 6\nR R\n2 10\n1 3\nL L\n1 10\n5\nR\n7 8\n6 1 7 2 3 5 4\nR L R L L L L"]
2 seconds
["1 1 1 1 2 -1 2 \n-1 -1 \n2 2 \n-1 \n-1 2 7 3 2 7 3"]
NoteHere is the picture for the seconds $$$0, 1, 2$$$ and $$$3$$$ of the first testcase: Notice that robots $$$2$$$ and $$$3$$$ don't collide because they meet at the same point $$$2.5$$$, which is not integer.After second $$$3$$$ robot $$$6$$$ just drive infinitely because there's no robot to collide with.
Java 8
standard input
[ "data structures", "greedy", "implementation", "sortings" ]
1a28b972e77966453cd8239cc5c8f59a
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5$$$; $$$2 \le m \le 10^8$$$) — the number of robots and the coordinate of the right wall. The second line of each testcase contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$0 &lt; x_i &lt; m$$$) — the starting coordinates of the robots. The third line of each testcase contains $$$n$$$ space-separated characters 'L' or 'R' — the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates $$$x_i$$$ in the testcase are distinct. The sum of $$$n$$$ over all testcases doesn't exceed $$$3 \cdot 10^5$$$.
2,000
For each testcase print $$$n$$$ integers — for the $$$i$$$-th robot output the time it explodes at if it does and $$$-1$$$ otherwise.
standard output
PASSED
b268e72ff0d3569df4b2bd83e1570b97
train_110.jsonl
1621152000
There are $$$n$$$ robots driving along an OX axis. There are also two walls: one is at coordinate $$$0$$$ and one is at coordinate $$$m$$$.The $$$i$$$-th robot starts at an integer coordinate $$$x_i~(0 &lt; x_i &lt; m)$$$ and moves either left (towards the $$$0$$$) or right with the speed of $$$1$$$ unit per second. No two robots start at the same coordinate.Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed.Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens.For each robot find out if it ever explodes and print the time of explosion if it happens and $$$-1$$$ otherwise.
256 megabytes
//package com.arnavarora.usaco_prac; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; 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.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 CodeforcePrac{ public static void main(String[] args) throws Exception{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); //BufferedReader br = new BufferedReader(new FileReader("auto.in")); //PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("auto.out"))); StringTokenizer st = new StringTokenizer(br.readLine()); int t = Integer.parseInt(st.nextToken()); for (int r = 0; r<t; r++) { st = new StringTokenizer(br.readLine()); int n = Integer.parseInt(st.nextToken()); int m = Integer.parseInt(st.nextToken()); st = new StringTokenizer(br.readLine()); StringTokenizer st2 = new StringTokenizer(br.readLine()); Robot[] robots = new Robot[n]; for (int i = 0; i<n; i++) { int p = Integer.parseInt(st.nextToken()); String c = st2.nextToken(); if (c.equals("R")) { robots[i] = new Robot(1, p, i); }else { robots[i] = new Robot(0, p, i); } } //create priorityqueues ArrayDeque<Robot> right1 = new ArrayDeque<>(); ArrayDeque<Robot> left1 = new ArrayDeque<>(); ArrayDeque<Robot> right0 = new ArrayDeque<>(); ArrayDeque<Robot> left0 = new ArrayDeque<>(); Arrays.sort(robots); int[] answers = new int[n]; //right and left first combo for (int i = 0; i<n; i++) { Robot cur = robots[i]; if (cur.dir==1) { if (cur.pos%2==1) { right1.add(cur); }else { right0.add(cur); } }else { if (cur.pos%2==1) { if (!right1.isEmpty()) { Robot to = right1.removeLast(); int meet = (cur.pos-to.pos)/2; answers[cur.id] = meet; answers[to.id] = meet; }else { left1.add(cur); } }else { if (!right0.isEmpty()) { Robot to = right0.removeLast(); int meet = (cur.pos-to.pos)/2; answers[cur.id] = meet; answers[to.id] = meet; }else { left0.add(cur); } } } } //remove adjacent elements in all queues while ((right1.size()>1)) { Robot one = right1.removeLast(); Robot two = right1.removeLast(); int diff = (one.pos-two.pos); int meet = m-(diff/2); answers[one.id] = m-one.pos+diff/2; answers[two.id] = answers[one.id]; } while ((right0.size()>1)) { Robot one = right0.removeLast(); Robot two = right0.removeLast(); int diff = (one.pos-two.pos); answers[one.id] = m-one.pos+diff/2; answers[two.id] = answers[one.id]; } while (left1.size()>1) { Robot one = left1.removeFirst(); Robot two = left1.removeFirst(); answers[one.id] = (one.pos+two.pos)/2; answers[two.id] = answers[one.id]; } while (left0.size()>1) { Robot one = left0.removeFirst(); Robot two = left0.removeFirst(); int meet = (one.pos-two.pos)/2; answers[one.id] = (one.pos+two.pos)/2; answers[two.id] = answers[one.id]; } //check right1 with left1 and right0 with left0 if (right1.isEmpty()) { if (!left1.isEmpty()) { answers[left1.removeLast().id] = -1; } }else { if (left1.isEmpty()) { answers[right1.removeLast().id] = -1; }else { Robot one = right1.removeLast(); Robot two = left1.removeLast(); answers[one.id] = (2*m-one.pos+two.pos)/2; answers[two.id] = (2*m-one.pos+two.pos)/2; } } if (right0.isEmpty()) { if (!left0.isEmpty()) { answers[left0.removeLast().id] = -1; } }else { if (left0.isEmpty()) { answers[right0.removeLast().id] = -1; }else { Robot one = right0.removeLast(); Robot two = left0.removeLast(); answers[one.id] = (2*m-one.pos+two.pos)/2; answers[two.id] = (2*m-one.pos+two.pos)/2; } } for (int item: answers) { System.out.print(item+" "); } System.out.println(); } br.close(); } static class Robot implements Comparable<Robot>{ int dir, pos, id; public Robot(int d, int p, int a) { dir = d; pos = p; id = a; } @Override public int compareTo(Robot o) { return Integer.compare(this.pos, o.pos); } public String toString() { return "Pos: "+pos; } } }
Java
["5\n7 12\n1 2 3 4 9 10 11\nR R L L R R R\n2 10\n1 6\nR R\n2 10\n1 3\nL L\n1 10\n5\nR\n7 8\n6 1 7 2 3 5 4\nR L R L L L L"]
2 seconds
["1 1 1 1 2 -1 2 \n-1 -1 \n2 2 \n-1 \n-1 2 7 3 2 7 3"]
NoteHere is the picture for the seconds $$$0, 1, 2$$$ and $$$3$$$ of the first testcase: Notice that robots $$$2$$$ and $$$3$$$ don't collide because they meet at the same point $$$2.5$$$, which is not integer.After second $$$3$$$ robot $$$6$$$ just drive infinitely because there's no robot to collide with.
Java 8
standard input
[ "data structures", "greedy", "implementation", "sortings" ]
1a28b972e77966453cd8239cc5c8f59a
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5$$$; $$$2 \le m \le 10^8$$$) — the number of robots and the coordinate of the right wall. The second line of each testcase contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$0 &lt; x_i &lt; m$$$) — the starting coordinates of the robots. The third line of each testcase contains $$$n$$$ space-separated characters 'L' or 'R' — the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates $$$x_i$$$ in the testcase are distinct. The sum of $$$n$$$ over all testcases doesn't exceed $$$3 \cdot 10^5$$$.
2,000
For each testcase print $$$n$$$ integers — for the $$$i$$$-th robot output the time it explodes at if it does and $$$-1$$$ otherwise.
standard output
PASSED
68d2db05c08bc28138c046b862bbaa0c
train_110.jsonl
1621152000
There are $$$n$$$ robots driving along an OX axis. There are also two walls: one is at coordinate $$$0$$$ and one is at coordinate $$$m$$$.The $$$i$$$-th robot starts at an integer coordinate $$$x_i~(0 &lt; x_i &lt; m)$$$ and moves either left (towards the $$$0$$$) or right with the speed of $$$1$$$ unit per second. No two robots start at the same coordinate.Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed.Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens.For each robot find out if it ever explodes and print the time of explosion if it happens and $$$-1$$$ otherwise.
256 megabytes
import java.util.*; public class Main { // swap() doesn't swap i and j public static void main(String[] args) { Scanner sc=new Scanner(System.in); int t=sc.nextInt(); while(t-->0){ int n=sc.nextInt(); int m=sc.nextInt(); int arr[]=new int[n]; int i; for(i=0;i<n;i++) arr[i]=sc.nextInt(); char ch[]=new char[n]; for(i=0;i<n;i++) ch[i]=sc.next().charAt(0); ArrayList<point> even=new ArrayList<>(); ArrayList<point> odd=new ArrayList<>(); for(i=0;i<n;i++){ if(arr[i]%2==0){ even.add(new point(arr[i],i,ch[i])); } else{ odd.add(new point(arr[i],i,ch[i])); } } Collections.sort(even,new Comparator<point>(){ public int compare(point a,point b){ return a.x-b.x; } }); Collections.sort(odd,new Comparator<point>(){ public int compare(point a,point b){ return a.x-b.x; } }); int ans[]=new int[n]; Arrays.fill(ans,-1); findans(ans,even,m); findans(ans,odd,m); for(int h:ans){ System.out.print(h+" "); } System.out.println(); } } public static void findans(int ans[],ArrayList<point> arr,int m){ Stack<point> stack=new Stack<>(); for(int i=0;i<arr.size();i++){ if(arr.get(i).dir=='R') stack.push(arr.get(i)); else{ if(stack.isEmpty()){ stack.push(arr.get(i)); } else{ point p=stack.pop(); if(p.dir=='R'){ ans[arr.get(i).index]=Math.abs(p.x-arr.get(i).x)/2; ans[p.index]=Math.abs(p.x-arr.get(i).x)/2; } else{ ans[arr.get(i).index]=(p.x+arr.get(i).x)/2; ans[p.index]=(p.x+arr.get(i).x)/2; } } } } while(stack.size()>=2){ point a=stack.pop(); point b=stack.pop(); if(b.dir == 'R'){ ans[a.index] = (m-a.x+m-b.x)/2; ans[b.index] = (m-a.x+m-b.x)/2; }else{ ans[a.index] = (m-a.x+m+b.x)/2; ans[b.index] = (m-a.x+m+b.x)/2; } } } } class point{ int x; int index; char dir; public point(int a,int b,char ch){ x=a; index=b; dir=ch; } }
Java
["5\n7 12\n1 2 3 4 9 10 11\nR R L L R R R\n2 10\n1 6\nR R\n2 10\n1 3\nL L\n1 10\n5\nR\n7 8\n6 1 7 2 3 5 4\nR L R L L L L"]
2 seconds
["1 1 1 1 2 -1 2 \n-1 -1 \n2 2 \n-1 \n-1 2 7 3 2 7 3"]
NoteHere is the picture for the seconds $$$0, 1, 2$$$ and $$$3$$$ of the first testcase: Notice that robots $$$2$$$ and $$$3$$$ don't collide because they meet at the same point $$$2.5$$$, which is not integer.After second $$$3$$$ robot $$$6$$$ just drive infinitely because there's no robot to collide with.
Java 8
standard input
[ "data structures", "greedy", "implementation", "sortings" ]
1a28b972e77966453cd8239cc5c8f59a
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5$$$; $$$2 \le m \le 10^8$$$) — the number of robots and the coordinate of the right wall. The second line of each testcase contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$0 &lt; x_i &lt; m$$$) — the starting coordinates of the robots. The third line of each testcase contains $$$n$$$ space-separated characters 'L' or 'R' — the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates $$$x_i$$$ in the testcase are distinct. The sum of $$$n$$$ over all testcases doesn't exceed $$$3 \cdot 10^5$$$.
2,000
For each testcase print $$$n$$$ integers — for the $$$i$$$-th robot output the time it explodes at if it does and $$$-1$$$ otherwise.
standard output
PASSED
bd1876133934d275599451347c5621eb
train_110.jsonl
1621152000
There are $$$n$$$ robots driving along an OX axis. There are also two walls: one is at coordinate $$$0$$$ and one is at coordinate $$$m$$$.The $$$i$$$-th robot starts at an integer coordinate $$$x_i~(0 &lt; x_i &lt; m)$$$ and moves either left (towards the $$$0$$$) or right with the speed of $$$1$$$ unit per second. No two robots start at the same coordinate.Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed.Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens.For each robot find out if it ever explodes and print the time of explosion if it happens and $$$-1$$$ otherwise.
256 megabytes
import java.util.*; public class Solution { public static void main(String[] args) { Scanner in = new Scanner(System.in); StringBuffer out=new StringBuffer(); int t=in.nextInt(); while(t--!=0) { int n=in.nextInt(), m=in.nextInt(); int x[]=new int[n]; for(int i=0; i<n; i++) x[i]=in.nextInt(); HashMap<Integer, Character> map=new HashMap<>(); for(int i=0; i<n; i++) map.put(x[i], in.next().charAt(0)); List<Integer> values[]=new ArrayList[2]; for(int i=0; i<2; i++) values[i]=new ArrayList<>(); for(int item: x) { values[item%2].add(item); } HashMap<Integer, Integer> ans=new HashMap<>(); for(int i=0; i<2; i++) { Collections.sort(values[i]); // System.out.println(values[i]); LinkedList<Integer> left=new LinkedList<>(), right=new LinkedList<>(); for(int item: values[i]) { if(map.get(item)=='L') { if(!right.isEmpty()) { int ant1=right.pollLast(), ant2=item; ans.put(ant1, Math.abs(ant1-ant2)/2); ans.put(ant2, Math.abs(ant1-ant2)/2); } else { left.add(item); } } else { right.add(item); } } while(left.size()>=2) { int ant1=left.pollFirst(), ant2=left.pollFirst(); ans.put(ant1, ant1+Math.abs(ant1-ant2)/2); ans.put(ant2, ant1+Math.abs(ant1-ant2)/2); } while(right.size()>=2) { int ant1=right.pollLast(), ant2=right.pollLast(); ans.put(ant1, (m-ant1)+Math.abs(ant1-ant2)/2); ans.put(ant2, (m-ant1)+Math.abs(ant1-ant2)/2); } if(left.size()==1 && right.size()==1) { int ant1=left.poll(), ant2=right.poll(); int min=Math.min(ant1, (m-ant2)); int max=Math.max(ant1, (m-ant2)); int diff=(ant2+min)-(ant1-min); ans.put(ant1, max+diff/2); ans.put(ant2, max+diff/2); } if(!left.isEmpty()) ans.put(left.poll(), -1); if(!right.isEmpty()) ans.put(right.poll(), -1); } for(int item: x) out.append(ans.get(item)+" "); out.append("\n"); } System.out.println(out); } private static int GCD(int a, int b) { if(a==0) return b; return GCD(b%a, a); } }
Java
["5\n7 12\n1 2 3 4 9 10 11\nR R L L R R R\n2 10\n1 6\nR R\n2 10\n1 3\nL L\n1 10\n5\nR\n7 8\n6 1 7 2 3 5 4\nR L R L L L L"]
2 seconds
["1 1 1 1 2 -1 2 \n-1 -1 \n2 2 \n-1 \n-1 2 7 3 2 7 3"]
NoteHere is the picture for the seconds $$$0, 1, 2$$$ and $$$3$$$ of the first testcase: Notice that robots $$$2$$$ and $$$3$$$ don't collide because they meet at the same point $$$2.5$$$, which is not integer.After second $$$3$$$ robot $$$6$$$ just drive infinitely because there's no robot to collide with.
Java 8
standard input
[ "data structures", "greedy", "implementation", "sortings" ]
1a28b972e77966453cd8239cc5c8f59a
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5$$$; $$$2 \le m \le 10^8$$$) — the number of robots and the coordinate of the right wall. The second line of each testcase contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$0 &lt; x_i &lt; m$$$) — the starting coordinates of the robots. The third line of each testcase contains $$$n$$$ space-separated characters 'L' or 'R' — the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates $$$x_i$$$ in the testcase are distinct. The sum of $$$n$$$ over all testcases doesn't exceed $$$3 \cdot 10^5$$$.
2,000
For each testcase print $$$n$$$ integers — for the $$$i$$$-th robot output the time it explodes at if it does and $$$-1$$$ otherwise.
standard output
PASSED
e17c4e1b982266dde3812102decdf934
train_110.jsonl
1621152000
There are $$$n$$$ robots driving along an OX axis. There are also two walls: one is at coordinate $$$0$$$ and one is at coordinate $$$m$$$.The $$$i$$$-th robot starts at an integer coordinate $$$x_i~(0 &lt; x_i &lt; m)$$$ and moves either left (towards the $$$0$$$) or right with the speed of $$$1$$$ unit per second. No two robots start at the same coordinate.Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed.Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens.For each robot find out if it ever explodes and print the time of explosion if it happens and $$$-1$$$ otherwise.
256 megabytes
import java.util.*; import java.io.*; public class Main { public static void main(String args[]) {new Main().run();} FastReader in = new FastReader(); PrintWriter out = new PrintWriter(System.out); void run(){ for(int q=ni();q>0;q--){ work(); } out.flush(); } long mod=998244353; long gcd(long a,long b) { return a==0?b:gcd(b%a,a); } final long inf=Long.MAX_VALUE; int[] ret; int m; void work() { int n=ni(); m=ni(); ret=new int[n]; Arrays.fill(ret,-1); int[] A=nia(n); TreeMap<Integer,Integer> l1=new TreeMap<>(); TreeMap<Integer,Integer> l2=new TreeMap<>(); TreeMap<Integer,Integer> r1=new TreeMap<>(); TreeMap<Integer,Integer> r2=new TreeMap<>(); for(int i=0;i<n;i++){ String s=ns(); if(s.equals("L")){ if(A[i]%2==0){ l2.put(A[i],i); }else{ l1.put(A[i],i); } }else if(s.equals("R")){ if(A[i]%2==0){ r2.put(A[i],i); }else{ r1.put(A[i],i); } } } count(l1,r1); count(l2,r2); for(int r:ret){ out.print(r+" "); } out.println(); } private void count(TreeMap<Integer, Integer> l1, TreeMap<Integer, Integer> r1) { Integer p1=l1.size()==0?null:l1.firstKey(); while(p1!=null){ Integer p2 = r1.lowerKey(p1); if(p2!=null){ int p3=p1+p2>>1; ret[l1.get(p1)]=p3-p2; ret[r1.get(p2)]=p3-p2; r1.remove(p2); l1.remove(p1); } p1=l1.size()==0?null:l1.higherKey(p1); } while(l1.size()>1){ Integer pos1 = l1.firstKey(); Integer pos2 = l1.higherKey(pos1); ret[l1.get(pos1)]=pos1+(pos2-pos1)/2; ret[l1.get(pos2)]=pos1+(pos2-pos1)/2; l1.remove(pos1); l1.remove(pos2); } while(r1.size()>1){ Integer pos1 = r1.lastKey(); Integer pos2 = r1.lowerKey(pos1); ret[r1.get(pos1)]=m-pos1+(pos1-pos2)/2; ret[r1.get(pos2)]=m-pos1+(pos1-pos2)/2; r1.remove(pos1); r1.remove(pos2); } while(l1.size()>0&&r1.size()>0){ Integer pos1=l1.firstKey(); Integer pos2=r1.lastKey(); int pos3=-pos1+m-pos2+m>>1; ret[l1.get(pos1)]=pos3+pos1; ret[r1.get(pos2)]=pos3+pos1; r1.remove(pos2); l1.remove(pos1); } } private ArrayList<long[]>[] ngw(int n, int m) { ArrayList<long[]>[] graph=(ArrayList<long[]>[])new ArrayList[n]; for(int i=0;i<n;i++) { graph[i]=new ArrayList<>(); } for(int i=1;i<=m;i++) { long s=in.nextLong()-1,e=in.nextLong()-1,w=in.nextLong(); graph[(int)s].add(new long[] {e,w}); graph[(int)e].add(new long[] {s,w}); } return graph; } private int ni() { return in.nextInt(); } private long nl() { return in.nextLong(); } private String ns() { return in.next(); } private long[] na(int n) { long[] A=new long[n]; for(int i=0;i<n;i++) { A[i]=in.nextLong(); } return A; } private int[] nia(int n) { int[] A=new int[n]; for(int i=0;i<n;i++) { A[i]=in.nextInt(); } return A; } } class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br=new BufferedReader(new InputStreamReader(System.in)); } public String next() { while(st==null || !st.hasMoreElements())//回车,空行情况 { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } }
Java
["5\n7 12\n1 2 3 4 9 10 11\nR R L L R R R\n2 10\n1 6\nR R\n2 10\n1 3\nL L\n1 10\n5\nR\n7 8\n6 1 7 2 3 5 4\nR L R L L L L"]
2 seconds
["1 1 1 1 2 -1 2 \n-1 -1 \n2 2 \n-1 \n-1 2 7 3 2 7 3"]
NoteHere is the picture for the seconds $$$0, 1, 2$$$ and $$$3$$$ of the first testcase: Notice that robots $$$2$$$ and $$$3$$$ don't collide because they meet at the same point $$$2.5$$$, which is not integer.After second $$$3$$$ robot $$$6$$$ just drive infinitely because there's no robot to collide with.
Java 8
standard input
[ "data structures", "greedy", "implementation", "sortings" ]
1a28b972e77966453cd8239cc5c8f59a
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5$$$; $$$2 \le m \le 10^8$$$) — the number of robots and the coordinate of the right wall. The second line of each testcase contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$0 &lt; x_i &lt; m$$$) — the starting coordinates of the robots. The third line of each testcase contains $$$n$$$ space-separated characters 'L' or 'R' — the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates $$$x_i$$$ in the testcase are distinct. The sum of $$$n$$$ over all testcases doesn't exceed $$$3 \cdot 10^5$$$.
2,000
For each testcase print $$$n$$$ integers — for the $$$i$$$-th robot output the time it explodes at if it does and $$$-1$$$ otherwise.
standard output
PASSED
e0bfd9574b8d0e2f6c923f244cf933cf
train_110.jsonl
1621152000
There are $$$n$$$ robots driving along an OX axis. There are also two walls: one is at coordinate $$$0$$$ and one is at coordinate $$$m$$$.The $$$i$$$-th robot starts at an integer coordinate $$$x_i~(0 &lt; x_i &lt; m)$$$ and moves either left (towards the $$$0$$$) or right with the speed of $$$1$$$ unit per second. No two robots start at the same coordinate.Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed.Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens.For each robot find out if it ever explodes and print the time of explosion if it happens and $$$-1$$$ otherwise.
256 megabytes
import java.io.BufferedInputStream; import java.io.BufferedWriter; import java.io.FileInputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.Arrays; import java.util.Comparator; import java.util.Scanner; import java.util.Stack; // https://codeforces.com/contest/1525/problem/C public class Main { public static void main(String[] args) throws Exception { Scanner in = new Scanner(new BufferedInputStream(System.in)); //Scanner in = new Scanner(new BufferedInputStream(new FileInputStream("/tmp/in.txt"))); PrintWriter writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); int numTests = in.nextInt(); for (int i = 0; i < numTests; i++) { Task t = new Task(); t.run(in, writer); } } private static class Task { int n; int m; public void run(Scanner in, PrintWriter writer) { n = in.nextInt(); m = in.nextInt(); int[] x = new int[n]; String[] dir = new String[n]; for (int i = 0; i < n; i++) { x[i] = in.nextInt(); } for (int i = 0; i < n; i++) { dir[i] = in.next(); } Robot[] robots = new Robot[n]; for (int i = 0; i < n; i++) { robots[i] = new Robot(x[i], dir[i], i); } Arrays.sort(robots, Comparator.comparingInt(o -> o.x)); solve(robots, 0); solve(robots, 1); Arrays.sort(robots, Comparator.comparingInt(o -> o.pos)); for (int i = 0; i < n; i++) { writer.print(robots[i].time); if (i != n-1) { writer.print(" "); } } writer.println(); writer.flush(); } // parity = 0 means even private void solve(Robot[] robots, int parity) { Stack<Robot> s = new Stack<>(); for (Robot r : robots) { if (r.x % 2 == parity) { if (s.empty()) { if (r.dir.equals("L")) { // reflect r.x = -r.x; } s.push(r); } else if (r.dir.equals("R")) { s.push(r); } else { // non empty and L. Robot movingRight = s.pop(); int dist = r.x - movingRight.x; r.time = movingRight.time = dist/2; } } } if (!s.empty()) { while(s.size() >= 2) { Robot r = s.pop(); Robot l = s.pop(); int dist = m + (m - r.x) - l.x; l.time = r.time = dist/2; } } if (!s.empty()) { Robot r = s.pop(); r.time = -1; } } private static class Robot { public int x; public String dir; public int pos; public int time; public Robot(int x, String dir, int pos) { this.x = x; this.dir = dir; this.pos = pos; } } } }
Java
["5\n7 12\n1 2 3 4 9 10 11\nR R L L R R R\n2 10\n1 6\nR R\n2 10\n1 3\nL L\n1 10\n5\nR\n7 8\n6 1 7 2 3 5 4\nR L R L L L L"]
2 seconds
["1 1 1 1 2 -1 2 \n-1 -1 \n2 2 \n-1 \n-1 2 7 3 2 7 3"]
NoteHere is the picture for the seconds $$$0, 1, 2$$$ and $$$3$$$ of the first testcase: Notice that robots $$$2$$$ and $$$3$$$ don't collide because they meet at the same point $$$2.5$$$, which is not integer.After second $$$3$$$ robot $$$6$$$ just drive infinitely because there's no robot to collide with.
Java 8
standard input
[ "data structures", "greedy", "implementation", "sortings" ]
1a28b972e77966453cd8239cc5c8f59a
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5$$$; $$$2 \le m \le 10^8$$$) — the number of robots and the coordinate of the right wall. The second line of each testcase contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$0 &lt; x_i &lt; m$$$) — the starting coordinates of the robots. The third line of each testcase contains $$$n$$$ space-separated characters 'L' or 'R' — the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates $$$x_i$$$ in the testcase are distinct. The sum of $$$n$$$ over all testcases doesn't exceed $$$3 \cdot 10^5$$$.
2,000
For each testcase print $$$n$$$ integers — for the $$$i$$$-th robot output the time it explodes at if it does and $$$-1$$$ otherwise.
standard output
PASSED
d2edf89183f0ff037b2b4a9b429419f1
train_110.jsonl
1621152000
There are $$$n$$$ robots driving along an OX axis. There are also two walls: one is at coordinate $$$0$$$ and one is at coordinate $$$m$$$.The $$$i$$$-th robot starts at an integer coordinate $$$x_i~(0 &lt; x_i &lt; m)$$$ and moves either left (towards the $$$0$$$) or right with the speed of $$$1$$$ unit per second. No two robots start at the same coordinate.Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed.Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens.For each robot find out if it ever explodes and print the time of explosion if it happens and $$$-1$$$ otherwise.
256 megabytes
import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.BitSet; import java.util.Calendar; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.PriorityQueue; import java.util.SortedSet; import java.util.Stack; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.TreeSet; /** * # * * @author pttrung */ public class C_Edu_Round_109 { public static long MOD = 1000000007; static int[][] dp; 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++) { int n = in.nextInt(); int m = in.nextInt(); P[] data = new P[n]; for (int i = 0; i < n; i++) { data[i] = new P(i, in.nextInt(), ' '); } PriorityQueue<Point>[] q = new PriorityQueue[2]; for (int i = 0; i < q.length; i++) { q[i] = new PriorityQueue<>((a, b) -> Integer.compare(b.y, a.y)); } for (int i = 0; i < n; i++) { data[i].c = in.next().charAt(0); } int[] result = new int[n]; Arrays.fill(result, -1); Arrays.sort(data, (a, b) -> Integer.compare(a.pos, b.pos)); for (P p : data) { if (p.c == 'L') { if (!q[p.pos % 2].isEmpty()) { Point tmp = q[p.pos % 2].poll(); int dist = (p.pos - tmp.y) / 2; result[p.index] = dist; result[tmp.x] = dist; } else { q[p.pos % 2].add(new Point(p.index, -p.pos)); } } else { q[p.pos % 2].add(new Point(p.index, p.pos)); } } for (int i = 0; i < q.length; i++) { while (!q[i].isEmpty()) { Point p = q[i].poll(); if (q[i].isEmpty()) { break; } Point o = q[i].poll(); int dist = 2 * m - p.y - o.y; result[p.x] = dist / 2; result[o.x] = dist / 2; } } for (int i : result) { out.print(i + " "); } out.println(); } out.close(); } static class P { int index, pos; char c; P(int index, int pos, char c) { this.index = index; this.pos = pos; this.c = c; } } public static int[] KMP(String val) { int i = 0; int j = -1; int[] result = new int[val.length() + 1]; result[0] = -1; while (i < val.length()) { while (j >= 0 && val.charAt(j) != val.charAt(i)) { j = result[j]; } j++; i++; result[i] = j; } return result; } public static boolean nextPer(int[] data) { int i = data.length - 1; while (i > 0 && data[i] < data[i - 1]) { i--; } if (i == 0) { return false; } int j = data.length - 1; while (data[j] < data[i - 1]) { j--; } int temp = data[i - 1]; data[i - 1] = data[j]; data[j] = temp; Arrays.sort(data, i, data.length); return true; } public static int digit(long n) { int result = 0; while (n > 0) { n /= 10; result++; } return result; } public static double dist(long a, long b, long x, long y) { double val = (b - a) * (b - a) + (x - y) * (x - y); val = Math.sqrt(val); double other = x * x + a * a; other = Math.sqrt(other); return val + other; } public static class Point implements Comparable<Point> { int x, y; public Point(int start, int end) { this.x = start; this.y = end; } @Override public int compareTo(Point o) { return Integer.compare(x, o.x); } } public static class FT { long[] data; FT(int n) { data = new long[n]; } public void update(int index, long value) { while (index < data.length) { data[index] += value; index += (index & (-index)); } } public long get(int index) { long result = 0; while (index > 0) { result += data[index]; index -= (index & (-index)); } return result; } } public static long gcd(long a, long b) { if (b == 0) { return a; } return gcd(b, a % b); } public static long pow(long a, 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
["5\n7 12\n1 2 3 4 9 10 11\nR R L L R R R\n2 10\n1 6\nR R\n2 10\n1 3\nL L\n1 10\n5\nR\n7 8\n6 1 7 2 3 5 4\nR L R L L L L"]
2 seconds
["1 1 1 1 2 -1 2 \n-1 -1 \n2 2 \n-1 \n-1 2 7 3 2 7 3"]
NoteHere is the picture for the seconds $$$0, 1, 2$$$ and $$$3$$$ of the first testcase: Notice that robots $$$2$$$ and $$$3$$$ don't collide because they meet at the same point $$$2.5$$$, which is not integer.After second $$$3$$$ robot $$$6$$$ just drive infinitely because there's no robot to collide with.
Java 8
standard input
[ "data structures", "greedy", "implementation", "sortings" ]
1a28b972e77966453cd8239cc5c8f59a
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5$$$; $$$2 \le m \le 10^8$$$) — the number of robots and the coordinate of the right wall. The second line of each testcase contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$0 &lt; x_i &lt; m$$$) — the starting coordinates of the robots. The third line of each testcase contains $$$n$$$ space-separated characters 'L' or 'R' — the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates $$$x_i$$$ in the testcase are distinct. The sum of $$$n$$$ over all testcases doesn't exceed $$$3 \cdot 10^5$$$.
2,000
For each testcase print $$$n$$$ integers — for the $$$i$$$-th robot output the time it explodes at if it does and $$$-1$$$ otherwise.
standard output
PASSED
8e0ffe54ead5b27997e1e430e955cf48
train_110.jsonl
1621152000
There are $$$n$$$ robots driving along an OX axis. There are also two walls: one is at coordinate $$$0$$$ and one is at coordinate $$$m$$$.The $$$i$$$-th robot starts at an integer coordinate $$$x_i~(0 &lt; x_i &lt; m)$$$ and moves either left (towards the $$$0$$$) or right with the speed of $$$1$$$ unit per second. No two robots start at the same coordinate.Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed.Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens.For each robot find out if it ever explodes and print the time of explosion if it happens and $$$-1$$$ otherwise.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.StringTokenizer; import java.util.*; public class RobotCollisions { class Element implements Comparable<Element>{ int loc; int idx; char dir; public Element(int loc, int idx, char dir) { this.loc = loc; this.idx = idx; this.dir = dir; } @Override public int compareTo(Element o) { return this.loc - o.loc; } } MyScanner scanner = new MyScanner(); private int[] solve(int right, int[] pos, char[] dir) { int[] ans = new int[pos.length]; Arrays.fill(ans, -1); Set<Element> set1 = new TreeSet<>(); Set<Element> set2 = new TreeSet<>(); for (int i = 0; i < pos.length; i++) { if (pos[i] % 2 == 0) { set1.add(new Element(pos[i], i, dir[i])); } else { set2.add(new Element(pos[i], i, dir[i])); } } collision(set1, right, ans); collision(set2, right, ans); return ans; } private void collision(Set<Element> elements, int right, int[] ans) { Deque<Element> stack = new ArrayDeque<>(); for (Element elem : elements) { if (stack.isEmpty() || elem.dir == 'R') { stack.push(elem); } else { int time = stack.peek().dir == 'R' ? (elem.loc - stack.peek().loc) / 2 : (elem.loc + stack.peek().loc) / 2; ans[stack.peek().idx] = time; ans[elem.idx] = time; stack.pop(); } } while (stack.size() > 1) { Element e1 = stack.pop(), e2 = stack.pop(); int time = e2.dir == 'R' ? right - (e1.loc + e2.loc) / 2 : right - (e1.loc - e2.loc) / 2; ans[e1.idx] = time; ans[e2.idx] = time; } } private void printArr(int[] arr) { StringBuilder sb = new StringBuilder(); for (int num : arr) { sb.append(num + " "); } System.out.println(sb.substring(0, sb.length() - 1)); } public static void main(String[] args) { RobotCollisions test = new RobotCollisions(); int t = test.scanner.nextInt(); for (int i = 0; i < t; i++) { int n = test.scanner.nextInt(), right = test.scanner.nextInt(); int[] pos = test.scanner.nextIntArray(n); char[] dir = test.scanner.nextCharArray(n); int[] ans = test.solve(right, pos, dir); test.print(ans); } } private void print(int[] arr) { StringBuilder sb = new StringBuilder(); for (int num : arr) { sb.append(num + " "); } System.out.println(sb.substring(0, sb.length() - 1)); } private int ask(int l, int r) { System.out.println("? " + (l + 1) + " " + (r + 1)); System.out.flush(); int ans = scanner.nextInt(); return ans - 1; } private void print(int n) { System.out.println("! " + (n + 1)); System.out.flush(); } private void print(boolean b, String s1, String s2) { if (b) { System.out.println(s1); } else { System.out.println(s2); } } 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()); } int[] nextIntArray(int len) { int[] arr = new int[len]; for (int i = 0; i < len; i++) { arr[i] = nextInt(); } return arr; } char[] nextCharArray(int len) { char[] arr = new char[len]; for (int i = 0; i < len; i++) { arr[i] = next().charAt(0); } return arr; } 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\n7 12\n1 2 3 4 9 10 11\nR R L L R R R\n2 10\n1 6\nR R\n2 10\n1 3\nL L\n1 10\n5\nR\n7 8\n6 1 7 2 3 5 4\nR L R L L L L"]
2 seconds
["1 1 1 1 2 -1 2 \n-1 -1 \n2 2 \n-1 \n-1 2 7 3 2 7 3"]
NoteHere is the picture for the seconds $$$0, 1, 2$$$ and $$$3$$$ of the first testcase: Notice that robots $$$2$$$ and $$$3$$$ don't collide because they meet at the same point $$$2.5$$$, which is not integer.After second $$$3$$$ robot $$$6$$$ just drive infinitely because there's no robot to collide with.
Java 8
standard input
[ "data structures", "greedy", "implementation", "sortings" ]
1a28b972e77966453cd8239cc5c8f59a
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5$$$; $$$2 \le m \le 10^8$$$) — the number of robots and the coordinate of the right wall. The second line of each testcase contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$0 &lt; x_i &lt; m$$$) — the starting coordinates of the robots. The third line of each testcase contains $$$n$$$ space-separated characters 'L' or 'R' — the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates $$$x_i$$$ in the testcase are distinct. The sum of $$$n$$$ over all testcases doesn't exceed $$$3 \cdot 10^5$$$.
2,000
For each testcase print $$$n$$$ integers — for the $$$i$$$-th robot output the time it explodes at if it does and $$$-1$$$ otherwise.
standard output
PASSED
0fc707ef6db4f039fee43c14401b7413
train_110.jsonl
1621152000
There are $$$n$$$ robots driving along an OX axis. There are also two walls: one is at coordinate $$$0$$$ and one is at coordinate $$$m$$$.The $$$i$$$-th robot starts at an integer coordinate $$$x_i~(0 &lt; x_i &lt; m)$$$ and moves either left (towards the $$$0$$$) or right with the speed of $$$1$$$ unit per second. No two robots start at the same coordinate.Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed.Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens.For each robot find out if it ever explodes and print the time of explosion if it happens and $$$-1$$$ otherwise.
256 megabytes
import java.util.*; import java.io.*; public class C1525 { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter pw = new PrintWriter(System.out); int t = sc.nextInt(); while (t-- > 0) { int n = sc.nextInt(); int m = sc.nextInt(); Robot[] x = new Robot[n]; int[] ans = new int[n]; Arrays.fill(ans, -1); for (int i = 0; i < x.length; i++) { x[i] = new Robot(i, sc.nextInt()); } for (int i = 0; i < x.length; i++) { x[i].setDir(sc.next().charAt(0)); } Arrays.sort(x, (u, v) -> u.x - v.x); LinkedList<Robot>[] right = new LinkedList[2]; for (int i = 0; i < right.length; i++) { right[i] = new LinkedList<Robot>(); } for (Robot r : x) { if (r.dir == 'R') { right[((r.x % 2) + 2) % 2].addLast(r); } else { if (!right[r.x % 2].isEmpty()) { Robot popped = right[((r.x % 2) + 2) % 2].pollLast(); ans[r.idx] = ans[popped.idx] = (r.x - popped.x) / 2; } else { int newX = -r.x; r.x = newX; right[((r.x % 2) + 2) % 2].addFirst(r); } } } for (int i = 0; i < 2; i++) { while (right[i].size() > 1) { Robot r1 = right[i].pollLast(); Robot r2 = right[i].pollLast(); ans[r1.idx] = ans[r2.idx] = (((m - r1.x) + m) - r2.x) / 2; } } for (int y : ans) { pw.print(y + " "); } pw.println(); } pw.close(); } static class Robot { int idx; int x; char dir; public Robot(int idx, int x) { this.x = x; this.idx = idx; } public void setDir(char dir) { this.dir = dir; } } static class Scanner { BufferedReader br; StringTokenizer st; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public Scanner(FileReader f) { br = new BufferedReader(f); } 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 double nextDouble() throws IOException { return Double.parseDouble(next()); } public int[] nextIntArr(int n) throws IOException { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = Integer.parseInt(next()); } return arr; } } }
Java
["5\n7 12\n1 2 3 4 9 10 11\nR R L L R R R\n2 10\n1 6\nR R\n2 10\n1 3\nL L\n1 10\n5\nR\n7 8\n6 1 7 2 3 5 4\nR L R L L L L"]
2 seconds
["1 1 1 1 2 -1 2 \n-1 -1 \n2 2 \n-1 \n-1 2 7 3 2 7 3"]
NoteHere is the picture for the seconds $$$0, 1, 2$$$ and $$$3$$$ of the first testcase: Notice that robots $$$2$$$ and $$$3$$$ don't collide because they meet at the same point $$$2.5$$$, which is not integer.After second $$$3$$$ robot $$$6$$$ just drive infinitely because there's no robot to collide with.
Java 8
standard input
[ "data structures", "greedy", "implementation", "sortings" ]
1a28b972e77966453cd8239cc5c8f59a
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5$$$; $$$2 \le m \le 10^8$$$) — the number of robots and the coordinate of the right wall. The second line of each testcase contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$0 &lt; x_i &lt; m$$$) — the starting coordinates of the robots. The third line of each testcase contains $$$n$$$ space-separated characters 'L' or 'R' — the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates $$$x_i$$$ in the testcase are distinct. The sum of $$$n$$$ over all testcases doesn't exceed $$$3 \cdot 10^5$$$.
2,000
For each testcase print $$$n$$$ integers — for the $$$i$$$-th robot output the time it explodes at if it does and $$$-1$$$ otherwise.
standard output
PASSED
eae1a51ebf025cf7ea4dc22f696ca094
train_110.jsonl
1621152000
There are $$$n$$$ robots driving along an OX axis. There are also two walls: one is at coordinate $$$0$$$ and one is at coordinate $$$m$$$.The $$$i$$$-th robot starts at an integer coordinate $$$x_i~(0 &lt; x_i &lt; m)$$$ and moves either left (towards the $$$0$$$) or right with the speed of $$$1$$$ unit per second. No two robots start at the same coordinate.Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed.Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens.For each robot find out if it ever explodes and print the time of explosion if it happens and $$$-1$$$ otherwise.
256 megabytes
import java.util.*; public class Solution { public static void main(String[] args) { Scanner in = new Scanner(System.in); StringBuffer out=new StringBuffer(); int t=in.nextInt(); while(t--!=0) { int n=in.nextInt(), m=in.nextInt(); int x[]=new int[n]; for(int i=0; i<n; i++) x[i]=in.nextInt(); HashMap<Integer, Character> map=new HashMap<>(); for(int i=0; i<n; i++) map.put(x[i], in.next().charAt(0)); List<Integer> values[]=new ArrayList[2]; for(int i=0; i<2; i++) values[i]=new ArrayList<>(); for(int item: x) { values[item%2].add(item); } HashMap<Integer, Integer> ans=new HashMap<>(); for(int i=0; i<2; i++) { Collections.sort(values[i]); // System.out.println(values[i]); LinkedList<Integer> left=new LinkedList<>(), right=new LinkedList<>(); for(int item: values[i]) { if(map.get(item)=='L') { if(!right.isEmpty()) { int ant1=right.pollLast(), ant2=item; ans.put(ant1, Math.abs(ant1-ant2)/2); ans.put(ant2, Math.abs(ant1-ant2)/2); } else { left.add(item); } } else { right.add(item); } } // System.out.println(left+" "+right); while(left.size()>=2) { int ant1=left.pollFirst(), ant2=left.pollFirst(); ans.put(ant1, ant1+Math.abs(ant1-ant2)/2); ans.put(ant2, ant1+Math.abs(ant1-ant2)/2); } // System.out.println(left+" "+right); while(right.size()>=2) { int ant1=right.pollLast(), ant2=right.pollLast(); ans.put(ant1, (m-ant1)+Math.abs(ant1-ant2)/2); ans.put(ant2, (m-ant1)+Math.abs(ant1-ant2)/2); } // System.out.println(left+" "+right); if(left.size()==1 && right.size()==1) { int ant1=left.poll(), ant2=right.poll(); int min=Math.min(ant1, (m-ant2)); int max=Math.max(ant1, (m-ant2)); int diff=(ant2+min)-(ant1-min); ans.put(ant1, max+diff/2); ans.put(ant2, max+diff/2); } // System.out.println(left+" "+right); if(!left.isEmpty()) ans.put(left.poll(), -1); if(!right.isEmpty()) ans.put(right.poll(), -1); // System.out.println(left+" "+right); } for(int item: x) out.append(ans.get(item)+" "); out.append("\n"); } System.out.println(out); } private static int GCD(int a, int b) { if(a==0) return b; return GCD(b%a, a); } }
Java
["5\n7 12\n1 2 3 4 9 10 11\nR R L L R R R\n2 10\n1 6\nR R\n2 10\n1 3\nL L\n1 10\n5\nR\n7 8\n6 1 7 2 3 5 4\nR L R L L L L"]
2 seconds
["1 1 1 1 2 -1 2 \n-1 -1 \n2 2 \n-1 \n-1 2 7 3 2 7 3"]
NoteHere is the picture for the seconds $$$0, 1, 2$$$ and $$$3$$$ of the first testcase: Notice that robots $$$2$$$ and $$$3$$$ don't collide because they meet at the same point $$$2.5$$$, which is not integer.After second $$$3$$$ robot $$$6$$$ just drive infinitely because there's no robot to collide with.
Java 8
standard input
[ "data structures", "greedy", "implementation", "sortings" ]
1a28b972e77966453cd8239cc5c8f59a
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5$$$; $$$2 \le m \le 10^8$$$) — the number of robots and the coordinate of the right wall. The second line of each testcase contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$0 &lt; x_i &lt; m$$$) — the starting coordinates of the robots. The third line of each testcase contains $$$n$$$ space-separated characters 'L' or 'R' — the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates $$$x_i$$$ in the testcase are distinct. The sum of $$$n$$$ over all testcases doesn't exceed $$$3 \cdot 10^5$$$.
2,000
For each testcase print $$$n$$$ integers — for the $$$i$$$-th robot output the time it explodes at if it does and $$$-1$$$ otherwise.
standard output
PASSED
ed26cddb0eeee1073850842c4eab7f1f
train_110.jsonl
1621152000
There are $$$n$$$ robots driving along an OX axis. There are also two walls: one is at coordinate $$$0$$$ and one is at coordinate $$$m$$$.The $$$i$$$-th robot starts at an integer coordinate $$$x_i~(0 &lt; x_i &lt; m)$$$ and moves either left (towards the $$$0$$$) or right with the speed of $$$1$$$ unit per second. No two robots start at the same coordinate.Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed.Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens.For each robot find out if it ever explodes and print the time of explosion if it happens and $$$-1$$$ otherwise.
256 megabytes
import java.util.*; import java.io.*; public class Pizza { public static void main(String[] args)throws IOException{ PrintWriter out = new PrintWriter(System.out); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); int t = Integer.parseInt(st.nextToken()); for(int z=0;z<t;z++){ st = new StringTokenizer(br.readLine()); int n = Integer.parseInt(st.nextToken()); int m = Integer.parseInt(st.nextToken()); Integer[] ind = new Integer[n]; int[] x = new int[n]; char[] d = new char[n]; st = new StringTokenizer(br.readLine()); for(int i=0;i<n;i++){ x[i] = Integer.parseInt(st.nextToken()); ind[i] = i; } st = new StringTokenizer(br.readLine()); for(int i=0;i<n;i++){ d[i] = st.nextToken().charAt(0); } Arrays.sort(ind,new Comparator<Integer>(){ public int compare(Integer i1,Integer i2){ return x[i1]-x[i2]; } }); //for(int i=0;i<n;i++) out.print(x[ind[i]]+" "); int[] score = new int[n]; LinkedList<Integer>[] s = new LinkedList[2]; for(int i=0;i<2;i++) s[i] = new LinkedList<Integer>(); for(int i=0;i<n;i++){ int indice = ind[i]; int pai = x[indice]%2; if(d[indice]=='L'){ if(s[pai].size()==0){ x[indice] *= -1; s[pai].addLast(indice); }else{ int in = s[pai].removeLast(); score[in] = (x[indice]-x[in])/2; score[indice] = (x[indice]-x[in])/2; } }else{ s[pai].addLast(indice); } } for(int pai=0;pai<2;pai++){ while(s[pai].size()>1){ int in1 = s[pai].removeLast(); int in2 = s[pai].removeLast(); x[in1] = m+m-x[in1]; score[in1] = (x[in1]-x[in2])/2; score[in2] = (x[in1]-x[in2])/2; } if(s[pai].size()==1){ int in = s[pai].removeLast(); score[in] = -1; } } for(int i=0;i<n;i++){ out.print(score[i]+" "); } out.println(""); } out.flush(); } }
Java
["5\n7 12\n1 2 3 4 9 10 11\nR R L L R R R\n2 10\n1 6\nR R\n2 10\n1 3\nL L\n1 10\n5\nR\n7 8\n6 1 7 2 3 5 4\nR L R L L L L"]
2 seconds
["1 1 1 1 2 -1 2 \n-1 -1 \n2 2 \n-1 \n-1 2 7 3 2 7 3"]
NoteHere is the picture for the seconds $$$0, 1, 2$$$ and $$$3$$$ of the first testcase: Notice that robots $$$2$$$ and $$$3$$$ don't collide because they meet at the same point $$$2.5$$$, which is not integer.After second $$$3$$$ robot $$$6$$$ just drive infinitely because there's no robot to collide with.
Java 8
standard input
[ "data structures", "greedy", "implementation", "sortings" ]
1a28b972e77966453cd8239cc5c8f59a
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5$$$; $$$2 \le m \le 10^8$$$) — the number of robots and the coordinate of the right wall. The second line of each testcase contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$0 &lt; x_i &lt; m$$$) — the starting coordinates of the robots. The third line of each testcase contains $$$n$$$ space-separated characters 'L' or 'R' — the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates $$$x_i$$$ in the testcase are distinct. The sum of $$$n$$$ over all testcases doesn't exceed $$$3 \cdot 10^5$$$.
2,000
For each testcase print $$$n$$$ integers — for the $$$i$$$-th robot output the time it explodes at if it does and $$$-1$$$ otherwise.
standard output
PASSED
859edc444f7f1b9656b05a2133963e45
train_110.jsonl
1621152000
There are $$$n$$$ robots driving along an OX axis. There are also two walls: one is at coordinate $$$0$$$ and one is at coordinate $$$m$$$.The $$$i$$$-th robot starts at an integer coordinate $$$x_i~(0 &lt; x_i &lt; m)$$$ and moves either left (towards the $$$0$$$) or right with the speed of $$$1$$$ unit per second. No two robots start at the same coordinate.Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed.Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens.For each robot find out if it ever explodes and print the time of explosion if it happens and $$$-1$$$ otherwise.
256 megabytes
//package codeforce.educational.r109; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Stack; import java.util.StringJoiner; import java.util.StringTokenizer; import java.util.TreeSet; import java.util.stream.Collectors; import java.util.List; import static java.util.stream.Collectors.joining; import static java.util.stream.Collectors.toList; /** * @author pribic (Priyank Doshi) * @see <a href="https://codeforces.com/contest/1525/problem/C" target="_top">https://codeforces.com/contest/1525/problem/C</a> * @since 16/05/21 1:49 PM */ public class C { static FastScanner sc = new FastScanner(System.in); public static void main(String[] args) { try (PrintWriter out = new PrintWriter(System.out)) { int T = sc.nextInt(); for (int tt = 1; tt <= T; tt++) { int n = sc.nextInt(); int m = sc.nextInt(); Car[] cars = new Car[n]; for (int i = 0; i < n; i++) { cars[i] = new Car(0, false, i); cars[i].pos = sc.nextInt(); } for (int i = 0; i < n; i++) { cars[i].dir = sc.next().equals("R"); } Arrays.sort(cars); List<Car> oddPosCar = Arrays.stream(cars).filter(car -> car.pos % 2 == 1).collect(toList()); List<Car> evenPosCar = Arrays.stream(cars).filter(car -> car.pos % 2 == 0).collect(toList()); int[] ans = new int[n]; solve(oddPosCar, ans, m); solve(evenPosCar, ans, m); for (int pos : ans) System.out.print((pos == 0 ? -1 : pos) + " "); System.out.println(); } } } // - L - R - - - 8 private static void solve(List<Car> cars, int[] ans, int m) { // System.out.println("cars.toString() = " + cars.toString()); Stack<Car> stack = new Stack<>(); for (Car car : cars) { if (stack.isEmpty()) { if (car.dir) { stack.push(car); } } else { if (car.dir) { stack.push(car); } else { //found a match Car car1 = stack.pop(); Car car2 = car; int dist = Math.abs(car1.pos - car2.pos); ans[car1.idx] = ans[car2.idx] = dist / 2; } } } //get rid of R List<Car> allRight = cars.stream().filter(car -> ans[car.idx] == 0 && car.dir).collect(Collectors.toList()); List<Car> allLeft = cars.stream().filter(car -> ans[car.idx] == 0 && !car.dir).collect(Collectors.toList()); for (int i = allRight.size() - 2; i >= 0; i -= 2) { Car car1 = allRight.get(i); Car car2 = allRight.get(i + 1); int dist = m - car2.pos + (Math.abs(car1.pos - car2.pos) / 2); ans[car1.idx] = ans[car2.idx] = dist; } for (int i = 1; i < allLeft.size(); i += 2) { Car car1 = allLeft.get(i - 1); Car car2 = allLeft.get(i); int dist = car1.pos + (Math.abs(car1.pos - car2.pos) / 2); ans[car1.idx] = ans[car2.idx] = dist; } List<Car> remaining = cars.stream().filter(car -> ans[car.idx] == 0).collect(toList()); if (remaining.size() == 2) { Car left = remaining.get(0); Car right = remaining.get(1); int distLeft = left.pos; int distRight = m - right.pos; if (distLeft == distRight) { int dist = distLeft + m / 2; ans[left.idx] = ans[right.idx] = dist; } else if (distLeft < distRight) { int dist = left.pos; // move left to 0 left.pos = 0; right.pos += dist; dist += m - right.pos; //move right to m left.pos += m - right.pos; right.pos = m; //now by 2 dist += Math.abs(left.pos - right.pos) / 2; ans[left.idx] = ans[right.idx] = dist; } else { int dist = m - right.pos; // move right to m left.pos -= (m - right.pos); right.pos = m; dist += left.pos; // move left to 0 right.pos -= left.pos; left.pos = 0; //now by 2 dist += Math.abs(right.pos - left.pos) / 2; ans[left.idx] = ans[right.idx] = dist; } } // R R //above code will match all R L // R R R or L L L // L L L R R R R R // L R } static class Car implements Comparable<Car> { int pos, idx; boolean dir; public Car(int pos, boolean dir, int idx) { this.pos = pos; this.dir = dir; this.idx = idx; } @Override public String toString() { return new StringJoiner(", ", "[", "]") .add("p=" + pos) .add("i=" + idx) .add("d=" + dir) .toString(); } @Override public int compareTo(Car o) { return pos - o.pos; } } /* cars will collide in group of 2, we cannot have more than 2 cars collide at the same time at same point 1 - - - - 6 - - - 10W all even positioned can collide all odd positioned can collide */ static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(File f) { try { br = new BufferedReader(new FileReader(f)); } catch (FileNotFoundException e) { e.printStackTrace(); } } public FastScanner(InputStream f) { br = new BufferedReader(new InputStreamReader(f)); } String next() { while (st == null || !st.hasMoreTokens()) { String s = null; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } if (s == null) return null; st = new StringTokenizer(s); } return st.nextToken(); } boolean hasMoreTokens() { while (st == null || !st.hasMoreTokens()) { String s = null; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } if (s == null) return false; st = new StringTokenizer(s); } return true; } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } } }
Java
["5\n7 12\n1 2 3 4 9 10 11\nR R L L R R R\n2 10\n1 6\nR R\n2 10\n1 3\nL L\n1 10\n5\nR\n7 8\n6 1 7 2 3 5 4\nR L R L L L L"]
2 seconds
["1 1 1 1 2 -1 2 \n-1 -1 \n2 2 \n-1 \n-1 2 7 3 2 7 3"]
NoteHere is the picture for the seconds $$$0, 1, 2$$$ and $$$3$$$ of the first testcase: Notice that robots $$$2$$$ and $$$3$$$ don't collide because they meet at the same point $$$2.5$$$, which is not integer.After second $$$3$$$ robot $$$6$$$ just drive infinitely because there's no robot to collide with.
Java 8
standard input
[ "data structures", "greedy", "implementation", "sortings" ]
1a28b972e77966453cd8239cc5c8f59a
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5$$$; $$$2 \le m \le 10^8$$$) — the number of robots and the coordinate of the right wall. The second line of each testcase contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$0 &lt; x_i &lt; m$$$) — the starting coordinates of the robots. The third line of each testcase contains $$$n$$$ space-separated characters 'L' or 'R' — the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates $$$x_i$$$ in the testcase are distinct. The sum of $$$n$$$ over all testcases doesn't exceed $$$3 \cdot 10^5$$$.
2,000
For each testcase print $$$n$$$ integers — for the $$$i$$$-th robot output the time it explodes at if it does and $$$-1$$$ otherwise.
standard output
PASSED
c5923a36a91f0cdb2493676191c55353
train_110.jsonl
1621152000
There are $$$n$$$ robots driving along an OX axis. There are also two walls: one is at coordinate $$$0$$$ and one is at coordinate $$$m$$$.The $$$i$$$-th robot starts at an integer coordinate $$$x_i~(0 &lt; x_i &lt; m)$$$ and moves either left (towards the $$$0$$$) or right with the speed of $$$1$$$ unit per second. No two robots start at the same coordinate.Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed.Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens.For each robot find out if it ever explodes and print the time of explosion if it happens and $$$-1$$$ otherwise.
256 megabytes
//------------------>>>>>>>>>>>>>>>> HI . HOW ARE YOU? <<<<<<<<<<<<<<<<<<<<<<<<<<<<<------------------------------ import java.util.*; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.List; import java.util.StringTokenizer; //---------------------------->>>>>>>>>>>>>>>>>>>>>> FK OFF <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<------------------- //--------------------------->>>>>>>>>>>>>>>>>>>>>>>> HACKER MF <<<<<<<<<<<<------------------------------------- public class practice{ static long[] count,count1,count2; static boolean[] prime; static int[] spf; static Node[] nodes,nodes1,nodes2; static long[] arr; static long[][] cost; static int[] arrInt,darrInt,farrInt; static long[][] dp; static char[] ch,ch1,ch2; static long[] darr,farr; static long[][] mat,mat1; static boolean[] vis; static long x,h; static long maxl,sum,total; static double dec; static long mx = (long)1e7; static long inf = (long)1e18; static String s,s1,s2,s3,s4; static long minl; static long mod = (long)1e9+7; // static int minl = -1; // static long n; static int n,n1,n2,q,r1,c1,r2,c2; static int arr_size = (int)2e5+10; static long a; static long b; static long c; static long d; static long y,z; static int m; static int ans; static long k; static FastScanner sc; static String[] str,str1; static Set<Long> set,set1,set2; static SortedSet<Long> ss; static List<Long> list,list1,list2,list3; static PriorityQueue<Node> pq,pq1; static LinkedList<Node> ll,ll1,ll2; static Map<Integer,List<Node>> map; static Map<Integer,Integer> map2; static Map<Integer,Node> map1; static StringBuilder sb,sb1,sb2; static int index; static int[] dx = {0,-1,0,1,-1,1,-1,1}; static int[] dy = {-1,0,1,0,-1,-1,1,1}; static class Node{ long first; char second; Node(long f,char s){ this.first = f; this.second = s; } } // public static void solve(){ // // FastScanner sc = new FastScanner(); // int t = sc.nextInt(); // // int t = 1; // for(int tt = 1 ; tt <= t ; tt++){ // //// int n = sc.nextInt(); //// arr = new long[n]; //// //// for(int i = 0 ; i < n ; i++){ //// arr[i] = sc.nextLong(); //// } // // System.out.println("Case #"+tt+": "+cost); // // } // // } //--------------->>>>IF YOU ARE HERE FOR QUICKSORT HACK THEN SORRY NO HACK FOR YOU<<<------------------------------ public static void solve(){ LinkedList<Long> oddL = new LinkedList<>(); LinkedList<Long> evenL = new LinkedList<>(); LinkedList<Long> evenR = new LinkedList<>(); LinkedList<Long> oddR = new LinkedList<>(); Arrays.sort(nodes, new Comparator<Node>() { @Override public int compare(Node a, Node b) { return Long.compare(a.first,b.first); } }); Map<Long,Long> map = new HashMap<>(); for(int i = 0 ; i < n ; i++){ Node node = nodes[i]; char dir = node.second; long pos = node.first; if(dir == 'R'){ if(pos%2 == 0) evenR.addLast(pos); else oddR.addLast(pos); } else{ if(pos%2 == 0){ if(evenR.isEmpty()) evenL.addLast(pos); else{ long num = evenR.removeLast(); long time = (pos-num)/2; map.put(num,time); map.put(pos,time); } } else{ if(oddR.isEmpty()) oddL.addLast(pos); else{ long num = oddR.removeLast(); long time = (pos-num)/2; map.put(num,time); map.put(pos,time); } } } } while(evenR.size() > 1){ long first = evenR.removeLast(); long second = evenR.removeLast(); long time = (abs(first-second))/2 + k-first; map.put(first,time); map.put(second,time); } while(oddR.size() > 1){ long first = oddR.removeLast(); long second = oddR.removeLast(); long time = (abs(first-second))/2 + k-first; map.put(first,time); map.put(second,time); } while(evenL.size() > 1){ long first = evenL.removeFirst(); long second = evenL.removeFirst(); long time = (abs(second-first))/2 + first; map.put(first,time); map.put(second,time); } while(oddL.size() > 1){ long first = oddL.removeFirst(); long second = oddL.removeFirst(); long time = (abs(second-first))/2+first; map.put(first,time); map.put(second,time); } while(evenR.size() > 0 && evenL.size() > 0){ long r = evenR.removeLast(); long l = evenL.removeFirst(); long time = l+k-r+(r-l)/2; map.put(l,time); map.put(r,time); } while(oddR.size() > 0 && oddL.size() > 0){ long r = oddR.removeLast(); long l = oddL.removeFirst(); long time = l+k-r+(r-l)/2; map.put(l,time); map.put(r,time); } for(int i = 0 ; i < n ; i++){ long num = arr[i]; if(map.containsKey(num)) sb.append(map.get(num)+" "); else sb.append("-1 "); } sb.append("\n"); } //----------->>>>>>> SPEED UP SPEED UP . THIS IS SPEEDFORCES . SPEED UP SPEEEEEEEEEEEEEEEEEEEEEEEEEEDDDDDD <<<<<<<------------------ public static void main(String[] args) { sc = new FastScanner(); // Scanner sc = new Scanner(System.in); sb = new StringBuilder(); int t = sc.nextInt(); // int t = 1; while(t > 0){ // k = sc.nextLong(); // x = sc.nextLong(); // y = sc.nextLong(); // z = sc.nextLong(); // a = sc.nextLong(); // b = sc.nextLong(); // c = sc.nextLong(); // d = sc.nextLong(); // x = sc.nextLong(); // y = sc.nextLong(); // z = sc.nextLong(); // d = sc.nextLong(); n = sc.nextInt(); // n1 = sc.nextInt(); // m = sc.nextInt(); // q = sc.nextInt(); // a = sc.nextLong(); // b = sc.nextLong(); k = sc.nextLong(); // x = sc.nextLong(); // d = sc.nextLong(); // s = sc.next(); // ch = sc.next().toCharArray(); // ch1 = sc.next().toCharArray(); // m = sc.nextInt(); // n = 6; arr = new long[n]; for(int i = 0 ; i < n ; i++){ arr[i] = sc.nextLong(); } // arrInt = new int[n]; // for(int i = 0 ; i < n ; i++){ // arrInt[i] = sc.nextInt(); // } // x = sc.nextLong(); // y = sc.nextLong(); // ch = sc.next().toCharArray(); // m = n; //// m = sc.nextInt(); // darr = new long[m]; // for(int i = 0 ; i < m ; i++){ // darr[i] = sc.nextLong(); // } // k = sc.nextLong(); // m = n; // darrInt = new int[n]; // for(int i = 0 ; i < n ; i++){ // darrInt[i] = sc.nextInt(); // } // farr = new long[m]; // for(int i = 0 ; i < m ; i++){ // farr[i] = sc.nextLong(); // } // farrInt = new int[m]; // for(int i = 0; i < m ; i++){ // farrInt[i] = sc.nextInt(); // } // m = n; // mat = new long[n+1][m+1]; // for(int i = 1 ; i <= n ; i++){ // for(int j = 1 ; j <= m ; j++){ // mat[i][j] = sc.nextLong(); // } // } // m = n; // mat = new char[n][m]; // for(int i = 0 ; i < n ; i++){ // String s = sc.next(); // for(int j = 0 ; j < m ; j++){ // mat[i][j] = s.charAt(j); // } // } // str = new String[n]; // for(int i = 0 ; i < n ; i++) // str[i] = sc.next(); nodes = new Node[n]; for(int i = 0 ; i < n ;i++) nodes[i] = new Node(arr[i],sc.next().charAt(0)); solve(); t -= 1; } System.out.print(sb); } public static int log(double n,double base){ if(n == 0 || n == 1) return 0; if(n == base) return 1; double num = Math.log(n); double den = Math.log(base); if(den == 0) return 0; return (int)(num/den); } public static boolean isPrime(long n) { // Corner cases if (n <= 1) return false; if (n <= 3) return true; // This is checked so that we can skip // middle five numbers in below loop if (n%2 == 0 || n%3 == 0) return false; for (int i=5; i*i<=n; i=i+6) if (n%i == 0 || n%(i+2) == 0) return false; return true; } public static void SpecialSieve(int MAXN) { spf = new int[MAXN]; 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; } } } public static ArrayList<Integer> getFactorization(int x) { ArrayList<Integer> ret = new ArrayList<Integer>(); while (x != 1) { ret.add(spf[x]); x = x / spf[x]; } return ret; } 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 (b/gcd(b, a % b)) * a; } public static long mod_inverse(long a,long mod){ long x1=1,x2=0; long p=mod,q,t; while(a%p!=0){ q = a/p; t = x1-q*x2; x1=x2; x2=t; t=a%p; a=p; p=t; } return x2<0 ? x2+mod : x2; } public static void swap(int[] curr,int i,int j){ int temp = curr[j]; curr[j] = curr[i]; curr[i] = temp; } static final Random random=new Random(); static void ruffleSortLong(long[] a) { int n=a.length;//shuffle, then sort for (int i=0; i<n; i++) { int oi=random.nextInt(n); long temp=a[oi]; a[oi]=a[i]; a[i]=temp; } Arrays.sort(a); } static void ruffleSortInt(int[] a) { int n=a.length;//shuffle, then sort 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 void ruffleSortChar(char[] a) { int n=a.length;//shuffle, then sort for (int i=0; i<n; i++) { int oi=random.nextInt(n); char temp=a[oi]; a[oi]=a[i]; a[i]=temp; } Arrays.sort(a); } static long binomialCoeff(long n, long k){ long res = 1; // Since C(n, k) = C(n, n-k) if (k > n - k) k = n - k; // Calculate value of // [n * (n-1) *---* (n-k+1)] / [k * (k-1) *----* 1] for (long i = 0; i < k; ++i) { res = (res*(n - i)); res = (res/(i + 1)); } return res; } static long mod(long x) { long y = mod; long result = x % y; if (result < 0) { result += y; } return result; } static long[] fact; public static long inv(long n){ return power(n, mod-2); } public static void fact(int n){ fact = new long[n+1]; fact[0] = 1; for(int j = 1;j<=n;j++) fact[j] = (fact[j-1]*(long)j)%mod; } public static long binom(int n, int k){ long prod = fact[n]; prod*=inv(fact[n-k]); prod%=mod; prod*=inv(fact[k]); prod%=mod; return prod; } static long power(long x, long y){ if (y == 0) return 1; if (y%2 == 1) return (x*power(x, y-1))%mod; return power((x*x)%mod, y/2)%mod; } static void sieve(int n){ prime = new boolean[n+1]; for(int i=2;i<n;i++) prime[i] = true; for(int p = 2; p*p <=n; p++) { if(prime[p]) { for(int i = p*p; i <= n; i += p) prime[i] = false; } } } static long abs(long a){ return Math.abs(a); } static int abs(int a){ return Math.abs(a); } static int max(int a,int b){ if(a>b) return a; else return b; } static double max(double a,double b){ if(a>b) return a; else return b; } static double min(double a,double b){ if(a>b) return b; else return a; } static int min(int a,int b){ if(a>b) return b; else return a; } static long max(long a,long b){ if(a>b) return a; else return b; } static long min(long a,long b){ if(a>b) return b; else return a; } static long sq(long num){ return num*num; } static double sq(double num){ return num*num; } static long sqrt(long num){ return (long)Math.sqrt(num); } static double sqrt(double num){ return Math.sqrt(num); } 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()); } void readArray(int n) { arr = new long[n]; for (int i = 0; i < n; i++) arr[i] = nextLong(); } long nextLong() { return Long.parseLong(next()); } } }
Java
["5\n7 12\n1 2 3 4 9 10 11\nR R L L R R R\n2 10\n1 6\nR R\n2 10\n1 3\nL L\n1 10\n5\nR\n7 8\n6 1 7 2 3 5 4\nR L R L L L L"]
2 seconds
["1 1 1 1 2 -1 2 \n-1 -1 \n2 2 \n-1 \n-1 2 7 3 2 7 3"]
NoteHere is the picture for the seconds $$$0, 1, 2$$$ and $$$3$$$ of the first testcase: Notice that robots $$$2$$$ and $$$3$$$ don't collide because they meet at the same point $$$2.5$$$, which is not integer.After second $$$3$$$ robot $$$6$$$ just drive infinitely because there's no robot to collide with.
Java 8
standard input
[ "data structures", "greedy", "implementation", "sortings" ]
1a28b972e77966453cd8239cc5c8f59a
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5$$$; $$$2 \le m \le 10^8$$$) — the number of robots and the coordinate of the right wall. The second line of each testcase contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$0 &lt; x_i &lt; m$$$) — the starting coordinates of the robots. The third line of each testcase contains $$$n$$$ space-separated characters 'L' or 'R' — the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates $$$x_i$$$ in the testcase are distinct. The sum of $$$n$$$ over all testcases doesn't exceed $$$3 \cdot 10^5$$$.
2,000
For each testcase print $$$n$$$ integers — for the $$$i$$$-th robot output the time it explodes at if it does and $$$-1$$$ otherwise.
standard output
PASSED
eb52953b585c35ba75ef8b3e763dfc58
train_110.jsonl
1621152000
There are $$$n$$$ robots driving along an OX axis. There are also two walls: one is at coordinate $$$0$$$ and one is at coordinate $$$m$$$.The $$$i$$$-th robot starts at an integer coordinate $$$x_i~(0 &lt; x_i &lt; m)$$$ and moves either left (towards the $$$0$$$) or right with the speed of $$$1$$$ unit per second. No two robots start at the same coordinate.Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed.Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens.For each robot find out if it ever explodes and print the time of explosion if it happens and $$$-1$$$ otherwise.
256 megabytes
import java.io.*; import java.util.*; public class Main { public static void main(String args[]) { FastReader input=new FastReader(); PrintWriter out=new PrintWriter(System.out); int T=input.nextInt(); while(T-->0) { int n=input.nextInt(); int m=input.nextInt(); int x[]=new int[n]; HashMap<Integer,Integer> map=new HashMap<>(); TreeSet<Integer> rightEven=new TreeSet<>(); TreeSet<Integer> leftEven=new TreeSet<>(); TreeSet<Integer> rightOdd=new TreeSet<>(); TreeSet<Integer> leftOdd=new TreeSet<>(); for(int i=0;i<n;i++) { x[i]=input.nextInt(); map.put(x[i],(i+1)); } ArrayList<Integer> leftEvenList=new ArrayList<>(); ArrayList<Integer> leftOddList=new ArrayList<>(); for(int i=0;i<n;i++) { char ch = input.next().charAt(0); if (ch=='R') { if(x[i]%2==0) { rightEven.add(x[i]); } else { rightOdd.add(x[i]); } } else { if(x[i]%2==0) { leftEven.add(x[i]); leftEvenList.add(x[i]); } else { leftOdd.add(x[i]); leftOddList.add(x[i]); } } } // out.println(rightEven); // out.println(leftEven); int arr[]=new int[n+1]; fun(m,arr,map,rightEven,leftEven,leftEvenList); fun(m,arr,map,rightOdd,leftOdd,leftOddList); for(int i=1;i<=n;i++) { out.print(arr[i]+" "); } out.println(); } out.close(); } public static void fun(int m,int arr[],HashMap<Integer,Integer> map,TreeSet<Integer> right,TreeSet<Integer> left, ArrayList<Integer> list) { Collections.sort(list); for(int i=0;i<list.size();i++) { int x=list.get(i); if(right.floor(x)!=null) { int y=right.floor(x); left.remove(x); right.remove(y); int t=(x-y)/2; arr[map.get(x)]=t; arr[map.get(y)]=t; } } while(right.size()>1) { int x=right.last(); right.remove(x); int y=right.last(); right.remove(y); int t=(m-x)+(x-y)/2; arr[map.get(x)]=t; arr[map.get(y)]=t; } while(left.size()>1) { int x=left.first(); left.remove(x); int y=left.first(); left.remove(y); int t=(x)+(y-x)/2; arr[map.get(x)]=t; arr[map.get(y)]=t; } if(right.size()==1 && left.size()==1) { int x=right.first(); int y=left.first(); int t=Math.max((m-x),y); t+=(Math.min((m-x),y)*2+(x-y))/2; arr[map.get(x)]=t; arr[map.get(y)]=t; } else if(right.size()==1) { int x=right.first(); arr[map.get(x)]=-1; } else if(left.size()==1) { int x=left.first(); arr[map.get(x)]=-1; } } public static int gcd(int a, int b) { if(a==0) { return b; } else { return gcd(b%a,a); } } 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\n7 12\n1 2 3 4 9 10 11\nR R L L R R R\n2 10\n1 6\nR R\n2 10\n1 3\nL L\n1 10\n5\nR\n7 8\n6 1 7 2 3 5 4\nR L R L L L L"]
2 seconds
["1 1 1 1 2 -1 2 \n-1 -1 \n2 2 \n-1 \n-1 2 7 3 2 7 3"]
NoteHere is the picture for the seconds $$$0, 1, 2$$$ and $$$3$$$ of the first testcase: Notice that robots $$$2$$$ and $$$3$$$ don't collide because they meet at the same point $$$2.5$$$, which is not integer.After second $$$3$$$ robot $$$6$$$ just drive infinitely because there's no robot to collide with.
Java 8
standard input
[ "data structures", "greedy", "implementation", "sortings" ]
1a28b972e77966453cd8239cc5c8f59a
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5$$$; $$$2 \le m \le 10^8$$$) — the number of robots and the coordinate of the right wall. The second line of each testcase contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$0 &lt; x_i &lt; m$$$) — the starting coordinates of the robots. The third line of each testcase contains $$$n$$$ space-separated characters 'L' or 'R' — the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates $$$x_i$$$ in the testcase are distinct. The sum of $$$n$$$ over all testcases doesn't exceed $$$3 \cdot 10^5$$$.
2,000
For each testcase print $$$n$$$ integers — for the $$$i$$$-th robot output the time it explodes at if it does and $$$-1$$$ otherwise.
standard output
PASSED
dc0a77dfec719633f857eef3fc4e1f32
train_110.jsonl
1621152000
There are $$$n$$$ robots driving along an OX axis. There are also two walls: one is at coordinate $$$0$$$ and one is at coordinate $$$m$$$.The $$$i$$$-th robot starts at an integer coordinate $$$x_i~(0 &lt; x_i &lt; m)$$$ and moves either left (towards the $$$0$$$) or right with the speed of $$$1$$$ unit per second. No two robots start at the same coordinate.Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed.Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens.For each robot find out if it ever explodes and print the time of explosion if it happens and $$$-1$$$ otherwise.
256 megabytes
import java.io.*; import java.util.ArrayList; import java.util.Arrays; import java.util.StringTokenizer; import java.util.List; import java.util.*; public class realfast implements Runnable { private static final int INF = (int) 1e9; long in= 1000000007; long fac[]= new long[1000001]; long inv[]=new long[1000001]; public void solve() throws IOException { //int t = readInt(); int t = readInt(); for(int f =0;f<t;f++) { int n = readInt(); int m = readInt(); ArrayList<edge> even = new ArrayList<edge>(); ArrayList<edge> odd = new ArrayList<edge>(); int x[]=new int[n+1]; for(int i=1;i<=n;i++) x[i]= readInt(); int s[]=new int[n+1]; for(int i=1;i<=n;i++) { String l = readString(); if(l.charAt(0)=='L') s[i]=0; else s[i]=1; } // out.println(s[1]); for(int i=1;i<=n;i++) { if(x[i]%2==0) { even.add(new edge(i,x[i],s[i])); } else odd.add(new edge(i,x[i],s[i])); } int ans[]=new int[n+1]; Arrays.fill(ans,-1); Collections.sort(even); Collections.sort(odd); list(odd,ans,x,s,m,n); list(even,ans,x,s,m,n); for(int i=1;i<=n;i++) { out.print(ans[i]+" "); } out.println(); } } public void list(ArrayList<edge> odd, int ans[], int x[], int s[], int m , int n) { int stack[]=new int[n+1]; int top=-1; for(int i=0;i<odd.size();i++) { int ind = odd.get(i).u; //out.print(ind+" "); if(s[ind]==1) { top++; stack[top]= ind; } else { if(top==-1||s[stack[top]]==0) { top++; stack[top]= ind; } else { int val = x[ind]-x[stack[top]]; val = val/2; ans[ind]= val; ans[stack[top]]=val; top--; //out.println(val); } } } // out.println(); int start=0; int end = top; while(start<=end-1) { if(s[stack[start]]==0&&s[stack[start+1]]==0) { int val = x[stack[start]]; val = val + (x[stack[start+1]]-x[stack[start]])/2; ans[stack[start]]= val; ans[stack[start+1]]=val; } else break; start=start+2; } while(end-1>=start) { if(s[stack[end-1]]==1&&s[stack[end]]==1) { int val = m- x[stack[end]]; val = val + (x[stack[end]]-x[stack[end-1]])/2; ans[stack[end]]= val; ans[stack[end-1]]=val; } else break; end=end-2; } //out.println(start+" "+end); if(start+1<=end) { int val = Math.max(m-x[stack[end]],x[stack[start]]); int pal= (m- Math.max(m-x[stack[end]],x[stack[start]])+Math.min(m-x[stack[end]],x[stack[start]]))/2; val= val+pal; ans[stack[start]]=val; ans[stack[end]]=val; } } public int value (int seg[], int left , int right ,int index, int l, int r) { if(left>right) { return -100000000; } if(right<l||left>r) return -100000000; if(left>=l&&right<=r) return seg[index]; int mid = left+(right-left)/2; int val = value(seg,left,mid,2*index+1,l,r); int val2 = value(seg,mid+1,right,2*index+2,l,r); return Math.max(val,val2); } public int gcd(int a , int b ) { if(a<b) { int t =a; a=b; b=t; } if(a%b==0) return b ; return gcd(b,a%b); } public long pow(long n , long p,long m) { if(p==0) return 1; long val = pow(n,p/2,m);; val= (val*val)%m; if(p%2==0) return val; else return (val*n)%m; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// public static void main(String[] args) { new Thread(null, new realfast(), "", 128 * (1L << 20)).start(); } private static final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null; private BufferedReader reader; private StringTokenizer tokenizer; private PrintWriter out; @Override public void run() { try { if (ONLINE_JUDGE || !new File("input.txt").exists()) { reader = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } else { reader = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter("output.txt"); } solve(); } catch (IOException e) { throw new RuntimeException(e); } finally { try { reader.close(); } catch (IOException e) { // nothing } out.close(); } } private String readString() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } @SuppressWarnings("unused") private int readInt() throws IOException { return Integer.parseInt(readString()); } @SuppressWarnings("unused") private long readLong() throws IOException { return Long.parseLong(readString()); } @SuppressWarnings("unused") private double readDouble() throws IOException { return Double.parseDouble(readString()); } } class edge implements Comparable<edge>{ int u ; int v; int dir; edge(int u, int v, int dir) { this.u=u; this.v=v; this.dir=dir; } public int compareTo(edge e) { return this.v-e.v; } }
Java
["5\n7 12\n1 2 3 4 9 10 11\nR R L L R R R\n2 10\n1 6\nR R\n2 10\n1 3\nL L\n1 10\n5\nR\n7 8\n6 1 7 2 3 5 4\nR L R L L L L"]
2 seconds
["1 1 1 1 2 -1 2 \n-1 -1 \n2 2 \n-1 \n-1 2 7 3 2 7 3"]
NoteHere is the picture for the seconds $$$0, 1, 2$$$ and $$$3$$$ of the first testcase: Notice that robots $$$2$$$ and $$$3$$$ don't collide because they meet at the same point $$$2.5$$$, which is not integer.After second $$$3$$$ robot $$$6$$$ just drive infinitely because there's no robot to collide with.
Java 8
standard input
[ "data structures", "greedy", "implementation", "sortings" ]
1a28b972e77966453cd8239cc5c8f59a
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5$$$; $$$2 \le m \le 10^8$$$) — the number of robots and the coordinate of the right wall. The second line of each testcase contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$0 &lt; x_i &lt; m$$$) — the starting coordinates of the robots. The third line of each testcase contains $$$n$$$ space-separated characters 'L' or 'R' — the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates $$$x_i$$$ in the testcase are distinct. The sum of $$$n$$$ over all testcases doesn't exceed $$$3 \cdot 10^5$$$.
2,000
For each testcase print $$$n$$$ integers — for the $$$i$$$-th robot output the time it explodes at if it does and $$$-1$$$ otherwise.
standard output
PASSED
2ede2f4fdec57a93f60b34379d2ee8a8
train_110.jsonl
1621152000
There are $$$n$$$ robots driving along an OX axis. There are also two walls: one is at coordinate $$$0$$$ and one is at coordinate $$$m$$$.The $$$i$$$-th robot starts at an integer coordinate $$$x_i~(0 &lt; x_i &lt; m)$$$ and moves either left (towards the $$$0$$$) or right with the speed of $$$1$$$ unit per second. No two robots start at the same coordinate.Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed.Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens.For each robot find out if it ever explodes and print the time of explosion if it happens and $$$-1$$$ otherwise.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Arrays; import java.io.IOException; import java.util.Stack; import java.util.ArrayList; import java.io.UncheckedIOException; import java.util.List; import java.util.Vector; import java.io.Closeable; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.Comparator; import java.util.LinkedList; import java.io.InputStream; /** * @author khokharnikunj8 */ public class Main { public static void main(String[] args) throws Exception { Thread thread = new Thread(null, new TaskAdapter(), "khokharnikunj8", 1 << 29); thread.start(); thread.join(); } static class TaskAdapter implements Runnable { @Override public void run() { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastInput in = new FastInput(inputStream); FastOutput out = new FastOutput(outputStream); CRobotCollisions solver = new CRobotCollisions(); int testCount = Integer.parseInt(in.next()); for (int i = 1; i <= testCount; i++) solver.solve(i, in, out); out.close(); } } static class CRobotCollisions { int[] ans; public void findIt(List<int[]> ar, int m) { Stack<int[]> st = new Stack<>(); List<int[]> right = new ArrayList<>(); for (int[] temp : ar) { // left if (temp[2] == 0) { st.push(temp); } // right else { if (st.size() == 0) { right.add(temp); } else { int[] temp1 = st.pop(); int dist = temp[0] - temp1[0]; dist /= 2; ans[temp[1]] = dist; ans[temp1[1]] = dist; } } } LinkedList<int[]> opening = new LinkedList<>(); while (st.size() > 0) { opening.add(st.pop()); } LinkedList<int[]> closing = new LinkedList<>(); for (int[] temp : right) closing.add(temp); while (closing.size() > 1) { int[] first = closing.removeFirst(); int[] second = closing.removeFirst(); int timeToReach0 = first[0]; int dist = second[0] - first[0]; dist /= 2; ans[first[1]] = dist + timeToReach0; ans[second[1]] = dist + timeToReach0; } while (opening.size() > 1) { int[] first = opening.removeFirst(); int[] second = opening.removeFirst(); int timeToReach0 = m - first[0]; int dist = first[0] - second[0]; dist /= 2; ans[first[1]] = dist + timeToReach0; ans[second[1]] = dist + timeToReach0; } if (closing.size() + opening.size() == 2) { int[] first = closing.removeFirst(); int[] second = opening.removeFirst(); int min = Math.min(m - second[0], first[0]); int dist1 = min * 2 + (second[0] - first[0]); int max = Math.max(m - second[0], first[0]); dist1 /= 2; ans[first[1]] = dist1 + max; ans[second[1]] = dist1 + max; } else if (closing.size() == 1) { int[] first = closing.removeFirst(); ans[first[1]] = -1; } else if (opening.size() == 1) { int[] first = opening.removeFirst(); ans[first[1]] = -1; } } public void solve(int testNumber, FastInput in, FastOutput out) { int n = in.readInt(); int m = in.readInt(); ans = new int[n]; int[][] ar = new int[n][3]; for (int i = 0; i < n; i++) { ar[i][0] = in.readInt(); ar[i][1] = i; } for (int i = 0; i < n; i++) ar[i][2] = (in.readChar() == 'R' ? 0 : 1); Arrays.sort(ar, Comparator.comparingInt(i -> i[0])); List<int[]> odd = new ArrayList<>(); List<int[]> even = new ArrayList<>(); for (int i = 0; i < n; i++) { if (ar[i][0] % 2 == 0) even.add(ar[i]); else odd.add(ar[i]); } findIt(odd, m); findIt(even, m); for (int i = 0; i < n; i++) { out.append(ans[i] + " "); } out.println(); } } static class FastInput { private final InputStream is; private final StringBuilder defaultStringBuf = new StringBuilder(1 << 13); private final byte[] buf = new byte[1 << 13]; private int bufLen; private int bufOffset; private int next; public FastInput(InputStream is) { this.is = is; } private int read() { while (bufLen == bufOffset) { bufOffset = 0; try { bufLen = is.read(buf); } catch (IOException e) { bufLen = -1; } if (bufLen == -1) { return -1; } } return buf[bufOffset++]; } public void skipBlank() { while (next >= 0 && next <= 32) { next = read(); } } public String next() { return readString(); } public int readInt() { int sign = 1; skipBlank(); if (next == '+' || next == '-') { sign = next == '+' ? 1 : -1; next = read(); } int val = 0; if (sign == 1) { while (next >= '0' && next <= '9') { val = val * 10 + next - '0'; next = read(); } } else { while (next >= '0' && next <= '9') { val = val * 10 - next + '0'; next = read(); } } return val; } public char readChar() { skipBlank(); char c = (char) next; next = read(); return c; } public String readString(StringBuilder builder) { skipBlank(); while (next > 32) { builder.append((char) next); next = read(); } return builder.toString(); } public String readString() { defaultStringBuf.setLength(0); return readString(defaultStringBuf); } } static class FastOutput implements AutoCloseable, Closeable, Appendable { private final Writer os; private final StringBuilder cache = new StringBuilder(5 << 20); public FastOutput(Writer os) { this.os = os; } public FastOutput(OutputStream os) { this(new OutputStreamWriter(os)); } public FastOutput append(CharSequence csq) { cache.append(csq); return this; } public FastOutput append(CharSequence csq, int start, int end) { cache.append(csq, start, end); return this; } public FastOutput append(char c) { cache.append(c); return this; } public FastOutput append(String c) { cache.append(c); return this; } public FastOutput println() { cache.append(System.lineSeparator()); return this; } public FastOutput flush() { try { os.append(cache); os.flush(); cache.setLength(0); } catch (IOException e) { throw new UncheckedIOException(e); } return this; } public void close() { flush(); try { os.close(); } catch (IOException e) { throw new UncheckedIOException(e); } } public String toString() { return cache.toString(); } } }
Java
["5\n7 12\n1 2 3 4 9 10 11\nR R L L R R R\n2 10\n1 6\nR R\n2 10\n1 3\nL L\n1 10\n5\nR\n7 8\n6 1 7 2 3 5 4\nR L R L L L L"]
2 seconds
["1 1 1 1 2 -1 2 \n-1 -1 \n2 2 \n-1 \n-1 2 7 3 2 7 3"]
NoteHere is the picture for the seconds $$$0, 1, 2$$$ and $$$3$$$ of the first testcase: Notice that robots $$$2$$$ and $$$3$$$ don't collide because they meet at the same point $$$2.5$$$, which is not integer.After second $$$3$$$ robot $$$6$$$ just drive infinitely because there's no robot to collide with.
Java 8
standard input
[ "data structures", "greedy", "implementation", "sortings" ]
1a28b972e77966453cd8239cc5c8f59a
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5$$$; $$$2 \le m \le 10^8$$$) — the number of robots and the coordinate of the right wall. The second line of each testcase contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$0 &lt; x_i &lt; m$$$) — the starting coordinates of the robots. The third line of each testcase contains $$$n$$$ space-separated characters 'L' or 'R' — the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates $$$x_i$$$ in the testcase are distinct. The sum of $$$n$$$ over all testcases doesn't exceed $$$3 \cdot 10^5$$$.
2,000
For each testcase print $$$n$$$ integers — for the $$$i$$$-th robot output the time it explodes at if it does and $$$-1$$$ otherwise.
standard output
PASSED
b310a795aad04ec717bebe7902e3456b
train_110.jsonl
1621152000
There are $$$n$$$ robots driving along an OX axis. There are also two walls: one is at coordinate $$$0$$$ and one is at coordinate $$$m$$$.The $$$i$$$-th robot starts at an integer coordinate $$$x_i~(0 &lt; x_i &lt; m)$$$ and moves either left (towards the $$$0$$$) or right with the speed of $$$1$$$ unit per second. No two robots start at the same coordinate.Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed.Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens.For each robot find out if it ever explodes and print the time of explosion if it happens and $$$-1$$$ otherwise.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.AbstractCollection; import java.util.StringTokenizer; import java.io.BufferedReader; import java.util.Comparator; import java.util.LinkedList; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author xwchen */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { public void solve(int testNumber, InputReader in, PrintWriter out) { int testCase = in.nextInt(); while (testCase-- > 0) { int n = in.nextInt(); int m = in.nextInt(); int[] x = in.nextIntArray(n); String[] direction = in.nextLine().split(" "); char[] d = new char[n]; ArrayList<Item> items = new ArrayList<>(n); for (int i = 0; i < n; ++i) { d[i] = direction[i].charAt(0); items.add(new Item(i, x[i], d[i])); } items.sort(Comparator.comparingInt(o -> o.pos)); LinkedList<Integer> queue = new LinkedList<>(); int[] res = new int[n]; gao(queue, items, res, m, n, 0); gao(queue, items, res, m, n, 1); for (int i = 0; i < n; i++) { out.print(res[i] + " "); } out.println(); } } void gao(LinkedList<Integer> queue, ArrayList<Item> items, int[] res, int m, int n, int r) { for (int i = 0; i < n; i++) { if (items.get(i).pos % 2 == r) { if (items.get(i).dir == 'L') { if (!queue.isEmpty()) { if (items.get(queue.getLast()).dir == 'R') { int idx = queue.pollLast(); int diff = items.get(i).pos - items.get(idx).pos; diff /= 2; res[items.get(i).idx] = res[items.get(idx).idx] = diff; } else { int idx = queue.pollLast(); int diff = items.get(i).pos + items.get(idx).pos; diff /= 2; res[items.get(i).idx] = res[items.get(idx).idx] = diff; } } else { queue.add(i); } } else { queue.addLast(i); } } } int left = gaoLeft(queue, items, res, m); int right = gaoRight(queue, items, res, m); if (left != -1 && right != -1) { int diff = items.get(left).pos + m - items.get(right).pos + m; diff /= 2; res[items.get(left).idx] = res[items.get(right).idx] = diff; } else { if (left != -1) { res[items.get(left).idx] = -1; } if (right != -1) { res[items.get(right).idx] = -1; } } } int gaoRight(LinkedList<Integer> queue, ArrayList<Item> items, int[] res, int m) { LinkedList<Integer> list = new LinkedList<>(); while (!queue.isEmpty() && items.get(queue.getLast()).dir == 'R') { list.addFirst(queue.pollLast()); } while (list.size() > 1) { int first = list.pollLast(); int second = list.pollLast(); int diff = m - items.get(first).pos + m - items.get(second).pos; diff /= 2; res[items.get(first).idx] = res[items.get(second).idx] = diff; } if (list.size() > 0) { return list.getFirst(); } else { return -1; } } int gaoLeft(LinkedList<Integer> queue, ArrayList<Item> items, int[] res, int m) { LinkedList<Integer> list = new LinkedList<>(); while (!queue.isEmpty() && items.get(queue.getFirst()).dir == 'L') { list.addLast(queue.pollFirst()); } while (list.size() > 1) { int first = list.pollFirst(); int second = list.pollFirst(); int diff = items.get(first).pos + items.get(second).pos; diff /= 2; res[items.get(first).idx] = res[items.get(second).idx] = diff; } if (list.size() > 0) { return list.getFirst(); } else { return -1; } } class Item { public int idx; public int pos; public char dir; public Item(int idx, int pos, char dir) { this.idx = idx; this.pos = pos; this.dir = dir; } } } static class InputReader { private BufferedReader reader; private StringTokenizer tokenizer = new StringTokenizer(""); public InputReader(InputStream inputStream) { this.reader = new BufferedReader( new InputStreamReader(inputStream)); } public String next() { while (!tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { e.printStackTrace(); } } return tokenizer.nextToken(); } public String nextLine() { String ret = ""; try { ret = reader.readLine(); } catch (IOException e) { e.printStackTrace(); } return ret; } public int nextInt() { return Integer.parseInt(next()); } public int[] nextIntArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } } }
Java
["5\n7 12\n1 2 3 4 9 10 11\nR R L L R R R\n2 10\n1 6\nR R\n2 10\n1 3\nL L\n1 10\n5\nR\n7 8\n6 1 7 2 3 5 4\nR L R L L L L"]
2 seconds
["1 1 1 1 2 -1 2 \n-1 -1 \n2 2 \n-1 \n-1 2 7 3 2 7 3"]
NoteHere is the picture for the seconds $$$0, 1, 2$$$ and $$$3$$$ of the first testcase: Notice that robots $$$2$$$ and $$$3$$$ don't collide because they meet at the same point $$$2.5$$$, which is not integer.After second $$$3$$$ robot $$$6$$$ just drive infinitely because there's no robot to collide with.
Java 8
standard input
[ "data structures", "greedy", "implementation", "sortings" ]
1a28b972e77966453cd8239cc5c8f59a
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5$$$; $$$2 \le m \le 10^8$$$) — the number of robots and the coordinate of the right wall. The second line of each testcase contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$0 &lt; x_i &lt; m$$$) — the starting coordinates of the robots. The third line of each testcase contains $$$n$$$ space-separated characters 'L' or 'R' — the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates $$$x_i$$$ in the testcase are distinct. The sum of $$$n$$$ over all testcases doesn't exceed $$$3 \cdot 10^5$$$.
2,000
For each testcase print $$$n$$$ integers — for the $$$i$$$-th robot output the time it explodes at if it does and $$$-1$$$ otherwise.
standard output
PASSED
a8cd83736ade88a22565c93f4ffb81a8
train_110.jsonl
1621152000
There are $$$n$$$ robots driving along an OX axis. There are also two walls: one is at coordinate $$$0$$$ and one is at coordinate $$$m$$$.The $$$i$$$-th robot starts at an integer coordinate $$$x_i~(0 &lt; x_i &lt; m)$$$ and moves either left (towards the $$$0$$$) or right with the speed of $$$1$$$ unit per second. No two robots start at the same coordinate.Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed.Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens.For each robot find out if it ever explodes and print the time of explosion if it happens and $$$-1$$$ otherwise.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; import java.lang.*; public class Practice { public static long mod = (long) Math.pow(10, 9) + 7; public static long tt = 0; public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw = new PrintWriter(System.out); int c = 1; int t = Integer.parseInt(br.readLine()); while (t-- > 0) { String[] s1 = br.readLine().split(" "); int n = Integer.valueOf(s1[0]); long m = Integer.valueOf(s1[1]); class Node { long val; int ind; char dir; public Node(int ind, long val, char dir) { this.val = val; this.ind = ind; this.dir = dir; } } ArrayList<Node> even = new ArrayList<>(); // ArrayList<Node> evenr = new ArrayList<>(); ArrayList<Node> odd = new ArrayList<>(); // ArrayList<Node> oddr = new ArrayList<>(); String str = (br.readLine()); String[] s2 = str.split(" "); str = (br.readLine()); String[] s3 = str.split(" "); int a = 0; for (int i = 0; i < n; i++) { long curr = Integer.valueOf(s2[i]); if (curr % 2 == 0) { Node node = new Node(i, curr, s3[i].charAt(0)); even.add(node); } else { Node node = new Node(i, curr, s3[i].charAt(0)); odd.add(node); } } Collections.sort(even, new Comparator<Node>() { @Override public int compare(Node o1, Node o2) { // TODO Auto-generated method stub return o1.val - o2.val > 0 ? 1 : -1; } }); Collections.sort(odd, new Comparator<Node>() { @Override public int compare(Node o1, Node o2) { // TODO Auto-generated method stub return o1.val - o2.val > 0 ? 1 : -1; } }); long[] ans = new long[n]; Arrays.fill(ans, -1); Stack<Integer> stack = new Stack<Integer>(); for (int i = 0; i < even.size(); i++) { if (even.get(i).dir == 'R') { stack.push(i); } else { if (!stack.isEmpty()) { int j = stack.pop(); long tt = (even.get(i).val - even.get(j).val) / 2; ans[even.get(i).ind] = tt; ans[even.get(j).ind] = tt; } } } int j = -1; for (int i = 0; i < even.size(); i++) { if (ans[even.get(i).ind] == -1 && even.get(i).dir == 'L') { if (j != -1) { long tt = (even.get(j).val + (even.get(i).val - even.get(j).val) / 2); ans[even.get(i).ind] = tt; ans[even.get(j).ind] = tt; j = -1; } else { j = i; } } } int k=-1; for (int i = even.size()-1; i>=0; i--) { if (ans[even.get(i).ind] == -1 && even.get(i).dir == 'R') { if (k != -1) { long tt = (m-even.get(k).val + ( even.get(k).val - even.get(i).val) / 2); ans[even.get(k).ind] = tt; ans[even.get(i).ind] = tt; k = -1; } else { k = i; } } } if(k!=-1&&j!=-1) { long tt = ((2*m-even.get(k).val+even.get(j).val) / 2); ans[even.get(k).ind] = tt; ans[even.get(j).ind] = tt; } stack = new Stack<Integer>(); even=odd; for (int i = 0; i < even.size(); i++) { if (even.get(i).dir == 'R') { stack.push(i); } else { if (!stack.isEmpty()) { int p = stack.pop(); long tt = (even.get(i).val - even.get(p).val) / 2; ans[even.get(i).ind] = tt; ans[even.get(p).ind] = tt; } } } j = -1; for (int i = 0; i < even.size(); i++) { if (ans[even.get(i).ind] == -1 && even.get(i).dir == 'L') { if (j != -1) { long tt = (even.get(j).val + (even.get(i).val - even.get(j).val) / 2); ans[even.get(i).ind] = tt; ans[even.get(j).ind] = tt; j = -1; } else { j = i; } } } k=-1; for (int i = even.size()-1; i>=0; i--) { if (ans[even.get(i).ind] == -1 && even.get(i).dir == 'R') { if (k != -1) { long tt = (m-even.get(k).val + ( even.get(k).val - even.get(i).val) / 2); ans[even.get(k).ind] = tt; ans[even.get(i).ind] = tt; k = -1; } else { k = i; } } } if(k!=-1&&j!=-1) { long tt = ((2*m-even.get(k).val+even.get(j).val) / 2); ans[even.get(k).ind] = tt; ans[even.get(j).ind] = tt; } StringBuilder ttt=new StringBuilder(); for(int i=0;i<n;i++) { ttt.append(ans[i]+" "); } pw.println(ttt.toString()); } pw.close(); } private static long getGCD(long l, long m) { // TODO Auto-generated method stub 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 long getGCD(long l, long m) { // // TODO Auto-generated method stub // // 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\n7 12\n1 2 3 4 9 10 11\nR R L L R R R\n2 10\n1 6\nR R\n2 10\n1 3\nL L\n1 10\n5\nR\n7 8\n6 1 7 2 3 5 4\nR L R L L L L"]
2 seconds
["1 1 1 1 2 -1 2 \n-1 -1 \n2 2 \n-1 \n-1 2 7 3 2 7 3"]
NoteHere is the picture for the seconds $$$0, 1, 2$$$ and $$$3$$$ of the first testcase: Notice that robots $$$2$$$ and $$$3$$$ don't collide because they meet at the same point $$$2.5$$$, which is not integer.After second $$$3$$$ robot $$$6$$$ just drive infinitely because there's no robot to collide with.
Java 8
standard input
[ "data structures", "greedy", "implementation", "sortings" ]
1a28b972e77966453cd8239cc5c8f59a
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5$$$; $$$2 \le m \le 10^8$$$) — the number of robots and the coordinate of the right wall. The second line of each testcase contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$0 &lt; x_i &lt; m$$$) — the starting coordinates of the robots. The third line of each testcase contains $$$n$$$ space-separated characters 'L' or 'R' — the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates $$$x_i$$$ in the testcase are distinct. The sum of $$$n$$$ over all testcases doesn't exceed $$$3 \cdot 10^5$$$.
2,000
For each testcase print $$$n$$$ integers — for the $$$i$$$-th robot output the time it explodes at if it does and $$$-1$$$ otherwise.
standard output
PASSED
d702af9a320ce8527cb2e93aa70afd63
train_110.jsonl
1621152000
There are $$$n$$$ robots driving along an OX axis. There are also two walls: one is at coordinate $$$0$$$ and one is at coordinate $$$m$$$.The $$$i$$$-th robot starts at an integer coordinate $$$x_i~(0 &lt; x_i &lt; m)$$$ and moves either left (towards the $$$0$$$) or right with the speed of $$$1$$$ unit per second. No two robots start at the same coordinate.Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed.Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens.For each robot find out if it ever explodes and print the time of explosion if it happens and $$$-1$$$ otherwise.
256 megabytes
//https://github.com/EgorKulikov/yaal/tree/master/lib/main/net/egork import java.util.*; import java.io.*; public class A{ static PrintWriter out; static InputReader in; public static void main(String args[]){ out = new PrintWriter(System.out); in = new InputReader(); new A(); out.flush(); out.close(); } A(){ solve(); } class pair{ int F, S; pair(int a, int b){ F = a; S = b; } } void solve(){ int t = in.nextInt(); while(t-- > 0){ int n = in.nextInt(), m = in.nextInt(); int id[] = new int[n + 1], st[] = new int[n + 1], ans[] = new int[n + 1]; Arrays.fill(ans, -1); ArrayList<pair> all = new ArrayList<>(); for(int i = 1; i <= n; i++){ st[i] = in.nextInt(); all.add(new pair(st[i], i)); } for(int i = 1; i <= n; i++){ id[i] = (in.next().trim().charAt(0) == 'L' ? 0 : 1); } Collections.sort(all, (A, B) -> B.F - A.F); // ArrayDeque<Integer> ad[] = new ArrayDeque[2]; for(int i = 0; i < 2; i++)ad[i] = new ArrayDeque<>(); for(int i = 0; i < n; i++){ pair p = all.get(i); if(id[p.S] == 0){ ad[p.F % 2].addFirst(p.S); }else{ if(ad[p.F % 2].isEmpty()){ }else{ int next = ad[p.F % 2].pollFirst(); ans[p.S] = ans[next] = (st[next] - st[p.S]) / 2; } } } // for(int i = 0; i < 2; i++)ad[i].clear(); for(int i = 0; i < n; i++){ pair p = all.get(i); if(id[p.S] == 0)continue; if(ans[p.S] != -1)continue; if(ad[p.F % 2].isEmpty()){ ad[p.F % 2].addFirst(p.S); }else{ int next = ad[p.F % 2].pollFirst(); ans[p.S] = ans[next] = (2 * m - st[next] - st[p.S]) / 2; } } // for(int i = 0; i < 2; i++)ad[i].clear(); for(int i = n - 1; i >= 0; i--){ pair p = all.get(i); if(id[p.S] == 1)continue; if(ans[p.S] != -1)continue; if(ad[p.F % 2].isEmpty()){ ad[p.F % 2].addFirst(p.S); }else{ int next = ad[p.F % 2].pollFirst(); ans[p.S] = ans[next] = (st[next] + st[p.S]) / 2; } } // for(int i = 0; i < n; i++){ pair p = all.get(i); if(id[p.S] == 0 || ans[p.S] != -1)continue; if(ad[p.F % 2].isEmpty())continue; else{ int next = ad[p.F % 2].pollLast(); ans[p.S] = ans[next] = (m + m - st[p.S] + st[next]) / 2; } } for(int i = 1; i <= n; i++)out.print(ans[i] + " "); out.println(); } } public static class InputReader{ BufferedReader br; StringTokenizer st; InputReader(){ br = new BufferedReader(new InputStreamReader(System.in)); } public int nextInt(){ return Integer.parseInt(next()); } public long nextLong(){ return Long.parseLong(next()); } public double nextDouble(){ return Double.parseDouble(next()); } public String next(){ while(st == null || !st.hasMoreTokens()){ try{ st = new StringTokenizer(br.readLine()); }catch(IOException e){} } return st.nextToken(); } } }
Java
["5\n7 12\n1 2 3 4 9 10 11\nR R L L R R R\n2 10\n1 6\nR R\n2 10\n1 3\nL L\n1 10\n5\nR\n7 8\n6 1 7 2 3 5 4\nR L R L L L L"]
2 seconds
["1 1 1 1 2 -1 2 \n-1 -1 \n2 2 \n-1 \n-1 2 7 3 2 7 3"]
NoteHere is the picture for the seconds $$$0, 1, 2$$$ and $$$3$$$ of the first testcase: Notice that robots $$$2$$$ and $$$3$$$ don't collide because they meet at the same point $$$2.5$$$, which is not integer.After second $$$3$$$ robot $$$6$$$ just drive infinitely because there's no robot to collide with.
Java 8
standard input
[ "data structures", "greedy", "implementation", "sortings" ]
1a28b972e77966453cd8239cc5c8f59a
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5$$$; $$$2 \le m \le 10^8$$$) — the number of robots and the coordinate of the right wall. The second line of each testcase contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$0 &lt; x_i &lt; m$$$) — the starting coordinates of the robots. The third line of each testcase contains $$$n$$$ space-separated characters 'L' or 'R' — the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates $$$x_i$$$ in the testcase are distinct. The sum of $$$n$$$ over all testcases doesn't exceed $$$3 \cdot 10^5$$$.
2,000
For each testcase print $$$n$$$ integers — for the $$$i$$$-th robot output the time it explodes at if it does and $$$-1$$$ otherwise.
standard output
PASSED
bc4f4971f9532341b5c3ac0eacffd7eb
train_110.jsonl
1621152000
You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.
256 megabytes
import java.util.*;import java.io.*;import java.math.*; public class D { static final Random random=new Random(); static boolean memory = true; 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; } ArrayList<Integer> lst = new ArrayList<>(); for(int i : a) lst.add(i); Collections.sort(lst); for(int i = 0; i < n; i++) a[i] = lst.get(i); } static void ruffleSort(long[] a) { int n = a.length; for (int i=0; i<n; i++) { int oi=random.nextInt(n); long temp=a[oi]; a[oi]=a[i]; a[i]=temp; } ArrayList<Long> lst = new ArrayList<>(); for(long i : a) lst.add(i); Collections.sort(lst); for(int i = 0; i < n; i++) a[i] = lst.get(i); } public static void process()throws IOException { int n=ii(); int[] a = iai(n); int[] b = new int[n]; for(int i=0;i<n;i++)b[i]=a[i]; int min = Integer.MAX_VALUE,max=0; ruffleSort(b); boolean f=false; for(int i=0;i<n;i++) { min = Math.min(a[i],min); max = Math.max(a[i],max); if(i!=0 && i!=n-1 && a[i]!=b[i])f=true; } int c=0; for(int i=0;i<n;i++) { if(a[i]==b[i])c++; } if(c==n) { System.out.println(0); return; } if(max==a[0] && min==a[n-1]) { System.out.println(3); return; } if(a[n-1]==n || 1==a[0])System.out.println(1); else System.out.println(2); } static AnotherReader sc; static PrintWriter out; public static void main(String[] args) throws Exception{ if(memory)new Thread(null, new Runnable() {public void run(){try{new D().run();}catch(Exception e){e.printStackTrace();System.exit(1);}}}, "1", 1 << 28).start(); else new D().run(); } static boolean check(long n) { for(int i=2;i*i<=n;i++) { if(n%i==0)return false; } return true; } void run()throws Exception { boolean oj = System.getProperty("ONLINE_JUDGE") != null; if(oj){sc=new AnotherReader();out=new PrintWriter(System.out);} else{sc=new AnotherReader(100);out=new PrintWriter("output.txt");} long s = System.currentTimeMillis(); // List<Long> a = new ArrayList<>(); // for(long i=2;i<=(1e6);i++) { // if(check(i)) { // a.add((long) i); // } // } int t=1; t=ii(); //int k = t; while(t-->0) {/*p("Case #"+ (k-t) + ": ")*/;process();} out.flush(); System.err.println(System.currentTimeMillis()-s+"ms"); out.close(); } static long power(long k, long c, long mod){ long y = 1; while(c > 0){ if(c%2 == 1) y = y * k % mod; c = c/2; k = k * k % mod; } return y; } static int power(int x, int y, int p){ 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 int log2(int N) { int result = (int)(Math.log(N) / Math.log(2)); return result; } static void pn(Object o){out.println(o);} static void p(Object o){out.print(o);} static void pni(Object o){out.println(o);out.flush();} static int ii()throws IOException{return sc.nextInt();} static long ll()throws IOException{return sc.nextLong();} static double nd()throws IOException{return sc.nextDouble();} static String iln()throws IOException{return sc.nextLine();} static int[] iai(int N)throws IOException{int[]A=new int[N];for(int i=0;i!=N;i++){A[i]=ii();}return A;} static long[] ial(int N)throws IOException{long[]A=new long[N];for(int i=0;i!=N;i++){A[i]=ll();}return A;} static long gcd(long a, long b)throws IOException{return (b==0)?a:gcd(b,a%b);} static int gcd(int a, int b)throws IOException{return (b==0)?a:gcd(b,a%b);} static int bit(long n)throws IOException{return (n==0)?0:(1+bit(n&(n-1)));} ///////////////////////////////////////////////////////////////////////////////////////////////////////// static class AnotherReader{BufferedReader br; StringTokenizer st; AnotherReader()throws FileNotFoundException{ br=new BufferedReader(new InputStreamReader(System.in));} AnotherReader(int a)throws FileNotFoundException{ br = new BufferedReader(new FileReader("C:\\Users\\Utkarsh\\OneDrive\\Desktop\\input1.txt"));} String next()throws IOException{ while (st == null || !st.hasMoreElements()) {try{ st = new StringTokenizer(br.readLine());} catch (IOException e){ e.printStackTrace(); }} return st.nextToken(); } int nextInt() throws IOException{ return Integer.parseInt(next());} long nextLong() throws IOException {return Long.parseLong(next());} double nextDouble()throws IOException { return Double.parseDouble(next()); } String nextLine() throws IOException{ String str = ""; try{ str = br.readLine();} catch (IOException e){ e.printStackTrace();} return str;}} ///////////////////////////////////////////////////////////////////////////////////////////////////////////// }
Java
["3\n4\n1 3 2 4\n3\n1 2 3\n5\n2 1 4 5 3"]
2 seconds
["1\n0\n2"]
NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
c212524cc1ad8e0332693e3cf644854b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.
900
For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.
standard output
PASSED
6c4041e4e0437e877b2a19b882c81b37
train_110.jsonl
1621152000
You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.
256 megabytes
import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigInteger; import java.util.* ; import java.io.* ; @SuppressWarnings("unused") //Scanner s = new Scanner(new File("input.txt")); //s.close(); //PrintWriter writer = new PrintWriter("output.txt"); //writer.close(); //BufferedReader in = new BufferedReader(new InputStreamReader(System.in)) ; //Scanner in = new Scanner(System.in) ; //[a-z] = [97-122] ------- [A-Z] = [65-90] /*counting number of bits in an integer : * * int x = (int)(Math.log(num) / Math.log(2)) + 1; */ public class cf { static final int mod = 1000000007 ; static boolean not_prime[] = new boolean[1000001] ; static void sieve() { for(int i=2 ; i*i<1000001 ; i++) { if(not_prime[i]==false) { for(int j=2*i ; j<1000001 ; j+=i) { not_prime[j]=true ; } } }not_prime[0]=true ; not_prime[1]=true ; } public static long bexp(long base , long power) { long res=1L ; //base = base%mod ; while(power>0) { if((power&1)==1) { res=(res*base);//%mod ; power-- ; } else { base=(base*base);//%mod ; power>>=1 ; } } return res ; } static long modInverse(long n, long p) { return power(n, p - 2, p); } static long power(long x, long y, long p) { // Initialize result long res = 1; // Update x if it is more than or // equal to p x = x % p; while (y > 0) { // If y is odd, multiply x // with result if (y % 2 == 1) res = (res * x) % p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return res; } static long nCrModPFermat(int n, int r, long p) { if(n<r) return 0 ; if (r == 0) return 1; long[] fac = new long[n + 1]; fac[0] = 1; for (int i = 1; i <= n; i++) fac[i] = fac[i - 1] * i % p; return (fac[n] * modInverse(fac[r], p) % p * modInverse(fac[n - r], p) % p) % p; } private static long modular_add(long a, long b) { return ((a % mod) + (b % mod)) % mod; } private static long modular_sub(long a, long b) { return ((a % mod) - (b % mod) + mod) % mod; } private static long modular_mult(long a, long b) { return ((a % mod) * (b % mod)) % mod; } static long lcm(int a, int b) { return (a / gcd(a, b)) * b; } private static long gcd(long a, long b) { if (b == 0) { return a; } return gcd(b, a % 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; } } //static HashMap<Integer , ArrayList<Integer>> map = new HashMap<>() ; static boolean vis[] ; public static void main(String[] args)throws IOException//throws FileNotFoundException { FastReader in = new FastReader() ; StringBuilder op = new StringBuilder() ; int t = in.nextInt() ; while(t-->0) { int n = in.nextInt() ; int a[] = new int[n] ; int index=-1 , min=Integer.MAX_VALUE , max=Integer.MIN_VALUE ; for(int i=0 ; i<n ; i++) { a[i] = in.nextInt() ; min=Math.min(a[i], min) ; max=Math.max(a[i], max) ; } for(int i=0 ; i<n-1 ; i++) { if(a[i]>a[i+1]) { index=i ; break ; } } if(index==-1) op.append(0+"\n") ; else if(a[0]==min || a[n-1]==max) op.append(1+"\n") ; else if(a[0]==max && a[n-1]==min) op.append("3\n") ; else if(a[0]!=min && a[n-1]!=max) op.append("2\n") ; } System.out.println(op.toString()); } }
Java
["3\n4\n1 3 2 4\n3\n1 2 3\n5\n2 1 4 5 3"]
2 seconds
["1\n0\n2"]
NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
c212524cc1ad8e0332693e3cf644854b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.
900
For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.
standard output
PASSED
7adfae128623abcdb17f21ac91e769d2
train_110.jsonl
1621152000
You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.
256 megabytes
import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigInteger; import java.util.* ; import java.io.* ; @SuppressWarnings("unused") //Scanner s = new Scanner(new File("input.txt")); //s.close(); //PrintWriter writer = new PrintWriter("output.txt"); //writer.close(); //BufferedReader in = new BufferedReader(new InputStreamReader(System.in)) ; //Scanner in = new Scanner(System.in) ; //[a-z] = [97-122] ------- [A-Z] = [65-90] /*counting number of bits in an integer : * * int x = (int)(Math.log(num) / Math.log(2)) + 1; */ public class cf { static final int mod = 1000000007 ; static boolean not_prime[] = new boolean[1000001] ; static void sieve() { for(int i=2 ; i*i<1000001 ; i++) { if(not_prime[i]==false) { for(int j=2*i ; j<1000001 ; j+=i) { not_prime[j]=true ; } } }not_prime[0]=true ; not_prime[1]=true ; } public static long bexp(long base , long power) { long res=1L ; //base = base%mod ; while(power>0) { if((power&1)==1) { res=(res*base);//%mod ; power-- ; } else { base=(base*base);//%mod ; power>>=1 ; } } return res ; } static long modInverse(long n, long p) { return power(n, p - 2, p); } static long power(long x, long y, long p) { // Initialize result long res = 1; // Update x if it is more than or // equal to p x = x % p; while (y > 0) { // If y is odd, multiply x // with result if (y % 2 == 1) res = (res * x) % p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return res; } static long nCrModPFermat(int n, int r, long p) { if(n<r) return 0 ; if (r == 0) return 1; long[] fac = new long[n + 1]; fac[0] = 1; for (int i = 1; i <= n; i++) fac[i] = fac[i - 1] * i % p; return (fac[n] * modInverse(fac[r], p) % p * modInverse(fac[n - r], p) % p) % p; } private static long modular_add(long a, long b) { return ((a % mod) + (b % mod)) % mod; } private static long modular_sub(long a, long b) { return ((a % mod) - (b % mod) + mod) % mod; } private static long modular_mult(long a, long b) { return ((a % mod) * (b % mod)) % mod; } static long lcm(int a, int b) { return (a / gcd(a, b)) * b; } private static long gcd(long a, long b) { if (b == 0) { return a; } return gcd(b, a % 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; } } //static HashMap<Integer , ArrayList<Integer>> map = new HashMap<>() ; static boolean vis[] ; public static void main(String[] args)throws IOException//throws FileNotFoundException { FastReader in = new FastReader() ; StringBuilder op = new StringBuilder() ; int t = in.nextInt() ; while(t-->0) { int n = in.nextInt() ; int a[] = new int[n] ; int index=-1 , min=Integer.MAX_VALUE , max=Integer.MIN_VALUE ; for(int i=0 ; i<n ; i++) { a[i] = in.nextInt() ; min=Math.min(a[i], min) ; max=Math.max(a[i], max) ; } for(int i=0 ; i<n-1 ; i++) { if(a[i]>a[i+1]) { index=i ; break ; } } // if(index==-1) // op.append(0+"\n") ; // else if(a[0]==max && a[n-1]==min) // op.append(3+"\n") ; // else if((a[0]==max || a[n-1]==min)||(a[0]!=min && a[n-1]!=max)) // op.append(2+"\n") ; // else if(a[0]==min && a[n-1]==max) // op.append(1+"\n") ; // else // op.append(1+"\n") ; if(index==-1) op.append(0+"\n") ; else if((a[0]==min && a[n-1]!=max)||(a[0]!=min && a[n-1]==max)||(a[0]==min && a[n-1]==max)) op.append(1+"\n") ; else if(a[0]==max && a[n-1]==min) op.append("3\n") ; else if(a[0]!=min && a[n-1]!=max) op.append("2\n") ; } System.out.println(op.toString()); } }
Java
["3\n4\n1 3 2 4\n3\n1 2 3\n5\n2 1 4 5 3"]
2 seconds
["1\n0\n2"]
NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
c212524cc1ad8e0332693e3cf644854b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.
900
For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.
standard output
PASSED
f8a34357313a92e5ea4e83468929476e
train_110.jsonl
1621152000
You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.
256 megabytes
import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigInteger; import java.util.* ; import java.io.* ; @SuppressWarnings("unused") //Scanner s = new Scanner(new File("input.txt")); //s.close(); //PrintWriter writer = new PrintWriter("output.txt"); //writer.close(); //BufferedReader in = new BufferedReader(new InputStreamReader(System.in)) ; //Scanner in = new Scanner(System.in) ; //[a-z] = [97-122] ------- [A-Z] = [65-90] /*counting number of bits in an integer : * * int x = (int)(Math.log(num) / Math.log(2)) + 1; */ public class cf { static final int mod = 1000000007 ; static boolean not_prime[] = new boolean[1000001] ; static void sieve() { for(int i=2 ; i*i<1000001 ; i++) { if(not_prime[i]==false) { for(int j=2*i ; j<1000001 ; j+=i) { not_prime[j]=true ; } } }not_prime[0]=true ; not_prime[1]=true ; } public static long bexp(long base , long power) { long res=1L ; //base = base%mod ; while(power>0) { if((power&1)==1) { res=(res*base);//%mod ; power-- ; } else { base=(base*base);//%mod ; power>>=1 ; } } return res ; } static long modInverse(long n, long p) { return power(n, p - 2, p); } static long power(long x, long y, long p) { // Initialize result long res = 1; // Update x if it is more than or // equal to p x = x % p; while (y > 0) { // If y is odd, multiply x // with result if (y % 2 == 1) res = (res * x) % p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return res; } static long nCrModPFermat(int n, int r, long p) { if(n<r) return 0 ; if (r == 0) return 1; long[] fac = new long[n + 1]; fac[0] = 1; for (int i = 1; i <= n; i++) fac[i] = fac[i - 1] * i % p; return (fac[n] * modInverse(fac[r], p) % p * modInverse(fac[n - r], p) % p) % p; } private static long modular_add(long a, long b) { return ((a % mod) + (b % mod)) % mod; } private static long modular_sub(long a, long b) { return ((a % mod) - (b % mod) + mod) % mod; } private static long modular_mult(long a, long b) { return ((a % mod) * (b % mod)) % mod; } static long lcm(int a, int b) { return (a / gcd(a, b)) * b; } private static long gcd(long a, long b) { if (b == 0) { return a; } return gcd(b, a % 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; } } //static HashMap<Integer , ArrayList<Integer>> map = new HashMap<>() ; static boolean vis[] ; public static void main(String[] args)throws IOException//throws FileNotFoundException { FastReader in = new FastReader() ; StringBuilder op = new StringBuilder() ; int t = in.nextInt() ; while(t-->0) { int n = in.nextInt() ; int a[] = new int[n] ; int index=-1 , min=Integer.MAX_VALUE , max=Integer.MIN_VALUE ; for(int i=0 ; i<n ; i++) { a[i] = in.nextInt() ; min=Math.min(a[i], min) ; max=Math.max(a[i], max) ; } for(int i=0 ; i<n-1 ; i++) { if(a[i]>a[i+1]) { index=i ; break ; } } if(index==-1) op.append(0+"\n") ; else if(a[0]==max && a[n-1]==min) op.append(3+"\n") ; else if((a[0]==max || a[n-1]==min)||(a[0]!=min && a[n-1]!=max)) op.append(2+"\n") ; else if(a[0]==min && a[n-1]==max) op.append(1+"\n") ; else op.append(1+"\n") ; } System.out.println(op.toString()); } }
Java
["3\n4\n1 3 2 4\n3\n1 2 3\n5\n2 1 4 5 3"]
2 seconds
["1\n0\n2"]
NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
c212524cc1ad8e0332693e3cf644854b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.
900
For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.
standard output
PASSED
3fbb0f0f986c1a036e5a26efe83b2741
train_110.jsonl
1621152000
You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.
256 megabytes
import java.io.*; import java.util.*; public class B { public static void main(String args[]){ FScanner in = new FScanner(); PrintWriter out = new PrintWriter(System.out); int t = in.nextInt(); while(t-->0) { int n=in.nextInt(); int arr[]=in.readArray(n); int copy[]=new int[n]; int c=0; for(int i=0;i<n;i++) copy[i]=arr[i]; Arrays.sort(copy); for(int i=0;i<n;i++) { if(copy[i]!=arr[i]) c++; } if(c==0) out.println(0); else if(arr[0]==1||arr[n-1]==n) out.println(1); else if(arr[n-1]==1&&arr[0]==n) out.println(3); else out.println(2); } out.close(); } static boolean checkprime(int n1) { if(n1%2==0||n1%3==0) return false; else { for(int i=5;i*i<=n1;i+=6) { if(n1%i==0||n1%(i+2)==0) return false; } return true; } } static class FScanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer sb = new StringTokenizer(""); String next(){ while(!sb.hasMoreTokens()){ try{ sb = new StringTokenizer(br.readLine()); } catch(IOException e){ } } return sb.nextToken(); } String nextLine(){ try{ return br.readLine(); } catch(IOException e) { } return ""; } int nextInt(){ return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } int[] readArray(int n) { int a[] = new int[n]; for(int i=0;i<n;i++) a[i] = nextInt(); return a; } float nextFloat(){ return Float.parseFloat(next()); } double nextDouble(){ return Double.parseDouble(next()); } } }
Java
["3\n4\n1 3 2 4\n3\n1 2 3\n5\n2 1 4 5 3"]
2 seconds
["1\n0\n2"]
NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
c212524cc1ad8e0332693e3cf644854b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.
900
For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.
standard output
PASSED
bd3e8b515e139be36e6ca2d6327d5f73
train_110.jsonl
1621152000
You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.
256 megabytes
import java.util.Arrays; import java.util.Scanner; public class hw11 { public static void main(String[] args) { Scanner scan = new Scanner(System.in); //problem 1 //permutation sort 1525B { int t = scan.nextInt(); for (int i = 0; i < t; i++) { int n = scan.nextInt(); int[] a = new int[n+1]; for (int j = 1; j <= n; j++) { a[j] = scan.nextInt(); } int[] sort= Arrays.copyOf(a,n+1); Arrays.sort(sort); if(Arrays.equals(a, sort)) { System.out.println(0); } else if(a[1]==1||a[n]==n) { System.out.println(1); } else if(a[1]==n&&a[n]==1) { System.out.println(3); } else{ System.out.println(2); } } } } }
Java
["3\n4\n1 3 2 4\n3\n1 2 3\n5\n2 1 4 5 3"]
2 seconds
["1\n0\n2"]
NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
c212524cc1ad8e0332693e3cf644854b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.
900
For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.
standard output
PASSED
e901d3b089836f1f39746a462c16ee23
train_110.jsonl
1621152000
You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.
256 megabytes
import java.util.Scanner; public class Problem1525B { public static Scanner scanner = new Scanner(System.in); public static void main(String[] args) { int tc = scanner.nextInt(); while (tc-->0){ int size = scanner.nextInt(); int [] array = new int[size]; for (int i =0;i< array.length;i++){ array[i] = scanner.nextInt(); } int count =0; for (int i =0 ;i< array.length;i++){ if (array[i] == i+1){ count++; } } if (count== array.length){ System.out.println(0); continue; } if (array[0]==1 || array[size-1]==size){ System.out.println(1); }else if (array[0]==size && array[size-1]==1){ System.out.println(3); }else System.out.println(2); } } }
Java
["3\n4\n1 3 2 4\n3\n1 2 3\n5\n2 1 4 5 3"]
2 seconds
["1\n0\n2"]
NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
c212524cc1ad8e0332693e3cf644854b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.
900
For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.
standard output
PASSED
f7f7c88ea387fc47762d97f2886bd895
train_110.jsonl
1621152000
You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.
256 megabytes
import java.util.Scanner; public class PermutationSort { static boolean checkSorted(int[] a){ for(int i = 0; i < a.length-1; i++) { if (a[i] > a[i + 1]) { return false; } } return true; } public static void main(String[] args) { int t; Scanner s = new Scanner(System.in); t = s.nextInt(); while (t>0){ int n; n = s.nextInt(); int[] a = new int[n]; for(int i=0; i<n; i++){ a[i] = s.nextInt(); } if(checkSorted(a)){ System.out.println(0); }else if(a[0]==1 || a[n-1]==n){ System.out.println(1); }else if(a[0]!=n || a[n-1]!=1){ System.out.println(2); }else { System.out.println(3); } t--; } } }
Java
["3\n4\n1 3 2 4\n3\n1 2 3\n5\n2 1 4 5 3"]
2 seconds
["1\n0\n2"]
NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
c212524cc1ad8e0332693e3cf644854b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.
900
For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.
standard output
PASSED
21ef421cc8d0c02b7ab215c7137c9ab3
train_110.jsonl
1621152000
You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.
256 megabytes
import java.util.*; import static java.lang.Math.*; import java.io.*; public class Exercise { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); int testcases = sc.nextInt(); while(testcases-- != 0) { int length = sc.nextInt(); int sort[] = new int[length]; int result = 0; int min = sc.nextInt(); sort[0] = min; int idx = 0; int max = min; int maxidx = 0; for(int i = 1; i < length; i++) { int number = sc.nextInt(); sort[i] = number; if(number < min) { min = number; idx = i; } if(number > max) { max = number; maxidx = i; } } boolean sorted = true; for(int i = 0; i < length - 1; i++) { if(sort[i] > sort[i + 1]) { sorted = false; break; } } if(sorted) { System.out.println(0); } else { if(sort[0] == 1 || sort[length - 1] == length) { System.out.println(1); } else if (sort[0] == length && sort[length - 1] == 1) { System.out.println(3); } else { System.out.println(2); } } } } }
Java
["3\n4\n1 3 2 4\n3\n1 2 3\n5\n2 1 4 5 3"]
2 seconds
["1\n0\n2"]
NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
c212524cc1ad8e0332693e3cf644854b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.
900
For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.
standard output
PASSED
aeb41cde2470c80b9def1ec64acf0684
train_110.jsonl
1621152000
You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.
256 megabytes
import java.util.*; public class Main { public static void main(String[] args){ Scanner in = new Scanner(System.in); int t = in.nextInt(); while(t-->0){ int n = in.nextInt(); int a[] = new int[n]; boolean flag = true; for(int i = 0; i < n; i++){ a[i] = in.nextInt(); if(a[i] != i+1){ flag = false; } } if(flag){ System.out.println(0); } else{ if(a[0] == 1 || a[n-1] == n){ System.out.println(1); } else if(a[0] == n && a[n-1] == 1){ System.out.println(3); } else System.out.println(2); } } } }
Java
["3\n4\n1 3 2 4\n3\n1 2 3\n5\n2 1 4 5 3"]
2 seconds
["1\n0\n2"]
NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
c212524cc1ad8e0332693e3cf644854b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.
900
For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.
standard output
PASSED
5e66899d9a768794913d18db93f10e0b
train_110.jsonl
1621152000
You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.
256 megabytes
import java.util.Scanner; public class permutationSort { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int testCase = sc.nextInt(); for( int i =0 ;i < testCase ; i++){ boolean oneSorted = false; boolean completeSorted = true; boolean reverseSorted = false; int size= sc.nextInt(); int[] arr= new int[size]; for( int j=0; j < size;j++){ int val = sc.nextInt(); arr[j]=val; } if(arr[0] == 1 || arr[size-1] ==size){ oneSorted=true; } if(arr[0] == size && arr[size-1] ==1){ reverseSorted=true; } for(int k =0; k < size-1 ; k ++){ if(arr[k+1]<arr[k]){ completeSorted =false; break; } } if(completeSorted){ System.out.println(0); }else if(reverseSorted){ System.out.println(3); }else if(oneSorted){ System.out.println(1); }else{ System.out.println(2); } } } }
Java
["3\n4\n1 3 2 4\n3\n1 2 3\n5\n2 1 4 5 3"]
2 seconds
["1\n0\n2"]
NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
c212524cc1ad8e0332693e3cf644854b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.
900
For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.
standard output
PASSED
b82690a8281b828e8e1f1e164491e5f6
train_110.jsonl
1621152000
You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.
256 megabytes
import java.io.*; import java.lang.*; import java.util.*; public class Main{ public static void main(String [] args){ Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while (t-->0){ int n = sc.nextInt(); int ar[] = new int [n]; int k =0; for (int i = 0; i<n; i++){ ar[i] = sc.nextInt(); if (i!=0 && ar[i]<ar[i-1]){ k=1; } } if (k == 0) System.out.println("0"); else if (ar[0] == n && ar[n-1] == 1) System.out.println("3"); else if(ar[0] == 1 || ar[n-1] == n) System.out.println("1"); else System.out.println("2"); } } }
Java
["3\n4\n1 3 2 4\n3\n1 2 3\n5\n2 1 4 5 3"]
2 seconds
["1\n0\n2"]
NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
c212524cc1ad8e0332693e3cf644854b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.
900
For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.
standard output
PASSED
93b98eb8915cdb61bcc1aef0571f8dae
train_110.jsonl
1621152000
You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.
256 megabytes
//package com.nt.practice; import java.util.Scanner; public class Interface_Test { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int t=sc.nextInt(); for(int T=0;T<t;T++) { int n=sc.nextInt(); int[] a=new int[n]; for(int i=0;i<n;i++) { a[i]=sc.nextInt(); } int count=0; for(int i=1;i<=n;i++) { if(a[i-1]==i) continue; else { count++; } } if(count==0) { System.out.println(0); } else if(a[0]==n && a[n-1]==1) { System.out.println(3); } else { if(a[0]==1 || a[n-1]==n) { System.out.println(1); } else System.out.println(2); } } } }
Java
["3\n4\n1 3 2 4\n3\n1 2 3\n5\n2 1 4 5 3"]
2 seconds
["1\n0\n2"]
NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
c212524cc1ad8e0332693e3cf644854b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.
900
For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.
standard output
PASSED
cf22b74536bfe45532190929864e49c1
train_110.jsonl
1621152000
You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; public class Stack2 { static class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } static Reader sc = new Reader(); static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); public static void main(String[] args) throws IOException { /* * For integer input: int n=inputInt(); * For long input: long n=inputLong(); * For double input: double n=inputDouble(); * For String input: String s=inputString(); * Logic goes here * For printing without space: print(a+""); where a is a variable of any datatype * For printing with space: printSp(a+""); where a is a variable of any datatype * For printing with new line: println(a+""); where a is a variable of any datatype */ Scanner sc = new Scanner(System.in); int t = sc.nextInt(); for (int i = 0; i < t; i++) { int n = sc.nextInt(); int[] ar = new int[n + 1]; boolean check=false; for (int j = 1; j <= n; j++) { ar[j] = sc.nextInt(); if(j!=ar[j]){ check=true; } } if(!check){ System.out.println(0); }else { if(ar[1]==1 && ar[n]!=n){ System.out.println(1); }else if(ar[1]!=1 && ar[n]==n){ System.out.println(1); }else if(ar[1]==1 && ar[n]==n){ System.out.println(1); }else if(ar[1]==n && ar[n]==1){ System.out.println(3); }else { System.out.println(2); } } } bw.flush(); bw.close(); } public static long getAns(int i, int[] ar, long[] dp, int lastnumber, int lastindex) { if (i < 0) { return 0; } /*if(dp[i]!=-1){ return dp[i]; }*/ if (lastnumber > ar[i] && lastindex % (i + 1) == 0) { return 1 + getAns((i) / 2, ar, dp, ar[i], i + 1); } else { return getAns(i - 1, ar, dp, lastnumber, lastindex); // return dp[i]; } } public static void bfs(int r, int c, Queue<int[]> queue, long[][] dis, char[][] map, boolean[][] visited) { while (!queue.isEmpty()) { int[] ar = queue.poll(); int x = ar[0]; int y = ar[1]; if (x + 1 < r) { if (map[x + 1][y] != 'T' && dis[x + 1][y] > (dis[x][y] + 1)) { dis[x + 1][y] = Math.min(dis[x + 1][y], (dis[x][y] + 1)); queue.add(new int[]{x + 1, y}); } /*else if (map[x][y] != map[x + 1][y] && dis[x + 1][y] > (dis[x][y] + 1)) { dis[x + 1][y] = Math.min(dis[x + 1][y], dis[x][y] + 1); queue.add(new int[]{x + 1, y}); }*/ /* if(!visited[x+1][y] ){ queue.add(new int[]{x + 1, y}); visited[x+1][y]=true; }*/ } if (y + 1 < c) { if (map[x][y + 1] != 'T' && dis[x][y + 1] > (dis[x][y] + 1)) { dis[x][y + 1] = Math.min(dis[x][y + 1], dis[x][y] + 1); queue.add(new int[]{x, y + 1}); } /*else if (map[x][y] != map[x][y + 1] && dis[x][y + 1] > (dis[x][y] + 1)) { dis[x][y + 1] = Math.min(dis[x][y + 1], dis[x][y] + 1); queue.add(new int[]{x, y + 1}); }*/ /* if( !visited[x][y+1]){ queue.add(new int[]{x, y+1}); visited[x][y+1]=true; }*/ } if (x - 1 >= 0) { if (map[x - 1][y] != 'T' && dis[x - 1][y] > (dis[x][y] + 1)) { dis[x - 1][y] = Math.min(dis[x - 1][y], (dis[x][y] + 1)); queue.add(new int[]{x - 1, y}); } /*else if (map[x][y] != map[x - 1][y] && dis[x - 1][y] > (dis[x][y] + 1)) { dis[x - 1][y] = Math.min(dis[x - 1][y], dis[x][y] + 1); queue.add(new int[]{x - 1, y}); }*/ /* if(!visited[x-1][y]){ queue.add(new int[]{x - 1, y}); visited[x-1][y]=true; }*/ } if (y - 1 >= 0) { if (map[x][y - 1] != 'T' && dis[x][y - 1] > (dis[x][y] + 1)) { dis[x][y - 1] = Math.min(dis[x][y - 1], (dis[x][y] + 1)); queue.add(new int[]{x, y - 1}); } /*else if (map[x][y] != map[x][y - 1] && dis[x][y - 1] > (dis[x][y] + 1)) { dis[x][y - 1] = Math.min(dis[x][y - 1], dis[x][y] + 1); queue.add(new int[]{x, y - 1}); }*/ /* if(!visited[x][y-1]){ queue.add(new int[]{x , y-1}); visited[x][y-1]=true; }*/ } } } public static void dfs1(List<List<Integer>> g, boolean[] visited, Stack<Integer> stack, int num) { visited[num] = true; for (Integer integer : g.get(num)) { if (!visited[integer]) { dfs1(g, visited, stack, integer); } } stack.push(num); } public static void dfs2(List<List<Integer>> g, boolean[] visited, List<Integer> list, int num, int c, int[] raj) { visited[num] = true; for (Integer integer : g.get(num)) { if (!visited[integer]) { dfs2(g, visited, list, integer, c, raj); } } raj[num] = c; list.add(num); } public static int inputInt() throws IOException { return sc.nextInt(); } public static long inputLong() throws IOException { return sc.nextLong(); } public static double inputDouble() throws IOException { return sc.nextDouble(); } public static String inputString() throws IOException { return sc.readLine(); } public static void print(String a) throws IOException { bw.write(a); } public static void printSp(String a) throws IOException { bw.write(a + " "); } public static void println(String a) throws IOException { bw.write(a + "\n"); } public static long getAns(int[] ar, int c, long[][] dp, int i, int sign) { if (i < 0) { return 1; } if (c <= 0) { return 1; } dp[i][c] = Math.max(dp[i][c], Math.max(ar[i] * getAns(ar, c - 1, dp, i - 1, sign), getAns(ar, c, dp, i - 1, 1))); return dp[i][c]; } public static long power(long a, long b, long c) { long ans = 1; while (b != 0) { if (b % 2 == 1) { ans = ans * a; ans %= c; } a = a * a; a %= c; b /= 2; } return ans; } public static long power1(long a, long b, long c) { long ans = 1; while (b != 0) { if (b % 2 == 1) { ans = multiply(ans, a, c); } a = multiply(a, a, c); b /= 2; } return ans; } public static long multiply(long a, long b, long c) { long res = 0; a %= c; while (b > 0) { if (b % 2 == 1) { res = (res + a) % c; } a = (a + a) % c; b /= 2; } return res % c; } public static long totient(long n) { long result = n; for (long i = 2; i * i <= n; i++) { if (n % i == 0) { //sum=sum+2*i; while (n % i == 0) { n /= i; // sum=sum+n; } result -= result / i; } } if (n > 1) { result -= result / n; } return result; } public static long gcd(long a, long b) { if (b == 0) { return a; } else { return gcd(b, a % b); } } public static boolean[] primes(int n) { boolean[] p = new boolean[n + 1]; p[0] = false; p[1] = false; for (int i = 2; i <= n; i++) { p[i] = true; } for (int i = 2; i * i <= n; i++) { if (p[i]) { for (int j = i * i; j <= n; j += i) { p[j] = false; } } } return p; } static void bogoSort(int[] a, int c) { // if array is not sorted then shuffle the // array again while (isSorted(a) == false) { c++; shuffle(a); } } // To generate permuatation of the array static void shuffle(int[] a) { // Math.random() returns a double positive // value, greater than or equal to 0.0 and // less than 1.0. for (int i = 1; i <= a.length; i++) swap(a, i, (int) (Math.random() * i)); } // Swapping 2 elements static void swap(int[] a, int i, int j) { int temp = a[i]; a[i] = a[j]; a[j] = temp; } // To check if array is sorted or not static boolean isSorted(int[] a) { for (int i = 1; i < a.length; i++) if (a[i] < a[i - 1]) return false; return true; } }
Java
["3\n4\n1 3 2 4\n3\n1 2 3\n5\n2 1 4 5 3"]
2 seconds
["1\n0\n2"]
NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
c212524cc1ad8e0332693e3cf644854b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.
900
For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.
standard output
PASSED
3d926a1bd8b07654420df046837934ef
train_110.jsonl
1621152000
You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.
256 megabytes
import java.lang.*; import java.util.*; import java.io.*; import java.math.BigInteger; public class Main { final static int mod = (int)(1e9 + 7); public static void main(String[] args) { FastReader fs = new FastReader(); int testcase = 1; testcase = fs.nextInt(); while (testcase-- > 0) { solve(fs); } } public static void solve(FastReader fs) { int n = fs.nextInt(); int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = fs.nextInt(); } long ans = 0; for (int i = 0; i < n - 1; i++) { if (a[i] > a[i + 1]) { ans++; } } if (ans == 0) { System.out.println(ans); return; } if (a[0] == 1 && a[n - 1] == n) { System.out.println(1); return; } if (a[0] == n && a[n - 1] == 1) { System.out.println(3); return; } if (a[0] == 1 && a[n - 1] != n) { System.out.println(1); return ; } if (a[0] != n && a[n - 1] == 1) { System.out.println(2); return; } if (a[0] == n && a[n - 1] != 1) { System.out.println(2); return; } if (a[0] != 1 && a[n - 1] == n) { System.out.println(1); return; } if (a[0] != n && a[0] != 1 && a[n - 1] != 1 && a[n - 1] != n) { System.out.println(2); return; } System.out.println("lol"); } //IO operation static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader( new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["3\n4\n1 3 2 4\n3\n1 2 3\n5\n2 1 4 5 3"]
2 seconds
["1\n0\n2"]
NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
c212524cc1ad8e0332693e3cf644854b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.
900
For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.
standard output
PASSED
ce8d21bc38eedee95a045221f1debfae
train_110.jsonl
1621152000
You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.
256 megabytes
import java.util.*; public class PermutationSort { 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+1]; int c=0; for(int i=1;i<=n;i++) { a[i]=sc.nextInt(); if(a[i]!=i) { c++; } } if(c==0) { System.out.println(c); } else if(a[1]==1 || a[n]==n){ System.out.println(1); } else if(a[1]==n && a[n]==1) { System.out.println(3); } else if(a[1]!=1 && a[n]!=n) { System.out.println(2); } t--; } } }
Java
["3\n4\n1 3 2 4\n3\n1 2 3\n5\n2 1 4 5 3"]
2 seconds
["1\n0\n2"]
NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
c212524cc1ad8e0332693e3cf644854b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.
900
For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.
standard output
PASSED
be531b8e583fc5648d03e0f087b76a00
train_110.jsonl
1621152000
You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.
256 megabytes
//package kriti; import java.math.*; import java.io.*; import java.util.*; public class A { static PrintWriter out = new PrintWriter(System.out); static StringBuilder ans=new StringBuilder(); static FastReader in=new FastReader(); public static void main(String args[])throws IOException { int t =i(); outer:while(t-->0) { int n = i(); int[] A = input(n); int[] B = new int[n]; for(int i=0;i<n;i++) { B[i]=A[i]; } int cnt=0; Arrays.sort(A); for(int i=0;i<n;i++) { if(A[i]!=B[i]) { cnt++; } } if(B[n-1]==1 && B[0]==n) { out.println(3); } else if(cnt==0) { out.println(0); } else if(B[n-1]==n || B[0]==1) { out.println(1); } else { out.println(2); } } out.close(); } static String ChartoString(char[] x) { String ans=""; for(char i:x) { ans+=i; } return ans; } static boolean check(int[] B, int idx , int k) { for(int i=0;i<idx;i++) { if(B[i]>k) { return true; } } return false; } static int HCF(int num1, int num2) { int temp1 = num1; int temp2 = num2; while(temp2 != 0){ int temp = temp2; temp2 = temp1%temp2; temp1 = temp; } int hcf = temp1; return hcf; } static boolean palindrome(String s) { char[] x = s.toCharArray(); int i=0; int r= x.length-1; while(i<r) { if(x[i]!=x[r]) { return false; } i++; r--; } return true; } static void sorting(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 boolean equal(int[] A) { int cnt=1;int prev=A[0]; for(int i=1;i<A.length;i++) { if(A[i]==prev)cnt++; } if(cnt==A.length)return true; return false; } static int findGcd(int x, int y) { if (x == 0) return y; return findGcd(y % x, x); } static int findLcm(int x, int y) { return (x / findGcd(x, y)) * y; } public static int checkTriangle(long a, long b, long c) { if (a + b <= c || a + c <= b || b + c <= a) return 0; else return 1; } static boolean isSorted(long A[]) { for(int i=1; i<A.length; i++)if(A[i]<A[i-1])return false; return true; } static int kadane(int A[]) { int lsum=A[0],gsum=A[0]; for(int i=1; i<A.length; i++) { lsum=Math.max(lsum+A[i],A[i]); gsum=Math.max(gsum,lsum); } return gsum; } 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(ArrayList<Long> A) { for(long a:A)System.out.print(a); System.out.println(); } 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 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 int i() { return in.nextInt(); } static long l() { return in.nextLong(); } static String S() { return in.next(); } 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 FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br=new BufferedReader(new InputStreamReader(System.in)); } String next() { while(st==null || !st.hasMoreElements()) { try { st=new StringTokenizer(br.readLine()); } catch(IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str=""; try { str=br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } }
Java
["3\n4\n1 3 2 4\n3\n1 2 3\n5\n2 1 4 5 3"]
2 seconds
["1\n0\n2"]
NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
c212524cc1ad8e0332693e3cf644854b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.
900
For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.
standard output
PASSED
0c843cde828a4578c1d43c1552683f94
train_110.jsonl
1621152000
You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.
256 megabytes
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); for (int i = 0; i < t; i++) { int n = sc.nextInt(); int[] arr = new int[n]; int sum = 0; for (int j = 0; j < n; j++) { arr[j] = sc.nextInt(); if (j != 0 && arr[j] == arr[j - 1] + 1) { sum++; } } if (sum == n - 1) { System.out.println(0); } else if (arr[0] == 1 || arr[n - 1] == n) { System.out.println(1); } else if (arr[n - 1] == 1 && arr[0] == n) { System.out.println(3); } else { System.out.println(2); } } } }
Java
["3\n4\n1 3 2 4\n3\n1 2 3\n5\n2 1 4 5 3"]
2 seconds
["1\n0\n2"]
NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
c212524cc1ad8e0332693e3cf644854b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.
900
For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.
standard output
PASSED
d8d8bd9f9ec077282d879ff10b91975e
train_110.jsonl
1621152000
You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.
256 megabytes
import java.util.Arrays; import java.math.*; import java.util.Scanner; public class ForTesting { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int test=sc.nextInt(); while(test>0) { int n=sc.nextInt(); int arr[]=new int[n]; for(int i=0; i<n; i++) arr[i]=sc.nextInt(); boolean sorted=true; for(int i=0; i<n-1; i++) { if(arr[i+1]!=arr[i]+1) { sorted=false; break; } } if(sorted==true) System.out.println(0); else if(arr[0]==1 || arr[n-1]==n) System.out.println(1); else if(arr[0]==n && arr[n-1]==1) System.out.println(3); else System.out.println(2); test--; } } }
Java
["3\n4\n1 3 2 4\n3\n1 2 3\n5\n2 1 4 5 3"]
2 seconds
["1\n0\n2"]
NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
c212524cc1ad8e0332693e3cf644854b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.
900
For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.
standard output
PASSED
c5668b064d6cfad66dbef9df8d470129
train_110.jsonl
1621152000
You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.
256 megabytes
import java.util.*; import java.math.*; public class PermutationSort { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int runs = sc.nextInt(); while(runs-->0) { int size = sc.nextInt(); int[] arr = new int[size]; int out = 0; boolean sorted = true; for(int i = 0;i<size;i++) { arr[i] = sc.nextInt(); if(i!=0&&arr[i]<arr[i-1]&&out==0) sorted = false; } if(sorted) System.out.println(0); else { if(arr[0]==1||arr[size-1]==size) System.out.println(1); else if(arr[0]!=size||arr[size-1]!=1) { System.out.println(2); } else System.out.println(3); } } } }
Java
["3\n4\n1 3 2 4\n3\n1 2 3\n5\n2 1 4 5 3"]
2 seconds
["1\n0\n2"]
NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
c212524cc1ad8e0332693e3cf644854b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.
900
For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.
standard output
PASSED
629b31a567dbd20caafc2ec42e395a74
train_110.jsonl
1621152000
You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.
256 megabytes
import java.util.*; public class New{ public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while(t-->0){ int n =sc.nextInt(); int arr[] = new int[n]; for(int i=0;i<n;i++) arr[i] = sc.nextInt(); if(isSorted(arr,n)){ System.out.println(0); } else if(arr[n-1]==n) System.out.println(1); else if(arr[0]==1) System.out.println(1); else if(arr[0]==n && arr[n-1]==1) System.out.println(3); else System.out.println(2); } } public static boolean isSorted(int arr[],int n){ for(int i=0;i<n;i++){ if(arr[i]!= i+1) return false; } return true; } }
Java
["3\n4\n1 3 2 4\n3\n1 2 3\n5\n2 1 4 5 3"]
2 seconds
["1\n0\n2"]
NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
c212524cc1ad8e0332693e3cf644854b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.
900
For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.
standard output
PASSED
11c9495d322fc6bc66f829e75d3ad399
train_110.jsonl
1621152000
You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.
256 megabytes
//WHEN IN DOUBT , USE BRUTE FORCE !!!!!!!!! import java.io.*; import java.util.*; //class Main //AtCoder //class Solution // Codechef public class Solution2 //Codeforces { public static void main(String args[]) { try { FastReader sc = new FastReader(); int TT = sc.nextInt(); for(int hehe=1 ; hehe <= TT ; hehe++) { int N=sc.nextInt(); int arr[]=new int[N]; int ar[]=new int[N]; int min=Integer.MAX_VALUE,max=Integer.MIN_VALUE; for(int i=0;i<N;i++) { arr[i] = sc.nextInt(); min=Math.min(arr[i],min); max=Math.max(arr[i],max); ar[i]=arr[i]; } //int ar[]=arr; ruffleSort(ar); if(Arrays.equals(ar,arr)){ sopln(0); } else { if (arr[0] == min || arr[N - 1] == max) { sopln(1); } else if(check(arr,max,min)){ sopln(2); } else { sopln(3); } } out.flush(); } }catch(Exception e){ sopln(e.toString()); } } private static boolean check(int[] arr, int max, int min) { boolean isMax=false,isMin=false; for(int i=0;i<arr.length-1;i++){ if(arr[i]==max){ isMax=true; } if(arr[i]==min){ isMin=true; } } if(isMax&&isMin)return true; isMax=false;isMin=false; for(int i=1;i<arr.length;i++){ if(arr[i]==max){ isMax=true; } if(arr[i]==min){ isMin=true; } } return isMax&&isMin; } static void ruffleSort(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 void ruffleSortRev(int[] a) { ArrayList<Integer> l=new ArrayList<>(); for (int i:a) l.add(i); Collections.sort(l);Collections.reverse(l); for (int i=0; i<a.length; i++) a[i]=l.get(i); } static int power(int x, int y, int p) { // Initialize result int res = 1; // Update x if it is more than or // equal to p x = x % p; while (y > 0) { // If y is odd, multiply x // with result if (y % 2 == 1) res = (res * x) % p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return res; } // Returns n^(-1) mod p static int modInverse(int n, int p) { return power(n, p - 2, p); } // Returns nCr % p using Fermat's // little theorem. static int nCrModPFermat(int n, int r, int p) { if (n<r) return 0; // Base case if (r == 0) return 1; // Fill factorial array so that we // can find all factorial of r, n // and n-r int[] fac = new int[n + 1]; fac[0] = 1; for (int i = 1; i <= n; i++) fac[i] = fac[i - 1] * i % p; return (fac[n] * modInverse(fac[r], p) % p * modInverse(fac[n - r], p) % p) % p; } static boolean isPrime(long n) { // Check if number is less than // equal to 1 if (n <= 1) return false; // Check if number is 2 else if (n == 2) return true; // Check if n is a multiple of 2 else if (n % 2 == 0) return false; // If not, then just check the odds for (int i = 3; i <= Math.sqrt(n); i += 2) { if (n % i == 0) return false; } return true; } static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } static long countDig(long N){ if(N < 10) return 1; else return 1+countDig(N/10); } private static boolean check(long[] arr) { for(int i=0;i<arr.length;i++){ if(arr[i]!=0) return false; } return true; } public final static int d = 256; static int MOD = 1000000007; static final double PI = Math.PI; private static BufferedReader in = new BufferedReader (new InputStreamReader (System.in)); private static PrintWriter out = new PrintWriter (new OutputStreamWriter (System.out)); 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()); } char nextChar() { try { return (char) (br.read()); }catch (IOException e){ return '~'; } } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } static void sop(Object o){System.out.print(o);} static double ceil(double d){ return Math.ceil(d); } static double floor(double d){ return Math.floor(d); } static double round(double d){ return Math.round(d); } static void sopln(Object o){System.out.println(o);} static void printArray(int[] arr){ for(int i=0;i<arr.length;i++){ sop(arr[i]+" "); } sopln(""); } static void printArray(Long[] arr){ for(int i=0;i<arr.length;i++){ sop(arr[i]+" "); } sopln(""); } static long power(long x, long y, long p) { // Initialize result long res = 1; // Update x if it is more than or // equal to p x = x % p; while (y > 0) { // If y is odd, multiply x // with result if (y % 2 == 1) res = (res * x) % p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return res; } // Returns n^(-1) mod p static long modInverse(long n, int p) { return power(n, p - 2, p); } // Returns nCr % p using Fermat's // little theorem. /// // Function to find modular // inverse of a under modulo p // using Fermat's method. // Assumption: p is prime static long modFact(int n, int p) { if (n >= p) return 0; long result = 1; for (int i = 1; i <= n; i++) result = (result * i) % p; return result; } }
Java
["3\n4\n1 3 2 4\n3\n1 2 3\n5\n2 1 4 5 3"]
2 seconds
["1\n0\n2"]
NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
c212524cc1ad8e0332693e3cf644854b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.
900
For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.
standard output
PASSED
9723f56547610af292e1189cc19e635b
train_110.jsonl
1621152000
You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.
256 megabytes
import java.util.*; import java.io.*; //import java.math.*; public class Task{ // ..............code begins here.............. static long mod=(long)1e9+7,inf=(long)1e17; static void solve() throws IOException { int n=int_v(read()); int[] a=int_arr(); int[] b=a.clone(); sort(b); boolean ok=true; int idx=0; for(int i=0;i<n;i++){ if(a[i]!=b[i])ok=false; if(a[i]==1)idx=i; } if(ok){out.write("0\n");return;} if(a[0]==1||a[n-1]==n){out.write("1\n");return;} if(idx==n-1){ if(a[0]!=n)out.write("2\n"); else out.write("3\n"); return; } out.write("2\n"); } // public static void main(String[] args) throws IOException{ assign(); int t=int_v(read()),cn=1; while(t--!=0){ //out.write("Case #"+cn+": "); solve(); //cn++; } out.flush(); } // taking inputs static BufferedReader s1; static BufferedWriter out; static String read() throws IOException{String line="";while(line.length()==0){line=s1.readLine();continue;}return line;} static int int_v (String s1){return Integer.parseInt(s1);} static long long_v(String s1){return Long.parseLong(s1);} static void sort(int[] a){List<Integer> l=new ArrayList<>();for(int x:a){l.add(x);}Collections.sort(l);for(int i=0;i<a.length;i++){a[i]=l.get(i);}} static int[] int_arr() throws IOException{String[] a=read().split(" ");int[] b=new int[a.length];for(int i=0;i<a.length;i++){b[i]=int_v(a[i]);}return b;} static long[] long_arr() throws IOException{String[] a=read().split(" ");long[] b=new long[a.length];for(int i=0;i<a.length;i++){b[i]=long_v(a[i]);}return b;} static void assign(){s1=new BufferedReader(new InputStreamReader(System.in));out=new BufferedWriter(new OutputStreamWriter(System.out));} //static String setpreciosion(double d,int k){BigDecimal d1 = new BigDecimal(Double.toString(d));return d1.setScale(k,RoundingMode.HALF_UP).toString();}//UP DOWN HALF_UP static int add(int a,int b){int z=a+b;if(z>=mod)z-=mod;return z;} static long gcd(long a,long b){if(b==0){return a;}return gcd(b,a%b);} static long Modpow(long a,long p,long m){long res=1;while(p>0){if((p&1)!=0){res=(res*a)%m;}p >>=1;a=(a*a)%m;}return res%m;} static long Modmul(long a,long b,long m){return ((a%m)*(b%m))%m;} static long ModInv(long a,long m){return Modpow(a,m-2,m);} //static long nck(int n,int r,long m){if(r>n){return 0l;}return Modmul(f[n],ModInv(Modmul(f[n-r],f[r],m),m),m);} //static long[] f; }
Java
["3\n4\n1 3 2 4\n3\n1 2 3\n5\n2 1 4 5 3"]
2 seconds
["1\n0\n2"]
NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
c212524cc1ad8e0332693e3cf644854b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.
900
For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.
standard output
PASSED
2195270849f161514dbaf7567aeb5411
train_110.jsonl
1621152000
You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.
256 megabytes
// Online Java Compiler // Use this editor to write, compile and run your Java code online import java.util.*; public class HelloWorld { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while(t--!=0){ int n=sc.nextInt(); int arr[] = new int[n]; for(int i=0;i<n;i++){ arr[i] = sc.nextInt(); } boolean flag=false; int cnt=1; for(int i=0;i<n;i++){ if(arr[i]!=cnt) { flag=true; break; } cnt++; } if(!flag){ System.out.println(0); }else{ if(arr[0]==n && arr[n-1]==1) System.out.println(3); else if(arr[0]==1){ System.out.println(1); }else if(arr[n-1]==n){ System.out.println(1); }else{ System.out.println(2); } } } } }
Java
["3\n4\n1 3 2 4\n3\n1 2 3\n5\n2 1 4 5 3"]
2 seconds
["1\n0\n2"]
NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
c212524cc1ad8e0332693e3cf644854b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.
900
For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.
standard output
PASSED
7101550383aa16e4a26eb1d187553b50
train_110.jsonl
1621152000
You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.
256 megabytes
//package MyPackage; import java.io.*; import java.util.*; public class MyClass { final static long mod = 1_000_000_007; final static int mini = Integer.MIN_VALUE; final static int maxi = Integer.MAX_VALUE; static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } static long ncr(long n, long r) { if (r > n - r) r = n - r; long[] C = new long[(int) r + 1]; C[0] = 1; for (int i = 1; i <= n; i++) { for (long j = Math.min(i, r); j > 0; j--) C[(int) j] = (C[(int) j] + C[(int) j - 1]) % mod; } return C[(int) r]; } static boolean isPrime(long n) { if (n <= 1) return false; else if (n == 2) return true; else if (n % 2 == 0) return false; for (int i = 3; i <= Math.sqrt(n); i += 2) { if (n % i == 0) return false; } return true; } static boolean isSquare(long x) { if (x >= 0) { long sr = (long) Math.sqrt(x); return ((sr * sr) == x); } return false; } static int countSetBits(int n) { int count = 0; while(n > 0) { n &= (n - 1); count++; } return count; } static int digits(long n) { int count = 0; long temp = n; while (temp > 0) { temp /= 10; count++; } return count; } static boolean isPalindrome(long i) { long originalNum = i; long remainder; long reversedNum = 0; while (i != 0) { remainder = i % 10; reversedNum = reversedNum * 10 + remainder; i /= 10; } return originalNum == reversedNum; } static long lcm(long a, long b) { return (a / gcd(a, b)) * b; } static void sort(long[] a) { ArrayList<Long> l = new ArrayList<>(); for (long value : a) { l.add(value); } Collections.sort(l); for (int i = 0; i < l.size(); i++) a[i] = l.get(i); } static void sort(int[] a) { ArrayList<Integer> l = new ArrayList<>(); for (int value : a) { l.add(value); } Collections.sort(l); for (int i = 0; i < l.size(); i++) a[i] = l.get(i); } static void reverse(int[] arr) { int l = 0; int h = arr.length - 1; while (l < h) { swap(arr, l, h); l++; h--; } } static String reverse(String s) { StringBuilder res = new StringBuilder(s); return res.reverse().toString(); } static long fact(long n) { long res = 1, i; for (i = 2; i <= n; i++) res *= i; return res; } static void swap(int[] arr, int i, int j) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String n() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nint() { return Integer.parseInt(n()); } long nlong() { return Long.parseLong(n()); } double ndouble() { return Double.parseDouble(n()); } int[] narr(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nint(); return a; } int[][] narr(int n, int m) { int[][] a = new int[n][m]; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) a[i][j] = nint(); return a; } String nline() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } public static class Pair { int a; int b; public Pair(int a, int b) { this.a = a; this.b = b; } } public static void main(String[] args) { FastReader sc = new FastReader(); PrintWriter out = new PrintWriter(System.out); int t = sc.nint(); while(t-- > 0) { int n = sc.nint(); int[] arr = sc.narr(n); int[] temp = arr.clone(); sort(temp); if(Arrays.toString(temp).equals(Arrays.toString(arr))) { out.println(0); } else if(temp[0] == arr[0] || temp[n - 1] == arr[n - 1]) { out.println(1); } else if(temp[0] == arr[n - 1] && temp[n - 1] == arr[0]) { out.println(3); } else out.println(2); } out.flush(); out.close(); } }
Java
["3\n4\n1 3 2 4\n3\n1 2 3\n5\n2 1 4 5 3"]
2 seconds
["1\n0\n2"]
NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
c212524cc1ad8e0332693e3cf644854b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.
900
For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.
standard output
PASSED
5f5618b73560f82c354741ef5cd9529f
train_110.jsonl
1621152000
You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.
256 megabytes
import java.util.*; public class Div2_109B { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int T=sc.nextInt(); while(T-- > 0){ int n=sc.nextInt(); int arr[]=new int[n]; for (int i=0;i<n;i++) { arr[i]=sc.nextInt(); } int ans=0; boolean flag=true; boolean reverse=true; for(int i=0;i<n-1;i++){ if(arr[i]>arr[i+1]){ flag=false; break; } } for(int i=0;i<n-1;i++){ if(arr[i]<arr[i+1]){ reverse=false; break; } } if(flag) System.out.println(ans); else if(arr[0]-1==0 || arr[n-1]-1==n-1) System.out.println(1); else if(reverse) System.out.println(3); else if(arr[0]-1==n-1 && arr[n-1]-1==0) System.out.println(3); else if(arr[0]-1==n-1 || arr[n-1]-1==0) System.out.println(2); else System.out.println(2); } } }
Java
["3\n4\n1 3 2 4\n3\n1 2 3\n5\n2 1 4 5 3"]
2 seconds
["1\n0\n2"]
NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
c212524cc1ad8e0332693e3cf644854b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.
900
For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.
standard output
PASSED
4214dc12aca9b55980e7acb50d53d040
train_110.jsonl
1621152000
You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.
256 megabytes
import java.util.*; public class Permutation { public static void main(String args[]) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); for(int i = 0; i< t; i++) { int n = sc.nextInt(); int a[] = new int[n]; for(int j = 0; j< n;j++) a[j]= sc.nextInt(); boolean flag1 = true; for(int j = 0; j< n;j++) { if(a[j]!=j+1) flag1 =false; } if(flag1) { System.out.println("0"); } else if(a[0]==1||a[n-1]==n) { System.out.println("1"); } else if((a[0]==n&&a[n-1]==1)) { System.out.println("3"); } else { System.out.println("2"); } } } }
Java
["3\n4\n1 3 2 4\n3\n1 2 3\n5\n2 1 4 5 3"]
2 seconds
["1\n0\n2"]
NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
c212524cc1ad8e0332693e3cf644854b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.
900
For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.
standard output
PASSED
f82cc4a547a610c4ab9d9e3f980735b7
train_110.jsonl
1621152000
You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.
256 megabytes
import java.util.*; import java.io.*; import java.lang.*; public class Solution{ public static void main(String[] args) { Scanner sc=new Scanner(System.in); int t=sc.nextInt(); for(int i=0; i<t; i++) { int n=sc.nextInt(); int[] arr= new int[n]; for(int x=0; x<n; x++){ arr[x] = sc.nextInt(); } System.out.println(getSteps(arr,n)); } } public static int getSteps(int[] arr,int n){ int[] e= new int[n]; for(int x=0; x<n; x++){ e[x] =arr[x]; } Arrays.sort(e); if(Arrays.equals(arr,e)) return 0; if(arr[n-1]==1 && arr[0]==n) return 3; if(arr[0]==1 || arr[n-1]==n ) return 1; else return 2; } }
Java
["3\n4\n1 3 2 4\n3\n1 2 3\n5\n2 1 4 5 3"]
2 seconds
["1\n0\n2"]
NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
c212524cc1ad8e0332693e3cf644854b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.
900
For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.
standard output
PASSED
084bc724b967b880313fa64fe16a93a8
train_110.jsonl
1621152000
You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.
256 megabytes
import java.io.*; import java.util.*; public class A { static final int INF = (int) 1e9 + 9; static final int MAXN = (int) 1e5 + 5; static final int MAXLOG = (int) (Math.log(MAXN) / Math.log(2) + 1e-10) + 1; static final int MOD = 1_000_000_007; static BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out)); static Reader in = new Reader(); static int n, m, t, q, k; static int[] a = new int[55]; public static void main(String[] args) throws IOException { // Scanner in = new Scanner(new File("div7.in")); // PrintWriter pw = new PrintWriter("div7.out"); Scanner in = new Scanner(System.in); PrintWriter pw = new PrintWriter(System.out); t = in.nextInt(); while(t-- > 0) { n = in.nextInt(); for(int i = 0; i < n; ++i) { a[i] = in.nextInt(); } if(a[0] == n && a[n - 1] == 1) pw.println(3); else if(a[0] != 1 && a[n - 1] != n) pw.println(2); else if(isSorted(a, n)) pw.println(0); else pw.println(1); } pw.close(); in.close(); } public static boolean isSorted(int[] a, int n) { for (int i = 0; i < n; i++) { if (a[i] != i + 1) { return false; } } return true; } static class Pair<U, V> implements Comparable<Pair<U, V>> { U first; V second; public Pair(U first, V second) { this.first = first; this.second = second; } @Override public boolean equals(Object obj) { if (obj == null) return false; Pair<U, V> o = (Pair<U, V>) obj; return this.first.equals(o.first) && this.second.equals(o.second); } @Override public int compareTo(Pair<U, V> p) { int firstC = ((Comparable) first).compareTo((Comparable) p.first); if (firstC == 0) return ((Comparable) second).compareTo((Comparable) p.second); return firstC; } } static class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public String next() throws IOException { byte[] buf = new byte[64]; // string length int cnt = 0, c; while ((c = read()) != -1) { if (c == ' ' || c == '\t' || c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } }
Java
["3\n4\n1 3 2 4\n3\n1 2 3\n5\n2 1 4 5 3"]
2 seconds
["1\n0\n2"]
NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
c212524cc1ad8e0332693e3cf644854b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.
900
For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.
standard output
PASSED
30ad9a4ec8c43ae94ed6f7cb67106c03
train_110.jsonl
1621152000
You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.
256 megabytes
import java.io.*; import java.util.*; public class Solution { public static void main(String[] args) throws Exception { FastReader fr=new FastReader(); int t=fr.nextInt(); while(t-->0) { int n=fr.nextInt(); int a[]=new int[n]; int min=Integer.MAX_VALUE; int max=Integer.MIN_VALUE; boolean sorted=true; for(int i=0;i<n;i++) { a[i]=fr.nextInt(); min=Math.min(min, a[i]); max=Math.max(max,a[i]); if(i>0) { if(a[i]<a[i-1]) sorted=false; } } if(sorted==true) { System.out.println(0); } else if(a[0]==max&&a[n-1]==min) { System.out.println(3); } else if(a[0]==min||a[n-1]==max) { System.out.println(1); } else System.out.println(2); } } public static String lcs(String a,String b) { int dp[][]=new int[a.length()+1][b.length()+1]; for(int i=0;i<=a.length();i++) { for(int j=0;j<=b.length();j++) { if(i==0||j==0) dp[i][j]=0; } } for(int i=1;i<=a.length();i++) { for(int j=1;j<=b.length();j++) { if(a.charAt(i-1)==b.charAt(j-1)) dp[i][j]=1+dp[i-1][j-1]; else dp[i][j]=Math.max(dp[i-1][j],dp[i][j-1]); } } int i=a.length(); int j=b.length(); String lcs=""; while(i>0&&j>0) { if(a.charAt(i-1)==b.charAt(j-1)) { lcs=a.charAt(i-1)+lcs; i--; j--; } else { if(dp[i-1][j]>dp[i][j-1]) i--; else j--; } } return lcs; } public static long facto(long n) { if(n==1||n==0) return 1; return n*facto(n-1); } public static long gcd(long n1,long n2) { if (n2 == 0) { return n1; } return gcd(n2, n1 % n2); } public static boolean isPali(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; } public static String reverse(String s) { String res=""; for(int i=0;i<s.length();i++) { res+=s.charAt(i); } return res; } public static int bsearch(long suf[],long val) { int i=0; int j=suf.length-1; while(i<=j) { int mid=(i+j)/2; if(suf[mid]==val) return mid; else if(suf[mid]<val) j=mid-1; else i=mid+1; } return -1; } public static int[] getFreq(String s) { int a[]=new int[26]; for(int i=0;i<s.length();i++) { a[s.charAt(i)-'a']++; } return a; } public static boolean isPrime(int n) { for(int i=2;(i*i)<=n;i++) { if(n%i==0) return false; } return true; } } class Pair{ long i; long j; Pair(long num,long freq){ this.i=num; this.j=freq; } } class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } }
Java
["3\n4\n1 3 2 4\n3\n1 2 3\n5\n2 1 4 5 3"]
2 seconds
["1\n0\n2"]
NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
c212524cc1ad8e0332693e3cf644854b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.
900
For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.
standard output
PASSED
f8487344fcd24fe2f443949d637ac1f8
train_110.jsonl
1621152000
You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.
256 megabytes
import java.io.*; import java.util.*; import java.lang.Math; public class Main{ static BufferedReader reader; static StringTokenizer tokenizer; static PrintWriter writer; static int nextInt() throws IOException { return Integer.parseInt(nextToken()); } static long nextLong() throws IOException { return Long.parseLong(nextToken()); } static double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } static String nextToken() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } static String nexts() throws IOException { tokenizer = new StringTokenizer(reader.readLine()); String s=""; while (tokenizer.hasMoreTokens()) { s+=tokenizer.nextElement()+" "; } return s; } public static int gcd(int x, int y){ if (y == 0) return x; else return gcd(y, x % y); } public static boolean isPrime(int nn) { if(nn<=1){ return false; } if(nn<=3){ return true; } if (nn%2==0||nn%3==0){ return false; } for (int i=5;i*i<=nn;i=i+6){ if(nn%i==0||nn%(i+2)==0){ return false; } } return true; } public static void shuffle(int[] A) { for (int i = 0; i < A.length; i++) { int j = (int)(i * Math.random()); int tmp = A[i]; A[i] = A[j]; A[j] = tmp; } } public static void shufflel(Long[] A) { for (int i = 0; i < A.length; i++) { int j = (int)(i * Math.random()); long tmp = A[i]; A[i] = A[j]; A[j] = tmp; } } public static String reverse(String input) { StringBuilder input2=new StringBuilder(); input2.append(input); input2 = input2.reverse(); return input2.toString(); } public static long power(int x, long n) { // long mod = 1000000007; if (n == 0) { return 1; } long pow = power(x, n / 2); if ((n & 1) == 1) { return (x * pow * pow); } return (pow * pow); } public static long power(long x, long y, long p) //x^y%p { long res = 1; x = x % p; while (y > 0) { if (y % 2 == 1) { res = (res * x) % p; } y = y >> 1; // y = y/2 x = (x * x) % p; } return res; } static long ncr(int n, int k) { long res = 1; // Since C(n, k) = C(n, n-k) if (k > n - k) { k = n - k; } // Calculate value of [n*(n-1)*---*(n-k+1)] / [k*(k-1)*---*1] for (int i = 0; i < k; ++i) { res *= (n - i); res /= (i + 1); } return res; } public static int inv(int a, int m) //Returns modulo inverse of a with respect to m using extended euclid algorithm { int m0=m,t,q; int x0=0,x1=1; if(m==1){ return 0; } while(a>1) { q=a/m; t=m; m=a%m;a=t; t=x0; x0=x1-q*x0; x1=t; } if(x1<0){ x1+=m0; } return x1; } static int modInverse(int n, int p) { return (int)power((long)n, (long)(p - 2),(long)p); } static int ncrmod(int n, int r, int p) { if (r == 0) // Base case return 1; int[] fac = new int[n + 1]; // Fill factorial array so that we can find all factorial of r, n and n-r fac[0] = 1; for (int i = 1; i <= n; i++) fac[i] = fac[i - 1] * i % p; return (fac[n] * modInverse(fac[r], p) % p * modInverse(fac[n - r], p) % p) % p; //IMPORTANT } static int upper(int a[], int x) //Returns rightest index of x in sorted arr else -1 { //If not present returns index of just smaller element int n=a.length; int l=0; int r=n-1; int ans=-1; while(l<=r){ int m=(r-l)/2+l; if(a[m]<=x){ ans=m; l=m+1; } else{ r=m-1; } } return ans; } static int lower(int a[], int x) //Returns leftest index of x in sorted arr else n { //If not present returns index of just greater element int n=a.length; int l=0; int r=n-1; int ans=n; while(l<=r){ int m=(r-l)/2+l; if(a[m]>=x){ ans=m; r=m-1; } else{ l=m+1; } } return ans; } public static long stringtoint(String s){ // Convert bit string to number long a = 1; long ans = 0; StringBuilder sb = new StringBuilder(); sb.append(s); sb.reverse(); s=sb.toString(); for(int i=0;i<s.length();i++){ ans = ans + a*(s.charAt(i)-'0'); a = a*2; } return ans; } String inttostring(long a,long m){ // a is number and m is length of string required String res = ""; // Convert a number in bit string representation for(int i=0;i<(int)m;i++){ if((a&(1<<i))==1){ res+='1'; }else res+='0'; } StringBuilder sb = new StringBuilder(); sb.append(res); sb.reverse(); res=sb.toString(); return res; } static class R implements Comparable<R>{ int x, y; public R(int x, int y) { //a[i]=new R(x,y); this.x = x; this.y = y; } public int compareTo(R o) { return x-o.x; //Increasing order(Which is usually required) } } /* FUNCTION TO SORT HASHMAP ACCORDING TO VALUE //USE IT AS FOLLOW //Make a new list List<Map.Entry<Integer, Integer> > list = new LinkedList<Map.Entry<Integer, Integer> >(h.entrySet()); // Sort the list Collections.sort(list, new Comparator<Map.Entry<Integer, Integer> >() { public int compare(Map.Entry<Integer, Integer> o1, Map.Entry<Integer, Integer> o2) { return (o1.getValue()).compareTo(o2.getValue()); //This is used to sort string stored as VALUE, use below function here accordingly } }); // put data from sorted list to new hashmap HashMap<String, Integer> temp = new LinkedHashMap<String, Integer>(); for (Map.Entry<String, Integer> aa : list) { temp.put(aa.getKey(), aa.getValue()); } return temp; //Now temp is our new sorted hashmap OR for(int i = 0;i<h.size();i++) //accessing elements from the list made { int count = list.get(i).getValue(); //Value while(count >= 0) { int key=list.get(i).getKey(); //key count -- ; } } //////////////////////////////////////////////////////////////////////////////////////// public int compare(Entry<Integer, Integer> o1, Entry<Integer, Integer> o2) { if(o1.getValue() != o2.getValue()) return o1.getValue() > o2.getValue()?1:-1; //Sorts Value in increasing order else if(o1.getValue() == o2.getValue()){ return o1.getKey() > o2.getKey() ? 1:-1; //If value equal, then sorts key in increasing order } return Integer.MIN_VALUE; } */ //Check if palindrome string - System.out.print(A.equals(new StringBuilder(A).reverse().toString())?"Yes":"No"); public static void main(String[] args) throws IOException { reader = new BufferedReader(new InputStreamReader(System.in)); tokenizer = null; writer = new PrintWriter(System.out); solve(); reader.close(); writer.close(); } private static void solve() throws IOException { int t = nextInt(); while(t-->0){ //String s= nextToken(); //String[] s = str.split("\\s+"); //ArrayList<Integer> ar=new ArrayList<Integer>(); //HashSet<Integer> set=new HashSet<Integer>(); //HashMap<Integer,String> h=new HashMap<Integer,String>(); //R[] a1=new R[n]; //char[] c=nextToken().toCharArray(); //PriorityQueue<Integer> pq=new PriorityQueue<Integer>(Collections.reverseOrder()); //NavigableSet<Integer> pq=new TreeSet<>(); int n = nextInt(); //long n = nextLong(); int[] a=new int[n]; int[] b=new int[n]; //long[] a=new long[n]; for(int i=0;i<n;i++){ a[i]=nextInt(); b[i]=a[i]; } //shuffle(a); //shufflel(a); Arrays.sort(a); int k=0; for(int i=0;i<n;i++){ if(a[i]!=b[i])k++; } if(k==0){ writer.println(0); continue; } k=0; for(int i=0;i<n;i++){ if(a[i]==b[n-1-i])k++; } if(a[0]==b[0]||a[n-1]==b[n-1]){ writer.println(1); continue; } if(b[0]==a[n-1]&&b[n-1]==a[0]){ writer.println(3); continue; } writer.println(2); } } }
Java
["3\n4\n1 3 2 4\n3\n1 2 3\n5\n2 1 4 5 3"]
2 seconds
["1\n0\n2"]
NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
c212524cc1ad8e0332693e3cf644854b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.
900
For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.
standard output
PASSED
1b926366015846f0487a22a9bfd4fdc4
train_110.jsonl
1621152000
You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.
256 megabytes
import java.io.*; import java.util.*; import java.lang.Math; public class Main{ static BufferedReader reader; static StringTokenizer tokenizer; static PrintWriter writer; static int nextInt() throws IOException { return Integer.parseInt(nextToken()); } static long nextLong() throws IOException { return Long.parseLong(nextToken()); } static double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } static String nextToken() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } static String nexts() throws IOException { tokenizer = new StringTokenizer(reader.readLine()); String s=""; while (tokenizer.hasMoreTokens()) { s+=tokenizer.nextElement()+" "; } return s; } public static int gcd(int x, int y){ if (y == 0) return x; else return gcd(y, x % y); } public static boolean isPrime(int nn) { if(nn<=1){ return false; } if(nn<=3){ return true; } if (nn%2==0||nn%3==0){ return false; } for (int i=5;i*i<=nn;i=i+6){ if(nn%i==0||nn%(i+2)==0){ return false; } } return true; } public static void shuffle(int[] A) { for (int i = 0; i < A.length; i++) { int j = (int)(i * Math.random()); int tmp = A[i]; A[i] = A[j]; A[j] = tmp; } } public static void shufflel(Long[] A) { for (int i = 0; i < A.length; i++) { int j = (int)(i * Math.random()); long tmp = A[i]; A[i] = A[j]; A[j] = tmp; } } public static String reverse(String input) { StringBuilder input2=new StringBuilder(); input2.append(input); input2 = input2.reverse(); return input2.toString(); } public static long power(int x, long n) { // long mod = 1000000007; if (n == 0) { return 1; } long pow = power(x, n / 2); if ((n & 1) == 1) { return (x * pow * pow); } return (pow * pow); } public static long power(long x, long y, long p) //x^y%p { long res = 1; x = x % p; while (y > 0) { if (y % 2 == 1) { res = (res * x) % p; } y = y >> 1; // y = y/2 x = (x * x) % p; } return res; } static long ncr(int n, int k) { long res = 1; // Since C(n, k) = C(n, n-k) if (k > n - k) { k = n - k; } // Calculate value of [n*(n-1)*---*(n-k+1)] / [k*(k-1)*---*1] for (int i = 0; i < k; ++i) { res *= (n - i); res /= (i + 1); } return res; } public static int inv(int a, int m) //Returns modulo inverse of a with respect to m using extended euclid algorithm { int m0=m,t,q; int x0=0,x1=1; if(m==1){ return 0; } while(a>1) { q=a/m; t=m; m=a%m;a=t; t=x0; x0=x1-q*x0; x1=t; } if(x1<0){ x1+=m0; } return x1; } static int modInverse(int n, int p) { return (int)power((long)n, (long)(p - 2),(long)p); } static int ncrmod(int n, int r, int p) { if (r == 0) // Base case return 1; int[] fac = new int[n + 1]; // Fill factorial array so that we can find all factorial of r, n and n-r fac[0] = 1; for (int i = 1; i <= n; i++) fac[i] = fac[i - 1] * i % p; return (fac[n] * modInverse(fac[r], p) % p * modInverse(fac[n - r], p) % p) % p; //IMPORTANT } static int upper(int a[], int x) //Returns rightest index of x in sorted arr else -1 { //If not present returns index of just smaller element int n=a.length; int l=0; int r=n-1; int ans=-1; while(l<=r){ int m=(r-l)/2+l; if(a[m]<=x){ ans=m; l=m+1; } else{ r=m-1; } } return ans; } static int lower(int a[], int x) //Returns leftest index of x in sorted arr else n { //If not present returns index of just greater element int n=a.length; int l=0; int r=n-1; int ans=n; while(l<=r){ int m=(r-l)/2+l; if(a[m]>=x){ ans=m; r=m-1; } else{ l=m+1; } } return ans; } public static long stringtoint(String s){ // Convert bit string to number long a = 1; long ans = 0; StringBuilder sb = new StringBuilder(); sb.append(s); sb.reverse(); s=sb.toString(); for(int i=0;i<s.length();i++){ ans = ans + a*(s.charAt(i)-'0'); a = a*2; } return ans; } String inttostring(long a,long m){ // a is number and m is length of string required String res = ""; // Convert a number in bit string representation for(int i=0;i<(int)m;i++){ if((a&(1<<i))==1){ res+='1'; }else res+='0'; } StringBuilder sb = new StringBuilder(); sb.append(res); sb.reverse(); res=sb.toString(); return res; } static class R implements Comparable<R>{ int x, y; public R(int x, int y) { //a[i]=new R(x,y); this.x = x; this.y = y; } public int compareTo(R o) { return x-o.x; //Increasing order(Which is usually required) } } /* FUNCTION TO SORT HASHMAP ACCORDING TO VALUE //USE IT AS FOLLOW //Make a new list List<Map.Entry<Integer, Integer> > list = new LinkedList<Map.Entry<Integer, Integer> >(h.entrySet()); // Sort the list Collections.sort(list, new Comparator<Map.Entry<Integer, Integer> >() { public int compare(Map.Entry<Integer, Integer> o1, Map.Entry<Integer, Integer> o2) { return (o1.getValue()).compareTo(o2.getValue()); //This is used to sort string stored as VALUE, use below function here accordingly } }); // put data from sorted list to new hashmap HashMap<String, Integer> temp = new LinkedHashMap<String, Integer>(); for (Map.Entry<String, Integer> aa : list) { temp.put(aa.getKey(), aa.getValue()); } return temp; //Now temp is our new sorted hashmap OR for(int i = 0;i<h.size();i++) //accessing elements from the list made { int count = list.get(i).getValue(); //Value while(count >= 0) { int key=list.get(i).getKey(); //key count -- ; } } //////////////////////////////////////////////////////////////////////////////////////// public int compare(Entry<Integer, Integer> o1, Entry<Integer, Integer> o2) { if(o1.getValue() != o2.getValue()) return o1.getValue() > o2.getValue()?1:-1; //Sorts Value in increasing order else if(o1.getValue() == o2.getValue()){ return o1.getKey() > o2.getKey() ? 1:-1; //If value equal, then sorts key in increasing order } return Integer.MIN_VALUE; } */ //Check if palindrome string - System.out.print(A.equals(new StringBuilder(A).reverse().toString())?"Yes":"No"); public static void main(String[] args) throws IOException { reader = new BufferedReader(new InputStreamReader(System.in)); tokenizer = null; writer = new PrintWriter(System.out); solve(); reader.close(); writer.close(); } private static void solve() throws IOException { int t = nextInt(); while(t-->0){ //String s= nextToken(); //String[] s = str.split("\\s+"); //ArrayList<Integer> ar=new ArrayList<Integer>(); //HashSet<Integer> set=new HashSet<Integer>(); //HashMap<Integer,String> h=new HashMap<Integer,String>(); //R[] a1=new R[n]; //char[] c=nextToken().toCharArray(); //PriorityQueue<Integer> pq=new PriorityQueue<Integer>(Collections.reverseOrder()); //NavigableSet<Integer> pq=new TreeSet<>(); int n = nextInt(); //long n = nextLong(); int[] a=new int[n]; int[] b=new int[n]; //long[] a=new long[n]; for(int i=0;i<n;i++){ a[i]=nextInt(); b[i]=a[i]; } //shuffle(a); //shufflel(a); Arrays.sort(a); int k=0; for(int i=0;i<n;i++){ if(a[i]!=b[i])k++; } if(k==0){ writer.println(0); continue; } k=0; for(int i=0;i<n;i++){ if(a[i]==b[n-1-i])k++; } if(a[0]==b[0]||a[n-1]==b[n-1]){ writer.println(1); continue; } if(b[0]!=a[n-1]||b[n-1]!=a[0]){ writer.println(2); continue; } writer.println(3); } } }
Java
["3\n4\n1 3 2 4\n3\n1 2 3\n5\n2 1 4 5 3"]
2 seconds
["1\n0\n2"]
NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
c212524cc1ad8e0332693e3cf644854b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.
900
For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.
standard output
PASSED
6eb70b49e6dae9c942dcbba01b17b088
train_110.jsonl
1621152000
You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.
256 megabytes
import java.awt.Point; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.ObjectInputStream.GetField; import java.lang.reflect.Array; import java.math.BigDecimal; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Hashtable; import java.util.LinkedList; import java.util.PriorityQueue; import java.util.Queue; import java.util.Set; import java.util.Stack; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.TreeSet; import javax.sound.sampled.ReverbType; public class Edu109 { static PrintWriter out; static Scanner sc; static ArrayList<int[]>q,w,x; static ArrayList<Integer>adj[]; static HashSet<Integer>primesH; static boolean prime[]; //static ArrayList<Integer>a; static HashSet<Long>tmp; static int[][][]dist; static boolean[]v; static int[]a,b,c,d; static Boolean[][]dp; static char[][]mp; static int A,B,n,m,h,ans,sum; //static String a,b; static long oo=(long)1e9+7; public static void main(String[]args) throws IOException { sc=new Scanner(System.in); out=new PrintWriter(System.out); //A(); B(); //C(); //D(); //E(); //F(); //G(); out.close(); } private static void A() throws IOException { int t=ni(); while(t-->0) { int k=ni(); int ans=0; for(int i=1;i<=100;i++) { if((i*100)%k==0) { ans=i*100/k;break; } } ol(ans); } } static void B() throws IOException { int t=ni(); while(t-->0) { int n=ni(); a=nai(n); boolean isSorted=true,one=a[0]==1; int pos=0; for(int i=1;i<n;i++) { if(a[i]<a[i-1])isSorted=false; if(a[i]==1)pos=i; } boolean ok=true; for(int i=pos+1;i<n;i++) { if(a[i]<a[i-1])ok=false; } boolean lst=a[0]==n; boolean fir=a[n-1]==1; if(isSorted)ol(0); else if(lst&&fir)ol(3); else if(lst||fir)ol(2); else if(a[0]==1||a[n-1]==n)ol(1); else ol(2); // if(isSorted)ol(0); // else out.println(fl&&lst?3:((one?1:2)-(ok?1:0)+(lst?1:0))); } } static void C() throws IOException{ int t=ni(); while(t-->0) { int n=ni(); int[]ans=new int[n]; boolean[]v=new boolean[n+1]; int k=n;if(k%2==1)k--; for(int i=0;i<k;i+=2) { out.println("? 1 "+(i+1)+" "+(i+2)+" "+(n-1)); out.flush(); int mx; int val=ni(); mx=val; if(val==n-1) { out.println("? 1 "+(i+2)+" "+(i+1)+" "+(n-1)); out.flush(); int tmp=ni(); if(tmp==n)mx=n; } out.println("? 1 "+(i+1)+" "+(i+2)+" "+(mx-1)); out.flush(); int tmp=ni(); if(tmp==mx-1) {//pi = mx ans[i]=mx; out.println("? 2 "+(i+2)+" "+(i+1)+" "+1); out.flush(); tmp=ni(); ans[i+1]=tmp; }else { ans[i+1]=mx; out.println("? 2 "+(i+1)+" "+(i+2)+" "+1); out.flush(); tmp=ni(); ans[i]=tmp; } v[mx]=v[tmp]=true; } if(n%2==1) { for(int i=1;i<=n;i++) { if(!v[i]) { ans[n-1]=i;break; } } } out.print("!"); for(int i=0;i<ans.length;i++) { out.print(" "+ans[i]); } out.println();out.flush(); } } private static Boolean dp(int i, int j) { if(j>sum/2)return false; if(i==x.size()) { return sum/2==j; } if(dp[i][j]!=null)return dp[i][j]; return dp[i][j]=dp(i+1,j+x.get(i)[0])||dp(i+1,j); } static boolean isPrime(long n) { if(n==2)return true; if(n<2||n%2==0)return false; for(long i=3L;i*i<n;i+=2l) { long rem=(n%i); if(rem==0)return false; } return true; } static void D() throws IOException { int t=1; while(t-->0) { int n=ni(),m=ni(),k=ni(); int[][]ans=new int[n][m]; dist=new int[n][m][4]; for(int i=0;i<n;i++)for(int j=0;j>m;j++) Arrays.fill(dist[i][j], Integer.MAX_VALUE); int x; for(int i=0;i<n;i++) { for(int j=0;j<m-1;j++) { dist[i][j][2]=(x=ni()); dist[i][j+1][3]=x; } } for(int i=0;i<n-1;i++) { for(int j=0;j<m;j++) { dist[i][j][1]=(x=ni()); dist[i+1][j][0]=x; } } int[][]nans=new int[n][m]; if(k%2==1) { for(int i=0;i<n;i++)Arrays.fill(ans[i], -1); }else { for(int ii=0;ii<k/2;ii++) { for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { nans[i][j]=Integer.MAX_VALUE; if(i>0) nans[i][j]=Math.min(nans[i][j], ans[i-1][j]+dist[i-1][j][1]); if(i<n-1) nans[i][j]=Math.min(nans[i][j], ans[i+1][j]+dist[i+1][j][0]); if(j>0) nans[i][j]=Math.min(nans[i][j], ans[i][j-1]+dist[i][j-1][2]); if(j<m-1) nans[i][j]=Math.min(nans[i][j], ans[i][j+1]+dist[i][j+1][3]); } } int[][]tmp=ans; ans=nans; nans=tmp; } } for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { if(ans[i][j]!=-1)ans[i][j]*=2; out.print(ans[i][j]+" "); } ol(""); } } } private static int bfs(int i, int j,int k) { boolean [][]vis=new boolean[dist.length][dist[0].length]; Queue<int[]>q=new LinkedList<int[]>(); int mn=Integer.MAX_VALUE; q.add(new int[] {i,j,0,0}); int[]dx=new int[] {-1,1,0,0}; int[]dy=new int[] {0,0,1,-1}; while(!q.isEmpty()) { int []x=q.poll(); vis[x[0]][x[1]]=true; int c=x[2]; if(c>k/2)continue; if(c>0&&k%c==0&&(k/c)%2==0) { mn=Math.min(mn,x[3]*k/c ); } for(int a=0;a<4;a++) { int nx=x[0]+dx[a]; int ny=x[1]+dy[a]; if(valid(nx,ny)&&!vis[nx][ny]) { q.add(new int[] {nx,ny,c+1,x[3]+dist[x[0]][x[1]][a]}); } } } return mn; } private static boolean valid(int nx, int ny) { return nx>=0&&nx<dist.length&&ny>=0&&ny<dist[0].length; } static int gcd (int a, int b) { return b==0?a:gcd (b, a % b); } static void E() throws IOException { int t=ni(); while(t-->0) { } } static void F() throws IOException { int t=ni(); while(t-->0) { } } static void CC() throws IOException { for(int kk=2;kk<21;kk++) { ol(kk+" -------"); int n=kk; int k=n-2; int msk=1<<k; int[]a=new int[k]; for(int i=0;i<a.length;i++)a[i]=i+2; int mx=1; int ms=0; for(int i=1;i<msk;i++) { long prod=1; int cnt=0; for(int j=0;j<a.length;j++) { if(((i>>j)&1)!=0) { prod*=a[j]; cnt++; } } if(cnt>=mx&&prod%n==1) { mx=cnt; ms=i; } } ol(mx==1?mx:mx+1); out.print(1+" "); long pr=1; for(int j=0;j<a.length;j++) { if(((ms>>j)&1)!=0) { out.print(a[j]+" "); pr*=a[j]; } } ol(""); ol("Prod: "+pr); ol(n+"*"+((pr-1)/n)+" + "+1); } } static int ni() throws IOException { return sc.nextInt(); } static double nd() throws IOException { return sc.nextDouble(); } static long nl() throws IOException { return sc.nextLong(); } static String ns() throws IOException { return sc.next(); } static int[] nai(int n) throws IOException { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = sc.nextInt(); return a; } static long[] nal(int n) throws IOException { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = sc.nextLong(); return a; } static int[][] nmi(int n,int m) throws IOException{ int[][]a=new int[n][m]; for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { a[i][j]=sc.nextInt(); } } return a; } static long[][] nml(int n,int m) throws IOException{ long[][]a=new long[n][m]; for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { a[i][j]=sc.nextLong(); } } return a; } static void o(String x) { out.print(x); } static void ol(String x) { out.println(x); } static void ol(int x) { out.println(x); } static void disp1(int []a) { for(int i=0;i<a.length;i++) { out.print(a[i]+" "); } out.println(); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(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
["3\n4\n1 3 2 4\n3\n1 2 3\n5\n2 1 4 5 3"]
2 seconds
["1\n0\n2"]
NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
c212524cc1ad8e0332693e3cf644854b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.
900
For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.
standard output
PASSED
68db4c80228c5ee5fa212a4c1fbe82a5
train_110.jsonl
1621152000
You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.
256 megabytes
import java.util.*; public class B{ static Scanner sc = new Scanner(System.in); public static void main(String[] args) { int t = sc.nextInt(); while(t--!=0)solve(); } public static void solve(){ int n = sc.nextInt(); int [] arr = new int[n]; boolean mark = true; for(int i=0;i<n;i++){ arr[i] = sc.nextInt(); if(arr[i] != i+1)mark = false; } if(mark){ System.out.println(0); return; } if(arr[0] == 1 || arr[n-1] == n){ System.out.println(1); return; } if(arr[0] == n && arr[n-1] == 1){ System.out.println(3); }else{ System.out.println(2); } } }
Java
["3\n4\n1 3 2 4\n3\n1 2 3\n5\n2 1 4 5 3"]
2 seconds
["1\n0\n2"]
NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
c212524cc1ad8e0332693e3cf644854b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.
900
For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.
standard output
PASSED
a421aba2f6dc9cac975a1440f7c70621
train_110.jsonl
1621152000
You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.
256 megabytes
import java.io.*; import java.lang.*; import java.util.*; public class b { static class FastScanner { InputStreamReader is; BufferedReader br; StringTokenizer st; public FastScanner() { is = new InputStreamReader(System.in); br = new BufferedReader(is); } String next() throws Exception { while (st == null || !st.hasMoreElements()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } int nextInt() throws Exception { return Integer.parseInt(next()); } long nextLong() throws Exception { return Long.parseLong(next()); } int[] readArray(int num) throws Exception { int arr[]=new int[num]; for(int i=0;i<num;i++) arr[i]=nextInt(); return arr; } String nextLine() throws Exception { return br.readLine(); } } public static boolean power_of_two(int a) { if((a&(a-1))==0) { return true; } return false; } static boolean PS(double x) { if (x >= 0) { double i= Math.sqrt(x); if(i%1!=0) { return false; } return ((i * i) == x); } return false; } public static int[] ia(int n) { int ar[]=new int[n]; return ar; } public static long[] la(int n) { long ar[]=new long[n]; return ar; } //**** M A I N C O D E **** public static void main(String args[]) throws java.lang.Exception { FastScanner sc=new FastScanner(); int t=sc.nextInt(); while(t-->0) { int n=sc.nextInt(); int ar[]=new int[n]; int count=0; for(int i=0;i<n;i++) { ar[i]=sc.nextInt(); } for(int i=1;i<n;i++) { if(ar[i]<ar[i-1]) { count++; } } if(count==0) { System.out.println(0); } else{ if(ar[0]==1 || ar[n-1]==n) { System.out.println(1); } else if(ar[0]==n && ar[n-1]==1) { System.out.println(3); } else{ System.out.println(2); } } } } }
Java
["3\n4\n1 3 2 4\n3\n1 2 3\n5\n2 1 4 5 3"]
2 seconds
["1\n0\n2"]
NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
c212524cc1ad8e0332693e3cf644854b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.
900
For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.
standard output
PASSED
250c0287d1b61be0676adaf138d22deb
train_110.jsonl
1621152000
You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.
256 megabytes
import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.StringTokenizer; public class Main{ static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader( new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } public static boolean isSorted(int[] a,int l, int r) { for (int i = l; i < r-1; i++) { if (a[i] > a[i + 1]) { return false; } } return true; } public static void main(String[] args) throws IOException { File file=new File("input.txt"); long startTime=0; if(file.exists()){ System.setIn(new FileInputStream("input.txt")); startTime=System.currentTimeMillis(); } FastReader sc=new FastReader(); int t = sc.nextInt(); while(t-- >0) { int n=sc.nextInt(); int arr[]=new int[n]; int arr1[]=new int[n]; int arr2[]=new int[n]; boolean check=true; for(int i=0;i<n;i++){ arr[i]=sc.nextInt(); arr1[i]=arr[i]; arr2[i]=arr[i]; } if(isSorted(arr, 0, n)){ System.out.println(0); continue; } if(isSorted(arr, 0, n-1) || isSorted(arr, 1, n)){ if(arr[n-1]<arr[0]){ System.out.println(2); } else{ System.out.println(1); } continue; } else { int ans=10; Arrays.sort(arr1,0,n-1); if(arr1[n-1]>arr1[n-2]){ ans=1; } else if(arr1[n-1]<arr1[0]){ ans=3; } else { ans=2; } Arrays.sort(arr2,1,n); int ans1=10; if(arr2[0]<arr2[1]){ ans1=1; } else if(arr2[0]>arr2[n-1]){ ans1=3; } else { ans1=2; } System.out.println(Math.min(ans,ans1)); } } if(file.exists()){ long endTime=System.currentTimeMillis(); System.out.println("Time Taken by program "+(endTime-startTime)+" miliseconds"); } } }
Java
["3\n4\n1 3 2 4\n3\n1 2 3\n5\n2 1 4 5 3"]
2 seconds
["1\n0\n2"]
NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
c212524cc1ad8e0332693e3cf644854b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.
900
For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.
standard output
PASSED
b845c9b445f36e5b2fcd660099677400
train_110.jsonl
1621152000
You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.
256 megabytes
import java.util.*; import java.io.*; public class second { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader( new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } public static int gcd(int a,int b) { if(b==0) return a; return gcd(b,a%b); } public static void main(String args[]) { FastReader in=new FastReader(); int t=in.nextInt(); int ar[]; while(t-->0) { int n=in.nextInt(); ar=new int[n]; int f=0; for(int i=0;i<n;i++) { ar[i]=in.nextInt(); if(i!=0) { if(ar[i-1]>ar[i]) f=1; } } if(f==0) System.out.println("0"); else if(ar[0]==1 || ar[n-1]==n) System.out.println("1"); else if(ar[0]!=n && ar[n-1]==1) System.out.println("2"); else if(ar[n-1]!=1 && ar[0]==n) System.out.println("2"); else if(ar[0]==n && ar[n-1]==1) System.out.println("3"); else System.out.println("2"); } } }
Java
["3\n4\n1 3 2 4\n3\n1 2 3\n5\n2 1 4 5 3"]
2 seconds
["1\n0\n2"]
NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
c212524cc1ad8e0332693e3cf644854b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.
900
For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.
standard output
PASSED
4b441c6a2ca03a986d9028151c5af20e
train_110.jsonl
1621152000
You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.
256 megabytes
import java.util.*; public class New{ public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while(t-->0){ int n =sc.nextInt(); int arr[] = new int[n]; for(int i=0;i<n;i++) arr[i] = sc.nextInt(); if(isSorted(arr,n)){ System.out.println(0); } else if(arr[n-1]==n) System.out.println(1); else if(arr[0]==1) System.out.println(1); else if(arr[0]==n && arr[n-1]==1) System.out.println(3); else System.out.println(2); } } public static boolean isSorted(int arr[],int n){ for(int i=0;i<n;i++){ if(arr[i]!= i+1) return false; } return true; } }
Java
["3\n4\n1 3 2 4\n3\n1 2 3\n5\n2 1 4 5 3"]
2 seconds
["1\n0\n2"]
NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
c212524cc1ad8e0332693e3cf644854b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.
900
For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.
standard output
PASSED
c8e17a8eaa590cfa27f0c5d05cfde5c7
train_110.jsonl
1621152000
You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.
256 megabytes
import java.util.*; import java.io.*; public class sol{ public static void main(String args[])throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(br.readLine().trim()); while(t-- > 0){ int n = Integer.parseInt(br.readLine().trim()); int arr[] = new int[n]; String a[] = br.readLine().split(" "); int count = 0; for(int i=0 ;i<n ; i++){ arr[i] = Integer.parseInt(a[i]); if(arr[i] != i+1) count++; } if(arr[0] == 1 && arr[n-1] == n){ if(count>0) System.out.println(1); else System.out.println(0); }else if(arr[0] == 1 && arr[n-1] != n){ System.out.println(1); }else if(arr[0] != 1 && arr[n-1] == n){ System.out.println(1); }else if(arr[0] != 1 && arr[n-1] != n){ if(n==2) System.out.println(1); else if(arr[0] == n && arr[n-1] == 1) System.out.println(3); else System.out.println(2); } } } }
Java
["3\n4\n1 3 2 4\n3\n1 2 3\n5\n2 1 4 5 3"]
2 seconds
["1\n0\n2"]
NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
c212524cc1ad8e0332693e3cf644854b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.
900
For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.
standard output
PASSED
e45956520bb5f493610156e2be5caed3
train_110.jsonl
1621152000
You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.
256 megabytes
import java.util.*; public class MainClass { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while (t-->0){ int n = sc.nextInt(); int []lst = new int[n]; int diff = 0; boolean check = false; for(int i=0; i<n; i++){ lst[i] = sc.nextInt(); if (lst[i]!=i+1) diff++; } if (diff != 0){ if (lst[0] == n && lst[n-1] == 1) System.out.println(3); else if (lst[n-1]==n || lst[0]==1) System.out.println(1); else System.out.println(2); } else System.out.println(0); } } }
Java
["3\n4\n1 3 2 4\n3\n1 2 3\n5\n2 1 4 5 3"]
2 seconds
["1\n0\n2"]
NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
c212524cc1ad8e0332693e3cf644854b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.
900
For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.
standard output
PASSED
62dfd62ad89709001afcf7986f02ce5d
train_110.jsonl
1621152000
You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.
256 megabytes
import java.util.*; public class cf1525B{ public static void main(String[] args) { Scanner scan = new Scanner(System.in); int n = scan.nextInt(); int ans = 0; for(int i = 0;i<n;i++){ int length = scan.nextInt(); int[] arr = new int[length]; int[] sorted = new int[length]; for(int j=0;j<length;j++){ int num = scan.nextInt(); arr[j] = num; sorted[j] = num; } Arrays.sort(sorted); int min = sorted[0]; int minIndex = 0; int maxIndex = 0; int max = sorted[length-1]; if(Arrays.equals(sorted, arr)){ System.out.println(0); }else { for (int j = 0; j < length; j++) { if (arr[j] == min) { minIndex = j; } else if (arr[j] == max) { maxIndex = j; } } if (minIndex == 0 || maxIndex == length - 1) { ans = 1; }else if(minIndex == length-1 && maxIndex == 0){ ans = 3; }else{ ans = 2; } System.out.println(ans); } } } }
Java
["3\n4\n1 3 2 4\n3\n1 2 3\n5\n2 1 4 5 3"]
2 seconds
["1\n0\n2"]
NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
c212524cc1ad8e0332693e3cf644854b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.
900
For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.
standard output
PASSED
9b9dfe274540a59dd8d7463549be48a4
train_110.jsonl
1621152000
You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.
256 megabytes
import java.util.*; public class Project { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int n = scan.nextInt(); int ans = 0; for(int i = 0;i<n;i++){ int length = scan.nextInt(); int[] arr = new int[length]; int[] sorted = new int[length]; for(int j=0;j<length;j++){ int num = scan.nextInt(); arr[j] = num; sorted[j] = num; } Arrays.sort(sorted); int min = sorted[0]; int minIndex = 0; int maxIndex = 0; int max = sorted[length-1]; if(Arrays.equals(sorted, arr)){ System.out.println(0); }else { for (int j = 0; j < length; j++) { if (arr[j] == min) { minIndex = j; } else if (arr[j] == max) { maxIndex = j; } } if (minIndex == 0 || maxIndex == length - 1) { ans = 1; }else if(minIndex == length-1 && maxIndex == 0){ ans = 3; }else{ ans = 2; } System.out.println(ans); } } } }
Java
["3\n4\n1 3 2 4\n3\n1 2 3\n5\n2 1 4 5 3"]
2 seconds
["1\n0\n2"]
NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
c212524cc1ad8e0332693e3cf644854b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.
900
For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.
standard output
PASSED
0aad05f2b4539669b050ced5ba962465
train_110.jsonl
1621152000
You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.
256 megabytes
import java.util.Scanner; public class PermutationSort { public static void main(String[] args) { Scanner iScanner = new Scanner(System.in); int test = iScanner.nextInt(); while(test>0){ test--; int n = iScanner.nextInt(); int[] arr = new int[n]; for(int i=0;i<n;i++){ arr[i] = iScanner.nextInt(); } boolean check = true; if(arr[0]==1) check = false; if(arr[arr.length-1] == arr.length) check = false; boolean dobleCheck = true; boolean isReverse = true; if(arr[0] == n && arr[n-1]==1) isReverse = false; for(int i=1;i<=n;i++){ if(arr[i-1]!=i) dobleCheck = false; } if(dobleCheck==true) System.out.println(0); else if(isReverse==false) System.out.println(3); else if(dobleCheck==false && check == false) System.out.println(1); else System.out.println(2); } } }
Java
["3\n4\n1 3 2 4\n3\n1 2 3\n5\n2 1 4 5 3"]
2 seconds
["1\n0\n2"]
NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
c212524cc1ad8e0332693e3cf644854b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.
900
For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.
standard output
PASSED
31804f9ce460e6bd4e7e4da120712b9e
train_110.jsonl
1621152000
You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; import static java.lang.System.currentTimeMillis; /* * @author: Hivilsm * @createTime: 2022-04-27, 23:29:16 * @description: Platform */ public class Accepted { static FastReader in = new FastReader(); static PrintWriter out = new PrintWriter(System.out); static Random rand = new Random(); static int[][] DIRS = new int[][]{{0, 1}, {0, -1}, {1, 0}, {-1, 0}}; static int MAX = (int)1e9 + 7; public static void main(String[] args) { // long start = currentTimeMillis(); // int t = 3; int t = i(); // out.println(); // out.println(); // out.println(); while (t-- > 0){ sol(); // out.println(sol()); // int[] ans = sol(); // for (int i : ans){ // out.print(i + " "); // } // out.println(); // boolean ans = sol(); // if (ans){ // out.println("YES"); // }else{ // out.println("NO"); // } } // long end = currentTimeMillis(); // out.println(end - start); out.flush(); out.close(); } static void sol() { int n = i(); int[] arr = inputI(n); if (arr[0] == n && arr[n - 1] == 1){ out.println(3); return ; } int ans = 0; for (int i = 1; i <= n; i++){ if (arr[i - 1] != i){ ans++; } } if (ans == 0){ out.println(0); }else if (arr[0] != 1 && arr[n - 1] != n){ out.println(2); }else if (arr[0] == 1 || arr[n - 1] == n){ out.println(1); } } static boolean check(int x, int y, int n, int m){ return x >= 0 && y >= 0 && x < n && y < m; } static void shuffle(int[] nums, int n){ for(int i = 0; i < n; i++){ int cur = rand.nextInt(n); swap(nums, i, cur); } } static void swap(int[] nums, int l, int r){ int tmp = nums[l]; nums[l] = nums[r]; nums[r] = tmp; } static void ranArr() { int n = 3, len = 10, val = 10; System.out.println(n); for (int i = 0; i < n; i++) { int cnt = rand.nextInt(len) + 1; System.out.println(cnt); for (int j = 0; j < cnt; j++) { System.out.print(rand.nextInt(val) + " "); } System.out.println(); } } static double fastPower(double x, int n) { if (x == 0) return 0; long b = n; double res = 1.0; if (b < 0) { x = 1 / x; b = -b; } while (b > 0) { if ((b & 1) == 1) res *= x; x *= x; b >>= 1; } return res; } static int i() { return in.nextInt(); } static long l() { return in.nextLong(); } static double d() { return in.nextDouble(); } static String s() { return in.nextLine(); } static int[] inputI(int n) { int nums[] = new int[n]; for (int i = 0; i < n; i++) { nums[i] = in.nextInt(); } return nums; } static long[] inputLong(int n) { long nums[] = new long[n]; for (int i = 0; i < n; i++) { nums[i] = in.nextLong(); } return nums; } } class ListNode { int val; ListNode next; public ListNode() { } public ListNode(int val) { this.val = val; } } class TreeNode { int val; TreeNode left; TreeNode right; public TreeNode() { } public TreeNode(int val) { this.val = val; } } class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } }
Java
["3\n4\n1 3 2 4\n3\n1 2 3\n5\n2 1 4 5 3"]
2 seconds
["1\n0\n2"]
NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
c212524cc1ad8e0332693e3cf644854b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.
900
For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.
standard output
PASSED
9488e9f20b285c975a888908b0087aec
train_110.jsonl
1621152000
You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; public class Test { public static void main(String[] args) throws IOException { Reader rd = new Reader(); int t = rd.nextInt(); while (t-- > 0) { int n = rd.nextInt(); int[] a = new int[n]; int[] b = new int[n]; for (int i = 0; i < n; i++) { a[i] = rd.nextInt(); b[i] = a[i]; } Arrays.sort(b); if (Arrays.equals(a, b)) System.out.println(0); else if (a[0] == b[n - 1] && a[n - 1] == b[0]) System.out.println(3); else if (a[0] != b[0] && a[n - 1] != b[n - 1]) System.out.println(2); else System.out.println(1); } rd.close(); } private static boolean isArraySorted(int n, int[] arr) { for (int i = 0; i < n - 1; i++) { if (arr[i] > arr[i + 1]) { return false; } } return true; } private static void debug(int value) { if (System.getProperty("ONLINE_JUDGE") == null) { System.out.println("int value = " + value); } } private static void debug(int value, String message) { if (System.getProperty("ONLINE_JUDGE") == null) { if (message.charAt(message.length() - 1) != ' ') message += " "; System.out.println(message + "" + value); } } static class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') { if (cnt != 0) { break; } else { continue; } } buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') { c = read(); } boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } }
Java
["3\n4\n1 3 2 4\n3\n1 2 3\n5\n2 1 4 5 3"]
2 seconds
["1\n0\n2"]
NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
c212524cc1ad8e0332693e3cf644854b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.
900
For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.
standard output
PASSED
1b7ae5f41868f86654fce0d3837e8039
train_110.jsonl
1621152000
You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.
256 megabytes
//CP- MASS_2701 import java.util.*; import java.io.*; public class B_Permutation_Sort { static FastReader in=new FastReader(); static final Random random=new Random(); static long mod=1000000007L; static HashMap<String,Integer>map=new HashMap<>(); public static void main(String args[]) throws IOException { int t=in.nextInt(); int cse=1; loop: while(t-->0) { StringBuilder res=new StringBuilder(); //res.append("Hello"+"\n"); int n=in.nextInt(); ArrayList<Integer> al=new ArrayList<>(); ArrayList<Integer> al_copy=new ArrayList<>(); for(int i=0;i<n;i++) { al.add(in.nextInt()); al_copy.add(al.get(i)); } Collections.sort(al_copy); if(al_copy.equals(al)) { println(0); continue; } Collections.reverse(al_copy); if(al_copy.equals(al) || ((int)al.get(0)==(int)al_copy.get(0) && (int)al.get(n-1)==(int)al_copy.get(n-1))) { res.append(3); } else{ Collections.reverse(al_copy); ArrayList<Integer> sec=new ArrayList<>(); ArrayList<Integer> one=new ArrayList<>(); for(int i=0;i<n;i++) { one.add(al.get(i)); } for(int i=0;i<n;i++) { sec.add(al.get(i)); } one.remove(al.size()-1); sec.remove(0); Collections.sort(one); Collections.sort(sec); one.add(al.get(n-1)); sec.add(0,al.get(0)); if(al_copy.equals(one) || al_copy.equals(sec)) { res.append(1); } else{ res.append(2); } } println(res); } } static int max(int a, int b) { if(a<b) return b; return a; } 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 < E > void print(E res) { System.out.print(res); } static < E > void println(E res) { System.out.println(res); } static int gcd(int a,int b) { if(b==0) { return a; } return gcd(b,a%b); } static int lcm(int a, int b) { return (a / gcd(a, b)) * b; } static int abs(int a) { if(a<0) return -1*a; return a; } static boolean isPrime(int n) { // Corner cases if (n <= 1) return false; if (n <= 3) return true; // This is checked so that we can skip // middle five numbers in below loop if (n % 2 == 0 || n % 3 == 0) return false; for (int i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } static 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; } int [] readintarray(int n) { int res [] = new int [n]; for(int i = 0; i<n; i++)res[i] = nextInt(); return res; } long [] readlongarray(int n) { long res [] = new long [n]; for(int i = 0; i<n; i++)res[i] = nextLong(); return res; } } }
Java
["3\n4\n1 3 2 4\n3\n1 2 3\n5\n2 1 4 5 3"]
2 seconds
["1\n0\n2"]
NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
c212524cc1ad8e0332693e3cf644854b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.
900
For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.
standard output
PASSED
8f8ebd1016cf03612cc84914a509b9c8
train_110.jsonl
1621152000
You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.
256 megabytes
/* 3 1 2 3 3 1 3 2 3 2 1 3 3 2 3 1 3 3 1 2 3 3 2 1 4 1 2 3 4 4 1 2 4 3 4 1 3 2 4 4 1 3 4 2 4 1 4 2 3 4 1 4 3 2 4 2 1 3 4 4 2 1 4 3 4 2 3 1 4 4 2 3 4 1 4 2 4 1 3 4 2 4 3 1 4 3 1 2 4 4 3 1 4 2 4 3 2 1 4 4 3 2 4 1 4 3 4 1 2 4 3 4 2 1 4 4 1 2 3 4 4 1 3 2 4 4 2 1 3 4 4 2 3 1 4 4 3 1 2 4 4 3 2 1 5 1 2 3 4 5 5 1 2 3 5 4 5 1 2 4 3 5 5 1 2 4 5 3 5 1 2 5 3 4 5 1 2 5 4 3 5 1 3 2 4 5 5 1 3 2 5 4 5 1 3 4 2 5 5 1 3 4 5 2 5 1 3 5 2 4 5 */ import java.util.*; import java.io.*; public class Main { static FastScanner sc = new FastScanner(); public static void solve() throws IOException { int n = sc.nextInt(); int[] arr = new int[n]; boolean flag = true; for(int i = 0; i < n; ++i) { arr[i] = sc.nextInt(); } for(int i = 0; i < n; ++i) { if(arr[i] != (i + 1)) { flag = false; break; } } if(flag) { sc.out("0"); } else { if((arr[0] == 1 && arr[n - 1] == n) || (arr[0] != 1 && arr[n - 1] == n) || (arr[0] == 1 && arr[n - 1] != n)) { sc.out("1"); } else { int[] temp = Arrays.copyOf(arr, n); sort(arr, 0, n - 2); sort(arr, 1, n - 1); // sort(arr, 1, n - 1); // sort(arr, 0, n - 2); sort(temp, 1, n - 1); sort(temp, 0, n - 2); // sc.out(Arrays.toString(arr)+"\n"); // sc.out(Arrays.toString(temp)+"\n"); flag = true; boolean flag2 = true; for(int i = 1; i <= n; ++i) { if(arr[i - 1] != i) { flag = false; } if (temp[i - 1] != i) { flag2 = false; } } if(flag || flag2) { sc.out("2"); } else { sc.out("3"); } } } sc.out("\n"); } public static void main(String[] args) throws IOException { int tt = 1; tt = sc.nextInt(); for(int t = 0; t < tt; ++t) { solve(); } } public static void sort(int[] arr, int start, int end) { if(start < end) { int mid = (start + end) / 2; sort(arr, start, mid); sort(arr, mid + 1, end); merge(arr, start, mid, end); } } public static void merge(int arr[], int start, int mid, int end) { int p = start, q = mid + 1, k = 0; int[] newArr = new int[end - start + 1]; for(int i = start; i <= end; ++i) { if(p > mid) { newArr[k++] = arr[q++]; } else if(q > end) { newArr[k++] = arr[p++]; } else if(arr[p] < arr[q]) { newArr[k++] = arr[p++]; } else { newArr[k++] = arr[q++]; } } for(int i = 0; i < k; ++i, ++start) { arr[start] = newArr[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) {} return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } public static void out(String n) throws IOException { System.out.print(n); } } }
Java
["3\n4\n1 3 2 4\n3\n1 2 3\n5\n2 1 4 5 3"]
2 seconds
["1\n0\n2"]
NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
c212524cc1ad8e0332693e3cf644854b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.
900
For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.
standard output
PASSED
8aaaf03c4f20499dd0ee9b1a6f5fde3c
train_110.jsonl
1621152000
You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.
256 megabytes
import java.io.PrintWriter; import java.util.*; public class codeforces2 { public static int abs(int x) { if(x<0)return -x; return x; } public static int gcd(int a,int b) { if(b==0)return a; return gcd(b,a%b); } public static void display(char[][]x) { for(int i=0;i<x.length;i++) { for(int j=0;j<x[i].length;j++) { System.out.print(x[i][j]+" "); } System.out.println(); } } public static boolean allEqual(int[] arr) { for(int i=0;i<arr.length-1;i++) { if(arr[i]!=arr[i+1])return false; } return true; } public static boolean isSorted(int[] x) { for(int i=0;i<x.length-1;i++) { if(x[i]>x[i+1])return false; } return true; } /*public static QueueObj multCons(QueueObj x) { QueueObj t1=new QueueObj(x.size()-1); QueueObj t2=new QueueObj(x.size()); int s=x.size(); for(int i=0;i<s-1;i++) { int n=(int)x.dequeue(); t2.enqueue(n); t1.enqueue(n*(int)(x.peek())); x.enqueue(n); //t1.printQueue(); } //while(!t2.isEmpty())x.enqueue(t2.dequeue()); x.enqueue(x.dequeue()); return t1; }*/ /*public static boolean num(QueueObj x,char c,int n) { int s=x.size(); int t=0; for(int i=0;i<s;i++) { char w=(char)x.dequeue(); if(w==c)t++; x.enqueue(w); } if(t==n)return true; else return false; }*/ public static void main(String[] args) { Scanner sc=new Scanner(System.in); PrintWriter pw = new PrintWriter(System.out); int t=sc.nextInt(); while(t-->0) { int n=sc.nextInt(); int[] x=new int[n]; boolean r1=true; boolean r2=true; int st=0; for(int i=0;i<n;i++) { x[i]=sc.nextInt(); if(x[i]<st) { r1=false; } //if(st!=0&&x[i]>st)r2=false; st=x[i]; } if(r1)pw.println(0); else { if(x[0]==n&&x[n-1]==1)pw.println(3); else { if(x[0]==1||x[n-1]==n)pw.println(1); else pw.println(2); } } } pw.flush(); } }
Java
["3\n4\n1 3 2 4\n3\n1 2 3\n5\n2 1 4 5 3"]
2 seconds
["1\n0\n2"]
NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
c212524cc1ad8e0332693e3cf644854b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.
900
For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.
standard output
PASSED
bb4468336ab8960c98c013d79cf8dfdb
train_110.jsonl
1621152000
You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Arrays; import java.util.StringTokenizer; import static java.lang.System.out; public class Round109Div2B { public static void main(String[] args) 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); int res = solution(arr, N); sb.append(res + "\n"); } out.println(sb); //BufferedReader infile = new BufferedReader(new FileReader("input.txt")); //System.setOut(new PrintStream(new File("output.txt"))); } private static int solution(int[] arr, int n) { boolean isSorted = true; for (int i = 0; i < n - 1; i++) { if(arr[i] > arr[i+1]){ isSorted = false; } } if(isSorted){ return 0; } if(arr[0] == 1 || arr[n-1] == n){ return 1; } else if(arr[0] == n && arr[n-1] == 1){ return 3; } else return 2; } 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; } public static void print(int[] arr) { //for debugging only for(int x: arr) out.print(x+" "); out.println(); } public static long[] readArr2(int N, BufferedReader infile, StringTokenizer st) throws Exception { long[] arr = new long[N]; st = new StringTokenizer(infile.readLine()); for(int i=0; i < N; i++) arr[i] = Long.parseLong(st.nextToken()); return arr; } public static boolean isPrime(long n) { if(n < 2) return false; if(n == 2 || n == 3) return true; if(n%2 == 0 || n%3 == 0) return false; long sqrtN = (long)Math.sqrt(n)+1; for(long i = 6L; i <= sqrtN; i += 6) { if(n%(i-1) == 0 || n%(i+1) == 0) return false; } return true; } 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 int lcm(int a, int b) { return (a * b) / lcm(a, b); } public static String sort(String s){ char[] c = s.toCharArray(); Arrays.sort(c); return new String(c); } static String deleteIth(String str, int i) { str = str.substring(0, i) + str.substring(i + 1); return str; } }
Java
["3\n4\n1 3 2 4\n3\n1 2 3\n5\n2 1 4 5 3"]
2 seconds
["1\n0\n2"]
NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
c212524cc1ad8e0332693e3cf644854b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.
900
For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.
standard output
PASSED
5157b11b4ac805a0a23b2a90d1e6c94d
train_110.jsonl
1621152000
You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.
256 megabytes
import java.util.*; import java.io.*; public class Test { static class Scan { private byte[] buf=new byte[1024]; private int index; private InputStream in; private int total; public Scan() { in=System.in; } public int scan()throws IOException { if(total<0) throw new InputMismatchException(); if(index>=total) { index=0; total=in.read(buf); if(total<=0) return -1; } return buf[index++]; } public int scanInt()throws IOException { int integer=0; int n=scan(); while(isWhiteSpace(n)) n=scan(); int neg=1; if(n=='-') { neg=-1; n=scan(); } while(!isWhiteSpace(n)) { if(n>='0'&&n<='9') { integer*=10; integer+=n-'0'; n=scan(); } else throw new InputMismatchException(); } return neg*integer; } public double scanDouble()throws IOException { double doub=0; int n=scan(); while(isWhiteSpace(n)) n=scan(); int neg=1; if(n=='-') { neg=-1; n=scan(); } while(!isWhiteSpace(n)&&n!='.') { if(n>='0'&&n<='9') { doub*=10; doub+=n-'0'; n=scan(); } else throw new InputMismatchException(); } if(n=='.') { n=scan(); double temp=1; while(!isWhiteSpace(n)) { if(n>='0'&&n<='9') { temp/=10; doub+=(n-'0')*temp; n=scan(); } else throw new InputMismatchException(); } } return doub*neg; } public String scanString()throws IOException { StringBuilder sb=new StringBuilder(); int n=scan(); while(isWhiteSpace(n)) n=scan(); while(!isWhiteSpace(n)) { sb.append((char)n); n=scan(); } return sb.toString(); } private boolean isWhiteSpace(int n) { if(n==' '||n=='\n'||n=='\r'||n=='\t'||n==-1) return true; return false; } } static class Print { private final BufferedWriter bw; public Print() { this.bw=new BufferedWriter(new OutputStreamWriter(System.out)); } public void print(Object object)throws IOException { bw.append(""+object); } public void println(Object object)throws IOException { print(object); bw.append("\n"); } public void close()throws IOException { bw.close(); } } public static void main(String[] args) throws IOException{ Scan scan = new Scan(); Print print = new Print(); int testcases = scan.scanInt(); while(testcases-->0){ int n = scan.scanInt(); int array[] = new int[n]; HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); boolean sorted = true; for(int i=0; i<n; i++){ array[i] = scan.scanInt(); map.put(array[i], i+1); if(array[i] != i+1 && sorted){ sorted = false; } } if(sorted){ print.println(0); } else if(map.get(1) == 1 || map.get(n) == n){ print.println(1); } else if(map.get(1)==n && map.get(n) == 1){ print.println(3); } else print.println(2); } print.close(); } public static int gcd(int a, int b){ if(b == 0){ return a; } else{ return gcd(b, a%b); } } }
Java
["3\n4\n1 3 2 4\n3\n1 2 3\n5\n2 1 4 5 3"]
2 seconds
["1\n0\n2"]
NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
c212524cc1ad8e0332693e3cf644854b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.
900
For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.
standard output
PASSED
85bc2c759694051ae51831bdefcd6f44
train_110.jsonl
1621152000
You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.
256 megabytes
import java.util.*; public class PermutationSort { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int t=sc.nextInt(); while(t-- > 0){ int n=sc.nextInt(); int[] arr=new int[n]; for(int i=0;i<n;i++) arr[i]=sc.nextInt(); int result = solve(n,arr); System.out.println(result); } sc.close(); } public static int solve(int n,int[] arr){ boolean sorted=true; for(int i=0;i<n;i++) { if(arr[i]!=(i+1)){ sorted=false; } } if(sorted)return 0; if(arr[0]==1 || arr[n-1]==n)return 1; if(arr[0]==n && arr[n-1]==1)return 3; return 2; } }
Java
["3\n4\n1 3 2 4\n3\n1 2 3\n5\n2 1 4 5 3"]
2 seconds
["1\n0\n2"]
NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
c212524cc1ad8e0332693e3cf644854b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.
900
For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.
standard output
PASSED
c45d56fdd5bacd739beb62215b86556a
train_110.jsonl
1621152000
You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.
256 megabytes
//package firstjava; import java.util.Scanner; public class tamim { public static void main(String[] args) { try(Scanner cin = new Scanner(System.in)){ int t=cin.nextInt(); for(int i=1;i<=t;i++) { int n=cin.nextInt(); int v[]=new int[55]; int j; for(j=0;j<n;j++) { v[j]=cin.nextInt(); } int ans=0; if(v[n-1]==1) { ans+=2; if(v[0]==n) { ++ans; } } else if(v[0]==1) { for(j=1;j<n;j++) { if(v[j]!=j+1) { ++ans; break; } } } else { ++ans; if(v[n-1]!=n) { ++ans; } } System.out.println(ans); } } } }
Java
["3\n4\n1 3 2 4\n3\n1 2 3\n5\n2 1 4 5 3"]
2 seconds
["1\n0\n2"]
NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
c212524cc1ad8e0332693e3cf644854b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.
900
For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.
standard output
PASSED
8f2cac7427eb48c2de62a9f3f6ec6c46
train_110.jsonl
1621152000
You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.
256 megabytes
//package Justtt; import java.util.*; public class Try { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int t=sc.nextInt(); Solution s=new Solution(); while(t--!=0) { int n=sc.nextInt(); int a[]=new int[n]; for(int i=0;i<n;i++) a[i]=sc.nextInt(); System.out.println(s.solve(n,a)); } } } class Solution { public int solve(int n,int a[]) { int count=0; if(a[0]==n&&a[n-1]==1) return 3; if(a[n-1]!=n&&a[0]!=1) return 2; else if(sorted(a)) return 0; return 1; } public boolean sorted(int a[]) { for(int i=1;i<a.length;i++) { if(a[i-1]>a[i]) return false; } return true; } }
Java
["3\n4\n1 3 2 4\n3\n1 2 3\n5\n2 1 4 5 3"]
2 seconds
["1\n0\n2"]
NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
c212524cc1ad8e0332693e3cf644854b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.
900
For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.
standard output
PASSED
12a52f5a402da47b0a744e4df0f19c8f
train_110.jsonl
1621152000
You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.
256 megabytes
import java.io.*;import java.util.*;import java.math.*; public class B { public void tq()throws Exception { st=new StringTokenizer(bq.readLine()); int tq=i(); sb=new StringBuilder(1000000); o: while(tq-->0) { int n =i() ; int[] a = ari(n) ; boolean flag = true ; for (int i = 0; i < n-1; i++) { if(a[i]>a[i+1])flag=false ; } if(flag)sl(0) ; else { int mn = Arrays.stream(a).min().getAsInt() ; int mx = Arrays.stream(a).max().getAsInt() ; if(a[n-1]==mn && a[0]==mx)sl(3) ; else if(a[0]==mn || a[n-1]==mx)sl(1) ; else sl(2) ; } } p(sb); } long mod=1000000007l;int max=Integer.MAX_VALUE,min=Integer.MIN_VALUE; long maxl=Long.MAX_VALUE,minl=Long.MIN_VALUE; BufferedReader bq=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st;StringBuilder sb; public static void main(String[] a)throws Exception{new B().tq();} int[] so(int ar[]){Integer r[]=new Integer[ar.length];for(int x=0;x<ar.length;x++)r[x]=ar[x]; Arrays.sort(r);for(int x=0;x<ar.length;x++)ar[x]=r[x];return ar;} long[] so(long ar[]){Long r[]=new Long[ar.length];for(int x=0;x<ar.length;x++)r[x]=ar[x]; Arrays.sort(r);for(int x=0;x<ar.length;x++)ar[x]=r[x];return ar;} char[] so(char ar[]) {Character r[]=new Character[ar.length];for(int x=0;x<ar.length;x++)r[x]=ar[x]; Arrays.sort(r);for(int x=0;x<ar.length;x++)ar[x]=r[x];return ar;} void s(String s){sb.append(s);}void s(int s){sb.append(s);}void s(long s){sb.append(s);} void s(char s){sb.append(s);}void s(double s){sb.append(s);} void ss(){sb.append(' ');}void sl(String s){sb.append(s);sb.append("\n");} void sl(int s){sb.append(s);sb.append("\n");} void sl(long s){sb.append(s);sb.append("\n");}void sl(char s){sb.append(s);sb.append("\n");} void sl(double s){sb.append(s);sb.append("\n");}void sl(){sb.append("\n");} int l(int v){return 31-Integer.numberOfLeadingZeros(v);} long l(long v){return 63-Long.numberOfLeadingZeros(v);} int min(int a,int b){return a<b?a:b;} int min(int a,int b,int c){return a<b?a<c?a:c:b<c?b:c;} int max(int a,int b){return a>b?a:b;} int max(int a,int b,int c){return a>b?a>c?a:c:b>c?b:c;} long min(long a,long b){return a<b?a:b;} long min(long a,long b,long c){return a<b?a<c?a:c:b<c?b:c;} long max(long a,long b){return a>b?a:b;} long max(long a,long b,long c){return a>b?a>c?a:c:b>c?b:c;} int abs(int a){return Math.abs(a);} long abs(long a){return Math.abs(a);} int sq(int a){return (int)Math.sqrt(a);}long sq(long a){return (long)Math.sqrt(a);} long gcd(long a,long b){while(b>0l){long c=a%b;a=b;b=c;}return a;} int gcd(int a,int b){while(b>0){int c=a%b;a=b;b=c;}return a;} boolean pa(String s,int i,int j){while(i<j)if(s.charAt(i++)!=s.charAt(j--))return false;return true;} boolean[] si(int n) {boolean bo[]=new boolean[n+1];bo[0]=true;bo[1]=true;for(int x=4;x<=n;x+=2)bo[x]=true; for(int x=3;x*x<=n;x+=2){if(!bo[x]){int vv=(x<<1);for(int y=x*x;y<=n;y+=vv)bo[y]=true;}} return bo;}long mul(long a,long b,long m) {long r=1l;a%=m;while(b>0){if((b&1)==1)r=(r*a)%m;b>>=1;a=(a*a)%m;}return r;} int i()throws IOException{if(!st.hasMoreTokens())st=new StringTokenizer(bq.readLine()); return Integer.parseInt(st.nextToken());} long l()throws IOException{if(!st.hasMoreTokens())st=new StringTokenizer(bq.readLine()); return Long.parseLong(st.nextToken());}String s()throws IOException {if(!st.hasMoreTokens())st=new StringTokenizer(bq.readLine());return st.nextToken();} double d()throws IOException{if(!st.hasMoreTokens())st=new StringTokenizer(bq.readLine()); return Double.parseDouble(st.nextToken());}void p(Object p){System.out.print(p);} void p(String p){System.out.print(p);}void p(int p){System.out.print(p);} void p(double p){System.out.print(p);}void p(long p){System.out.print(p);} void p(char p){System.out.print(p);}void p(boolean p){System.out.print(p);} void pl(Object p){System.out.println(p);}void pl(String p){System.out.println(p);} void pl(int p){System.out.println(p);}void pl(char p){System.out.println(p);} void pl(double p){System.out.println(p);}void pl(long p){System.out.println(p);} void pl(boolean p){System.out.println(p);}void pl(){System.out.println();} void s(int a[]){for(int e:a){sb.append(e);sb.append(' ');}sb.append("\n");} void s(long a[]){for(long e:a){sb.append(e);sb.append(' ');}sb.append("\n");} void s(int ar[][]){for(int a[]:ar){for(int e:a){sb.append(e);sb.append(' ');}sb.append("\n");}} void s(char a[]){for(char e:a){sb.append(e);sb.append(' ');}sb.append("\n");} void s(char ar[][]){for(char a[]:ar){for(char e:a){sb.append(e);sb.append(' ');}sb.append("\n");}} int[] ari(int n)throws IOException {int ar[]=new int[n];if(!st.hasMoreTokens())st=new StringTokenizer(bq.readLine()); for(int x=0;x<n;x++)ar[x]=Integer.parseInt(st.nextToken());return ar;} int[][] ari(int n,int m)throws IOException {int ar[][]=new int[n][m];for(int x=0;x<n;x++){if(!st.hasMoreTokens())st=new StringTokenizer(bq.readLine()); for(int y=0;y<m;y++)ar[x][y]=Integer.parseInt(st.nextToken());}return ar;} long[] arl(int n)throws IOException {long ar[]=new long[n];if(!st.hasMoreTokens())st=new StringTokenizer(bq.readLine()); for(int x=0;x<n;x++) ar[x]=Long.parseLong(st.nextToken());return ar;} long[][] arl(int n,int m)throws IOException {long ar[][]=new long[n][m];for(int x=0;x<n;x++) {if(!st.hasMoreTokens())st=new StringTokenizer(bq.readLine()); for(int y=0;y<m;y++)ar[x][y]=Long.parseLong(st.nextToken());}return ar;} String[] ars(int n)throws IOException {String ar[]=new String[n];if(!st.hasMoreTokens())st=new StringTokenizer(bq.readLine()); for(int x=0;x<n;x++) ar[x]=st.nextToken();return ar;} double[] ard(int n)throws IOException {double ar[]=new double[n];if(!st.hasMoreTokens())st=new StringTokenizer(bq.readLine()); for(int x=0;x<n;x++)ar[x]=Double.parseDouble(st.nextToken());return ar;} double[][] ard(int n,int m)throws IOException {double ar[][]=new double[n][m];for(int x=0;x<n;x++) {if(!st.hasMoreTokens())st=new StringTokenizer(bq.readLine()); for(int y=0;y<m;y++)ar[x][y]=Double.parseDouble(st.nextToken());}return ar;} char[] arc(int n)throws IOException{char ar[]=new char[n];if(!st.hasMoreTokens())st=new StringTokenizer(bq.readLine()); for(int x=0;x<n;x++)ar[x]=st.nextToken().charAt(0);return ar;} char[][] arc(int n,int m)throws IOException{char ar[][]=new char[n][m]; for(int x=0;x<n;x++){String s=bq.readLine();for(int y=0;y<m;y++)ar[x][y]=s.charAt(y);}return ar;} void p(int ar[]){StringBuilder sb=new StringBuilder(2*ar.length); for(int a:ar){sb.append(a);sb.append(' ');}System.out.println(sb);} void p(int ar[][]){StringBuilder sb=new StringBuilder(2*ar.length*ar[0].length); for(int a[]:ar){for(int aa:a){sb.append(aa);sb.append(' ');}sb.append("\n");}p(sb);} void p(long ar[]){StringBuilder sb=new StringBuilder(2*ar.length); for(long a:ar){sb.append(a);sb.append(' ');}System.out.println(sb);} void p(long ar[][]){StringBuilder sb=new StringBuilder(2*ar.length*ar[0].length); for(long a[]:ar){for(long aa:a){sb.append(aa);sb.append(' ');}sb.append("\n");}p(sb);} void p(String ar[]){int c=0;for(String s:ar)c+=s.length()+1;StringBuilder sb=new StringBuilder(c); for(String a:ar){sb.append(a);sb.append(' ');}System.out.println(sb);} void p(double ar[]){StringBuilder sb=new StringBuilder(2*ar.length); for(double a:ar){sb.append(a);sb.append(' ');}System.out.println(sb);} void p(double ar[][]){StringBuilder sb=new StringBuilder(2*ar.length*ar[0].length); for(double a[]:ar){for(double aa:a){sb.append(aa);sb.append(' ');}sb.append("\n");}p(sb);} void p(char ar[]){StringBuilder sb=new StringBuilder(2*ar.length); for(char aa:ar){sb.append(aa);sb.append(' ');}System.out.println(sb);} void p(char ar[][]){StringBuilder sb=new StringBuilder(2*ar.length*ar[0].length); for(char a[]:ar){for(char aa:a){sb.append(aa);sb.append(' ');}sb.append("\n");}p(sb);} }
Java
["3\n4\n1 3 2 4\n3\n1 2 3\n5\n2 1 4 5 3"]
2 seconds
["1\n0\n2"]
NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
c212524cc1ad8e0332693e3cf644854b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.
900
For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.
standard output
PASSED
1e15a3d8a1eb3992d947cae031e5a02a
train_110.jsonl
1621152000
You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.
256 megabytes
import java.io.*;import java.util.*;import java.math.*; public class B { public void tq()throws Exception { st=new StringTokenizer(bq.readLine()); int tq=i(); sb=new StringBuilder(1000000); o: while(tq-->0) { int n =i() ; int[] a = ari(n) ; boolean flag = true ; for (int i = 0; i < n-1; i++) { if(a[i]>a[i+1])flag=false ; } if(flag)sl(0) ; else { int mn = max ; for(int i=0;i<n;i++){ if(a[i]<mn)mn=a[i] ; } int mx = min ; for(int i=0;i<n;i++){ if(a[i]>mx)mx=a[i] ; } if(a[n-1]==mn && a[0]==mx)sl(3) ; else if(a[0]==mn || a[n-1]==mx)sl(1) ; else sl(2) ; } } p(sb); } long mod=1000000007l;int max=Integer.MAX_VALUE,min=Integer.MIN_VALUE; long maxl=Long.MAX_VALUE,minl=Long.MIN_VALUE; BufferedReader bq=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st;StringBuilder sb; public static void main(String[] a)throws Exception{new B().tq();} int[] so(int ar[]){Integer r[]=new Integer[ar.length];for(int x=0;x<ar.length;x++)r[x]=ar[x]; Arrays.sort(r);for(int x=0;x<ar.length;x++)ar[x]=r[x];return ar;} long[] so(long ar[]){Long r[]=new Long[ar.length];for(int x=0;x<ar.length;x++)r[x]=ar[x]; Arrays.sort(r);for(int x=0;x<ar.length;x++)ar[x]=r[x];return ar;} char[] so(char ar[]) {Character r[]=new Character[ar.length];for(int x=0;x<ar.length;x++)r[x]=ar[x]; Arrays.sort(r);for(int x=0;x<ar.length;x++)ar[x]=r[x];return ar;} void s(String s){sb.append(s);}void s(int s){sb.append(s);}void s(long s){sb.append(s);} void s(char s){sb.append(s);}void s(double s){sb.append(s);} void ss(){sb.append(' ');}void sl(String s){sb.append(s);sb.append("\n");} void sl(int s){sb.append(s);sb.append("\n");} void sl(long s){sb.append(s);sb.append("\n");}void sl(char s){sb.append(s);sb.append("\n");} void sl(double s){sb.append(s);sb.append("\n");}void sl(){sb.append("\n");} int l(int v){return 31-Integer.numberOfLeadingZeros(v);} long l(long v){return 63-Long.numberOfLeadingZeros(v);} int min(int a,int b){return a<b?a:b;} int min(int a,int b,int c){return a<b?a<c?a:c:b<c?b:c;} int max(int a,int b){return a>b?a:b;} int max(int a,int b,int c){return a>b?a>c?a:c:b>c?b:c;} long min(long a,long b){return a<b?a:b;} long min(long a,long b,long c){return a<b?a<c?a:c:b<c?b:c;} long max(long a,long b){return a>b?a:b;} long max(long a,long b,long c){return a>b?a>c?a:c:b>c?b:c;} int abs(int a){return Math.abs(a);} long abs(long a){return Math.abs(a);} int sq(int a){return (int)Math.sqrt(a);}long sq(long a){return (long)Math.sqrt(a);} long gcd(long a,long b){while(b>0l){long c=a%b;a=b;b=c;}return a;} int gcd(int a,int b){while(b>0){int c=a%b;a=b;b=c;}return a;} boolean pa(String s,int i,int j){while(i<j)if(s.charAt(i++)!=s.charAt(j--))return false;return true;} boolean[] si(int n) {boolean bo[]=new boolean[n+1];bo[0]=true;bo[1]=true;for(int x=4;x<=n;x+=2)bo[x]=true; for(int x=3;x*x<=n;x+=2){if(!bo[x]){int vv=(x<<1);for(int y=x*x;y<=n;y+=vv)bo[y]=true;}} return bo;}long mul(long a,long b,long m) {long r=1l;a%=m;while(b>0){if((b&1)==1)r=(r*a)%m;b>>=1;a=(a*a)%m;}return r;} int i()throws IOException{if(!st.hasMoreTokens())st=new StringTokenizer(bq.readLine()); return Integer.parseInt(st.nextToken());} long l()throws IOException{if(!st.hasMoreTokens())st=new StringTokenizer(bq.readLine()); return Long.parseLong(st.nextToken());}String s()throws IOException {if(!st.hasMoreTokens())st=new StringTokenizer(bq.readLine());return st.nextToken();} double d()throws IOException{if(!st.hasMoreTokens())st=new StringTokenizer(bq.readLine()); return Double.parseDouble(st.nextToken());}void p(Object p){System.out.print(p);} void p(String p){System.out.print(p);}void p(int p){System.out.print(p);} void p(double p){System.out.print(p);}void p(long p){System.out.print(p);} void p(char p){System.out.print(p);}void p(boolean p){System.out.print(p);} void pl(Object p){System.out.println(p);}void pl(String p){System.out.println(p);} void pl(int p){System.out.println(p);}void pl(char p){System.out.println(p);} void pl(double p){System.out.println(p);}void pl(long p){System.out.println(p);} void pl(boolean p){System.out.println(p);}void pl(){System.out.println();} void s(int a[]){for(int e:a){sb.append(e);sb.append(' ');}sb.append("\n");} void s(long a[]){for(long e:a){sb.append(e);sb.append(' ');}sb.append("\n");} void s(int ar[][]){for(int a[]:ar){for(int e:a){sb.append(e);sb.append(' ');}sb.append("\n");}} void s(char a[]){for(char e:a){sb.append(e);sb.append(' ');}sb.append("\n");} void s(char ar[][]){for(char a[]:ar){for(char e:a){sb.append(e);sb.append(' ');}sb.append("\n");}} int[] ari(int n)throws IOException {int ar[]=new int[n];if(!st.hasMoreTokens())st=new StringTokenizer(bq.readLine()); for(int x=0;x<n;x++)ar[x]=Integer.parseInt(st.nextToken());return ar;} int[][] ari(int n,int m)throws IOException {int ar[][]=new int[n][m];for(int x=0;x<n;x++){if(!st.hasMoreTokens())st=new StringTokenizer(bq.readLine()); for(int y=0;y<m;y++)ar[x][y]=Integer.parseInt(st.nextToken());}return ar;} long[] arl(int n)throws IOException {long ar[]=new long[n];if(!st.hasMoreTokens())st=new StringTokenizer(bq.readLine()); for(int x=0;x<n;x++) ar[x]=Long.parseLong(st.nextToken());return ar;} long[][] arl(int n,int m)throws IOException {long ar[][]=new long[n][m];for(int x=0;x<n;x++) {if(!st.hasMoreTokens())st=new StringTokenizer(bq.readLine()); for(int y=0;y<m;y++)ar[x][y]=Long.parseLong(st.nextToken());}return ar;} String[] ars(int n)throws IOException {String ar[]=new String[n];if(!st.hasMoreTokens())st=new StringTokenizer(bq.readLine()); for(int x=0;x<n;x++) ar[x]=st.nextToken();return ar;} double[] ard(int n)throws IOException {double ar[]=new double[n];if(!st.hasMoreTokens())st=new StringTokenizer(bq.readLine()); for(int x=0;x<n;x++)ar[x]=Double.parseDouble(st.nextToken());return ar;} double[][] ard(int n,int m)throws IOException {double ar[][]=new double[n][m];for(int x=0;x<n;x++) {if(!st.hasMoreTokens())st=new StringTokenizer(bq.readLine()); for(int y=0;y<m;y++)ar[x][y]=Double.parseDouble(st.nextToken());}return ar;} char[] arc(int n)throws IOException{char ar[]=new char[n];if(!st.hasMoreTokens())st=new StringTokenizer(bq.readLine()); for(int x=0;x<n;x++)ar[x]=st.nextToken().charAt(0);return ar;} char[][] arc(int n,int m)throws IOException{char ar[][]=new char[n][m]; for(int x=0;x<n;x++){String s=bq.readLine();for(int y=0;y<m;y++)ar[x][y]=s.charAt(y);}return ar;} void p(int ar[]){StringBuilder sb=new StringBuilder(2*ar.length); for(int a:ar){sb.append(a);sb.append(' ');}System.out.println(sb);} void p(int ar[][]){StringBuilder sb=new StringBuilder(2*ar.length*ar[0].length); for(int a[]:ar){for(int aa:a){sb.append(aa);sb.append(' ');}sb.append("\n");}p(sb);} void p(long ar[]){StringBuilder sb=new StringBuilder(2*ar.length); for(long a:ar){sb.append(a);sb.append(' ');}System.out.println(sb);} void p(long ar[][]){StringBuilder sb=new StringBuilder(2*ar.length*ar[0].length); for(long a[]:ar){for(long aa:a){sb.append(aa);sb.append(' ');}sb.append("\n");}p(sb);} void p(String ar[]){int c=0;for(String s:ar)c+=s.length()+1;StringBuilder sb=new StringBuilder(c); for(String a:ar){sb.append(a);sb.append(' ');}System.out.println(sb);} void p(double ar[]){StringBuilder sb=new StringBuilder(2*ar.length); for(double a:ar){sb.append(a);sb.append(' ');}System.out.println(sb);} void p(double ar[][]){StringBuilder sb=new StringBuilder(2*ar.length*ar[0].length); for(double a[]:ar){for(double aa:a){sb.append(aa);sb.append(' ');}sb.append("\n");}p(sb);} void p(char ar[]){StringBuilder sb=new StringBuilder(2*ar.length); for(char aa:ar){sb.append(aa);sb.append(' ');}System.out.println(sb);} void p(char ar[][]){StringBuilder sb=new StringBuilder(2*ar.length*ar[0].length); for(char a[]:ar){for(char aa:a){sb.append(aa);sb.append(' ');}sb.append("\n");}p(sb);} }
Java
["3\n4\n1 3 2 4\n3\n1 2 3\n5\n2 1 4 5 3"]
2 seconds
["1\n0\n2"]
NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
c212524cc1ad8e0332693e3cf644854b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.
900
For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.
standard output
PASSED
90ae2f0d32b684a8e5fca185ea52da54
train_110.jsonl
1621152000
You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.
256 megabytes
//package starting; import java.util.* ; public class Main { public static int solve(int[] nums) { boolean flag = true ; for(int i = 0 ; i < nums.length ; i++) { //System.out.print(nums[i] + " "); if( i+1 < nums.length && nums[i] > nums[i+1]) { flag = false ; } } if(flag) return 0 ; if(nums[0] == 1 || nums[nums.length-1] == nums.length) return 1 ; if(nums[nums.length-1] == 1 && nums[0] == nums.length) return 3 ; return 2; } public static void main(String[] args) { Scanner s = new Scanner(System.in) ; int n = Integer.parseInt(s.nextLine()) ; for(int i = 0 ; i< n ; i++) { s.nextLine() ; String[] str= s.nextLine().split("\\s+") ; int[] stri = new int[str.length] ; for(int j = 0 ; j < stri.length ; j++) { stri[j] = Integer.parseInt(str[j]) ; } int ans = solve(stri) ; System.out.println(ans); } } }
Java
["3\n4\n1 3 2 4\n3\n1 2 3\n5\n2 1 4 5 3"]
2 seconds
["1\n0\n2"]
NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
c212524cc1ad8e0332693e3cf644854b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.
900
For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.
standard output
PASSED
b7f61a6b563a71fba6da24ef9e6ae617
train_110.jsonl
1621152000
You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import static java.lang.Math.*; import static java.lang.System.out; import java.util.*; import java.io.File; import java.io.PrintStream; import java.io.PrintWriter; import java.math.BigInteger; public class A { /* 10^(7) = 1s. * ceilVal = (a+b-1) / b */ static final int mod = 1000000007; static final long temp = 998244353; static final long MOD = 1000000007; static final long M = (long)1e9+7; static class Pair implements Comparable<Pair> { int first, second; public Pair(int first, int second) { this.first = first; this.second = second; } public int compareTo(Pair ob) { return (int)(ob.second - second); } } static class Tuple implements Comparable<Tuple> { int first, second,third; public Tuple(int first, int second, int third) { this.first = first; this.second = second; this.third = third; } public int compareTo(Tuple o) { return (int)(o.third - this.third); } } public static class DSU { int[] parent; int[] rank; //Size of the trees is used as the rank public DSU(int n) { parent = new int[n]; rank = new int[n]; Arrays.fill(parent, -1); Arrays.fill(rank, 1); } public int find(int i) //finding through path compression { return parent[i] < 0 ? i : (parent[i] = find(parent[i])); } public boolean union(int a, int b) //Union Find by Rank { a = find(a); b = find(b); if(a == b) return false; //if they are already connected we exit by returning false. // if a's parent is less than b's parent if(rank[a] < rank[b]) { //then move a under b parent[a] = b; } //else if rank of j's parent is less than i's parent else if(rank[a] > rank[b]) { //then move b under a parent[b] = a; } //if both have the same rank. else { //move a under b (it doesnt matter if its the other way around. parent[b] = a; rank[a] = 1 + rank[a]; } return true; } } static class Reader { 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) throws IOException { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } long[] longReadArray(int n) throws IOException { long[] a=new long[n]; for (int i=0; i<n; i++) a[i]=nextLong(); return a; } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } } public static boolean isPrime(long n) { if(n == 1) { return false; } for(int i = 2;i*i<=n;i++) { if(n%i == 0) { return false; } } return true; } public static List<Long> SieveList(int n) { boolean prime[] = new boolean[(int)(n+1)]; Arrays.fill(prime, true); List<Long> l = new ArrayList<>(); for (long p=2; p*p<=n; p++) { if (prime[(int)(p)] == true) { for(long i=p*p; i<=n; i += p) { prime[(int)(p)] = false; } } } for (long p=2; p<=n; p++) { if (prime[(int)(p)] == true) { l.add(p); } } return l; } public static int gcd(int a, int b) { if(b == 0) return a; else return gcd(b,a%b); } public static long lcm(long a, long b) { return (a / LongGCD(a, b)) * b; } public static long LongGCD(long a, long b) { if(b == 0) return a; else return LongGCD(b,a%b); } public static long LongLCM(long a, long b) { return (a / LongGCD(a, b)) * b; } //Count the number of coprime's upto N public static long phi(long n) //euler totient/phi function { long ans = n; // for(long i = 2;i*i<=n;i++) // { // if(n%i == 0) // { // while(n%i == 0) n/=i; // ans -= (ans/i); // } // } // // if(n > 1) // { // ans -= (ans/n); // } for(long i = 2;i<=n;i++) { if(isPrime(i)) { ans -= (ans/i); } } return ans; } public static long fastPow(long x, long n) { if(n == 0) return 1; else if(n%2 == 0) return fastPow(x*x,n/2); else return x*fastPow(x*x,(n-1)/2); } public static long modPow(long x, long y, long p) { long res = 1; x = x % p; while (y > 0) { if (y % 2 == 1) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return res; } static long modInverse(long n, long p) { return modPow(n, p - 2, p); } // Returns nCr % p using Fermat's little theorem. public static long nCrModP(long n, long r,long p) { if (n<r) return 0; if (r == 0) return 1; long[] fac = new long[(int)(n) + 1]; fac[0] = 1; for (int i = 1; i <= n; i++) fac[i] = fac[i - 1] * i % p; return (fac[(int)(n)] * modInverse(fac[(int)(r)], p) % p * modInverse(fac[(int)(n - r)], p) % p) % p; } public static long fact(long n) { long[] fac = new long[(int)(n) + 1]; fac[0] = 1; for (long i = 1; i <= n; i++) fac[(int)(i)] = fac[(int)(i - 1)] * i; return fac[(int)(n)]; } public static long nCr(long n, long k) { long ans = 1; for(long i = 0;i<k;i++) { ans *= (n-i); ans /= (i+1); } return ans; } //Modular Operations for Addition and Multiplication. public static long perfomMod(long x) { return ((x%M + M)%M); } public static long addMod(long a, long b) { return perfomMod(perfomMod(a)+perfomMod(b)); } public static long subMod(long a, long b) { return perfomMod(perfomMod(a)-perfomMod(b)); } public static long mulMod(long a, long b) { return perfomMod(perfomMod(a)*perfomMod(b)); } /* * * >= <= 0 1 2 3 4 5 6 7 5 5 5 6 6 6 7 7 lower_bound for 6 at index 3 (>=) upper_bound for 6 at index 6(To get six reduce by one) (<=) */ public static int LowerBound(int a[], int x) { int l=-1,r=a.length; while(l+1<r) { int m=(l+r)>>>1; if(a[m]>=x) r=m; else l=m; } return r; } public static int UpperBound(int a[], int x) { int l=-1, r=a.length; while(l+1<r) { int m=(l+r)>>>1; if(a[m]<=x) l=m; else r=m; } return l+1; } public static long log2(long n) { long ans = (long)(log(n)/log(2)); return ans; } public static boolean isPow2(long n) { return (n != 0 && ((n & (n-1))) == 0); } public static boolean isSq(int x) { long s = (long)Math.round(Math.sqrt(x)); return s*s==x; } 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 void Sort(int[] a) { List<Integer> l = new ArrayList<>(); for (int i : a) l.add(i); Collections.sort(l); Collections.reverse(l); //Use to Sort decreasingly for (int i=0; i<a.length; i++) a[i]=l.get(i); } public static void ssort(char[] a) { List<Character> l = new ArrayList<>(); for (char i : a) l.add(i); Collections.sort(l); for (int i=0; i<a.length; i++) a[i]=l.get(i); } public static void main(String[] args) throws Exception { Reader sc = new Reader(); PrintWriter fout = new PrintWriter(System.out); int t = sc.nextInt(); while(t-- > 0) { int n = sc.nextInt(); int[] a = sc.readArray(n); if(isSorted(a)) { fout.println(0); } else if(a[0] == 1 || a[n-1] == n) { fout.println(1); } else if(a[0] != n || a[n-1] != 1) { fout.println(2); } else { fout.println(3); } } fout.close(); } }
Java
["3\n4\n1 3 2 4\n3\n1 2 3\n5\n2 1 4 5 3"]
2 seconds
["1\n0\n2"]
NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
c212524cc1ad8e0332693e3cf644854b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.
900
For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.
standard output
PASSED
ca4cb113c83104ea94a3fbd7e9affc23
train_110.jsonl
1621152000
You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.
256 megabytes
import java.util.*; public class PermutationSort { public static boolean sort(int a []) { boolean s = false; int b [] = new int [a.length]; for(int i =0;i<a.length;i++) b [i] = a [i]; Arrays.sort(b); if(Arrays.equals(a, b)) s = true; else s = false; return s; } public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while(t-->0) { int n = sc.nextInt(); int a [] = new int [n]; for(int i =0;i<n;i++) a [i] = sc.nextInt(); int count =0; if(sort(a)) { count =0; } else if(a [0] == n && n<=3 && a [n-1] == 1){ count = 3; } else if(a [0] == n && a [n-1] == 1){ count = 3; } else if(a [n-1] == n || a [0] ==1) { count =1; } else { count = 2; } System.out.println(count); } } }
Java
["3\n4\n1 3 2 4\n3\n1 2 3\n5\n2 1 4 5 3"]
2 seconds
["1\n0\n2"]
NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.
Java 8
standard input
[ "constructive algorithms", "greedy" ]
c212524cc1ad8e0332693e3cf644854b
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.
900
For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.
standard output