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
3a623ef59045f4c89af17687d15e8e6f
train_108.jsonl
1635863700
The robot is located on a checkered rectangular board of size $$$n \times m$$$ ($$$n$$$ rows, $$$m$$$ columns). The rows in the board are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and the columns — from $$$1$$$ to $$$m$$$ from left to right.The robot is able to move from the current cell to one of the four cells adjacent by side.The sequence of commands $$$s$$$ executed by the robot is given. Each command is denoted by one of the symbols 'L', 'R', 'D' or 'U', and triggers the movement to left, right, down or up, respectively.The robot can start its movement in any cell. The robot executes the commands starting from the first one, strictly in the order in which they are listed in $$$s$$$. If the robot moves beyond the edge of the board, it falls and breaks. A command that causes the robot to break is not considered successfully executed.The robot's task is to execute as many commands as possible without falling off the board. For example, on board $$$3 \times 3$$$, if the robot starts a sequence of actions $$$s=$$$"RRDLUU" ("right", "right", "down", "left", "up", "up") from the central cell, the robot will perform one command, then the next command will force him to cross the edge. If the robot starts moving from the cell $$$(2, 1)$$$ (second row, first column) then all commands will be executed successfully and the robot will stop at the cell $$$(1, 2)$$$ (first row, second column). The robot starts from cell $$$(2, 1)$$$ (second row, first column). It moves right, right, down, left, up, and up. In this case it ends in the cell $$$(1, 2)$$$ (first row, second column). Determine the cell from which the robot should start its movement in order to execute as many commands as possible.
256 megabytes
import java.util.*; import java.io.*; public class fastTemp { static FastScanner fs = null; public static void main(String[] args) { fs = new FastScanner(); PrintWriter out = new PrintWriter(System.out); int t = fs.nextInt(); while (t-->0) { int n = fs.nextInt(); int m = fs.nextInt(); String s = fs.next(); int x=0; int y=0; int lx = 0; int ly=0; int hy=0; int hx=0; int r=1; int col=1; char[] c = s.toCharArray(); for(int i=0;i<c.length;i++){ if(c[i]=='L') x--; else if(c[i]=='R') x++; else if(c[i]=='U') y--; else y++; lx = Math.min(lx,x); hx = Math.max(hx,x); ly = Math.min(ly,y); hy = Math.max(hy,y); if(hx-lx < m && hy-ly < n){ r = 1-lx; col = 1-ly; } } out.println(col+" "+r); } out.println(); out.close(); } static void sort(int[] a) { ArrayList<Integer> l=new ArrayList<>(); for (int i:a) l.add(i); Collections.sort(l); for (int i=0; i<a.length; i++) a[i]=l.get(i); } static class FastScanner { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readArray(int n) { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } long nextLong() { return Long.parseLong(next()); } } }
Java
["4\n1 1\nL\n1 2\nL\n3 3\nRRDLUU\n4 3\nLUURRDDLLLUU"]
2 seconds
["1 1\n1 2\n2 1\n3 2"]
null
Java 11
standard input
[ "implementation" ]
585bb4a040144da39ed240366193e705
The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. In the description of each test case, the first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^6$$$) — the height and width of the field that the robot is located on. The second line of the description is a string $$$s$$$ consisting solely of characters 'L', 'R', 'D' and 'U' — the sequence of commands the robot executes. The string has a length from $$$1$$$ to $$$10^6$$$ commands. It is guaranteed that the total length of $$$s$$$ over all test cases does not exceed $$$10^6$$$.
1,600
Print $$$t$$$ lines, each of which contains the answer to the corresponding test case. The answer to the test case are two integers $$$r$$$ ($$$1 \leq r \leq n$$$) and $$$c$$$ ($$$1 \leq c \leq m$$$), separated by a space — the coordinates of the cell (row number and column number) from which the robot should start moving to perform as many commands as possible. If there are several such cells, you may output any of them.
standard output
PASSED
eca3b02f4fda96c39ce947d30028c8bb
train_108.jsonl
1635863700
The robot is located on a checkered rectangular board of size $$$n \times m$$$ ($$$n$$$ rows, $$$m$$$ columns). The rows in the board are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and the columns — from $$$1$$$ to $$$m$$$ from left to right.The robot is able to move from the current cell to one of the four cells adjacent by side.The sequence of commands $$$s$$$ executed by the robot is given. Each command is denoted by one of the symbols 'L', 'R', 'D' or 'U', and triggers the movement to left, right, down or up, respectively.The robot can start its movement in any cell. The robot executes the commands starting from the first one, strictly in the order in which they are listed in $$$s$$$. If the robot moves beyond the edge of the board, it falls and breaks. A command that causes the robot to break is not considered successfully executed.The robot's task is to execute as many commands as possible without falling off the board. For example, on board $$$3 \times 3$$$, if the robot starts a sequence of actions $$$s=$$$"RRDLUU" ("right", "right", "down", "left", "up", "up") from the central cell, the robot will perform one command, then the next command will force him to cross the edge. If the robot starts moving from the cell $$$(2, 1)$$$ (second row, first column) then all commands will be executed successfully and the robot will stop at the cell $$$(1, 2)$$$ (first row, second column). The robot starts from cell $$$(2, 1)$$$ (second row, first column). It moves right, right, down, left, up, and up. In this case it ends in the cell $$$(1, 2)$$$ (first row, second column). Determine the cell from which the robot should start its movement in order to execute as many commands as possible.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class Solution{ static FastScanner sc = new FastScanner(); public static void solve(){ int n=sc.nextInt(); int m=sc.nextInt(); char[] c=sc.next().toCharArray(); int x=1,y=1; int sum=0; int l=0,r=0,d=0,u=0; int a=0,b=0; for (int i=0;i<c.length;i++) { if (c[i]=='R') { a++; }else if(c[i]=='L'){ a--; }else if(c[i]=='U'){ b++; }else{ b--; } l=min(a,l); r=max(r,a); u=max(u,b); d=min(d,b); if(m>(r-l)&&(n>(u-d))) { x=(n+d); y=(m-r); } } System.out.println((x)+" "+(y)); } public static void main(String[] args) { int t = sc.nextInt(); outer: for (int tt = 0; tt < t; tt++) { solve(); } } static boolean isPrime(int n) { if (n <= 1) return false; if (n <= 3) return true; if (n % 2 == 0 || n % 3 == 0) return false; for (int i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } public static int[] LPS(String s){ int[] lps=new int[s.length()]; int i=0,j=1; while (j<s.length()) { if(s.charAt(i)==s.charAt(j)){ lps[j]=i+1; i++; j++; continue; }else{ if (i==0) { j++; continue; } i=lps[i-1]; while(s.charAt(i)!=s.charAt(j) && i!=0) { i=lps[i-1]; } if(s.charAt(i)==s.charAt(j)){ lps[j]=i+1; i++; } j++; } } return lps; } static long getPairsCount(int n, double sum,int[] arr) { HashMap<Double, Integer> hm = new HashMap<>(); for (int i = 0; i < n; i++) { if (!hm.containsKey((double)arr[i])) hm.put((double)arr[i], 0); hm.put((double)arr[i], hm.get((double)arr[i]) + 1); } long twice_count = 0; for (int i = 0; i < n; i++) { if (hm.get(sum - arr[i]) != null) twice_count += hm.get(sum - arr[i]); if (sum - (double)arr[i] == (double)arr[i]) twice_count--; } return twice_count / 2l; } static boolean[] sieveOfEratosthenes(int n) { boolean prime[] = new boolean[n + 1]; for (int i = 0; i <= n; i++) prime[i] = true; for (int p = 2; p * p <= n; p++) { if (prime[p] == true) { for (int i = p * p; i <= n; i += p) prime[i] = false; } } return prime; } static long power(long x, long y, long p) { long res = 1l; x = x % p; if (x == 0) return 0; while (y > 0) { if ((y & 1) != 0) res = (res * x) % p; y>>=1; x = (x * x) % p; } return res; } public static int log2(int N) { int result = (int)(Math.log(N) / Math.log(2)); return result; } //////////////////////////////////////////////////////////////////////////////////// ////////////////////DO NOT READ AFTER THIS LINE ////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////// static long modFact(int n, int p) { if (n >= p) return 0; long result = 1l; for (int i = 3; i <= n; i++) result = (result * i) % p; return result; } static boolean isPalindrom(char[] arr, int i, int j) { boolean ok = true; while (i <= j) { if (arr[i] != arr[j]) { ok = false; break; } i++; j--; } return ok; } static int max(int a, int b) { return Math.max(a, b); } static int min(int a, int b) { return Math.min(a, b); } static long max(long a, long b) { return Math.max(a, b); } static long min(long a, long b) { return Math.min(a, b); } static int abs(int a) { return Math.abs(a); } static long abs(long a) { return Math.abs(a); } static void swap(long arr[], int i, int j) { long temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } static void swap(int arr[], int i, int j) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } static int maxArr(int arr[]) { int maxi = Integer.MIN_VALUE; for (int x : arr) maxi = max(maxi, x); return maxi; } static int minArr(int arr[]) { int mini = Integer.MAX_VALUE; for (int x : arr) mini = min(mini, x); return mini; } static long maxArr(long arr[]) { long maxi = Long.MIN_VALUE; for (long x : arr) maxi = max(maxi, x); return maxi; } static long minArr(long arr[]) { long mini = Long.MAX_VALUE; for (long x : arr) mini = min(mini, x); return mini; } static int lcm(int a,int b){ return (int)(((long)a*b)/(long)gcd(a,b)); } static int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } static void ruffleSort(int[] a) { int n = a.length; Random r = new Random(); for (int i = 0; i < a.length; i++) { int oi = r.nextInt(n); int temp = a[i]; a[i] = a[oi]; a[oi] = temp; } Arrays.sort(a); } public static int binarySearch(int a[], int target) { int left = 0; int right = a.length - 1; int mid = (left + right) / 2; int i = 0; while (left <= right) { if (a[mid] <= target) { i = mid + 1; left = mid + 1; } else { right = mid - 1; } mid = (left + right) / 2; } return i-1; } static class FastScanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } long[] readLongArray(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } int[][] read2dArray(int n, int m) { int arr[][] = new int[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { arr[i][j] = nextInt(); } } return arr; } ArrayList<Integer> readArrayList(int n) { ArrayList<Integer> arr = new ArrayList<Integer>(); for (int i = 0; i < n; i++) { int a = nextInt(); arr.add(a); } return arr; } long nextLong() { return Long.parseLong(next()); } } static class Pair { int l, r; Pair(int fr, int sc) { this.l = fr; this.r = sc; } } }
Java
["4\n1 1\nL\n1 2\nL\n3 3\nRRDLUU\n4 3\nLUURRDDLLLUU"]
2 seconds
["1 1\n1 2\n2 1\n3 2"]
null
Java 11
standard input
[ "implementation" ]
585bb4a040144da39ed240366193e705
The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. In the description of each test case, the first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^6$$$) — the height and width of the field that the robot is located on. The second line of the description is a string $$$s$$$ consisting solely of characters 'L', 'R', 'D' and 'U' — the sequence of commands the robot executes. The string has a length from $$$1$$$ to $$$10^6$$$ commands. It is guaranteed that the total length of $$$s$$$ over all test cases does not exceed $$$10^6$$$.
1,600
Print $$$t$$$ lines, each of which contains the answer to the corresponding test case. The answer to the test case are two integers $$$r$$$ ($$$1 \leq r \leq n$$$) and $$$c$$$ ($$$1 \leq c \leq m$$$), separated by a space — the coordinates of the cell (row number and column number) from which the robot should start moving to perform as many commands as possible. If there are several such cells, you may output any of them.
standard output
PASSED
b07e7edd32b334fc4f943e35cbcacb5f
train_108.jsonl
1635863700
The robot is located on a checkered rectangular board of size $$$n \times m$$$ ($$$n$$$ rows, $$$m$$$ columns). The rows in the board are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and the columns — from $$$1$$$ to $$$m$$$ from left to right.The robot is able to move from the current cell to one of the four cells adjacent by side.The sequence of commands $$$s$$$ executed by the robot is given. Each command is denoted by one of the symbols 'L', 'R', 'D' or 'U', and triggers the movement to left, right, down or up, respectively.The robot can start its movement in any cell. The robot executes the commands starting from the first one, strictly in the order in which they are listed in $$$s$$$. If the robot moves beyond the edge of the board, it falls and breaks. A command that causes the robot to break is not considered successfully executed.The robot's task is to execute as many commands as possible without falling off the board. For example, on board $$$3 \times 3$$$, if the robot starts a sequence of actions $$$s=$$$"RRDLUU" ("right", "right", "down", "left", "up", "up") from the central cell, the robot will perform one command, then the next command will force him to cross the edge. If the robot starts moving from the cell $$$(2, 1)$$$ (second row, first column) then all commands will be executed successfully and the robot will stop at the cell $$$(1, 2)$$$ (first row, second column). The robot starts from cell $$$(2, 1)$$$ (second row, first column). It moves right, right, down, left, up, and up. In this case it ends in the cell $$$(1, 2)$$$ (first row, second column). Determine the cell from which the robot should start its movement in order to execute as many commands as possible.
256 megabytes
//package codeforces; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; public class codeforces{ public static void main(String[] args){ FastScanner s=new FastScanner(); PrintWriter out=new PrintWriter(System.out); int t=s.nextInt(); for(int tt=0;tt<t;tt++) { int n=s.nextInt(),m=s.nextInt(); String a=s.next(); int px=0,nx=0,py=0,ny=0; int x=0,y=0; int fx=0,fy=0; for(int i=0;i<a.length();i++) { if(a.charAt(i)=='U') { y--; py=Math.max(py, y); ny=Math.min(ny,y); }else if(a.charAt(i)=='D') { y++; py=Math.max(py, y); ny=Math.min(ny,y); }else if(a.charAt(i)=='R') { x++; px=Math.max(px, x); nx=Math.min(nx, x); }else { x--; px=Math.max(px, x); nx=Math.min(nx, x); } if((px-nx<m) && (py-ny<n)) { fx=-nx; fy=-ny; }else { break; } } out.println((fy+1)+" "+(fx+1)); } out.close(); } static int isPrime(long n){ HashSet<Long> set=new HashSet<>(); if (n <= 1) return 1; for (long i = 2; i <= Math.sqrt(n); i ++){ if (n % i == 0) { set.add(i); //System.out.println(i+" "+n/i); set.add(n/i); } } return set.size()+1; } public static void printb(boolean ans) { if(ans) { System.out.println("Yes"); }else { System.out.println("No"); } } static void sort(long [] a) { ArrayList<Long> l=new ArrayList<>(); for (long i:a) l.add(i); Collections.sort(l); for (int i=0; i<a.length; i++) a[i]=l.get(i); } static 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 int gcd(int a, int b){ if (b == 0) return a; return gcd(b, a % b); } static void sortcol(int a[][],int c) { Arrays.sort(a, (x, y) -> { if(x[c]>y[c]) { return 1; }else { return -1; } }); } 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(); } double nextDouble() { return Double.parseDouble(next()); } int nextInt() { return Integer.parseInt(next()); } boolean nextBoolean() { return Boolean.parseBoolean(next()); } int[] readArray(int n) { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } long nextLong() { return Long.parseLong(next()); } long[] readLongArray(int n) { long[] a=new long[n]; for (int i=0; i<n; i++) a[i]=nextLong(); return a; } } } class Pair implements Comparable<Pair>{ int a; char c; Pair(int a,char c){ this.a=a; this.c=c; } public int compareTo(Pair o) { return a-o.a; } }
Java
["4\n1 1\nL\n1 2\nL\n3 3\nRRDLUU\n4 3\nLUURRDDLLLUU"]
2 seconds
["1 1\n1 2\n2 1\n3 2"]
null
Java 11
standard input
[ "implementation" ]
585bb4a040144da39ed240366193e705
The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. In the description of each test case, the first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^6$$$) — the height and width of the field that the robot is located on. The second line of the description is a string $$$s$$$ consisting solely of characters 'L', 'R', 'D' and 'U' — the sequence of commands the robot executes. The string has a length from $$$1$$$ to $$$10^6$$$ commands. It is guaranteed that the total length of $$$s$$$ over all test cases does not exceed $$$10^6$$$.
1,600
Print $$$t$$$ lines, each of which contains the answer to the corresponding test case. The answer to the test case are two integers $$$r$$$ ($$$1 \leq r \leq n$$$) and $$$c$$$ ($$$1 \leq c \leq m$$$), separated by a space — the coordinates of the cell (row number and column number) from which the robot should start moving to perform as many commands as possible. If there are several such cells, you may output any of them.
standard output
PASSED
af8bd4f124aa0fece05bb1a5c2abf189
train_108.jsonl
1635863700
The robot is located on a checkered rectangular board of size $$$n \times m$$$ ($$$n$$$ rows, $$$m$$$ columns). The rows in the board are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and the columns — from $$$1$$$ to $$$m$$$ from left to right.The robot is able to move from the current cell to one of the four cells adjacent by side.The sequence of commands $$$s$$$ executed by the robot is given. Each command is denoted by one of the symbols 'L', 'R', 'D' or 'U', and triggers the movement to left, right, down or up, respectively.The robot can start its movement in any cell. The robot executes the commands starting from the first one, strictly in the order in which they are listed in $$$s$$$. If the robot moves beyond the edge of the board, it falls and breaks. A command that causes the robot to break is not considered successfully executed.The robot's task is to execute as many commands as possible without falling off the board. For example, on board $$$3 \times 3$$$, if the robot starts a sequence of actions $$$s=$$$"RRDLUU" ("right", "right", "down", "left", "up", "up") from the central cell, the robot will perform one command, then the next command will force him to cross the edge. If the robot starts moving from the cell $$$(2, 1)$$$ (second row, first column) then all commands will be executed successfully and the robot will stop at the cell $$$(1, 2)$$$ (first row, second column). The robot starts from cell $$$(2, 1)$$$ (second row, first column). It moves right, right, down, left, up, and up. In this case it ends in the cell $$$(1, 2)$$$ (first row, second column). Determine the cell from which the robot should start its movement in order to execute as many commands as possible.
256 megabytes
import java.io.*; import java.util.*; public class Main { // static boolean[] prime = new boolean[10000000]; final static long mod = 1000000007; public static void main(String[] args) { // sieve(); InputReader in = new InputReader(System.in); PrintWriter out = new PrintWriter(System.out); int t = in.nextInt(); while (t-- > 0) { int h = in.nextInt(), w = in.nextInt(); int x = 0, y = 0, min_x = 0, min_y = 0, max_x = 0, max_y = 0; String str = in.next(); for(char c : str.toCharArray()) { if(c == 'L') { x--; min_x = Math.min(min_x, x); if(max_x - min_x + 1 > w) { min_x++; break; } }else if(c == 'R') { x++; max_x = Math.max(max_x, x); if(max_x - min_x + 1 > w) { max_x--; break; } }else if(c == 'U') { y--; min_y = Math.min(min_y, y); if(max_y - min_y + 1 > h) { min_y++; break; } }else { y++; max_y = Math.max(max_y, y); if(max_y - min_y + 1 > h) { max_y--; break; } } } x = Math.abs(min_x)+1; y = Math.abs(min_y)+1; out.println(y + " " + x); } out.flush(); } static long gcd(long a, long b) { if (a % b == 0) { return b; } else { return gcd(b, a % b); } } static void reverseArray(int[] a) { for (int i = 0; i < (a.length >> 1); i++) { int temp = a[i]; a[i] = a[a.length - 1 - i]; a[a.length - 1 - i] = temp; } } static Integer[] intInput(int n, InputReader in) { Integer[] a = new Integer[n]; for (int i = 0; i < a.length; i++) a[i] = in.nextInt(); return a; } static Long[] longInput(int n, InputReader in) { Long[] a = new Long[n]; for (int i = 0; i < a.length; i++) a[i] = in.nextLong(); return a; } static String[] strInput(int n, InputReader in) { String[] a = new String[n]; for (int i = 0; i < a.length; i++) a[i] = in.next(); return a; } // static void sieve() { // for (int i = 2; i * i < prime.length; i++) { // if (prime[i]) // continue; // for (int j = i * i; j < prime.length; j += i) { // prime[j] = true; // } // } // } } class Data { int val; int ind; Data(int val, int ind) { this.val = Math.abs(val); this.ind = ind; } } class compareVal implements Comparator<Data> { @Override public int compare(Data o1, Data o2) { return (o1.val - o2.val); } } class compareInd implements Comparator<Data> { @Override public int compare(Data o1, Data o2) { return o1.ind - o2.ind == 0 ? o1.val - o2.val : o1.ind - o2.ind; } } 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()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = reader.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } }
Java
["4\n1 1\nL\n1 2\nL\n3 3\nRRDLUU\n4 3\nLUURRDDLLLUU"]
2 seconds
["1 1\n1 2\n2 1\n3 2"]
null
Java 11
standard input
[ "implementation" ]
585bb4a040144da39ed240366193e705
The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. In the description of each test case, the first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^6$$$) — the height and width of the field that the robot is located on. The second line of the description is a string $$$s$$$ consisting solely of characters 'L', 'R', 'D' and 'U' — the sequence of commands the robot executes. The string has a length from $$$1$$$ to $$$10^6$$$ commands. It is guaranteed that the total length of $$$s$$$ over all test cases does not exceed $$$10^6$$$.
1,600
Print $$$t$$$ lines, each of which contains the answer to the corresponding test case. The answer to the test case are two integers $$$r$$$ ($$$1 \leq r \leq n$$$) and $$$c$$$ ($$$1 \leq c \leq m$$$), separated by a space — the coordinates of the cell (row number and column number) from which the robot should start moving to perform as many commands as possible. If there are several such cells, you may output any of them.
standard output
PASSED
1dcca96be754374fc12b372eabdbbf56
train_108.jsonl
1635863700
The robot is located on a checkered rectangular board of size $$$n \times m$$$ ($$$n$$$ rows, $$$m$$$ columns). The rows in the board are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and the columns — from $$$1$$$ to $$$m$$$ from left to right.The robot is able to move from the current cell to one of the four cells adjacent by side.The sequence of commands $$$s$$$ executed by the robot is given. Each command is denoted by one of the symbols 'L', 'R', 'D' or 'U', and triggers the movement to left, right, down or up, respectively.The robot can start its movement in any cell. The robot executes the commands starting from the first one, strictly in the order in which they are listed in $$$s$$$. If the robot moves beyond the edge of the board, it falls and breaks. A command that causes the robot to break is not considered successfully executed.The robot's task is to execute as many commands as possible without falling off the board. For example, on board $$$3 \times 3$$$, if the robot starts a sequence of actions $$$s=$$$"RRDLUU" ("right", "right", "down", "left", "up", "up") from the central cell, the robot will perform one command, then the next command will force him to cross the edge. If the robot starts moving from the cell $$$(2, 1)$$$ (second row, first column) then all commands will be executed successfully and the robot will stop at the cell $$$(1, 2)$$$ (first row, second column). The robot starts from cell $$$(2, 1)$$$ (second row, first column). It moves right, right, down, left, up, and up. In this case it ends in the cell $$$(1, 2)$$$ (first row, second column). Determine the cell from which the robot should start its movement in order to execute as many commands as possible.
256 megabytes
import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.PriorityQueue; import java.util.Queue; import java.util.Stack; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.TreeSet; import java.io.*; public class Div2 { private 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; } } public static void solution(int n, int m, String st) { int l = 0; int r = 0; int x = 0; int ax = 1; for(int i = 0; i<st.length();i++) { if(st.charAt(i)=='L') x--; if(st.charAt(i)=='R') x++; if(x<0) l = Math.min(l, x); if(x>0) r = Math.max(r,x); if((1-l)<=(m-r)) ax = 1-l; else break; } int u = 0; int d = 0; int y = 0; int ay = 1; for(int i = 0; i<st.length();i++) { if(st.charAt(i)=='U') y--; if(st.charAt(i)=='D') y++; if(y<0) u = Math.min(u, y); if(y>0) d = Math.max(d,y); if((1-u)<=(n-d)) ay = 1-u; else break; } out.println(ay+" "+ax); } private static PrintWriter out = new PrintWriter(System.out); public static void main (String[] args) { MyScanner s = new MyScanner(); int t = s.nextInt(); for(int j = 0; j<t ; j++) { int n = s.nextInt(); int m = s.nextInt(); String st = s.next(); solution(n,m,st); } out.flush(); out.close(); } }
Java
["4\n1 1\nL\n1 2\nL\n3 3\nRRDLUU\n4 3\nLUURRDDLLLUU"]
2 seconds
["1 1\n1 2\n2 1\n3 2"]
null
Java 11
standard input
[ "implementation" ]
585bb4a040144da39ed240366193e705
The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. In the description of each test case, the first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^6$$$) — the height and width of the field that the robot is located on. The second line of the description is a string $$$s$$$ consisting solely of characters 'L', 'R', 'D' and 'U' — the sequence of commands the robot executes. The string has a length from $$$1$$$ to $$$10^6$$$ commands. It is guaranteed that the total length of $$$s$$$ over all test cases does not exceed $$$10^6$$$.
1,600
Print $$$t$$$ lines, each of which contains the answer to the corresponding test case. The answer to the test case are two integers $$$r$$$ ($$$1 \leq r \leq n$$$) and $$$c$$$ ($$$1 \leq c \leq m$$$), separated by a space — the coordinates of the cell (row number and column number) from which the robot should start moving to perform as many commands as possible. If there are several such cells, you may output any of them.
standard output
PASSED
54b4d25a1745738ac25ab3edc4d6a95e
train_108.jsonl
1635863700
The robot is located on a checkered rectangular board of size $$$n \times m$$$ ($$$n$$$ rows, $$$m$$$ columns). The rows in the board are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and the columns — from $$$1$$$ to $$$m$$$ from left to right.The robot is able to move from the current cell to one of the four cells adjacent by side.The sequence of commands $$$s$$$ executed by the robot is given. Each command is denoted by one of the symbols 'L', 'R', 'D' or 'U', and triggers the movement to left, right, down or up, respectively.The robot can start its movement in any cell. The robot executes the commands starting from the first one, strictly in the order in which they are listed in $$$s$$$. If the robot moves beyond the edge of the board, it falls and breaks. A command that causes the robot to break is not considered successfully executed.The robot's task is to execute as many commands as possible without falling off the board. For example, on board $$$3 \times 3$$$, if the robot starts a sequence of actions $$$s=$$$"RRDLUU" ("right", "right", "down", "left", "up", "up") from the central cell, the robot will perform one command, then the next command will force him to cross the edge. If the robot starts moving from the cell $$$(2, 1)$$$ (second row, first column) then all commands will be executed successfully and the robot will stop at the cell $$$(1, 2)$$$ (first row, second column). The robot starts from cell $$$(2, 1)$$$ (second row, first column). It moves right, right, down, left, up, and up. In this case it ends in the cell $$$(1, 2)$$$ (first row, second column). Determine the cell from which the robot should start its movement in order to execute as many commands as possible.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class E { public static void main(String[] args) throws IOException { FastScanner fs = new FastScanner(); PrintWriter out = new PrintWriter(System.out); int t = fs.nextInt(); for (int tc = 0; tc < t; tc++) { int n = fs.nextInt(); int m = fs.nextInt(); String s = fs.nextLine(); int curx = 0; int cury = 0; int mnx = 0; int mxx = 0; int mny = 0; int mxy = 0; int ansx = 0; int ansy = 0; boolean f = true; for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); switch (c) { case 'L': curx--; mnx = Math.min(mnx, curx); break; case 'R': curx++; mxx = Math.max(mxx, curx); break; case 'D': cury++; mxy = Math.max(mxy, cury); break; case 'U': cury--; mny = Math.min(mny, cury); break; } if (-mnx + mxx >= m) { if (c == 'L') { mnx++; } ansx = -mnx; ansy = -mny; f = false; break; } if (-mny + mxy >= n) { if (c == 'U') { mny++; } ansx = -mnx; ansy = -mny; f = false; break; } } if (f) { ansx = -mnx; ansy = -mny; } ansx++; ansy++; out.println(ansy + " " + ansx); } out.close(); } static class FastScanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } long nextLong() { return Long.parseLong(next()); } String nextLine() throws IOException { return br.readLine(); } } }
Java
["4\n1 1\nL\n1 2\nL\n3 3\nRRDLUU\n4 3\nLUURRDDLLLUU"]
2 seconds
["1 1\n1 2\n2 1\n3 2"]
null
Java 11
standard input
[ "implementation" ]
585bb4a040144da39ed240366193e705
The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. In the description of each test case, the first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^6$$$) — the height and width of the field that the robot is located on. The second line of the description is a string $$$s$$$ consisting solely of characters 'L', 'R', 'D' and 'U' — the sequence of commands the robot executes. The string has a length from $$$1$$$ to $$$10^6$$$ commands. It is guaranteed that the total length of $$$s$$$ over all test cases does not exceed $$$10^6$$$.
1,600
Print $$$t$$$ lines, each of which contains the answer to the corresponding test case. The answer to the test case are two integers $$$r$$$ ($$$1 \leq r \leq n$$$) and $$$c$$$ ($$$1 \leq c \leq m$$$), separated by a space — the coordinates of the cell (row number and column number) from which the robot should start moving to perform as many commands as possible. If there are several such cells, you may output any of them.
standard output
PASSED
c4b65d698b32000e8f4dafda83b00db0
train_108.jsonl
1635863700
The robot is located on a checkered rectangular board of size $$$n \times m$$$ ($$$n$$$ rows, $$$m$$$ columns). The rows in the board are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and the columns — from $$$1$$$ to $$$m$$$ from left to right.The robot is able to move from the current cell to one of the four cells adjacent by side.The sequence of commands $$$s$$$ executed by the robot is given. Each command is denoted by one of the symbols 'L', 'R', 'D' or 'U', and triggers the movement to left, right, down or up, respectively.The robot can start its movement in any cell. The robot executes the commands starting from the first one, strictly in the order in which they are listed in $$$s$$$. If the robot moves beyond the edge of the board, it falls and breaks. A command that causes the robot to break is not considered successfully executed.The robot's task is to execute as many commands as possible without falling off the board. For example, on board $$$3 \times 3$$$, if the robot starts a sequence of actions $$$s=$$$"RRDLUU" ("right", "right", "down", "left", "up", "up") from the central cell, the robot will perform one command, then the next command will force him to cross the edge. If the robot starts moving from the cell $$$(2, 1)$$$ (second row, first column) then all commands will be executed successfully and the robot will stop at the cell $$$(1, 2)$$$ (first row, second column). The robot starts from cell $$$(2, 1)$$$ (second row, first column). It moves right, right, down, left, up, and up. In this case it ends in the cell $$$(1, 2)$$$ (first row, second column). Determine the cell from which the robot should start its movement in order to execute as many commands as possible.
256 megabytes
// \(≧▽≦)/ import java.io.*; import java.util.*; public class tank { static final FastScanner fs = new FastScanner(); static PrintWriter out = new PrintWriter(System.out); public static void main(String[] args) { int t = fs.nextInt(); while(t-- > 0) run_case(); out.close(); } static void run_case() { int n = fs.nextInt(), m = fs.nextInt(); char[] s = fs.next().toCharArray(); int x = 0, y = 0, ly = 0, ry = 0, ux = 0, dx = 0; for(char c: s) { if(c == 'L') { if(ry - ly + 1 == m && y == ly) break; y--; ly = Math.min(ly, y); } else if(c == 'R') { if(ry - ly + 1 == m && y == ry) break; y++; ry = Math.max(ry, y); } else if(c == 'D') { if(dx - ux + 1 == n && x == dx) break; x++; dx = Math.max(dx, x); } else { if(dx - ux + 1 == n && x == ux) break; x--; ux = Math.min(ux, x); } } x = 0; y = 0; y -= ly; y++; x -= ux; x++; out.println(x + " " + y); } 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(); } String nextLine(){ try { return br.readLine(); } catch (IOException e) { e.printStackTrace(); } return ""; } int nextInt() { return Integer.parseInt(next()); } int[] readArray(int n) { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } } }
Java
["4\n1 1\nL\n1 2\nL\n3 3\nRRDLUU\n4 3\nLUURRDDLLLUU"]
2 seconds
["1 1\n1 2\n2 1\n3 2"]
null
Java 11
standard input
[ "implementation" ]
585bb4a040144da39ed240366193e705
The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. In the description of each test case, the first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^6$$$) — the height and width of the field that the robot is located on. The second line of the description is a string $$$s$$$ consisting solely of characters 'L', 'R', 'D' and 'U' — the sequence of commands the robot executes. The string has a length from $$$1$$$ to $$$10^6$$$ commands. It is guaranteed that the total length of $$$s$$$ over all test cases does not exceed $$$10^6$$$.
1,600
Print $$$t$$$ lines, each of which contains the answer to the corresponding test case. The answer to the test case are two integers $$$r$$$ ($$$1 \leq r \leq n$$$) and $$$c$$$ ($$$1 \leq c \leq m$$$), separated by a space — the coordinates of the cell (row number and column number) from which the robot should start moving to perform as many commands as possible. If there are several such cells, you may output any of them.
standard output
PASSED
401485796f728f38f078e292214a216f
train_108.jsonl
1635863700
The robot is located on a checkered rectangular board of size $$$n \times m$$$ ($$$n$$$ rows, $$$m$$$ columns). The rows in the board are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and the columns — from $$$1$$$ to $$$m$$$ from left to right.The robot is able to move from the current cell to one of the four cells adjacent by side.The sequence of commands $$$s$$$ executed by the robot is given. Each command is denoted by one of the symbols 'L', 'R', 'D' or 'U', and triggers the movement to left, right, down or up, respectively.The robot can start its movement in any cell. The robot executes the commands starting from the first one, strictly in the order in which they are listed in $$$s$$$. If the robot moves beyond the edge of the board, it falls and breaks. A command that causes the robot to break is not considered successfully executed.The robot's task is to execute as many commands as possible without falling off the board. For example, on board $$$3 \times 3$$$, if the robot starts a sequence of actions $$$s=$$$"RRDLUU" ("right", "right", "down", "left", "up", "up") from the central cell, the robot will perform one command, then the next command will force him to cross the edge. If the robot starts moving from the cell $$$(2, 1)$$$ (second row, first column) then all commands will be executed successfully and the robot will stop at the cell $$$(1, 2)$$$ (first row, second column). The robot starts from cell $$$(2, 1)$$$ (second row, first column). It moves right, right, down, left, up, and up. In this case it ends in the cell $$$(1, 2)$$$ (first row, second column). Determine the cell from which the robot should start its movement in order to execute as many commands as possible.
256 megabytes
import java.io.*; import java.util.*; public class Main { void solveA() { String s = scanner.nextLine(); String t = scanner.nextLine(); int[] pos = new int[26]; for(int i = 0; i < 26; i++){ pos[s.charAt(i) - 'a'] = i; } long res = 0; for(int i = 1; i < t.length(); i++){ int a = pos[t.charAt(i-1)-'a']; int b = pos[t.charAt(i)-'a']; res += Math.abs(a-b); } out.println(res); } void solveB(){ long x = scanner.nextLong(), n = scanner.nextLong(); if(n % 4 == 0){ out.println(x); } else{ long mod = n % 4, res = x; for(long i = 1; i <= mod; i++){ long num = n / 4 * 4 + i; if(i == 1){ res += (x % 2 == 0? -1L:1L) * num; } else{ res += (x % 2 == 0? 1L:-1L) * num; } } out.println(res); } } void solveC(){ int n = scanner.nextInt(); long[] arr = scanner.nextLongArray(n, 0); if(n == 1){ out.println(arr[0]); return; } PriorityQueue<Long> pq = new PriorityQueue<>(); long offset = 0, res = Long.MIN_VALUE; for(long val: arr){ pq.offer(val); } while(!pq.isEmpty()){ long curr = pq.poll(); res = Math.max(res, curr - offset); offset += curr - offset; } out.println(res); } void solveD(){ int n = scanner.nextInt(); int[] arr = scanner.nextIntArray(n, 0); String str = scanner.nextLine(); int[] count = new int[n + 3]; List<int[]> intervals = new ArrayList<>(); for(int i = 0; i < n; i++){ char ch = str.charAt(i); if(ch == 'B' && arr[i] < 1){ out.println("NO"); return; } if(ch == 'R' && arr[i] > n){ out.println("NO"); return; } int l, r; if(ch == 'B'){ l = 1; r = Math.min(arr[i], n); } else{ l = Math.max(1, arr[i]); r = n; } intervals.add(new int[]{l, r}); count[l]++; count[r+1]--; } Collections.sort(intervals, new Comparator<int[]>() { @Override public int compare(int[] a, int[] b) { if(a[0] == b[0]){ return a[1] - b[1]; } return a[0] - b[0]; } }); for(int i = 1; i <= n; i++){ int[] interval = intervals.get(i-1); if(i < interval[0] || i > interval[1]){ out.println("NO"); return; } } out.println("YES"); } private static final int[] dx = {-1,1,0,0}; //U D L R private static final int[] dy = {0,0,-1,1}; int getDir(char ch){ if(ch == 'U'){return 0;} if(ch == 'D'){return 1;} if(ch == 'L'){return 2;} if(ch == 'R'){return 3;} return -1; } void solveE(){ int n = scanner.nextInt(), m = scanner.nextInt(); String s = scanner.nextLine(); int x = 0, y = 0; int minx = 0, miny = 0, maxx = 0, maxy = 0; int[][] memo = new int[s.length()][4]; for(int i = 0; i < s.length(); i++){ int d = getDir(s.charAt(i)); x += dx[d]; y += dy[d]; minx = Math.min(minx, x); miny = Math.min(miny, y); maxx = Math.max(maxx, x); maxy = Math.max(maxy, y); memo[i][0] = minx; memo[i][1] = miny; memo[i][2] = maxx; memo[i][3] = maxy; } int resX1 = 1, resX2 = n; int resY1 = 1, resY2 = m; for(int i = 0; i < s.length(); i++){ int x1 = 1 - memo[i][0]; int x2 = n - memo[i][2]; int y1 = 1 - memo[i][1]; int y2 = m - memo[i][3]; if(isOverlap(resX1, resX2, x1, x2) && isOverlap(resY1, resY2, y1, y2)){ resX1 = Math.max(resX1, x1); resX2 = Math.min(resX2, x2); resY1 = Math.max(resY1, y1); resY2 = Math.min(resY2, y2); } else{ break; } } out.println(resX1 + " " + resY1); } boolean isOverlap(int l1, int r1, int l2, int r2){ if(r1 < l2 || r2 < l1){ return false; } return true; } private static final boolean memory = false; private static final boolean singleTest = false; // read inputs and call solvers void run() { int numOfTests = singleTest? 1: scanner.nextInt(); for(int testIdx = 1; testIdx <= numOfTests; testIdx++){ solveE(); } out.flush(); out.close(); } // ----- runner templates ----- // public static void main(String[] args) { if(memory) { new Thread(null, new Runnable() { @Override public void run() { new Main().run(); } }, "go", 1 << 26).start(); } else{ new Main().run(); } } //------ input and output ------// public static MyScanner scanner = new MyScanner(); public static PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); 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; } int[] nextIntArray(int n, int base){ int[] arr = new int[n + base]; for(int i = base; i < n + base; i++){ arr[i] = scanner.nextInt(); } return arr; } long[] nextLongArray(int n, int base){ long[] arr = new long[n + base]; for(int i = base; i < n + base; i++){ arr[i] = scanner.nextLong(); } return arr; } int[][] nextIntGrid(int n, int m, int base){ int[][] grid = new int[n + base][m + base]; for(int i = base; i < n + base; i++){ for(int j = base; j < m + base; j++){ grid[i][j] = scanner.nextInt(); } } return grid; } Map<Integer, List<Integer>> nextSimpleGraph(int numOfVertices, int numOfEdges, boolean directed){ Map<Integer, List<Integer>> g = new HashMap<>(); for(int i = 1; i <= numOfVertices; i++){ g.put(i, new ArrayList<>()); } for(int i = 1; i <= numOfEdges; i++){ int u = scanner.nextInt(); int v = scanner.nextInt(); g.get(u).add(v); if(!directed){g.get(v).add(u);} } return g; } } //------ debug and print functions ------// void debug(Object...o){ out.println(Arrays.deepToString(o)); } void print(Object...o) { for(int i = 0; i < o.length; i++){ out.print(Arrays.toString(o)); out.print(i == o.length-1? '\n':' '); } } void println(Object...o){ for(int i = 0; i < o.length; i++){ out.println(Arrays.toString(o)); } } void println(Object o){ out.println(o); } //------ sort primitive data types arrays ------// static void sort(int[] arr){ List<Integer> temp = new ArrayList<>(); for(int val: arr){temp.add(val);} Collections.sort(temp); for(int i = 0; i < arr.length; i++){arr[i] = temp.get(i);} } static void sort(long[] arr){ List<Long> temp = new ArrayList<>(); for(long val: arr){temp.add(val);} Collections.sort(temp); for(int i = 0; i < arr.length; i++){arr[i] = temp.get(i);} } }
Java
["4\n1 1\nL\n1 2\nL\n3 3\nRRDLUU\n4 3\nLUURRDDLLLUU"]
2 seconds
["1 1\n1 2\n2 1\n3 2"]
null
Java 11
standard input
[ "implementation" ]
585bb4a040144da39ed240366193e705
The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. In the description of each test case, the first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^6$$$) — the height and width of the field that the robot is located on. The second line of the description is a string $$$s$$$ consisting solely of characters 'L', 'R', 'D' and 'U' — the sequence of commands the robot executes. The string has a length from $$$1$$$ to $$$10^6$$$ commands. It is guaranteed that the total length of $$$s$$$ over all test cases does not exceed $$$10^6$$$.
1,600
Print $$$t$$$ lines, each of which contains the answer to the corresponding test case. The answer to the test case are two integers $$$r$$$ ($$$1 \leq r \leq n$$$) and $$$c$$$ ($$$1 \leq c \leq m$$$), separated by a space — the coordinates of the cell (row number and column number) from which the robot should start moving to perform as many commands as possible. If there are several such cells, you may output any of them.
standard output
PASSED
f5af44450ddb7c32a4785f7c91f9de92
train_108.jsonl
1635863700
The robot is located on a checkered rectangular board of size $$$n \times m$$$ ($$$n$$$ rows, $$$m$$$ columns). The rows in the board are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and the columns — from $$$1$$$ to $$$m$$$ from left to right.The robot is able to move from the current cell to one of the four cells adjacent by side.The sequence of commands $$$s$$$ executed by the robot is given. Each command is denoted by one of the symbols 'L', 'R', 'D' or 'U', and triggers the movement to left, right, down or up, respectively.The robot can start its movement in any cell. The robot executes the commands starting from the first one, strictly in the order in which they are listed in $$$s$$$. If the robot moves beyond the edge of the board, it falls and breaks. A command that causes the robot to break is not considered successfully executed.The robot's task is to execute as many commands as possible without falling off the board. For example, on board $$$3 \times 3$$$, if the robot starts a sequence of actions $$$s=$$$"RRDLUU" ("right", "right", "down", "left", "up", "up") from the central cell, the robot will perform one command, then the next command will force him to cross the edge. If the robot starts moving from the cell $$$(2, 1)$$$ (second row, first column) then all commands will be executed successfully and the robot will stop at the cell $$$(1, 2)$$$ (first row, second column). The robot starts from cell $$$(2, 1)$$$ (second row, first column). It moves right, right, down, left, up, and up. In this case it ends in the cell $$$(1, 2)$$$ (first row, second column). Determine the cell from which the robot should start its movement in order to execute as many commands as possible.
256 megabytes
import java.io.*; import java.lang.*; import java.util.*; public class Main { public static int mod = (int)1e9 + 7; // **** -----> Disjoint Set Union(DSU) Start ********** public static int findPar(int node, int[] parent) { if (parent[node] == node) return node; return parent[node] = findPar(parent[node], parent); } public static boolean union(int u, int v, int[] rank, int[] parent) { u = findPar(u, parent); v = findPar(v, parent); if(u == v) return false; if (rank[u] < rank[v]) parent[u] = v; else if (rank[u] > rank[v]) parent[v] = u; else { parent[u] = v; rank[v]++; } return true; } // **** DSU Ends *********** //Pair with int int public static class Pair{ public int a; public int b; Pair(int a , int b){ this.a = a; this.b = b; } @Override public String toString(){ return a + " -> " + b; } } public static String toBinary(int n) {return Integer.toBinaryString(n);} public static boolean isPalindrome(String s) {int i = 0, j = s.length() - 1;while (i < j) {if (s.charAt(i) != s.charAt(j))return false;i++;j--;}return true;} public static boolean isPalindrome(int[] arr) {int i = 0, j = arr.length - 1;while (i < j) {if (arr[i] != arr[j])return false;}return true;} public static int pow(int x, int y) {int res = 1;x = x % mod;if (x == 0)return 0;while (y > 0) {if ((y & 1) != 0)res = (res * x) % mod;y = y >> 1;x = (x * x) % mod;}return res;} public static int gcd(int a, int b) {if (b == 0)return a;return gcd(b, a % b);} public static long gcd(long a, long b) {if (b == 0)return a;return gcd(b, a % b);} public static void sort(long[] a) {Random rnd = new Random();for (int i = 0; i < a.length; i++) {int pos = i + rnd.nextInt(a.length - i);long temp = a[i];a[i] = a[pos];a[pos] = temp;}Arrays.sort(a);} public static void reverse(int a[]) {int i, k, t, n = a.length;for (i = 0; i < n / 2; i++) {t = a[i];a[i] = a[n - i - 1];a[n - i - 1] = t;}} public static void sort(int[] a) {Random rnd = new Random();for (int i = 0; i < a.length; i++) {int pos = i + rnd.nextInt(a.length - i);int temp = a[i];a[i] = a[pos];a[pos] = temp;}Arrays.sort(a);} public static void revSort(int[] a) {Random rnd = new Random();for (int i = 0; i < a.length; i++) {int pos = i + rnd.nextInt(a.length - i);int temp = a[i];a[i] = a[pos];a[pos] = temp;}Arrays.sort(a);reverse(a);} public static long LCM(long a, long b) {if (a > b) {long t = a;a = b;b = t;}a /= gcd(a, b);return (a * b);} public static int findMax(int[] a, int left, int right) {int res = left;int max = a[left];for (int i = left + 1; i <= right; i++) {if (a[i] > max) {max = a[i];res = i;}}return res;} public static long findClosest(long arr[], long target) {int n = arr.length;if (target <= arr[0])return arr[0];if (target >= arr[n - 1])return arr[n - 1];int i = 0, j = n, mid = 0;while (i < j) {mid = (i + j) / 2;if (arr[mid] == target)return arr[mid];if (target < arr[mid]) {if (mid > 0 && target > arr[mid - 1])return getClosest(arr[mid - 1], arr[mid], target);j = mid;} else {if (mid < n - 1 && target < arr[mid + 1])return getClosest(arr[mid], arr[mid + 1], target);i = mid + 1;}}return arr[mid];} public static long getClosest(long val1, long val2, long target) {if (target - val1 >= val2 - target)return val2;else return val1;} public static int findClosest(int arr[], int target) { int n = arr.length; if (target <= arr[0]) return arr[0]; if (target >= arr[n - 1]) return arr[n - 1]; int i = 0, j = n, mid = 0; while (i < j) { mid = (i + j) / 2; if (arr[mid] == target) return arr[mid];if (target < arr[mid]) {if (mid > 0 && target > arr[mid - 1])return getClosest(arr[mid - 1], arr[mid], target);j = mid;} else {if (mid < n - 1 && target < arr[mid + 1])return getClosest(arr[mid], arr[mid + 1], target);i = mid + 1;}}return arr[mid];} public static int getClosest(int val1, int val2, int target) {if (target - val1 >= val2 - target)return val2;else return val1;} public static String reverse(String str) {StringBuilder sb = new StringBuilder(str);sb.reverse();return sb.toString();} public static boolean isPrime(int n){if (n <= 1)return false;if (n <= 3)return true;if (n % 2 == 0 || n % 3 == 0)return false;for (int i = 5; i * i <= n; i = i + 6)if (n % i == 0 || n % (i + 2) == 0)return false;return true;} public static int xorSum(int arr[], int n){int bits = 0;for (int i = 0; i < n; ++i)bits |= arr[i];int ans = bits * (int)Math.pow(2, n-1);return ans;} public static ArrayList<Integer> primeFactors(int n) { ArrayList<Integer> res = new ArrayList<>();while (n%2 == 0) { res.add(2); n = n/2; } for (int i = 3; i <= Math.sqrt(n); i = i+2) { while (n%i == 0) { res.add(i); n = n/i; } } if (n > 2) res.add(n);return res;} public static ArrayList<Long> primeFactors(long n) { ArrayList<Long> res = new ArrayList<>();while (n%2 == 0) { res.add(2L); n = n/2; } for (long i = 3; i <= Math.sqrt(n); i = i+2) { while (n%i == 0) { res.add(i); n = n/i; } } if (n > 2) res.add(n);return res;} static int lower_bound(int array[], int low, int high, int key){ int mid; while (low < high) { mid = low + (high - low) / 2; if (key <= array[mid]) high = mid; else low = mid + 1; } if (low < array.length && array[low] < key) low++; return low; } static long fastPower(long a, long b, long mod){ long ans = 1 ; while (b > 0) { if ((b&1) != 0) ans = (ans%mod * a%mod) %mod; b >>= 1 ; a = (a%mod * a%mod)%mod ; } return ans ; } /********************************* Start Here ***********************************/ // int mod = 1000000007; static HashMap<String, Integer> map; static Set<Integer> set1, set2; static boolean[] vis; public static void main(String[] args) throws java.lang.Exception { if (System.getProperty("ONLINE_JUDGE") == null) { PrintStream ps = new PrintStream(new File("output.txt")); System.setOut(ps); } FastScanner sc = new FastScanner("input.txt"); StringBuilder result = new StringBuilder(); // sieveOfEratosthenes(1000000); int T = sc.nextInt(); // int T = 1; for(int test = 1; test <= T; test++){ int n = sc.nextInt(); int m = sc.nextInt(); String s = sc.next(); int low = 0, hi = s.length()-1, r1 = 0, r2 = 0; while(low <= hi){ int l = 0, r = 0, u = 0, d = 0; int x = 0, y = 0; int mid = (low+hi)/2; for(int i = 0; i <= mid; i++){ if(s.charAt(i) == 'L'){ y--; l = Math.min(l, y); }else if(s.charAt(i) == 'R'){ y++; r = Math.max(r, y); }else if(s.charAt(i) == 'U'){ x--; u = Math.min(u, x); }else{ x++; d = Math.max(d, x); } } // System.out.println(x+" "+y); x = 0; y = 0; if(l < 0) y = -l; if(u < 0) x = -u; if(r-l >= m || d-u >= n) hi = mid-1; else { r1 = x; r2 = y; low = mid+1; } } result.append((r1+1)+" "+(r2+1)+"\n"); } System.out.println(result); System.out.close(); } public static long lcm(long a, long b){ if(a>b) return a/gcd(b,a) * b; return b/gcd(a,b) * a; } public static int[] difference(int[] start, int[] stop){ int[] res = new int[2]; if(start[1] > stop[1]){ --stop[0]; stop[1] += 60; } res[1] = stop[1] - start[1]; res[0] = stop[0] - start[0]; // return the difference time return res; } // static void sieveOfEratosthenes(int n){ // boolean prime[] = new boolean[n + 1]; // for (int i = 0; i <= n; i++) // prime[i] = true; // for (int p = 2; p * p <= n; p++){ // if (prime[p] == true){ // for (int i = p * p; i <= n; i += p) // prime[i] = false; // } // } // for (int i = 2; i <= n; i++){ // if (prime[i] == true) // set.add(i); // } // } // public int[] ncr(){ // int ncr[][] = new int[1001][1001]; // for (int i = 0; i < 1001; i++) { // ncr[i][0] = 1; // } // for (int i = 1; i < 1001; i++) { // for (int j = 1; j <= i; j++) { // if (i == j) { // ncr[i][j] = 1; // continue; // } // ncr[i][j] = (ncr[i - 1][j]+ncr[i - 1][j - 1])%mod; // } // } // } public static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(String s) { try { br = new BufferedReader(new FileReader(s)); } catch (FileNotFoundException e) { 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(); } public String nextLine() { if (st == null || !st.hasMoreTokens()) { try { return br.readLine(); } catch (IOException e) { throw new RuntimeException(e); } } return st.nextToken("\n"); } public String[] readStringArray(int n) { String[] a = new String[n]; for (int i = 0; i < n; i++) { a[i] = next(); } return a; } int nextInt() { return Integer.parseInt(nextToken()); } String next() { return nextToken(); } long nextLong() { return Long.parseLong(nextToken()); } double nextDouble() { return Double.parseDouble(nextToken()); } int[] readArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } int[][] readArray(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] = nextInt(); } } return a; } long[] readLongArray(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } long[][] readLongArray(int n, int m) { long[][] a = new long[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { a[i][j] = nextLong(); } } return a; } } }
Java
["4\n1 1\nL\n1 2\nL\n3 3\nRRDLUU\n4 3\nLUURRDDLLLUU"]
2 seconds
["1 1\n1 2\n2 1\n3 2"]
null
Java 11
standard input
[ "implementation" ]
585bb4a040144da39ed240366193e705
The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. In the description of each test case, the first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^6$$$) — the height and width of the field that the robot is located on. The second line of the description is a string $$$s$$$ consisting solely of characters 'L', 'R', 'D' and 'U' — the sequence of commands the robot executes. The string has a length from $$$1$$$ to $$$10^6$$$ commands. It is guaranteed that the total length of $$$s$$$ over all test cases does not exceed $$$10^6$$$.
1,600
Print $$$t$$$ lines, each of which contains the answer to the corresponding test case. The answer to the test case are two integers $$$r$$$ ($$$1 \leq r \leq n$$$) and $$$c$$$ ($$$1 \leq c \leq m$$$), separated by a space — the coordinates of the cell (row number and column number) from which the robot should start moving to perform as many commands as possible. If there are several such cells, you may output any of them.
standard output
PASSED
945530cdd1a01aee72e4ea9970078ac8
train_108.jsonl
1635863700
The robot is located on a checkered rectangular board of size $$$n \times m$$$ ($$$n$$$ rows, $$$m$$$ columns). The rows in the board are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and the columns — from $$$1$$$ to $$$m$$$ from left to right.The robot is able to move from the current cell to one of the four cells adjacent by side.The sequence of commands $$$s$$$ executed by the robot is given. Each command is denoted by one of the symbols 'L', 'R', 'D' or 'U', and triggers the movement to left, right, down or up, respectively.The robot can start its movement in any cell. The robot executes the commands starting from the first one, strictly in the order in which they are listed in $$$s$$$. If the robot moves beyond the edge of the board, it falls and breaks. A command that causes the robot to break is not considered successfully executed.The robot's task is to execute as many commands as possible without falling off the board. For example, on board $$$3 \times 3$$$, if the robot starts a sequence of actions $$$s=$$$"RRDLUU" ("right", "right", "down", "left", "up", "up") from the central cell, the robot will perform one command, then the next command will force him to cross the edge. If the robot starts moving from the cell $$$(2, 1)$$$ (second row, first column) then all commands will be executed successfully and the robot will stop at the cell $$$(1, 2)$$$ (first row, second column). The robot starts from cell $$$(2, 1)$$$ (second row, first column). It moves right, right, down, left, up, and up. In this case it ends in the cell $$$(1, 2)$$$ (first row, second column). Determine the cell from which the robot should start its movement in order to execute as many commands as possible.
256 megabytes
// Hydro submission #62c56285c3a9fda5622969a1@1657102982467 import java.io.*; import java.util.*; public class E1607 { static String s; static int N, M, L; public static void main(String[] args) throws IOException, FileNotFoundException { Kattio in = new Kattio(); int T = in.nextInt(); while(T > 0){ N = in.nextInt(); M = in.nextInt(); s = in.next(); L = s.length(); int a = 0; int b = L; while(a != b){ int mid = (a + b + 1)/2; if(works(mid)){ a = mid; } else { b = mid - 1; } } int left = calculateMaximum('L', 'R', a); int right = calculateMaximum('R', 'L', a); int up = calculateMaximum('U', 'D', a); int down = calculateMaximum('D', 'U', a); System.out.println((1 + up) + " " + (1 + left)); T--; } } public static boolean works(int last){ int left = calculateMaximum('L', 'R', last); int right = calculateMaximum('R', 'L', last); int up = calculateMaximum('U', 'D', last); int down = calculateMaximum('D', 'U', last); int minLeft = 1 + left; int maxRight = M - right; int minUp = 1 + up; int maxDown = N - down; if(minLeft <= maxRight && minUp <= maxDown){ return true; } return false; } public static int calculateMaximum(char direction, char opposite, int last){ int max = 0; int curr = 0; for(int i = 0; i < last; i++){ if(s.charAt(i) == direction){ curr++; } else if (s.charAt(i) == opposite) { curr--; } max = Math.max(max, curr); } return max; } static class Kattio extends PrintWriter { private BufferedReader r; private StringTokenizer st; public Kattio() { this(System.in, System.out); } public Kattio(InputStream i, OutputStream o) { super(o); r = new BufferedReader(new InputStreamReader(i)); } public Kattio(String problemName) throws IOException { super(problemName + ".out"); r = new BufferedReader(new FileReader(problemName + ".in")); } public String next() { try { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(r.readLine()); return st.nextToken(); } catch (Exception e) { } return null; } public int nextInt() { return Integer.parseInt(next()); } public double nextDouble() { return Double.parseDouble(next()); } public long nextLong() { return Long.parseLong(next()); } } }
Java
["4\n1 1\nL\n1 2\nL\n3 3\nRRDLUU\n4 3\nLUURRDDLLLUU"]
2 seconds
["1 1\n1 2\n2 1\n3 2"]
null
Java 11
standard input
[ "implementation" ]
585bb4a040144da39ed240366193e705
The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. In the description of each test case, the first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^6$$$) — the height and width of the field that the robot is located on. The second line of the description is a string $$$s$$$ consisting solely of characters 'L', 'R', 'D' and 'U' — the sequence of commands the robot executes. The string has a length from $$$1$$$ to $$$10^6$$$ commands. It is guaranteed that the total length of $$$s$$$ over all test cases does not exceed $$$10^6$$$.
1,600
Print $$$t$$$ lines, each of which contains the answer to the corresponding test case. The answer to the test case are two integers $$$r$$$ ($$$1 \leq r \leq n$$$) and $$$c$$$ ($$$1 \leq c \leq m$$$), separated by a space — the coordinates of the cell (row number and column number) from which the robot should start moving to perform as many commands as possible. If there are several such cells, you may output any of them.
standard output
PASSED
2d266cc438ff00fea3751b4ba3aee2fa
train_108.jsonl
1635863700
The robot is located on a checkered rectangular board of size $$$n \times m$$$ ($$$n$$$ rows, $$$m$$$ columns). The rows in the board are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and the columns — from $$$1$$$ to $$$m$$$ from left to right.The robot is able to move from the current cell to one of the four cells adjacent by side.The sequence of commands $$$s$$$ executed by the robot is given. Each command is denoted by one of the symbols 'L', 'R', 'D' or 'U', and triggers the movement to left, right, down or up, respectively.The robot can start its movement in any cell. The robot executes the commands starting from the first one, strictly in the order in which they are listed in $$$s$$$. If the robot moves beyond the edge of the board, it falls and breaks. A command that causes the robot to break is not considered successfully executed.The robot's task is to execute as many commands as possible without falling off the board. For example, on board $$$3 \times 3$$$, if the robot starts a sequence of actions $$$s=$$$"RRDLUU" ("right", "right", "down", "left", "up", "up") from the central cell, the robot will perform one command, then the next command will force him to cross the edge. If the robot starts moving from the cell $$$(2, 1)$$$ (second row, first column) then all commands will be executed successfully and the robot will stop at the cell $$$(1, 2)$$$ (first row, second column). The robot starts from cell $$$(2, 1)$$$ (second row, first column). It moves right, right, down, left, up, and up. In this case it ends in the cell $$$(1, 2)$$$ (first row, second column). Determine the cell from which the robot should start its movement in order to execute as many commands as possible.
256 megabytes
// JAI SHREE RAM, HAR HAR MAHADEV, HARE KRISHNA import java.util.*; import java.util.Map.Entry; import java.util.stream.*; import java.lang.*; import java.math.BigInteger; import java.text.DecimalFormat; import java.io.*; public class CodeForces { static private final String INPUT = "input.txt"; static private final String OUTPUT = "output.txt"; static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); static StringTokenizer st; static PrintWriter out = new PrintWriter(System.out); static DecimalFormat df = new DecimalFormat("0.00000"); final static int MAX = Integer.MAX_VALUE, MIN = Integer.MIN_VALUE, mod = (int) (1e9 + 7); final static long LMAX = Long.MAX_VALUE, LMIN = Long.MIN_VALUE; final static long INF = (long) 1e18, Neg_INF = (long) -1e18; static Random rand = new Random(); // ======================= MAIN ================================== public static void main(String[] args) throws IOException { long time = System.currentTimeMillis(); boolean oj = System.getProperty("ONLINE_JUDGE") != null; // ==== start ==== input(); preprocess(); int t = 1; t = readInt(); while (t-- > 0) { solve(); } out.flush(); // ==== end ==== if (!oj) System.out.println(Arrays.deepToString(new Object[] { System.currentTimeMillis() - time + " ms" })); } private static void solve() throws IOException { int n = readInt(), m = readInt(); String s = readLine(); int ml = 0, mr = 0, mu = 0, md = 0; int l = 0, r = 0, u = 0, d = 0; for (char ch : s.toCharArray()) { int MU = mu, MD = md, ML = ml, MR = mr; if (ch == 'U') { if (d > 0) d--; else u++; MU = Math.max(MU, u); } else if (ch == 'D') { if (u > 0) u--; else d++; MD = Math.max(MD, d); } else if (ch == 'L') { if (r > 0) r--; else l++; ML = Math.max(ML, l); } else { if (l > 0) l--; else r++; MR = Math.max(MR, r); } if (MD + MU >= n || ML + MR >= m) break; mu = MU; md = MD; ml = ML; mr = MR; } out.println((1 + mu) + " " + (1 + ml)); } private static void preprocess() throws IOException { } // cd C:\Users\Eshan Bhatt\Visual Studio Code\Competitive Programming\CodeForces // javac CodeForces.java // java CodeForces // javac CodeForces.java && java CodeForces // change Stack size -> java -Xss16M CodeForces.java // ==================== CUSTOM CLASSES ================================ static class Pair implements Comparable<Pair> { int first, second; Pair(int f, int s) { first = f; second = s; } public int compareTo(Pair o) { if (this.first == o.first) return this.second - o.second; return this.first - o.first; } @Override public boolean equals(Object obj) { if (obj == this) return true; if (obj == null) return false; if (this.getClass() != obj.getClass()) return false; Pair other = (Pair) (obj); if (this.first != other.first) return false; if (this.second != other.second) return false; return true; } @Override public int hashCode() { return this.first ^ this.second; } @Override public String toString() { return this.first + " " + this.second; } } static class DequeNode { DequeNode prev, next; int val; DequeNode(int val) { this.val = val; } DequeNode(int val, DequeNode prev, DequeNode next) { this.val = val; this.prev = prev; this.next = next; } } // ======================= FOR INPUT ================================== private static void input() { FileInputStream instream = null; PrintStream outstream = null; try { instream = new FileInputStream(INPUT); outstream = new PrintStream(new FileOutputStream(OUTPUT)); System.setIn(instream); System.setOut(outstream); } catch (Exception e) { System.err.println("Error Occurred."); } br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } static String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(readLine()); return st.nextToken(); } static long readLong() throws IOException { return Long.parseLong(next()); } static int readInt() throws IOException { return Integer.parseInt(next()); } static double readDouble() throws IOException { return Double.parseDouble(next()); } static char readCharacter() throws IOException { return next().charAt(0); } static String readString() throws IOException { return next(); } static String readLine() throws IOException { return br.readLine().trim(); } static int[] readIntArray(int n) throws IOException { int[] arr = new int[n]; for (int i = 0; i < n; i++) arr[i] = readInt(); return arr; } static int[][] read2DIntArray(int n, int m) throws IOException { int[][] arr = new int[n][m]; for (int i = 0; i < n; i++) arr[i] = readIntArray(m); return arr; } static List<Integer> readIntList(int n) throws IOException { List<Integer> list = new ArrayList<>(n); for (int i = 0; i < n; i++) list.add(readInt()); return list; } static long[] readLongArray(int n) throws IOException { long[] arr = new long[n]; for (int i = 0; i < n; i++) arr[i] = readLong(); return arr; } static long[][] read2DLongArray(int n, int m) throws IOException { long[][] arr = new long[n][m]; for (int i = 0; i < n; i++) arr[i] = readLongArray(m); return arr; } static List<Long> readLongList(int n) throws IOException { List<Long> list = new ArrayList<>(n); for (int i = 0; i < n; i++) list.add(readLong()); return list; } static char[] readCharArray() throws IOException { return readString().toCharArray(); } static char[][] readMatrix(int n, int m) throws IOException { char[][] mat = new char[n][m]; for (int i = 0; i < n; i++) mat[i] = readCharArray(); return mat; } // ========================= FOR OUTPUT ================================== private static void printIList(List<Integer> list) { for (int i = 0; i < list.size(); i++) out.print(list.get(i) + " "); out.println(" "); } private static void printLList(List<Long> list) { for (int i = 0; i < list.size(); i++) out.print(list.get(i) + " "); out.println(" "); } private static void printIArray(int[] arr) { for (int i = 0; i < arr.length; i++) out.print(arr[i] + " "); out.println(" "); } private static void print2DIArray(int[][] arr) { for (int i = 0; i < arr.length; i++) printIArray(arr[i]); } private static void printLArray(long[] arr) { for (int i = 0; i < arr.length; i++) out.print(arr[i] + " "); out.println(" "); } private static void print2DLArray(long[][] arr) { for (int i = 0; i < arr.length; i++) printLArray(arr[i]); } private static void yes() { out.println("YES"); } private static void no() { out.println("NO"); } // ====================== TO CHECK IF STRING IS NUMBER ======================== private static boolean isInteger(String s) { try { Integer.parseInt(s); } catch (NumberFormatException e) { return false; } catch (NullPointerException e) { return false; } return true; } private static boolean isLong(String s) { try { Long.parseLong(s); } catch (NumberFormatException e) { return false; } catch (NullPointerException e) { return false; } return true; } // ==================== FASTER SORT ================================ private static void sort(int[] arr) { int n = arr.length; List<Integer> list = new ArrayList<>(n); for (int i = 0; i < n; i++) list.add(arr[i]); Collections.sort(list); for (int i = 0; i < n; i++) arr[i] = list.get(i); } private static void reverseSort(int[] arr) { int n = arr.length; List<Integer> list = new ArrayList<>(n); for (int i = 0; i < n; i++) list.add(arr[i]); Collections.sort(list, Collections.reverseOrder()); for (int i = 0; i < n; i++) arr[i] = list.get(i); } private static void sort(long[] arr) { int n = arr.length; List<Long> list = new ArrayList<>(n); for (int i = 0; i < n; i++) list.add(arr[i]); Collections.sort(list); for (int i = 0; i < n; i++) arr[i] = list.get(i); } private static void reverseSort(long[] arr) { int n = arr.length; List<Long> list = new ArrayList<>(n); for (int i = 0; i < n; i++) list.add(arr[i]); Collections.sort(list, Collections.reverseOrder()); for (int i = 0; i < n; i++) arr[i] = list.get(i); } // ==================== MATHEMATICAL FUNCTIONS =========================== private static int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } private static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } private static int lcm(int a, int b) { return (a / gcd(a, b)) * b; } private static long lcm(long a, long b) { return (a / gcd(a, b)) * b; } private static int mod_pow(long a, long b, int mod) { if (b == 0) return 1; int temp = mod_pow(a, b >> 1, mod); temp %= mod; temp = (int) ((1L * temp * temp) % mod); if ((b & 1) == 1) temp = (int) ((1L * temp * a) % mod); return temp; } private static int multiply(int a, int b) { return (int) ((((1L * a) % mod) * ((1L * b) % mod)) % mod); } private static int divide(int a, int b) { return multiply(a, mod_pow(b, mod - 2, mod)); } private static boolean isPrime(long n) { for (long i = 2; i * i <= n; i++) if (n % i == 0) return false; return true; } private static long nCr(long n, long r) { if (n - r > r) r = n - r; long ans = 1L; for (long i = r + 1; i <= n; i++) ans *= i; for (long i = 2; i <= n - r; i++) ans /= i; return ans; } private static List<Integer> factors(int n) { List<Integer> list = new ArrayList<>(); for (int i = 1; 1L * i * i <= n; i++) if (n % i == 0) { list.add(i); if (i != n / i) list.add(n / i); } return list; } private static List<Long> factors(long n) { List<Long> list = new ArrayList<>(); for (long i = 1; i * i <= n; i++) if (n % i == 0) { list.add(i); if (i != n / i) list.add(n / i); } return list; } // ==================== Primes using Seive ===================== private static List<Integer> getPrimes(int n) { boolean[] prime = new boolean[n + 1]; Arrays.fill(prime, true); for (int i = 2; 1L * i * i <= n; i++) if (prime[i]) for (int j = i * i; j <= n; j += i) prime[j] = false; // return prime; List<Integer> list = new ArrayList<>(); for (int i = 2; i <= n; i++) if (prime[i]) list.add(i); return list; } private static int[] SeivePrime(int n) { int[] primes = new int[n]; for (int i = 0; i < n; i++) primes[i] = i; for (int i = 2; 1L * i * i < n; i++) { if (primes[i] != i) continue; for (int j = i * i; j < n; j += i) if (primes[j] == j) primes[j] = i; } return primes; } // ==================== STRING FUNCTIONS ================================ private static boolean isPalindrome(String str) { int i = 0, j = str.length() - 1; while (i < j) if (str.charAt(i++) != str.charAt(j--)) return false; return true; } // check if a is subsequence of b private static boolean isSubsequence(String a, String b) { int idx = 0; for (int i = 0; i < b.length() && idx < a.length(); i++) if (a.charAt(idx) == b.charAt(i)) idx++; return idx == a.length(); } private static String reverseString(String str) { StringBuilder sb = new StringBuilder(str); return sb.reverse().toString(); } private static String sortString(String str) { int[] arr = new int[256]; for (char ch : str.toCharArray()) arr[ch]++; StringBuilder sb = new StringBuilder(); for (int i = 0; i < 256; i++) while (arr[i]-- > 0) sb.append((char) i); return sb.toString(); } // ==================== LIS & LNDS ================================ private static int LIS(int arr[], int n) { List<Integer> list = new ArrayList<>(); for (int i = 0; i < n; i++) { int idx = find1(list, arr[i]); if (idx < list.size()) list.set(idx, arr[i]); else list.add(arr[i]); } return list.size(); } private static int find1(List<Integer> list, int val) { int ret = list.size(), i = 0, j = list.size() - 1; while (i <= j) { int mid = (i + j) / 2; if (list.get(mid) >= val) { ret = mid; j = mid - 1; } else { i = mid + 1; } } return ret; } private static int LNDS(int[] arr, int n) { List<Integer> list = new ArrayList<>(); for (int i = 0; i < n; i++) { int idx = find2(list, arr[i]); if (idx < list.size()) list.set(idx, arr[i]); else list.add(arr[i]); } return list.size(); } private static int find2(List<Integer> list, int val) { int ret = list.size(), i = 0, j = list.size() - 1; while (i <= j) { int mid = (i + j) / 2; if (list.get(mid) <= val) { i = mid + 1; } else { ret = mid; j = mid - 1; } } return ret; } // =============== Lower Bound & Upper Bound =========== // less than or equal private static int lower_bound(List<Integer> list, int val) { int ans = -1, lo = 0, hi = list.size() - 1; while (lo <= hi) { int mid = (lo + hi) / 2; if (list.get(mid) <= val) { ans = mid; lo = mid + 1; } else { hi = mid - 1; } } return ans; } private static int lower_bound(List<Long> list, long val) { int ans = -1, lo = 0, hi = list.size() - 1; while (lo <= hi) { int mid = (lo + hi) / 2; if (list.get(mid) <= val) { ans = mid; lo = mid + 1; } else { hi = mid - 1; } } return ans; } private static int lower_bound(int[] arr, int val) { int ans = -1, lo = 0, hi = arr.length - 1; while (lo <= hi) { int mid = (lo + hi) / 2; if (arr[mid] <= val) { ans = mid; lo = mid + 1; } else { hi = mid - 1; } } return ans; } private static int lower_bound(long[] arr, long val) { int ans = -1, lo = 0, hi = arr.length - 1; while (lo <= hi) { int mid = (lo + hi) / 2; if (arr[mid] <= val) { ans = mid; lo = mid + 1; } else { hi = mid - 1; } } return ans; } // greater than or equal private static int upper_bound(List<Integer> list, int val) { int ans = list.size(), lo = 0, hi = ans - 1; while (lo <= hi) { int mid = (lo + hi) / 2; if (list.get(mid) >= val) { ans = mid; hi = mid - 1; } else { lo = mid + 1; } } return ans; } private static int upper_bound(List<Long> list, long val) { int ans = list.size(), lo = 0, hi = ans - 1; while (lo <= hi) { int mid = (lo + hi) / 2; if (list.get(mid) >= val) { ans = mid; hi = mid - 1; } else { lo = mid + 1; } } return ans; } private static int upper_bound(int[] arr, int val) { int ans = arr.length, lo = 0, hi = ans - 1; while (lo <= hi) { int mid = (lo + hi) / 2; if (arr[mid] >= val) { ans = mid; hi = mid - 1; } else { lo = mid + 1; } } return ans; } private static int upper_bound(long[] arr, long val) { int ans = arr.length, lo = 0, hi = ans - 1; while (lo <= hi) { int mid = (lo + hi) / 2; if (arr[mid] >= val) { ans = mid; hi = mid - 1; } else { lo = mid + 1; } } return ans; } // ==================== UNION FIND ===================== private static int find(int x, int[] parent) { if (parent[x] == x) return x; return parent[x] = find(parent[x], parent); } private static boolean union(int x, int y, int[] parent, int[] rank) { int lx = find(x, parent), ly = find(y, parent); if (lx == ly) return false; if (rank[lx] > rank[ly]) parent[ly] = lx; else if (rank[lx] < rank[ly]) parent[lx] = ly; else { parent[lx] = ly; rank[ly]++; } return true; } // ==================== TRIE ================================ static class Trie { class Node { Node[] children; boolean isEnd; Node() { children = new Node[26]; } } Node root; Trie() { root = new Node(); } void insert(String word) { Node curr = root; for (char ch : word.toCharArray()) { if (curr.children[ch - 'a'] == null) curr.children[ch - 'a'] = new Node(); curr = curr.children[ch - 'a']; } curr.isEnd = true; } boolean find(String word) { Node curr = root; for (char ch : word.toCharArray()) { if (curr.children[ch - 'a'] == null) return false; curr = curr.children[ch - 'a']; } return curr.isEnd; } } // ================== SEGMENT TREE (RANGE SUM & RANGE UPDATE) ================== public static class SegmentTree { int n; long[] arr, tree, lazy; SegmentTree(long arr[]) { this.arr = arr; this.n = arr.length; this.tree = new long[(n << 2)]; this.lazy = new long[(n << 2)]; build(1, 0, n - 1); } void build(int id, int start, int end) { if (start == end) tree[id] = arr[start]; else { int mid = (start + end) / 2, left = (id << 1), right = left + 1; build(left, start, mid); build(right, mid + 1, end); tree[id] = tree[left] + tree[right]; } } void update(int l, int r, long val) { update(1, 0, n - 1, l, r, val); } void update(int id, int start, int end, int l, int r, long val) { distribute(id, start, end); if (end < l || r < start) return; if (start == end) tree[id] += val; else if (l <= start && end <= r) { lazy[id] += val; distribute(id, start, end); } else { int mid = (start + end) / 2, left = (id << 1), right = left + 1; update(left, start, mid, l, r, val); update(right, mid + 1, end, l, r, val); tree[id] = tree[left] + tree[right]; } } long query(int l, int r) { return query(1, 0, n - 1, l, r); } long query(int id, int start, int end, int l, int r) { if (end < l || r < start) return 0L; distribute(id, start, end); if (start == end) return tree[id]; else if (l <= start && end <= r) return tree[id]; else { int mid = (start + end) / 2, left = (id << 1), right = left + 1; return query(left, start, mid, l, r) + query(right, mid + 1, end, l, r); } } void distribute(int id, int start, int end) { if (start == end) tree[id] += lazy[id]; else { tree[id] += lazy[id] * (end - start + 1); lazy[(id << 1)] += lazy[id]; lazy[(id << 1) + 1] += lazy[id]; } lazy[id] = 0; } } // ==================== FENWICK TREE ================================ static class FT { int n; int[] arr; int[] tree; FT(int[] arr, int n) { this.arr = arr; this.n = n; this.tree = new int[n + 1]; for (int i = 1; i <= n; i++) { update(i, arr[i - 1]); } } FT(int n) { this.n = n; this.tree = new int[n + 1]; } // 1 based indexing void update(int idx, int val) { while (idx <= n) { tree[idx] += val; idx += idx & -idx; } } // 1 based indexing long query(int l, int r) { return getSum(r) - getSum(l - 1); } long getSum(int idx) { long ans = 0L; while (idx > 0) { ans += tree[idx]; idx -= idx & -idx; } return ans; } } // ==================== BINARY INDEX TREE ================================ static class BIT { long[][] tree; int n, m; BIT(int[][] mat, int n, int m) { this.n = n; this.m = m; tree = new long[n + 1][m + 1]; for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { update(i, j, mat[i - 1][j - 1]); } } } void update(int x, int y, int val) { while (x <= n) { int t = y; while (t <= m) { tree[x][t] += val; t += t & -t; } x += x & -x; } } long query(int x1, int y1, int x2, int y2) { return getSum(x2, y2) - getSum(x1 - 1, y2) - getSum(x2, y1 - 1) + getSum(x1 - 1, y1 - 1); } long getSum(int x, int y) { long ans = 0L; while (x > 0) { int t = y; while (t > 0) { ans += tree[x][t]; t -= t & -t; } x -= x & -x; } return ans; } } }
Java
["4\n1 1\nL\n1 2\nL\n3 3\nRRDLUU\n4 3\nLUURRDDLLLUU"]
2 seconds
["1 1\n1 2\n2 1\n3 2"]
null
Java 11
standard input
[ "implementation" ]
585bb4a040144da39ed240366193e705
The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. In the description of each test case, the first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^6$$$) — the height and width of the field that the robot is located on. The second line of the description is a string $$$s$$$ consisting solely of characters 'L', 'R', 'D' and 'U' — the sequence of commands the robot executes. The string has a length from $$$1$$$ to $$$10^6$$$ commands. It is guaranteed that the total length of $$$s$$$ over all test cases does not exceed $$$10^6$$$.
1,600
Print $$$t$$$ lines, each of which contains the answer to the corresponding test case. The answer to the test case are two integers $$$r$$$ ($$$1 \leq r \leq n$$$) and $$$c$$$ ($$$1 \leq c \leq m$$$), separated by a space — the coordinates of the cell (row number and column number) from which the robot should start moving to perform as many commands as possible. If there are several such cells, you may output any of them.
standard output
PASSED
2efb07a16f38cd3a1ddcb262a5790d2c
train_108.jsonl
1635863700
The robot is located on a checkered rectangular board of size $$$n \times m$$$ ($$$n$$$ rows, $$$m$$$ columns). The rows in the board are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and the columns — from $$$1$$$ to $$$m$$$ from left to right.The robot is able to move from the current cell to one of the four cells adjacent by side.The sequence of commands $$$s$$$ executed by the robot is given. Each command is denoted by one of the symbols 'L', 'R', 'D' or 'U', and triggers the movement to left, right, down or up, respectively.The robot can start its movement in any cell. The robot executes the commands starting from the first one, strictly in the order in which they are listed in $$$s$$$. If the robot moves beyond the edge of the board, it falls and breaks. A command that causes the robot to break is not considered successfully executed.The robot's task is to execute as many commands as possible without falling off the board. For example, on board $$$3 \times 3$$$, if the robot starts a sequence of actions $$$s=$$$"RRDLUU" ("right", "right", "down", "left", "up", "up") from the central cell, the robot will perform one command, then the next command will force him to cross the edge. If the robot starts moving from the cell $$$(2, 1)$$$ (second row, first column) then all commands will be executed successfully and the robot will stop at the cell $$$(1, 2)$$$ (first row, second column). The robot starts from cell $$$(2, 1)$$$ (second row, first column). It moves right, right, down, left, up, and up. In this case it ends in the cell $$$(1, 2)$$$ (first row, second column). Determine the cell from which the robot should start its movement in order to execute as many commands as possible.
256 megabytes
import java.util.*; import java.io.*; public class Main { static String io[], ss; static int n, m, k, t, N = 200010, M = 100010, P = (int)1e6+7; static int[] a = new int[N], b = new int[N]; static void solve() throws Exception { io = in.readLine().split(" "); n = ni(io[0]); m = ni(io[1]); ss = in.readLine(); int x = 0, y = 0, x1 = 1, x2 = n, y1 = 1, y2 = m; int ax = 1, ay = 1; for (int i = 0;i < ss.length();i++){ char c = ss.charAt(i); if (c == 'U') --x; if (c == 'D') ++x; if (c == 'L') --y; if (c == 'R') ++y; if (x < 0) x1 = max(x1, 1-x); if (x > 0) x2 = min(x2, n-x); if (y < 0) y1 = max(y1, 1-y); if (y > 0) y2 = min(y2, m-y); if (x1 > x2 || y1 > y2) break; ax = x1; ay = y1; } out.println(ax+" "+ay); } public static void main(String[] args) throws Exception { t = Integer.parseInt(in.readLine()); while (t-- > 0) solve(); out.flush(); } static int ni() throws IOException{input.nextToken();return (int) input.nval;} static long nl() throws IOException{input.nextToken();return (long) input.nval;} static int ni(String x) {return Integer.parseInt(x);} static long nl(String x) {return Long.parseLong(x);} static int max(int a, int b) {return a > b ? a : b;} static int min(int a, int b) {return a < b ? a : b;} static long max(long a, long b) {return a > b ? a : b;} static long min(long a, long b) {return a < b ? a : b;} static int abs(int a) {return a > 0?a:-a;} static BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); static StreamTokenizer input = new StreamTokenizer(in); static PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); }
Java
["4\n1 1\nL\n1 2\nL\n3 3\nRRDLUU\n4 3\nLUURRDDLLLUU"]
2 seconds
["1 1\n1 2\n2 1\n3 2"]
null
Java 11
standard input
[ "implementation" ]
585bb4a040144da39ed240366193e705
The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. In the description of each test case, the first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^6$$$) — the height and width of the field that the robot is located on. The second line of the description is a string $$$s$$$ consisting solely of characters 'L', 'R', 'D' and 'U' — the sequence of commands the robot executes. The string has a length from $$$1$$$ to $$$10^6$$$ commands. It is guaranteed that the total length of $$$s$$$ over all test cases does not exceed $$$10^6$$$.
1,600
Print $$$t$$$ lines, each of which contains the answer to the corresponding test case. The answer to the test case are two integers $$$r$$$ ($$$1 \leq r \leq n$$$) and $$$c$$$ ($$$1 \leq c \leq m$$$), separated by a space — the coordinates of the cell (row number and column number) from which the robot should start moving to perform as many commands as possible. If there are several such cells, you may output any of them.
standard output
PASSED
50881b1e6a16ca099b7914160c90e8bd
train_108.jsonl
1635863700
The robot is located on a checkered rectangular board of size $$$n \times m$$$ ($$$n$$$ rows, $$$m$$$ columns). The rows in the board are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and the columns — from $$$1$$$ to $$$m$$$ from left to right.The robot is able to move from the current cell to one of the four cells adjacent by side.The sequence of commands $$$s$$$ executed by the robot is given. Each command is denoted by one of the symbols 'L', 'R', 'D' or 'U', and triggers the movement to left, right, down or up, respectively.The robot can start its movement in any cell. The robot executes the commands starting from the first one, strictly in the order in which they are listed in $$$s$$$. If the robot moves beyond the edge of the board, it falls and breaks. A command that causes the robot to break is not considered successfully executed.The robot's task is to execute as many commands as possible without falling off the board. For example, on board $$$3 \times 3$$$, if the robot starts a sequence of actions $$$s=$$$"RRDLUU" ("right", "right", "down", "left", "up", "up") from the central cell, the robot will perform one command, then the next command will force him to cross the edge. If the robot starts moving from the cell $$$(2, 1)$$$ (second row, first column) then all commands will be executed successfully and the robot will stop at the cell $$$(1, 2)$$$ (first row, second column). The robot starts from cell $$$(2, 1)$$$ (second row, first column). It moves right, right, down, left, up, and up. In this case it ends in the cell $$$(1, 2)$$$ (first row, second column). Determine the cell from which the robot should start its movement in order to execute as many commands as possible.
256 megabytes
import java.io.*; import java.util.*; public class E1607 { static String s; static int N, M, L; public static void main(String[] args) throws IOException, FileNotFoundException { // Scanner in = new Scanner(new File("test.in")); Kattio in = new Kattio(); int T = in.nextInt(); while(T > 0){ N = in.nextInt(); M = in.nextInt(); s = in.next(); L = s.length(); // System.out.println("-------" + s); int a = 0; int b = L; while(a != b){ int mid = (a + b + 1)/2; if(works(mid)){ a = mid; } else { b = mid - 1; } } int left = calculateMaximum('L', 'R', a); int right = calculateMaximum('R', 'L', a); int up = calculateMaximum('U', 'D', a); int down = calculateMaximum('D', 'U', a); // System.out.println(left + " " + right + " " + up + " " + down); System.out.println((1 + up) + " " + (1 + left)); T--; } } public static boolean works(int last){ int left = calculateMaximum('L', 'R', last); int right = calculateMaximum('R', 'L', last); int up = calculateMaximum('U', 'D', last); int down = calculateMaximum('D', 'U', last); // System.out.println(last + " " + left + " " + right + " " + up + " " + down); int minLeft = 1 + left; int maxRight = M - right; int minUp = 1 + up; int maxDown = N - down; if(minLeft <= maxRight && minUp <= maxDown){ return true; } return false; } public static int calculateMaximum(char direction, char opposite, int last){ int max = 0; int curr = 0; for(int i = 0; i < last; i++){ if(s.charAt(i) == direction){ curr++; } else if (s.charAt(i) == opposite) { curr--; } max = Math.max(max, curr); } return max; } static class Kattio extends PrintWriter { private BufferedReader r; private StringTokenizer st; // standard input public Kattio() { this(System.in, System.out); } public Kattio(InputStream i, OutputStream o) { super(o); r = new BufferedReader(new InputStreamReader(i)); } // USACO-style file input public Kattio(String problemName) throws IOException { super(problemName + ".out"); r = new BufferedReader(new FileReader(problemName + ".in")); } // returns null if no more input public String next() { try { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(r.readLine()); return st.nextToken(); } catch (Exception e) { } return null; } public int nextInt() { return Integer.parseInt(next()); } public double nextDouble() { return Double.parseDouble(next()); } public long nextLong() { return Long.parseLong(next()); } } }
Java
["4\n1 1\nL\n1 2\nL\n3 3\nRRDLUU\n4 3\nLUURRDDLLLUU"]
2 seconds
["1 1\n1 2\n2 1\n3 2"]
null
Java 11
standard input
[ "implementation" ]
585bb4a040144da39ed240366193e705
The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. In the description of each test case, the first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^6$$$) — the height and width of the field that the robot is located on. The second line of the description is a string $$$s$$$ consisting solely of characters 'L', 'R', 'D' and 'U' — the sequence of commands the robot executes. The string has a length from $$$1$$$ to $$$10^6$$$ commands. It is guaranteed that the total length of $$$s$$$ over all test cases does not exceed $$$10^6$$$.
1,600
Print $$$t$$$ lines, each of which contains the answer to the corresponding test case. The answer to the test case are two integers $$$r$$$ ($$$1 \leq r \leq n$$$) and $$$c$$$ ($$$1 \leq c \leq m$$$), separated by a space — the coordinates of the cell (row number and column number) from which the robot should start moving to perform as many commands as possible. If there are several such cells, you may output any of them.
standard output
PASSED
d4ef02be692f4f5ae6adbd91a772dea0
train_108.jsonl
1635863700
The robot is located on a checkered rectangular board of size $$$n \times m$$$ ($$$n$$$ rows, $$$m$$$ columns). The rows in the board are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and the columns — from $$$1$$$ to $$$m$$$ from left to right.The robot is able to move from the current cell to one of the four cells adjacent by side.The sequence of commands $$$s$$$ executed by the robot is given. Each command is denoted by one of the symbols 'L', 'R', 'D' or 'U', and triggers the movement to left, right, down or up, respectively.The robot can start its movement in any cell. The robot executes the commands starting from the first one, strictly in the order in which they are listed in $$$s$$$. If the robot moves beyond the edge of the board, it falls and breaks. A command that causes the robot to break is not considered successfully executed.The robot's task is to execute as many commands as possible without falling off the board. For example, on board $$$3 \times 3$$$, if the robot starts a sequence of actions $$$s=$$$"RRDLUU" ("right", "right", "down", "left", "up", "up") from the central cell, the robot will perform one command, then the next command will force him to cross the edge. If the robot starts moving from the cell $$$(2, 1)$$$ (second row, first column) then all commands will be executed successfully and the robot will stop at the cell $$$(1, 2)$$$ (first row, second column). The robot starts from cell $$$(2, 1)$$$ (second row, first column). It moves right, right, down, left, up, and up. In this case it ends in the cell $$$(1, 2)$$$ (first row, second column). Determine the cell from which the robot should start its movement in order to execute as many commands as possible.
256 megabytes
import java.util.*; import java.io.*; import java.math.*; public class Main{ public static void main(String[]args){ long s = System.currentTimeMillis(); new Solver().run(); System.err.println(System.currentTimeMillis()-s+"ms"); } } class Solver{ final long mod = (long)1e9+7l; final boolean DEBUG = true, MULTIPLE_TC = true; FastReader sc; PrintWriter out; int N, M; char arr[]; void init(){ N = ni(); M = ni(); arr = nln().toCharArray(); } boolean valid(int l, int u, int r, int d){ return (r - l + 1) <= M && (d - u + 1) <= N; } void process(int testNumber){ init(); int row = 1, col = 1, l = 0, u = 0, r = 0, d = 0, posR = 0, posC = 0; for(char c : arr){ if(c == 'L'){ posC -= 1; }else if(c == 'R'){ posC += 1; }else if(c == 'U'){ posR -= 1; }else{ posR += 1; } l = Math.min(l, posC); r = Math.max(r, posC); u = Math.min(u, posR); d = Math.max(d, posR); if(!valid(l, u, r, d)){ break; } row = (-u) + 1; col = (-l) + 1; } pn(row + " " + col); } void run(){ sc = new FastReader(); out = new PrintWriter(System.out); int t = MULTIPLE_TC ? ni() : 1; for(int test = 1; test <= t; test++){ process(test); } out.flush(); } void trace(Object... o){ if(!DEBUG) return; System.err.println(Arrays.deepToString(o)); }; void pn(Object o){ out.println(o); } void p(Object o){ out.print(o); } int ni(){ return Integer.parseInt(sc.next()); } long nl(){ return Long.parseLong(sc.next()); } double nd(){ return Double.parseDouble(sc.next()); } String nln(){ return sc.nextLine(); } long gcd(long a, long b){ return (b==0)?a:gcd(b,a%b);} int gcd(int a, int b){ return (b==0)?a:gcd(b,a%b); } 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(); } String nextLine(){ String str = ""; try{ str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } } class pair implements Comparable<pair> { int first, second; public pair(int first, int second){ this.first = first; this.second = second; } @Override public int compareTo(pair ob){ if(this.first != ob.first) return this.first - ob.first; return this.second - ob.second; } @Override public String toString(){ return this.first + " " + this.second; } static public pair from(int f, int s){ return new pair(f, s); } }
Java
["4\n1 1\nL\n1 2\nL\n3 3\nRRDLUU\n4 3\nLUURRDDLLLUU"]
2 seconds
["1 1\n1 2\n2 1\n3 2"]
null
Java 11
standard input
[ "implementation" ]
585bb4a040144da39ed240366193e705
The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. In the description of each test case, the first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^6$$$) — the height and width of the field that the robot is located on. The second line of the description is a string $$$s$$$ consisting solely of characters 'L', 'R', 'D' and 'U' — the sequence of commands the robot executes. The string has a length from $$$1$$$ to $$$10^6$$$ commands. It is guaranteed that the total length of $$$s$$$ over all test cases does not exceed $$$10^6$$$.
1,600
Print $$$t$$$ lines, each of which contains the answer to the corresponding test case. The answer to the test case are two integers $$$r$$$ ($$$1 \leq r \leq n$$$) and $$$c$$$ ($$$1 \leq c \leq m$$$), separated by a space — the coordinates of the cell (row number and column number) from which the robot should start moving to perform as many commands as possible. If there are several such cells, you may output any of them.
standard output
PASSED
2238223bc30266241257640cb4b8a4c0
train_108.jsonl
1635863700
The robot is located on a checkered rectangular board of size $$$n \times m$$$ ($$$n$$$ rows, $$$m$$$ columns). The rows in the board are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and the columns — from $$$1$$$ to $$$m$$$ from left to right.The robot is able to move from the current cell to one of the four cells adjacent by side.The sequence of commands $$$s$$$ executed by the robot is given. Each command is denoted by one of the symbols 'L', 'R', 'D' or 'U', and triggers the movement to left, right, down or up, respectively.The robot can start its movement in any cell. The robot executes the commands starting from the first one, strictly in the order in which they are listed in $$$s$$$. If the robot moves beyond the edge of the board, it falls and breaks. A command that causes the robot to break is not considered successfully executed.The robot's task is to execute as many commands as possible without falling off the board. For example, on board $$$3 \times 3$$$, if the robot starts a sequence of actions $$$s=$$$"RRDLUU" ("right", "right", "down", "left", "up", "up") from the central cell, the robot will perform one command, then the next command will force him to cross the edge. If the robot starts moving from the cell $$$(2, 1)$$$ (second row, first column) then all commands will be executed successfully and the robot will stop at the cell $$$(1, 2)$$$ (first row, second column). The robot starts from cell $$$(2, 1)$$$ (second row, first column). It moves right, right, down, left, up, and up. In this case it ends in the cell $$$(1, 2)$$$ (first row, second column). Determine the cell from which the robot should start its movement in order to execute as many commands as possible.
256 megabytes
import java.io.*; import java.util.StringTokenizer; /** * Accomplished using the EduTools plugin by JetBrains https://plugins.jetbrains.com/plugin/10081-edutools * * To modify the template, go to Preferences -> Editor -> File and Code Templates -> Other */ public class Main { public static void main(String[] args) { int t = fs.nextInt(); while (t-- > 0) { int m = fs.nextInt(), n = fs.nextInt(); String s = fs.next(); int minRowDiff = 0, maxRowDiff = 0, minColDiff = 0, maxColDiff = 0; int prevMinRowDiff = 0, prevMinColDiff = 0; int currRow = 0, currCol = 0; for (int i = 0; i<s.length(); i++) { switch (s.charAt(i)) { case 'L': currCol--; break; case 'R': currCol++; break; case 'D': currRow++; break; case 'U': currRow--; break; } minRowDiff = Math.min(minRowDiff, currRow); maxRowDiff = Math.max(maxRowDiff, currRow); minColDiff = Math.min(minColDiff, currCol); maxColDiff = Math.max(maxColDiff, currCol); if (maxColDiff - minColDiff + 1 > n || maxRowDiff - minRowDiff + 1 > m) { break; } // prepare for next prevMinRowDiff = minRowDiff; prevMinColDiff = minColDiff; } o.print(-prevMinRowDiff+1); o.print(' '); o.println(-prevMinColDiff+1); } o.flush(); } static FastScanner fs = new FastScanner(); static class FastScanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } long nextLong() { return Long.parseLong(next()); } } static PrintWriter o = new PrintWriter(new OutputStreamWriter(System.out)); }
Java
["4\n1 1\nL\n1 2\nL\n3 3\nRRDLUU\n4 3\nLUURRDDLLLUU"]
2 seconds
["1 1\n1 2\n2 1\n3 2"]
null
Java 11
standard input
[ "implementation" ]
585bb4a040144da39ed240366193e705
The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. In the description of each test case, the first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^6$$$) — the height and width of the field that the robot is located on. The second line of the description is a string $$$s$$$ consisting solely of characters 'L', 'R', 'D' and 'U' — the sequence of commands the robot executes. The string has a length from $$$1$$$ to $$$10^6$$$ commands. It is guaranteed that the total length of $$$s$$$ over all test cases does not exceed $$$10^6$$$.
1,600
Print $$$t$$$ lines, each of which contains the answer to the corresponding test case. The answer to the test case are two integers $$$r$$$ ($$$1 \leq r \leq n$$$) and $$$c$$$ ($$$1 \leq c \leq m$$$), separated by a space — the coordinates of the cell (row number and column number) from which the robot should start moving to perform as many commands as possible. If there are several such cells, you may output any of them.
standard output
PASSED
03d450c1f8786645108c72e3e641b4e2
train_108.jsonl
1635863700
The robot is located on a checkered rectangular board of size $$$n \times m$$$ ($$$n$$$ rows, $$$m$$$ columns). The rows in the board are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and the columns — from $$$1$$$ to $$$m$$$ from left to right.The robot is able to move from the current cell to one of the four cells adjacent by side.The sequence of commands $$$s$$$ executed by the robot is given. Each command is denoted by one of the symbols 'L', 'R', 'D' or 'U', and triggers the movement to left, right, down or up, respectively.The robot can start its movement in any cell. The robot executes the commands starting from the first one, strictly in the order in which they are listed in $$$s$$$. If the robot moves beyond the edge of the board, it falls and breaks. A command that causes the robot to break is not considered successfully executed.The robot's task is to execute as many commands as possible without falling off the board. For example, on board $$$3 \times 3$$$, if the robot starts a sequence of actions $$$s=$$$"RRDLUU" ("right", "right", "down", "left", "up", "up") from the central cell, the robot will perform one command, then the next command will force him to cross the edge. If the robot starts moving from the cell $$$(2, 1)$$$ (second row, first column) then all commands will be executed successfully and the robot will stop at the cell $$$(1, 2)$$$ (first row, second column). The robot starts from cell $$$(2, 1)$$$ (second row, first column). It moves right, right, down, left, up, and up. In this case it ends in the cell $$$(1, 2)$$$ (first row, second column). Determine the cell from which the robot should start its movement in order to execute as many commands as possible.
256 megabytes
import java.math.BigInteger; import java.util.*; import java.io.*; public class CodeForces { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); public void solve() throws Exception { StringTokenizer st = new StringTokenizer(br.readLine()); int n = Integer.parseInt(st.nextToken()); int m = Integer.parseInt(st.nextToken()); char[] move = br.readLine().toCharArray(); int xl = 0; int xr = 0; int yh = 0; int yl = 0; int xp = 0; int yp = 0; for (char c : move) { if (c == 'L' || c == 'R') { if (c == 'L') { xp--; } else { xp++; } xl = Math.min(xl, xp); xr = Math.max(xr, xp); if (xr - xl + 1 > m) { if (c == 'L') { xl++; } else { xr--; } break; } } if (c == 'U' || c == 'D') { if (c == 'U') { yp++; } else { yp--; } yh = Math.max(yh, yp); yl = Math.min(yl, yp); if (yh - yl + 1 > n) { if (c == 'U') { yh--; } else { yl++; } break; } } } System.out.printf("%d %d%n", 1 + yh, 1 - xl); } public void run() throws Exception { int t = Integer.parseInt(br.readLine()); while (t-- > 0) { solve(); } // solve(); } public static void main(String[] args) throws Exception { new CodeForces().run(); } }
Java
["4\n1 1\nL\n1 2\nL\n3 3\nRRDLUU\n4 3\nLUURRDDLLLUU"]
2 seconds
["1 1\n1 2\n2 1\n3 2"]
null
Java 11
standard input
[ "implementation" ]
585bb4a040144da39ed240366193e705
The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. In the description of each test case, the first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^6$$$) — the height and width of the field that the robot is located on. The second line of the description is a string $$$s$$$ consisting solely of characters 'L', 'R', 'D' and 'U' — the sequence of commands the robot executes. The string has a length from $$$1$$$ to $$$10^6$$$ commands. It is guaranteed that the total length of $$$s$$$ over all test cases does not exceed $$$10^6$$$.
1,600
Print $$$t$$$ lines, each of which contains the answer to the corresponding test case. The answer to the test case are two integers $$$r$$$ ($$$1 \leq r \leq n$$$) and $$$c$$$ ($$$1 \leq c \leq m$$$), separated by a space — the coordinates of the cell (row number and column number) from which the robot should start moving to perform as many commands as possible. If there are several such cells, you may output any of them.
standard output
PASSED
65fa820f718a91a9a6064963cd9ebd1b
train_108.jsonl
1635863700
The robot is located on a checkered rectangular board of size $$$n \times m$$$ ($$$n$$$ rows, $$$m$$$ columns). The rows in the board are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and the columns — from $$$1$$$ to $$$m$$$ from left to right.The robot is able to move from the current cell to one of the four cells adjacent by side.The sequence of commands $$$s$$$ executed by the robot is given. Each command is denoted by one of the symbols 'L', 'R', 'D' or 'U', and triggers the movement to left, right, down or up, respectively.The robot can start its movement in any cell. The robot executes the commands starting from the first one, strictly in the order in which they are listed in $$$s$$$. If the robot moves beyond the edge of the board, it falls and breaks. A command that causes the robot to break is not considered successfully executed.The robot's task is to execute as many commands as possible without falling off the board. For example, on board $$$3 \times 3$$$, if the robot starts a sequence of actions $$$s=$$$"RRDLUU" ("right", "right", "down", "left", "up", "up") from the central cell, the robot will perform one command, then the next command will force him to cross the edge. If the robot starts moving from the cell $$$(2, 1)$$$ (second row, first column) then all commands will be executed successfully and the robot will stop at the cell $$$(1, 2)$$$ (first row, second column). The robot starts from cell $$$(2, 1)$$$ (second row, first column). It moves right, right, down, left, up, and up. In this case it ends in the cell $$$(1, 2)$$$ (first row, second column). Determine the cell from which the robot should start its movement in order to execute as many commands as possible.
256 megabytes
import java.io.*; import java.util.*; public class Codeforces { static long M = 1000000007; public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int cases = Integer.parseInt(br.readLine()); o:while(cases-- > 0) { StringBuffer buf = new StringBuffer(); String[] str = br.readLine().split(" "); int n = Integer.parseInt(str[0]); int m = Integer.parseInt(str[1]); String path = br.readLine(); int[] ans = {1, 1}; int[] cur = {0, 0}; // let us the start block as 0,0 and solve relatively. (horiz, vertical) int[] dp = new int[4]; // indicates extreme values traveled to L, R, U, D. all 0 currently for(int i=0; i<path.length(); i++) { if(path.charAt(i) == 'L') { cur[0]--; }else if(path.charAt(i) == 'R') { cur[0]++; }else if(path.charAt(i) == 'U') { cur[1]--; }else { cur[1]++; } // No we have an updated cur position, so lets update the extremes reached till now // since we start at 0,0 the more left we are the lesser horiz val and more right is larger horiz val dp[0] = Math.min(dp[0], cur[0]); dp[1] = Math.max(dp[1], cur[0]); dp[2] = Math.min(dp[2], cur[1]); dp[3] = Math.max(dp[3], cur[1]); // now we use use diff between extremes to see if we can still stay in if(dp[1] - dp[0] < m && dp[3] - dp[2] < n) { ans[0] = Math.abs(dp[0]) + 1; // +1 bcoz to convert 0 based index to 1 based ans[1] = Math.abs(dp[2]) + 1; } } System.out.println(ans[1] + " " + ans[0]); } } }
Java
["4\n1 1\nL\n1 2\nL\n3 3\nRRDLUU\n4 3\nLUURRDDLLLUU"]
2 seconds
["1 1\n1 2\n2 1\n3 2"]
null
Java 11
standard input
[ "implementation" ]
585bb4a040144da39ed240366193e705
The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. In the description of each test case, the first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^6$$$) — the height and width of the field that the robot is located on. The second line of the description is a string $$$s$$$ consisting solely of characters 'L', 'R', 'D' and 'U' — the sequence of commands the robot executes. The string has a length from $$$1$$$ to $$$10^6$$$ commands. It is guaranteed that the total length of $$$s$$$ over all test cases does not exceed $$$10^6$$$.
1,600
Print $$$t$$$ lines, each of which contains the answer to the corresponding test case. The answer to the test case are two integers $$$r$$$ ($$$1 \leq r \leq n$$$) and $$$c$$$ ($$$1 \leq c \leq m$$$), separated by a space — the coordinates of the cell (row number and column number) from which the robot should start moving to perform as many commands as possible. If there are several such cells, you may output any of them.
standard output
PASSED
a77f002f38ea76d1ee3d41db8211d3c7
train_108.jsonl
1635863700
The robot is located on a checkered rectangular board of size $$$n \times m$$$ ($$$n$$$ rows, $$$m$$$ columns). The rows in the board are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and the columns — from $$$1$$$ to $$$m$$$ from left to right.The robot is able to move from the current cell to one of the four cells adjacent by side.The sequence of commands $$$s$$$ executed by the robot is given. Each command is denoted by one of the symbols 'L', 'R', 'D' or 'U', and triggers the movement to left, right, down or up, respectively.The robot can start its movement in any cell. The robot executes the commands starting from the first one, strictly in the order in which they are listed in $$$s$$$. If the robot moves beyond the edge of the board, it falls and breaks. A command that causes the robot to break is not considered successfully executed.The robot's task is to execute as many commands as possible without falling off the board. For example, on board $$$3 \times 3$$$, if the robot starts a sequence of actions $$$s=$$$"RRDLUU" ("right", "right", "down", "left", "up", "up") from the central cell, the robot will perform one command, then the next command will force him to cross the edge. If the robot starts moving from the cell $$$(2, 1)$$$ (second row, first column) then all commands will be executed successfully and the robot will stop at the cell $$$(1, 2)$$$ (first row, second column). The robot starts from cell $$$(2, 1)$$$ (second row, first column). It moves right, right, down, left, up, and up. In this case it ends in the cell $$$(1, 2)$$$ (first row, second column). Determine the cell from which the robot should start its movement in order to execute as many commands as possible.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class App { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } static void solve(FastReader reader, PrintWriter writer) { int n = reader.nextInt(); int m = reader.nextInt(); String moves = reader.nextLine(); int top = 0; int bottom = n - 1; int left = 0; int right = m - 1; int minVertical = 0; int maxVertical = 0; int minHorizontal = 0; int maxHorizontal = 0; int currentVerticalStreak = 0; int currentHorizontalStreak = 0; for (int i = 0; i < moves.length(); i++) { switch (moves.charAt(i)) { case 'U' : currentVerticalStreak--; break; case 'D' : currentVerticalStreak++; break; case 'R' : currentHorizontalStreak++; break; case 'L' : currentHorizontalStreak--; } if (currentHorizontalStreak > maxHorizontal) { if (left == right) break; right--; maxHorizontal = currentHorizontalStreak; } else if (currentHorizontalStreak < minHorizontal) { if (left == right) break; left++; minHorizontal = currentHorizontalStreak; } else if (currentVerticalStreak > maxVertical) { if (top == bottom) break; bottom--; maxVertical = currentVerticalStreak; } else if (currentVerticalStreak < minVertical) { if (top == bottom) break; top++; minVertical = currentVerticalStreak; } } writer.println(top + 1 + " " + (left + 1)); } public static void main(String[] args){ FastReader reader = new FastReader(); PrintWriter writer = new PrintWriter(System.out, true); int t = reader.nextInt(); // int t = 1; for (int i = 1; i <= t; i++) { solve(reader, writer); } } }
Java
["4\n1 1\nL\n1 2\nL\n3 3\nRRDLUU\n4 3\nLUURRDDLLLUU"]
2 seconds
["1 1\n1 2\n2 1\n3 2"]
null
Java 11
standard input
[ "implementation" ]
585bb4a040144da39ed240366193e705
The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. In the description of each test case, the first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^6$$$) — the height and width of the field that the robot is located on. The second line of the description is a string $$$s$$$ consisting solely of characters 'L', 'R', 'D' and 'U' — the sequence of commands the robot executes. The string has a length from $$$1$$$ to $$$10^6$$$ commands. It is guaranteed that the total length of $$$s$$$ over all test cases does not exceed $$$10^6$$$.
1,600
Print $$$t$$$ lines, each of which contains the answer to the corresponding test case. The answer to the test case are two integers $$$r$$$ ($$$1 \leq r \leq n$$$) and $$$c$$$ ($$$1 \leq c \leq m$$$), separated by a space — the coordinates of the cell (row number and column number) from which the robot should start moving to perform as many commands as possible. If there are several such cells, you may output any of them.
standard output
PASSED
35d08507c7969d489560b8bdc3172c0e
train_108.jsonl
1635863700
The robot is located on a checkered rectangular board of size $$$n \times m$$$ ($$$n$$$ rows, $$$m$$$ columns). The rows in the board are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and the columns — from $$$1$$$ to $$$m$$$ from left to right.The robot is able to move from the current cell to one of the four cells adjacent by side.The sequence of commands $$$s$$$ executed by the robot is given. Each command is denoted by one of the symbols 'L', 'R', 'D' or 'U', and triggers the movement to left, right, down or up, respectively.The robot can start its movement in any cell. The robot executes the commands starting from the first one, strictly in the order in which they are listed in $$$s$$$. If the robot moves beyond the edge of the board, it falls and breaks. A command that causes the robot to break is not considered successfully executed.The robot's task is to execute as many commands as possible without falling off the board. For example, on board $$$3 \times 3$$$, if the robot starts a sequence of actions $$$s=$$$"RRDLUU" ("right", "right", "down", "left", "up", "up") from the central cell, the robot will perform one command, then the next command will force him to cross the edge. If the robot starts moving from the cell $$$(2, 1)$$$ (second row, first column) then all commands will be executed successfully and the robot will stop at the cell $$$(1, 2)$$$ (first row, second column). The robot starts from cell $$$(2, 1)$$$ (second row, first column). It moves right, right, down, left, up, and up. In this case it ends in the cell $$$(1, 2)$$$ (first row, second column). Determine the cell from which the robot should start its movement in order to execute as many commands as possible.
256 megabytes
import java.util.*; import java.io.*; public class Main { // when can't think of anything -->> // 1. In sorting questions try to think about all possibilities like sorting from start, end, middle. // 2. Two pointers, brute force. // 3. In graph query questions try to solve it reversely or try to process all the queries in a single parse. // 4. If order does not matter then just sort the data if constraints allow. It'll never harm. // 5. In greedy problems if you are just overwhelmed by the possibilities and stuck, try to code whatever you come up with. // 6. Think like a robot, just consider all the possibilities not probabilities if you still can't solve. // 7. Try to solve it from back or reversely. // 8. When can't prove something take help of contradiction. public static void main(String[] args) throws Exception { FastReader sc = new FastReader(); PrintWriter writer = new PrintWriter(System.out); int t = sc.nextInt(); while(t-->0) { int n = sc.nextInt(); int m = sc.nextInt(); String s = sc.next(); int up=0,un=0,rp=0,rn=0; Pair pair = new Pair(0,0); for(char c : s.toCharArray()) { if(c=='R') { int prevp = pair.a; int prevv = rp; pair.a+=1; if(pair.a>0) rp = Math.max(rp, Math.abs(pair.a)); if(rp+rn>=m) { rp = prevv; pair.a = prevp; break; } }else if(c=='L') { int prevp = pair.a; int prevv = rn; pair.a-=1; if(pair.a<0) rn = Math.max(rn, Math.abs(pair.a)); if(rp+rn>=m) { rn = prevv; pair.a = prevp; break; } }else if(c=='U') { int prevp = pair.b; int prevv = up; pair.b+=1; if(pair.b>0) up = Math.max(up, Math.abs(pair.b)); if(up+un>=n) { up = prevv; pair.b = prevp; break; } }else { int prevp = pair.b; int prevv = un; pair.b-=1; if(pair.b<0) un = Math.max(un, Math.abs(pair.b)); if(up+un>=n) { un= prevv; pair.b = prevp; break; } } } int left = rn+1; int right = m -rp; int down = n - un; int upp = up+1; //writer.println(left + " " + right); writer.println(upp + " " + left); } writer.flush(); writer.close(); } private static int findVal(String a, String b, int n) { int diff1 = 0; for(int i = 0; i < n; i++) { if(a.charAt(i) != b.charAt(i))diff1++; } return diff1; } private static long power (long a, long n, long p) { long res = 1; while(n!=0) { if(n%2==1) { res=(res*a)%p; n--; }else { a= (a*a)%p; n/=2; } } return res; } private static boolean isPrime(int c) { for (int i = 2; i*i <= c; i++) { if(c%i==0)return false; } return true; } private static int find(int a , int arr[]) { if(arr[a] != a) return arr[a] = find(arr[a], arr); return arr[a]; } private static void union(int a, int b, int arr[]) { int aa = find(a,arr); int bb = find(b, arr); arr[aa] = bb; } private static int gcd(int a, int b) { if(a==0)return b; return gcd(b%a, a); } public static int[] readIntArray(int size, FastReader s) { int[] array = new int[size]; for (int i = 0; i < size; i++) { array[i] = s.nextInt(); } return array; } 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; } } } class Pair implements Comparable<Pair>{ int a; int b; Pair(int a, int b){ this.a = a; this.b = b; } @Override public boolean equals(Object obj) { if(this == obj) return true; if(obj == null || obj.getClass()!= this.getClass()) return false; Pair pair = (Pair) obj; return (pair.a == this.a && pair.b == this.b); } @Override public int hashCode() { return Objects.hash(a,b); } @Override public int compareTo(Pair o) { if(this.a == o.a) { return Integer.compare(this.b, o.b); }else { return Integer.compare(this.a, o.a); } } @Override public String toString() { return this.a + " " + this.b; } }
Java
["4\n1 1\nL\n1 2\nL\n3 3\nRRDLUU\n4 3\nLUURRDDLLLUU"]
2 seconds
["1 1\n1 2\n2 1\n3 2"]
null
Java 11
standard input
[ "implementation" ]
585bb4a040144da39ed240366193e705
The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. In the description of each test case, the first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^6$$$) — the height and width of the field that the robot is located on. The second line of the description is a string $$$s$$$ consisting solely of characters 'L', 'R', 'D' and 'U' — the sequence of commands the robot executes. The string has a length from $$$1$$$ to $$$10^6$$$ commands. It is guaranteed that the total length of $$$s$$$ over all test cases does not exceed $$$10^6$$$.
1,600
Print $$$t$$$ lines, each of which contains the answer to the corresponding test case. The answer to the test case are two integers $$$r$$$ ($$$1 \leq r \leq n$$$) and $$$c$$$ ($$$1 \leq c \leq m$$$), separated by a space — the coordinates of the cell (row number and column number) from which the robot should start moving to perform as many commands as possible. If there are several such cells, you may output any of them.
standard output
PASSED
eaf7adcf3e10a65fb2c611f95a065cd8
train_108.jsonl
1635863700
The robot is located on a checkered rectangular board of size $$$n \times m$$$ ($$$n$$$ rows, $$$m$$$ columns). The rows in the board are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and the columns — from $$$1$$$ to $$$m$$$ from left to right.The robot is able to move from the current cell to one of the four cells adjacent by side.The sequence of commands $$$s$$$ executed by the robot is given. Each command is denoted by one of the symbols 'L', 'R', 'D' or 'U', and triggers the movement to left, right, down or up, respectively.The robot can start its movement in any cell. The robot executes the commands starting from the first one, strictly in the order in which they are listed in $$$s$$$. If the robot moves beyond the edge of the board, it falls and breaks. A command that causes the robot to break is not considered successfully executed.The robot's task is to execute as many commands as possible without falling off the board. For example, on board $$$3 \times 3$$$, if the robot starts a sequence of actions $$$s=$$$"RRDLUU" ("right", "right", "down", "left", "up", "up") from the central cell, the robot will perform one command, then the next command will force him to cross the edge. If the robot starts moving from the cell $$$(2, 1)$$$ (second row, first column) then all commands will be executed successfully and the robot will stop at the cell $$$(1, 2)$$$ (first row, second column). The robot starts from cell $$$(2, 1)$$$ (second row, first column). It moves right, right, down, left, up, and up. In this case it ends in the cell $$$(1, 2)$$$ (first row, second column). Determine the cell from which the robot should start its movement in order to execute as many commands as possible.
256 megabytes
import java.io.*; import java.lang.reflect.Constructor; import java.util.*; public class CodeE { private static final boolean SHOULD_BUFFER_OUTPUT = true; static final SuperWriter sw = new SuperWriter(System.out); static final SuperScanner sc = new SuperScanner(); public static void solve() { int n = sc.nextInt(); int m = sc.nextInt(); int leftMostColumn = 0; int rightMostColumn = 0; int leftMostRow = 0; int rightMostRow = 0; int currentColumn = 0; int currentRow = 0; int lastAnswerRow = 0; int lastAnswerColumn = 0; for (char c : sc.next().toCharArray()) { if (c == 'L') { currentColumn--; } if (c == 'R') { currentColumn++; } if (c == 'U') { currentRow--; } if (c == 'D') { currentRow++; } leftMostColumn = Math.min(leftMostColumn, currentColumn); rightMostColumn = Math.max(rightMostColumn, currentColumn); leftMostRow = Math.min(leftMostRow, currentRow); rightMostRow = Math.max(rightMostRow, currentRow); int columnsNeeded = Math.abs(leftMostColumn) + Math.abs(rightMostColumn) + 1; int rowsNeeded = Math.abs(leftMostRow) + Math.abs(rightMostRow) + 1; if (rowsNeeded > n || columnsNeeded > m) { break; } lastAnswerRow = Math.abs(leftMostRow); lastAnswerColumn = Math.abs(leftMostColumn); } sw.printLine(lastAnswerRow + 1, lastAnswerColumn + 1); } public static void main() { int t = sc.nextInt(); for (int cc = 0; cc < t; cc++) { solve(); } } static class LineScanner extends Scanner { private StringTokenizer st; public LineScanner(String input) { st = new StringTokenizer(input); } @Override public String next() { return st.hasMoreTokens() ? st.nextToken() : null; } @Override public String nextLine() { throw new RuntimeException("not supported"); } public boolean hasNext() { return st.hasMoreTokens(); } private final ArrayList<Object> temp = new ArrayList<Object>(); private void fillTemp() { while (st.hasMoreTokens()) { temp.add(st.nextToken()); } } public String[] asStringArray() { fillTemp(); String[] answer = new String[temp.size()]; for (int i = 0; i < answer.length; i++) { answer[i] = (String) temp.get(i); } temp.clear(); return answer; } public int[] asIntArray() { fillTemp(); int[] answer = new int[temp.size()]; for (int i = 0; i < answer.length; i++) { answer[i] = Integer.parseInt((String) temp.get(i)); } temp.clear(); return answer; } public long[] asLongArray() { fillTemp(); long[] answer = new long[temp.size()]; for (int i = 0; i < answer.length; i++) { answer[i] = Long.parseLong((String) temp.get(i)); } temp.clear(); return answer; } public double[] asDoubleArray() { fillTemp(); double[] answer = new double[temp.size()]; for (int i = 0; i < answer.length; i++) { answer[i] = Double.parseDouble((String) temp.get(i)); } temp.clear(); return answer; } } static class SuperScanner extends Scanner { private InputStream stream; private byte[] buf = new byte[8096]; private int curChar; private int numChars; public SuperScanner() { this.stream = System.in; } public int read() { if (numChars == -1) return -1; if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { return -1; } if (numChars <= 0) return -1; } return buf[curChar++]; } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public static boolean isLineEnd(int c) { return c == '\n' || c == -1; } private final StringBuilder sb = new StringBuilder(); @Override public String next() { int c = read(); while (isWhitespace(c)) { if (c == -1) { return null; } c = read(); } sb.setLength(0); do { sb.append((char) c); c = read(); } while (!isWhitespace(c)); return sb.toString(); } @Override public String nextLine() { sb.setLength(0); int c; while (true) { c = read(); if (!isLineEnd(c)) { sb.append((char) c); } else { break; } } if (c == -1 && sb.length() == 0) { return null; } else { if (sb.length() > 0 && sb.charAt(sb.length() - 1) == '\r') { return sb.substring(0, sb.length() - 1); } else { return sb.toString(); } } } public LineScanner nextLineScanner() { String line = nextLine(); if (line == null) { return null; } else { return new LineScanner(line); } } public LineScanner nextNonEmptyLineScanner() { while (true) { String line = nextLine(); if (line == null) { return null; } else if (!line.isEmpty()) { return new LineScanner(line); } } } @Override public int nextInt() { int c = read(); while (isWhitespace(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res = (res << 3) + (res << 1); res += c - '0'; c = read(); } while (!isWhitespace(c)); return res * sgn; } @Override public long nextLong() { int c = read(); while (isWhitespace(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res = (res << 3) + (res << 1); res += c - '0'; c = read(); } while (!isWhitespace(c)); return res * sgn; } } static abstract class Scanner { public abstract String next(); public abstract String nextLine(); public int nextIntOrQuit() { Integer n = nextInteger(); if (n == null) { sw.close(); System.exit(0); } return n.intValue(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public int[] nextIntArray(int n) { int[] res = new int[n]; for (int i = 0; i < res.length; i++) res[i] = nextInt(); return res; } public long[] nextLongArray(int n) { long[] res = new long[n]; for (int i = 0; i < res.length; i++) res[i] = nextLong(); return res; } public double[] nextDoubleArray(int n) { double[] res = new double[n]; for (int i = 0; i < res.length; i++) res[i] = nextDouble(); return res; } public void sortIntArray(int[] array) { Integer[] vals = new Integer[array.length]; for (int i = 0; i < array.length; i++) vals[i] = array[i]; Arrays.sort(vals); for (int i = 0; i < array.length; i++) array[i] = vals[i]; } public void sortLongArray(long[] array) { Long[] vals = new Long[array.length]; for (int i = 0; i < array.length; i++) vals[i] = array[i]; Arrays.sort(vals); for (int i = 0; i < array.length; i++) array[i] = vals[i]; } public void sortDoubleArray(double[] array) { Double[] vals = new Double[array.length]; for (int i = 0; i < array.length; i++) vals[i] = array[i]; Arrays.sort(vals); for (int i = 0; i < array.length; i++) array[i] = vals[i]; } public String[] nextStringArray(int n) { String[] vals = new String[n]; for (int i = 0; i < n; i++) vals[i] = next(); return vals; } public Integer nextInteger() { String s = next(); if (s == null) return null; return Integer.parseInt(s); } public int[][] nextIntMatrix(int n, int m) { int[][] ans = new int[n][]; for (int i = 0; i < n; i++) ans[i] = nextIntArray(m); return ans; } public char[][] nextGrid(int r) { char[][] grid = new char[r][]; for (int i = 0; i < r; i++) grid[i] = next().toCharArray(); return grid; } public static <T> T fill(T arreglo, int val) { if (arreglo instanceof Object[]) { Object[] a = (Object[]) arreglo; for (Object x : a) fill(x, val); } else if (arreglo instanceof int[]) Arrays.fill((int[]) arreglo, val); else if (arreglo instanceof double[]) Arrays.fill((double[]) arreglo, val); else if (arreglo instanceof long[]) Arrays.fill((long[]) arreglo, val); return arreglo; } public <T> T[] nextObjectArray(Class<T> clazz, int size) { @SuppressWarnings("unchecked") T[] result = (T[]) java.lang.reflect.Array.newInstance(clazz, size); for (int c = 0; c < 3; c++) { Constructor<T> constructor; try { if (c == 0) constructor = clazz.getDeclaredConstructor(Scanner.class, Integer.TYPE); else if (c == 1) constructor = clazz.getDeclaredConstructor(Scanner.class); else constructor = clazz.getDeclaredConstructor(); } catch (Exception e) { continue; } try { for (int i = 0; i < result.length; i++) { if (c == 0) result[i] = constructor.newInstance(this, i); else if (c == 1) result[i] = constructor.newInstance(this); else result[i] = constructor.newInstance(); } } catch (Exception e) { throw new RuntimeException(e); } return result; } throw new RuntimeException("Constructor not found"); } public Collection<Integer> wrap(int[] as) { ArrayList<Integer> ans = new ArrayList<Integer>(); for (int i : as) ans.add(i); return ans; } public int[] unwrap(Collection<Integer> collection) { int[] vals = new int[collection.size()]; int index = 0; for (int i : collection) vals[index++] = i; return vals; } int testCases = Integer.MIN_VALUE; boolean testCases() { if (testCases == Integer.MIN_VALUE) { testCases = nextInt(); } return --testCases >= 0; } } static class SuperWriter { private final PrintWriter writer; public SuperWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public SuperWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void close() { writer.flush(); writer.close(); } public void printLine(String line) { writer.println(line); if (!SHOULD_BUFFER_OUTPUT) { writer.flush(); } } public void printLine(int... vals) { if (vals.length == 0) { writer.println(); } else { writer.print(vals[0]); for (int i = 1; i < vals.length; i++) writer.print(" ".concat(String.valueOf(vals[i]))); writer.println(); } if (!SHOULD_BUFFER_OUTPUT) { writer.flush(); } } public void printLine(long... vals) { if (vals.length == 0) { writer.println(); } else { writer.print(vals[0]); for (int i = 1; i < vals.length; i++) writer.print(" ".concat(String.valueOf(vals[i]))); writer.println(); } if (!SHOULD_BUFFER_OUTPUT) { writer.flush(); } } public void printLine(double... vals) { if (vals.length == 0) { writer.println(); } else { writer.print(vals[0]); for (int i = 1; i < vals.length; i++) writer.print(" ".concat(String.valueOf(vals[i]))); writer.println(); } if (!SHOULD_BUFFER_OUTPUT) { writer.flush(); } } public void printLine(int prec, double... vals) { if (vals.length == 0) { writer.println(); } else { String precision = "%." + prec + "f"; writer.print(String.format(precision, vals[0]).replace(',', '.')); precision = " " + precision; for (int i = 1; i < vals.length; i++) writer.print(String.format(precision, vals[i]).replace(',', '.')); writer.println(); } if (!SHOULD_BUFFER_OUTPUT) { writer.flush(); } } public <E> void printLine(Collection<E> vals) { if (vals.size() == 0) { writer.println(); } else { int i = 0; for (E val : vals) { if (i++ == 0) { writer.print(val.toString()); } else { writer.print(" ".concat(val.toString())); } } writer.println(); } if (!SHOULD_BUFFER_OUTPUT) { writer.flush(); } } public void printSimple(String value) { writer.print(value); if (!SHOULD_BUFFER_OUTPUT) { writer.flush(); } } public boolean ifZeroExit(Number... values) { for (Number number : values) { if (number.doubleValue() != 0.0d || number.longValue() != 0) { return false; } } close(); System.exit(0); return true; } } public static void main(String[] args) { main(); sw.close(); } }
Java
["4\n1 1\nL\n1 2\nL\n3 3\nRRDLUU\n4 3\nLUURRDDLLLUU"]
2 seconds
["1 1\n1 2\n2 1\n3 2"]
null
Java 11
standard input
[ "implementation" ]
585bb4a040144da39ed240366193e705
The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. In the description of each test case, the first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^6$$$) — the height and width of the field that the robot is located on. The second line of the description is a string $$$s$$$ consisting solely of characters 'L', 'R', 'D' and 'U' — the sequence of commands the robot executes. The string has a length from $$$1$$$ to $$$10^6$$$ commands. It is guaranteed that the total length of $$$s$$$ over all test cases does not exceed $$$10^6$$$.
1,600
Print $$$t$$$ lines, each of which contains the answer to the corresponding test case. The answer to the test case are two integers $$$r$$$ ($$$1 \leq r \leq n$$$) and $$$c$$$ ($$$1 \leq c \leq m$$$), separated by a space — the coordinates of the cell (row number and column number) from which the robot should start moving to perform as many commands as possible. If there are several such cells, you may output any of them.
standard output
PASSED
1d59a71e4242d38a56e161403eaf8d46
train_108.jsonl
1635863700
The robot is located on a checkered rectangular board of size $$$n \times m$$$ ($$$n$$$ rows, $$$m$$$ columns). The rows in the board are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and the columns — from $$$1$$$ to $$$m$$$ from left to right.The robot is able to move from the current cell to one of the four cells adjacent by side.The sequence of commands $$$s$$$ executed by the robot is given. Each command is denoted by one of the symbols 'L', 'R', 'D' or 'U', and triggers the movement to left, right, down or up, respectively.The robot can start its movement in any cell. The robot executes the commands starting from the first one, strictly in the order in which they are listed in $$$s$$$. If the robot moves beyond the edge of the board, it falls and breaks. A command that causes the robot to break is not considered successfully executed.The robot's task is to execute as many commands as possible without falling off the board. For example, on board $$$3 \times 3$$$, if the robot starts a sequence of actions $$$s=$$$"RRDLUU" ("right", "right", "down", "left", "up", "up") from the central cell, the robot will perform one command, then the next command will force him to cross the edge. If the robot starts moving from the cell $$$(2, 1)$$$ (second row, first column) then all commands will be executed successfully and the robot will stop at the cell $$$(1, 2)$$$ (first row, second column). The robot starts from cell $$$(2, 1)$$$ (second row, first column). It moves right, right, down, left, up, and up. In this case it ends in the cell $$$(1, 2)$$$ (first row, second column). Determine the cell from which the robot should start its movement in order to execute as many commands as possible.
256 megabytes
/* "Everything in the universe is balanced. Every disappointment you face in life will be balanced by something good for you! Keep going, never give up." Just have Patience + 1... */ import java.util.*; import java.lang.*; import java.io.*; public class Solution { public static void main(String[] args) throws java.lang.Exception { out = new PrintWriter(new BufferedOutputStream(System.out)); sc = new FastReader(); int test = sc.nextInt(); for (int t = 1; t <= test; t++) { solve(); } out.close(); } private static void solve() { int rows = sc.nextInt(); int cols = sc.nextInt(); char[] moves = sc.next().toCharArray(); int n = moves.length; // since robot stops when it goes out of bound, we must choose starting position such that the largest prefix of moves for which robot is in range. int currRow = 0, currCol = 0, rowMin = 0, rowMax = 0, colMin = 0, colMax = 0; for (int i = 0; i < n; i++) { if (moves[i] == 'U') { currRow--; }else if (moves[i] == 'D') { currRow++; }else if (moves[i] == 'L') { currCol--; }else { currCol++; } int nextRowMin = Math.min(rowMin, currRow); int nextRowMax = Math.max(rowMax, currRow); int nextColMin = Math.min(colMin, currCol); int nextColMax = Math.max(colMax, currCol); if (nextRowMax - nextRowMin + 1 > rows || nextColMax - nextColMin + 1 > cols) { break; } rowMin = nextRowMin; rowMax = nextRowMax; colMin = nextColMin; colMax = nextColMax; } out.println((1 - rowMin) + " " + (1 - colMin)); } public static FastReader sc; public static PrintWriter out; static class FastReader { BufferedReader br; StringTokenizer str; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (str == null || !str.hasMoreElements()) { try { str = new StringTokenizer(br.readLine()); } catch (IOException lastMonthOfVacation) { lastMonthOfVacation.printStackTrace(); } } return str.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 lastMonthOfVacation) { lastMonthOfVacation.printStackTrace(); } return str; } } }
Java
["4\n1 1\nL\n1 2\nL\n3 3\nRRDLUU\n4 3\nLUURRDDLLLUU"]
2 seconds
["1 1\n1 2\n2 1\n3 2"]
null
Java 11
standard input
[ "implementation" ]
585bb4a040144da39ed240366193e705
The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. In the description of each test case, the first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^6$$$) — the height and width of the field that the robot is located on. The second line of the description is a string $$$s$$$ consisting solely of characters 'L', 'R', 'D' and 'U' — the sequence of commands the robot executes. The string has a length from $$$1$$$ to $$$10^6$$$ commands. It is guaranteed that the total length of $$$s$$$ over all test cases does not exceed $$$10^6$$$.
1,600
Print $$$t$$$ lines, each of which contains the answer to the corresponding test case. The answer to the test case are two integers $$$r$$$ ($$$1 \leq r \leq n$$$) and $$$c$$$ ($$$1 \leq c \leq m$$$), separated by a space — the coordinates of the cell (row number and column number) from which the robot should start moving to perform as many commands as possible. If there are several such cells, you may output any of them.
standard output
PASSED
3cd8cef3e0cb97282d1b2fa15f8c3400
train_108.jsonl
1635863700
The robot is located on a checkered rectangular board of size $$$n \times m$$$ ($$$n$$$ rows, $$$m$$$ columns). The rows in the board are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and the columns — from $$$1$$$ to $$$m$$$ from left to right.The robot is able to move from the current cell to one of the four cells adjacent by side.The sequence of commands $$$s$$$ executed by the robot is given. Each command is denoted by one of the symbols 'L', 'R', 'D' or 'U', and triggers the movement to left, right, down or up, respectively.The robot can start its movement in any cell. The robot executes the commands starting from the first one, strictly in the order in which they are listed in $$$s$$$. If the robot moves beyond the edge of the board, it falls and breaks. A command that causes the robot to break is not considered successfully executed.The robot's task is to execute as many commands as possible without falling off the board. For example, on board $$$3 \times 3$$$, if the robot starts a sequence of actions $$$s=$$$"RRDLUU" ("right", "right", "down", "left", "up", "up") from the central cell, the robot will perform one command, then the next command will force him to cross the edge. If the robot starts moving from the cell $$$(2, 1)$$$ (second row, first column) then all commands will be executed successfully and the robot will stop at the cell $$$(1, 2)$$$ (first row, second column). The robot starts from cell $$$(2, 1)$$$ (second row, first column). It moves right, right, down, left, up, and up. In this case it ends in the cell $$$(1, 2)$$$ (first row, second column). Determine the cell from which the robot should start its movement in order to execute as many commands as possible.
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; public class Main { void solve() { int n = in.nextInt(); int m = in.nextInt(); char[] a = in.nextLine().toCharArray(); int c = find(a, 'L', 'R', m); int r = find(a, 'U', 'D', n); out.append(r + " " + c + endl); } int find(char[] a, char sub, char add, int length) { int onSub = 0; int onAdd = 0; int n = a.length; int score = 0; int pos = 1; for (int i = 0 ; i < n; i++) { char ch = a[i]; if (ch != sub && ch != add)continue; if (ch == sub) { score--; } else { score++; } if (score < 0) { onSub = Math.max(onSub, -score); } else { onAdd = Math.max(onAdd, score); } if (onSub + onAdd >= length)return pos; pos = onSub + 1; } return pos; } public static void main (String[] args) { // It happens - Syed Mizbahuddin Main sol = new Main(); int t = 1; t = in.nextInt(); while (t-- != 0) { sol.solve(); } System.out.print(out); } <T> void println(T[] s) { if (err == null)return; err.println(Arrays.toString(s)); } <T> void println(T s) { if (err == null)return; err.println(s); } void println(int s) { if (err == null)return; err.println(s); } void println(int[] a) { if (err == null)return; println(Arrays.toString(a)); } int[] array(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = in.nextInt(); } return a; } int[] array1(int n) { int[] a = new int[n + 1]; for (int i = 1; i <= n; i++) { a[i] = in.nextInt(); } return a; } int max(int[] a) { int max = a[0]; for (int i = 0; i < a.length; i++)max = Math.max(max, a[i]); return max; } int min(int[] a) { int min = a[0]; for (int i = 0; i < a.length; i++)min = Math.min(min, a[i]); return min; } int count(int[] a, int x) { int count = 0; for (int i = 0; i < a.length; i++)if (x == a[i])count++; return count; } void printArray(int[] a) { for (int ele : a)out.append(ele + " "); out.append("\n"); } static { try { System.setIn(new FileInputStream("input.txt")); System.setOut(new PrintStream(new FileOutputStream("output.txt"))); err = new PrintStream(new FileOutputStream("error.txt")); } catch (Exception e) {} } static FastReader in; static StringBuilder out; static PrintStream err; static String yes , no , endl; final int MAX; final int MIN; int mod ; Main() { in = new FastReader(); out = new StringBuilder(); MAX = Integer.MAX_VALUE; MIN = Integer.MIN_VALUE; mod = (int)1e9 + 7; yes = "YES\n"; no = "NO\n"; endl = "\n"; } class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader( new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } class Pair implements Comparable<Pair> { int first , second; Pair(int first, int second) { this.first = first; this.second = second; } public int compareTo(Pair b) { return this.first - b.first; } public String toString() { String s = "{ " + Integer.toString(first) + " , " + Integer.toString(second) + " }"; return s; } } }
Java
["4\n1 1\nL\n1 2\nL\n3 3\nRRDLUU\n4 3\nLUURRDDLLLUU"]
2 seconds
["1 1\n1 2\n2 1\n3 2"]
null
Java 11
standard input
[ "implementation" ]
585bb4a040144da39ed240366193e705
The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. In the description of each test case, the first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^6$$$) — the height and width of the field that the robot is located on. The second line of the description is a string $$$s$$$ consisting solely of characters 'L', 'R', 'D' and 'U' — the sequence of commands the robot executes. The string has a length from $$$1$$$ to $$$10^6$$$ commands. It is guaranteed that the total length of $$$s$$$ over all test cases does not exceed $$$10^6$$$.
1,600
Print $$$t$$$ lines, each of which contains the answer to the corresponding test case. The answer to the test case are two integers $$$r$$$ ($$$1 \leq r \leq n$$$) and $$$c$$$ ($$$1 \leq c \leq m$$$), separated by a space — the coordinates of the cell (row number and column number) from which the robot should start moving to perform as many commands as possible. If there are several such cells, you may output any of them.
standard output
PASSED
c0ec68917d5167928685dd281bf025e2
train_108.jsonl
1635863700
The robot is located on a checkered rectangular board of size $$$n \times m$$$ ($$$n$$$ rows, $$$m$$$ columns). The rows in the board are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and the columns — from $$$1$$$ to $$$m$$$ from left to right.The robot is able to move from the current cell to one of the four cells adjacent by side.The sequence of commands $$$s$$$ executed by the robot is given. Each command is denoted by one of the symbols 'L', 'R', 'D' or 'U', and triggers the movement to left, right, down or up, respectively.The robot can start its movement in any cell. The robot executes the commands starting from the first one, strictly in the order in which they are listed in $$$s$$$. If the robot moves beyond the edge of the board, it falls and breaks. A command that causes the robot to break is not considered successfully executed.The robot's task is to execute as many commands as possible without falling off the board. For example, on board $$$3 \times 3$$$, if the robot starts a sequence of actions $$$s=$$$"RRDLUU" ("right", "right", "down", "left", "up", "up") from the central cell, the robot will perform one command, then the next command will force him to cross the edge. If the robot starts moving from the cell $$$(2, 1)$$$ (second row, first column) then all commands will be executed successfully and the robot will stop at the cell $$$(1, 2)$$$ (first row, second column). The robot starts from cell $$$(2, 1)$$$ (second row, first column). It moves right, right, down, left, up, and up. In this case it ends in the cell $$$(1, 2)$$$ (first row, second column). Determine the cell from which the robot should start its movement in order to execute as many commands as possible.
256 megabytes
import java.io.*; import java.util.*; // Problem Link: https://codeforces.com/problemset/problem/1607/E public class robot { public static void main (String[] args) throws IOException { // set up BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); int T = Integer.parseInt(in.readLine()); for (int i=0;i<T;i++) { // read in each test case StringTokenizer st = new StringTokenizer(in.readLine()); int n = Integer.parseInt(st.nextToken()); int m = Integer.parseInt(st.nextToken()); String s = in.readLine(); // find optimal starting location int[] ans = solve(n, m , s); out.println((ans[0]+1) + " " + (ans[1]+1)); } out.close(); } static int[] solve(int n, int m, String commands) { // finds location robot can start at to execute most commands int curr_x = 0; int curr_y = 0; int max_x = 0; int min_x = 0; int max_y = 0; int min_y = 0; int x_cor = 0; int y_cor = 0; for (int i=0;i<commands.length();i++) { char com = commands.charAt(i); // System.out.println(curr_x + " " + curr_y); // System.out.println(min_x + " " + max_x); // System.out.println(min_y + " " + max_y); // System.out.println(x_cor + " " + y_cor); // System.out.println(com); // update current x and y differentials from start if (com=='L') curr_x -= 1; if (com=='R') curr_x += 1; if (com=='U') curr_y -= 1; if (com=='D') curr_y += 1; // update min and max trackers max_x = Math.max(curr_x, max_x); min_x = Math.min(curr_x, min_x); max_y = Math.max(curr_y, max_y); min_y = Math.min(curr_y, min_y); // System.out.println(curr_x + " " + curr_y); // System.out.println(min_x + " " + max_x); // System.out.println(min_y + " " + max_y); // System.out.println(x_cor + " " + y_cor); // System.out.println(com); // check if it is possible to have this x position int smallest_x_start = Math.abs(min_x); int largest_x_start = m - max_x - 1; //System.out.println(smallest_x_start + " " + largest_x_start); if (smallest_x_start > largest_x_start || smallest_x_start >= m || largest_x_start < 0) { return new int[] {y_cor, x_cor}; } else x_cor = smallest_x_start; // check if it is possible to have this y position int smallest_y_start = Math.abs(min_y); int largest_y_start = n - max_y - 1; //System.out.println(smallest_y_start + " " + largest_y_start); if (smallest_y_start > largest_y_start || smallest_y_start >= n || largest_y_start < 0) { return new int[] {y_cor, x_cor}; } else y_cor = smallest_y_start; } return new int[] {y_cor, x_cor}; } }
Java
["4\n1 1\nL\n1 2\nL\n3 3\nRRDLUU\n4 3\nLUURRDDLLLUU"]
2 seconds
["1 1\n1 2\n2 1\n3 2"]
null
Java 11
standard input
[ "implementation" ]
585bb4a040144da39ed240366193e705
The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. In the description of each test case, the first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^6$$$) — the height and width of the field that the robot is located on. The second line of the description is a string $$$s$$$ consisting solely of characters 'L', 'R', 'D' and 'U' — the sequence of commands the robot executes. The string has a length from $$$1$$$ to $$$10^6$$$ commands. It is guaranteed that the total length of $$$s$$$ over all test cases does not exceed $$$10^6$$$.
1,600
Print $$$t$$$ lines, each of which contains the answer to the corresponding test case. The answer to the test case are two integers $$$r$$$ ($$$1 \leq r \leq n$$$) and $$$c$$$ ($$$1 \leq c \leq m$$$), separated by a space — the coordinates of the cell (row number and column number) from which the robot should start moving to perform as many commands as possible. If there are several such cells, you may output any of them.
standard output
PASSED
133a97a5e3d8ef7df4721a354a3e18a3
train_108.jsonl
1635863700
The robot is located on a checkered rectangular board of size $$$n \times m$$$ ($$$n$$$ rows, $$$m$$$ columns). The rows in the board are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and the columns — from $$$1$$$ to $$$m$$$ from left to right.The robot is able to move from the current cell to one of the four cells adjacent by side.The sequence of commands $$$s$$$ executed by the robot is given. Each command is denoted by one of the symbols 'L', 'R', 'D' or 'U', and triggers the movement to left, right, down or up, respectively.The robot can start its movement in any cell. The robot executes the commands starting from the first one, strictly in the order in which they are listed in $$$s$$$. If the robot moves beyond the edge of the board, it falls and breaks. A command that causes the robot to break is not considered successfully executed.The robot's task is to execute as many commands as possible without falling off the board. For example, on board $$$3 \times 3$$$, if the robot starts a sequence of actions $$$s=$$$"RRDLUU" ("right", "right", "down", "left", "up", "up") from the central cell, the robot will perform one command, then the next command will force him to cross the edge. If the robot starts moving from the cell $$$(2, 1)$$$ (second row, first column) then all commands will be executed successfully and the robot will stop at the cell $$$(1, 2)$$$ (first row, second column). The robot starts from cell $$$(2, 1)$$$ (second row, first column). It moves right, right, down, left, up, and up. In this case it ends in the cell $$$(1, 2)$$$ (first row, second column). Determine the cell from which the robot should start its movement in order to execute as many commands as possible.
256 megabytes
// package c1607; import java.io.File; import java.lang.invoke.MethodHandles; import java.util.Random; import java.util.Scanner; // // Codeforces Round #753 (Div. 3) 2021-11-02 06:35 // E. Robot on the Board 1 // https://codeforces.com/contest/1607/problem/E // time limit per test 2 seconds; memory limit per test 256 megabytes // public class Pseudo for 'Source should satisfy regex [^{}]*public\s+(final)?\s*class\s+(\w+).*' // // The robot is located on a checkered rectangular board of size n x m (n rows, m columns). The rows // in the board are numbered from 1 to n from top to bottom, and the columns-- from 1 to m from left // to right. // // The robot is able to move from the current cell to one of the four cells adjacent by side. // // The sequence of commands s executed by the robot is given. Each command is denoted by one of the // symbols '', '', '' or '', and triggers the movement to left, right, down or up, respectively. // // The robot can start its movement in cell. The robot executes the commands starting from the first // one, strictly in the order in which they are listed in s. If the robot moves beyond the edge of // the board, it falls and breaks. A command that causes the robot to break is successfully // executed. // // The robot's task is to execute as many commands as possible without falling off the board. For // example, on board 3 x 3, if the robot starts a sequence of actions s="" ("right", "right", // "down", "left", "up", "up") from the central cell, the robot will perform one command, then the // next command will force him to cross the edge. If the robot starts moving from the cell (2, 1) // (second row, first column) then all commands will be executed successfully and the robot will // stop at the cell (1, 2) (first row, second column). // https://espresso.codeforces.com/6d205e0bc924fe4671a320832791b28070e90297.png // // Determine the cell from which the robot should start its movement in order to execute as many // commands as possible. // // Input // // The first line contains an integer t (1 <= t <= 10^4)-- the number of test cases. // // The next 2t lines contain descriptions of the test cases. // // In the description of each test case, the first line contains two integers n and m (1 <= n, m <= // 10^6)-- the height and width of the field that the robot is located on. The second line of the // description is a string s consisting solely of characters '', '', '' and ''-- the sequence of // commands the robot executes. The string has a length from 1 to 10^6 commands. // // It is guaranteed that the total length of s over all test cases does not exceed 10^6. // // Output // // Print t lines, each of which contains the answer to the corresponding test case. The answer to // the test case are two integers r (1 <= r <= n) and c (1 <= c <= m), separated by a space-- the // coordinates of the cell (row number and column number) from which the robot should start moving // to perform as many commands as possible. // // If there are several such cells, you may output any of them. // // Example /* input: 4 1 1 L 1 2 L 3 3 RRDLUU 4 3 LUURRDDLLLUU output: 1 1 1 2 2 1 3 2 */ // public class C1607E { static final int MOD = (int)1e9+7; static final Random RAND = new Random(); static int[] solve(int n, int m, String s) { // Assume starts from (0,0), range[] tracks relevant values (minx, miny, maxx, maxy) // Assume starts from (0,0) // // | minx maxx // | v v // ------O--------------------> x | // miny -> | * // | // | // maxy -> | * // | // v // y int x = 0; int y = 0; int minx = 0; int miny = 0; int maxx = 0; int maxy = 0; for (char c : s.toCharArray()) { if (c == 'L') { if (x == minx && maxx - minx + 1 >= m) { break; } x--; minx = Math.min(minx, x); } else if (c == 'R') { if (x == maxx && maxx - minx + 1 >= m) { break; } x++; maxx = Math.max(maxx, x); } else if (c == 'U') { if (y == miny && maxy - miny + 1 >= n) { break; } y--; miny = Math.min(miny, y); } else { if (y == maxy && maxy - miny + 1 >= n) { break; } y++; maxy = Math.max(maxy, y); } } return new int[] {1 - miny, 1 - minx}; } static String trace(int[] a) { StringBuilder sb = new StringBuilder(); for (int v : a) { if (sb.length() > 0) { sb.append(' '); } sb.append(v); } return sb.toString(); } public static void main(String[] args) { Scanner in = getInputScanner(); int T = in.nextInt(); for (int t = 1; t <= T; t++) { int n = in.nextInt(); int m = in.nextInt(); String s = in.next(); int[] ans = solve(n, m, s); System.out.format("%d %d\n", ans[0], ans[1]); } in.close(); } static Scanner getInputScanner() { try { final String USERDIR = System.getProperty("user.dir"); final String CNAME = MethodHandles.lookup().lookupClass().getSimpleName(); final File fin = new File(USERDIR + "/io/c" + CNAME.substring(1,5) + "/" + CNAME + ".in"); return fin.exists() ? new Scanner(fin) : new Scanner(System.in); } catch (Exception e) { return new Scanner(System.in); } } }
Java
["4\n1 1\nL\n1 2\nL\n3 3\nRRDLUU\n4 3\nLUURRDDLLLUU"]
2 seconds
["1 1\n1 2\n2 1\n3 2"]
null
Java 11
standard input
[ "implementation" ]
585bb4a040144da39ed240366193e705
The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. In the description of each test case, the first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^6$$$) — the height and width of the field that the robot is located on. The second line of the description is a string $$$s$$$ consisting solely of characters 'L', 'R', 'D' and 'U' — the sequence of commands the robot executes. The string has a length from $$$1$$$ to $$$10^6$$$ commands. It is guaranteed that the total length of $$$s$$$ over all test cases does not exceed $$$10^6$$$.
1,600
Print $$$t$$$ lines, each of which contains the answer to the corresponding test case. The answer to the test case are two integers $$$r$$$ ($$$1 \leq r \leq n$$$) and $$$c$$$ ($$$1 \leq c \leq m$$$), separated by a space — the coordinates of the cell (row number and column number) from which the robot should start moving to perform as many commands as possible. If there are several such cells, you may output any of them.
standard output
PASSED
0def6774f800914227db89e8ca0890c7
train_108.jsonl
1635863700
The robot is located on a checkered rectangular board of size $$$n \times m$$$ ($$$n$$$ rows, $$$m$$$ columns). The rows in the board are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and the columns — from $$$1$$$ to $$$m$$$ from left to right.The robot is able to move from the current cell to one of the four cells adjacent by side.The sequence of commands $$$s$$$ executed by the robot is given. Each command is denoted by one of the symbols 'L', 'R', 'D' or 'U', and triggers the movement to left, right, down or up, respectively.The robot can start its movement in any cell. The robot executes the commands starting from the first one, strictly in the order in which they are listed in $$$s$$$. If the robot moves beyond the edge of the board, it falls and breaks. A command that causes the robot to break is not considered successfully executed.The robot's task is to execute as many commands as possible without falling off the board. For example, on board $$$3 \times 3$$$, if the robot starts a sequence of actions $$$s=$$$"RRDLUU" ("right", "right", "down", "left", "up", "up") from the central cell, the robot will perform one command, then the next command will force him to cross the edge. If the robot starts moving from the cell $$$(2, 1)$$$ (second row, first column) then all commands will be executed successfully and the robot will stop at the cell $$$(1, 2)$$$ (first row, second column). The robot starts from cell $$$(2, 1)$$$ (second row, first column). It moves right, right, down, left, up, and up. In this case it ends in the cell $$$(1, 2)$$$ (first row, second column). Determine the cell from which the robot should start its movement in order to execute as many commands as possible.
256 megabytes
import java.io.*; import java.util.*; public class E { public static void main(String[] args) { for (int i = 0; i < N; i++) { solve(); } out.close(); } public static void solve() { int row = sc.nextInt(); int col = sc.nextInt(); int row_t = 0; int row_b = 0; int col_l = 0; int col_r = 0; int row_c = 0; int col_c = 0; boolean flag = false; String mov = sc.nextLine(); for (int i = 0; i < mov.length(); i++) { if (mov.charAt(i) == 'U') { if (row_b - --row_c < row) { row_t = row_t < row_c ? row_t : row_c; } else { flag = true; } } else if (mov.charAt(i) == 'D') { if (++row_c - row_t < row) { row_b = row_b > row_c ? row_b : row_c; } else { flag = true; } } else if (mov.charAt(i) == 'L') { if (col_r - --col_c < col) { col_l = col_l < col_c ? col_l : col_c; } else { flag = true; } } else { if (++col_c - col_l < col) { col_r = col_r > col_c ? col_r : col_c; } else { flag = true; } } if (flag) { break; } } out.println(-row_t + 1 + " " + (-col_l + 1)); } private static PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); private static MyScanner sc = new MyScanner(); private static int N = sc.nextInt(); @SuppressWarnings("unused") private 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; } } @SuppressWarnings("unused") private class Pair<K, V> { public K f; public V s; Pair(K first, V second) { this.f = first; this.s = second; } } }
Java
["4\n1 1\nL\n1 2\nL\n3 3\nRRDLUU\n4 3\nLUURRDDLLLUU"]
2 seconds
["1 1\n1 2\n2 1\n3 2"]
null
Java 11
standard input
[ "implementation" ]
585bb4a040144da39ed240366193e705
The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. In the description of each test case, the first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^6$$$) — the height and width of the field that the robot is located on. The second line of the description is a string $$$s$$$ consisting solely of characters 'L', 'R', 'D' and 'U' — the sequence of commands the robot executes. The string has a length from $$$1$$$ to $$$10^6$$$ commands. It is guaranteed that the total length of $$$s$$$ over all test cases does not exceed $$$10^6$$$.
1,600
Print $$$t$$$ lines, each of which contains the answer to the corresponding test case. The answer to the test case are two integers $$$r$$$ ($$$1 \leq r \leq n$$$) and $$$c$$$ ($$$1 \leq c \leq m$$$), separated by a space — the coordinates of the cell (row number and column number) from which the robot should start moving to perform as many commands as possible. If there are several such cells, you may output any of them.
standard output
PASSED
c0f8817cbf72f10ce639d0e4eb99c679
train_108.jsonl
1635863700
The robot is located on a checkered rectangular board of size $$$n \times m$$$ ($$$n$$$ rows, $$$m$$$ columns). The rows in the board are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and the columns — from $$$1$$$ to $$$m$$$ from left to right.The robot is able to move from the current cell to one of the four cells adjacent by side.The sequence of commands $$$s$$$ executed by the robot is given. Each command is denoted by one of the symbols 'L', 'R', 'D' or 'U', and triggers the movement to left, right, down or up, respectively.The robot can start its movement in any cell. The robot executes the commands starting from the first one, strictly in the order in which they are listed in $$$s$$$. If the robot moves beyond the edge of the board, it falls and breaks. A command that causes the robot to break is not considered successfully executed.The robot's task is to execute as many commands as possible without falling off the board. For example, on board $$$3 \times 3$$$, if the robot starts a sequence of actions $$$s=$$$"RRDLUU" ("right", "right", "down", "left", "up", "up") from the central cell, the robot will perform one command, then the next command will force him to cross the edge. If the robot starts moving from the cell $$$(2, 1)$$$ (second row, first column) then all commands will be executed successfully and the robot will stop at the cell $$$(1, 2)$$$ (first row, second column). The robot starts from cell $$$(2, 1)$$$ (second row, first column). It moves right, right, down, left, up, and up. In this case it ends in the cell $$$(1, 2)$$$ (first row, second column). Determine the cell from which the robot should start its movement in order to execute as many commands as possible.
256 megabytes
//package FirstProject; import java.util.*; import java.io.*; public class solution { public static void main(String[] args) { MyScanner s = new MyScanner(); out = new PrintWriter(new BufferedOutputStream(System.out)); int testcases=s.nextInt(); while(testcases-->0) { int n=s.nextInt(); int m=s.nextInt(); char[] arr=s.next().toCharArray(); int maxx=Integer.MIN_VALUE,minx=Integer.MAX_VALUE; int maxy=Integer.MIN_VALUE,miny=Integer.MAX_VALUE; maxx=0; minx=0; maxy=0; miny=0; int i=1,j=1; int verti=0,hori=0; for(char ch : arr) { if(ch=='L')hori--; else if(ch=='R')hori++; else if(ch=='U')verti--; else verti++; // if(hori>m || verti>n || verti<=0 || hori<=0) { // i=-1; // j=-1; // break; // } maxx=Math.max(maxx, hori); minx=Math.min(minx, hori); maxy=Math.max(maxy, verti); miny=Math.min(miny, verti); if(maxx + (-minx) >=m || maxy + (-miny) >=n)break; if(m-maxx>=(-minx)) { j=(-minx)+1; } if(n-maxy>=(-miny)) { i=(-miny)+1; } } System.out.println(i + " " + j); } out.close(); } private static boolean check(int num, int[] arr) { int i=0; int j=arr.length-1; while(i<=j) { if(arr[i]==num)i++; else if(arr[j]==num)j--; else if(arr[i]!=arr[j])return false; else { i++; j--; } } return true; } static long gcd(long a, long b) { // Everything divides 0 if (a == 0) return b; if (b == 0) return a; // base case if (a == b) return a; // a is greater if (a > b) return gcd(a-b, b); return gcd(a, b-a); } public static PrintWriter out; public static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine(){ String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["4\n1 1\nL\n1 2\nL\n3 3\nRRDLUU\n4 3\nLUURRDDLLLUU"]
2 seconds
["1 1\n1 2\n2 1\n3 2"]
null
Java 11
standard input
[ "implementation" ]
585bb4a040144da39ed240366193e705
The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. In the description of each test case, the first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^6$$$) — the height and width of the field that the robot is located on. The second line of the description is a string $$$s$$$ consisting solely of characters 'L', 'R', 'D' and 'U' — the sequence of commands the robot executes. The string has a length from $$$1$$$ to $$$10^6$$$ commands. It is guaranteed that the total length of $$$s$$$ over all test cases does not exceed $$$10^6$$$.
1,600
Print $$$t$$$ lines, each of which contains the answer to the corresponding test case. The answer to the test case are two integers $$$r$$$ ($$$1 \leq r \leq n$$$) and $$$c$$$ ($$$1 \leq c \leq m$$$), separated by a space — the coordinates of the cell (row number and column number) from which the robot should start moving to perform as many commands as possible. If there are several such cells, you may output any of them.
standard output
PASSED
6461ffe5bc77383787e0faddd6e5c9e6
train_108.jsonl
1635863700
The robot is located on a checkered rectangular board of size $$$n \times m$$$ ($$$n$$$ rows, $$$m$$$ columns). The rows in the board are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and the columns — from $$$1$$$ to $$$m$$$ from left to right.The robot is able to move from the current cell to one of the four cells adjacent by side.The sequence of commands $$$s$$$ executed by the robot is given. Each command is denoted by one of the symbols 'L', 'R', 'D' or 'U', and triggers the movement to left, right, down or up, respectively.The robot can start its movement in any cell. The robot executes the commands starting from the first one, strictly in the order in which they are listed in $$$s$$$. If the robot moves beyond the edge of the board, it falls and breaks. A command that causes the robot to break is not considered successfully executed.The robot's task is to execute as many commands as possible without falling off the board. For example, on board $$$3 \times 3$$$, if the robot starts a sequence of actions $$$s=$$$"RRDLUU" ("right", "right", "down", "left", "up", "up") from the central cell, the robot will perform one command, then the next command will force him to cross the edge. If the robot starts moving from the cell $$$(2, 1)$$$ (second row, first column) then all commands will be executed successfully and the robot will stop at the cell $$$(1, 2)$$$ (first row, second column). The robot starts from cell $$$(2, 1)$$$ (second row, first column). It moves right, right, down, left, up, and up. In this case it ends in the cell $$$(1, 2)$$$ (first row, second column). Determine the cell from which the robot should start its movement in order to execute as many commands as possible.
256 megabytes
import static java.lang.Integer.parseInt; import static java.lang.Long.parseLong; import static java.lang.Double.parseDouble; import static java.lang.Math.PI; import static java.lang.Math.min; import static java.lang.System.arraycopy; import static java.lang.System.exit; import static java.util.Arrays.copyOf; import java.util.LinkedList; import java.util.List; import java.util.Iterator; import java.io.FileReader; import java.io.FileWriter; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.HashMap; import java.util.Map; import java.util.NoSuchElementException; import java.util.PriorityQueue; import java.util.Queue; import java.util.Stack; import java.util.StringTokenizer; import java.util.Comparator; import java.lang.StringBuilder; import java.util.Collections; import java.text.DecimalFormat; public class Solution { static BufferedReader in; static PrintWriter out; static StringTokenizer tok; static long mod= (long)1e9+7; static boolean isPrime[]; private static void solve() throws IOException{ int n = scanInt(), m = scanInt(); String str = scanString(); int startX =1 , currentX = 1 , maxX = 1, startY = 1, currentY = 1, maxY = 1; for(int i = 0 ; i< str.length(); ++i){ char current = str.charAt(i); if(current == 'L'){ if(currentX == 1){ if(maxX == m){ break; } else{ ++startX; ++maxX; } } else --currentX; } else if(current == 'R'){ if(currentX == m){ break; } else{ ++currentX; maxX = Math.max(currentX, maxX); } } else if(current == 'D'){ if(currentY == n) break; else{ ++currentY; maxY = Math.max(maxY, currentY); } } else{ if(currentY == 1){ if(maxY == n) break; startY++; ++maxY; } else --currentY; } } out.println(startY+" "+startX); } public static void main(String[] args) { try { long startTime = System.currentTimeMillis(); in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); //in = new BufferedReader(new FileReader("input.txt")); //out = new PrintWriter(new FileWriter("output.txt")); int test=scanInt(); for(int t=1; t<=test; t++){ // out.print("Case #"+t+": "); solve(); } long endTime = System.currentTimeMillis(); long totalTime = endTime - startTime; //out.println(totalTime+" "+System.currentTimeMillis() ); in.close(); out.close(); } catch (Throwable e) { e.printStackTrace(); exit(1); } } static int scanInt() throws IOException { return parseInt(scanString()); } static long scanLong() throws IOException { return parseLong(scanString()); } static double scanDouble() throws IOException { return parseDouble(scanString()); } static String scanString() throws IOException { if (tok == null || !tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); } return tok.nextToken(); } static String scanLine() throws IOException { return in.readLine(); } }
Java
["4\n1 1\nL\n1 2\nL\n3 3\nRRDLUU\n4 3\nLUURRDDLLLUU"]
2 seconds
["1 1\n1 2\n2 1\n3 2"]
null
Java 11
standard input
[ "implementation" ]
585bb4a040144da39ed240366193e705
The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. In the description of each test case, the first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^6$$$) — the height and width of the field that the robot is located on. The second line of the description is a string $$$s$$$ consisting solely of characters 'L', 'R', 'D' and 'U' — the sequence of commands the robot executes. The string has a length from $$$1$$$ to $$$10^6$$$ commands. It is guaranteed that the total length of $$$s$$$ over all test cases does not exceed $$$10^6$$$.
1,600
Print $$$t$$$ lines, each of which contains the answer to the corresponding test case. The answer to the test case are two integers $$$r$$$ ($$$1 \leq r \leq n$$$) and $$$c$$$ ($$$1 \leq c \leq m$$$), separated by a space — the coordinates of the cell (row number and column number) from which the robot should start moving to perform as many commands as possible. If there are several such cells, you may output any of them.
standard output
PASSED
5ff282af2d1468abf0c01d161549821d
train_108.jsonl
1635863700
The robot is located on a checkered rectangular board of size $$$n \times m$$$ ($$$n$$$ rows, $$$m$$$ columns). The rows in the board are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and the columns — from $$$1$$$ to $$$m$$$ from left to right.The robot is able to move from the current cell to one of the four cells adjacent by side.The sequence of commands $$$s$$$ executed by the robot is given. Each command is denoted by one of the symbols 'L', 'R', 'D' or 'U', and triggers the movement to left, right, down or up, respectively.The robot can start its movement in any cell. The robot executes the commands starting from the first one, strictly in the order in which they are listed in $$$s$$$. If the robot moves beyond the edge of the board, it falls and breaks. A command that causes the robot to break is not considered successfully executed.The robot's task is to execute as many commands as possible without falling off the board. For example, on board $$$3 \times 3$$$, if the robot starts a sequence of actions $$$s=$$$"RRDLUU" ("right", "right", "down", "left", "up", "up") from the central cell, the robot will perform one command, then the next command will force him to cross the edge. If the robot starts moving from the cell $$$(2, 1)$$$ (second row, first column) then all commands will be executed successfully and the robot will stop at the cell $$$(1, 2)$$$ (first row, second column). The robot starts from cell $$$(2, 1)$$$ (second row, first column). It moves right, right, down, left, up, and up. In this case it ends in the cell $$$(1, 2)$$$ (first row, second column). Determine the cell from which the robot should start its movement in order to execute as many commands as possible.
256 megabytes
import java.io.*; import java.util.*; public class RobotOnTheBoard1 { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); handleMultiTest(br); } private static void handleMultiTest(BufferedReader br) throws IOException { int T = Integer.parseInt(br.readLine()); for (int i = 0; i < T; i++) { handleTest(br); } } private static void handleTest(BufferedReader br) throws IOException { int[] NM = Arrays.stream(br.readLine().split(" ")).mapToInt(Integer::parseInt).toArray(); String input = br.readLine(); evaluate(NM[0], NM[1], input); } private static void evaluate(int n, int m, String input) { int startr = 0; int startc = 0; int RSize = 1; int CSize = 1; int r = 0; int r1 = 0; int r2 = 0; int c = 0; int c1 = 0; int c2 = 0; for (int i = 0; i < input.length(); i++) { char ch = input.charAt(i); switch (ch) { case 'U': r--; break; case 'D': r++; break; case 'L': c--; break; case 'R': c++; break; } r1 = Math.min(r1, r); r2 = Math.max(r2, r); c1 = Math.min(c1, c); c2 = Math.max(c2, c); if ((r2 - r1 + 1) <= n && (c2 - c1 + 1) <= m) { RSize = r2 - r1 + 1; CSize = c2 - c1 + 1; startr = r1; startc = c1; } else { break; } } System.out.println(((-1 * (startr - 1))) + " " + ((-1 * (startc - 1)))); } }
Java
["4\n1 1\nL\n1 2\nL\n3 3\nRRDLUU\n4 3\nLUURRDDLLLUU"]
2 seconds
["1 1\n1 2\n2 1\n3 2"]
null
Java 11
standard input
[ "implementation" ]
585bb4a040144da39ed240366193e705
The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. In the description of each test case, the first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^6$$$) — the height and width of the field that the robot is located on. The second line of the description is a string $$$s$$$ consisting solely of characters 'L', 'R', 'D' and 'U' — the sequence of commands the robot executes. The string has a length from $$$1$$$ to $$$10^6$$$ commands. It is guaranteed that the total length of $$$s$$$ over all test cases does not exceed $$$10^6$$$.
1,600
Print $$$t$$$ lines, each of which contains the answer to the corresponding test case. The answer to the test case are two integers $$$r$$$ ($$$1 \leq r \leq n$$$) and $$$c$$$ ($$$1 \leq c \leq m$$$), separated by a space — the coordinates of the cell (row number and column number) from which the robot should start moving to perform as many commands as possible. If there are several such cells, you may output any of them.
standard output
PASSED
142fad9aff1d1233b0d8dfeb185627c3
train_108.jsonl
1635863700
The robot is located on a checkered rectangular board of size $$$n \times m$$$ ($$$n$$$ rows, $$$m$$$ columns). The rows in the board are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and the columns — from $$$1$$$ to $$$m$$$ from left to right.The robot is able to move from the current cell to one of the four cells adjacent by side.The sequence of commands $$$s$$$ executed by the robot is given. Each command is denoted by one of the symbols 'L', 'R', 'D' or 'U', and triggers the movement to left, right, down or up, respectively.The robot can start its movement in any cell. The robot executes the commands starting from the first one, strictly in the order in which they are listed in $$$s$$$. If the robot moves beyond the edge of the board, it falls and breaks. A command that causes the robot to break is not considered successfully executed.The robot's task is to execute as many commands as possible without falling off the board. For example, on board $$$3 \times 3$$$, if the robot starts a sequence of actions $$$s=$$$"RRDLUU" ("right", "right", "down", "left", "up", "up") from the central cell, the robot will perform one command, then the next command will force him to cross the edge. If the robot starts moving from the cell $$$(2, 1)$$$ (second row, first column) then all commands will be executed successfully and the robot will stop at the cell $$$(1, 2)$$$ (first row, second column). The robot starts from cell $$$(2, 1)$$$ (second row, first column). It moves right, right, down, left, up, and up. In this case it ends in the cell $$$(1, 2)$$$ (first row, second column). Determine the cell from which the robot should start its movement in order to execute as many commands as possible.
256 megabytes
import java.io.*; import java.util.*; public class P1607E { public static void main(String[] args) throws IOException { MyScanner scanner = new MyScanner(System.in); PrintWriter writer = new PrintWriter(System.out); int t = scanner.nextInt(); while (t > 0) { int n = scanner.nextInt(); int m = scanner.nextInt(); String dir = scanner.nextToken(); int rMin = 0; int rMax = 0; int cMin = 0; int cMax = 0; int r = 0; int c = 0; int ansR = 1 - rMin; int ansC = 1 - cMin; for (int i = 0; i < dir.length(); i++) { char d = dir.charAt(i); if (d == 'U') { r--; } else if (d == 'D') { r++; } else if (d == 'L') { c--; } else { c++; } rMin = Math.min(rMin, r); rMax = Math.max(rMax, r); cMin = Math.min(cMin, c); cMax = Math.max(cMax, c); if (rMax - rMin + 1 > n || cMax - cMin + 1 > m) { break; } ansR = 1 - rMin; ansC = 1 - cMin; } writer.println(ansR + " " + ansC); t--; } writer.flush(); } private static class MyScanner { private BufferedReader reader; private StringTokenizer st; public MyScanner(InputStream inputStream) { reader = new BufferedReader(new InputStreamReader(inputStream)); } private String nextToken() throws IOException { while(st == null || !st.hasMoreTokens()) { st = new StringTokenizer(reader.readLine()); } return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(nextToken()); } public long nextLong() throws IOException { return Long.parseLong(nextToken()); } } }
Java
["4\n1 1\nL\n1 2\nL\n3 3\nRRDLUU\n4 3\nLUURRDDLLLUU"]
2 seconds
["1 1\n1 2\n2 1\n3 2"]
null
Java 11
standard input
[ "implementation" ]
585bb4a040144da39ed240366193e705
The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. In the description of each test case, the first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^6$$$) — the height and width of the field that the robot is located on. The second line of the description is a string $$$s$$$ consisting solely of characters 'L', 'R', 'D' and 'U' — the sequence of commands the robot executes. The string has a length from $$$1$$$ to $$$10^6$$$ commands. It is guaranteed that the total length of $$$s$$$ over all test cases does not exceed $$$10^6$$$.
1,600
Print $$$t$$$ lines, each of which contains the answer to the corresponding test case. The answer to the test case are two integers $$$r$$$ ($$$1 \leq r \leq n$$$) and $$$c$$$ ($$$1 \leq c \leq m$$$), separated by a space — the coordinates of the cell (row number and column number) from which the robot should start moving to perform as many commands as possible. If there are several such cells, you may output any of them.
standard output
PASSED
51fe4dfa39a639ce48b9bd777872acdd
train_108.jsonl
1635863700
The robot is located on a checkered rectangular board of size $$$n \times m$$$ ($$$n$$$ rows, $$$m$$$ columns). The rows in the board are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and the columns — from $$$1$$$ to $$$m$$$ from left to right.The robot is able to move from the current cell to one of the four cells adjacent by side.The sequence of commands $$$s$$$ executed by the robot is given. Each command is denoted by one of the symbols 'L', 'R', 'D' or 'U', and triggers the movement to left, right, down or up, respectively.The robot can start its movement in any cell. The robot executes the commands starting from the first one, strictly in the order in which they are listed in $$$s$$$. If the robot moves beyond the edge of the board, it falls and breaks. A command that causes the robot to break is not considered successfully executed.The robot's task is to execute as many commands as possible without falling off the board. For example, on board $$$3 \times 3$$$, if the robot starts a sequence of actions $$$s=$$$"RRDLUU" ("right", "right", "down", "left", "up", "up") from the central cell, the robot will perform one command, then the next command will force him to cross the edge. If the robot starts moving from the cell $$$(2, 1)$$$ (second row, first column) then all commands will be executed successfully and the robot will stop at the cell $$$(1, 2)$$$ (first row, second column). The robot starts from cell $$$(2, 1)$$$ (second row, first column). It moves right, right, down, left, up, and up. In this case it ends in the cell $$$(1, 2)$$$ (first row, second column). Determine the cell from which the robot should start its movement in order to execute as many commands as possible.
256 megabytes
/* _oo0oo_ o8888888o 88" . "88 (| -_- |) 0\ = /0 ___/`---'\___ .' \\| |// '. / \\||| : |||// \ / _||||| -:- |||||- \ | | \\\ - /// | | | \_| ''\---/'' |_/ | \ .-\__ '-' ___/-. / ___'. .' /--.--\ `. .'___ ."" '< `.___\_<|>_/___.' >' "". | | : `- \`.;`\ _ /`;.`/ - ` : | | \ \ `_. \_ __\ /__ _/ .-` / / =====`-.____`.___ \_____/___.-`___.-'===== `=---=' */ import java.util.*; import java.math.*; import java.io.*; import java.lang.Math.*; public class KickStart2020 { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } float nextFloat() { return Float.parseFloat(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } static long lcm(long a, long b) { return a / gcd(a, b) * b; } public static class Pair implements Comparable<Pair> { public int index; public int value; public Pair(int index,int value) { this.index = index; this.value = value; } @Override public int compareTo(Pair other) { // multiplied to -1 as the author need descending sort order if(other.index < this.index) return -1; if(other.index > this.index) return 1; if(other.value < this.value) return 1; else return -1; } @Override public String toString() { return this.index + " " + this.value; } } static boolean isPrime(long d) { if (d == 3) return false; for (int i = 2; i <= (long) Math.sqrt(d); i++) { if (d % i == 0) return false; } return true; } static void decimalTob(int n, int k, Stack<Integer> ss) { int x = n % k; int y = n / k; ss.push(x); if(y > 0) { decimalTob(y, k, ss); } } static long powermod(long x, long y, long mod) { long ans = 1; x = x % mod; if (x == 0) return 0; int i = 1; while (y > 0) { if ((y & 1) != 0) ans = (ans * x) % mod; y = y >> 1; x = (x * x) % mod; } return ans; } static long power(long x, long y) { long res = 1; while (y > 0) { if ((y & 1) != 0) res = res * x; y = y >> 1; x = x * x; } return res; } static boolean check(char a[], char b[]) { for(int i = 0; i < Math.min(a.length, b.length); i++) { if(a[i] < b[i]) return true; else if(a[i] > b[i]) return false; } if(a.length < b.length) return true; return false; } public static void main(String[] args) throws Exception { FastReader sc = new FastReader(); PrintWriter out = new PrintWriter(System.out); int t = sc.nextInt(); outerloop: while(t-- > 0) { int n = sc.nextInt(); int m = sc.nextInt(); String s = sc.next(); int l = 1; int r = m; int u = 1; int d = n; int x = 0; int y = 0; for(int i = 0; i < s.length(); i++) { if(s.charAt(i) == 'L') { x++; if(x > 0 && l - 1 < x) { l++; } if(r < l) { out.println((u) + " " + (--l)); continue outerloop; } } else if(s.charAt(i) == 'R') { x--; if(x < 0 && m - r < Math.abs(x)) { r--; } if(r < l) { out.println(u + " " + l); continue outerloop; } } else if(s.charAt(i) == 'U') { y++; if(y > 0 && u - 1 < y) { u++; } if(d < u) { out.println((--u) + " " + l); continue outerloop; } } else { y--; if(y < 0 && n - d < Math.abs(y)) { d--; } if(d < u) { out.println(u + " " + l); continue outerloop; } } } out.println(u + " " + l); } out.close(); } }
Java
["4\n1 1\nL\n1 2\nL\n3 3\nRRDLUU\n4 3\nLUURRDDLLLUU"]
2 seconds
["1 1\n1 2\n2 1\n3 2"]
null
Java 11
standard input
[ "implementation" ]
585bb4a040144da39ed240366193e705
The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. In the description of each test case, the first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^6$$$) — the height and width of the field that the robot is located on. The second line of the description is a string $$$s$$$ consisting solely of characters 'L', 'R', 'D' and 'U' — the sequence of commands the robot executes. The string has a length from $$$1$$$ to $$$10^6$$$ commands. It is guaranteed that the total length of $$$s$$$ over all test cases does not exceed $$$10^6$$$.
1,600
Print $$$t$$$ lines, each of which contains the answer to the corresponding test case. The answer to the test case are two integers $$$r$$$ ($$$1 \leq r \leq n$$$) and $$$c$$$ ($$$1 \leq c \leq m$$$), separated by a space — the coordinates of the cell (row number and column number) from which the robot should start moving to perform as many commands as possible. If there are several such cells, you may output any of them.
standard output
PASSED
92c4944e0d7796d6c46571b00516a3fd
train_108.jsonl
1635863700
The robot is located on a checkered rectangular board of size $$$n \times m$$$ ($$$n$$$ rows, $$$m$$$ columns). The rows in the board are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and the columns — from $$$1$$$ to $$$m$$$ from left to right.The robot is able to move from the current cell to one of the four cells adjacent by side.The sequence of commands $$$s$$$ executed by the robot is given. Each command is denoted by one of the symbols 'L', 'R', 'D' or 'U', and triggers the movement to left, right, down or up, respectively.The robot can start its movement in any cell. The robot executes the commands starting from the first one, strictly in the order in which they are listed in $$$s$$$. If the robot moves beyond the edge of the board, it falls and breaks. A command that causes the robot to break is not considered successfully executed.The robot's task is to execute as many commands as possible without falling off the board. For example, on board $$$3 \times 3$$$, if the robot starts a sequence of actions $$$s=$$$"RRDLUU" ("right", "right", "down", "left", "up", "up") from the central cell, the robot will perform one command, then the next command will force him to cross the edge. If the robot starts moving from the cell $$$(2, 1)$$$ (second row, first column) then all commands will be executed successfully and the robot will stop at the cell $$$(1, 2)$$$ (first row, second column). The robot starts from cell $$$(2, 1)$$$ (second row, first column). It moves right, right, down, left, up, and up. In this case it ends in the cell $$$(1, 2)$$$ (first row, second column). Determine the cell from which the robot should start its movement in order to execute as many commands as possible.
256 megabytes
import java.io.*; import java.util.*; public class E { public static void main (String[] args) throws IOException { Kattio io = new Kattio(); int t = io.nextInt(); for (int iii=0; iii<t; iii++) { int n = io.nextInt(); int m = io.nextInt(); String s = io.next(); int absR = 0; int absU = 0; int left = 0; int right = 0; int up = 0; int down = 0; int oleft = 0; int oright = 0; int oup = 0; int odown = 0; for (int i=0; i<s.length(); i++) { if (s.charAt(i) == 'R') { absR++; } else if (s.charAt(i) == 'L') { absR--; } else if (s.charAt(i) == 'U') { absU++; } else { absU--; } left = Math.min(left, absR); right = Math.max(right, absR); up = Math.max(up, absU); down = Math.min(down, absU); if (right - left >= m || up - down >= n) { break; } oleft = left; oright = right; oup = up; odown = down; } int ansx = Math.abs(oleft)+1; int ansy = Math.abs(oup)+1; //System.out.println(oleft + " " + oright + " " + odown + " " + oup); System.out.println(ansy + " " + ansx); } io.close(); } static class Kattio extends PrintWriter { private BufferedReader r; private StringTokenizer st; // standard input public Kattio() { this(System.in, System.out); } public Kattio(InputStream i, OutputStream o) { super(o); r = new BufferedReader(new InputStreamReader(i)); } // USACO-style file input public Kattio(String problemName) throws IOException { super(new FileWriter(problemName + ".out")); r = new BufferedReader(new FileReader(problemName + ".in")); } // returns null if no more input public String next() { try { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(r.readLine()); return st.nextToken(); } catch (Exception e) { } return null; } public int nextInt() { return Integer.parseInt(next()); } public double nextDouble() { return Double.parseDouble(next()); } public long nextLong() { return Long.parseLong(next()); } } }
Java
["4\n1 1\nL\n1 2\nL\n3 3\nRRDLUU\n4 3\nLUURRDDLLLUU"]
2 seconds
["1 1\n1 2\n2 1\n3 2"]
null
Java 11
standard input
[ "implementation" ]
585bb4a040144da39ed240366193e705
The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. In the description of each test case, the first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^6$$$) — the height and width of the field that the robot is located on. The second line of the description is a string $$$s$$$ consisting solely of characters 'L', 'R', 'D' and 'U' — the sequence of commands the robot executes. The string has a length from $$$1$$$ to $$$10^6$$$ commands. It is guaranteed that the total length of $$$s$$$ over all test cases does not exceed $$$10^6$$$.
1,600
Print $$$t$$$ lines, each of which contains the answer to the corresponding test case. The answer to the test case are two integers $$$r$$$ ($$$1 \leq r \leq n$$$) and $$$c$$$ ($$$1 \leq c \leq m$$$), separated by a space — the coordinates of the cell (row number and column number) from which the robot should start moving to perform as many commands as possible. If there are several such cells, you may output any of them.
standard output
PASSED
3fa6dba7ce0218382657f41317373fcb
train_108.jsonl
1635863700
The robot is located on a checkered rectangular board of size $$$n \times m$$$ ($$$n$$$ rows, $$$m$$$ columns). The rows in the board are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and the columns — from $$$1$$$ to $$$m$$$ from left to right.The robot is able to move from the current cell to one of the four cells adjacent by side.The sequence of commands $$$s$$$ executed by the robot is given. Each command is denoted by one of the symbols 'L', 'R', 'D' or 'U', and triggers the movement to left, right, down or up, respectively.The robot can start its movement in any cell. The robot executes the commands starting from the first one, strictly in the order in which they are listed in $$$s$$$. If the robot moves beyond the edge of the board, it falls and breaks. A command that causes the robot to break is not considered successfully executed.The robot's task is to execute as many commands as possible without falling off the board. For example, on board $$$3 \times 3$$$, if the robot starts a sequence of actions $$$s=$$$"RRDLUU" ("right", "right", "down", "left", "up", "up") from the central cell, the robot will perform one command, then the next command will force him to cross the edge. If the robot starts moving from the cell $$$(2, 1)$$$ (second row, first column) then all commands will be executed successfully and the robot will stop at the cell $$$(1, 2)$$$ (first row, second column). The robot starts from cell $$$(2, 1)$$$ (second row, first column). It moves right, right, down, left, up, and up. In this case it ends in the cell $$$(1, 2)$$$ (first row, second column). Determine the cell from which the robot should start its movement in order to execute as many commands as possible.
256 megabytes
import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException; import java.io.IOException;import java.io.InputStream;import java.io.PrintWriter; import java.security.AccessControlException;import java.util.List;public class _E1 { static public void main(final String[] args) throws IOException{E1._main(args);} static class E1 extends Solver{public E1(){}@Override public void solve()throws IOException {int n=sc.nextInt();int m=sc.nextInt();sc.nextLine();int[]s=sc.nextLine().chars().toArray(); int left=0;int right=0;int top=0;int bottom=0;int h=0;int v=0;int prev_left=0;int prev_top=0;for(int i=0;i<s.length;i++){switch(s[i]){case'L':h--;if(h<left){left= h;}break;case'R':h++;if(h>right){right=h;}break;case'U':v--;if(v<top){top=v;}break; case'D':v++;if(v>bottom){bottom=v;}break;}if(right-left>=m || bottom-top>=n){break; }prev_left=left;prev_top=top;}int res_v=1;int res_h=1;if(prev_left<0){res_h-=prev_left; }if(prev_top<0){res_v-=prev_top;}pw.println(res_v+" "+res_h);}static public void _main(String[]args)throws IOException{new E1().run();}}static class MyScanner{private StringBuilder cache=new StringBuilder();int cache_pos=0;private int first_linebreak =-1;private int second_linebreak=-1;private StringBuilder sb=new StringBuilder(); private InputStream is=null;public MyScanner(final InputStream is){this.is=is;}public String charToString(final int c){return String.format("'%s'",c=='\n'?"\\n":(c=='\r' ?"\\r":String.valueOf((char)c)));}public int get(){int res=-1;if(cache_pos<cache.length()) {res=cache.charAt(cache_pos);cache_pos++;if(cache_pos==cache.length()){cache.delete(0, cache_pos);cache_pos=0;}}else{try{res=is.read();}catch(IOException ex){throw new RuntimeException(ex);}}return res;}private void unget(final int c){if(cache_pos== 0){cache.insert(0,(char)c);}else{cache_pos--;}}public String nextLine(){sb.delete(0, sb.length());int c;boolean done=false;boolean end=false;while((c=get())!=-1){if(check_linebreak(c)) {done=true;if(c==first_linebreak){if(!end){end=true;}else{cache.append((char)c); break;}}else if(second_linebreak!=-1 && c==second_linebreak){break;}}if(end && c !=first_linebreak && c!=second_linebreak){cache.append((char)c);break;}if(!done) {sb.append((char)c);}}return!done && sb.length()==0?null:sb.toString();}private boolean check_linebreak(int c){if(c=='\n'|| c=='\r'){if(first_linebreak==-1){first_linebreak =c;}else if(c!=first_linebreak && second_linebreak==-1){second_linebreak=c;}return true;}return false;}public int nextInt(){return Integer.parseInt(next());}public long nextLong(){return Long.parseLong(next());}public boolean hasNext(){boolean res=false;int c;while((c=get())!=-1){if(!check_linebreak(c)&& c!=' '&& c!='\t'){ res=true;unget(c);break;}}return res;}public String next(){sb.delete(0,sb.length()); boolean started=false;int c;while((c=get())!=-1){if(check_linebreak(c)|| c==' '|| c=='\t'){if(started){unget(c);break;}}else{started=true;sb.append((char)c);}}return sb.toString();}public int nextChar(){return get();}public boolean eof(){int c=get(); boolean res=false;if(c!=-1){unget(c);}else{res=true;}return res;}public double nextDouble() {return Double.parseDouble(next());}}static abstract class Solver{protected String nameIn=null;protected String nameOut=null;protected boolean singleTest=false;protected MyScanner sc=null;protected PrintWriter pw=null;private int current_test=0;private int count_tests=0;protected int currentTest(){return current_test;}protected int countTests(){return count_tests;}private void process()throws IOException{if(!singleTest) {count_tests=sc.nextInt();sc.nextLine();for(current_test=1;current_test<=count_tests; current_test++){solve();pw.flush();}}else{count_tests=1;current_test=1;solve();} }abstract protected void solve()throws IOException;public void run()throws IOException {boolean done=false;try{if(nameIn!=null){if(new File(nameIn).exists()){try(FileInputStream fis=new FileInputStream(nameIn);PrintWriter pw0=select_output();){select_output(); done=true;sc=new MyScanner(fis);pw=pw0;process();}}else{throw new RuntimeException("File " +new File(nameIn).getAbsolutePath()+" does not exist!");}}}catch(IOException | AccessControlException ex){}if(!done){try(PrintWriter pw0=select_output();){sc=new MyScanner(System.in); pw=pw0;process();}}}private PrintWriter select_output()throws FileNotFoundException {if(nameOut!=null){return new PrintWriter(nameOut);}return new PrintWriter(System.out); }}static abstract class Tester{static public int getRandomInt(final int min,final int max){return(min+(int)Math.floor(Math.random()*(max-min+1)));}static public long getRandomLong(final long min,final long max){return(min+(long)Math.floor(Math.random() *(max-min+1)));}static public double getRandomDouble(final double min,final double maxExclusive){return(min+Math.random()*(maxExclusive-min));}abstract protected void testOutput(final List<String>output_data);abstract protected void generateInput(); abstract protected String inputDataToString();private boolean break_tester=false; protected void beforeTesting(){}protected void breakTester(){break_tester=true;} public boolean broken(){return break_tester;}}}
Java
["4\n1 1\nL\n1 2\nL\n3 3\nRRDLUU\n4 3\nLUURRDDLLLUU"]
2 seconds
["1 1\n1 2\n2 1\n3 2"]
null
Java 11
standard input
[ "implementation" ]
585bb4a040144da39ed240366193e705
The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. In the description of each test case, the first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^6$$$) — the height and width of the field that the robot is located on. The second line of the description is a string $$$s$$$ consisting solely of characters 'L', 'R', 'D' and 'U' — the sequence of commands the robot executes. The string has a length from $$$1$$$ to $$$10^6$$$ commands. It is guaranteed that the total length of $$$s$$$ over all test cases does not exceed $$$10^6$$$.
1,600
Print $$$t$$$ lines, each of which contains the answer to the corresponding test case. The answer to the test case are two integers $$$r$$$ ($$$1 \leq r \leq n$$$) and $$$c$$$ ($$$1 \leq c \leq m$$$), separated by a space — the coordinates of the cell (row number and column number) from which the robot should start moving to perform as many commands as possible. If there are several such cells, you may output any of them.
standard output
PASSED
f2e86db4d6ba7e2550df371e4ac383f9
train_108.jsonl
1635863700
The robot is located on a checkered rectangular board of size $$$n \times m$$$ ($$$n$$$ rows, $$$m$$$ columns). The rows in the board are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and the columns — from $$$1$$$ to $$$m$$$ from left to right.The robot is able to move from the current cell to one of the four cells adjacent by side.The sequence of commands $$$s$$$ executed by the robot is given. Each command is denoted by one of the symbols 'L', 'R', 'D' or 'U', and triggers the movement to left, right, down or up, respectively.The robot can start its movement in any cell. The robot executes the commands starting from the first one, strictly in the order in which they are listed in $$$s$$$. If the robot moves beyond the edge of the board, it falls and breaks. A command that causes the robot to break is not considered successfully executed.The robot's task is to execute as many commands as possible without falling off the board. For example, on board $$$3 \times 3$$$, if the robot starts a sequence of actions $$$s=$$$"RRDLUU" ("right", "right", "down", "left", "up", "up") from the central cell, the robot will perform one command, then the next command will force him to cross the edge. If the robot starts moving from the cell $$$(2, 1)$$$ (second row, first column) then all commands will be executed successfully and the robot will stop at the cell $$$(1, 2)$$$ (first row, second column). The robot starts from cell $$$(2, 1)$$$ (second row, first column). It moves right, right, down, left, up, and up. In this case it ends in the cell $$$(1, 2)$$$ (first row, second column). Determine the cell from which the robot should start its movement in order to execute as many commands as possible.
256 megabytes
//package robotontheboard1; import java.util.*; import java.io.*; public class robotontheboard1 { public static void main(String[] args) throws IOException { BufferedReader fin = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(fin.readLine()); StringBuilder fout = new StringBuilder(); while(t-- > 0) { StringTokenizer st = new StringTokenizer(fin.readLine()); int n = Integer.parseInt(st.nextToken()); int m = Integer.parseInt(st.nextToken()); char[] s = fin.readLine().toCharArray(); int[][] commands = new int[s.length][2]; for(int i = 0; i < s.length; i++) { if(s[i] == 'R') { commands[i] = new int[] {1, 0}; } else if(s[i] == 'L') { commands[i] = new int[] {-1, 0}; } else if(s[i] == 'U') { commands[i] = new int[] {0, -1}; } else { commands[i] = new int[] {0, 1}; } } int curX = 1; int curY = 1; int minX = 1; int minY = 1; int maxX = 1; int maxY = 1; for(int i = 0; i < commands.length; i++) { curX += commands[i][0]; curY += commands[i][1]; if(curX < minX) { if(maxX - curX + 1 > m) { break; } minX = curX; } else if(curY < minY) { if(maxY - curY + 1 > n) { break; } minY = curY; } else if(curX > maxX) { if(maxX - curX + 1 > m) { break; } maxX = curX; } else if(curY > maxY) { if(maxY - curY + 1 > n) { break; } maxY = curY; } //System.out.println("LOO"); } //System.out.println(minX + " " + minY); fout.append((1 + (1 - minY)) + " " + (1 + (1 - minX)) + "\n"); } System.out.print(fout); } }
Java
["4\n1 1\nL\n1 2\nL\n3 3\nRRDLUU\n4 3\nLUURRDDLLLUU"]
2 seconds
["1 1\n1 2\n2 1\n3 2"]
null
Java 11
standard input
[ "implementation" ]
585bb4a040144da39ed240366193e705
The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. In the description of each test case, the first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^6$$$) — the height and width of the field that the robot is located on. The second line of the description is a string $$$s$$$ consisting solely of characters 'L', 'R', 'D' and 'U' — the sequence of commands the robot executes. The string has a length from $$$1$$$ to $$$10^6$$$ commands. It is guaranteed that the total length of $$$s$$$ over all test cases does not exceed $$$10^6$$$.
1,600
Print $$$t$$$ lines, each of which contains the answer to the corresponding test case. The answer to the test case are two integers $$$r$$$ ($$$1 \leq r \leq n$$$) and $$$c$$$ ($$$1 \leq c \leq m$$$), separated by a space — the coordinates of the cell (row number and column number) from which the robot should start moving to perform as many commands as possible. If there are several such cells, you may output any of them.
standard output
PASSED
4a5c2c51261e53a2e5f5bd414912e0cd
train_108.jsonl
1635863700
The robot is located on a checkered rectangular board of size $$$n \times m$$$ ($$$n$$$ rows, $$$m$$$ columns). The rows in the board are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and the columns — from $$$1$$$ to $$$m$$$ from left to right.The robot is able to move from the current cell to one of the four cells adjacent by side.The sequence of commands $$$s$$$ executed by the robot is given. Each command is denoted by one of the symbols 'L', 'R', 'D' or 'U', and triggers the movement to left, right, down or up, respectively.The robot can start its movement in any cell. The robot executes the commands starting from the first one, strictly in the order in which they are listed in $$$s$$$. If the robot moves beyond the edge of the board, it falls and breaks. A command that causes the robot to break is not considered successfully executed.The robot's task is to execute as many commands as possible without falling off the board. For example, on board $$$3 \times 3$$$, if the robot starts a sequence of actions $$$s=$$$"RRDLUU" ("right", "right", "down", "left", "up", "up") from the central cell, the robot will perform one command, then the next command will force him to cross the edge. If the robot starts moving from the cell $$$(2, 1)$$$ (second row, first column) then all commands will be executed successfully and the robot will stop at the cell $$$(1, 2)$$$ (first row, second column). The robot starts from cell $$$(2, 1)$$$ (second row, first column). It moves right, right, down, left, up, and up. In this case it ends in the cell $$$(1, 2)$$$ (first row, second column). Determine the cell from which the robot should start its movement in order to execute as many commands as possible.
256 megabytes
import java.util.*; import java.io.*; public class RobotOnTheBoard{ static String solve(int n, int m, char arr[]){ int len = arr.length, i=0, x=1, y=1; int left, right, top, bottom; int maxLeft, maxRight, maxTop, maxBottom; left = maxLeft = 1; right = maxRight = m; top = maxTop = 1; bottom = maxBottom = n; while(maxLeft<=maxRight && maxTop<=maxBottom){ x = maxTop; y = maxLeft; if(i>=len) break; char ch = arr[i++]; if(ch == 'L') { if(right != m) right++; else left++; maxLeft = Math.max(maxLeft, left); } else if(ch == 'R'){ if(left != 1) left--; else right--; maxRight = Math.min(maxRight, right); } else if(ch == 'U'){ if(bottom != n) bottom++; else top++; maxTop = Math.max(maxTop, top); } else { if(top != 1) top--; else bottom--; maxBottom = Math.min(maxBottom, bottom); } } return x + " " + y; } public static void main(String args[])throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int tests = Integer.parseInt(br.readLine()); StringBuilder sb = new StringBuilder(); while(tests --> 0){ String l[] = br.readLine().split(" "); int n = Integer.parseInt(l[0]); int m = Integer.parseInt(l[1]); char []s = br.readLine().toCharArray(); String res = solve(n, m, s); sb.append(res+"\n"); } System.out.println(sb.toString()); } }
Java
["4\n1 1\nL\n1 2\nL\n3 3\nRRDLUU\n4 3\nLUURRDDLLLUU"]
2 seconds
["1 1\n1 2\n2 1\n3 2"]
null
Java 11
standard input
[ "implementation" ]
585bb4a040144da39ed240366193e705
The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. In the description of each test case, the first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^6$$$) — the height and width of the field that the robot is located on. The second line of the description is a string $$$s$$$ consisting solely of characters 'L', 'R', 'D' and 'U' — the sequence of commands the robot executes. The string has a length from $$$1$$$ to $$$10^6$$$ commands. It is guaranteed that the total length of $$$s$$$ over all test cases does not exceed $$$10^6$$$.
1,600
Print $$$t$$$ lines, each of which contains the answer to the corresponding test case. The answer to the test case are two integers $$$r$$$ ($$$1 \leq r \leq n$$$) and $$$c$$$ ($$$1 \leq c \leq m$$$), separated by a space — the coordinates of the cell (row number and column number) from which the robot should start moving to perform as many commands as possible. If there are several such cells, you may output any of them.
standard output
PASSED
4833fb735c29c30a13ea848c69dfbc9c
train_108.jsonl
1635863700
The robot is located on a checkered rectangular board of size $$$n \times m$$$ ($$$n$$$ rows, $$$m$$$ columns). The rows in the board are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and the columns — from $$$1$$$ to $$$m$$$ from left to right.The robot is able to move from the current cell to one of the four cells adjacent by side.The sequence of commands $$$s$$$ executed by the robot is given. Each command is denoted by one of the symbols 'L', 'R', 'D' or 'U', and triggers the movement to left, right, down or up, respectively.The robot can start its movement in any cell. The robot executes the commands starting from the first one, strictly in the order in which they are listed in $$$s$$$. If the robot moves beyond the edge of the board, it falls and breaks. A command that causes the robot to break is not considered successfully executed.The robot's task is to execute as many commands as possible without falling off the board. For example, on board $$$3 \times 3$$$, if the robot starts a sequence of actions $$$s=$$$"RRDLUU" ("right", "right", "down", "left", "up", "up") from the central cell, the robot will perform one command, then the next command will force him to cross the edge. If the robot starts moving from the cell $$$(2, 1)$$$ (second row, first column) then all commands will be executed successfully and the robot will stop at the cell $$$(1, 2)$$$ (first row, second column). The robot starts from cell $$$(2, 1)$$$ (second row, first column). It moves right, right, down, left, up, and up. In this case it ends in the cell $$$(1, 2)$$$ (first row, second column). Determine the cell from which the robot should start its movement in order to execute as many commands as possible.
256 megabytes
import java.util.*; import java.util.concurrent.Exchanger; public class Codeforces { static int[] mass = new int[200_001]; public static void main(String[] args) { Scanner scanner = new Scanner(System.in); StringBuilder stringBuilder = new StringBuilder(); int t = scanner.nextInt(); for (int z =0 ; z < t ; ++z) { solve(scanner, stringBuilder); } System.out.print(stringBuilder); } private static void solve(Scanner scanner, StringBuilder stringBuilder) { int n = scanner.nextInt(); int m = scanner.nextInt(); String path = scanner.next(); int x = 0; int y = 0; int ax = 0; int ay = 0; int maxX = 0; int minY = 0; int maxY = 0; int minX = 0; for (int i = 0 ; i < path.length() ; ++i) { switch (path.charAt(i)) { case 'D' : ++y; break; case 'U' : --y; break; case 'L' : --x; break; case 'R' : ++x; break; } maxX = Math.max(maxX, x); minX = Math.min(minX, x); maxY = Math.max(maxY, y); minY = Math.min(minY, y); int height = maxY - minY + 1; int width = maxX - minX + 1; if (height <= n && width <= m) { ay = -minY; ax = -minX; } else break; } stringBuilder.append(ay + 1).append(' ').append(ax + 1).append('\n'); } }
Java
["4\n1 1\nL\n1 2\nL\n3 3\nRRDLUU\n4 3\nLUURRDDLLLUU"]
2 seconds
["1 1\n1 2\n2 1\n3 2"]
null
Java 11
standard input
[ "implementation" ]
585bb4a040144da39ed240366193e705
The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. In the description of each test case, the first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^6$$$) — the height and width of the field that the robot is located on. The second line of the description is a string $$$s$$$ consisting solely of characters 'L', 'R', 'D' and 'U' — the sequence of commands the robot executes. The string has a length from $$$1$$$ to $$$10^6$$$ commands. It is guaranteed that the total length of $$$s$$$ over all test cases does not exceed $$$10^6$$$.
1,600
Print $$$t$$$ lines, each of which contains the answer to the corresponding test case. The answer to the test case are two integers $$$r$$$ ($$$1 \leq r \leq n$$$) and $$$c$$$ ($$$1 \leq c \leq m$$$), separated by a space — the coordinates of the cell (row number and column number) from which the robot should start moving to perform as many commands as possible. If there are several such cells, you may output any of them.
standard output
PASSED
271986f2b7e05ff9592e72192ea904f6
train_108.jsonl
1635863700
The robot is located on a checkered rectangular board of size $$$n \times m$$$ ($$$n$$$ rows, $$$m$$$ columns). The rows in the board are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and the columns — from $$$1$$$ to $$$m$$$ from left to right.The robot is able to move from the current cell to one of the four cells adjacent by side.The sequence of commands $$$s$$$ executed by the robot is given. Each command is denoted by one of the symbols 'L', 'R', 'D' or 'U', and triggers the movement to left, right, down or up, respectively.The robot can start its movement in any cell. The robot executes the commands starting from the first one, strictly in the order in which they are listed in $$$s$$$. If the robot moves beyond the edge of the board, it falls and breaks. A command that causes the robot to break is not considered successfully executed.The robot's task is to execute as many commands as possible without falling off the board. For example, on board $$$3 \times 3$$$, if the robot starts a sequence of actions $$$s=$$$"RRDLUU" ("right", "right", "down", "left", "up", "up") from the central cell, the robot will perform one command, then the next command will force him to cross the edge. If the robot starts moving from the cell $$$(2, 1)$$$ (second row, first column) then all commands will be executed successfully and the robot will stop at the cell $$$(1, 2)$$$ (first row, second column). The robot starts from cell $$$(2, 1)$$$ (second row, first column). It moves right, right, down, left, up, and up. In this case it ends in the cell $$$(1, 2)$$$ (first row, second column). Determine the cell from which the robot should start its movement in order to execute as many commands as possible.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintStream; import java.io.File; import java.io.FileInputStream; import java.util.*; public class Main { // static final File ip = new File("input.txt"); // static final File op = new File("output.txt"); // static { // try { // System.setOut(new PrintStream(op)); // System.setIn(new FileInputStream(ip)); // } catch (Exception e) { // } // } public static void main(String[] args) { FastReader sc = new FastReader(); int test = sc.nextInt(); while (test-- > 0) { int n = sc.nextInt(); int m = sc.nextInt(); String s = sc.next(); int x=0,y=0,ansX=1,ansY=1; int minX = 0,maxX = 0,minY = 0,maxY = 0; for(int i=0;i<s.length();i++) { if(s.charAt(i) == 'L') minY = Math.min(minY,--y); else if(s.charAt(i) == 'R') maxY = Math.max(maxY, ++y); else if(s.charAt(i) == 'U') minX = Math.min(minX, --x); else maxX = Math.max(maxX, ++x); if(maxX - minX >= n) break; if(maxY - minY >= m) break; ansX = 1 - minX; ansY = 1 - minY; } System.out.println(ansX +" "+ansY); } } static long power(long x, long y, long p) { long res = 1; x = x % p; if (x == 0) return 0; while (y > 0) { if ((y & 1) != 0) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return res; } public static int countSetBits(long number) { int count = 0; while (number > 0) { ++count; number &= number - 1; } return count; } static int lower_bound(long target, pair[] a, int pos) { if (pos >= a.length) return -1; int low = pos, high = a.length - 1; while (low < high) { int mid = low + (high - low) / 2; if (a[mid].a < target) low = mid + 1; else high = mid; } return a[low].a >= target ? low : -1; } private static <T> void swap(int[] a, int i, int j) { int tmp = a[i]; a[i] = a[j]; a[j] = tmp; } static class pair { long a; int b; pair(long x, int y) { this.a = x; this.b = y; } } static class first implements Comparator<pair> { public int compare(pair p1, pair p2) { if (p1.a > p2.a) return 1; else if (p1.a < p2.a) return -1; return 0; } } static class second implements Comparator<pair> { public int compare(pair p1, pair p2) { if (p1.b > p2.b) return 1; else if (p1.b < p2.b) return -1; return 0; } } private static long getSum(int[] array) { long sum = 0; for (int value : array) { sum += value; } return sum; } private static boolean isPrime(Long x) { if (x < 2) return false; for (long d = 2; d * d <= x; ++d) { if (x % d == 0) return false; } return true; } static int[] reverse(int a[], int n) { int i, k, t; for (i = 0; i < n / 2; i++) { t = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = t; } return a; } private static boolean isPrimeInt(int x) { if (x < 2) return false; for (int d = 2; d * d <= x; ++d) { if (x % d == 0) return false; } return true; } public static String reverse(String input) { StringBuilder str = new StringBuilder(""); for (int i = input.length() - 1; i >= 0; i--) { str.append(input.charAt(i)); } return str.toString(); } private static int[] getPrimes(int n) { boolean[] used = new boolean[n + 1]; used[0] = used[1] = true; int size = 0; for (int i = 2; i <= n; ++i) { if (!used[i]) { ++size; for (int j = 2 * i; j <= n; j += i) { used[j] = true; } } } int[] primes = new int[size]; for (int i = 0, cur = 0; i <= n; ++i) { if (!used[i]) { primes[cur++] = i; } } return primes; } private static long lcm(long a, long b) { return a / gcd(a, b) * b; } private static long gcd(long a, long b) { return (a == 0 ? b : gcd(b % a, a)); } static void sortI(int[] arr) { int n = arr.length; Random rnd = new Random(); for (int i = 0; i < n; ++i) { int tmp = arr[i]; int randomPos = i + rnd.nextInt(n - i); arr[i] = arr[randomPos]; arr[randomPos] = tmp; } Arrays.sort(arr); } static void shuffleList(ArrayList<Long> arr) { int n = arr.size(); Random rnd = new Random(); for (int i = 0; i < n; ++i) { long tmp = arr.get(i); int randomPos = i + rnd.nextInt(n - i); arr.set(i, arr.get(randomPos)); arr.set(randomPos, tmp); } } static void factorize(long n) { int count = 0; while (!(n % 2 > 0)) { n >>= 1; count++; } if (count > 0) { // System.out.println("2" + " " + count); } long i = 0; for (i = 3; i <= (long) Math.sqrt(n); i += 2) { count = 0; while (n % i == 0) { count++; n = n / i; } if (count > 0) { // System.out.println(i + " " + count); } } if (n > 2) { // System.out.println(i + " " + count); } } static void sortL(long[] arr) { int n = arr.length; Random rnd = new Random(); for (int i = 0; i < n; ++i) { long tmp = arr[i]; int randomPos = i + rnd.nextInt(n - i); arr[i] = arr[randomPos]; arr[randomPos] = tmp; } Arrays.sort(arr); } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } public boolean hasNext() { return false; } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["4\n1 1\nL\n1 2\nL\n3 3\nRRDLUU\n4 3\nLUURRDDLLLUU"]
2 seconds
["1 1\n1 2\n2 1\n3 2"]
null
Java 11
standard input
[ "implementation" ]
585bb4a040144da39ed240366193e705
The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. In the description of each test case, the first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^6$$$) — the height and width of the field that the robot is located on. The second line of the description is a string $$$s$$$ consisting solely of characters 'L', 'R', 'D' and 'U' — the sequence of commands the robot executes. The string has a length from $$$1$$$ to $$$10^6$$$ commands. It is guaranteed that the total length of $$$s$$$ over all test cases does not exceed $$$10^6$$$.
1,600
Print $$$t$$$ lines, each of which contains the answer to the corresponding test case. The answer to the test case are two integers $$$r$$$ ($$$1 \leq r \leq n$$$) and $$$c$$$ ($$$1 \leq c \leq m$$$), separated by a space — the coordinates of the cell (row number and column number) from which the robot should start moving to perform as many commands as possible. If there are several such cells, you may output any of them.
standard output
PASSED
aad429a1ebbb9924d2ad541bdba1c149
train_108.jsonl
1635863700
The robot is located on a checkered rectangular board of size $$$n \times m$$$ ($$$n$$$ rows, $$$m$$$ columns). The rows in the board are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and the columns — from $$$1$$$ to $$$m$$$ from left to right.The robot is able to move from the current cell to one of the four cells adjacent by side.The sequence of commands $$$s$$$ executed by the robot is given. Each command is denoted by one of the symbols 'L', 'R', 'D' or 'U', and triggers the movement to left, right, down or up, respectively.The robot can start its movement in any cell. The robot executes the commands starting from the first one, strictly in the order in which they are listed in $$$s$$$. If the robot moves beyond the edge of the board, it falls and breaks. A command that causes the robot to break is not considered successfully executed.The robot's task is to execute as many commands as possible without falling off the board. For example, on board $$$3 \times 3$$$, if the robot starts a sequence of actions $$$s=$$$"RRDLUU" ("right", "right", "down", "left", "up", "up") from the central cell, the robot will perform one command, then the next command will force him to cross the edge. If the robot starts moving from the cell $$$(2, 1)$$$ (second row, first column) then all commands will be executed successfully and the robot will stop at the cell $$$(1, 2)$$$ (first row, second column). The robot starts from cell $$$(2, 1)$$$ (second row, first column). It moves right, right, down, left, up, and up. In this case it ends in the cell $$$(1, 2)$$$ (first row, second column). Determine the cell from which the robot should start its movement in order to execute as many commands as possible.
256 megabytes
import java.util.*; public class E { public static final int MOD998 = 998244353; public static final int MOD100 = 1000000007; public static void main(String[] args) throws Exception { ContestScanner sc = new ContestScanner(); ContestPrinter cp = new ContestPrinter(); int T = sc.nextInt(); for (int t = 0; t < T; t++) { int N = sc.nextInt(); int M = sc.nextInt(); String C = sc.next(); int nowx = 0; int nowy = 0; int xmin = 0; int xmax = 0; int ymin = 0; int ymax = 0; int xminprev = 0; int xmaxprev = 0; int yminprev = 0; int ymaxprev = 0; for (char c : C.toCharArray()) { switch (c) { case 'L': nowx--; break; case 'R': nowx++; break; case 'U': nowy--; break; case 'D': nowy++; break; } xmin = Math.min(nowx, xmin); xmax = Math.max(nowx, xmax); ymin = Math.min(nowy, ymin); ymax = Math.max(nowy, ymax); if (xmax - xmin >= M || ymax - ymin >= N) { break; } xminprev = xmin; xmaxprev = xmax; yminprev = ymin; ymaxprev = ymax; } cp.println((-yminprev + 1) + " " + (-xminprev + 1)); } cp.close(); } ////////////////// // My Library // ////////////////// public static int zeroOneBFS(int[][][] weighted_graph, int start, int goal) { int[] dist = new int[weighted_graph.length]; Arrays.fill(dist, Integer.MAX_VALUE); dist[start] = 0; LinkedList<Integer> queue = new LinkedList<>(); queue.add(start); while (!queue.isEmpty()) { int now = queue.poll(); if (now == goal) { return dist[goal]; } for (int[] info : weighted_graph[now]) { if (dist[info[0]] > dist[now] + info[1]) { dist[info[0]] = dist[now] + info[1]; if (info[1] == 0) { queue.addFirst(info[0]); } else { queue.addLast(info[0]); } } } } return -1; } public static int[] zeroOneBFSAll(int[][][] weighted_graph, int start) { int[] dist = new int[weighted_graph.length]; Arrays.fill(dist, Integer.MAX_VALUE); dist[start] = 0; LinkedList<Integer> queue = new LinkedList<>(); queue.add(start); while (!queue.isEmpty()) { int now = queue.poll(); for (int[] info : weighted_graph[now]) { if (dist[info[0]] > dist[now] + info[1]) { dist[info[0]] = dist[now] + info[1]; if (info[1] == 0) { queue.addFirst(info[0]); } else { queue.addLast(info[0]); } } } } return dist; } public static long dijkstra(int[][][] weighted_graph, int start, int goal) { long[] dist = new long[weighted_graph.length]; Arrays.fill(dist, 0, dist.length, Long.MAX_VALUE); dist[start] = 0; PriorityQueue<Pair<Integer, Long>> unsettled = new PriorityQueue<>((u, v) -> (int) (u.cdr - v.cdr)); unsettled.offer(new Pair<Integer, Long>(start, 0L)); while (!unsettled.isEmpty()) { Pair<Integer, Long> pair = unsettled.poll(); int now = pair.car; if (now == goal) { return dist[goal]; } if (dist[now] < pair.cdr) { continue; } for (int[] info : weighted_graph[now]) { if (dist[info[0]] > dist[now] + info[1]) { dist[info[0]] = dist[now] + info[1]; unsettled.offer(new Pair<Integer, Long>(info[0], dist[info[0]])); } } } return -1; } public static long[] dijkstraAll(int[][][] weighted_graph, int start) { long[] dist = new long[weighted_graph.length]; Arrays.fill(dist, 0, dist.length, Long.MAX_VALUE); dist[start] = 0; PriorityQueue<Pair<Integer, Long>> unsettled = new PriorityQueue<>((u, v) -> (int) (u.cdr - v.cdr)); unsettled.offer(new Pair<Integer, Long>(start, 0L)); while (!unsettled.isEmpty()) { Pair<Integer, Long> pair = unsettled.poll(); int now = pair.car; if (dist[now] < pair.cdr) { continue; } for (int[] info : weighted_graph[now]) { if (dist[info[0]] > dist[now] + info[1]) { dist[info[0]] = dist[now] + info[1]; unsettled.offer(new Pair<Integer, Long>(info[0], dist[info[0]])); } } } return dist; } public static class Pair<A, B> { public final A car; public final B cdr; public Pair(A car_, B cdr_) { car = car_; cdr = cdr_; } private static boolean eq(Object o1, Object o2) { return o1 == null ? o2 == null : o1.equals(o2); } private static int hc(Object o) { return o == null ? 0 : o.hashCode(); } @Override public boolean equals(Object o) { if (!(o instanceof Pair)) return false; Pair<?, ?> rhs = (Pair<?, ?>) o; return eq(car, rhs.car) && eq(cdr, rhs.cdr); } @Override public int hashCode() { return hc(car) ^ hc(cdr); } } public static class Tuple1<A> extends Pair<A, Object> { public Tuple1(A a) { super(a, null); } } public static class Tuple2<A, B> extends Pair<A, Tuple1<B>> { public Tuple2(A a, B b) { super(a, new Tuple1<>(b)); } } public static class Tuple3<A, B, C> extends Pair<A, Tuple2<B, C>> { public Tuple3(A a, B b, C c) { super(a, new Tuple2<>(b, c)); } } public static class Tuple4<A, B, C, D> extends Pair<A, Tuple3<B, C, D>> { public Tuple4(A a, B b, C c, D d) { super(a, new Tuple3<>(b, c, d)); } } public static class Tuple5<A, B, C, D, E> extends Pair<A, Tuple4<B, C, D, E>> { public Tuple5(A a, B b, C c, D d, E e) { super(a, new Tuple4<>(b, c, d, e)); } } public static class PriorityQueueLogTime<T> { private PriorityQueue<T> queue; private Multiset<T> total; private int size = 0; public PriorityQueueLogTime() { queue = new PriorityQueue<>(); total = new Multiset<>(); } public PriorityQueueLogTime(Comparator<T> c) { queue = new PriorityQueue<>(c); total = new Multiset<>(); } public void clear() { queue.clear(); total.clear(); size = 0; } public boolean contains(T e) { return total.count(e) > 0; } public boolean isEmpty() { return size == 0; } public boolean offer(T e) { total.addOne(e); size++; return queue.offer(e); } public T peek() { if (total.isEmpty()) { return null; } simplify(); return queue.peek(); } public T poll() { if (total.isEmpty()) { return null; } simplify(); size--; T res = queue.poll(); total.removeOne(res); return res; } public void remove(T e) { total.removeOne(e); size--; } public int size() { return size; } private void simplify() { while (total.count(queue.peek()) == 0) { queue.poll(); } } } static int[][] scanGraphOneIndexed(ContestScanner sc, int node, int edge, boolean undirected) { int[][] arr = sc.nextIntArrayMulti(edge, 2); for (int n = 0; n < edge; n++) { arr[0][n]--; arr[1][n]--; } return GraphBuilder.makeGraph(node, edge, arr[0], arr[1], undirected); } static int[][][] scanWeightedGraphOneIndexed(ContestScanner sc, int node, int edge, boolean undirected) { int[][] arr = sc.nextIntArrayMulti(edge, 3); for (int n = 0; n < edge; n++) { arr[0][n]--; arr[1][n]--; } return GraphBuilder.makeGraphWithWeight(node, edge, arr[0], arr[1], arr[2], undirected); } static class EdgeData { private int capacity; private int[] from, to, weight; private int p = 0; private boolean weighted; public EdgeData(boolean weighted) { this(weighted, 500000); } public EdgeData(boolean weighted, int initial_capacity) { capacity = initial_capacity; from = new int[capacity]; to = new int[capacity]; weight = new int[capacity]; this.weighted = weighted; } public void addEdge(int u, int v) { if (weighted) { System.err.println("The graph is weighted!"); return; } if (p == capacity) { int[] newfrom = new int[capacity * 2]; int[] newto = new int[capacity * 2]; System.arraycopy(from, 0, newfrom, 0, capacity); System.arraycopy(to, 0, newto, 0, capacity); capacity *= 2; } from[p] = u; to[p] = v; p++; } public void addEdge(int u, int v, int w) { if (!weighted) { System.err.println("The graph is NOT weighted!"); return; } if (p == capacity) { int[] newfrom = new int[capacity * 2]; int[] newto = new int[capacity * 2]; int[] newweight = new int[capacity * 2]; System.arraycopy(from, 0, newfrom, 0, capacity); System.arraycopy(to, 0, newto, 0, capacity); System.arraycopy(weight, 0, newweight, 0, capacity); capacity *= 2; } from[p] = u; to[p] = v; weight[p] = w; p++; } public int[] getFrom() { int[] result = new int[p]; System.arraycopy(from, 0, result, 0, p); return result; } public int[] getTo() { int[] result = new int[p]; System.arraycopy(to, 0, result, 0, p); return result; } public int[] getWeight() { int[] result = new int[p]; System.arraycopy(weight, 0, result, 0, p); return result; } public int size() { return p; } } //////////////////////////////// // Atcoder Library for Java // //////////////////////////////// static class MathLib { private static long safe_mod(long x, long m) { x %= m; if (x < 0) x += m; return x; } private static long[] inv_gcd(long a, long b) { a = safe_mod(a, b); if (a == 0) return new long[] { b, 0 }; long s = b, t = a; long m0 = 0, m1 = 1; while (t > 0) { long u = s / t; s -= t * u; m0 -= m1 * u; long tmp = s; s = t; t = tmp; tmp = m0; m0 = m1; m1 = tmp; } if (m0 < 0) m0 += b / s; return new long[] { s, m0 }; } public static long gcd(long a, long b) { a = java.lang.Math.abs(a); b = java.lang.Math.abs(b); return inv_gcd(a, b)[0]; } public static long lcm(long a, long b) { a = java.lang.Math.abs(a); b = java.lang.Math.abs(b); return a / gcd(a, b) * b; } public static long pow_mod(long x, long n, int m) { assert n >= 0; assert m >= 1; if (m == 1) return 0L; x = safe_mod(x, m); long ans = 1L; while (n > 0) { if ((n & 1) == 1) ans = (ans * x) % m; x = (x * x) % m; n >>>= 1; } return ans; } public static long[] crt(long[] r, long[] m) { assert (r.length == m.length); int n = r.length; long r0 = 0, m0 = 1; for (int i = 0; i < n; i++) { assert (1 <= m[i]); long r1 = safe_mod(r[i], m[i]), m1 = m[i]; if (m0 < m1) { long tmp = r0; r0 = r1; r1 = tmp; tmp = m0; m0 = m1; m1 = tmp; } if (m0 % m1 == 0) { if (r0 % m1 != r1) return new long[] { 0, 0 }; continue; } long[] ig = inv_gcd(m0, m1); long g = ig[0], im = ig[1]; long u1 = m1 / g; if ((r1 - r0) % g != 0) return new long[] { 0, 0 }; long x = (r1 - r0) / g % u1 * im % u1; r0 += x * m0; m0 *= u1; if (r0 < 0) r0 += m0; // System.err.printf("%d %d\n", r0, m0); } return new long[] { r0, m0 }; } public static long floor_sum(long n, long m, long a, long b) { long ans = 0; if (a >= m) { ans += (n - 1) * n * (a / m) / 2; a %= m; } if (b >= m) { ans += n * (b / m); b %= m; } long y_max = (a * n + b) / m; long x_max = y_max * m - b; if (y_max == 0) return ans; ans += (n - (x_max + a - 1) / a) * y_max; ans += floor_sum(y_max, a, m, (a - x_max % a) % a); return ans; } public static java.util.ArrayList<Long> divisors(long n) { java.util.ArrayList<Long> divisors = new ArrayList<>(); java.util.ArrayList<Long> large = new ArrayList<>(); for (long i = 1; i * i <= n; i++) if (n % i == 0) { divisors.add(i); if (i * i < n) large.add(n / i); } for (int p = large.size() - 1; p >= 0; p--) { divisors.add(large.get(p)); } return divisors; } } static class Multiset<T> extends java.util.TreeMap<T, Long> { public Multiset() { super(); } public Multiset(java.util.List<T> list) { super(); for (T e : list) this.addOne(e); } public long count(Object elm) { return getOrDefault(elm, 0L); } public void add(T elm, long amount) { if (!this.containsKey(elm)) put(elm, amount); else replace(elm, get(elm) + amount); if (this.count(elm) == 0) this.remove(elm); } public void addOne(T elm) { this.add(elm, 1); } public void removeOne(T elm) { this.add(elm, -1); } public void removeAll(T elm) { this.add(elm, -this.count(elm)); } public static <T> Multiset<T> merge(Multiset<T> a, Multiset<T> b) { Multiset<T> c = new Multiset<>(); for (T x : a.keySet()) c.add(x, a.count(x)); for (T y : b.keySet()) c.add(y, b.count(y)); return c; } } static class GraphBuilder { public static int[][] makeGraph(int NumberOfNodes, int NumberOfEdges, int[] from, int[] to, boolean undirected) { int[][] graph = new int[NumberOfNodes][]; int[] outdegree = new int[NumberOfNodes]; for (int i = 0; i < NumberOfEdges; i++) { outdegree[from[i]]++; if (undirected) outdegree[to[i]]++; } for (int i = 0; i < NumberOfNodes; i++) graph[i] = new int[outdegree[i]]; for (int i = 0; i < NumberOfEdges; i++) { graph[from[i]][--outdegree[from[i]]] = to[i]; if (undirected) graph[to[i]][--outdegree[to[i]]] = from[i]; } return graph; } public static int[][][] makeGraphWithWeight(int NumberOfNodes, int NumberOfEdges, int[] from, int[] to, int[] weight, boolean undirected) { int[][][] graph = new int[NumberOfNodes][][]; int[] outdegree = new int[NumberOfNodes]; for (int i = 0; i < NumberOfEdges; i++) { outdegree[from[i]]++; if (undirected) outdegree[to[i]]++; } for (int i = 0; i < NumberOfNodes; i++) graph[i] = new int[outdegree[i]][]; for (int i = 0; i < NumberOfEdges; i++) { graph[from[i]][--outdegree[from[i]]] = new int[] { to[i], weight[i] }; if (undirected) graph[to[i]][--outdegree[to[i]]] = new int[] { from[i], weight[i] }; } return graph; } public static int[][][] makeGraphWithEdgeInfo(int NumberOfNodes, int NumberOfEdges, int[] from, int[] to, boolean undirected) { int[][][] graph = new int[NumberOfNodes][][]; int[] outdegree = new int[NumberOfNodes]; for (int i = 0; i < NumberOfEdges; i++) { outdegree[from[i]]++; if (undirected) outdegree[to[i]]++; } for (int i = 0; i < NumberOfNodes; i++) graph[i] = new int[outdegree[i]][]; for (int i = 0; i < NumberOfEdges; i++) { graph[from[i]][--outdegree[from[i]]] = new int[] { to[i], i, 0 }; if (undirected) graph[to[i]][--outdegree[to[i]]] = new int[] { from[i], i, 1 }; } return graph; } public static int[][][] makeGraphWithWeightAndEdgeInfo(int NumberOfNodes, int NumberOfEdges, int[] from, int[] to, int[] weight, boolean undirected) { int[][][] graph = new int[NumberOfNodes][][]; int[] outdegree = new int[NumberOfNodes]; for (int i = 0; i < NumberOfEdges; i++) { outdegree[from[i]]++; if (undirected) outdegree[to[i]]++; } for (int i = 0; i < NumberOfNodes; i++) graph[i] = new int[outdegree[i]][]; for (int i = 0; i < NumberOfEdges; i++) { graph[from[i]][--outdegree[from[i]]] = new int[] { to[i], weight[i], i, 0 }; if (undirected) graph[to[i]][--outdegree[to[i]]] = new int[] { from[i], weight[i], i, 1 }; } return graph; } } static class DSU { private int n; private int[] parentOrSize; public DSU(int n) { this.n = n; this.parentOrSize = new int[n]; java.util.Arrays.fill(parentOrSize, -1); } int merge(int a, int b) { if (!(0 <= a && a < n)) throw new IndexOutOfBoundsException("a=" + a); if (!(0 <= b && b < n)) throw new IndexOutOfBoundsException("b=" + b); int x = leader(a); int y = leader(b); if (x == y) return x; if (-parentOrSize[x] < -parentOrSize[y]) { int tmp = x; x = y; y = tmp; } parentOrSize[x] += parentOrSize[y]; parentOrSize[y] = x; return x; } boolean same(int a, int b) { if (!(0 <= a && a < n)) throw new IndexOutOfBoundsException("a=" + a); if (!(0 <= b && b < n)) throw new IndexOutOfBoundsException("b=" + b); return leader(a) == leader(b); } int leader(int a) { if (parentOrSize[a] < 0) { return a; } else { parentOrSize[a] = leader(parentOrSize[a]); return parentOrSize[a]; } } int size(int a) { if (!(0 <= a && a < n)) throw new IndexOutOfBoundsException("" + a); return -parentOrSize[leader(a)]; } java.util.ArrayList<java.util.ArrayList<Integer>> groups() { int[] leaderBuf = new int[n]; int[] groupSize = new int[n]; for (int i = 0; i < n; i++) { leaderBuf[i] = leader(i); groupSize[leaderBuf[i]]++; } java.util.ArrayList<java.util.ArrayList<Integer>> result = new java.util.ArrayList<>(n); for (int i = 0; i < n; i++) { result.add(new java.util.ArrayList<>(groupSize[i])); } for (int i = 0; i < n; i++) { result.get(leaderBuf[i]).add(i); } result.removeIf(java.util.ArrayList::isEmpty); return result; } } static class ModIntFactory { private final ModArithmetic ma; private final int mod; private final boolean usesMontgomery; private final ModArithmetic.ModArithmeticMontgomery maMontgomery; private ArrayList<Integer> factorial; private ArrayList<Integer> factorial_inversion; public ModIntFactory(int mod) { this.ma = ModArithmetic.of(mod); this.usesMontgomery = ma instanceof ModArithmetic.ModArithmeticMontgomery; this.maMontgomery = usesMontgomery ? (ModArithmetic.ModArithmeticMontgomery) ma : null; this.mod = mod; this.factorial = new ArrayList<>(); this.factorial_inversion = new ArrayList<>(); } public ModInt create(long value) { if ((value %= mod) < 0) value += mod; if (usesMontgomery) { return new ModInt(maMontgomery.generate(value)); } else { return new ModInt((int) value); } } private void prepareFactorial(int max) { factorial.ensureCapacity(max + 1); if (factorial.size() == 0) factorial.add(1); for (int i = factorial.size(); i <= max; i++) { factorial.add(ma.mul(factorial.get(i - 1), i)); } } public ModInt factorial(int i) { prepareFactorial(i); return create(factorial.get(i)); } public ModInt permutation(int n, int r) { if (n < 0 || r < 0 || n < r) return create(0); prepareFactorial(n); if (factorial_inversion.size() > n) { return create(ma.mul(factorial.get(n), factorial_inversion.get(n - r))); } return create(ma.div(factorial.get(n), factorial.get(n - r))); } public ModInt combination(int n, int r) { if (n < 0 || r < 0 || n < r) return create(0); prepareFactorial(n); if (factorial_inversion.size() > n) { return create( ma.mul(factorial.get(n), ma.mul(factorial_inversion.get(n - r), factorial_inversion.get(r)))); } return create(ma.div(factorial.get(n), ma.mul(factorial.get(r), factorial.get(n - r)))); } public void prepareFactorialInv(int max) { prepareFactorial(max); factorial_inversion.ensureCapacity(max + 1); for (int i = factorial_inversion.size(); i <= max; i++) { factorial_inversion.add(ma.inv(factorial.get(i))); } } public int getMod() { return mod; } public class ModInt { private int value; private ModInt(int value) { this.value = value; } public int mod() { return mod; } public int value() { if (ma instanceof ModArithmetic.ModArithmeticMontgomery) { return ((ModArithmetic.ModArithmeticMontgomery) ma).reduce(value); } return value; } public ModInt add(ModInt mi) { return new ModInt(ma.add(value, mi.value)); } public ModInt add(ModInt mi1, ModInt mi2) { return new ModInt(ma.add(value, mi1.value)).addAsg(mi2); } public ModInt add(ModInt mi1, ModInt mi2, ModInt mi3) { return new ModInt(ma.add(value, mi1.value)).addAsg(mi2).addAsg(mi3); } public ModInt add(ModInt mi1, ModInt mi2, ModInt mi3, ModInt mi4) { return new ModInt(ma.add(value, mi1.value)).addAsg(mi2).addAsg(mi3).addAsg(mi4); } public ModInt add(ModInt mi1, ModInt... mis) { ModInt mi = add(mi1); for (ModInt m : mis) mi.addAsg(m); return mi; } public ModInt add(long mi) { return new ModInt(ma.add(value, ma.remainder(mi))); } public ModInt sub(ModInt mi) { return new ModInt(ma.sub(value, mi.value)); } public ModInt sub(long mi) { return new ModInt(ma.sub(value, ma.remainder(mi))); } public ModInt mul(ModInt mi) { return new ModInt(ma.mul(value, mi.value)); } public ModInt mul(ModInt mi1, ModInt mi2) { return new ModInt(ma.mul(value, mi1.value)).mulAsg(mi2); } public ModInt mul(ModInt mi1, ModInt mi2, ModInt mi3) { return new ModInt(ma.mul(value, mi1.value)).mulAsg(mi2).mulAsg(mi3); } public ModInt mul(ModInt mi1, ModInt mi2, ModInt mi3, ModInt mi4) { return new ModInt(ma.mul(value, mi1.value)).mulAsg(mi2).mulAsg(mi3).mulAsg(mi4); } public ModInt mul(ModInt mi1, ModInt... mis) { ModInt mi = mul(mi1); for (ModInt m : mis) mi.mulAsg(m); return mi; } public ModInt mul(long mi) { return new ModInt(ma.mul(value, ma.remainder(mi))); } public ModInt div(ModInt mi) { return new ModInt(ma.div(value, mi.value)); } public ModInt div(long mi) { return new ModInt(ma.div(value, ma.remainder(mi))); } public ModInt inv() { return new ModInt(ma.inv(value)); } public ModInt pow(long b) { return new ModInt(ma.pow(value, b)); } public ModInt addAsg(ModInt mi) { this.value = ma.add(value, mi.value); return this; } public ModInt addAsg(ModInt mi1, ModInt mi2) { return addAsg(mi1).addAsg(mi2); } public ModInt addAsg(ModInt mi1, ModInt mi2, ModInt mi3) { return addAsg(mi1).addAsg(mi2).addAsg(mi3); } public ModInt addAsg(ModInt mi1, ModInt mi2, ModInt mi3, ModInt mi4) { return addAsg(mi1).addAsg(mi2).addAsg(mi3).addAsg(mi4); } public ModInt addAsg(ModInt... mis) { for (ModInt m : mis) addAsg(m); return this; } public ModInt addAsg(long mi) { this.value = ma.add(value, ma.remainder(mi)); return this; } public ModInt subAsg(ModInt mi) { this.value = ma.sub(value, mi.value); return this; } public ModInt subAsg(long mi) { this.value = ma.sub(value, ma.remainder(mi)); return this; } public ModInt mulAsg(ModInt mi) { this.value = ma.mul(value, mi.value); return this; } public ModInt mulAsg(ModInt mi1, ModInt mi2) { return mulAsg(mi1).mulAsg(mi2); } public ModInt mulAsg(ModInt mi1, ModInt mi2, ModInt mi3) { return mulAsg(mi1).mulAsg(mi2).mulAsg(mi3); } public ModInt mulAsg(ModInt mi1, ModInt mi2, ModInt mi3, ModInt mi4) { return mulAsg(mi1).mulAsg(mi2).mulAsg(mi3).mulAsg(mi4); } public ModInt mulAsg(ModInt... mis) { for (ModInt m : mis) mulAsg(m); return this; } public ModInt mulAsg(long mi) { this.value = ma.mul(value, ma.remainder(mi)); return this; } public ModInt divAsg(ModInt mi) { this.value = ma.div(value, mi.value); return this; } public ModInt divAsg(long mi) { this.value = ma.div(value, ma.remainder(mi)); return this; } @Override public String toString() { return String.valueOf(value()); } @Override public boolean equals(Object o) { if (o instanceof ModInt) { ModInt mi = (ModInt) o; return mod() == mi.mod() && value() == mi.value(); } return false; } @Override public int hashCode() { return (1 * 37 + mod()) * 37 + value(); } } private static abstract class ModArithmetic { abstract int mod(); abstract int remainder(long value); abstract int add(int a, int b); abstract int sub(int a, int b); abstract int mul(int a, int b); int div(int a, int b) { return mul(a, inv(b)); } int inv(int a) { int b = mod(); if (b == 1) return 0; long u = 1, v = 0; while (b >= 1) { int t = a / b; a -= t * b; int tmp1 = a; a = b; b = tmp1; u -= t * v; long tmp2 = u; u = v; v = tmp2; } if (a != 1) { throw new ArithmeticException("divide by zero"); } return remainder(u); } int pow(int a, long b) { if (b < 0) throw new ArithmeticException("negative power"); int r = 1; int x = a; while (b > 0) { if ((b & 1) == 1) r = mul(r, x); x = mul(x, x); b >>= 1; } return r; } static ModArithmetic of(int mod) { if (mod <= 0) { throw new IllegalArgumentException(); } else if (mod == 1) { return new ModArithmetic1(); } else if (mod == 2) { return new ModArithmetic2(); } else if (mod == 998244353) { return new ModArithmetic998244353(); } else if (mod == 1000000007) { return new ModArithmetic1000000007(); } else if ((mod & 1) == 1) { return new ModArithmeticMontgomery(mod); } else { return new ModArithmeticBarrett(mod); } } private static final class ModArithmetic1 extends ModArithmetic { int mod() { return 1; } int remainder(long value) { return 0; } int add(int a, int b) { return 0; } int sub(int a, int b) { return 0; } int mul(int a, int b) { return 0; } int pow(int a, long b) { return 0; } } private static final class ModArithmetic2 extends ModArithmetic { int mod() { return 2; } int remainder(long value) { return (int) (value & 1); } int add(int a, int b) { return a ^ b; } int sub(int a, int b) { return a ^ b; } int mul(int a, int b) { return a & b; } } private static final class ModArithmetic998244353 extends ModArithmetic { private final int mod = 998244353; int mod() { return mod; } int remainder(long value) { return (int) ((value %= mod) < 0 ? value + mod : value); } int add(int a, int b) { int res = a + b; return res >= mod ? res - mod : res; } int sub(int a, int b) { int res = a - b; return res < 0 ? res + mod : res; } int mul(int a, int b) { return (int) (((long) a * b) % mod); } } private static final class ModArithmetic1000000007 extends ModArithmetic { private final int mod = 1000000007; int mod() { return mod; } int remainder(long value) { return (int) ((value %= mod) < 0 ? value + mod : value); } int add(int a, int b) { int res = a + b; return res >= mod ? res - mod : res; } int sub(int a, int b) { int res = a - b; return res < 0 ? res + mod : res; } int mul(int a, int b) { return (int) (((long) a * b) % mod); } } private static final class ModArithmeticMontgomery extends ModArithmeticDynamic { private final long negInv; private final long r2; private ModArithmeticMontgomery(int mod) { super(mod); long inv = 0; long s = 1, t = 0; for (int i = 0; i < 32; i++) { if ((t & 1) == 0) { t += mod; inv += s; } t >>= 1; s <<= 1; } long r = (1l << 32) % mod; this.negInv = inv; this.r2 = (r * r) % mod; } private int generate(long x) { return reduce(x * r2); } private int reduce(long x) { x = (x + ((x * negInv) & 0xffff_ffffl) * mod) >>> 32; return (int) (x < mod ? x : x - mod); } @Override int remainder(long value) { return generate((value %= mod) < 0 ? value + mod : value); } @Override int mul(int a, int b) { return reduce((long) a * b); } @Override int inv(int a) { return super.inv(reduce(a)); } @Override int pow(int a, long b) { return generate(super.pow(a, b)); } } private static final class ModArithmeticBarrett extends ModArithmeticDynamic { private static final long mask = 0xffff_ffffl; private final long mh; private final long ml; private ModArithmeticBarrett(int mod) { super(mod); /** * m = floor(2^64/mod) 2^64 = p*mod + q, 2^32 = a*mod + b => (a*mod + b)^2 = * p*mod + q => p = mod*a^2 + 2ab + floor(b^2/mod) */ long a = (1l << 32) / mod; long b = (1l << 32) % mod; long m = a * a * mod + 2 * a * b + (b * b) / mod; mh = m >>> 32; ml = m & mask; } private int reduce(long x) { long z = (x & mask) * ml; z = (x & mask) * mh + (x >>> 32) * ml + (z >>> 32); z = (x >>> 32) * mh + (z >>> 32); x -= z * mod; return (int) (x < mod ? x : x - mod); } @Override int remainder(long value) { return (int) ((value %= mod) < 0 ? value + mod : value); } @Override int mul(int a, int b) { return reduce((long) a * b); } } private static class ModArithmeticDynamic extends ModArithmetic { final int mod; ModArithmeticDynamic(int mod) { this.mod = mod; } int mod() { return mod; } int remainder(long value) { return (int) ((value %= mod) < 0 ? value + mod : value); } int add(int a, int b) { int sum = a + b; return sum >= mod ? sum - mod : sum; } int sub(int a, int b) { int sum = a - b; return sum < 0 ? sum + mod : sum; } int mul(int a, int b) { return (int) (((long) a * b) % mod); } } } } static class Convolution { /** * Find a primitive root. * * @param m A prime number. * @return Primitive root. */ private static int primitiveRoot(int m) { if (m == 2) return 1; if (m == 167772161) return 3; if (m == 469762049) return 3; if (m == 754974721) return 11; if (m == 998244353) return 3; int[] divs = new int[20]; divs[0] = 2; int cnt = 1; int x = (m - 1) / 2; while (x % 2 == 0) x /= 2; for (int i = 3; (long) (i) * i <= x; i += 2) { if (x % i == 0) { divs[cnt++] = i; while (x % i == 0) { x /= i; } } } if (x > 1) { divs[cnt++] = x; } for (int g = 2;; g++) { boolean ok = true; for (int i = 0; i < cnt; i++) { if (pow(g, (m - 1) / divs[i], m) == 1) { ok = false; break; } } if (ok) return g; } } /** * Power. * * @param x Parameter x. * @param n Parameter n. * @param m Mod. * @return n-th power of x mod m. */ private static long pow(long x, long n, int m) { if (m == 1) return 0; long r = 1; long y = x % m; while (n > 0) { if ((n & 1) != 0) r = (r * y) % m; y = (y * y) % m; n >>= 1; } return r; } /** * Ceil of power 2. * * @param n Value. * @return Ceil of power 2. */ private static int ceilPow2(int n) { int x = 0; while ((1L << x) < n) x++; return x; } /** * Garner's algorithm. * * @param c Mod convolution results. * @param mods Mods. * @return Result. */ private static long garner(long[] c, int[] mods) { int n = c.length + 1; long[] cnst = new long[n]; long[] coef = new long[n]; java.util.Arrays.fill(coef, 1); for (int i = 0; i < n - 1; i++) { int m1 = mods[i]; long v = (c[i] - cnst[i] + m1) % m1; v = v * pow(coef[i], m1 - 2, m1) % m1; for (int j = i + 1; j < n; j++) { long m2 = mods[j]; cnst[j] = (cnst[j] + coef[j] * v) % m2; coef[j] = (coef[j] * m1) % m2; } } return cnst[n - 1]; } /** * Pre-calculation for NTT. * * @param mod NTT Prime. * @param g Primitive root of mod. * @return Pre-calculation table. */ private static long[] sumE(int mod, int g) { long[] sum_e = new long[30]; long[] es = new long[30]; long[] ies = new long[30]; int cnt2 = Integer.numberOfTrailingZeros(mod - 1); long e = pow(g, (mod - 1) >> cnt2, mod); long ie = pow(e, mod - 2, mod); for (int i = cnt2; i >= 2; i--) { es[i - 2] = e; ies[i - 2] = ie; e = e * e % mod; ie = ie * ie % mod; } long now = 1; for (int i = 0; i < cnt2 - 2; i++) { sum_e[i] = es[i] * now % mod; now = now * ies[i] % mod; } return sum_e; } /** * Pre-calculation for inverse NTT. * * @param mod Mod. * @param g Primitive root of mod. * @return Pre-calculation table. */ private static long[] sumIE(int mod, int g) { long[] sum_ie = new long[30]; long[] es = new long[30]; long[] ies = new long[30]; int cnt2 = Integer.numberOfTrailingZeros(mod - 1); long e = pow(g, (mod - 1) >> cnt2, mod); long ie = pow(e, mod - 2, mod); for (int i = cnt2; i >= 2; i--) { es[i - 2] = e; ies[i - 2] = ie; e = e * e % mod; ie = ie * ie % mod; } long now = 1; for (int i = 0; i < cnt2 - 2; i++) { sum_ie[i] = ies[i] * now % mod; now = now * es[i] % mod; } return sum_ie; } /** * Inverse NTT. * * @param a Target array. * @param sumIE Pre-calculation table. * @param mod NTT Prime. */ private static void butterflyInv(long[] a, long[] sumIE, int mod) { int n = a.length; int h = ceilPow2(n); for (int ph = h; ph >= 1; ph--) { int w = 1 << (ph - 1), p = 1 << (h - ph); long inow = 1; for (int s = 0; s < w; s++) { int offset = s << (h - ph + 1); for (int i = 0; i < p; i++) { long l = a[i + offset]; long r = a[i + offset + p]; a[i + offset] = (l + r) % mod; a[i + offset + p] = (mod + l - r) * inow % mod; } int x = Integer.numberOfTrailingZeros(~s); inow = inow * sumIE[x] % mod; } } } /** * Inverse NTT. * * @param a Target array. * @param sumE Pre-calculation table. * @param mod NTT Prime. */ private static void butterfly(long[] a, long[] sumE, int mod) { int n = a.length; int h = ceilPow2(n); for (int ph = 1; ph <= h; ph++) { int w = 1 << (ph - 1), p = 1 << (h - ph); long now = 1; for (int s = 0; s < w; s++) { int offset = s << (h - ph + 1); for (int i = 0; i < p; i++) { long l = a[i + offset]; long r = a[i + offset + p] * now % mod; a[i + offset] = (l + r) % mod; a[i + offset + p] = (l - r + mod) % mod; } int x = Integer.numberOfTrailingZeros(~s); now = now * sumE[x] % mod; } } } /** * Convolution. * * @param a Target array 1. * @param b Target array 2. * @param mod NTT Prime. * @return Answer. */ public static long[] convolution(long[] a, long[] b, int mod) { int n = a.length; int m = b.length; if (n == 0 || m == 0) return new long[0]; int z = 1 << ceilPow2(n + m - 1); { long[] na = new long[z]; long[] nb = new long[z]; System.arraycopy(a, 0, na, 0, n); System.arraycopy(b, 0, nb, 0, m); a = na; b = nb; } int g = primitiveRoot(mod); long[] sume = sumE(mod, g); long[] sumie = sumIE(mod, g); butterfly(a, sume, mod); butterfly(b, sume, mod); for (int i = 0; i < z; i++) { a[i] = a[i] * b[i] % mod; } butterflyInv(a, sumie, mod); a = java.util.Arrays.copyOf(a, n + m - 1); long iz = pow(z, mod - 2, mod); for (int i = 0; i < n + m - 1; i++) a[i] = a[i] * iz % mod; return a; } /** * Convolution. * * @param a Target array 1. * @param b Target array 2. * @param mod Any mod. * @return Answer. */ public static long[] convolutionLL(long[] a, long[] b, int mod) { int n = a.length; int m = b.length; if (n == 0 || m == 0) return new long[0]; int mod1 = 754974721; int mod2 = 167772161; int mod3 = 469762049; long[] c1 = convolution(a, b, mod1); long[] c2 = convolution(a, b, mod2); long[] c3 = convolution(a, b, mod3); int retSize = c1.length; long[] ret = new long[retSize]; int[] mods = { mod1, mod2, mod3, mod }; for (int i = 0; i < retSize; ++i) { ret[i] = garner(new long[] { c1[i], c2[i], c3[i] }, mods); } return ret; } /** * Convolution by ModInt. * * @param a Target array 1. * @param b Target array 2. * @return Answer. */ public static java.util.List<ModIntFactory.ModInt> convolution(java.util.List<ModIntFactory.ModInt> a, java.util.List<ModIntFactory.ModInt> b) { int mod = a.get(0).mod(); long[] va = a.stream().mapToLong(ModIntFactory.ModInt::value).toArray(); long[] vb = b.stream().mapToLong(ModIntFactory.ModInt::value).toArray(); long[] c = convolutionLL(va, vb, mod); ModIntFactory factory = new ModIntFactory(mod); return java.util.Arrays.stream(c).mapToObj(factory::create).collect(java.util.stream.Collectors.toList()); } /** * Naive convolution. (Complexity is O(N^2)!!) * * @param a Target array 1. * @param b Target array 2. * @param mod Mod. * @return Answer. */ public static long[] convolutionNaive(long[] a, long[] b, int mod) { int n = a.length; int m = b.length; int k = n + m - 1; long[] ret = new long[k]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { ret[i + j] += a[i] * b[j] % mod; ret[i + j] %= mod; } } return ret; } } static class ContestScanner { private final java.io.InputStream in; private final byte[] buffer = new byte[1024]; private int ptr = 0; private int buflen = 0; private static final long LONG_MAX_TENTHS = 922337203685477580L; private static final int LONG_MAX_LAST_DIGIT = 7; private static final int LONG_MIN_LAST_DIGIT = 8; public ContestScanner(java.io.InputStream in) { this.in = in; } public ContestScanner() { this(System.in); } private boolean hasNextByte() { if (ptr < buflen) { return true; } else { ptr = 0; try { buflen = in.read(buffer); } catch (java.io.IOException e) { e.printStackTrace(); } if (buflen <= 0) { return false; } } return true; } private int readByte() { if (hasNextByte()) return buffer[ptr++]; else return -1; } private static boolean isPrintableChar(int c) { return 33 <= c && c <= 126; } public boolean hasNext() { while (hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++; return hasNextByte(); } public String next() { if (!hasNext()) throw new java.util.NoSuchElementException(); StringBuilder sb = new StringBuilder(); int b = readByte(); while (isPrintableChar(b)) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } public long nextLong() { if (!hasNext()) throw new java.util.NoSuchElementException(); long n = 0; boolean minus = false; int b = readByte(); if (b == '-') { minus = true; b = readByte(); } if (b < '0' || '9' < b) { throw new NumberFormatException(); } while (true) { if ('0' <= b && b <= '9') { int digit = b - '0'; if (n >= LONG_MAX_TENTHS) { if (n == LONG_MAX_TENTHS) { if (minus) { if (digit <= LONG_MIN_LAST_DIGIT) { n = -n * 10 - digit; b = readByte(); if (!isPrintableChar(b)) { return n; } else if (b < '0' || '9' < b) { throw new NumberFormatException( String.format("%d%s... is not number", n, Character.toString(b))); } } } else { if (digit <= LONG_MAX_LAST_DIGIT) { n = n * 10 + digit; b = readByte(); if (!isPrintableChar(b)) { return n; } else if (b < '0' || '9' < b) { throw new NumberFormatException( String.format("%d%s... is not number", n, Character.toString(b))); } } } } throw new ArithmeticException( String.format("%s%d%d... overflows long.", minus ? "-" : "", n, digit)); } n = n * 10 + digit; } else if (b == -1 || !isPrintableChar(b)) { return minus ? -n : n; } else { throw new NumberFormatException(); } b = readByte(); } } public int nextInt() { long nl = nextLong(); if (nl < Integer.MIN_VALUE || nl > Integer.MAX_VALUE) throw new NumberFormatException(); return (int) nl; } public double nextDouble() { return Double.parseDouble(next()); } public long[] nextLongArray(int length) { long[] array = new long[length]; for (int i = 0; i < length; i++) array[i] = this.nextLong(); return array; } public long[] nextLongArray(int length, java.util.function.LongUnaryOperator map) { long[] array = new long[length]; for (int i = 0; i < length; i++) array[i] = map.applyAsLong(this.nextLong()); return array; } public int[] nextIntArray(int length) { int[] array = new int[length]; for (int i = 0; i < length; i++) array[i] = this.nextInt(); return array; } public int[][] nextIntArrayMulti(int length, int width) { int[][] arrays = new int[width][length]; for (int i = 0; i < length; i++) { for (int j = 0; j < width; j++) arrays[j][i] = this.nextInt(); } return arrays; } public int[] nextIntArray(int length, java.util.function.IntUnaryOperator map) { int[] array = new int[length]; for (int i = 0; i < length; i++) array[i] = map.applyAsInt(this.nextInt()); return array; } public double[] nextDoubleArray(int length) { double[] array = new double[length]; for (int i = 0; i < length; i++) array[i] = this.nextDouble(); return array; } public double[] nextDoubleArray(int length, java.util.function.DoubleUnaryOperator map) { double[] array = new double[length]; for (int i = 0; i < length; i++) array[i] = map.applyAsDouble(this.nextDouble()); return array; } public long[][] nextLongMatrix(int height, int width) { long[][] mat = new long[height][width]; for (int h = 0; h < height; h++) for (int w = 0; w < width; w++) { mat[h][w] = this.nextLong(); } return mat; } public int[][] nextIntMatrix(int height, int width) { int[][] mat = new int[height][width]; for (int h = 0; h < height; h++) for (int w = 0; w < width; w++) { mat[h][w] = this.nextInt(); } return mat; } public double[][] nextDoubleMatrix(int height, int width) { double[][] mat = new double[height][width]; for (int h = 0; h < height; h++) for (int w = 0; w < width; w++) { mat[h][w] = this.nextDouble(); } return mat; } public char[][] nextCharMatrix(int height, int width) { char[][] mat = new char[height][width]; for (int h = 0; h < height; h++) { String s = this.next(); for (int w = 0; w < width; w++) { mat[h][w] = s.charAt(w); } } return mat; } } static class ContestPrinter extends java.io.PrintWriter { public ContestPrinter(java.io.PrintStream stream) { super(stream); } public ContestPrinter() { super(System.out); } private static String dtos(double x, int n) { StringBuilder sb = new StringBuilder(); if (x < 0) { sb.append('-'); x = -x; } x += Math.pow(10, -n) / 2; sb.append((long) x); sb.append("."); x -= (long) x; for (int i = 0; i < n; i++) { x *= 10; sb.append((int) x); x -= (int) x; } return sb.toString(); } @Override public void print(float f) { super.print(dtos(f, 20)); } @Override public void println(float f) { super.println(dtos(f, 20)); } @Override public void print(double d) { super.print(dtos(d, 20)); } @Override public void println(double d) { super.println(dtos(d, 20)); } public void printArray(int[] array, String separator) { int n = array.length; for (int i = 0; i < n - 1; i++) { super.print(array[i]); super.print(separator); } super.println(array[n - 1]); } public void printArray(int[] array) { this.printArray(array, " "); } public void printArray(int[] array, String separator, java.util.function.IntUnaryOperator map) { int n = array.length; for (int i = 0; i < n - 1; i++) { super.print(map.applyAsInt(array[i])); super.print(separator); } super.println(map.applyAsInt(array[n - 1])); } public void printArray(int[] array, java.util.function.IntUnaryOperator map) { this.printArray(array, " ", map); } public void printArray(long[] array, String separator) { int n = array.length; for (int i = 0; i < n - 1; i++) { super.print(array[i]); super.print(separator); } super.println(array[n - 1]); } public void printArray(long[] array) { this.printArray(array, " "); } public void printArray(long[] array, String separator, java.util.function.LongUnaryOperator map) { int n = array.length; for (int i = 0; i < n - 1; i++) { super.print(map.applyAsLong(array[i])); super.print(separator); } super.println(map.applyAsLong(array[n - 1])); } public void printArray(long[] array, java.util.function.LongUnaryOperator map) { this.printArray(array, " ", map); } } public static void safeSort(int[] array) { Integer[] temp = new Integer[array.length]; for (int n = 0; n < array.length; n++) { temp[n] = array[n]; } Arrays.sort(temp); for (int n = 0; n < array.length; n++) { array[n] = temp[n]; } } public static void safeSort(long[] array) { Long[] temp = new Long[array.length]; for (int n = 0; n < array.length; n++) { temp[n] = array[n]; } Arrays.sort(temp); for (int n = 0; n < array.length; n++) { array[n] = temp[n]; } } public static void safeSort(double[] array) { Double[] temp = new Double[array.length]; for (int n = 0; n < array.length; n++) { temp[n] = array[n]; } Arrays.sort(temp); for (int n = 0; n < array.length; n++) { array[n] = temp[n]; } } }
Java
["4\n1 1\nL\n1 2\nL\n3 3\nRRDLUU\n4 3\nLUURRDDLLLUU"]
2 seconds
["1 1\n1 2\n2 1\n3 2"]
null
Java 11
standard input
[ "implementation" ]
585bb4a040144da39ed240366193e705
The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. In the description of each test case, the first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^6$$$) — the height and width of the field that the robot is located on. The second line of the description is a string $$$s$$$ consisting solely of characters 'L', 'R', 'D' and 'U' — the sequence of commands the robot executes. The string has a length from $$$1$$$ to $$$10^6$$$ commands. It is guaranteed that the total length of $$$s$$$ over all test cases does not exceed $$$10^6$$$.
1,600
Print $$$t$$$ lines, each of which contains the answer to the corresponding test case. The answer to the test case are two integers $$$r$$$ ($$$1 \leq r \leq n$$$) and $$$c$$$ ($$$1 \leq c \leq m$$$), separated by a space — the coordinates of the cell (row number and column number) from which the robot should start moving to perform as many commands as possible. If there are several such cells, you may output any of them.
standard output
PASSED
e12a86dcba754362b63cf9e5f2bce7d1
train_108.jsonl
1635863700
The robot is located on a checkered rectangular board of size $$$n \times m$$$ ($$$n$$$ rows, $$$m$$$ columns). The rows in the board are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and the columns — from $$$1$$$ to $$$m$$$ from left to right.The robot is able to move from the current cell to one of the four cells adjacent by side.The sequence of commands $$$s$$$ executed by the robot is given. Each command is denoted by one of the symbols 'L', 'R', 'D' or 'U', and triggers the movement to left, right, down or up, respectively.The robot can start its movement in any cell. The robot executes the commands starting from the first one, strictly in the order in which they are listed in $$$s$$$. If the robot moves beyond the edge of the board, it falls and breaks. A command that causes the robot to break is not considered successfully executed.The robot's task is to execute as many commands as possible without falling off the board. For example, on board $$$3 \times 3$$$, if the robot starts a sequence of actions $$$s=$$$"RRDLUU" ("right", "right", "down", "left", "up", "up") from the central cell, the robot will perform one command, then the next command will force him to cross the edge. If the robot starts moving from the cell $$$(2, 1)$$$ (second row, first column) then all commands will be executed successfully and the robot will stop at the cell $$$(1, 2)$$$ (first row, second column). The robot starts from cell $$$(2, 1)$$$ (second row, first column). It moves right, right, down, left, up, and up. In this case it ends in the cell $$$(1, 2)$$$ (first row, second column). Determine the cell from which the robot should start its movement in order to execute as many commands as possible.
256 megabytes
import java.util.*; public class Solutin{ public static void main(String[] args){ Scanner sc=new Scanner(System.in); int t=sc.nextInt(); while (t-->0) { int n=sc.nextInt(), m=sc.nextInt(); char[] s=sc.next().toCharArray(); int bx = 0, by = 0; int min_bx = 0, max_bx = 0, min_by = 0, max_by = 0; for (char c: s) { if(c == 'L') min_by = Math.min(min_by, --by); else if (c == 'R') max_by = Math.max(max_by, ++by); else if (c == 'U') min_bx = Math.min(min_bx, --bx); else max_bx = Math.max(max_bx, ++bx); if (max_bx - min_bx >= n) { if (bx == min_bx) min_bx++; break; } if (max_by - min_by >= m) { if (by == min_by) min_by++; break; } } System.out.print(( 1 - min_bx)+" "+ ( 1 - min_by )+"\n"); } } }
Java
["4\n1 1\nL\n1 2\nL\n3 3\nRRDLUU\n4 3\nLUURRDDLLLUU"]
2 seconds
["1 1\n1 2\n2 1\n3 2"]
null
Java 11
standard input
[ "implementation" ]
585bb4a040144da39ed240366193e705
The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. In the description of each test case, the first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^6$$$) — the height and width of the field that the robot is located on. The second line of the description is a string $$$s$$$ consisting solely of characters 'L', 'R', 'D' and 'U' — the sequence of commands the robot executes. The string has a length from $$$1$$$ to $$$10^6$$$ commands. It is guaranteed that the total length of $$$s$$$ over all test cases does not exceed $$$10^6$$$.
1,600
Print $$$t$$$ lines, each of which contains the answer to the corresponding test case. The answer to the test case are two integers $$$r$$$ ($$$1 \leq r \leq n$$$) and $$$c$$$ ($$$1 \leq c \leq m$$$), separated by a space — the coordinates of the cell (row number and column number) from which the robot should start moving to perform as many commands as possible. If there are several such cells, you may output any of them.
standard output
PASSED
f7ec10b01e837d6af0c1c445b67179e9
train_108.jsonl
1635863700
The robot is located on a checkered rectangular board of size $$$n \times m$$$ ($$$n$$$ rows, $$$m$$$ columns). The rows in the board are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and the columns — from $$$1$$$ to $$$m$$$ from left to right.The robot is able to move from the current cell to one of the four cells adjacent by side.The sequence of commands $$$s$$$ executed by the robot is given. Each command is denoted by one of the symbols 'L', 'R', 'D' or 'U', and triggers the movement to left, right, down or up, respectively.The robot can start its movement in any cell. The robot executes the commands starting from the first one, strictly in the order in which they are listed in $$$s$$$. If the robot moves beyond the edge of the board, it falls and breaks. A command that causes the robot to break is not considered successfully executed.The robot's task is to execute as many commands as possible without falling off the board. For example, on board $$$3 \times 3$$$, if the robot starts a sequence of actions $$$s=$$$"RRDLUU" ("right", "right", "down", "left", "up", "up") from the central cell, the robot will perform one command, then the next command will force him to cross the edge. If the robot starts moving from the cell $$$(2, 1)$$$ (second row, first column) then all commands will be executed successfully and the robot will stop at the cell $$$(1, 2)$$$ (first row, second column). The robot starts from cell $$$(2, 1)$$$ (second row, first column). It moves right, right, down, left, up, and up. In this case it ends in the cell $$$(1, 2)$$$ (first row, second column). Determine the cell from which the robot should start its movement in order to execute as many commands as possible.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class E { public static void main(String[] args) { FastScanner sc=new FastScanner(); int t=sc.nextInt(); PrintWriter pw=new PrintWriter(System.out); while(t-->0) { int r=sc.nextInt(); int col=sc.nextInt(); char[] a=sc.next().toCharArray(); int maxL=0; int maxR=0; int maxU=0; int maxD=0; int H=0; int V=0; for(char c:a){ if(c=='L'){ H++; if(H>0){ maxL=Math.max(maxL,H); } } else if(c=='D'){ V--; if(V<0){ maxD=Math.max(maxD,Math.abs(V)); } } else if(c=='U'){ V++; if(V>0){ maxU=Math.max(maxU,V); } } else { H--; if(H<0){ maxR=Math.max(maxR,Math.abs(H)); } } if(maxL+maxR>=col){ if(H==maxL){ maxL--; } else { maxR--; } break; } if(maxU+maxD>=r){ if(V==maxU){ maxU--; } else { maxD--; } break; } } int ansX=-1; int ansY=-1; if(maxL>=maxR){ ansY=maxL+1; } else { ansY=col-maxR; } if(maxU>=maxD){ ansX=maxU+1; } else { ansX=r-maxD; } pw.println(ansX+" "+ansY); } pw.flush(); } static class FastScanner { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readArray(int n) { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } long nextLong() { return Long.parseLong(next()); } } }
Java
["4\n1 1\nL\n1 2\nL\n3 3\nRRDLUU\n4 3\nLUURRDDLLLUU"]
2 seconds
["1 1\n1 2\n2 1\n3 2"]
null
Java 11
standard input
[ "implementation" ]
585bb4a040144da39ed240366193e705
The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. In the description of each test case, the first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^6$$$) — the height and width of the field that the robot is located on. The second line of the description is a string $$$s$$$ consisting solely of characters 'L', 'R', 'D' and 'U' — the sequence of commands the robot executes. The string has a length from $$$1$$$ to $$$10^6$$$ commands. It is guaranteed that the total length of $$$s$$$ over all test cases does not exceed $$$10^6$$$.
1,600
Print $$$t$$$ lines, each of which contains the answer to the corresponding test case. The answer to the test case are two integers $$$r$$$ ($$$1 \leq r \leq n$$$) and $$$c$$$ ($$$1 \leq c \leq m$$$), separated by a space — the coordinates of the cell (row number and column number) from which the robot should start moving to perform as many commands as possible. If there are several such cells, you may output any of them.
standard output
PASSED
bfd33df714744e6cedee90ec466c4033
train_108.jsonl
1635863700
The robot is located on a checkered rectangular board of size $$$n \times m$$$ ($$$n$$$ rows, $$$m$$$ columns). The rows in the board are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and the columns — from $$$1$$$ to $$$m$$$ from left to right.The robot is able to move from the current cell to one of the four cells adjacent by side.The sequence of commands $$$s$$$ executed by the robot is given. Each command is denoted by one of the symbols 'L', 'R', 'D' or 'U', and triggers the movement to left, right, down or up, respectively.The robot can start its movement in any cell. The robot executes the commands starting from the first one, strictly in the order in which they are listed in $$$s$$$. If the robot moves beyond the edge of the board, it falls and breaks. A command that causes the robot to break is not considered successfully executed.The robot's task is to execute as many commands as possible without falling off the board. For example, on board $$$3 \times 3$$$, if the robot starts a sequence of actions $$$s=$$$"RRDLUU" ("right", "right", "down", "left", "up", "up") from the central cell, the robot will perform one command, then the next command will force him to cross the edge. If the robot starts moving from the cell $$$(2, 1)$$$ (second row, first column) then all commands will be executed successfully and the robot will stop at the cell $$$(1, 2)$$$ (first row, second column). The robot starts from cell $$$(2, 1)$$$ (second row, first column). It moves right, right, down, left, up, and up. In this case it ends in the cell $$$(1, 2)$$$ (first row, second column). Determine the cell from which the robot should start its movement in order to execute as many commands as possible.
256 megabytes
//package eround101; import java.util.*; import java.io.*; import java.lang.*; import java.util.StringTokenizer; public class Solution { static HritikScanner sc = new HritikScanner(); static PrintWriter pw = new PrintWriter(System.out, true); final static int MOD = 1000000007; static StringBuilder sb = new StringBuilder(); public static void main(String[] args) { int t = ni(); while (t-- > 0) { solve(); } } static void solve() { int n = ni(); int m = ni(); char[] arr = sc.next().toCharArray(); int min_x = 0, min_y = 0, max_x = 0, max_y = 0; int x = 0, y = 0; for(char ele : arr) { if(ele == 'L') { min_y = Math.min(min_y, --y); } if(ele == 'R') { max_y = Math.max(max_y, ++y); } if(ele == 'U') { min_x = Math.min(min_x, --x); } if(ele == 'D') { max_x = Math.max(max_x, ++x); } if(max_y-min_y >= m) { if(y == min_y)min_y++; break; } if(max_x-min_x >= n) { if(x == min_x)min_x++; break; } } //pl(min_x+" "+min_y); pl((1-min_x)+" "+(1-min_y)); } ///////////////////////////////////////////////////////////////////////////////// static class FenwickTree { // Binary Index Tree int[] tree; static int size; public FenwickTree(int size) { this.size = size; tree = new int[size + 5]; } public void add(int i, int val) { while (i <= size) { tree[i] += val; i += i & -i; // adding the decimal value of the last set bit. } } public int sum(int i) { int res = 0; while (i >= 1) { res += tree[i]; i -= i & -i; // deleting the last set bit } return res; } public int sum(int l, int r) { return sum(r) - sum(l - 1); } } ///////////////////////////////////////////////////////////////////////////////// static int[] nextIntArray(int n) { int[] arr = new int[n]; int i = 0; while (i < n) { arr[i++] = ni(); } return arr; } static long[] nextLongArray(int n) { long[] arr = new long[n]; int i = 0; while (i < n) { arr[i++] = nl(); } return arr; } static int[] nextIntArray1(int n) { int[] arr = new int[n + 1]; int i = 1; while (i <= n) { arr[i++] = ni(); } return arr; } ///////////////////////////////////////////////////////////////////////////////// static int ni() { return sc.nextInt(); } static long nl() { return sc.nextLong(); } static double nd() { return sc.nextDouble(); } ///////////////////////////////////////////////////////////////////////////////// static void pl() { pw.println(); } static void p(Object o) { pw.print(o + " "); } static void pl(Object o) { pw.println(o); } ///////////////////////////////////////////////////////////////////////////////// static void print(Object s) { System.out.println(s); } ///////////////////////////////////////////////////////////////////////////////// //-----------HritikScanner class for faster input----------// static class HritikScanner { BufferedReader br; StringTokenizer st; public HritikScanner() { 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 class Pair implements Comparable<Pair> { int num, row, col; Pair(int num, int row, int col) { this.num = num; this.row = row; this.col = col; } public int get1() { return num; } public int get2() { return row; } public int compareTo(Pair A) { return this.num - A.num; } public String toString() { return num + " " + row + " " + col; } } ////////////////////////////////////////////////////////////////// // Function to return gcd of a and b time complexity O(log(a+b)) static long gcd(long a, long b) { if (a == 0) { return b; } return gcd(b % a, a); } // method to return LCM of two numbers static long lcm(long a, long b) { return (a / gcd(a, b)) * b; } ////////////////////////////////////////////////////////////////// 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 (long i = 5; i * i <= n; i = i + 6) { if (n % i == 0 || n % (i + 2) == 0) { return false; } } return true; } ////////////////////////////////////////////////////////////////// static boolean isPowerOfTwo(long n) { if (n == 0) { return false; } return (long) (Math.ceil((Math.log(n) / Math.log(2)))) == (long) (Math.floor(((Math.log(n) / Math.log(2))))); } public static long getFact(int n) { long ans = 1; while (n > 0) { ans *= n; ans %= MOD; n--; } return ans; } public static long pow(long n, int pow) { if (pow == 0) { return 1; } long temp = pow(n, pow / 2) % MOD; temp *= temp; temp %= MOD; if (pow % 2 == 1) { temp *= n; } temp %= MOD; return temp; } public static long nCr(int n, int r) { long ans = 1; int temp = n - r; while (n > temp) { ans *= n; ans %= MOD; n--; } ans *= pow(getFact(r) % MOD, MOD - 2) % MOD; ans %= MOD; return ans; } ////////////////////////////////////////////////////////////////// // method returns Nth power of A static double nthRoot(int A, int N) { // intially guessing a random number between // 0 and 9 double xPre = Math.random() % 10; // smaller eps, denotes more accuracy double eps = 0.001; // initializing difference between two // roots by INT_MAX double delX = 2147483647; // xK denotes current value of x double xK = 0.0; // loop untill we reach desired accuracy while (delX > eps) { // calculating current value from previous // value by newton's method xK = ((N - 1.0) * xPre + (double) A / Math.pow(xPre, N - 1)) / (double) N; delX = Math.abs(xK - xPre); xPre = xK; } return xK; } }
Java
["4\n1 1\nL\n1 2\nL\n3 3\nRRDLUU\n4 3\nLUURRDDLLLUU"]
2 seconds
["1 1\n1 2\n2 1\n3 2"]
null
Java 11
standard input
[ "implementation" ]
585bb4a040144da39ed240366193e705
The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. In the description of each test case, the first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^6$$$) — the height and width of the field that the robot is located on. The second line of the description is a string $$$s$$$ consisting solely of characters 'L', 'R', 'D' and 'U' — the sequence of commands the robot executes. The string has a length from $$$1$$$ to $$$10^6$$$ commands. It is guaranteed that the total length of $$$s$$$ over all test cases does not exceed $$$10^6$$$.
1,600
Print $$$t$$$ lines, each of which contains the answer to the corresponding test case. The answer to the test case are two integers $$$r$$$ ($$$1 \leq r \leq n$$$) and $$$c$$$ ($$$1 \leq c \leq m$$$), separated by a space — the coordinates of the cell (row number and column number) from which the robot should start moving to perform as many commands as possible. If there are several such cells, you may output any of them.
standard output
PASSED
6cbe8697093df73f2ee07138f2b00635
train_108.jsonl
1635863700
The robot is located on a checkered rectangular board of size $$$n \times m$$$ ($$$n$$$ rows, $$$m$$$ columns). The rows in the board are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and the columns — from $$$1$$$ to $$$m$$$ from left to right.The robot is able to move from the current cell to one of the four cells adjacent by side.The sequence of commands $$$s$$$ executed by the robot is given. Each command is denoted by one of the symbols 'L', 'R', 'D' or 'U', and triggers the movement to left, right, down or up, respectively.The robot can start its movement in any cell. The robot executes the commands starting from the first one, strictly in the order in which they are listed in $$$s$$$. If the robot moves beyond the edge of the board, it falls and breaks. A command that causes the robot to break is not considered successfully executed.The robot's task is to execute as many commands as possible without falling off the board. For example, on board $$$3 \times 3$$$, if the robot starts a sequence of actions $$$s=$$$"RRDLUU" ("right", "right", "down", "left", "up", "up") from the central cell, the robot will perform one command, then the next command will force him to cross the edge. If the robot starts moving from the cell $$$(2, 1)$$$ (second row, first column) then all commands will be executed successfully and the robot will stop at the cell $$$(1, 2)$$$ (first row, second column). The robot starts from cell $$$(2, 1)$$$ (second row, first column). It moves right, right, down, left, up, and up. In this case it ends in the cell $$$(1, 2)$$$ (first row, second column). Determine the cell from which the robot should start its movement in order to execute as many commands as possible.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class Codeforces { public static void main(String[] args) { FastReader fastReader = new FastReader(); int t = fastReader.nextInt(); while (t-- > 0) { int n = fastReader.nextInt(); int m = fastReader.nextInt(); char c [] = fastReader.next().toCharArray(); Pair rangex = new Pair(1,n); Pair rangey = new Pair(1,m); Pair ans = new Pair(1,1); int x = 0 ; int y = 0; int size = c.length; for (int i = 0 ; i < size ; i++){ if (c[i] == 'U') x--; else if (c[i] == 'L') y--; else if (c[i] == 'R') y++; else x++; Pair x1 , y1; if (x >= 0){ x1 = new Pair(1,n- x); }else{ x1 = new Pair(1 - x , n); } if (y >= 0){ y1 = new Pair(1,m- y); }else{ y1 = new Pair(1 - y, m); } rangex = intersection(rangex,x1); rangey = intersection(rangey,y1); if (rangex.x > rangex.y || rangey.x > rangey.y){ break; }else{ ans = new Pair(rangex.x , rangey.x); } } System.out.println(ans.x + " " + ans.y); } } public static Pair intersection( Pair p1 , Pair p2){ Pair ans = null; int x = Math.max(p1.x , p2.x); int y = Math.min(p2.y,p1.y); return ans = new Pair(x,y); } static class Pair{ int x; int y; Pair(int x, int y){ this.x = x; this.y = y; } } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader( new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["4\n1 1\nL\n1 2\nL\n3 3\nRRDLUU\n4 3\nLUURRDDLLLUU"]
2 seconds
["1 1\n1 2\n2 1\n3 2"]
null
Java 11
standard input
[ "implementation" ]
585bb4a040144da39ed240366193e705
The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. In the description of each test case, the first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^6$$$) — the height and width of the field that the robot is located on. The second line of the description is a string $$$s$$$ consisting solely of characters 'L', 'R', 'D' and 'U' — the sequence of commands the robot executes. The string has a length from $$$1$$$ to $$$10^6$$$ commands. It is guaranteed that the total length of $$$s$$$ over all test cases does not exceed $$$10^6$$$.
1,600
Print $$$t$$$ lines, each of which contains the answer to the corresponding test case. The answer to the test case are two integers $$$r$$$ ($$$1 \leq r \leq n$$$) and $$$c$$$ ($$$1 \leq c \leq m$$$), separated by a space — the coordinates of the cell (row number and column number) from which the robot should start moving to perform as many commands as possible. If there are several such cells, you may output any of them.
standard output
PASSED
0544ff7c84aecf0ab48666c8169d3bf0
train_108.jsonl
1635863700
The robot is located on a checkered rectangular board of size $$$n \times m$$$ ($$$n$$$ rows, $$$m$$$ columns). The rows in the board are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and the columns — from $$$1$$$ to $$$m$$$ from left to right.The robot is able to move from the current cell to one of the four cells adjacent by side.The sequence of commands $$$s$$$ executed by the robot is given. Each command is denoted by one of the symbols 'L', 'R', 'D' or 'U', and triggers the movement to left, right, down or up, respectively.The robot can start its movement in any cell. The robot executes the commands starting from the first one, strictly in the order in which they are listed in $$$s$$$. If the robot moves beyond the edge of the board, it falls and breaks. A command that causes the robot to break is not considered successfully executed.The robot's task is to execute as many commands as possible without falling off the board. For example, on board $$$3 \times 3$$$, if the robot starts a sequence of actions $$$s=$$$"RRDLUU" ("right", "right", "down", "left", "up", "up") from the central cell, the robot will perform one command, then the next command will force him to cross the edge. If the robot starts moving from the cell $$$(2, 1)$$$ (second row, first column) then all commands will be executed successfully and the robot will stop at the cell $$$(1, 2)$$$ (first row, second column). The robot starts from cell $$$(2, 1)$$$ (second row, first column). It moves right, right, down, left, up, and up. In this case it ends in the cell $$$(1, 2)$$$ (first row, second column). Determine the cell from which the robot should start its movement in order to execute as many commands as possible.
256 megabytes
import java.util.*; import java.util.concurrent.CyclicBarrier; import java.io.*; import java.awt.Point; public class Main{ static int mod = (int) (Math.pow(10, 9)+7); static final int dx[] = { -1, 0, 1, 0 }, dy[] = { 0, -1, 0, 1 }; static final int[] dx8 = { -1, -1, -1, 0, 0, 1, 1, 1 }, dy8 = { -1, 0, 1, -1, 1, -1, 0, 1 }; static final int[] dx9 = { -1, -1, -1, 0, 0, 0, 1, 1, 1 }, dy9 = { -1, 0, 1, -1, 0, 1, -1, 0, 1 }; static final int inf = Integer.MAX_VALUE / 2; static final long infL = Long.MAX_VALUE / 3; static final double infD = Double.MAX_VALUE / 3; static final double eps = 1e-10; static final double pi = Math.PI; static List<Integer> primeNumbers = new ArrayList<>(); public static void main(String[] args) throws IOException{ MyScanner sc = new MyScanner(); //changes in this line of code out = new PrintWriter(new BufferedOutputStream(System.out)); // out = new PrintWriter(new BufferedWriter(new FileWriter("output.out"))); //WRITE YOUR CODE IN HERE int test = sc.nextInt(); while(test --> 0){ //boundaries int n = sc.nextInt(); int m = sc.nextInt(); char[] str = sc.nextLine().toCharArray(); //current pos int cx = 1; int cy = 1; //int best pos int bx = 1; int by = 1; //max vlaues int tm = 1, lm = 1, bm = 1, rm = 1; //according to question for(char ch: str){ // out.println(ch); if(ch == 'L'){ //solve for one case if(cy-1 == 0){ if(rm == m){ break; }else{ rm++; by++; } }else{ cy--; } }else if(ch == 'R'){ if(cy == m){ break; }else{ cy++; rm = Math.max(rm,cy); } }else if(ch == 'U'){ if(cx-1 == 0){ if(bm == n){ break; }else{ bm++; bx++; } }else{ cx--; } }else{ if(cx == n){ break; }else{ cx++; bm = Math.max(bm,cx); } } // out.p rintln(bx+ " " + by); } out.println(bx+ " " + by); } out.close(); } //------------------------------------------------------------------- //------------------------------------------------------------------- //------------------------------------------------------------------- //------------------------------------------------------------------- //------------------------------------------------------------------- //fast java implementation for sure public static class Graph{ public int V; public ArrayList<ArrayList<Integer>> edges; Graph(int V){ this.V = V; edges = new ArrayList<>(V+1); for(int i= 0; i <= V; i++){ edges.add(new ArrayList<>()); } } ///single sided this for sure public void addEdge(int from , int to){ edges.get(from).add(to); } } public static class DisjointUnionSets { int[] rank, parent; int n; // Constructor public DisjointUnionSets(int n) { rank = new int[n]; parent = new int[n]; this.n = n; makeSet(); } // Creates n sets with single item in each void makeSet() { for (int i = 0; i < n; i++) { // Initially, all elements are in // their own set. parent[i] = i; } } // Returns representative of x's set int find(int x) { // Finds the representative of the set // that x is an element of if (parent[x] != x) { // if x is not the parent of itself // Then x is not the representative of // his set, parent[x] = find(parent[x]); // so we recursively call Find on its parent // and move i's node directly under the // representative of this set } return parent[x]; } // Unites the set that includes x and the set // that includes x void union(int x, int y) { // Find representatives of two sets int xRoot = find(x), yRoot = find(y); // Elements are in the same set, no need // to unite anything. if (xRoot == yRoot) return; // If x's rank is less than y's rank if (rank[xRoot] < rank[yRoot]) // Then move x under y so that depth // of tree remains less parent[xRoot] = yRoot; // Else if y's rank is less than x's rank else if (rank[yRoot] < rank[xRoot]) // Then move y under x so that depth of // tree remains less parent[yRoot] = xRoot; else // if ranks are the same { // Then move y under x (doesn't matter // which one goes where) parent[yRoot] = xRoot; // And increment the result tree's // rank by 1 rank[xRoot] = rank[xRoot] + 1; } } } //with mod public static long power(long x, long y) { long res = 1L; // Initialize result while (y > 0) { // If y is odd, multiply x with result if ((y & 1) != 0){ x %= mod; res %= mod; res = (res * x)%mod; } // y must be even now y = y >> 1; // y = y/2 x%= mod; x = (x * x)%mod; // Change x to x^2 } // 550193677 return res%mod; } //without mod public static long power2(long x, long y) { long res = 1L; // 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/ x = (x * x); } // 550193677 return res; } public static class segmentTree{ public long[] arr; public long[] tree; public long[] lazy; segmentTree(long[] array){ int n = array.length; arr = new long[n]; for(int i= 0; i < n; i++) arr[i] = array[i]; tree = new long[4*n + 1]; lazy = new long[4*n + 1]; } public void build(int[]arr, int s, int e, int[] tree, int index){ if(s == e){ tree[index] = arr[s]; return; } //otherwise divide in two parts and fill both sides simply int mid = (s+e)/2; build(arr, s, mid, tree, 2*index); build(arr, mid+1, e, tree, 2*index+1); //who will build the current position dude tree[index] = Math.min(tree[2*index], tree[2*index+1]); } public int query(int sr, int er, int sc, int ec, int index, int[] tree){ if(lazy[index] != 0){ tree[index] += lazy[index]; if(sc != ec){ lazy[2*index+1] += lazy[index]; lazy[2*index] += lazy[index]; } lazy[index] = 0; } //no overlap if(sr > ec || sc > er) return Integer.MAX_VALUE; //found the index baby if(sr <= sc && ec <= er) return tree[index]; //finding the index on both sides hehehehhe int mid = (sc + ec)/2; int left = query(sr, er, sc, mid, 2*index, tree); int right = query(sr, er, mid+1, ec, 2*index + 1, tree); return Integer.min(left, right); } //now we will do point update implementation //it should be simple then we expected for sure public void update(int index, int indexr, int increment, int[] tree, int s, int e){ if(lazy[index] != 0){ tree[index] += lazy[index]; if(s != e){ lazy[2*index+1] = lazy[index]; lazy[2*index] = lazy[index]; } lazy[index] = 0; } //no overlap if(indexr < s || indexr > e) return; //found the required index if(s == e){ tree[index] += increment; return; } //search for the index on both sides int mid = (s+e)/2; update(2*index, indexr, increment, tree, s, mid); update(2*index+1, indexr, increment, tree, mid+1, e); //now update the current range simply tree[index] = Math.min(tree[2*index+1], tree[2*index]); } public void rangeUpdate(int[] tree , int index, int s, int e, int sr, int er, int increment){ //if not at all in the same range if(e < sr || er < s) return; //complete then also move forward if(s == e){ tree[index] += increment; return; } //otherwise move in both subparts int mid = (s+e)/2; rangeUpdate(tree, 2*index, s, mid, sr, er, increment); rangeUpdate(tree, 2*index + 1, mid+1, e, sr, er, increment); //update current range too na //i always forget this step for some reasons hehehe, idiot tree[index] = Math.min(tree[2*index], tree[2*index + 1]); } public void rangeUpdateLazy(int[] tree, int index, int s, int e, int sr, int er, int increment){ //update lazy values //resolve lazy value before going down if(lazy[index] != 0){ tree[index] += lazy[index]; if(s != e){ lazy[2*index+1] += lazy[index]; lazy[2*index] += lazy[index]; } lazy[index] = 0; } //no overlap case if(sr > e || s > er) return; //complete overlap if(sr <= s && er >= e){ tree[index] += increment; if(s != e){ lazy[2*index+1] += increment; lazy[2*index] += increment; } return; } //otherwise go on both left and right side and do your shit int mid = (s + e)/2; rangeUpdateLazy(tree, 2*index, s, mid, sr, er, increment); rangeUpdateLazy(tree, 2*index + 1, mid+1, e, sr, er, increment); tree[index] = Math.min(tree[2*index+1], tree[2*index]); return; } } //prime sieve public static void primeSieve(int n){ BitSet bitset = new BitSet(n+1); for(long i = 0; i < n ; i++){ if (i == 0 || i == 1) { bitset.set((int) i); continue; } if(bitset.get((int) i)) continue; primeNumbers.add((int)i); for(long j = i; j <= n ; j+= i) bitset.set((int)j); } } //number of divisors public static int countDivisors(long number){ if(number == 1) return 1; List<Integer> primeFactors = new ArrayList<>(); int index = 0; long curr = primeNumbers.get(index); while(curr * curr <= number){ while(number % curr == 0){ number = number/curr; primeFactors.add((int) curr); } index++; curr = primeNumbers.get(index); } if(number != 1) primeFactors.add((int) number); int current = primeFactors.get(0); int totalDivisors = 1; int currentCount = 2; for (int i = 1; i < primeFactors.size(); i++) { if (primeFactors.get(i) == current) { currentCount++; } else { totalDivisors *= currentCount; currentCount = 2; current = primeFactors.get(i); } } totalDivisors *= currentCount; return totalDivisors; } //now adding next permutation function to java hehe public static boolean next_permutation(int[] p) { for (int a = p.length - 2; a >= 0; --a) if (p[a] < p[a + 1]) for (int b = p.length - 1;; --b) if (p[b] > p[a]) { int t = p[a]; p[a] = p[b]; p[b] = t; for (++a, b = p.length - 1; a < b; ++a, --b) { t = p[a]; p[a] = p[b]; p[b] = t; } return true; } return false; } //finding the value of NCR in O(RlogN) time and O(1) space public static long getNcR(int n, int r) { long p = 1, k = 1; if (n - r < r) r = n - r; if (r != 0) { while (r > 0) { p *= n; k *= r; long m = __gcd(p, k); p /= m; k /= m; n--; r--; } } else { p = 1; } return p; } public static void sort(long[] a) { ArrayList<Long> l=new ArrayList<>(); for (long i:a) l.add(i); Collections.sort(l); for (int i=0; i<a.length; i++) a[i]=l.get(i); } //for ncr calculator public static long __gcd(long n1, long n2) { long gcd = 1; for (int i = 1; i <= n1 && i <= n2; ++i) { // Checks if i is factor of both integers if (n1 % i == 0 && n2 % i == 0) { gcd = i; } } return gcd; } //is vowel function public static boolean isVowel(char c) { return (c=='a' || c=='A' || c=='e' || c=='E' || c=='i' || c=='I' || c=='o' || c=='O' || c=='u' || c=='U'); } //two add two big numbers with some mod public static int add(int a, int b) { a+=b; if (a>=mod) return a-mod; return a; } //two sub two numbers public static int sub(int a, int b) { a-=b; if (a<0) a+=mod; else if (a>=mod) a-=mod; return a; } //to sort the array with better method public static void sort(int[] a) { ArrayList<Integer> l=new ArrayList<>(); for (int i:a) l.add(i); Collections.sort(l); for (int i=0; i<a.length; i++) a[i]=l.get(i); } //for calculating binomialCoeff public static int binomialCoeff(int n, int k) { int C[] = new int[k + 1]; // nC0 is 1 C[0] = 1; for (int i = 1; i <= n; i++) { // Compute next row of pascal // triangle using the previous row for (int j = Math.min(i, k); j > 0; j--) C[j] = C[j] + C[j - 1]; } return C[k]; } //Pair with int int public static class Pair{ public int a; public int b; Pair(int a , int b){ this.a = a; this.b = b; } @Override public String toString(){ return a + " -> " + b; } } //Triplet with int int int public static class Triplet{ public int a; public int b; public int c; Triplet(int a , int b, int c){ this.a = a; this.b = b; this.c = c; } @Override public String toString(){ return a + " -> " + b; } } //Shortcut function public static long lcm(long a , long b){ return a * (b/gcd(a,b)); } //let's make one for calculating lcm basically public static int lcm(int a , int b){ return (a * b)/gcd(a,b); } //int version for gcd public static int gcd(int a, int b){ if(b == 0) return a; return gcd(b , a%b); } //long version for gcd public static long gcd(long a, long b){ if(b == 0) return a; return gcd(b , a%b); } //swapping two elements in an array public static void swap(int[] arr, int left , int right){ int temp = arr[left]; arr[left] = arr[right]; arr[right] = temp; } // //for char array public static void swap(char[] arr, int left , int right){ char temp = arr[left]; arr[left] = arr[right]; arr[right] = temp; } //reversing an array public static void reverse(int[] arr){ int left = 0; int right = arr.length-1; while(left <= right){ swap(arr, left,right); left++; right--; } } //-----------PrintWriter for faster output--------------------------------- public static PrintWriter out; //-----------MyScanner class for faster input---------- public static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } // public MyScanner() throws FileNotFoundException { // br = new BufferedReader(new FileReader("input.in")); // } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine(){ String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } //-------------------------------------------------------- }
Java
["4\n1 1\nL\n1 2\nL\n3 3\nRRDLUU\n4 3\nLUURRDDLLLUU"]
2 seconds
["1 1\n1 2\n2 1\n3 2"]
null
Java 11
standard input
[ "implementation" ]
585bb4a040144da39ed240366193e705
The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. In the description of each test case, the first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^6$$$) — the height and width of the field that the robot is located on. The second line of the description is a string $$$s$$$ consisting solely of characters 'L', 'R', 'D' and 'U' — the sequence of commands the robot executes. The string has a length from $$$1$$$ to $$$10^6$$$ commands. It is guaranteed that the total length of $$$s$$$ over all test cases does not exceed $$$10^6$$$.
1,600
Print $$$t$$$ lines, each of which contains the answer to the corresponding test case. The answer to the test case are two integers $$$r$$$ ($$$1 \leq r \leq n$$$) and $$$c$$$ ($$$1 \leq c \leq m$$$), separated by a space — the coordinates of the cell (row number and column number) from which the robot should start moving to perform as many commands as possible. If there are several such cells, you may output any of them.
standard output
PASSED
fb33ca74f0a3b4bd2a6753849deab5e5
train_108.jsonl
1635863700
The robot is located on a checkered rectangular board of size $$$n \times m$$$ ($$$n$$$ rows, $$$m$$$ columns). The rows in the board are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and the columns — from $$$1$$$ to $$$m$$$ from left to right.The robot is able to move from the current cell to one of the four cells adjacent by side.The sequence of commands $$$s$$$ executed by the robot is given. Each command is denoted by one of the symbols 'L', 'R', 'D' or 'U', and triggers the movement to left, right, down or up, respectively.The robot can start its movement in any cell. The robot executes the commands starting from the first one, strictly in the order in which they are listed in $$$s$$$. If the robot moves beyond the edge of the board, it falls and breaks. A command that causes the robot to break is not considered successfully executed.The robot's task is to execute as many commands as possible without falling off the board. For example, on board $$$3 \times 3$$$, if the robot starts a sequence of actions $$$s=$$$"RRDLUU" ("right", "right", "down", "left", "up", "up") from the central cell, the robot will perform one command, then the next command will force him to cross the edge. If the robot starts moving from the cell $$$(2, 1)$$$ (second row, first column) then all commands will be executed successfully and the robot will stop at the cell $$$(1, 2)$$$ (first row, second column). The robot starts from cell $$$(2, 1)$$$ (second row, first column). It moves right, right, down, left, up, and up. In this case it ends in the cell $$$(1, 2)$$$ (first row, second column). Determine the cell from which the robot should start its movement in order to execute as many commands as possible.
256 megabytes
// HOPE //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //---------------------------------------------------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //---------------------------------------------------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////// ////////// /////// ////////// /////// RRRRRRRRRRRRR YY YY AA NN NN ////////// /////// RR RR YY YY AA AA NN NN NN ////////// /////// RR RR YY YY AA AA NN NN NN ////////// /////// RRRRRRRRRR YY YY AAAAAAAAAAAA NN NN NN ////////// /////// RR RR YY AAAAAAAAAAAAAA NN NN NN ////////// /////// RR RR YY AA AA NN NNNN ////////// /////// RR RR YY AA AA NN NN ////////// /////// RR RR_____________________________________________________________________________ ////////// //////// ////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //---------------------------------------------------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //---------------------------------------------------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; public class Codeforces2 { static PrintWriter out = new PrintWriter(System.out); static final int mod=1_000_000_007; 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()); } int[] readIntArray(int n){ int[] a = new int[n]; for(int i=0;i<n;i++) a[i] = nextInt(); return a; } long[] readLongArray(int n){ long[] a = new long[n]; for(int i=0;i<n;i++) a[i] = nextLong(); return a; } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } //Try seeing general case public static void main(String[] args) { FastReader s = new FastReader(); int t = s.nextInt(); while(t-->0) { int n = s.nextInt(); int m = s.nextInt(); char[] ch = s.nextLine().toCharArray(); find(n, m, ch); } out.close(); } public static void find(int n, int m, char[] ch) { int x=0, y=0; int minX = 0, maxX = 0, minY = 0, maxY = 0; int resX = 1, resY = 1; for (char c : ch) { if (c == 'L') y--; else if (c == 'R') y++; else if (c == 'U') x--; else x++; minX = Math.min(minX, x); maxX = Math.max(maxX, x); minY = Math.min(minY, y); maxY = Math.max(maxY, y); if(maxX - minX >= n) break; if(maxY - minY >= m) break; resX = n - maxX; resY = m - maxY; } out.println(resX+" "+resY); } /////////////////////////////////////////////////THE END/////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// public static int gcd(int x,int y) { return y==0?x:gcd(y,x%y); } public static long gcd(long x,long y) { return y==0L?x:gcd(y,x%y); } public static int lcm(int a, int b) { return (a * b) / gcd(a, b); } public static long lcm(long a, long b) { return (a * b) / gcd(a, b); } public static long pow(long a,long b) { if(b==0L) return 1L; long tmp=1; while(b>1L) { if((b&1L)==1) tmp*=a; a*=a; b>>=1; } return (tmp*a); } public static long modPow(long a,long b,long mod) { if(b==0L) return 1L; long tmp=1; while(b>1L) { if((b&1L)==1L) tmp*=a; a*=a; a%=mod; tmp%=mod; b>>=1; } return (tmp*a)%mod; } static long mul(long a, long b) { return a*b%mod; } static long fact(int n) { long ans=1; for (int i=2; i<=n; i++) ans=mul(ans, i); return ans; } static long fastPow(long base, long exp) { if (exp==0) return 1; long half=fastPow(base, exp/2); if (exp%2==0) return mul(half, half); return mul(half, mul(half, base)); } static void debug(int ...a) { for(int x: a) out.print(x+" "); out.println(); } static void debug(long ...a) { for(long x: a) out.print(x+" "); out.println(); } static void debugMatrix(int[][] a) { for(int[] x:a) out.println(Arrays.toString(x)); } static void debugMatrix(long[][] a) { for(long[] x:a) out.println(Arrays.toString(x)); } static void reverseArray(int[] a) { int n = a.length; int[] arr = new int[n]; for (int i = 0; i < n; i++) arr[i] = a[n - i - 1]; for (int i = 0; i < n; i++) a[i] = arr[i]; } static void reverseArray(long[] a) { int n = a.length; long[] arr = new long[n]; for (int i = 0; i < n; i++) arr[i] = a[n - i - 1]; for (int i = 0; i < n; i++) a[i] = arr[i]; } static void sort(int[] a) { ArrayList<Integer> ls = new ArrayList<>(); for(int x: a) ls.add(x); Collections.sort(ls); for(int i=0;i<a.length;i++) a[i] = ls.get(i); } static class Pair{ int x, y; Pair(int x, int y) { this.x = x; this.y = y; } @Override public String toString() { return "Pair{" + "x=" + x + ", y=" + y + '}'; } } static class MyCmp implements Comparator<Pair> { public int compare(Pair p1, Pair p2) { return p1.x-p2.x; } } }
Java
["4\n1 1\nL\n1 2\nL\n3 3\nRRDLUU\n4 3\nLUURRDDLLLUU"]
2 seconds
["1 1\n1 2\n2 1\n3 2"]
null
Java 11
standard input
[ "implementation" ]
585bb4a040144da39ed240366193e705
The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. In the description of each test case, the first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^6$$$) — the height and width of the field that the robot is located on. The second line of the description is a string $$$s$$$ consisting solely of characters 'L', 'R', 'D' and 'U' — the sequence of commands the robot executes. The string has a length from $$$1$$$ to $$$10^6$$$ commands. It is guaranteed that the total length of $$$s$$$ over all test cases does not exceed $$$10^6$$$.
1,600
Print $$$t$$$ lines, each of which contains the answer to the corresponding test case. The answer to the test case are two integers $$$r$$$ ($$$1 \leq r \leq n$$$) and $$$c$$$ ($$$1 \leq c \leq m$$$), separated by a space — the coordinates of the cell (row number and column number) from which the robot should start moving to perform as many commands as possible. If there are several such cells, you may output any of them.
standard output
PASSED
f542f719df91d5807c9e4876d0a687e6
train_108.jsonl
1635863700
The robot is located on a checkered rectangular board of size $$$n \times m$$$ ($$$n$$$ rows, $$$m$$$ columns). The rows in the board are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and the columns — from $$$1$$$ to $$$m$$$ from left to right.The robot is able to move from the current cell to one of the four cells adjacent by side.The sequence of commands $$$s$$$ executed by the robot is given. Each command is denoted by one of the symbols 'L', 'R', 'D' or 'U', and triggers the movement to left, right, down or up, respectively.The robot can start its movement in any cell. The robot executes the commands starting from the first one, strictly in the order in which they are listed in $$$s$$$. If the robot moves beyond the edge of the board, it falls and breaks. A command that causes the robot to break is not considered successfully executed.The robot's task is to execute as many commands as possible without falling off the board. For example, on board $$$3 \times 3$$$, if the robot starts a sequence of actions $$$s=$$$"RRDLUU" ("right", "right", "down", "left", "up", "up") from the central cell, the robot will perform one command, then the next command will force him to cross the edge. If the robot starts moving from the cell $$$(2, 1)$$$ (second row, first column) then all commands will be executed successfully and the robot will stop at the cell $$$(1, 2)$$$ (first row, second column). The robot starts from cell $$$(2, 1)$$$ (second row, first column). It moves right, right, down, left, up, and up. In this case it ends in the cell $$$(1, 2)$$$ (first row, second column). Determine the cell from which the robot should start its movement in order to execute as many commands as possible.
256 megabytes
import java.util.*; import java.util.Map; public class Sol{ static class Pair{ int a; char c; Pair(int f,char s){ a=f; c=s; } } 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 row=0,col=0,maxr=0,minr=0,maxc=0,minc=0; String s=sc.next(); for(int i=0;i<s.length();i++) { if(s.charAt(i)=='L') col--; if(s.charAt(i)=='R') col++; if(s.charAt(i)=='U') row--; if(s.charAt(i)=='D') row++; int mr=Math.max(maxr,row); int mir=Math.min(minr,row); int mc=Math.max(maxc,col); int mic=Math.min(minc,col); if(mr-mir>=n) break; if(mc-mic>=m) break; maxr=mr; minr=mir;maxc=mc;minc=mic; } if(minc<0) minc=1-minc; else minc++; if(minr<0) minr=1-minr; else minr++; System.out.println(minr+" "+minc); } } }
Java
["4\n1 1\nL\n1 2\nL\n3 3\nRRDLUU\n4 3\nLUURRDDLLLUU"]
2 seconds
["1 1\n1 2\n2 1\n3 2"]
null
Java 11
standard input
[ "implementation" ]
585bb4a040144da39ed240366193e705
The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. In the description of each test case, the first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^6$$$) — the height and width of the field that the robot is located on. The second line of the description is a string $$$s$$$ consisting solely of characters 'L', 'R', 'D' and 'U' — the sequence of commands the robot executes. The string has a length from $$$1$$$ to $$$10^6$$$ commands. It is guaranteed that the total length of $$$s$$$ over all test cases does not exceed $$$10^6$$$.
1,600
Print $$$t$$$ lines, each of which contains the answer to the corresponding test case. The answer to the test case are two integers $$$r$$$ ($$$1 \leq r \leq n$$$) and $$$c$$$ ($$$1 \leq c \leq m$$$), separated by a space — the coordinates of the cell (row number and column number) from which the robot should start moving to perform as many commands as possible. If there are several such cells, you may output any of them.
standard output
PASSED
02418e068d63590601e9e68d1ef54d7a
train_108.jsonl
1635863700
The robot is located on a checkered rectangular board of size $$$n \times m$$$ ($$$n$$$ rows, $$$m$$$ columns). The rows in the board are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and the columns — from $$$1$$$ to $$$m$$$ from left to right.The robot is able to move from the current cell to one of the four cells adjacent by side.The sequence of commands $$$s$$$ executed by the robot is given. Each command is denoted by one of the symbols 'L', 'R', 'D' or 'U', and triggers the movement to left, right, down or up, respectively.The robot can start its movement in any cell. The robot executes the commands starting from the first one, strictly in the order in which they are listed in $$$s$$$. If the robot moves beyond the edge of the board, it falls and breaks. A command that causes the robot to break is not considered successfully executed.The robot's task is to execute as many commands as possible without falling off the board. For example, on board $$$3 \times 3$$$, if the robot starts a sequence of actions $$$s=$$$"RRDLUU" ("right", "right", "down", "left", "up", "up") from the central cell, the robot will perform one command, then the next command will force him to cross the edge. If the robot starts moving from the cell $$$(2, 1)$$$ (second row, first column) then all commands will be executed successfully and the robot will stop at the cell $$$(1, 2)$$$ (first row, second column). The robot starts from cell $$$(2, 1)$$$ (second row, first column). It moves right, right, down, left, up, and up. In this case it ends in the cell $$$(1, 2)$$$ (first row, second column). Determine the cell from which the robot should start its movement in order to execute as many commands as possible.
256 megabytes
import java.util.*; import java.io.*; import java.math.*; import java.lang.*; public class RobotontheBoard { // static int mod = 998244353; static int mod = 1000000007; private static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } public static void main(String[] args) throws Exception { FastReader scn = new FastReader(); PrintWriter pw = new PrintWriter(System.out); int t = scn.nextInt(); outer : while(t-->0){ int n = scn.nextInt(); int m = scn.nextInt(); String s = scn.nextLine(); int maxL = m-1; int le = 0, re = 0, x = 0; for(int i=0; i<s.length(); i++){ char ch = s.charAt(i); if(ch == 'L'){ x--; le = Math.min(x, le); int diff = re - le; if(diff > maxL){ le++; break; } }else if(ch == 'R'){ x++; re = Math.max(x, re); int diff = re - le; if(diff > maxL){ re--; break; } } } int maxW = n-1; int de = 0, ue = 0; x = 0; for(int i=0; i<s.length(); i++){ char ch = s.charAt(i); if(ch == 'U'){ x++; ue = Math.max(ue, x); int diff = ue - de; if(diff > maxW){ ue--; break; } }else if(ch == 'D'){ x--; de = Math.min(de, x); int diff = ue - de; if(diff > maxW){ de++; break; } } } int r = 1 + ue; int c = m - re; pw.println(r + " " + c); } pw.close(); } public static class Pair{ int x; int y; Pair(int x, int y){ this.x = x; this.y = y; } } private static void sort(int[] arr) { List<Integer> list = new ArrayList<>(); for (int i=0; i<arr.length; i++){ list.add(arr[i]); } Collections.sort(list); // collections.sort uses nlogn in backend for (int i = 0; i < arr.length; i++){ arr[i] = list.get(i); } } private static void sort(long[] arr) { List<Long> list = new ArrayList<>(); for(int i=0; i<arr.length; i++){ list.add(arr[i]); } Collections.sort(list); // collections.sort uses nlogn in backend for (int i = 0; i < arr.length; i++){ arr[i] = list.get(i); } } // private static void sort(Pair[] arr) { // List<Pair> list = new ArrayList<>(); // for(int i=0; i<arr.length; i++){ // list.add(arr[i]); // } // Collections.sort(list); // collections.sort uses nlogn in backend // for (int i = 0; i < arr.length; i++){ // arr[i] = list.get(i); // } // } private static void reverseSort(int[] arr){ List<Integer> list = new ArrayList<>(); for (int i=0; i<arr.length; i++){ list.add(arr[i]); } Collections.sort(list, Collections.reverseOrder()); // collections.sort uses nlogn in backend for (int i = 0; i < arr.length; i++){ arr[i] = list.get(i); } } private static void reverseSort(long[] arr){ List<Long> list = new ArrayList<>(); for (int i=0; i<arr.length; i++){ list.add(arr[i]); } Collections.sort(list, Collections.reverseOrder()); // collections.sort uses nlogn in backend for (int i = 0; i < arr.length; i++){ arr[i] = list.get(i); } } private static void reverseSort(ArrayList<Integer> list){ Collections.sort(list, Collections.reverseOrder()); } private static int lowerBound(int[] arr, int x){ int n = arr.length, si = 0, ei = n - 1; while(si <= ei){ int mid = si + (ei - si)/2; if(arr[mid] == x){ if(mid-1 >= 0 && arr[mid-1] == arr[mid]){ ei = mid-1; }else{ return mid; } }else if(arr[mid] > x){ ei = mid - 1; }else{ si = mid+1; } } return si; } private static int upperBound(int[] arr, int x){ int n = arr.length, si = 0, ei = n - 1; while(si <= ei){ int mid = si + (ei - si)/2; if(arr[mid] == x){ if(mid+1 < n && arr[mid+1] == arr[mid]){ si = mid+1; }else{ return mid + 1; } }else if(arr[mid] > x){ ei = mid - 1; }else{ si = mid+1; } } return si; } private static int upperBound(ArrayList<Integer> list, int x){ int n = list.size(), si = 0, ei = n - 1; while(si <= ei){ int mid = si + (ei - si)/2; if(list.get(mid) == x){ if(mid+1 < n && list.get(mid+1) == list.get(mid)){ si = mid+1; }else{ return mid + 1; } }else if(list.get(mid) > x){ ei = mid - 1; }else{ si = mid+1; } } return si; } // (x^y)%p in O(logy) private static long power(long x, long y){ long res = 1; x = x % mod; while(y > 0){ if ((y & 1) == 1){ res = (res * x) % mod; } y = y >> 1; x = (x * x) % mod; } return res; } public static boolean nextPermutation(int[] arr) { if(arr == null || arr.length <= 1){ return false; } int last = arr.length-2; while(last >= 0){ if(arr[last] < arr[last+1]){ break; } last--; } if (last < 0){ return false; } if(last >= 0){ int nextGreater = arr.length-1; for(int i=arr.length-1; i>last; i--){ if(arr[i] > arr[last]){ nextGreater = i; break; } } swap(arr, last, nextGreater); } reverse(arr, last+1, arr.length-1); return true; } private static void swap(int[] arr, int i, int j){ int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } private static void reverse(int[] arr, int i, int j){ while(i < j){ swap(arr, i++, j--); } } private static String reverseStr(String s){ StringBuilder sb = new StringBuilder(s); return sb.reverse().toString(); } // TC- O(logmax(a,b)) private static int gcd(int a, int b) { if(a == 0){ return b; } return gcd(b%a, a); } private static long gcd(long a, long b) { if(a == 0L){ return b; } return gcd(b%a, a); } private static long lcm(long a, long b) { return a / gcd(a, b) * b; } // TC- O(logmax(a,b)) private static int lcm(int a, int b) { return a / gcd(a, b) * b; } private static long inv(long x){ return power(x, mod - 2); } private static long summation(long n){ return (n * (n + 1L)) >> 1; } }
Java
["4\n1 1\nL\n1 2\nL\n3 3\nRRDLUU\n4 3\nLUURRDDLLLUU"]
2 seconds
["1 1\n1 2\n2 1\n3 2"]
null
Java 11
standard input
[ "implementation" ]
585bb4a040144da39ed240366193e705
The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. In the description of each test case, the first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^6$$$) — the height and width of the field that the robot is located on. The second line of the description is a string $$$s$$$ consisting solely of characters 'L', 'R', 'D' and 'U' — the sequence of commands the robot executes. The string has a length from $$$1$$$ to $$$10^6$$$ commands. It is guaranteed that the total length of $$$s$$$ over all test cases does not exceed $$$10^6$$$.
1,600
Print $$$t$$$ lines, each of which contains the answer to the corresponding test case. The answer to the test case are two integers $$$r$$$ ($$$1 \leq r \leq n$$$) and $$$c$$$ ($$$1 \leq c \leq m$$$), separated by a space — the coordinates of the cell (row number and column number) from which the robot should start moving to perform as many commands as possible. If there are several such cells, you may output any of them.
standard output
PASSED
788707a193fe4e64e3ff969bfc975d0b
train_108.jsonl
1635863700
The robot is located on a checkered rectangular board of size $$$n \times m$$$ ($$$n$$$ rows, $$$m$$$ columns). The rows in the board are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and the columns — from $$$1$$$ to $$$m$$$ from left to right.The robot is able to move from the current cell to one of the four cells adjacent by side.The sequence of commands $$$s$$$ executed by the robot is given. Each command is denoted by one of the symbols 'L', 'R', 'D' or 'U', and triggers the movement to left, right, down or up, respectively.The robot can start its movement in any cell. The robot executes the commands starting from the first one, strictly in the order in which they are listed in $$$s$$$. If the robot moves beyond the edge of the board, it falls and breaks. A command that causes the robot to break is not considered successfully executed.The robot's task is to execute as many commands as possible without falling off the board. For example, on board $$$3 \times 3$$$, if the robot starts a sequence of actions $$$s=$$$"RRDLUU" ("right", "right", "down", "left", "up", "up") from the central cell, the robot will perform one command, then the next command will force him to cross the edge. If the robot starts moving from the cell $$$(2, 1)$$$ (second row, first column) then all commands will be executed successfully and the robot will stop at the cell $$$(1, 2)$$$ (first row, second column). The robot starts from cell $$$(2, 1)$$$ (second row, first column). It moves right, right, down, left, up, and up. In this case it ends in the cell $$$(1, 2)$$$ (first row, second column). Determine the cell from which the robot should start its movement in order to execute as many commands as possible.
256 megabytes
import java.io.DataInputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.PrintWriter; public class Main { private static void run() throws IOException { int n, m; n = in.nextInt(); m = in.nextInt(); char[] s = in.next().toCharArray(); int left = 1; int right = 1; int top = 1; int bottom = 1; int x = 1; int y = 1; int ans_x = 1; int ans_y = 1; for (int i = 0; i < s.length; i++) { int dx = 0, dy = 0; if (s[i] == 'R') { dy = 1; } else if (s[i] == 'L') { dy = -1; } else if (s[i] == 'U') { dx = -1; } else if (s[i] == 'D') { dx = 1; } int nx = x + dx; int ny = y + dy; left = Math.min(ny, left); right = Math.max(ny, right); top = Math.min(nx, top); bottom = Math.max(nx, bottom); if (right - left + 1 > m) break; if (bottom - top + 1 > n) break; x = nx; y = ny; ans_x = 1 + (1 - top); ans_y = 1 + (1 - left); } out.print(ans_x); out.print(' '); out.print(ans_y); out.println(); } public static void main(String[] args) throws IOException { in = new Reader(); out = new PrintWriter(new OutputStreamWriter(System.out)); int t = in.nextInt(); for (int i = 0; i < t; i++) { run(); } out.flush(); in.close(); out.close(); } private static int gcd(int a, int b) { if (a == 0 || b == 0) return 0; while (b != 0) { int tmp; tmp = a % b; a = b; b = tmp; } return a; } static final long mod = 1000000007; static long pow_mod(long a, long b) { long result = 1; while (b != 0) { if ((b & 1) != 0) result = (result * a) % mod; a = (a * a) % mod; b >>= 1; } return result; } private static long multiplied_mod(long... longs) { long ans = 1; for (long now : longs) { ans = (ans * now) % mod; } return ans; } @SuppressWarnings("FieldCanBeLocal") private static Reader in; private static PrintWriter out; private static int[] read_int_array(int len) throws IOException { int[] a = new int[len]; for (int i = 0; i < len; i++) { a[i] = in.nextInt(); } return a; } private static long[] read_long_array(int len) throws IOException { long[] a = new long[len]; for (int i = 0; i < len; i++) { a[i] = in.nextLong(); } return a; } private static void print_array(int[] array) { for (int now : array) { out.print(now); out.print(' '); } out.println(); } private static void print_array(long[] array) { for (long now : array) { out.print(now); out.print(' '); } out.println(); } static class Reader { private static final int BUFFER_SIZE = 1 << 16; private final DataInputStream din; private final byte[] buffer; private int bufferPointer, bytesRead; Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { final byte[] buf = new byte[1024]; // 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 nextSign() throws IOException { byte c = read(); while ('+' != c && '-' != c) { c = read(); } return '+' == c ? 0 : 1; } private static boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } public int skip() throws IOException { int b; // noinspection ALL while ((b = read()) != -1 && isSpaceChar(b)) { ; } return b; } public char nc() throws IOException { return (char) skip(); } public String next() throws IOException { int b = skip(); final StringBuilder sb = new StringBuilder(); while (!isSpaceChar(b)) { // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = read(); } return sb.toString(); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') { c = read(); } final 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(); } final 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(); } final 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 { din.close(); } } }
Java
["4\n1 1\nL\n1 2\nL\n3 3\nRRDLUU\n4 3\nLUURRDDLLLUU"]
2 seconds
["1 1\n1 2\n2 1\n3 2"]
null
Java 11
standard input
[ "implementation" ]
585bb4a040144da39ed240366193e705
The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. In the description of each test case, the first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^6$$$) — the height and width of the field that the robot is located on. The second line of the description is a string $$$s$$$ consisting solely of characters 'L', 'R', 'D' and 'U' — the sequence of commands the robot executes. The string has a length from $$$1$$$ to $$$10^6$$$ commands. It is guaranteed that the total length of $$$s$$$ over all test cases does not exceed $$$10^6$$$.
1,600
Print $$$t$$$ lines, each of which contains the answer to the corresponding test case. The answer to the test case are two integers $$$r$$$ ($$$1 \leq r \leq n$$$) and $$$c$$$ ($$$1 \leq c \leq m$$$), separated by a space — the coordinates of the cell (row number and column number) from which the robot should start moving to perform as many commands as possible. If there are several such cells, you may output any of them.
standard output
PASSED
1a4d290da2f260eee2612459e21a85db
train_108.jsonl
1635863700
The robot is located on a checkered rectangular board of size $$$n \times m$$$ ($$$n$$$ rows, $$$m$$$ columns). The rows in the board are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and the columns — from $$$1$$$ to $$$m$$$ from left to right.The robot is able to move from the current cell to one of the four cells adjacent by side.The sequence of commands $$$s$$$ executed by the robot is given. Each command is denoted by one of the symbols 'L', 'R', 'D' or 'U', and triggers the movement to left, right, down or up, respectively.The robot can start its movement in any cell. The robot executes the commands starting from the first one, strictly in the order in which they are listed in $$$s$$$. If the robot moves beyond the edge of the board, it falls and breaks. A command that causes the robot to break is not considered successfully executed.The robot's task is to execute as many commands as possible without falling off the board. For example, on board $$$3 \times 3$$$, if the robot starts a sequence of actions $$$s=$$$"RRDLUU" ("right", "right", "down", "left", "up", "up") from the central cell, the robot will perform one command, then the next command will force him to cross the edge. If the robot starts moving from the cell $$$(2, 1)$$$ (second row, first column) then all commands will be executed successfully and the robot will stop at the cell $$$(1, 2)$$$ (first row, second column). The robot starts from cell $$$(2, 1)$$$ (second row, first column). It moves right, right, down, left, up, and up. In this case it ends in the cell $$$(1, 2)$$$ (first row, second column). Determine the cell from which the robot should start its movement in order to execute as many commands as possible.
256 megabytes
import java.io.*; import java.util.*; public class Main { static PrintWriter out; static Reader in; public static void main(String[] args) throws Exception { input_output(); Main solver = new Main(); solver.solve(); out.close(); out.flush(); } static int INF = (int)1e9; static int MAXN = (int)2e6 + 5; static int q, t, n, m, k; void solve() throws Exception { t = in.nextInt(); while (t --> 0) { n = in.nextInt(); m = in.nextInt(); String s = in.next(); int l = 0, r = 0, u = 0, d = 0; int x = 1, y = 1, curX = 0, curY = 0; for (int i = 0; i < s.length(); i++) { if (s.charAt(i) == 'L') {curX--;l = Math.min(l, curX);} else if (s.charAt(i) == 'R') {curX++; r = Math.max(r, curX);} else if (s.charAt(i) == 'U') {curY++; u = Math.max(u, curY);} else {curY--; d = Math.min(d, curY);} int testX = -l+1, testY = u+1; if (testX <= m && testX+r <= m && testY <= n && testY-d <= n) { y = testX; x = testY; } else break; } out.println(x+" "+y); } } static class Reader { private InputStream mIs; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public Reader() { this(System.in); } public Reader(InputStream is) { mIs = is; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = mIs.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public String nextLine() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public String next() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } double nextDouble() { return Double.parseDouble(next()); } public long nextLong() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } } static void input_output() throws IOException { File f = new File("in.txt"); if (f.exists() && !f.isDirectory()) { in = new Reader(new FileInputStream("in.txt")); } else in = new Reader(); f = new File("out.txt"); if (f.exists() && !f.isDirectory()) { out = new PrintWriter(new File("out.txt")); } else out = new PrintWriter(System.out); } }
Java
["4\n1 1\nL\n1 2\nL\n3 3\nRRDLUU\n4 3\nLUURRDDLLLUU"]
2 seconds
["1 1\n1 2\n2 1\n3 2"]
null
Java 11
standard input
[ "implementation" ]
585bb4a040144da39ed240366193e705
The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. In the description of each test case, the first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^6$$$) — the height and width of the field that the robot is located on. The second line of the description is a string $$$s$$$ consisting solely of characters 'L', 'R', 'D' and 'U' — the sequence of commands the robot executes. The string has a length from $$$1$$$ to $$$10^6$$$ commands. It is guaranteed that the total length of $$$s$$$ over all test cases does not exceed $$$10^6$$$.
1,600
Print $$$t$$$ lines, each of which contains the answer to the corresponding test case. The answer to the test case are two integers $$$r$$$ ($$$1 \leq r \leq n$$$) and $$$c$$$ ($$$1 \leq c \leq m$$$), separated by a space — the coordinates of the cell (row number and column number) from which the robot should start moving to perform as many commands as possible. If there are several such cells, you may output any of them.
standard output
PASSED
bf5e21d4b54ce89e842adedb189eb5cc
train_108.jsonl
1635863700
The robot is located on a checkered rectangular board of size $$$n \times m$$$ ($$$n$$$ rows, $$$m$$$ columns). The rows in the board are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and the columns — from $$$1$$$ to $$$m$$$ from left to right.The robot is able to move from the current cell to one of the four cells adjacent by side.The sequence of commands $$$s$$$ executed by the robot is given. Each command is denoted by one of the symbols 'L', 'R', 'D' or 'U', and triggers the movement to left, right, down or up, respectively.The robot can start its movement in any cell. The robot executes the commands starting from the first one, strictly in the order in which they are listed in $$$s$$$. If the robot moves beyond the edge of the board, it falls and breaks. A command that causes the robot to break is not considered successfully executed.The robot's task is to execute as many commands as possible without falling off the board. For example, on board $$$3 \times 3$$$, if the robot starts a sequence of actions $$$s=$$$"RRDLUU" ("right", "right", "down", "left", "up", "up") from the central cell, the robot will perform one command, then the next command will force him to cross the edge. If the robot starts moving from the cell $$$(2, 1)$$$ (second row, first column) then all commands will be executed successfully and the robot will stop at the cell $$$(1, 2)$$$ (first row, second column). The robot starts from cell $$$(2, 1)$$$ (second row, first column). It moves right, right, down, left, up, and up. In this case it ends in the cell $$$(1, 2)$$$ (first row, second column). Determine the cell from which the robot should start its movement in order to execute as many commands as possible.
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 E_Round_753_Div3 { public static long MOD = 1000000007; static long[][] 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(); String command = "LRUD"; int[]X = {0,0,-1,1}; int[]Y = {-1,1,0,0}; for (int Z = 0; Z < T; Z++) { int r = in.nextInt(); int c = in.nextInt(); String data = in.next(); int x = 0; int y = 0; int[]pre = new int[4]; int reX = 1; int reY = 1; for(int i = 0; i < data.length(); i++){ int index = command.indexOf(data.charAt(i)); x += X[index]; y += Y[index]; pre[0] = Integer.min(x, pre[0]); pre[1] = Integer.max(x, pre[1]); pre[2] = Integer.min(y, pre[2]); pre[3] = Integer.max(y, pre[3]); int a = pre[1] - pre[0] + 1; int b = pre[3] - pre[2] + 1; if(a > r || b > c){ break; } reX = -pre[0] + 1; reY = -pre[2] + 1; } out.println(reX + " " + reY); } out.close(); } static int abs(int a) { return a < 0 ? -a : a; } public static int[] KMP(String val) { int i = 0; int j = -1; int[] result = new int[val.length() + 1]; result[0] = -1; while (i < val.length()) { while (j >= 0 && val.charAt(j) != val.charAt(i)) { j = result[j]; } j++; i++; result[i] = j; } return result; } public static boolean nextPer(int[] data) { int i = data.length - 1; while (i > 0 && data[i] < data[i - 1]) { i--; } if (i == 0) { return false; } int j = data.length - 1; while (data[j] < data[i - 1]) { j--; } int temp = data[i - 1]; data[i - 1] = data[j]; data[j] = temp; Arrays.sort(data, i, data.length); return true; } public static int digit(long n) { int result = 0; while (n > 0) { n /= 10; result++; } return result; } public static double dist(long a, long b, long x, long y) { double val = (b - a) * (b - a) + (x - y) * (x - y); val = Math.sqrt(val); double other = x * x + a * a; other = Math.sqrt(other); return val + other; } public static class Point { long x; long y; public Point(long start, long end) { this.x = start; this.y = end; } public String toString() { return x + " " + y; } } public static class FT { long[] data; FT(int n) { data = new long[n]; } public void update(int index, long value) { while (index < data.length) { data[index] += value; index += (index & (-index)); } } public long get(int index) { long result = 0; while (index > 0) { result += data[index]; index -= (index & (-index)); } return result; } } public static long gcd(long a, long b) { if (b == 0) { return a; } return gcd(b, a % b); } public static long pow(long a, int b) { if (b == 0) { return 1; } if (b == 1) { return a; } long val = pow(a, b / 2); if (b % 2 == 0) { return val * val; } else { return val * (val * a); } } static class Scanner { BufferedReader br; StringTokenizer st; public Scanner() throws FileNotFoundException { // System.setOut(new PrintStream(new BufferedOutputStream(System.out), true)); br = new BufferedReader(new InputStreamReader(System.in)); //br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("input.txt")))); } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { throw new RuntimeException(); } } return st.nextToken(); } public long nextLong() { return Long.parseLong(next()); } public int nextInt() { return Integer.parseInt(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String nextLine() { st = null; try { return br.readLine(); } catch (Exception e) { throw new RuntimeException(); } } public boolean endLine() { try { String next = br.readLine(); while (next != null && next.trim().isEmpty()) { next = br.readLine(); } if (next == null) { return true; } st = new StringTokenizer(next); return st.hasMoreTokens(); } catch (Exception e) { throw new RuntimeException(); } } } }
Java
["4\n1 1\nL\n1 2\nL\n3 3\nRRDLUU\n4 3\nLUURRDDLLLUU"]
2 seconds
["1 1\n1 2\n2 1\n3 2"]
null
Java 17
standard input
[ "implementation" ]
585bb4a040144da39ed240366193e705
The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. In the description of each test case, the first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^6$$$) — the height and width of the field that the robot is located on. The second line of the description is a string $$$s$$$ consisting solely of characters 'L', 'R', 'D' and 'U' — the sequence of commands the robot executes. The string has a length from $$$1$$$ to $$$10^6$$$ commands. It is guaranteed that the total length of $$$s$$$ over all test cases does not exceed $$$10^6$$$.
1,600
Print $$$t$$$ lines, each of which contains the answer to the corresponding test case. The answer to the test case are two integers $$$r$$$ ($$$1 \leq r \leq n$$$) and $$$c$$$ ($$$1 \leq c \leq m$$$), separated by a space — the coordinates of the cell (row number and column number) from which the robot should start moving to perform as many commands as possible. If there are several such cells, you may output any of them.
standard output
PASSED
86c7fd6f96dbc06ec1ec66e4683b76e0
train_108.jsonl
1635863700
The robot is located on a checkered rectangular board of size $$$n \times m$$$ ($$$n$$$ rows, $$$m$$$ columns). The rows in the board are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and the columns — from $$$1$$$ to $$$m$$$ from left to right.The robot is able to move from the current cell to one of the four cells adjacent by side.The sequence of commands $$$s$$$ executed by the robot is given. Each command is denoted by one of the symbols 'L', 'R', 'D' or 'U', and triggers the movement to left, right, down or up, respectively.The robot can start its movement in any cell. The robot executes the commands starting from the first one, strictly in the order in which they are listed in $$$s$$$. If the robot moves beyond the edge of the board, it falls and breaks. A command that causes the robot to break is not considered successfully executed.The robot's task is to execute as many commands as possible without falling off the board. For example, on board $$$3 \times 3$$$, if the robot starts a sequence of actions $$$s=$$$"RRDLUU" ("right", "right", "down", "left", "up", "up") from the central cell, the robot will perform one command, then the next command will force him to cross the edge. If the robot starts moving from the cell $$$(2, 1)$$$ (second row, first column) then all commands will be executed successfully and the robot will stop at the cell $$$(1, 2)$$$ (first row, second column). The robot starts from cell $$$(2, 1)$$$ (second row, first column). It moves right, right, down, left, up, and up. In this case it ends in the cell $$$(1, 2)$$$ (first row, second column). Determine the cell from which the robot should start its movement in order to execute as many commands as possible.
256 megabytes
import java.util.*; import java.util.function.*; import java.io.*; // you can compare with output.txt and expected out public class Round753E { MyPrintWriter out; MyScanner in; // final static long FIXED_RANDOM; // static { // FIXED_RANDOM = System.currentTimeMillis(); // } final static String IMPOSSIBLE = "IMPOSSIBLE"; final static String POSSIBLE = "POSSIBLE"; final static String YES = "YES"; final static String NO = "NO"; private void initIO(boolean isFileIO) { if (System.getProperty("ONLINE_JUDGE") == null && isFileIO) { try{ in = new MyScanner(new FileInputStream("input.txt")); out = new MyPrintWriter(new FileOutputStream("output.txt")); } catch(FileNotFoundException e){ e.printStackTrace(); } } else{ in = new MyScanner(System.in); out = new MyPrintWriter(new BufferedOutputStream(System.out)); } } public static void main(String[] args){ // Scanner in = new Scanner(new BufferedReader(new InputStreamReader(System.in))); // the code for the deep recursion (more than 100k or 3~400k or so) // Thread t = new Thread(null, new RoundEdu130F(), "threadName", 1<<28); // t.start(); // t.join(); Round753E sol = new Round753E(); sol.run(); } private void run() { boolean isDebug = false; boolean isFileIO = true; boolean hasMultipleTests = true; initIO(isFileIO); int t = hasMultipleTests? in.nextInt() : 1; for (int i = 1; i <= t; ++i) { if(isDebug){ out.printf("Test %d\n", i); } getInput(); solve(); printOutput(); } in.close(); out.close(); } // use suitable one between matrix(2, n), matrix(n, 2), transposedMatrix(2, n) for graph edges, pairs, ... int n, m; String s; void getInput() { n = in.nextInt(); m = in.nextInt(); s = in.next(); } void printOutput() { out.print(r); out.print(' '); out.println(c); } final char L = 'L', R = 'R', D = 'D', U = 'U'; int r, c; void solve(){ final int len = s.length(); int maxL = 0; int maxR = 0; int maxD = 0; int maxU = 0; int currR = 0; int currC = 0; LOOP: for(int i=0; i<len; i++) { switch(s.charAt(i)) { case L: currC--; if(maxR - currC + 1 > m) break LOOP; maxL = Math.max(maxL, -currC); break; case R: currC++; if(maxL + currC + 1 > m) break LOOP; maxR = Math.max(maxR, currC); break; case D: currR++; if(maxU + currR + 1 > n) break LOOP; maxD = Math.max(maxD, currR); break; case U: currR--; if(maxD - currR + 1 > n) break LOOP; maxU = Math.max(maxU, -currR); break; } } r = 1 + maxU; c = 1 + maxL; } // Optional<T> solve() // return Optional.empty(); static class Pair implements Comparable<Pair>{ final static long FIXED_RANDOM = System.currentTimeMillis(); int first, second; public Pair(int first, int second) { this.first = first; this.second = second; } @Override public int hashCode() { // http://xorshift.di.unimi.it/splitmix64.c long x = first; x <<= 32; x += second; x += FIXED_RANDOM; x += 0x9e3779b97f4a7c15l; x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9l; x = (x ^ (x >> 27)) * 0x94d049bb133111ebl; return (int)(x ^ (x >> 31)); } @Override public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; Pair other = (Pair) obj; return first == other.first && second == other.second; } @Override public String toString() { return "[" + first + "," + second + "]"; } @Override public int compareTo(Pair o) { int cmp = Integer.compare(first, o.first); return cmp != 0? cmp: Integer.compare(second, o.second); } } public static class MyScanner { BufferedReader br; StringTokenizer st; // 32768? public MyScanner(InputStream is, int bufferSize) { br = new BufferedReader(new InputStreamReader(is), bufferSize); } public MyScanner(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); // br = new BufferedReader(new InputStreamReader(System.in)); // br = new BufferedReader(new InputStreamReader(new FileInputStream("input.txt"))); } public void close() { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine(){ String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } int[][] nextMatrix(int n, int m) { return nextMatrix(n, m, 0); } int[][] nextMatrix(int n, int m, int offset) { int[][] mat = new int[n][m]; for(int i=0; i<n; i++) { for(int j=0; j<m; j++) { mat[i][j] = nextInt()+offset; } } return mat; } int[][] nextTransposedMatrix(int n, int m){ return nextTransposedMatrix(n, m, 0); } int[][] nextTransposedMatrix(int n, int m, int offset){ int[][] mat = new int[m][n]; for(int i=0; i<n; i++) { for(int j=0; j<m; j++) { mat[j][i] = nextInt()+offset; } } return mat; } int[] nextIntArray(int len) { return nextIntArray(len, 0); } int[] nextIntArray(int len, int offset){ int[] a = new int[len]; for(int j=0; j<len; j++) a[j] = nextInt()+offset; return a; } long[] nextLongArray(int len) { return nextLongArray(len, 0); } long[] nextLongArray(int len, int offset){ long[] a = new long[len]; for(int j=0; j<len; j++) a[j] = nextLong()+offset; return a; } String[] nextStringArray(int len) { String[] s = new String[len]; for(int i=0; i<len; i++) s[i] = next(); return s; } } public static class MyPrintWriter extends PrintWriter{ public MyPrintWriter(OutputStream os) { super(os); } // public <T> void printlnAns(Optional<T> ans) { // if(ans.isEmpty()) // println(-1); // else // printlnAns(ans.get()); // } public void printlnAns(OptionalInt ans) { println(ans.orElse(-1)); } public void printlnAns(long ans) { println(ans); } public void printlnAns(int ans) { println(ans); } public void printlnAns(boolean[] ans) { for(boolean b: ans) printlnAns(b); } public void printlnAns(boolean ans) { if(ans) println(YES); else println(NO); } public void printAns(long[] arr){ if(arr != null && arr.length > 0){ print(arr[0]); for(int i=1; i<arr.length; i++){ print(" "); print(arr[i]); } } } public void printlnAns(long[] arr){ printAns(arr); println(); } public void printAns(int[] arr){ if(arr != null && arr.length > 0){ print(arr[0]); for(int i=1; i<arr.length; i++){ print(" "); print(arr[i]); } } } public void printlnAns(int[] arr){ printAns(arr); println(); } public <T> void printAns(ArrayList<T> arr){ if(arr != null && arr.size() > 0){ print(arr.get(0)); for(int i=1; i<arr.size(); i++){ print(" "); print(arr.get(i)); } } } public <T> void printlnAns(ArrayList<T> arr){ printAns(arr); println(); } public void printAns(int[] arr, int add){ if(arr != null && arr.length > 0){ print(arr[0]+add); for(int i=1; i<arr.length; i++){ print(" "); print(arr[i]+add); } } } public void printlnAns(int[] arr, int add){ printAns(arr, add); println(); } public void printAns(ArrayList<Integer> arr, int add) { if(arr != null && arr.size() > 0){ print(arr.get(0)+add); for(int i=1; i<arr.size(); i++){ print(" "); print(arr.get(i)+add); } } } public void printlnAns(ArrayList<Integer> arr, int add){ printAns(arr, add); println(); } public void printlnAnsSplit(long[] arr, int split){ if(arr != null){ for(int i=0; i<arr.length; i+=split){ print(arr[i]); for(int j=i+1; j<i+split; j++){ print(" "); print(arr[j]); } println(); } } } public void printlnAnsSplit(int[] arr, int split){ if(arr != null){ for(int i=0; i<arr.length; i+=split){ print(arr[i]); for(int j=i+1; j<i+split; j++){ print(" "); print(arr[j]); } println(); } } } public <T> void printlnAnsSplit(ArrayList<T> arr, int split){ if(arr != null && !arr.isEmpty()){ for(int i=0; i<arr.size(); i+=split){ print(arr.get(i)); for(int j=i+1; j<i+split; j++){ print(" "); print(arr.get(j)); } println(); } } } } static private void permutateAndSort(long[] a) { int n = a.length; Random R = new Random(System.currentTimeMillis()); for(int i=0; i<n; i++) { int t = R.nextInt(n-i); long temp = a[n-1-i]; a[n-1-i] = a[t]; a[t] = temp; } Arrays.sort(a); } static private void permutateAndSort(int[] a) { int n = a.length; Random R = new Random(System.currentTimeMillis()); for(int i=0; i<n; i++) { int t = R.nextInt(n-i); int temp = a[n-1-i]; a[n-1-i] = a[t]; a[t] = temp; } Arrays.sort(a); } static private int[][] constructChildren(int n, int[] parent, int parentRoot){ int[][] childrens = new int[n][]; int[] numChildren = new int[n]; for(int i=0; i<parent.length; i++) { if(parent[i] != parentRoot) numChildren[parent[i]]++; } for(int i=0; i<n; i++) { childrens[i] = new int[numChildren[i]]; } int[] idx = new int[n]; for(int i=0; i<parent.length; i++) { if(parent[i] != parentRoot) childrens[parent[i]][idx[parent[i]]++] = i; } return childrens; } static private int[][][] constructDirectedNeighborhood(int n, int[][] e){ int[] inDegree = new int[n]; int[] outDegree = new int[n]; for(int i=0; i<e.length; i++) { int u = e[i][0]; int v = e[i][1]; outDegree[u]++; inDegree[v]++; } int[][] inNeighbors = new int[n][]; int[][] outNeighbors = new int[n][]; for(int i=0; i<n; i++) { inNeighbors[i] = new int[inDegree[i]]; outNeighbors[i] = new int[outDegree[i]]; } for(int i=0; i<e.length; i++) { int u = e[i][0]; int v = e[i][1]; outNeighbors[u][--outDegree[u]] = v; inNeighbors[v][--inDegree[v]] = u; } return new int[][][] {inNeighbors, outNeighbors}; } static private int[][] constructNeighborhood(int n, int[][] e) { int[] degree = new int[n]; for(int i=0; i<e.length; i++) { int u = e[i][0]; int v = e[i][1]; degree[u]++; degree[v]++; } int[][] neighbors = new int[n][]; for(int i=0; i<n; i++) neighbors[i] = new int[degree[i]]; for(int i=0; i<e.length; i++) { int u = e[i][0]; int v = e[i][1]; neighbors[u][--degree[u]] = v; neighbors[v][--degree[v]] = u; } return neighbors; } static private void drawGraph(int[][] e) { makeDotUndirected(e); try { final Process process = new ProcessBuilder("dot", "-Tpng", "graph.dot") .redirectOutput(new File("graph.png")) .start(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } static private void makeDotUndirected(int[][] e) { MyPrintWriter out2 = null; try { out2 = new MyPrintWriter(new FileOutputStream("graph.dot")); } catch (FileNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } out2.println("strict graph {"); for(int i=0; i<e.length; i++){ out2.println(e[i][0] + "--" + e[i][1] + ";"); } out2.println("}"); out2.close(); } static private void makeDotDirected(int[][] e) { MyPrintWriter out2 = null; try { out2 = new MyPrintWriter(new FileOutputStream("graph.dot")); } catch (FileNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } out2.println("strict digraph {"); for(int i=0; i<e.length; i++){ out2.println(e[i][0] + "->" + e[i][1] + ";"); } out2.println("}"); out2.close(); } }
Java
["4\n1 1\nL\n1 2\nL\n3 3\nRRDLUU\n4 3\nLUURRDDLLLUU"]
2 seconds
["1 1\n1 2\n2 1\n3 2"]
null
Java 17
standard input
[ "implementation" ]
585bb4a040144da39ed240366193e705
The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. In the description of each test case, the first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^6$$$) — the height and width of the field that the robot is located on. The second line of the description is a string $$$s$$$ consisting solely of characters 'L', 'R', 'D' and 'U' — the sequence of commands the robot executes. The string has a length from $$$1$$$ to $$$10^6$$$ commands. It is guaranteed that the total length of $$$s$$$ over all test cases does not exceed $$$10^6$$$.
1,600
Print $$$t$$$ lines, each of which contains the answer to the corresponding test case. The answer to the test case are two integers $$$r$$$ ($$$1 \leq r \leq n$$$) and $$$c$$$ ($$$1 \leq c \leq m$$$), separated by a space — the coordinates of the cell (row number and column number) from which the robot should start moving to perform as many commands as possible. If there are several such cells, you may output any of them.
standard output
PASSED
adfbf2f3d0a88672beb1088a9f7a3a2f
train_108.jsonl
1635863700
You are given an array of integers $$$a$$$ of length $$$n$$$. The elements of the array can be either different or the same. Each element of the array is colored either blue or red. There are no unpainted elements in the array. One of the two operations described below can be applied to an array in a single step: either you can select any blue element and decrease its value by $$$1$$$; or you can select any red element and increase its value by $$$1$$$. Situations in which there are no elements of some color at all are also possible. For example, if the whole array is colored blue or red, one of the operations becomes unavailable.Determine whether it is possible to make $$$0$$$ or more steps such that the resulting array is a permutation of numbers from $$$1$$$ to $$$n$$$?In other words, check whether there exists a sequence of steps (possibly empty) such that after applying it, the array $$$a$$$ contains in some order all numbers from $$$1$$$ to $$$n$$$ (inclusive), each exactly once.
256 megabytes
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.*; /* -> Give your 100%, that's it! -> Rules To Solve Any Problem: 1. Read the problem. 2. Think About It. 3. Solve it! */ public class Template { static int mod = 1000000007; public static void main(String[] args){ FastScanner sc = new FastScanner(); PrintWriter out = new PrintWriter(System.out); int yo = sc.nextInt(); ot: while (yo-- > 0) { int n = sc.nextInt(); int[] a = new int[n]; for(int i = 0; i < n; i++){ a[i] = sc.nextInt(); } char[] c = sc.next().toCharArray(); List<Pair> list = new ArrayList<>(); for(int i = 0; i < n; i++){ if(c[i] == 'R'){ // +1 // if(a[i] > n){ // out.println("NO"); // continue ot; // } int x = max(a[i],1); int y = n; list.add(new Pair(x,y)); } else { // -1 // if(a[i] < 1){ // out.println("NO"); // continue; // } int x = 1; int y = min(a[i],n); list.add(new Pair(x,y)); } } // Collections.sort(list, (x,y) -> x.x - y.x == 0 ? (x.y-y.y) : (x.x-y.x)); Collections.sort(list, new Comparator<Pair>() { @Override public int compare(Pair p1, Pair p2) { if(p1.x - p2.x == 0){ return p1.y-p2.y; } return p1.x - p2.x; } }); for(int i = 0; i < n; i++){ int X = list.get(i).x; int Y = list.get(i).y; if((i+1) >= X && (i+1) <= Y){ } else { out.println("NO"); continue ot; } } out.println("YES"); } out.close(); } /* Source: hu_tao Random stuff to try when stuck: - use bruteforcer - always check for n = 1, n = 2, so on -if it's 2C then it's dp -for combo/probability problems, expand the given form we're interested in -make everything the same then build an answer (constructive, make everything 0 then do something) -something appears in parts of 2 --> model as graph -assume a greedy then try to show why it works -find way to simplify into one variable if multiple exist -treat it like fmc (note any passing thoughts/algo that could be used so you can revisit them) -find lower and upper bounds on answer -figure out what ur trying to find and isolate it -see what observations you have and come up with more continuations -work backwards (in constructive, go from the goal to the start) -turn into prefix/suffix sum argument (often works if problem revolves around adjacent array elements) -instead of solving for answer, try solving for complement (ex, find n-(min) instead of max) -draw something -simulate a process -dont implement something unless if ur fairly confident its correct -after 3 bad submissions move on to next problem if applicable -do something instead of nothing and stay organized -write stuff down Random stuff to check when wa: -if code is way too long/cancer then reassess -switched N/M -int overflow -switched variables -wrong MOD -hardcoded edge case incorrectly Random stuff to check when tle: -continue instead of break -condition in for/while loop bad Random stuff to check when rte: -switched N/M -long to int/int overflow -division by 0 -edge case for empty list/data structure/N=1 */ public static class Pair { int x; int y; public Pair(int x, int y) { this.x = x; this.y = y; } } public static void sort(int[] arr) { ArrayList<Integer> ls = new ArrayList<Integer>(); for (int x : arr) ls.add(x); Collections.sort(ls); for (int i = 0; i < arr.length; i++) arr[i] = ls.get(i); } public static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } static boolean[] sieve(int N) { boolean[] sieve = new boolean[N + 1]; for (int i = 2; i <= N; i++) sieve[i] = true; for (int i = 2; i <= N; i++) { if (sieve[i]) { for (int j = 2 * i; j <= N; j += i) { sieve[j] = false; } } } return sieve; } public static long power(long x, long y, long p) { long res = 1L; x = x % p; while (y > 0) { if ((y & 1) == 1) res = (res * x) % p; y >>= 1; x = (x * x) % p; } return res; } public static void print(int[] arr, PrintWriter out) { //for debugging only for (int x : arr) out.print(x + " "); out.println(); } public static int log2(int a){ return (int)(Math.log(a)/Math.log(2)); } static class FastScanner { private int BS = 1 << 16; private char NC = (char) 0; private byte[] buf = new byte[BS]; private int bId = 0, size = 0; private char c = NC; private double cnt = 1; private BufferedInputStream in; public FastScanner() { in = new BufferedInputStream(System.in, BS); } public FastScanner(String s) { try { in = new BufferedInputStream(new FileInputStream(new File(s)), BS); } catch (Exception e) { in = new BufferedInputStream(System.in, BS); } } private char getChar() { while (bId == size) { try { size = in.read(buf); } catch (Exception e) { return NC; } if (size == -1) return NC; bId = 0; } return (char) buf[bId++]; } public int nextInt() { return (int) nextLong(); } public int[] readInts(int N) { int[] res = new int[N]; for (int i = 0; i < N; i++) { res[i] = (int) nextLong(); } return res; } public long[] readLongs(int N) { long[] res = new long[N]; for (int i = 0; i < N; i++) { res[i] = nextLong(); } return res; } public long nextLong() { cnt = 1; boolean neg = false; if (c == NC) c = getChar(); for (; (c < '0' || c > '9'); c = getChar()) { if (c == '-') neg = true; } long res = 0; for (; c >= '0' && c <= '9'; c = getChar()) { res = (res << 3) + (res << 1) + c - '0'; cnt *= 10; } return neg ? -res : res; } public double nextDouble() { double cur = nextLong(); return c != '.' ? cur : cur + nextLong() / cnt; } public double[] readDoubles(int N) { double[] res = new double[N]; for (int i = 0; i < N; i++) { res[i] = nextDouble(); } return res; } public String next() { StringBuilder res = new StringBuilder(); while (c <= 32) c = getChar(); while (c > 32) { res.append(c); c = getChar(); } return res.toString(); } public String nextLine() { StringBuilder res = new StringBuilder(); while (c <= 32) c = getChar(); while (c != '\n') { res.append(c); c = getChar(); } return res.toString(); } public boolean hasNext() { if (c > 32) return true; while (true) { c = getChar(); if (c == NC) return false; else if (c > 32) return true; } } } // For Input.txt and Output.txt // FileInputStream in = new FileInputStream("input.txt"); // FileOutputStream out = new FileOutputStream("output.txt"); // PrintWriter pw = new PrintWriter(out); // Scanner sc = new Scanner(in); }
Java
["8\n4\n1 2 5 2\nBRBR\n2\n1 1\nBB\n5\n3 1 4 2 5\nRBRRB\n5\n3 1 3 1 3\nRBRRB\n5\n5 1 5 1 5\nRBRRB\n4\n2 2 2 2\nBRBR\n2\n1 -2\nBR\n4\n-2 -1 4 0\nRRRR"]
1 second
["YES\nNO\nYES\nYES\nNO\nYES\nYES\nYES"]
NoteIn the first test case of the example, the following sequence of moves can be performed: choose $$$i=3$$$, element $$$a_3=5$$$ is blue, so we decrease it, we get $$$a=[1,2,4,2]$$$; choose $$$i=2$$$, element $$$a_2=2$$$ is red, so we increase it, we get $$$a=[1,3,4,2]$$$; choose $$$i=3$$$, element $$$a_3=4$$$ is blue, so we decrease it, we get $$$a=[1,3,3,2]$$$; choose $$$i=2$$$, element $$$a_2=2$$$ is red, so we increase it, we get $$$a=[1,4,3,2]$$$. We got that $$$a$$$ is a permutation. Hence the answer is YES.
Java 11
standard input
[ "greedy", "math", "sortings" ]
c3df88e22a17492d4eb0f3239a27d404
The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of input data sets in the test. The description of each set of input data consists of three lines. The first line contains an integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$) — the length of the original array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$-10^9 \leq a_i \leq 10^9$$$) — the array elements themselves. The third line has length $$$n$$$ and consists exclusively of the letters 'B' and/or 'R': $$$i$$$th character is 'B' if $$$a_i$$$ is colored blue, and is 'R' if colored red. It is guaranteed that the sum of $$$n$$$ over all input sets does not exceed $$$2 \cdot 10^5$$$.
1,300
Print $$$t$$$ lines, each of which contains the answer to the corresponding test case of the input. Print YES as an answer if the corresponding array can be transformed into a permutation, and NO otherwise. You can print the answer in any case (for example, the strings yEs, yes, Yes, and YES will be recognized as a positive answer).
standard output
PASSED
db47e77c0f8189758115b63cedb56480
train_108.jsonl
1635863700
You are given an array of integers $$$a$$$ of length $$$n$$$. The elements of the array can be either different or the same. Each element of the array is colored either blue or red. There are no unpainted elements in the array. One of the two operations described below can be applied to an array in a single step: either you can select any blue element and decrease its value by $$$1$$$; or you can select any red element and increase its value by $$$1$$$. Situations in which there are no elements of some color at all are also possible. For example, if the whole array is colored blue or red, one of the operations becomes unavailable.Determine whether it is possible to make $$$0$$$ or more steps such that the resulting array is a permutation of numbers from $$$1$$$ to $$$n$$$?In other words, check whether there exists a sequence of steps (possibly empty) such that after applying it, the array $$$a$$$ contains in some order all numbers from $$$1$$$ to $$$n$$$ (inclusive), each exactly once.
256 megabytes
import java.util.*; import java.io.*; import java.math.*; import java.lang.*; public class BlueRedPermutation { // static int mod = 998244353; static int mod = 1000000007; private static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } public static void main(String[] args) throws Exception { FastReader scn = new FastReader(); PrintWriter pw = new PrintWriter(System.out); int t = scn.nextInt(); outer : while(t-->0){ int n = scn.nextInt(); int[] arr = new int[n]; for(int i=0; i<n; i++){ arr[i] = scn.nextInt(); } String s = scn.nextLine(); ArrayList<Integer> blue = new ArrayList<>(); ArrayList<Integer> red = new ArrayList<>(); for(int i=0; i<n; i++){ char ch = s.charAt(i); if(ch == 'B'){ blue.add(arr[i]); }else{ red.add(arr[i]); } } Collections.sort(blue); Collections.sort(red); int idx = 1; for(int i=0; i<blue.size(); i++){ if(blue.get(i) < idx){ pw.println("NO"); continue outer; } idx++; } for(int i=0; i<red.size(); i++){ if(red.get(i) > idx){ pw.println("NO"); continue outer; } idx++; } pw.println("YES"); } pw.close(); } public static class Pair{ int x; int y; Pair(int x, int y){ this.x = x; this.y = y; } } private static void sort(int[] arr) { List<Integer> list = new ArrayList<>(); for (int i=0; i<arr.length; i++){ list.add(arr[i]); } Collections.sort(list); // collections.sort uses nlogn in backend for (int i = 0; i < arr.length; i++){ arr[i] = list.get(i); } } private static void sort(long[] arr) { List<Long> list = new ArrayList<>(); for(int i=0; i<arr.length; i++){ list.add(arr[i]); } Collections.sort(list); // collections.sort uses nlogn in backend for (int i = 0; i < arr.length; i++){ arr[i] = list.get(i); } } // private static void sort(Pair[] arr) { // List<Pair> list = new ArrayList<>(); // for(int i=0; i<arr.length; i++){ // list.add(arr[i]); // } // Collections.sort(list); // collections.sort uses nlogn in backend // for (int i = 0; i < arr.length; i++){ // arr[i] = list.get(i); // } // } private static void reverseSort(int[] arr){ List<Integer> list = new ArrayList<>(); for (int i=0; i<arr.length; i++){ list.add(arr[i]); } Collections.sort(list, Collections.reverseOrder()); // collections.sort uses nlogn in backend for (int i = 0; i < arr.length; i++){ arr[i] = list.get(i); } } private static void reverseSort(long[] arr){ List<Long> list = new ArrayList<>(); for (int i=0; i<arr.length; i++){ list.add(arr[i]); } Collections.sort(list, Collections.reverseOrder()); // collections.sort uses nlogn in backend for (int i = 0; i < arr.length; i++){ arr[i] = list.get(i); } } private static void reverseSort(ArrayList<Integer> list){ Collections.sort(list, Collections.reverseOrder()); } private static int lowerBound(int[] arr, int x){ int n = arr.length, si = 0, ei = n - 1; while(si <= ei){ int mid = si + (ei - si)/2; if(arr[mid] == x){ if(mid-1 >= 0 && arr[mid-1] == arr[mid]){ ei = mid-1; }else{ return mid; } }else if(arr[mid] > x){ ei = mid - 1; }else{ si = mid+1; } } return si; } private static int upperBound(int[] arr, int x){ int n = arr.length, si = 0, ei = n - 1; while(si <= ei){ int mid = si + (ei - si)/2; if(arr[mid] == x){ if(mid+1 < n && arr[mid+1] == arr[mid]){ si = mid+1; }else{ return mid + 1; } }else if(arr[mid] > x){ ei = mid - 1; }else{ si = mid+1; } } return si; } private static int upperBound(ArrayList<Integer> list, int x){ int n = list.size(), si = 0, ei = n - 1; while(si <= ei){ int mid = si + (ei - si)/2; if(list.get(mid) == x){ if(mid+1 < n && list.get(mid+1) == list.get(mid)){ si = mid+1; }else{ return mid + 1; } }else if(list.get(mid) > x){ ei = mid - 1; }else{ si = mid+1; } } return si; } // (x^y)%p in O(logy) private static long power(long x, long y){ long res = 1; x = x % mod; while(y > 0){ if ((y & 1) == 1){ res = (res * x) % mod; } y = y >> 1; x = (x * x) % mod; } return res; } public static boolean nextPermutation(int[] arr) { if(arr == null || arr.length <= 1){ return false; } int last = arr.length-2; while(last >= 0){ if(arr[last] < arr[last+1]){ break; } last--; } if (last < 0){ return false; } if(last >= 0){ int nextGreater = arr.length-1; for(int i=arr.length-1; i>last; i--){ if(arr[i] > arr[last]){ nextGreater = i; break; } } swap(arr, last, nextGreater); } reverse(arr, last+1, arr.length-1); return true; } private static void swap(int[] arr, int i, int j){ int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } private static void reverse(int[] arr, int i, int j){ while(i < j){ swap(arr, i++, j--); } } private static String reverseStr(String s){ StringBuilder sb = new StringBuilder(s); return sb.reverse().toString(); } // TC- O(logmax(a,b)) private static int gcd(int a, int b) { if(a == 0){ return b; } return gcd(b%a, a); } private static long gcd(long a, long b) { if(a == 0L){ return b; } return gcd(b%a, a); } private static long lcm(long a, long b) { return a / gcd(a, b) * b; } // TC- O(logmax(a,b)) private static int lcm(int a, int b) { return a / gcd(a, b) * b; } private static long inv(long x){ return power(x, mod - 2); } private static long summation(long n){ return (n * (n + 1L)) >> 1; } }
Java
["8\n4\n1 2 5 2\nBRBR\n2\n1 1\nBB\n5\n3 1 4 2 5\nRBRRB\n5\n3 1 3 1 3\nRBRRB\n5\n5 1 5 1 5\nRBRRB\n4\n2 2 2 2\nBRBR\n2\n1 -2\nBR\n4\n-2 -1 4 0\nRRRR"]
1 second
["YES\nNO\nYES\nYES\nNO\nYES\nYES\nYES"]
NoteIn the first test case of the example, the following sequence of moves can be performed: choose $$$i=3$$$, element $$$a_3=5$$$ is blue, so we decrease it, we get $$$a=[1,2,4,2]$$$; choose $$$i=2$$$, element $$$a_2=2$$$ is red, so we increase it, we get $$$a=[1,3,4,2]$$$; choose $$$i=3$$$, element $$$a_3=4$$$ is blue, so we decrease it, we get $$$a=[1,3,3,2]$$$; choose $$$i=2$$$, element $$$a_2=2$$$ is red, so we increase it, we get $$$a=[1,4,3,2]$$$. We got that $$$a$$$ is a permutation. Hence the answer is YES.
Java 11
standard input
[ "greedy", "math", "sortings" ]
c3df88e22a17492d4eb0f3239a27d404
The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of input data sets in the test. The description of each set of input data consists of three lines. The first line contains an integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$) — the length of the original array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$-10^9 \leq a_i \leq 10^9$$$) — the array elements themselves. The third line has length $$$n$$$ and consists exclusively of the letters 'B' and/or 'R': $$$i$$$th character is 'B' if $$$a_i$$$ is colored blue, and is 'R' if colored red. It is guaranteed that the sum of $$$n$$$ over all input sets does not exceed $$$2 \cdot 10^5$$$.
1,300
Print $$$t$$$ lines, each of which contains the answer to the corresponding test case of the input. Print YES as an answer if the corresponding array can be transformed into a permutation, and NO otherwise. You can print the answer in any case (for example, the strings yEs, yes, Yes, and YES will be recognized as a positive answer).
standard output
PASSED
430a7acb8cc230ce7e64554439e7361e
train_108.jsonl
1635863700
You are given an array of integers $$$a$$$ of length $$$n$$$. The elements of the array can be either different or the same. Each element of the array is colored either blue or red. There are no unpainted elements in the array. One of the two operations described below can be applied to an array in a single step: either you can select any blue element and decrease its value by $$$1$$$; or you can select any red element and increase its value by $$$1$$$. Situations in which there are no elements of some color at all are also possible. For example, if the whole array is colored blue or red, one of the operations becomes unavailable.Determine whether it is possible to make $$$0$$$ or more steps such that the resulting array is a permutation of numbers from $$$1$$$ to $$$n$$$?In other words, check whether there exists a sequence of steps (possibly empty) such that after applying it, the array $$$a$$$ contains in some order all numbers from $$$1$$$ to $$$n$$$ (inclusive), each exactly once.
256 megabytes
//import java.io.IOException; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.InputMismatchException; import java.util.TreeSet; import java.util.*; public class BlueRedPermutation { static InputReader inputReader=new InputReader(System.in); static void solve() { int n = inputReader.nextInt(); int arr[] = new int[n]; for (int i = 0; i < n; i++) { arr[i] = inputReader.nextInt(); } String str = inputReader.readString(); int len=str.length(); List<Integer> blue = new ArrayList<>(); List<Integer> red = new ArrayList<>(); for (int i=0;i<len;i++) { if (str.charAt(i)=='B') { blue.add(arr[i]); } else { red.add(arr[i]); } } Collections.sort(blue); Collections.sort(red); int bind=0; int rind=0; int bsize=blue.size(); int rsize=red.size(); int count=1; while (bind<bsize&&rind<rsize) { if (blue.get(bind)>=count) { bind++; } else if (red.get(rind)<=count) { rind++; } else { out.println("NO"); return; } count++; } while (bind<bsize) { if (blue.get(bind)>=count) { bind++; } else { out.println("NO"); return; } count++; } while (rind<rsize) { if (red.get(rind)<=count) { rind++; } else { out.println("NO"); return; } count++; } out.println("YES"); } static PrintWriter out=new PrintWriter((System.out)); public static void main(String args[])throws IOException { int t=inputReader.nextInt(); while(t-->0) { solve(); } out.close(); } static class InputReader { private InputStream stream; private byte[] buf = new byte[8192]; private int curChar, snumChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int snext() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = snext(); while (isSpaceChar(c)) c = snext(); int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = snext(); while (isSpaceChar(c)) c = snext(); int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public String readString() { int c = snext(); while (isSpaceChar(c)) c = snext(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["8\n4\n1 2 5 2\nBRBR\n2\n1 1\nBB\n5\n3 1 4 2 5\nRBRRB\n5\n3 1 3 1 3\nRBRRB\n5\n5 1 5 1 5\nRBRRB\n4\n2 2 2 2\nBRBR\n2\n1 -2\nBR\n4\n-2 -1 4 0\nRRRR"]
1 second
["YES\nNO\nYES\nYES\nNO\nYES\nYES\nYES"]
NoteIn the first test case of the example, the following sequence of moves can be performed: choose $$$i=3$$$, element $$$a_3=5$$$ is blue, so we decrease it, we get $$$a=[1,2,4,2]$$$; choose $$$i=2$$$, element $$$a_2=2$$$ is red, so we increase it, we get $$$a=[1,3,4,2]$$$; choose $$$i=3$$$, element $$$a_3=4$$$ is blue, so we decrease it, we get $$$a=[1,3,3,2]$$$; choose $$$i=2$$$, element $$$a_2=2$$$ is red, so we increase it, we get $$$a=[1,4,3,2]$$$. We got that $$$a$$$ is a permutation. Hence the answer is YES.
Java 11
standard input
[ "greedy", "math", "sortings" ]
c3df88e22a17492d4eb0f3239a27d404
The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of input data sets in the test. The description of each set of input data consists of three lines. The first line contains an integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$) — the length of the original array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$-10^9 \leq a_i \leq 10^9$$$) — the array elements themselves. The third line has length $$$n$$$ and consists exclusively of the letters 'B' and/or 'R': $$$i$$$th character is 'B' if $$$a_i$$$ is colored blue, and is 'R' if colored red. It is guaranteed that the sum of $$$n$$$ over all input sets does not exceed $$$2 \cdot 10^5$$$.
1,300
Print $$$t$$$ lines, each of which contains the answer to the corresponding test case of the input. Print YES as an answer if the corresponding array can be transformed into a permutation, and NO otherwise. You can print the answer in any case (for example, the strings yEs, yes, Yes, and YES will be recognized as a positive answer).
standard output
PASSED
2ede0b01bbf3b8cfd9ad7b023a913d0d
train_108.jsonl
1635863700
You are given an array of integers $$$a$$$ of length $$$n$$$. The elements of the array can be either different or the same. Each element of the array is colored either blue or red. There are no unpainted elements in the array. One of the two operations described below can be applied to an array in a single step: either you can select any blue element and decrease its value by $$$1$$$; or you can select any red element and increase its value by $$$1$$$. Situations in which there are no elements of some color at all are also possible. For example, if the whole array is colored blue or red, one of the operations becomes unavailable.Determine whether it is possible to make $$$0$$$ or more steps such that the resulting array is a permutation of numbers from $$$1$$$ to $$$n$$$?In other words, check whether there exists a sequence of steps (possibly empty) such that after applying it, the array $$$a$$$ contains in some order all numbers from $$$1$$$ to $$$n$$$ (inclusive), each exactly once.
256 megabytes
import java.io.*; import java.util.*; public class CodeForces{ /*-------------------------------------------EDITING CODE STARTS HERE-------------------------------------------*/ public static void main(String[] args) throws IOException{ openIO(); int testCase = 1; testCase = sc.nextInt(); preCompute(); for (int i = 1; i <= testCase; i++) solve(i); closeIO(); } public static void solve(int tCase)throws IOException { int n = sc.nextInt(); int[] arr = new int[n]; List<Integer> red = new ArrayList<>(); List<Integer> blue = new ArrayList<>(); for(int i=0;i<n;i++) { arr[i] = sc.nextInt(); } char[] color = sc.next().toCharArray(); for(int i=0;i<n;i++){ if(color[i]=='R')red.add(arr[i]); else blue.add(arr[i]); } Collections.sort(red); Collections.sort(blue); int r = 0; int b = 0; for(int i=1;i<=n;i++){ if(b<blue.size() && blue.get(b) >=i)b++; else if(r<red.size() && red.get(r) <=i)r++; else { out.println("NO"); return; } } out.println("YES"); } private static void preCompute(){ } /*-------------------------------------------EDITING CODE ENDS HERE-------------------------------------------*/ static FastestReader sc; static PrintWriter out; private static void openIO() throws IOException{ sc = new FastestReader(); out = new PrintWriter(System.out); } /*------------------------------------------HELPER FUNCTION STARTS HERE------------------------------------------*/ public static final int mod = (int) 1e9 +7; private static final int mod2 = 998244353; public static final int inf_int = (int) 2e9; public static final long inf_long = (long) 4e18; // euclidean algorithm time O(max (loga ,logb)) public static long _gcd(long a, long b) { if (a == 0) return b; return _gcd(b % a, a); } public static long _lcm(long a, long b) { // lcm(a,b) * gcd(a,b) = a * b return (a / _gcd(a, b)) * b; } // binary exponentiation time O(logn) public static long _power(long x, long n) { long ans = 1; while (n > 0) { if ((n & 1) == 1) { ans *= x; ans %= mod; n--; } else { x *= x; x %= mod; n >>= 1; } } return ans; } //sieve/first divisor time : O(mx * log ( log (mx) ) ) public static int[] _seive(int mx){ int[] firstDivisor = new int[mx+1]; for(int i=0;i<=mx;i++)firstDivisor[i] = i; for(int i=2;i*i<=mx;i++) if(firstDivisor[i] == i) for(int j = i*i;j<=mx;j+=i) firstDivisor[j] = i; return firstDivisor; } private static boolean _isPrime(long x){ for(long i=2;i*i<=x;i++) if(x%i==0)return false; return true; } /*------------------------------------------HELPER FUNCTION ENDS HERE-------------------------------------------*/ /*-------------------------------------------FAST INPUT STARTS HERE---------------------------------------------*/ public static void closeIO() throws IOException{ out.flush(); out.close(); sc.close(); } private static final class FastestReader { private static final int BUFFER_SIZE = 1 << 16; private final DataInputStream din; private final byte[] buffer; private int bufferPointer, bytesRead; public FastestReader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public FastestReader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } private static boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() throws IOException { int b; //noinspection StatementWithEmptyBody while ((b = read()) != -1 && isSpaceChar(b)) {} return b; } public String next() throws IOException { int b = skip(); final StringBuilder sb = new StringBuilder(); while (!isSpaceChar(b)) { // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = read(); } return sb.toString(); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') { c = read(); } final 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(); } final 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(); } final 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 { din.close(); } } /*---------------------------------------------FAST INPUT ENDS HERE ---------------------------------------------*/ }
Java
["8\n4\n1 2 5 2\nBRBR\n2\n1 1\nBB\n5\n3 1 4 2 5\nRBRRB\n5\n3 1 3 1 3\nRBRRB\n5\n5 1 5 1 5\nRBRRB\n4\n2 2 2 2\nBRBR\n2\n1 -2\nBR\n4\n-2 -1 4 0\nRRRR"]
1 second
["YES\nNO\nYES\nYES\nNO\nYES\nYES\nYES"]
NoteIn the first test case of the example, the following sequence of moves can be performed: choose $$$i=3$$$, element $$$a_3=5$$$ is blue, so we decrease it, we get $$$a=[1,2,4,2]$$$; choose $$$i=2$$$, element $$$a_2=2$$$ is red, so we increase it, we get $$$a=[1,3,4,2]$$$; choose $$$i=3$$$, element $$$a_3=4$$$ is blue, so we decrease it, we get $$$a=[1,3,3,2]$$$; choose $$$i=2$$$, element $$$a_2=2$$$ is red, so we increase it, we get $$$a=[1,4,3,2]$$$. We got that $$$a$$$ is a permutation. Hence the answer is YES.
Java 11
standard input
[ "greedy", "math", "sortings" ]
c3df88e22a17492d4eb0f3239a27d404
The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of input data sets in the test. The description of each set of input data consists of three lines. The first line contains an integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$) — the length of the original array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$-10^9 \leq a_i \leq 10^9$$$) — the array elements themselves. The third line has length $$$n$$$ and consists exclusively of the letters 'B' and/or 'R': $$$i$$$th character is 'B' if $$$a_i$$$ is colored blue, and is 'R' if colored red. It is guaranteed that the sum of $$$n$$$ over all input sets does not exceed $$$2 \cdot 10^5$$$.
1,300
Print $$$t$$$ lines, each of which contains the answer to the corresponding test case of the input. Print YES as an answer if the corresponding array can be transformed into a permutation, and NO otherwise. You can print the answer in any case (for example, the strings yEs, yes, Yes, and YES will be recognized as a positive answer).
standard output
PASSED
7c18ae0e05f2afd0a732199f18d5ac54
train_108.jsonl
1635863700
You are given an array of integers $$$a$$$ of length $$$n$$$. The elements of the array can be either different or the same. Each element of the array is colored either blue or red. There are no unpainted elements in the array. One of the two operations described below can be applied to an array in a single step: either you can select any blue element and decrease its value by $$$1$$$; or you can select any red element and increase its value by $$$1$$$. Situations in which there are no elements of some color at all are also possible. For example, if the whole array is colored blue or red, one of the operations becomes unavailable.Determine whether it is possible to make $$$0$$$ or more steps such that the resulting array is a permutation of numbers from $$$1$$$ to $$$n$$$?In other words, check whether there exists a sequence of steps (possibly empty) such that after applying it, the array $$$a$$$ contains in some order all numbers from $$$1$$$ to $$$n$$$ (inclusive), each exactly once.
256 megabytes
import java.io.*; import java.util.*; public class CodeForces{ /*-------------------------------------------EDITING CODE STARTS HERE-------------------------------------------*/ public static void main(String[] args) throws IOException{ openIO(); int testCase = 1; testCase = sc.nextInt(); preCompute(); for (int i = 1; i <= testCase; i++) solve(i); closeIO(); } public static void solve(int tCase)throws IOException { int n = sc.nextInt(); int[] arr = new int[n]; List<Integer> red = new ArrayList<>(); List<Integer> blue = new ArrayList<>(); for(int i=0;i<n;i++) { arr[i] = sc.nextInt(); } char[] color = sc.next().toCharArray(); for(int i=0;i<n;i++){ if(color[i]=='R')red.add(arr[i]); else blue.add(arr[i]); } for(int i=0;i<1;i++) for(int j=0;j<1;j++){ if(isPossible(red,blue,i,j,n)){ out.println("YES"); // out.println(i+" "+j); return; } } out.println("NO"); } private static boolean isPossible(List<Integer> red,List<Integer> blue,int a,int bb,int n){ // if(a==0)Collections.sort(red); // else red.sort(Collections.reverseOrder()); // if(bb==0)Collections.sort(blue); // else blue.sort(Collections.reverseOrder()); Collections.sort(red); Collections.sort(blue); int r = 0; int b = 0; boolean isPossible = true; for(int i=1;i<=n;i++){ if(b<blue.size() && blue.get(b) >=i)b++; else if(r<red.size() && red.get(r) <=i)r++; else { isPossible = false; break; } } return isPossible; } private static void preCompute(){ } /*-------------------------------------------EDITING CODE ENDS HERE-------------------------------------------*/ static FastestReader sc; static PrintWriter out; private static void openIO() throws IOException{ sc = new FastestReader(); out = new PrintWriter(System.out); } /*------------------------------------------HELPER FUNCTION STARTS HERE------------------------------------------*/ public static final int mod = (int) 1e9 +7; private static final int mod2 = 998244353; public static final int inf_int = (int) 2e9; public static final long inf_long = (long) 4e18; // euclidean algorithm time O(max (loga ,logb)) public static long _gcd(long a, long b) { if (a == 0) return b; return _gcd(b % a, a); } public static long _lcm(long a, long b) { // lcm(a,b) * gcd(a,b) = a * b return (a / _gcd(a, b)) * b; } // binary exponentiation time O(logn) public static long _power(long x, long n) { long ans = 1; while (n > 0) { if ((n & 1) == 1) { ans *= x; ans %= mod; n--; } else { x *= x; x %= mod; n >>= 1; } } return ans; } //sieve/first divisor time : O(mx * log ( log (mx) ) ) public static int[] _seive(int mx){ int[] firstDivisor = new int[mx+1]; for(int i=0;i<=mx;i++)firstDivisor[i] = i; for(int i=2;i*i<=mx;i++) if(firstDivisor[i] == i) for(int j = i*i;j<=mx;j+=i) firstDivisor[j] = i; return firstDivisor; } private static boolean _isPrime(long x){ for(long i=2;i*i<=x;i++) if(x%i==0)return false; return true; } /*------------------------------------------HELPER FUNCTION ENDS HERE-------------------------------------------*/ /*-------------------------------------------FAST INPUT STARTS HERE---------------------------------------------*/ public static void closeIO() throws IOException{ out.flush(); out.close(); sc.close(); } private static final class FastestReader { private static final int BUFFER_SIZE = 1 << 16; private final DataInputStream din; private final byte[] buffer; private int bufferPointer, bytesRead; public FastestReader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public FastestReader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } private static boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() throws IOException { int b; //noinspection StatementWithEmptyBody while ((b = read()) != -1 && isSpaceChar(b)) {} return b; } public String next() throws IOException { int b = skip(); final StringBuilder sb = new StringBuilder(); while (!isSpaceChar(b)) { // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = read(); } return sb.toString(); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') { c = read(); } final 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(); } final 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(); } final 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 { din.close(); } } /*---------------------------------------------FAST INPUT ENDS HERE ---------------------------------------------*/ }
Java
["8\n4\n1 2 5 2\nBRBR\n2\n1 1\nBB\n5\n3 1 4 2 5\nRBRRB\n5\n3 1 3 1 3\nRBRRB\n5\n5 1 5 1 5\nRBRRB\n4\n2 2 2 2\nBRBR\n2\n1 -2\nBR\n4\n-2 -1 4 0\nRRRR"]
1 second
["YES\nNO\nYES\nYES\nNO\nYES\nYES\nYES"]
NoteIn the first test case of the example, the following sequence of moves can be performed: choose $$$i=3$$$, element $$$a_3=5$$$ is blue, so we decrease it, we get $$$a=[1,2,4,2]$$$; choose $$$i=2$$$, element $$$a_2=2$$$ is red, so we increase it, we get $$$a=[1,3,4,2]$$$; choose $$$i=3$$$, element $$$a_3=4$$$ is blue, so we decrease it, we get $$$a=[1,3,3,2]$$$; choose $$$i=2$$$, element $$$a_2=2$$$ is red, so we increase it, we get $$$a=[1,4,3,2]$$$. We got that $$$a$$$ is a permutation. Hence the answer is YES.
Java 11
standard input
[ "greedy", "math", "sortings" ]
c3df88e22a17492d4eb0f3239a27d404
The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of input data sets in the test. The description of each set of input data consists of three lines. The first line contains an integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$) — the length of the original array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$-10^9 \leq a_i \leq 10^9$$$) — the array elements themselves. The third line has length $$$n$$$ and consists exclusively of the letters 'B' and/or 'R': $$$i$$$th character is 'B' if $$$a_i$$$ is colored blue, and is 'R' if colored red. It is guaranteed that the sum of $$$n$$$ over all input sets does not exceed $$$2 \cdot 10^5$$$.
1,300
Print $$$t$$$ lines, each of which contains the answer to the corresponding test case of the input. Print YES as an answer if the corresponding array can be transformed into a permutation, and NO otherwise. You can print the answer in any case (for example, the strings yEs, yes, Yes, and YES will be recognized as a positive answer).
standard output
PASSED
5040912ec8b4a38362043bc85388531b
train_108.jsonl
1635863700
You are given an array of integers $$$a$$$ of length $$$n$$$. The elements of the array can be either different or the same. Each element of the array is colored either blue or red. There are no unpainted elements in the array. One of the two operations described below can be applied to an array in a single step: either you can select any blue element and decrease its value by $$$1$$$; or you can select any red element and increase its value by $$$1$$$. Situations in which there are no elements of some color at all are also possible. For example, if the whole array is colored blue or red, one of the operations becomes unavailable.Determine whether it is possible to make $$$0$$$ or more steps such that the resulting array is a permutation of numbers from $$$1$$$ to $$$n$$$?In other words, check whether there exists a sequence of steps (possibly empty) such that after applying it, the array $$$a$$$ contains in some order all numbers from $$$1$$$ to $$$n$$$ (inclusive), each exactly once.
256 megabytes
import java.io.*; import java.util.*; public class CodeForces{ /*-------------------------------------------EDITING CODE STARTS HERE-------------------------------------------*/ public static void main(String[] args) throws IOException{ openIO(); int testCase = 1; testCase = sc.nextInt(); preCompute(); for (int i = 1; i <= testCase; i++) solve(i); closeIO(); } public static void solve(int tCase)throws IOException { int n = sc.nextInt(); int[] arr = new int[n]; List<Integer> red = new ArrayList<>(); List<Integer> blue = new ArrayList<>(); for(int i=0;i<n;i++) { arr[i] = sc.nextInt(); } char[] color = sc.next().toCharArray(); for(int i=0;i<n;i++){ if(color[i]=='R')red.add(arr[i]); else blue.add(arr[i]); } for(int i=0;i<2;i++) for(int j=0;j<2;j++){ if(isPossible(red,blue,i,j,n)){ out.println("YES"); return; } } out.println("NO"); } private static boolean isPossible(List<Integer> red,List<Integer> blue,int a,int bb,int n){ if(a==0)Collections.sort(red); else red.sort(Collections.reverseOrder()); if(bb==0)Collections.sort(blue); else blue.sort(Collections.reverseOrder()); int r = 0; int b = 0; boolean isPossible = true; // for(int i=1;i<=n;i++){ // if(r<red.size() && red.get(r) <=i)r++; // else if(b<blue.size() && blue.get(b) >=i)b++; // else { // isPossible = false; // break; // } // } // if(isPossible)return true; isPossible = true; r = 0; b = 0; for(int i=1;i<=n;i++){ if(b<blue.size() && blue.get(b) >=i)b++; else if(r<red.size() && red.get(r) <=i)r++; else { isPossible = false; break; } } return isPossible; } private static void preCompute(){ } /*-------------------------------------------EDITING CODE ENDS HERE-------------------------------------------*/ static FastestReader sc; static PrintWriter out; private static void openIO() throws IOException{ sc = new FastestReader(); out = new PrintWriter(System.out); } /*------------------------------------------HELPER FUNCTION STARTS HERE------------------------------------------*/ public static final int mod = (int) 1e9 +7; private static final int mod2 = 998244353; public static final int inf_int = (int) 2e9; public static final long inf_long = (long) 4e18; // euclidean algorithm time O(max (loga ,logb)) public static long _gcd(long a, long b) { if (a == 0) return b; return _gcd(b % a, a); } public static long _lcm(long a, long b) { // lcm(a,b) * gcd(a,b) = a * b return (a / _gcd(a, b)) * b; } // binary exponentiation time O(logn) public static long _power(long x, long n) { long ans = 1; while (n > 0) { if ((n & 1) == 1) { ans *= x; ans %= mod; n--; } else { x *= x; x %= mod; n >>= 1; } } return ans; } //sieve/first divisor time : O(mx * log ( log (mx) ) ) public static int[] _seive(int mx){ int[] firstDivisor = new int[mx+1]; for(int i=0;i<=mx;i++)firstDivisor[i] = i; for(int i=2;i*i<=mx;i++) if(firstDivisor[i] == i) for(int j = i*i;j<=mx;j+=i) firstDivisor[j] = i; return firstDivisor; } private static boolean _isPrime(long x){ for(long i=2;i*i<=x;i++) if(x%i==0)return false; return true; } /*------------------------------------------HELPER FUNCTION ENDS HERE-------------------------------------------*/ /*-------------------------------------------FAST INPUT STARTS HERE---------------------------------------------*/ public static void closeIO() throws IOException{ out.flush(); out.close(); sc.close(); } private static final class FastestReader { private static final int BUFFER_SIZE = 1 << 16; private final DataInputStream din; private final byte[] buffer; private int bufferPointer, bytesRead; public FastestReader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public FastestReader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } private static boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() throws IOException { int b; //noinspection StatementWithEmptyBody while ((b = read()) != -1 && isSpaceChar(b)) {} return b; } public String next() throws IOException { int b = skip(); final StringBuilder sb = new StringBuilder(); while (!isSpaceChar(b)) { // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = read(); } return sb.toString(); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') { c = read(); } final 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(); } final 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(); } final 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 { din.close(); } } /*---------------------------------------------FAST INPUT ENDS HERE ---------------------------------------------*/ }
Java
["8\n4\n1 2 5 2\nBRBR\n2\n1 1\nBB\n5\n3 1 4 2 5\nRBRRB\n5\n3 1 3 1 3\nRBRRB\n5\n5 1 5 1 5\nRBRRB\n4\n2 2 2 2\nBRBR\n2\n1 -2\nBR\n4\n-2 -1 4 0\nRRRR"]
1 second
["YES\nNO\nYES\nYES\nNO\nYES\nYES\nYES"]
NoteIn the first test case of the example, the following sequence of moves can be performed: choose $$$i=3$$$, element $$$a_3=5$$$ is blue, so we decrease it, we get $$$a=[1,2,4,2]$$$; choose $$$i=2$$$, element $$$a_2=2$$$ is red, so we increase it, we get $$$a=[1,3,4,2]$$$; choose $$$i=3$$$, element $$$a_3=4$$$ is blue, so we decrease it, we get $$$a=[1,3,3,2]$$$; choose $$$i=2$$$, element $$$a_2=2$$$ is red, so we increase it, we get $$$a=[1,4,3,2]$$$. We got that $$$a$$$ is a permutation. Hence the answer is YES.
Java 11
standard input
[ "greedy", "math", "sortings" ]
c3df88e22a17492d4eb0f3239a27d404
The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of input data sets in the test. The description of each set of input data consists of three lines. The first line contains an integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$) — the length of the original array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$-10^9 \leq a_i \leq 10^9$$$) — the array elements themselves. The third line has length $$$n$$$ and consists exclusively of the letters 'B' and/or 'R': $$$i$$$th character is 'B' if $$$a_i$$$ is colored blue, and is 'R' if colored red. It is guaranteed that the sum of $$$n$$$ over all input sets does not exceed $$$2 \cdot 10^5$$$.
1,300
Print $$$t$$$ lines, each of which contains the answer to the corresponding test case of the input. Print YES as an answer if the corresponding array can be transformed into a permutation, and NO otherwise. You can print the answer in any case (for example, the strings yEs, yes, Yes, and YES will be recognized as a positive answer).
standard output
PASSED
c1f4aebb1d0821fa4936b841397e394d
train_108.jsonl
1635863700
You are given an array of integers $$$a$$$ of length $$$n$$$. The elements of the array can be either different or the same. Each element of the array is colored either blue or red. There are no unpainted elements in the array. One of the two operations described below can be applied to an array in a single step: either you can select any blue element and decrease its value by $$$1$$$; or you can select any red element and increase its value by $$$1$$$. Situations in which there are no elements of some color at all are also possible. For example, if the whole array is colored blue or red, one of the operations becomes unavailable.Determine whether it is possible to make $$$0$$$ or more steps such that the resulting array is a permutation of numbers from $$$1$$$ to $$$n$$$?In other words, check whether there exists a sequence of steps (possibly empty) such that after applying it, the array $$$a$$$ contains in some order all numbers from $$$1$$$ to $$$n$$$ (inclusive), each exactly once.
256 megabytes
import java.io.*; import java.util.*; public class CodeForces{ /*-------------------------------------------EDITING CODE STARTS HERE-------------------------------------------*/ public static void main(String[] args) throws IOException{ openIO(); int testCase = 1; testCase = sc.nextInt(); preCompute(); for (int i = 1; i <= testCase; i++) solve(i); closeIO(); } public static void solve(int tCase)throws IOException { int n = sc.nextInt(); int[] arr = new int[n]; List<Integer> red = new ArrayList<>(); List<Integer> blue = new ArrayList<>(); for(int i=0;i<n;i++) { arr[i] = sc.nextInt(); } char[] color = sc.next().toCharArray(); for(int i=0;i<n;i++){ if(color[i]=='R')red.add(arr[i]); else blue.add(arr[i]); } for(int i=0;i<2;i++) for(int j=0;j<2;j++){ if(isPossible(red,blue,i,j,n)){ out.println("YES"); return; } } out.println("NO"); } private static boolean isPossible(List<Integer> red,List<Integer> blue,int a,int bb,int n){ if(a==0)Collections.sort(red); else red.sort(Collections.reverseOrder()); if(bb==0)Collections.sort(blue); else blue.sort(Collections.reverseOrder()); int r = 0; int b = 0; boolean isPossible = true; for(int i=1;i<=n;i++){ if(r<red.size() && red.get(r) <=i)r++; else if(b<blue.size() && blue.get(b) >=i)b++; else { isPossible = false; break; } } if(isPossible)return true; isPossible = true; r = 0; b = 0; for(int i=1;i<=n;i++){ if(b<blue.size() && blue.get(b) >=i)b++; else if(r<red.size() && red.get(r) <=i)r++; else { isPossible = false; break; } } return isPossible; } private static void preCompute(){ } /*-------------------------------------------EDITING CODE ENDS HERE-------------------------------------------*/ static FastestReader sc; static PrintWriter out; private static void openIO() throws IOException{ sc = new FastestReader(); out = new PrintWriter(System.out); } /*------------------------------------------HELPER FUNCTION STARTS HERE------------------------------------------*/ public static final int mod = (int) 1e9 +7; private static final int mod2 = 998244353; public static final int inf_int = (int) 2e9; public static final long inf_long = (long) 4e18; // euclidean algorithm time O(max (loga ,logb)) public static long _gcd(long a, long b) { if (a == 0) return b; return _gcd(b % a, a); } public static long _lcm(long a, long b) { // lcm(a,b) * gcd(a,b) = a * b return (a / _gcd(a, b)) * b; } // binary exponentiation time O(logn) public static long _power(long x, long n) { long ans = 1; while (n > 0) { if ((n & 1) == 1) { ans *= x; ans %= mod; n--; } else { x *= x; x %= mod; n >>= 1; } } return ans; } //sieve/first divisor time : O(mx * log ( log (mx) ) ) public static int[] _seive(int mx){ int[] firstDivisor = new int[mx+1]; for(int i=0;i<=mx;i++)firstDivisor[i] = i; for(int i=2;i*i<=mx;i++) if(firstDivisor[i] == i) for(int j = i*i;j<=mx;j+=i) firstDivisor[j] = i; return firstDivisor; } private static boolean _isPrime(long x){ for(long i=2;i*i<=x;i++) if(x%i==0)return false; return true; } /*------------------------------------------HELPER FUNCTION ENDS HERE-------------------------------------------*/ /*-------------------------------------------FAST INPUT STARTS HERE---------------------------------------------*/ public static void closeIO() throws IOException{ out.flush(); out.close(); sc.close(); } private static final class FastestReader { private static final int BUFFER_SIZE = 1 << 16; private final DataInputStream din; private final byte[] buffer; private int bufferPointer, bytesRead; public FastestReader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public FastestReader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } private static boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() throws IOException { int b; //noinspection StatementWithEmptyBody while ((b = read()) != -1 && isSpaceChar(b)) {} return b; } public String next() throws IOException { int b = skip(); final StringBuilder sb = new StringBuilder(); while (!isSpaceChar(b)) { // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = read(); } return sb.toString(); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') { c = read(); } final 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(); } final 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(); } final 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 { din.close(); } } /*---------------------------------------------FAST INPUT ENDS HERE ---------------------------------------------*/ }
Java
["8\n4\n1 2 5 2\nBRBR\n2\n1 1\nBB\n5\n3 1 4 2 5\nRBRRB\n5\n3 1 3 1 3\nRBRRB\n5\n5 1 5 1 5\nRBRRB\n4\n2 2 2 2\nBRBR\n2\n1 -2\nBR\n4\n-2 -1 4 0\nRRRR"]
1 second
["YES\nNO\nYES\nYES\nNO\nYES\nYES\nYES"]
NoteIn the first test case of the example, the following sequence of moves can be performed: choose $$$i=3$$$, element $$$a_3=5$$$ is blue, so we decrease it, we get $$$a=[1,2,4,2]$$$; choose $$$i=2$$$, element $$$a_2=2$$$ is red, so we increase it, we get $$$a=[1,3,4,2]$$$; choose $$$i=3$$$, element $$$a_3=4$$$ is blue, so we decrease it, we get $$$a=[1,3,3,2]$$$; choose $$$i=2$$$, element $$$a_2=2$$$ is red, so we increase it, we get $$$a=[1,4,3,2]$$$. We got that $$$a$$$ is a permutation. Hence the answer is YES.
Java 11
standard input
[ "greedy", "math", "sortings" ]
c3df88e22a17492d4eb0f3239a27d404
The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of input data sets in the test. The description of each set of input data consists of three lines. The first line contains an integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$) — the length of the original array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$-10^9 \leq a_i \leq 10^9$$$) — the array elements themselves. The third line has length $$$n$$$ and consists exclusively of the letters 'B' and/or 'R': $$$i$$$th character is 'B' if $$$a_i$$$ is colored blue, and is 'R' if colored red. It is guaranteed that the sum of $$$n$$$ over all input sets does not exceed $$$2 \cdot 10^5$$$.
1,300
Print $$$t$$$ lines, each of which contains the answer to the corresponding test case of the input. Print YES as an answer if the corresponding array can be transformed into a permutation, and NO otherwise. You can print the answer in any case (for example, the strings yEs, yes, Yes, and YES will be recognized as a positive answer).
standard output
PASSED
b65a254d637669b800d3555b0bd4ad56
train_108.jsonl
1635863700
You are given an array of integers $$$a$$$ of length $$$n$$$. The elements of the array can be either different or the same. Each element of the array is colored either blue or red. There are no unpainted elements in the array. One of the two operations described below can be applied to an array in a single step: either you can select any blue element and decrease its value by $$$1$$$; or you can select any red element and increase its value by $$$1$$$. Situations in which there are no elements of some color at all are also possible. For example, if the whole array is colored blue or red, one of the operations becomes unavailable.Determine whether it is possible to make $$$0$$$ or more steps such that the resulting array is a permutation of numbers from $$$1$$$ to $$$n$$$?In other words, check whether there exists a sequence of steps (possibly empty) such that after applying it, the array $$$a$$$ contains in some order all numbers from $$$1$$$ to $$$n$$$ (inclusive), each exactly once.
256 megabytes
import java.util.*; import java.io.*; public class Main{ static final Random random=new Random(); static long mod=1000000007L; static HashMap<String,Integer>map=new HashMap<>(); static int[] arr,brr=new int[200005]; static class FastReader{ BufferedReader br; StringTokenizer st; public FastReader(){ br=new BufferedReader(new InputStreamReader(System.in)); } String next(){ while(st==null || !st.hasMoreTokens()){ try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt(){ return Integer.parseInt(next()); } long nextLong(){ return Long.parseLong(next()); } double nextDouble(){ return Double.parseDouble(next()); } String nextLine(){ String str=""; try { str=br.readLine().trim(); } catch (Exception e) { e.printStackTrace(); } return str; } int[] readIntArray(int n){ int[] res=new int[n]; for(int i=0;i<n;i++)res[i]=nextInt(); return res; } } static class FastWriter { private final BufferedWriter bw; public FastWriter() { this.bw = new BufferedWriter(new OutputStreamWriter(System.out)); } public void print(Object object) throws IOException { bw.append("" + object); } public void println(Object object) throws IOException { print(object); bw.append("\n"); } public void close() throws IOException { bw.close(); } } public static void main(String[] args) { try { FastReader in=new FastReader(); FastWriter out = new FastWriter(); int testCases=in.nextInt(); //int testCases=1; while(testCases-- > 0){ solve(in); } out.close(); } catch (Exception e) { return; } } public static void solve( FastReader in){ int n=in.nextInt(); //String s=in.next(); //String t=in.next(); //long y=in.nextInt(); //long n=in.nextLong(); //int k=in.nextInt(); //long k=in.nextLong(); StringBuilder res=new StringBuilder(); int[] arr=in.readIntArray(n); String s=in.next(); List<Integer> l=new ArrayList<>(); List<Integer> r=new ArrayList<>(); for(int i=0;i<n;i++){ if(s.charAt(i)=='B'){ l.add(arr[i]); } else{ r.add(arr[i]); } } Collections.sort(l); Collections.sort(r); //Collections.reverse(r); boolean t=true; for(int i=0;i<l.size();i++){ if(l.get(i)<i+1){ t=false; } } int w=l.size(); for(int i=0;i<r.size();i++){ if(r.get(i)>w+1+i){ t=false; } //w++; } if(t){ res.append("yes"); } else res.append("no"); System.out.println(res.toString()); } static boolean ch(int[] arr,int x){ int l=0; int r=arr.length-1; while(l<r){ if(arr[l]==x){ l++; } else if(arr[r]==x){ r--; } else if(arr[l]!=arr[r])return false; else{ l++; r--; } } return true; } static int gcd(int a,int b){ if(b==0){ return a; } return gcd(b,a%b); } static void sort(int[] arr) { ArrayList<Integer> ls = new ArrayList<Integer>(); for(int x: arr) ls.add(x); Collections.sort(ls); for(int i=0; i < arr.length; i++) arr[i] = ls.get(i); } static void reversesort(int[] arr) { ArrayList<Integer> ls = new ArrayList<Integer>(); for(int x: arr) ls.add(x); Collections.sort(ls); Collections.reverse(ls); for(int i=0; i < arr.length; i++) arr[i] = ls.get(i); } static int lcm(int a, int b) { return (a / gcd(a, b)) * b; } static void debug(String x){ System.out.println(x); } static < E > void print(E res) { System.out.println(res); } static String rString(String s){ StringBuilder sb=new StringBuilder(); sb.append(s); return sb.reverse().toString(); } }
Java
["8\n4\n1 2 5 2\nBRBR\n2\n1 1\nBB\n5\n3 1 4 2 5\nRBRRB\n5\n3 1 3 1 3\nRBRRB\n5\n5 1 5 1 5\nRBRRB\n4\n2 2 2 2\nBRBR\n2\n1 -2\nBR\n4\n-2 -1 4 0\nRRRR"]
1 second
["YES\nNO\nYES\nYES\nNO\nYES\nYES\nYES"]
NoteIn the first test case of the example, the following sequence of moves can be performed: choose $$$i=3$$$, element $$$a_3=5$$$ is blue, so we decrease it, we get $$$a=[1,2,4,2]$$$; choose $$$i=2$$$, element $$$a_2=2$$$ is red, so we increase it, we get $$$a=[1,3,4,2]$$$; choose $$$i=3$$$, element $$$a_3=4$$$ is blue, so we decrease it, we get $$$a=[1,3,3,2]$$$; choose $$$i=2$$$, element $$$a_2=2$$$ is red, so we increase it, we get $$$a=[1,4,3,2]$$$. We got that $$$a$$$ is a permutation. Hence the answer is YES.
Java 11
standard input
[ "greedy", "math", "sortings" ]
c3df88e22a17492d4eb0f3239a27d404
The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of input data sets in the test. The description of each set of input data consists of three lines. The first line contains an integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$) — the length of the original array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$-10^9 \leq a_i \leq 10^9$$$) — the array elements themselves. The third line has length $$$n$$$ and consists exclusively of the letters 'B' and/or 'R': $$$i$$$th character is 'B' if $$$a_i$$$ is colored blue, and is 'R' if colored red. It is guaranteed that the sum of $$$n$$$ over all input sets does not exceed $$$2 \cdot 10^5$$$.
1,300
Print $$$t$$$ lines, each of which contains the answer to the corresponding test case of the input. Print YES as an answer if the corresponding array can be transformed into a permutation, and NO otherwise. You can print the answer in any case (for example, the strings yEs, yes, Yes, and YES will be recognized as a positive answer).
standard output
PASSED
211262b275ddac8549bf2ff708d6fbd0
train_108.jsonl
1635863700
You are given an array of integers $$$a$$$ of length $$$n$$$. The elements of the array can be either different or the same. Each element of the array is colored either blue or red. There are no unpainted elements in the array. One of the two operations described below can be applied to an array in a single step: either you can select any blue element and decrease its value by $$$1$$$; or you can select any red element and increase its value by $$$1$$$. Situations in which there are no elements of some color at all are also possible. For example, if the whole array is colored blue or red, one of the operations becomes unavailable.Determine whether it is possible to make $$$0$$$ or more steps such that the resulting array is a permutation of numbers from $$$1$$$ to $$$n$$$?In other words, check whether there exists a sequence of steps (possibly empty) such that after applying it, the array $$$a$$$ contains in some order all numbers from $$$1$$$ to $$$n$$$ (inclusive), each exactly once.
256 megabytes
import java.util.*; import java.io.*; public class Main{ static final Random random=new Random(); static long mod=1000000007L; static HashMap<String,Integer>map=new HashMap<>(); static int[] arr,brr=new int[200005]; static class FastReader{ BufferedReader br; StringTokenizer st; public FastReader(){ br=new BufferedReader(new InputStreamReader(System.in)); } String next(){ while(st==null || !st.hasMoreTokens()){ try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt(){ return Integer.parseInt(next()); } long nextLong(){ return Long.parseLong(next()); } double nextDouble(){ return Double.parseDouble(next()); } String nextLine(){ String str=""; try { str=br.readLine().trim(); } catch (Exception e) { e.printStackTrace(); } return str; } int[] readIntArray(int n){ int[] res=new int[n]; for(int i=0;i<n;i++)res[i]=nextInt(); return res; } } static class FastWriter { private final BufferedWriter bw; public FastWriter() { this.bw = new BufferedWriter(new OutputStreamWriter(System.out)); } public void print(Object object) throws IOException { bw.append("" + object); } public void println(Object object) throws IOException { print(object); bw.append("\n"); } public void close() throws IOException { bw.close(); } } public static void main(String[] args) { try { FastReader in=new FastReader(); FastWriter out = new FastWriter(); int testCases=in.nextInt(); //int testCases=1; while(testCases-- > 0){ solve(in); } out.close(); } catch (Exception e) { return; } } public static void solve( FastReader in){ int n=in.nextInt(); //String s=in.next(); //String t=in.next(); //long y=in.nextInt(); //long n=in.nextLong(); //int k=in.nextInt(); //long k=in.nextLong(); StringBuilder res=new StringBuilder(); int[] arr=in.readIntArray(n); String s=in.next(); List<Integer> l=new ArrayList<>(); List<Integer> r=new ArrayList<>(); for(int i=0;i<n;i++){ if(s.charAt(i)=='B'){ l.add(arr[i]); } else{ r.add(arr[i]); } } Collections.sort(l); Collections.sort(r); Collections.reverse(r); boolean t=true; for(int i=0;i<l.size();i++){ if(l.get(i)<i+1){ t=false; } } for(int i=0;i<r.size();i++){ if(r.get(i)>n-i){ t=false; } } if(t){ res.append("yes"); } else res.append("no"); System.out.println(res.toString()); } static boolean ch(int[] arr,int x){ int l=0; int r=arr.length-1; while(l<r){ if(arr[l]==x){ l++; } else if(arr[r]==x){ r--; } else if(arr[l]!=arr[r])return false; else{ l++; r--; } } return true; } static int gcd(int a,int b){ if(b==0){ return a; } return gcd(b,a%b); } static void sort(int[] arr) { ArrayList<Integer> ls = new ArrayList<Integer>(); for(int x: arr) ls.add(x); Collections.sort(ls); for(int i=0; i < arr.length; i++) arr[i] = ls.get(i); } static void reversesort(int[] arr) { ArrayList<Integer> ls = new ArrayList<Integer>(); for(int x: arr) ls.add(x); Collections.sort(ls); Collections.reverse(ls); for(int i=0; i < arr.length; i++) arr[i] = ls.get(i); } static int lcm(int a, int b) { return (a / gcd(a, b)) * b; } static void debug(String x){ System.out.println(x); } static < E > void print(E res) { System.out.println(res); } static String rString(String s){ StringBuilder sb=new StringBuilder(); sb.append(s); return sb.reverse().toString(); } }
Java
["8\n4\n1 2 5 2\nBRBR\n2\n1 1\nBB\n5\n3 1 4 2 5\nRBRRB\n5\n3 1 3 1 3\nRBRRB\n5\n5 1 5 1 5\nRBRRB\n4\n2 2 2 2\nBRBR\n2\n1 -2\nBR\n4\n-2 -1 4 0\nRRRR"]
1 second
["YES\nNO\nYES\nYES\nNO\nYES\nYES\nYES"]
NoteIn the first test case of the example, the following sequence of moves can be performed: choose $$$i=3$$$, element $$$a_3=5$$$ is blue, so we decrease it, we get $$$a=[1,2,4,2]$$$; choose $$$i=2$$$, element $$$a_2=2$$$ is red, so we increase it, we get $$$a=[1,3,4,2]$$$; choose $$$i=3$$$, element $$$a_3=4$$$ is blue, so we decrease it, we get $$$a=[1,3,3,2]$$$; choose $$$i=2$$$, element $$$a_2=2$$$ is red, so we increase it, we get $$$a=[1,4,3,2]$$$. We got that $$$a$$$ is a permutation. Hence the answer is YES.
Java 11
standard input
[ "greedy", "math", "sortings" ]
c3df88e22a17492d4eb0f3239a27d404
The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of input data sets in the test. The description of each set of input data consists of three lines. The first line contains an integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$) — the length of the original array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$-10^9 \leq a_i \leq 10^9$$$) — the array elements themselves. The third line has length $$$n$$$ and consists exclusively of the letters 'B' and/or 'R': $$$i$$$th character is 'B' if $$$a_i$$$ is colored blue, and is 'R' if colored red. It is guaranteed that the sum of $$$n$$$ over all input sets does not exceed $$$2 \cdot 10^5$$$.
1,300
Print $$$t$$$ lines, each of which contains the answer to the corresponding test case of the input. Print YES as an answer if the corresponding array can be transformed into a permutation, and NO otherwise. You can print the answer in any case (for example, the strings yEs, yes, Yes, and YES will be recognized as a positive answer).
standard output
PASSED
2804bf6cfdff35d0ff3344c5f9e3b54f
train_108.jsonl
1635863700
You are given an array of integers $$$a$$$ of length $$$n$$$. The elements of the array can be either different or the same. Each element of the array is colored either blue or red. There are no unpainted elements in the array. One of the two operations described below can be applied to an array in a single step: either you can select any blue element and decrease its value by $$$1$$$; or you can select any red element and increase its value by $$$1$$$. Situations in which there are no elements of some color at all are also possible. For example, if the whole array is colored blue or red, one of the operations becomes unavailable.Determine whether it is possible to make $$$0$$$ or more steps such that the resulting array is a permutation of numbers from $$$1$$$ to $$$n$$$?In other words, check whether there exists a sequence of steps (possibly empty) such that after applying it, the array $$$a$$$ contains in some order all numbers from $$$1$$$ to $$$n$$$ (inclusive), each exactly once.
256 megabytes
import java.io.*; import java.util.*; public class edu130 { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine().trim(); } catch (Exception e) { e.printStackTrace(); } return str; } } static class FastWriter { private final BufferedWriter bw; public FastWriter() { this.bw = new BufferedWriter(new OutputStreamWriter(System.out)); } public void print(Object object) throws IOException { bw.append("" + object); } public void println(Object object) throws IOException { print(object); bw.append("\n"); } public void close() throws IOException { bw.close(); } } public static boolean func(long x,long k){ return (k-((x*x)+(x)+1))%(2*x)==0; } public static void gg(int [] arr, int l, int r, int count , int[] ans){ if(r<l){ return; } if(r==l){ ans[l]=count; return; } int m=l; for(int i=l+1;i<=r;i++){ if(arr[i]>arr[m]){ m=i; } } ans[m]=count; gg(arr,l,m-1,count+1,ans); gg(arr,m+1,r,count+1,ans); } public static void main(String[] args) { //RSRRSRSSSR try { FastReader sc = new FastReader(); FastWriter out = new FastWriter(); 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(); } String s=sc.next(); //HashMap<Integer,Integer> blue=new HashMap<>(); //HashMap<Integer,Integer> red=new HashMap<>(); int bl=0; int re=0; ArrayList<Integer> blue=new ArrayList<>(); ArrayList<Integer> red=new ArrayList<>(); for(int i=0;i<n;i++){ if(s.charAt(i)=='B'){ blue.add(arr[i]); }else{ red.add(arr[i]); } } Collections.sort(blue); Collections.sort(red); boolean temp=false; for(int i=1;i<=blue.size();i++){ if(blue.get(i-1)<i){ temp=true; break; } } if(temp){ System.out.println("NO"); continue; } int kk=n; for(int i=red.size()-1;i>=0;i--){ if(red.get(i)>kk){ temp=true; break; } kk--; } if(temp){ System.out.println("NO"); continue; } System.out.println("YES"); } }catch(Exception e){ return; } } private static char check(char c, char c1, char c2) { if(c2=='-'){ for(int i=0;i<26;i++){ char gg=(char)('a'+i); if(gg!=c && gg!=c1 ){ return gg; } } return '+'; }else{ for(int i=0;i<26;i++){ char gg=(char)('a'+i); if(gg!=c && gg!=c1 && gg!=c2){ return gg; } } return '+'; } } private static char get(StringBuilder sb, int i,char ff,char ss) { if(i==sb.length()-1){ for(int f = 0; f<26; f++){ if((char)('a'+f)!=ff ){ return (char) ('a'+ f); } } } else if(i==sb.length()-2){ for(int f = 0; f<26; f++){ if((char)('a'+f)!=ff && (char)('a'+f)!=ss && (char)('a'+f)!=sb.charAt(i+1) ){ return (char) ('a'+ f); } } }else{ for(int f = 0; f<26; f++){ if((char)('a'+f)!=ff && (char)('a'+f)!=ss && (char)('a'+f)!=sb.charAt(i+1) && (char)('a'+f)!=sb.charAt(i+2)){ return (char) ('a'+ f); } } } return 'l'; } public static int gg(int num){ int count=0; while(num>0){ count++; num=(num>>1); } return count; } private static void swap(int[] arr, int i, int ii) { int temp=arr[i]; arr[i]=arr[ii]; arr[ii]=temp; } public static int lcm(int a,int b){ return (a/gcd(a,b))*b; } private static int gcd(int a, int b) { if(b==0)return a; return gcd(b,a%b); } static class Pair { int a; int b; Pair(int a, int b) { this.a = a; this.b = b; } } }
Java
["8\n4\n1 2 5 2\nBRBR\n2\n1 1\nBB\n5\n3 1 4 2 5\nRBRRB\n5\n3 1 3 1 3\nRBRRB\n5\n5 1 5 1 5\nRBRRB\n4\n2 2 2 2\nBRBR\n2\n1 -2\nBR\n4\n-2 -1 4 0\nRRRR"]
1 second
["YES\nNO\nYES\nYES\nNO\nYES\nYES\nYES"]
NoteIn the first test case of the example, the following sequence of moves can be performed: choose $$$i=3$$$, element $$$a_3=5$$$ is blue, so we decrease it, we get $$$a=[1,2,4,2]$$$; choose $$$i=2$$$, element $$$a_2=2$$$ is red, so we increase it, we get $$$a=[1,3,4,2]$$$; choose $$$i=3$$$, element $$$a_3=4$$$ is blue, so we decrease it, we get $$$a=[1,3,3,2]$$$; choose $$$i=2$$$, element $$$a_2=2$$$ is red, so we increase it, we get $$$a=[1,4,3,2]$$$. We got that $$$a$$$ is a permutation. Hence the answer is YES.
Java 11
standard input
[ "greedy", "math", "sortings" ]
c3df88e22a17492d4eb0f3239a27d404
The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of input data sets in the test. The description of each set of input data consists of three lines. The first line contains an integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$) — the length of the original array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$-10^9 \leq a_i \leq 10^9$$$) — the array elements themselves. The third line has length $$$n$$$ and consists exclusively of the letters 'B' and/or 'R': $$$i$$$th character is 'B' if $$$a_i$$$ is colored blue, and is 'R' if colored red. It is guaranteed that the sum of $$$n$$$ over all input sets does not exceed $$$2 \cdot 10^5$$$.
1,300
Print $$$t$$$ lines, each of which contains the answer to the corresponding test case of the input. Print YES as an answer if the corresponding array can be transformed into a permutation, and NO otherwise. You can print the answer in any case (for example, the strings yEs, yes, Yes, and YES will be recognized as a positive answer).
standard output
PASSED
b11b00051ce97589b1580d02dd58a0ce
train_108.jsonl
1635863700
You are given an array of integers $$$a$$$ of length $$$n$$$. The elements of the array can be either different or the same. Each element of the array is colored either blue or red. There are no unpainted elements in the array. One of the two operations described below can be applied to an array in a single step: either you can select any blue element and decrease its value by $$$1$$$; or you can select any red element and increase its value by $$$1$$$. Situations in which there are no elements of some color at all are also possible. For example, if the whole array is colored blue or red, one of the operations becomes unavailable.Determine whether it is possible to make $$$0$$$ or more steps such that the resulting array is a permutation of numbers from $$$1$$$ to $$$n$$$?In other words, check whether there exists a sequence of steps (possibly empty) such that after applying it, the array $$$a$$$ contains in some order all numbers from $$$1$$$ to $$$n$$$ (inclusive), each exactly once.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; import java.util.Map.Entry; public class codeforces { static int mod = 1000000007; public static void main(String[] args) { FastReader sc = new FastReader(); try { StringBuilder ss = new StringBuilder(); 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(); } String s = sc.next(); Pair arr[] = new Pair[n]; for(int i = 0 ; i<n;i++) { arr[i] = new Pair(a[i],s.charAt(i)); } Arrays.parallelSort(arr); ArrayList<Integer> red = new ArrayList<>(); ArrayList<Integer> blue = new ArrayList<>(); for(int i = 0 ;i <n;i++) { if(s.charAt(i) == 'R') { red.add(a[i]); } else { blue.add(a[i]); } } Collections.sort(red); Collections.sort(blue); int max = n; boolean flag = true; for(int i = red.size() - 1 ; i>=0 ; i--) { if(red.get(i) >max) { flag = false; break; } max--; } int min = 1; for(int i = 0 ; i <blue.size() ; i++) { if(blue.get(i)<min) { flag = false; break; } min++; } if(flag) { ss.append("YES" +"\n"); } else { ss.append("NO" +"\n"); } } System.out.println(ss); } catch(Exception e) { System.out.println(e.getMessage()); } } static long pow(long a, long b) { long ans = 1; long temp = a; while(b>0) { if((b&1) == 1) { ans*=temp; } temp = temp*temp; b = b>>1; } return ans; } static long ncr(int n, int r) { return fact(n) / (fact(r) * fact(n - r)); } static long fact(long n) { long res = 1; for (int i = 2; i <= n; i++) { res = (res * i); } return res; } static long gcd(long a, long b) { if(b == 0) { return a; } return gcd(b , a%b); } static ArrayList<Integer> factor(long n) { ArrayList<Integer> al = new ArrayList<>(); for(int i = 1 ; i*i<=n;i++) { if(n%i == 0) { if(n/i == i) { al.add(i); } else { al.add(i); al.add((int) (n/i)); } } } return al; } static class Pair implements Comparable<Pair>{ long a; char b ; Pair(long a, char b){ this.a = a; this.b = b; } @Override public int compareTo(Pair o) { // TODO Auto-generated method stub return (int)(this.a - o.a); } } static ArrayList<Integer> sieve(int n) { boolean a[] = new boolean[n+1]; Arrays.fill(a, false); for(int i = 2 ; i*i <=n ; i++) { if(!a[i]) { for(int j = 2*i ; j<=n ; j+=i) { a[j] = true; } } } ArrayList<Integer> al = new ArrayList<>(); for(int i = 2 ; i <=n;i++) { if(!a[i]) { al.add(i); } } return al; } static ArrayList<Long> pf(long n) { ArrayList<Long> al = new ArrayList<>(); while(n%2 == 0) { al.add(2l); n = n/2; } for(long i = 3 ; i*i<=n ; i+=2) { while(n%i == 0) { al.add(i); n = n/i; } } if(n>2) { al.add( n); } return al; } 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
["8\n4\n1 2 5 2\nBRBR\n2\n1 1\nBB\n5\n3 1 4 2 5\nRBRRB\n5\n3 1 3 1 3\nRBRRB\n5\n5 1 5 1 5\nRBRRB\n4\n2 2 2 2\nBRBR\n2\n1 -2\nBR\n4\n-2 -1 4 0\nRRRR"]
1 second
["YES\nNO\nYES\nYES\nNO\nYES\nYES\nYES"]
NoteIn the first test case of the example, the following sequence of moves can be performed: choose $$$i=3$$$, element $$$a_3=5$$$ is blue, so we decrease it, we get $$$a=[1,2,4,2]$$$; choose $$$i=2$$$, element $$$a_2=2$$$ is red, so we increase it, we get $$$a=[1,3,4,2]$$$; choose $$$i=3$$$, element $$$a_3=4$$$ is blue, so we decrease it, we get $$$a=[1,3,3,2]$$$; choose $$$i=2$$$, element $$$a_2=2$$$ is red, so we increase it, we get $$$a=[1,4,3,2]$$$. We got that $$$a$$$ is a permutation. Hence the answer is YES.
Java 11
standard input
[ "greedy", "math", "sortings" ]
c3df88e22a17492d4eb0f3239a27d404
The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of input data sets in the test. The description of each set of input data consists of three lines. The first line contains an integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$) — the length of the original array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$-10^9 \leq a_i \leq 10^9$$$) — the array elements themselves. The third line has length $$$n$$$ and consists exclusively of the letters 'B' and/or 'R': $$$i$$$th character is 'B' if $$$a_i$$$ is colored blue, and is 'R' if colored red. It is guaranteed that the sum of $$$n$$$ over all input sets does not exceed $$$2 \cdot 10^5$$$.
1,300
Print $$$t$$$ lines, each of which contains the answer to the corresponding test case of the input. Print YES as an answer if the corresponding array can be transformed into a permutation, and NO otherwise. You can print the answer in any case (for example, the strings yEs, yes, Yes, and YES will be recognized as a positive answer).
standard output
PASSED
a33ec1b816a401d852d9941ab37dbf2e
train_108.jsonl
1635863700
You are given an array of integers $$$a$$$ of length $$$n$$$. The elements of the array can be either different or the same. Each element of the array is colored either blue or red. There are no unpainted elements in the array. One of the two operations described below can be applied to an array in a single step: either you can select any blue element and decrease its value by $$$1$$$; or you can select any red element and increase its value by $$$1$$$. Situations in which there are no elements of some color at all are also possible. For example, if the whole array is colored blue or red, one of the operations becomes unavailable.Determine whether it is possible to make $$$0$$$ or more steps such that the resulting array is a permutation of numbers from $$$1$$$ to $$$n$$$?In other words, check whether there exists a sequence of steps (possibly empty) such that after applying it, the array $$$a$$$ contains in some order all numbers from $$$1$$$ to $$$n$$$ (inclusive), each exactly once.
256 megabytes
import java.util.*; import java.lang.*; import java.math.BigInteger; import java.io.*; public class Main implements Runnable { public static void main(String[] args) { new Thread(null, new Main(), "whatever", 1 << 26).start(); } private FastScanner sc; private PrintWriter pw; public void run() { try { // pw = new PrintWriter(new BufferedWriter(new FileWriter("output.txt"))); // sc = new FastScanner(new BufferedReader(new FileReader("input.txt"))); pw = new PrintWriter(System.out); sc = new FastScanner(new BufferedReader(new InputStreamReader(System.in))); } catch (Exception e) { throw new RuntimeException(); } int t = sc.nextInt(); // int t = 1; while (t-- > 0) { // sc.nextLine(); solve(); } pw.close(); } public long mod = 1_000_000_007; public void solve() { int n = sc.nextInt(); int[][] arr = new int[n][2]; for (int i = 0; i < n; i++) { arr[i][0] = sc.nextInt(); } boolean ex = false; String s = sc.next(); for (int i = 0; i < n; i++) { if (s.charAt(i) == 'R') { arr[i][1] = 1; if (arr[i][0] > n) { ex = true; } else if (arr[i][0] < 1) arr[i][0] = 1; } else { arr[i][1] = 0; if (arr[i][0] < 1) { ex = true; } else if (arr[i][0] > n) arr[i][0] = n; } } if (ex) { pw.println("NO"); return; } Arrays.sort(arr, (o1, o2)-> { return o1[0] - o2[0]; }); int suffixb[] = new int[n], prefixr[] = new int[n]; for (int i = 0; i < n; i++) { if (arr[i][1] == 1) prefixr[arr[i][0] - 1]++; if (arr[i][1] == 0) suffixb[arr[i][0] - 1]++; } for (int i = 1; i < n; i++) { prefixr[i] += prefixr[i - 1]; } for (int i = n - 2; i >= 0; i--) { suffixb[i] += suffixb[i + 1]; } int subr = 0, subb = 0, countr = 0, countb = 0, takenFromAbove = 0; // int nb = suffixb[0], nr = prefixr[n - 1]; for (int i = 0; i < n; i++) { if (suffixb[i] - takenFromAbove > 0) { // pw.println("Adding Blue to i=" + i); countb++; if (i + 1 < n && suffixb[i] == suffixb[i + 1]) { takenFromAbove++; continue; } if (i + 1 < n && suffixb[i] - suffixb[i + 1] > 0) { int temp = suffixb[i] - suffixb[i + 1] - 1; if (temp == 0) continue; // pw.println("Inside for i =" + i); if (takenFromAbove < temp) { temp -= takenFromAbove; takenFromAbove = 0; } else { takenFromAbove -= temp; continue; } if (countr >= temp) { subr -= temp; countr -= temp; countb += temp; } else { pw.println("NO"); // pw.println("NO for i=" + i); return; } } } else if (prefixr[i] - subr > 0) { // pw.println("Adding Red to i=" + i); subr++; countr++; } else { pw.println("NO"); // pw.println("NO for i=" + i); // pw.println("Subr=" + subr + " and prefixr[" + i + "] = " + prefixr[i]); // pw.println("Subb=" + countb + " and suffixb[" + i + "] = " + suffixb[i]); return; } } pw.println("YES"); } class FastScanner { private BufferedReader reader = null; private StringTokenizer tokenizer = null; public FastScanner(BufferedReader bf) { reader = bf; tokenizer = null; } public String next() { if (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public String nextLine() { if (tokenizer == null || !tokenizer.hasMoreTokens()) { try { return reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken("\n"); } public long nextLong() { return Long.parseLong(next()); } public int nextInt() { return Integer.parseInt(next()); } public double nextDouble() { return Double.parseDouble(next()); } public float nextFloat() { return Float.parseFloat(next()); } public int[] nextIntArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } public String[] nextStringArray(int n) { String[] a = new String[n]; for (int i = 0; i < n; i++) { a[i] = next(); } return a; } public long[] nextLongArray(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) { a[i] = nextLong(); } return a; } } public long fastPow(long x, long y, long mod) { if (y == 0) return 1; if (y == 1) return x % mod; long temp = fastPow(x, y / 2, mod); long ans = (temp * temp) % mod; return (y % 2 == 1) ? (ans * (x % mod)) % mod : ans; } // public long fastPow(long x, long y) { // if (y == 0) return 1; // if (y == 1) return x; // long temp = fastPow(x, y / 2); // long ans = (temp * temp); // return (y % 2 == 1) ? (ans * x) : ans; // } }
Java
["8\n4\n1 2 5 2\nBRBR\n2\n1 1\nBB\n5\n3 1 4 2 5\nRBRRB\n5\n3 1 3 1 3\nRBRRB\n5\n5 1 5 1 5\nRBRRB\n4\n2 2 2 2\nBRBR\n2\n1 -2\nBR\n4\n-2 -1 4 0\nRRRR"]
1 second
["YES\nNO\nYES\nYES\nNO\nYES\nYES\nYES"]
NoteIn the first test case of the example, the following sequence of moves can be performed: choose $$$i=3$$$, element $$$a_3=5$$$ is blue, so we decrease it, we get $$$a=[1,2,4,2]$$$; choose $$$i=2$$$, element $$$a_2=2$$$ is red, so we increase it, we get $$$a=[1,3,4,2]$$$; choose $$$i=3$$$, element $$$a_3=4$$$ is blue, so we decrease it, we get $$$a=[1,3,3,2]$$$; choose $$$i=2$$$, element $$$a_2=2$$$ is red, so we increase it, we get $$$a=[1,4,3,2]$$$. We got that $$$a$$$ is a permutation. Hence the answer is YES.
Java 11
standard input
[ "greedy", "math", "sortings" ]
c3df88e22a17492d4eb0f3239a27d404
The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of input data sets in the test. The description of each set of input data consists of three lines. The first line contains an integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$) — the length of the original array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$-10^9 \leq a_i \leq 10^9$$$) — the array elements themselves. The third line has length $$$n$$$ and consists exclusively of the letters 'B' and/or 'R': $$$i$$$th character is 'B' if $$$a_i$$$ is colored blue, and is 'R' if colored red. It is guaranteed that the sum of $$$n$$$ over all input sets does not exceed $$$2 \cdot 10^5$$$.
1,300
Print $$$t$$$ lines, each of which contains the answer to the corresponding test case of the input. Print YES as an answer if the corresponding array can be transformed into a permutation, and NO otherwise. You can print the answer in any case (for example, the strings yEs, yes, Yes, and YES will be recognized as a positive answer).
standard output
PASSED
00dca0eca98286018a00f5f8cd3b075d
train_108.jsonl
1635863700
You are given an array of integers $$$a$$$ of length $$$n$$$. The elements of the array can be either different or the same. Each element of the array is colored either blue or red. There are no unpainted elements in the array. One of the two operations described below can be applied to an array in a single step: either you can select any blue element and decrease its value by $$$1$$$; or you can select any red element and increase its value by $$$1$$$. Situations in which there are no elements of some color at all are also possible. For example, if the whole array is colored blue or red, one of the operations becomes unavailable.Determine whether it is possible to make $$$0$$$ or more steps such that the resulting array is a permutation of numbers from $$$1$$$ to $$$n$$$?In other words, check whether there exists a sequence of steps (possibly empty) such that after applying it, the array $$$a$$$ contains in some order all numbers from $$$1$$$ to $$$n$$$ (inclusive), each exactly once.
256 megabytes
import java.util.*; public class A { public static void main(String[] args) { Scanner sc = new Scanner(System.in); StringBuilder str = new StringBuilder(); int t = sc.nextInt(); for (int xx = 0; xx < t; xx++) { int n = sc.nextInt(); Integer[] arr = new Integer[n]; for(int i=0;i<n;i++) arr[i] = sc.nextInt(); String s = sc.next(); ArrayList<Integer> Blue = new ArrayList<>(); ArrayList<Integer> Red = new ArrayList<>(); for(int i=0;i<s.length();i++) { if(s.charAt(i)=='B') { Blue.add(arr[i]); } else { Red.add(arr[i]); } } int c =1; Collections.sort(Blue); Collections.sort(Red); if(Blue.size()!=0) for(int i=0;i<Blue.size();i++) { if(Blue.get(i)>=c) { Blue.set(i, c); c++; } else { c=-1; break; } } if(Red.size()!=0&&c!=-1) for(int i=0;i<Red.size();i++) { if(Red.get(i)<=c) { Red.set(i, c); c++; } else { c=-1; break; } } if(c>n+1) str.append("No"+"\n"); else str.append((c!=-1?"YES":"NO")+"\n"); } System.out.println(str); } }
Java
["8\n4\n1 2 5 2\nBRBR\n2\n1 1\nBB\n5\n3 1 4 2 5\nRBRRB\n5\n3 1 3 1 3\nRBRRB\n5\n5 1 5 1 5\nRBRRB\n4\n2 2 2 2\nBRBR\n2\n1 -2\nBR\n4\n-2 -1 4 0\nRRRR"]
1 second
["YES\nNO\nYES\nYES\nNO\nYES\nYES\nYES"]
NoteIn the first test case of the example, the following sequence of moves can be performed: choose $$$i=3$$$, element $$$a_3=5$$$ is blue, so we decrease it, we get $$$a=[1,2,4,2]$$$; choose $$$i=2$$$, element $$$a_2=2$$$ is red, so we increase it, we get $$$a=[1,3,4,2]$$$; choose $$$i=3$$$, element $$$a_3=4$$$ is blue, so we decrease it, we get $$$a=[1,3,3,2]$$$; choose $$$i=2$$$, element $$$a_2=2$$$ is red, so we increase it, we get $$$a=[1,4,3,2]$$$. We got that $$$a$$$ is a permutation. Hence the answer is YES.
Java 11
standard input
[ "greedy", "math", "sortings" ]
c3df88e22a17492d4eb0f3239a27d404
The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of input data sets in the test. The description of each set of input data consists of three lines. The first line contains an integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$) — the length of the original array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$-10^9 \leq a_i \leq 10^9$$$) — the array elements themselves. The third line has length $$$n$$$ and consists exclusively of the letters 'B' and/or 'R': $$$i$$$th character is 'B' if $$$a_i$$$ is colored blue, and is 'R' if colored red. It is guaranteed that the sum of $$$n$$$ over all input sets does not exceed $$$2 \cdot 10^5$$$.
1,300
Print $$$t$$$ lines, each of which contains the answer to the corresponding test case of the input. Print YES as an answer if the corresponding array can be transformed into a permutation, and NO otherwise. You can print the answer in any case (for example, the strings yEs, yes, Yes, and YES will be recognized as a positive answer).
standard output
PASSED
1fb0835c81139d4e68d680ab6cdfaf9f
train_108.jsonl
1635863700
You are given an array of integers $$$a$$$ of length $$$n$$$. The elements of the array can be either different or the same. Each element of the array is colored either blue or red. There are no unpainted elements in the array. One of the two operations described below can be applied to an array in a single step: either you can select any blue element and decrease its value by $$$1$$$; or you can select any red element and increase its value by $$$1$$$. Situations in which there are no elements of some color at all are also possible. For example, if the whole array is colored blue or red, one of the operations becomes unavailable.Determine whether it is possible to make $$$0$$$ or more steps such that the resulting array is a permutation of numbers from $$$1$$$ to $$$n$$$?In other words, check whether there exists a sequence of steps (possibly empty) such that after applying it, the array $$$a$$$ contains in some order all numbers from $$$1$$$ to $$$n$$$ (inclusive), each exactly once.
256 megabytes
import java.util.*; public class Main { public static void main(String[] args) { Scanner sc= new Scanner(System.in); int t=sc.nextInt(); while(t-->0){ int n=sc.nextInt(); int[] a=new int[n]; for(int i=0;i<n;i++)a[i]=sc.nextInt(); String x=sc.next(); Vector<Integer> R=new Vector<>(); Vector<Integer> B=new Vector<>(); for(int i=0;i<n;i++){ if(x.charAt(i)=='B') R.add(a[i]); else B.add(a[i]); } Collections.sort(R); Collections.sort(B); boolean yes=true; for(int i=0;i<R.size();i++){ if(R.get(i)-i<1){System.out.println("NO");yes=false;break;} } if(yes) { int s=B.size(); for(int j=0;j<s;j++){ if(B.get(j)+s-j>n+1){System.out.println("NO");yes=false;break;} } } if(yes)System.out.println("YES"); } sc.close(); } }
Java
["8\n4\n1 2 5 2\nBRBR\n2\n1 1\nBB\n5\n3 1 4 2 5\nRBRRB\n5\n3 1 3 1 3\nRBRRB\n5\n5 1 5 1 5\nRBRRB\n4\n2 2 2 2\nBRBR\n2\n1 -2\nBR\n4\n-2 -1 4 0\nRRRR"]
1 second
["YES\nNO\nYES\nYES\nNO\nYES\nYES\nYES"]
NoteIn the first test case of the example, the following sequence of moves can be performed: choose $$$i=3$$$, element $$$a_3=5$$$ is blue, so we decrease it, we get $$$a=[1,2,4,2]$$$; choose $$$i=2$$$, element $$$a_2=2$$$ is red, so we increase it, we get $$$a=[1,3,4,2]$$$; choose $$$i=3$$$, element $$$a_3=4$$$ is blue, so we decrease it, we get $$$a=[1,3,3,2]$$$; choose $$$i=2$$$, element $$$a_2=2$$$ is red, so we increase it, we get $$$a=[1,4,3,2]$$$. We got that $$$a$$$ is a permutation. Hence the answer is YES.
Java 11
standard input
[ "greedy", "math", "sortings" ]
c3df88e22a17492d4eb0f3239a27d404
The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of input data sets in the test. The description of each set of input data consists of three lines. The first line contains an integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$) — the length of the original array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$-10^9 \leq a_i \leq 10^9$$$) — the array elements themselves. The third line has length $$$n$$$ and consists exclusively of the letters 'B' and/or 'R': $$$i$$$th character is 'B' if $$$a_i$$$ is colored blue, and is 'R' if colored red. It is guaranteed that the sum of $$$n$$$ over all input sets does not exceed $$$2 \cdot 10^5$$$.
1,300
Print $$$t$$$ lines, each of which contains the answer to the corresponding test case of the input. Print YES as an answer if the corresponding array can be transformed into a permutation, and NO otherwise. You can print the answer in any case (for example, the strings yEs, yes, Yes, and YES will be recognized as a positive answer).
standard output
PASSED
a143266c27e3d99427d38c6997769c76
train_108.jsonl
1635863700
You are given an array of integers $$$a$$$ of length $$$n$$$. The elements of the array can be either different or the same. Each element of the array is colored either blue or red. There are no unpainted elements in the array. One of the two operations described below can be applied to an array in a single step: either you can select any blue element and decrease its value by $$$1$$$; or you can select any red element and increase its value by $$$1$$$. Situations in which there are no elements of some color at all are also possible. For example, if the whole array is colored blue or red, one of the operations becomes unavailable.Determine whether it is possible to make $$$0$$$ or more steps such that the resulting array is a permutation of numbers from $$$1$$$ to $$$n$$$?In other words, check whether there exists a sequence of steps (possibly empty) such that after applying it, the array $$$a$$$ contains in some order all numbers from $$$1$$$ to $$$n$$$ (inclusive), each exactly once.
256 megabytes
import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintStream; import java.io.PrintWriter; import java.util.*; public class Mainnn { // static final File ip = new File("input.txt"); // static final File op = new File("output.txt"); // static { // try { // System.setOut(new PrintStream(op)); // System.setIn(new FileInputStream(ip)); // } catch (Exception e) { // } // // in = new InputReader(System.in); // } private static final PrintWriter out = new PrintWriter(System.out); public static void main(String[] args) { MyScanner sc = new MyScanner(); // out = new PrintWriter(new BufferedOutputStream(System.out)); // out.println(result); // print via PrintWriter ///////////////////////////////////////////// int test = sc.nextInt(); while (test-- != 0) { int n = sc.nextInt(); long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = sc.nextLong(); String s = sc.next(); ArrayList<Long> blue = new ArrayList<>(); ArrayList<Long> red = new ArrayList<>(); for (int i = 0; i < n; i++) { if (s.charAt(i) == 'B') blue.add(a[i]); else red.add(a[i]); } Collections.sort(blue); Collections.sort(red, Collections.reverseOrder()); int i = 0, j = 0; boolean ok = true; while (i < blue.size()) { if (blue.get(i) <= i) { ok = false; break; } i++; } while (j < red.size()) { if (red.get(j) > n-j) { ok = false; break; } j++; } if (ok == true) System.out.println("YES"); else System.out.println("NO"); } /////////////////////////////////////// } static long power(long x, long y, long p) { long res = 1; x = x % p; if (x == 0) return 0; while (y > 0) { if ((y & 1) != 0) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return res; } static void sortI(int[] arr) { int n = arr.length; Random rnd = new Random(); for (int i = 0; i < n; ++i) { int tmp = arr[i]; int randomPos = i + rnd.nextInt(n - i); arr[i] = arr[randomPos]; arr[randomPos] = tmp; } Arrays.sort(arr); } static void sortL(long[] arr) { int n = arr.length; Random rnd = new Random(); for (int i = 0; i < n; ++i) { long tmp = arr[i]; int randomPos = i + rnd.nextInt(n - i); arr[i] = arr[randomPos]; arr[randomPos] = tmp; } Arrays.sort(arr); } private static long gcd(long a, long b) { return (a == 0 ? b : gcd(b % a, a)); } static class pair implements Comparator<pair> { long a; int b; pair(long x, int y) { this.a = x; this.b = y; } public int compare(pair p1, pair p2) { if (p1.a > p2.a) return 1; else if (p1.a < p2.a) return -1; return 0; } } static class first implements Comparator<pair> { public int compare(pair p1, pair p2) { if (p1.a > p2.a) return 1; else if (p1.a < p2.a) return -1; return 0; } } static class second implements Comparator<pair> { public int compare(pair p1, pair p2) { if (p1.b > p2.b) return 1; else if (p1.b < p2.b) return -1; return 0; } } // -----------PrintWriter for faster output--------------------------------- // -----------MyScanner class for faster input---------- public static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } // -------------------------------------------------------- }
Java
["8\n4\n1 2 5 2\nBRBR\n2\n1 1\nBB\n5\n3 1 4 2 5\nRBRRB\n5\n3 1 3 1 3\nRBRRB\n5\n5 1 5 1 5\nRBRRB\n4\n2 2 2 2\nBRBR\n2\n1 -2\nBR\n4\n-2 -1 4 0\nRRRR"]
1 second
["YES\nNO\nYES\nYES\nNO\nYES\nYES\nYES"]
NoteIn the first test case of the example, the following sequence of moves can be performed: choose $$$i=3$$$, element $$$a_3=5$$$ is blue, so we decrease it, we get $$$a=[1,2,4,2]$$$; choose $$$i=2$$$, element $$$a_2=2$$$ is red, so we increase it, we get $$$a=[1,3,4,2]$$$; choose $$$i=3$$$, element $$$a_3=4$$$ is blue, so we decrease it, we get $$$a=[1,3,3,2]$$$; choose $$$i=2$$$, element $$$a_2=2$$$ is red, so we increase it, we get $$$a=[1,4,3,2]$$$. We got that $$$a$$$ is a permutation. Hence the answer is YES.
Java 11
standard input
[ "greedy", "math", "sortings" ]
c3df88e22a17492d4eb0f3239a27d404
The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of input data sets in the test. The description of each set of input data consists of three lines. The first line contains an integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$) — the length of the original array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$-10^9 \leq a_i \leq 10^9$$$) — the array elements themselves. The third line has length $$$n$$$ and consists exclusively of the letters 'B' and/or 'R': $$$i$$$th character is 'B' if $$$a_i$$$ is colored blue, and is 'R' if colored red. It is guaranteed that the sum of $$$n$$$ over all input sets does not exceed $$$2 \cdot 10^5$$$.
1,300
Print $$$t$$$ lines, each of which contains the answer to the corresponding test case of the input. Print YES as an answer if the corresponding array can be transformed into a permutation, and NO otherwise. You can print the answer in any case (for example, the strings yEs, yes, Yes, and YES will be recognized as a positive answer).
standard output
PASSED
a2e7bf3fb3a1944985137ae36775a11d
train_108.jsonl
1635863700
You are given an array of integers $$$a$$$ of length $$$n$$$. The elements of the array can be either different or the same. Each element of the array is colored either blue or red. There are no unpainted elements in the array. One of the two operations described below can be applied to an array in a single step: either you can select any blue element and decrease its value by $$$1$$$; or you can select any red element and increase its value by $$$1$$$. Situations in which there are no elements of some color at all are also possible. For example, if the whole array is colored blue or red, one of the operations becomes unavailable.Determine whether it is possible to make $$$0$$$ or more steps such that the resulting array is a permutation of numbers from $$$1$$$ to $$$n$$$?In other words, check whether there exists a sequence of steps (possibly empty) such that after applying it, the array $$$a$$$ contains in some order all numbers from $$$1$$$ to $$$n$$$ (inclusive), each exactly once.
256 megabytes
//package eround101; import java.util.*; import java.io.*; import java.lang.*; import java.util.StringTokenizer; public class Solution { static HritikScanner sc = new HritikScanner(); static PrintWriter pw = new PrintWriter(System.out, true); final static int MOD = 1000000007; static StringBuilder sb = new StringBuilder(); public static void main(String[] args) { int t = ni(); while (t-- > 0) { solve(); } } static void solve() { int n = ni(); int[] arr = nextIntArray(n); char[] col = sc.next().toCharArray(); int[] cB = new int[n+1]; int[] cR = new int[n+1]; for(int i = 0; i < n; i++) { // pl((col[i] == 'R' && arr[i] > n)); // pl((col[i] == 'B' && arr[i] < 1)); if((col[i] == 'R' && arr[i] > n)||(col[i] == 'B' && arr[i] < 1)) { pl("NO"); return; } if(col[i] == 'B') { if(arr[i] > n) continue; cB[arr[i]]++; if(cB[arr[i]] > arr[i]) { pl("NO"); return; } } else { if(arr[i] < 1) continue; cR[arr[i]]++; if(cR[arr[i]] > (n-(arr[i]-1))) { pl("NO"); return; } } // pa(cB); // pa(cR); } // pa(cB); // pa(cR); int[] psum = new int[n+1]; for(int i = 1; i<= n; i++) { psum[i] = psum[i-1]+cB[i]; if(psum[i] > i) { pl("NO"); return; } } // pa(psum); int[] psum1 = new int[n+1]; psum1[n] = cR[n]; for(int i = n-1; i>= 0; i--) { psum1[i] = psum1[i+1]+cR[i]; if(psum1[i] > (n-(i-1))) { pl("NO"); return; } } // pa(psum1); pl("YES"); } ///////////////////////////////////////////////////////////////////////////////// static class FenwickTree { // Binary Index Tree int[] tree; static int size; public FenwickTree(int size) { this.size = size; tree = new int[size + 5]; } public void add(int i, int val) { while (i <= size) { tree[i] += val; i += i & -i; // adding the decimal value of the last set bit. } } public int sum(int i) { int res = 0; while (i >= 1) { res += tree[i]; i -= i & -i; // deleting the last set bit } return res; } public int sum(int l, int r) { return sum(r) - sum(l - 1); } } ///////////////////////////////////////////////////////////////////////////////// static int[] nextIntArray(int n) { int[] arr = new int[n]; int i = 0; while (i < n) { arr[i++] = ni(); } return arr; } static long[] nextLongArray(int n) { long[] arr = new long[n]; int i = 0; while (i < n) { arr[i++] = nl(); } return arr; } static int[] nextIntArray1(int n) { int[] arr = new int[n + 1]; int i = 1; while (i <= n) { arr[i++] = ni(); } return arr; } ///////////////////////////////////////////////////////////////////////////////// static int ni() { return sc.nextInt(); } static long nl() { return sc.nextLong(); } static double nd() { return sc.nextDouble(); } ///////////////////////////////////////////////////////////////////////////////// static void pl() { pw.println(); } static void p(Object o) { pw.print(o + " "); } static void pl(Object o) { pw.println(o); } static void psb(StringBuilder sb) { pw.print(sb); } static void pa(Object arr[]) { for (Object o : arr) { p(o); } pl(); } static void pa(int arr[]) { for (int o : arr) { p(o); } pl(); } static void pa(long arr[]) { for (long o : arr) { p(o); } pl(); } static void pa(double arr[]) { for (double o : arr) { p(o); } pl(); } static void pa(char arr[]) { for (char o : arr) { p(o); } pl(); } static void pa(List list) { for (Object o : list) { p(o); } pl(); } static void pa(Object[][] arr) { for (int i = 0; i < arr.length; ++i) { for (Object o : arr[i]) { p(o); } pl(); } } static void pa(int[][] arr) { for (int i = 0; i < arr.length; ++i) { for (int o : arr[i]) { p(o); } pl(); } } static void pa(long[][] arr) { for (int i = 0; i < arr.length; ++i) { for (long o : arr[i]) { p(o); } pl(); } } static void pa(char[][] arr) { for (int i = 0; i < arr.length; ++i) { for (char o : arr[i]) { p(o); } pl(); } } static void pa(double[][] arr) { for (int i = 0; i < arr.length; ++i) { for (double o : arr[i]) { p(o); } pl(); } } ///////////////////////////////////////////////////////////////////////////////// static void print(Object s) { System.out.println(s); } ///////////////////////////////////////////////////////////////////////////////// //-----------HritikScanner class for faster input----------// static class HritikScanner { BufferedReader br; StringTokenizer st; public HritikScanner() { 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 class Pair implements Comparable<Pair> { int num, row, col; Pair(int num, int row, int col) { this.num = num; this.row = row; this.col = col; } public int get1() { return num; } public int get2() { return row; } public int compareTo(Pair A) { return this.num - A.num; } public String toString() { return num + " " + row + " " + col; } } ////////////////////////////////////////////////////////////////// // Function to return gcd of a and b time complexity O(log(a+b)) static long gcd(long a, long b) { if (a == 0) { return b; } return gcd(b % a, a); } // method to return LCM of two numbers static long lcm(long a, long b) { return (a / gcd(a, b)) * b; } ////////////////////////////////////////////////////////////////// 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 (long i = 5; i * i <= n; i = i + 6) { if (n % i == 0 || n % (i + 2) == 0) { return false; } } return true; } ////////////////////////////////////////////////////////////////// static boolean isPowerOfTwo(long n) { if (n == 0) { return false; } return (long) (Math.ceil((Math.log(n) / Math.log(2)))) == (long) (Math.floor(((Math.log(n) / Math.log(2))))); } public static long getFact(int n) { long ans = 1; while (n > 0) { ans *= n; ans %= MOD; n--; } return ans; } public static long pow(long n, int pow) { if (pow == 0) { return 1; } long temp = pow(n, pow / 2) % MOD; temp *= temp; temp %= MOD; if (pow % 2 == 1) { temp *= n; } temp %= MOD; return temp; } public static long nCr(int n, int r) { long ans = 1; int temp = n - r; while (n > temp) { ans *= n; ans %= MOD; n--; } ans *= pow(getFact(r) % MOD, MOD - 2) % MOD; ans %= MOD; return ans; } ////////////////////////////////////////////////////////////////// // method returns Nth power of A static double nthRoot(int A, int N) { // intially guessing a random number between // 0 and 9 double xPre = Math.random() % 10; // smaller eps, denotes more accuracy double eps = 0.001; // initializing difference between two // roots by INT_MAX double delX = 2147483647; // xK denotes current value of x double xK = 0.0; // loop untill we reach desired accuracy while (delX > eps) { // calculating current value from previous // value by newton's method xK = ((N - 1.0) * xPre + (double) A / Math.pow(xPre, N - 1)) / (double) N; delX = Math.abs(xK - xPre); xPre = xK; } return xK; } }
Java
["8\n4\n1 2 5 2\nBRBR\n2\n1 1\nBB\n5\n3 1 4 2 5\nRBRRB\n5\n3 1 3 1 3\nRBRRB\n5\n5 1 5 1 5\nRBRRB\n4\n2 2 2 2\nBRBR\n2\n1 -2\nBR\n4\n-2 -1 4 0\nRRRR"]
1 second
["YES\nNO\nYES\nYES\nNO\nYES\nYES\nYES"]
NoteIn the first test case of the example, the following sequence of moves can be performed: choose $$$i=3$$$, element $$$a_3=5$$$ is blue, so we decrease it, we get $$$a=[1,2,4,2]$$$; choose $$$i=2$$$, element $$$a_2=2$$$ is red, so we increase it, we get $$$a=[1,3,4,2]$$$; choose $$$i=3$$$, element $$$a_3=4$$$ is blue, so we decrease it, we get $$$a=[1,3,3,2]$$$; choose $$$i=2$$$, element $$$a_2=2$$$ is red, so we increase it, we get $$$a=[1,4,3,2]$$$. We got that $$$a$$$ is a permutation. Hence the answer is YES.
Java 11
standard input
[ "greedy", "math", "sortings" ]
c3df88e22a17492d4eb0f3239a27d404
The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of input data sets in the test. The description of each set of input data consists of three lines. The first line contains an integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$) — the length of the original array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$-10^9 \leq a_i \leq 10^9$$$) — the array elements themselves. The third line has length $$$n$$$ and consists exclusively of the letters 'B' and/or 'R': $$$i$$$th character is 'B' if $$$a_i$$$ is colored blue, and is 'R' if colored red. It is guaranteed that the sum of $$$n$$$ over all input sets does not exceed $$$2 \cdot 10^5$$$.
1,300
Print $$$t$$$ lines, each of which contains the answer to the corresponding test case of the input. Print YES as an answer if the corresponding array can be transformed into a permutation, and NO otherwise. You can print the answer in any case (for example, the strings yEs, yes, Yes, and YES will be recognized as a positive answer).
standard output
PASSED
42e6b89e98c2acf8df810907d34131ce
train_108.jsonl
1635863700
You are given an array of integers $$$a$$$ of length $$$n$$$. The elements of the array can be either different or the same. Each element of the array is colored either blue or red. There are no unpainted elements in the array. One of the two operations described below can be applied to an array in a single step: either you can select any blue element and decrease its value by $$$1$$$; or you can select any red element and increase its value by $$$1$$$. Situations in which there are no elements of some color at all are also possible. For example, if the whole array is colored blue or red, one of the operations becomes unavailable.Determine whether it is possible to make $$$0$$$ or more steps such that the resulting array is a permutation of numbers from $$$1$$$ to $$$n$$$?In other words, check whether there exists a sequence of steps (possibly empty) such that after applying it, the array $$$a$$$ contains in some order all numbers from $$$1$$$ to $$$n$$$ (inclusive), each exactly once.
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; /* Name of the class has to be "Main" only if the class is public. */ public class Main { public static void main (String[] args) throws java.lang.Exception { Scanner scn = new Scanner(System.in); int t = scn.nextInt(); while(t-->0){ int n = scn.nextInt(); int[] arr = new int[n]; for(int i=0;i<arr.length;i++){ arr[i]=scn.nextInt(); } String str = scn.next(); char[] ch = str.toCharArray(); if(isPossible(n,arr,ch)){ System.out.println("Yes"); }else { System.out.println("No"); } } } public static boolean isPossible(int n ,int[] arr,char[] ch){ ArrayList<Integer> listB = new ArrayList<>(); ArrayList<Integer> listA = new ArrayList<>(); for(int i=0;i<ch.length;i++){ (ch[i]=='B'?listB:listA).add(arr[i]); } Collections.sort(listA); Collections.sort(listB); int curr=1; for(int i=0;i<listB.size();i++){ if(listB.get(i)>=curr){ curr++; }else { return false; } } for(int i=0;i<listA.size();i++){ if(listA.get(i)<=curr){ curr++; }else { return false; } } return true; } }
Java
["8\n4\n1 2 5 2\nBRBR\n2\n1 1\nBB\n5\n3 1 4 2 5\nRBRRB\n5\n3 1 3 1 3\nRBRRB\n5\n5 1 5 1 5\nRBRRB\n4\n2 2 2 2\nBRBR\n2\n1 -2\nBR\n4\n-2 -1 4 0\nRRRR"]
1 second
["YES\nNO\nYES\nYES\nNO\nYES\nYES\nYES"]
NoteIn the first test case of the example, the following sequence of moves can be performed: choose $$$i=3$$$, element $$$a_3=5$$$ is blue, so we decrease it, we get $$$a=[1,2,4,2]$$$; choose $$$i=2$$$, element $$$a_2=2$$$ is red, so we increase it, we get $$$a=[1,3,4,2]$$$; choose $$$i=3$$$, element $$$a_3=4$$$ is blue, so we decrease it, we get $$$a=[1,3,3,2]$$$; choose $$$i=2$$$, element $$$a_2=2$$$ is red, so we increase it, we get $$$a=[1,4,3,2]$$$. We got that $$$a$$$ is a permutation. Hence the answer is YES.
Java 11
standard input
[ "greedy", "math", "sortings" ]
c3df88e22a17492d4eb0f3239a27d404
The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of input data sets in the test. The description of each set of input data consists of three lines. The first line contains an integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$) — the length of the original array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$-10^9 \leq a_i \leq 10^9$$$) — the array elements themselves. The third line has length $$$n$$$ and consists exclusively of the letters 'B' and/or 'R': $$$i$$$th character is 'B' if $$$a_i$$$ is colored blue, and is 'R' if colored red. It is guaranteed that the sum of $$$n$$$ over all input sets does not exceed $$$2 \cdot 10^5$$$.
1,300
Print $$$t$$$ lines, each of which contains the answer to the corresponding test case of the input. Print YES as an answer if the corresponding array can be transformed into a permutation, and NO otherwise. You can print the answer in any case (for example, the strings yEs, yes, Yes, and YES will be recognized as a positive answer).
standard output
PASSED
3c845810da5870fd3934aff530a92af0
train_108.jsonl
1635863700
You are given an array of integers $$$a$$$ of length $$$n$$$. The elements of the array can be either different or the same. Each element of the array is colored either blue or red. There are no unpainted elements in the array. One of the two operations described below can be applied to an array in a single step: either you can select any blue element and decrease its value by $$$1$$$; or you can select any red element and increase its value by $$$1$$$. Situations in which there are no elements of some color at all are also possible. For example, if the whole array is colored blue or red, one of the operations becomes unavailable.Determine whether it is possible to make $$$0$$$ or more steps such that the resulting array is a permutation of numbers from $$$1$$$ to $$$n$$$?In other words, check whether there exists a sequence of steps (possibly empty) such that after applying it, the array $$$a$$$ contains in some order all numbers from $$$1$$$ to $$$n$$$ (inclusive), each exactly once.
256 megabytes
import java.util.Scanner; import java.io.OutputStreamWriter; import java.io.BufferedWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.Stack; public class bluered { public static void main(String[] args) throws IOException { class Par { int vrijednost; char karakter; public Par(int vrijednost, char karakter) { this.vrijednost = vrijednost; this.karakter = karakter; } } class poredi implements Comparator<Par> { @Override public int compare(Par o1, Par o2) { return o1.karakter - o2.karakter; } } Scanner in = new Scanner(System.in); BufferedWriter log = new BufferedWriter(new OutputStreamWriter(System.out)); int tt = in.nextInt(); for(int w = 0; w<tt; w++) { int n = in.nextInt(); int[] a = new int[n]; ArrayList<Integer> l1 = new ArrayList<>(); ArrayList<Integer> l2 = new ArrayList<>(); for(int i = 0; i < n; i++) { a[i] = in.nextInt(); } String s = in.next(); Par[] niz = new Par[n]; boolean[] pos = new boolean[n]; for(int i = 0; i<n; i++) { niz[i] = new Par(a[i],s.charAt(i)); } Arrays.sort(niz,new poredi()); int x = 0; int y = 0; if(n==1) { if((a[0]<=n && s.charAt(0)=='R') || (a[0]>=n && s.charAt(0)=='B')) { log.write("YES"+"\n"); } else { log.write("NO"+"\n"); } } else { int i = n-1; while(i>=0 && niz[i].karakter=='R') { l1.add(niz[i].vrijednost); i--; } for(int j = i; j>=0; j--) { l2.add(niz[j].vrijednost); } Collections.sort(l1); Collections.sort(l2); boolean found = false; int cnt = l1.size() -1; int gornja = n; while(cnt>=0) { if(l1.get(cnt)>gornja) { found = true; break; } else { gornja--; } cnt--; } cnt = 0; int donja = 1; while(cnt<l2.size()) { if(l2.get(cnt)<donja) { found = true; break; } else { donja++; } cnt++; } if(found) { log.write("NO"+"\n"); } else { log.write("YES"+"\n"); } } log.flush(); } } }
Java
["8\n4\n1 2 5 2\nBRBR\n2\n1 1\nBB\n5\n3 1 4 2 5\nRBRRB\n5\n3 1 3 1 3\nRBRRB\n5\n5 1 5 1 5\nRBRRB\n4\n2 2 2 2\nBRBR\n2\n1 -2\nBR\n4\n-2 -1 4 0\nRRRR"]
1 second
["YES\nNO\nYES\nYES\nNO\nYES\nYES\nYES"]
NoteIn the first test case of the example, the following sequence of moves can be performed: choose $$$i=3$$$, element $$$a_3=5$$$ is blue, so we decrease it, we get $$$a=[1,2,4,2]$$$; choose $$$i=2$$$, element $$$a_2=2$$$ is red, so we increase it, we get $$$a=[1,3,4,2]$$$; choose $$$i=3$$$, element $$$a_3=4$$$ is blue, so we decrease it, we get $$$a=[1,3,3,2]$$$; choose $$$i=2$$$, element $$$a_2=2$$$ is red, so we increase it, we get $$$a=[1,4,3,2]$$$. We got that $$$a$$$ is a permutation. Hence the answer is YES.
Java 11
standard input
[ "greedy", "math", "sortings" ]
c3df88e22a17492d4eb0f3239a27d404
The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of input data sets in the test. The description of each set of input data consists of three lines. The first line contains an integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$) — the length of the original array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$-10^9 \leq a_i \leq 10^9$$$) — the array elements themselves. The third line has length $$$n$$$ and consists exclusively of the letters 'B' and/or 'R': $$$i$$$th character is 'B' if $$$a_i$$$ is colored blue, and is 'R' if colored red. It is guaranteed that the sum of $$$n$$$ over all input sets does not exceed $$$2 \cdot 10^5$$$.
1,300
Print $$$t$$$ lines, each of which contains the answer to the corresponding test case of the input. Print YES as an answer if the corresponding array can be transformed into a permutation, and NO otherwise. You can print the answer in any case (for example, the strings yEs, yes, Yes, and YES will be recognized as a positive answer).
standard output
PASSED
8a7f3fe4e600bfedd7af5951cca27454
train_108.jsonl
1635863700
You are given an array of integers $$$a$$$ of length $$$n$$$. The elements of the array can be either different or the same. Each element of the array is colored either blue or red. There are no unpainted elements in the array. One of the two operations described below can be applied to an array in a single step: either you can select any blue element and decrease its value by $$$1$$$; or you can select any red element and increase its value by $$$1$$$. Situations in which there are no elements of some color at all are also possible. For example, if the whole array is colored blue or red, one of the operations becomes unavailable.Determine whether it is possible to make $$$0$$$ or more steps such that the resulting array is a permutation of numbers from $$$1$$$ to $$$n$$$?In other words, check whether there exists a sequence of steps (possibly empty) such that after applying it, the array $$$a$$$ contains in some order all numbers from $$$1$$$ to $$$n$$$ (inclusive), each exactly once.
256 megabytes
import java.util.*; public class Blue_Red_Permutation { public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc = new Scanner(System.in); StringBuilder sb = new StringBuilder(); 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(); sc.nextLine(); String s = sc.nextLine(); ArrayList<Integer> blue = new ArrayList<>(); ArrayList<Integer> red = new ArrayList<>(); for(int i=0;i<n;i++) { if(s.charAt(i)=='B') blue.add(arr[i]); else red.add(arr[i]); } Collections.sort(red); Collections.sort(blue); boolean flag = true; int k = blue.size(); for(int i=1;i<=red.size();i++) { if(red.get(i-1)>k+i) { flag = false; break; } } for(int i=k;i>0;i--) { if(blue.get(i-1)<i) { flag = false; break; } } if(flag) sb.append("YES\n"); else sb.append("NO\n"); } System.out.println(sb); } }
Java
["8\n4\n1 2 5 2\nBRBR\n2\n1 1\nBB\n5\n3 1 4 2 5\nRBRRB\n5\n3 1 3 1 3\nRBRRB\n5\n5 1 5 1 5\nRBRRB\n4\n2 2 2 2\nBRBR\n2\n1 -2\nBR\n4\n-2 -1 4 0\nRRRR"]
1 second
["YES\nNO\nYES\nYES\nNO\nYES\nYES\nYES"]
NoteIn the first test case of the example, the following sequence of moves can be performed: choose $$$i=3$$$, element $$$a_3=5$$$ is blue, so we decrease it, we get $$$a=[1,2,4,2]$$$; choose $$$i=2$$$, element $$$a_2=2$$$ is red, so we increase it, we get $$$a=[1,3,4,2]$$$; choose $$$i=3$$$, element $$$a_3=4$$$ is blue, so we decrease it, we get $$$a=[1,3,3,2]$$$; choose $$$i=2$$$, element $$$a_2=2$$$ is red, so we increase it, we get $$$a=[1,4,3,2]$$$. We got that $$$a$$$ is a permutation. Hence the answer is YES.
Java 11
standard input
[ "greedy", "math", "sortings" ]
c3df88e22a17492d4eb0f3239a27d404
The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of input data sets in the test. The description of each set of input data consists of three lines. The first line contains an integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$) — the length of the original array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$-10^9 \leq a_i \leq 10^9$$$) — the array elements themselves. The third line has length $$$n$$$ and consists exclusively of the letters 'B' and/or 'R': $$$i$$$th character is 'B' if $$$a_i$$$ is colored blue, and is 'R' if colored red. It is guaranteed that the sum of $$$n$$$ over all input sets does not exceed $$$2 \cdot 10^5$$$.
1,300
Print $$$t$$$ lines, each of which contains the answer to the corresponding test case of the input. Print YES as an answer if the corresponding array can be transformed into a permutation, and NO otherwise. You can print the answer in any case (for example, the strings yEs, yes, Yes, and YES will be recognized as a positive answer).
standard output
PASSED
82d3ac24560b236c7f166109063b39ad
train_108.jsonl
1635863700
You are given an array of integers $$$a$$$ of length $$$n$$$. The elements of the array can be either different or the same. Each element of the array is colored either blue or red. There are no unpainted elements in the array. One of the two operations described below can be applied to an array in a single step: either you can select any blue element and decrease its value by $$$1$$$; or you can select any red element and increase its value by $$$1$$$. Situations in which there are no elements of some color at all are also possible. For example, if the whole array is colored blue or red, one of the operations becomes unavailable.Determine whether it is possible to make $$$0$$$ or more steps such that the resulting array is a permutation of numbers from $$$1$$$ to $$$n$$$?In other words, check whether there exists a sequence of steps (possibly empty) such that after applying it, the array $$$a$$$ contains in some order all numbers from $$$1$$$ to $$$n$$$ (inclusive), each exactly once.
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 arr[] = new int[n]; for (int i = 0; i < n; i++) { arr[i] = in.nextInt(); } in.nextLine(); String line = in.nextLine(); int b[] = new int[n]; int c[] = new int[n]; int pb = 0,pc = 0; for (int i = 0; i < n; i++) { if (line.charAt(i) == 'B') b[pb++] = arr[i]; else c[pc++] = arr[i]; } Arrays.sort(b,0,pb); Arrays.sort(c,0,pc); boolean flag = false; for (int i = 0; i < pb; i++) { if (b[i] < i+1){ flag = true; break; } } for (int i = pc-1; i >= 0; i--) { if (c[i] > n-(pc-i)+1){ flag = true; break; } } if (flag) System.out.println("NO"); else System.out.println("Yes"); } } }
Java
["8\n4\n1 2 5 2\nBRBR\n2\n1 1\nBB\n5\n3 1 4 2 5\nRBRRB\n5\n3 1 3 1 3\nRBRRB\n5\n5 1 5 1 5\nRBRRB\n4\n2 2 2 2\nBRBR\n2\n1 -2\nBR\n4\n-2 -1 4 0\nRRRR"]
1 second
["YES\nNO\nYES\nYES\nNO\nYES\nYES\nYES"]
NoteIn the first test case of the example, the following sequence of moves can be performed: choose $$$i=3$$$, element $$$a_3=5$$$ is blue, so we decrease it, we get $$$a=[1,2,4,2]$$$; choose $$$i=2$$$, element $$$a_2=2$$$ is red, so we increase it, we get $$$a=[1,3,4,2]$$$; choose $$$i=3$$$, element $$$a_3=4$$$ is blue, so we decrease it, we get $$$a=[1,3,3,2]$$$; choose $$$i=2$$$, element $$$a_2=2$$$ is red, so we increase it, we get $$$a=[1,4,3,2]$$$. We got that $$$a$$$ is a permutation. Hence the answer is YES.
Java 11
standard input
[ "greedy", "math", "sortings" ]
c3df88e22a17492d4eb0f3239a27d404
The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of input data sets in the test. The description of each set of input data consists of three lines. The first line contains an integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$) — the length of the original array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$-10^9 \leq a_i \leq 10^9$$$) — the array elements themselves. The third line has length $$$n$$$ and consists exclusively of the letters 'B' and/or 'R': $$$i$$$th character is 'B' if $$$a_i$$$ is colored blue, and is 'R' if colored red. It is guaranteed that the sum of $$$n$$$ over all input sets does not exceed $$$2 \cdot 10^5$$$.
1,300
Print $$$t$$$ lines, each of which contains the answer to the corresponding test case of the input. Print YES as an answer if the corresponding array can be transformed into a permutation, and NO otherwise. You can print the answer in any case (for example, the strings yEs, yes, Yes, and YES will be recognized as a positive answer).
standard output
PASSED
13662aab55f936b674a95ad2e30106e6
train_108.jsonl
1635863700
You are given an array of integers $$$a$$$ of length $$$n$$$. The elements of the array can be either different or the same. Each element of the array is colored either blue or red. There are no unpainted elements in the array. One of the two operations described below can be applied to an array in a single step: either you can select any blue element and decrease its value by $$$1$$$; or you can select any red element and increase its value by $$$1$$$. Situations in which there are no elements of some color at all are also possible. For example, if the whole array is colored blue or red, one of the operations becomes unavailable.Determine whether it is possible to make $$$0$$$ or more steps such that the resulting array is a permutation of numbers from $$$1$$$ to $$$n$$$?In other words, check whether there exists a sequence of steps (possibly empty) such that after applying it, the array $$$a$$$ contains in some order all numbers from $$$1$$$ to $$$n$$$ (inclusive), each exactly once.
256 megabytes
import java.util.*; public class D_Blue_Red_Permutation{ public static void main(String[] args) { Scanner sc = new Scanner(System.in); int tc = sc.nextInt(); while(tc-- >0){ int n = sc.nextInt(); int[][] arr = new int[n][2]; for(int i=0;i<n;i++){ arr[i][0]=sc.nextInt(); } String str = sc.next(); for(int i=0;i<n;i++) arr[i][1] = str.charAt(i); Arrays.sort(arr, new Comparator<int[]>() { public int compare(int[] a,int[] b){ if(a[1]>b[1]) return 1; else if(b[1]>a[1]) return -1; else if(a[0]>b[0]) return 1; else if (a[0]==b[0]) return 0; return -1; } }); boolean uttar = true; for(int i=0;i<n;i++){ if(arr[i][1]=='B'){ if(arr[i][0]<i+1){ uttar = false; break; } } else{ if(arr[i][0]>i+1){ uttar = false; break; } } } if(!uttar) System.out.println("NO"); else System.out.println("YES"); // for(int i=0;i<n;i++){ // System.out.println(arr[i][0]+" "+arr[i][1]); // } } } }
Java
["8\n4\n1 2 5 2\nBRBR\n2\n1 1\nBB\n5\n3 1 4 2 5\nRBRRB\n5\n3 1 3 1 3\nRBRRB\n5\n5 1 5 1 5\nRBRRB\n4\n2 2 2 2\nBRBR\n2\n1 -2\nBR\n4\n-2 -1 4 0\nRRRR"]
1 second
["YES\nNO\nYES\nYES\nNO\nYES\nYES\nYES"]
NoteIn the first test case of the example, the following sequence of moves can be performed: choose $$$i=3$$$, element $$$a_3=5$$$ is blue, so we decrease it, we get $$$a=[1,2,4,2]$$$; choose $$$i=2$$$, element $$$a_2=2$$$ is red, so we increase it, we get $$$a=[1,3,4,2]$$$; choose $$$i=3$$$, element $$$a_3=4$$$ is blue, so we decrease it, we get $$$a=[1,3,3,2]$$$; choose $$$i=2$$$, element $$$a_2=2$$$ is red, so we increase it, we get $$$a=[1,4,3,2]$$$. We got that $$$a$$$ is a permutation. Hence the answer is YES.
Java 11
standard input
[ "greedy", "math", "sortings" ]
c3df88e22a17492d4eb0f3239a27d404
The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of input data sets in the test. The description of each set of input data consists of three lines. The first line contains an integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$) — the length of the original array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$-10^9 \leq a_i \leq 10^9$$$) — the array elements themselves. The third line has length $$$n$$$ and consists exclusively of the letters 'B' and/or 'R': $$$i$$$th character is 'B' if $$$a_i$$$ is colored blue, and is 'R' if colored red. It is guaranteed that the sum of $$$n$$$ over all input sets does not exceed $$$2 \cdot 10^5$$$.
1,300
Print $$$t$$$ lines, each of which contains the answer to the corresponding test case of the input. Print YES as an answer if the corresponding array can be transformed into a permutation, and NO otherwise. You can print the answer in any case (for example, the strings yEs, yes, Yes, and YES will be recognized as a positive answer).
standard output
PASSED
561cdb171bff14194aa0df6bb44a4a31
train_108.jsonl
1635863700
You are given an array of integers $$$a$$$ of length $$$n$$$. The elements of the array can be either different or the same. Each element of the array is colored either blue or red. There are no unpainted elements in the array. One of the two operations described below can be applied to an array in a single step: either you can select any blue element and decrease its value by $$$1$$$; or you can select any red element and increase its value by $$$1$$$. Situations in which there are no elements of some color at all are also possible. For example, if the whole array is colored blue or red, one of the operations becomes unavailable.Determine whether it is possible to make $$$0$$$ or more steps such that the resulting array is a permutation of numbers from $$$1$$$ to $$$n$$$?In other words, check whether there exists a sequence of steps (possibly empty) such that after applying it, the array $$$a$$$ contains in some order all numbers from $$$1$$$ to $$$n$$$ (inclusive), each exactly once.
256 megabytes
import java.util.*; public class Main { public static boolean solve(int[] arr,String color) { int n = arr.length; //long sum = 0; int[][] nums = new int[n][2]; for(int i =0; i < n; i++) { int c = color.charAt(i); /*if(c == 'B' && arr[i] < 1) return false; if(c == 'R' && arr[i] > n) return false; */ nums[i][0] = arr[i]; if(c == 'B'){ nums[i][1] = 0; } else { nums[i][1] = 1; } } Arrays.sort(nums, (x,y) -> x[0]-y[0]); int k = 1; for(int i =0; i < n; i++) { if(nums[i][1] == 0) { if(nums[i][0] < k) return false; k++; } } k = n; for(int i =n-1; i >= 0; i--) { if(nums[i][1] == 1) { if(nums[i][0] > k) return false; k--; } } return true; } public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); for(int i =0; i < n; i++) { int size = sc.nextInt(); int[] arr = new int[size]; for(int j =0; j < size; j++) arr[j] = sc.nextInt(); String color = sc.next(); System.out.println( solve(arr,color)? "YES" : "NO"); } } }
Java
["8\n4\n1 2 5 2\nBRBR\n2\n1 1\nBB\n5\n3 1 4 2 5\nRBRRB\n5\n3 1 3 1 3\nRBRRB\n5\n5 1 5 1 5\nRBRRB\n4\n2 2 2 2\nBRBR\n2\n1 -2\nBR\n4\n-2 -1 4 0\nRRRR"]
1 second
["YES\nNO\nYES\nYES\nNO\nYES\nYES\nYES"]
NoteIn the first test case of the example, the following sequence of moves can be performed: choose $$$i=3$$$, element $$$a_3=5$$$ is blue, so we decrease it, we get $$$a=[1,2,4,2]$$$; choose $$$i=2$$$, element $$$a_2=2$$$ is red, so we increase it, we get $$$a=[1,3,4,2]$$$; choose $$$i=3$$$, element $$$a_3=4$$$ is blue, so we decrease it, we get $$$a=[1,3,3,2]$$$; choose $$$i=2$$$, element $$$a_2=2$$$ is red, so we increase it, we get $$$a=[1,4,3,2]$$$. We got that $$$a$$$ is a permutation. Hence the answer is YES.
Java 11
standard input
[ "greedy", "math", "sortings" ]
c3df88e22a17492d4eb0f3239a27d404
The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of input data sets in the test. The description of each set of input data consists of three lines. The first line contains an integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$) — the length of the original array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$-10^9 \leq a_i \leq 10^9$$$) — the array elements themselves. The third line has length $$$n$$$ and consists exclusively of the letters 'B' and/or 'R': $$$i$$$th character is 'B' if $$$a_i$$$ is colored blue, and is 'R' if colored red. It is guaranteed that the sum of $$$n$$$ over all input sets does not exceed $$$2 \cdot 10^5$$$.
1,300
Print $$$t$$$ lines, each of which contains the answer to the corresponding test case of the input. Print YES as an answer if the corresponding array can be transformed into a permutation, and NO otherwise. You can print the answer in any case (for example, the strings yEs, yes, Yes, and YES will be recognized as a positive answer).
standard output
PASSED
cfb5afe5d0cdf7bee0e402b4a774b627
train_108.jsonl
1635863700
You are given an array of integers $$$a$$$ of length $$$n$$$. The elements of the array can be either different or the same. Each element of the array is colored either blue or red. There are no unpainted elements in the array. One of the two operations described below can be applied to an array in a single step: either you can select any blue element and decrease its value by $$$1$$$; or you can select any red element and increase its value by $$$1$$$. Situations in which there are no elements of some color at all are also possible. For example, if the whole array is colored blue or red, one of the operations becomes unavailable.Determine whether it is possible to make $$$0$$$ or more steps such that the resulting array is a permutation of numbers from $$$1$$$ to $$$n$$$?In other words, check whether there exists a sequence of steps (possibly empty) such that after applying it, the array $$$a$$$ contains in some order all numbers from $$$1$$$ to $$$n$$$ (inclusive), each exactly once.
256 megabytes
import java.util.*; import java.io.*; // THIS TEMPLATE MADE BY AKSH BANSAL. public class Solution { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } static void sort(int a[]){ // int -> long ArrayList<Integer> arr=new ArrayList<>(); // Integer -> Long for(int i=0;i<a.length;i++) arr.add(a[i]); Collections.sort(arr); for(int i=0;i<a.length;i++) a[i]=arr.get(i); } private static long gcd(long a, long b){ if(b==0)return a; return gcd(b,a%b); } private static long pow(long x,long y){ if(y==0)return 1; long temp = pow(x, y/2); if(y%2==1){ return x*temp*temp; } else{ return temp*temp; } } static int log(long n){ int res = 0; while(n>0){ res++; n/=2; } return res; } static int mod = (int)1e9+7; static PrintWriter out; static FastReader sc ; public static void main(String[] args) throws IOException { sc = new FastReader(); out = new PrintWriter(System.out); // primes(); // ________________________________ int test = sc.nextInt(); StringBuilder output = new StringBuilder(); while (test-- > 0) { int n= sc.nextInt(); long[][]arr =new long[n][2]; for(int i=0;i<n;i++){ arr[i][0] = sc.nextInt(); } String s = sc.nextLine(); for(int i=0;i<n;i++){ arr[i][1] = s.charAt(i)=='B'?-1:1; } output.append(solver(arr, n)).append("\n"); } out.println(output); // _______________________________ // int n = sc.nextInt(); // out.println(solver()); // ________________________________ out.flush(); } public static String solver(long[][] arr, int n) { Arrays.sort(arr, (a,b)->a[1]==b[1]?(int)(a[0]-b[0]):(int)(a[1]-b[1])); for(int i=0;i<n;i++){ if(arr[i][1]<0 && arr[i][0]<i+1){ return "NO"; } else if(arr[i][1]>0 && arr[i][0]>i+1){ return "NO"; } } return "YES"; } }
Java
["8\n4\n1 2 5 2\nBRBR\n2\n1 1\nBB\n5\n3 1 4 2 5\nRBRRB\n5\n3 1 3 1 3\nRBRRB\n5\n5 1 5 1 5\nRBRRB\n4\n2 2 2 2\nBRBR\n2\n1 -2\nBR\n4\n-2 -1 4 0\nRRRR"]
1 second
["YES\nNO\nYES\nYES\nNO\nYES\nYES\nYES"]
NoteIn the first test case of the example, the following sequence of moves can be performed: choose $$$i=3$$$, element $$$a_3=5$$$ is blue, so we decrease it, we get $$$a=[1,2,4,2]$$$; choose $$$i=2$$$, element $$$a_2=2$$$ is red, so we increase it, we get $$$a=[1,3,4,2]$$$; choose $$$i=3$$$, element $$$a_3=4$$$ is blue, so we decrease it, we get $$$a=[1,3,3,2]$$$; choose $$$i=2$$$, element $$$a_2=2$$$ is red, so we increase it, we get $$$a=[1,4,3,2]$$$. We got that $$$a$$$ is a permutation. Hence the answer is YES.
Java 11
standard input
[ "greedy", "math", "sortings" ]
c3df88e22a17492d4eb0f3239a27d404
The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of input data sets in the test. The description of each set of input data consists of three lines. The first line contains an integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$) — the length of the original array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$-10^9 \leq a_i \leq 10^9$$$) — the array elements themselves. The third line has length $$$n$$$ and consists exclusively of the letters 'B' and/or 'R': $$$i$$$th character is 'B' if $$$a_i$$$ is colored blue, and is 'R' if colored red. It is guaranteed that the sum of $$$n$$$ over all input sets does not exceed $$$2 \cdot 10^5$$$.
1,300
Print $$$t$$$ lines, each of which contains the answer to the corresponding test case of the input. Print YES as an answer if the corresponding array can be transformed into a permutation, and NO otherwise. You can print the answer in any case (for example, the strings yEs, yes, Yes, and YES will be recognized as a positive answer).
standard output
PASSED
b5e775396c1df436eab54c5e0df7d1b0
train_108.jsonl
1635863700
You are given an array of integers $$$a$$$ of length $$$n$$$. The elements of the array can be either different or the same. Each element of the array is colored either blue or red. There are no unpainted elements in the array. One of the two operations described below can be applied to an array in a single step: either you can select any blue element and decrease its value by $$$1$$$; or you can select any red element and increase its value by $$$1$$$. Situations in which there are no elements of some color at all are also possible. For example, if the whole array is colored blue or red, one of the operations becomes unavailable.Determine whether it is possible to make $$$0$$$ or more steps such that the resulting array is a permutation of numbers from $$$1$$$ to $$$n$$$?In other words, check whether there exists a sequence of steps (possibly empty) such that after applying it, the array $$$a$$$ contains in some order all numbers from $$$1$$$ to $$$n$$$ (inclusive), each exactly once.
256 megabytes
import java.util.*; import java.io.*; public class BlueRedPermutation { 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) { int t=in.nextInt(); while(t-->0) { int n=in.nextInt(); int a[]=new int[n]; for(int i=0;i<n;i++) { a[i]=in.nextInt(); } String s=in.nextLine(); ArrayList<Integer> b=new ArrayList<Integer>(); ArrayList<Integer> r=new ArrayList<Integer>(); for(int i=0;i<n;i++) { if(s.charAt(i)=='B') { b.add(a[i]); } else{ r.add(a[i]); } } Collections.sort(b); Collections.sort(r); int c=1; boolean flag=true; for(int i=0;i<b.size();i++) { if(b.get(i)<c) { flag=false; break; } c++; } if(flag) { for(int i=0;i<r.size();i++) { if(r.get(i)>c) { flag=false; break; } c++; } } System.out.println(flag==true?"YES":"NO"); } } static void swap(int[] a, int i, int j) { int temp = a[i]; a[i] = a[j]; a[j] = temp; } 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.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 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
["8\n4\n1 2 5 2\nBRBR\n2\n1 1\nBB\n5\n3 1 4 2 5\nRBRRB\n5\n3 1 3 1 3\nRBRRB\n5\n5 1 5 1 5\nRBRRB\n4\n2 2 2 2\nBRBR\n2\n1 -2\nBR\n4\n-2 -1 4 0\nRRRR"]
1 second
["YES\nNO\nYES\nYES\nNO\nYES\nYES\nYES"]
NoteIn the first test case of the example, the following sequence of moves can be performed: choose $$$i=3$$$, element $$$a_3=5$$$ is blue, so we decrease it, we get $$$a=[1,2,4,2]$$$; choose $$$i=2$$$, element $$$a_2=2$$$ is red, so we increase it, we get $$$a=[1,3,4,2]$$$; choose $$$i=3$$$, element $$$a_3=4$$$ is blue, so we decrease it, we get $$$a=[1,3,3,2]$$$; choose $$$i=2$$$, element $$$a_2=2$$$ is red, so we increase it, we get $$$a=[1,4,3,2]$$$. We got that $$$a$$$ is a permutation. Hence the answer is YES.
Java 11
standard input
[ "greedy", "math", "sortings" ]
c3df88e22a17492d4eb0f3239a27d404
The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of input data sets in the test. The description of each set of input data consists of three lines. The first line contains an integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$) — the length of the original array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$-10^9 \leq a_i \leq 10^9$$$) — the array elements themselves. The third line has length $$$n$$$ and consists exclusively of the letters 'B' and/or 'R': $$$i$$$th character is 'B' if $$$a_i$$$ is colored blue, and is 'R' if colored red. It is guaranteed that the sum of $$$n$$$ over all input sets does not exceed $$$2 \cdot 10^5$$$.
1,300
Print $$$t$$$ lines, each of which contains the answer to the corresponding test case of the input. Print YES as an answer if the corresponding array can be transformed into a permutation, and NO otherwise. You can print the answer in any case (for example, the strings yEs, yes, Yes, and YES will be recognized as a positive answer).
standard output
PASSED
a4ffd6c5e2826476d505639eb6847cac
train_108.jsonl
1635863700
You are given an array of integers $$$a$$$ of length $$$n$$$. The elements of the array can be either different or the same. Each element of the array is colored either blue or red. There are no unpainted elements in the array. One of the two operations described below can be applied to an array in a single step: either you can select any blue element and decrease its value by $$$1$$$; or you can select any red element and increase its value by $$$1$$$. Situations in which there are no elements of some color at all are also possible. For example, if the whole array is colored blue or red, one of the operations becomes unavailable.Determine whether it is possible to make $$$0$$$ or more steps such that the resulting array is a permutation of numbers from $$$1$$$ to $$$n$$$?In other words, check whether there exists a sequence of steps (possibly empty) such that after applying it, the array $$$a$$$ contains in some order all numbers from $$$1$$$ to $$$n$$$ (inclusive), each exactly once.
256 megabytes
//jai Shree Krishna import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.util.Collections; import java.util.Comparator; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.OutputStreamWriter; import java.util.ArrayList; import java.util.StringTokenizer; public class C{ // author: Tarun Verma static FastScanner sc = new FastScanner(); static int inf = Integer.MAX_VALUE; static long mod = 1000000007; static BufferedWriter output = new BufferedWriter( new OutputStreamWriter(System.out)); static PrintWriter out=new PrintWriter(System.out); /* Common Mistakes By Me * make sure to read the bottom part of question * special cases (n=1?) * In Game Theory Check your solution and consider all the solutions * Always initialise value to the declare array in local scope * don't use debugs in interactive problems * Always Reset vis,adj array upto n+1 otherwise can cause TLE */ static Comparator<pair> comp = new Comparator<pair>() { @Override public int compare(pair o1, pair o2) { if(o1.fr == o2.fr) { return o1.sc - o2.sc; } return o1.fr - o2.fr; } }; public static void solve() { int n = sc.nextInt(); int arr[] =sc.readArray(n); String s = sc.next(); for(int i= 0;i<n;i++) { if(arr[i] < 1 && s.charAt(i) == 'B') { System.out.println("NO"); return; } if(arr[i] > n && s.charAt(i) == 'R') { System.out.println("NO"); return; } } ArrayList<pair> a = new ArrayList<>(); for(int i =0;i<n;i++) { if(s.charAt(i) == 'B') { a.add(new pair(1, min(n, arr[i]))); } else { a.add(new pair(max(arr[i], 1), n)); } } Collections.sort(a, comp); // for(pair i: a) { // System.out.println(i.fr + " " + i.sc); // } int k = 1; for(pair i: a) { if(i.fr > k || i.sc < k ) { System.out.println("NO"); return; } k++; } System.out.println("YES"); } public static void main(String[] args) { int t = 1; t = sc.nextInt(); outer: for (int tt = 0; tt < t; tt++) { solve(); } } //////////////////////////////////////////////////////////////////////////////////// ////////////////////DO NOT BELOW THIS LINE ////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////// static int max(int a, int b) { return Math.max(a, b);} static int min(int a, int b) {return Math.min(a, b);} static long max(long a, long b){return Math.max(a, b);} static long min(long a, long b) {return Math.min(a, b);} static void sort(int arr[]) { ArrayList<Integer> a = new ArrayList<Integer>(); for(int i: arr) a.add(i); Collections.sort(a); for(int i=0;i<arr.length;i++) arr[i] = a.get(i); } static void sort(long arr[]) { ArrayList<Long> a = new ArrayList<Long>(); for(long i: arr) a.add(i); Collections.sort(a); for(int i=0;i<arr.length;i++) arr[i] = a.get(i); } static int abs(int a) {return Math.abs(a);} static long abs(long a) {return Math.abs(a);} static int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } static class FastScanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } long[] readLongArray(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } int[][] read2dArray(int n, int m) { int arr[][] = new int[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { arr[i][j] = nextInt(); } } return arr; } ArrayList<Integer> readArrayList(int n) { ArrayList<Integer> arr = new ArrayList<Integer>(); for (int i = 0; i < n; i++) { int a = nextInt(); arr.add(a); } return arr; } long nextLong() { return Long.parseLong(next()); } } static class pair { int fr, sc; pair(int fr, int sc) { this.fr = fr; this.sc = sc; } } //////////////////////////////////////////////////////////////////////////////////// }
Java
["8\n4\n1 2 5 2\nBRBR\n2\n1 1\nBB\n5\n3 1 4 2 5\nRBRRB\n5\n3 1 3 1 3\nRBRRB\n5\n5 1 5 1 5\nRBRRB\n4\n2 2 2 2\nBRBR\n2\n1 -2\nBR\n4\n-2 -1 4 0\nRRRR"]
1 second
["YES\nNO\nYES\nYES\nNO\nYES\nYES\nYES"]
NoteIn the first test case of the example, the following sequence of moves can be performed: choose $$$i=3$$$, element $$$a_3=5$$$ is blue, so we decrease it, we get $$$a=[1,2,4,2]$$$; choose $$$i=2$$$, element $$$a_2=2$$$ is red, so we increase it, we get $$$a=[1,3,4,2]$$$; choose $$$i=3$$$, element $$$a_3=4$$$ is blue, so we decrease it, we get $$$a=[1,3,3,2]$$$; choose $$$i=2$$$, element $$$a_2=2$$$ is red, so we increase it, we get $$$a=[1,4,3,2]$$$. We got that $$$a$$$ is a permutation. Hence the answer is YES.
Java 11
standard input
[ "greedy", "math", "sortings" ]
c3df88e22a17492d4eb0f3239a27d404
The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of input data sets in the test. The description of each set of input data consists of three lines. The first line contains an integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$) — the length of the original array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$-10^9 \leq a_i \leq 10^9$$$) — the array elements themselves. The third line has length $$$n$$$ and consists exclusively of the letters 'B' and/or 'R': $$$i$$$th character is 'B' if $$$a_i$$$ is colored blue, and is 'R' if colored red. It is guaranteed that the sum of $$$n$$$ over all input sets does not exceed $$$2 \cdot 10^5$$$.
1,300
Print $$$t$$$ lines, each of which contains the answer to the corresponding test case of the input. Print YES as an answer if the corresponding array can be transformed into a permutation, and NO otherwise. You can print the answer in any case (for example, the strings yEs, yes, Yes, and YES will be recognized as a positive answer).
standard output
PASSED
098403ce040af164dd0a361fa7f09f01
train_108.jsonl
1635863700
You are given an array of integers $$$a$$$ of length $$$n$$$. The elements of the array can be either different or the same. Each element of the array is colored either blue or red. There are no unpainted elements in the array. One of the two operations described below can be applied to an array in a single step: either you can select any blue element and decrease its value by $$$1$$$; or you can select any red element and increase its value by $$$1$$$. Situations in which there are no elements of some color at all are also possible. For example, if the whole array is colored blue or red, one of the operations becomes unavailable.Determine whether it is possible to make $$$0$$$ or more steps such that the resulting array is a permutation of numbers from $$$1$$$ to $$$n$$$?In other words, check whether there exists a sequence of steps (possibly empty) such that after applying it, the array $$$a$$$ contains in some order all numbers from $$$1$$$ to $$$n$$$ (inclusive), each exactly once.
256 megabytes
//jai Shree Krishna import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.util.Collections; import java.util.Comparator; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.OutputStreamWriter; import java.util.ArrayList; import java.util.StringTokenizer; public class C{ // author: Tarun Verma static FastScanner sc = new FastScanner(); static int inf = Integer.MAX_VALUE; static long mod = 1000000007; static BufferedWriter output = new BufferedWriter( new OutputStreamWriter(System.out)); static PrintWriter out=new PrintWriter(System.out); /* Common Mistakes By Me * make sure to read the bottom part of question * special cases (n=1?) * In Game Theory Check your solution and consider all the solutions * Always initialise value to the declare array in local scope * don't use debugs in interactive problems * Always Reset vis,adj array upto n+1 otherwise can cause TLE */ public static void solve() { int n = sc.nextInt(); int arr[] =sc.readArray(n); String s = sc.next(); for(int i= 0;i<n;i++) { if(arr[i] < 1 && s.charAt(i) == 'B') { System.out.println("NO"); return; } if(arr[i] > n && s.charAt(i) == 'R') { System.out.println("NO"); return; } } ArrayList<pair> a = new ArrayList<>(); for(int i =0;i<n;i++) { if(s.charAt(i) == 'B') { a.add(new pair(1, min(n, arr[i]))); } else { a.add(new pair(max(arr[i], 1), n)); } } Collections.sort(a, new Comparator<pair>() { @Override public int compare(pair o1, pair o2) { if(o1.fr == o2.fr) { return o1.sc - o2.sc; } return o1.fr - o2.fr; } }); // for(pair i: a) { // System.out.println(i.fr + " " + i.sc); // } int k = 1; for(pair i: a) { if(i.fr > k || i.sc < k ) { System.out.println("NO"); return; } k++; } System.out.println("YES"); } public static void main(String[] args) { int t = 1; t = sc.nextInt(); outer: for (int tt = 0; tt < t; tt++) { solve(); } } //////////////////////////////////////////////////////////////////////////////////// ////////////////////DO NOT BELOW THIS LINE ////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////// static int max(int a, int b) { return Math.max(a, b);} static int min(int a, int b) {return Math.min(a, b);} static long max(long a, long b){return Math.max(a, b);} static long min(long a, long b) {return Math.min(a, b);} static void sort(int arr[]) { ArrayList<Integer> a = new ArrayList<Integer>(); for(int i: arr) a.add(i); Collections.sort(a); for(int i=0;i<arr.length;i++) arr[i] = a.get(i); } static void sort(long arr[]) { ArrayList<Long> a = new ArrayList<Long>(); for(long i: arr) a.add(i); Collections.sort(a); for(int i=0;i<arr.length;i++) arr[i] = a.get(i); } static int abs(int a) {return Math.abs(a);} static long abs(long a) {return Math.abs(a);} static int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } static class FastScanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } long[] readLongArray(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } int[][] read2dArray(int n, int m) { int arr[][] = new int[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { arr[i][j] = nextInt(); } } return arr; } ArrayList<Integer> readArrayList(int n) { ArrayList<Integer> arr = new ArrayList<Integer>(); for (int i = 0; i < n; i++) { int a = nextInt(); arr.add(a); } return arr; } long nextLong() { return Long.parseLong(next()); } } static class pair { int fr, sc; pair(int fr, int sc) { this.fr = fr; this.sc = sc; } } //////////////////////////////////////////////////////////////////////////////////// }
Java
["8\n4\n1 2 5 2\nBRBR\n2\n1 1\nBB\n5\n3 1 4 2 5\nRBRRB\n5\n3 1 3 1 3\nRBRRB\n5\n5 1 5 1 5\nRBRRB\n4\n2 2 2 2\nBRBR\n2\n1 -2\nBR\n4\n-2 -1 4 0\nRRRR"]
1 second
["YES\nNO\nYES\nYES\nNO\nYES\nYES\nYES"]
NoteIn the first test case of the example, the following sequence of moves can be performed: choose $$$i=3$$$, element $$$a_3=5$$$ is blue, so we decrease it, we get $$$a=[1,2,4,2]$$$; choose $$$i=2$$$, element $$$a_2=2$$$ is red, so we increase it, we get $$$a=[1,3,4,2]$$$; choose $$$i=3$$$, element $$$a_3=4$$$ is blue, so we decrease it, we get $$$a=[1,3,3,2]$$$; choose $$$i=2$$$, element $$$a_2=2$$$ is red, so we increase it, we get $$$a=[1,4,3,2]$$$. We got that $$$a$$$ is a permutation. Hence the answer is YES.
Java 11
standard input
[ "greedy", "math", "sortings" ]
c3df88e22a17492d4eb0f3239a27d404
The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of input data sets in the test. The description of each set of input data consists of three lines. The first line contains an integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$) — the length of the original array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$-10^9 \leq a_i \leq 10^9$$$) — the array elements themselves. The third line has length $$$n$$$ and consists exclusively of the letters 'B' and/or 'R': $$$i$$$th character is 'B' if $$$a_i$$$ is colored blue, and is 'R' if colored red. It is guaranteed that the sum of $$$n$$$ over all input sets does not exceed $$$2 \cdot 10^5$$$.
1,300
Print $$$t$$$ lines, each of which contains the answer to the corresponding test case of the input. Print YES as an answer if the corresponding array can be transformed into a permutation, and NO otherwise. You can print the answer in any case (for example, the strings yEs, yes, Yes, and YES will be recognized as a positive answer).
standard output
PASSED
e5b8939050522969e1c471014e9affe2
train_108.jsonl
1635863700
You are given an array of integers $$$a$$$ of length $$$n$$$. The elements of the array can be either different or the same. Each element of the array is colored either blue or red. There are no unpainted elements in the array. One of the two operations described below can be applied to an array in a single step: either you can select any blue element and decrease its value by $$$1$$$; or you can select any red element and increase its value by $$$1$$$. Situations in which there are no elements of some color at all are also possible. For example, if the whole array is colored blue or red, one of the operations becomes unavailable.Determine whether it is possible to make $$$0$$$ or more steps such that the resulting array is a permutation of numbers from $$$1$$$ to $$$n$$$?In other words, check whether there exists a sequence of steps (possibly empty) such that after applying it, the array $$$a$$$ contains in some order all numbers from $$$1$$$ to $$$n$$$ (inclusive), each exactly once.
256 megabytes
import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class Heat { public static void print(Object o) { System.out.println(o); } public static void print(String pattern, Object ...args) { System.out.println(String.format(pattern, args)); } public static void main(String[] args) throws java.io.IOException{ InputReader ir = new InputReader(); int caseNo = ir.nextInt(); for (int j = 0; j < caseNo; j++) { int l = ir.nextInt(); int[] nums = new int[l]; for (int i = 0; i < l; i++) { nums[i] = ir.nextInt(); } String s = ir.nextString(); int redNo = 0; int blueNo = 0; for (int i = 0; i < l;i++) { if (s.charAt(i) == 'R') { redNo++; } else { blueNo++; } } int[] sums = new int[l]; String result = "NOT_SET"; for (int i = 0; i < l;i++) { if (s.charAt(i) == 'R') { int pos = nums[i]; if (pos < blueNo + 1) { pos = blueNo + 1; } else if (pos > l) { result = "NO"; break; } sums[pos - 1] += 1; } else { int pos = nums[i]; if (pos > blueNo) { pos = blueNo; } else if (pos < 1) { result = "NO"; break; } sums[pos - 1] += 1; } } if (result.equals("NO")) { print(result); continue; } if (blueNo > 0 && sums[0] > 1) { print("NO"); continue; } if (redNo > 0 && sums[l - 1] > 1) { print("NO"); continue; } for (int i = 1; i < blueNo; i++) { //Convert to cumulative sum sums[i] = sums[i] + sums[i - 1]; //Check if cumulative sum < index if (sums[i] > i + 1) { result = "NO"; break; } } if (result.equals("NO")) { print(result); continue; } int counter = 2; for (int i = l - 2; i >= blueNo ; i--) { sums[i] = sums[i] + sums[i + 1]; //Check if cumulative sum < index if (sums[i] > counter++) { result = "NO"; break; } } if (result.equals("NO")) { print(result); continue; } print("YES"); // if 5 is red, no other 5 should exist //if 5 and 4 is red, other 4 and 5 should not exist } } } class InputReader { /** * The default size of the InputReader's buffer is 2<sup>16</sup>. */ private static final int DEFAULT_BUFFER_SIZE = 1 << 16; /** * The default stream for the InputReader is standard input. */ private static final InputStream DEFAULT_STREAM = System.in; /** * The maximum number of accurate decimal digits the method * {@link #nextDoubleFast() nextDoubleFast()} can read. Currently this value is * set to 21 because it is the maximum number of digits a double precision float * can have at the moment. */ private static final int MAX_DECIMAL_PRECISION = 21; // 'c' is used to refer to the current character in the stream private int c; // Variables associated with the byte buffer. private byte[] buf; private int bufferSize, bufIndex, numBytesRead; private InputStream stream; // End Of File (EOF) character private static final byte EOF = -1; // New line character: '\n' private static final byte NEW_LINE = 10; // Space character: ' ' private static final byte SPACE = 32; // Dash character: '-' private static final byte DASH = 45; // Dot character: '.' private static final byte DOT = 46; // A reusable character buffer when reading string data. private char[] charBuffer; // Primitive data type lookup tables used for optimizations private static byte[] bytes = new byte[58]; private static int[] ints = new int[58]; private static char[] chars = new char[128]; static { char ch = ' '; int value = 0; byte _byte = 0; for (int i = 48; i < 58; i++) bytes[i] = _byte++; for (int i = 48; i < 58; i++) ints[i] = value++; for (int i = 32; i < 128; i++) chars[i] = ch++; } // Primitive double lookup table used for optimizations. private static final double[][] doubles = { { 0.0d, 0.00d, 0.000d, 0.0000d, 0.00000d, 0.000000d, 0.0000000d, 0.00000000d, 0.000000000d, 0.0000000000d, 0.00000000000d, 0.000000000000d, 0.0000000000000d, 0.00000000000000d, 0.000000000000000d, 0.0000000000000000d, 0.00000000000000000d, 0.000000000000000000d, 0.0000000000000000000d, 0.00000000000000000000d, 0.000000000000000000000d }, { 0.1d, 0.01d, 0.001d, 0.0001d, 0.00001d, 0.000001d, 0.0000001d, 0.00000001d, 0.000000001d, 0.0000000001d, 0.00000000001d, 0.000000000001d, 0.0000000000001d, 0.00000000000001d, 0.000000000000001d, 0.0000000000000001d, 0.00000000000000001d, 0.000000000000000001d, 0.0000000000000000001d, 0.00000000000000000001d, 0.000000000000000000001d }, { 0.2d, 0.02d, 0.002d, 0.0002d, 0.00002d, 0.000002d, 0.0000002d, 0.00000002d, 0.000000002d, 0.0000000002d, 0.00000000002d, 0.000000000002d, 0.0000000000002d, 0.00000000000002d, 0.000000000000002d, 0.0000000000000002d, 0.00000000000000002d, 0.000000000000000002d, 0.0000000000000000002d, 0.00000000000000000002d, 0.000000000000000000002d }, { 0.3d, 0.03d, 0.003d, 0.0003d, 0.00003d, 0.000003d, 0.0000003d, 0.00000003d, 0.000000003d, 0.0000000003d, 0.00000000003d, 0.000000000003d, 0.0000000000003d, 0.00000000000003d, 0.000000000000003d, 0.0000000000000003d, 0.00000000000000003d, 0.000000000000000003d, 0.0000000000000000003d, 0.00000000000000000003d, 0.000000000000000000003d }, { 0.4d, 0.04d, 0.004d, 0.0004d, 0.00004d, 0.000004d, 0.0000004d, 0.00000004d, 0.000000004d, 0.0000000004d, 0.00000000004d, 0.000000000004d, 0.0000000000004d, 0.00000000000004d, 0.000000000000004d, 0.0000000000000004d, 0.00000000000000004d, 0.000000000000000004d, 0.0000000000000000004d, 0.00000000000000000004d, 0.000000000000000000004d }, { 0.5d, 0.05d, 0.005d, 0.0005d, 0.00005d, 0.000005d, 0.0000005d, 0.00000005d, 0.000000005d, 0.0000000005d, 0.00000000005d, 0.000000000005d, 0.0000000000005d, 0.00000000000005d, 0.000000000000005d, 0.0000000000000005d, 0.00000000000000005d, 0.000000000000000005d, 0.0000000000000000005d, 0.00000000000000000005d, 0.000000000000000000005d }, { 0.6d, 0.06d, 0.006d, 0.0006d, 0.00006d, 0.000006d, 0.0000006d, 0.00000006d, 0.000000006d, 0.0000000006d, 0.00000000006d, 0.000000000006d, 0.0000000000006d, 0.00000000000006d, 0.000000000000006d, 0.0000000000000006d, 0.00000000000000006d, 0.000000000000000006d, 0.0000000000000000006d, 0.00000000000000000006d, 0.000000000000000000006d }, { 0.7d, 0.07d, 0.007d, 0.0007d, 0.00007d, 0.000007d, 0.0000007d, 0.00000007d, 0.000000007d, 0.0000000007d, 0.00000000007d, 0.000000000007d, 0.0000000000007d, 0.00000000000007d, 0.000000000000007d, 0.0000000000000007d, 0.00000000000000007d, 0.000000000000000007d, 0.0000000000000000007d, 0.00000000000000000007d, 0.000000000000000000007d }, { 0.8d, 0.08d, 0.008d, 0.0008d, 0.00008d, 0.000008d, 0.0000008d, 0.00000008d, 0.000000008d, 0.0000000008d, 0.00000000008d, 0.000000000008d, 0.0000000000008d, 0.00000000000008d, 0.000000000000008d, 0.0000000000000008d, 0.00000000000000008d, 0.000000000000000008d, 0.0000000000000000008d, 0.00000000000000000008d, 0.000000000000000000008d }, { 0.9d, 0.09d, 0.009d, 0.0009d, 0.00009d, 0.000009d, 0.0000009d, 0.00000009d, 0.000000009d, 0.0000000009d, 0.00000000009d, 0.000000000009d, 0.0000000000009d, 0.00000000000009d, 0.000000000000009d, 0.0000000000000009d, 0.00000000000000009d, 0.000000000000000009d, 0.0000000000000000009d, 0.00000000000000000009d, 0.000000000000000000009d } }; /** * Create an InputReader that reads from standard input. */ public InputReader() { this(DEFAULT_STREAM, DEFAULT_BUFFER_SIZE); } /** * Create an InputReader that reads from standard input. * * @param bufferSize The buffer size for this input reader. */ public InputReader(int bufferSize) { this(DEFAULT_STREAM, bufferSize); } /** * Create an InputReader that reads from standard input. * * @param stream Takes an InputStream as a parameter to read from. */ public InputReader(InputStream stream) { this(stream, DEFAULT_BUFFER_SIZE); } /** * Create an InputReader that reads from standard input. * * @param stream Takes an {@link java.io.InputStream#InputStream() * InputStream} as a parameter to read from. * @param bufferSize The size of the buffer to use. */ public InputReader(InputStream stream, int bufferSize) { if (stream == null || bufferSize <= 0) throw new IllegalArgumentException(); buf = new byte[bufferSize]; charBuffer = new char[128]; this.bufferSize = bufferSize; this.stream = stream; } /** * Reads a single character from the input stream. * * @return Returns the byte value of the next character in the buffer and EOF at * the end of the stream. * @throws IOException throws exception if there is no more data to read */ private byte read() throws IOException { if (numBytesRead == EOF) throw new IOException(); if (bufIndex >= numBytesRead) { bufIndex = 0; numBytesRead = stream.read(buf); if (numBytesRead == EOF) return EOF; } return buf[bufIndex++]; } /** * Read values from the input stream until you reach a character with a higher * ASCII value than 'token'. * * @param token The token is a value which we use to stop reading junk out of * the stream. * @return Returns 0 if a value greater than the token was reached or -1 if the * end of the stream was reached. * @throws IOException Throws exception at end of stream. */ private int readJunk(int token) throws IOException { if (numBytesRead == EOF) return EOF; // Seek to the first valid position index do { while (bufIndex < numBytesRead) { if (buf[bufIndex] > token) return 0; bufIndex++; } // reload buffer numBytesRead = stream.read(buf); if (numBytesRead == EOF) return EOF; bufIndex = 0; } while (true); } /** * Reads a single byte from the input stream. * * @return The next byte in the input stream * @throws IOException Throws exception at end of stream. */ public byte nextByte() throws IOException { return (byte) nextInt(); } /** * Reads a 32 bit signed integer from input stream. * * @return The next integer value in the stream. * @throws IOException Throws exception at end of stream. */ public int nextInt() throws IOException { if (readJunk(DASH - 1) == EOF) throw new IOException(); int sgn = 1, res = 0; c = buf[bufIndex]; if (c == DASH) { sgn = -1; bufIndex++; } do { while (bufIndex < numBytesRead) { if (buf[bufIndex] > SPACE) { res = (res << 3) + (res << 1); res += ints[buf[bufIndex++]]; } else { bufIndex++; return res * sgn; } } // Reload buffer numBytesRead = stream.read(buf); if (numBytesRead == EOF) return res * sgn; bufIndex = 0; } while (true); } /** * Reads a 64 bit signed long from input stream. * * @return The next long value in the stream. * @throws IOException Throws exception at end of stream. */ public long nextLong() throws IOException { if (readJunk(DASH - 1) == EOF) throw new IOException(); int sgn = 1; long res = 0L; c = buf[bufIndex]; if (c == DASH) { sgn = -1; bufIndex++; } do { while (bufIndex < numBytesRead) { if (buf[bufIndex] > SPACE) { res = (res << 3) + (res << 1); res += ints[buf[bufIndex++]]; } else { bufIndex++; return res * sgn; } } // Reload buffer numBytesRead = stream.read(buf); if (numBytesRead == EOF) return res * sgn; bufIndex = 0; } while (true); } /** * Doubles the size of the internal char buffer for strings */ private void doubleCharBufferSize() { char[] newBuffer = new char[charBuffer.length << 1]; for (int i = 0; i < charBuffer.length; i++) newBuffer[i] = charBuffer[i]; charBuffer = newBuffer; } /** * Reads a line from the input stream. * * @return Returns a line from the input stream in the form a String not * including the new line character. Returns <code>null</code> when * there are no more lines. * @throws IOException Throws IOException when something terrible happens. */ public String nextLine() throws IOException { try { c = read(); } catch (IOException e) { return null; } if (c == NEW_LINE) return ""; // Empty line if (c == EOF) return null; // EOF int i = 0; charBuffer[i++] = (char) c; do { while (bufIndex < numBytesRead) { if (buf[bufIndex] != NEW_LINE) { if (i == charBuffer.length) doubleCharBufferSize(); charBuffer[i++] = (char) buf[bufIndex++]; } else { bufIndex++; return new String(charBuffer, 0, i); } } // Reload buffer numBytesRead = stream.read(buf); if (numBytesRead == EOF) return new String(charBuffer, 0, i); bufIndex = 0; } while (true); } // Reads a string of characters from the input stream. // The delimiter separating a string of characters is set to be: // any ASCII value <= 32 meaning any spaces, new lines, EOF, tabs... public String nextString() throws IOException { if (numBytesRead == EOF) return null; if (readJunk(SPACE) == EOF) return null; for (int i = 0;;) { while (bufIndex < numBytesRead) { if (buf[bufIndex] > SPACE) { if (i == charBuffer.length) doubleCharBufferSize(); charBuffer[i++] = (char) buf[bufIndex++]; } else { bufIndex++; return new String(charBuffer, 0, i); } } // Reload buffer numBytesRead = stream.read(buf); if (numBytesRead == EOF) return new String(charBuffer, 0, i); bufIndex = 0; } } // Returns an exact value a double value from the input stream. public double nextDouble() throws IOException { String doubleVal = nextString(); if (doubleVal == null) throw new IOException(); return Double.valueOf(doubleVal); } // Very quickly reads a double value from the input stream (~3x faster than // nextDouble()). However, // this method may provide a slightly less accurate reading than .nextDouble() // if there are a lot // of digits (~16+). In particular, it will only read double values with at most // 21 digits after // the decimal point and the reading my be as inaccurate as ~5*10^-16 from the // true value. public double nextDoubleFast() throws IOException { c = read(); int sgn = 1; while (c <= SPACE) c = read(); // while c is either: ' ', '\n', EOF if (c == DASH) { sgn = -1; c = read(); } double res = 0.0; // while c is not: ' ', '\n', '.' or -1 while (c > DOT) { res *= 10.0; res += ints[c]; c = read(); } if (c == DOT) { int i = 0; c = read(); // while c is digit and we are less than the maximum decimal precision while (c > SPACE && i < MAX_DECIMAL_PRECISION) { res += doubles[ints[c]][i++]; c = read(); } } return res * sgn; } // Read an array of n byte values public byte[] nextByteArray(int n) throws IOException { byte[] ar = new byte[n]; for (int i = 0; i < n; i++) ar[i] = nextByte(); return ar; } // Read an integer array of size n public int[] nextIntArray(int n) throws IOException { int[] ar = new int[n]; for (int i = 0; i < n; i++) ar[i] = nextInt(); return ar; } // Read a long array of size n public long[] nextLongArray(int n) throws IOException { long[] ar = new long[n]; for (int i = 0; i < n; i++) ar[i] = nextLong(); return ar; } // read an of doubles of size n public double[] nextDoubleArray(int n) throws IOException { double[] ar = new double[n]; for (int i = 0; i < n; i++) ar[i] = nextDouble(); return ar; } // Quickly read an array of doubles public double[] nextDoubleArrayFast(int n) throws IOException { double[] ar = new double[n]; for (int i = 0; i < n; i++) ar[i] = nextDoubleFast(); return ar; } // Read a string array of size n public String[] nextStringArray(int n) throws IOException { String[] ar = new String[n]; for (int i = 0; i < n; i++) { String str = nextString(); if (str == null) throw new IOException(); ar[i] = str; } return ar; } // Read a 1-based byte array of size n+1 public byte[] nextByteArray1(int n) throws IOException { byte[] ar = new byte[n + 1]; for (int i = 1; i <= n; i++) ar[i] = nextByte(); return ar; } // Read a 1-based integer array of size n+1 public int[] nextIntArray1(int n) throws IOException { int[] ar = new int[n + 1]; for (int i = 1; i <= n; i++) ar[i] = nextInt(); return ar; } // Read a 1-based long array of size n+1 public long[] nextLongArray1(int n) throws IOException { long[] ar = new long[n + 1]; for (int i = 1; i <= n; i++) ar[i] = nextLong(); return ar; } // Read a 1-based double array of size n+1 public double[] nextDoubleArray1(int n) throws IOException { double[] ar = new double[n + 1]; for (int i = 1; i <= n; i++) ar[i] = nextDouble(); return ar; } // Quickly read a 1-based double array of size n+1 public double[] nextDoubleArrayFast1(int n) throws IOException { double[] ar = new double[n + 1]; for (int i = 1; i <= n; i++) ar[i] = nextDoubleFast(); return ar; } // Read a 1-based string array of size n+1 public String[] nextStringArray1(int n) throws IOException { String[] ar = new String[n + 1]; for (int i = 1; i <= n; i++) ar[i] = nextString(); return ar; } // Read a two dimensional matrix of bytes of size rows x cols public byte[][] nextByteMatrix(int rows, int cols) throws IOException { byte[][] matrix = new byte[rows][cols]; for (int i = 0; i < rows; i++) for (int j = 0; j < cols; j++) matrix[i][j] = nextByte(); return matrix; } // Read a two dimensional matrix of ints of size rows x cols public int[][] nextIntMatrix(int rows, int cols) throws IOException { int[][] matrix = new int[rows][cols]; for (int i = 0; i < rows; i++) for (int j = 0; j < cols; j++) matrix[i][j] = nextInt(); return matrix; } // Read a two dimensional matrix of longs of size rows x cols public long[][] nextLongMatrix(int rows, int cols) throws IOException { long[][] matrix = new long[rows][cols]; for (int i = 0; i < rows; i++) for (int j = 0; j < cols; j++) matrix[i][j] = nextLong(); return matrix; } // Read a two dimensional matrix of doubles of size rows x cols public double[][] nextDoubleMatrix(int rows, int cols) throws IOException { double[][] matrix = new double[rows][cols]; for (int i = 0; i < rows; i++) for (int j = 0; j < cols; j++) matrix[i][j] = nextDouble(); return matrix; } // Quickly read a two dimensional matrix of doubles of size rows x cols public double[][] nextDoubleMatrixFast(int rows, int cols) throws IOException { double[][] matrix = new double[rows][cols]; for (int i = 0; i < rows; i++) for (int j = 0; j < cols; j++) matrix[i][j] = nextDoubleFast(); return matrix; } // Read a two dimensional matrix of Strings of size rows x cols public String[][] nextStringMatrix(int rows, int cols) throws IOException { String[][] matrix = new String[rows][cols]; for (int i = 0; i < rows; i++) for (int j = 0; j < cols; j++) matrix[i][j] = nextString(); return matrix; } // Read a 1-based two dimensional matrix of bytes of size rows x cols public byte[][] nextByteMatrix1(int rows, int cols) throws IOException { byte[][] matrix = new byte[rows + 1][cols + 1]; for (int i = 1; i <= rows; i++) for (int j = 1; j <= cols; j++) matrix[i][j] = nextByte(); return matrix; } // Read a 1-based two dimensional matrix of ints of size rows x cols public int[][] nextIntMatrix1(int rows, int cols) throws IOException { int[][] matrix = new int[rows + 1][cols + 1]; for (int i = 1; i <= rows; i++) for (int j = 1; j <= cols; j++) matrix[i][j] = nextInt(); return matrix; } // Read a 1-based two dimensional matrix of longs of size rows x cols public long[][] nextLongMatrix1(int rows, int cols) throws IOException { long[][] matrix = new long[rows + 1][cols + 1]; for (int i = 1; i <= rows; i++) for (int j = 1; j <= cols; j++) matrix[i][j] = nextLong(); return matrix; } // Read a 1-based two dimensional matrix of doubles of size rows x cols public double[][] nextDoubleMatrix1(int rows, int cols) throws IOException { double[][] matrix = new double[rows + 1][cols + 1]; for (int i = 1; i <= rows; i++) for (int j = 1; j <= cols; j++) matrix[i][j] = nextDouble(); return matrix; } // Quickly read a 1-based two dimensional matrix of doubles of size rows x cols public double[][] nextDoubleMatrixFast1(int rows, int cols) throws IOException { double[][] matrix = new double[rows + 1][cols + 1]; for (int i = 1; i <= rows; i++) for (int j = 1; j <= cols; j++) matrix[i][j] = nextDoubleFast(); return matrix; } // Read a 1-based two dimensional matrix of Strings of size rows x cols public String[][] nextStringMatrix1(int rows, int cols) throws IOException { String[][] matrix = new String[rows + 1][cols + 1]; for (int i = 1; i <= rows; i++) for (int j = 1; j <= cols; j++) matrix[i][j] = nextString(); return matrix; } // Closes the input stream public void close() throws IOException { stream.close(); } }
Java
["8\n4\n1 2 5 2\nBRBR\n2\n1 1\nBB\n5\n3 1 4 2 5\nRBRRB\n5\n3 1 3 1 3\nRBRRB\n5\n5 1 5 1 5\nRBRRB\n4\n2 2 2 2\nBRBR\n2\n1 -2\nBR\n4\n-2 -1 4 0\nRRRR"]
1 second
["YES\nNO\nYES\nYES\nNO\nYES\nYES\nYES"]
NoteIn the first test case of the example, the following sequence of moves can be performed: choose $$$i=3$$$, element $$$a_3=5$$$ is blue, so we decrease it, we get $$$a=[1,2,4,2]$$$; choose $$$i=2$$$, element $$$a_2=2$$$ is red, so we increase it, we get $$$a=[1,3,4,2]$$$; choose $$$i=3$$$, element $$$a_3=4$$$ is blue, so we decrease it, we get $$$a=[1,3,3,2]$$$; choose $$$i=2$$$, element $$$a_2=2$$$ is red, so we increase it, we get $$$a=[1,4,3,2]$$$. We got that $$$a$$$ is a permutation. Hence the answer is YES.
Java 11
standard input
[ "greedy", "math", "sortings" ]
c3df88e22a17492d4eb0f3239a27d404
The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of input data sets in the test. The description of each set of input data consists of three lines. The first line contains an integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$) — the length of the original array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$-10^9 \leq a_i \leq 10^9$$$) — the array elements themselves. The third line has length $$$n$$$ and consists exclusively of the letters 'B' and/or 'R': $$$i$$$th character is 'B' if $$$a_i$$$ is colored blue, and is 'R' if colored red. It is guaranteed that the sum of $$$n$$$ over all input sets does not exceed $$$2 \cdot 10^5$$$.
1,300
Print $$$t$$$ lines, each of which contains the answer to the corresponding test case of the input. Print YES as an answer if the corresponding array can be transformed into a permutation, and NO otherwise. You can print the answer in any case (for example, the strings yEs, yes, Yes, and YES will be recognized as a positive answer).
standard output
PASSED
41a52c89c84699eb0298273595f9f959
train_108.jsonl
1635863700
You are given an array of integers $$$a$$$ of length $$$n$$$. The elements of the array can be either different or the same. Each element of the array is colored either blue or red. There are no unpainted elements in the array. One of the two operations described below can be applied to an array in a single step: either you can select any blue element and decrease its value by $$$1$$$; or you can select any red element and increase its value by $$$1$$$. Situations in which there are no elements of some color at all are also possible. For example, if the whole array is colored blue or red, one of the operations becomes unavailable.Determine whether it is possible to make $$$0$$$ or more steps such that the resulting array is a permutation of numbers from $$$1$$$ to $$$n$$$?In other words, check whether there exists a sequence of steps (possibly empty) such that after applying it, the array $$$a$$$ contains in some order all numbers from $$$1$$$ to $$$n$$$ (inclusive), each exactly once.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.Comparator; import java.util.Random; import java.util.StringTokenizer; public class A339 { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } public static void main(String[] args) { FastReader sc = new FastReader(); 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(); } String s = sc.next(); System.out.println(solve(arr, s, n)); t--; } } private static String solve(int[] arr, String s, int n) { int[][] test = new int[n][2]; for (int i = 0; i < n; i++) { test[i][0] = arr[i]; if (s.charAt(i) == 'R') { test[i][1] = 1; } else { test[i][1] = -1; } } Arrays.sort(test, new Comparator<int[]>() { @Override public int compare(int[] a, int[] b) { if (a[1] == b[1] && a[0] > b[0]) return 1; else if (a[1] == b[1] && a[0] < b[0]) return -1; return a[1] - b[1]; } }); for (int i = 0; i < n; i++) { if ((test[i][0] < i+1 && test[i][1] == -1) || (test[i][0] > i+1 && test[i][1] == 1)) return "NO"; } return "YES"; } }
Java
["8\n4\n1 2 5 2\nBRBR\n2\n1 1\nBB\n5\n3 1 4 2 5\nRBRRB\n5\n3 1 3 1 3\nRBRRB\n5\n5 1 5 1 5\nRBRRB\n4\n2 2 2 2\nBRBR\n2\n1 -2\nBR\n4\n-2 -1 4 0\nRRRR"]
1 second
["YES\nNO\nYES\nYES\nNO\nYES\nYES\nYES"]
NoteIn the first test case of the example, the following sequence of moves can be performed: choose $$$i=3$$$, element $$$a_3=5$$$ is blue, so we decrease it, we get $$$a=[1,2,4,2]$$$; choose $$$i=2$$$, element $$$a_2=2$$$ is red, so we increase it, we get $$$a=[1,3,4,2]$$$; choose $$$i=3$$$, element $$$a_3=4$$$ is blue, so we decrease it, we get $$$a=[1,3,3,2]$$$; choose $$$i=2$$$, element $$$a_2=2$$$ is red, so we increase it, we get $$$a=[1,4,3,2]$$$. We got that $$$a$$$ is a permutation. Hence the answer is YES.
Java 11
standard input
[ "greedy", "math", "sortings" ]
c3df88e22a17492d4eb0f3239a27d404
The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of input data sets in the test. The description of each set of input data consists of three lines. The first line contains an integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$) — the length of the original array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$-10^9 \leq a_i \leq 10^9$$$) — the array elements themselves. The third line has length $$$n$$$ and consists exclusively of the letters 'B' and/or 'R': $$$i$$$th character is 'B' if $$$a_i$$$ is colored blue, and is 'R' if colored red. It is guaranteed that the sum of $$$n$$$ over all input sets does not exceed $$$2 \cdot 10^5$$$.
1,300
Print $$$t$$$ lines, each of which contains the answer to the corresponding test case of the input. Print YES as an answer if the corresponding array can be transformed into a permutation, and NO otherwise. You can print the answer in any case (for example, the strings yEs, yes, Yes, and YES will be recognized as a positive answer).
standard output
PASSED
4a632f4f19467b2e2e3c8a7bdd517549
train_108.jsonl
1635863700
You are given an array of integers $$$a$$$ of length $$$n$$$. The elements of the array can be either different or the same. Each element of the array is colored either blue or red. There are no unpainted elements in the array. One of the two operations described below can be applied to an array in a single step: either you can select any blue element and decrease its value by $$$1$$$; or you can select any red element and increase its value by $$$1$$$. Situations in which there are no elements of some color at all are also possible. For example, if the whole array is colored blue or red, one of the operations becomes unavailable.Determine whether it is possible to make $$$0$$$ or more steps such that the resulting array is a permutation of numbers from $$$1$$$ to $$$n$$$?In other words, check whether there exists a sequence of steps (possibly empty) such that after applying it, the array $$$a$$$ contains in some order all numbers from $$$1$$$ to $$$n$$$ (inclusive), each exactly once.
256 megabytes
import java.io.*; import java.util.*; public class BlueRedPermutation { public static void main(String args[]) throws IOException { FastReader sc = new FastReader(); PrintWriter out = new PrintWriter(System.out); int tc, i, j; String s; char p; tc = sc.nextInt(); while (tc-- > 0) { int n = sc.nextInt(); int temp[] = sc.readArray(n); s = sc.nextLine(); char temp2[] = s.toCharArray(); int countblue=0; for (i = 0; i < n; i++) if (temp2[i]=='B') countblue++; Pair arr[] = new Pair[n]; for (i = 0; i < n; i++) arr[i] = new Pair(temp[i], temp2[i]); Arrays.sort(arr); Arrays.sort(arr,(a,b)->a.y-b.y); boolean flag=true; for (i = 0; i < countblue; i++) { if(arr[i].x<(i+1)) { flag = false; break; } } if (flag) { for (i = countblue; i < n; i++) { if (arr[i].x > (i + 1)) { flag = false; break; } } } if (flag) out.println("YES"); else out.println("NO"); // for (Pair pr:arr) // out.print(pr.x+" "); // out.println(); } out.close(); } /*-------------------------------------------------------- ----------------------------------------------------------*/ //Pair Class public static class Pair implements Comparable<Pair> { int x; char y; Pair(int x, char y) { this.x = x; this.y = y; } @Override public int compareTo(Pair o) { return this.x - o.x; } } /* FASTREADER */ 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; } /*DEFINED BY ME*/ //READING ARRAY int[] readArray(int n) { int arr[] = new int[n]; for (int i = 0; i < n; i++) arr[i] = nextInt(); return arr; } //COLLECTIONS SORT void sort(int arr[]) { ArrayList<Integer> l = new ArrayList<>(); for (int i : arr) l.add(i); Collections.sort(l); for (int i = 0; i < arr.length; i++) arr[i] = l.get(i); } //EUCLID'S GCD int gcd(int a, int b) { if (b != 0) return gcd(b, a % b); else return a; } void swap(int arr[], int i, int j) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } }
Java
["8\n4\n1 2 5 2\nBRBR\n2\n1 1\nBB\n5\n3 1 4 2 5\nRBRRB\n5\n3 1 3 1 3\nRBRRB\n5\n5 1 5 1 5\nRBRRB\n4\n2 2 2 2\nBRBR\n2\n1 -2\nBR\n4\n-2 -1 4 0\nRRRR"]
1 second
["YES\nNO\nYES\nYES\nNO\nYES\nYES\nYES"]
NoteIn the first test case of the example, the following sequence of moves can be performed: choose $$$i=3$$$, element $$$a_3=5$$$ is blue, so we decrease it, we get $$$a=[1,2,4,2]$$$; choose $$$i=2$$$, element $$$a_2=2$$$ is red, so we increase it, we get $$$a=[1,3,4,2]$$$; choose $$$i=3$$$, element $$$a_3=4$$$ is blue, so we decrease it, we get $$$a=[1,3,3,2]$$$; choose $$$i=2$$$, element $$$a_2=2$$$ is red, so we increase it, we get $$$a=[1,4,3,2]$$$. We got that $$$a$$$ is a permutation. Hence the answer is YES.
Java 11
standard input
[ "greedy", "math", "sortings" ]
c3df88e22a17492d4eb0f3239a27d404
The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of input data sets in the test. The description of each set of input data consists of three lines. The first line contains an integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$) — the length of the original array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$-10^9 \leq a_i \leq 10^9$$$) — the array elements themselves. The third line has length $$$n$$$ and consists exclusively of the letters 'B' and/or 'R': $$$i$$$th character is 'B' if $$$a_i$$$ is colored blue, and is 'R' if colored red. It is guaranteed that the sum of $$$n$$$ over all input sets does not exceed $$$2 \cdot 10^5$$$.
1,300
Print $$$t$$$ lines, each of which contains the answer to the corresponding test case of the input. Print YES as an answer if the corresponding array can be transformed into a permutation, and NO otherwise. You can print the answer in any case (for example, the strings yEs, yes, Yes, and YES will be recognized as a positive answer).
standard output
PASSED
a77e2d0119ff8d6011a92811f3e77b8f
train_108.jsonl
1635863700
You are given an array of integers $$$a$$$ of length $$$n$$$. The elements of the array can be either different or the same. Each element of the array is colored either blue or red. There are no unpainted elements in the array. One of the two operations described below can be applied to an array in a single step: either you can select any blue element and decrease its value by $$$1$$$; or you can select any red element and increase its value by $$$1$$$. Situations in which there are no elements of some color at all are also possible. For example, if the whole array is colored blue or red, one of the operations becomes unavailable.Determine whether it is possible to make $$$0$$$ or more steps such that the resulting array is a permutation of numbers from $$$1$$$ to $$$n$$$?In other words, check whether there exists a sequence of steps (possibly empty) such that after applying it, the array $$$a$$$ contains in some order all numbers from $$$1$$$ to $$$n$$$ (inclusive), each exactly once.
256 megabytes
import java.util.*; import java.lang.*; import java.math.BigInteger; import java.io.*; public class snackDown3 { public static class FastReader { BufferedReader b; StringTokenizer s; public FastReader() { b=new BufferedReader(new InputStreamReader(System.in)); } String next() { while(s==null ||!s.hasMoreElements()) { try { s=new StringTokenizer(b.readLine()); } catch(IOException e) { e.printStackTrace(); } } return s.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str=""; try { str=b.readLine(); } catch(IOException e) { e.printStackTrace(); } return str; } boolean hasNext() { if (s != null && s.hasMoreTokens()) { return true; } String tmp; try { b.mark(1000); tmp = b.readLine(); if (tmp == null) { return false; } b.reset(); } catch (IOException e) { return false; } return true; } } public static class pair{ int a; char b; public pair(int aa,char bb) { a=aa; b=bb; } int compareTo(pair b) { if(this.b==b.b)return this.a-b.a; return this.b-b.b; } int comapreToo(pair b) { return this.a-b.a; } } public static void main (String[] args) throws Exception { // your code goes here FastReader sc=new FastReader(); BufferedWriter log = new BufferedWriter(new OutputStreamWriter(System.out)); 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(); } char s[]=sc.next().toCharArray(); ArrayList<pair> ar=new ArrayList<>(); for(int i=0;i<n;i++) { ar.add(new pair(a[i],s[i])); } Collections.sort(ar,(o1,o2)->o1.compareTo(o2)); boolean ans=true; for(int i=1;i<=n;i++) { if(ar.get(i-1).b=='B' && ar.get(i-1).a<i) { ans=false; break; } else if(ar.get(i-1).b=='R' && ar.get(i-1).a>i) { ans=false; break; } } if(ans)log.write("YES"); else log.write("NO"); log.write("\n"); log.flush(); } } }
Java
["8\n4\n1 2 5 2\nBRBR\n2\n1 1\nBB\n5\n3 1 4 2 5\nRBRRB\n5\n3 1 3 1 3\nRBRRB\n5\n5 1 5 1 5\nRBRRB\n4\n2 2 2 2\nBRBR\n2\n1 -2\nBR\n4\n-2 -1 4 0\nRRRR"]
1 second
["YES\nNO\nYES\nYES\nNO\nYES\nYES\nYES"]
NoteIn the first test case of the example, the following sequence of moves can be performed: choose $$$i=3$$$, element $$$a_3=5$$$ is blue, so we decrease it, we get $$$a=[1,2,4,2]$$$; choose $$$i=2$$$, element $$$a_2=2$$$ is red, so we increase it, we get $$$a=[1,3,4,2]$$$; choose $$$i=3$$$, element $$$a_3=4$$$ is blue, so we decrease it, we get $$$a=[1,3,3,2]$$$; choose $$$i=2$$$, element $$$a_2=2$$$ is red, so we increase it, we get $$$a=[1,4,3,2]$$$. We got that $$$a$$$ is a permutation. Hence the answer is YES.
Java 11
standard input
[ "greedy", "math", "sortings" ]
c3df88e22a17492d4eb0f3239a27d404
The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of input data sets in the test. The description of each set of input data consists of three lines. The first line contains an integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$) — the length of the original array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$-10^9 \leq a_i \leq 10^9$$$) — the array elements themselves. The third line has length $$$n$$$ and consists exclusively of the letters 'B' and/or 'R': $$$i$$$th character is 'B' if $$$a_i$$$ is colored blue, and is 'R' if colored red. It is guaranteed that the sum of $$$n$$$ over all input sets does not exceed $$$2 \cdot 10^5$$$.
1,300
Print $$$t$$$ lines, each of which contains the answer to the corresponding test case of the input. Print YES as an answer if the corresponding array can be transformed into a permutation, and NO otherwise. You can print the answer in any case (for example, the strings yEs, yes, Yes, and YES will be recognized as a positive answer).
standard output
PASSED
f8fbf213da4fb2b68707c94987e367ad
train_108.jsonl
1635863700
You are given an array of integers $$$a$$$ of length $$$n$$$. The elements of the array can be either different or the same. Each element of the array is colored either blue or red. There are no unpainted elements in the array. One of the two operations described below can be applied to an array in a single step: either you can select any blue element and decrease its value by $$$1$$$; or you can select any red element and increase its value by $$$1$$$. Situations in which there are no elements of some color at all are also possible. For example, if the whole array is colored blue or red, one of the operations becomes unavailable.Determine whether it is possible to make $$$0$$$ or more steps such that the resulting array is a permutation of numbers from $$$1$$$ to $$$n$$$?In other words, check whether there exists a sequence of steps (possibly empty) such that after applying it, the array $$$a$$$ contains in some order all numbers from $$$1$$$ to $$$n$$$ (inclusive), each exactly once.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class Solution { private static final FastScanner fs = new FastScanner(); public static void main(String[] args) { int testCase = fs.nextInt(); for (int i = 1; i <= testCase; i++) { solve(); } } public static void solve() { int n = fs.nextInt(); long[] arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = fs.nextLong(); } String clr = fs.next(); List<Long> blue = new ArrayList<>(); List<Long> red = new ArrayList<>(); for (int i = 0; i < clr.length(); i++) { if (clr.charAt(i) == 'B') blue.add(arr[i]); else red.add(arr[i]); } Collections.sort(blue); Collections.sort(red); int currentValue = 1; int redIndex = 0; int blueIndex = 0; boolean found = true; while (redIndex < red.size() && blueIndex < blue.size() && currentValue <= n) { long blueWala = blue.get(blueIndex); long redWala = red.get(redIndex); if (blueWala >= currentValue) blueIndex++; else if (redWala <= currentValue) redIndex++; else { found = false; break; } currentValue++; } while (redIndex < red.size() && currentValue <= n) { long redWala = red.get(redIndex); if (redWala <= currentValue) redIndex++; else { found = false; break; } currentValue++; } while (blueIndex < blue.size() && currentValue <= n) { long blueWala = blue.get(blueIndex); if (blueWala < currentValue) { found = false; break; } blueIndex++; currentValue++; } if (currentValue < n + 1) found = false; if (found) System.out.println("YES"); else System.out.println("NO"); } } class FastScanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } }
Java
["8\n4\n1 2 5 2\nBRBR\n2\n1 1\nBB\n5\n3 1 4 2 5\nRBRRB\n5\n3 1 3 1 3\nRBRRB\n5\n5 1 5 1 5\nRBRRB\n4\n2 2 2 2\nBRBR\n2\n1 -2\nBR\n4\n-2 -1 4 0\nRRRR"]
1 second
["YES\nNO\nYES\nYES\nNO\nYES\nYES\nYES"]
NoteIn the first test case of the example, the following sequence of moves can be performed: choose $$$i=3$$$, element $$$a_3=5$$$ is blue, so we decrease it, we get $$$a=[1,2,4,2]$$$; choose $$$i=2$$$, element $$$a_2=2$$$ is red, so we increase it, we get $$$a=[1,3,4,2]$$$; choose $$$i=3$$$, element $$$a_3=4$$$ is blue, so we decrease it, we get $$$a=[1,3,3,2]$$$; choose $$$i=2$$$, element $$$a_2=2$$$ is red, so we increase it, we get $$$a=[1,4,3,2]$$$. We got that $$$a$$$ is a permutation. Hence the answer is YES.
Java 11
standard input
[ "greedy", "math", "sortings" ]
c3df88e22a17492d4eb0f3239a27d404
The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of input data sets in the test. The description of each set of input data consists of three lines. The first line contains an integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$) — the length of the original array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$-10^9 \leq a_i \leq 10^9$$$) — the array elements themselves. The third line has length $$$n$$$ and consists exclusively of the letters 'B' and/or 'R': $$$i$$$th character is 'B' if $$$a_i$$$ is colored blue, and is 'R' if colored red. It is guaranteed that the sum of $$$n$$$ over all input sets does not exceed $$$2 \cdot 10^5$$$.
1,300
Print $$$t$$$ lines, each of which contains the answer to the corresponding test case of the input. Print YES as an answer if the corresponding array can be transformed into a permutation, and NO otherwise. You can print the answer in any case (for example, the strings yEs, yes, Yes, and YES will be recognized as a positive answer).
standard output
PASSED
32acaad07445e0da5f835e9a70f5639b
train_108.jsonl
1635863700
You are given an array of integers $$$a$$$ of length $$$n$$$. The elements of the array can be either different or the same. Each element of the array is colored either blue or red. There are no unpainted elements in the array. One of the two operations described below can be applied to an array in a single step: either you can select any blue element and decrease its value by $$$1$$$; or you can select any red element and increase its value by $$$1$$$. Situations in which there are no elements of some color at all are also possible. For example, if the whole array is colored blue or red, one of the operations becomes unavailable.Determine whether it is possible to make $$$0$$$ or more steps such that the resulting array is a permutation of numbers from $$$1$$$ to $$$n$$$?In other words, check whether there exists a sequence of steps (possibly empty) such that after applying it, the array $$$a$$$ contains in some order all numbers from $$$1$$$ to $$$n$$$ (inclusive), each exactly once.
256 megabytes
import java.util.*; public class Solution{ 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]; for(int i=0;i<n;i++) a[i]=sc.nextInt(); char[] c=sc.next().toCharArray(); Vector<Integer> l=new Vector<>(), r=new Vector<>(); for(int i=0;i<n;i++) (c[i] == 'B' ? l : r).add(a[i]); Collections.sort(l); Collections.sort(r,Collections.reverseOrder()); boolean ok = true; for(int i=0;i<l.size();i++) if (l.get(i) < i + 1) ok = false; for(int i=0;i<r.size();i++) if (r.get(i) > n - i) ok = false; System.out.print((ok ? "YES" : "NO")+'\n'); } } }
Java
["8\n4\n1 2 5 2\nBRBR\n2\n1 1\nBB\n5\n3 1 4 2 5\nRBRRB\n5\n3 1 3 1 3\nRBRRB\n5\n5 1 5 1 5\nRBRRB\n4\n2 2 2 2\nBRBR\n2\n1 -2\nBR\n4\n-2 -1 4 0\nRRRR"]
1 second
["YES\nNO\nYES\nYES\nNO\nYES\nYES\nYES"]
NoteIn the first test case of the example, the following sequence of moves can be performed: choose $$$i=3$$$, element $$$a_3=5$$$ is blue, so we decrease it, we get $$$a=[1,2,4,2]$$$; choose $$$i=2$$$, element $$$a_2=2$$$ is red, so we increase it, we get $$$a=[1,3,4,2]$$$; choose $$$i=3$$$, element $$$a_3=4$$$ is blue, so we decrease it, we get $$$a=[1,3,3,2]$$$; choose $$$i=2$$$, element $$$a_2=2$$$ is red, so we increase it, we get $$$a=[1,4,3,2]$$$. We got that $$$a$$$ is a permutation. Hence the answer is YES.
Java 11
standard input
[ "greedy", "math", "sortings" ]
c3df88e22a17492d4eb0f3239a27d404
The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of input data sets in the test. The description of each set of input data consists of three lines. The first line contains an integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$) — the length of the original array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$-10^9 \leq a_i \leq 10^9$$$) — the array elements themselves. The third line has length $$$n$$$ and consists exclusively of the letters 'B' and/or 'R': $$$i$$$th character is 'B' if $$$a_i$$$ is colored blue, and is 'R' if colored red. It is guaranteed that the sum of $$$n$$$ over all input sets does not exceed $$$2 \cdot 10^5$$$.
1,300
Print $$$t$$$ lines, each of which contains the answer to the corresponding test case of the input. Print YES as an answer if the corresponding array can be transformed into a permutation, and NO otherwise. You can print the answer in any case (for example, the strings yEs, yes, Yes, and YES will be recognized as a positive answer).
standard output
PASSED
d38bbc6a338eab02817757c45204019d
train_108.jsonl
1635863700
You are given an array of integers $$$a$$$ of length $$$n$$$. The elements of the array can be either different or the same. Each element of the array is colored either blue or red. There are no unpainted elements in the array. One of the two operations described below can be applied to an array in a single step: either you can select any blue element and decrease its value by $$$1$$$; or you can select any red element and increase its value by $$$1$$$. Situations in which there are no elements of some color at all are also possible. For example, if the whole array is colored blue or red, one of the operations becomes unavailable.Determine whether it is possible to make $$$0$$$ or more steps such that the resulting array is a permutation of numbers from $$$1$$$ to $$$n$$$?In other words, check whether there exists a sequence of steps (possibly empty) such that after applying it, the array $$$a$$$ contains in some order all numbers from $$$1$$$ to $$$n$$$ (inclusive), each exactly once.
256 megabytes
// HOPE //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //---------------------------------------------------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //---------------------------------------------------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////// ////////// /////// ////////// /////// RRRRRRRRRRRRR YY YY AA NN NN ////////// /////// RR RR YY YY AA AA NN NN NN ////////// /////// RR RR YY YY AA AA NN NN NN ////////// /////// RRRRRRRRRR YY YY AAAAAAAAAAAA NN NN NN ////////// /////// RR RR YY AAAAAAAAAAAAAA NN NN NN ////////// /////// RR RR YY AA AA NN NNNN ////////// /////// RR RR YY AA AA NN NN ////////// /////// RR RR_____________________________________________________________________________ ////////// //////// ////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //---------------------------------------------------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //---------------------------------------------------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; public class Codeforces2 { static PrintWriter out = new PrintWriter(System.out); static final int mod=1_000_000_007; 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()); } int[] readIntArray(int n){ int[] a = new int[n]; for(int i=0;i<n;i++) a[i] = nextInt(); return a; } long[] readLongArray(int n){ long[] a = new long[n]; for(int i=0;i<n;i++) a[i] = nextLong(); return a; } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } //Try seeing general case public static void main(String[] args) { FastReader s = new FastReader(); int t = s.nextInt(); while(t-->0) { int n = s.nextInt(); long[] a = s.readLongArray(n); char[] ch = s.nextLine().toCharArray(); out.println(find(n, a, ch)); } out.close(); } public static String find(int n, long[] a, char[] ch) { List<Long> minus = new ArrayList<>(); List<Long> plus = new ArrayList<>(); for(int i=0;i<n;i++) { if(ch[i]=='B') minus.add(a[i]); else plus.add(a[i]); } Collections.sort(minus); Collections.sort(plus); int count = 1; for (Long aLong : minus) { if (aLong < count) return "NO"; count++; } for (Long aLong : plus) { if (aLong > count) return "NO"; count++; } return "YES"; } /////////////////////////////////////////////////THE END/////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// public static int gcd(int x,int y) { return y==0?x:gcd(y,x%y); } public static long gcd(long x,long y) { return y==0L?x:gcd(y,x%y); } public static int lcm(int a, int b) { return (a * b) / gcd(a, b); } public static long lcm(long a, long b) { return (a * b) / gcd(a, b); } public static long pow(long a,long b) { if(b==0L) return 1L; long tmp=1; while(b>1L) { if((b&1L)==1) tmp*=a; a*=a; b>>=1; } return (tmp*a); } public static long modPow(long a,long b,long mod) { if(b==0L) return 1L; long tmp=1; while(b>1L) { if((b&1L)==1L) tmp*=a; a*=a; a%=mod; tmp%=mod; b>>=1; } return (tmp*a)%mod; } static long mul(long a, long b) { return a*b%mod; } static long fact(int n) { long ans=1; for (int i=2; i<=n; i++) ans=mul(ans, i); return ans; } static long fastPow(long base, long exp) { if (exp==0) return 1; long half=fastPow(base, exp/2); if (exp%2==0) return mul(half, half); return mul(half, mul(half, base)); } static void debug(int ...a) { for(int x: a) out.print(x+" "); out.println(); } static void debug(long ...a) { for(long x: a) out.print(x+" "); out.println(); } static void debugMatrix(int[][] a) { for(int[] x:a) out.println(Arrays.toString(x)); } static void debugMatrix(long[][] a) { for(long[] x:a) out.println(Arrays.toString(x)); } static void reverseArray(int[] a) { int n = a.length; int[] arr = new int[n]; for (int i = 0; i < n; i++) arr[i] = a[n - i - 1]; for (int i = 0; i < n; i++) a[i] = arr[i]; } static void reverseArray(long[] a) { int n = a.length; long[] arr = new long[n]; for (int i = 0; i < n; i++) arr[i] = a[n - i - 1]; for (int i = 0; i < n; i++) a[i] = arr[i]; } static void sort(int[] a) { ArrayList<Integer> ls = new ArrayList<>(); for(int x: a) ls.add(x); Collections.sort(ls); for(int i=0;i<a.length;i++) a[i] = ls.get(i); } static class Pair{ int x, y; Pair(int x, int y) { this.x = x; this.y = y; } @Override public String toString() { return "Pair{" + "x=" + x + ", y=" + y + '}'; } } static class MyCmp implements Comparator<Pair> { public int compare(Pair p1, Pair p2) { return p1.x-p2.x; } } }
Java
["8\n4\n1 2 5 2\nBRBR\n2\n1 1\nBB\n5\n3 1 4 2 5\nRBRRB\n5\n3 1 3 1 3\nRBRRB\n5\n5 1 5 1 5\nRBRRB\n4\n2 2 2 2\nBRBR\n2\n1 -2\nBR\n4\n-2 -1 4 0\nRRRR"]
1 second
["YES\nNO\nYES\nYES\nNO\nYES\nYES\nYES"]
NoteIn the first test case of the example, the following sequence of moves can be performed: choose $$$i=3$$$, element $$$a_3=5$$$ is blue, so we decrease it, we get $$$a=[1,2,4,2]$$$; choose $$$i=2$$$, element $$$a_2=2$$$ is red, so we increase it, we get $$$a=[1,3,4,2]$$$; choose $$$i=3$$$, element $$$a_3=4$$$ is blue, so we decrease it, we get $$$a=[1,3,3,2]$$$; choose $$$i=2$$$, element $$$a_2=2$$$ is red, so we increase it, we get $$$a=[1,4,3,2]$$$. We got that $$$a$$$ is a permutation. Hence the answer is YES.
Java 11
standard input
[ "greedy", "math", "sortings" ]
c3df88e22a17492d4eb0f3239a27d404
The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of input data sets in the test. The description of each set of input data consists of three lines. The first line contains an integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$) — the length of the original array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$-10^9 \leq a_i \leq 10^9$$$) — the array elements themselves. The third line has length $$$n$$$ and consists exclusively of the letters 'B' and/or 'R': $$$i$$$th character is 'B' if $$$a_i$$$ is colored blue, and is 'R' if colored red. It is guaranteed that the sum of $$$n$$$ over all input sets does not exceed $$$2 \cdot 10^5$$$.
1,300
Print $$$t$$$ lines, each of which contains the answer to the corresponding test case of the input. Print YES as an answer if the corresponding array can be transformed into a permutation, and NO otherwise. You can print the answer in any case (for example, the strings yEs, yes, Yes, and YES will be recognized as a positive answer).
standard output
PASSED
ffaf6de0e0545645c4ace05cdaa4f5ff
train_108.jsonl
1635863700
You are given an array of integers $$$a$$$ of length $$$n$$$. The elements of the array can be either different or the same. Each element of the array is colored either blue or red. There are no unpainted elements in the array. One of the two operations described below can be applied to an array in a single step: either you can select any blue element and decrease its value by $$$1$$$; or you can select any red element and increase its value by $$$1$$$. Situations in which there are no elements of some color at all are also possible. For example, if the whole array is colored blue or red, one of the operations becomes unavailable.Determine whether it is possible to make $$$0$$$ or more steps such that the resulting array is a permutation of numbers from $$$1$$$ to $$$n$$$?In other words, check whether there exists a sequence of steps (possibly empty) such that after applying it, the array $$$a$$$ contains in some order all numbers from $$$1$$$ to $$$n$$$ (inclusive), each exactly once.
256 megabytes
import java.io.*; import java.util.*; public class MyClass { public static void main(String args[])throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); int t=Integer.parseInt(br.readLine()); while(t-->0){ int n=Integer.parseInt(br.readLine()); String s[]=br.readLine().split(" "); int arr[]=new int[n]; String st=br.readLine(); for(int i=0;i<n;i++) arr[i]=Integer.parseInt(s[i]); int b=0,r=0; for(int i=0;i<n;i++){ if(st.charAt(i)=='B') b++; else r++; } int bl[]=new int[b]; int re[]=new int[r]; for(int i=0;i<n;i++){ if(st.charAt(i)=='B') bl[--b]=arr[i]; else re[--r]=arr[i]; } Arrays.sort(bl); Arrays.sort(re); if((bl.length>0&&bl[0]<=0)||(re.length>0&&re[re.length-1]>n)){ System.out.println("NO"); continue; } boolean f=true; for(int i=1;i<=bl.length;i++){ int count=0; for(int j=0;j<bl.length;j++){ if(bl[j]<=i) count++; else break; } if(count >i){ f=false; break; } } if(!f) {System.out.println("NO");continue;} for(int i=n;i>=bl.length;i--){ int count=0; for(int j=re.length-1;j>=0;j--){ if(re[j]>=i) count++; else break; } if(count>n-i+1){ f=false; break; } } if(f) System.out.println("YES"); else System.out.println("NO"); } } }
Java
["8\n4\n1 2 5 2\nBRBR\n2\n1 1\nBB\n5\n3 1 4 2 5\nRBRRB\n5\n3 1 3 1 3\nRBRRB\n5\n5 1 5 1 5\nRBRRB\n4\n2 2 2 2\nBRBR\n2\n1 -2\nBR\n4\n-2 -1 4 0\nRRRR"]
1 second
["YES\nNO\nYES\nYES\nNO\nYES\nYES\nYES"]
NoteIn the first test case of the example, the following sequence of moves can be performed: choose $$$i=3$$$, element $$$a_3=5$$$ is blue, so we decrease it, we get $$$a=[1,2,4,2]$$$; choose $$$i=2$$$, element $$$a_2=2$$$ is red, so we increase it, we get $$$a=[1,3,4,2]$$$; choose $$$i=3$$$, element $$$a_3=4$$$ is blue, so we decrease it, we get $$$a=[1,3,3,2]$$$; choose $$$i=2$$$, element $$$a_2=2$$$ is red, so we increase it, we get $$$a=[1,4,3,2]$$$. We got that $$$a$$$ is a permutation. Hence the answer is YES.
Java 11
standard input
[ "greedy", "math", "sortings" ]
c3df88e22a17492d4eb0f3239a27d404
The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of input data sets in the test. The description of each set of input data consists of three lines. The first line contains an integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$) — the length of the original array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$-10^9 \leq a_i \leq 10^9$$$) — the array elements themselves. The third line has length $$$n$$$ and consists exclusively of the letters 'B' and/or 'R': $$$i$$$th character is 'B' if $$$a_i$$$ is colored blue, and is 'R' if colored red. It is guaranteed that the sum of $$$n$$$ over all input sets does not exceed $$$2 \cdot 10^5$$$.
1,300
Print $$$t$$$ lines, each of which contains the answer to the corresponding test case of the input. Print YES as an answer if the corresponding array can be transformed into a permutation, and NO otherwise. You can print the answer in any case (for example, the strings yEs, yes, Yes, and YES will be recognized as a positive answer).
standard output
PASSED
ab5adb4e4d322b32f5d806f28c43a350
train_108.jsonl
1635863700
You are given an array of integers $$$a$$$ of length $$$n$$$. The elements of the array can be either different or the same. Each element of the array is colored either blue or red. There are no unpainted elements in the array. One of the two operations described below can be applied to an array in a single step: either you can select any blue element and decrease its value by $$$1$$$; or you can select any red element and increase its value by $$$1$$$. Situations in which there are no elements of some color at all are also possible. For example, if the whole array is colored blue or red, one of the operations becomes unavailable.Determine whether it is possible to make $$$0$$$ or more steps such that the resulting array is a permutation of numbers from $$$1$$$ to $$$n$$$?In other words, check whether there exists a sequence of steps (possibly empty) such that after applying it, the array $$$a$$$ contains in some order all numbers from $$$1$$$ to $$$n$$$ (inclusive), each exactly once.
256 megabytes
//package com.company; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Scanner; public class D { private static Scanner scanner = new Scanner(System.in); public static void main(String[] args) { int t = scanner.nextInt(); while (t-- > 0) { int n = scanner.nextInt(); int[] ar = new int[n]; for (int i = 0; i < n; i++) { ar[i] = scanner.nextInt(); } String s = scanner.next(); List<Integer> blue = new ArrayList<Integer>(); List<Integer> red = new ArrayList<Integer>(); for (int i = 0; i < s.length(); i++) { if(s.charAt(i) == 'B') { blue.add(ar[i]); } else { red.add(ar[i]); } } Collections.sort(blue); red.sort(Collections.reverseOrder()); boolean ok = true; for (int i = 0; i < blue.size(); i++) { if(blue.get(i) <= i) { ok = false; break; } } for (int i = 0; i <red.size() ; i++) { if(red.get(i) > n-i) { ok = false; break; } } System.out.println(ok ? "YES" : "NO"); } } }
Java
["8\n4\n1 2 5 2\nBRBR\n2\n1 1\nBB\n5\n3 1 4 2 5\nRBRRB\n5\n3 1 3 1 3\nRBRRB\n5\n5 1 5 1 5\nRBRRB\n4\n2 2 2 2\nBRBR\n2\n1 -2\nBR\n4\n-2 -1 4 0\nRRRR"]
1 second
["YES\nNO\nYES\nYES\nNO\nYES\nYES\nYES"]
NoteIn the first test case of the example, the following sequence of moves can be performed: choose $$$i=3$$$, element $$$a_3=5$$$ is blue, so we decrease it, we get $$$a=[1,2,4,2]$$$; choose $$$i=2$$$, element $$$a_2=2$$$ is red, so we increase it, we get $$$a=[1,3,4,2]$$$; choose $$$i=3$$$, element $$$a_3=4$$$ is blue, so we decrease it, we get $$$a=[1,3,3,2]$$$; choose $$$i=2$$$, element $$$a_2=2$$$ is red, so we increase it, we get $$$a=[1,4,3,2]$$$. We got that $$$a$$$ is a permutation. Hence the answer is YES.
Java 11
standard input
[ "greedy", "math", "sortings" ]
c3df88e22a17492d4eb0f3239a27d404
The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of input data sets in the test. The description of each set of input data consists of three lines. The first line contains an integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$) — the length of the original array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$-10^9 \leq a_i \leq 10^9$$$) — the array elements themselves. The third line has length $$$n$$$ and consists exclusively of the letters 'B' and/or 'R': $$$i$$$th character is 'B' if $$$a_i$$$ is colored blue, and is 'R' if colored red. It is guaranteed that the sum of $$$n$$$ over all input sets does not exceed $$$2 \cdot 10^5$$$.
1,300
Print $$$t$$$ lines, each of which contains the answer to the corresponding test case of the input. Print YES as an answer if the corresponding array can be transformed into a permutation, and NO otherwise. You can print the answer in any case (for example, the strings yEs, yes, Yes, and YES will be recognized as a positive answer).
standard output
PASSED
fac40c03a33fe1d9e935e7c6bee6751b
train_108.jsonl
1635863700
You are given an array of integers $$$a$$$ of length $$$n$$$. The elements of the array can be either different or the same. Each element of the array is colored either blue or red. There are no unpainted elements in the array. One of the two operations described below can be applied to an array in a single step: either you can select any blue element and decrease its value by $$$1$$$; or you can select any red element and increase its value by $$$1$$$. Situations in which there are no elements of some color at all are also possible. For example, if the whole array is colored blue or red, one of the operations becomes unavailable.Determine whether it is possible to make $$$0$$$ or more steps such that the resulting array is a permutation of numbers from $$$1$$$ to $$$n$$$?In other words, check whether there exists a sequence of steps (possibly empty) such that after applying it, the array $$$a$$$ contains in some order all numbers from $$$1$$$ to $$$n$$$ (inclusive), each exactly once.
256 megabytes
import java.io.*; import java.util.*; public class q4 { public static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); public static long mod = 1000000007; public static void solve() throws Exception { String[] parts = br.readLine().split(" "); int n = Integer.parseInt(parts[0]); Integer[] arr = new Integer[n]; parts = br.readLine().split(" "); for (int i = 0; i < n; i++) { arr[i] = Integer.parseInt(parts[i]); } ArrayList<Integer> start = new ArrayList<>(),end = new ArrayList<>(); String str = br.readLine(); for(int i = 0;i < str.length();i++){ if(str.charAt(i) == 'B') start.add(arr[i]); else end.add(arr[i]); } Collections.sort(start); Collections.sort(end); boolean flag = true; for(int i = 0;i < start.size();i++){ if(start.get(i) <= i){ flag = false; break; } } for(int i = end.size() - 1;i >= 0;i--){ if(end.get(i) > n - (end.size() - i - 1)){ flag = false; break; } } if(flag) System.out.println("YES"); else System.out.println("NO"); } public static void main(String[] args) throws Exception { int tests = Integer.parseInt(br.readLine()); for (int test = 1; test <= tests; test++) { solve(); } } public static long power(long a,long b,long mod){ if(b == 0) return 1; long p = power(a,b / 2,mod); p = (p * p) % mod; if(b % 2 == 1) return (p * a) % mod; return p; } public static long GCD(long a,long b){ return b == 0 ? a : GCD(b,a % b); } public static long LCM(long a,long b){ return a * b / GCD(a,b); } }
Java
["8\n4\n1 2 5 2\nBRBR\n2\n1 1\nBB\n5\n3 1 4 2 5\nRBRRB\n5\n3 1 3 1 3\nRBRRB\n5\n5 1 5 1 5\nRBRRB\n4\n2 2 2 2\nBRBR\n2\n1 -2\nBR\n4\n-2 -1 4 0\nRRRR"]
1 second
["YES\nNO\nYES\nYES\nNO\nYES\nYES\nYES"]
NoteIn the first test case of the example, the following sequence of moves can be performed: choose $$$i=3$$$, element $$$a_3=5$$$ is blue, so we decrease it, we get $$$a=[1,2,4,2]$$$; choose $$$i=2$$$, element $$$a_2=2$$$ is red, so we increase it, we get $$$a=[1,3,4,2]$$$; choose $$$i=3$$$, element $$$a_3=4$$$ is blue, so we decrease it, we get $$$a=[1,3,3,2]$$$; choose $$$i=2$$$, element $$$a_2=2$$$ is red, so we increase it, we get $$$a=[1,4,3,2]$$$. We got that $$$a$$$ is a permutation. Hence the answer is YES.
Java 11
standard input
[ "greedy", "math", "sortings" ]
c3df88e22a17492d4eb0f3239a27d404
The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of input data sets in the test. The description of each set of input data consists of three lines. The first line contains an integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$) — the length of the original array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$-10^9 \leq a_i \leq 10^9$$$) — the array elements themselves. The third line has length $$$n$$$ and consists exclusively of the letters 'B' and/or 'R': $$$i$$$th character is 'B' if $$$a_i$$$ is colored blue, and is 'R' if colored red. It is guaranteed that the sum of $$$n$$$ over all input sets does not exceed $$$2 \cdot 10^5$$$.
1,300
Print $$$t$$$ lines, each of which contains the answer to the corresponding test case of the input. Print YES as an answer if the corresponding array can be transformed into a permutation, and NO otherwise. You can print the answer in any case (for example, the strings yEs, yes, Yes, and YES will be recognized as a positive answer).
standard output
PASSED
8760c49d1547c0afc9bf45fef2244b6a
train_108.jsonl
1635863700
You are given an array of integers $$$a$$$ of length $$$n$$$. The elements of the array can be either different or the same. Each element of the array is colored either blue or red. There are no unpainted elements in the array. One of the two operations described below can be applied to an array in a single step: either you can select any blue element and decrease its value by $$$1$$$; or you can select any red element and increase its value by $$$1$$$. Situations in which there are no elements of some color at all are also possible. For example, if the whole array is colored blue or red, one of the operations becomes unavailable.Determine whether it is possible to make $$$0$$$ or more steps such that the resulting array is a permutation of numbers from $$$1$$$ to $$$n$$$?In other words, check whether there exists a sequence of steps (possibly empty) such that after applying it, the array $$$a$$$ contains in some order all numbers from $$$1$$$ to $$$n$$$ (inclusive), each exactly once.
256 megabytes
import java.util.*; public class MyClass { public static void main(String args[]) { Scanner s=new Scanner(System.in); int t=s.nextInt(); while(t-->0) { int n=s.nextInt(); int a[]=new int[n]; HashMap<Integer,Integer> inc=new HashMap<>(); HashMap<Integer,Integer> dec=new HashMap<>(); for(int i=0;i<n;i++) { a[i]=s.nextInt(); } s.nextLine(); String b=s.nextLine(); boolean flag=false; for(int i=0;i<n;i++) { if(b.charAt(i)=='B') { if(a[i]<1) flag=true; if(a[i]>n) a[i]=n; if(dec.containsKey(a[i])) dec.put(a[i],dec.get(a[i])+1); else dec.put(a[i],1); } else { if(a[i]>n) flag=true; if(a[i]<1) a[i]=1; if(inc.containsKey(a[i])) inc.put(a[i],inc.get(a[i])+1); else inc.put(a[i],1); } } int decsum=0; // System.out.println(inc); // System.out.println(dec); for(int i=1;i<=n;i++) { if(dec.containsKey(i)) decsum+=dec.get(i); if(decsum>i) { flag=true; break; } } int incsum=0; //System.out.println(flag); int l=1; for(int i=n;i>=1;i--) { if(inc.containsKey(i)) incsum+=inc.get(i); if(incsum>(l)) { flag=true; break; } l++; } if(flag) System.out.println("NO"); else System.out.println("YES"); } } }
Java
["8\n4\n1 2 5 2\nBRBR\n2\n1 1\nBB\n5\n3 1 4 2 5\nRBRRB\n5\n3 1 3 1 3\nRBRRB\n5\n5 1 5 1 5\nRBRRB\n4\n2 2 2 2\nBRBR\n2\n1 -2\nBR\n4\n-2 -1 4 0\nRRRR"]
1 second
["YES\nNO\nYES\nYES\nNO\nYES\nYES\nYES"]
NoteIn the first test case of the example, the following sequence of moves can be performed: choose $$$i=3$$$, element $$$a_3=5$$$ is blue, so we decrease it, we get $$$a=[1,2,4,2]$$$; choose $$$i=2$$$, element $$$a_2=2$$$ is red, so we increase it, we get $$$a=[1,3,4,2]$$$; choose $$$i=3$$$, element $$$a_3=4$$$ is blue, so we decrease it, we get $$$a=[1,3,3,2]$$$; choose $$$i=2$$$, element $$$a_2=2$$$ is red, so we increase it, we get $$$a=[1,4,3,2]$$$. We got that $$$a$$$ is a permutation. Hence the answer is YES.
Java 11
standard input
[ "greedy", "math", "sortings" ]
c3df88e22a17492d4eb0f3239a27d404
The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of input data sets in the test. The description of each set of input data consists of three lines. The first line contains an integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$) — the length of the original array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$-10^9 \leq a_i \leq 10^9$$$) — the array elements themselves. The third line has length $$$n$$$ and consists exclusively of the letters 'B' and/or 'R': $$$i$$$th character is 'B' if $$$a_i$$$ is colored blue, and is 'R' if colored red. It is guaranteed that the sum of $$$n$$$ over all input sets does not exceed $$$2 \cdot 10^5$$$.
1,300
Print $$$t$$$ lines, each of which contains the answer to the corresponding test case of the input. Print YES as an answer if the corresponding array can be transformed into a permutation, and NO otherwise. You can print the answer in any case (for example, the strings yEs, yes, Yes, and YES will be recognized as a positive answer).
standard output
PASSED
5fcce72aee299ef30868f42a6e18fcd2
train_108.jsonl
1635863700
You are given an array of integers $$$a$$$ of length $$$n$$$. The elements of the array can be either different or the same. Each element of the array is colored either blue or red. There are no unpainted elements in the array. One of the two operations described below can be applied to an array in a single step: either you can select any blue element and decrease its value by $$$1$$$; or you can select any red element and increase its value by $$$1$$$. Situations in which there are no elements of some color at all are also possible. For example, if the whole array is colored blue or red, one of the operations becomes unavailable.Determine whether it is possible to make $$$0$$$ or more steps such that the resulting array is a permutation of numbers from $$$1$$$ to $$$n$$$?In other words, check whether there exists a sequence of steps (possibly empty) such that after applying it, the array $$$a$$$ contains in some order all numbers from $$$1$$$ to $$$n$$$ (inclusive), each exactly once.
256 megabytes
import java.math.BigInteger; import java.util.*; import java.io.*; public class D_Blue_Red_Permutation { public static void main (String[] args) { FastReader scan = new FastReader(); int t = scan.nextInt(); while (t-- > 0) { int n = scan.nextInt(); int[] arr = new int[n]; inputArray(arr, n, scan); String str = scan.nextLine(); TreeSet<Integer> set = new TreeSet<>(); for (int i=1; i<=n; i++) { set.add(i); } ArrayList<Integer> red = new ArrayList<>(), blue = new ArrayList<>(); for (int i=0; i<n; i++) { if (str.charAt(i) == 'B') { blue.add(arr[i]); } else { red.add(arr[i]); } } Collections.sort(blue); Collections.sort(red); boolean possible = true; for (int i=0; i<blue.size(); i++) { if (blue.get(i) < set.first()) { possible = false; break; } else { set.pollFirst(); } } for (int i=0; i<red.size(); i++) { if (red.get(i) > set.first()) { possible = false; break; } else { set.pollFirst(); } } if (possible) System.out.println("YES"); else System.out.println("NO"); } } public static void inputArray (int[] arr, int n, FastReader scan) { for (int i=0; i<n; i++) { arr[i] = scan.nextInt(); } } public static void printArray (int[] arr) { for (int i=0; i<arr.length; i++) { System.out.print(arr[i] + " "); } System.out.println(); } public static boolean isPrime (int n) { if (n <= 1) return false; if (n <= 3) return true; if (n % 2 == 0 || n % 3 == 0) return false; for (int i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } public static int gcd (int a, int b) { BigInteger a1 = BigInteger.valueOf(a); BigInteger b1 = BigInteger.valueOf(b); return a1.gcd(b1).intValue(); } public static int numberOfDigitsInNumber (int n) { return (int)Math.floor(Math.log10(n)) + 1; } public static boolean isPowerOfTwo (int x) { return x!=0 && ((x&(x-1)) == 0); } public static String toBinaryString (int n) { return Integer.toString(n, 2); // for other bases change 2 to other bases } 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; } } } // For IO using Files // public static void main throws IOException // BufferedReader br = new BufferedReader(new FileReader("input.txt")); // PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter("output.txt"))); // String st[]=br.readLine().split(" "); // int n=Integer.parseInt(st[0]); // int m=Integer.parseInt(st[1]); // at the end // br.close(); pw.close(); // for printing pw.println(), pw.print(), etc... // for arrays : int arr[] = Arrays.stream(br.readLine().split(" ")).mapToInt(Integer::parseInt).toArray();
Java
["8\n4\n1 2 5 2\nBRBR\n2\n1 1\nBB\n5\n3 1 4 2 5\nRBRRB\n5\n3 1 3 1 3\nRBRRB\n5\n5 1 5 1 5\nRBRRB\n4\n2 2 2 2\nBRBR\n2\n1 -2\nBR\n4\n-2 -1 4 0\nRRRR"]
1 second
["YES\nNO\nYES\nYES\nNO\nYES\nYES\nYES"]
NoteIn the first test case of the example, the following sequence of moves can be performed: choose $$$i=3$$$, element $$$a_3=5$$$ is blue, so we decrease it, we get $$$a=[1,2,4,2]$$$; choose $$$i=2$$$, element $$$a_2=2$$$ is red, so we increase it, we get $$$a=[1,3,4,2]$$$; choose $$$i=3$$$, element $$$a_3=4$$$ is blue, so we decrease it, we get $$$a=[1,3,3,2]$$$; choose $$$i=2$$$, element $$$a_2=2$$$ is red, so we increase it, we get $$$a=[1,4,3,2]$$$. We got that $$$a$$$ is a permutation. Hence the answer is YES.
Java 11
standard input
[ "greedy", "math", "sortings" ]
c3df88e22a17492d4eb0f3239a27d404
The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of input data sets in the test. The description of each set of input data consists of three lines. The first line contains an integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$) — the length of the original array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$-10^9 \leq a_i \leq 10^9$$$) — the array elements themselves. The third line has length $$$n$$$ and consists exclusively of the letters 'B' and/or 'R': $$$i$$$th character is 'B' if $$$a_i$$$ is colored blue, and is 'R' if colored red. It is guaranteed that the sum of $$$n$$$ over all input sets does not exceed $$$2 \cdot 10^5$$$.
1,300
Print $$$t$$$ lines, each of which contains the answer to the corresponding test case of the input. Print YES as an answer if the corresponding array can be transformed into a permutation, and NO otherwise. You can print the answer in any case (for example, the strings yEs, yes, Yes, and YES will be recognized as a positive answer).
standard output
PASSED
b8dd26b4c9cbf2db79e889d5fb7225c1
train_108.jsonl
1635863700
You are given an array of integers $$$a$$$ of length $$$n$$$. The elements of the array can be either different or the same. Each element of the array is colored either blue or red. There are no unpainted elements in the array. One of the two operations described below can be applied to an array in a single step: either you can select any blue element and decrease its value by $$$1$$$; or you can select any red element and increase its value by $$$1$$$. Situations in which there are no elements of some color at all are also possible. For example, if the whole array is colored blue or red, one of the operations becomes unavailable.Determine whether it is possible to make $$$0$$$ or more steps such that the resulting array is a permutation of numbers from $$$1$$$ to $$$n$$$?In other words, check whether there exists a sequence of steps (possibly empty) such that after applying it, the array $$$a$$$ contains in some order all numbers from $$$1$$$ to $$$n$$$ (inclusive), each exactly once.
256 megabytes
import java.net.Inet4Address; import java.util.*; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class practiceb{ static FastScanner sc; static int ans; static long[] arr,arr1; static char[][] board; static long mul,mul1; static int[] spf; static char[] ch; static int n,q,m; static long k,a,x,c; static StringBuilder sb,sb1; static long b,sum; static Map<Integer,List<Integer>> map; static Map<Long,List<Integer>> map2; static Map<Long,List<Integer>> map3; static Map<Integer,Integer> shortest; static Map<Integer,Integer> map1,in; static List<Integer> list,list1; static long[] count; static boolean[] vis; static boolean flag; static long total,xor1; // static class Node{ // long dist; // Set<Integer> set; // Node(){ // this.set = new HashSet<>(); // } // Node(int f){ // this.dist = f; // this.set = new HashSet<>(); // } // } // public static class Lca { // int[] depth; // int[] dfs_order; // int cnt; // int[] first; // int[] minPos; // int n; // void dfs(List<Integer>[] tree, int u, int d) { // depth[u] = d; // dfs_order[cnt++] = u; // for (int v : tree[u]) // if (depth[v] == -1) { // dfs(tree, v, d + 1); // dfs_order[cnt++] = u; // } // } // void buildTree(int node, int left, int right) { // if (left == right) { // minPos[node] = dfs_order[left]; // return; // } // int mid = (left + right) >> 1; // buildTree(2 * node + 1, left, mid); // buildTree(2 * node + 2, mid + 1, right); // minPos[node] = depth[minPos[2 * node + 1]] < depth[minPos[2 * node + 2]] ? minPos[2 * node + 1] : minPos[2 * node + 2]; // } // public Lca(List<Integer>[] tree, int root) { // int nodes = tree.length; // depth = new int[nodes]; // Arrays.fill(depth, -1); // n = 2 * nodes - 1; // dfs_order = new int[n]; // cnt = 0; // dfs(tree, root, 0); // minPos = new int[4 * n]; // buildTree(0, 0, n - 1); // first = new int[nodes]; // Arrays.fill(first, -1); // for (int i = 0; i < dfs_order.length; i++) // if (first[dfs_order[i]] == -1) // first[dfs_order[i]] = i; // } // public int lca(int a, int b) { // return minPos(Math.min(first[a], first[b]), Math.max(first[a], first[b]), 0, 0, n - 1); // } // int minPos(int a, int b, int node, int left, int right) { // if (a == left && right == b) // return minPos[node]; // int mid = (left + right) >> 1; // if (a <= mid && b > mid) { // int p1 = minPos(a, Math.min(b, mid), 2 * node + 1, left, mid); // int p2 = minPos(Math.max(a, mid + 1), b, 2 * node + 2, mid + 1, right); // return depth[p1] < depth[p2] ? p1 : p2; // } else if (a <= mid) { // return minPos(a, Math.min(b, mid), 2 * node + 1, left, mid); // } else if (b > mid) { // return minPos(Math.max(a, mid + 1), b, 2 * node + 2, mid + 1, right); // } else { // throw new RuntimeException(); // } // } // } // private static long dfs(int v, int parent,long ht) { // List<Integer> list = map.get(v); // hyt[v] = ht; // if(list.size() == 1){ // if(!map3.containsKey(ht)) // map3.put(ht,new ArrayList<>()); // map3.get(ht).add(v); // return ht; // } // long maxl = -1; // for(Integer i : list){ // if(i == parent) // continue; // maxl = Math.max(maxl,dfs(i,v,ht+1)); // } // return maxl; // } // public static int N = 100005; // long a[N]; // long sfx[N]; // long pfx[N]; // public static boolean f(int width){ // // // long[] a = new long[n]; // long[] sfx = new long[n]; // long[] pfx = new long[n]; // for (int j = 0; j < n; j++){ // if (j % width == 0){ // pfx[j] = a[j]; // } // else pfx[j] = gcd(pfx[j - 1], a[j]); // } // for (int j = n - 2; j >= 0; j--){ // if (j % width == width - 1){ // sfx[j] = a[j]; // } // else sfx[j] = gcd(sfx[j + 1], a[j]); // } // // for(int j = 0; j < n - width + 1 ; j++){ // if (gcd(sfx[j], pfx[j + width - 1]) >= k) return true; // if (((j % width) == width - 1) && pfx[j] >= k){ // return true; // } // } // return false; // } public static class Node { int v; int wt; Node(int v,int wt) { this.v = v; this.wt = wt; } } public static long lcm(long a, long b) { return (b / gcd(b, a % b)) * a; } 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 void solve1(List<Integer> list) { int n = list.size(); long lcm = arr[list.get(0)]; for(int i = 1 ; i < n ; i++) lcm = lcm(lcm,arr[list.get(i)]); if(n%2 == 0) { for(int i = 0 ; i < n ; i++) { if(i%2 == 0) { count[list.get(i)] = (lcm/arr[list.get(i)]); } else { count[list.get(i)] = (-(lcm/arr[list.get(i)])); } } } else { count[list.get(0)] = (lcm/arr[list.get(0)]); count[list.get(1)] = (lcm/arr[list.get(1)]); count[list.get(2)] = (-2*lcm/arr[list.get(2)]); for(int i = 3 ; i < n ; i++) { if(i%2 == 0) { count[list.get(i)] = (lcm/arr[list.get(i)]); } else { count[list.get(i)] = (-(lcm/arr[list.get(i)])); } } } } public static void solve() { List<Long> list = new ArrayList<>(); List<Long> list1 = new ArrayList<>(); for(int i = 0 ; i < n ; i++) { if(ch[i] == 'B') { if(arr[i] <= 0) { sb.append("NO").append("\n"); return; } list.add(arr[i]); } else { list1.add(arr[i]); } } Collections.sort(list); Collections.sort(list1); for(int i = 0 ; i < list.size() ; i++) { if(i != 0 && (list.get(i) <= list.get(i-1))) { sb.append("NO").append("\n"); return; } else list.set(i,i+1L); } if((list.size() > 0 && list1.size() > 0) && (list1.get(0) > (list.get(list.size()-1) + 1))) { sb.append("NO").append("\n"); return; } if(list.size() == 0 && list1.get(0) > 1) { sb.append("NO").append("\n"); return; } for(int i = 0 ; i < list1.size() ; i++) { if(i != 0 && list1.get(i) > (list1.get(i-1)+1)) { sb.append("NO").append("\n"); return; } else list1.set(i,i+1L+list.size()); } sb.append("YES").append("\n"); } public static void main(String[] args) { sc = new FastScanner(); // Scanner sc = new Scanner(System.in); // SpecialSieve(5000000+5); // long num = 1; // list = new ArrayList<>(); // for(int i = 0 ; i <= 60 ; i++) { // list.add(num); // num *= 2; // } int t = sc.nextInt(); // SpecialSieve(10001); // fact(200000+1); sb = new StringBuilder(); // int t = 1; while(t > 0){ // a = sc.nextLong(); // b = sc.nextLong(); // c = sc.nextLong(); n = sc.nextInt(); // x = sc.nextLong(); // m = sc.nextInt(); // k = sc.nextInt(); // mat = new int[2][m]; // for(int i = 0 ; i < 2 ; i++) // for(int j = 0 ; j < m ; j++) // mat[i][j] = sc.nextLong(); // for(int i = 1 ; i <= 15 ; i++){ // m = i; // solve(); // // } // board = new char[3][3]; // for(int i = 0 ; i < 3 ; i++){ // String s = sc.next(); // for(int j = 0 ; j < 3 ; j++){ // board[i][j] = s.charAt(j); // } // } // x = sc.nextInt(); // ch = sc.next().toCharArray(); // q = sc.nextInt(); // ch = sc.next().toCharArray(); arr = new long[n]; for(int i = 0 ; i < n ; i++) arr[i] = sc.nextLong(); ch = sc.next().toCharArray(); // arr1 = new long[m]; // for(int i = 0 ; i < m ; i++) // arr1[i] = sc.nextLong(); // // a = new long[n-1]; // for(int i = 1 ; i < n ; i++) // a[i-1] = Math.abs(arr[i] - arr[i-1]); // // n -= 1; solve(); t -= 1; } System.out.print(sb); } // Use this instead of Arrays.sort() on an array of ints. Arrays.sort() is n^2 // worst case since it uses a version of quicksort. Although this would never // actually show up in the real world, in codeforces, people can hack, so // this is needed. static void ruffleSort(long[] a) { //ruffle int n=a.length; Random r=new Random(); for (int i=0; i<a.length; i++) { int oi=r.nextInt(n);long temp=a[i]; a[i]=a[oi]; a[oi]=temp; } //then sort Arrays.sort(a); } public static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } 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 long mod(long x, long mod) { long result = x % mod; if (result < 0) { result += mod; } return result; } // Use this to input code since it is faster than a Scanner static class FastScanner { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readArray(int n) { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } long nextLong() { return Long.parseLong(next()); } } }
Java
["8\n4\n1 2 5 2\nBRBR\n2\n1 1\nBB\n5\n3 1 4 2 5\nRBRRB\n5\n3 1 3 1 3\nRBRRB\n5\n5 1 5 1 5\nRBRRB\n4\n2 2 2 2\nBRBR\n2\n1 -2\nBR\n4\n-2 -1 4 0\nRRRR"]
1 second
["YES\nNO\nYES\nYES\nNO\nYES\nYES\nYES"]
NoteIn the first test case of the example, the following sequence of moves can be performed: choose $$$i=3$$$, element $$$a_3=5$$$ is blue, so we decrease it, we get $$$a=[1,2,4,2]$$$; choose $$$i=2$$$, element $$$a_2=2$$$ is red, so we increase it, we get $$$a=[1,3,4,2]$$$; choose $$$i=3$$$, element $$$a_3=4$$$ is blue, so we decrease it, we get $$$a=[1,3,3,2]$$$; choose $$$i=2$$$, element $$$a_2=2$$$ is red, so we increase it, we get $$$a=[1,4,3,2]$$$. We got that $$$a$$$ is a permutation. Hence the answer is YES.
Java 11
standard input
[ "greedy", "math", "sortings" ]
c3df88e22a17492d4eb0f3239a27d404
The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of input data sets in the test. The description of each set of input data consists of three lines. The first line contains an integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$) — the length of the original array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$-10^9 \leq a_i \leq 10^9$$$) — the array elements themselves. The third line has length $$$n$$$ and consists exclusively of the letters 'B' and/or 'R': $$$i$$$th character is 'B' if $$$a_i$$$ is colored blue, and is 'R' if colored red. It is guaranteed that the sum of $$$n$$$ over all input sets does not exceed $$$2 \cdot 10^5$$$.
1,300
Print $$$t$$$ lines, each of which contains the answer to the corresponding test case of the input. Print YES as an answer if the corresponding array can be transformed into a permutation, and NO otherwise. You can print the answer in any case (for example, the strings yEs, yes, Yes, and YES will be recognized as a positive answer).
standard output
PASSED
dfeb33d75ac3825c148f8452ce28baf0
train_108.jsonl
1635863700
You are given an array of integers $$$a$$$ of length $$$n$$$. The elements of the array can be either different or the same. Each element of the array is colored either blue or red. There are no unpainted elements in the array. One of the two operations described below can be applied to an array in a single step: either you can select any blue element and decrease its value by $$$1$$$; or you can select any red element and increase its value by $$$1$$$. Situations in which there are no elements of some color at all are also possible. For example, if the whole array is colored blue or red, one of the operations becomes unavailable.Determine whether it is possible to make $$$0$$$ or more steps such that the resulting array is a permutation of numbers from $$$1$$$ to $$$n$$$?In other words, check whether there exists a sequence of steps (possibly empty) such that after applying it, the array $$$a$$$ contains in some order all numbers from $$$1$$$ to $$$n$$$ (inclusive), each exactly once.
256 megabytes
import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashSet; import java.util.List; import java.util.StringTokenizer; public class codeforces { //-----------PrintWriter for faster output--------------------------------- public static PrintWriter out; public static int cnt; //-----------MyScanner class for faster input---------- public static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine(){ String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } 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; } public class ArrayListComparator<T extends Comparable<T>> implements Comparator<ArrayList<T>> { @Override public int compare(ArrayList<T> o1, ArrayList<T> o2) { for (int i = 0; i < Math.min(o1.size(), o2.size()); i++) { int c = o1.get(i).compareTo(o2.get(i)); if (c != 0) { return c; } } return Integer.compare(o1.size(), o2.size()); } } public static int reverseBits(int n) { int rev = 0; // traversing bits of 'n' // from the right while (n > 0) { // bitwise left shift // 'rev' by 1 rev <<= 1; // if current bit is '1' if ((int)(n & 1) == 1) rev ^= 1; // bitwise right shift //'n' by 1 n >>= 1; } // required number return rev; } public static void main(String[] args) { // TODO Auto-generated method stub MyScanner sc = new MyScanner(); out = new PrintWriter(new BufferedOutputStream(System.out)); StringBuilder sb = new StringBuilder(); 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(); } String s=sc.next(); HashSet<Integer> x=new HashSet<Integer>(); ArrayList<Integer> x1=new ArrayList<Integer>(); ArrayList<Integer> x2=new ArrayList<Integer>(); for(int i=0;i<n;i++) { if(s.charAt(i)=='R') { x1.add(arr[i]); } else { x2.add(arr[i]); } } Collections.sort(x1); Collections.sort(x2); boolean p=true,p1=true; int k=1; for(int i=0;i<x2.size();i++) { if(x2.get(i)==i+1) { x.add(i+1); k++; } else if(x2.get(i)>i+1) { x.add(i+1); k++; } } for(int i=0;i<x1.size();i++) { if(x1.get(i)==k) { x.add(k); k++; } else if(x1.get(i)<k) { x.add(k); k++; } } if(x.size()==n) { out.println("YES"); } else { out.println("NO"); } } out.close(); } }
Java
["8\n4\n1 2 5 2\nBRBR\n2\n1 1\nBB\n5\n3 1 4 2 5\nRBRRB\n5\n3 1 3 1 3\nRBRRB\n5\n5 1 5 1 5\nRBRRB\n4\n2 2 2 2\nBRBR\n2\n1 -2\nBR\n4\n-2 -1 4 0\nRRRR"]
1 second
["YES\nNO\nYES\nYES\nNO\nYES\nYES\nYES"]
NoteIn the first test case of the example, the following sequence of moves can be performed: choose $$$i=3$$$, element $$$a_3=5$$$ is blue, so we decrease it, we get $$$a=[1,2,4,2]$$$; choose $$$i=2$$$, element $$$a_2=2$$$ is red, so we increase it, we get $$$a=[1,3,4,2]$$$; choose $$$i=3$$$, element $$$a_3=4$$$ is blue, so we decrease it, we get $$$a=[1,3,3,2]$$$; choose $$$i=2$$$, element $$$a_2=2$$$ is red, so we increase it, we get $$$a=[1,4,3,2]$$$. We got that $$$a$$$ is a permutation. Hence the answer is YES.
Java 11
standard input
[ "greedy", "math", "sortings" ]
c3df88e22a17492d4eb0f3239a27d404
The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of input data sets in the test. The description of each set of input data consists of three lines. The first line contains an integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$) — the length of the original array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$-10^9 \leq a_i \leq 10^9$$$) — the array elements themselves. The third line has length $$$n$$$ and consists exclusively of the letters 'B' and/or 'R': $$$i$$$th character is 'B' if $$$a_i$$$ is colored blue, and is 'R' if colored red. It is guaranteed that the sum of $$$n$$$ over all input sets does not exceed $$$2 \cdot 10^5$$$.
1,300
Print $$$t$$$ lines, each of which contains the answer to the corresponding test case of the input. Print YES as an answer if the corresponding array can be transformed into a permutation, and NO otherwise. You can print the answer in any case (for example, the strings yEs, yes, Yes, and YES will be recognized as a positive answer).
standard output
PASSED
0f0f6d2ffa58e670002bd47d6cdb5d5f
train_108.jsonl
1635863700
You are given an array of integers $$$a$$$ of length $$$n$$$. The elements of the array can be either different or the same. Each element of the array is colored either blue or red. There are no unpainted elements in the array. One of the two operations described below can be applied to an array in a single step: either you can select any blue element and decrease its value by $$$1$$$; or you can select any red element and increase its value by $$$1$$$. Situations in which there are no elements of some color at all are also possible. For example, if the whole array is colored blue or red, one of the operations becomes unavailable.Determine whether it is possible to make $$$0$$$ or more steps such that the resulting array is a permutation of numbers from $$$1$$$ to $$$n$$$?In other words, check whether there exists a sequence of steps (possibly empty) such that after applying it, the array $$$a$$$ contains in some order all numbers from $$$1$$$ to $$$n$$$ (inclusive), each exactly once.
256 megabytes
import java.io.*; import java.util.*; import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.util.TreeSet; import java.util.StringTokenizer; import java.io.Writer; import java.io.OutputStreamWriter; import java.io.BufferedReader; import java.io.InputStream; public class Solution{ public static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader( new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } public static void swap(int i, int j) { int temp = i; i = j; j = temp; } static class Pair{ int val; char c; public Pair(int v, char ch) { val=v; c = ch; } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) { writer.print(' '); } writer.print(objects[i]); } } public void println(Object... objects) { print(objects); writer.println(); } public void close() { writer.close(); } } public static void main(String[] args) throws Exception { FastReader scn = new FastReader(); int t = scn.nextInt(); while(t>0) { int n = scn.nextInt(); Pair[] a = new Pair[n]; TreeSet<Integer> set = new TreeSet<>(); for(int i=0;i<n;i++) { int x = scn.nextInt(); a[i] = new Pair(x,'_'); set.add(i+1); } String s = scn.next(); for(int i=0;i<n;i++) { a[i].c = s.charAt(i); } Arrays.sort(a,(x,y)->{ if(x.c!=y.c) { return (int)(x.c-y.c); } return x.val-y.val; }); boolean b = true; boolean[] o = new boolean[n]; int j =0; for(int i=0;i<n;i++) { if(a[i].c=='B') { if(j+1<=a[i].val) { o[j]=true; j++; continue; } b= false; break; }else { if(j+1>=a[i].val) { o[j]=true; j++; continue; } b= false; break; } } if(b==false) { System.out.println("NO"); }else { System.out.println("YES"); } t--; } } }
Java
["8\n4\n1 2 5 2\nBRBR\n2\n1 1\nBB\n5\n3 1 4 2 5\nRBRRB\n5\n3 1 3 1 3\nRBRRB\n5\n5 1 5 1 5\nRBRRB\n4\n2 2 2 2\nBRBR\n2\n1 -2\nBR\n4\n-2 -1 4 0\nRRRR"]
1 second
["YES\nNO\nYES\nYES\nNO\nYES\nYES\nYES"]
NoteIn the first test case of the example, the following sequence of moves can be performed: choose $$$i=3$$$, element $$$a_3=5$$$ is blue, so we decrease it, we get $$$a=[1,2,4,2]$$$; choose $$$i=2$$$, element $$$a_2=2$$$ is red, so we increase it, we get $$$a=[1,3,4,2]$$$; choose $$$i=3$$$, element $$$a_3=4$$$ is blue, so we decrease it, we get $$$a=[1,3,3,2]$$$; choose $$$i=2$$$, element $$$a_2=2$$$ is red, so we increase it, we get $$$a=[1,4,3,2]$$$. We got that $$$a$$$ is a permutation. Hence the answer is YES.
Java 11
standard input
[ "greedy", "math", "sortings" ]
c3df88e22a17492d4eb0f3239a27d404
The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of input data sets in the test. The description of each set of input data consists of three lines. The first line contains an integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$) — the length of the original array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$-10^9 \leq a_i \leq 10^9$$$) — the array elements themselves. The third line has length $$$n$$$ and consists exclusively of the letters 'B' and/or 'R': $$$i$$$th character is 'B' if $$$a_i$$$ is colored blue, and is 'R' if colored red. It is guaranteed that the sum of $$$n$$$ over all input sets does not exceed $$$2 \cdot 10^5$$$.
1,300
Print $$$t$$$ lines, each of which contains the answer to the corresponding test case of the input. Print YES as an answer if the corresponding array can be transformed into a permutation, and NO otherwise. You can print the answer in any case (for example, the strings yEs, yes, Yes, and YES will be recognized as a positive answer).
standard output
PASSED
9f8e2ce5c14ef23a3fa3faf38dfb00e3
train_108.jsonl
1635863700
You are given an array of integers $$$a$$$ of length $$$n$$$. The elements of the array can be either different or the same. Each element of the array is colored either blue or red. There are no unpainted elements in the array. One of the two operations described below can be applied to an array in a single step: either you can select any blue element and decrease its value by $$$1$$$; or you can select any red element and increase its value by $$$1$$$. Situations in which there are no elements of some color at all are also possible. For example, if the whole array is colored blue or red, one of the operations becomes unavailable.Determine whether it is possible to make $$$0$$$ or more steps such that the resulting array is a permutation of numbers from $$$1$$$ to $$$n$$$?In other words, check whether there exists a sequence of steps (possibly empty) such that after applying it, the array $$$a$$$ contains in some order all numbers from $$$1$$$ to $$$n$$$ (inclusive), each exactly once.
256 megabytes
//<———My cp———— import java.util.*; import java.io.*; public class D{ public static void main(String[] args) throws Exception{ FastReader fr = new FastReader(System.in); int t = fr.nextInt(); while(t-->0){ int n = fr.nextInt(); int[] vals = new int[n]; for(int i = 0;i<vals.length;i++){ vals[i]=fr.nextInt(); } char[] col = fr.next().toCharArray(); ArrayList<Pair> pairs = new ArrayList<>(); for(int i = 0;i<n;i++){ if(col[i]=='R'){ int start =Integer.max(vals[i], 1); int end = n; pairs.add(new Pair(start, end)); }else{ int start = 1; int end = Integer.min(n, vals[i]); pairs.add(new Pair(start, end)); } } Collections.sort(pairs,new Comparator<Pair>() { @Override public int compare(Pair o1, Pair o2) { if(o1.start==o2.start){ return o1.end-o2.end; }else{ return o1.start-o2.start; } } }); boolean possible = true; int start = 1; for(int i = 0;i<n && possible && start<=n;i++){ if(pairs.get(i).start<=start && pairs.get(i).end>=start){ start++; } } // System.out.println(pairs); // System.out.println(start); // System.out.println(possible); if(possible && start>n){ System.out.println("YES"); }else{ System.out.println("NO"); } } } static class Pair{ int start; int end; public Pair(int start,int end){ this.start = start; this.end = end; } @Override public String toString() { return "start: "+start+" end:"+end+"\n"; } } public static void print(Object val){ System.out.print(val); } public static void println(Object val){ System.out.println(val); } public static int[] sort(int[] vals){ ArrayList<Integer> values = new ArrayList<>(); for(int i = 0;i<vals.length;i++){ values.add(vals[i]); } Collections.sort(values); for(int i =0;i<values.size();i++){ vals[i] = values.get(i); } return vals; } public static long[] sort(long[] vals){ ArrayList<Long> values = new ArrayList<>(); for(int i = 0;i<vals.length;i++){ values.add(vals[i]); } Collections.sort(values); for(int i =0;i<values.size();i++){ vals[i] = values.get(i); } return vals; } public static void reverseArray(long[] vals){ int startIndex = 0; int endIndex = vals.length-1; while(startIndex<=endIndex){ long temp = vals[startIndex]; vals[startIndex] = vals[endIndex]; vals[endIndex] = temp; startIndex++; endIndex--; } } public static void reverseArray(int[] vals){ int startIndex = 0; int endIndex = vals.length-1; while(startIndex<=endIndex){ int temp = vals[startIndex]; vals[startIndex] = vals[endIndex]; vals[endIndex] = temp; startIndex++; endIndex--; } } static class FastReader{ byte[] buf = new byte[2048]; int index, total; InputStream in; FastReader(InputStream is) { in = is; } int scan() throws IOException { if (index >= total) { index = 0; total = in.read(buf); if (total <= 0) { return -1; } } return buf[index++]; } String next() throws IOException { int c; for (c = scan(); c <= 32; c = scan()); StringBuilder sb = new StringBuilder(); for (; c > 32; c = scan()) { sb.append((char) c); } return sb.toString(); } int nextInt() throws IOException { int c, val = 0; for (c = scan(); c <= 32; c = scan()); boolean neg = c == '-'; if (c == '-' || c == '+') { c = scan(); } for (; c >= '0' && c <= '9'; c = scan()) { val = (val << 3) + (val << 1) + (c & 15); } return neg ? -val : val; } long nextLong() throws IOException { int c; long val = 0; for (c = scan(); c <= 32; c = scan()); boolean neg = c == '-'; if (c == '-' || c == '+') { c = scan(); } for (; c >= '0' && c <= '9'; c = scan()) { val = (val << 3) + (val << 1) + (c & 15); } return neg ? -val : val; } } public static int GCD(int numA, int numB){ if(numA==0){ return numB; }else if(numB==0){ return numA; }else{ if(numA>numB){ return GCD(numA%numB,numB); }else{ return GCD(numA,numB%numA); } } } }
Java
["8\n4\n1 2 5 2\nBRBR\n2\n1 1\nBB\n5\n3 1 4 2 5\nRBRRB\n5\n3 1 3 1 3\nRBRRB\n5\n5 1 5 1 5\nRBRRB\n4\n2 2 2 2\nBRBR\n2\n1 -2\nBR\n4\n-2 -1 4 0\nRRRR"]
1 second
["YES\nNO\nYES\nYES\nNO\nYES\nYES\nYES"]
NoteIn the first test case of the example, the following sequence of moves can be performed: choose $$$i=3$$$, element $$$a_3=5$$$ is blue, so we decrease it, we get $$$a=[1,2,4,2]$$$; choose $$$i=2$$$, element $$$a_2=2$$$ is red, so we increase it, we get $$$a=[1,3,4,2]$$$; choose $$$i=3$$$, element $$$a_3=4$$$ is blue, so we decrease it, we get $$$a=[1,3,3,2]$$$; choose $$$i=2$$$, element $$$a_2=2$$$ is red, so we increase it, we get $$$a=[1,4,3,2]$$$. We got that $$$a$$$ is a permutation. Hence the answer is YES.
Java 11
standard input
[ "greedy", "math", "sortings" ]
c3df88e22a17492d4eb0f3239a27d404
The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of input data sets in the test. The description of each set of input data consists of three lines. The first line contains an integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$) — the length of the original array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$-10^9 \leq a_i \leq 10^9$$$) — the array elements themselves. The third line has length $$$n$$$ and consists exclusively of the letters 'B' and/or 'R': $$$i$$$th character is 'B' if $$$a_i$$$ is colored blue, and is 'R' if colored red. It is guaranteed that the sum of $$$n$$$ over all input sets does not exceed $$$2 \cdot 10^5$$$.
1,300
Print $$$t$$$ lines, each of which contains the answer to the corresponding test case of the input. Print YES as an answer if the corresponding array can be transformed into a permutation, and NO otherwise. You can print the answer in any case (for example, the strings yEs, yes, Yes, and YES will be recognized as a positive answer).
standard output
PASSED
74c96116775122153f44185a0aba0687
train_108.jsonl
1635863700
You are given an array of integers $$$a$$$ of length $$$n$$$. The elements of the array can be either different or the same. Each element of the array is colored either blue or red. There are no unpainted elements in the array. One of the two operations described below can be applied to an array in a single step: either you can select any blue element and decrease its value by $$$1$$$; or you can select any red element and increase its value by $$$1$$$. Situations in which there are no elements of some color at all are also possible. For example, if the whole array is colored blue or red, one of the operations becomes unavailable.Determine whether it is possible to make $$$0$$$ or more steps such that the resulting array is a permutation of numbers from $$$1$$$ to $$$n$$$?In other words, check whether there exists a sequence of steps (possibly empty) such that after applying it, the array $$$a$$$ contains in some order all numbers from $$$1$$$ to $$$n$$$ (inclusive), each exactly once.
256 megabytes
import java.io.*; import java.util.*; public class Test{ static boolean palindrome(String s,int i,int j) { if(j==s.length())return false; while(i<j) { if(s.charAt(i)!=s.charAt(j))return false; i++;j--; } return true; } static int valid(String s,int i) { Stack<Character>st=new Stack<>(); int n=s.length(); return -1; } static int msb(long num){ int c=0; while(num!=0) { num>>=1; c++; } return c-1; } static boolean isPrime(long n, int k) { // Corner cases if (n <= 1 || n == 4) return false; if (n <= 3) return true; // Try k times while (k > 0) { // Pick a random number in [2..n-2] // Above corner cases make sure that n > 4 int a = 2 + (int)(Math.random() % (n - 4)); // Fermat's little theorem if (Math.pow(a,n - 1) != 1) return false; k--; } return true; } static void swap(int a[],int i,int j){ int temp=a[i]; a[i]=a[j]; a[j]=temp; } static boolean collinear(int x1, int y1, int x2, int y2, int x3, int y3) { int a = x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2); if (a == 0)return true; else return false; } public static void main(String[] args) throws ArithmeticException{ FastScanner fs=new FastScanner(); int t=fs.nextInt(); while(t-->0){ int n=fs.nextInt(); int a[][]=new int[n][2]; for(int i=0;i<n;i++){ a[i][0]=fs.nextInt(); } String s=fs.next(); for(int i=0;i<n;i++){ a[i][1]=s.charAt(i)-'B'; } Arrays.sort(a, (b,c)->{ if(b[1]==c[1])return b[0]-c[0]; return b[1]-c[1]; }); boolean ans=true; for(int i=1;i<=n;i++){ if(a[i-1][1]==0 && a[i-1][0]<i)ans=false; else if(a[i-1][1]!=0 && a[i-1][0]>i)ans=false; } if(ans) System.out.println("yes"); else System.out.println("no"); } } } class FastScanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); String next(){ while (!st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } char nextChar() { return next().charAt(0); } }
Java
["8\n4\n1 2 5 2\nBRBR\n2\n1 1\nBB\n5\n3 1 4 2 5\nRBRRB\n5\n3 1 3 1 3\nRBRRB\n5\n5 1 5 1 5\nRBRRB\n4\n2 2 2 2\nBRBR\n2\n1 -2\nBR\n4\n-2 -1 4 0\nRRRR"]
1 second
["YES\nNO\nYES\nYES\nNO\nYES\nYES\nYES"]
NoteIn the first test case of the example, the following sequence of moves can be performed: choose $$$i=3$$$, element $$$a_3=5$$$ is blue, so we decrease it, we get $$$a=[1,2,4,2]$$$; choose $$$i=2$$$, element $$$a_2=2$$$ is red, so we increase it, we get $$$a=[1,3,4,2]$$$; choose $$$i=3$$$, element $$$a_3=4$$$ is blue, so we decrease it, we get $$$a=[1,3,3,2]$$$; choose $$$i=2$$$, element $$$a_2=2$$$ is red, so we increase it, we get $$$a=[1,4,3,2]$$$. We got that $$$a$$$ is a permutation. Hence the answer is YES.
Java 11
standard input
[ "greedy", "math", "sortings" ]
c3df88e22a17492d4eb0f3239a27d404
The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of input data sets in the test. The description of each set of input data consists of three lines. The first line contains an integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$) — the length of the original array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$-10^9 \leq a_i \leq 10^9$$$) — the array elements themselves. The third line has length $$$n$$$ and consists exclusively of the letters 'B' and/or 'R': $$$i$$$th character is 'B' if $$$a_i$$$ is colored blue, and is 'R' if colored red. It is guaranteed that the sum of $$$n$$$ over all input sets does not exceed $$$2 \cdot 10^5$$$.
1,300
Print $$$t$$$ lines, each of which contains the answer to the corresponding test case of the input. Print YES as an answer if the corresponding array can be transformed into a permutation, and NO otherwise. You can print the answer in any case (for example, the strings yEs, yes, Yes, and YES will be recognized as a positive answer).
standard output
PASSED
07db74018fa3a78ec433a6ee4e9cf96d
train_108.jsonl
1635863700
You are given an array of integers $$$a$$$ of length $$$n$$$. The elements of the array can be either different or the same. Each element of the array is colored either blue or red. There are no unpainted elements in the array. One of the two operations described below can be applied to an array in a single step: either you can select any blue element and decrease its value by $$$1$$$; or you can select any red element and increase its value by $$$1$$$. Situations in which there are no elements of some color at all are also possible. For example, if the whole array is colored blue or red, one of the operations becomes unavailable.Determine whether it is possible to make $$$0$$$ or more steps such that the resulting array is a permutation of numbers from $$$1$$$ to $$$n$$$?In other words, check whether there exists a sequence of steps (possibly empty) such that after applying it, the array $$$a$$$ contains in some order all numbers from $$$1$$$ to $$$n$$$ (inclusive), each exactly once.
256 megabytes
import java.util.Collections; import java.util.Scanner; import java.util.Vector; public class BlueRedPermutation { 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]; for (int i = 0; i < n; i++) { a[i] = sc.nextInt(); } String s = sc.next(); Vector<Integer> b = new Vector<>(), r = new Vector<>(); for (int i = 0; i < n; i++) { (s.charAt(i) == 'B' ? b : r).add(a[i]); } Collections.sort(b); r.sort(Collections.reverseOrder()); boolean ok = true; for (int i = 0; i < b.size(); i++) { if (b.get(i) < i + 1) { ok = false; break; } } for (int i = 0; i < r.size(); i++) { if (r.get(i) > n - i) { ok = false; break; } } System.out.print((ok ? "YES" : "NO") + '\n'); } } }
Java
["8\n4\n1 2 5 2\nBRBR\n2\n1 1\nBB\n5\n3 1 4 2 5\nRBRRB\n5\n3 1 3 1 3\nRBRRB\n5\n5 1 5 1 5\nRBRRB\n4\n2 2 2 2\nBRBR\n2\n1 -2\nBR\n4\n-2 -1 4 0\nRRRR"]
1 second
["YES\nNO\nYES\nYES\nNO\nYES\nYES\nYES"]
NoteIn the first test case of the example, the following sequence of moves can be performed: choose $$$i=3$$$, element $$$a_3=5$$$ is blue, so we decrease it, we get $$$a=[1,2,4,2]$$$; choose $$$i=2$$$, element $$$a_2=2$$$ is red, so we increase it, we get $$$a=[1,3,4,2]$$$; choose $$$i=3$$$, element $$$a_3=4$$$ is blue, so we decrease it, we get $$$a=[1,3,3,2]$$$; choose $$$i=2$$$, element $$$a_2=2$$$ is red, so we increase it, we get $$$a=[1,4,3,2]$$$. We got that $$$a$$$ is a permutation. Hence the answer is YES.
Java 11
standard input
[ "greedy", "math", "sortings" ]
c3df88e22a17492d4eb0f3239a27d404
The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of input data sets in the test. The description of each set of input data consists of three lines. The first line contains an integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$) — the length of the original array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$-10^9 \leq a_i \leq 10^9$$$) — the array elements themselves. The third line has length $$$n$$$ and consists exclusively of the letters 'B' and/or 'R': $$$i$$$th character is 'B' if $$$a_i$$$ is colored blue, and is 'R' if colored red. It is guaranteed that the sum of $$$n$$$ over all input sets does not exceed $$$2 \cdot 10^5$$$.
1,300
Print $$$t$$$ lines, each of which contains the answer to the corresponding test case of the input. Print YES as an answer if the corresponding array can be transformed into a permutation, and NO otherwise. You can print the answer in any case (for example, the strings yEs, yes, Yes, and YES will be recognized as a positive answer).
standard output
PASSED
f33c56d083cc6c1cadc19d0c0c5958d7
train_108.jsonl
1635863700
You are given an array of integers $$$a$$$ of length $$$n$$$. The elements of the array can be either different or the same. Each element of the array is colored either blue or red. There are no unpainted elements in the array. One of the two operations described below can be applied to an array in a single step: either you can select any blue element and decrease its value by $$$1$$$; or you can select any red element and increase its value by $$$1$$$. Situations in which there are no elements of some color at all are also possible. For example, if the whole array is colored blue or red, one of the operations becomes unavailable.Determine whether it is possible to make $$$0$$$ or more steps such that the resulting array is a permutation of numbers from $$$1$$$ to $$$n$$$?In other words, check whether there exists a sequence of steps (possibly empty) such that after applying it, the array $$$a$$$ contains in some order all numbers from $$$1$$$ to $$$n$$$ (inclusive), each exactly once.
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; public class A { public static void main(String[] args) throws IOException { InputStreamReader re=new InputStreamReader(System.in); BufferedReader br=new BufferedReader(re); int t = Integer.parseInt(br.readLine()); int i,j,k; for(i=0;i<t;i++) { int n = Integer.parseInt(br.readLine()); String s = br.readLine(); String[] c = s.split(" "); int[] arr = new int[n]; ArrayList<Integer> r = new ArrayList<>(); ArrayList<Integer> b = new ArrayList<>(); for(j=0;j<n;j++) arr[j] = Integer.parseInt(c[j]); s = br.readLine(); for(j=0;j<n;j++) { if(s.charAt(j)=='R') r.add(arr[j]); else b.add(arr[j]); } Collections.sort(r); Collections.sort(b); int flag,g; int in1 = 0; int in2 = 0; for(j=1;j<=n;j++) { flag = 0; //System.out.println(j+" "+r.size()+" "+b.size()); if(in1<b.size()) { g = b.get(in1); //System.out.println("h"+g); if(g<1) break; if(g>=j) { flag = 1; in1++; } } if(flag==0 && in2<r.size()) { g = r.get(in2); //System.out.println("hi"+g); if(g>n) break; if(g<=j){ flag = 1; in2++; } } if(flag==0) break; } if(j!=n+1) System.out.println("NO"); else System.out.println("YES"); } } static long solve(long[] arr,long l,long r, int n,int k) { int j; if(l<=r) { long m = l+(r-l)/2; long sum = arr[0]+m; for(j=1;j<n;j++) { if((double)arr[j]> (double)(sum*k)/(double)100) break; sum+=arr[j]; } if(j==n) return solve(arr,l,m-1,n,k); else return solve(arr,m+1,r,n,k); } return l; } static long factorial(long n) { return (n == 1 || n == 0) ? 1 : n * factorial(n - 1); } static long setbitNumber(long n) { long k = (int)(Math.log(n) / Math.log(2)); return 1 << k; } static void leftrotate(int arr[],int i, int n) { int t = arr[i]; int f; int j = i+1; for(;j<=n;j++) { f = arr[j]; arr[j] = t; t = f; } arr[i] = t; } static int search(int l, int r,int x, int[]arr) { if (r >= l) { int mid = l + (r - l) / 2; if (arr[mid] == x) return mid; if (arr[mid] > x) return search( l, mid - 1, x,arr); return search( mid + 1, r, x,arr); } return -1; } static long combination(long n, long k){ // nCr combination long res = 1; 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; } 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; } static int xor(int n){ // If n is a multiple of 4 if (n % 4 == 0) return n; // If n%4 gives remainder 1 if (n % 4 == 1) return 1; // If n%4 gives remainder 2 if (n % 4 == 2) return n + 1; return 0; } static int getsum(int n) // sum of digits { int sum = 0; while (n != 0) { sum = sum + n % 10; n = n/10; } return sum; } static boolean isPrime(int n) // check prime { 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 long gcd(long a, long b) { if (a == 0) return b; return gcd(b % a, a); } }
Java
["8\n4\n1 2 5 2\nBRBR\n2\n1 1\nBB\n5\n3 1 4 2 5\nRBRRB\n5\n3 1 3 1 3\nRBRRB\n5\n5 1 5 1 5\nRBRRB\n4\n2 2 2 2\nBRBR\n2\n1 -2\nBR\n4\n-2 -1 4 0\nRRRR"]
1 second
["YES\nNO\nYES\nYES\nNO\nYES\nYES\nYES"]
NoteIn the first test case of the example, the following sequence of moves can be performed: choose $$$i=3$$$, element $$$a_3=5$$$ is blue, so we decrease it, we get $$$a=[1,2,4,2]$$$; choose $$$i=2$$$, element $$$a_2=2$$$ is red, so we increase it, we get $$$a=[1,3,4,2]$$$; choose $$$i=3$$$, element $$$a_3=4$$$ is blue, so we decrease it, we get $$$a=[1,3,3,2]$$$; choose $$$i=2$$$, element $$$a_2=2$$$ is red, so we increase it, we get $$$a=[1,4,3,2]$$$. We got that $$$a$$$ is a permutation. Hence the answer is YES.
Java 11
standard input
[ "greedy", "math", "sortings" ]
c3df88e22a17492d4eb0f3239a27d404
The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of input data sets in the test. The description of each set of input data consists of three lines. The first line contains an integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$) — the length of the original array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$-10^9 \leq a_i \leq 10^9$$$) — the array elements themselves. The third line has length $$$n$$$ and consists exclusively of the letters 'B' and/or 'R': $$$i$$$th character is 'B' if $$$a_i$$$ is colored blue, and is 'R' if colored red. It is guaranteed that the sum of $$$n$$$ over all input sets does not exceed $$$2 \cdot 10^5$$$.
1,300
Print $$$t$$$ lines, each of which contains the answer to the corresponding test case of the input. Print YES as an answer if the corresponding array can be transformed into a permutation, and NO otherwise. You can print the answer in any case (for example, the strings yEs, yes, Yes, and YES will be recognized as a positive answer).
standard output
PASSED
d92177131d8b9224b29ba23e82575228
train_108.jsonl
1635863700
You are given an array of integers $$$a$$$ of length $$$n$$$. The elements of the array can be either different or the same. Each element of the array is colored either blue or red. There are no unpainted elements in the array. One of the two operations described below can be applied to an array in a single step: either you can select any blue element and decrease its value by $$$1$$$; or you can select any red element and increase its value by $$$1$$$. Situations in which there are no elements of some color at all are also possible. For example, if the whole array is colored blue or red, one of the operations becomes unavailable.Determine whether it is possible to make $$$0$$$ or more steps such that the resulting array is a permutation of numbers from $$$1$$$ to $$$n$$$?In other words, check whether there exists a sequence of steps (possibly empty) such that after applying it, the array $$$a$$$ contains in some order all numbers from $$$1$$$ to $$$n$$$ (inclusive), each exactly once.
256 megabytes
// ceil using integer division: ceil(x/y) = (x+y-1)/y import java.lang.reflect.Array; import java.util.*; import java.lang.*; import java.io.*; public class practice { static ArrayList<ArrayList<Integer>> graph; public static void main(String[] args) throws IOException { Reader.init(System.in); int t = Reader.nextInt(); while(t-->0){ int n = Reader.nextInt(); Long[] arr = new Long[n]; for(int i = 0;i<n;i++){ arr[i] = Reader.nextLong(); } String s = Reader.next(); ArrayList<Long> red = new ArrayList<>(); ArrayList<Long> blue = new ArrayList<>(); for(int i = 0;i<n;i++){ if(s.charAt(i)=='B'){ blue.add(arr[i]); } else red.add(arr[i]); } boolean flag = true; Collections.sort(blue); Collections.sort(red); if(red.size()==0){ for(int i = 0;i<n;i++){ if(blue.get(i)<i+1){ flag = false; break; } } if(flag) System.out.println("YES"); else System.out.println("NO"); continue; } else if(blue.size()==0){ for(int i = 0;i<n;i++){ if(red.get(i)>i+1){ flag = false; break; } } if(flag) System.out.println("YES"); else System.out.println("NO"); continue; } int i = 0, j = 0; int v = 1; for(int k = 1;k<=n;k++){ if(j==blue.size()){ v = k; break; } if(blue.get(j)<k){ flag = false; break; } j++; } for(;i<red.size();i++){ if(red.get(i)>v){ flag = false; break; } v++; } if(flag) System.out.println("YES"); else System.out.println("NO"); } } } class Reader { static BufferedReader reader; static StringTokenizer tokenizer; /** call this method to initialize reader for InputStream */ static void init(InputStream input) { reader = new BufferedReader( new InputStreamReader(input) ); tokenizer = new StringTokenizer(""); } /** get next word */ static String next() throws IOException { while ( ! tokenizer.hasMoreTokens() ) { //TODO add check for eof if necessary tokenizer = new StringTokenizer( reader.readLine() ); } return tokenizer.nextToken(); } static String nextLine() throws IOException { return reader.readLine(); } static int nextInt() throws IOException { return Integer.parseInt( next() ); } static long nextLong() throws IOException{ return Long.parseLong(next() ); } static double nextDouble() throws IOException { return Double.parseDouble( next() ); } }
Java
["8\n4\n1 2 5 2\nBRBR\n2\n1 1\nBB\n5\n3 1 4 2 5\nRBRRB\n5\n3 1 3 1 3\nRBRRB\n5\n5 1 5 1 5\nRBRRB\n4\n2 2 2 2\nBRBR\n2\n1 -2\nBR\n4\n-2 -1 4 0\nRRRR"]
1 second
["YES\nNO\nYES\nYES\nNO\nYES\nYES\nYES"]
NoteIn the first test case of the example, the following sequence of moves can be performed: choose $$$i=3$$$, element $$$a_3=5$$$ is blue, so we decrease it, we get $$$a=[1,2,4,2]$$$; choose $$$i=2$$$, element $$$a_2=2$$$ is red, so we increase it, we get $$$a=[1,3,4,2]$$$; choose $$$i=3$$$, element $$$a_3=4$$$ is blue, so we decrease it, we get $$$a=[1,3,3,2]$$$; choose $$$i=2$$$, element $$$a_2=2$$$ is red, so we increase it, we get $$$a=[1,4,3,2]$$$. We got that $$$a$$$ is a permutation. Hence the answer is YES.
Java 11
standard input
[ "greedy", "math", "sortings" ]
c3df88e22a17492d4eb0f3239a27d404
The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of input data sets in the test. The description of each set of input data consists of three lines. The first line contains an integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$) — the length of the original array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$-10^9 \leq a_i \leq 10^9$$$) — the array elements themselves. The third line has length $$$n$$$ and consists exclusively of the letters 'B' and/or 'R': $$$i$$$th character is 'B' if $$$a_i$$$ is colored blue, and is 'R' if colored red. It is guaranteed that the sum of $$$n$$$ over all input sets does not exceed $$$2 \cdot 10^5$$$.
1,300
Print $$$t$$$ lines, each of which contains the answer to the corresponding test case of the input. Print YES as an answer if the corresponding array can be transformed into a permutation, and NO otherwise. You can print the answer in any case (for example, the strings yEs, yes, Yes, and YES will be recognized as a positive answer).
standard output
PASSED
4eaf6e3d12b1531dc7fe3775baf87bad
train_108.jsonl
1635863700
You are given an array of integers $$$a$$$ of length $$$n$$$. The elements of the array can be either different or the same. Each element of the array is colored either blue or red. There are no unpainted elements in the array. One of the two operations described below can be applied to an array in a single step: either you can select any blue element and decrease its value by $$$1$$$; or you can select any red element and increase its value by $$$1$$$. Situations in which there are no elements of some color at all are also possible. For example, if the whole array is colored blue or red, one of the operations becomes unavailable.Determine whether it is possible to make $$$0$$$ or more steps such that the resulting array is a permutation of numbers from $$$1$$$ to $$$n$$$?In other words, check whether there exists a sequence of steps (possibly empty) such that after applying it, the array $$$a$$$ contains in some order all numbers from $$$1$$$ to $$$n$$$ (inclusive), each exactly once.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.BufferedWriter; import java.util.InputMismatchException; import java.io.IOException; import java.util.TreeMap; import java.util.Map; import java.util.Map.Entry; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.Collections; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author saikat021 */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } static class TaskD { public void solve(int testNumber, InputReader in, OutputWriter out) { int T = in.nextInt(); while (T-- > 0) { int n = in.nextInt(), i, cnt = 0; int[] arr = in.nextIntArray(n); String colors = in.readLine(); TreeMap<Integer, Integer> mapB = new TreeMap<>(), mapR = new TreeMap<>(Collections.reverseOrder()); boolean outOfRange = false; for (i = 0; i < n; i++) { if (colors.charAt(i) == 'B') { if (arr[i] < 1) { outOfRange = true; break; } else if (arr[i] >= 1 && arr[i] <= n) { if (mapB.containsKey(arr[i])) { mapB.put(arr[i], mapB.get(arr[i]) + 1); } else { mapB.put(arr[i], 1); } } else { cnt++; } } else { //R if (arr[i] > n) { outOfRange = true; } else if (arr[i] >= 1 && arr[i] <= n) { if (mapR.containsKey(arr[i])) { mapR.put(arr[i], mapR.get(arr[i]) + 1); } else { mapR.put(arr[i], 1); } } else { cnt++; } } } if (outOfRange) { out.println("NO"); } else { boolean notProssible = false; int cntB = 0; for (Map.Entry<Integer, Integer> e : mapB.entrySet()) { if (e.getValue() > (e.getKey() - cntB)) { notProssible = true; break; } else { cntB += e.getValue(); cnt += e.getValue(); } } int cntR = 0; for (Map.Entry<Integer, Integer> e : mapR.entrySet()) { if (e.getValue() > (n + 1 - e.getKey() - cntR)) { notProssible = true; break; } else { cntR += e.getValue(); cnt += e.getValue(); } } if (cnt == n && !notProssible) { out.println("YES"); } else { out.println("NO"); } } } } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) { writer.print(' '); } writer.print(objects[i]); } } public void println(Object... objects) { print(objects); writer.println(); } public void close() { writer.close(); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private String readLine0() { StringBuilder buf = new StringBuilder(); int c = read(); while (c != '\n' && c != -1) { if (c != '\r') { buf.appendCodePoint(c); } c = read(); } return buf.toString(); } public String readLine() { String s = readLine0(); while (s.trim().length() == 0) { s = readLine0(); } return s; } public int[] nextIntArray(int n) { int[] array = new int[n]; for (int i = 0; i < n; ++i) array[i] = nextInt(); return array; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["8\n4\n1 2 5 2\nBRBR\n2\n1 1\nBB\n5\n3 1 4 2 5\nRBRRB\n5\n3 1 3 1 3\nRBRRB\n5\n5 1 5 1 5\nRBRRB\n4\n2 2 2 2\nBRBR\n2\n1 -2\nBR\n4\n-2 -1 4 0\nRRRR"]
1 second
["YES\nNO\nYES\nYES\nNO\nYES\nYES\nYES"]
NoteIn the first test case of the example, the following sequence of moves can be performed: choose $$$i=3$$$, element $$$a_3=5$$$ is blue, so we decrease it, we get $$$a=[1,2,4,2]$$$; choose $$$i=2$$$, element $$$a_2=2$$$ is red, so we increase it, we get $$$a=[1,3,4,2]$$$; choose $$$i=3$$$, element $$$a_3=4$$$ is blue, so we decrease it, we get $$$a=[1,3,3,2]$$$; choose $$$i=2$$$, element $$$a_2=2$$$ is red, so we increase it, we get $$$a=[1,4,3,2]$$$. We got that $$$a$$$ is a permutation. Hence the answer is YES.
Java 11
standard input
[ "greedy", "math", "sortings" ]
c3df88e22a17492d4eb0f3239a27d404
The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of input data sets in the test. The description of each set of input data consists of three lines. The first line contains an integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$) — the length of the original array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$-10^9 \leq a_i \leq 10^9$$$) — the array elements themselves. The third line has length $$$n$$$ and consists exclusively of the letters 'B' and/or 'R': $$$i$$$th character is 'B' if $$$a_i$$$ is colored blue, and is 'R' if colored red. It is guaranteed that the sum of $$$n$$$ over all input sets does not exceed $$$2 \cdot 10^5$$$.
1,300
Print $$$t$$$ lines, each of which contains the answer to the corresponding test case of the input. Print YES as an answer if the corresponding array can be transformed into a permutation, and NO otherwise. You can print the answer in any case (for example, the strings yEs, yes, Yes, and YES will be recognized as a positive answer).
standard output
PASSED
ab5c982e92e21962f4136d66f755e871
train_108.jsonl
1635863700
You are given an array of integers $$$a$$$ of length $$$n$$$. The elements of the array can be either different or the same. Each element of the array is colored either blue or red. There are no unpainted elements in the array. One of the two operations described below can be applied to an array in a single step: either you can select any blue element and decrease its value by $$$1$$$; or you can select any red element and increase its value by $$$1$$$. Situations in which there are no elements of some color at all are also possible. For example, if the whole array is colored blue or red, one of the operations becomes unavailable.Determine whether it is possible to make $$$0$$$ or more steps such that the resulting array is a permutation of numbers from $$$1$$$ to $$$n$$$?In other words, check whether there exists a sequence of steps (possibly empty) such that after applying it, the array $$$a$$$ contains in some order all numbers from $$$1$$$ to $$$n$$$ (inclusive), each exactly once.
256 megabytes
import java.util.*; public class Main{ public static void main(String args[]) { Scanner s=new Scanner(System.in); int t=s.nextInt(); while(t-->0) { int n=s.nextInt(); int a[]=new int[n]; for(int i=0;i<n;i++) { a[i]=s.nextInt(); } String str=s.next(); int red=0; int blue=0; for(int i=0;i<n;i++) { if(str.charAt(i)=='B') { blue++; } else { red++; } } int rc=0; int bc=0; int b[]=new int[blue]; int r[]=new int[red]; for(int i=0;i<n;i++) { if(str.charAt(i)=='R') { r[rc++]=a[i]; } else { b[bc++]=a[i]; } } Arrays.sort(r); Arrays.sort(b); int f=0; for(int i=0;i<blue;i++) { if(b[i]>=i+1) { } else { System.out.println("NO"); f=1; break; } } if(f==1) { continue; } for(int i=0;i<red;i++) { if(r[i]<=i+blue+1) { } else { System.out.println("NO"); f=1; break; } } if(f==1) { continue; } System.out.println("YES"); } } }
Java
["8\n4\n1 2 5 2\nBRBR\n2\n1 1\nBB\n5\n3 1 4 2 5\nRBRRB\n5\n3 1 3 1 3\nRBRRB\n5\n5 1 5 1 5\nRBRRB\n4\n2 2 2 2\nBRBR\n2\n1 -2\nBR\n4\n-2 -1 4 0\nRRRR"]
1 second
["YES\nNO\nYES\nYES\nNO\nYES\nYES\nYES"]
NoteIn the first test case of the example, the following sequence of moves can be performed: choose $$$i=3$$$, element $$$a_3=5$$$ is blue, so we decrease it, we get $$$a=[1,2,4,2]$$$; choose $$$i=2$$$, element $$$a_2=2$$$ is red, so we increase it, we get $$$a=[1,3,4,2]$$$; choose $$$i=3$$$, element $$$a_3=4$$$ is blue, so we decrease it, we get $$$a=[1,3,3,2]$$$; choose $$$i=2$$$, element $$$a_2=2$$$ is red, so we increase it, we get $$$a=[1,4,3,2]$$$. We got that $$$a$$$ is a permutation. Hence the answer is YES.
Java 11
standard input
[ "greedy", "math", "sortings" ]
c3df88e22a17492d4eb0f3239a27d404
The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of input data sets in the test. The description of each set of input data consists of three lines. The first line contains an integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$) — the length of the original array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$-10^9 \leq a_i \leq 10^9$$$) — the array elements themselves. The third line has length $$$n$$$ and consists exclusively of the letters 'B' and/or 'R': $$$i$$$th character is 'B' if $$$a_i$$$ is colored blue, and is 'R' if colored red. It is guaranteed that the sum of $$$n$$$ over all input sets does not exceed $$$2 \cdot 10^5$$$.
1,300
Print $$$t$$$ lines, each of which contains the answer to the corresponding test case of the input. Print YES as an answer if the corresponding array can be transformed into a permutation, and NO otherwise. You can print the answer in any case (for example, the strings yEs, yes, Yes, and YES will be recognized as a positive answer).
standard output
PASSED
cb6178ab6443dfadec883890fb5450cc
train_108.jsonl
1635863700
You are given an array of integers $$$a$$$ of length $$$n$$$. The elements of the array can be either different or the same. Each element of the array is colored either blue or red. There are no unpainted elements in the array. One of the two operations described below can be applied to an array in a single step: either you can select any blue element and decrease its value by $$$1$$$; or you can select any red element and increase its value by $$$1$$$. Situations in which there are no elements of some color at all are also possible. For example, if the whole array is colored blue or red, one of the operations becomes unavailable.Determine whether it is possible to make $$$0$$$ or more steps such that the resulting array is a permutation of numbers from $$$1$$$ to $$$n$$$?In other words, check whether there exists a sequence of steps (possibly empty) such that after applying it, the array $$$a$$$ contains in some order all numbers from $$$1$$$ to $$$n$$$ (inclusive), each exactly once.
256 megabytes
import java.io.*; import java.util.*; public class a { public static void printArray(Object[] a) { for (Object x : a) System.out.print(x + " "); System.out.println(); } public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringBuilder str = new StringBuilder(); int t = Integer.parseInt(br.readLine()); while (t-- > 0) { int n = Integer.parseInt(br.readLine()); String[] l = br.readLine().split(" "); Long[] arr = new Long[n]; for (int i = 0; i < n; i++) arr[i] = Long.parseLong(l[i]); String string = br.readLine(); boolean ans = true; ArrayList<Long> left = new ArrayList<>(); ArrayList<Long> right = new ArrayList<>(); for (int i = 0; i < n; i++) { char ch = string.charAt(i); if (ch == 'B') left.add(arr[i]); else right.add(arr[i]); } Collections.sort(left); Collections.sort(right, Collections.reverseOrder()); for (int i = 0; i < left.size(); i++) { if (left.get(i) < i + 1) { ans = false; break; } } for (int i = 0; i < right.size(); i++) { if (right.get(i) > n - i) { ans = false; break; } } str.append((ans)?"YES\n":"NO\n"); } System.out.print(str); } }
Java
["8\n4\n1 2 5 2\nBRBR\n2\n1 1\nBB\n5\n3 1 4 2 5\nRBRRB\n5\n3 1 3 1 3\nRBRRB\n5\n5 1 5 1 5\nRBRRB\n4\n2 2 2 2\nBRBR\n2\n1 -2\nBR\n4\n-2 -1 4 0\nRRRR"]
1 second
["YES\nNO\nYES\nYES\nNO\nYES\nYES\nYES"]
NoteIn the first test case of the example, the following sequence of moves can be performed: choose $$$i=3$$$, element $$$a_3=5$$$ is blue, so we decrease it, we get $$$a=[1,2,4,2]$$$; choose $$$i=2$$$, element $$$a_2=2$$$ is red, so we increase it, we get $$$a=[1,3,4,2]$$$; choose $$$i=3$$$, element $$$a_3=4$$$ is blue, so we decrease it, we get $$$a=[1,3,3,2]$$$; choose $$$i=2$$$, element $$$a_2=2$$$ is red, so we increase it, we get $$$a=[1,4,3,2]$$$. We got that $$$a$$$ is a permutation. Hence the answer is YES.
Java 11
standard input
[ "greedy", "math", "sortings" ]
c3df88e22a17492d4eb0f3239a27d404
The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of input data sets in the test. The description of each set of input data consists of three lines. The first line contains an integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$) — the length of the original array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$-10^9 \leq a_i \leq 10^9$$$) — the array elements themselves. The third line has length $$$n$$$ and consists exclusively of the letters 'B' and/or 'R': $$$i$$$th character is 'B' if $$$a_i$$$ is colored blue, and is 'R' if colored red. It is guaranteed that the sum of $$$n$$$ over all input sets does not exceed $$$2 \cdot 10^5$$$.
1,300
Print $$$t$$$ lines, each of which contains the answer to the corresponding test case of the input. Print YES as an answer if the corresponding array can be transformed into a permutation, and NO otherwise. You can print the answer in any case (for example, the strings yEs, yes, Yes, and YES will be recognized as a positive answer).
standard output
PASSED
6607bbbd5ad36e885f610af3bcb76f97
train_108.jsonl
1635863700
You are given an array of integers $$$a$$$ of length $$$n$$$. The elements of the array can be either different or the same. Each element of the array is colored either blue or red. There are no unpainted elements in the array. One of the two operations described below can be applied to an array in a single step: either you can select any blue element and decrease its value by $$$1$$$; or you can select any red element and increase its value by $$$1$$$. Situations in which there are no elements of some color at all are also possible. For example, if the whole array is colored blue or red, one of the operations becomes unavailable.Determine whether it is possible to make $$$0$$$ or more steps such that the resulting array is a permutation of numbers from $$$1$$$ to $$$n$$$?In other words, check whether there exists a sequence of steps (possibly empty) such that after applying it, the array $$$a$$$ contains in some order all numbers from $$$1$$$ to $$$n$$$ (inclusive), each exactly once.
256 megabytes
// package c1607; import java.io.File; import java.lang.invoke.MethodHandles; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Random; import java.util.Scanner; // // Codeforces Round #753 (Div. 3) 2021-11-02 06:35 // D. Blue-Red Permutation // https://codeforces.com/contest/1607/problem/D // time limit per test 1 second; memory limit per test 256 megabytes // public class Pseudo for 'Source should satisfy regex [^{}]*public\s+(final)?\s*class\s+(\w+).*' // // You are given an array of integers a of length n. The elements of the array can be either // different or the same. // // Each element of the array is colored either blue or red. There are no unpainted elements in the // array. One of the two operations described below can be applied to an array in a single step: // * either you can select any blue element and decrease its value by 1; // * or you can select any red element and increase its value by 1. // // Situations in which there are no elements of some color at all are also possible. For example, if // the whole array is colored blue or red, one of the operations becomes unavailable. // // Determine whether it is possible to make 0 or more steps such that the resulting array is a // permutation of numbers from 1 to n? // // In other words, check whether there exists a sequence of steps (possibly empty) such that after // applying it, the array a contains in some order all numbers from 1 to n (inclusive), each exactly // once. // // Input // // The first line contains an integer t (1 <= t <= 10^4)-- the number of input data sets in the // test. // // The description of each set of input data consists of three lines. The first line contains an // integer n (1 <= n <= 2 * 10^5)-- the length of the original array a. The second line contains n // integers a_1, a_2, ..., a_n (-10^9 <= a_i <= 10^9)-- the array elements themselves. // // The third line has length n and consists exclusively of the letters '' and/or '': ith character // is '' if a_i is colored blue, and is '' if colored red. // // It is guaranteed that the sum of n over all input sets does not exceed 2 * 10^5. // // Output // // Print t lines, each of which contains the answer to the corresponding test case of the input. // Print as an answer if the corresponding array can be transformed into a permutation, and // otherwise. // // You can print the answer in any case (for example, the strings , , , and will be recognized as a // positive answer). // // Example /* input: 8 4 1 2 5 2 BRBR 2 1 1 BB 5 3 1 4 2 5 RBRRB 5 3 1 3 1 3 RBRRB 5 5 1 5 1 5 RBRRB 4 2 2 2 2 BRBR 2 1 -2 BR 4 -2 -1 4 0 RRRR output: YES NO YES YES NO YES YES YES */ // Note // // In the first test case of the example, the following sequence of moves can be performed: // * choose i=3, element a_3=5 is blue, so we decrease it, we get a=[1,2,4,2]; // * choose i=2, element a_2=2 is red, so we increase it, we get a=[1,3,4,2]; // * choose i=3, element a_3=4 is blue, so we decrease it, we get a=[1,3,3,2]; // * choose i=2, element a_2=2 is red, so we increase it, we get a=[1,4,3,2]. // // We got that a is a permutation. Hence the answer is . // public class C1607D { static final int MOD = (int)1e9+7; static final Random RAND = new Random(); static boolean solve(int[] a, String s) { int n = a.length; List<Integer> red = new ArrayList<>(); List<Integer> blue = new ArrayList<>(); for (int i = 0; i < n; i++) { if (s.charAt(i) == 'R') { red.add(a[i]); } else { blue.add(a[i]); } } Collections.sort(red); Collections.sort(blue); int m = blue.size(); if (m > 0) { // Can we make blue to be [1,m]? conditions: // count(v <= 1) <= 1 // count(v <= 2) <= 2 // ... // count(v <= m) <= m int ct = 0; int idx = 0; if (blue.get(0) < 1) { return false; } for (int k = 1; k <= m; k++) { while (idx < m && blue.get(idx) <= k) { ct++; idx++; } if (ct > k) { return false; } } } if (m < n) { // Can we make red be [m+1,n]? Conditions: // count(v >= n) <= 1 // count(v >= n-1) <= 2 // count(v >= n-k) <= k + 1 // count(v >= m + 1) <= n-m int idx = red.size() - 1; int ct = 0; if (red.get(idx) > n) { return false; } for (int v = n; v > m; v--) { while (idx >= 0 && red.get(idx) >= v) { ct++; idx--; } if (ct > n + 1 - v) { return false; } } } return true; } static String trace(int[] a) { StringBuilder sb = new StringBuilder(); for (int v : a) { if (sb.length() > 0) { sb.append(' '); } sb.append(v); } return sb.toString(); } public static void main(String[] args) { Scanner in = getInputScanner(); int T = in.nextInt(); for (int t = 1; t <= T; t++) { int n = in.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = in.nextInt(); } String s = in.next(); boolean ans = solve(a, s); System.out.println(ans ? "YES":"NO"); } in.close(); } static Scanner getInputScanner() { try { final String USERDIR = System.getProperty("user.dir"); final String CNAME = MethodHandles.lookup().lookupClass().getSimpleName(); final File fin = new File(USERDIR + "/io/c" + CNAME.substring(1,5) + "/" + CNAME + ".in"); return fin.exists() ? new Scanner(fin) : new Scanner(System.in); } catch (Exception e) { return new Scanner(System.in); } } }
Java
["8\n4\n1 2 5 2\nBRBR\n2\n1 1\nBB\n5\n3 1 4 2 5\nRBRRB\n5\n3 1 3 1 3\nRBRRB\n5\n5 1 5 1 5\nRBRRB\n4\n2 2 2 2\nBRBR\n2\n1 -2\nBR\n4\n-2 -1 4 0\nRRRR"]
1 second
["YES\nNO\nYES\nYES\nNO\nYES\nYES\nYES"]
NoteIn the first test case of the example, the following sequence of moves can be performed: choose $$$i=3$$$, element $$$a_3=5$$$ is blue, so we decrease it, we get $$$a=[1,2,4,2]$$$; choose $$$i=2$$$, element $$$a_2=2$$$ is red, so we increase it, we get $$$a=[1,3,4,2]$$$; choose $$$i=3$$$, element $$$a_3=4$$$ is blue, so we decrease it, we get $$$a=[1,3,3,2]$$$; choose $$$i=2$$$, element $$$a_2=2$$$ is red, so we increase it, we get $$$a=[1,4,3,2]$$$. We got that $$$a$$$ is a permutation. Hence the answer is YES.
Java 11
standard input
[ "greedy", "math", "sortings" ]
c3df88e22a17492d4eb0f3239a27d404
The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of input data sets in the test. The description of each set of input data consists of three lines. The first line contains an integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$) — the length of the original array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$-10^9 \leq a_i \leq 10^9$$$) — the array elements themselves. The third line has length $$$n$$$ and consists exclusively of the letters 'B' and/or 'R': $$$i$$$th character is 'B' if $$$a_i$$$ is colored blue, and is 'R' if colored red. It is guaranteed that the sum of $$$n$$$ over all input sets does not exceed $$$2 \cdot 10^5$$$.
1,300
Print $$$t$$$ lines, each of which contains the answer to the corresponding test case of the input. Print YES as an answer if the corresponding array can be transformed into a permutation, and NO otherwise. You can print the answer in any case (for example, the strings yEs, yes, Yes, and YES will be recognized as a positive answer).
standard output
PASSED
77437d893f486d6b9050a76512363901
train_108.jsonl
1635863700
You are given an array of integers $$$a$$$ of length $$$n$$$. The elements of the array can be either different or the same. Each element of the array is colored either blue or red. There are no unpainted elements in the array. One of the two operations described below can be applied to an array in a single step: either you can select any blue element and decrease its value by $$$1$$$; or you can select any red element and increase its value by $$$1$$$. Situations in which there are no elements of some color at all are also possible. For example, if the whole array is colored blue or red, one of the operations becomes unavailable.Determine whether it is possible to make $$$0$$$ or more steps such that the resulting array is a permutation of numbers from $$$1$$$ to $$$n$$$?In other words, check whether there exists a sequence of steps (possibly empty) such that after applying it, the array $$$a$$$ contains in some order all numbers from $$$1$$$ to $$$n$$$ (inclusive), each exactly once.
256 megabytes
import java.util.*; import java.io.*; public class D_1607 { public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); PrintWriter pw = new PrintWriter(System.out); int t = sc.nextInt(); while(t-->0) { int n = sc.nextInt(); int[] array = sc.nextIntArray(n); char[] type = sc.next().toCharArray(); TreeMap<Integer, Integer> redMap = new TreeMap<>(); TreeMap<Integer, Integer> blueMap = new TreeMap<>(); int min = n + 1, max = 0; for(int i = 0; i < n; i++) if(type[i] == 'R') { redMap.put(array[i], redMap.getOrDefault(array[i], 0) + 1); min = Math.min(min, array[i]); } else { blueMap.put(array[i], blueMap.getOrDefault(array[i], 0) + 1); max = Math.max(max, array[i]); } min = Math.max(min, 1); max = Math.min(max, n); boolean flag = true; for(int i = max + 1; i <= n; i++) { if(redMap.containsKey(i)) { int c = redMap.get(i) - 1; if(c == 0) redMap.remove(i); else redMap.put(i, c); } else if(redMap.lowerEntry(i) != null) { Map.Entry<Integer, Integer> e = redMap.lowerEntry(i); if(e.getValue().intValue() == 1) redMap.remove(e.getKey()); else redMap.put(e.getKey(), e.getValue() - 1); } else { flag = false; break; } } for(int i = min - 1; i >= 1; i--) { if(blueMap.containsKey(i)) { int c = blueMap.get(i) - 1; if(c == 0) blueMap.remove(i); else blueMap.put(i, c); } else if(blueMap.higherEntry(i) != null) { Map.Entry<Integer, Integer> e = blueMap.higherEntry(i); if(e.getValue().intValue() == 1) blueMap.remove(e.getKey()); else blueMap.put(e.getKey(), e.getValue() - 1); } else { flag = false; break; } } boolean[] done = new boolean[n + 1]; for(int i = n; i >= 1; i--) { if(i < min || i > max) continue; int red = Integer.MIN_VALUE; if(redMap.containsKey(i)) { red = i; } else if(redMap.lowerEntry(i) != null) { Map.Entry<Integer, Integer> e = redMap.lowerEntry(i); red = e.getKey(); } if(red != Integer.MIN_VALUE) { done[i] = true; int c = redMap.get(red) - 1; if(c == 0) redMap.remove(red); else redMap.put(red, c); } } for(int i = 1; i <= n; i++) { if(i < min || i > max || done[i]) continue; int blue = Integer.MIN_VALUE; if(blueMap.containsKey(i)) { blue = i; } else if(blueMap.higherEntry(i) != null) { Map.Entry<Integer, Integer> e = blueMap.higherEntry(i); blue = e.getKey(); } else { flag = false; break; } if(blue != Integer.MIN_VALUE) { int c = blueMap.get(blue) - 1; if(c == 0) blueMap.remove(blue); else blueMap.put(blue, c); } } pw.println(flag ? "YES" : "NO"); } pw.flush(); } public static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream system) { br = new BufferedReader(new InputStreamReader(system)); } public Scanner(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 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 int[] nextIntArray(int n) throws IOException { int[] array = new int[n]; for (int i = 0; i < n; i++) array[i] = nextInt(); return array; } public Integer[] nextIntegerArray(int n) throws IOException { Integer[] array = new Integer[n]; for (int i = 0; i < n; i++) array[i] = new Integer(nextInt()); return array; } public long[] nextLongArray(int n) throws IOException { long[] array = new long[n]; for (int i = 0; i < n; i++) array[i] = nextLong(); return array; } public double[] nextDoubleArray(int n) throws IOException { double[] array = new double[n]; for (int i = 0; i < n; i++) array[i] = nextDouble(); return array; } public static int[] shuffle(int[] a) { int n = a.length; Random rand = new Random(); for (int i = 0; i < n; i++) { int tmpIdx = rand.nextInt(n); int tmp = a[i]; a[i] = a[tmpIdx]; a[tmpIdx] = tmp; } return a; } public boolean ready() throws IOException { return br.ready(); } public void waitForInput() throws InterruptedException { Thread.sleep(3000); } } }
Java
["8\n4\n1 2 5 2\nBRBR\n2\n1 1\nBB\n5\n3 1 4 2 5\nRBRRB\n5\n3 1 3 1 3\nRBRRB\n5\n5 1 5 1 5\nRBRRB\n4\n2 2 2 2\nBRBR\n2\n1 -2\nBR\n4\n-2 -1 4 0\nRRRR"]
1 second
["YES\nNO\nYES\nYES\nNO\nYES\nYES\nYES"]
NoteIn the first test case of the example, the following sequence of moves can be performed: choose $$$i=3$$$, element $$$a_3=5$$$ is blue, so we decrease it, we get $$$a=[1,2,4,2]$$$; choose $$$i=2$$$, element $$$a_2=2$$$ is red, so we increase it, we get $$$a=[1,3,4,2]$$$; choose $$$i=3$$$, element $$$a_3=4$$$ is blue, so we decrease it, we get $$$a=[1,3,3,2]$$$; choose $$$i=2$$$, element $$$a_2=2$$$ is red, so we increase it, we get $$$a=[1,4,3,2]$$$. We got that $$$a$$$ is a permutation. Hence the answer is YES.
Java 11
standard input
[ "greedy", "math", "sortings" ]
c3df88e22a17492d4eb0f3239a27d404
The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of input data sets in the test. The description of each set of input data consists of three lines. The first line contains an integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$) — the length of the original array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$-10^9 \leq a_i \leq 10^9$$$) — the array elements themselves. The third line has length $$$n$$$ and consists exclusively of the letters 'B' and/or 'R': $$$i$$$th character is 'B' if $$$a_i$$$ is colored blue, and is 'R' if colored red. It is guaranteed that the sum of $$$n$$$ over all input sets does not exceed $$$2 \cdot 10^5$$$.
1,300
Print $$$t$$$ lines, each of which contains the answer to the corresponding test case of the input. Print YES as an answer if the corresponding array can be transformed into a permutation, and NO otherwise. You can print the answer in any case (for example, the strings yEs, yes, Yes, and YES will be recognized as a positive answer).
standard output