exec_outcome
stringclasses
1 value
code_uid
stringlengths
32
32
file_name
stringclasses
111 values
prob_desc_created_at
stringlengths
10
10
prob_desc_description
stringlengths
63
3.8k
prob_desc_memory_limit
stringclasses
18 values
source_code
stringlengths
117
65.5k
lang_cluster
stringclasses
1 value
prob_desc_sample_inputs
stringlengths
2
802
prob_desc_time_limit
stringclasses
27 values
prob_desc_sample_outputs
stringlengths
2
796
prob_desc_notes
stringlengths
4
3k
lang
stringclasses
5 values
prob_desc_input_from
stringclasses
3 values
tags
sequencelengths
0
11
src_uid
stringlengths
32
32
prob_desc_input_spec
stringlengths
28
2.37k
difficulty
int64
-1
3.5k
prob_desc_output_spec
stringlengths
17
1.47k
prob_desc_output_to
stringclasses
3 values
hidden_unit_tests
stringclasses
1 value
PASSED
03fca8d8ddec93e027ec8777823e61a4
train_110.jsonl
1662993300
Polycarp was given a row of tiles. Each tile contains one lowercase letter of the Latin alphabet. The entire sequence of tiles forms the string $$$s$$$.In other words, you are given a string $$$s$$$ consisting of lowercase Latin letters.Initially, Polycarp is on the first tile of the row and wants to get to the last tile by jumping on the tiles. Jumping from $$$i$$$-th tile to $$$j$$$-th tile has a cost equal to $$$|index(s_i) - index(s_j)|$$$, where $$$index(c)$$$ is the index of the letter $$$c$$$ in the alphabet (for example, $$$index($$$'a'$$$)=1$$$, $$$index($$$'b'$$$)=2$$$, ..., $$$index($$$'z'$$$)=26$$$) .Polycarp wants to get to the $$$n$$$-th tile for the minimum total cost, but at the same time make maximum number of jumps.In other words, among all possible ways to get to the last tile for the minimum total cost, he will choose the one with the maximum number of jumps.Polycarp can visit each tile at most once.Polycarp asks you to help — print the sequence of indices of string $$$s$$$ on which he should jump.
256 megabytes
import java.io.*; import java.lang.reflect.Array; import java.util.*; public class Prog { public static void main(String[] args) throws Exception { //FileInputStream inputStream = new FileInputStream("input.txt"); //FileOutputStream outputStream = new FileOutputStream("output.txt"); InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); Solver solver = new Solver(in, out); for (int i = 0; i < args.length; i++) out.println(args[i]); int t = 1; //t = in.nextInt(); while (t-- > 0) solver.solve(1, in, out); out.close(); } static class Solver { static InputReader in; static PrintWriter out; Solver(InputReader in, PrintWriter out) { this.in = in; this.out = out; } static int countS(char i, char j) { return Math.abs((int)i - (int)j); } public class Pair { public char c; public int i; public Pair(char c, int i) { this.c = c; this.i = i; } } public void solve(int testNumber, InputReader in, PrintWriter out) throws IOException, CloneNotSupportedException { int q = in.nextInt(); while (q-- > 0) { String s = in.next(); int n = s.length(); char f = s.charAt(0), l = s.charAt(n - 1); int ANS = countS(f, l); Map<Character, ArrayList<Integer>> posSym = new HashMap<>(); List<Integer> ans = new ArrayList<>(); int d = f < l ? 1 : -1; for (int i = 0; i < n; i++) { char ch = s.charAt(i); posSym.computeIfAbsent(ch, k -> new ArrayList<>()); posSym.get(ch).add(i + 1); } for (int i = (int)f; i != (int)l; i += d) { if (posSym.get((char)i) != null) ans.addAll(posSym.get((char) i)); } if (posSym.get(l) != null) ans.addAll(posSym.get(l)); out.println(ANS + " " + ans.size()); for (int i : ans) out.print(i + " "); out.println(); } } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public float nextFloat() { return Float.parseFloat(next()); } } }
Java
["6\n\nlogic\n\ncodeforces\n\nbca\n\naaaaaaaaaaa\n\nadbaadabad\n\nto"]
1 second
["9 4\n1 4 3 5\n16 10\n1 8 3 4 9 5 2 6 7 10\n1 2\n1 3\n0 11\n1 8 10 4 3 5 7 2 9 6 11\n3 10\n1 9 5 4 7 3 8 6 2 10\n5 2\n1 2"]
NoteIn the first test case, the required path corresponds to the picture: In this case, the minimum possible total cost of the path is achieved. Since $$$index($$$'l'$$$)=12$$$, $$$index($$$'o'$$$)=15$$$, $$$index($$$'g'$$$)=7$$$, $$$index($$$'i'$$$)=9$$$, $$$index($$$'c'$$$)=3$$$, then the total cost of the path is $$$|12-9|+|9-7|+|7-3|=3+2+4=9$$$.
Java 17
standard input
[ "constructive algorithms", "strings" ]
d17c9f91504e1d4c4eae7294bf09dcfc
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. Each test case is given by the string $$$s$$$ ($$$2 \le |s| \le 2 \cdot 10^5$$$), where $$$|s|$$$ — is the length of string $$$s$$$. The string $$$s$$$ consists of lowercase Latin letters. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,100
The answer to each test case consists of two lines. In the first line print two integers $$$cost$$$, $$$m$$$, where $$$cost$$$ is the minimum total cost of the path, and $$$m$$$ is the maximum number of visited tiles Polycarp can make to get to $$$n$$$-th tiles for the minimum total cost $$$cost$$$ (i.e. the number of jumps is $$$m-1$$$). In the next line print $$$m$$$ different numbers $$$j_1, j_2, \dots, j_m$$$ ($$$1 \le j_i \le |s|$$$) — the sequence of indices of the tiles Polycarp will jump on. The first number in the sequence must be $$$1$$$ (that is, $$$j_1=1$$$) and the last number must be the value of $$$|s|$$$ (that is, $$$j_m=|s|$$$). If there are multiple answers, print any of them.
standard output
PASSED
375f65e54c0a50f3d3192c80426dd537
train_110.jsonl
1662993300
Polycarp was given a row of tiles. Each tile contains one lowercase letter of the Latin alphabet. The entire sequence of tiles forms the string $$$s$$$.In other words, you are given a string $$$s$$$ consisting of lowercase Latin letters.Initially, Polycarp is on the first tile of the row and wants to get to the last tile by jumping on the tiles. Jumping from $$$i$$$-th tile to $$$j$$$-th tile has a cost equal to $$$|index(s_i) - index(s_j)|$$$, where $$$index(c)$$$ is the index of the letter $$$c$$$ in the alphabet (for example, $$$index($$$'a'$$$)=1$$$, $$$index($$$'b'$$$)=2$$$, ..., $$$index($$$'z'$$$)=26$$$) .Polycarp wants to get to the $$$n$$$-th tile for the minimum total cost, but at the same time make maximum number of jumps.In other words, among all possible ways to get to the last tile for the minimum total cost, he will choose the one with the maximum number of jumps.Polycarp can visit each tile at most once.Polycarp asks you to help — print the sequence of indices of string $$$s$$$ on which he should jump.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; // import java.util.Arrays; // import java.util.Comparator; import java.util.Collections; // import java.util.PriorityQueue; import java.util.StringTokenizer; public class sequence { static class pair{ int index; int val; pair(int val, int index){ this.index = index; this.val = val; } } static class Fastreader{ BufferedReader bf; StringTokenizer sr; Fastreader(){ bf = new BufferedReader(new InputStreamReader(System.in)); } String next(){ while(sr==null || !sr.hasMoreElements()){ try{ sr = new StringTokenizer(bf.readLine()); } catch(IOException e){ e.printStackTrace(); } } return sr.nextToken(); } String nextLine() throws IOException{ sr = new StringTokenizer(bf.readLine()); String str = sr.nextToken("\n"); return str; } int intVAl(){ return Integer.parseInt(next()); } double doubleVal(){ return Double.parseDouble(next()); } long longVal(){ return Long.parseLong(next()); } } public static void main(String[] args) throws IOException { Fastreader sc = new Fastreader(); int test = sc.intVAl(); while(test>0){ String str = sc.nextLine(); int n = str.length(); int first = str.charAt(0) - 96; int last = str.charAt(n-1) - 96; // System.out.println(str.length()); if(first > last){ ArrayList<pair> que = new ArrayList<>(); for(int i = 1; i<n-1; i++){ int get = (str.charAt(i)-96); if(get<=first && last<=get){ que.add(new pair(get, i+1)); } } Collections.sort(que, (a, b)->(b.val - a.val)); int cost = first - last; int path = que.size()+2; System.out.println(cost + " "+path); System.out.print(1+" "); for(int i = 0; i<que.size(); i++){ System.out.print(que.get(i).index+" "); } System.out.println(n); } else{ ArrayList<pair> que = new ArrayList<>(); for(int i = 1; i<n-1; i++){ int get = (str.charAt(i) - 96); if(get>=first && last>=get){ que.add(new pair(get, i+1)); } } Collections.sort(que, (a, b)-> (a.val-b.val)); int cost = last - first; int path = que.size()+2; System.out.println(cost + " "+path); System.out.print(1+" "); for(int i = 0; i<que.size(); i++){ System.out.print(que.get(i).index+" "); } System.out.println(n); } test--; } } }
Java
["6\n\nlogic\n\ncodeforces\n\nbca\n\naaaaaaaaaaa\n\nadbaadabad\n\nto"]
1 second
["9 4\n1 4 3 5\n16 10\n1 8 3 4 9 5 2 6 7 10\n1 2\n1 3\n0 11\n1 8 10 4 3 5 7 2 9 6 11\n3 10\n1 9 5 4 7 3 8 6 2 10\n5 2\n1 2"]
NoteIn the first test case, the required path corresponds to the picture: In this case, the minimum possible total cost of the path is achieved. Since $$$index($$$'l'$$$)=12$$$, $$$index($$$'o'$$$)=15$$$, $$$index($$$'g'$$$)=7$$$, $$$index($$$'i'$$$)=9$$$, $$$index($$$'c'$$$)=3$$$, then the total cost of the path is $$$|12-9|+|9-7|+|7-3|=3+2+4=9$$$.
Java 17
standard input
[ "constructive algorithms", "strings" ]
d17c9f91504e1d4c4eae7294bf09dcfc
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. Each test case is given by the string $$$s$$$ ($$$2 \le |s| \le 2 \cdot 10^5$$$), where $$$|s|$$$ — is the length of string $$$s$$$. The string $$$s$$$ consists of lowercase Latin letters. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,100
The answer to each test case consists of two lines. In the first line print two integers $$$cost$$$, $$$m$$$, where $$$cost$$$ is the minimum total cost of the path, and $$$m$$$ is the maximum number of visited tiles Polycarp can make to get to $$$n$$$-th tiles for the minimum total cost $$$cost$$$ (i.e. the number of jumps is $$$m-1$$$). In the next line print $$$m$$$ different numbers $$$j_1, j_2, \dots, j_m$$$ ($$$1 \le j_i \le |s|$$$) — the sequence of indices of the tiles Polycarp will jump on. The first number in the sequence must be $$$1$$$ (that is, $$$j_1=1$$$) and the last number must be the value of $$$|s|$$$ (that is, $$$j_m=|s|$$$). If there are multiple answers, print any of them.
standard output
PASSED
72b40fa8ad3d153dd8201e62b9d95e13
train_110.jsonl
1662993300
Polycarp was given a row of tiles. Each tile contains one lowercase letter of the Latin alphabet. The entire sequence of tiles forms the string $$$s$$$.In other words, you are given a string $$$s$$$ consisting of lowercase Latin letters.Initially, Polycarp is on the first tile of the row and wants to get to the last tile by jumping on the tiles. Jumping from $$$i$$$-th tile to $$$j$$$-th tile has a cost equal to $$$|index(s_i) - index(s_j)|$$$, where $$$index(c)$$$ is the index of the letter $$$c$$$ in the alphabet (for example, $$$index($$$'a'$$$)=1$$$, $$$index($$$'b'$$$)=2$$$, ..., $$$index($$$'z'$$$)=26$$$) .Polycarp wants to get to the $$$n$$$-th tile for the minimum total cost, but at the same time make maximum number of jumps.In other words, among all possible ways to get to the last tile for the minimum total cost, he will choose the one with the maximum number of jumps.Polycarp can visit each tile at most once.Polycarp asks you to help — print the sequence of indices of string $$$s$$$ on which he should jump.
256 megabytes
//package practise; import java.io.*; import java.util.*; public class C { static HashMap<List<Long>,Integer> dp; // static int dp[]; // static Reader sc; static Scanner sc; static PrintWriter w; static List<Integer> ans; public static void main(String[] args) throws IOException { // sc = new Reader(); sc= new Scanner(System.in); w = new PrintWriter(System.out); int t=sc.nextInt(); while(t-->0) { solve(); } w.close(); } //Timur static void solve() throws IOException { String s=sc.next(); int a[]= new int [s.length()]; for(int i=0;i<s.length();i++) { int index=(int)(s.charAt(i))-(int)('a')+1; a[i]=index; } // System.out.println(Arrays.toString(a)+"Fds"); Map<Integer,List<Integer>>map=new HashMap<>(); int n=s.length(); for(int i=n-1;i>=0;i--) { List<Integer> list= map.getOrDefault(a[i], new ArrayList<>()); list.add(i); map.put(a[i],list); } List<Integer> cur= new ArrayList<>(); if(a[0]<=a[n-1]) { List<Integer>t=map.get(a[0]); for(int i=t.size()-1;i>=0;i--) { cur.add(t.get(i)); } // cur.addAll(map.get(a[0])); for(int al=a[0]+1;al<=26;al++) { if(map.containsKey(al)) { List<Integer> list=map.get(al); for(int i=list.size()-1;i>=0;i--)cur.add(list.get(i)); } } } else { List<Integer>t=map.get(a[0]); for(int i=t.size()-1;i>=0;i--) { cur.add(t.get(i)); } for(int al=a[0]-1;al>=1;al--) { if(map.containsKey(al)) { List<Integer> list=map.get(al); for(int i=list.size()-1;i>=0;i--)cur.add(list.get(i)); } } } // System.out.println(cur); int indcc=-1; for(int i=0;i<cur.size();i++) { if(cur.get(i)==n-1) { indcc=i; } } for(int i=indcc+1;i<cur.size();i++) { cur.set(i,-1 ); } for(int i=0;i<cur.size();i++) { if(cur.get(i)==0 || cur.get(i)==n-1) { cur.set(i, -1); } } // System.out.println(cur); List<Integer> ans= new ArrayList<>(); ans.add(0); for(int i=0;i<cur.size();i++) { if(cur.get(i)!=-1)ans.add(cur.get(i)); } ans.add(n-1); // System.out.println(ans); int cost=0; for(int i=0;i<ans.size()-1;i++) { cost+=Math.abs(a[ans.get(i)]-a[ans.get(i+1)]); } if(cost!=Math.abs(a[0]-a[n-1])) { w.println(s); } w.print(Math.abs(a[0]-a[n-1])+" "); w.println(ans.size()); for(int num:ans) { w.print((num+1)+ " "); } w.println(); // return 0; } static class FenwickTree{ int tree[]; void contructFenwickTree(int ar[],int n) { tree= new int[n+1]; for(int i=0;i<ar.length;i++) { update(i,ar[i],n); } } void update(int i,int delta,int n) { //delta means newValue - preValue. //i is index of array. i++; while(i<=n) { tree[i]+=delta; i=i+Integer.lowestOneBit(i); } } int getSum(int i ){ int sum=0; i++; while(i>0) { sum+=tree[i]; i-=Integer.lowestOneBit(i); } return sum; } int rangeOfSum(int i,int j) { return getSum(j)-getSum(i-1); } } static ArrayList<Integer> findDiv(int N) { //gens all divisors of N ArrayList<Integer> ls1 = new ArrayList<Integer>(); ArrayList<Integer> ls2 = new ArrayList<Integer>(); for(int i=1; i <= (int)(Math.sqrt(N)+0.00000001); i++) if(N%i == 0) { ls1.add(i); ls2.add(N/i); } Collections.reverse(ls2); for(int b: ls2) if(b != ls1.get(ls1.size()-1)) ls1.add(b); return ls1; } static void sort(int[] arr) { //because Arrays.sort() uses quicksort which is dumb //Collections.sort() uses merge sort 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 sort(long[] arr) { //because Arrays.sort() uses quicksort which is dumb //Collections.sort() uses merge sort ArrayList<Long> ls = new ArrayList<>(); for(long x: arr) ls.add(x); Collections.sort(ls); for(int i=0; i < arr.length; i++) arr[i] = ls.get(i); } static long power(long x, long y, long p) { //0^0 = 1 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; } static long power(long x, long y) { long res = 1; // Initialize result while (y > 0) { // If y is odd, multiply x with result if ((y & 1) != 0) res = res * x; // y must be even now y = y >> 1; // y = y/2 x = x * x; // Change x to x^2 } return res; } static class Reader // here reader class is defined. { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } }
Java
["6\n\nlogic\n\ncodeforces\n\nbca\n\naaaaaaaaaaa\n\nadbaadabad\n\nto"]
1 second
["9 4\n1 4 3 5\n16 10\n1 8 3 4 9 5 2 6 7 10\n1 2\n1 3\n0 11\n1 8 10 4 3 5 7 2 9 6 11\n3 10\n1 9 5 4 7 3 8 6 2 10\n5 2\n1 2"]
NoteIn the first test case, the required path corresponds to the picture: In this case, the minimum possible total cost of the path is achieved. Since $$$index($$$'l'$$$)=12$$$, $$$index($$$'o'$$$)=15$$$, $$$index($$$'g'$$$)=7$$$, $$$index($$$'i'$$$)=9$$$, $$$index($$$'c'$$$)=3$$$, then the total cost of the path is $$$|12-9|+|9-7|+|7-3|=3+2+4=9$$$.
Java 17
standard input
[ "constructive algorithms", "strings" ]
d17c9f91504e1d4c4eae7294bf09dcfc
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. Each test case is given by the string $$$s$$$ ($$$2 \le |s| \le 2 \cdot 10^5$$$), where $$$|s|$$$ — is the length of string $$$s$$$. The string $$$s$$$ consists of lowercase Latin letters. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,100
The answer to each test case consists of two lines. In the first line print two integers $$$cost$$$, $$$m$$$, where $$$cost$$$ is the minimum total cost of the path, and $$$m$$$ is the maximum number of visited tiles Polycarp can make to get to $$$n$$$-th tiles for the minimum total cost $$$cost$$$ (i.e. the number of jumps is $$$m-1$$$). In the next line print $$$m$$$ different numbers $$$j_1, j_2, \dots, j_m$$$ ($$$1 \le j_i \le |s|$$$) — the sequence of indices of the tiles Polycarp will jump on. The first number in the sequence must be $$$1$$$ (that is, $$$j_1=1$$$) and the last number must be the value of $$$|s|$$$ (that is, $$$j_m=|s|$$$). If there are multiple answers, print any of them.
standard output
PASSED
686c71dc2192e83f06da9f03110e7c9f
train_110.jsonl
1662993300
Polycarp was given a row of tiles. Each tile contains one lowercase letter of the Latin alphabet. The entire sequence of tiles forms the string $$$s$$$.In other words, you are given a string $$$s$$$ consisting of lowercase Latin letters.Initially, Polycarp is on the first tile of the row and wants to get to the last tile by jumping on the tiles. Jumping from $$$i$$$-th tile to $$$j$$$-th tile has a cost equal to $$$|index(s_i) - index(s_j)|$$$, where $$$index(c)$$$ is the index of the letter $$$c$$$ in the alphabet (for example, $$$index($$$'a'$$$)=1$$$, $$$index($$$'b'$$$)=2$$$, ..., $$$index($$$'z'$$$)=26$$$) .Polycarp wants to get to the $$$n$$$-th tile for the minimum total cost, but at the same time make maximum number of jumps.In other words, among all possible ways to get to the last tile for the minimum total cost, he will choose the one with the maximum number of jumps.Polycarp can visit each tile at most once.Polycarp asks you to help — print the sequence of indices of string $$$s$$$ on which he should jump.
256 megabytes
import java.util.*; import java.io.*; import java.math.BigInteger; public class Main { public static FastReader cin; public static PrintWriter out; public static void main(String[] args) throws Exception { out = new PrintWriter(new BufferedOutputStream(System.out)); cin = new FastReader(); int ttt = cin.nextInt(); for(int qqq = 1; qqq <= ttt ;qqq++ ){ String s = cin.next(); int len = s.length(); int startIndex = s.charAt(0) - 'a'; int endIndex = s.charAt(len - 1) - 'a'; boolean inc = false; boolean dec = false; boolean eq = false; if(startIndex == endIndex)eq = true; else if(startIndex > endIndex)dec = true; else inc = true; ArrayList<long[]>list = new ArrayList<>(); for(int i = 0; i < len; i++){ int temp = s.charAt(i) - 'a'; if(eq){ if(temp == startIndex){ list.add(new long []{i,temp}); } }else if(inc){ if(temp >= startIndex && temp <= endIndex){ list.add(new long []{i,temp}); } }else{ if(temp <= startIndex && temp >= endIndex){ list.add(new long []{i,temp}); } } } final boolean flag = inc ? true:false; Collections.sort(list,(a,b)->{ if(a[1] != b[1]){ if(flag)return Long.compare(a[1],b[1]); else return Long.compare(b[1],a[1]); }else return Long.compare(a[0],b[0]); }); long ans = 0; long nowIndex = startIndex; long times = 0; ArrayList<Integer>step = new ArrayList<>(); for(int i = 0; i < list.size(); i++){ long []temp = list.get(i); ans += Math.abs(nowIndex - temp[1]); nowIndex = temp[1]; step.add((int)temp[0] + 1); } out.println(ans+" "+step.size()); // out.println("step="+step); for(Integer t:step){ out.printf("%d ",t); } out.println(); //最小代价最大步数 //cost times //step } out.close(); } public static long lcm(long a,long b ){ long ans = a / gcd(a,b) * b ; return ans; } public static long gcd(long a,long b){ if(b==0)return a; else return gcd(b,a%b); } 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
["6\n\nlogic\n\ncodeforces\n\nbca\n\naaaaaaaaaaa\n\nadbaadabad\n\nto"]
1 second
["9 4\n1 4 3 5\n16 10\n1 8 3 4 9 5 2 6 7 10\n1 2\n1 3\n0 11\n1 8 10 4 3 5 7 2 9 6 11\n3 10\n1 9 5 4 7 3 8 6 2 10\n5 2\n1 2"]
NoteIn the first test case, the required path corresponds to the picture: In this case, the minimum possible total cost of the path is achieved. Since $$$index($$$'l'$$$)=12$$$, $$$index($$$'o'$$$)=15$$$, $$$index($$$'g'$$$)=7$$$, $$$index($$$'i'$$$)=9$$$, $$$index($$$'c'$$$)=3$$$, then the total cost of the path is $$$|12-9|+|9-7|+|7-3|=3+2+4=9$$$.
Java 17
standard input
[ "constructive algorithms", "strings" ]
d17c9f91504e1d4c4eae7294bf09dcfc
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. Each test case is given by the string $$$s$$$ ($$$2 \le |s| \le 2 \cdot 10^5$$$), where $$$|s|$$$ — is the length of string $$$s$$$. The string $$$s$$$ consists of lowercase Latin letters. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,100
The answer to each test case consists of two lines. In the first line print two integers $$$cost$$$, $$$m$$$, where $$$cost$$$ is the minimum total cost of the path, and $$$m$$$ is the maximum number of visited tiles Polycarp can make to get to $$$n$$$-th tiles for the minimum total cost $$$cost$$$ (i.e. the number of jumps is $$$m-1$$$). In the next line print $$$m$$$ different numbers $$$j_1, j_2, \dots, j_m$$$ ($$$1 \le j_i \le |s|$$$) — the sequence of indices of the tiles Polycarp will jump on. The first number in the sequence must be $$$1$$$ (that is, $$$j_1=1$$$) and the last number must be the value of $$$|s|$$$ (that is, $$$j_m=|s|$$$). If there are multiple answers, print any of them.
standard output
PASSED
228e46362df078470e64460e6685542b
train_110.jsonl
1662993300
Polycarp was given a row of tiles. Each tile contains one lowercase letter of the Latin alphabet. The entire sequence of tiles forms the string $$$s$$$.In other words, you are given a string $$$s$$$ consisting of lowercase Latin letters.Initially, Polycarp is on the first tile of the row and wants to get to the last tile by jumping on the tiles. Jumping from $$$i$$$-th tile to $$$j$$$-th tile has a cost equal to $$$|index(s_i) - index(s_j)|$$$, where $$$index(c)$$$ is the index of the letter $$$c$$$ in the alphabet (for example, $$$index($$$'a'$$$)=1$$$, $$$index($$$'b'$$$)=2$$$, ..., $$$index($$$'z'$$$)=26$$$) .Polycarp wants to get to the $$$n$$$-th tile for the minimum total cost, but at the same time make maximum number of jumps.In other words, among all possible ways to get to the last tile for the minimum total cost, he will choose the one with the maximum number of jumps.Polycarp can visit each tile at most once.Polycarp asks you to help — print the sequence of indices of string $$$s$$$ on which he should jump.
256 megabytes
/**/ import java.io.*; import java.util.*; import java.lang.*; public class JumpingOnTiles { public static void main(String[] args) throws IOException{ FastReader s = new FastReader(); PrintWriter out = new PrintWriter(System.out); int t = s.nextInt(); while(t-->0){ char[] letters = s.next().toCharArray(); int n = letters.length; ArrayList<Integer> idx[] = new ArrayList[26]; for(int i = 0; i < 26; i++){ idx[i] = new ArrayList<>(); } for(int i = 0; i < n; i++){ idx[(letters[i] - 'a')].add(i); } StringBuilder sb = new StringBuilder(); int count = 0; for(int i = letters[0]; i != letters[n - 1];){ for(int num: idx[i - 'a']){ count++; sb.append((num + 1) + " "); } if(i > letters[n-1]){ i--; } else{ i++; } } for(int num: idx[letters[n - 1] - 'a']){ count++; sb.append((num + 1) + " "); } out.println(Math.abs(letters[0] - letters[n - 1]) + " " + count); out.println(sb); } out.flush(); } public static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } public String next() throws IOException { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } String nextLine() throws IOException { String str = ""; if (st.hasMoreTokens()) { str = st.nextToken("\n"); } else { str = br.readLine(); } return str; } } }
Java
["6\n\nlogic\n\ncodeforces\n\nbca\n\naaaaaaaaaaa\n\nadbaadabad\n\nto"]
1 second
["9 4\n1 4 3 5\n16 10\n1 8 3 4 9 5 2 6 7 10\n1 2\n1 3\n0 11\n1 8 10 4 3 5 7 2 9 6 11\n3 10\n1 9 5 4 7 3 8 6 2 10\n5 2\n1 2"]
NoteIn the first test case, the required path corresponds to the picture: In this case, the minimum possible total cost of the path is achieved. Since $$$index($$$'l'$$$)=12$$$, $$$index($$$'o'$$$)=15$$$, $$$index($$$'g'$$$)=7$$$, $$$index($$$'i'$$$)=9$$$, $$$index($$$'c'$$$)=3$$$, then the total cost of the path is $$$|12-9|+|9-7|+|7-3|=3+2+4=9$$$.
Java 17
standard input
[ "constructive algorithms", "strings" ]
d17c9f91504e1d4c4eae7294bf09dcfc
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. Each test case is given by the string $$$s$$$ ($$$2 \le |s| \le 2 \cdot 10^5$$$), where $$$|s|$$$ — is the length of string $$$s$$$. The string $$$s$$$ consists of lowercase Latin letters. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,100
The answer to each test case consists of two lines. In the first line print two integers $$$cost$$$, $$$m$$$, where $$$cost$$$ is the minimum total cost of the path, and $$$m$$$ is the maximum number of visited tiles Polycarp can make to get to $$$n$$$-th tiles for the minimum total cost $$$cost$$$ (i.e. the number of jumps is $$$m-1$$$). In the next line print $$$m$$$ different numbers $$$j_1, j_2, \dots, j_m$$$ ($$$1 \le j_i \le |s|$$$) — the sequence of indices of the tiles Polycarp will jump on. The first number in the sequence must be $$$1$$$ (that is, $$$j_1=1$$$) and the last number must be the value of $$$|s|$$$ (that is, $$$j_m=|s|$$$). If there are multiple answers, print any of them.
standard output
PASSED
de99bbc91ce9f9a88c56036ebcf11bb3
train_110.jsonl
1662993300
Polycarp was given a row of tiles. Each tile contains one lowercase letter of the Latin alphabet. The entire sequence of tiles forms the string $$$s$$$.In other words, you are given a string $$$s$$$ consisting of lowercase Latin letters.Initially, Polycarp is on the first tile of the row and wants to get to the last tile by jumping on the tiles. Jumping from $$$i$$$-th tile to $$$j$$$-th tile has a cost equal to $$$|index(s_i) - index(s_j)|$$$, where $$$index(c)$$$ is the index of the letter $$$c$$$ in the alphabet (for example, $$$index($$$'a'$$$)=1$$$, $$$index($$$'b'$$$)=2$$$, ..., $$$index($$$'z'$$$)=26$$$) .Polycarp wants to get to the $$$n$$$-th tile for the minimum total cost, but at the same time make maximum number of jumps.In other words, among all possible ways to get to the last tile for the minimum total cost, he will choose the one with the maximum number of jumps.Polycarp can visit each tile at most once.Polycarp asks you to help — print the sequence of indices of string $$$s$$$ on which he should jump.
256 megabytes
import java.util.*; public class test { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while (t > 0) { String str = sc.next(); int n = str.length(); ArrayList<ArrayList<Integer>> arr = new ArrayList<>(); for(int i=0; i<26; i++){ arr.add(new ArrayList<Integer>()); } for(int i=0; i<n; i++){ arr.get(str.charAt(i)-'a').add(Integer.valueOf(i)); } // for(int i=0; i<26; i++){ // for(int j=0; j<arr.get(i).size(); j++){ // System.out.print(arr.get(i).get(j)); // } // System.out.println(); // } int start = str.charAt(0) - 'a'; int end = str.charAt(n-1) - 'a'; if(start>end){ int move = 0; for(int i=start; i>=end; i--){ move+=arr.get(i).size(); } System.out.println(start-end +" "+ move); for(int i=start; i>=end; i--){ for(int j=0; j<arr.get(i).size(); j++){ System.out.print(arr.get(i).get(j)+1 + " "); } } }else{ int move = 0; for(int i=start; i<=end; i++){ move+=arr.get(i).size(); } System.out.println(end-start +" "+ move); for(int i=start; i<=end; i++){ for(int j=0; j<arr.get(i).size(); j++){ System.out.print(arr.get(i).get(j)+1 + " "); } } } t--; } } }
Java
["6\n\nlogic\n\ncodeforces\n\nbca\n\naaaaaaaaaaa\n\nadbaadabad\n\nto"]
1 second
["9 4\n1 4 3 5\n16 10\n1 8 3 4 9 5 2 6 7 10\n1 2\n1 3\n0 11\n1 8 10 4 3 5 7 2 9 6 11\n3 10\n1 9 5 4 7 3 8 6 2 10\n5 2\n1 2"]
NoteIn the first test case, the required path corresponds to the picture: In this case, the minimum possible total cost of the path is achieved. Since $$$index($$$'l'$$$)=12$$$, $$$index($$$'o'$$$)=15$$$, $$$index($$$'g'$$$)=7$$$, $$$index($$$'i'$$$)=9$$$, $$$index($$$'c'$$$)=3$$$, then the total cost of the path is $$$|12-9|+|9-7|+|7-3|=3+2+4=9$$$.
Java 17
standard input
[ "constructive algorithms", "strings" ]
d17c9f91504e1d4c4eae7294bf09dcfc
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. Each test case is given by the string $$$s$$$ ($$$2 \le |s| \le 2 \cdot 10^5$$$), where $$$|s|$$$ — is the length of string $$$s$$$. The string $$$s$$$ consists of lowercase Latin letters. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,100
The answer to each test case consists of two lines. In the first line print two integers $$$cost$$$, $$$m$$$, where $$$cost$$$ is the minimum total cost of the path, and $$$m$$$ is the maximum number of visited tiles Polycarp can make to get to $$$n$$$-th tiles for the minimum total cost $$$cost$$$ (i.e. the number of jumps is $$$m-1$$$). In the next line print $$$m$$$ different numbers $$$j_1, j_2, \dots, j_m$$$ ($$$1 \le j_i \le |s|$$$) — the sequence of indices of the tiles Polycarp will jump on. The first number in the sequence must be $$$1$$$ (that is, $$$j_1=1$$$) and the last number must be the value of $$$|s|$$$ (that is, $$$j_m=|s|$$$). If there are multiple answers, print any of them.
standard output
PASSED
b1dfae8d20cd0d1f267112053db9b248
train_110.jsonl
1662993300
Polycarp was given a row of tiles. Each tile contains one lowercase letter of the Latin alphabet. The entire sequence of tiles forms the string $$$s$$$.In other words, you are given a string $$$s$$$ consisting of lowercase Latin letters.Initially, Polycarp is on the first tile of the row and wants to get to the last tile by jumping on the tiles. Jumping from $$$i$$$-th tile to $$$j$$$-th tile has a cost equal to $$$|index(s_i) - index(s_j)|$$$, where $$$index(c)$$$ is the index of the letter $$$c$$$ in the alphabet (for example, $$$index($$$'a'$$$)=1$$$, $$$index($$$'b'$$$)=2$$$, ..., $$$index($$$'z'$$$)=26$$$) .Polycarp wants to get to the $$$n$$$-th tile for the minimum total cost, but at the same time make maximum number of jumps.In other words, among all possible ways to get to the last tile for the minimum total cost, he will choose the one with the maximum number of jumps.Polycarp can visit each tile at most once.Polycarp asks you to help — print the sequence of indices of string $$$s$$$ on which he should jump.
256 megabytes
import java.io.*; import java.util.*; public class Solution { public static Tmp sol(String b) { Map<Character, List<Integer>> map = new HashMap<>(); for (int i = 0; i < b.length(); i++) { List<Integer> list = map.getOrDefault(b.charAt(i), new ArrayList<>()); list.add(i+1); map.put(b.charAt(i), list); } int start = b.charAt(0); int finish = b.charAt(b.length() - 1); Tmp res = new Tmp(new ArrayList<>(), Math.abs(start - finish)); if (start > finish) { for (int i = start; i >= finish; i--) { if (map.containsKey((char) (i))) { var list = map.get((char) (i)); res.list.addAll(list); } } } else { for (int i = start; i <= finish; i++) { if (map.containsKey((char) (i))) { var list = map.get((char) (i)); res.list.addAll(list); } } } return res; } public static Tmp req(int[] arr, boolean[] isCome, int index, int price) { if (index == arr.length - 1) { List<Integer> v = new ArrayList<>(); v.add(index + 1); return new Tmp(v, price); } Tmp min = new Tmp(new ArrayList<>(), 9999999); int value = arr[index]; for (int i = 0; i < arr.length; i++) { if (!isCome[i]) { int v2 = arr[i]; isCome[i] = true; Tmp t = req(arr, isCome, i, Math.abs(v2 - value)); isCome[i] = false; min = compair(min, t); } } min.list.add(index + 1); min.price += price; return min; } public static Tmp compair(Tmp t1, Tmp t2) { if (t1.price < t2.price) return t1; if (t2.price < t1.price) return t2; return t1.list.size() > t2.list.size() ? t1 : t2; } static class Tmp { public Tmp(List<Integer> list, int price) { this.list = list; this.price = price; } private List<Integer> list; private int price; public List<Integer> getList() { return list; } public void setList(List<Integer> list) { this.list = list; } public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } } static class FastScanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } } public static void main(String[] args) { read(); } public static void read() { FastScanner fastScanner = new FastScanner(); PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); int n = fastScanner.nextInt(); for (int i = 0; i < n; i++) { String b; b = fastScanner.next(); Tmp t = sol(b); out.println(t.price + " " + t.list.size()); StringBuilder stringBuilder = new StringBuilder(); for (int i1 = 0; i1 < t.list.size(); i1++) { stringBuilder.append(t.list.get(i1) + " "); } stringBuilder.setLength(stringBuilder.length() - 1); out.println(stringBuilder); } out.close(); } }
Java
["6\n\nlogic\n\ncodeforces\n\nbca\n\naaaaaaaaaaa\n\nadbaadabad\n\nto"]
1 second
["9 4\n1 4 3 5\n16 10\n1 8 3 4 9 5 2 6 7 10\n1 2\n1 3\n0 11\n1 8 10 4 3 5 7 2 9 6 11\n3 10\n1 9 5 4 7 3 8 6 2 10\n5 2\n1 2"]
NoteIn the first test case, the required path corresponds to the picture: In this case, the minimum possible total cost of the path is achieved. Since $$$index($$$'l'$$$)=12$$$, $$$index($$$'o'$$$)=15$$$, $$$index($$$'g'$$$)=7$$$, $$$index($$$'i'$$$)=9$$$, $$$index($$$'c'$$$)=3$$$, then the total cost of the path is $$$|12-9|+|9-7|+|7-3|=3+2+4=9$$$.
Java 17
standard input
[ "constructive algorithms", "strings" ]
d17c9f91504e1d4c4eae7294bf09dcfc
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. Each test case is given by the string $$$s$$$ ($$$2 \le |s| \le 2 \cdot 10^5$$$), where $$$|s|$$$ — is the length of string $$$s$$$. The string $$$s$$$ consists of lowercase Latin letters. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,100
The answer to each test case consists of two lines. In the first line print two integers $$$cost$$$, $$$m$$$, where $$$cost$$$ is the minimum total cost of the path, and $$$m$$$ is the maximum number of visited tiles Polycarp can make to get to $$$n$$$-th tiles for the minimum total cost $$$cost$$$ (i.e. the number of jumps is $$$m-1$$$). In the next line print $$$m$$$ different numbers $$$j_1, j_2, \dots, j_m$$$ ($$$1 \le j_i \le |s|$$$) — the sequence of indices of the tiles Polycarp will jump on. The first number in the sequence must be $$$1$$$ (that is, $$$j_1=1$$$) and the last number must be the value of $$$|s|$$$ (that is, $$$j_m=|s|$$$). If there are multiple answers, print any of them.
standard output
PASSED
cb6a088df5235743690a525ad7f5f740
train_110.jsonl
1662993300
Polycarp was given a row of tiles. Each tile contains one lowercase letter of the Latin alphabet. The entire sequence of tiles forms the string $$$s$$$.In other words, you are given a string $$$s$$$ consisting of lowercase Latin letters.Initially, Polycarp is on the first tile of the row and wants to get to the last tile by jumping on the tiles. Jumping from $$$i$$$-th tile to $$$j$$$-th tile has a cost equal to $$$|index(s_i) - index(s_j)|$$$, where $$$index(c)$$$ is the index of the letter $$$c$$$ in the alphabet (for example, $$$index($$$'a'$$$)=1$$$, $$$index($$$'b'$$$)=2$$$, ..., $$$index($$$'z'$$$)=26$$$) .Polycarp wants to get to the $$$n$$$-th tile for the minimum total cost, but at the same time make maximum number of jumps.In other words, among all possible ways to get to the last tile for the minimum total cost, he will choose the one with the maximum number of jumps.Polycarp can visit each tile at most once.Polycarp asks you to help — print the sequence of indices of string $$$s$$$ on which he should jump.
256 megabytes
import java.lang.reflect.Parameter; import java.util.ArrayList; import java.util.Arrays; import java.util.Scanner; public class Solution { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int t = scanner.nextInt(); while (t-- > 0) { String s = scanner.next(); solve(s); } } private static void solve(String s) { Pair[] pairs = new Pair[s.length()]; int start = s.charAt(0) - 'a' + 1; int last = s.charAt(s.length() - 1) - 'a' + 1; for (int i = 0; i < s.length(); i++) { pairs[i] = new Pair(s.charAt(i) - 'a' + 1, i + 1); } int a = Math.abs(last - start); System.out.print(a + " "); Arrays.sort(pairs); StringBuilder ans = new StringBuilder(); int i; if(start <= last){ i = 0; for(; i < s.length() ; i++) { if (pairs[i].i == start) break; } int x = 0; while(i < s.length() && pairs[i].i != last) { ans.append(pairs[i].j).append(" "); i++; x++; } while(i < s.length() && pairs[i].i== last){ if(pairs[i].j != s.length()) ans.append(pairs[i].j).append(" "); i++; x++; } System.out.println(x); }else{ i = s.length() - 1; for(; i >= 0; i--) { if (pairs[i].i == start) break; } int x = 0; while(i >= 0 && pairs[i].i != last) { if(pairs[i].j == 1) ans.insert(0, 1 + " "); else ans.append(pairs[i].j).append(" "); i--; x++; } while(i >= 0 && pairs[i].i == last){ if(pairs[i].j != s.length()) ans.append(pairs[i].j).append(" "); i--; x++; } System.out.println(x); } ans.append(s.length()).append(" "); System.out.println(ans); } static class Pair implements Comparable<Pair> { int i; int j; Pair(int i, int j) { this.i = i; this.j = j; } @Override public int compareTo(Pair o) { return this.i - o.i; } } }
Java
["6\n\nlogic\n\ncodeforces\n\nbca\n\naaaaaaaaaaa\n\nadbaadabad\n\nto"]
1 second
["9 4\n1 4 3 5\n16 10\n1 8 3 4 9 5 2 6 7 10\n1 2\n1 3\n0 11\n1 8 10 4 3 5 7 2 9 6 11\n3 10\n1 9 5 4 7 3 8 6 2 10\n5 2\n1 2"]
NoteIn the first test case, the required path corresponds to the picture: In this case, the minimum possible total cost of the path is achieved. Since $$$index($$$'l'$$$)=12$$$, $$$index($$$'o'$$$)=15$$$, $$$index($$$'g'$$$)=7$$$, $$$index($$$'i'$$$)=9$$$, $$$index($$$'c'$$$)=3$$$, then the total cost of the path is $$$|12-9|+|9-7|+|7-3|=3+2+4=9$$$.
Java 17
standard input
[ "constructive algorithms", "strings" ]
d17c9f91504e1d4c4eae7294bf09dcfc
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. Each test case is given by the string $$$s$$$ ($$$2 \le |s| \le 2 \cdot 10^5$$$), where $$$|s|$$$ — is the length of string $$$s$$$. The string $$$s$$$ consists of lowercase Latin letters. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,100
The answer to each test case consists of two lines. In the first line print two integers $$$cost$$$, $$$m$$$, where $$$cost$$$ is the minimum total cost of the path, and $$$m$$$ is the maximum number of visited tiles Polycarp can make to get to $$$n$$$-th tiles for the minimum total cost $$$cost$$$ (i.e. the number of jumps is $$$m-1$$$). In the next line print $$$m$$$ different numbers $$$j_1, j_2, \dots, j_m$$$ ($$$1 \le j_i \le |s|$$$) — the sequence of indices of the tiles Polycarp will jump on. The first number in the sequence must be $$$1$$$ (that is, $$$j_1=1$$$) and the last number must be the value of $$$|s|$$$ (that is, $$$j_m=|s|$$$). If there are multiple answers, print any of them.
standard output
PASSED
d2cceee6530293251587cdd56ba0cd5d
train_110.jsonl
1662993300
Polycarp was given a row of tiles. Each tile contains one lowercase letter of the Latin alphabet. The entire sequence of tiles forms the string $$$s$$$.In other words, you are given a string $$$s$$$ consisting of lowercase Latin letters.Initially, Polycarp is on the first tile of the row and wants to get to the last tile by jumping on the tiles. Jumping from $$$i$$$-th tile to $$$j$$$-th tile has a cost equal to $$$|index(s_i) - index(s_j)|$$$, where $$$index(c)$$$ is the index of the letter $$$c$$$ in the alphabet (for example, $$$index($$$'a'$$$)=1$$$, $$$index($$$'b'$$$)=2$$$, ..., $$$index($$$'z'$$$)=26$$$) .Polycarp wants to get to the $$$n$$$-th tile for the minimum total cost, but at the same time make maximum number of jumps.In other words, among all possible ways to get to the last tile for the minimum total cost, he will choose the one with the maximum number of jumps.Polycarp can visit each tile at most once.Polycarp asks you to help — print the sequence of indices of string $$$s$$$ on which he should jump.
256 megabytes
import java.io.*; import java.util.*; 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 { if(st.hasMoreTokens()){ str = st.nextToken("\n"); } else{ str = br.readLine(); } } catch (IOException e) { e.printStackTrace(); } return str; } } static int gcd(int a, int b) { if (a == 0) return b; if (b == 0) return a; if (a == b) return a; if (a > b) return gcd(a-b, b); return gcd(a, b-a); } static void print(long []arr) { for(long a : arr) System.out.print(a + " "); System.out.println(); } static void print(int []arr) { for(int a : arr) System.out.print(a + " "); System.out.println(); } static void print(long a) { System.out.print(a); } static void printl(long a) { System.out.println(a); } static void printl(char ch) { System.out.println(ch); } static void print(char ch) { System.out.print(ch); } static void printl(String s) { System.out.println(s); } static void print(String s) { System.out.print(s); } static int[] intArray(int n) { int arr[] = new int[n]; for(int i = 0; i < n; i++) arr[i] = sc.nextInt(); return arr; } static long[] longArray(int n) { long arr[] = new long[n]; for(int i = 0; i < n; i++) arr[i] = sc.nextLong(); return arr; } static double[] doubleArray(int n) { double arr[] = new double[n]; for(int i = 0; i < n; i++) arr[i] = sc.nextDouble(); return arr; } static int[][] intMatrix(int n, int m) { int mat[][] = new int[n][m]; for(int i = 0; i < mat.length; i++) for(int j = 0; j < mat[0].length; j++) mat[i][j] = sc.nextInt(); return mat; } static long[][] longMatrix(int n, int m) { long mat[][] = new long[n][m]; for(int i = 0; i < mat.length; i++) for(int j = 0; j < mat[0].length; j++) mat[i][j] = sc.nextLong(); return mat; } static class Pair { int v1, v2; Pair(int v1, int v2) { this.v1 = v1; this.v2 = v2; } } static FastReader sc = new FastReader(); public static void main(String[] args) { int tc = sc.nextInt(); while(tc-- > 0) { String s = sc.next(); int cost = (int)Math.abs((s.charAt(0) - 'a') - (s.charAt(s.length() - 1) - 'a')); List<List<Integer>> indices = new ArrayList<>(); for(int i = 1; i <= 26; i++) indices.add(new ArrayList<>()); for(int i = 0; i < s.length(); i++) indices.get(s.charAt(i) - 'a').add(i + 1); List<Integer> ls = new ArrayList<>(); if(s.charAt(0) <= s.charAt(s.length() - 1)) { for(char ch = s.charAt(0); ch <= s.charAt(s.length() - 1); ch++) { for(int x : indices.get(ch - 'a')) ls.add(x); } } else { for(char ch = s.charAt(0); ch >= s.charAt(s.length() - 1); ch--) { for(int x : indices.get(ch - 'a')) ls.add(x); } } System.out.println(cost + " " + ls.size()); for(int i : ls) System.out.print(i + " "); System.out.println(); } } }
Java
["6\n\nlogic\n\ncodeforces\n\nbca\n\naaaaaaaaaaa\n\nadbaadabad\n\nto"]
1 second
["9 4\n1 4 3 5\n16 10\n1 8 3 4 9 5 2 6 7 10\n1 2\n1 3\n0 11\n1 8 10 4 3 5 7 2 9 6 11\n3 10\n1 9 5 4 7 3 8 6 2 10\n5 2\n1 2"]
NoteIn the first test case, the required path corresponds to the picture: In this case, the minimum possible total cost of the path is achieved. Since $$$index($$$'l'$$$)=12$$$, $$$index($$$'o'$$$)=15$$$, $$$index($$$'g'$$$)=7$$$, $$$index($$$'i'$$$)=9$$$, $$$index($$$'c'$$$)=3$$$, then the total cost of the path is $$$|12-9|+|9-7|+|7-3|=3+2+4=9$$$.
Java 17
standard input
[ "constructive algorithms", "strings" ]
d17c9f91504e1d4c4eae7294bf09dcfc
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. Each test case is given by the string $$$s$$$ ($$$2 \le |s| \le 2 \cdot 10^5$$$), where $$$|s|$$$ — is the length of string $$$s$$$. The string $$$s$$$ consists of lowercase Latin letters. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,100
The answer to each test case consists of two lines. In the first line print two integers $$$cost$$$, $$$m$$$, where $$$cost$$$ is the minimum total cost of the path, and $$$m$$$ is the maximum number of visited tiles Polycarp can make to get to $$$n$$$-th tiles for the minimum total cost $$$cost$$$ (i.e. the number of jumps is $$$m-1$$$). In the next line print $$$m$$$ different numbers $$$j_1, j_2, \dots, j_m$$$ ($$$1 \le j_i \le |s|$$$) — the sequence of indices of the tiles Polycarp will jump on. The first number in the sequence must be $$$1$$$ (that is, $$$j_1=1$$$) and the last number must be the value of $$$|s|$$$ (that is, $$$j_m=|s|$$$). If there are multiple answers, print any of them.
standard output
PASSED
4ecf656956cd2ff94b53f253cab14bc7
train_110.jsonl
1662993300
Polycarp was given a row of tiles. Each tile contains one lowercase letter of the Latin alphabet. The entire sequence of tiles forms the string $$$s$$$.In other words, you are given a string $$$s$$$ consisting of lowercase Latin letters.Initially, Polycarp is on the first tile of the row and wants to get to the last tile by jumping on the tiles. Jumping from $$$i$$$-th tile to $$$j$$$-th tile has a cost equal to $$$|index(s_i) - index(s_j)|$$$, where $$$index(c)$$$ is the index of the letter $$$c$$$ in the alphabet (for example, $$$index($$$'a'$$$)=1$$$, $$$index($$$'b'$$$)=2$$$, ..., $$$index($$$'z'$$$)=26$$$) .Polycarp wants to get to the $$$n$$$-th tile for the minimum total cost, but at the same time make maximum number of jumps.In other words, among all possible ways to get to the last tile for the minimum total cost, he will choose the one with the maximum number of jumps.Polycarp can visit each tile at most once.Polycarp asks you to help — print the sequence of indices of string $$$s$$$ on which he should jump.
256 megabytes
//package com; import java.util.*; public class Main { public static void main(String[] args) { // write your code here Scanner in = new Scanner(System.in); Map<Character,Integer> map = new HashMap(); for(int i=1;i<=26;i++){ map.put((char)(96+i),i); } int t = in.nextInt(); while(t-- >0) { String s = in.next(); Str str[] = new Str[s.length()]; for(int i=0;i<s.length();i++){ str[i] = new Str(); str[i].aChar = s.charAt(i); str[i].pos = i+1; } int sroce = Math.abs(map.get(s.charAt(0)) - map.get(s.charAt(s.length()-1))); boolean flag = true; List<Integer> list = new ArrayList<>(); if(s.charAt(0) > s.charAt(s.length()-1)) { Arrays.sort(str,(o1,o2)-> { if(o1.aChar == o2.aChar){ return o1.pos - o2.pos; } return o2.aChar - o1.aChar; }); for (int i = 0; i < s.length(); i++) { if (flag && str[i].pos != 1) continue; flag = false; list.add(str[i].pos); if (str[i].pos == s.length()) break; } } else{ Arrays.sort(str,(o1,o2)-> { if(o1.aChar == o2.aChar){ return o1.pos - o2.pos; } return o1.aChar - o2.aChar; }); for(int i=0;i<s.length();i++){ if(flag && str[i].pos != 1) continue; flag = false; list.add(str[i].pos); if(str[i].pos == s.length()) break; } } System.out.println(sroce +" "+list.size()); for(int x:list){ System.out.print(x + " "); } System.out.println(); } } } class Str{ int pos; char aChar; }
Java
["6\n\nlogic\n\ncodeforces\n\nbca\n\naaaaaaaaaaa\n\nadbaadabad\n\nto"]
1 second
["9 4\n1 4 3 5\n16 10\n1 8 3 4 9 5 2 6 7 10\n1 2\n1 3\n0 11\n1 8 10 4 3 5 7 2 9 6 11\n3 10\n1 9 5 4 7 3 8 6 2 10\n5 2\n1 2"]
NoteIn the first test case, the required path corresponds to the picture: In this case, the minimum possible total cost of the path is achieved. Since $$$index($$$'l'$$$)=12$$$, $$$index($$$'o'$$$)=15$$$, $$$index($$$'g'$$$)=7$$$, $$$index($$$'i'$$$)=9$$$, $$$index($$$'c'$$$)=3$$$, then the total cost of the path is $$$|12-9|+|9-7|+|7-3|=3+2+4=9$$$.
Java 17
standard input
[ "constructive algorithms", "strings" ]
d17c9f91504e1d4c4eae7294bf09dcfc
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. Each test case is given by the string $$$s$$$ ($$$2 \le |s| \le 2 \cdot 10^5$$$), where $$$|s|$$$ — is the length of string $$$s$$$. The string $$$s$$$ consists of lowercase Latin letters. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,100
The answer to each test case consists of two lines. In the first line print two integers $$$cost$$$, $$$m$$$, where $$$cost$$$ is the minimum total cost of the path, and $$$m$$$ is the maximum number of visited tiles Polycarp can make to get to $$$n$$$-th tiles for the minimum total cost $$$cost$$$ (i.e. the number of jumps is $$$m-1$$$). In the next line print $$$m$$$ different numbers $$$j_1, j_2, \dots, j_m$$$ ($$$1 \le j_i \le |s|$$$) — the sequence of indices of the tiles Polycarp will jump on. The first number in the sequence must be $$$1$$$ (that is, $$$j_1=1$$$) and the last number must be the value of $$$|s|$$$ (that is, $$$j_m=|s|$$$). If there are multiple answers, print any of them.
standard output
PASSED
9111a8cb96f08cb003d775a60da4ee5a
train_110.jsonl
1662993300
Polycarp was given a row of tiles. Each tile contains one lowercase letter of the Latin alphabet. The entire sequence of tiles forms the string $$$s$$$.In other words, you are given a string $$$s$$$ consisting of lowercase Latin letters.Initially, Polycarp is on the first tile of the row and wants to get to the last tile by jumping on the tiles. Jumping from $$$i$$$-th tile to $$$j$$$-th tile has a cost equal to $$$|index(s_i) - index(s_j)|$$$, where $$$index(c)$$$ is the index of the letter $$$c$$$ in the alphabet (for example, $$$index($$$'a'$$$)=1$$$, $$$index($$$'b'$$$)=2$$$, ..., $$$index($$$'z'$$$)=26$$$) .Polycarp wants to get to the $$$n$$$-th tile for the minimum total cost, but at the same time make maximum number of jumps.In other words, among all possible ways to get to the last tile for the minimum total cost, he will choose the one with the maximum number of jumps.Polycarp can visit each tile at most once.Polycarp asks you to help — print the sequence of indices of string $$$s$$$ on which he should jump.
256 megabytes
import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Scanner; public class ContestX { public static void main(String[] args) { try (Scanner sc = new Scanner(System.in)) { var t = sc.nextInt(); for (var ti = 0; ti < t; ti++) { var s = sc.next(); var s0 = s.charAt(0); var sN = s.charAt(s.length() - 1); var cost = Math.abs(sN - s0); var smin = Math.min(s0, sN); var smax = Math.max(s0, sN); var map = new HashMap<Character, List<Integer>>(); // build map like // example: logic would only use ligc (no 'o') // {c=[4], g=[2], i=[3], l=[0]} for (var i = 0; i < s.length(); i++) { var si = s.charAt(i); if (smin <= si && si <= smax) { if (!map.containsKey(si)) { map.put(si, new ArrayList<>()); } var list = map.get(si); list.add(i); } } // flat indices var indices0 = new ArrayList<Integer>(); for (var letter = 'a'; letter <= 'z'; letter++) { if (!map.containsKey(letter)) { continue; } indices0.addAll(map.get(letter)); } var indices = new ArrayList<Integer>(); for (var i : indices0) { if (i != 0 && i != s.length() - 1) { indices.add(i); } } //System.out.println(s); System.out.println(cost + " " + (indices.size() + 2)); System.out.print(1 + " "); for (int i = 0; i < indices.size(); i++) { var index = indices.get( s0 == smin ? i : indices.size() - 1 - i); System.out.print((index + 1) + " "); // System.out.print(s.charAt(index) + (" ")); } System.out.print(s.length()); System.out.println(); } } } }
Java
["6\n\nlogic\n\ncodeforces\n\nbca\n\naaaaaaaaaaa\n\nadbaadabad\n\nto"]
1 second
["9 4\n1 4 3 5\n16 10\n1 8 3 4 9 5 2 6 7 10\n1 2\n1 3\n0 11\n1 8 10 4 3 5 7 2 9 6 11\n3 10\n1 9 5 4 7 3 8 6 2 10\n5 2\n1 2"]
NoteIn the first test case, the required path corresponds to the picture: In this case, the minimum possible total cost of the path is achieved. Since $$$index($$$'l'$$$)=12$$$, $$$index($$$'o'$$$)=15$$$, $$$index($$$'g'$$$)=7$$$, $$$index($$$'i'$$$)=9$$$, $$$index($$$'c'$$$)=3$$$, then the total cost of the path is $$$|12-9|+|9-7|+|7-3|=3+2+4=9$$$.
Java 17
standard input
[ "constructive algorithms", "strings" ]
d17c9f91504e1d4c4eae7294bf09dcfc
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. Each test case is given by the string $$$s$$$ ($$$2 \le |s| \le 2 \cdot 10^5$$$), where $$$|s|$$$ — is the length of string $$$s$$$. The string $$$s$$$ consists of lowercase Latin letters. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,100
The answer to each test case consists of two lines. In the first line print two integers $$$cost$$$, $$$m$$$, where $$$cost$$$ is the minimum total cost of the path, and $$$m$$$ is the maximum number of visited tiles Polycarp can make to get to $$$n$$$-th tiles for the minimum total cost $$$cost$$$ (i.e. the number of jumps is $$$m-1$$$). In the next line print $$$m$$$ different numbers $$$j_1, j_2, \dots, j_m$$$ ($$$1 \le j_i \le |s|$$$) — the sequence of indices of the tiles Polycarp will jump on. The first number in the sequence must be $$$1$$$ (that is, $$$j_1=1$$$) and the last number must be the value of $$$|s|$$$ (that is, $$$j_m=|s|$$$). If there are multiple answers, print any of them.
standard output
PASSED
436b22862ce97242d6d2e620aeaf463c
train_110.jsonl
1662993300
Polycarp was given a row of tiles. Each tile contains one lowercase letter of the Latin alphabet. The entire sequence of tiles forms the string $$$s$$$.In other words, you are given a string $$$s$$$ consisting of lowercase Latin letters.Initially, Polycarp is on the first tile of the row and wants to get to the last tile by jumping on the tiles. Jumping from $$$i$$$-th tile to $$$j$$$-th tile has a cost equal to $$$|index(s_i) - index(s_j)|$$$, where $$$index(c)$$$ is the index of the letter $$$c$$$ in the alphabet (for example, $$$index($$$'a'$$$)=1$$$, $$$index($$$'b'$$$)=2$$$, ..., $$$index($$$'z'$$$)=26$$$) .Polycarp wants to get to the $$$n$$$-th tile for the minimum total cost, but at the same time make maximum number of jumps.In other words, among all possible ways to get to the last tile for the minimum total cost, he will choose the one with the maximum number of jumps.Polycarp can visit each tile at most once.Polycarp asks you to help — print the sequence of indices of string $$$s$$$ on which he should jump.
256 megabytes
import java.io.*; import java.util.*; public class Main { static long mod = (long) 1e9 + 7; public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); long t=Long.parseLong(br.readLine()); while(t-->0){ // int n=Integer.parseInt(br.readLine()); // String[] in=br.readLine().split(" "); // int m=Integer.parseInt(br.readLine()); // String[] in1=br.readLine().split(" "); // int m=Integer.parseInt(in[0]); // int n=Integer.parseInt(in[1]); // int[] a=new int[n]; // int[] b=new int[m]; // for(int i=0;i<n;i++){ // a[i]=Integer.parseInt(in[i]); // } // for(int i=0;i<m;i++){ // b[i]=Integer.parseInt(in1[i]); // } // long x=0; // long y=0; // long max=0; // for(int i=0;i<n;i++){ // int low=0; // int high=m-1; // int ans=-1; // while(low<=high){ // int mid=low+(high-low)/2; // if(b[mid]<=a[i]){ // ans=mid; // low=mid+1; // } // else{ // high=mid-1; // } // } // long score_a=(long)3*(long)(n-i)+2*(long)i; // long score_b=3*(long)(m-ans)+2*(long)(ans); // long diff=score_a-score_b; // if(max<diff){ // max=diff; // x=score_a; // y=score_b; // } // } // out.println(x+":"+y); String s=br.readLine(); char[] c=s.toCharArray(); int m=Math.abs(c[c.length-1]-c[0]); boolean max=false; if(c[c.length-1]>c[0]){ max=true; } if(!max) { PriorityQueue<pair>pq=new PriorityQueue<>((x,y)->Integer.compare(y.a,x.a)); ArrayList<Integer>l1=new ArrayList<>(); for(int i=1;i<c.length-1;i++){ if(c[i]-'a'<=c[0]-'a' && c[i]-'a'>=c[c.length-1]-'a') pq.add(new pair((c[i]-'a'),i+1)); } int a=c[0]-'a'; l1.add(1); while(pq.size()>=1 && pq.peek().a<=a){ l1.add(pq.peek().b); pq.poll(); } l1.add(c.length); out.println(m+" "+l1.size()); for(int i:l1){ out.print(i+" "); } } else{ PriorityQueue<pair>pq=new PriorityQueue<>((x,y)->Integer.compare(x.a,y.a)); ArrayList<Integer>l1=new ArrayList<>(); for(int i=1;i<c.length-1;i++){ if(c[i]-'a'>=c[0]-'a' && c[i]-'a'<=c[c.length-1]-'a') pq.add(new pair((c[i]-'a'),i+1)); } int a=c[0]-'a'; l1.add(1); while(pq.size()>=1 && pq.peek().a>=a){ l1.add(pq.peek().b); pq.poll(); } l1.add(c.length); out.println(m+" "+l1.size()); for(int i:l1){ out.print(i+" "); } } out.println(); } out.close(); } static void swap(int[] a,int x,int y){ a[x]=a[x]^a[y]; a[y]=a[x]^a[y]; a[x]=a[x]^a[y]; } static long memo(int i,ArrayList<Integer>l1,int sum,long[][] dp){ if(i==l1.size()){ if(sum==0) return 1; return 0; } if(dp[i][sum]!=-1) return dp[i][sum]; long not_pick=memo(i+1,l1,sum,dp); long pick=0; if(sum-l1.get(i)>=0) pick=memo(i,l1,sum-l1.get(i),dp); return dp[i][sum]=(pick+not_pick)%mod; } static long n_of_factors(long[][] a) { long ans = 1; for (int i = 0; i < a.length; i++) { ans = ans * (a[i][1] + 1) % mod; } return ans % mod; } static long sum_of_factors(long[][] a) { long ans = 1; for (int i = 0; i < a.length; i++) { long res = (((expo(a[i][0], a[i][1] + 1) - 1) % mod) * (modular_inverse(a[i][0] - 1)) % mod) % mod; ans = ((res % mod) * (ans % mod)) % mod; } return (ans % mod); } static long prod_of_divisors(long[][] a) { long ans = 1; long d = 1; for (int i = 0; i < a.length; i++) { long res = expo(a[i][0], (a[i][1] * (a[i][1] + 1) / 2)); ans = ((expo(ans, a[i][1] + 1) % mod) * (expo(res, d) % mod)) % mod; d = (d * (a[i][1] + 1)) % (mod - 1); } return ans % mod; } static long expo(long a, long b) { long ans = 1; a = a % mod; while (b > 0) { if ((b & 1) == 1) { ans = ans * a % mod; } a = a * a % mod; b >>= 1; } return ans % mod; } static long modular_inverse(long a) { return expo(a, mod - 2) % mod; } static long phin(long a) { if (isPrime(a)) return a - 1; long res = a; for (int i = 2; i * i <= (int) a; i++) { if (a % i == 0) { while (a % i == 0) { a = a / i; } res -= res / i; } } if (a > 1) { res -= res / a; } return res; } static boolean isPrime(long a) { if (a < 2) return false; for (int i = 2; i * i <= (int) a; i++) { if (a % i == 0) return false; } return true; } static long catlan(long a) { long ans = 1; for (int i = 1; i <= a; i++) { ans = ans * (4 * i - 2) % mod; ans = ((ans % mod) * modular_inverse(i + 1)) % mod; } return ans % mod; } static HashMap<Long, Long> primeFactors(long n) { HashMap<Long, Long> m1 = new HashMap<>(); for (int i = 2; (long) i * (long) i <= n; i++) { if (n % i == 0) { while (n % i == 0) { m1.put((long) i, m1.getOrDefault(i, 0l) + 1); n = n / i; } } } return m1; } static long gcd(long a,long b){ a=Math.abs(a); b=Math.abs(b); if(b==0) return a; return gcd(b,a%b); } static boolean isPalin(String s){ int i=0; int j=s.length()-1; while(i<j){ if(s.charAt(i)!=s.charAt(j)) return false; i++; j--; } return true; } static boolean valid(long[] a,int mid){ long[] temp=a.clone(); for(int i=a.length-1;i>=2;i--){ if(temp[i]<mid) return false; long d=Math.min(a[i],temp[i]-mid)/3; temp[i-1]+=d; temp[i-2]+=2*d; } for(long i:temp){ if(i<mid) return false; } return true; } // } } class pair{ int a; int b; pair(int a,int b){ this.a=a; this.b=b; } }
Java
["6\n\nlogic\n\ncodeforces\n\nbca\n\naaaaaaaaaaa\n\nadbaadabad\n\nto"]
1 second
["9 4\n1 4 3 5\n16 10\n1 8 3 4 9 5 2 6 7 10\n1 2\n1 3\n0 11\n1 8 10 4 3 5 7 2 9 6 11\n3 10\n1 9 5 4 7 3 8 6 2 10\n5 2\n1 2"]
NoteIn the first test case, the required path corresponds to the picture: In this case, the minimum possible total cost of the path is achieved. Since $$$index($$$'l'$$$)=12$$$, $$$index($$$'o'$$$)=15$$$, $$$index($$$'g'$$$)=7$$$, $$$index($$$'i'$$$)=9$$$, $$$index($$$'c'$$$)=3$$$, then the total cost of the path is $$$|12-9|+|9-7|+|7-3|=3+2+4=9$$$.
Java 17
standard input
[ "constructive algorithms", "strings" ]
d17c9f91504e1d4c4eae7294bf09dcfc
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. Each test case is given by the string $$$s$$$ ($$$2 \le |s| \le 2 \cdot 10^5$$$), where $$$|s|$$$ — is the length of string $$$s$$$. The string $$$s$$$ consists of lowercase Latin letters. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,100
The answer to each test case consists of two lines. In the first line print two integers $$$cost$$$, $$$m$$$, where $$$cost$$$ is the minimum total cost of the path, and $$$m$$$ is the maximum number of visited tiles Polycarp can make to get to $$$n$$$-th tiles for the minimum total cost $$$cost$$$ (i.e. the number of jumps is $$$m-1$$$). In the next line print $$$m$$$ different numbers $$$j_1, j_2, \dots, j_m$$$ ($$$1 \le j_i \le |s|$$$) — the sequence of indices of the tiles Polycarp will jump on. The first number in the sequence must be $$$1$$$ (that is, $$$j_1=1$$$) and the last number must be the value of $$$|s|$$$ (that is, $$$j_m=|s|$$$). If there are multiple answers, print any of them.
standard output
PASSED
96d806d043ed79761c7b3fd1f6ec9825
train_110.jsonl
1662993300
Polycarp was given a row of tiles. Each tile contains one lowercase letter of the Latin alphabet. The entire sequence of tiles forms the string $$$s$$$.In other words, you are given a string $$$s$$$ consisting of lowercase Latin letters.Initially, Polycarp is on the first tile of the row and wants to get to the last tile by jumping on the tiles. Jumping from $$$i$$$-th tile to $$$j$$$-th tile has a cost equal to $$$|index(s_i) - index(s_j)|$$$, where $$$index(c)$$$ is the index of the letter $$$c$$$ in the alphabet (for example, $$$index($$$'a'$$$)=1$$$, $$$index($$$'b'$$$)=2$$$, ..., $$$index($$$'z'$$$)=26$$$) .Polycarp wants to get to the $$$n$$$-th tile for the minimum total cost, but at the same time make maximum number of jumps.In other words, among all possible ways to get to the last tile for the minimum total cost, he will choose the one with the maximum number of jumps.Polycarp can visit each tile at most once.Polycarp asks you to help — print the sequence of indices of string $$$s$$$ on which he should jump.
256 megabytes
import java.util.Arrays; import java.util.Comparator; import java.util.Scanner; public class JumpingOnTiles { public static Scanner sc = new Scanner(System.in); public static void main(String[] args) { int cases = sc.nextInt(); for(int i = 0; i<cases;i++){ String s = sc.next(); sol(s); } } public static void sol(String s){ int cost = 0; int tiles = 2; int count = 0; char[] letters = s.toCharArray(); cost = Math.abs(letters[0]-letters[letters.length-1]); int[][] tileArr = new int[s.length()][2]; if(letters[0]<letters[letters.length-1]){ for(int j= 1; j<letters.length-1;j++){ if(letters[j]>=letters[0]&&letters[j]<=letters[letters.length-1]){ tileArr[count][0] = j+1; tileArr[count][1] = letters[j]; count++; tiles++; } } Arrays.sort(tileArr,0,count, Comparator.comparingInt(a -> a[1])); System.out.println(cost+" "+tiles); System.out.print(1+" "); for(int j = 0;j<count;j++){ System.out.print(tileArr[j][0]+" "); } System.out.print(letters.length); System.out.println(); }else if(letters[0]>letters[letters.length-1]){ for(int j= 1; j<letters.length-1;j++){ if(letters[j]<=letters[0]&&letters[j]>=letters[letters.length-1]){ tileArr[count][0] = j+1; tileArr[count][1] = letters[j]; count++; tiles++; } } Arrays.sort(tileArr,0,count, Comparator.comparingInt(a -> a[1])); System.out.println(cost+" "+tiles); System.out.print(1+" "); for(int j = count-1;j>=0;j--){ System.out.print(tileArr[j][0]+" "); } System.out.print(letters.length); System.out.println(); }else { for(int j= 1; j<letters.length-1;j++){ if(letters[j]==letters[0]){ tileArr[count][0] = j+1; tileArr[count][1] = letters[j]; count++; tiles++; } } Arrays.sort(tileArr,0,count, Comparator.comparingInt(a -> a[1])); System.out.println(cost+" "+tiles); System.out.print(1+" "); for(int j = 0;j<count;j++){ System.out.print(tileArr[j][0]+" "); } System.out.print(letters.length); System.out.println(); } } }
Java
["6\n\nlogic\n\ncodeforces\n\nbca\n\naaaaaaaaaaa\n\nadbaadabad\n\nto"]
1 second
["9 4\n1 4 3 5\n16 10\n1 8 3 4 9 5 2 6 7 10\n1 2\n1 3\n0 11\n1 8 10 4 3 5 7 2 9 6 11\n3 10\n1 9 5 4 7 3 8 6 2 10\n5 2\n1 2"]
NoteIn the first test case, the required path corresponds to the picture: In this case, the minimum possible total cost of the path is achieved. Since $$$index($$$'l'$$$)=12$$$, $$$index($$$'o'$$$)=15$$$, $$$index($$$'g'$$$)=7$$$, $$$index($$$'i'$$$)=9$$$, $$$index($$$'c'$$$)=3$$$, then the total cost of the path is $$$|12-9|+|9-7|+|7-3|=3+2+4=9$$$.
Java 17
standard input
[ "constructive algorithms", "strings" ]
d17c9f91504e1d4c4eae7294bf09dcfc
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. Each test case is given by the string $$$s$$$ ($$$2 \le |s| \le 2 \cdot 10^5$$$), where $$$|s|$$$ — is the length of string $$$s$$$. The string $$$s$$$ consists of lowercase Latin letters. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,100
The answer to each test case consists of two lines. In the first line print two integers $$$cost$$$, $$$m$$$, where $$$cost$$$ is the minimum total cost of the path, and $$$m$$$ is the maximum number of visited tiles Polycarp can make to get to $$$n$$$-th tiles for the minimum total cost $$$cost$$$ (i.e. the number of jumps is $$$m-1$$$). In the next line print $$$m$$$ different numbers $$$j_1, j_2, \dots, j_m$$$ ($$$1 \le j_i \le |s|$$$) — the sequence of indices of the tiles Polycarp will jump on. The first number in the sequence must be $$$1$$$ (that is, $$$j_1=1$$$) and the last number must be the value of $$$|s|$$$ (that is, $$$j_m=|s|$$$). If there are multiple answers, print any of them.
standard output
PASSED
1b8ef7cf6099df2a37f2af195a5d69ff
train_110.jsonl
1662993300
Polycarp was given a row of tiles. Each tile contains one lowercase letter of the Latin alphabet. The entire sequence of tiles forms the string $$$s$$$.In other words, you are given a string $$$s$$$ consisting of lowercase Latin letters.Initially, Polycarp is on the first tile of the row and wants to get to the last tile by jumping on the tiles. Jumping from $$$i$$$-th tile to $$$j$$$-th tile has a cost equal to $$$|index(s_i) - index(s_j)|$$$, where $$$index(c)$$$ is the index of the letter $$$c$$$ in the alphabet (for example, $$$index($$$'a'$$$)=1$$$, $$$index($$$'b'$$$)=2$$$, ..., $$$index($$$'z'$$$)=26$$$) .Polycarp wants to get to the $$$n$$$-th tile for the minimum total cost, but at the same time make maximum number of jumps.In other words, among all possible ways to get to the last tile for the minimum total cost, he will choose the one with the maximum number of jumps.Polycarp can visit each tile at most once.Polycarp asks you to help — print the sequence of indices of string $$$s$$$ on which he should jump.
256 megabytes
// package cf1729.cf1729c; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.Scanner; public class CF1729C { public static void main(String[] args) { Scanner s = new Scanner(System.in); int t = s.nextInt(); while (t-- > 0) { String x = s.next(); cf1729c(x, x.length()); } s.close(); } private static void cf1729c(String x, int n) { int f = x.charAt(0); int l = x.charAt(n - 1); int i; Map<Character, ArrayList<Integer>> m = new HashMap<>(); int direction = f > l ? -1 : 1; for (i = 0; i < n; i++) { if (m.containsKey(x.charAt(i))) { m.get(x.charAt(i)).add(i); } else { m.put(x.charAt(i), new ArrayList<>()); m.get(x.charAt(i)).add(i); } } int cost = Math.abs(l - f); int count = 0; ArrayList<Integer> result = new ArrayList<>(); for (i = f; i != l + direction; i += direction) { if (m.containsKey((char) i)) { ArrayList<Integer> al = m.get((char) i); count += al.size(); for (int ind : al) { result.add(ind + 1); } } } System.out.println(cost + " " + count); for (int index : result) { System.out.print(index + " "); } System.out.println(); } }
Java
["6\n\nlogic\n\ncodeforces\n\nbca\n\naaaaaaaaaaa\n\nadbaadabad\n\nto"]
1 second
["9 4\n1 4 3 5\n16 10\n1 8 3 4 9 5 2 6 7 10\n1 2\n1 3\n0 11\n1 8 10 4 3 5 7 2 9 6 11\n3 10\n1 9 5 4 7 3 8 6 2 10\n5 2\n1 2"]
NoteIn the first test case, the required path corresponds to the picture: In this case, the minimum possible total cost of the path is achieved. Since $$$index($$$'l'$$$)=12$$$, $$$index($$$'o'$$$)=15$$$, $$$index($$$'g'$$$)=7$$$, $$$index($$$'i'$$$)=9$$$, $$$index($$$'c'$$$)=3$$$, then the total cost of the path is $$$|12-9|+|9-7|+|7-3|=3+2+4=9$$$.
Java 17
standard input
[ "constructive algorithms", "strings" ]
d17c9f91504e1d4c4eae7294bf09dcfc
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. Each test case is given by the string $$$s$$$ ($$$2 \le |s| \le 2 \cdot 10^5$$$), where $$$|s|$$$ — is the length of string $$$s$$$. The string $$$s$$$ consists of lowercase Latin letters. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,100
The answer to each test case consists of two lines. In the first line print two integers $$$cost$$$, $$$m$$$, where $$$cost$$$ is the minimum total cost of the path, and $$$m$$$ is the maximum number of visited tiles Polycarp can make to get to $$$n$$$-th tiles for the minimum total cost $$$cost$$$ (i.e. the number of jumps is $$$m-1$$$). In the next line print $$$m$$$ different numbers $$$j_1, j_2, \dots, j_m$$$ ($$$1 \le j_i \le |s|$$$) — the sequence of indices of the tiles Polycarp will jump on. The first number in the sequence must be $$$1$$$ (that is, $$$j_1=1$$$) and the last number must be the value of $$$|s|$$$ (that is, $$$j_m=|s|$$$). If there are multiple answers, print any of them.
standard output
PASSED
840f55cbee158005f071ce994fce46cb
train_110.jsonl
1662993300
Polycarp was given a row of tiles. Each tile contains one lowercase letter of the Latin alphabet. The entire sequence of tiles forms the string $$$s$$$.In other words, you are given a string $$$s$$$ consisting of lowercase Latin letters.Initially, Polycarp is on the first tile of the row and wants to get to the last tile by jumping on the tiles. Jumping from $$$i$$$-th tile to $$$j$$$-th tile has a cost equal to $$$|index(s_i) - index(s_j)|$$$, where $$$index(c)$$$ is the index of the letter $$$c$$$ in the alphabet (for example, $$$index($$$'a'$$$)=1$$$, $$$index($$$'b'$$$)=2$$$, ..., $$$index($$$'z'$$$)=26$$$) .Polycarp wants to get to the $$$n$$$-th tile for the minimum total cost, but at the same time make maximum number of jumps.In other words, among all possible ways to get to the last tile for the minimum total cost, he will choose the one with the maximum number of jumps.Polycarp can visit each tile at most once.Polycarp asks you to help — print the sequence of indices of string $$$s$$$ on which he should jump.
256 megabytes
import java.util.*; import java.io.*; public class C_Jumping_on_Tiles { final int mod = 1000000007; 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(long[] a, int i, int j) { long temp = a[i]; a[i] = a[j]; a[j] = temp; } public static void main(String[] args) { // TODO Auto-generated method stub FastReader t = new FastReader(); PrintWriter o = new PrintWriter(System.out); int test = t.nextInt(); while (test-- > 0) { long min = Integer.MIN_VALUE, max = Integer.MAX_VALUE; long ans =0 ; String s = t.next(); HashMap<Integer, ArrayList<Integer>> map = new HashMap<>(); int q = 26, qq = 0; while(qq<q) { map.put(qq, new ArrayList<Integer>()); qq++; } qq = 1; for (char a : s.toCharArray()) { if (qq == 1) { } else { ArrayList<Integer> b = map.get(a-'a'); b.add(qq); } qq++; } char[] c = s.toCharArray(); Arrays.sort(c); int n = s.length(); char st = s.charAt(0); char e = s.charAt(n-1); int i = -1, j=-1, k = 0; if (st<=e) { for (char a : c) { if (a == st && i == -1) { i = k; } if (a == e) { j = k; } k++; } } else { for (char a : c) { if (a == st) { i = k; } if (a == e && j == -1) { j = k; } k++; } } boolean bo = false; if (i>j) { // int p = i; // i = j; // j = p; bo = true; } ArrayList<Integer> r = new ArrayList<Integer>(); r.add(1); if (!bo) { for (k=i+1; k<=j; k++) { ans += c[k]-c[k-1]; ArrayList<Integer> rr = map.get(c[k]-'a'); //o.println("ii "+c[k]); r.add(rr.get(0)); rr.remove(0); } } else { for (k=i-1; k>=j; k--) { ans += c[k+1]-c[k]; ArrayList<Integer> rr = map.get(c[k]-'a'); //o.println("ii "+c[k]); r.add(rr.get(0)); rr.remove(0); } } if (i>j) { int p = i; i = j; j = p; bo = true; } o.println(ans+" "+(j-i+1)); for (int y : r) { o.print(y+" "); } o.println(); // long m = t.nextLong(); // ArrayList<Integer> al = new ArrayList<>(); // HashSet<Integer> set = new HashSet<>(); // HashMap<Integer, Integer> map = new HashMap<>(); // TreeMap<Integer, Integer> map = new TreeMap<>(); // for (int i = 0; i < n; ++i) { // for (int j = 0; j < n; ++j) { // } // } } o.flush(); o.close(); } }
Java
["6\n\nlogic\n\ncodeforces\n\nbca\n\naaaaaaaaaaa\n\nadbaadabad\n\nto"]
1 second
["9 4\n1 4 3 5\n16 10\n1 8 3 4 9 5 2 6 7 10\n1 2\n1 3\n0 11\n1 8 10 4 3 5 7 2 9 6 11\n3 10\n1 9 5 4 7 3 8 6 2 10\n5 2\n1 2"]
NoteIn the first test case, the required path corresponds to the picture: In this case, the minimum possible total cost of the path is achieved. Since $$$index($$$'l'$$$)=12$$$, $$$index($$$'o'$$$)=15$$$, $$$index($$$'g'$$$)=7$$$, $$$index($$$'i'$$$)=9$$$, $$$index($$$'c'$$$)=3$$$, then the total cost of the path is $$$|12-9|+|9-7|+|7-3|=3+2+4=9$$$.
Java 17
standard input
[ "constructive algorithms", "strings" ]
d17c9f91504e1d4c4eae7294bf09dcfc
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. Each test case is given by the string $$$s$$$ ($$$2 \le |s| \le 2 \cdot 10^5$$$), where $$$|s|$$$ — is the length of string $$$s$$$. The string $$$s$$$ consists of lowercase Latin letters. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,100
The answer to each test case consists of two lines. In the first line print two integers $$$cost$$$, $$$m$$$, where $$$cost$$$ is the minimum total cost of the path, and $$$m$$$ is the maximum number of visited tiles Polycarp can make to get to $$$n$$$-th tiles for the minimum total cost $$$cost$$$ (i.e. the number of jumps is $$$m-1$$$). In the next line print $$$m$$$ different numbers $$$j_1, j_2, \dots, j_m$$$ ($$$1 \le j_i \le |s|$$$) — the sequence of indices of the tiles Polycarp will jump on. The first number in the sequence must be $$$1$$$ (that is, $$$j_1=1$$$) and the last number must be the value of $$$|s|$$$ (that is, $$$j_m=|s|$$$). If there are multiple answers, print any of them.
standard output
PASSED
ba239b030e77a2a3d153fa771dada121
train_110.jsonl
1662993300
Polycarp was given a row of tiles. Each tile contains one lowercase letter of the Latin alphabet. The entire sequence of tiles forms the string $$$s$$$.In other words, you are given a string $$$s$$$ consisting of lowercase Latin letters.Initially, Polycarp is on the first tile of the row and wants to get to the last tile by jumping on the tiles. Jumping from $$$i$$$-th tile to $$$j$$$-th tile has a cost equal to $$$|index(s_i) - index(s_j)|$$$, where $$$index(c)$$$ is the index of the letter $$$c$$$ in the alphabet (for example, $$$index($$$'a'$$$)=1$$$, $$$index($$$'b'$$$)=2$$$, ..., $$$index($$$'z'$$$)=26$$$) .Polycarp wants to get to the $$$n$$$-th tile for the minimum total cost, but at the same time make maximum number of jumps.In other words, among all possible ways to get to the last tile for the minimum total cost, he will choose the one with the maximum number of jumps.Polycarp can visit each tile at most once.Polycarp asks you to help — print the sequence of indices of string $$$s$$$ on which he should jump.
256 megabytes
import java.util.Arrays; import java.util.Comparator; import java.util.Scanner; import java.util.stream.Collectors; import java.util.stream.IntStream; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); for (int tc = 0; tc < t; ++tc) { String s = sc.next(); System.out.println(solve(s)); } sc.close(); } static String solve(String s) { int[] indices = IntStream.range(0, s.length()) .filter( i -> (s.charAt(i) - s.charAt(0)) * (s.charAt(i) - s.charAt(s.length() - 1)) <= 0) .boxed() .sorted(Comparator.comparing(i -> Math.abs(s.charAt(i) - s.charAt(0)))) .mapToInt(x -> x) .toArray(); return String.format( "%d %d\n%s", Math.abs(s.charAt(0) - s.charAt(s.length() - 1)), indices.length, Arrays.stream(indices) .map(i -> i + 1) .mapToObj(String::valueOf) .collect(Collectors.joining(" "))); } }
Java
["6\n\nlogic\n\ncodeforces\n\nbca\n\naaaaaaaaaaa\n\nadbaadabad\n\nto"]
1 second
["9 4\n1 4 3 5\n16 10\n1 8 3 4 9 5 2 6 7 10\n1 2\n1 3\n0 11\n1 8 10 4 3 5 7 2 9 6 11\n3 10\n1 9 5 4 7 3 8 6 2 10\n5 2\n1 2"]
NoteIn the first test case, the required path corresponds to the picture: In this case, the minimum possible total cost of the path is achieved. Since $$$index($$$'l'$$$)=12$$$, $$$index($$$'o'$$$)=15$$$, $$$index($$$'g'$$$)=7$$$, $$$index($$$'i'$$$)=9$$$, $$$index($$$'c'$$$)=3$$$, then the total cost of the path is $$$|12-9|+|9-7|+|7-3|=3+2+4=9$$$.
Java 17
standard input
[ "constructive algorithms", "strings" ]
d17c9f91504e1d4c4eae7294bf09dcfc
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. Each test case is given by the string $$$s$$$ ($$$2 \le |s| \le 2 \cdot 10^5$$$), where $$$|s|$$$ — is the length of string $$$s$$$. The string $$$s$$$ consists of lowercase Latin letters. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,100
The answer to each test case consists of two lines. In the first line print two integers $$$cost$$$, $$$m$$$, where $$$cost$$$ is the minimum total cost of the path, and $$$m$$$ is the maximum number of visited tiles Polycarp can make to get to $$$n$$$-th tiles for the minimum total cost $$$cost$$$ (i.e. the number of jumps is $$$m-1$$$). In the next line print $$$m$$$ different numbers $$$j_1, j_2, \dots, j_m$$$ ($$$1 \le j_i \le |s|$$$) — the sequence of indices of the tiles Polycarp will jump on. The first number in the sequence must be $$$1$$$ (that is, $$$j_1=1$$$) and the last number must be the value of $$$|s|$$$ (that is, $$$j_m=|s|$$$). If there are multiple answers, print any of them.
standard output
PASSED
067093a3a2dd507f34c5becf221d60df
train_110.jsonl
1662993300
Polycarp was given a row of tiles. Each tile contains one lowercase letter of the Latin alphabet. The entire sequence of tiles forms the string $$$s$$$.In other words, you are given a string $$$s$$$ consisting of lowercase Latin letters.Initially, Polycarp is on the first tile of the row and wants to get to the last tile by jumping on the tiles. Jumping from $$$i$$$-th tile to $$$j$$$-th tile has a cost equal to $$$|index(s_i) - index(s_j)|$$$, where $$$index(c)$$$ is the index of the letter $$$c$$$ in the alphabet (for example, $$$index($$$'a'$$$)=1$$$, $$$index($$$'b'$$$)=2$$$, ..., $$$index($$$'z'$$$)=26$$$) .Polycarp wants to get to the $$$n$$$-th tile for the minimum total cost, but at the same time make maximum number of jumps.In other words, among all possible ways to get to the last tile for the minimum total cost, he will choose the one with the maximum number of jumps.Polycarp can visit each tile at most once.Polycarp asks you to help — print the sequence of indices of string $$$s$$$ on which he should jump.
256 megabytes
import java.util.*; import java.util.stream.IntStream; public class C { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int t = scanner.nextInt(); while(t-- > 0) { String s = scanner.next(); int n = s.length(); // char[] chs = s.toCharArray(); Pair[] pairs = new Pair[n]; for(int i = 0;i < n;i++) { pairs[i] = new Pair(i, s.charAt(i)); } if(pairs[0].val <= pairs[n - 1].val) { Arrays.sort(pairs, (o, p) -> o.val != p.val ? o.val - p.val : o.index - p.index); } else { Arrays.sort(pairs, (o, p) -> p.val != o.val ? p.val - o.val : o.index - p.index); } char begin = s.charAt(0), end = s.charAt(n - 1); int m = 0; long cost = 0L; char last = begin; List<Integer> res = new ArrayList<>(); for(int i = 0;i < n;i++) { if(pairs[i].val >= Math.min(begin, end) && pairs[i].val <= Math.max(begin, end)) { m++; cost += Math.abs(last - pairs[i].val); last = pairs[i].val; res.add(pairs[i].index); } } System.out.println(cost + " " + m); for(int i = 0;i < res.size();i++) { System.out.print((res.get(i) + 1) + " "); } System.out.println(); } } static class Pair { char val; int index; public Pair(int index, char val) { this.val = val; this.index = index; } } }
Java
["6\n\nlogic\n\ncodeforces\n\nbca\n\naaaaaaaaaaa\n\nadbaadabad\n\nto"]
1 second
["9 4\n1 4 3 5\n16 10\n1 8 3 4 9 5 2 6 7 10\n1 2\n1 3\n0 11\n1 8 10 4 3 5 7 2 9 6 11\n3 10\n1 9 5 4 7 3 8 6 2 10\n5 2\n1 2"]
NoteIn the first test case, the required path corresponds to the picture: In this case, the minimum possible total cost of the path is achieved. Since $$$index($$$'l'$$$)=12$$$, $$$index($$$'o'$$$)=15$$$, $$$index($$$'g'$$$)=7$$$, $$$index($$$'i'$$$)=9$$$, $$$index($$$'c'$$$)=3$$$, then the total cost of the path is $$$|12-9|+|9-7|+|7-3|=3+2+4=9$$$.
Java 17
standard input
[ "constructive algorithms", "strings" ]
d17c9f91504e1d4c4eae7294bf09dcfc
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. Each test case is given by the string $$$s$$$ ($$$2 \le |s| \le 2 \cdot 10^5$$$), where $$$|s|$$$ — is the length of string $$$s$$$. The string $$$s$$$ consists of lowercase Latin letters. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,100
The answer to each test case consists of two lines. In the first line print two integers $$$cost$$$, $$$m$$$, where $$$cost$$$ is the minimum total cost of the path, and $$$m$$$ is the maximum number of visited tiles Polycarp can make to get to $$$n$$$-th tiles for the minimum total cost $$$cost$$$ (i.e. the number of jumps is $$$m-1$$$). In the next line print $$$m$$$ different numbers $$$j_1, j_2, \dots, j_m$$$ ($$$1 \le j_i \le |s|$$$) — the sequence of indices of the tiles Polycarp will jump on. The first number in the sequence must be $$$1$$$ (that is, $$$j_1=1$$$) and the last number must be the value of $$$|s|$$$ (that is, $$$j_m=|s|$$$). If there are multiple answers, print any of them.
standard output
PASSED
49ea30ed74282aa977a1913de635454c
train_110.jsonl
1662993300
Polycarp was given a row of tiles. Each tile contains one lowercase letter of the Latin alphabet. The entire sequence of tiles forms the string $$$s$$$.In other words, you are given a string $$$s$$$ consisting of lowercase Latin letters.Initially, Polycarp is on the first tile of the row and wants to get to the last tile by jumping on the tiles. Jumping from $$$i$$$-th tile to $$$j$$$-th tile has a cost equal to $$$|index(s_i) - index(s_j)|$$$, where $$$index(c)$$$ is the index of the letter $$$c$$$ in the alphabet (for example, $$$index($$$'a'$$$)=1$$$, $$$index($$$'b'$$$)=2$$$, ..., $$$index($$$'z'$$$)=26$$$) .Polycarp wants to get to the $$$n$$$-th tile for the minimum total cost, but at the same time make maximum number of jumps.In other words, among all possible ways to get to the last tile for the minimum total cost, he will choose the one with the maximum number of jumps.Polycarp can visit each tile at most once.Polycarp asks you to help — print the sequence of indices of string $$$s$$$ on which he should jump.
256 megabytes
/****************************************************************************** Online Java Compiler. Code, Compile, Run and Debug java program online. Write your code in this editor and press "Run" button to execute it. *******************************************************************************/ import java.util.*; public class Main { public static boolean issorted(int []arr){ for(int i = 1;i<arr.length;i++){ if(arr[i]<arr[i-1]){ return false; } } return true; } public static long sum(int []arr){ long sum = 0; for(int i = 0;i<arr.length;i++){ sum+=arr[i]; } return sum; } public static class pair implements Comparable<pair>{ int x; int y; pair(int x,int y){ this.x = x; this.y = y; } public int compareTo(pair o){ return this.x - o.x; // sort increasingly on the basis of x // return o.x - this.x // sort decreasingly on the basis of x } } public static void swap(int i,int j){ int temp = i; i = j; j = temp; } public static int gcd(int a, int b){ if (b == 0) return a; return gcd(b, a % b); } static int []parent = new int[1000]; static int []size = new int[1000]; public static void make(int v){ parent[v] = v; size[v] = 1; } public static int find(int v){ if(parent[v]==v){ return v; } else{ return parent[v] = find(parent[v]); } } public static void union(int a,int b){ a = find(a); b = find(b); if(a!=b){ if(size[a]>size[b]){ parent[b] = parent[a]; size[b]+=size[a]; } else{ parent[a] = parent[b]; size[a]+=size[b]; } } } static boolean []visited = new boolean[1000]; public static void dfs(int vertex,ArrayList<ArrayList<Integer>>graph){ if(visited[vertex] == true){ return; } System.out.println(vertex); for(int child : graph.get(vertex)){ // work to be done before entering the child dfs(child,graph); // work to be done after exitting the child } } public static void displayint(int []arr){ for(int i = 0;i<arr.length;i++){ System.out.print(arr[i]+" "); } System.out.println(); } public static void displaystr(String str){ StringBuilder sb = new StringBuilder(str); for(int i = 0;i<sb.length();i++){ System.out.print(sb.charAt(i)); } System.out.println(); } public static boolean checkbalanceparenthesis(StringBuilder ans){ Stack<Character>st = new Stack<>(); int i = 0; while(i<ans.length()){ if(ans.charAt(i) == '('){ st.push('('); } else{ if(st.size() == 0 || st.peek()!='('){ return false; } else{ st.pop(); } } } return st.size() == 0; } public static long binaryExp(long a,long b,long m){ /// This is Iterative Version long res = 1; while(b>0){ if((b&1)!=0){ res = (res*a)%m; } b>>=1; a = (a*a)%m; } return res; } public static void main(String[] args) { Scanner scn = new Scanner(System.in); int t = scn.nextInt(); while(t-->0){ HashMap<Character,Integer>map = new HashMap<>(); int j = 1; for(char ch = 'a';ch<='z';ch++){ map.put(ch,j); j++; } String str = scn.next(); int v1 = map.get(str.charAt(0)); // System.out.println(v1); int v2 = map.get(str.charAt(str.length()-1)); if(v1>v2){ ///decreasing case ArrayList<pair>list = new ArrayList<>(); list.add(new pair(v1,1)); for(int i = 1;i<str.length();i++){ int x = map.get(str.charAt(i)); if(x<=v1 && x>=v2){ pair p = new pair(map.get(str.charAt(i)),i+1); list.add(p); } else{ } } //System.out.println(list.size()); Collections.sort(list,Collections.reverseOrder()); StringBuilder sb = new StringBuilder(""); int jumps = list.size(); long ans = 0; StringBuilder path = new StringBuilder(""); path.append(1+" "); for(int i = 1;i<list.size();i++){ ans+=Math.abs(list.get(i).x-list.get(i-1).x); path.append(list.get(i).y+" "); } System.out.println(ans+" "+jumps); System.out.println(path); } else{ ArrayList<pair>list = new ArrayList<>(); list.add(new pair(v1,1)); for(int i = 1;i<str.length();i++){ int x = map.get(str.charAt(i)); if(x>=v1 && x<=v2){ pair p = new pair(map.get(str.charAt(i)),i+1); list.add(p); } else{ } } Collections.sort(list); //StringBuilder sb = new StringBuilder(""); int jumps = list.size(); long ans = 0; StringBuilder path = new StringBuilder(""); path.append(1+" "); for(int i = 1;i<list.size();i++){ ans+=Math.abs(list.get(i).x-list.get(i-1).x); path.append(list.get(i).y+" "); } System.out.println(ans+" "+jumps); System.out.println(path); } } } }
Java
["6\n\nlogic\n\ncodeforces\n\nbca\n\naaaaaaaaaaa\n\nadbaadabad\n\nto"]
1 second
["9 4\n1 4 3 5\n16 10\n1 8 3 4 9 5 2 6 7 10\n1 2\n1 3\n0 11\n1 8 10 4 3 5 7 2 9 6 11\n3 10\n1 9 5 4 7 3 8 6 2 10\n5 2\n1 2"]
NoteIn the first test case, the required path corresponds to the picture: In this case, the minimum possible total cost of the path is achieved. Since $$$index($$$'l'$$$)=12$$$, $$$index($$$'o'$$$)=15$$$, $$$index($$$'g'$$$)=7$$$, $$$index($$$'i'$$$)=9$$$, $$$index($$$'c'$$$)=3$$$, then the total cost of the path is $$$|12-9|+|9-7|+|7-3|=3+2+4=9$$$.
Java 17
standard input
[ "constructive algorithms", "strings" ]
d17c9f91504e1d4c4eae7294bf09dcfc
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. Each test case is given by the string $$$s$$$ ($$$2 \le |s| \le 2 \cdot 10^5$$$), where $$$|s|$$$ — is the length of string $$$s$$$. The string $$$s$$$ consists of lowercase Latin letters. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,100
The answer to each test case consists of two lines. In the first line print two integers $$$cost$$$, $$$m$$$, where $$$cost$$$ is the minimum total cost of the path, and $$$m$$$ is the maximum number of visited tiles Polycarp can make to get to $$$n$$$-th tiles for the minimum total cost $$$cost$$$ (i.e. the number of jumps is $$$m-1$$$). In the next line print $$$m$$$ different numbers $$$j_1, j_2, \dots, j_m$$$ ($$$1 \le j_i \le |s|$$$) — the sequence of indices of the tiles Polycarp will jump on. The first number in the sequence must be $$$1$$$ (that is, $$$j_1=1$$$) and the last number must be the value of $$$|s|$$$ (that is, $$$j_m=|s|$$$). If there are multiple answers, print any of them.
standard output
PASSED
efb08619ad7377957334fad9eee1a725
train_110.jsonl
1662993300
Polycarp was given a row of tiles. Each tile contains one lowercase letter of the Latin alphabet. The entire sequence of tiles forms the string $$$s$$$.In other words, you are given a string $$$s$$$ consisting of lowercase Latin letters.Initially, Polycarp is on the first tile of the row and wants to get to the last tile by jumping on the tiles. Jumping from $$$i$$$-th tile to $$$j$$$-th tile has a cost equal to $$$|index(s_i) - index(s_j)|$$$, where $$$index(c)$$$ is the index of the letter $$$c$$$ in the alphabet (for example, $$$index($$$'a'$$$)=1$$$, $$$index($$$'b'$$$)=2$$$, ..., $$$index($$$'z'$$$)=26$$$) .Polycarp wants to get to the $$$n$$$-th tile for the minimum total cost, but at the same time make maximum number of jumps.In other words, among all possible ways to get to the last tile for the minimum total cost, he will choose the one with the maximum number of jumps.Polycarp can visit each tile at most once.Polycarp asks you to help — print the sequence of indices of string $$$s$$$ on which he should jump.
256 megabytes
import java.util.*; import java.io.*; public class Main{ public static Integer[] array(BufferedReader br,int n) throws IOException{ String [] values = br.readLine().split(" "); Integer [] arr = new Integer[n]; for(int i =0; i<n; i++){ arr[i] = Integer.parseInt(values[i]); } return arr; } public static class Pair implements Comparable<Pair>{ int val; int idx; Pair(int val, int idx){ this.val = val; this.idx = idx; } public int compareTo(Pair o){ return this.val-o.val; } } public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(br.readLine()); while(t-->0){ String str = br.readLine(); Pair [] arr = new Pair[str.length()]; for(int i =0; i<arr.length; i++){ char ch = str.charAt(i); arr[i] = new Pair((int) ch-'a' +1, i); } ArrayList<Integer> list = new ArrayList<>(); if(arr[0].val>arr[arr.length-1].val){ Arrays.sort(arr,1,arr.length-1); list.add(0); int i = arr.length-2; while(i!=0){ if(arr[i].val<=arr[0].val && arr[i].val>=arr[arr.length-1].val){ list.add(arr[i].idx); } else{ } i--; } list.add(arr.length-1); } else{ Arrays.sort(arr,1,arr.length-1); int i = 0; while(i!=arr.length-1){ if(arr[i].val>=arr[0].val && arr[i].val<=arr[arr.length-1].val){ list.add(arr[i].idx); } else{ } i++; } list.add(arr.length-1); } System.out.println(Math.abs(arr[0].val - arr[arr.length-1].val) + " " + list.size()); StringBuilder sb = new StringBuilder(); for(int i =0; i<list.size(); i++){ sb.append(list.get(i)+1 + " "); } System.out.println(sb); } } }
Java
["6\n\nlogic\n\ncodeforces\n\nbca\n\naaaaaaaaaaa\n\nadbaadabad\n\nto"]
1 second
["9 4\n1 4 3 5\n16 10\n1 8 3 4 9 5 2 6 7 10\n1 2\n1 3\n0 11\n1 8 10 4 3 5 7 2 9 6 11\n3 10\n1 9 5 4 7 3 8 6 2 10\n5 2\n1 2"]
NoteIn the first test case, the required path corresponds to the picture: In this case, the minimum possible total cost of the path is achieved. Since $$$index($$$'l'$$$)=12$$$, $$$index($$$'o'$$$)=15$$$, $$$index($$$'g'$$$)=7$$$, $$$index($$$'i'$$$)=9$$$, $$$index($$$'c'$$$)=3$$$, then the total cost of the path is $$$|12-9|+|9-7|+|7-3|=3+2+4=9$$$.
Java 17
standard input
[ "constructive algorithms", "strings" ]
d17c9f91504e1d4c4eae7294bf09dcfc
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. Each test case is given by the string $$$s$$$ ($$$2 \le |s| \le 2 \cdot 10^5$$$), where $$$|s|$$$ — is the length of string $$$s$$$. The string $$$s$$$ consists of lowercase Latin letters. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,100
The answer to each test case consists of two lines. In the first line print two integers $$$cost$$$, $$$m$$$, where $$$cost$$$ is the minimum total cost of the path, and $$$m$$$ is the maximum number of visited tiles Polycarp can make to get to $$$n$$$-th tiles for the minimum total cost $$$cost$$$ (i.e. the number of jumps is $$$m-1$$$). In the next line print $$$m$$$ different numbers $$$j_1, j_2, \dots, j_m$$$ ($$$1 \le j_i \le |s|$$$) — the sequence of indices of the tiles Polycarp will jump on. The first number in the sequence must be $$$1$$$ (that is, $$$j_1=1$$$) and the last number must be the value of $$$|s|$$$ (that is, $$$j_m=|s|$$$). If there are multiple answers, print any of them.
standard output
PASSED
123150421067eec979a5be7f63d62c24
train_110.jsonl
1662993300
Polycarp was given a row of tiles. Each tile contains one lowercase letter of the Latin alphabet. The entire sequence of tiles forms the string $$$s$$$.In other words, you are given a string $$$s$$$ consisting of lowercase Latin letters.Initially, Polycarp is on the first tile of the row and wants to get to the last tile by jumping on the tiles. Jumping from $$$i$$$-th tile to $$$j$$$-th tile has a cost equal to $$$|index(s_i) - index(s_j)|$$$, where $$$index(c)$$$ is the index of the letter $$$c$$$ in the alphabet (for example, $$$index($$$'a'$$$)=1$$$, $$$index($$$'b'$$$)=2$$$, ..., $$$index($$$'z'$$$)=26$$$) .Polycarp wants to get to the $$$n$$$-th tile for the minimum total cost, but at the same time make maximum number of jumps.In other words, among all possible ways to get to the last tile for the minimum total cost, he will choose the one with the maximum number of jumps.Polycarp can visit each tile at most once.Polycarp asks you to help — print the sequence of indices of string $$$s$$$ on which he should jump.
256 megabytes
import java.util.*; public class text1 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int cs = sc.nextInt(); for(int dz = 0;dz < cs;dz ++){ String word = sc.next(); int a = Math.abs((int)(word.charAt(0) - word.charAt(word.length() - 1))); System.out.print(a + " "); char big = (char)Math.max(word.charAt(0),word.charAt(word.length() - 1)); char small = (char)Math.min(word.charAt(0),word.charAt(word.length() - 1)); TreeMap<Character,List<Integer>> map = new TreeMap<>(); int number = 2; for(int dz1 = 1;dz1 < word.length() - 1;dz1 ++){ if(word.charAt(dz1) >= small && word.charAt(dz1) <= big){ if(!map.containsKey(word.charAt(dz1))){ List<Integer> list = new ArrayList<>(); list.add(dz1 + 1); map.put(word.charAt(dz1),list); number ++; }else{ List<Integer> list = map.get(word.charAt(dz1)); list.add(dz1 + 1); map.put(word.charAt(dz1),list); number ++; } } } System.out.println(number); System.out.print(1 + " "); if(word.charAt(0) < word.charAt(word.length() - 1)) { for (char b : map.keySet()) { List<Integer> list = map.get(b); for (int dz1 = 0; dz1 < list.size(); dz1++) { System.out.print(list.get(dz1) + " "); } } }else{ List<Integer> location = new ArrayList<>(); for (char b : map.keySet()) { List<Integer> list = map.get(b); for (int dz1 = 0; dz1 < list.size(); dz1++) location.add(list.get(dz1)); } for(int dj = location.size() - 1;dj >= 0;dj --) System.out.print(location.get(dj) + " "); } System.out.print(word.length()); System.out.println(); } return ; } }
Java
["6\n\nlogic\n\ncodeforces\n\nbca\n\naaaaaaaaaaa\n\nadbaadabad\n\nto"]
1 second
["9 4\n1 4 3 5\n16 10\n1 8 3 4 9 5 2 6 7 10\n1 2\n1 3\n0 11\n1 8 10 4 3 5 7 2 9 6 11\n3 10\n1 9 5 4 7 3 8 6 2 10\n5 2\n1 2"]
NoteIn the first test case, the required path corresponds to the picture: In this case, the minimum possible total cost of the path is achieved. Since $$$index($$$'l'$$$)=12$$$, $$$index($$$'o'$$$)=15$$$, $$$index($$$'g'$$$)=7$$$, $$$index($$$'i'$$$)=9$$$, $$$index($$$'c'$$$)=3$$$, then the total cost of the path is $$$|12-9|+|9-7|+|7-3|=3+2+4=9$$$.
Java 17
standard input
[ "constructive algorithms", "strings" ]
d17c9f91504e1d4c4eae7294bf09dcfc
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. Each test case is given by the string $$$s$$$ ($$$2 \le |s| \le 2 \cdot 10^5$$$), where $$$|s|$$$ — is the length of string $$$s$$$. The string $$$s$$$ consists of lowercase Latin letters. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,100
The answer to each test case consists of two lines. In the first line print two integers $$$cost$$$, $$$m$$$, where $$$cost$$$ is the minimum total cost of the path, and $$$m$$$ is the maximum number of visited tiles Polycarp can make to get to $$$n$$$-th tiles for the minimum total cost $$$cost$$$ (i.e. the number of jumps is $$$m-1$$$). In the next line print $$$m$$$ different numbers $$$j_1, j_2, \dots, j_m$$$ ($$$1 \le j_i \le |s|$$$) — the sequence of indices of the tiles Polycarp will jump on. The first number in the sequence must be $$$1$$$ (that is, $$$j_1=1$$$) and the last number must be the value of $$$|s|$$$ (that is, $$$j_m=|s|$$$). If there are multiple answers, print any of them.
standard output
PASSED
7e9bd2d84365684b2baae932d21ef072
train_110.jsonl
1662993300
Polycarp was given a row of tiles. Each tile contains one lowercase letter of the Latin alphabet. The entire sequence of tiles forms the string $$$s$$$.In other words, you are given a string $$$s$$$ consisting of lowercase Latin letters.Initially, Polycarp is on the first tile of the row and wants to get to the last tile by jumping on the tiles. Jumping from $$$i$$$-th tile to $$$j$$$-th tile has a cost equal to $$$|index(s_i) - index(s_j)|$$$, where $$$index(c)$$$ is the index of the letter $$$c$$$ in the alphabet (for example, $$$index($$$'a'$$$)=1$$$, $$$index($$$'b'$$$)=2$$$, ..., $$$index($$$'z'$$$)=26$$$) .Polycarp wants to get to the $$$n$$$-th tile for the minimum total cost, but at the same time make maximum number of jumps.In other words, among all possible ways to get to the last tile for the minimum total cost, he will choose the one with the maximum number of jumps.Polycarp can visit each tile at most once.Polycarp asks you to help — print the sequence of indices of string $$$s$$$ on which he should jump.
256 megabytes
import java.io.*; import java.util.*; import static java.lang.Math.*; public class Main { static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); static int tcs, n; static StringTokenizer st; static String str; static int cost, tj; static StringBuilder sb; static int[] steps = new int[200005]; private static void solved() throws IOException { str = " " + br.readLine(); n = str.length() - 1; steps[1] = 1; tj = 1; cost = abs(str.charAt(n) - str.charAt(1)); int min = min(str.charAt(1),str.charAt(n)); int max = max(str.charAt(1),str.charAt(n)); List<int[]> ls = new ArrayList<>(); ls.add(new int[] {1, str.charAt(1)}); char c; for (int i = 2 ; i <= n -1 ; i++) { c = str.charAt(i); if(c >= min && c <= max) { tj++; steps[tj] = i; ls.add(new int[] {i, c}); } } tj++; steps[tj] = n; ls.add(new int[] {n, str.charAt(n)}); System.out.println(cost + " " + tj); if (str.charAt(1) == min) { ls.sort((a,b) -> a[1] - b[1]); } else { ls.sort((a,b) -> - a[1] + b[1]); } for (int[] node: ls) { System.out.print(node[0] +" "); } // for(int i = 1; i <= tj; i++) { // System.out.print(steps[i]+" "); // } System.out.println(); } public static void main(String[] args) throws IOException { tcs = Integer.parseInt(br.readLine()); while (tcs-- > 0) { solved(); } } }
Java
["6\n\nlogic\n\ncodeforces\n\nbca\n\naaaaaaaaaaa\n\nadbaadabad\n\nto"]
1 second
["9 4\n1 4 3 5\n16 10\n1 8 3 4 9 5 2 6 7 10\n1 2\n1 3\n0 11\n1 8 10 4 3 5 7 2 9 6 11\n3 10\n1 9 5 4 7 3 8 6 2 10\n5 2\n1 2"]
NoteIn the first test case, the required path corresponds to the picture: In this case, the minimum possible total cost of the path is achieved. Since $$$index($$$'l'$$$)=12$$$, $$$index($$$'o'$$$)=15$$$, $$$index($$$'g'$$$)=7$$$, $$$index($$$'i'$$$)=9$$$, $$$index($$$'c'$$$)=3$$$, then the total cost of the path is $$$|12-9|+|9-7|+|7-3|=3+2+4=9$$$.
Java 17
standard input
[ "constructive algorithms", "strings" ]
d17c9f91504e1d4c4eae7294bf09dcfc
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. Each test case is given by the string $$$s$$$ ($$$2 \le |s| \le 2 \cdot 10^5$$$), where $$$|s|$$$ — is the length of string $$$s$$$. The string $$$s$$$ consists of lowercase Latin letters. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,100
The answer to each test case consists of two lines. In the first line print two integers $$$cost$$$, $$$m$$$, where $$$cost$$$ is the minimum total cost of the path, and $$$m$$$ is the maximum number of visited tiles Polycarp can make to get to $$$n$$$-th tiles for the minimum total cost $$$cost$$$ (i.e. the number of jumps is $$$m-1$$$). In the next line print $$$m$$$ different numbers $$$j_1, j_2, \dots, j_m$$$ ($$$1 \le j_i \le |s|$$$) — the sequence of indices of the tiles Polycarp will jump on. The first number in the sequence must be $$$1$$$ (that is, $$$j_1=1$$$) and the last number must be the value of $$$|s|$$$ (that is, $$$j_m=|s|$$$). If there are multiple answers, print any of them.
standard output
PASSED
5e95752b262a34fef7ffe229452dea35
train_110.jsonl
1662993300
Polycarp was given a row of tiles. Each tile contains one lowercase letter of the Latin alphabet. The entire sequence of tiles forms the string $$$s$$$.In other words, you are given a string $$$s$$$ consisting of lowercase Latin letters.Initially, Polycarp is on the first tile of the row and wants to get to the last tile by jumping on the tiles. Jumping from $$$i$$$-th tile to $$$j$$$-th tile has a cost equal to $$$|index(s_i) - index(s_j)|$$$, where $$$index(c)$$$ is the index of the letter $$$c$$$ in the alphabet (for example, $$$index($$$'a'$$$)=1$$$, $$$index($$$'b'$$$)=2$$$, ..., $$$index($$$'z'$$$)=26$$$) .Polycarp wants to get to the $$$n$$$-th tile for the minimum total cost, but at the same time make maximum number of jumps.In other words, among all possible ways to get to the last tile for the minimum total cost, he will choose the one with the maximum number of jumps.Polycarp can visit each tile at most once.Polycarp asks you to help — print the sequence of indices of string $$$s$$$ on which he should jump.
256 megabytes
import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Scanner; import java.util.TreeMap; public class CF1729C { public static void main(String[] args) { Scanner scanner = new Scanner(System.in, StandardCharsets.UTF_8); int t = scanner.nextInt(); for (int i = 0; i < t; i++) { String s = scanner.next(); List<String> res = solve(s); for (String re : res) { System.out.println(re); } } } private static List<String> solve(String s) { int len = s.length(); char begin = s.charAt(0); char end = s.charAt(len - 1); TreeMap<Character, List<Integer>> idxListTreeMap = new TreeMap<>(); for (int i = 0; i < len; i++) { char ch = s.charAt(i); idxListTreeMap.computeIfAbsent(ch, key -> new ArrayList<>()).add(i + 1); } List<String> orderList = new ArrayList<>(); int cost; if (begin == end) { cost = 0; List<Integer> idxList = idxListTreeMap.get(begin); for (int id : idxList) { orderList.add(String.valueOf(id)); } } else if (begin < end) { cost = end - begin; // 小到大 char ch = begin; while (ch <= end) { List<Integer> idxList = idxListTreeMap.get(ch); for (int id : idxList) { orderList.add(String.valueOf(id)); } Character higherKey = idxListTreeMap.higherKey(ch); if (higherKey == null) { break; } ch = higherKey; } } else { cost = begin - end; // 大到小 char ch = begin; while (ch >= end) { List<Integer> idxList = idxListTreeMap.get(ch); for (int id : idxList) { orderList.add(String.valueOf(id)); } Character lowerKey = idxListTreeMap.lowerKey(ch); if (lowerKey == null) { break; } ch = lowerKey; } } List<String> resList = new ArrayList<>(); resList.add(cost + " " + orderList.size()); resList.add(String.join(" ", orderList)); return resList; } }
Java
["6\n\nlogic\n\ncodeforces\n\nbca\n\naaaaaaaaaaa\n\nadbaadabad\n\nto"]
1 second
["9 4\n1 4 3 5\n16 10\n1 8 3 4 9 5 2 6 7 10\n1 2\n1 3\n0 11\n1 8 10 4 3 5 7 2 9 6 11\n3 10\n1 9 5 4 7 3 8 6 2 10\n5 2\n1 2"]
NoteIn the first test case, the required path corresponds to the picture: In this case, the minimum possible total cost of the path is achieved. Since $$$index($$$'l'$$$)=12$$$, $$$index($$$'o'$$$)=15$$$, $$$index($$$'g'$$$)=7$$$, $$$index($$$'i'$$$)=9$$$, $$$index($$$'c'$$$)=3$$$, then the total cost of the path is $$$|12-9|+|9-7|+|7-3|=3+2+4=9$$$.
Java 17
standard input
[ "constructive algorithms", "strings" ]
d17c9f91504e1d4c4eae7294bf09dcfc
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. Each test case is given by the string $$$s$$$ ($$$2 \le |s| \le 2 \cdot 10^5$$$), where $$$|s|$$$ — is the length of string $$$s$$$. The string $$$s$$$ consists of lowercase Latin letters. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,100
The answer to each test case consists of two lines. In the first line print two integers $$$cost$$$, $$$m$$$, where $$$cost$$$ is the minimum total cost of the path, and $$$m$$$ is the maximum number of visited tiles Polycarp can make to get to $$$n$$$-th tiles for the minimum total cost $$$cost$$$ (i.e. the number of jumps is $$$m-1$$$). In the next line print $$$m$$$ different numbers $$$j_1, j_2, \dots, j_m$$$ ($$$1 \le j_i \le |s|$$$) — the sequence of indices of the tiles Polycarp will jump on. The first number in the sequence must be $$$1$$$ (that is, $$$j_1=1$$$) and the last number must be the value of $$$|s|$$$ (that is, $$$j_m=|s|$$$). If there are multiple answers, print any of them.
standard output
PASSED
df75047a38e38302a77394c5dee226f4
train_110.jsonl
1662993300
Polycarp was given a row of tiles. Each tile contains one lowercase letter of the Latin alphabet. The entire sequence of tiles forms the string $$$s$$$.In other words, you are given a string $$$s$$$ consisting of lowercase Latin letters.Initially, Polycarp is on the first tile of the row and wants to get to the last tile by jumping on the tiles. Jumping from $$$i$$$-th tile to $$$j$$$-th tile has a cost equal to $$$|index(s_i) - index(s_j)|$$$, where $$$index(c)$$$ is the index of the letter $$$c$$$ in the alphabet (for example, $$$index($$$'a'$$$)=1$$$, $$$index($$$'b'$$$)=2$$$, ..., $$$index($$$'z'$$$)=26$$$) .Polycarp wants to get to the $$$n$$$-th tile for the minimum total cost, but at the same time make maximum number of jumps.In other words, among all possible ways to get to the last tile for the minimum total cost, he will choose the one with the maximum number of jumps.Polycarp can visit each tile at most once.Polycarp asks you to help — print the sequence of indices of string $$$s$$$ on which he should jump.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.PriorityQueue; import java.util.StringTokenizer; public class C { private static Scan sc = new Scan(); public static void main(String[] args) { int n = sc.nextInt(); for (int i = 0; i < n; i++) { solve(); } } private static void solve() { char[] a = sc.next().toCharArray(); int s = (int) a[0]; int e = (int) a[a.length - 1]; PriorityQueue<int[]> pq; if (s <= e) { pq = new PriorityQueue<int[]>((x, y) -> x[0] - y[0]); } else { pq = new PriorityQueue<int[]>((x, y) -> y[0] - x[0]); } for (int i = 0; i < a.length - 1; i++) { if ((int) a[i] >= Math.min(s, e) && (int) a[i] <= Math.max(s, e)) { int[] b = new int[2]; b[0] = (int) a[i]; b[1] = i + 1; pq.add(b); } } StringBuilder sb = new StringBuilder(); int count = 1; while (!pq.isEmpty()) { sb.append(pq.poll()[1]); sb.append(" "); count++; } sb.append(a.length); System.out.println(Math.abs(s - e) + " " + count); System.out.println(sb); } private static class Scan { BufferedReader br; StringTokenizer st; public Scan() { 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()); } String nextLine() { String line = ""; try { line = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return line; } int[] readArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } } }
Java
["6\n\nlogic\n\ncodeforces\n\nbca\n\naaaaaaaaaaa\n\nadbaadabad\n\nto"]
1 second
["9 4\n1 4 3 5\n16 10\n1 8 3 4 9 5 2 6 7 10\n1 2\n1 3\n0 11\n1 8 10 4 3 5 7 2 9 6 11\n3 10\n1 9 5 4 7 3 8 6 2 10\n5 2\n1 2"]
NoteIn the first test case, the required path corresponds to the picture: In this case, the minimum possible total cost of the path is achieved. Since $$$index($$$'l'$$$)=12$$$, $$$index($$$'o'$$$)=15$$$, $$$index($$$'g'$$$)=7$$$, $$$index($$$'i'$$$)=9$$$, $$$index($$$'c'$$$)=3$$$, then the total cost of the path is $$$|12-9|+|9-7|+|7-3|=3+2+4=9$$$.
Java 17
standard input
[ "constructive algorithms", "strings" ]
d17c9f91504e1d4c4eae7294bf09dcfc
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. Each test case is given by the string $$$s$$$ ($$$2 \le |s| \le 2 \cdot 10^5$$$), where $$$|s|$$$ — is the length of string $$$s$$$. The string $$$s$$$ consists of lowercase Latin letters. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,100
The answer to each test case consists of two lines. In the first line print two integers $$$cost$$$, $$$m$$$, where $$$cost$$$ is the minimum total cost of the path, and $$$m$$$ is the maximum number of visited tiles Polycarp can make to get to $$$n$$$-th tiles for the minimum total cost $$$cost$$$ (i.e. the number of jumps is $$$m-1$$$). In the next line print $$$m$$$ different numbers $$$j_1, j_2, \dots, j_m$$$ ($$$1 \le j_i \le |s|$$$) — the sequence of indices of the tiles Polycarp will jump on. The first number in the sequence must be $$$1$$$ (that is, $$$j_1=1$$$) and the last number must be the value of $$$|s|$$$ (that is, $$$j_m=|s|$$$). If there are multiple answers, print any of them.
standard output
PASSED
0b244ca297224cc5246caf11880cead2
train_110.jsonl
1662993300
Polycarp was given a row of tiles. Each tile contains one lowercase letter of the Latin alphabet. The entire sequence of tiles forms the string $$$s$$$.In other words, you are given a string $$$s$$$ consisting of lowercase Latin letters.Initially, Polycarp is on the first tile of the row and wants to get to the last tile by jumping on the tiles. Jumping from $$$i$$$-th tile to $$$j$$$-th tile has a cost equal to $$$|index(s_i) - index(s_j)|$$$, where $$$index(c)$$$ is the index of the letter $$$c$$$ in the alphabet (for example, $$$index($$$'a'$$$)=1$$$, $$$index($$$'b'$$$)=2$$$, ..., $$$index($$$'z'$$$)=26$$$) .Polycarp wants to get to the $$$n$$$-th tile for the minimum total cost, but at the same time make maximum number of jumps.In other words, among all possible ways to get to the last tile for the minimum total cost, he will choose the one with the maximum number of jumps.Polycarp can visit each tile at most once.Polycarp asks you to help — print the sequence of indices of string $$$s$$$ on which he should jump.
256 megabytes
import java.io.*; import java.util.*; public class Main{ public static void main(String[] args) { MyScanner sc = new MyScanner(); out = new PrintWriter(new BufferedOutputStream(System.out)); int t = sc.nextInt(); while(t-->0){ String str = sc.nextLine(); int len = str.length(),i,cost = Math.abs(str.charAt(0)-str.charAt(len-1)); HashMap<Character,ArrayList<Integer>> map = new HashMap<>(); for(i=2;i<len;i++){ char curr = str.charAt(i-1); if(map.containsKey(curr)) map.get(curr).add(i); else{ ArrayList<Integer> al = new ArrayList<>(); al.add(i); map.put(curr,al); } } ArrayList<Integer> hops = new ArrayList<>(); if(str.charAt(0)<=str.charAt(len-1)){ char curr = str.charAt(0); while(curr<=str.charAt(len-1)){ if(map.containsKey(curr)) hops.addAll(map.get(curr)); curr++; } }else{ char curr = str.charAt(0); while(curr>=str.charAt(len-1)){ if(map.containsKey(curr)) hops.addAll(map.get(curr)); curr--; } } out.println(cost + " "+(hops.size()+2)); out.print(1+" "); for(int x : hops) out.print(x+" "); out.println(len); // int [] a = new int[n]; // for(i=0;i<n;i++) // a[i]=sc.nextInt(); } out.close(); } 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
["6\n\nlogic\n\ncodeforces\n\nbca\n\naaaaaaaaaaa\n\nadbaadabad\n\nto"]
1 second
["9 4\n1 4 3 5\n16 10\n1 8 3 4 9 5 2 6 7 10\n1 2\n1 3\n0 11\n1 8 10 4 3 5 7 2 9 6 11\n3 10\n1 9 5 4 7 3 8 6 2 10\n5 2\n1 2"]
NoteIn the first test case, the required path corresponds to the picture: In this case, the minimum possible total cost of the path is achieved. Since $$$index($$$'l'$$$)=12$$$, $$$index($$$'o'$$$)=15$$$, $$$index($$$'g'$$$)=7$$$, $$$index($$$'i'$$$)=9$$$, $$$index($$$'c'$$$)=3$$$, then the total cost of the path is $$$|12-9|+|9-7|+|7-3|=3+2+4=9$$$.
Java 17
standard input
[ "constructive algorithms", "strings" ]
d17c9f91504e1d4c4eae7294bf09dcfc
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. Each test case is given by the string $$$s$$$ ($$$2 \le |s| \le 2 \cdot 10^5$$$), where $$$|s|$$$ — is the length of string $$$s$$$. The string $$$s$$$ consists of lowercase Latin letters. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,100
The answer to each test case consists of two lines. In the first line print two integers $$$cost$$$, $$$m$$$, where $$$cost$$$ is the minimum total cost of the path, and $$$m$$$ is the maximum number of visited tiles Polycarp can make to get to $$$n$$$-th tiles for the minimum total cost $$$cost$$$ (i.e. the number of jumps is $$$m-1$$$). In the next line print $$$m$$$ different numbers $$$j_1, j_2, \dots, j_m$$$ ($$$1 \le j_i \le |s|$$$) — the sequence of indices of the tiles Polycarp will jump on. The first number in the sequence must be $$$1$$$ (that is, $$$j_1=1$$$) and the last number must be the value of $$$|s|$$$ (that is, $$$j_m=|s|$$$). If there are multiple answers, print any of them.
standard output
PASSED
372b9f9e6de513b192f18df7daa56cce
train_110.jsonl
1662993300
Polycarp was given a row of tiles. Each tile contains one lowercase letter of the Latin alphabet. The entire sequence of tiles forms the string $$$s$$$.In other words, you are given a string $$$s$$$ consisting of lowercase Latin letters.Initially, Polycarp is on the first tile of the row and wants to get to the last tile by jumping on the tiles. Jumping from $$$i$$$-th tile to $$$j$$$-th tile has a cost equal to $$$|index(s_i) - index(s_j)|$$$, where $$$index(c)$$$ is the index of the letter $$$c$$$ in the alphabet (for example, $$$index($$$'a'$$$)=1$$$, $$$index($$$'b'$$$)=2$$$, ..., $$$index($$$'z'$$$)=26$$$) .Polycarp wants to get to the $$$n$$$-th tile for the minimum total cost, but at the same time make maximum number of jumps.In other words, among all possible ways to get to the last tile for the minimum total cost, he will choose the one with the maximum number of jumps.Polycarp can visit each tile at most once.Polycarp asks you to help — print the sequence of indices of string $$$s$$$ on which he should jump.
256 megabytes
// Input : Pratik import java.io.*; import java.util.*; public class JavaDeveoper { final int mod = 1000000007; 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(long[] a, int i, int j) { long temp = a[i]; a[i] = a[j]; a[j] = temp; } public static void main(String[] args) { try { System.setIn(new FileInputStream("input.txt")); System.setOut (new PrintStream(new FileOutputStream("output.txt"))); } catch (Exception e) { System.err.println("Error"); } // TODO Auto-generated method stub FastReader t = new FastReader(); PrintWriter o = new PrintWriter(System.out); int test = t.nextInt(); while (test-- > 0) { long min = Integer.MIN_VALUE, max = Integer.MAX_VALUE; long ans = 0 ; String s = t.next(); HashMap<Integer, ArrayList<Integer>> map = new HashMap<>(); int q = 26, qq = 0; while (qq < q) { map.put(qq, new ArrayList<Integer>()); qq++; } qq = 1; for (char a : s.toCharArray()) { if (qq == 1) { } else { ArrayList<Integer> b = map.get(a - 'a'); b.add(qq); } qq++; } char[] c = s.toCharArray(); Arrays.sort(c); int n = s.length(); char st = s.charAt(0); char e = s.charAt(n - 1); int i = -1, j = -1, k = 0; if (st <= e) { for (char a : c) { if (a == st && i == -1) { i = k; } if (a == e) { j = k; } k++; } } else { for (char a : c) { if (a == st) { i = k; } if (a == e && j == -1) { j = k; } k++; } } boolean bo = false; if (i > j) { // int p = i; // i = j; // j = p; bo = true; } ArrayList<Integer> r = new ArrayList<Integer>(); r.add(1); if (!bo) { for (k = i + 1; k <= j; k++) { ans += c[k] - c[k - 1]; ArrayList<Integer> rr = map.get(c[k] - 'a'); //o.println("ii "+c[k]); r.add(rr.get(0)); rr.remove(0); } } else { for (k = i - 1; k >= j; k--) { ans += c[k + 1] - c[k]; ArrayList<Integer> rr = map.get(c[k] - 'a'); //o.println("ii "+c[k]); r.add(rr.get(0)); rr.remove(0); } } if (i > j) { int p = i; i = j; j = p; bo = true; } o.println(ans + " " + (j - i + 1)); for (int y : r) { o.print(y + " "); } o.println(); } o.flush(); o.close(); } }
Java
["6\n\nlogic\n\ncodeforces\n\nbca\n\naaaaaaaaaaa\n\nadbaadabad\n\nto"]
1 second
["9 4\n1 4 3 5\n16 10\n1 8 3 4 9 5 2 6 7 10\n1 2\n1 3\n0 11\n1 8 10 4 3 5 7 2 9 6 11\n3 10\n1 9 5 4 7 3 8 6 2 10\n5 2\n1 2"]
NoteIn the first test case, the required path corresponds to the picture: In this case, the minimum possible total cost of the path is achieved. Since $$$index($$$'l'$$$)=12$$$, $$$index($$$'o'$$$)=15$$$, $$$index($$$'g'$$$)=7$$$, $$$index($$$'i'$$$)=9$$$, $$$index($$$'c'$$$)=3$$$, then the total cost of the path is $$$|12-9|+|9-7|+|7-3|=3+2+4=9$$$.
Java 17
standard input
[ "constructive algorithms", "strings" ]
d17c9f91504e1d4c4eae7294bf09dcfc
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. Each test case is given by the string $$$s$$$ ($$$2 \le |s| \le 2 \cdot 10^5$$$), where $$$|s|$$$ — is the length of string $$$s$$$. The string $$$s$$$ consists of lowercase Latin letters. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,100
The answer to each test case consists of two lines. In the first line print two integers $$$cost$$$, $$$m$$$, where $$$cost$$$ is the minimum total cost of the path, and $$$m$$$ is the maximum number of visited tiles Polycarp can make to get to $$$n$$$-th tiles for the minimum total cost $$$cost$$$ (i.e. the number of jumps is $$$m-1$$$). In the next line print $$$m$$$ different numbers $$$j_1, j_2, \dots, j_m$$$ ($$$1 \le j_i \le |s|$$$) — the sequence of indices of the tiles Polycarp will jump on. The first number in the sequence must be $$$1$$$ (that is, $$$j_1=1$$$) and the last number must be the value of $$$|s|$$$ (that is, $$$j_m=|s|$$$). If there are multiple answers, print any of them.
standard output
PASSED
c1cf01a6abac76177d3b6a4a0bb9da64
train_110.jsonl
1662993300
Polycarp was given a row of tiles. Each tile contains one lowercase letter of the Latin alphabet. The entire sequence of tiles forms the string $$$s$$$.In other words, you are given a string $$$s$$$ consisting of lowercase Latin letters.Initially, Polycarp is on the first tile of the row and wants to get to the last tile by jumping on the tiles. Jumping from $$$i$$$-th tile to $$$j$$$-th tile has a cost equal to $$$|index(s_i) - index(s_j)|$$$, where $$$index(c)$$$ is the index of the letter $$$c$$$ in the alphabet (for example, $$$index($$$'a'$$$)=1$$$, $$$index($$$'b'$$$)=2$$$, ..., $$$index($$$'z'$$$)=26$$$) .Polycarp wants to get to the $$$n$$$-th tile for the minimum total cost, but at the same time make maximum number of jumps.In other words, among all possible ways to get to the last tile for the minimum total cost, he will choose the one with the maximum number of jumps.Polycarp can visit each tile at most once.Polycarp asks you to help — print the sequence of indices of string $$$s$$$ on which he should jump.
256 megabytes
import java.util.*; import java.io.*; public class A1{ static BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); static BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(System.out)); static StringTokenizer st; static final long mod=1000000007; public static void Solve() throws IOException{ // st=new StringTokenizer(br.readLine()); // int a=Integer.parseInt(st.nextToken()); char[] ch=getStr(); int n=ch.length,s=ch[0]-'a',e=ch[n-1]-'a'; Map<Integer,List<Integer>> at; if(s>e) at=new TreeMap<>(Collections.reverseOrder()); else at=new TreeMap<>(); for(char c:ch) at.put(c-'a',new ArrayList<>()); for(int i=0;i<n;i++) at.get(ch[i]-'a').add(i+1); int c=0; for(int i:at.keySet()){ if((i>=s && i<=e) || (i<=s && i>=e)) c+=at.get(i).size(); } int max=Math.abs(s-e); bw.write(max+" "+c+"\n"); for(int i:at.keySet()){ if((i>=s && i<=e) || (i<=s && i>=e)){ List<Integer> al=at.get(i); for(int j:al) bw.write(j+" "); } } bw.newLine(); } /** Main Method**/ public static void main(String[] YDSV) throws IOException{ //int t=1; int t=Integer.parseInt(br.readLine()); while(t-->0) Solve(); bw.flush(); } /** Helpers**/ private static char[] getStr()throws IOException{ return br.readLine().toCharArray(); } 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[] getArrIn(int n) throws IOException{ st=new StringTokenizer(br.readLine()); int[] ar=new int[n]; for(int i=0;i<n;i++) ar[i]=Integer.parseInt(st.nextToken()); return ar; } private static Integer[] getArrInP(int n) throws IOException{ st=new StringTokenizer(br.readLine()); Integer[] ar=new Integer[n]; for(int i=0;i<n;i++) ar[i]=Integer.parseInt(st.nextToken()); return ar; } private static long[] getArrLo(int n) throws IOException{ st=new StringTokenizer(br.readLine()); long[] ar=new long[n]; for(int i=0;i<n;i++) ar[i]=Long.parseLong(st.nextToken()); return ar; } private static List<Integer> getListIn(int n) throws IOException{ st=new StringTokenizer(br.readLine()); List<Integer> al=new ArrayList<>(); for(int i=0;i<n;i++) al.add(Integer.parseInt(st.nextToken())); return al; } private static List<Long> getListLo(int n) throws IOException{ st=new StringTokenizer(br.readLine()); List<Long> al=new ArrayList<>(); for(int i=0;i<n;i++) al.add(Long.parseLong(st.nextToken())); return al; } private 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 int lower_bound(int a[],int x){ int l=-1,r=a.length; while(l+1<r){ int m=(l+r)>>>1; if(a[m]>=x) r=m; else l=m; } return r+1; } private static long lower_bound(long a[],long x){ int l=-1,r=a.length; while(l+1<r){ int m=(l+r)>>>1; if(a[m]>=x) r=m; else l=m; } return r+1; } private static int upper_bound(int a[],int x){ int l=-1,r=a.length; while(l+1<r){ int m=(l+r)>>>1; if(a[m]<=x) l=m; else r=m; } return l+1; } private static long upper_bound(long a[],long x){ int l=-1,r=a.length; while(l+1<r){ int m=(l+r)>>>1; if(a[m]<=x) l=m; else r=m; } return l+1; } private static boolean Sqrt(int x){ int a=(int)Math.sqrt(x); return a*a==x; } private static boolean Sqrt(long x){ long a=(long)Math.sqrt(x); return a*a==x; } }
Java
["6\n\nlogic\n\ncodeforces\n\nbca\n\naaaaaaaaaaa\n\nadbaadabad\n\nto"]
1 second
["9 4\n1 4 3 5\n16 10\n1 8 3 4 9 5 2 6 7 10\n1 2\n1 3\n0 11\n1 8 10 4 3 5 7 2 9 6 11\n3 10\n1 9 5 4 7 3 8 6 2 10\n5 2\n1 2"]
NoteIn the first test case, the required path corresponds to the picture: In this case, the minimum possible total cost of the path is achieved. Since $$$index($$$'l'$$$)=12$$$, $$$index($$$'o'$$$)=15$$$, $$$index($$$'g'$$$)=7$$$, $$$index($$$'i'$$$)=9$$$, $$$index($$$'c'$$$)=3$$$, then the total cost of the path is $$$|12-9|+|9-7|+|7-3|=3+2+4=9$$$.
Java 17
standard input
[ "constructive algorithms", "strings" ]
d17c9f91504e1d4c4eae7294bf09dcfc
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. Each test case is given by the string $$$s$$$ ($$$2 \le |s| \le 2 \cdot 10^5$$$), where $$$|s|$$$ — is the length of string $$$s$$$. The string $$$s$$$ consists of lowercase Latin letters. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,100
The answer to each test case consists of two lines. In the first line print two integers $$$cost$$$, $$$m$$$, where $$$cost$$$ is the minimum total cost of the path, and $$$m$$$ is the maximum number of visited tiles Polycarp can make to get to $$$n$$$-th tiles for the minimum total cost $$$cost$$$ (i.e. the number of jumps is $$$m-1$$$). In the next line print $$$m$$$ different numbers $$$j_1, j_2, \dots, j_m$$$ ($$$1 \le j_i \le |s|$$$) — the sequence of indices of the tiles Polycarp will jump on. The first number in the sequence must be $$$1$$$ (that is, $$$j_1=1$$$) and the last number must be the value of $$$|s|$$$ (that is, $$$j_m=|s|$$$). If there are multiple answers, print any of them.
standard output
PASSED
514c25a14a37b8f023422b7e22027fc6
train_110.jsonl
1662993300
Polycarp was given a row of tiles. Each tile contains one lowercase letter of the Latin alphabet. The entire sequence of tiles forms the string $$$s$$$.In other words, you are given a string $$$s$$$ consisting of lowercase Latin letters.Initially, Polycarp is on the first tile of the row and wants to get to the last tile by jumping on the tiles. Jumping from $$$i$$$-th tile to $$$j$$$-th tile has a cost equal to $$$|index(s_i) - index(s_j)|$$$, where $$$index(c)$$$ is the index of the letter $$$c$$$ in the alphabet (for example, $$$index($$$'a'$$$)=1$$$, $$$index($$$'b'$$$)=2$$$, ..., $$$index($$$'z'$$$)=26$$$) .Polycarp wants to get to the $$$n$$$-th tile for the minimum total cost, but at the same time make maximum number of jumps.In other words, among all possible ways to get to the last tile for the minimum total cost, he will choose the one with the maximum number of jumps.Polycarp can visit each tile at most once.Polycarp asks you to help — print the sequence of indices of string $$$s$$$ on which he should jump.
256 megabytes
import java.io.*; import java.util.*; import java.lang.*; public class Question3 { public static void main(String[] args) throws IOException{ FastReader s = new FastReader(); PrintWriter out = new PrintWriter(System.out); int t = s.nextInt(); while(t-->0){ char[] letters = s.next().toCharArray(); int n = letters.length; ArrayList<Integer> idx[] = new ArrayList[26]; for(int i = 0; i < 26; i++){ idx[i] = new ArrayList<>(); } for(int i = 0; i < n; i++){ idx[(letters[i] - 'a')].add(i); } StringBuilder sb = new StringBuilder(); int count = 0; for(int i = letters[0]; i != letters[n - 1];){ for(int num: idx[i - 'a']){ count++; sb.append((num + 1) + " "); } if(i > letters[n-1]){ i--; } else{ i++; } } for(int num: idx[letters[n - 1] - 'a']){ count++; sb.append((num + 1) + " "); } out.println(Math.abs(letters[0] - letters[n - 1]) + " " + count); out.println(sb); } out.flush(); } public static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } public String next() throws IOException { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } String nextLine() throws IOException { String str = ""; if (st.hasMoreTokens()) { str = st.nextToken("\n"); } else { str = br.readLine(); } return str; } } }
Java
["6\n\nlogic\n\ncodeforces\n\nbca\n\naaaaaaaaaaa\n\nadbaadabad\n\nto"]
1 second
["9 4\n1 4 3 5\n16 10\n1 8 3 4 9 5 2 6 7 10\n1 2\n1 3\n0 11\n1 8 10 4 3 5 7 2 9 6 11\n3 10\n1 9 5 4 7 3 8 6 2 10\n5 2\n1 2"]
NoteIn the first test case, the required path corresponds to the picture: In this case, the minimum possible total cost of the path is achieved. Since $$$index($$$'l'$$$)=12$$$, $$$index($$$'o'$$$)=15$$$, $$$index($$$'g'$$$)=7$$$, $$$index($$$'i'$$$)=9$$$, $$$index($$$'c'$$$)=3$$$, then the total cost of the path is $$$|12-9|+|9-7|+|7-3|=3+2+4=9$$$.
Java 17
standard input
[ "constructive algorithms", "strings" ]
d17c9f91504e1d4c4eae7294bf09dcfc
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. Each test case is given by the string $$$s$$$ ($$$2 \le |s| \le 2 \cdot 10^5$$$), where $$$|s|$$$ — is the length of string $$$s$$$. The string $$$s$$$ consists of lowercase Latin letters. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,100
The answer to each test case consists of two lines. In the first line print two integers $$$cost$$$, $$$m$$$, where $$$cost$$$ is the minimum total cost of the path, and $$$m$$$ is the maximum number of visited tiles Polycarp can make to get to $$$n$$$-th tiles for the minimum total cost $$$cost$$$ (i.e. the number of jumps is $$$m-1$$$). In the next line print $$$m$$$ different numbers $$$j_1, j_2, \dots, j_m$$$ ($$$1 \le j_i \le |s|$$$) — the sequence of indices of the tiles Polycarp will jump on. The first number in the sequence must be $$$1$$$ (that is, $$$j_1=1$$$) and the last number must be the value of $$$|s|$$$ (that is, $$$j_m=|s|$$$). If there are multiple answers, print any of them.
standard output
PASSED
a5ed8d4004d45fd457292e0d67fba06c
train_110.jsonl
1662993300
Polycarp was given a row of tiles. Each tile contains one lowercase letter of the Latin alphabet. The entire sequence of tiles forms the string $$$s$$$.In other words, you are given a string $$$s$$$ consisting of lowercase Latin letters.Initially, Polycarp is on the first tile of the row and wants to get to the last tile by jumping on the tiles. Jumping from $$$i$$$-th tile to $$$j$$$-th tile has a cost equal to $$$|index(s_i) - index(s_j)|$$$, where $$$index(c)$$$ is the index of the letter $$$c$$$ in the alphabet (for example, $$$index($$$'a'$$$)=1$$$, $$$index($$$'b'$$$)=2$$$, ..., $$$index($$$'z'$$$)=26$$$) .Polycarp wants to get to the $$$n$$$-th tile for the minimum total cost, but at the same time make maximum number of jumps.In other words, among all possible ways to get to the last tile for the minimum total cost, he will choose the one with the maximum number of jumps.Polycarp can visit each tile at most once.Polycarp asks you to help — print the sequence of indices of string $$$s$$$ on which he should jump.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.StringTokenizer; public final class Code { 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 int[] parent = new int[100000]; static int[] rank = new int[100000]; static void makeset() { for (int i = 1; i < 100000; i++) { parent[i] = i; rank[i] = 0; } } //Uses path compression static int findpar(int node) { if (node == parent[node]) return node; return parent[node] = findpar(parent[node]); } //Uses union by rank static void union(int u, int v) { u = findpar(u); v = findpar(v); if (rank[u] < rank[v]) parent[u] = v; if (rank[u] > rank[v]) parent[v] = u; else { parent[v] = u; rank[u]++; } } static boolean areConnected(int a, int b) { return findpar(a) == findpar(b); } static int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); } static int lcm(int a, int b) { return a * b / gcd(a, b); } static boolean isPrime(int n) { // Check if n=1 or n=0 if (n <= 1) return false; // Check if n=2 or n=3 if (n == 2 || n == 3) return true; // Check whether n is divisible by 2 or 3 if (n % 2 == 0 || n % 3 == 0) return false; // Check from 5 to square root of n // Iterate i by (i+6) for (int i = 5; i <= Math.sqrt(n); i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } public static int hsb(int x) { return (int) (Math.log(x) / Math.log(2)); } public static void main(String[] args) { try { FastReader y = new FastReader(); int t = y.nextInt(); while (t-- > 0) { String s = y.nextLine(); int n = s.length(); Map<Character, ArrayList<Integer>> map = new HashMap<>(); for (int i = 0; i < n; i++) { char ch = s.charAt(i); if (map.containsKey(ch)) map.get(ch).add(i); else { ArrayList<Integer> lst = new ArrayList<>(); lst.add(i); map.put(ch, lst); } } StringBuilder ans = new StringBuilder(); char strt = s.charAt(0), end = s.charAt(n - 1); int cost = Math.abs(strt - end), jumps = 0; if (strt < end) { for (int i = strt; i <= end; i++) { char x = (char) i; if (map.containsKey(x)) for (int j = 0; j < map.get(x).size(); j++) { ans.append(map.get(x).get(j)+1+" "); jumps++; } } } else { for (int i = strt; i >= end; i--) { char x = (char) i; if (map.containsKey(x)) for (int j = 0; j < map.get(x).size(); j++) { ans.append(map.get(x).get(j)+1+" "); jumps++; } } } System.out.println(cost + " " + jumps); System.out.println(ans.toString().trim()); } } catch (Exception e) { e.printStackTrace(); } } }
Java
["6\n\nlogic\n\ncodeforces\n\nbca\n\naaaaaaaaaaa\n\nadbaadabad\n\nto"]
1 second
["9 4\n1 4 3 5\n16 10\n1 8 3 4 9 5 2 6 7 10\n1 2\n1 3\n0 11\n1 8 10 4 3 5 7 2 9 6 11\n3 10\n1 9 5 4 7 3 8 6 2 10\n5 2\n1 2"]
NoteIn the first test case, the required path corresponds to the picture: In this case, the minimum possible total cost of the path is achieved. Since $$$index($$$'l'$$$)=12$$$, $$$index($$$'o'$$$)=15$$$, $$$index($$$'g'$$$)=7$$$, $$$index($$$'i'$$$)=9$$$, $$$index($$$'c'$$$)=3$$$, then the total cost of the path is $$$|12-9|+|9-7|+|7-3|=3+2+4=9$$$.
Java 17
standard input
[ "constructive algorithms", "strings" ]
d17c9f91504e1d4c4eae7294bf09dcfc
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. Each test case is given by the string $$$s$$$ ($$$2 \le |s| \le 2 \cdot 10^5$$$), where $$$|s|$$$ — is the length of string $$$s$$$. The string $$$s$$$ consists of lowercase Latin letters. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,100
The answer to each test case consists of two lines. In the first line print two integers $$$cost$$$, $$$m$$$, where $$$cost$$$ is the minimum total cost of the path, and $$$m$$$ is the maximum number of visited tiles Polycarp can make to get to $$$n$$$-th tiles for the minimum total cost $$$cost$$$ (i.e. the number of jumps is $$$m-1$$$). In the next line print $$$m$$$ different numbers $$$j_1, j_2, \dots, j_m$$$ ($$$1 \le j_i \le |s|$$$) — the sequence of indices of the tiles Polycarp will jump on. The first number in the sequence must be $$$1$$$ (that is, $$$j_1=1$$$) and the last number must be the value of $$$|s|$$$ (that is, $$$j_m=|s|$$$). If there are multiple answers, print any of them.
standard output
PASSED
981a271d92c432bc2ee0dd054371fafd
train_110.jsonl
1662993300
Polycarp was given a row of tiles. Each tile contains one lowercase letter of the Latin alphabet. The entire sequence of tiles forms the string $$$s$$$.In other words, you are given a string $$$s$$$ consisting of lowercase Latin letters.Initially, Polycarp is on the first tile of the row and wants to get to the last tile by jumping on the tiles. Jumping from $$$i$$$-th tile to $$$j$$$-th tile has a cost equal to $$$|index(s_i) - index(s_j)|$$$, where $$$index(c)$$$ is the index of the letter $$$c$$$ in the alphabet (for example, $$$index($$$'a'$$$)=1$$$, $$$index($$$'b'$$$)=2$$$, ..., $$$index($$$'z'$$$)=26$$$) .Polycarp wants to get to the $$$n$$$-th tile for the minimum total cost, but at the same time make maximum number of jumps.In other words, among all possible ways to get to the last tile for the minimum total cost, he will choose the one with the maximum number of jumps.Polycarp can visit each tile at most once.Polycarp asks you to help — print the sequence of indices of string $$$s$$$ on which he should jump.
256 megabytes
/** * * @author AshwinA */ import java.util.*; import java.lang.*; import java.io.*; public class CP_IMP_2{ public static void main (String[] args) throws java.lang.Exception{ Reader in = new Reader(); Writer out = new Writer(); int t = in.nextInt(); while(t-->0){ String st = in.nextLine(); int n = st.length(); Map<Character, ArrayList<Integer>> map = new HashMap<Character, ArrayList<Integer>>(26); for(int i=0;i<n;i++){ if( !map.containsKey(st.charAt(i))) map.put(st.charAt(i), new ArrayList<Integer>()); map.get(st.charAt(i)).add(i+1); } int cnt = 0, cost = 0, prev = st.charAt(0); ArrayList<Integer> jumpIndex = new ArrayList<Integer>(); if(st.charAt(0) > st.charAt(n-1)){ for(int i=(int)st.charAt(0); i>=(int) st.charAt(n-1); i--){ char temp = (char)i; if(map.containsKey(temp)){ cnt += map.get(temp).size(); cost += Math.abs(prev - temp); jumpIndex.addAll(map.get(temp)); prev = i; } } }else{ for(int i=(int)st.charAt(0); i<=(int) st.charAt(n-1); i++){ char temp = (char)i; if(map.containsKey(temp)){ cnt += map.get(temp).size(); cost += Math.abs(prev - temp); jumpIndex.addAll(map.get(temp)); prev = i; } } } out.println(cost+ " "+cnt); for(int i=0;i<jumpIndex.size();i++) out.print(jumpIndex.get(i) + " "); out.println(""); } out.close(); } static class Reader { private final BufferedReader br; private StringTokenizer st; public Reader() { this.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 string = ""; try { string = br.readLine().trim(); } catch (IOException e) { e.printStackTrace(); } return string; } } static class Writer { private final BufferedWriter bw; public Writer() { 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 { this.print(object); bw.append("\n"); } public void close() throws IOException { bw.close(); } } }
Java
["6\n\nlogic\n\ncodeforces\n\nbca\n\naaaaaaaaaaa\n\nadbaadabad\n\nto"]
1 second
["9 4\n1 4 3 5\n16 10\n1 8 3 4 9 5 2 6 7 10\n1 2\n1 3\n0 11\n1 8 10 4 3 5 7 2 9 6 11\n3 10\n1 9 5 4 7 3 8 6 2 10\n5 2\n1 2"]
NoteIn the first test case, the required path corresponds to the picture: In this case, the minimum possible total cost of the path is achieved. Since $$$index($$$'l'$$$)=12$$$, $$$index($$$'o'$$$)=15$$$, $$$index($$$'g'$$$)=7$$$, $$$index($$$'i'$$$)=9$$$, $$$index($$$'c'$$$)=3$$$, then the total cost of the path is $$$|12-9|+|9-7|+|7-3|=3+2+4=9$$$.
Java 17
standard input
[ "constructive algorithms", "strings" ]
d17c9f91504e1d4c4eae7294bf09dcfc
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. Each test case is given by the string $$$s$$$ ($$$2 \le |s| \le 2 \cdot 10^5$$$), where $$$|s|$$$ — is the length of string $$$s$$$. The string $$$s$$$ consists of lowercase Latin letters. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,100
The answer to each test case consists of two lines. In the first line print two integers $$$cost$$$, $$$m$$$, where $$$cost$$$ is the minimum total cost of the path, and $$$m$$$ is the maximum number of visited tiles Polycarp can make to get to $$$n$$$-th tiles for the minimum total cost $$$cost$$$ (i.e. the number of jumps is $$$m-1$$$). In the next line print $$$m$$$ different numbers $$$j_1, j_2, \dots, j_m$$$ ($$$1 \le j_i \le |s|$$$) — the sequence of indices of the tiles Polycarp will jump on. The first number in the sequence must be $$$1$$$ (that is, $$$j_1=1$$$) and the last number must be the value of $$$|s|$$$ (that is, $$$j_m=|s|$$$). If there are multiple answers, print any of them.
standard output
PASSED
3b8c316ef1d18db08b950ce3db92131e
train_110.jsonl
1662993300
Polycarp was given a row of tiles. Each tile contains one lowercase letter of the Latin alphabet. The entire sequence of tiles forms the string $$$s$$$.In other words, you are given a string $$$s$$$ consisting of lowercase Latin letters.Initially, Polycarp is on the first tile of the row and wants to get to the last tile by jumping on the tiles. Jumping from $$$i$$$-th tile to $$$j$$$-th tile has a cost equal to $$$|index(s_i) - index(s_j)|$$$, where $$$index(c)$$$ is the index of the letter $$$c$$$ in the alphabet (for example, $$$index($$$'a'$$$)=1$$$, $$$index($$$'b'$$$)=2$$$, ..., $$$index($$$'z'$$$)=26$$$) .Polycarp wants to get to the $$$n$$$-th tile for the minimum total cost, but at the same time make maximum number of jumps.In other words, among all possible ways to get to the last tile for the minimum total cost, he will choose the one with the maximum number of jumps.Polycarp can visit each tile at most once.Polycarp asks you to help — print the sequence of indices of string $$$s$$$ on which he should jump.
256 megabytes
import static java.lang.System.out; import static java.lang.Math.abs; import static java.lang.Math.min; import static java.lang.Math.max; import static java.lang.Math.log; import java.util.*; import java.lang.*; import java.io.*; public class a_Codeforces { public static void main(String[] args) throws java.lang.Exception { FastReader sc = new FastReader(); FastWriter out = new FastWriter(); int t = sc.nextInt(); while (t-- > 0) { String s = sc.next(); int st = s.charAt(0) - 'a' + 1; int o2 = 0, o1; int en = s.charAt(s.length() - 1) - 'a' + 1; if (st < en) o1 = en - st; else o1 = st - en; out.print(o1 + " "); for (int i = 1; i < s.length() - 1; i++) { int chi = s.charAt(i) - 'a' + 1; if (chi <= max(st, en) && chi >= min(st, en)) o2++; } out.println(o2 + 2); if (st < en) { out.print("1 "); for (int i = st; i <= en; i++) { for (int j = 1; j < s.length() - 1; j++) { int cmp = s.charAt(j) - 'a' + 1; if (i == cmp) out.print((j + 1) + " "); } } out.println(s.length() + " "); } else { out.print("1 "); for (int i = st; i >= en; i--) { for (int j = 1; j < s.length() - 1; j++) { int cmp = s.charAt(j) - 'a' + 1; if (i == cmp) out.print((j + 1) + " "); } } out.println(s.length() + " "); } } out.close(); } static void no() { out.println("NO"); } static void yes() { out.println("YES"); } static void print(int arr[]) { for (int i = 0; i < arr.length; i++) { out.print(arr[i] + " "); } out.println(""); } static int[] input(int n) { FastReader sc = new FastReader(); int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = sc.nextInt(); } return arr; } static int[] swap(int arr[], int a, int b) { int temp = arr[b]; arr[b] = arr[a]; arr[a] = temp; return arr; } /* * int[] arr = new int[n]; * for (int i=0; i<n; i++){ * arr[i] = sc.nextInt(); * } */ 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(); } } }
Java
["6\n\nlogic\n\ncodeforces\n\nbca\n\naaaaaaaaaaa\n\nadbaadabad\n\nto"]
1 second
["9 4\n1 4 3 5\n16 10\n1 8 3 4 9 5 2 6 7 10\n1 2\n1 3\n0 11\n1 8 10 4 3 5 7 2 9 6 11\n3 10\n1 9 5 4 7 3 8 6 2 10\n5 2\n1 2"]
NoteIn the first test case, the required path corresponds to the picture: In this case, the minimum possible total cost of the path is achieved. Since $$$index($$$'l'$$$)=12$$$, $$$index($$$'o'$$$)=15$$$, $$$index($$$'g'$$$)=7$$$, $$$index($$$'i'$$$)=9$$$, $$$index($$$'c'$$$)=3$$$, then the total cost of the path is $$$|12-9|+|9-7|+|7-3|=3+2+4=9$$$.
Java 17
standard input
[ "constructive algorithms", "strings" ]
d17c9f91504e1d4c4eae7294bf09dcfc
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. Each test case is given by the string $$$s$$$ ($$$2 \le |s| \le 2 \cdot 10^5$$$), where $$$|s|$$$ — is the length of string $$$s$$$. The string $$$s$$$ consists of lowercase Latin letters. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,100
The answer to each test case consists of two lines. In the first line print two integers $$$cost$$$, $$$m$$$, where $$$cost$$$ is the minimum total cost of the path, and $$$m$$$ is the maximum number of visited tiles Polycarp can make to get to $$$n$$$-th tiles for the minimum total cost $$$cost$$$ (i.e. the number of jumps is $$$m-1$$$). In the next line print $$$m$$$ different numbers $$$j_1, j_2, \dots, j_m$$$ ($$$1 \le j_i \le |s|$$$) — the sequence of indices of the tiles Polycarp will jump on. The first number in the sequence must be $$$1$$$ (that is, $$$j_1=1$$$) and the last number must be the value of $$$|s|$$$ (that is, $$$j_m=|s|$$$). If there are multiple answers, print any of them.
standard output
PASSED
79737ee0cb809f818e643b7563be2f77
train_110.jsonl
1662993300
Polycarp was given a row of tiles. Each tile contains one lowercase letter of the Latin alphabet. The entire sequence of tiles forms the string $$$s$$$.In other words, you are given a string $$$s$$$ consisting of lowercase Latin letters.Initially, Polycarp is on the first tile of the row and wants to get to the last tile by jumping on the tiles. Jumping from $$$i$$$-th tile to $$$j$$$-th tile has a cost equal to $$$|index(s_i) - index(s_j)|$$$, where $$$index(c)$$$ is the index of the letter $$$c$$$ in the alphabet (for example, $$$index($$$'a'$$$)=1$$$, $$$index($$$'b'$$$)=2$$$, ..., $$$index($$$'z'$$$)=26$$$) .Polycarp wants to get to the $$$n$$$-th tile for the minimum total cost, but at the same time make maximum number of jumps.In other words, among all possible ways to get to the last tile for the minimum total cost, he will choose the one with the maximum number of jumps.Polycarp can visit each tile at most once.Polycarp asks you to help — print the sequence of indices of string $$$s$$$ on which he should jump.
256 megabytes
import static java.lang.System.*; import java.util.*; public class C_Jumping_on_Tiles { static Scanner sc = new Scanner(System.in); public static void main(String args[]) { int t = sc.nextInt(); while (t-- != 0) { String str = sc.next(); int n = str.length(); ArrayList<ArrayList<Integer>> arr = new ArrayList<>(26); for (int i = 0; i < 26; i++) arr.add(new ArrayList<Integer>()); for (int i = 0; i < n; i++) { arr.get(str.charAt(i) - 'a').add(i); } if (str.charAt(0) > str.charAt(n - 1)) { System.out.print(str.charAt(0) - str.charAt(n - 1) + " "); int move = 0, start = str.charAt(0) - 'a', end = str.charAt(n - 1) - 'a'; for (int i = start; i >= end; i--) move += arr.get(i).size(); System.out.println(move); for (int i = start; i >= end; i--) { for (int j = 0; j < arr.get(i).size(); j++) { System.out.print(arr.get(i).get(j) + 1 + " "); } } } else { System.out.println(str.charAt(n - 1) - str.charAt(0) + " "); int move = 0, start = str.charAt(0) - 'a', end = str.charAt(n - 1) - 'a'; for (int i = start; i <= end; i++) move += arr.get(i).size(); System.out.println(move); for (int i = start; i <= end; i++) { for (int j = 0; j < arr.get(i).size(); j++) { System.out.print(arr.get(i).get(j) + 1 + " "); } } } System.out.println(); } } }
Java
["6\n\nlogic\n\ncodeforces\n\nbca\n\naaaaaaaaaaa\n\nadbaadabad\n\nto"]
1 second
["9 4\n1 4 3 5\n16 10\n1 8 3 4 9 5 2 6 7 10\n1 2\n1 3\n0 11\n1 8 10 4 3 5 7 2 9 6 11\n3 10\n1 9 5 4 7 3 8 6 2 10\n5 2\n1 2"]
NoteIn the first test case, the required path corresponds to the picture: In this case, the minimum possible total cost of the path is achieved. Since $$$index($$$'l'$$$)=12$$$, $$$index($$$'o'$$$)=15$$$, $$$index($$$'g'$$$)=7$$$, $$$index($$$'i'$$$)=9$$$, $$$index($$$'c'$$$)=3$$$, then the total cost of the path is $$$|12-9|+|9-7|+|7-3|=3+2+4=9$$$.
Java 17
standard input
[ "constructive algorithms", "strings" ]
d17c9f91504e1d4c4eae7294bf09dcfc
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. Each test case is given by the string $$$s$$$ ($$$2 \le |s| \le 2 \cdot 10^5$$$), where $$$|s|$$$ — is the length of string $$$s$$$. The string $$$s$$$ consists of lowercase Latin letters. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,100
The answer to each test case consists of two lines. In the first line print two integers $$$cost$$$, $$$m$$$, where $$$cost$$$ is the minimum total cost of the path, and $$$m$$$ is the maximum number of visited tiles Polycarp can make to get to $$$n$$$-th tiles for the minimum total cost $$$cost$$$ (i.e. the number of jumps is $$$m-1$$$). In the next line print $$$m$$$ different numbers $$$j_1, j_2, \dots, j_m$$$ ($$$1 \le j_i \le |s|$$$) — the sequence of indices of the tiles Polycarp will jump on. The first number in the sequence must be $$$1$$$ (that is, $$$j_1=1$$$) and the last number must be the value of $$$|s|$$$ (that is, $$$j_m=|s|$$$). If there are multiple answers, print any of them.
standard output
PASSED
d0024186471c8604f4d2d44d4e4dcc07
train_110.jsonl
1662993300
Polycarp was given a row of tiles. Each tile contains one lowercase letter of the Latin alphabet. The entire sequence of tiles forms the string $$$s$$$.In other words, you are given a string $$$s$$$ consisting of lowercase Latin letters.Initially, Polycarp is on the first tile of the row and wants to get to the last tile by jumping on the tiles. Jumping from $$$i$$$-th tile to $$$j$$$-th tile has a cost equal to $$$|index(s_i) - index(s_j)|$$$, where $$$index(c)$$$ is the index of the letter $$$c$$$ in the alphabet (for example, $$$index($$$'a'$$$)=1$$$, $$$index($$$'b'$$$)=2$$$, ..., $$$index($$$'z'$$$)=26$$$) .Polycarp wants to get to the $$$n$$$-th tile for the minimum total cost, but at the same time make maximum number of jumps.In other words, among all possible ways to get to the last tile for the minimum total cost, he will choose the one with the maximum number of jumps.Polycarp can visit each tile at most once.Polycarp asks you to help — print the sequence of indices of string $$$s$$$ on which he should jump.
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.HashSet; import java.util.List; import java.util.Set; import java.util.StringTokenizer; public class Solution { public static class CFScanner { BufferedReader br; StringTokenizer st; public CFScanner() { 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) { // int n = in.nextInt(); // long n = in.nextLong(); // double n = in.nextDouble(); // String s = in.next(); CFScanner in = new CFScanner(); PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); int T = in.nextInt(); for (int t = 1; t <= T; t++) { String s = in.next(); getIndexes(s, out); // out.println(); } out.close(); } private static void getIndexes(String s, PrintWriter out) { char first = s.charAt(0); char second = s.charAt(s.length() - 1); List<Node> nodes = new ArrayList<>(); for (int i = 0; i < s.length(); i++) { char ch = s.charAt(i); if ((ch >= first && ch <= second) || (ch <= first && ch >= second)) { nodes.add(new Node(ch, i + 1)); } } Collections.sort(nodes, (a, b) -> (a.ch - b.ch)); out.println(Math.abs(first - second) + " " + nodes.size()); StringBuilder strBd = new StringBuilder(); strBd.append(1).append(" "); if (first < second) { for (Node node : nodes) { if (node.pos == 1 || node.pos == s.length()) { continue; } strBd.append(node.pos).append(" "); } } else { for (int i = nodes.size() - 1; i >= 0; i--) { Node node = nodes.get(i); if (node.pos == 1 || node.pos == s.length()) { continue; } strBd.append(node.pos).append(" "); } } strBd.append(s.length()); out.println(strBd); } private static String getStr(String s) { StringBuilder strBd = new StringBuilder(); Set<Integer> zeros = new HashSet<>(); for (int i = 0; i < s.length(); i++) { if (s.charAt(i) == '0') { if (i + 1 < s.length() && s.charAt(i + 1) == '0') { continue; } zeros.add(i); } } for (int i = 0; i < s.length(); i++) { if (zeros.contains(i)) { continue; } else if (zeros.contains(i + 2)) { String sub = s.charAt(i) + "" + s.charAt(i + 1); int val = Integer.valueOf(sub); strBd.append((char)('a' + --val)); i += 2; } else { String sub = s.charAt(i) + ""; int val = Integer.valueOf(sub); strBd.append((char)('a' + --val)); } } return strBd.toString(); } private static int getEle(int a, int b, int c) { int first = Math.abs(a - 1); int second = Math.abs(c - 1) + Math.abs(c - b); if (first == second) { return 3; } return first < second ? 1 : 2; } } class Node { char ch; int pos; public Node(char ch, int pos) { this.ch = ch; this.pos = pos; } }
Java
["6\n\nlogic\n\ncodeforces\n\nbca\n\naaaaaaaaaaa\n\nadbaadabad\n\nto"]
1 second
["9 4\n1 4 3 5\n16 10\n1 8 3 4 9 5 2 6 7 10\n1 2\n1 3\n0 11\n1 8 10 4 3 5 7 2 9 6 11\n3 10\n1 9 5 4 7 3 8 6 2 10\n5 2\n1 2"]
NoteIn the first test case, the required path corresponds to the picture: In this case, the minimum possible total cost of the path is achieved. Since $$$index($$$'l'$$$)=12$$$, $$$index($$$'o'$$$)=15$$$, $$$index($$$'g'$$$)=7$$$, $$$index($$$'i'$$$)=9$$$, $$$index($$$'c'$$$)=3$$$, then the total cost of the path is $$$|12-9|+|9-7|+|7-3|=3+2+4=9$$$.
Java 17
standard input
[ "constructive algorithms", "strings" ]
d17c9f91504e1d4c4eae7294bf09dcfc
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. Each test case is given by the string $$$s$$$ ($$$2 \le |s| \le 2 \cdot 10^5$$$), where $$$|s|$$$ — is the length of string $$$s$$$. The string $$$s$$$ consists of lowercase Latin letters. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,100
The answer to each test case consists of two lines. In the first line print two integers $$$cost$$$, $$$m$$$, where $$$cost$$$ is the minimum total cost of the path, and $$$m$$$ is the maximum number of visited tiles Polycarp can make to get to $$$n$$$-th tiles for the minimum total cost $$$cost$$$ (i.e. the number of jumps is $$$m-1$$$). In the next line print $$$m$$$ different numbers $$$j_1, j_2, \dots, j_m$$$ ($$$1 \le j_i \le |s|$$$) — the sequence of indices of the tiles Polycarp will jump on. The first number in the sequence must be $$$1$$$ (that is, $$$j_1=1$$$) and the last number must be the value of $$$|s|$$$ (that is, $$$j_m=|s|$$$). If there are multiple answers, print any of them.
standard output
PASSED
4653bddf1eeeeb51035837135709b393
train_110.jsonl
1662993300
Polycarp was given a row of tiles. Each tile contains one lowercase letter of the Latin alphabet. The entire sequence of tiles forms the string $$$s$$$.In other words, you are given a string $$$s$$$ consisting of lowercase Latin letters.Initially, Polycarp is on the first tile of the row and wants to get to the last tile by jumping on the tiles. Jumping from $$$i$$$-th tile to $$$j$$$-th tile has a cost equal to $$$|index(s_i) - index(s_j)|$$$, where $$$index(c)$$$ is the index of the letter $$$c$$$ in the alphabet (for example, $$$index($$$'a'$$$)=1$$$, $$$index($$$'b'$$$)=2$$$, ..., $$$index($$$'z'$$$)=26$$$) .Polycarp wants to get to the $$$n$$$-th tile for the minimum total cost, but at the same time make maximum number of jumps.In other words, among all possible ways to get to the last tile for the minimum total cost, he will choose the one with the maximum number of jumps.Polycarp can visit each tile at most once.Polycarp asks you to help — print the sequence of indices of string $$$s$$$ on which he should jump.
256 megabytes
import java.util.*; public class JumpingTiles { public static void main(String[] args) { Scanner pratiksc = new Scanner(System.in); int t = pratiksc.nextInt(); while (t-- > 0) { String str = pratiksc.next(); List<Pair> arr = new ArrayList<>(); for (int i = 0; i < str.length(); i++) arr.add(new Pair(str.charAt(i) - 'a' + 1, i + 1)); int st = arr.get(0).val; int end = arr.get(arr.size() - 1).val; int cost = Math.abs(end - st); Collections.sort(arr, (a, b) -> a.val - b.val); List<Integer> ans = new ArrayList<>(); if (end < st) { Collections.reverse(arr); for (int i = 0; i < arr.size(); i++) { if (arr.get(i).val <= st && arr.get(i).val >= end) ans.add(arr.get(i).ind); } } else { for (int i = 0; i < arr.size(); i++) { if (arr.get(i).val <= end && arr.get(i).val >= st) ans.add(arr.get(i).ind); } } System.out.println(cost + " " + ans.size()); System.out.print(1 + " "); for (int i = 0; i < ans.size(); i++) { if (ans.get(i) == 1 || ans.get(i) == str.length()) continue; System.out.print(ans.get(i) + " "); } System.out.print(str.length()); System.out.println(); } pratiksc.close(); } } class Pair { int val, ind; Pair(int val, int ind) { this.val = val; this.ind = ind; } }
Java
["6\n\nlogic\n\ncodeforces\n\nbca\n\naaaaaaaaaaa\n\nadbaadabad\n\nto"]
1 second
["9 4\n1 4 3 5\n16 10\n1 8 3 4 9 5 2 6 7 10\n1 2\n1 3\n0 11\n1 8 10 4 3 5 7 2 9 6 11\n3 10\n1 9 5 4 7 3 8 6 2 10\n5 2\n1 2"]
NoteIn the first test case, the required path corresponds to the picture: In this case, the minimum possible total cost of the path is achieved. Since $$$index($$$'l'$$$)=12$$$, $$$index($$$'o'$$$)=15$$$, $$$index($$$'g'$$$)=7$$$, $$$index($$$'i'$$$)=9$$$, $$$index($$$'c'$$$)=3$$$, then the total cost of the path is $$$|12-9|+|9-7|+|7-3|=3+2+4=9$$$.
Java 17
standard input
[ "constructive algorithms", "strings" ]
d17c9f91504e1d4c4eae7294bf09dcfc
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. Each test case is given by the string $$$s$$$ ($$$2 \le |s| \le 2 \cdot 10^5$$$), where $$$|s|$$$ — is the length of string $$$s$$$. The string $$$s$$$ consists of lowercase Latin letters. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,100
The answer to each test case consists of two lines. In the first line print two integers $$$cost$$$, $$$m$$$, where $$$cost$$$ is the minimum total cost of the path, and $$$m$$$ is the maximum number of visited tiles Polycarp can make to get to $$$n$$$-th tiles for the minimum total cost $$$cost$$$ (i.e. the number of jumps is $$$m-1$$$). In the next line print $$$m$$$ different numbers $$$j_1, j_2, \dots, j_m$$$ ($$$1 \le j_i \le |s|$$$) — the sequence of indices of the tiles Polycarp will jump on. The first number in the sequence must be $$$1$$$ (that is, $$$j_1=1$$$) and the last number must be the value of $$$|s|$$$ (that is, $$$j_m=|s|$$$). If there are multiple answers, print any of them.
standard output
PASSED
50107e3ae9b129d6ab256469340f1fba
train_110.jsonl
1662993300
Polycarp was given a row of tiles. Each tile contains one lowercase letter of the Latin alphabet. The entire sequence of tiles forms the string $$$s$$$.In other words, you are given a string $$$s$$$ consisting of lowercase Latin letters.Initially, Polycarp is on the first tile of the row and wants to get to the last tile by jumping on the tiles. Jumping from $$$i$$$-th tile to $$$j$$$-th tile has a cost equal to $$$|index(s_i) - index(s_j)|$$$, where $$$index(c)$$$ is the index of the letter $$$c$$$ in the alphabet (for example, $$$index($$$'a'$$$)=1$$$, $$$index($$$'b'$$$)=2$$$, ..., $$$index($$$'z'$$$)=26$$$) .Polycarp wants to get to the $$$n$$$-th tile for the minimum total cost, but at the same time make maximum number of jumps.In other words, among all possible ways to get to the last tile for the minimum total cost, he will choose the one with the maximum number of jumps.Polycarp can visit each tile at most once.Polycarp asks you to help — print the sequence of indices of string $$$s$$$ on which he should jump.
256 megabytes
import java.util.*; import java.io.*; public class Main{ 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; } } static class Pair{ public char c; public int index ; Pair(char s, int i){ this.index = i ; this.c = s; } } public static void main(String[] args) { sc = new FastReader(); out = new PrintWriter(new BufferedOutputStream(System.out)); int t = sc.nextInt(); for(int T = 0 ; T<t ; T++){ String str = sc.next(); int l = str.charAt(0) - 'a' + 1; int r = str.charAt(str.length()-1) - 'a' + 1; if(l>=r){ function1(str,l,r); } else{ function2(str, l, r); } } out.close(); } private static void function1(String str, int l, int r){ ArrayList<Pair> list = new ArrayList<>(); int jumps = 2; for(int j = 1; j<str.length()-1; j++){ int k = (int)(str.charAt(j)-'a')+1; if(k<=l && k>=r){ Pair p = new Pair(str.charAt(j),j+1); list.add(p); jumps++; } } Collections.sort(list, new Comparator<Pair>() { @Override public int compare(Pair o1, Pair o2) { return (int)o2.c - (int)o1.c; } }); long cost = (int)str.charAt(0) - (int)str.charAt(str.length()-1); out.println(cost +" "+jumps); out.print(1+" "); for(int j = 0; j<list.size() ; j++){ out.print(list.get(j).index+" "); } out.println(str.length()); } private static void function2(String str ,int l, int r){ ArrayList<Pair> list = new ArrayList<>(); int jumps = 2; for(int j = 1; j<str.length()-1; j++){ int k = (int)(str.charAt(j)-'a')+1; if(k>=l && k<=r){ Pair p = new Pair(str.charAt(j),j+1); list.add(p); jumps++; } } Collections.sort(list, new Comparator<Pair>() { @Override public int compare(Pair o1, Pair o2) { return (int)o1.c - (int)o2.c; } }); long cost = -(int)str.charAt(0) + (int)str.charAt(str.length()-1); out.println(cost +" "+jumps); out.print(1+" "); for(int j = 0; j<list.size() ; j++){ out.print(list.get(j).index+" "); } out.println(str.length()); } }
Java
["6\n\nlogic\n\ncodeforces\n\nbca\n\naaaaaaaaaaa\n\nadbaadabad\n\nto"]
1 second
["9 4\n1 4 3 5\n16 10\n1 8 3 4 9 5 2 6 7 10\n1 2\n1 3\n0 11\n1 8 10 4 3 5 7 2 9 6 11\n3 10\n1 9 5 4 7 3 8 6 2 10\n5 2\n1 2"]
NoteIn the first test case, the required path corresponds to the picture: In this case, the minimum possible total cost of the path is achieved. Since $$$index($$$'l'$$$)=12$$$, $$$index($$$'o'$$$)=15$$$, $$$index($$$'g'$$$)=7$$$, $$$index($$$'i'$$$)=9$$$, $$$index($$$'c'$$$)=3$$$, then the total cost of the path is $$$|12-9|+|9-7|+|7-3|=3+2+4=9$$$.
Java 17
standard input
[ "constructive algorithms", "strings" ]
d17c9f91504e1d4c4eae7294bf09dcfc
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. Each test case is given by the string $$$s$$$ ($$$2 \le |s| \le 2 \cdot 10^5$$$), where $$$|s|$$$ — is the length of string $$$s$$$. The string $$$s$$$ consists of lowercase Latin letters. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,100
The answer to each test case consists of two lines. In the first line print two integers $$$cost$$$, $$$m$$$, where $$$cost$$$ is the minimum total cost of the path, and $$$m$$$ is the maximum number of visited tiles Polycarp can make to get to $$$n$$$-th tiles for the minimum total cost $$$cost$$$ (i.e. the number of jumps is $$$m-1$$$). In the next line print $$$m$$$ different numbers $$$j_1, j_2, \dots, j_m$$$ ($$$1 \le j_i \le |s|$$$) — the sequence of indices of the tiles Polycarp will jump on. The first number in the sequence must be $$$1$$$ (that is, $$$j_1=1$$$) and the last number must be the value of $$$|s|$$$ (that is, $$$j_m=|s|$$$). If there are multiple answers, print any of them.
standard output
PASSED
53e8b71220319288ec37b4c174e02d96
train_110.jsonl
1662993300
Polycarp was given a row of tiles. Each tile contains one lowercase letter of the Latin alphabet. The entire sequence of tiles forms the string $$$s$$$.In other words, you are given a string $$$s$$$ consisting of lowercase Latin letters.Initially, Polycarp is on the first tile of the row and wants to get to the last tile by jumping on the tiles. Jumping from $$$i$$$-th tile to $$$j$$$-th tile has a cost equal to $$$|index(s_i) - index(s_j)|$$$, where $$$index(c)$$$ is the index of the letter $$$c$$$ in the alphabet (for example, $$$index($$$'a'$$$)=1$$$, $$$index($$$'b'$$$)=2$$$, ..., $$$index($$$'z'$$$)=26$$$) .Polycarp wants to get to the $$$n$$$-th tile for the minimum total cost, but at the same time make maximum number of jumps.In other words, among all possible ways to get to the last tile for the minimum total cost, he will choose the one with the maximum number of jumps.Polycarp can visit each tile at most once.Polycarp asks you to help — print the sequence of indices of string $$$s$$$ on which he should jump.
256 megabytes
import java.util.*; import java.io.*; public class Main{ private static FastReader sc; private static PrintWriter out; public static void main(String[] args) { sc = new FastReader(); out = new PrintWriter(new BufferedOutputStream(System.out)); int t = sc.nextInt(); for(int T = 0 ; T<t ; T++){ String str = sc.next(); int l = str.charAt(0) - 'a' + 1; int r = str.charAt(str.length()-1) - 'a' + 1; if(l>=r){ ArrayList<Pair> list = new ArrayList<>(); int jumps = 2; for(int j = 1; j<str.length()-1; j++){ int k = (int)(str.charAt(j)-'a')+1; if(k<=l && k>=r){ Pair p = new Pair(str.charAt(j),j+1); list.add(p); jumps++; } } Collections.sort(list, new Comparator<Pair>() { @Override public int compare(Pair o1, Pair o2) { return (int)o2.c - (int)o1.c; } }); long cost = (int)str.charAt(0) - (int)str.charAt(str.length()-1); out.println(cost +" "+jumps); out.print(1+" "); for(int j = 0; j<list.size() ; j++){ out.print(list.get(j).index+" "); } out.println(str.length()); } else{ ArrayList<Pair> list = new ArrayList<>(); int jumps = 2; for(int j = 1; j<str.length()-1; j++){ int k = (int)(str.charAt(j)-'a')+1; if(k>=l && k<=r){ Pair p = new Pair(str.charAt(j),j+1); list.add(p); jumps++; } } Collections.sort(list, new Comparator<Pair>() { @Override public int compare(Pair o1, Pair o2) { return (int)o1.c - (int)o2.c; } }); long cost = -(int)str.charAt(0) + (int)str.charAt(str.length()-1); out.println(cost +" "+jumps); out.print(1+" "); for(int j = 0; j<list.size() ; j++){ out.print(list.get(j).index+" "); } out.println(str.length()); } } out.close(); } } class Pair{ char c; int index ; Pair(char s, int i){ this.index = i ; this.c = s; } } 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 Error){ Error.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 Error){ Error.printStackTrace(); } return str; } }
Java
["6\n\nlogic\n\ncodeforces\n\nbca\n\naaaaaaaaaaa\n\nadbaadabad\n\nto"]
1 second
["9 4\n1 4 3 5\n16 10\n1 8 3 4 9 5 2 6 7 10\n1 2\n1 3\n0 11\n1 8 10 4 3 5 7 2 9 6 11\n3 10\n1 9 5 4 7 3 8 6 2 10\n5 2\n1 2"]
NoteIn the first test case, the required path corresponds to the picture: In this case, the minimum possible total cost of the path is achieved. Since $$$index($$$'l'$$$)=12$$$, $$$index($$$'o'$$$)=15$$$, $$$index($$$'g'$$$)=7$$$, $$$index($$$'i'$$$)=9$$$, $$$index($$$'c'$$$)=3$$$, then the total cost of the path is $$$|12-9|+|9-7|+|7-3|=3+2+4=9$$$.
Java 17
standard input
[ "constructive algorithms", "strings" ]
d17c9f91504e1d4c4eae7294bf09dcfc
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. Each test case is given by the string $$$s$$$ ($$$2 \le |s| \le 2 \cdot 10^5$$$), where $$$|s|$$$ — is the length of string $$$s$$$. The string $$$s$$$ consists of lowercase Latin letters. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,100
The answer to each test case consists of two lines. In the first line print two integers $$$cost$$$, $$$m$$$, where $$$cost$$$ is the minimum total cost of the path, and $$$m$$$ is the maximum number of visited tiles Polycarp can make to get to $$$n$$$-th tiles for the minimum total cost $$$cost$$$ (i.e. the number of jumps is $$$m-1$$$). In the next line print $$$m$$$ different numbers $$$j_1, j_2, \dots, j_m$$$ ($$$1 \le j_i \le |s|$$$) — the sequence of indices of the tiles Polycarp will jump on. The first number in the sequence must be $$$1$$$ (that is, $$$j_1=1$$$) and the last number must be the value of $$$|s|$$$ (that is, $$$j_m=|s|$$$). If there are multiple answers, print any of them.
standard output
PASSED
e8710040e75222ddf1e05caff62c9d1c
train_110.jsonl
1662993300
Polycarp was given a row of tiles. Each tile contains one lowercase letter of the Latin alphabet. The entire sequence of tiles forms the string $$$s$$$.In other words, you are given a string $$$s$$$ consisting of lowercase Latin letters.Initially, Polycarp is on the first tile of the row and wants to get to the last tile by jumping on the tiles. Jumping from $$$i$$$-th tile to $$$j$$$-th tile has a cost equal to $$$|index(s_i) - index(s_j)|$$$, where $$$index(c)$$$ is the index of the letter $$$c$$$ in the alphabet (for example, $$$index($$$'a'$$$)=1$$$, $$$index($$$'b'$$$)=2$$$, ..., $$$index($$$'z'$$$)=26$$$) .Polycarp wants to get to the $$$n$$$-th tile for the minimum total cost, but at the same time make maximum number of jumps.In other words, among all possible ways to get to the last tile for the minimum total cost, he will choose the one with the maximum number of jumps.Polycarp can visit each tile at most once.Polycarp asks you to help — print the sequence of indices of string $$$s$$$ on which he should jump.
256 megabytes
import java.util.*; import java.io.*; import java.math.*; public class Codechef { static class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din;private byte[] buffer;private int bufferPointer, bytesRead;public Reader() {din = new DataInputStream(System.in);buffer = new byte[BUFFER_SIZE];bufferPointer = bytesRead = 0;}BufferedReader in;StringTokenizer st; 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 int nextInt() throws IOException {int ret = 0;byte c = read();while (c <= ' ') c = read();boolean neg = (c == '-'); if (neg) c = read();do {ret = ret * 10 + c - '0';} while ((c = read()) >= '0' && c <= '9');if (neg) return -ret;return ret;} public long nextLong() throws IOException {int ret = 0;byte c = read();while (c <= ' ') c = read();boolean neg = (c == '-'); if (neg) c = read();do {ret = ret * 10 + c - '0';} while ((c = read()) >= '0' && c <= '9');if (neg) return -ret;return ret;} public String nextLine() throws IOException {st = new StringTokenizer("");return in.readLine();} public String next() throws IOException {while (!st.hasMoreTokens()) {st = new StringTokenizer(in.readLine());}return st.nextToken();}} static Reader in = new Reader();static PrintWriter out = new PrintWriter(System.out);static long mod = (long)(1e9+7); static class TreeMultiset<T> {NavigableMap<T,Integer> h; public TreeMultiset() {h = new TreeMap<>();}private boolean has(T key) {return h.containsKey(key);} private void add(T key) {h.put(key,h.getOrDefault(key,0)+1);}private int get(T key) {return h.get(key);} public void del(T key) {if(h.containsKey(key)) {if(h.get(key)==1) h.remove(key);else h.put(key,h.getOrDefault(key,0)-1);}} private T down(T key) { Map.Entry<T, Integer> val;val=h.lowerEntry(key );if(val!=null) {return val.getKey();}return null;} public T up(T key) { Map.Entry<T, Integer> val;val=h.ceilingEntry(key);if(val!=null) {return val.getKey();}return null;} public int size(){int s=0; for(int k:h.values()) s+=k; return s; }} //-----------------------------INPUT-------------------------------------------------// public static int ni() throws IOException {return in.nextInt();} public static long nl() throws IOException {return in.nextLong();} public static String rl() throws IOException {return in.next();} public static char nc() throws IOException {return in.next().charAt(0);} //----------------------------ARRAYS INPUT--------------------------------------------// public static int[] ai(long n) throws IOException {int[] arr = new int[(int)n]; for (int i = 0; i < n; i++) {arr[i] = in.nextInt();}return arr;} public static long[] al(long n) throws IOException {long[] arr = new long[(int)n]; for (int i = 0; i < n; i++) {arr[i] = in.nextLong();}return arr;} public static char[] ac() throws IOException {String s = in.next();return s.toCharArray();} //----------------------------Print---------------------------------------------------// public static void pt(int a) {out.println(a + " ");} public static void pt(long a) {out.println(a + " ");} public static void pt(double a) {out.println(a + " ");} public static void pt(char a) {out.println(a + " ");} public static void pt(int[] arr) {for (int j : arr) out.print(j + " ");out.println();} public static void pt(long[] arr) {for (long l : arr) out.print(l + " ");out.println();} public static void pt(char[] arr) {for (char l : arr) out.print(l );out.println();} public static void pt(String s) {out.println(s + " ");} public static void y() {out.println("YES");} public static void n() {out.println("NO");} //--------------------------------------------Other Functions----------------------------------------------------// public static long gcd(long a, long b) {BigInteger x = BigInteger.valueOf(a).gcd(BigInteger.valueOf(b)); return Long.parseLong(String.valueOf(x));} public static long expo(long a, long b) {long res = 1; while (b > 0) {if ((b & 1) != 0) res = res * a;a = a * a;b >>= 1;}return res;} public static long modexp(long a, long b) {long res = 1; while (b > 0) {if ((b & 1) != 0) res = (res * a % mod) % mod;a = (a % mod * a % mod) % mod;b >>= 1;}return res % mod;} public static int[] permute(int n) {int[] arr = new int[n];for (int i = 0; i < n; i++) {arr[i] = i;}return arr;} public static long min(long[] arr) {long min = Long.MAX_VALUE;for (long l : arr) {if (l < min) min = l;}return min;} public static long max(long[] arr) {long max = Long.MIN_VALUE;for (long l : arr) {if (l > max) max = l;}return max;} public static void sort(long[] arr) { List<Long> list = new ArrayList<>();for (long i : arr) {list.add(i);}Collections.sort(list); for (int i = 0; i < arr.length; i++) {arr[i] = list.get(i);}} public static void sort(int[] arr) { List<Integer> list = new ArrayList<>();for (int i : arr) {list.add(i);}Collections.sort(list); for (int i = 0; i < arr.length; i++) {arr[i] = list.get(i);}} public static long countfactors(long n) {long ans = 0;for (long i = 1; i * i <= n; i++) {if (n % i == 0) {ans += 2;if (n / i == i) ans--;}} return ans;} public static boolean isprime(long n) {for (long i = 2; i * i <= n; i++) {if (n % i == 0) return false;}return true;} public static long [] copy(long[] arr) {long []brr=new long[arr.length];System.arraycopy(arr, 0, brr, 0, arr.length);return brr;} public static long countDigit(long n) {long count = 0;while (n != 0) {n = n / 10;++count;}return count;} static Scanner sc=new Scanner(System.in); //---------------------------------------------------------------------------------------------------------------------------------------// public static void Khud_Bhi_Krle_Kuch() throws IOException { // Scanner sc = new Scanner(System.in); String s = sc.next(); int n = s.length(), x = 0; HashMap<Character, ArrayList<Integer>> h = new HashMap<>(); for(int i=1;i<n-1;i++) { if (h.containsKey(s.charAt(i))) { ArrayList<Integer> arr = h.get(s.charAt(i)); arr.add(i + 1); h.put(s.charAt(i),arr); } else { ArrayList<Integer> arr = new ArrayList<>(); arr.add(i + 1); h.put(s.charAt(i),arr); } } long sum=0; if(s.charAt(0)<s.charAt(n-1)) { for(char c=s.charAt(0);c<=s.charAt(s.length()-1);c++) { if(h.containsKey(c)) sum+=h.get(c).size(); } System.out.println(s.charAt(n-1)-s.charAt(0)+" "+(sum+2)); System.out.print(1+" "); for(char c=s.charAt(0);c<=s.charAt(s.length()-1);c++) { if (h.containsKey(c)) { for (int i : h.get(c)) System.out.print(i + " "); } } } else { for(char c=s.charAt(0);c>=s.charAt(s.length()-1);c--) { if(h.containsKey(c)) sum+=h.get(c).size(); } System.out.println(s.charAt(0)-s.charAt(n-1)+" "+(sum+2)); System.out.print(1+" "); for(char c=s.charAt(0);c>=s.charAt(s.length()-1);c--){ if(h.containsKey(c)) { for (int i : h.get(c)) { System.out.print(i + " "); } } } } System.out.println(n); } //--------------------------------------MAIN--------------------------------------------// public static void main(String[] args) throws Exception { int t=sc.nextInt();while(t--!=0) Khud_Bhi_Krle_Kuch(); // out.close(); }}
Java
["6\n\nlogic\n\ncodeforces\n\nbca\n\naaaaaaaaaaa\n\nadbaadabad\n\nto"]
1 second
["9 4\n1 4 3 5\n16 10\n1 8 3 4 9 5 2 6 7 10\n1 2\n1 3\n0 11\n1 8 10 4 3 5 7 2 9 6 11\n3 10\n1 9 5 4 7 3 8 6 2 10\n5 2\n1 2"]
NoteIn the first test case, the required path corresponds to the picture: In this case, the minimum possible total cost of the path is achieved. Since $$$index($$$'l'$$$)=12$$$, $$$index($$$'o'$$$)=15$$$, $$$index($$$'g'$$$)=7$$$, $$$index($$$'i'$$$)=9$$$, $$$index($$$'c'$$$)=3$$$, then the total cost of the path is $$$|12-9|+|9-7|+|7-3|=3+2+4=9$$$.
Java 17
standard input
[ "constructive algorithms", "strings" ]
d17c9f91504e1d4c4eae7294bf09dcfc
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. Each test case is given by the string $$$s$$$ ($$$2 \le |s| \le 2 \cdot 10^5$$$), where $$$|s|$$$ — is the length of string $$$s$$$. The string $$$s$$$ consists of lowercase Latin letters. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,100
The answer to each test case consists of two lines. In the first line print two integers $$$cost$$$, $$$m$$$, where $$$cost$$$ is the minimum total cost of the path, and $$$m$$$ is the maximum number of visited tiles Polycarp can make to get to $$$n$$$-th tiles for the minimum total cost $$$cost$$$ (i.e. the number of jumps is $$$m-1$$$). In the next line print $$$m$$$ different numbers $$$j_1, j_2, \dots, j_m$$$ ($$$1 \le j_i \le |s|$$$) — the sequence of indices of the tiles Polycarp will jump on. The first number in the sequence must be $$$1$$$ (that is, $$$j_1=1$$$) and the last number must be the value of $$$|s|$$$ (that is, $$$j_m=|s|$$$). If there are multiple answers, print any of them.
standard output
PASSED
1b22fa9707ebbfa5dd73d4fed91d21dd
train_110.jsonl
1662993300
Polycarp was given a row of tiles. Each tile contains one lowercase letter of the Latin alphabet. The entire sequence of tiles forms the string $$$s$$$.In other words, you are given a string $$$s$$$ consisting of lowercase Latin letters.Initially, Polycarp is on the first tile of the row and wants to get to the last tile by jumping on the tiles. Jumping from $$$i$$$-th tile to $$$j$$$-th tile has a cost equal to $$$|index(s_i) - index(s_j)|$$$, where $$$index(c)$$$ is the index of the letter $$$c$$$ in the alphabet (for example, $$$index($$$'a'$$$)=1$$$, $$$index($$$'b'$$$)=2$$$, ..., $$$index($$$'z'$$$)=26$$$) .Polycarp wants to get to the $$$n$$$-th tile for the minimum total cost, but at the same time make maximum number of jumps.In other words, among all possible ways to get to the last tile for the minimum total cost, he will choose the one with the maximum number of jumps.Polycarp can visit each tile at most once.Polycarp asks you to help — print the sequence of indices of string $$$s$$$ on which he should jump.
256 megabytes
import java.util.*; public class MyClass { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int tc = sc.nextInt(); while(tc-- > 0){ String s = sc.next(); char[] arr = s.toCharArray(); int n = arr.length; ArrayList<Pair> arr2 = new ArrayList<>(); for(int i = 1; i < n-1; i++){ Pair p = new Pair(); p.c = arr[i]-'a'; p.idx = i; arr2.add(p); } Collections.sort(arr2,new Sorting()); Pair p1 = new Pair(); p1.c = arr[0]-'a'; p1.idx = 0; arr2.add(0,p1); Pair p2 = new Pair(); p2.c = arr[n-1]-'a'; p2.idx = n-1; arr2.add(p2); // for(Pair p : arr2){ // System.out.print(p.c+" "); // } // System.out.println(); int st = arr[0]-'a'; int end = arr[n-1]-'a'; int ans = Math.abs(st-end); ArrayList<Integer> l = new ArrayList<>(); l.add(1); if(st > end){ //decreasing int i = n-2; while(i >= 1){ int crr = arr2.get(i).c; if( crr <= st && crr >= end){ l.add(arr2.get(i).idx+1); } i--; } }else{ //incresing int i = 1; while(i < n-1){ int crr = arr2.get(i).c; if( crr >= st && crr <= end){ l.add(arr2.get(i).idx+1); } i++; } } l.add(n); System.out.println(ans + " " + (l.size())); for(int val: l){ System.out.print(val+" "); } System.out.println(); } } static class Pair{ int c,idx; } static class Sorting implements Comparator<Pair>{ public int compare(Pair p1, Pair p2){ return p1.c - p2.c; } } }
Java
["6\n\nlogic\n\ncodeforces\n\nbca\n\naaaaaaaaaaa\n\nadbaadabad\n\nto"]
1 second
["9 4\n1 4 3 5\n16 10\n1 8 3 4 9 5 2 6 7 10\n1 2\n1 3\n0 11\n1 8 10 4 3 5 7 2 9 6 11\n3 10\n1 9 5 4 7 3 8 6 2 10\n5 2\n1 2"]
NoteIn the first test case, the required path corresponds to the picture: In this case, the minimum possible total cost of the path is achieved. Since $$$index($$$'l'$$$)=12$$$, $$$index($$$'o'$$$)=15$$$, $$$index($$$'g'$$$)=7$$$, $$$index($$$'i'$$$)=9$$$, $$$index($$$'c'$$$)=3$$$, then the total cost of the path is $$$|12-9|+|9-7|+|7-3|=3+2+4=9$$$.
Java 17
standard input
[ "constructive algorithms", "strings" ]
d17c9f91504e1d4c4eae7294bf09dcfc
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. Each test case is given by the string $$$s$$$ ($$$2 \le |s| \le 2 \cdot 10^5$$$), where $$$|s|$$$ — is the length of string $$$s$$$. The string $$$s$$$ consists of lowercase Latin letters. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,100
The answer to each test case consists of two lines. In the first line print two integers $$$cost$$$, $$$m$$$, where $$$cost$$$ is the minimum total cost of the path, and $$$m$$$ is the maximum number of visited tiles Polycarp can make to get to $$$n$$$-th tiles for the minimum total cost $$$cost$$$ (i.e. the number of jumps is $$$m-1$$$). In the next line print $$$m$$$ different numbers $$$j_1, j_2, \dots, j_m$$$ ($$$1 \le j_i \le |s|$$$) — the sequence of indices of the tiles Polycarp will jump on. The first number in the sequence must be $$$1$$$ (that is, $$$j_1=1$$$) and the last number must be the value of $$$|s|$$$ (that is, $$$j_m=|s|$$$). If there are multiple answers, print any of them.
standard output
PASSED
f076cfaec872564e498ef47acfcfb342
train_110.jsonl
1662993300
Polycarp was given a row of tiles. Each tile contains one lowercase letter of the Latin alphabet. The entire sequence of tiles forms the string $$$s$$$.In other words, you are given a string $$$s$$$ consisting of lowercase Latin letters.Initially, Polycarp is on the first tile of the row and wants to get to the last tile by jumping on the tiles. Jumping from $$$i$$$-th tile to $$$j$$$-th tile has a cost equal to $$$|index(s_i) - index(s_j)|$$$, where $$$index(c)$$$ is the index of the letter $$$c$$$ in the alphabet (for example, $$$index($$$'a'$$$)=1$$$, $$$index($$$'b'$$$)=2$$$, ..., $$$index($$$'z'$$$)=26$$$) .Polycarp wants to get to the $$$n$$$-th tile for the minimum total cost, but at the same time make maximum number of jumps.In other words, among all possible ways to get to the last tile for the minimum total cost, he will choose the one with the maximum number of jumps.Polycarp can visit each tile at most once.Polycarp asks you to help — print the sequence of indices of string $$$s$$$ on which he should jump.
256 megabytes
import java.util.*; import java.io.*; public class CF1729C { // For fast input output static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { try { br = new BufferedReader( new FileReader("input.txt")); PrintStream out = new PrintStream(new FileOutputStream("output.txt")); System.setOut(out); } catch (Exception e) { 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()); } int[] readArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } // end of fast i/o code public static boolean isPalindrome(String str) { int i = 0; int j = str.length() - 1; int flag = 0; while (i <= j) { if (str.charAt(i) != str.charAt(j)) { flag = 1; break; } i++; j--; } return flag == 1 ? false : true; } public static int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a); } class Pair { int x1; int x2; public Pair(int x1, int x2) { this.x1 = x1; this.x2 = x2; } } static void solve() { } public static void main(String[] args) { FastReader fs = new FastReader(); PrintWriter out = new PrintWriter(System.out); // solve(); int t=fs.nextInt(); while(t-->0){ String s=fs.next(); int n =s.length(); HashMap<Character,List<Integer>>hm=new HashMap<>(); List<Integer>res=new ArrayList<>(); for(int i =0;i<n;i++){ char ch=s.charAt(i); if(!hm.containsKey(ch)) hm.put(ch,new ArrayList<>()); hm.get(ch).add(i+1); } char s1=s.charAt(0),e1=s.charAt(n-1); char ch[]=s.toCharArray(); Arrays.sort(ch); HashSet<Character>hs=new HashSet<>(); int startIdx=-1,endIdx=-1; for(int i =0;i<n;i++){ if(ch[i]==s1) startIdx=i; if(ch[i]==e1) endIdx=i; } int indexs[]=new int [n]; if(startIdx==endIdx){ res.addAll(hm.get(s1)); out.print(0 +" "+ res.size()); out.println(); for(int tmp:res) out.print(tmp+" "); out.println(); } else{ int sum=0; char prev=s1; res.addAll(hm.get(s1)); hs.add(s1); if(endIdx<startIdx){ for(int i =startIdx-1;i>=endIdx;i--){ char c=ch[i]; if(!hs.contains(c)){ hs.add(c); sum+=prev-c; prev=c; res.addAll(hm.get(c)); } } out.print(sum +" "+ res.size()); out.println(); for(int tmp:res) out.print(tmp+" "); out.println(); } else{ for(int i =startIdx+1;i<=endIdx;i++){ char c=ch[i]; if(!hs.contains(c)){ hs.add(c); sum+=c-prev; prev=c; res.addAll(hm.get(c)); } } out.print(sum +" "+ res.size()); out.println(); for(int tmp:res) out.print(tmp+" "); out.println(); } } } out.close(); } }
Java
["6\n\nlogic\n\ncodeforces\n\nbca\n\naaaaaaaaaaa\n\nadbaadabad\n\nto"]
1 second
["9 4\n1 4 3 5\n16 10\n1 8 3 4 9 5 2 6 7 10\n1 2\n1 3\n0 11\n1 8 10 4 3 5 7 2 9 6 11\n3 10\n1 9 5 4 7 3 8 6 2 10\n5 2\n1 2"]
NoteIn the first test case, the required path corresponds to the picture: In this case, the minimum possible total cost of the path is achieved. Since $$$index($$$'l'$$$)=12$$$, $$$index($$$'o'$$$)=15$$$, $$$index($$$'g'$$$)=7$$$, $$$index($$$'i'$$$)=9$$$, $$$index($$$'c'$$$)=3$$$, then the total cost of the path is $$$|12-9|+|9-7|+|7-3|=3+2+4=9$$$.
Java 17
standard input
[ "constructive algorithms", "strings" ]
d17c9f91504e1d4c4eae7294bf09dcfc
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. Each test case is given by the string $$$s$$$ ($$$2 \le |s| \le 2 \cdot 10^5$$$), where $$$|s|$$$ — is the length of string $$$s$$$. The string $$$s$$$ consists of lowercase Latin letters. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,100
The answer to each test case consists of two lines. In the first line print two integers $$$cost$$$, $$$m$$$, where $$$cost$$$ is the minimum total cost of the path, and $$$m$$$ is the maximum number of visited tiles Polycarp can make to get to $$$n$$$-th tiles for the minimum total cost $$$cost$$$ (i.e. the number of jumps is $$$m-1$$$). In the next line print $$$m$$$ different numbers $$$j_1, j_2, \dots, j_m$$$ ($$$1 \le j_i \le |s|$$$) — the sequence of indices of the tiles Polycarp will jump on. The first number in the sequence must be $$$1$$$ (that is, $$$j_1=1$$$) and the last number must be the value of $$$|s|$$$ (that is, $$$j_m=|s|$$$). If there are multiple answers, print any of them.
standard output
PASSED
1b8238d58b84d11b384c5101f605137f
train_110.jsonl
1662993300
Polycarp was given a row of tiles. Each tile contains one lowercase letter of the Latin alphabet. The entire sequence of tiles forms the string $$$s$$$.In other words, you are given a string $$$s$$$ consisting of lowercase Latin letters.Initially, Polycarp is on the first tile of the row and wants to get to the last tile by jumping on the tiles. Jumping from $$$i$$$-th tile to $$$j$$$-th tile has a cost equal to $$$|index(s_i) - index(s_j)|$$$, where $$$index(c)$$$ is the index of the letter $$$c$$$ in the alphabet (for example, $$$index($$$'a'$$$)=1$$$, $$$index($$$'b'$$$)=2$$$, ..., $$$index($$$'z'$$$)=26$$$) .Polycarp wants to get to the $$$n$$$-th tile for the minimum total cost, but at the same time make maximum number of jumps.In other words, among all possible ways to get to the last tile for the minimum total cost, he will choose the one with the maximum number of jumps.Polycarp can visit each tile at most once.Polycarp asks you to help — print the sequence of indices of string $$$s$$$ on which he should jump.
256 megabytes
import java.io.*; import java.util.*; public class Main { static BufferedReader br; static long cnt=0; static int mod=998244353; //static ArrayList<ArrayList<Integer>> arr=new ArrayList<>(); static StringBuilder ans=new StringBuilder(""); public static void main(String args[]) throws IOException { // Your code goes here /* 1 2 3 1 2 4 1 2 5 1 3 4 1 3 5 1 4 5 2 3 4 2 3 5 2 4 5 3 4 5 1 3 4 5 4 5 5 code aj abacaba ll codeforces aaaak aaaaj aaaaa zf */ br=new BufferedReader(new InputStreamReader(System.in)); int t=Int(); while(t-->0){ //int n=Int(); String str=br.readLine(); int n=str.length(); char ch[]=str.toCharArray(); int i; TreeMap<Integer,TreeSet<Integer>> map=new TreeMap<>(); for(i=0;i<n;i++){ int x=(ch[i]-'a'); map.putIfAbsent(x,new TreeSet<>()); map.get(x).add(i); } int x=ch[0]-'a'; int y=ch[n-1]-'a'; StringBuilder temp=new StringBuilder(""); int res=0; if(x==y){ res=map.get(x).size(); ans.append(0+" "+res+""+"\n"); for(i=0;i<res;i++){ ans.append((map.get(x).first()+1)+" "); map.get(x).remove(map.get(x).first()); } ans.append("\n"); } else if(x>y){ int g=x-y; // System.out.println(x); // System.out.println(map.get(x).size()); i=0; while(true){ int l=map.get(x).size(); for(i=0;i<l;i++){ temp.append((map.get(x).first()+1)+" "); map.get(x).remove(map.get(x).first()); res++; } map.remove(x); if((char)(97+x)==ch[n-1]){ break; } if(map.floorKey(x)==null) break; x=map.floorKey(x); } ans.append(g+" "+res+"\n"); ans.append(temp+"\n"); } else{ i=0; int g=y-x; while(true){ int l=map.get(x).size(); for(i=0;i<l;i++){ temp.append((map.get(x).first()+1)+" "); map.get(x).remove(map.get(x).first()); res++; } map.remove(x); if((char)(97+x)==ch[n-1]){ break; } if(map.ceilingKey(x)==null) break; x=map.ceilingKey(x); } ans.append(g+" "+(res)+"\n"); ans.append(temp+"\n"); } } printString(ans.toString()); } public static boolean isPalindrome(String str) { // Initializing an empty string to store the reverse // of the original str String rev = ""; // Initializing a new boolean variable for the // answer boolean ans = false; for (int i = str.length() - 1; i >= 0; i--) { rev = rev + str.charAt(i); } // Checking if both the strings are equal if (str.equals(rev)) { ans = true; } return ans; } public static void dfs(int u,boolean visited[],int color[],ArrayList<Integer> graph[],int c){ visited[u]=true; color[u]=c; int cnt=0; for(int v:graph[u]){ if(visited[v]==true) continue; c=1-c; dfs(v,visited,color,graph,c); } } public static long memo(long dp[][],int i,int j,long arr[]){ if(j==dp[0].length) return 0; if(i>=arr.length) return -1*(long)Math.pow(10,15); if(dp[i][j]!=-1) return dp[i][j]; dp[i][j]=Math.max(memo(dp,i+1,j+1,arr)+arr[i]*(j+1),memo(dp,i+1,j,arr)); return dp[i][j]; } public static int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } public static void fun(int curr,int count,int x,int y,ArrayList<Integer> pres){ } // public static mine min(mine x,mine y){ // if(x.a>y.a) // return y; // if(y.a>x.a) // return x; // if(x.b>y.b) // return y; // return x; // } public static int[] readInt(int n) throws IOException { String str[]=br.readLine().split(" "); int a[]=new int[n]; for(int i=0;i<n;i++) a[i]=Integer.parseInt(str[i]); return a; } public static ArrayList<Integer> readList(int n) throws IOException { String str[]=br.readLine().split(" "); ArrayList<Integer> arr=new ArrayList<>(); for(int i=0;i<n;i++) arr.add(Integer.parseInt(str[i])); return arr; } public static char[] readChar(int n) throws IOException { String str=br.readLine(); char a[]=new char[n]; for(int i=0;i<n;i++) a[i]=str.charAt(i); return a; } public static long[] readLong(int n) throws IOException { String str[]=br.readLine().split(" "); long a[]=new long[n]; for(int i=0;i<n;i++) a[i]=Long.parseLong(str[i]); return a; } public static void printString(String str){ System.out.println(str); } public static void printInt(int str){ System.out.println(str); } public static void printLong(long str){ System.out.println(str); } public static int Int() throws IOException { return Integer.parseInt(br.readLine()); } public static long Long() throws IOException { return Long.parseLong(br.readLine()); } public static String[] readString() throws IOException { return br.readLine().split(" "); } } class mine{ long num; int index; public mine(long x,int y){ num=x; index=y; } }
Java
["6\n\nlogic\n\ncodeforces\n\nbca\n\naaaaaaaaaaa\n\nadbaadabad\n\nto"]
1 second
["9 4\n1 4 3 5\n16 10\n1 8 3 4 9 5 2 6 7 10\n1 2\n1 3\n0 11\n1 8 10 4 3 5 7 2 9 6 11\n3 10\n1 9 5 4 7 3 8 6 2 10\n5 2\n1 2"]
NoteIn the first test case, the required path corresponds to the picture: In this case, the minimum possible total cost of the path is achieved. Since $$$index($$$'l'$$$)=12$$$, $$$index($$$'o'$$$)=15$$$, $$$index($$$'g'$$$)=7$$$, $$$index($$$'i'$$$)=9$$$, $$$index($$$'c'$$$)=3$$$, then the total cost of the path is $$$|12-9|+|9-7|+|7-3|=3+2+4=9$$$.
Java 17
standard input
[ "constructive algorithms", "strings" ]
d17c9f91504e1d4c4eae7294bf09dcfc
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. Each test case is given by the string $$$s$$$ ($$$2 \le |s| \le 2 \cdot 10^5$$$), where $$$|s|$$$ — is the length of string $$$s$$$. The string $$$s$$$ consists of lowercase Latin letters. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,100
The answer to each test case consists of two lines. In the first line print two integers $$$cost$$$, $$$m$$$, where $$$cost$$$ is the minimum total cost of the path, and $$$m$$$ is the maximum number of visited tiles Polycarp can make to get to $$$n$$$-th tiles for the minimum total cost $$$cost$$$ (i.e. the number of jumps is $$$m-1$$$). In the next line print $$$m$$$ different numbers $$$j_1, j_2, \dots, j_m$$$ ($$$1 \le j_i \le |s|$$$) — the sequence of indices of the tiles Polycarp will jump on. The first number in the sequence must be $$$1$$$ (that is, $$$j_1=1$$$) and the last number must be the value of $$$|s|$$$ (that is, $$$j_m=|s|$$$). If there are multiple answers, print any of them.
standard output
PASSED
1be797bce501aacd83c33265b3bbb2fe
train_110.jsonl
1662993300
Polycarp was given a row of tiles. Each tile contains one lowercase letter of the Latin alphabet. The entire sequence of tiles forms the string $$$s$$$.In other words, you are given a string $$$s$$$ consisting of lowercase Latin letters.Initially, Polycarp is on the first tile of the row and wants to get to the last tile by jumping on the tiles. Jumping from $$$i$$$-th tile to $$$j$$$-th tile has a cost equal to $$$|index(s_i) - index(s_j)|$$$, where $$$index(c)$$$ is the index of the letter $$$c$$$ in the alphabet (for example, $$$index($$$'a'$$$)=1$$$, $$$index($$$'b'$$$)=2$$$, ..., $$$index($$$'z'$$$)=26$$$) .Polycarp wants to get to the $$$n$$$-th tile for the minimum total cost, but at the same time make maximum number of jumps.In other words, among all possible ways to get to the last tile for the minimum total cost, he will choose the one with the maximum number of jumps.Polycarp can visit each tile at most once.Polycarp asks you to help — print the sequence of indices of string $$$s$$$ on which he should jump.
256 megabytes
import java.io.*; import java.util.*; public class C { final static boolean multipleTests = true; Input in; PrintWriter out; public C() { in = new Input(System.in); out = new PrintWriter(System.out); } public static void main(String[] args) { C solution = new C(); int t = 1; if (multipleTests) t = solution.in.nextInt(); for (; t > 0; t--) { solution.solve(); } solution.out.close(); } void solve() { char[] s = in.nextString().toCharArray(); int n = s.length; Map<Character, List<Integer>> map = new HashMap<>(); for (char c = 'a'; c<='z'; c++) map.put(c, new ArrayList<>()); for (int i=1; i<n-1; i++) { map.get(s[i]).add(i+1); } if (s[0] <= s[n-1]) { out.print(s[n-1] - s[0]); out.print(' '); int jumps = 2; StringBuilder sb = new StringBuilder(); sb.append(1).append(' '); for (char c=s[0]; c<=s[n-1]; c++) { for (int idx: map.get(c)) { jumps++; sb.append(idx).append(' '); } } sb.append(n); out.println(jumps); out.println(sb); } else { out.print(s[0] - s[n-1]); out.print(' '); int jumps = 2; StringBuilder sb = new StringBuilder(); sb.append(1).append(' '); for (char c=s[0]; c>=s[n-1]; c--) { for (int idx: map.get(c)) { jumps++; sb.append(idx).append(' '); } } sb.append(n); out.println(jumps); out.println(sb); } } static class Input { BufferedReader br; StringTokenizer st; public Input(InputStream in) { br = new BufferedReader(new InputStreamReader(in)); st = new StringTokenizer(""); } String nextString() { while (!st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(nextString()); } long nextLong() { return Long.parseLong(nextString()); } double nextDouble() { return Double.parseDouble(nextString()); } int[] nextIntArray(int size) { int[] ans = new int[size]; for (int i = 0; i < size; i++) { ans[i] = nextInt(); } return ans; } } }
Java
["6\n\nlogic\n\ncodeforces\n\nbca\n\naaaaaaaaaaa\n\nadbaadabad\n\nto"]
1 second
["9 4\n1 4 3 5\n16 10\n1 8 3 4 9 5 2 6 7 10\n1 2\n1 3\n0 11\n1 8 10 4 3 5 7 2 9 6 11\n3 10\n1 9 5 4 7 3 8 6 2 10\n5 2\n1 2"]
NoteIn the first test case, the required path corresponds to the picture: In this case, the minimum possible total cost of the path is achieved. Since $$$index($$$'l'$$$)=12$$$, $$$index($$$'o'$$$)=15$$$, $$$index($$$'g'$$$)=7$$$, $$$index($$$'i'$$$)=9$$$, $$$index($$$'c'$$$)=3$$$, then the total cost of the path is $$$|12-9|+|9-7|+|7-3|=3+2+4=9$$$.
Java 17
standard input
[ "constructive algorithms", "strings" ]
d17c9f91504e1d4c4eae7294bf09dcfc
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. Each test case is given by the string $$$s$$$ ($$$2 \le |s| \le 2 \cdot 10^5$$$), where $$$|s|$$$ — is the length of string $$$s$$$. The string $$$s$$$ consists of lowercase Latin letters. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,100
The answer to each test case consists of two lines. In the first line print two integers $$$cost$$$, $$$m$$$, where $$$cost$$$ is the minimum total cost of the path, and $$$m$$$ is the maximum number of visited tiles Polycarp can make to get to $$$n$$$-th tiles for the minimum total cost $$$cost$$$ (i.e. the number of jumps is $$$m-1$$$). In the next line print $$$m$$$ different numbers $$$j_1, j_2, \dots, j_m$$$ ($$$1 \le j_i \le |s|$$$) — the sequence of indices of the tiles Polycarp will jump on. The first number in the sequence must be $$$1$$$ (that is, $$$j_1=1$$$) and the last number must be the value of $$$|s|$$$ (that is, $$$j_m=|s|$$$). If there are multiple answers, print any of them.
standard output
PASSED
6720ae58d2601dc25bae2f23016afb4d
train_110.jsonl
1662993300
Polycarp was given a row of tiles. Each tile contains one lowercase letter of the Latin alphabet. The entire sequence of tiles forms the string $$$s$$$.In other words, you are given a string $$$s$$$ consisting of lowercase Latin letters.Initially, Polycarp is on the first tile of the row and wants to get to the last tile by jumping on the tiles. Jumping from $$$i$$$-th tile to $$$j$$$-th tile has a cost equal to $$$|index(s_i) - index(s_j)|$$$, where $$$index(c)$$$ is the index of the letter $$$c$$$ in the alphabet (for example, $$$index($$$'a'$$$)=1$$$, $$$index($$$'b'$$$)=2$$$, ..., $$$index($$$'z'$$$)=26$$$) .Polycarp wants to get to the $$$n$$$-th tile for the minimum total cost, but at the same time make maximum number of jumps.In other words, among all possible ways to get to the last tile for the minimum total cost, he will choose the one with the maximum number of jumps.Polycarp can visit each tile at most once.Polycarp asks you to help — print the sequence of indices of string $$$s$$$ on which he should jump.
256 megabytes
import java.util.*; public class Test1 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while(t-->0) { String s = sc.next(); int n = s.length(); StringBuilder sb = new StringBuilder(); sb.append(1).append(' '); char ch1 = s.charAt(0); char ch2 = s.charAt(n-1); char min = ch1 < ch2? ch1 : ch2; char max = ch1 < ch2? ch2 : ch1; List<Pair> list = new ArrayList<>(); for(int i=1;i<n-1;i++) { char ch = s.charAt(i); if(min <= ch && ch <= max) { list.add(new Pair(ch, i+1)); } } if(ch1 > ch2) Collections.sort(list, (a, b) -> b.ch-a.ch); else Collections.sort(list, (a, b) -> a.ch-b.ch); int cost = 0; char last = ch1; for(Pair pair : list) { char curr = pair.ch; int ind = pair.ind; sb.append(ind).append(' '); cost += Math.abs(curr-last); last = curr; } cost += Math.abs(ch2-last); sb.append(n); int cells = 2 + list.size(); System.out.println(cost+" "+cells); System.out.println(sb.toString()); } } static class Pair{ char ch; int ind; Pair(char ch, int ind){ this.ch = ch; this.ind = ind; } } }
Java
["6\n\nlogic\n\ncodeforces\n\nbca\n\naaaaaaaaaaa\n\nadbaadabad\n\nto"]
1 second
["9 4\n1 4 3 5\n16 10\n1 8 3 4 9 5 2 6 7 10\n1 2\n1 3\n0 11\n1 8 10 4 3 5 7 2 9 6 11\n3 10\n1 9 5 4 7 3 8 6 2 10\n5 2\n1 2"]
NoteIn the first test case, the required path corresponds to the picture: In this case, the minimum possible total cost of the path is achieved. Since $$$index($$$'l'$$$)=12$$$, $$$index($$$'o'$$$)=15$$$, $$$index($$$'g'$$$)=7$$$, $$$index($$$'i'$$$)=9$$$, $$$index($$$'c'$$$)=3$$$, then the total cost of the path is $$$|12-9|+|9-7|+|7-3|=3+2+4=9$$$.
Java 17
standard input
[ "constructive algorithms", "strings" ]
d17c9f91504e1d4c4eae7294bf09dcfc
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. Each test case is given by the string $$$s$$$ ($$$2 \le |s| \le 2 \cdot 10^5$$$), where $$$|s|$$$ — is the length of string $$$s$$$. The string $$$s$$$ consists of lowercase Latin letters. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,100
The answer to each test case consists of two lines. In the first line print two integers $$$cost$$$, $$$m$$$, where $$$cost$$$ is the minimum total cost of the path, and $$$m$$$ is the maximum number of visited tiles Polycarp can make to get to $$$n$$$-th tiles for the minimum total cost $$$cost$$$ (i.e. the number of jumps is $$$m-1$$$). In the next line print $$$m$$$ different numbers $$$j_1, j_2, \dots, j_m$$$ ($$$1 \le j_i \le |s|$$$) — the sequence of indices of the tiles Polycarp will jump on. The first number in the sequence must be $$$1$$$ (that is, $$$j_1=1$$$) and the last number must be the value of $$$|s|$$$ (that is, $$$j_m=|s|$$$). If there are multiple answers, print any of them.
standard output
PASSED
d69ce7fb5d29b984df6b84ab9751a39d
train_110.jsonl
1662993300
Polycarp was given a row of tiles. Each tile contains one lowercase letter of the Latin alphabet. The entire sequence of tiles forms the string $$$s$$$.In other words, you are given a string $$$s$$$ consisting of lowercase Latin letters.Initially, Polycarp is on the first tile of the row and wants to get to the last tile by jumping on the tiles. Jumping from $$$i$$$-th tile to $$$j$$$-th tile has a cost equal to $$$|index(s_i) - index(s_j)|$$$, where $$$index(c)$$$ is the index of the letter $$$c$$$ in the alphabet (for example, $$$index($$$'a'$$$)=1$$$, $$$index($$$'b'$$$)=2$$$, ..., $$$index($$$'z'$$$)=26$$$) .Polycarp wants to get to the $$$n$$$-th tile for the minimum total cost, but at the same time make maximum number of jumps.In other words, among all possible ways to get to the last tile for the minimum total cost, he will choose the one with the maximum number of jumps.Polycarp can visit each tile at most once.Polycarp asks you to help — print the sequence of indices of string $$$s$$$ on which he should jump.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.StringTokenizer; public class TaskC { public static void main(String[] args) { FastReader reader = new FastReader(); int tt = reader.nextInt(); // int tt = 1; for (; tt > 0; tt--) { String str = reader.nextLine(); char firstChar = str.charAt(0); char lastChar = str.charAt(str.length() - 1); int cost = Math.abs(firstChar - lastChar); ArrayList<ArrayList<Integer>> indexes = new ArrayList<>(); for (int i = Math.min(firstChar, lastChar); i <= Math.max(firstChar, lastChar); i++) { indexes.add(new ArrayList<>()); } int count = 2; for (int i = 1; i < str.length() - 1; i++) { int c = str.charAt(i) - Math.min(firstChar, lastChar); if (c >= 0 && c <= Math.abs(lastChar - firstChar)) { indexes.get(c).add(i); count++; } } StringBuilder sb = new StringBuilder(); sb.append(1).append(" "); if (firstChar > lastChar) { Collections.reverse(indexes); } for (ArrayList<Integer> list : indexes) { for (Integer index : list) { sb.append(index + 1).append(" "); } } sb.append(str.length()); System.out.println(cost + " " + count); System.out.println(sb); } } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { if (st.hasMoreTokens()) { str = st.nextToken("\n"); } else { str = br.readLine(); } } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["6\n\nlogic\n\ncodeforces\n\nbca\n\naaaaaaaaaaa\n\nadbaadabad\n\nto"]
1 second
["9 4\n1 4 3 5\n16 10\n1 8 3 4 9 5 2 6 7 10\n1 2\n1 3\n0 11\n1 8 10 4 3 5 7 2 9 6 11\n3 10\n1 9 5 4 7 3 8 6 2 10\n5 2\n1 2"]
NoteIn the first test case, the required path corresponds to the picture: In this case, the minimum possible total cost of the path is achieved. Since $$$index($$$'l'$$$)=12$$$, $$$index($$$'o'$$$)=15$$$, $$$index($$$'g'$$$)=7$$$, $$$index($$$'i'$$$)=9$$$, $$$index($$$'c'$$$)=3$$$, then the total cost of the path is $$$|12-9|+|9-7|+|7-3|=3+2+4=9$$$.
Java 17
standard input
[ "constructive algorithms", "strings" ]
d17c9f91504e1d4c4eae7294bf09dcfc
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. Each test case is given by the string $$$s$$$ ($$$2 \le |s| \le 2 \cdot 10^5$$$), where $$$|s|$$$ — is the length of string $$$s$$$. The string $$$s$$$ consists of lowercase Latin letters. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,100
The answer to each test case consists of two lines. In the first line print two integers $$$cost$$$, $$$m$$$, where $$$cost$$$ is the minimum total cost of the path, and $$$m$$$ is the maximum number of visited tiles Polycarp can make to get to $$$n$$$-th tiles for the minimum total cost $$$cost$$$ (i.e. the number of jumps is $$$m-1$$$). In the next line print $$$m$$$ different numbers $$$j_1, j_2, \dots, j_m$$$ ($$$1 \le j_i \le |s|$$$) — the sequence of indices of the tiles Polycarp will jump on. The first number in the sequence must be $$$1$$$ (that is, $$$j_1=1$$$) and the last number must be the value of $$$|s|$$$ (that is, $$$j_m=|s|$$$). If there are multiple answers, print any of them.
standard output
PASSED
14f5d434c1ad9b1af9e4b31670374b50
train_110.jsonl
1662993300
Polycarp was given a row of tiles. Each tile contains one lowercase letter of the Latin alphabet. The entire sequence of tiles forms the string $$$s$$$.In other words, you are given a string $$$s$$$ consisting of lowercase Latin letters.Initially, Polycarp is on the first tile of the row and wants to get to the last tile by jumping on the tiles. Jumping from $$$i$$$-th tile to $$$j$$$-th tile has a cost equal to $$$|index(s_i) - index(s_j)|$$$, where $$$index(c)$$$ is the index of the letter $$$c$$$ in the alphabet (for example, $$$index($$$'a'$$$)=1$$$, $$$index($$$'b'$$$)=2$$$, ..., $$$index($$$'z'$$$)=26$$$) .Polycarp wants to get to the $$$n$$$-th tile for the minimum total cost, but at the same time make maximum number of jumps.In other words, among all possible ways to get to the last tile for the minimum total cost, he will choose the one with the maximum number of jumps.Polycarp can visit each tile at most once.Polycarp asks you to help — print the sequence of indices of string $$$s$$$ on which he should jump.
256 megabytes
import java.util.*; public class Solution { public static void main(String[] args) { Scanner in = new Scanner(System.in); int T=in.nextInt(); while(T-->0) { String s=in.next(); int diff=Math.abs((int)s.charAt(0)-(int)s.charAt(s.length()-1)); ArrayList<ArrayList<Integer>> l1=new ArrayList<ArrayList<Integer>>(); for(int i=0;i<=26;i++) { ArrayList<Integer> k1=new ArrayList<>(); l1.add(k1); } for(int i=0;i<s.length();i++) { l1.get(s.charAt(i)-96).add(i); } ArrayList<Integer> ans=new ArrayList<>(); int count=0; if(s.charAt(0)<s.charAt(s.length()-1)) { for(int i=s.charAt(0)-96;i<=s.charAt(s.length()-1)-96;i++) { for(int j:l1.get(i)) { count++; ans.add(j+1); } } } else { for(int i=s.charAt(0)-96;i>=s.charAt(s.length()-1)-96;i--) { for(int j:l1.get(i)) { count++; ans.add(j+1); } } } System.out.println(diff+" "+count); for(int p:ans) System.out.print(p+" "); System.out.println(); } } }
Java
["6\n\nlogic\n\ncodeforces\n\nbca\n\naaaaaaaaaaa\n\nadbaadabad\n\nto"]
1 second
["9 4\n1 4 3 5\n16 10\n1 8 3 4 9 5 2 6 7 10\n1 2\n1 3\n0 11\n1 8 10 4 3 5 7 2 9 6 11\n3 10\n1 9 5 4 7 3 8 6 2 10\n5 2\n1 2"]
NoteIn the first test case, the required path corresponds to the picture: In this case, the minimum possible total cost of the path is achieved. Since $$$index($$$'l'$$$)=12$$$, $$$index($$$'o'$$$)=15$$$, $$$index($$$'g'$$$)=7$$$, $$$index($$$'i'$$$)=9$$$, $$$index($$$'c'$$$)=3$$$, then the total cost of the path is $$$|12-9|+|9-7|+|7-3|=3+2+4=9$$$.
Java 17
standard input
[ "constructive algorithms", "strings" ]
d17c9f91504e1d4c4eae7294bf09dcfc
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. Each test case is given by the string $$$s$$$ ($$$2 \le |s| \le 2 \cdot 10^5$$$), where $$$|s|$$$ — is the length of string $$$s$$$. The string $$$s$$$ consists of lowercase Latin letters. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,100
The answer to each test case consists of two lines. In the first line print two integers $$$cost$$$, $$$m$$$, where $$$cost$$$ is the minimum total cost of the path, and $$$m$$$ is the maximum number of visited tiles Polycarp can make to get to $$$n$$$-th tiles for the minimum total cost $$$cost$$$ (i.e. the number of jumps is $$$m-1$$$). In the next line print $$$m$$$ different numbers $$$j_1, j_2, \dots, j_m$$$ ($$$1 \le j_i \le |s|$$$) — the sequence of indices of the tiles Polycarp will jump on. The first number in the sequence must be $$$1$$$ (that is, $$$j_1=1$$$) and the last number must be the value of $$$|s|$$$ (that is, $$$j_m=|s|$$$). If there are multiple answers, print any of them.
standard output
PASSED
b5687547b8c1570c6f339d20f50e889a
train_110.jsonl
1662993300
Polycarp was given a row of tiles. Each tile contains one lowercase letter of the Latin alphabet. The entire sequence of tiles forms the string $$$s$$$.In other words, you are given a string $$$s$$$ consisting of lowercase Latin letters.Initially, Polycarp is on the first tile of the row and wants to get to the last tile by jumping on the tiles. Jumping from $$$i$$$-th tile to $$$j$$$-th tile has a cost equal to $$$|index(s_i) - index(s_j)|$$$, where $$$index(c)$$$ is the index of the letter $$$c$$$ in the alphabet (for example, $$$index($$$'a'$$$)=1$$$, $$$index($$$'b'$$$)=2$$$, ..., $$$index($$$'z'$$$)=26$$$) .Polycarp wants to get to the $$$n$$$-th tile for the minimum total cost, but at the same time make maximum number of jumps.In other words, among all possible ways to get to the last tile for the minimum total cost, he will choose the one with the maximum number of jumps.Polycarp can visit each tile at most once.Polycarp asks you to help — print the sequence of indices of string $$$s$$$ on which he should jump.
256 megabytes
import java.util.*; import java.io.*; public class C { static class Node{ int id, val; Node(int id, int val){ this.id = id; this.val = val; } } public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); int tc = sc.nextInt(); StringBuilder sb = new StringBuilder(); while (tc-->0){ String s = sc.next(); int n = s.length(); Node[] nodes = new Node[n]; for(int i=0;i<n;i++){ nodes[i] = new Node(i, s.charAt(i) - 'a'); } HashMap<Integer, List<Node>> hash = new HashMap<>(); for(int i=0;i<n;i++){ int c = nodes[i].val; List<Node> nodelist = hash.getOrDefault(c, new ArrayList<>()); nodelist.add(nodes[i]); hash.put(c, nodelist); } Node source = nodes[0]; Node dest = nodes[n-1]; List<Node> list = new ArrayList<>(); list.add(source); if(source.val <= dest.val){ for(int i=source.val;i<=dest.val;i++){ List<Node> nodeList = hash.getOrDefault(i, new ArrayList<>()); for(Node node : nodeList){ if(node != source && node != dest){ list.add(node); } } } } else{ for(int i=source.val;i>=dest.val;i--){ List<Node> nodeList = hash.getOrDefault(i, new ArrayList<>()); for(Node node : nodeList){ if(node != source && node != dest){ list.add(node); } } } } list.add(dest); sb.append(Math.abs(dest.val - source.val)).append(" ").append(list.size()).append("\n"); for(Node node : list){ sb.append(node.id + 1).append(" "); } sb.append("\n"); } System.out.println(sb); sc.close(); } static class Soumit { final private int BUFFER_SIZE = 1 << 18; final private DataInputStream din; final private byte[] buffer; private PrintWriter pw; private int bufferPointer, bytesRead; StringTokenizer st; public Soumit() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Soumit(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public void streamOutput(String file) throws IOException { FileWriter fw = new FileWriter(file); BufferedWriter bw = new BufferedWriter(fw); pw = new PrintWriter(bw); } public void println(String a) { pw.println(a); } public void print(String a) { pw.print(a); } public String readLine() throws IOException { byte[] buf = new byte[3000064]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public void sort(int[] arr) { ArrayList<Integer> arlist = new ArrayList<>(); for (int i : arr) arlist.add(i); Collections.sort(arlist); for (int i = 0; i < arr.length; i++) arr[i] = arlist.get(i); } public void sort(long[] arr) { ArrayList<Long> arlist = new ArrayList<>(); for (long i : arr) arlist.add(i); Collections.sort(arlist); for (int i = 0; i < arr.length; i++) arr[i] = arlist.get(i); } public int[] nextIntArray(int n) throws IOException { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = nextInt(); } return arr; } public long[] nextLongArray(int n) throws IOException { long[] arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = nextLong(); } return arr; } public double[] nextDoubleArray(int n) throws IOException { double[] arr = new double[n]; for (int i = 0; i < n; i++) { arr[i] = nextDouble(); } return arr; } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { /*if (din == null) return;*/ if (din != null) din.close(); if (pw != null) pw.close(); } } }
Java
["6\n\nlogic\n\ncodeforces\n\nbca\n\naaaaaaaaaaa\n\nadbaadabad\n\nto"]
1 second
["9 4\n1 4 3 5\n16 10\n1 8 3 4 9 5 2 6 7 10\n1 2\n1 3\n0 11\n1 8 10 4 3 5 7 2 9 6 11\n3 10\n1 9 5 4 7 3 8 6 2 10\n5 2\n1 2"]
NoteIn the first test case, the required path corresponds to the picture: In this case, the minimum possible total cost of the path is achieved. Since $$$index($$$'l'$$$)=12$$$, $$$index($$$'o'$$$)=15$$$, $$$index($$$'g'$$$)=7$$$, $$$index($$$'i'$$$)=9$$$, $$$index($$$'c'$$$)=3$$$, then the total cost of the path is $$$|12-9|+|9-7|+|7-3|=3+2+4=9$$$.
Java 17
standard input
[ "constructive algorithms", "strings" ]
d17c9f91504e1d4c4eae7294bf09dcfc
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. Each test case is given by the string $$$s$$$ ($$$2 \le |s| \le 2 \cdot 10^5$$$), where $$$|s|$$$ — is the length of string $$$s$$$. The string $$$s$$$ consists of lowercase Latin letters. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,100
The answer to each test case consists of two lines. In the first line print two integers $$$cost$$$, $$$m$$$, where $$$cost$$$ is the minimum total cost of the path, and $$$m$$$ is the maximum number of visited tiles Polycarp can make to get to $$$n$$$-th tiles for the minimum total cost $$$cost$$$ (i.e. the number of jumps is $$$m-1$$$). In the next line print $$$m$$$ different numbers $$$j_1, j_2, \dots, j_m$$$ ($$$1 \le j_i \le |s|$$$) — the sequence of indices of the tiles Polycarp will jump on. The first number in the sequence must be $$$1$$$ (that is, $$$j_1=1$$$) and the last number must be the value of $$$|s|$$$ (that is, $$$j_m=|s|$$$). If there are multiple answers, print any of them.
standard output
PASSED
cc50313bcdf1142fe2f46051d902a9e9
train_110.jsonl
1662993300
Polycarp was given a row of tiles. Each tile contains one lowercase letter of the Latin alphabet. The entire sequence of tiles forms the string $$$s$$$.In other words, you are given a string $$$s$$$ consisting of lowercase Latin letters.Initially, Polycarp is on the first tile of the row and wants to get to the last tile by jumping on the tiles. Jumping from $$$i$$$-th tile to $$$j$$$-th tile has a cost equal to $$$|index(s_i) - index(s_j)|$$$, where $$$index(c)$$$ is the index of the letter $$$c$$$ in the alphabet (for example, $$$index($$$'a'$$$)=1$$$, $$$index($$$'b'$$$)=2$$$, ..., $$$index($$$'z'$$$)=26$$$) .Polycarp wants to get to the $$$n$$$-th tile for the minimum total cost, but at the same time make maximum number of jumps.In other words, among all possible ways to get to the last tile for the minimum total cost, he will choose the one with the maximum number of jumps.Polycarp can visit each tile at most once.Polycarp asks you to help — print the sequence of indices of string $$$s$$$ on which he should jump.
256 megabytes
import javax.print.attribute.IntegerSyntax; import java.util.*; import java.io.*; import java.math.*; import java.text.*; public class Main{ public static void main(String args[]) throws IOException{ Read sc=new Read(); int n=sc.nextInt(); for(int i=0;i<n;i++){ char c[]=sc.next().toCharArray(); char a=c[0],b=c[c.length-1]; List<Integer> list=new ArrayList<>(); for(int j=1;j<c.length-1;j++){ if((c[j]-a)*(c[j]-b)<=0){ list.add(j+1); } } if(a-b>=0){ Collections.sort(list,(l1,l2)->c[l2-1]-c[l1-1]); } else{ Collections.sort(list,(l1,l2)->c[l1-1]-c[l2-1]); } sc.println(Math.abs(a-b)+" "+(list.size()+2)); sc.print("1 "); for(int aa:list){ sc.print(aa+" "); } sc.println(c.length); } //sc.print(0); sc.bw.flush(); sc.bw.close(); } } //记住看数字范围,需要开long吗,需要用BigInteger吗,需要手动处理字符串吗,复杂度数量级控制在1e7或者以下了吗 //开数组的数据范围最高不能超过1e7,数据范围再大就要用哈希表离散化了 //基本数据类型不能自定义sort排序,二维数组就可以了,顺序排序的时候是小减大,注意返回值应该是int class Read{ BufferedReader bf; StringTokenizer st; BufferedWriter bw; public Read(){ bf=new BufferedReader(new InputStreamReader(System.in)); st=new StringTokenizer(""); bw=new BufferedWriter(new OutputStreamWriter(System.out)); } public String nextLine() throws IOException{ return bf.readLine(); } public String next() throws IOException{ while(!st.hasMoreTokens()){ st=new StringTokenizer(bf.readLine()); } return st.nextToken(); } public char nextChar() throws IOException{ //确定下一个token只有一个字符的时候再用 return next().charAt(0); } public int nextInt() throws IOException{ return Integer.parseInt(next()); } public long nextLong() throws IOException{ return Long.parseLong(next()); } public double nextDouble() throws IOException{ return Double.parseDouble(next()); } public float nextFloat() throws IOException{ return Float.parseFloat(next()); } public byte nextByte() throws IOException{ return Byte.parseByte(next()); } public short nextShort() throws IOException{ return Short.parseShort(next()); } public BigInteger nextBigInteger() throws IOException{ return new BigInteger(next()); } public void println(int a) throws IOException{ bw.write(String.valueOf(a)); bw.newLine(); return; } public void print(int a) throws IOException{ bw.write(String.valueOf(a)); return; } public void println(String a) throws IOException{ bw.write(a); bw.newLine(); return; } public void print(String a) throws IOException{ bw.write(a); return; } public void println(long a) throws IOException{ bw.write(String.valueOf(a)); bw.newLine(); return; } public void print(long a) throws IOException{ bw.write(String.valueOf(a)); return; } public void println(double a) throws IOException{ bw.write(String.valueOf(a)); bw.newLine(); return; } public void print(double a) throws IOException{ bw.write(String.valueOf(a)); return; } public void print(BigInteger a) throws IOException{ bw.write(a.toString()); return; } public void print(char a) throws IOException{ bw.write(String.valueOf(a)); return; } public void println(char a) throws IOException{ bw.write(String.valueOf(a)); bw.newLine(); return; } }
Java
["6\n\nlogic\n\ncodeforces\n\nbca\n\naaaaaaaaaaa\n\nadbaadabad\n\nto"]
1 second
["9 4\n1 4 3 5\n16 10\n1 8 3 4 9 5 2 6 7 10\n1 2\n1 3\n0 11\n1 8 10 4 3 5 7 2 9 6 11\n3 10\n1 9 5 4 7 3 8 6 2 10\n5 2\n1 2"]
NoteIn the first test case, the required path corresponds to the picture: In this case, the minimum possible total cost of the path is achieved. Since $$$index($$$'l'$$$)=12$$$, $$$index($$$'o'$$$)=15$$$, $$$index($$$'g'$$$)=7$$$, $$$index($$$'i'$$$)=9$$$, $$$index($$$'c'$$$)=3$$$, then the total cost of the path is $$$|12-9|+|9-7|+|7-3|=3+2+4=9$$$.
Java 17
standard input
[ "constructive algorithms", "strings" ]
d17c9f91504e1d4c4eae7294bf09dcfc
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. Each test case is given by the string $$$s$$$ ($$$2 \le |s| \le 2 \cdot 10^5$$$), where $$$|s|$$$ — is the length of string $$$s$$$. The string $$$s$$$ consists of lowercase Latin letters. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,100
The answer to each test case consists of two lines. In the first line print two integers $$$cost$$$, $$$m$$$, where $$$cost$$$ is the minimum total cost of the path, and $$$m$$$ is the maximum number of visited tiles Polycarp can make to get to $$$n$$$-th tiles for the minimum total cost $$$cost$$$ (i.e. the number of jumps is $$$m-1$$$). In the next line print $$$m$$$ different numbers $$$j_1, j_2, \dots, j_m$$$ ($$$1 \le j_i \le |s|$$$) — the sequence of indices of the tiles Polycarp will jump on. The first number in the sequence must be $$$1$$$ (that is, $$$j_1=1$$$) and the last number must be the value of $$$|s|$$$ (that is, $$$j_m=|s|$$$). If there are multiple answers, print any of them.
standard output
PASSED
de4c4439dbcd4d4b9fd2dd33b1c2c6e6
train_110.jsonl
1662993300
Polycarp was given a row of tiles. Each tile contains one lowercase letter of the Latin alphabet. The entire sequence of tiles forms the string $$$s$$$.In other words, you are given a string $$$s$$$ consisting of lowercase Latin letters.Initially, Polycarp is on the first tile of the row and wants to get to the last tile by jumping on the tiles. Jumping from $$$i$$$-th tile to $$$j$$$-th tile has a cost equal to $$$|index(s_i) - index(s_j)|$$$, where $$$index(c)$$$ is the index of the letter $$$c$$$ in the alphabet (for example, $$$index($$$'a'$$$)=1$$$, $$$index($$$'b'$$$)=2$$$, ..., $$$index($$$'z'$$$)=26$$$) .Polycarp wants to get to the $$$n$$$-th tile for the minimum total cost, but at the same time make maximum number of jumps.In other words, among all possible ways to get to the last tile for the minimum total cost, he will choose the one with the maximum number of jumps.Polycarp can visit each tile at most once.Polycarp asks you to help — print the sequence of indices of string $$$s$$$ on which he should jump.
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; /** * * @author eslam */ public class Solution { // Beginning of the solution static Kattio input = new Kattio(); static BufferedWriter log = new BufferedWriter(new OutputStreamWriter(System.out)); static ArrayList<ArrayList<Integer>> powerSet = new ArrayList<>(); static ArrayList<LinkedList<Integer>> allprem = new ArrayList<>(); static ArrayList<LinkedList<String>> allprems = new ArrayList<>(); static ArrayList<Long> luc = new ArrayList<>(); static long mod = (long) (Math.pow(10, 9) + 7); static int grid[][] = {{0, 0, 1, -1, 1, 1, -1, -1}, {1, -1, 0, 0, 1, -1, 1, -1}}; static int dp[][]; static double cmp = 0.000000001; public static void main(String[] args) throws IOException { // Kattio input = new Kattio("input"); // BufferedWriter log = new BufferedWriter(new FileWriter("output.txt")); int test = input.nextInt(); loop: for (int o = 1; o <= test; o++) { String w = input.next(); ArrayList<Integer> j = new ArrayList<>(); int ans = 0; ArrayList<Integer> fre[] = new ArrayList[26]; for (int i = 0; i < 26; i++) { fre[i] = new ArrayList<>(); } for (int i = 0; i < w.length(); i++) { fre[w.charAt(i) - 'a'].add(i + 1); } if (w.charAt(0) > w.charAt(w.length() - 1)) { int ch = w.charAt(0) - 'a'; ll: for (int i = w.charAt(0) - 'a'; i > -1; i--) { if (!fre[i].isEmpty()) { ans += Math.abs(ch - i); ch = i; for (int k = 0; k < fre[i].size(); k++) { j.add(fre[i].get(k)); if (j.get(j.size() - 1) == w.length()) { break ll; } } } } } else { int ch = w.charAt(0) - 'a'; ll: for (int i = w.charAt(0) - 'a'; i < 26; i++) { if (!fre[i].isEmpty()) { ans += Math.abs(ch - i); ch = i; for (int k = 0; k < fre[i].size(); k++) { j.add(fre[i].get(k)); if (j.get(j.size() - 1) == w.length()) { break ll; } } } } } log.write(ans + " " + j.size() + "\n"); for (Integer x : j) { log.write(x + " "); } log.write("\n"); } log.flush(); } static Comparator<tri> cmpTri() { Comparator<tri> c = new Comparator<tri>() { @Override public int compare(tri o1, tri o2) { if (o1.x > o2.x) { return 1; } else if (o1.x < o2.x) { return -1; } else { if (o1.y > o2.y) { return 1; } else if (o1.y < o2.y) { return -1; } else { if (o1.z > o2.z) { return 1; } else if (o1.z < o2.z) { return -1; } else { return 0; } } } } }; return c; } static Comparator<pair> cmpPair() { Comparator<pair> c = new Comparator<pair>() { @Override public int compare(pair o1, pair o2) { if (o1.x > o2.x) { return 1; } else if (o1.x < o2.x) { return -1; } else { if (o1.y > o2.y) { return 1; } else if (o1.y < o2.y) { return -1; } else { return 0; } } } }; return c; } static class rec { long x1; long x2; long y1; long y2; public rec(long x1, long y1, long x2, long y2) { this.x1 = x1; this.y1 = y1; this.x2 = x2; this.y2 = y2; } public long getArea() { return (x2 - x1) * (y2 - y1); } } static int sumOfRange(int x1, int y1, int x2, int y2, int e, int a[][][]) { return (a[e][x2][y2] - a[e][x1 - 1][y2] - a[e][x2][y1 - 1]) + a[e][x1 - 1][y1 - 1]; } public static int[][] bfs(int i, int j, String w[]) { Queue<pair> q = new ArrayDeque<>(); q.add(new pair(i, j)); int dis[][] = new int[w.length][w[0].length()]; for (int k = 0; k < w.length; k++) { Arrays.fill(dis[k], -1); } dis[i][j] = 0; while (!q.isEmpty()) { pair p = q.poll(); int cost = dis[p.x][p.y]; for (int k = 0; k < 4; k++) { int nx = p.x + grid[0][k]; int ny = p.y + grid[1][k]; if (isValid(nx, ny, w.length, w[0].length())) { if (dis[nx][ny] == -1 && w[nx].charAt(ny) == '.') { q.add(new pair(nx, ny)); dis[nx][ny] = cost + 1; } } } } return dis; } public static void dfs(int node, ArrayList<Integer> a[], boolean vi[]) { vi[node] = true; for (Integer ch : a[node]) { if (!vi[ch]) { dfs(ch, a, vi); } } } public static void graphRepresintion(ArrayList<Integer>[] a, int q) throws IOException { for (int i = 0; i < a.length; i++) { a[i] = new ArrayList<>(); } while (q-- > 0) { int x = input.nextInt(); int y = input.nextInt(); a[x].add(y); a[y].add(x); } } public static boolean isValid(int i, int j, int n, int m) { return (i > -1 && i < n) && (j > -1 && j < m); } // present in the left and right indices public static int[] swap(int data[], int left, int right) { // Swap the data int temp = data[left]; data[left] = data[right]; data[right] = temp; // Return the updated array return data; } // Function to reverse the sub-array // starting from left to the right // both inclusive public static int[] reverse(int data[], int left, int right) { // Reverse the sub-array while (left < right) { int temp = data[left]; data[left++] = data[right]; data[right--] = temp; } // Return the updated array return data; } // Function to find the next permutation // of the given integer array public static boolean findNextPermutation(int data[]) { // If the given dataset is empty // or contains only one element // next_permutation is not possible if (data.length <= 1) { return false; } int last = data.length - 2; // find the longest non-increasing suffix // and find the pivot while (last >= 0) { if (data[last] < data[last + 1]) { break; } last--; } // If there is no increasing pair // there is no higher order permutation if (last < 0) { return false; } int nextGreater = data.length - 1; // Find the rightmost successor to the pivot for (int i = data.length - 1; i > last; i--) { if (data[i] > data[last]) { nextGreater = i; break; } } // Swap the successor and the pivot data = swap(data, nextGreater, last); // Reverse the suffix data = reverse(data, last + 1, data.length - 1); // Return true as the next_permutation is done return true; } public static pair[] dijkstra(int node, ArrayList<pair> a[]) { PriorityQueue<tri> q = new PriorityQueue<>(new Comparator<tri>() { @Override public int compare(tri o1, tri o2) { if (o1.y > o2.y) { return 1; } else if (o1.y < o2.y) { return -1; } else { return 0; } } }); q.add(new tri(node, 0, -1)); pair distance[] = new pair[a.length]; while (!q.isEmpty()) { tri p = q.poll(); int cost = p.y; if (distance[p.x] != null) { continue; } distance[p.x] = new pair(p.z, cost); ArrayList<pair> nodes = a[p.x]; for (pair node1 : nodes) { if (distance[node1.x] == null) { tri pa = new tri(node1.x, cost + node1.y, p.x); q.add(pa); } } } return distance; } public static String revs(String w) { String ans = ""; for (int i = w.length() - 1; i > -1; i--) { ans += w.charAt(i); } return ans; } public static boolean isPalindrome(String w) { for (int i = 0; i < w.length() / 2; i++) { if (w.charAt(i) != w.charAt(w.length() - i - 1)) { return false; } } return true; } public static void getPowerSet(Queue<Integer> a) { int n = a.poll(); if (!a.isEmpty()) { getPowerSet(a); } int s = powerSet.size(); for (int i = 0; i < s; i++) { ArrayList<Integer> ne = new ArrayList<>(); ne.add(n); for (int j = 0; j < powerSet.get(i).size(); j++) { ne.add(powerSet.get(i).get(j)); } powerSet.add(ne); } ArrayList<Integer> p = new ArrayList<>(); p.add(n); powerSet.add(p); } public static int getlo(int va) { int v = 1; while (v <= va) { if ((va&v) != 0) { return v; } v <<= 1; } return 0; } static long fast_pow(long a, long p, long mod) { long res = 1; while (p > 0) { if (p % 2 == 0) { a = (a * a) % mod; p /= 2; } else { res = (res * a) % mod; p--; } } return res; } public static int countPrimeInRange(int n, boolean isPrime[]) { int cnt = 0; Arrays.fill(isPrime, true); for (int i = 2; i * i <= n; i++) { if (isPrime[i]) { for (int j = i * 2; j <= n; j += i) { isPrime[j] = false; } } } for (int i = 2; i <= n; i++) { if (isPrime[i]) { cnt++; } } return cnt; } public static void create(long num) { luc.add(num); if (num > power(10, 9)) { return; } create(num * 10 + 4); create(num * 10 + 7); } public static long ceil(long a, long b) { return (a + b - 1) / b; } public static long round(long a, long b) { if (a < 0) { return (a - b / 2) / b; } return (a + b / 2) / b; } public static void allPremutationsst(LinkedList<String> l, boolean visited[], ArrayList<String> st) { if (l.size() == st.size()) { allprems.add(l); } for (int i = 0; i < st.size(); i++) { if (!visited[i]) { visited[i] = true; LinkedList<String> nl = new LinkedList<>(); for (String x : l) { nl.add(x); } nl.add(st.get(i)); allPremutationsst(nl, visited, st); visited[i] = false; } } } public static void allPremutations(LinkedList<Integer> l, boolean visited[], int a[]) { if (l.size() == a.length) { allprem.add(l); } for (int i = 0; i < a.length; i++) { if (!visited[i]) { visited[i] = true; LinkedList<Integer> nl = new LinkedList<>(); for (Integer x : l) { nl.add(x); } nl.add(a[i]); allPremutations(nl, visited, a); visited[i] = false; } } } public static int binarySearch(long[] a, long value) { int l = 0; int r = a.length - 1; while (l <= r) { int m = (l + r) / 2; if (a[m] == value) { return m; } else if (a[m] > value) { r = m - 1; } else { l = m + 1; } } return -1; } public static void reverse(int l, int r, char ch[]) { for (int i = 0; i < r / 2; i++) { char c = ch[i]; ch[i] = ch[r - i - 1]; ch[r - i - 1] = c; } } public static int logK(long v, long k) { int ans = 0; while (v > 1) { ans++; v /= k; } return ans; } public static long power(long a, long n) { if (n == 1) { return a; } long pow = power(a, n / 2); pow *= pow; if (n % 2 != 0) { pow *= a; } return pow; } public static long get(long max, long x) { if (x == 1) { return max; } int cnt = 0; while (max > 0) { cnt++; max /= x; } return cnt; } public static int numOF0(long v) { long x = 1; int cnt = 0; while (x <= v) { if ((x & v) == 0) { cnt++; } x <<= 1; } return cnt; } public static int log2(double n) { int cnt = 0; while (n > 1) { n /= 2; cnt++; } return cnt; } public static int[] bfs(int node, ArrayList<Integer> a[]) { Queue<Integer> q = new LinkedList<>(); q.add(node); int distances[] = new int[a.length]; Arrays.fill(distances, -1); distances[node] = 0; while (!q.isEmpty()) { int parent = q.poll(); ArrayList<Integer> nodes = a[parent]; int cost = distances[parent]; for (Integer node1 : nodes) { if (distances[node1] == -1) { q.add(node1); distances[node1] = cost + 1; } } } return distances; } public static ArrayList<Integer> primeFactors(int n) { ArrayList<Integer> a = new ArrayList<>(); while (n % 2 == 0) { a.add(2); n /= 2; } for (int i = 3; i <= Math.sqrt(n); i += 2) { while (n % i == 0) { a.add(i); n /= i; } if (n < i) { break; } } if (n > 2) { a.add(n); } return a; } public static ArrayList<Integer> printPrimeFactoriztion(int n) { ArrayList<Integer> a = new ArrayList<>(); for (int i = 1; i < Math.sqrt(n) + 1; i++) { if (n % i == 0) { if (isPrime(i)) { a.add(i); n /= i; i = 0; } else if (isPrime(n / i)) { a.add(n / i); n = i; i = 0; } } } return a; } // end of solution public static BigInteger f(long n) { if (n <= 1) { return BigInteger.ONE; } long t = n - 1; BigInteger b = new BigInteger(t + ""); BigInteger ans = new BigInteger(n + ""); while (t > 1) { ans = ans.multiply(b); b = b.subtract(BigInteger.ONE); t--; } return ans; } public static long factorial(long n) { if (n <= 1) { return 1; } long t = n - 1; while (t > 1) { n = mod((mod(n, mod) * mod(t, mod)), mod); t--; } return n; } public static long rev(long n) { long t = n; long ans = 0; while (t > 0) { ans = ans * 10 + t % 10; t /= 10; } return ans; } public static boolean isPalindrome(int n) { int t = n; int ans = 0; while (t > 0) { ans = ans * 10 + t % 10; t /= 10; } return ans == n; } static class tri { int x, y, z; public tri(int x, int y, int z) { this.x = x; this.y = y; this.z = z; } @Override public String toString() { return x + " " + y + " " + z; } } static boolean isPrime(long num) { if (num == 1) { return false; } if (num == 2) { return true; } if (num % 2 == 0) { return false; } if (num == 3) { return true; } for (int i = 3; i <= Math.sqrt(num) + 1; i += 2) { if (num % i == 0) { return false; } } return true; } public static void prefixSum(int[] a) { for (int i = 1; i < a.length; i++) { a[i] = a[i] + a[i - 1]; } } public static void suffixSum(long[] a) { for (int i = a.length - 2; i > -1; i--) { a[i] = a[i] + a[i + 1]; } } static long mod(long a, long b) { long r = a % b; return r < 0 ? r + b : r; } public static long binaryToDecimal(String w) { long r = 0; long l = 0; for (int i = w.length() - 1; i > -1; i--) { long x = (w.charAt(i) - '0') * (long) Math.pow(2, l); r = r + x; l++; } return r; } public static String decimalToBinary(long n) { String w = ""; while (n > 0) { w = n % 2 + w; n /= 2; } return w; } public static boolean isSorted(int[] a) { for (int i = 0; i < a.length - 1; i++) { if (a[i] >= a[i + 1]) { return false; } } return true; } public static void print(int[] a) throws IOException { for (int i = 0; i < a.length; i++) { log.write(a[i] + " "); } log.write("\n"); } public static void read(int[] a) { for (int i = 0; i < a.length; i++) { a[i] = input.nextInt(); } } static class gepair { long x; long y; public gepair(long x, long y) { this.x = x; this.y = y; } @Override public String toString() { return x + " " + y; } } static class pair { int x; int y; public pair(int x, int y) { this.x = x; this.y = y; } @Override public String toString() { return x + " " + y; } } static class pai { long x; int y; public pai(long x, int y) { this.x = x; this.y = y; } @Override public String toString() { return x + " " + y; } } public static long LCM(long x, long y) { return x / GCD(x, y) * y; } public static long GCD(long x, long y) { if (y == 0) { return x; } return GCD(y, x % y); } public static void simplifyTheFraction(int a, int b) { long GCD = GCD(a, b); System.out.println(a / GCD + " " + b / GCD); } 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 String nextLine() { String str = ""; try { str = r.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } 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
["6\n\nlogic\n\ncodeforces\n\nbca\n\naaaaaaaaaaa\n\nadbaadabad\n\nto"]
1 second
["9 4\n1 4 3 5\n16 10\n1 8 3 4 9 5 2 6 7 10\n1 2\n1 3\n0 11\n1 8 10 4 3 5 7 2 9 6 11\n3 10\n1 9 5 4 7 3 8 6 2 10\n5 2\n1 2"]
NoteIn the first test case, the required path corresponds to the picture: In this case, the minimum possible total cost of the path is achieved. Since $$$index($$$'l'$$$)=12$$$, $$$index($$$'o'$$$)=15$$$, $$$index($$$'g'$$$)=7$$$, $$$index($$$'i'$$$)=9$$$, $$$index($$$'c'$$$)=3$$$, then the total cost of the path is $$$|12-9|+|9-7|+|7-3|=3+2+4=9$$$.
Java 17
standard input
[ "constructive algorithms", "strings" ]
d17c9f91504e1d4c4eae7294bf09dcfc
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. Each test case is given by the string $$$s$$$ ($$$2 \le |s| \le 2 \cdot 10^5$$$), where $$$|s|$$$ — is the length of string $$$s$$$. The string $$$s$$$ consists of lowercase Latin letters. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,100
The answer to each test case consists of two lines. In the first line print two integers $$$cost$$$, $$$m$$$, where $$$cost$$$ is the minimum total cost of the path, and $$$m$$$ is the maximum number of visited tiles Polycarp can make to get to $$$n$$$-th tiles for the minimum total cost $$$cost$$$ (i.e. the number of jumps is $$$m-1$$$). In the next line print $$$m$$$ different numbers $$$j_1, j_2, \dots, j_m$$$ ($$$1 \le j_i \le |s|$$$) — the sequence of indices of the tiles Polycarp will jump on. The first number in the sequence must be $$$1$$$ (that is, $$$j_1=1$$$) and the last number must be the value of $$$|s|$$$ (that is, $$$j_m=|s|$$$). If there are multiple answers, print any of them.
standard output
PASSED
90d2129beb701219eb2842d4867b29d7
train_110.jsonl
1662993300
Polycarp was given a row of tiles. Each tile contains one lowercase letter of the Latin alphabet. The entire sequence of tiles forms the string $$$s$$$.In other words, you are given a string $$$s$$$ consisting of lowercase Latin letters.Initially, Polycarp is on the first tile of the row and wants to get to the last tile by jumping on the tiles. Jumping from $$$i$$$-th tile to $$$j$$$-th tile has a cost equal to $$$|index(s_i) - index(s_j)|$$$, where $$$index(c)$$$ is the index of the letter $$$c$$$ in the alphabet (for example, $$$index($$$'a'$$$)=1$$$, $$$index($$$'b'$$$)=2$$$, ..., $$$index($$$'z'$$$)=26$$$) .Polycarp wants to get to the $$$n$$$-th tile for the minimum total cost, but at the same time make maximum number of jumps.In other words, among all possible ways to get to the last tile for the minimum total cost, he will choose the one with the maximum number of jumps.Polycarp can visit each tile at most once.Polycarp asks you to help — print the sequence of indices of string $$$s$$$ on which he should jump.
256 megabytes
import java.io.*; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.StringTokenizer; public class codeforces_820_C { private static void solve(FastIOAdapter in, PrintWriter out) { char[] s = in.next().toCharArray(); var inds = new ArrayList<int[]>(); inds.add(new int[]{1, s[0]}); int min = Math.min(s[0], s[s.length - 1]); int max = Math.max(s[0], s[s.length - 1]); for (int i = 1; i < s.length - 1; i++) { if (s[i] <= max && s[i] >= min) inds.add(new int[]{i + 1, s[i]}); } inds.add(new int[]{s.length, s[s.length - 1]}); if (min == s[0]) inds.sort(Comparator.comparingInt(x -> x[1])); else inds.sort((x, y) -> Integer.compare(y[1], x[1])); out.println(max - min + " " + inds.size()); for (int[] ind : inds) out.print(ind[0] + " "); out.println(); } public static void main(String[] args) throws Exception { try (FastIOAdapter ioAdapter = new FastIOAdapter()) { int count = 1; count = ioAdapter.nextInt(); while (count-- > 0) { solve(ioAdapter, ioAdapter.out); } } } static class FastIOAdapter implements AutoCloseable { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); public PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter((System.out)))); StringTokenizer st = new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } String nextLine() { try { return br.readLine(); } catch (IOException e) { e.printStackTrace(); return null; } } int nextInt() { return Integer.parseInt(next()); } int[] readArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } long[] readArrayLong(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } long nextLong() { return Long.parseLong(next()); } @Override public void close() throws Exception { out.flush(); out.close(); br.close(); } } }
Java
["6\n\nlogic\n\ncodeforces\n\nbca\n\naaaaaaaaaaa\n\nadbaadabad\n\nto"]
1 second
["9 4\n1 4 3 5\n16 10\n1 8 3 4 9 5 2 6 7 10\n1 2\n1 3\n0 11\n1 8 10 4 3 5 7 2 9 6 11\n3 10\n1 9 5 4 7 3 8 6 2 10\n5 2\n1 2"]
NoteIn the first test case, the required path corresponds to the picture: In this case, the minimum possible total cost of the path is achieved. Since $$$index($$$'l'$$$)=12$$$, $$$index($$$'o'$$$)=15$$$, $$$index($$$'g'$$$)=7$$$, $$$index($$$'i'$$$)=9$$$, $$$index($$$'c'$$$)=3$$$, then the total cost of the path is $$$|12-9|+|9-7|+|7-3|=3+2+4=9$$$.
Java 17
standard input
[ "constructive algorithms", "strings" ]
d17c9f91504e1d4c4eae7294bf09dcfc
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. Each test case is given by the string $$$s$$$ ($$$2 \le |s| \le 2 \cdot 10^5$$$), where $$$|s|$$$ — is the length of string $$$s$$$. The string $$$s$$$ consists of lowercase Latin letters. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,100
The answer to each test case consists of two lines. In the first line print two integers $$$cost$$$, $$$m$$$, where $$$cost$$$ is the minimum total cost of the path, and $$$m$$$ is the maximum number of visited tiles Polycarp can make to get to $$$n$$$-th tiles for the minimum total cost $$$cost$$$ (i.e. the number of jumps is $$$m-1$$$). In the next line print $$$m$$$ different numbers $$$j_1, j_2, \dots, j_m$$$ ($$$1 \le j_i \le |s|$$$) — the sequence of indices of the tiles Polycarp will jump on. The first number in the sequence must be $$$1$$$ (that is, $$$j_1=1$$$) and the last number must be the value of $$$|s|$$$ (that is, $$$j_m=|s|$$$). If there are multiple answers, print any of them.
standard output
PASSED
37efa81eb326910c8ca23c5363a98c3e
train_110.jsonl
1662993300
Polycarp was given a row of tiles. Each tile contains one lowercase letter of the Latin alphabet. The entire sequence of tiles forms the string $$$s$$$.In other words, you are given a string $$$s$$$ consisting of lowercase Latin letters.Initially, Polycarp is on the first tile of the row and wants to get to the last tile by jumping on the tiles. Jumping from $$$i$$$-th tile to $$$j$$$-th tile has a cost equal to $$$|index(s_i) - index(s_j)|$$$, where $$$index(c)$$$ is the index of the letter $$$c$$$ in the alphabet (for example, $$$index($$$'a'$$$)=1$$$, $$$index($$$'b'$$$)=2$$$, ..., $$$index($$$'z'$$$)=26$$$) .Polycarp wants to get to the $$$n$$$-th tile for the minimum total cost, but at the same time make maximum number of jumps.In other words, among all possible ways to get to the last tile for the minimum total cost, he will choose the one with the maximum number of jumps.Polycarp can visit each tile at most once.Polycarp asks you to help — print the sequence of indices of string $$$s$$$ on which he should jump.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; public class Main { // static int[] prime = new int[100001]; 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){ String str = in.next(); int n = str.length(); final int s = Math.min(str.charAt(0) - 'a', str.charAt(n-1) - 'a'), e = Math.max(str.charAt(0) - 'a', str.charAt(n-1) - 'a'); ArrayList<Data> arr = new ArrayList<>(); for(int i = 0; i < n; i++){ int k = str.charAt(i) - 'a'; if(k >= s && k <= e){ arr.add(new Data(k, i)); } } if(str.charAt(0) - 'a' >= str.charAt(n-1) - 'a'){ Collections.sort(arr, (a, b) -> b.i - a.i); }else{ Collections.sort(arr, (a, b) -> a.i - b.i); } out.println((e-s) + " " + (arr.size())); for(Data d: arr){ out.print((d.ind+1) + " "); } out.println(); } out.flush(); } static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } 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 Segment { int[] a; final int n; Segment(int n){ this.n = n; a = new int[4*n]; Arrays.fill(a, Integer.MIN_VALUE); } void set(int index, int val){ set(0, n-1, 0, index, val); } private void set(int s, int e, int ind, int index, int val) { if(s == e){ a[ind] = val; return; } int mid = (s+e)/2; if(mid <= index){ set(s, mid, 2*ind+1, index, val); }else{ set(mid+1, e, 2*ind+2, index, val); } a[ind] = Math.max(a[2*ind+1], a[2*ind+2]); } int get(int l, int h){ return get(0, n-1, l, h, 0); } private int get(int s, int e, int l, int h, int ind) { if(s >= l && e <= h){ return a[ind]; } if(s > h || e < l){ return Integer.MIN_VALUE; } int mid = (s+e)/2; return Math.max(get(s, mid, l, h, 2*ind+1), get(mid+1, e, l, h, 2*ind+2)); } } class Data{ int i, ind; public Data(int i, int ind) { this.i = i; 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
["6\n\nlogic\n\ncodeforces\n\nbca\n\naaaaaaaaaaa\n\nadbaadabad\n\nto"]
1 second
["9 4\n1 4 3 5\n16 10\n1 8 3 4 9 5 2 6 7 10\n1 2\n1 3\n0 11\n1 8 10 4 3 5 7 2 9 6 11\n3 10\n1 9 5 4 7 3 8 6 2 10\n5 2\n1 2"]
NoteIn the first test case, the required path corresponds to the picture: In this case, the minimum possible total cost of the path is achieved. Since $$$index($$$'l'$$$)=12$$$, $$$index($$$'o'$$$)=15$$$, $$$index($$$'g'$$$)=7$$$, $$$index($$$'i'$$$)=9$$$, $$$index($$$'c'$$$)=3$$$, then the total cost of the path is $$$|12-9|+|9-7|+|7-3|=3+2+4=9$$$.
Java 17
standard input
[ "constructive algorithms", "strings" ]
d17c9f91504e1d4c4eae7294bf09dcfc
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. Each test case is given by the string $$$s$$$ ($$$2 \le |s| \le 2 \cdot 10^5$$$), where $$$|s|$$$ — is the length of string $$$s$$$. The string $$$s$$$ consists of lowercase Latin letters. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,100
The answer to each test case consists of two lines. In the first line print two integers $$$cost$$$, $$$m$$$, where $$$cost$$$ is the minimum total cost of the path, and $$$m$$$ is the maximum number of visited tiles Polycarp can make to get to $$$n$$$-th tiles for the minimum total cost $$$cost$$$ (i.e. the number of jumps is $$$m-1$$$). In the next line print $$$m$$$ different numbers $$$j_1, j_2, \dots, j_m$$$ ($$$1 \le j_i \le |s|$$$) — the sequence of indices of the tiles Polycarp will jump on. The first number in the sequence must be $$$1$$$ (that is, $$$j_1=1$$$) and the last number must be the value of $$$|s|$$$ (that is, $$$j_m=|s|$$$). If there are multiple answers, print any of them.
standard output
PASSED
184aa01bc46a97828ad537c3621346a7
train_110.jsonl
1662993300
Polycarp was given a row of tiles. Each tile contains one lowercase letter of the Latin alphabet. The entire sequence of tiles forms the string $$$s$$$.In other words, you are given a string $$$s$$$ consisting of lowercase Latin letters.Initially, Polycarp is on the first tile of the row and wants to get to the last tile by jumping on the tiles. Jumping from $$$i$$$-th tile to $$$j$$$-th tile has a cost equal to $$$|index(s_i) - index(s_j)|$$$, where $$$index(c)$$$ is the index of the letter $$$c$$$ in the alphabet (for example, $$$index($$$'a'$$$)=1$$$, $$$index($$$'b'$$$)=2$$$, ..., $$$index($$$'z'$$$)=26$$$) .Polycarp wants to get to the $$$n$$$-th tile for the minimum total cost, but at the same time make maximum number of jumps.In other words, among all possible ways to get to the last tile for the minimum total cost, he will choose the one with the maximum number of jumps.Polycarp can visit each tile at most once.Polycarp asks you to help — print the sequence of indices of string $$$s$$$ on which he should jump.
256 megabytes
import static java.lang.Math.max; import static java.lang.Math.min; import static java.lang.Math.abs; import java.util.*; import java.io.*; import java.math.*; /** * * @Har_Har_Mahadev */ public class C { public static void process() throws IOException { String s = sc.next(); int n = s.length(); ArrayList<Integer> lis[] = new ArrayList[30]; for(int i =0; i<30; i++)lis[i] = new ArrayList<Integer>(); for(int i = 0; i<n; i++) { lis[s.charAt(i)-'a'].add(i+1); } int curr = s.charAt(0)-'a'; int last = s.charAt(n-1) - 'a'; ArrayList<Integer> jump = new ArrayList<Integer>(); if(curr <= last) { for(int i = curr; i<=last; i++) { for(int e : lis[i])jump.add(e); } } else { for(int i = curr; i>=last; i--) { for(int e : lis[i])jump.add(e); } } out.println(abs(s.charAt(0) - s.charAt(n-1)) + " "+ jump.size()); for(int e : jump)out.print(e+" "); out.println(); } //============================================================================= //--------------------------The End--------------------------------- //============================================================================= private static long INF = 2000000000000000000L, M = 1000000007, MM = 998244353; private static int N = 0; private static void google(int tt) { System.out.print("Case #" + (tt) + ": "); } static FastScanner sc; static FastWriter out; public static void main(String[] args) throws IOException { boolean oj = true; if (oj) { sc = new FastScanner(); out = new FastWriter(System.out); } else { sc = new FastScanner("input.txt"); out = new FastWriter("output.txt"); } long s = System.currentTimeMillis(); int t = 1; t = sc.nextInt(); int TTT = 1; while (t-- > 0) { // google(TTT++); process(); } out.flush(); // tr(System.currentTimeMillis()-s+"ms"); } private static boolean oj = System.getProperty("ONLINE_JUDGE") != null; private static void tr(Object... o) { if (!oj) System.err.println(Arrays.deepToString(o)); } static class Pair implements Comparable<Pair> { int x, y; Pair(int x, int y) { this.x = x; this.y = y; } @Override public int compareTo(Pair o) { return Integer.compare(this.x, o.x); } /* @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Pair)) return false; Pair key = (Pair) o; return x == key.x && y == key.y; } @Override public int hashCode() { int result = x; result = 31 * result + y; return result; } */ } ///////////////////////////////////////////////////////////////////////////////////////////////////////// static int ceil(int x, int y) { return (x % y == 0 ? x / y : (x / y + 1)); } static long ceil(long x, long y) { return (x % y == 0 ? x / y : (x / y + 1)); } static long sqrt(long z) { long sqz = (long) Math.sqrt(z); while (sqz * 1L * sqz < z) { sqz++; } while (sqz * 1L * sqz > z) { sqz--; } return sqz; } static int log2(int N) { int result = (int) (Math.log(N) / Math.log(2)); return result; } public static long gcd(long a, long b) { if (a > b) a = (a + b) - (b = a); if (a == 0L) return b; return gcd(b % a, a); } public static long lcm(long a, long b) { return (a * b) / gcd(a, b); } public static int lower_bound(int[] arr, int x) { int low = 0, high = arr.length - 1, mid = -1; int ans = -1; while (low <= high) { mid = (low + high) / 2; if (arr[mid] > x) { high = mid - 1; } else { ans = mid; low = mid + 1; } } return ans; } public static int upper_bound(int[] arr, int x) { int low = 0, high = arr.length - 1, mid = -1; int ans = arr.length; while (low < high) { mid = (low + high) / 2; if (arr[mid] >= x) { ans = mid; high = mid - 1; } else { low = mid + 1; } } return ans; } static void ruffleSort(int[] a) { Random get = new Random(); for (int i = 0; i < a.length; i++) { int r = get.nextInt(a.length); int temp = a[i]; a[i] = a[r]; a[r] = temp; } Arrays.sort(a); } static void ruffleSort(long[] a) { Random get = new Random(); for (int i = 0; i < a.length; i++) { int r = get.nextInt(a.length); long temp = a[i]; a[i] = a[r]; a[r] = temp; } Arrays.sort(a); } static void reverseArray(int[] a) { int n = a.length; int arr[] = new int[n]; for (int i = 0; i < n; i++) arr[i] = a[n - i - 1]; for (int i = 0; i < n; i++) a[i] = arr[i]; } static void reverseArray(long[] a) { int n = a.length; long arr[] = new long[n]; for (int i = 0; i < n; i++) arr[i] = a[n - i - 1]; for (int i = 0; i < n; i++) a[i] = arr[i]; } //custom multiset (replace with HashMap if needed) public static void push(TreeMap<Integer, Integer> map, int k, int v) { //map[k] += v; if (!map.containsKey(k)) map.put(k, v); else map.put(k, map.get(k) + v); } public static void pull(TreeMap<Integer, Integer> map, int k, int v) { //assumes map[k] >= v //map[k] -= v int lol = map.get(k); if (lol == v) map.remove(k); else map.put(k, lol - v); } // compress Big value to Time Limit public static int[] compress(int[] arr) { ArrayList<Integer> ls = new ArrayList<Integer>(); for (int x : arr) ls.add(x); Collections.sort(ls); HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); int boof = 1; //min value for (int x : ls) if (!map.containsKey(x)) map.put(x, boof++); int[] brr = new int[arr.length]; for (int i = 0; i < arr.length; i++) brr[i] = map.get(arr[i]); return brr; } // Fast Writer public static class FastWriter { private static final int BUF_SIZE = 1 << 13; private final byte[] buf = new byte[BUF_SIZE]; private final OutputStream out; private int ptr = 0; private FastWriter() { out = null; } public FastWriter(OutputStream os) { this.out = os; } public FastWriter(String path) { try { this.out = new FileOutputStream(path); } catch (FileNotFoundException e) { throw new RuntimeException("FastWriter"); } } public FastWriter write(byte b) { buf[ptr++] = b; if (ptr == BUF_SIZE) innerflush(); return this; } public FastWriter write(char c) { return write((byte) c); } public FastWriter write(char[] s) { for (char c : s) { buf[ptr++] = (byte) c; if (ptr == BUF_SIZE) innerflush(); } return this; } public FastWriter write(String s) { s.chars().forEach(c -> { buf[ptr++] = (byte) c; if (ptr == BUF_SIZE) innerflush(); }); return this; } private static int countDigits(int l) { if (l >= 1000000000) return 10; if (l >= 100000000) return 9; if (l >= 10000000) return 8; if (l >= 1000000) return 7; if (l >= 100000) return 6; if (l >= 10000) return 5; if (l >= 1000) return 4; if (l >= 100) return 3; if (l >= 10) return 2; return 1; } public FastWriter write(int x) { if (x == Integer.MIN_VALUE) { return write((long) x); } if (ptr + 12 >= BUF_SIZE) innerflush(); if (x < 0) { write((byte) '-'); x = -x; } int d = countDigits(x); for (int i = ptr + d - 1; i >= ptr; i--) { buf[i] = (byte) ('0' + x % 10); x /= 10; } ptr += d; return this; } private static int countDigits(long l) { if (l >= 1000000000000000000L) return 19; if (l >= 100000000000000000L) return 18; if (l >= 10000000000000000L) return 17; if (l >= 1000000000000000L) return 16; if (l >= 100000000000000L) return 15; if (l >= 10000000000000L) return 14; if (l >= 1000000000000L) return 13; if (l >= 100000000000L) return 12; if (l >= 10000000000L) return 11; if (l >= 1000000000L) return 10; if (l >= 100000000L) return 9; if (l >= 10000000L) return 8; if (l >= 1000000L) return 7; if (l >= 100000L) return 6; if (l >= 10000L) return 5; if (l >= 1000L) return 4; if (l >= 100L) return 3; if (l >= 10L) return 2; return 1; } public FastWriter write(long x) { if (x == Long.MIN_VALUE) { return write("" + x); } if (ptr + 21 >= BUF_SIZE) innerflush(); if (x < 0) { write((byte) '-'); x = -x; } int d = countDigits(x); for (int i = ptr + d - 1; i >= ptr; i--) { buf[i] = (byte) ('0' + x % 10); x /= 10; } ptr += d; return this; } public FastWriter write(double x, int precision) { if (x < 0) { write('-'); x = -x; } x += Math.pow(10, -precision) / 2; // if(x < 0){ x = 0; } write((long) x).write("."); x -= (long) x; for (int i = 0; i < precision; i++) { x *= 10; write((char) ('0' + (int) x)); x -= (int) x; } return this; } public FastWriter writeln(char c) { return write(c).writeln(); } public FastWriter writeln(int x) { return write(x).writeln(); } public FastWriter writeln(long x) { return write(x).writeln(); } public FastWriter writeln(double x, int precision) { return write(x, precision).writeln(); } public FastWriter write(int... xs) { boolean first = true; for (int x : xs) { if (!first) write(' '); first = false; write(x); } return this; } public FastWriter write(long... xs) { boolean first = true; for (long x : xs) { if (!first) write(' '); first = false; write(x); } return this; } public FastWriter writeln() { return write((byte) '\n'); } public FastWriter writeln(int... xs) { return write(xs).writeln(); } public FastWriter writeln(long... xs) { return write(xs).writeln(); } public FastWriter writeln(char[] line) { return write(line).writeln(); } public FastWriter writeln(char[]... map) { for (char[] line : map) write(line).writeln(); return this; } public FastWriter writeln(String s) { return write(s).writeln(); } private void innerflush() { try { out.write(buf, 0, ptr); ptr = 0; } catch (IOException e) { throw new RuntimeException("innerflush"); } } public void flush() { innerflush(); try { out.flush(); } catch (IOException e) { throw new RuntimeException("flush"); } } public FastWriter print(byte b) { return write(b); } public FastWriter print(char c) { return write(c); } public FastWriter print(char[] s) { return write(s); } public FastWriter print(String s) { return write(s); } public FastWriter print(int x) { return write(x); } public FastWriter print(long x) { return write(x); } public FastWriter print(double x, int precision) { return write(x, precision); } public FastWriter println(char c) { return writeln(c); } public FastWriter println(int x) { return writeln(x); } public FastWriter println(long x) { return writeln(x); } public FastWriter println(double x, int precision) { return writeln(x, precision); } public FastWriter print(int... xs) { return write(xs); } public FastWriter print(long... xs) { return write(xs); } public FastWriter println(int... xs) { return writeln(xs); } public FastWriter println(long... xs) { return writeln(xs); } public FastWriter println(char[] line) { return writeln(line); } public FastWriter println(char[]... map) { return writeln(map); } public FastWriter println(String s) { return writeln(s); } public FastWriter println() { return writeln(); } } // Fast Inputs static class FastScanner { //I don't understand how this works lmao private int BS = 1 << 16; private char NC = (char) 0; private byte[] buf = new byte[BS]; private int bId = 0, size = 0; private char c = NC; private double cnt = 1; private BufferedInputStream in; public FastScanner() { in = new BufferedInputStream(System.in, BS); } public FastScanner(String s) { try { in = new BufferedInputStream(new FileInputStream(new File(s)), BS); } catch (Exception e) { in = new BufferedInputStream(System.in, BS); } } private char getChar() { while (bId == size) { try { size = in.read(buf); } catch (Exception e) { return NC; } if (size == -1) return NC; bId = 0; } return (char) buf[bId++]; } public int nextInt() { return (int) nextLong(); } public int[] readArray(int N) { int[] res = new int[N]; for (int i = 0; i < N; i++) { res[i] = (int) nextLong(); } return res; } public long[] readArrayLong(int N) { long[] res = new long[N]; for (int i = 0; i < N; i++) { res[i] = nextLong(); } return res; } public int[][] readArrayMatrix(int N, int M, int Index) { if (Index == 0) { int[][] res = new int[N][M]; for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) res[i][j] = (int) nextLong(); } return res; } int[][] res = new int[N][M]; for (int i = 1; i <= N; i++) { for (int j = 1; j <= M; j++) res[i][j] = (int) nextLong(); } return res; } public long[][] readArrayMatrixLong(int N, int M, int Index) { if (Index == 0) { long[][] res = new long[N][M]; for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) res[i][j] = nextLong(); } return res; } long[][] res = new long[N][M]; for (int i = 1; i <= N; i++) { for (int j = 1; j <= M; j++) res[i][j] = nextLong(); } return res; } public long nextLong() { cnt = 1; boolean neg = false; if (c == NC) c = getChar(); for (; (c < '0' || c > '9'); c = getChar()) { if (c == '-') neg = true; } long res = 0; for (; c >= '0' && c <= '9'; c = getChar()) { res = (res << 3) + (res << 1) + c - '0'; cnt *= 10; } return neg ? -res : res; } public double nextDouble() { double cur = nextLong(); return c != '.' ? cur : cur + nextLong() / cnt; } public double[] readArrayDouble(int N) { double[] res = new double[N]; for (int i = 0; i < N; i++) { res[i] = nextDouble(); } return res; } public String next() { StringBuilder res = new StringBuilder(); while (c <= 32) c = getChar(); while (c > 32) { res.append(c); c = getChar(); } return res.toString(); } public String nextLine() { StringBuilder res = new StringBuilder(); while (c <= 32) c = getChar(); while (c != '\n') { res.append(c); c = getChar(); } return res.toString(); } public boolean hasNext() { if (c > 32) return true; while (true) { c = getChar(); if (c == NC) return false; else if (c > 32) return true; } } } }
Java
["6\n\nlogic\n\ncodeforces\n\nbca\n\naaaaaaaaaaa\n\nadbaadabad\n\nto"]
1 second
["9 4\n1 4 3 5\n16 10\n1 8 3 4 9 5 2 6 7 10\n1 2\n1 3\n0 11\n1 8 10 4 3 5 7 2 9 6 11\n3 10\n1 9 5 4 7 3 8 6 2 10\n5 2\n1 2"]
NoteIn the first test case, the required path corresponds to the picture: In this case, the minimum possible total cost of the path is achieved. Since $$$index($$$'l'$$$)=12$$$, $$$index($$$'o'$$$)=15$$$, $$$index($$$'g'$$$)=7$$$, $$$index($$$'i'$$$)=9$$$, $$$index($$$'c'$$$)=3$$$, then the total cost of the path is $$$|12-9|+|9-7|+|7-3|=3+2+4=9$$$.
Java 17
standard input
[ "constructive algorithms", "strings" ]
d17c9f91504e1d4c4eae7294bf09dcfc
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. Each test case is given by the string $$$s$$$ ($$$2 \le |s| \le 2 \cdot 10^5$$$), where $$$|s|$$$ — is the length of string $$$s$$$. The string $$$s$$$ consists of lowercase Latin letters. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,100
The answer to each test case consists of two lines. In the first line print two integers $$$cost$$$, $$$m$$$, where $$$cost$$$ is the minimum total cost of the path, and $$$m$$$ is the maximum number of visited tiles Polycarp can make to get to $$$n$$$-th tiles for the minimum total cost $$$cost$$$ (i.e. the number of jumps is $$$m-1$$$). In the next line print $$$m$$$ different numbers $$$j_1, j_2, \dots, j_m$$$ ($$$1 \le j_i \le |s|$$$) — the sequence of indices of the tiles Polycarp will jump on. The first number in the sequence must be $$$1$$$ (that is, $$$j_1=1$$$) and the last number must be the value of $$$|s|$$$ (that is, $$$j_m=|s|$$$). If there are multiple answers, print any of them.
standard output
PASSED
0c5bf6a28bcdbda9b57cd0d36e4688b4
train_110.jsonl
1662993300
Given the string $$$s$$$ of decimal digits (0-9) of length $$$n$$$.A substring is a sequence of consecutive characters of a string. The substring of this string is defined by a pair of indexes — with its left and right ends. So, each pair of indexes ($$$l, r$$$), where $$$1 \le l \le r \le n$$$, corresponds to a substring of the string $$$s$$$. We will define as $$$v(l,r)$$$ the numeric value of the corresponding substring (leading zeros are allowed in it).For example, if $$$n=7$$$, $$$s=$$$"1003004", then $$$v(1,3)=100$$$, $$$v(2,3)=0$$$ and $$$v(2,7)=3004$$$.You are given $$$n$$$, $$$s$$$ and an integer $$$w$$$ ($$$1 \le w &lt; n$$$).You need to process $$$m$$$ queries, each of which is characterized by $$$3$$$ numbers $$$l_i, r_i, k_i$$$ ($$$1 \le l_i \le r_i \le n; 0 \le k_i \le 8$$$).The answer to the $$$i$$$th query is such a pair of substrings of length $$$w$$$ that if we denote them as $$$(L_1, L_1+w-1)$$$ and $$$(L_2, L_2+w-1)$$$, then: $$$L_1 \ne L_2$$$, that is, the substrings are different; the remainder of dividing a number $$$v(L_1, L_1+w-1) \cdot v(l_i, r_i) + v(L_2, L_2 + w - 1)$$$ by $$$9$$$ is equal to $$$k_i$$$. If there are many matching substring pairs, then find a pair where $$$L_1$$$ is as small as possible. If there are many matching pairs in this case, then minimize $$$L_2$$$.Note that the answer may not exist.
256 megabytes
import java.io.*; import java.util.*; public class ProblemD { static ArrayList<Integer>res ; public static void main(String[] args) throws Exception { Scanner in = new Scanner(); StringBuilder sb = new StringBuilder(); int test = in.readInt(); Comparator<Pair>cmp = new Comparator<Pair>(){ @Override public int compare(Pair a, Pair b) { return a.x == b.x? a.y-b.y:a.x-b.x; } }; while(test-->0){ char c[] = in.readLine().toCharArray(); int n = c.length; int w = in.readInt();int m = in.readInt(); int pref[] = new int[n]; ArrayList<Integer>li[] = new ArrayList[10]; for(int i = 0;i<10;i++)li[i] = new ArrayList<>(); for(int i = 0;i<n;i++){ pref[i] = c[i]-'0'; if(i-1>=0){ pref[i] = (pref[i-1]+pref[i]); } } for(int i =0;i+w-1<n;i++){ int sum = pref[i+w-1]-(i-1>=0?pref[i-1]:0); sum%=9; if(li[sum].size()<=1){ li[sum].add(i); } } ArrayList<Pair> p = new ArrayList<>(); while(m-->0){ int l = in.readInt()-1;int r = in.readInt()-1; int k = in.readInt(); int v = (pref[r] - (l-1>=0?pref[l-1]:0))%9; int l1 = 300000,l2 = 300000; for(int i = 0;i<=8;i++){ int req = k - ((v*i)%9); if(req<0)req+=9; if(req == i && li[req].size()>=2){ p.clear(); p.add(new Pair(l1,l2)); l1 = li[req].get(0); l2 = li[req].get(1); p.add(new Pair(l1,l2)); Collections.sort(p,cmp); l1 = p.get(0).x;l2= p.get(0).y; }else if(req != i && li[req].size()> 0 && li[i].size() >0){ p.clear(); p.add(new Pair(l1,l2)); l1 = li[i].get(0); l2 = li[req].get(0); p.add(new Pair(l1,l2)); Collections.sort(p,cmp); l1 = p.get(0).x;l2= p.get(0).y; } } if(l1 == 300000)l1=l2=-2; sb.append((l1+1)+" "+(l2+1)+"\n"); } } System.out.println(sb); } public static int min(int a,int b,int c){ int first = a-c-1; if(first<0)first+=c; System.out.println(Math.abs(b-a-1)+" "+" "+a+" "+b+" "+(c-1)); return Math.min(Math.min(Math.abs(b-a-1), Math.abs(c-b-1)),a-1); } public static long go(int flag, LinkedList<Integer>ll[]){ int t = flag^1; LinkedList<Integer>l[] = new LinkedList[2]; for(int i = 0;i<2;i++){ l[i] = new LinkedList<>(); for(int it:ll[i])l[i].add(it); } long ans = l[flag].size()>0?l[flag].remove():-1; flag^=1; for(int i = 0;;i++){ if(l[flag].size() == 0 || ans == -1)break; if(l[flag].size()>0)ans+=2*l[flag].removeLast(); flag^=1; } while(l[0].size()>0)ans+=l[0].remove(); while(l[1].size()>0)ans+=l[1].remove(); return ans; } public static boolean vis(boolean vis[][]){ boolean ok = true; int n = vis.length,m = vis[0].length; for(int i = 0;i<n;i++){ for(int j = 0;j<m;j++){ ok&=vis[i][j]; } } return ok; } public static int begin(ArrayList<Pair>list,int l,int r,long target){ int index = -1; while(l<=r){ int mid = (l+r)/2; if(list.get(mid).y - list.get(mid).x >= target){ index = mid; l = mid+1; }else { r = mid-1; } } return index; } public static void build(int seg[],int ind,int l,int r,int a[]){ if(l == r){ seg[ind] = a[l]; return; } int mid = (l+r)/2; build(seg,(2*ind)+1,l,mid,a); build(seg,(2*ind)+2,mid+1,r,a); seg[ind] = Math.min(seg[(2*ind)+1],seg[(2*ind)+2]); } public static long gcd(long a, long b){ return b ==0 ?a:gcd(b,a%b); } public static long nearest(TreeSet<Long> list,long target){ long nearest = -1,sofar = Integer.MAX_VALUE; for(long it:list){ if(Math.abs(it - target)<sofar){ sofar = Math.abs(it - target); nearest = it; } } return nearest; } public static ArrayList<Long> factors(long n){ ArrayList<Long>l = new ArrayList<>(); for(long i = 1;i*i<=n;i++){ if(n%i == 0){ l.add(i); if(n/i != i)l.add(n/i); } } Collections.sort(l); return l; } public static void swap(int a[],int i, int j){ int t = a[i]; a[i] = a[j]; a[j] = t; } public static boolean isSorted(long a[]){ for(int i =0;i<a.length;i++){ if(i+1<a.length && a[i]>a[i+1])return false; } return true; } public static int first(ArrayList<Long>list,long target){ int index = -1; int l = 0,r = list.size()-1; while(l<=r){ int mid = (l+r)/2; if(list.get(mid) == target){ index = mid; r = mid-1; }else if(list.get(mid)>target){ r = mid-1; }else l = mid+1; } return index; } public static int last(ArrayList<Long>list,long target){ int index = -1; int l = 0,r = list.size()-1; while(l<=r){ int mid = (l+r)/2; if(list.get(mid) == target){ index= mid; l = mid+1; }else if(list.get(mid)<target){ l = mid+1; }else r = mid-1; } return index; } public static void sort(int arr[]){ ArrayList<Integer>list = new ArrayList<>(); for(int it:arr)list.add(it); Collections.sort(list); for(int i = 0;i<arr.length;i++)arr[i] = list.get(i); } static class Pair{ int x,y; public Pair(int x,int y){ this.x = x; this.y = y; } } static class Scanner{ BufferedReader br; StringTokenizer st; public Scanner(){ br = new BufferedReader(new InputStreamReader(System.in)); } public String read() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { e.printStackTrace(); } } return st.nextToken(); } public int readInt() { return Integer.parseInt(read()); } public long readLong() { return Long.parseLong(read()); } public double readDouble(){return Double.parseDouble(read());} public String readLine() throws Exception { return br.readLine(); } } }
Java
["5\n\n1003004\n\n4 1\n\n1 2 1\n\n179572007\n\n4 2\n\n2 7 3\n\n2 7 4\n\n111\n\n2 1\n\n2 2 6\n\n0000\n\n1 2\n\n1 4 0\n\n1 4 1\n\n484\n\n1 5\n\n2 2 0\n\n2 3 7\n\n1 2 5\n\n3 3 8\n\n2 2 6"]
3 seconds
["2 4\n1 5\n1 2\n-1 -1\n1 2\n-1 -1\n1 3\n1 3\n-1 -1\n-1 -1\n-1 -1"]
NoteConsider the first test case of example inputs. In this test case $$$n=7$$$, $$$s=$$$"1003004", $$$w=4$$$ and one query $$$l_1=1$$$, $$$r_1=2$$$, $$$k_1=1$$$. Note that $$$v(1,2)=10$$$. We need to find a pair of substrings of length $$$4$$$ such that $$$v(L_1, L_1+3)\cdot10+v(L_2,L_2+3)$$$ has a remainder of $$$k_1=1$$$ when divided by $$$9$$$. The values $$$L_1=2, L_2=4$$$ actually satisfy all the requirements: $$$v(L_1, L_1+w-1)=v(2,5)=30$$$, $$$v(L_2, L_2+w-1)=v(4,7)=3004$$$. Indeed, $$$30\cdot10+3004=3304$$$, which has a remainder of $$$1$$$ when divided by $$$9$$$. It can be shown that $$$L_1=2$$$ is the minimum possible value, and $$$L_2=4$$$ is the minimum possible with $$$L_1=2$$$.
Java 11
standard input
[ "hashing", "math" ]
b67870dcffa7bad682ef980dacd1f3db
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — number of input test cases. The first line of each test case contains a string $$$s$$$, which contains only the characters 0-9 and has a length $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$). The second line contains two integers $$$w, m$$$ ($$$1 \le w &lt; n, 1 \le m \le 2 \cdot 10^5$$$), where $$$n$$$ — is the length of the given string $$$s$$$. The number $$$w$$$ denotes the lengths of the substrings being searched for, and $$$m$$$ is the number of queries to be processed. The following $$$m$$$ lines contain integers $$$l_i, r_i, k_i$$$ ($$$1 \le l_i \le r_i \le n$$$, $$$0 \le k_i \le 8$$$) — $$$i$$$th query parameters. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$. It is also guaranteed that the sum of $$$m$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,900
For each request, print in a separate line: left borders of the required substrings: $$$L_1$$$ and $$$L_2$$$; -1 -1 otherwise, if there is no solution. If there are several solutions, minimize $$$L_1$$$ first, and minimize $$$L_2$$$ second.
standard output
PASSED
2890c8890442b47265d508460d398801
train_110.jsonl
1662993300
Given the string $$$s$$$ of decimal digits (0-9) of length $$$n$$$.A substring is a sequence of consecutive characters of a string. The substring of this string is defined by a pair of indexes — with its left and right ends. So, each pair of indexes ($$$l, r$$$), where $$$1 \le l \le r \le n$$$, corresponds to a substring of the string $$$s$$$. We will define as $$$v(l,r)$$$ the numeric value of the corresponding substring (leading zeros are allowed in it).For example, if $$$n=7$$$, $$$s=$$$"1003004", then $$$v(1,3)=100$$$, $$$v(2,3)=0$$$ and $$$v(2,7)=3004$$$.You are given $$$n$$$, $$$s$$$ and an integer $$$w$$$ ($$$1 \le w &lt; n$$$).You need to process $$$m$$$ queries, each of which is characterized by $$$3$$$ numbers $$$l_i, r_i, k_i$$$ ($$$1 \le l_i \le r_i \le n; 0 \le k_i \le 8$$$).The answer to the $$$i$$$th query is such a pair of substrings of length $$$w$$$ that if we denote them as $$$(L_1, L_1+w-1)$$$ and $$$(L_2, L_2+w-1)$$$, then: $$$L_1 \ne L_2$$$, that is, the substrings are different; the remainder of dividing a number $$$v(L_1, L_1+w-1) \cdot v(l_i, r_i) + v(L_2, L_2 + w - 1)$$$ by $$$9$$$ is equal to $$$k_i$$$. If there are many matching substring pairs, then find a pair where $$$L_1$$$ is as small as possible. If there are many matching pairs in this case, then minimize $$$L_2$$$.Note that the answer may not exist.
256 megabytes
import java.io.*; import java.util.*; public class ProblemB { static int n; public static void main(String[] args) throws Exception { Scanner in = new Scanner(); int test = in.readInt(); StringBuilder sb = new StringBuilder(); Comparator<Pair>cmp = new Comparator<Pair>(){ @Override public int compare(Pair o1, Pair o2) { return o1.x == o2.x? o1.y-o2.y:o1.x-o2.x; } }; while(test-->0){ String ss = in.readLine().trim(); char c[] = ss.toCharArray(); int n = c.length; long prefix[] = new long[n]; for(int i = 0;i<n;i++){ prefix[i] = c[i]-'0'; if(i-1>=0)prefix[i]+=prefix[i-1]; } int w = in.readInt(); int q = in.readInt(); ArrayList<Integer> p [] = new ArrayList[9]; for(int i = 0;i<9;i++)p[i] = new ArrayList<>(); for(int i = 0;i+w-1<n;i++){ int val = (int)((prefix[i+w-1]-(i-1>=0?prefix[i-1]:0)))%9; p[val].add(i); } while(q-->0){ int l= in.readInt()-1,r = in.readInt()-1,k = in.readInt(); int v = (int)((prefix[r] - (l-1>=0?prefix[l-1]:0))%9); int l1 = (int)2e9,l2 = (int)2e9; for(int i = 0;i<=8;i++){ int look = k - ((v*i)%9); if(look<0)look+=9; if(p[look].size() == 0 || p[i].size() == 0)continue; int t1 = p[i].get(0),t2 = p[look].get(0); ArrayList<Pair>list = new ArrayList<>(); list.add(new Pair(l1,l2)); if(i != look){ list.add(new Pair(t1,t2)); Collections.sort(list,cmp); l1 = list.get(0).x; l2 = list.get(0).y; }else if(p[i].size()>=2){ t2 = p[i].get(1); list.add(new Pair(t1,t2)); Collections.sort(list,cmp); l1 = list.get(0).x; l2 = list.get(0).y; } } if(l1 == 2e9){l1 = l2 = -2;} sb.append((l1+1)+" "+(l2+1)); sb.append("\n"); } } System.out.println(sb); } public static void build(int seg[],int ind,int l,int r,int a[]){ if(l == r){ seg[ind] = a[l]; return; } int mid = (l+r)/2; build(seg,(2*ind)+1,l,mid,a); build(seg,(2*ind)+2,mid+1,r,a); seg[ind] = Math.min(seg[(2*ind)+1],seg[(2*ind)+2]); } public static long gcd(long a, long b){ return b ==0 ?a:gcd(b,a%b); } public static long nearest(TreeSet<Long> list,long target){ long nearest = -1,sofar = Integer.MAX_VALUE; for(long it:list){ if(Math.abs(it - target)<sofar){ sofar = Math.abs(it - target); nearest = it; } } return nearest; } public static ArrayList<Long> factors(long n){ ArrayList<Long>l = new ArrayList<>(); for(long i = 1;i*i<=n;i++){ if(n%i == 0){ l.add(i); if(n/i != i)l.add(n/i); } } Collections.sort(l); return l; } public static void swap(int a[],int i, int j){ int t = a[i]; a[i] = a[j]; a[j] = t; } public static boolean isSorted(long a[]){ for(int i =0;i<a.length;i++){ if(i+1<a.length && a[i]>a[i+1])return false; } return true; } public static int first(ArrayList<Long>list,long target){ int index = -1; int l = 0,r = list.size()-1; while(l<=r){ int mid = (l+r)/2; if(list.get(mid) == target){ index = mid; r = mid-1; }else if(list.get(mid)>target){ r = mid-1; }else l = mid+1; } return index; } public static int last(ArrayList<Long>list,long target){ int index = -1; int l = 0,r = list.size()-1; while(l<=r){ int mid = (l+r)/2; if(list.get(mid) == target){ index= mid; l = mid+1; }else if(list.get(mid)<target){ l = mid+1; }else r = mid-1; } return index; } public static void sort(int arr[]){ ArrayList<Integer>list = new ArrayList<>(); for(int it:arr)list.add(it); Collections.sort(list); for(int i = 0;i<arr.length;i++)arr[i] = list.get(i); } static class Pair{ int x,y; public Pair(int x,int y){ this.x = x; this.y = y; } } static class Scanner{ BufferedReader br; StringTokenizer st; public Scanner(){ br = new BufferedReader(new InputStreamReader(System.in)); } public String read() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { e.printStackTrace(); } } return st.nextToken(); } public int readInt() { return Integer.parseInt(read()); } public long readLong() { return Long.parseLong(read()); } public double readDouble(){return Double.parseDouble(read());} public String readLine() throws Exception { return br.readLine(); } } }
Java
["5\n\n1003004\n\n4 1\n\n1 2 1\n\n179572007\n\n4 2\n\n2 7 3\n\n2 7 4\n\n111\n\n2 1\n\n2 2 6\n\n0000\n\n1 2\n\n1 4 0\n\n1 4 1\n\n484\n\n1 5\n\n2 2 0\n\n2 3 7\n\n1 2 5\n\n3 3 8\n\n2 2 6"]
3 seconds
["2 4\n1 5\n1 2\n-1 -1\n1 2\n-1 -1\n1 3\n1 3\n-1 -1\n-1 -1\n-1 -1"]
NoteConsider the first test case of example inputs. In this test case $$$n=7$$$, $$$s=$$$"1003004", $$$w=4$$$ and one query $$$l_1=1$$$, $$$r_1=2$$$, $$$k_1=1$$$. Note that $$$v(1,2)=10$$$. We need to find a pair of substrings of length $$$4$$$ such that $$$v(L_1, L_1+3)\cdot10+v(L_2,L_2+3)$$$ has a remainder of $$$k_1=1$$$ when divided by $$$9$$$. The values $$$L_1=2, L_2=4$$$ actually satisfy all the requirements: $$$v(L_1, L_1+w-1)=v(2,5)=30$$$, $$$v(L_2, L_2+w-1)=v(4,7)=3004$$$. Indeed, $$$30\cdot10+3004=3304$$$, which has a remainder of $$$1$$$ when divided by $$$9$$$. It can be shown that $$$L_1=2$$$ is the minimum possible value, and $$$L_2=4$$$ is the minimum possible with $$$L_1=2$$$.
Java 11
standard input
[ "hashing", "math" ]
b67870dcffa7bad682ef980dacd1f3db
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — number of input test cases. The first line of each test case contains a string $$$s$$$, which contains only the characters 0-9 and has a length $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$). The second line contains two integers $$$w, m$$$ ($$$1 \le w &lt; n, 1 \le m \le 2 \cdot 10^5$$$), where $$$n$$$ — is the length of the given string $$$s$$$. The number $$$w$$$ denotes the lengths of the substrings being searched for, and $$$m$$$ is the number of queries to be processed. The following $$$m$$$ lines contain integers $$$l_i, r_i, k_i$$$ ($$$1 \le l_i \le r_i \le n$$$, $$$0 \le k_i \le 8$$$) — $$$i$$$th query parameters. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$. It is also guaranteed that the sum of $$$m$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,900
For each request, print in a separate line: left borders of the required substrings: $$$L_1$$$ and $$$L_2$$$; -1 -1 otherwise, if there is no solution. If there are several solutions, minimize $$$L_1$$$ first, and minimize $$$L_2$$$ second.
standard output
PASSED
4cbe23a5acd1676db01d5f47eba110d5
train_110.jsonl
1662993300
Given the string $$$s$$$ of decimal digits (0-9) of length $$$n$$$.A substring is a sequence of consecutive characters of a string. The substring of this string is defined by a pair of indexes — with its left and right ends. So, each pair of indexes ($$$l, r$$$), where $$$1 \le l \le r \le n$$$, corresponds to a substring of the string $$$s$$$. We will define as $$$v(l,r)$$$ the numeric value of the corresponding substring (leading zeros are allowed in it).For example, if $$$n=7$$$, $$$s=$$$"1003004", then $$$v(1,3)=100$$$, $$$v(2,3)=0$$$ and $$$v(2,7)=3004$$$.You are given $$$n$$$, $$$s$$$ and an integer $$$w$$$ ($$$1 \le w &lt; n$$$).You need to process $$$m$$$ queries, each of which is characterized by $$$3$$$ numbers $$$l_i, r_i, k_i$$$ ($$$1 \le l_i \le r_i \le n; 0 \le k_i \le 8$$$).The answer to the $$$i$$$th query is such a pair of substrings of length $$$w$$$ that if we denote them as $$$(L_1, L_1+w-1)$$$ and $$$(L_2, L_2+w-1)$$$, then: $$$L_1 \ne L_2$$$, that is, the substrings are different; the remainder of dividing a number $$$v(L_1, L_1+w-1) \cdot v(l_i, r_i) + v(L_2, L_2 + w - 1)$$$ by $$$9$$$ is equal to $$$k_i$$$. If there are many matching substring pairs, then find a pair where $$$L_1$$$ is as small as possible. If there are many matching pairs in this case, then minimize $$$L_2$$$.Note that the answer may not exist.
256 megabytes
import java.util.*; import java.io.*; public class Main { public static FastReader obj=new FastReader(); public static PrintWriter out = new PrintWriter(System.out); public static int base = 10, mod = 9, N = (int) (1e6 + 5); public static int[] pw = new int[N]; public static int[] inv = new int[N]; public static void precal() { pw[0] = 1; inv[0] = 1; int pw_inv = bp(base, 7, mod); for (int i = 1; i < pw.length; i++) { pw[i] = mult(pw[i - 1], base, mod); inv[i] = mult(inv[i - 1], pw_inv, mod); } } public static int add(int a, int b, int mod) { int val = (a % mod + b % mod) % mod; if (val < 0) val += mod; return val; } public static int mult(int a, int b, int mod) { int val = (int) ((a * 1L * b) % mod); if (val < 0) val += mod; return val; } public static int bp(int a, int b, int mod) { int res = 1; while (b > 0) { if (b % 2 != 0) res = mult(res, a, mod); a = mult(a, a, mod); b >>= 1; } return res; } public static class string_hash { public int[] hash; public int n; string_hash(String s) { n = s.length(); hash = new int[s.length() + 5]; hash[0] = mult((s.charAt(0) - 'a' + 1), 1, mod); for (int i = 1; i < s.length(); i++) hash[i] = add(hash[i - 1], mult(s.charAt(i) - 'a' + 1, pw[i], mod), mod); } public int range(int i, int j) { int val = add(hash[j], (i == 0) ? -0 : -hash[i - 1], mod); int res = mult(val, inv[i], mod); return res; } public int tut() { return hash[n - 1]; } } public static int range(int i, int j, int[] hash) { int val = add(hash[j], (i == 0) ? -0 : -hash[i - 1], mod); int res = mult(val, inv[i], mod); return res; } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { if (st.hasMoreTokens()) { str = st.nextToken("\n"); } else { str = br.readLine(); } } catch (IOException e) { e.printStackTrace(); } return str; } } public static void main(String[] args) { int len = obj.nextInt(); precal(); while (len-- != 0) { String s = obj.next(); int w = obj.nextInt(); int m = obj.nextInt(); int[] hash = new int[s.length()]; hash[0] = mult((s.charAt(0) - '0'), 1, mod); for (int i = 1; i < s.length(); i++) hash[i] = add(hash[i - 1], mult(s.charAt(i) - '0', pw[i], mod), mod); int sz = s.length() - w + 1; int[] values = new int[sz]; HashMap<Integer, Vector<Integer>> map = new HashMap<>(); for (int i = 0; i <= s.length() - w; i++) { values[i] = range(i, i + w - 1, hash) % 9; Vector<Integer> v = map.get(values[i]); if (v == null) v = new Vector<>(); v.add(i); map.put(values[i], v); } for (int i = 0; i < m; i++) { int l = obj.nextInt() - 1; int r = obj.nextInt() - 1; int k = obj.nextInt() + 9; int val = range(l, r, hash); boolean ans = false; int xans=Integer.MAX_VALUE; int yans=Integer.MAX_VALUE; for(int j=0;j<9;j++) { if(!map.containsKey(j))continue; Vector<Integer> g=map.get(j); int v5=g.get(0); int v1 = k - ((j % 9) * (val % 9)) % 9 + 9; if (map.containsKey(v1 % 9)) { Vector<Integer> v = map.get(v1 % 9); int v2 = -1; for (int a : v) { if (a != v5) { v2 = a; break; } } if (v2 != -1) { ans = true; if((v5+1)<xans) { xans=v5+1; yans=v2+1; } else if(v5+1==xans) yans=Math.min(yans, v2+1); } } } if(ans)out.println(xans+" "+yans); if (!ans) out.println("-1 -1"); } } out.flush(); } }
Java
["5\n\n1003004\n\n4 1\n\n1 2 1\n\n179572007\n\n4 2\n\n2 7 3\n\n2 7 4\n\n111\n\n2 1\n\n2 2 6\n\n0000\n\n1 2\n\n1 4 0\n\n1 4 1\n\n484\n\n1 5\n\n2 2 0\n\n2 3 7\n\n1 2 5\n\n3 3 8\n\n2 2 6"]
3 seconds
["2 4\n1 5\n1 2\n-1 -1\n1 2\n-1 -1\n1 3\n1 3\n-1 -1\n-1 -1\n-1 -1"]
NoteConsider the first test case of example inputs. In this test case $$$n=7$$$, $$$s=$$$"1003004", $$$w=4$$$ and one query $$$l_1=1$$$, $$$r_1=2$$$, $$$k_1=1$$$. Note that $$$v(1,2)=10$$$. We need to find a pair of substrings of length $$$4$$$ such that $$$v(L_1, L_1+3)\cdot10+v(L_2,L_2+3)$$$ has a remainder of $$$k_1=1$$$ when divided by $$$9$$$. The values $$$L_1=2, L_2=4$$$ actually satisfy all the requirements: $$$v(L_1, L_1+w-1)=v(2,5)=30$$$, $$$v(L_2, L_2+w-1)=v(4,7)=3004$$$. Indeed, $$$30\cdot10+3004=3304$$$, which has a remainder of $$$1$$$ when divided by $$$9$$$. It can be shown that $$$L_1=2$$$ is the minimum possible value, and $$$L_2=4$$$ is the minimum possible with $$$L_1=2$$$.
Java 11
standard input
[ "hashing", "math" ]
b67870dcffa7bad682ef980dacd1f3db
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — number of input test cases. The first line of each test case contains a string $$$s$$$, which contains only the characters 0-9 and has a length $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$). The second line contains two integers $$$w, m$$$ ($$$1 \le w &lt; n, 1 \le m \le 2 \cdot 10^5$$$), where $$$n$$$ — is the length of the given string $$$s$$$. The number $$$w$$$ denotes the lengths of the substrings being searched for, and $$$m$$$ is the number of queries to be processed. The following $$$m$$$ lines contain integers $$$l_i, r_i, k_i$$$ ($$$1 \le l_i \le r_i \le n$$$, $$$0 \le k_i \le 8$$$) — $$$i$$$th query parameters. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$. It is also guaranteed that the sum of $$$m$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,900
For each request, print in a separate line: left borders of the required substrings: $$$L_1$$$ and $$$L_2$$$; -1 -1 otherwise, if there is no solution. If there are several solutions, minimize $$$L_1$$$ first, and minimize $$$L_2$$$ second.
standard output
PASSED
b9cd2602dca9dd1d2f877261460c5713
train_110.jsonl
1662993300
Given the string $$$s$$$ of decimal digits (0-9) of length $$$n$$$.A substring is a sequence of consecutive characters of a string. The substring of this string is defined by a pair of indexes — with its left and right ends. So, each pair of indexes ($$$l, r$$$), where $$$1 \le l \le r \le n$$$, corresponds to a substring of the string $$$s$$$. We will define as $$$v(l,r)$$$ the numeric value of the corresponding substring (leading zeros are allowed in it).For example, if $$$n=7$$$, $$$s=$$$"1003004", then $$$v(1,3)=100$$$, $$$v(2,3)=0$$$ and $$$v(2,7)=3004$$$.You are given $$$n$$$, $$$s$$$ and an integer $$$w$$$ ($$$1 \le w &lt; n$$$).You need to process $$$m$$$ queries, each of which is characterized by $$$3$$$ numbers $$$l_i, r_i, k_i$$$ ($$$1 \le l_i \le r_i \le n; 0 \le k_i \le 8$$$).The answer to the $$$i$$$th query is such a pair of substrings of length $$$w$$$ that if we denote them as $$$(L_1, L_1+w-1)$$$ and $$$(L_2, L_2+w-1)$$$, then: $$$L_1 \ne L_2$$$, that is, the substrings are different; the remainder of dividing a number $$$v(L_1, L_1+w-1) \cdot v(l_i, r_i) + v(L_2, L_2 + w - 1)$$$ by $$$9$$$ is equal to $$$k_i$$$. If there are many matching substring pairs, then find a pair where $$$L_1$$$ is as small as possible. If there are many matching pairs in this case, then minimize $$$L_2$$$.Note that the answer may not exist.
256 megabytes
import java.util.*; import java.io.*; public class Main { public static FastReader obj=new FastReader(); public static PrintWriter out = new PrintWriter(System.out); public static int base = 10, mod = 9, N = (int) (1e6 + 5); public static int[] pw = new int[N]; public static int[] inv = new int[N]; public static void precal() { pw[0] = 1; inv[0] = 1; int pw_inv = bp(base, 5, mod); for (int i = 1; i < pw.length; i++) { pw[i] = mult(pw[i - 1], base, mod); inv[i] = mult(inv[i - 1], pw_inv, mod); } } public static int add(int a, int b, int mod) { int val = (a % mod + b % mod) % mod; if (val < 0) val += mod; return val; } public static int mult(int a, int b, int mod) { int val = (int) ((a * 1L * b) % mod); if (val < 0) val += mod; return val; } public static int bp(int a, int b, int mod) { int res = 1; while (b > 0) { if (b % 2 != 0) res = mult(res, a, mod); a = mult(a, a, mod); b >>= 1; } return res; } public static class string_hash { public int[] hash; public int n; string_hash(String s) { n = s.length(); hash = new int[s.length() + 5]; hash[0] = mult((s.charAt(0) - 'a' + 1), 1, mod); for (int i = 1; i < s.length(); i++) hash[i] = add(hash[i - 1], mult(s.charAt(i) - 'a' + 1, pw[i], mod), mod); } public int range(int i, int j) { int val = add(hash[j], (i == 0) ? -0 : -hash[i - 1], mod); int res = mult(val, inv[i], mod); return res; } public int tut() { return hash[n - 1]; } } public static int range(int i, int j, int[] hash) { int val = add(hash[j], (i == 0) ? -0 : -hash[i - 1], mod); int res = mult(val, inv[i], mod); return res; } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { if (st.hasMoreTokens()) { str = st.nextToken("\n"); } else { str = br.readLine(); } } catch (IOException e) { e.printStackTrace(); } return str; } } public static void main(String[] args) { int len = obj.nextInt(); precal(); while (len-- != 0) { String s = obj.next(); int w = obj.nextInt(); int m = obj.nextInt(); int[] hash = new int[s.length()]; hash[0] = mult((s.charAt(0) - '0'), 1, mod); for (int i = 1; i < s.length(); i++) hash[i] = add(hash[i - 1], mult(s.charAt(i) - '0', pw[i], mod), mod); int sz = s.length() - w + 1; int[] values = new int[sz]; HashMap<Integer, Vector<Integer>> map = new HashMap<>(); for (int i = 0; i <= s.length() - w; i++) { values[i] = range(i, i + w - 1, hash) % 9; Vector<Integer> v = map.get(values[i]); if (v == null) v = new Vector<>(); v.add(i); map.put(values[i], v); } for (int i = 0; i < m; i++) { int l = obj.nextInt() - 1; int r = obj.nextInt() - 1; int k = obj.nextInt() + 9; int val = range(l, r, hash); boolean ans = false; int xans=Integer.MAX_VALUE; int yans=Integer.MAX_VALUE; for(int j=0;j<9;j++) { if(!map.containsKey(j))continue; Vector<Integer> g=map.get(j); int v5=g.get(0); int v1 = k - ((j % 9) * (val % 9)) % 9 + 9; if (map.containsKey(v1 % 9)) { Vector<Integer> v = map.get(v1 % 9); int v2 = -1; for (int a : v) { if (a != v5) { v2 = a; break; } } if (v2 != -1) { ans = true; if((v5+1)<xans) { xans=v5+1; yans=v2+1; } else if(v5+1==xans) yans=Math.min(yans, v2+1); } } } if(ans)out.println(xans+" "+yans); if (!ans) out.println("-1 -1"); } } out.flush(); } }
Java
["5\n\n1003004\n\n4 1\n\n1 2 1\n\n179572007\n\n4 2\n\n2 7 3\n\n2 7 4\n\n111\n\n2 1\n\n2 2 6\n\n0000\n\n1 2\n\n1 4 0\n\n1 4 1\n\n484\n\n1 5\n\n2 2 0\n\n2 3 7\n\n1 2 5\n\n3 3 8\n\n2 2 6"]
3 seconds
["2 4\n1 5\n1 2\n-1 -1\n1 2\n-1 -1\n1 3\n1 3\n-1 -1\n-1 -1\n-1 -1"]
NoteConsider the first test case of example inputs. In this test case $$$n=7$$$, $$$s=$$$"1003004", $$$w=4$$$ and one query $$$l_1=1$$$, $$$r_1=2$$$, $$$k_1=1$$$. Note that $$$v(1,2)=10$$$. We need to find a pair of substrings of length $$$4$$$ such that $$$v(L_1, L_1+3)\cdot10+v(L_2,L_2+3)$$$ has a remainder of $$$k_1=1$$$ when divided by $$$9$$$. The values $$$L_1=2, L_2=4$$$ actually satisfy all the requirements: $$$v(L_1, L_1+w-1)=v(2,5)=30$$$, $$$v(L_2, L_2+w-1)=v(4,7)=3004$$$. Indeed, $$$30\cdot10+3004=3304$$$, which has a remainder of $$$1$$$ when divided by $$$9$$$. It can be shown that $$$L_1=2$$$ is the minimum possible value, and $$$L_2=4$$$ is the minimum possible with $$$L_1=2$$$.
Java 11
standard input
[ "hashing", "math" ]
b67870dcffa7bad682ef980dacd1f3db
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — number of input test cases. The first line of each test case contains a string $$$s$$$, which contains only the characters 0-9 and has a length $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$). The second line contains two integers $$$w, m$$$ ($$$1 \le w &lt; n, 1 \le m \le 2 \cdot 10^5$$$), where $$$n$$$ — is the length of the given string $$$s$$$. The number $$$w$$$ denotes the lengths of the substrings being searched for, and $$$m$$$ is the number of queries to be processed. The following $$$m$$$ lines contain integers $$$l_i, r_i, k_i$$$ ($$$1 \le l_i \le r_i \le n$$$, $$$0 \le k_i \le 8$$$) — $$$i$$$th query parameters. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$. It is also guaranteed that the sum of $$$m$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,900
For each request, print in a separate line: left borders of the required substrings: $$$L_1$$$ and $$$L_2$$$; -1 -1 otherwise, if there is no solution. If there are several solutions, minimize $$$L_1$$$ first, and minimize $$$L_2$$$ second.
standard output
PASSED
882dd6e7d0c4718ee057e3b05405d9d4
train_110.jsonl
1662993300
Given the string $$$s$$$ of decimal digits (0-9) of length $$$n$$$.A substring is a sequence of consecutive characters of a string. The substring of this string is defined by a pair of indexes — with its left and right ends. So, each pair of indexes ($$$l, r$$$), where $$$1 \le l \le r \le n$$$, corresponds to a substring of the string $$$s$$$. We will define as $$$v(l,r)$$$ the numeric value of the corresponding substring (leading zeros are allowed in it).For example, if $$$n=7$$$, $$$s=$$$"1003004", then $$$v(1,3)=100$$$, $$$v(2,3)=0$$$ and $$$v(2,7)=3004$$$.You are given $$$n$$$, $$$s$$$ and an integer $$$w$$$ ($$$1 \le w &lt; n$$$).You need to process $$$m$$$ queries, each of which is characterized by $$$3$$$ numbers $$$l_i, r_i, k_i$$$ ($$$1 \le l_i \le r_i \le n; 0 \le k_i \le 8$$$).The answer to the $$$i$$$th query is such a pair of substrings of length $$$w$$$ that if we denote them as $$$(L_1, L_1+w-1)$$$ and $$$(L_2, L_2+w-1)$$$, then: $$$L_1 \ne L_2$$$, that is, the substrings are different; the remainder of dividing a number $$$v(L_1, L_1+w-1) \cdot v(l_i, r_i) + v(L_2, L_2 + w - 1)$$$ by $$$9$$$ is equal to $$$k_i$$$. If there are many matching substring pairs, then find a pair where $$$L_1$$$ is as small as possible. If there are many matching pairs in this case, then minimize $$$L_2$$$.Note that the answer may not exist.
256 megabytes
import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.Arrays; import java.io.BufferedReader; import java.io.BufferedWriter; public class F { public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader( new InputStreamReader(System.in)); int numCases = Integer.parseInt(br.readLine()); for (int i=0; i<numCases; i++) { solveProblem(br); } br.close(); } static void solveProblem(BufferedReader br) throws Exception { int[] s; int w; int m; // num queries String s_str = br.readLine(); s = new int[s_str.length()]; int[] cum_s = new int[s_str.length()]; for (int i=0; i<s.length; i++) { s[i] = (byte) (s_str.charAt(i) - '0'); if (i == 0) cum_s[i] = s[i]; else cum_s[i] = cum_s[i - 1] + s[i]; cum_s[i] = ((cum_s[i] % 9) + 9) % 9; } String[] nums = br.readLine().split(" "); w = Integer.parseInt(nums[0]); m = Integer.parseInt(nums[1]); // Do pre-processing int[] first_indicies = new int[10]; int[] second_indicies = new int[10]; for (int i=0; i<10; i++) { first_indicies[i] = -1; second_indicies[i] = -1; } int[] seqVals = new int[s.length - w + 1]; int v = 0; for (int i=0; i<w; i++) { v += s[i]; } v = ((v % 9) + 9) % 9; seqVals[0] = v; first_indicies[v] = 0; int filled_nums = 0; int i; for (i=w; i<s.length && filled_nums != 17; i++) { v -= s[i-w]; v += s[i]; v = ((v % 9) + 9) % 9; seqVals[i - w + 1] = v; if (first_indicies[v] == -1) { first_indicies[v] = (i - w + 1); filled_nums++; } else if (second_indicies[v] == -1) { second_indicies[v] = (i - w + 1); filled_nums++; } } // System.out.println("PreProc, filledNums: " + filled_nums); // System.out.println("i, lim: " + i + ", " + s.length()); // System.out.println("\n\n[["); // printArr(seqVals); // printArr(first_indicies); // printArr(second_indicies); // System.out.println("]]\n"); // Handle queries for (i=0; i<m; i++) { String[] _s = br.readLine().split(" "); int li = Integer.parseInt(_s[0]); int ri = Integer.parseInt(_s[1]); int ki = Integer.parseInt(_s[2]); int val = getModNine(cum_s, li, ri); int first_ind = -1; int second_ind = -1; for (int k=0; k<9; k++) { if (first_indicies[k] == -1) continue; int sec_test = ki - k * val; sec_test = ((sec_test % 9) + 9) % 9; // System.out.println(k + " * " + val + " + " + sec_test + " = " + ki + " mod 9"); if (sec_test == k) { if (second_indicies[sec_test] != -1) { if (first_ind == -1 || first_ind > first_indicies[k] + 1) { first_ind = first_indicies[k] + 1; second_ind = second_indicies[sec_test] + 1; } } } else { if (first_indicies[sec_test] != -1) { if (first_ind == -1 || first_ind > first_indicies[k] + 1) { first_ind = first_indicies[k] + 1; second_ind = first_indicies[sec_test] + 1; } } } } System.out.println(first_ind + " " + second_ind); } } static int getModNine (int[] cum_sum, int leftInd, int rightInd) { if (leftInd == 1) return cum_sum[rightInd - 1]; else return cum_sum[rightInd - 1] - cum_sum[leftInd - 2]; // int sum = 0; // for (int i=leftInd; i<rightInd; i++) { // sum += s[i]; // sum %= 9; // } // return sum; } static void printArr (int[] a) { for (int _a : a) { System.out.print(_a + " "); } System.out.println(); } }
Java
["5\n\n1003004\n\n4 1\n\n1 2 1\n\n179572007\n\n4 2\n\n2 7 3\n\n2 7 4\n\n111\n\n2 1\n\n2 2 6\n\n0000\n\n1 2\n\n1 4 0\n\n1 4 1\n\n484\n\n1 5\n\n2 2 0\n\n2 3 7\n\n1 2 5\n\n3 3 8\n\n2 2 6"]
3 seconds
["2 4\n1 5\n1 2\n-1 -1\n1 2\n-1 -1\n1 3\n1 3\n-1 -1\n-1 -1\n-1 -1"]
NoteConsider the first test case of example inputs. In this test case $$$n=7$$$, $$$s=$$$"1003004", $$$w=4$$$ and one query $$$l_1=1$$$, $$$r_1=2$$$, $$$k_1=1$$$. Note that $$$v(1,2)=10$$$. We need to find a pair of substrings of length $$$4$$$ such that $$$v(L_1, L_1+3)\cdot10+v(L_2,L_2+3)$$$ has a remainder of $$$k_1=1$$$ when divided by $$$9$$$. The values $$$L_1=2, L_2=4$$$ actually satisfy all the requirements: $$$v(L_1, L_1+w-1)=v(2,5)=30$$$, $$$v(L_2, L_2+w-1)=v(4,7)=3004$$$. Indeed, $$$30\cdot10+3004=3304$$$, which has a remainder of $$$1$$$ when divided by $$$9$$$. It can be shown that $$$L_1=2$$$ is the minimum possible value, and $$$L_2=4$$$ is the minimum possible with $$$L_1=2$$$.
Java 11
standard input
[ "hashing", "math" ]
b67870dcffa7bad682ef980dacd1f3db
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — number of input test cases. The first line of each test case contains a string $$$s$$$, which contains only the characters 0-9 and has a length $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$). The second line contains two integers $$$w, m$$$ ($$$1 \le w &lt; n, 1 \le m \le 2 \cdot 10^5$$$), where $$$n$$$ — is the length of the given string $$$s$$$. The number $$$w$$$ denotes the lengths of the substrings being searched for, and $$$m$$$ is the number of queries to be processed. The following $$$m$$$ lines contain integers $$$l_i, r_i, k_i$$$ ($$$1 \le l_i \le r_i \le n$$$, $$$0 \le k_i \le 8$$$) — $$$i$$$th query parameters. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$. It is also guaranteed that the sum of $$$m$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,900
For each request, print in a separate line: left borders of the required substrings: $$$L_1$$$ and $$$L_2$$$; -1 -1 otherwise, if there is no solution. If there are several solutions, minimize $$$L_1$$$ first, and minimize $$$L_2$$$ second.
standard output
PASSED
ae9fcf58fd8d6dc8daab8064bc3977b7
train_110.jsonl
1662993300
Given the string $$$s$$$ of decimal digits (0-9) of length $$$n$$$.A substring is a sequence of consecutive characters of a string. The substring of this string is defined by a pair of indexes — with its left and right ends. So, each pair of indexes ($$$l, r$$$), where $$$1 \le l \le r \le n$$$, corresponds to a substring of the string $$$s$$$. We will define as $$$v(l,r)$$$ the numeric value of the corresponding substring (leading zeros are allowed in it).For example, if $$$n=7$$$, $$$s=$$$"1003004", then $$$v(1,3)=100$$$, $$$v(2,3)=0$$$ and $$$v(2,7)=3004$$$.You are given $$$n$$$, $$$s$$$ and an integer $$$w$$$ ($$$1 \le w &lt; n$$$).You need to process $$$m$$$ queries, each of which is characterized by $$$3$$$ numbers $$$l_i, r_i, k_i$$$ ($$$1 \le l_i \le r_i \le n; 0 \le k_i \le 8$$$).The answer to the $$$i$$$th query is such a pair of substrings of length $$$w$$$ that if we denote them as $$$(L_1, L_1+w-1)$$$ and $$$(L_2, L_2+w-1)$$$, then: $$$L_1 \ne L_2$$$, that is, the substrings are different; the remainder of dividing a number $$$v(L_1, L_1+w-1) \cdot v(l_i, r_i) + v(L_2, L_2 + w - 1)$$$ by $$$9$$$ is equal to $$$k_i$$$. If there are many matching substring pairs, then find a pair where $$$L_1$$$ is as small as possible. If there are many matching pairs in this case, then minimize $$$L_2$$$.Note that the answer may not exist.
256 megabytes
import java.io.PrintWriter; import java.util.Scanner; public class F { public static void main(String[] args) { Scanner sc = new Scanner(System.in); PrintWriter pw = new PrintWriter(System.out); int tests = sc.nextInt(); for (int t = 0; t < tests; t++) { solve(sc, pw); } sc.close(); pw.close(); } static void solve(Scanner sc, PrintWriter pw) { String s = sc.next(); int n = s.length(); int w = sc.nextInt(); int m = sc.nextInt(); int[] sumMod9 = new int[n]; sumMod9[0] = (s.charAt(0) - '0') % 9; for (int i = 1; i < n; i++) { sumMod9[i] = (sumMod9[i - 1] + (s.charAt(i) - '0')) % 9; } int[][] indexesOfRemainders = new int[9][2]; for (int i = 0; i < 9; i++) { for (int j = 0; j < 2; j++) { indexesOfRemainders[i][j] = Integer.MAX_VALUE; } } indexesOfRemainders[sumMod9[w - 1]][0] = 0; for (int i = 1; i < n - w + 1; i++) { int remainder = (sumMod9[i + w - 1] + 9 - sumMod9[i - 1]) % 9; if (indexesOfRemainders[remainder][0] == Integer.MAX_VALUE) { indexesOfRemainders[remainder][0] = i; continue; } if (indexesOfRemainders[remainder][1] == Integer.MAX_VALUE) { indexesOfRemainders[remainder][1] = i; } } for (int i = 0; i < m; i++) { int l = sc.nextInt() - 1; int r = sc.nextInt() - 1; int k = sc.nextInt(); int firstIdx = Integer.MAX_VALUE; int secondIdx = Integer.MAX_VALUE; int curReminder = l == 0 ? sumMod9[r] : (sumMod9[r] + 9 - sumMod9[l - 1]) % 9; for (int firstR = 0; firstR < 9; firstR++) { int secondR = (k + 9 - ((firstR * curReminder) % 9)) % 9; int firstIdxCur; int secondIdxCur; try{ throw new IndexOutOfBoundsException(); } catch (IndexOutOfBoundsException e) { test++; } if (firstR == secondR) { firstIdxCur = indexesOfRemainders[firstR][0]; secondIdxCur = indexesOfRemainders[firstR][1]; } else { firstIdxCur = indexesOfRemainders[firstR][0]; secondIdxCur = indexesOfRemainders[secondR][0]; } if (firstIdxCur < firstIdx && secondIdxCur!=Integer.MAX_VALUE) { firstIdx = firstIdxCur; secondIdx = secondIdxCur; } if (firstIdxCur == firstIdx && secondIdxCur < secondIdx) { secondIdx = secondIdxCur; } } if (firstIdx == Integer.MAX_VALUE || secondIdx == Integer.MAX_VALUE) { pw.println("-1 -1"); } else { pw.println(firstIdx + 1 + " " + (secondIdx + 1)); } } } static int test = 0; }
Java
["5\n\n1003004\n\n4 1\n\n1 2 1\n\n179572007\n\n4 2\n\n2 7 3\n\n2 7 4\n\n111\n\n2 1\n\n2 2 6\n\n0000\n\n1 2\n\n1 4 0\n\n1 4 1\n\n484\n\n1 5\n\n2 2 0\n\n2 3 7\n\n1 2 5\n\n3 3 8\n\n2 2 6"]
3 seconds
["2 4\n1 5\n1 2\n-1 -1\n1 2\n-1 -1\n1 3\n1 3\n-1 -1\n-1 -1\n-1 -1"]
NoteConsider the first test case of example inputs. In this test case $$$n=7$$$, $$$s=$$$"1003004", $$$w=4$$$ and one query $$$l_1=1$$$, $$$r_1=2$$$, $$$k_1=1$$$. Note that $$$v(1,2)=10$$$. We need to find a pair of substrings of length $$$4$$$ such that $$$v(L_1, L_1+3)\cdot10+v(L_2,L_2+3)$$$ has a remainder of $$$k_1=1$$$ when divided by $$$9$$$. The values $$$L_1=2, L_2=4$$$ actually satisfy all the requirements: $$$v(L_1, L_1+w-1)=v(2,5)=30$$$, $$$v(L_2, L_2+w-1)=v(4,7)=3004$$$. Indeed, $$$30\cdot10+3004=3304$$$, which has a remainder of $$$1$$$ when divided by $$$9$$$. It can be shown that $$$L_1=2$$$ is the minimum possible value, and $$$L_2=4$$$ is the minimum possible with $$$L_1=2$$$.
Java 11
standard input
[ "hashing", "math" ]
b67870dcffa7bad682ef980dacd1f3db
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — number of input test cases. The first line of each test case contains a string $$$s$$$, which contains only the characters 0-9 and has a length $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$). The second line contains two integers $$$w, m$$$ ($$$1 \le w &lt; n, 1 \le m \le 2 \cdot 10^5$$$), where $$$n$$$ — is the length of the given string $$$s$$$. The number $$$w$$$ denotes the lengths of the substrings being searched for, and $$$m$$$ is the number of queries to be processed. The following $$$m$$$ lines contain integers $$$l_i, r_i, k_i$$$ ($$$1 \le l_i \le r_i \le n$$$, $$$0 \le k_i \le 8$$$) — $$$i$$$th query parameters. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$. It is also guaranteed that the sum of $$$m$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,900
For each request, print in a separate line: left borders of the required substrings: $$$L_1$$$ and $$$L_2$$$; -1 -1 otherwise, if there is no solution. If there are several solutions, minimize $$$L_1$$$ first, and minimize $$$L_2$$$ second.
standard output
PASSED
68ec8ec3a49978fa18ad39db2d2524bf
train_110.jsonl
1662993300
Given the string $$$s$$$ of decimal digits (0-9) of length $$$n$$$.A substring is a sequence of consecutive characters of a string. The substring of this string is defined by a pair of indexes — with its left and right ends. So, each pair of indexes ($$$l, r$$$), where $$$1 \le l \le r \le n$$$, corresponds to a substring of the string $$$s$$$. We will define as $$$v(l,r)$$$ the numeric value of the corresponding substring (leading zeros are allowed in it).For example, if $$$n=7$$$, $$$s=$$$"1003004", then $$$v(1,3)=100$$$, $$$v(2,3)=0$$$ and $$$v(2,7)=3004$$$.You are given $$$n$$$, $$$s$$$ and an integer $$$w$$$ ($$$1 \le w &lt; n$$$).You need to process $$$m$$$ queries, each of which is characterized by $$$3$$$ numbers $$$l_i, r_i, k_i$$$ ($$$1 \le l_i \le r_i \le n; 0 \le k_i \le 8$$$).The answer to the $$$i$$$th query is such a pair of substrings of length $$$w$$$ that if we denote them as $$$(L_1, L_1+w-1)$$$ and $$$(L_2, L_2+w-1)$$$, then: $$$L_1 \ne L_2$$$, that is, the substrings are different; the remainder of dividing a number $$$v(L_1, L_1+w-1) \cdot v(l_i, r_i) + v(L_2, L_2 + w - 1)$$$ by $$$9$$$ is equal to $$$k_i$$$. If there are many matching substring pairs, then find a pair where $$$L_1$$$ is as small as possible. If there are many matching pairs in this case, then minimize $$$L_2$$$.Note that the answer may not exist.
256 megabytes
import java.io.PrintWriter; import java.util.Scanner; public class F { public static void main(String[] args) { Scanner sc = new Scanner(System.in); PrintWriter pw = new PrintWriter(System.out); int tests = sc.nextInt(); for (int t = 0; t < tests; t++) { solve(sc, pw); } sc.close(); pw.close(); } static void solve(Scanner sc, PrintWriter pw) { String s = sc.next(); int n = s.length(); int w = sc.nextInt(); int m = sc.nextInt(); int[] sumMod9 = new int[n]; sumMod9[0] = (s.charAt(0) - '0') % 9; for (int i = 1; i < n; i++) { sumMod9[i] = (sumMod9[i - 1] + (s.charAt(i) - '0')) % 9; } int[][] indexesOfRemainders = new int[9][2]; for (int i = 0; i < 9; i++) { for (int j = 0; j < 2; j++) { indexesOfRemainders[i][j] = Integer.MAX_VALUE; } } indexesOfRemainders[sumMod9[w - 1]][0] = 0; for (int i = 1; i < n - w + 1; i++) { int remainder = (sumMod9[i + w - 1] + 9 - sumMod9[i - 1]) % 9; if (indexesOfRemainders[remainder][0] == Integer.MAX_VALUE) { indexesOfRemainders[remainder][0] = i; continue; } if (indexesOfRemainders[remainder][1] == Integer.MAX_VALUE) { indexesOfRemainders[remainder][1] = i; } } for (int i = 0; i < m; i++) { int l = sc.nextInt() - 1; int r = sc.nextInt() - 1; int k = sc.nextInt(); int firstIdx = Integer.MAX_VALUE; int secondIdx = Integer.MAX_VALUE; int curReminder = l == 0 ? sumMod9[r] : (sumMod9[r] + 9 - sumMod9[l - 1]) % 9; for (int firstR = 0; firstR < 9; firstR++) { int secondR = (k + 9 - ((firstR * curReminder) % 9)) % 9; int firstIdxCur; int secondIdxCur; if (firstR == secondR) { firstIdxCur = indexesOfRemainders[firstR][0]; secondIdxCur = indexesOfRemainders[firstR][1]; } else { firstIdxCur = indexesOfRemainders[firstR][0]; secondIdxCur = indexesOfRemainders[secondR][0]; } if (firstIdxCur < firstIdx && secondIdxCur!=Integer.MAX_VALUE) { firstIdx = firstIdxCur; secondIdx = secondIdxCur; } if (firstIdxCur == firstIdx && secondIdxCur < secondIdx) { secondIdx = secondIdxCur; } } if (firstIdx == Integer.MAX_VALUE || secondIdx == Integer.MAX_VALUE) { pw.println("-1 -1"); } else { pw.println(firstIdx + 1 + " " + (secondIdx + 1)); } } } }
Java
["5\n\n1003004\n\n4 1\n\n1 2 1\n\n179572007\n\n4 2\n\n2 7 3\n\n2 7 4\n\n111\n\n2 1\n\n2 2 6\n\n0000\n\n1 2\n\n1 4 0\n\n1 4 1\n\n484\n\n1 5\n\n2 2 0\n\n2 3 7\n\n1 2 5\n\n3 3 8\n\n2 2 6"]
3 seconds
["2 4\n1 5\n1 2\n-1 -1\n1 2\n-1 -1\n1 3\n1 3\n-1 -1\n-1 -1\n-1 -1"]
NoteConsider the first test case of example inputs. In this test case $$$n=7$$$, $$$s=$$$"1003004", $$$w=4$$$ and one query $$$l_1=1$$$, $$$r_1=2$$$, $$$k_1=1$$$. Note that $$$v(1,2)=10$$$. We need to find a pair of substrings of length $$$4$$$ such that $$$v(L_1, L_1+3)\cdot10+v(L_2,L_2+3)$$$ has a remainder of $$$k_1=1$$$ when divided by $$$9$$$. The values $$$L_1=2, L_2=4$$$ actually satisfy all the requirements: $$$v(L_1, L_1+w-1)=v(2,5)=30$$$, $$$v(L_2, L_2+w-1)=v(4,7)=3004$$$. Indeed, $$$30\cdot10+3004=3304$$$, which has a remainder of $$$1$$$ when divided by $$$9$$$. It can be shown that $$$L_1=2$$$ is the minimum possible value, and $$$L_2=4$$$ is the minimum possible with $$$L_1=2$$$.
Java 11
standard input
[ "hashing", "math" ]
b67870dcffa7bad682ef980dacd1f3db
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — number of input test cases. The first line of each test case contains a string $$$s$$$, which contains only the characters 0-9 and has a length $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$). The second line contains two integers $$$w, m$$$ ($$$1 \le w &lt; n, 1 \le m \le 2 \cdot 10^5$$$), where $$$n$$$ — is the length of the given string $$$s$$$. The number $$$w$$$ denotes the lengths of the substrings being searched for, and $$$m$$$ is the number of queries to be processed. The following $$$m$$$ lines contain integers $$$l_i, r_i, k_i$$$ ($$$1 \le l_i \le r_i \le n$$$, $$$0 \le k_i \le 8$$$) — $$$i$$$th query parameters. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$. It is also guaranteed that the sum of $$$m$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,900
For each request, print in a separate line: left borders of the required substrings: $$$L_1$$$ and $$$L_2$$$; -1 -1 otherwise, if there is no solution. If there are several solutions, minimize $$$L_1$$$ first, and minimize $$$L_2$$$ second.
standard output
PASSED
6f866973972d2ed1d5351f9fea84fe7f
train_110.jsonl
1662993300
Given the string $$$s$$$ of decimal digits (0-9) of length $$$n$$$.A substring is a sequence of consecutive characters of a string. The substring of this string is defined by a pair of indexes — with its left and right ends. So, each pair of indexes ($$$l, r$$$), where $$$1 \le l \le r \le n$$$, corresponds to a substring of the string $$$s$$$. We will define as $$$v(l,r)$$$ the numeric value of the corresponding substring (leading zeros are allowed in it).For example, if $$$n=7$$$, $$$s=$$$"1003004", then $$$v(1,3)=100$$$, $$$v(2,3)=0$$$ and $$$v(2,7)=3004$$$.You are given $$$n$$$, $$$s$$$ and an integer $$$w$$$ ($$$1 \le w &lt; n$$$).You need to process $$$m$$$ queries, each of which is characterized by $$$3$$$ numbers $$$l_i, r_i, k_i$$$ ($$$1 \le l_i \le r_i \le n; 0 \le k_i \le 8$$$).The answer to the $$$i$$$th query is such a pair of substrings of length $$$w$$$ that if we denote them as $$$(L_1, L_1+w-1)$$$ and $$$(L_2, L_2+w-1)$$$, then: $$$L_1 \ne L_2$$$, that is, the substrings are different; the remainder of dividing a number $$$v(L_1, L_1+w-1) \cdot v(l_i, r_i) + v(L_2, L_2 + w - 1)$$$ by $$$9$$$ is equal to $$$k_i$$$. If there are many matching substring pairs, then find a pair where $$$L_1$$$ is as small as possible. If there are many matching pairs in this case, then minimize $$$L_2$$$.Note that the answer may not exist.
256 megabytes
import java.io.*; import java.util.*; public class F { static PrintWriter out; static Kioken sc; static boolean checkOnlineJudge = System.getProperty("ONLINE_JUDGE") == null; public static void main(String[] args) throws FileNotFoundException { if (checkOnlineJudge) { out = new PrintWriter("E:/CF_V2/output.txt"); sc = new Kioken(new File("E:/CF_V2/input.txt")); } else { out = new PrintWriter((System.out)); sc = new Kioken(); } int tt = 1; tt = sc.nextInt(); while (tt-- > 0) { solve(); } out.flush(); out.close(); } public static void solve() { char[] c = sc.nextLine().toCharArray(); int n = c.length; int w = sc.nextInt(), m = sc.nextInt(); // Since divisible by 9 is sum should be divisible by 9, we will maintain a prefix sum of it for // finding remainder int[] prefix = new int[n+1]; for(int i = 0; i < n; i++){ prefix[i+1] = prefix[i] + (c[i] - '0'); } HashMap<Integer,TreeSet<Integer>> map = new HashMap<>(); for(int i = 0; i <= n - w; i++){ int sum = prefix[i+w] - prefix[i]; int rem = sum%9; if(map.containsKey(rem)){ TreeSet<Integer> l = map.get(rem); l.add(i); map.put(rem, l); }else{ TreeSet<Integer> l = new TreeSet<>(); l.add(i); map.put(rem, l); } } while(m-- > 0){ int li = sc.nextInt() - 1; int ri = sc.nextInt() - 1; int k = sc.nextInt(); int sum = prefix[ri+1] - prefix[li]; int rem = sum%9; int L = Integer.MAX_VALUE, R = Integer.MAX_VALUE; // we will go through all possible ans and store min L and then min R for(int i = 0; i < 9; i++){ if(map.containsKey(i)){ int nxtRem = k - ((i*rem)%9) + 9; nxtRem = nxtRem%9; TreeSet<Integer> set = map.get(i); int x = set.pollFirst(); map.put(i, set); TreeSet<Integer> nxtSet = map.getOrDefault(nxtRem, new TreeSet<>()); if(nxtSet.size() > 0){ int r = nxtSet.first(); if(x < L){ L = x; R = r; }else if(x == L){ if(r < R){ R = r; } } } set.add(x); map.put(i, set); } } if(L == Integer.MAX_VALUE || R == Integer.MAX_VALUE || (L == R)){ out.println(-1 + " " + -1); }else{ out.println((L+1) + " " + (R+1)); } } return; } public static long gcd(long a, long b) { while (b != 0) { long rem = a % b; a = b; b = rem; } return a; } static long MOD = 1000000007; 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());for (int i = 0; i < arr.length; i++){arr[i] = list.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 void sort(long[] a){ ArrayList<Long> l=new ArrayList<>(); for (long i:a) l.add(i); Collections.sort(l); for (int i=0; i<a.length; i++) a[i]=l.get(i); } static class Kioken { // FileInputStream br = new FileInputStream("input.txt"); BufferedReader br; StringTokenizer st; Kioken(File filename) { try { FileReader fr = new FileReader(filename); br = new BufferedReader(fr); st = new StringTokenizer(""); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } } Kioken() { try { br = new BufferedReader(new InputStreamReader(System.in)); st = new StringTokenizer(""); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } } public String next() { while (!st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String nextLine() { try { return br.readLine(); } catch (Exception e) { e.printStackTrace(); } return null; } public boolean hasNext() { String next = null; try { next = br.readLine(); } catch (Exception e) { } if (next == null || next.length() == 0) { return false; } st = new StringTokenizer(next); return true; } public int[] readArrayInt(int n){ int[] arr = new int[n]; for(int i = 0; i < n; i++){ arr[i] = nextInt(); } return arr; } public long[] readArrayLong(int n){ long[] arr = new long[n]; for(int i = 0; i < n; i++){ arr[i] = nextLong(); } return arr; } } }
Java
["5\n\n1003004\n\n4 1\n\n1 2 1\n\n179572007\n\n4 2\n\n2 7 3\n\n2 7 4\n\n111\n\n2 1\n\n2 2 6\n\n0000\n\n1 2\n\n1 4 0\n\n1 4 1\n\n484\n\n1 5\n\n2 2 0\n\n2 3 7\n\n1 2 5\n\n3 3 8\n\n2 2 6"]
3 seconds
["2 4\n1 5\n1 2\n-1 -1\n1 2\n-1 -1\n1 3\n1 3\n-1 -1\n-1 -1\n-1 -1"]
NoteConsider the first test case of example inputs. In this test case $$$n=7$$$, $$$s=$$$"1003004", $$$w=4$$$ and one query $$$l_1=1$$$, $$$r_1=2$$$, $$$k_1=1$$$. Note that $$$v(1,2)=10$$$. We need to find a pair of substrings of length $$$4$$$ such that $$$v(L_1, L_1+3)\cdot10+v(L_2,L_2+3)$$$ has a remainder of $$$k_1=1$$$ when divided by $$$9$$$. The values $$$L_1=2, L_2=4$$$ actually satisfy all the requirements: $$$v(L_1, L_1+w-1)=v(2,5)=30$$$, $$$v(L_2, L_2+w-1)=v(4,7)=3004$$$. Indeed, $$$30\cdot10+3004=3304$$$, which has a remainder of $$$1$$$ when divided by $$$9$$$. It can be shown that $$$L_1=2$$$ is the minimum possible value, and $$$L_2=4$$$ is the minimum possible with $$$L_1=2$$$.
Java 11
standard input
[ "hashing", "math" ]
b67870dcffa7bad682ef980dacd1f3db
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — number of input test cases. The first line of each test case contains a string $$$s$$$, which contains only the characters 0-9 and has a length $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$). The second line contains two integers $$$w, m$$$ ($$$1 \le w &lt; n, 1 \le m \le 2 \cdot 10^5$$$), where $$$n$$$ — is the length of the given string $$$s$$$. The number $$$w$$$ denotes the lengths of the substrings being searched for, and $$$m$$$ is the number of queries to be processed. The following $$$m$$$ lines contain integers $$$l_i, r_i, k_i$$$ ($$$1 \le l_i \le r_i \le n$$$, $$$0 \le k_i \le 8$$$) — $$$i$$$th query parameters. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$. It is also guaranteed that the sum of $$$m$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,900
For each request, print in a separate line: left borders of the required substrings: $$$L_1$$$ and $$$L_2$$$; -1 -1 otherwise, if there is no solution. If there are several solutions, minimize $$$L_1$$$ first, and minimize $$$L_2$$$ second.
standard output
PASSED
d80a68c7ec9ec1c5f6351b1d56fe91e0
train_110.jsonl
1662993300
Given the string $$$s$$$ of decimal digits (0-9) of length $$$n$$$.A substring is a sequence of consecutive characters of a string. The substring of this string is defined by a pair of indexes — with its left and right ends. So, each pair of indexes ($$$l, r$$$), where $$$1 \le l \le r \le n$$$, corresponds to a substring of the string $$$s$$$. We will define as $$$v(l,r)$$$ the numeric value of the corresponding substring (leading zeros are allowed in it).For example, if $$$n=7$$$, $$$s=$$$"1003004", then $$$v(1,3)=100$$$, $$$v(2,3)=0$$$ and $$$v(2,7)=3004$$$.You are given $$$n$$$, $$$s$$$ and an integer $$$w$$$ ($$$1 \le w &lt; n$$$).You need to process $$$m$$$ queries, each of which is characterized by $$$3$$$ numbers $$$l_i, r_i, k_i$$$ ($$$1 \le l_i \le r_i \le n; 0 \le k_i \le 8$$$).The answer to the $$$i$$$th query is such a pair of substrings of length $$$w$$$ that if we denote them as $$$(L_1, L_1+w-1)$$$ and $$$(L_2, L_2+w-1)$$$, then: $$$L_1 \ne L_2$$$, that is, the substrings are different; the remainder of dividing a number $$$v(L_1, L_1+w-1) \cdot v(l_i, r_i) + v(L_2, L_2 + w - 1)$$$ by $$$9$$$ is equal to $$$k_i$$$. If there are many matching substring pairs, then find a pair where $$$L_1$$$ is as small as possible. If there are many matching pairs in this case, then minimize $$$L_2$$$.Note that the answer may not exist.
256 megabytes
//Utilities import java.io.*; import java.util.*; import java.math.*; public class a { static int t; static int n; static String str; static int w, q; static int l1, r1, k; static int[] psa; static ArrayList<Integer>[] arr; static long[] pow10; static int[] mod; static Result[][] res; public static void main(String[] args) throws IOException { t = in.iscan(); outer : while (t-- > 0) { str = in.sscan(); n = str.length(); w = in.iscan(); q = in.iscan(); int[] a = new int[n]; psa = new int[n]; for (int i = 0; i < n; i++) { a[i] = Integer.parseInt(""+str.charAt(i)); psa[i] = a[i]; if (i > 0) { psa[i] += psa[i-1]; } } arr = new ArrayList[9]; for (int i = 0; i < 9; i++) { arr[i] = new ArrayList<Integer>(); } mod = new int[n-w+1]; for (int i = 0; i + w - 1 < n; i++) { mod[i] = psa[i+w-1] % 9; if (i - 1 >= 0) { mod[i] = ((mod[i] - psa[i-1] % 9) + 9) % 9; } arr[mod[i]].add(i); } res = new Result[9][9]; // [modV][k] for (int modV = 0; modV < 9; modV++) { for (int kk = 0; kk < 9; kk++) { Result curRes = new Result(-1, -1); for (int l1 = 0; l1 + w - 1 < n; l1++) { int modNeed = ((kk - mod[l1]*modV%9)%9 + 9) % 9; Integer l2 = null; if (!arr[modNeed].isEmpty() && arr[modNeed].get(0) != l1) { l2 = arr[modNeed].get(0); } else if (arr[modNeed].size() > 1 && arr[modNeed].get(1) != l1) { l2 = arr[modNeed].get(1); } if (l2 != null) { curRes = new Result(l1, l2); break; } } res[modV][kk] = curRes; } } while (q-- > 0) { l1 = in.iscan(); r1 = in.iscan(); k = in.iscan(); int mv = psa[r1-1] % 9; if (l1-2 >= 0) { mv = ((mv - psa[l1-2]) % 9 + 9) % 9; } Result r = res[mv][k]; if (r.l1 != -1 && r.l2 != -1) { out.println((r.l1+1) + " " + (r.l2+1)); } else { out.println(-1 + " " + -1); } } } out.close(); } static class Result { int l1, l2; Result(int l1, int l2){ this.l1 = l1; this.l2 = l2; } } static INPUT in = new INPUT(System.in); static PrintWriter out = new PrintWriter(System.out); private static class INPUT { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar, numChars; public INPUT (InputStream stream) { this.stream = stream; } public INPUT (String file) throws IOException { this.stream = new FileInputStream (file); } public int cscan () throws IOException { if (curChar >= numChars) { curChar = 0; numChars = stream.read (buf); } if (numChars == -1) return numChars; return buf[curChar++]; } public int iscan () throws IOException { int c = cscan (), sgn = 1; while (space (c)) c = cscan (); if (c == '-') { sgn = -1; c = cscan (); } int res = 0; do { res = (res << 1) + (res << 3); res += c - '0'; c = cscan (); } while (!space (c)); return res * sgn; } public String sscan () throws IOException { int c = cscan (); while (space (c)) c = cscan (); StringBuilder res = new StringBuilder (); do { res.appendCodePoint (c); c = cscan (); } while (!space (c)); return res.toString (); } public double dscan () throws IOException { int c = cscan (), sgn = 1; while (space (c)) c = cscan (); if (c == '-') { sgn = -1; c = cscan (); } double res = 0; while (!space (c) && c != '.') { if (c == 'e' || c == 'E') return res * UTILITIES.fast_pow (10, iscan ()); res *= 10; res += c - '0'; c = cscan (); } if (c == '.') { c = cscan (); double m = 1; while (!space (c)) { if (c == 'e' || c == 'E') return res * UTILITIES.fast_pow (10, iscan ()); m /= 10; res += (c - '0') * m; c = cscan (); } } return res * sgn; } public long lscan () throws IOException { int c = cscan (), sgn = 1; while (space (c)) c = cscan (); if (c == '-') { sgn = -1; c = cscan (); } long res = 0; do { res = (res << 1) + (res << 3); res += c - '0'; c = cscan (); } while (!space (c)); return res * sgn; } public boolean space (int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } public static class UTILITIES { static final double EPS = 10e-6; public static void sort(int[] a, boolean increasing) { ArrayList<Integer> arr = new ArrayList<Integer>(); int n = a.length; for (int i = 0; i < n; i++) { arr.add(a[i]); } Collections.sort(arr); for (int i = 0; i < n; i++) { if (increasing) { a[i] = arr.get(i); } else { a[i] = arr.get(n-1-i); } } } public static void sort(long[] a, boolean increasing) { ArrayList<Long> arr = new ArrayList<Long>(); int n = a.length; for (int i = 0; i < n; i++) { arr.add(a[i]); } Collections.sort(arr); for (int i = 0; i < n; i++) { if (increasing) { a[i] = arr.get(i); } else { a[i] = arr.get(n-1-i); } } } public static void sort(double[] a, boolean increasing) { ArrayList<Double> arr = new ArrayList<Double>(); int n = a.length; for (int i = 0; i < n; i++) { arr.add(a[i]); } Collections.sort(arr); for (int i = 0; i < n; i++) { if (increasing) { a[i] = arr.get(i); } else { a[i] = arr.get(n-1-i); } } } public static int lower_bound (int[] arr, int x) { int low = 0, high = arr.length, mid = -1; while (low < high) { mid = (low + high) / 2; if (arr[mid] >= x) high = mid; else low = mid + 1; } return low; } public static int upper_bound (int[] arr, int x) { int low = 0, high = arr.length, mid = -1; while (low < high) { mid = (low + high) / 2; if (arr[mid] > x) high = mid; else low = mid + 1; } return low; } public static void updateMap(HashMap<Integer, Integer> map, int key, int v) { if (!map.containsKey(key)) { map.put(key, v); } else { map.put(key, map.get(key) + v); } if (map.get(key) == 0) { map.remove(key); } } public static long gcd (long a, long b) { return b == 0 ? a : gcd (b, a % b); } public static long lcm (long a, long b) { return a * b / gcd (a, b); } public static long fast_pow_mod (long b, long x, int mod) { if (x == 0) return 1; if (x == 1) return b; if (x % 2 == 0) return fast_pow_mod (b * b % mod, x / 2, mod) % mod; return b * fast_pow_mod (b * b % mod, x / 2, mod) % mod; } public static long fast_pow (long b, long x) { if (x == 0) return 1; if (x == 1) return b; if (x % 2 == 0) return fast_pow (b * b, x / 2); return b * fast_pow (b * b, x / 2); } public static long choose (long n, long k) { k = Math.min (k, n - k); long val = 1; for (int i = 0; i < k; ++i) val = val * (n - i) / (i + 1); return val; } public static long permute (int n, int k) { if (n < k) return 0; long val = 1; for (int i = 0; i < k; ++i) val = (val * (n - i)); return val; } // start of permutation and lower/upper bound template public static void nextPermutation(int[] nums) { //find first decreasing digit int mark = -1; for (int i = nums.length - 1; i > 0; i--) { if (nums[i] > nums[i - 1]) { mark = i - 1; break; } } if (mark == -1) { reverse(nums, 0, nums.length - 1); return; } int idx = nums.length-1; for (int i = nums.length-1; i >= mark+1; i--) { if (nums[i] > nums[mark]) { idx = i; break; } } swap(nums, mark, idx); reverse(nums, mark + 1, nums.length - 1); } public static void swap(int[] nums, int i, int j) { int t = nums[i]; nums[i] = nums[j]; nums[j] = t; } public static void reverse(int[] nums, int i, int j) { while (i < j) { swap(nums, i, j); i++; j--; } } static int lower_bound (int[] arr, int hi, int cmp) { int low = 0, high = hi, mid = -1; while (low < high) { mid = (low + high) / 2; if (arr[mid] >= cmp) high = mid; else low = mid + 1; } return low; } static int upper_bound (int[] arr, int hi, int cmp) { int low = 0, high = hi, mid = -1; while (low < high) { mid = (low + high) / 2; if (arr[mid] > cmp) high = mid; else low = mid + 1; } return low; } // end of permutation and lower/upper bound template } }
Java
["5\n\n1003004\n\n4 1\n\n1 2 1\n\n179572007\n\n4 2\n\n2 7 3\n\n2 7 4\n\n111\n\n2 1\n\n2 2 6\n\n0000\n\n1 2\n\n1 4 0\n\n1 4 1\n\n484\n\n1 5\n\n2 2 0\n\n2 3 7\n\n1 2 5\n\n3 3 8\n\n2 2 6"]
3 seconds
["2 4\n1 5\n1 2\n-1 -1\n1 2\n-1 -1\n1 3\n1 3\n-1 -1\n-1 -1\n-1 -1"]
NoteConsider the first test case of example inputs. In this test case $$$n=7$$$, $$$s=$$$"1003004", $$$w=4$$$ and one query $$$l_1=1$$$, $$$r_1=2$$$, $$$k_1=1$$$. Note that $$$v(1,2)=10$$$. We need to find a pair of substrings of length $$$4$$$ such that $$$v(L_1, L_1+3)\cdot10+v(L_2,L_2+3)$$$ has a remainder of $$$k_1=1$$$ when divided by $$$9$$$. The values $$$L_1=2, L_2=4$$$ actually satisfy all the requirements: $$$v(L_1, L_1+w-1)=v(2,5)=30$$$, $$$v(L_2, L_2+w-1)=v(4,7)=3004$$$. Indeed, $$$30\cdot10+3004=3304$$$, which has a remainder of $$$1$$$ when divided by $$$9$$$. It can be shown that $$$L_1=2$$$ is the minimum possible value, and $$$L_2=4$$$ is the minimum possible with $$$L_1=2$$$.
Java 11
standard input
[ "hashing", "math" ]
b67870dcffa7bad682ef980dacd1f3db
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — number of input test cases. The first line of each test case contains a string $$$s$$$, which contains only the characters 0-9 and has a length $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$). The second line contains two integers $$$w, m$$$ ($$$1 \le w &lt; n, 1 \le m \le 2 \cdot 10^5$$$), where $$$n$$$ — is the length of the given string $$$s$$$. The number $$$w$$$ denotes the lengths of the substrings being searched for, and $$$m$$$ is the number of queries to be processed. The following $$$m$$$ lines contain integers $$$l_i, r_i, k_i$$$ ($$$1 \le l_i \le r_i \le n$$$, $$$0 \le k_i \le 8$$$) — $$$i$$$th query parameters. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$. It is also guaranteed that the sum of $$$m$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,900
For each request, print in a separate line: left borders of the required substrings: $$$L_1$$$ and $$$L_2$$$; -1 -1 otherwise, if there is no solution. If there are several solutions, minimize $$$L_1$$$ first, and minimize $$$L_2$$$ second.
standard output
PASSED
a66e1c5f80237bb185e825fce6db619f
train_110.jsonl
1662993300
Given the string $$$s$$$ of decimal digits (0-9) of length $$$n$$$.A substring is a sequence of consecutive characters of a string. The substring of this string is defined by a pair of indexes — with its left and right ends. So, each pair of indexes ($$$l, r$$$), where $$$1 \le l \le r \le n$$$, corresponds to a substring of the string $$$s$$$. We will define as $$$v(l,r)$$$ the numeric value of the corresponding substring (leading zeros are allowed in it).For example, if $$$n=7$$$, $$$s=$$$"1003004", then $$$v(1,3)=100$$$, $$$v(2,3)=0$$$ and $$$v(2,7)=3004$$$.You are given $$$n$$$, $$$s$$$ and an integer $$$w$$$ ($$$1 \le w &lt; n$$$).You need to process $$$m$$$ queries, each of which is characterized by $$$3$$$ numbers $$$l_i, r_i, k_i$$$ ($$$1 \le l_i \le r_i \le n; 0 \le k_i \le 8$$$).The answer to the $$$i$$$th query is such a pair of substrings of length $$$w$$$ that if we denote them as $$$(L_1, L_1+w-1)$$$ and $$$(L_2, L_2+w-1)$$$, then: $$$L_1 \ne L_2$$$, that is, the substrings are different; the remainder of dividing a number $$$v(L_1, L_1+w-1) \cdot v(l_i, r_i) + v(L_2, L_2 + w - 1)$$$ by $$$9$$$ is equal to $$$k_i$$$. If there are many matching substring pairs, then find a pair where $$$L_1$$$ is as small as possible. If there are many matching pairs in this case, then minimize $$$L_2$$$.Note that the answer may not exist.
256 megabytes
//Utilities import java.io.*; import java.util.*; import java.math.*; public class a { static int t; static int n; static String str; static int w, q; static int l1, r1, k; static SegmentTree st; static ArrayList<Integer>[] arr; static long[] pow10; static int[] mod; static Result[][] res; public static void main(String[] args) throws IOException { pow10 = new long[(int)2e5+5]; pow10[0] = 1; for (int i = 1; i < (int)2e5+5; i++) { pow10[i] = pow10[i-1] * 10 % 9; } t = in.iscan(); outer : while (t-- > 0) { str = in.sscan(); n = str.length(); w = in.iscan(); q = in.iscan(); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = Integer.parseInt(""+str.charAt(i)); } st = new SegmentTree(n, a); arr = new ArrayList[9]; for (int i = 0; i < 9; i++) { arr[i] = new ArrayList<Integer>(); } mod = new int[n-w+1]; for (int i = 0; i + w - 1 < n; i++) { mod[i] = (int)st.query(1, 0, n-1, i, i+w-1); arr[mod[i]].add(i); } res = new Result[9][9]; // [modV][k] for (int modV = 0; modV < 9; modV++) { for (int kk = 0; kk < 9; kk++) { Result curRes = new Result(-1, -1); for (int l1 = 0; l1 + w - 1 < n; l1++) { int modNeed = ((kk - mod[l1]*modV%9)%9 + 9) % 9; Integer l2 = null; if (!arr[modNeed].isEmpty() && arr[modNeed].get(0) != l1) { l2 = arr[modNeed].get(0); } else if (arr[modNeed].size() > 1 && arr[modNeed].get(1) != l1) { l2 = arr[modNeed].get(1); } if (l2 != null) { curRes = new Result(l1, l2); break; } } res[modV][kk] = curRes; } } while (q-- > 0) { l1 = in.iscan(); r1 = in.iscan(); k = in.iscan(); int mv = (int)st.query(1, 0, n-1, l1-1, r1-1); Result r = res[mv][k]; if (r.l1 != -1 && r.l2 != -1) { out.println((r.l1+1) + " " + (r.l2+1)); } else { out.println(-1 + " " + -1); } } } out.close(); } static class Result { int l1, l2; Result(int l1, int l2){ this.l1 = l1; this.l2 = l2; } } static class SegmentTree { int n; int[] a; long[] st; SegmentTree(int n){ this.n = n; a = new int[n]; st = new long[4*n+5]; } SegmentTree(int n, int[] b){ this.n = n; a = new int[n]; for (int i = 0; i < n; i++) { a[i] = b[i]; } st = new long[4*n+5]; init(1, 0, n-1); } void init(int i, int l, int r){ if (l == r) { st[i] = a[l] % 9; return; } int mid = (l+r)/2; init(2*i, l, mid); init(2*i+1, mid + 1, r); st[i] = comb(st[2*i], st[2*i+1], r-(mid+1)+1); } void update(int i, int l, int r, int idx, int v){ if (l == r) { st[i] = v; return; } int mid = (l+r)/2; if (idx <= mid) { update(2*i, l, mid, idx, v); } else { update(2*i+1, mid + 1, r, idx, v); } st[i] = comb(st[2*i], st[2*i+1], r-(mid+1)+1); } long query(int i, int l, int r, int ql, int qr){ if (qr < l || ql > r) return 0; if (ql <= l && r <= qr) return st[i]; int mid = (l+r) / 2; return comb(query(2*i, l, mid, ql, qr), query(2*i+1, mid + 1, r, ql, qr), r-(mid+1)+1); } long comb(long a, long b, int lenB) { return (a * pow10[lenB] % 9 + b) % 9; } } static INPUT in = new INPUT(System.in); static PrintWriter out = new PrintWriter(System.out); private static class INPUT { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar, numChars; public INPUT (InputStream stream) { this.stream = stream; } public INPUT (String file) throws IOException { this.stream = new FileInputStream (file); } public int cscan () throws IOException { if (curChar >= numChars) { curChar = 0; numChars = stream.read (buf); } if (numChars == -1) return numChars; return buf[curChar++]; } public int iscan () throws IOException { int c = cscan (), sgn = 1; while (space (c)) c = cscan (); if (c == '-') { sgn = -1; c = cscan (); } int res = 0; do { res = (res << 1) + (res << 3); res += c - '0'; c = cscan (); } while (!space (c)); return res * sgn; } public String sscan () throws IOException { int c = cscan (); while (space (c)) c = cscan (); StringBuilder res = new StringBuilder (); do { res.appendCodePoint (c); c = cscan (); } while (!space (c)); return res.toString (); } public double dscan () throws IOException { int c = cscan (), sgn = 1; while (space (c)) c = cscan (); if (c == '-') { sgn = -1; c = cscan (); } double res = 0; while (!space (c) && c != '.') { if (c == 'e' || c == 'E') return res * UTILITIES.fast_pow (10, iscan ()); res *= 10; res += c - '0'; c = cscan (); } if (c == '.') { c = cscan (); double m = 1; while (!space (c)) { if (c == 'e' || c == 'E') return res * UTILITIES.fast_pow (10, iscan ()); m /= 10; res += (c - '0') * m; c = cscan (); } } return res * sgn; } public long lscan () throws IOException { int c = cscan (), sgn = 1; while (space (c)) c = cscan (); if (c == '-') { sgn = -1; c = cscan (); } long res = 0; do { res = (res << 1) + (res << 3); res += c - '0'; c = cscan (); } while (!space (c)); return res * sgn; } public boolean space (int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } public static class UTILITIES { static final double EPS = 10e-6; public static void sort(int[] a, boolean increasing) { ArrayList<Integer> arr = new ArrayList<Integer>(); int n = a.length; for (int i = 0; i < n; i++) { arr.add(a[i]); } Collections.sort(arr); for (int i = 0; i < n; i++) { if (increasing) { a[i] = arr.get(i); } else { a[i] = arr.get(n-1-i); } } } public static void sort(long[] a, boolean increasing) { ArrayList<Long> arr = new ArrayList<Long>(); int n = a.length; for (int i = 0; i < n; i++) { arr.add(a[i]); } Collections.sort(arr); for (int i = 0; i < n; i++) { if (increasing) { a[i] = arr.get(i); } else { a[i] = arr.get(n-1-i); } } } public static void sort(double[] a, boolean increasing) { ArrayList<Double> arr = new ArrayList<Double>(); int n = a.length; for (int i = 0; i < n; i++) { arr.add(a[i]); } Collections.sort(arr); for (int i = 0; i < n; i++) { if (increasing) { a[i] = arr.get(i); } else { a[i] = arr.get(n-1-i); } } } public static int lower_bound (int[] arr, int x) { int low = 0, high = arr.length, mid = -1; while (low < high) { mid = (low + high) / 2; if (arr[mid] >= x) high = mid; else low = mid + 1; } return low; } public static int upper_bound (int[] arr, int x) { int low = 0, high = arr.length, mid = -1; while (low < high) { mid = (low + high) / 2; if (arr[mid] > x) high = mid; else low = mid + 1; } return low; } public static void updateMap(HashMap<Integer, Integer> map, int key, int v) { if (!map.containsKey(key)) { map.put(key, v); } else { map.put(key, map.get(key) + v); } if (map.get(key) == 0) { map.remove(key); } } public static long gcd (long a, long b) { return b == 0 ? a : gcd (b, a % b); } public static long lcm (long a, long b) { return a * b / gcd (a, b); } public static long fast_pow_mod (long b, long x, int mod) { if (x == 0) return 1; if (x == 1) return b; if (x % 2 == 0) return fast_pow_mod (b * b % mod, x / 2, mod) % mod; return b * fast_pow_mod (b * b % mod, x / 2, mod) % mod; } public static long fast_pow (long b, long x) { if (x == 0) return 1; if (x == 1) return b; if (x % 2 == 0) return fast_pow (b * b, x / 2); return b * fast_pow (b * b, x / 2); } public static long choose (long n, long k) { k = Math.min (k, n - k); long val = 1; for (int i = 0; i < k; ++i) val = val * (n - i) / (i + 1); return val; } public static long permute (int n, int k) { if (n < k) return 0; long val = 1; for (int i = 0; i < k; ++i) val = (val * (n - i)); return val; } // start of permutation and lower/upper bound template public static void nextPermutation(int[] nums) { //find first decreasing digit int mark = -1; for (int i = nums.length - 1; i > 0; i--) { if (nums[i] > nums[i - 1]) { mark = i - 1; break; } } if (mark == -1) { reverse(nums, 0, nums.length - 1); return; } int idx = nums.length-1; for (int i = nums.length-1; i >= mark+1; i--) { if (nums[i] > nums[mark]) { idx = i; break; } } swap(nums, mark, idx); reverse(nums, mark + 1, nums.length - 1); } public static void swap(int[] nums, int i, int j) { int t = nums[i]; nums[i] = nums[j]; nums[j] = t; } public static void reverse(int[] nums, int i, int j) { while (i < j) { swap(nums, i, j); i++; j--; } } static int lower_bound (int[] arr, int hi, int cmp) { int low = 0, high = hi, mid = -1; while (low < high) { mid = (low + high) / 2; if (arr[mid] >= cmp) high = mid; else low = mid + 1; } return low; } static int upper_bound (int[] arr, int hi, int cmp) { int low = 0, high = hi, mid = -1; while (low < high) { mid = (low + high) / 2; if (arr[mid] > cmp) high = mid; else low = mid + 1; } return low; } // end of permutation and lower/upper bound template } }
Java
["5\n\n1003004\n\n4 1\n\n1 2 1\n\n179572007\n\n4 2\n\n2 7 3\n\n2 7 4\n\n111\n\n2 1\n\n2 2 6\n\n0000\n\n1 2\n\n1 4 0\n\n1 4 1\n\n484\n\n1 5\n\n2 2 0\n\n2 3 7\n\n1 2 5\n\n3 3 8\n\n2 2 6"]
3 seconds
["2 4\n1 5\n1 2\n-1 -1\n1 2\n-1 -1\n1 3\n1 3\n-1 -1\n-1 -1\n-1 -1"]
NoteConsider the first test case of example inputs. In this test case $$$n=7$$$, $$$s=$$$"1003004", $$$w=4$$$ and one query $$$l_1=1$$$, $$$r_1=2$$$, $$$k_1=1$$$. Note that $$$v(1,2)=10$$$. We need to find a pair of substrings of length $$$4$$$ such that $$$v(L_1, L_1+3)\cdot10+v(L_2,L_2+3)$$$ has a remainder of $$$k_1=1$$$ when divided by $$$9$$$. The values $$$L_1=2, L_2=4$$$ actually satisfy all the requirements: $$$v(L_1, L_1+w-1)=v(2,5)=30$$$, $$$v(L_2, L_2+w-1)=v(4,7)=3004$$$. Indeed, $$$30\cdot10+3004=3304$$$, which has a remainder of $$$1$$$ when divided by $$$9$$$. It can be shown that $$$L_1=2$$$ is the minimum possible value, and $$$L_2=4$$$ is the minimum possible with $$$L_1=2$$$.
Java 11
standard input
[ "hashing", "math" ]
b67870dcffa7bad682ef980dacd1f3db
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — number of input test cases. The first line of each test case contains a string $$$s$$$, which contains only the characters 0-9 and has a length $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$). The second line contains two integers $$$w, m$$$ ($$$1 \le w &lt; n, 1 \le m \le 2 \cdot 10^5$$$), where $$$n$$$ — is the length of the given string $$$s$$$. The number $$$w$$$ denotes the lengths of the substrings being searched for, and $$$m$$$ is the number of queries to be processed. The following $$$m$$$ lines contain integers $$$l_i, r_i, k_i$$$ ($$$1 \le l_i \le r_i \le n$$$, $$$0 \le k_i \le 8$$$) — $$$i$$$th query parameters. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$. It is also guaranteed that the sum of $$$m$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,900
For each request, print in a separate line: left borders of the required substrings: $$$L_1$$$ and $$$L_2$$$; -1 -1 otherwise, if there is no solution. If there are several solutions, minimize $$$L_1$$$ first, and minimize $$$L_2$$$ second.
standard output
PASSED
f818404a9b4d5289b90ae86560c03708
train_110.jsonl
1662993300
Given the string $$$s$$$ of decimal digits (0-9) of length $$$n$$$.A substring is a sequence of consecutive characters of a string. The substring of this string is defined by a pair of indexes — with its left and right ends. So, each pair of indexes ($$$l, r$$$), where $$$1 \le l \le r \le n$$$, corresponds to a substring of the string $$$s$$$. We will define as $$$v(l,r)$$$ the numeric value of the corresponding substring (leading zeros are allowed in it).For example, if $$$n=7$$$, $$$s=$$$"1003004", then $$$v(1,3)=100$$$, $$$v(2,3)=0$$$ and $$$v(2,7)=3004$$$.You are given $$$n$$$, $$$s$$$ and an integer $$$w$$$ ($$$1 \le w &lt; n$$$).You need to process $$$m$$$ queries, each of which is characterized by $$$3$$$ numbers $$$l_i, r_i, k_i$$$ ($$$1 \le l_i \le r_i \le n; 0 \le k_i \le 8$$$).The answer to the $$$i$$$th query is such a pair of substrings of length $$$w$$$ that if we denote them as $$$(L_1, L_1+w-1)$$$ and $$$(L_2, L_2+w-1)$$$, then: $$$L_1 \ne L_2$$$, that is, the substrings are different; the remainder of dividing a number $$$v(L_1, L_1+w-1) \cdot v(l_i, r_i) + v(L_2, L_2 + w - 1)$$$ by $$$9$$$ is equal to $$$k_i$$$. If there are many matching substring pairs, then find a pair where $$$L_1$$$ is as small as possible. If there are many matching pairs in this case, then minimize $$$L_2$$$.Note that the answer may not exist.
256 megabytes
import java.io.*; import java.util.*; public class Main { static class Pair { int x, y; Pair (int x, int y){ this.x = x; this.y = y; } } public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); int testcase = Integer.parseInt(br.readLine()); ArrayList<Pair>[][] ans = new ArrayList[9][9]; for (int i=0;i<9;i++){ for (int j=0;j<9;j++) ans[i][j] = new ArrayList<>(); } for(int i=0;i<9;i++) { for (int j=0;j<9;j++) { for (int k=0;k<9;k++) { ans[i][(j * i + k) % 9].add(new Pair(j, k)); } } } Pair[][] aa = new Pair[9][9]; ArrayList<Integer>[] lines = new ArrayList[9]; for(int i=0;i<9;i++) lines[i] = new ArrayList<>(); while(testcase-->0) { int[] num = changer(br.readLine().toCharArray()); StringTokenizer st = new StringTokenizer(br.readLine()); int w = Integer.parseInt(st.nextToken()), queries = Integer.parseInt(st.nextToken()); int[] prefix = new int[num.length+1]; for (int i=1;i< prefix.length;i++) { prefix[i] = prefix[i-1] + num[i-1]; } for(int i=0;i+w<prefix.length;i++) { int v = (prefix[i+w] - prefix[i]) % 9; lines[v].add(i+1); } if (queries > 9) { for(int i=0;i<9;i++) { for(int j=0;j<9;j++) { Pair answer = new Pair(Integer.MAX_VALUE, Integer.MAX_VALUE); for (Pair p : ans[i][j]) { try { if (p.x == p.y) { compare(answer, lines[p.x].get(0), lines[p.y].get(1)); } else { compare(answer, lines[p.x].get(0), lines[p.y].get(0)); } } catch (Exception ex) { } } if(answer.x == Integer.MAX_VALUE) { answer.x = -1; answer.y = -1; } aa[i][j] = answer; } } for (int i=0;i<queries;i++) { st = new StringTokenizer(br.readLine()); int a = Integer.parseInt(st.nextToken()), b = Integer.parseInt(st.nextToken()), c = Integer.parseInt(st.nextToken()); int v = (prefix[b] - prefix[a-1]) % 9; bw.write(aa[v][c].x +" "+aa[v][c].y+"\n"); } } else { for (int i=0;i<queries;i++) { st = new StringTokenizer(br.readLine()); int a = Integer.parseInt(st.nextToken()), b = Integer.parseInt(st.nextToken()), c = Integer.parseInt(st.nextToken()); Pair answer = new Pair(Integer.MAX_VALUE, Integer.MAX_VALUE); int v = (prefix[b] - prefix[a-1]) % 9; for (Pair p : ans[v][c]) { try { if (p.x == p.y) { compare(answer, lines[p.x].get(0), lines[p.y].get(1)); } else { compare(answer, lines[p.x].get(0), lines[p.y].get(0)); } } catch (Exception ex) { } } if (answer.x == Integer.MAX_VALUE) { bw.write("-1 -1\n"); } else { bw.write(answer.x+" "+answer.y+"\n"); } } } for(ArrayList<Integer> l : lines) l.clear(); } bw.flush(); } public static void compare(Pair a, int x, int y) { if (x == 0 || y==0) return; if (a.x > x) { a.x = x; a.y = y; } else if (a.x == x) { a.y = Math.min(a.y, y); } } public static int[] changer(char[] s) { int[] r = new int[s.length]; for (int i=0;i<s.length;i++) { r[i] = s[i] - '0'; } return r; } }
Java
["5\n\n1003004\n\n4 1\n\n1 2 1\n\n179572007\n\n4 2\n\n2 7 3\n\n2 7 4\n\n111\n\n2 1\n\n2 2 6\n\n0000\n\n1 2\n\n1 4 0\n\n1 4 1\n\n484\n\n1 5\n\n2 2 0\n\n2 3 7\n\n1 2 5\n\n3 3 8\n\n2 2 6"]
3 seconds
["2 4\n1 5\n1 2\n-1 -1\n1 2\n-1 -1\n1 3\n1 3\n-1 -1\n-1 -1\n-1 -1"]
NoteConsider the first test case of example inputs. In this test case $$$n=7$$$, $$$s=$$$"1003004", $$$w=4$$$ and one query $$$l_1=1$$$, $$$r_1=2$$$, $$$k_1=1$$$. Note that $$$v(1,2)=10$$$. We need to find a pair of substrings of length $$$4$$$ such that $$$v(L_1, L_1+3)\cdot10+v(L_2,L_2+3)$$$ has a remainder of $$$k_1=1$$$ when divided by $$$9$$$. The values $$$L_1=2, L_2=4$$$ actually satisfy all the requirements: $$$v(L_1, L_1+w-1)=v(2,5)=30$$$, $$$v(L_2, L_2+w-1)=v(4,7)=3004$$$. Indeed, $$$30\cdot10+3004=3304$$$, which has a remainder of $$$1$$$ when divided by $$$9$$$. It can be shown that $$$L_1=2$$$ is the minimum possible value, and $$$L_2=4$$$ is the minimum possible with $$$L_1=2$$$.
Java 11
standard input
[ "hashing", "math" ]
b67870dcffa7bad682ef980dacd1f3db
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — number of input test cases. The first line of each test case contains a string $$$s$$$, which contains only the characters 0-9 and has a length $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$). The second line contains two integers $$$w, m$$$ ($$$1 \le w &lt; n, 1 \le m \le 2 \cdot 10^5$$$), where $$$n$$$ — is the length of the given string $$$s$$$. The number $$$w$$$ denotes the lengths of the substrings being searched for, and $$$m$$$ is the number of queries to be processed. The following $$$m$$$ lines contain integers $$$l_i, r_i, k_i$$$ ($$$1 \le l_i \le r_i \le n$$$, $$$0 \le k_i \le 8$$$) — $$$i$$$th query parameters. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$. It is also guaranteed that the sum of $$$m$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,900
For each request, print in a separate line: left borders of the required substrings: $$$L_1$$$ and $$$L_2$$$; -1 -1 otherwise, if there is no solution. If there are several solutions, minimize $$$L_1$$$ first, and minimize $$$L_2$$$ second.
standard output
PASSED
e961dfc2e3925e827d966edc40a6d7f5
train_110.jsonl
1662993300
Given the string $$$s$$$ of decimal digits (0-9) of length $$$n$$$.A substring is a sequence of consecutive characters of a string. The substring of this string is defined by a pair of indexes — with its left and right ends. So, each pair of indexes ($$$l, r$$$), where $$$1 \le l \le r \le n$$$, corresponds to a substring of the string $$$s$$$. We will define as $$$v(l,r)$$$ the numeric value of the corresponding substring (leading zeros are allowed in it).For example, if $$$n=7$$$, $$$s=$$$"1003004", then $$$v(1,3)=100$$$, $$$v(2,3)=0$$$ and $$$v(2,7)=3004$$$.You are given $$$n$$$, $$$s$$$ and an integer $$$w$$$ ($$$1 \le w &lt; n$$$).You need to process $$$m$$$ queries, each of which is characterized by $$$3$$$ numbers $$$l_i, r_i, k_i$$$ ($$$1 \le l_i \le r_i \le n; 0 \le k_i \le 8$$$).The answer to the $$$i$$$th query is such a pair of substrings of length $$$w$$$ that if we denote them as $$$(L_1, L_1+w-1)$$$ and $$$(L_2, L_2+w-1)$$$, then: $$$L_1 \ne L_2$$$, that is, the substrings are different; the remainder of dividing a number $$$v(L_1, L_1+w-1) \cdot v(l_i, r_i) + v(L_2, L_2 + w - 1)$$$ by $$$9$$$ is equal to $$$k_i$$$. If there are many matching substring pairs, then find a pair where $$$L_1$$$ is as small as possible. If there are many matching pairs in this case, then minimize $$$L_2$$$.Note that the answer may not exist.
256 megabytes
//package com.example.practice.codeforces; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.StringTokenizer; public class Solution { public static void main (String [] args) throws IOException { // Use BufferedReader rather than RandomAccessFile; it's much faster final BufferedReader input = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); // input file name goes above int Q = Integer.parseInt(input.readLine()); while (Q > 0) { final char[] cc = input.readLine().toCharArray(); StringTokenizer st = new StringTokenizer(input.readLine()); final int w = Integer.parseInt(st.nextToken()), m = Integer.parseInt(st.nextToken()); final int[][] qs = readArray2DInt(m, m, input); printArray2DInt(calc(cc, w, m, qs), m, out); Q--; } out.close(); // close the output file } private static int[][] calc(final char[] cc, final int w, final int m, final int[][] qs) { final int n = cc.length; int[][] rd = new int[9][2]; int[] sum = new int[n], sum2 = new int[n+1]; for (int i=0;i<9;++i){ Arrays.fill(rd[i], -1); } sum2[0] = 1; for (int i=1;i<=n;++i){ sum2[i] = sum2[i-1] * 10 % 9; sum[i-1] = cc[i-1] - '0'; if (i>1){ sum[i-1] += sum[i-2] * 10; } sum[i-1] = sum[i-1] % 9; } rd[get(sum, sum2, 0, w-1)][0] = 0; for (int i=1;i+w<=n;++i){ int v = get(sum, sum2, i, i+w-1); if (rd[v][0]==-1){ rd[v][0] = i; }else if (rd[v][1]==-1){ rd[v][1] = i; } } int[][] res = new int[m][]; for (int i=0;i<m;++i){ res[i] = new int[]{-1, -1}; final int v = get(sum, sum2, qs[i][0]-1, qs[i][1]-1); for (int j=0;j<9;++j){ for (int k=0;k<9;++k){ if (((j*v+k) % 9) == qs[i][2]){ if (j==k){ if (rd[j][1] >= 0){ if (res[i][0]==-1 || res[i][0]>rd[j][0] || (res[i][0]==rd[j][0] && res[i][1]>rd[j][1])){ res[i][0] = rd[j][0]; res[i][1] = rd[j][1]; } } }else if (rd[j][0]>=0 && rd[k][0]>=0){ if (res[i][0]==-1 || res[i][0]>rd[j][0] || (res[i][0]==rd[j][0] && res[i][1]>rd[k][0])){ res[i][0] = rd[j][0]; res[i][1] = rd[k][0]; } } } } } if (res[i][0]!=-1){ res[i][0]++; res[i][1]++; } } return res; } private static int get(final int[] sum, final int[] sum2, int l, int r){ int res = sum[r] - (l==0 ? 0 : (sum[l-1] * sum2[r-l+1]) % 9); if (res<0)res+=9; return res; } private static void printArray(long[] ns, final PrintWriter out){ for (int i=0;i<ns.length;++i){ out.print(ns[i]); if (i+1<ns.length)out.print(" "); else out.println(); } } private static void printArrayInt(int[] ns, final PrintWriter out){ for (int i=0;i<ns.length;++i){ out.print(ns[i]); if (i+1<ns.length)out.print(" "); else out.println(); } } private static void printArrayVertical(long[] ns, final PrintWriter out){ for (long a : ns){ out.println(a); } } private static void printArrayVerticalInt(int[] ns, final PrintWriter out){ for (int a : ns){ out.println(a); } } private static void printArray2D(long[][] ns, final int len, final PrintWriter out){ int cnt = 0; for (long[] kk : ns){ cnt++; if (cnt > len)break; for (int i=0;i<kk.length;++i){ out.print(kk[i]); if (i+1<kk.length)out.print(" "); else out.println(); } } } private static void printArray2DInt(int[][] ns, final int len, final PrintWriter out){ int cnt = 0; for (int[] kk : ns){ cnt++; if (cnt > len)break; for (int i=0;i<kk.length;++i){ out.print(kk[i]); if (i+1<kk.length)out.print(" "); else out.println(); } } } private static long[] readArray(final int n, final BufferedReader input) throws IOException{ long[] ns = new long[n]; StringTokenizer st = new StringTokenizer(input.readLine()); for (int i=0;i<n;++i){ ns[i] = Long.parseLong(st.nextToken()); } return ns; } private static int[] readArrayInt(final int n, final BufferedReader input) throws IOException{ int[] ns = new int[n]; StringTokenizer st = new StringTokenizer(input.readLine()); for (int i=0;i<n;++i){ ns[i] = Integer.parseInt(st.nextToken()); } return ns; } private static long[] readArrayVertical(final int n, final BufferedReader input) throws IOException{ long[] ns = new long[n]; for (int i=0;i<n;++i){ ns[i] = Long.parseLong(input.readLine()); } return ns; } private static int[] readArrayVerticalInt(final int n, final BufferedReader input) throws IOException{ int[] ns = new int[n]; for (int i=0;i<n;++i){ ns[i] = Integer.parseInt(input.readLine()); } return ns; } private static long[][] readArray2D(final int n, final int len, final BufferedReader input) throws IOException{ long[][] ns = new long[len][]; for (int i=0;i<n;++i){ StringTokenizer st = new StringTokenizer(input.readLine()); ArrayList<Long> al = new ArrayList<>(); while (st.hasMoreTokens()){ al.add(Long.parseLong(st.nextToken())); } long[] kk = new long[al.size()]; for (int j=0;j<kk.length;++j){ kk[j] = al.get(j); } ns[i] = kk; } return ns; } private static int[][] readArray2DInt(final int n, final int len, final BufferedReader input) throws IOException{ int[][] ns = new int[len][]; for (int i=0;i<n;++i){ StringTokenizer st = new StringTokenizer(input.readLine()); ArrayList<Integer> al = new ArrayList<>(); while (st.hasMoreTokens()){ al.add(Integer.parseInt(st.nextToken())); } int[] kk = new int[al.size()]; for (int j=0;j<kk.length;++j){ kk[j] = al.get(j); } ns[i] = kk; } return ns; } private static int GCD(int x, int y){ if (x > y)return GCD(y, x); if (x==0)return y; return GCD(y%x, x); } private static long GCD(long x, long y){ if (x > y)return GCD(y, x); if (x==0)return y; return GCD(y%x, x); } static class SegTree{ int st; int en; int mid; int val1; int val2; SegTree left; SegTree right; public SegTree(int l, int r, int d){ st = l; en = r; mid = (st + en) >> 1; val1 = val2 = d; if (st<en){ left = new SegTree(st, mid, d); right = new SegTree(mid+1, en, d); }else { left = right = null; } } public SegTree(int l, int r, int[] ns){ st = l; en = r; mid = (st + en) >> 1; if (st==en){ val1 = val2 = ns[st]; }else { left = new SegTree(l, mid, ns); right = new SegTree(mid+1, r, ns); val1 = Math.min(left.val1, right.val1); val2 = Math.max(left.val2, right.val2); } } void update(int idx, int v){ if (st==en){ val1 = val2 = v; }else { if (idx <= mid){ left.update(idx, v); }else { right.update(idx, v); } val1 = Math.min(left.val1, right.val1); val2 = Math.max(left.val2, right.val2); } } int getMin(int l, int r){ if (st==en || (l==st && r==en))return val1; if (r<=mid){ return left.getMin(l, r); } if (l>mid){ return right.getMin(l, r); } return Math.min(left.getMin(l, mid), right.getMin(mid+1, r)); } int getMax(int l, int r){ if (st==en || (l==st && r==en))return val2; if (r<=mid){ return left.getMax(l, r); } if (l>mid){ return right.getMax(l, r); } return Math.max(left.getMax(l, mid), right.getMax(mid+1, r)); } } static class SparseTable{ int[][] minTable; int[][] maxTable; int[] log2; int n; public SparseTable(final int[] ns){ n = ns.length; int m = 0, pre = 0; while (1<<m < n){ m++; } m++; minTable = new int[n][m]; maxTable = new int[n][m]; log2 = new int[n+1]; for (int i=0;i<n;++i){ minTable[i][0] = ns[i]; maxTable[i][0] = ns[i]; if ((1<<(pre+1)) == i+1){ pre++; } log2[i+1] = pre; } for (int i=1;i<m;++i){ for (int j=0;j<n;++j){ int r = Math.min(n-1, j+(1<<i)-1); if (r-(1<<(i-1))+1 <= j){ minTable[j][i] = minTable[j][i-1]; maxTable[j][i] = maxTable[j][i-1]; }else { minTable[j][i] = Math.min(minTable[j][i-1], minTable[r-(1<<(i-1))+1][i-1]); maxTable[j][i] = Math.max(maxTable[j][i-1], maxTable[r-(1<<(i-1))+1][i-1]); } } } } int getMin(final int l, final int r){ int d = log2[r-l+1]; return Math.min(minTable[l][d], minTable[r-(1<<d)+1][d]); } int getMax(final int l, final int r){ int d = log2[r-l+1]; return Math.max(maxTable[l][d], maxTable[r-(1<<d)+1][d]); } } static class BIT{ long[] ns; public BIT(int n){ ns = new long[n]; } void add(int idx, int v){ for (int i=idx; i<ns.length; i += -i & i){ ns[i] += v; } } long get(int idx){ long res = 0; for (int i=idx; i>0; i -= -i & i){ res += ns[i]; } return res; } } }
Java
["5\n\n1003004\n\n4 1\n\n1 2 1\n\n179572007\n\n4 2\n\n2 7 3\n\n2 7 4\n\n111\n\n2 1\n\n2 2 6\n\n0000\n\n1 2\n\n1 4 0\n\n1 4 1\n\n484\n\n1 5\n\n2 2 0\n\n2 3 7\n\n1 2 5\n\n3 3 8\n\n2 2 6"]
3 seconds
["2 4\n1 5\n1 2\n-1 -1\n1 2\n-1 -1\n1 3\n1 3\n-1 -1\n-1 -1\n-1 -1"]
NoteConsider the first test case of example inputs. In this test case $$$n=7$$$, $$$s=$$$"1003004", $$$w=4$$$ and one query $$$l_1=1$$$, $$$r_1=2$$$, $$$k_1=1$$$. Note that $$$v(1,2)=10$$$. We need to find a pair of substrings of length $$$4$$$ such that $$$v(L_1, L_1+3)\cdot10+v(L_2,L_2+3)$$$ has a remainder of $$$k_1=1$$$ when divided by $$$9$$$. The values $$$L_1=2, L_2=4$$$ actually satisfy all the requirements: $$$v(L_1, L_1+w-1)=v(2,5)=30$$$, $$$v(L_2, L_2+w-1)=v(4,7)=3004$$$. Indeed, $$$30\cdot10+3004=3304$$$, which has a remainder of $$$1$$$ when divided by $$$9$$$. It can be shown that $$$L_1=2$$$ is the minimum possible value, and $$$L_2=4$$$ is the minimum possible with $$$L_1=2$$$.
Java 11
standard input
[ "hashing", "math" ]
b67870dcffa7bad682ef980dacd1f3db
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — number of input test cases. The first line of each test case contains a string $$$s$$$, which contains only the characters 0-9 and has a length $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$). The second line contains two integers $$$w, m$$$ ($$$1 \le w &lt; n, 1 \le m \le 2 \cdot 10^5$$$), where $$$n$$$ — is the length of the given string $$$s$$$. The number $$$w$$$ denotes the lengths of the substrings being searched for, and $$$m$$$ is the number of queries to be processed. The following $$$m$$$ lines contain integers $$$l_i, r_i, k_i$$$ ($$$1 \le l_i \le r_i \le n$$$, $$$0 \le k_i \le 8$$$) — $$$i$$$th query parameters. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$. It is also guaranteed that the sum of $$$m$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,900
For each request, print in a separate line: left borders of the required substrings: $$$L_1$$$ and $$$L_2$$$; -1 -1 otherwise, if there is no solution. If there are several solutions, minimize $$$L_1$$$ first, and minimize $$$L_2$$$ second.
standard output
PASSED
eb7943f797d2c6ddff3dcf1f1576d574
train_110.jsonl
1662993300
Given the string $$$s$$$ of decimal digits (0-9) of length $$$n$$$.A substring is a sequence of consecutive characters of a string. The substring of this string is defined by a pair of indexes — with its left and right ends. So, each pair of indexes ($$$l, r$$$), where $$$1 \le l \le r \le n$$$, corresponds to a substring of the string $$$s$$$. We will define as $$$v(l,r)$$$ the numeric value of the corresponding substring (leading zeros are allowed in it).For example, if $$$n=7$$$, $$$s=$$$"1003004", then $$$v(1,3)=100$$$, $$$v(2,3)=0$$$ and $$$v(2,7)=3004$$$.You are given $$$n$$$, $$$s$$$ and an integer $$$w$$$ ($$$1 \le w &lt; n$$$).You need to process $$$m$$$ queries, each of which is characterized by $$$3$$$ numbers $$$l_i, r_i, k_i$$$ ($$$1 \le l_i \le r_i \le n; 0 \le k_i \le 8$$$).The answer to the $$$i$$$th query is such a pair of substrings of length $$$w$$$ that if we denote them as $$$(L_1, L_1+w-1)$$$ and $$$(L_2, L_2+w-1)$$$, then: $$$L_1 \ne L_2$$$, that is, the substrings are different; the remainder of dividing a number $$$v(L_1, L_1+w-1) \cdot v(l_i, r_i) + v(L_2, L_2 + w - 1)$$$ by $$$9$$$ is equal to $$$k_i$$$. If there are many matching substring pairs, then find a pair where $$$L_1$$$ is as small as possible. If there are many matching pairs in this case, then minimize $$$L_2$$$.Note that the answer may not exist.
256 megabytes
//package com.example.practice.codeforces; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.StringTokenizer; public class Solution { public static void main (String [] args) throws IOException { // Use BufferedReader rather than RandomAccessFile; it's much faster final BufferedReader input = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); // input file name goes above int Q = Integer.parseInt(input.readLine()); while (Q > 0) { final char[] cc = input.readLine().toCharArray(); StringTokenizer st = new StringTokenizer(input.readLine()); final int w = Integer.parseInt(st.nextToken()), m = Integer.parseInt(st.nextToken()); int[][] qs = readArray2DInt(m, m, input); printArray2DInt(calc(cc, w, m, qs), m, out); Q--; } out.close(); // close the output file } private static int[][] calc(final char[] cc, final int w, final int m, final int[][] qs) { final int n = cc.length; int[][] rd = new int[9][2]; int[] sum = new int[n], sum2 = new int[n+1]; for (int i=0;i<9;++i){ Arrays.fill(rd[i], -1); } sum2[0] = 1; for (int i=1;i<=n;++i){ sum2[i] = sum2[i-1] * 10 % 9; sum[i-1] = cc[i-1] - '0'; if (i>1){ sum[i-1] += sum[i-2] * 10; } sum[i-1] = sum[i-1] % 9; } rd[get(sum, sum2, 0, w-1)][0] = 0; for (int i=1;i+w<=n;++i){ int v = get(sum, sum2, i, i+w-1); if (rd[v][0]==-1){ rd[v][0] = i; }else if (rd[v][1]==-1){ rd[v][1] = i; } } int[][] res = new int[m][]; for (int i=0;i<m;++i){ res[i] = new int[]{-1, -1}; final int v = get(sum, sum2, qs[i][0]-1, qs[i][1]-1); for (int j=0;j<9;++j){ for (int k=0;k<9;++k){ if (((j*v+k) % 9) == qs[i][2]){ if (j==k){ if (rd[j][1] >= 0){ if (res[i][0]==-1 || res[i][0]>rd[j][0] || (res[i][0]==rd[j][0] && res[i][1]>rd[j][1])){ res[i][0] = rd[j][0]; res[i][1] = rd[j][1]; } } }else if (rd[j][0]>=0 && rd[k][0]>=0){ if (res[i][0]==-1 || res[i][0]>rd[j][0] || (res[i][0]==rd[j][0] && res[i][1]>rd[k][0])){ res[i][0] = rd[j][0]; res[i][1] = rd[k][0]; } } } } } if (res[i][0]!=-1){ res[i][0]++; res[i][1]++; } } return res; } private static int get(final int[] sum, final int[] sum2, int l, int r){ int res = sum[r] - (l==0 ? 0 : (sum[l-1] * sum2[r-l+1]) % 9); if (res<0)res+=9; return res; } private static void printArray(long[] ns, final PrintWriter out){ for (int i=0;i<ns.length;++i){ out.print(ns[i]); if (i+1<ns.length)out.print(" "); else out.println(); } } private static void printArrayInt(int[] ns, final PrintWriter out){ for (int i=0;i<ns.length;++i){ out.print(ns[i]); if (i+1<ns.length)out.print(" "); else out.println(); } } private static void printArrayVertical(long[] ns, final PrintWriter out){ for (long a : ns){ out.println(a); } } private static void printArrayVerticalInt(int[] ns, final PrintWriter out){ for (int a : ns){ out.println(a); } } private static void printArray2D(long[][] ns, final int len, final PrintWriter out){ int cnt = 0; for (long[] kk : ns){ cnt++; if (cnt > len)break; for (int i=0;i<kk.length;++i){ out.print(kk[i]); if (i+1<kk.length)out.print(" "); else out.println(); } } } private static void printArray2DInt(int[][] ns, final int len, final PrintWriter out){ int cnt = 0; for (int[] kk : ns){ cnt++; if (cnt > len)break; for (int i=0;i<kk.length;++i){ out.print(kk[i]); if (i+1<kk.length)out.print(" "); else out.println(); } } } private static long[] readArray(final int n, final BufferedReader input) throws IOException{ long[] ns = new long[n]; StringTokenizer st = new StringTokenizer(input.readLine()); for (int i=0;i<n;++i){ ns[i] = Long.parseLong(st.nextToken()); } return ns; } private static int[] readArrayInt(final int n, final BufferedReader input) throws IOException{ int[] ns = new int[n]; StringTokenizer st = new StringTokenizer(input.readLine()); for (int i=0;i<n;++i){ ns[i] = Integer.parseInt(st.nextToken()); } return ns; } private static long[] readArrayVertical(final int n, final BufferedReader input) throws IOException{ long[] ns = new long[n]; for (int i=0;i<n;++i){ ns[i] = Long.parseLong(input.readLine()); } return ns; } private static int[] readArrayVerticalInt(final int n, final BufferedReader input) throws IOException{ int[] ns = new int[n]; for (int i=0;i<n;++i){ ns[i] = Integer.parseInt(input.readLine()); } return ns; } private static long[][] readArray2D(final int n, final int len, final BufferedReader input) throws IOException{ long[][] ns = new long[len][]; for (int i=0;i<n;++i){ StringTokenizer st = new StringTokenizer(input.readLine()); ArrayList<Long> al = new ArrayList<>(); while (st.hasMoreTokens()){ al.add(Long.parseLong(st.nextToken())); } long[] kk = new long[al.size()]; for (int j=0;j<kk.length;++j){ kk[j] = al.get(j); } ns[i] = kk; } return ns; } private static int[][] readArray2DInt(final int n, final int len, final BufferedReader input) throws IOException{ int[][] ns = new int[len][]; for (int i=0;i<n;++i){ StringTokenizer st = new StringTokenizer(input.readLine()); ArrayList<Integer> al = new ArrayList<>(); while (st.hasMoreTokens()){ al.add(Integer.parseInt(st.nextToken())); } int[] kk = new int[al.size()]; for (int j=0;j<kk.length;++j){ kk[j] = al.get(j); } ns[i] = kk; } return ns; } private static int GCD(int x, int y){ if (x > y)return GCD(y, x); if (x==0)return y; return GCD(y%x, x); } private static long GCD(long x, long y){ if (x > y)return GCD(y, x); if (x==0)return y; return GCD(y%x, x); } static class SegTree{ int st; int en; int mid; int val1; int val2; SegTree left; SegTree right; public SegTree(int l, int r, int d){ st = l; en = r; mid = (st + en) >> 1; val1 = val2 = d; if (st<en){ left = new SegTree(st, mid, d); right = new SegTree(mid+1, en, d); }else { left = right = null; } } public SegTree(int l, int r, int[] ns){ st = l; en = r; mid = (st + en) >> 1; if (st==en){ val1 = val2 = ns[st]; }else { left = new SegTree(l, mid, ns); right = new SegTree(mid+1, r, ns); val1 = Math.min(left.val1, right.val1); val2 = Math.max(left.val2, right.val2); } } void update(int idx, int v){ if (st==en){ val1 = val2 = v; }else { if (idx <= mid){ left.update(idx, v); }else { right.update(idx, v); } val1 = Math.min(left.val1, right.val1); val2 = Math.max(left.val2, right.val2); } } int getMin(int l, int r){ if (st==en || (l==st && r==en))return val1; if (r<=mid){ return left.getMin(l, r); } if (l>mid){ return right.getMin(l, r); } return Math.min(left.getMin(l, mid), right.getMin(mid+1, r)); } int getMax(int l, int r){ if (st==en || (l==st && r==en))return val2; if (r<=mid){ return left.getMax(l, r); } if (l>mid){ return right.getMax(l, r); } return Math.max(left.getMax(l, mid), right.getMax(mid+1, r)); } } static class SparseTable{ int[][] minTable; int[][] maxTable; int[] log2; int n; public SparseTable(final int[] ns){ n = ns.length; int m = 0, pre = 0; while (1<<m < n){ m++; } m++; minTable = new int[n][m]; maxTable = new int[n][m]; log2 = new int[n+1]; for (int i=0;i<n;++i){ minTable[i][0] = ns[i]; maxTable[i][0] = ns[i]; if ((1<<(pre+1)) == i+1){ pre++; } log2[i+1] = pre; } for (int i=1;i<m;++i){ for (int j=0;j<n;++j){ int r = Math.min(n-1, j+(1<<i)-1); if (r-(1<<(i-1))+1 <= j){ minTable[j][i] = minTable[j][i-1]; maxTable[j][i] = maxTable[j][i-1]; }else { minTable[j][i] = Math.min(minTable[j][i-1], minTable[r-(1<<(i-1))+1][i-1]); maxTable[j][i] = Math.max(maxTable[j][i-1], maxTable[r-(1<<(i-1))+1][i-1]); } } } } int getMin(final int l, final int r){ int d = log2[r-l+1]; return Math.min(minTable[l][d], minTable[r-(1<<d)+1][d]); } int getMax(final int l, final int r){ int d = log2[r-l+1]; return Math.max(maxTable[l][d], maxTable[r-(1<<d)+1][d]); } } static class BIT{ long[] ns; public BIT(int n){ ns = new long[n]; } void add(int idx, int v){ for (int i=idx; i<ns.length; i += -i & i){ ns[i] += v; } } long get(int idx){ long res = 0; for (int i=idx; i>0; i -= -i & i){ res += ns[i]; } return res; } } }
Java
["5\n\n1003004\n\n4 1\n\n1 2 1\n\n179572007\n\n4 2\n\n2 7 3\n\n2 7 4\n\n111\n\n2 1\n\n2 2 6\n\n0000\n\n1 2\n\n1 4 0\n\n1 4 1\n\n484\n\n1 5\n\n2 2 0\n\n2 3 7\n\n1 2 5\n\n3 3 8\n\n2 2 6"]
3 seconds
["2 4\n1 5\n1 2\n-1 -1\n1 2\n-1 -1\n1 3\n1 3\n-1 -1\n-1 -1\n-1 -1"]
NoteConsider the first test case of example inputs. In this test case $$$n=7$$$, $$$s=$$$"1003004", $$$w=4$$$ and one query $$$l_1=1$$$, $$$r_1=2$$$, $$$k_1=1$$$. Note that $$$v(1,2)=10$$$. We need to find a pair of substrings of length $$$4$$$ such that $$$v(L_1, L_1+3)\cdot10+v(L_2,L_2+3)$$$ has a remainder of $$$k_1=1$$$ when divided by $$$9$$$. The values $$$L_1=2, L_2=4$$$ actually satisfy all the requirements: $$$v(L_1, L_1+w-1)=v(2,5)=30$$$, $$$v(L_2, L_2+w-1)=v(4,7)=3004$$$. Indeed, $$$30\cdot10+3004=3304$$$, which has a remainder of $$$1$$$ when divided by $$$9$$$. It can be shown that $$$L_1=2$$$ is the minimum possible value, and $$$L_2=4$$$ is the minimum possible with $$$L_1=2$$$.
Java 11
standard input
[ "hashing", "math" ]
b67870dcffa7bad682ef980dacd1f3db
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — number of input test cases. The first line of each test case contains a string $$$s$$$, which contains only the characters 0-9 and has a length $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$). The second line contains two integers $$$w, m$$$ ($$$1 \le w &lt; n, 1 \le m \le 2 \cdot 10^5$$$), where $$$n$$$ — is the length of the given string $$$s$$$. The number $$$w$$$ denotes the lengths of the substrings being searched for, and $$$m$$$ is the number of queries to be processed. The following $$$m$$$ lines contain integers $$$l_i, r_i, k_i$$$ ($$$1 \le l_i \le r_i \le n$$$, $$$0 \le k_i \le 8$$$) — $$$i$$$th query parameters. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$. It is also guaranteed that the sum of $$$m$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,900
For each request, print in a separate line: left borders of the required substrings: $$$L_1$$$ and $$$L_2$$$; -1 -1 otherwise, if there is no solution. If there are several solutions, minimize $$$L_1$$$ first, and minimize $$$L_2$$$ second.
standard output
PASSED
bb084382ad3ba80a3dbd3d4509917790
train_110.jsonl
1662993300
Given the string $$$s$$$ of decimal digits (0-9) of length $$$n$$$.A substring is a sequence of consecutive characters of a string. The substring of this string is defined by a pair of indexes — with its left and right ends. So, each pair of indexes ($$$l, r$$$), where $$$1 \le l \le r \le n$$$, corresponds to a substring of the string $$$s$$$. We will define as $$$v(l,r)$$$ the numeric value of the corresponding substring (leading zeros are allowed in it).For example, if $$$n=7$$$, $$$s=$$$"1003004", then $$$v(1,3)=100$$$, $$$v(2,3)=0$$$ and $$$v(2,7)=3004$$$.You are given $$$n$$$, $$$s$$$ and an integer $$$w$$$ ($$$1 \le w &lt; n$$$).You need to process $$$m$$$ queries, each of which is characterized by $$$3$$$ numbers $$$l_i, r_i, k_i$$$ ($$$1 \le l_i \le r_i \le n; 0 \le k_i \le 8$$$).The answer to the $$$i$$$th query is such a pair of substrings of length $$$w$$$ that if we denote them as $$$(L_1, L_1+w-1)$$$ and $$$(L_2, L_2+w-1)$$$, then: $$$L_1 \ne L_2$$$, that is, the substrings are different; the remainder of dividing a number $$$v(L_1, L_1+w-1) \cdot v(l_i, r_i) + v(L_2, L_2 + w - 1)$$$ by $$$9$$$ is equal to $$$k_i$$$. If there are many matching substring pairs, then find a pair where $$$L_1$$$ is as small as possible. If there are many matching pairs in this case, then minimize $$$L_2$$$.Note that the answer may not exist.
256 megabytes
import java.io.*; import java.util.*; public class CF1562C extends PrintWriter { CF1562C() { super(System.out); } public static Scanner sc = new Scanner(System.in); public static void main(String[] $) { CF1562C o = new CF1562C(); o.main(); o.flush(); } static long calculate(long p, long q) { long mod = 1000000007, expo; expo = mod - 2; // Loop to find the value // until the expo is not zero while (expo != 0) { // Multiply p with q // if expo is odd if ((expo & 1) == 1) { p = (p * q) % mod; } q = (q * q) % mod; // Reduce the value of // expo by 2 expo >>= 1; } return p; } static String longestPalSubstr(String str) { // The result (length of LPS) int maxLength = 1; int start = 0; int len = str.length(); int low, high; // One by one consider every // character as center // point of even and length // palindromes for (int i = 1; i < len; ++i) { // Find the longest even // length palindrome with // center points as i-1 and i. low = i - 1; high = i; while (low >= 0 && high < len && str.charAt(low) == str.charAt(high)) { --low; ++high; } // Move back to the last possible valid palindrom substring // as that will anyway be the longest from above loop ++low; --high; if (str.charAt(low) == str.charAt(high) && high - low + 1 > maxLength) { start = low; maxLength = high - low + 1; } // Find the longest odd length // palindrome with center point as i low = i - 1; high = i + 1; while (low >= 0 && high < len && str.charAt(low) == str.charAt(high)) { --low; ++high; } // Move back to the last possible valid palindrom substring // as that will anyway be the longest from above loop ++low; --high; if (str.charAt(low) == str.charAt(high) && high - low + 1 > maxLength) { start = low; maxLength = high - low + 1; } } return str.substring(start, start + maxLength - 1); } long check(long a){ long ret=0; for(long k=2;(k*k*k)<=a;k++){ ret=ret+(a/(k*k*k)); } return ret; } /*public static int getFirstSetBitPos(int n) { return (int)((Math.log10(n & -n)) / Math.log10(2)) + 1; } public static int bfsq(int n, int m, HashMap<Integer,ArrayList<Integer>>h,boolean v ){ v[n]=true; if(n==m) return 1; else { int a=h.get(n).get(0); int b=h.get(n).get(1); if(b>m) return(m-n); else { int a1=bfsq(a,m,h,v); int b1=bfsq(b,m,h,v); return 1+Math.min(a1,b1); } } }*/ static long nCr(int n, int r) { return fact(n) / (fact(r) * fact(n - r)); } // Returns factorial of n static long fact(long n) { long res = 1; for (long i = 2; i <= n; i++) res = res * i; return res; } /*void bfs(int src, HashMap<Integer,ArrayList<Integer,Integer>>h,int deg, boolean v[] ){ a[src]=deg; Queue<Integer>= new LinkedList<Integer>(); q.add(src); while(!q.isEmpty()){ (int a:h.get(src)){ if() } } }*/ /* void dfs(int root, int par, HashMap<Integer,ArrayList<Integer>>h,int dp[], int child[]) { dp[root]=0; child[root]=1; for(int x: h.get(root)){ if(x == par) continue; dfs(x,root,h,in,dp); child[root]+=child[x]; } ArrayList<Integer> mine= new ArrayList<Integer>(); for(int x: h.get(root)) { if(x == par) continue; mine.add(x); } if(mine.size() >=2){ int y= Math.max(child[mine.get(0)] - 1 + dp[mine.get(1)] , child[mine.get(1)] -1 + dp[mine.get(0)]); dp[root]=y;} else if(mine.size() == 1) dp[root]=child[mine.get(0)] - 1; } */ class Pair implements Comparable<Pair>{ int i; int j; Pair (int a, int b){ i = a; j = b; } public int compareTo(Pair A){ return (int)(this.i-A.i); }} /*static class Pair { int i; int j; Pair() { } Pair(int i, int j) { this.i = i; this.j = j; } }*/ /*ArrayList<Integer> check(int a[], int b){ int n=a.length; long ans=0;int k=0; ArrayList<Integer>ab= new ArrayList<Integer>(); for(int i=0;i<n;i++){ if(a[i]%m==0) {k=a[i]; while(a[i]%m==0){ a[i]=a[i]/m; } for(int z=0;z<k/a[i];z++){ ab.add(a[i]); } } else{ ab.add(a[i]); } } return ab; } */ /*int check[]; int tree[]; static void build( int []arr) { // insert leaf nodes in tree for (int i = 0; i < n; i++) tree[n + i] = arr[i]; // build the tree by calculating // parents for (int i = n - 1; i > 0; --i){ int ans= Math.min(tree[i << 1], tree[i << 1 | 1]); int ans1=Math.max((tree[i << 1], tree[i << 1 | 1])); if(ans==0) } }*/ /*static void ab(long n) { // Note that this loop runs till square root for (long i=1; i<=Math.sqrt(n); i++) { if(i==1) { p.add(n/i); continue; } if (n%i==0) { // If divisors are equal, print only one if (n/i == i) p.add(i); else // Otherwise print both { p.add(i); p.add(n/i); } } } }*/ void main() { int g=sc.nextInt(); int mod=1000000007; for(int w1=0;w1<g;w1++){ sc.nextLine(); String s=sc.nextLine(); int n=s.length(); int w=sc.nextInt(); int m=sc.nextInt(); int pref[]= new int[n]; pref[0]=s.charAt(0)-'0'; pref[0]=pref[0]%9; for(int i=1;i<n;i++){ pref[i]=s.charAt(i)-'0'; pref[i]+=pref[i-1]; pref[i]=pref[i]%9; } // for(int i=0;i<n;i++) // print(pref[i]+" "); HashMap<Integer,TreeSet<Integer>>h= new HashMap<Integer,TreeSet<Integer>>(); for(int i=0;i<9;i++){ TreeSet<Integer>t= new TreeSet<Integer>(); t.add(Integer.MAX_VALUE); h.put(i,t); } h.get(pref[w-1]).add(1); for(int i=w;i<n;i++){ h.get((pref[i]-pref[i-w]+9)%9).add(i+2-w); } //println(h); for(int i=0;i<m;i++){ int l=sc.nextInt(); int r=sc.nextInt(); int k=sc.nextInt(); int last=pref[r-1]; if(l!=1) last-=pref[l-2]; //println(last); int l1=Integer.MAX_VALUE; int l2=Integer.MAX_VALUE; for(int j=0;j<9;j++){ int lp=(last*j)%9; lp=(k-lp+9)%9; int d=h.get(j).first(); // if(j==4){ // println(lp); // println(d); // } int d2=0; if(d!=Integer.MAX_VALUE){ d2=h.get(lp).first(); if(d2==d) d2=h.get(lp).higher(d); if(d2!=Integer.MAX_VALUE){ if(d<=l1){ l1=d; l2=d2; } } } } if(l1==Integer.MAX_VALUE) println(-1+" "+-1); else println(l1+" "+l2); } } } }
Java
["5\n\n1003004\n\n4 1\n\n1 2 1\n\n179572007\n\n4 2\n\n2 7 3\n\n2 7 4\n\n111\n\n2 1\n\n2 2 6\n\n0000\n\n1 2\n\n1 4 0\n\n1 4 1\n\n484\n\n1 5\n\n2 2 0\n\n2 3 7\n\n1 2 5\n\n3 3 8\n\n2 2 6"]
3 seconds
["2 4\n1 5\n1 2\n-1 -1\n1 2\n-1 -1\n1 3\n1 3\n-1 -1\n-1 -1\n-1 -1"]
NoteConsider the first test case of example inputs. In this test case $$$n=7$$$, $$$s=$$$"1003004", $$$w=4$$$ and one query $$$l_1=1$$$, $$$r_1=2$$$, $$$k_1=1$$$. Note that $$$v(1,2)=10$$$. We need to find a pair of substrings of length $$$4$$$ such that $$$v(L_1, L_1+3)\cdot10+v(L_2,L_2+3)$$$ has a remainder of $$$k_1=1$$$ when divided by $$$9$$$. The values $$$L_1=2, L_2=4$$$ actually satisfy all the requirements: $$$v(L_1, L_1+w-1)=v(2,5)=30$$$, $$$v(L_2, L_2+w-1)=v(4,7)=3004$$$. Indeed, $$$30\cdot10+3004=3304$$$, which has a remainder of $$$1$$$ when divided by $$$9$$$. It can be shown that $$$L_1=2$$$ is the minimum possible value, and $$$L_2=4$$$ is the minimum possible with $$$L_1=2$$$.
Java 11
standard input
[ "hashing", "math" ]
b67870dcffa7bad682ef980dacd1f3db
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — number of input test cases. The first line of each test case contains a string $$$s$$$, which contains only the characters 0-9 and has a length $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$). The second line contains two integers $$$w, m$$$ ($$$1 \le w &lt; n, 1 \le m \le 2 \cdot 10^5$$$), where $$$n$$$ — is the length of the given string $$$s$$$. The number $$$w$$$ denotes the lengths of the substrings being searched for, and $$$m$$$ is the number of queries to be processed. The following $$$m$$$ lines contain integers $$$l_i, r_i, k_i$$$ ($$$1 \le l_i \le r_i \le n$$$, $$$0 \le k_i \le 8$$$) — $$$i$$$th query parameters. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$. It is also guaranteed that the sum of $$$m$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,900
For each request, print in a separate line: left borders of the required substrings: $$$L_1$$$ and $$$L_2$$$; -1 -1 otherwise, if there is no solution. If there are several solutions, minimize $$$L_1$$$ first, and minimize $$$L_2$$$ second.
standard output
PASSED
125296bf9869dee90d2e67a80c88d87a
train_110.jsonl
1662993300
Given the string $$$s$$$ of decimal digits (0-9) of length $$$n$$$.A substring is a sequence of consecutive characters of a string. The substring of this string is defined by a pair of indexes — with its left and right ends. So, each pair of indexes ($$$l, r$$$), where $$$1 \le l \le r \le n$$$, corresponds to a substring of the string $$$s$$$. We will define as $$$v(l,r)$$$ the numeric value of the corresponding substring (leading zeros are allowed in it).For example, if $$$n=7$$$, $$$s=$$$"1003004", then $$$v(1,3)=100$$$, $$$v(2,3)=0$$$ and $$$v(2,7)=3004$$$.You are given $$$n$$$, $$$s$$$ and an integer $$$w$$$ ($$$1 \le w &lt; n$$$).You need to process $$$m$$$ queries, each of which is characterized by $$$3$$$ numbers $$$l_i, r_i, k_i$$$ ($$$1 \le l_i \le r_i \le n; 0 \le k_i \le 8$$$).The answer to the $$$i$$$th query is such a pair of substrings of length $$$w$$$ that if we denote them as $$$(L_1, L_1+w-1)$$$ and $$$(L_2, L_2+w-1)$$$, then: $$$L_1 \ne L_2$$$, that is, the substrings are different; the remainder of dividing a number $$$v(L_1, L_1+w-1) \cdot v(l_i, r_i) + v(L_2, L_2 + w - 1)$$$ by $$$9$$$ is equal to $$$k_i$$$. If there are many matching substring pairs, then find a pair where $$$L_1$$$ is as small as possible. If there are many matching pairs in this case, then minimize $$$L_2$$$.Note that the answer may not exist.
256 megabytes
import java.io.PrintWriter; import java.util.*; public class f { public static void main(String[] args) { Scanner in = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int numT = in.nextInt(); for (int ci = 0; ci < numT; ci++) { String str = in.next(); int n = str.length(); int[] arr = new int[n + 1]; int[] sums = new int[n + 1]; for (int i = 0; i < n; i++) { arr[i] = str.charAt(i) - '0'; sums[i + 1] = (sums[i] + arr[i]) % 9; } int w = in.nextInt(); int m = in.nextInt(); int curMod = 0; for (int i = 0; i < w; i++) { curMod = (curMod + arr[i]) % 9; } int[] mods = new int[n - w + 1]; ArrayList<Integer>[] sets = new ArrayList[9]; for (int i = 0; i < 9; i++) { sets[i] = new ArrayList<>(); } for (int i = 0; i < mods.length; i++) { mods[i] = curMod; curMod = (curMod + 9 - arr[i] + arr[i + w]) % 9; sets[mods[i]].add(i); } for (int qi = 0; qi < m; qi++) { int l = in.nextInt(); int r = in.nextInt(); int k = in.nextInt(); int lr = (9 + sums[r] - sums[l - 1]) % 9; int l1 = -1; int l2 = -1; for (int a = 0; a < 9; a++) { if (sets[a].isEmpty()) continue; int l11 = sets[a].get(0); for (int b = 0; b < 9; b++) { if ((a * lr + b) % 9 != k) { continue; } if (sets[b].isEmpty() || (a == b && sets[b].size() == 1)) continue; int l22 = a == b ? sets[b].get(1) : sets[b].get(0); if (l1 == -1 || l11 < l1 || (l11 == l1 && l22 < l2)) { l1 = l11; l2 = l22; } } } if (l1 != -1) { l1++; l2++; } out.printf("%d %d\n", l1, l2); } } out.flush(); } }
Java
["5\n\n1003004\n\n4 1\n\n1 2 1\n\n179572007\n\n4 2\n\n2 7 3\n\n2 7 4\n\n111\n\n2 1\n\n2 2 6\n\n0000\n\n1 2\n\n1 4 0\n\n1 4 1\n\n484\n\n1 5\n\n2 2 0\n\n2 3 7\n\n1 2 5\n\n3 3 8\n\n2 2 6"]
3 seconds
["2 4\n1 5\n1 2\n-1 -1\n1 2\n-1 -1\n1 3\n1 3\n-1 -1\n-1 -1\n-1 -1"]
NoteConsider the first test case of example inputs. In this test case $$$n=7$$$, $$$s=$$$"1003004", $$$w=4$$$ and one query $$$l_1=1$$$, $$$r_1=2$$$, $$$k_1=1$$$. Note that $$$v(1,2)=10$$$. We need to find a pair of substrings of length $$$4$$$ such that $$$v(L_1, L_1+3)\cdot10+v(L_2,L_2+3)$$$ has a remainder of $$$k_1=1$$$ when divided by $$$9$$$. The values $$$L_1=2, L_2=4$$$ actually satisfy all the requirements: $$$v(L_1, L_1+w-1)=v(2,5)=30$$$, $$$v(L_2, L_2+w-1)=v(4,7)=3004$$$. Indeed, $$$30\cdot10+3004=3304$$$, which has a remainder of $$$1$$$ when divided by $$$9$$$. It can be shown that $$$L_1=2$$$ is the minimum possible value, and $$$L_2=4$$$ is the minimum possible with $$$L_1=2$$$.
Java 11
standard input
[ "hashing", "math" ]
b67870dcffa7bad682ef980dacd1f3db
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — number of input test cases. The first line of each test case contains a string $$$s$$$, which contains only the characters 0-9 and has a length $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$). The second line contains two integers $$$w, m$$$ ($$$1 \le w &lt; n, 1 \le m \le 2 \cdot 10^5$$$), where $$$n$$$ — is the length of the given string $$$s$$$. The number $$$w$$$ denotes the lengths of the substrings being searched for, and $$$m$$$ is the number of queries to be processed. The following $$$m$$$ lines contain integers $$$l_i, r_i, k_i$$$ ($$$1 \le l_i \le r_i \le n$$$, $$$0 \le k_i \le 8$$$) — $$$i$$$th query parameters. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$. It is also guaranteed that the sum of $$$m$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,900
For each request, print in a separate line: left borders of the required substrings: $$$L_1$$$ and $$$L_2$$$; -1 -1 otherwise, if there is no solution. If there are several solutions, minimize $$$L_1$$$ first, and minimize $$$L_2$$$ second.
standard output
PASSED
c1a5123a35f6430c4dcce33626af7290
train_110.jsonl
1662993300
Given the string $$$s$$$ of decimal digits (0-9) of length $$$n$$$.A substring is a sequence of consecutive characters of a string. The substring of this string is defined by a pair of indexes — with its left and right ends. So, each pair of indexes ($$$l, r$$$), where $$$1 \le l \le r \le n$$$, corresponds to a substring of the string $$$s$$$. We will define as $$$v(l,r)$$$ the numeric value of the corresponding substring (leading zeros are allowed in it).For example, if $$$n=7$$$, $$$s=$$$"1003004", then $$$v(1,3)=100$$$, $$$v(2,3)=0$$$ and $$$v(2,7)=3004$$$.You are given $$$n$$$, $$$s$$$ and an integer $$$w$$$ ($$$1 \le w &lt; n$$$).You need to process $$$m$$$ queries, each of which is characterized by $$$3$$$ numbers $$$l_i, r_i, k_i$$$ ($$$1 \le l_i \le r_i \le n; 0 \le k_i \le 8$$$).The answer to the $$$i$$$th query is such a pair of substrings of length $$$w$$$ that if we denote them as $$$(L_1, L_1+w-1)$$$ and $$$(L_2, L_2+w-1)$$$, then: $$$L_1 \ne L_2$$$, that is, the substrings are different; the remainder of dividing a number $$$v(L_1, L_1+w-1) \cdot v(l_i, r_i) + v(L_2, L_2 + w - 1)$$$ by $$$9$$$ is equal to $$$k_i$$$. If there are many matching substring pairs, then find a pair where $$$L_1$$$ is as small as possible. If there are many matching pairs in this case, then minimize $$$L_2$$$.Note that the answer may not exist.
256 megabytes
//some updates in import stuff import static java.lang.Math.max; import static java.lang.Math.min; import static java.lang.Math.abs; import java.util.*; import java.io.*; import java.math.*; //key points learned //max space ever that could be alloted in a program to pass in cf //int[][] prefixSum = new int[201][200_005]; -> not a single array more!!! //never allocate memory again again to such bigg array, it will give memory exceeded for sure //believe in your fucking solution and keep improving it!!! (sometimes) ///common mistakes // didn't read the question properly public class F{ static int mod = (int) (Math.pow(10, 9)+7); static final int dx[] = { -1, 0, 1, 0 }, dy[] = { 0, -1, 0, 1 }; static final int[] dx8 = { -1, -1, -1, 0, 0, 1, 1, 1 }, dy8 = { -1, 0, 1, -1, 1, -1, 0, 1 }; static final int[] dx9 = { -1, -1, -1, 0, 0, 0, 1, 1, 1 }, dy9 = { -1, 0, 1, -1, 0, 1, -1, 0, 1 }; static final double eps = 1e-10; static List<Integer> primeNumbers = new ArrayList<>(); public static void main(String[] args) { MyScanner sc = new MyScanner(); //pretty important for sure - out = new PrintWriter(new BufferedOutputStream(System.out)); //dope shit output for sure //code here int test = sc.nextInt(); while(test --> 0){ char[] inp = sc.nextLine().toCharArray(); int w = sc.nextInt(); int m = sc.nextInt(); //now I gotta do some work in here for sure int n = inp.length; int[] psum = new int[n + 1]; for(int i = 0; i < n; i++){ psum[i + 1] = psum[i] + (inp[i] - '0'); } //pretty dope shit for sure //now for all L the remainder we would be wantin ArrayList<ArrayList<Integer>> remPos = new ArrayList<>(); for(int i = 0; i < 9; i++){ remPos.add(new ArrayList<>()); } for(int i = 0; i < n - w + 1; i++){ int sum = psum[i + w] - psum[i]; int rem = sum % 9; remPos.get(rem).add(i); } // System.out.println(w + " " + m); // System.out.println(Arrays.toString(psum)); // System.out.println(remPos); //pretty decent question of prefix sums and shit for sure!! (really really really liked it) for(int i= 0; i < m; i++){ int l = sc.nextInt(); int r = sc.nextInt(); int k = sc.nextInt(); // System.out.println(l + " " + r + " " + k); int csum = psum[r] - psum[l - 1]; int rem = csum % 9; //makes sense - int L1 = -1; int L2 = -1; for(int j = 0; j < 9; j++){ //checking for all basically int req = ((k - (j * rem)) + 90)%9; if(j == req){ if(remPos.get(j).size() < 2) continue; if(L1 == -1 || remPos.get(j).get(0) < L1){ L1 = remPos.get(j).get(0); L2 = remPos.get(j).get(1); } }else{ if(remPos.get(j).size() < 1 || remPos.get(req).size() < 1) continue; if(L1 == -1 || remPos.get(j).get(0) < L1){ L1 = remPos.get(j).get(0); L2 = remPos.get(req).get(0); } } } // out.println("hello"); if(L1 != -1) out.println((L1 + 1) + " " + (L2 + 1)); else out.println((L1) + " " + (L2 )); } } out.close(); } //new stuff to learn (whenever this is need for them, then only) //Lazy Segment Trees //Persistent Segment Trees //Square Root Decomposition //Geometry & Convex Hull //High Level DP -- yk yk //String Matching Algorithms //Heavy light Decomposition //Updation Required //Fenwick Tree - both are done (sum) //Segment Tree - both are done (min, max, sum) //-----CURRENTLY PRESENT-------// //Graph //DSU //powerMODe //power //Segment Tree (work on this one) //Prime Sieve //Count Divisors //Next Permutation //Get NCR //isVowel //Sort (int) //Sort (long) //Binomial Coefficient //Pair //Triplet //lcm (int & long) //gcd (int & long) //gcd (for binomial coefficient) //swap (int & char) //reverse //primeExponentCounts //Fast input and output //------------------------------------------------------------------- //------------------------------------------------------------------- //------------------------------------------------------------------- //------------------------------------------------------------------- //------------------------------------------------------------------- //GRAPH (basic structure) public static class Graph{ public int V; public ArrayList<ArrayList<Integer>> edges; //2 -> [0,1,2] (current) Graph(int V){ this.V = V; edges = new ArrayList<>(V+1); for(int i= 0; i <= V; i++){ edges.add(new ArrayList<>()); } } public void addEdge(int from , int to){ edges.get(from).add(to); edges.get(to).add(from); } } //DSU (path and rank optimised) public static class DisjointUnionSets { int[] rank, parent; int n; public DisjointUnionSets(int n) { rank = new int[n]; parent = new int[n]; Arrays.fill(rank, 1); Arrays.fill(parent,-1); this.n = n; } public int find(int curr){ if(parent[curr] == -1) return curr; //path compression optimisation return parent[curr] = find(parent[curr]); } public void union(int a, int b){ int s1 = find(a); int s2 = find(b); if(s1 != s2){ //union by size if(rank[s1] < rank[s2]){ parent[s1] = s2; rank[s2] += rank[s1]; }else{ parent[s2] = s1; rank[s1] += rank[s2]; } } } } //with mod public static long powerMOD(long x, long y) { long res = 1L; while (y > 0) { // If y is odd, multiply x with result if ((y & 1) != 0){ x %= mod; res %= mod; res = (res * x)%mod; } // y must be even now y = y >> 1; // y = y/2 x%= mod; x = (x * x)%mod; // Change x to x^2 } return res%mod; } //without mod public static long power(long x, long y) { long res = 1L; while (y > 0) { // If y is odd, multiply x with result if ((y & 1) != 0){ res = (res * x); } // y must be even now y = y >> 1; // y = y/ x = (x * x); } return res; } public static class segmentTree{ //so let's make a constructor function for this bad boi for sure!!! public long[] arr; public long[] tree; //COMPLEXITY (normal segment tree, stuff) //build -> O(n) //query -> O(logn) //update -> O(logn) //update-range -> O(n) (worst case) //simple iteration and stuff for sure public segmentTree(long[] arr){ int n = arr.length; this.arr = new long[n]; for(int i= 0; i < n; i++){ this.arr[i] = arr[i]; } tree = new long[4*n + 1]; } //pretty basic idea if you read the code once //first make child node once //then form the parent node using them public void buildTree(int s, int e, int index){ if(s == e){ tree[index] = arr[s]; return; } //recursive case int mid = (s + e)/2; buildTree(s, mid, 2 * index); buildTree(mid + 1, e, 2*index + 1); //the condition we want from children be like this tree[index] = min(tree[2 * index], tree[2 * index + 1]); return; } //definitely index based 0 query!!! //only int index = 1!! //baaki everything is simple as fuck public long query(int s, int e, int qs , int qe, int index){ //complete overlap if(s >= qs && e <= qe){ return tree[index]; } //no overlap if(qe < s || qs > e){ return Long.MAX_VALUE; } //partial overlap int mid = (s + e)/2; long left = query( s, mid , qs, qe, 2*index); long right = query( mid + 1, e, qs, qe, 2*index + 1); return min(left, right); } //gonna do range updates for sure now!! //let's do this bois!!! (solve this problem for sure) public void updateRange(int s, int e, int l, int r, long increment, int index){ //out of bounds if(l > e || r < s){ return; } //leaf node if(s == e){ tree[index] += increment; return; //behnchoda return tera baap krvayege? } //recursive case int mid = (s + e)/2; updateRange(s, mid, l, r, increment, 2 * index); updateRange(mid + 1, e, l, r, increment, 2 * index + 1); tree[index] = min(tree[2 * index], tree[2 * index + 1]); } } public static class segmentTreeLazy{ //so let's make a constructor function for this bad boi for sure!!! public long[] arr; public long[] tree; public long[] lazy; //COMPLEXITY (normal segment tree, stuff) //build -> O(n) //query-range -> O(logn) //lazy update-range -> O(logn) (imp) //simple iteration and stuff for sure public segmentTreeLazy(long[] arr){ int n = arr.length; this.arr = new long[n]; for(int i= 0; i < n; i++){ this.arr[i] = arr[i]; } tree = new long[4*n + 1]; lazy = new long[1000000]; //pretty big for no inconvenience (no?) NONONONOONON! NO fucker NO! } //pretty basic idea if you read the code once //first make child node once //then form the parent node using them public void buildTree(int s, int e, int index){ if(s == e){ tree[index] = arr[s]; return; } //recursive case int mid = (s + e)/2; buildTree(s, mid, 2 * index); buildTree(mid + 1, e, 2*index + 1); //the condition we want from children be like this tree[index] = min(tree[2 * index], tree[2 * index + 1]); return; } //definitely index based 0 query!!! //only int index = 1!! //baaki everything is simple as fuck public long queryLazy(int s, int e, int qs, int qe, int index){ //before going down resolve if it exist if(lazy[index] != 0){ tree[index] += lazy[index]; //non leaf node if(s != e){ lazy[2*index] += lazy[index]; lazy[2*index + 1] += lazy[index]; } lazy[index] = 0; //clear the lazy value at current node for sure } //no overlap if(s > qe || e < qs){ return Long.MAX_VALUE; } //complete overlap if(s >= qs && e <= qe){ return tree[index]; } //partial overlap int mid = (s + e)/2; long left = queryLazy(s, mid, qs, qe, 2 * index); long right = queryLazy(mid + 1, e, qs, qe, 2 * index + 1); return Math.min(left, right); } //update range in O(logn) -- using lazy array public void updateRangeLazy(int s, int e, int l, int r, int inc, int index){ //before going down resolve if it exist if(lazy[index] != 0){ tree[index] += lazy[index]; //non leaf node if(s != e){ lazy[2*index] += lazy[index]; lazy[2*index + 1] += lazy[index]; } lazy[index] = 0; //clear the lazy value at current node for sure } //no overlap if(s > r || l > e){ return; } //another case if(l <= s && e <= r){ tree[index] += inc; //create a new lazy value for children node if(s != e){ lazy[2*index] += inc; lazy[2*index + 1] += inc; } return; } //recursive case int mid = (s + e)/2; updateRangeLazy(s, mid, l, r, inc, 2*index); updateRangeLazy(mid + 1, e, l, r, inc, 2*index + 1); //update the tree index tree[index] = Math.min(tree[2*index], tree[2*index + 1]); return; } } //prime sieve public static void primeSieve(int n){ BitSet bitset = new BitSet(n+1); for(long i = 0; i < n ; i++){ if (i == 0 || i == 1) { bitset.set((int) i); continue; } if(bitset.get((int) i)) continue; primeNumbers.add((int)i); for(long j = i; j <= n ; j+= i) bitset.set((int)j); } } //number of divisors public static int countDivisors(long number){ if(number == 1) return 1; List<Integer> primeFactors = new ArrayList<>(); int index = 0; long curr = primeNumbers.get(index); while(curr * curr <= number){ while(number % curr == 0){ number = number/curr; primeFactors.add((int) curr); } index++; curr = primeNumbers.get(index); } if(number != 1) primeFactors.add((int) number); int current = primeFactors.get(0); int totalDivisors = 1; int currentCount = 2; for (int i = 1; i < primeFactors.size(); i++) { if (primeFactors.get(i) == current) { currentCount++; } else { totalDivisors *= currentCount; currentCount = 2; current = primeFactors.get(i); } } totalDivisors *= currentCount; return totalDivisors; } //primeExponentCounts public static int primeExponentsCount(int n) { if (n <= 1) return 0; int sqrt = (int) Math.sqrt(n); int remainingNumber = n; int result = 0; for (int i = 2; i <= sqrt; i++) { while (remainingNumber % i == 0) { result++; remainingNumber /= i; } } //in case of prime numbers this would happen if (remainingNumber > 1) { result++; } return result; } //now adding next permutation function to java hehe public static boolean next_permutation(int[] p) { for (int a = p.length - 2; a >= 0; --a) if (p[a] < p[a + 1]) for (int b = p.length - 1;; --b) if (p[b] > p[a]) { int t = p[a]; p[a] = p[b]; p[b] = t; for (++a, b = p.length - 1; a < b; ++a, --b) { t = p[a]; p[a] = p[b]; p[b] = t; } return true; } return false; } //finding the value of NCR in O(RlogN) time and O(1) space public static long getNcR(int n, int r) { long p = 1, k = 1; if (n - r < r) r = n - r; if (r != 0) { while (r > 0) { p *= n; k *= r; long m = __gcd(p, k); p /= m; k /= m; n--; r--; } } else { p = 1; } return p; } //is vowel function public static boolean isVowel(char c) { return (c=='a' || c=='A' || c=='e' || c=='E' || c=='i' || c=='I' || c=='o' || c=='O' || c=='u' || c=='U'); } //to sort the array with better method public static void sort(int[] a) { ArrayList<Integer> l=new ArrayList<>(); for (int i:a) l.add(i); Collections.sort(l); for (int i=0; i<a.length; i++) a[i]=l.get(i); } //sort long public static void sort(long[] a) { ArrayList<Long> l=new ArrayList<>(); for (long i:a) l.add(i); Collections.sort(l); for (int i=0; i<a.length; i++) a[i]=l.get(i); } //for calculating binomialCoeff public static int binomialCoeff(int n, int k) { int C[] = new int[k + 1]; // nC0 is 1 C[0] = 1; for (int i = 1; i <= n; i++) { // Compute next row of pascal // triangle using the previous row for (int j = Math.min(i, k); j > 0; j--) C[j] = C[j] + C[j - 1]; } return C[k]; } //Pair with int int public static class Pair{ public int a; public int b; public int hashCode; Pair(int a , int b){ this.a = a; this.b = b; this.hashCode = Objects.hash(a, b); } @Override public String toString(){ return a + " -> " + b; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Pair that = (Pair) o; return a == that.a && b == that.b; } @Override public int hashCode() { return this.hashCode; } } //Triplet with int int int public static class Triplet{ public int a; public int b; public int c; Triplet(int a , int b, int c){ this.a = a; this.b = b; this.c = c; } @Override public String toString(){ return a + " -> " + b; } } //Shortcut function public static long lcm(long a , long b){ return a * (b/gcd(a,b)); } //let's make one for calculating lcm basically public static int lcm(int a , int b){ return (a * b)/gcd(a,b); } //int version for gcd public static int gcd(int a, int b){ if(b == 0) return a; return gcd(b , a%b); } //long version for gcd public static long gcd(long a, long b){ if(b == 0) return a; return gcd(b , a%b); } //for ncr calculator(ignore this code) public static long __gcd(long n1, long n2) { long gcd = 1; for (int i = 1; i <= n1 && i <= n2; ++i) { // Checks if i is factor of both integers if (n1 % i == 0 && n2 % i == 0) { gcd = i; } } return gcd; } //swapping two elements in an array public static void swap(int[] arr, int left , int right){ int temp = arr[left]; arr[left] = arr[right]; arr[right] = temp; } //for char array public static void swap(char[] arr, int left , int right){ char temp = arr[left]; arr[left] = arr[right]; arr[right] = temp; } //reversing an array public static void reverse(int[] arr){ int left = 0; int right = arr.length-1; while(left <= right){ swap(arr, left,right); left++; right--; } } public static long expo(long a, long b, long mod) { long res = 1; while (b > 0) { if ((b & 1) == 1L) res = (res * a) % mod; //think about this one for a second a = (a * a) % mod; b = b >> 1; } return res; } //SOME EXTRA DOPE FUNCTIONS public static long mminvprime(long a, long b) { return expo(a, b - 2, b); } public static long mod_add(long a, long b, long m) { a = a % m; b = b % m; return (((a + b) % m) + m) % m; } public static long mod_sub(long a, long b, long m) { a = a % m; b = b % m; return (((a - b) % m) + m) % m; } public static long mod_mul(long a, long b, long m) { a = a % m; b = b % m; return (((a * b) % m) + m) % m; } public static long mod_div(long a, long b, long m) { a = a % m; b = b % m; return (mod_mul(a, mminvprime(b, m), m) + m) % m; } //O(n) every single time remember that public static long nCr(long N, long K , long mod){ long upper = 1L; long lower = 1L; long lowerr = 1L; for(long i = 1; i <= N; i++){ upper = mod_mul(upper, i, mod); } for(long i = 1; i <= K; i++){ lower = mod_mul(lower, i, mod); } for(long i = 1; i <= (N - K); i++){ lowerr = mod_mul(lowerr, i, mod); } // out.println(upper + " " + lower + " " + lowerr); long answer = mod_mul(lower, lowerr, mod); answer = mod_div(upper, answer, mod); return answer; } // long[] fact = new long[2 * n + 1]; // long[] ifact = new long[2 * n + 1]; // fact[0] = 1; // ifact[0] = 1; // for (long i = 1; i <= 2 * n; i++) // { // fact[(int)i] = mod_mul(fact[(int)i - 1], i, mod); // ifact[(int)i] = mminvprime(fact[(int)i], mod); // } //ifact is basically inverse factorial in here!!!!!(imp) public static long combination(long n, long r, long m, long[] fact, long[] ifact) { long val1 = fact[(int)n]; long val2 = ifact[(int)(n - r)]; long val3 = ifact[(int)r]; return (((val1 * val2) % m) * val3) % m; } //-----------PrintWriter for faster output--------------------------------- public static PrintWriter out; //-----------MyScanner class for faster input---------- public static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine(){ String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } //-------------------------------------------------------- }
Java
["5\n\n1003004\n\n4 1\n\n1 2 1\n\n179572007\n\n4 2\n\n2 7 3\n\n2 7 4\n\n111\n\n2 1\n\n2 2 6\n\n0000\n\n1 2\n\n1 4 0\n\n1 4 1\n\n484\n\n1 5\n\n2 2 0\n\n2 3 7\n\n1 2 5\n\n3 3 8\n\n2 2 6"]
3 seconds
["2 4\n1 5\n1 2\n-1 -1\n1 2\n-1 -1\n1 3\n1 3\n-1 -1\n-1 -1\n-1 -1"]
NoteConsider the first test case of example inputs. In this test case $$$n=7$$$, $$$s=$$$"1003004", $$$w=4$$$ and one query $$$l_1=1$$$, $$$r_1=2$$$, $$$k_1=1$$$. Note that $$$v(1,2)=10$$$. We need to find a pair of substrings of length $$$4$$$ such that $$$v(L_1, L_1+3)\cdot10+v(L_2,L_2+3)$$$ has a remainder of $$$k_1=1$$$ when divided by $$$9$$$. The values $$$L_1=2, L_2=4$$$ actually satisfy all the requirements: $$$v(L_1, L_1+w-1)=v(2,5)=30$$$, $$$v(L_2, L_2+w-1)=v(4,7)=3004$$$. Indeed, $$$30\cdot10+3004=3304$$$, which has a remainder of $$$1$$$ when divided by $$$9$$$. It can be shown that $$$L_1=2$$$ is the minimum possible value, and $$$L_2=4$$$ is the minimum possible with $$$L_1=2$$$.
Java 11
standard input
[ "hashing", "math" ]
b67870dcffa7bad682ef980dacd1f3db
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — number of input test cases. The first line of each test case contains a string $$$s$$$, which contains only the characters 0-9 and has a length $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$). The second line contains two integers $$$w, m$$$ ($$$1 \le w &lt; n, 1 \le m \le 2 \cdot 10^5$$$), where $$$n$$$ — is the length of the given string $$$s$$$. The number $$$w$$$ denotes the lengths of the substrings being searched for, and $$$m$$$ is the number of queries to be processed. The following $$$m$$$ lines contain integers $$$l_i, r_i, k_i$$$ ($$$1 \le l_i \le r_i \le n$$$, $$$0 \le k_i \le 8$$$) — $$$i$$$th query parameters. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$. It is also guaranteed that the sum of $$$m$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,900
For each request, print in a separate line: left borders of the required substrings: $$$L_1$$$ and $$$L_2$$$; -1 -1 otherwise, if there is no solution. If there are several solutions, minimize $$$L_1$$$ first, and minimize $$$L_2$$$ second.
standard output
PASSED
23e41bdd3a53a527f34f3b2554d813e7
train_110.jsonl
1662993300
Given the string $$$s$$$ of decimal digits (0-9) of length $$$n$$$.A substring is a sequence of consecutive characters of a string. The substring of this string is defined by a pair of indexes — with its left and right ends. So, each pair of indexes ($$$l, r$$$), where $$$1 \le l \le r \le n$$$, corresponds to a substring of the string $$$s$$$. We will define as $$$v(l,r)$$$ the numeric value of the corresponding substring (leading zeros are allowed in it).For example, if $$$n=7$$$, $$$s=$$$"1003004", then $$$v(1,3)=100$$$, $$$v(2,3)=0$$$ and $$$v(2,7)=3004$$$.You are given $$$n$$$, $$$s$$$ and an integer $$$w$$$ ($$$1 \le w &lt; n$$$).You need to process $$$m$$$ queries, each of which is characterized by $$$3$$$ numbers $$$l_i, r_i, k_i$$$ ($$$1 \le l_i \le r_i \le n; 0 \le k_i \le 8$$$).The answer to the $$$i$$$th query is such a pair of substrings of length $$$w$$$ that if we denote them as $$$(L_1, L_1+w-1)$$$ and $$$(L_2, L_2+w-1)$$$, then: $$$L_1 \ne L_2$$$, that is, the substrings are different; the remainder of dividing a number $$$v(L_1, L_1+w-1) \cdot v(l_i, r_i) + v(L_2, L_2 + w - 1)$$$ by $$$9$$$ is equal to $$$k_i$$$. If there are many matching substring pairs, then find a pair where $$$L_1$$$ is as small as possible. If there are many matching pairs in this case, then minimize $$$L_2$$$.Note that the answer may not exist.
256 megabytes
import java.util.*; import java.io.*; public class F_Kirei_and_the_Linear_Function { static class Scan { private byte[] buf=new byte[1024]; private int index; private InputStream in; private int total; public Scan() { in=System.in; } public int scan()throws IOException { if(total<0) throw new InputMismatchException(); if(index>=total) { index=0; total=in.read(buf); if(total<=0) return -1; } return buf[index++]; } public int scanInt()throws IOException { int integer=0; int n=scan(); while(isWhiteSpace(n)) n=scan(); int neg=1; if(n=='-') { neg=-1; n=scan(); } while(!isWhiteSpace(n)) { if(n>='0'&&n<='9') { integer*=10; integer+=n-'0'; n=scan(); } else throw new InputMismatchException(); } return neg*integer; } public double scanDouble()throws IOException { double doub=0; int n=scan(); while(isWhiteSpace(n)) n=scan(); int neg=1; if(n=='-') { neg=-1; n=scan(); } while(!isWhiteSpace(n)&&n!='.') { if(n>='0'&&n<='9') { doub*=10; doub+=n-'0'; n=scan(); } else throw new InputMismatchException(); } if(n=='.') { n=scan(); double temp=1; while(!isWhiteSpace(n)) { if(n>='0'&&n<='9') { temp/=10; doub+=(n-'0')*temp; n=scan(); } else throw new InputMismatchException(); } } return doub*neg; } public String scanString()throws IOException { StringBuilder sb=new StringBuilder(); int n=scan(); while(isWhiteSpace(n)) n=scan(); while(!isWhiteSpace(n)) { sb.append((char)n); n=scan(); } return sb.toString(); } private boolean isWhiteSpace(int n) { if(n==' '||n=='\n'||n=='\r'||n=='\t'||n==-1) return true; return false; } } public static void sort(int arr[],int l,int r) { //sort(arr,0,n-1); if(l==r) { return; } int mid=(l+r)/2; sort(arr,l,mid); sort(arr,mid+1,r); merge(arr,l,mid,mid+1,r); } public static void merge(int arr[],int l1,int r1,int l2,int r2) { int tmp[]=new int[r2-l1+1]; int indx1=l1,indx2=l2; //sorting the two halves using a tmp array for(int i=0;i<tmp.length;i++) { if(indx1>r1) { tmp[i]=arr[indx2]; indx2++; continue; } if(indx2>r2) { tmp[i]=arr[indx1]; indx1++; continue; } if(arr[indx1]<arr[indx2]) { tmp[i]=arr[indx1]; indx1++; continue; } tmp[i]=arr[indx2]; indx2++; } //Copying the elements of tmp into the main array for(int i=0,j=l1;i<tmp.length;i++,j++) { arr[j]=tmp[i]; } } public static void sort(long arr[],int l,int r) { //sort(arr,0,n-1); if(l==r) { return; } int mid=(l+r)/2; sort(arr,l,mid); sort(arr,mid+1,r); merge(arr,l,mid,mid+1,r); } public static void merge(long arr[],int l1,int r1,int l2,int r2) { long tmp[]=new long[r2-l1+1]; int indx1=l1,indx2=l2; //sorting the two halves using a tmp array for(int i=0;i<tmp.length;i++) { if(indx1>r1) { tmp[i]=arr[indx2]; indx2++; continue; } if(indx2>r2) { tmp[i]=arr[indx1]; indx1++; continue; } if(arr[indx1]<arr[indx2]) { tmp[i]=arr[indx1]; indx1++; continue; } tmp[i]=arr[indx2]; indx2++; } //Copying the elements of tmp into the main array for(int i=0,j=l1;i<tmp.length;i++,j++) { arr[j]=tmp[i]; } } public static void main(String args[]) throws IOException { Scan input=new Scan(); StringBuilder ans=new StringBuilder(""); int test=input.scanInt(); for(int tt=1;tt<=test;tt++) { String str=input.scanString(); int w=input.scanInt(); int m=input.scanInt(); int arr[]=new int[str.length()]; int prefix[]=new int[str.length()]; for(int i=0;i<str.length();i++) { prefix[i]=str.charAt(i)-'0'; if(i>0) { prefix[i]+=prefix[i-1]; } } int indx1[]=new int[9]; int indx2[]=new int[9]; Arrays.fill(indx1, -1); Arrays.fill(indx2, -1); for(int i=w-1;i<str.length();i++) { int val=get(prefix,i-w+1,i)%9; if(indx1[val]==-1) { indx1[val]=i-w+1+1; } else if(indx2[val]==-1) { indx2[val]=i-w+1+1; } } for(int q=0;q<m;q++) { int ll=input.scanInt()-1; int rr=input.scanInt()-1; int k=input.scanInt(); int mul=get(prefix,ll,rr)%9; int a=-1,b=-1; for(int i=0;i<indx1.length;i++) { if(indx1[i]==-1) { continue; } int val=(i*mul)%9; int rem=get_rem(val,k); if(rem==-1) { continue; } if(rem!=i && indx1[rem]!=-1) { long prev=(a*1000000L)+b; long curr=(indx1[i]*1000000L)+indx1[rem]; if(a==-1 || curr<prev) { a=indx1[i]; b=indx1[rem]; } } if(rem==i && indx2[rem]!=-1) { long prev=(a*1000000L)+b; long curr=(indx1[i]*1000000L)+indx2[rem]; if(a==-1 || curr<prev) { a=indx1[i]; b=indx2[rem]; } } } ans.append(a+" "+b+"\n"); } } System.out.print(ans); } public static int get_rem(int val,int k) { for(int i=0;i<9;i++) { if((val+i)%9==k) { return i; } } return -1; } public static int get(int arr[],int l,int r) { return arr[r]-(l==0?0:arr[l-1]); } }
Java
["5\n\n1003004\n\n4 1\n\n1 2 1\n\n179572007\n\n4 2\n\n2 7 3\n\n2 7 4\n\n111\n\n2 1\n\n2 2 6\n\n0000\n\n1 2\n\n1 4 0\n\n1 4 1\n\n484\n\n1 5\n\n2 2 0\n\n2 3 7\n\n1 2 5\n\n3 3 8\n\n2 2 6"]
3 seconds
["2 4\n1 5\n1 2\n-1 -1\n1 2\n-1 -1\n1 3\n1 3\n-1 -1\n-1 -1\n-1 -1"]
NoteConsider the first test case of example inputs. In this test case $$$n=7$$$, $$$s=$$$"1003004", $$$w=4$$$ and one query $$$l_1=1$$$, $$$r_1=2$$$, $$$k_1=1$$$. Note that $$$v(1,2)=10$$$. We need to find a pair of substrings of length $$$4$$$ such that $$$v(L_1, L_1+3)\cdot10+v(L_2,L_2+3)$$$ has a remainder of $$$k_1=1$$$ when divided by $$$9$$$. The values $$$L_1=2, L_2=4$$$ actually satisfy all the requirements: $$$v(L_1, L_1+w-1)=v(2,5)=30$$$, $$$v(L_2, L_2+w-1)=v(4,7)=3004$$$. Indeed, $$$30\cdot10+3004=3304$$$, which has a remainder of $$$1$$$ when divided by $$$9$$$. It can be shown that $$$L_1=2$$$ is the minimum possible value, and $$$L_2=4$$$ is the minimum possible with $$$L_1=2$$$.
Java 11
standard input
[ "hashing", "math" ]
b67870dcffa7bad682ef980dacd1f3db
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — number of input test cases. The first line of each test case contains a string $$$s$$$, which contains only the characters 0-9 and has a length $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$). The second line contains two integers $$$w, m$$$ ($$$1 \le w &lt; n, 1 \le m \le 2 \cdot 10^5$$$), where $$$n$$$ — is the length of the given string $$$s$$$. The number $$$w$$$ denotes the lengths of the substrings being searched for, and $$$m$$$ is the number of queries to be processed. The following $$$m$$$ lines contain integers $$$l_i, r_i, k_i$$$ ($$$1 \le l_i \le r_i \le n$$$, $$$0 \le k_i \le 8$$$) — $$$i$$$th query parameters. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$. It is also guaranteed that the sum of $$$m$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,900
For each request, print in a separate line: left borders of the required substrings: $$$L_1$$$ and $$$L_2$$$; -1 -1 otherwise, if there is no solution. If there are several solutions, minimize $$$L_1$$$ first, and minimize $$$L_2$$$ second.
standard output
PASSED
28a1090fdd11f043f5afc5af5f50b585
train_110.jsonl
1662993300
Given the string $$$s$$$ of decimal digits (0-9) of length $$$n$$$.A substring is a sequence of consecutive characters of a string. The substring of this string is defined by a pair of indexes — with its left and right ends. So, each pair of indexes ($$$l, r$$$), where $$$1 \le l \le r \le n$$$, corresponds to a substring of the string $$$s$$$. We will define as $$$v(l,r)$$$ the numeric value of the corresponding substring (leading zeros are allowed in it).For example, if $$$n=7$$$, $$$s=$$$"1003004", then $$$v(1,3)=100$$$, $$$v(2,3)=0$$$ and $$$v(2,7)=3004$$$.You are given $$$n$$$, $$$s$$$ and an integer $$$w$$$ ($$$1 \le w &lt; n$$$).You need to process $$$m$$$ queries, each of which is characterized by $$$3$$$ numbers $$$l_i, r_i, k_i$$$ ($$$1 \le l_i \le r_i \le n; 0 \le k_i \le 8$$$).The answer to the $$$i$$$th query is such a pair of substrings of length $$$w$$$ that if we denote them as $$$(L_1, L_1+w-1)$$$ and $$$(L_2, L_2+w-1)$$$, then: $$$L_1 \ne L_2$$$, that is, the substrings are different; the remainder of dividing a number $$$v(L_1, L_1+w-1) \cdot v(l_i, r_i) + v(L_2, L_2 + w - 1)$$$ by $$$9$$$ is equal to $$$k_i$$$. If there are many matching substring pairs, then find a pair where $$$L_1$$$ is as small as possible. If there are many matching pairs in this case, then minimize $$$L_2$$$.Note that the answer may not exist.
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 s; int end; public Pair(int a, int e) { end = e; s = a; } } 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(); OutputStream outputStream = System.out; OutputWriter output = new OutputWriter(outputStream); int t = scn.nextInt(); long mod = 1000000007L; // String[] pal = {"0000", "0110","0220","0330","0440","0550","1001","1111","1221","1331","1441","1551","2002","2112","2222","2332"}; while(t>0) { String s = scn.next(); int n = s.length(); int[] sum = new int[n]; int w = scn.nextInt(); int m = scn.nextInt(); sum[0] = Integer.parseInt(s.charAt(0)+""); for(int i=1;i<n;i++) { sum[i] = sum[i-1]+Integer.parseInt(s.charAt(i)+""); } int[] wl = new int[n-w+1]; List<List<Integer>> a= new ArrayList<>(); for(int i=0;i<=8;i++) { a.add(new ArrayList<>()); } for(int i=0;i<=n-w;i++) { wl[i] = sum[i+w-1]-(i-1>=0?sum[i-1]:0); wl[i]%=9; a.get(wl[i]).add(i); } while(m>0) { int l = scn.nextInt()-1; int r = scn.nextInt()-1; int k = scn.nextInt(); int p1p1 = (sum[r]-(l-1>=0?sum[l-1]:0))%9; int minl1 = n+1; int minl2 = n+1; for(int i=0;i<=8;i++) { if(a.get(i).size()==0) { continue; } int rem = (p1p1*i)%9; int idx = k-rem; if(k<rem) { idx = 9+k-rem; } if(a.get(i).get(0)<minl1 && a.get(idx).size()>0) { int j = 0; while(j<a.get(idx).size() && a.get(idx).get(j)==a.get(i).get(0)) { j++; } if(j!=a.get(idx).size()) { minl1 = Math.min(minl1,a.get(i).get(0)+1); minl2 = a.get(idx).get(j)+1; } } } if(minl1==n+1) { output.println("-1 -1"); }else { output.println(minl1+" "+minl2); } m--; } t--; } output.close(); } static int CeilIndex(int A[], int l, int r, int key) { while (r - l > 1) { int m = l + (r - l) / 2; if (A[m] >= key) r = m; else l = m; } return r; } static int lis(int A[], int size) { // Add boundary case, when array size is one int[] tailTable = new int[size]; int len; // always points empty slot tailTable[0] = A[0]; len = 1; for (int i = 1; i < size; i++) { if (A[i] < tailTable[0]) // new smallest value tailTable[0] = A[i]; else if (A[i] > tailTable[len - 1]) // A[i] wants to extend largest subsequence tailTable[len++] = A[i]; else // A[i] wants to be current end candidate of an existing // subsequence. It will replace ceil value in tailTable tailTable[CeilIndex(tailTable, -1, len - 1, A[i])] = A[i]; } return len; } public static int checkL(char[][] a, int r, int c, boolean[][] mark) { int cnt=0; for(int i=Math.max(r-1,0);i<=Math.min(r+2,a.length-1);i++) { for(int j= Math.max(c-1,0);j<=Math.min(c+2,a[0].length-1);j++) { if(a[i][j]=='*') { cnt++; } } } char ch11 = a[r][c]; char ch12 = a[r][c+1]; char ch21 = a[r+1][c]; char ch22 = a[r+1][c+1]; int n = a.length; int m = a[0].length; if(cnt==4) { if(ch22!='*' && r+2<n && c+2<m && a[r+2][c+2]=='*') { cnt--; }else if(ch21!='*' && r+2<n && c-1>=0 && a[r+2][c-1]=='*') { cnt--; }else if(ch11!='*' && r-1>=0 && c-1>=0 && a[r-1][c-1]=='*') { cnt--; }else if(ch12!='*' && r-1>=0 && c+2<m && a[r-1][c+2]=='*') { cnt--; } } if(cnt==0) { return 1; } if(cnt>3) { return 4; } if(cnt<3) { return 2; } if((ch11=='*' && ch12=='*' && ch22=='*' && ch21!='*')|| (ch11=='*' && ch21=='*' && ch22=='*' && ch12!='*') || (ch12=='*'&&ch22=='*'&&ch21=='*'&&ch11!='*')||(ch11=='*'&&ch12=='*'&&ch21=='*'&&ch22!='*')) { for(int i=r;i<r+2;i++) { for(int j=c;j<c+2;j++) { if(a[i][j]=='*') { mark[i][j] = true; } } } return 1; } return 1; } public static void addTime(int h, int m, int ah, int am) { int rm = m+am; int rh = (h+ah+(rm/60))%24; rm = rm%60; } public static long power(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; } }
Java
["5\n\n1003004\n\n4 1\n\n1 2 1\n\n179572007\n\n4 2\n\n2 7 3\n\n2 7 4\n\n111\n\n2 1\n\n2 2 6\n\n0000\n\n1 2\n\n1 4 0\n\n1 4 1\n\n484\n\n1 5\n\n2 2 0\n\n2 3 7\n\n1 2 5\n\n3 3 8\n\n2 2 6"]
3 seconds
["2 4\n1 5\n1 2\n-1 -1\n1 2\n-1 -1\n1 3\n1 3\n-1 -1\n-1 -1\n-1 -1"]
NoteConsider the first test case of example inputs. In this test case $$$n=7$$$, $$$s=$$$"1003004", $$$w=4$$$ and one query $$$l_1=1$$$, $$$r_1=2$$$, $$$k_1=1$$$. Note that $$$v(1,2)=10$$$. We need to find a pair of substrings of length $$$4$$$ such that $$$v(L_1, L_1+3)\cdot10+v(L_2,L_2+3)$$$ has a remainder of $$$k_1=1$$$ when divided by $$$9$$$. The values $$$L_1=2, L_2=4$$$ actually satisfy all the requirements: $$$v(L_1, L_1+w-1)=v(2,5)=30$$$, $$$v(L_2, L_2+w-1)=v(4,7)=3004$$$. Indeed, $$$30\cdot10+3004=3304$$$, which has a remainder of $$$1$$$ when divided by $$$9$$$. It can be shown that $$$L_1=2$$$ is the minimum possible value, and $$$L_2=4$$$ is the minimum possible with $$$L_1=2$$$.
Java 11
standard input
[ "hashing", "math" ]
b67870dcffa7bad682ef980dacd1f3db
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — number of input test cases. The first line of each test case contains a string $$$s$$$, which contains only the characters 0-9 and has a length $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$). The second line contains two integers $$$w, m$$$ ($$$1 \le w &lt; n, 1 \le m \le 2 \cdot 10^5$$$), where $$$n$$$ — is the length of the given string $$$s$$$. The number $$$w$$$ denotes the lengths of the substrings being searched for, and $$$m$$$ is the number of queries to be processed. The following $$$m$$$ lines contain integers $$$l_i, r_i, k_i$$$ ($$$1 \le l_i \le r_i \le n$$$, $$$0 \le k_i \le 8$$$) — $$$i$$$th query parameters. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$. It is also guaranteed that the sum of $$$m$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,900
For each request, print in a separate line: left borders of the required substrings: $$$L_1$$$ and $$$L_2$$$; -1 -1 otherwise, if there is no solution. If there are several solutions, minimize $$$L_1$$$ first, and minimize $$$L_2$$$ second.
standard output
PASSED
17ab81d6c75ff6377d473f001d402736
train_110.jsonl
1662993300
Given the string $$$s$$$ of decimal digits (0-9) of length $$$n$$$.A substring is a sequence of consecutive characters of a string. The substring of this string is defined by a pair of indexes — with its left and right ends. So, each pair of indexes ($$$l, r$$$), where $$$1 \le l \le r \le n$$$, corresponds to a substring of the string $$$s$$$. We will define as $$$v(l,r)$$$ the numeric value of the corresponding substring (leading zeros are allowed in it).For example, if $$$n=7$$$, $$$s=$$$"1003004", then $$$v(1,3)=100$$$, $$$v(2,3)=0$$$ and $$$v(2,7)=3004$$$.You are given $$$n$$$, $$$s$$$ and an integer $$$w$$$ ($$$1 \le w &lt; n$$$).You need to process $$$m$$$ queries, each of which is characterized by $$$3$$$ numbers $$$l_i, r_i, k_i$$$ ($$$1 \le l_i \le r_i \le n; 0 \le k_i \le 8$$$).The answer to the $$$i$$$th query is such a pair of substrings of length $$$w$$$ that if we denote them as $$$(L_1, L_1+w-1)$$$ and $$$(L_2, L_2+w-1)$$$, then: $$$L_1 \ne L_2$$$, that is, the substrings are different; the remainder of dividing a number $$$v(L_1, L_1+w-1) \cdot v(l_i, r_i) + v(L_2, L_2 + w - 1)$$$ by $$$9$$$ is equal to $$$k_i$$$. If there are many matching substring pairs, then find a pair where $$$L_1$$$ is as small as possible. If there are many matching pairs in this case, then minimize $$$L_2$$$.Note that the answer may not exist.
256 megabytes
import java.io.*; import java.util.*; public class F { static IOHandler sc = new IOHandler(); public static void main(String[] args) { // TODO Auto-generated method stub int testCases = sc.nextInt(); for (int i = 1; i <= testCases; ++i) { solve(i); } } private static void solve(int t) { String s = sc.next(); int [] prefix = new int [s.length()]; Arrays.fill(prefix, -1); int sum = 0; int w = sc.nextInt(); int q = sc.nextInt(); for (int i = s.length() - 1; i >= 0; --i) { sum += s.charAt(i) - '0'; sum %= 9; if (i + w <= s.length()) { prefix[i] = sum; sum -= s.charAt(i + w - 1) - '0'; sum += 9; sum %= 9; } } TreeSet<Integer> [] set = new TreeSet[9]; for (int i = 0; i < 9; ++i) set[i] = new TreeSet<>(); for (int i = 0; i < prefix.length; ++i) { if (prefix[i] == -1) continue; set[prefix[i]].add(i + 1); } int [][][] pairs = new int [9][9][9]; int [][][] pairs2 = new int [9][9][]; int val; Integer first, second; for (int i = 0; i < 9; ++i) { for (int j = 0; j < 9; ++j) { for (int k = 0; k < 9; ++k) { val = i * j; val += k; val %= 9; pairs[i][j][k] = val; first = set[j].ceiling(0); if (first != null) { int start = k == j ? first + 1 : 0; second = set[k].ceiling(start); if (second != null) { if (pairs2[i][val] == null) pairs2[i][val] = new int [] {first , second}; else if (pairs2[i][val][0] > first) { pairs2[i][val] = new int [] {first , second}; }else if (pairs2[i][val][0] == first && pairs2[i][val][1] > second) { pairs2[i][val] = new int [] {first , second}; } } } } } } int [] prefix2 = new int [s.length()]; sum = 0; for (int i = 0; i < s.length(); ++i) { sum += s.charAt(i) - '0'; sum %= 9; prefix2[i] = sum; } int l,r,k, v; StringBuilder sb = new StringBuilder(); for (int i = 0; i < q; ++i) { l = sc.nextInt(); r = sc.nextInt(); k = sc.nextInt(); v = prefix2[r - 1] - (l == 1 ? 0 : prefix2[l - 2]); v += 9; v %= 9; if (pairs2[v][k] == null) { sb.append(-1 + " " + -1); }else { sb.append(pairs2[v][k][0] + " " + pairs2[v][k][1]); } sb.append("\n"); } System.out.print(sb); } private static class IOHandler { BufferedReader br; StringTokenizer st; public IOHandler() { 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 [] readArray(int n) { int [] res = new int [n]; for (int i = 0; i < n; ++i) res[i] = nextInt(); return res; } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine(){ String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["5\n\n1003004\n\n4 1\n\n1 2 1\n\n179572007\n\n4 2\n\n2 7 3\n\n2 7 4\n\n111\n\n2 1\n\n2 2 6\n\n0000\n\n1 2\n\n1 4 0\n\n1 4 1\n\n484\n\n1 5\n\n2 2 0\n\n2 3 7\n\n1 2 5\n\n3 3 8\n\n2 2 6"]
3 seconds
["2 4\n1 5\n1 2\n-1 -1\n1 2\n-1 -1\n1 3\n1 3\n-1 -1\n-1 -1\n-1 -1"]
NoteConsider the first test case of example inputs. In this test case $$$n=7$$$, $$$s=$$$"1003004", $$$w=4$$$ and one query $$$l_1=1$$$, $$$r_1=2$$$, $$$k_1=1$$$. Note that $$$v(1,2)=10$$$. We need to find a pair of substrings of length $$$4$$$ such that $$$v(L_1, L_1+3)\cdot10+v(L_2,L_2+3)$$$ has a remainder of $$$k_1=1$$$ when divided by $$$9$$$. The values $$$L_1=2, L_2=4$$$ actually satisfy all the requirements: $$$v(L_1, L_1+w-1)=v(2,5)=30$$$, $$$v(L_2, L_2+w-1)=v(4,7)=3004$$$. Indeed, $$$30\cdot10+3004=3304$$$, which has a remainder of $$$1$$$ when divided by $$$9$$$. It can be shown that $$$L_1=2$$$ is the minimum possible value, and $$$L_2=4$$$ is the minimum possible with $$$L_1=2$$$.
Java 11
standard input
[ "hashing", "math" ]
b67870dcffa7bad682ef980dacd1f3db
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — number of input test cases. The first line of each test case contains a string $$$s$$$, which contains only the characters 0-9 and has a length $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$). The second line contains two integers $$$w, m$$$ ($$$1 \le w &lt; n, 1 \le m \le 2 \cdot 10^5$$$), where $$$n$$$ — is the length of the given string $$$s$$$. The number $$$w$$$ denotes the lengths of the substrings being searched for, and $$$m$$$ is the number of queries to be processed. The following $$$m$$$ lines contain integers $$$l_i, r_i, k_i$$$ ($$$1 \le l_i \le r_i \le n$$$, $$$0 \le k_i \le 8$$$) — $$$i$$$th query parameters. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$. It is also guaranteed that the sum of $$$m$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,900
For each request, print in a separate line: left borders of the required substrings: $$$L_1$$$ and $$$L_2$$$; -1 -1 otherwise, if there is no solution. If there are several solutions, minimize $$$L_1$$$ first, and minimize $$$L_2$$$ second.
standard output
PASSED
4cbe1d1d86d4908004940361ee9b1b9c
train_110.jsonl
1662993300
Given the string $$$s$$$ of decimal digits (0-9) of length $$$n$$$.A substring is a sequence of consecutive characters of a string. The substring of this string is defined by a pair of indexes — with its left and right ends. So, each pair of indexes ($$$l, r$$$), where $$$1 \le l \le r \le n$$$, corresponds to a substring of the string $$$s$$$. We will define as $$$v(l,r)$$$ the numeric value of the corresponding substring (leading zeros are allowed in it).For example, if $$$n=7$$$, $$$s=$$$"1003004", then $$$v(1,3)=100$$$, $$$v(2,3)=0$$$ and $$$v(2,7)=3004$$$.You are given $$$n$$$, $$$s$$$ and an integer $$$w$$$ ($$$1 \le w &lt; n$$$).You need to process $$$m$$$ queries, each of which is characterized by $$$3$$$ numbers $$$l_i, r_i, k_i$$$ ($$$1 \le l_i \le r_i \le n; 0 \le k_i \le 8$$$).The answer to the $$$i$$$th query is such a pair of substrings of length $$$w$$$ that if we denote them as $$$(L_1, L_1+w-1)$$$ and $$$(L_2, L_2+w-1)$$$, then: $$$L_1 \ne L_2$$$, that is, the substrings are different; the remainder of dividing a number $$$v(L_1, L_1+w-1) \cdot v(l_i, r_i) + v(L_2, L_2 + w - 1)$$$ by $$$9$$$ is equal to $$$k_i$$$. If there are many matching substring pairs, then find a pair where $$$L_1$$$ is as small as possible. If there are many matching pairs in this case, then minimize $$$L_2$$$.Note that the answer may not exist.
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; public final class Main{ static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader( new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } static void print(int[] arr){ PrintWriter out=new PrintWriter(System.out); for(int i=0;i<arr.length-1;i++) { out.print(arr[i]+" "); } out.println(arr[arr.length-1]); out.flush(); } public static void main(String[] args) throws java.lang.Exception{ FastReader sc = new FastReader(); int t=sc.nextInt(); PrintWriter out=new PrintWriter(System.out); while(t-->0) { String s = sc.nextLine(); int n=s.length(); int[] arr = new int[n]; int[] pre=new int[n]; for(int i=0;i<n;i++){ arr[i]=(s.charAt(i)-'0')%9; pre[i]=((i-1>=0?pre[i-1]:0)+arr[i])%9; } int w=sc.nextInt(); int[] win = new int[n-w+1]; ArrayList<ArrayList<Integer>> map = new ArrayList<>(); for(int i=0;i<9;i++) map.add(new ArrayList<>()); // Arrays.fill(map,-1); for(int i=0;i<win.length;i++){ win[i]=(pre[i+w-1]-(i-1>=0?pre[i-1]:0)+18)%9; map.get(win[i]).add(i); } int m=sc.nextInt(); while(m-->0){ int l=sc.nextInt(), r=sc.nextInt(), k=sc.nextInt(); l--; r--; int val=(pre[r]-(l-1>=0?pre[l-1]:0)+18)%9; boolean mila=false; int ansx=Integer.MAX_VALUE, ansy=Integer.MAX_VALUE; for(int ind=0;ind<9;ind++){ if(map.get(ind).size()>0){ int i=map.get(ind).get(0); int req=(k-(val*win[i])+9999)%9; if(map.get(req).size()!=0){ for(int c:map.get(req)){ if(c!=i){ if(i+1<ansx){ ansx=(i+1); ansy=(c+1); } mila=true; break; } } } } } if(!mila) out.println(-1+" "+(-1)); else out.println(ansx+" "+ansy); } } out.flush(); } }
Java
["5\n\n1003004\n\n4 1\n\n1 2 1\n\n179572007\n\n4 2\n\n2 7 3\n\n2 7 4\n\n111\n\n2 1\n\n2 2 6\n\n0000\n\n1 2\n\n1 4 0\n\n1 4 1\n\n484\n\n1 5\n\n2 2 0\n\n2 3 7\n\n1 2 5\n\n3 3 8\n\n2 2 6"]
3 seconds
["2 4\n1 5\n1 2\n-1 -1\n1 2\n-1 -1\n1 3\n1 3\n-1 -1\n-1 -1\n-1 -1"]
NoteConsider the first test case of example inputs. In this test case $$$n=7$$$, $$$s=$$$"1003004", $$$w=4$$$ and one query $$$l_1=1$$$, $$$r_1=2$$$, $$$k_1=1$$$. Note that $$$v(1,2)=10$$$. We need to find a pair of substrings of length $$$4$$$ such that $$$v(L_1, L_1+3)\cdot10+v(L_2,L_2+3)$$$ has a remainder of $$$k_1=1$$$ when divided by $$$9$$$. The values $$$L_1=2, L_2=4$$$ actually satisfy all the requirements: $$$v(L_1, L_1+w-1)=v(2,5)=30$$$, $$$v(L_2, L_2+w-1)=v(4,7)=3004$$$. Indeed, $$$30\cdot10+3004=3304$$$, which has a remainder of $$$1$$$ when divided by $$$9$$$. It can be shown that $$$L_1=2$$$ is the minimum possible value, and $$$L_2=4$$$ is the minimum possible with $$$L_1=2$$$.
Java 11
standard input
[ "hashing", "math" ]
b67870dcffa7bad682ef980dacd1f3db
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — number of input test cases. The first line of each test case contains a string $$$s$$$, which contains only the characters 0-9 and has a length $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$). The second line contains two integers $$$w, m$$$ ($$$1 \le w &lt; n, 1 \le m \le 2 \cdot 10^5$$$), where $$$n$$$ — is the length of the given string $$$s$$$. The number $$$w$$$ denotes the lengths of the substrings being searched for, and $$$m$$$ is the number of queries to be processed. The following $$$m$$$ lines contain integers $$$l_i, r_i, k_i$$$ ($$$1 \le l_i \le r_i \le n$$$, $$$0 \le k_i \le 8$$$) — $$$i$$$th query parameters. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$. It is also guaranteed that the sum of $$$m$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,900
For each request, print in a separate line: left borders of the required substrings: $$$L_1$$$ and $$$L_2$$$; -1 -1 otherwise, if there is no solution. If there are several solutions, minimize $$$L_1$$$ first, and minimize $$$L_2$$$ second.
standard output
PASSED
ec36421f7885d4fc6f6c358104b7a0b5
train_110.jsonl
1662993300
Given the string $$$s$$$ of decimal digits (0-9) of length $$$n$$$.A substring is a sequence of consecutive characters of a string. The substring of this string is defined by a pair of indexes — with its left and right ends. So, each pair of indexes ($$$l, r$$$), where $$$1 \le l \le r \le n$$$, corresponds to a substring of the string $$$s$$$. We will define as $$$v(l,r)$$$ the numeric value of the corresponding substring (leading zeros are allowed in it).For example, if $$$n=7$$$, $$$s=$$$"1003004", then $$$v(1,3)=100$$$, $$$v(2,3)=0$$$ and $$$v(2,7)=3004$$$.You are given $$$n$$$, $$$s$$$ and an integer $$$w$$$ ($$$1 \le w &lt; n$$$).You need to process $$$m$$$ queries, each of which is characterized by $$$3$$$ numbers $$$l_i, r_i, k_i$$$ ($$$1 \le l_i \le r_i \le n; 0 \le k_i \le 8$$$).The answer to the $$$i$$$th query is such a pair of substrings of length $$$w$$$ that if we denote them as $$$(L_1, L_1+w-1)$$$ and $$$(L_2, L_2+w-1)$$$, then: $$$L_1 \ne L_2$$$, that is, the substrings are different; the remainder of dividing a number $$$v(L_1, L_1+w-1) \cdot v(l_i, r_i) + v(L_2, L_2 + w - 1)$$$ by $$$9$$$ is equal to $$$k_i$$$. If there are many matching substring pairs, then find a pair where $$$L_1$$$ is as small as possible. If there are many matching pairs in this case, then minimize $$$L_2$$$.Note that the answer may not exist.
256 megabytes
import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.math.BigDecimal; import java.math.BigInteger; import java.text.DecimalFormat; import java.util.*; public class Main { static final long MOD1=1000000007; static final long MOD=998244353; static final int NTT_MOD1 = 998244353; static final int NTT_MOD2 = 1053818881; static final int NTT_MOD3 = 1004535809; static long MAX = 1000000000000000000l;//10^18 static int index = 2; public static void main(String[] args){ PrintWriter out = new PrintWriter(System.out); InputReader sc=new InputReader(System.in); int t = sc.nextInt(); for (int i = 0; i < t; i++) { char[] cs = sc.next().toCharArray(); int w = sc.nextInt(); int m = sc.nextInt(); int n = cs.length; int[] sum = new int[n + 1]; for (int j = 1; j <= n; j++) { sum[j] = (sum[j - 1] + Character.getNumericValue(cs[j - 1])) % 9; } int[][] L = new int[9][2]; for (int j = 0; j < L.length; j++) Arrays.fill(L[j], -1); for (int j = 0; j + w - 1 < n; j++) { int r = (sum[j + w] - sum[j] + 9) % 9; if (L[r][0] == -1) { L[r][0] = j + 1; }else { if (L[r][1] == -1) { L[r][1] = j + 1; } } } for (int j = 0; j < m; j++) { int l = sc.nextInt(); int r = sc.nextInt(); int k = sc.nextInt(); int rem = (sum[r] - sum[l - 1] + 9) % 9; int ansl = Integer.MAX_VALUE; int ansr = -1; for (int j2 = 0; j2 < 9; j2++) { for (int o = 0; o < 9; o++) { if (((j2 * rem) + o) % 9 == k) { if (j2 == o) { if (L[j2][0] != -1 && L[o][1] != -1 && ansl > L[j2][0]) { ansl = L[j2][0]; ansr = L[o][1]; } }else { if (L[j2][0] != -1 && L[o][0] != -1 && ansl > L[j2][0]) { ansl = L[j2][0]; ansr = L[o][0]; } } } } } if(ansr == -1) ansl = -1; out.println(ansl + " " + ansr); } } out.flush(); } static class InputReader { private InputStream in; private byte[] buffer = new byte[1024]; private int curbuf; private int lenbuf; public InputReader(InputStream in) { this.in = in; this.curbuf = this.lenbuf = 0; } public boolean hasNextByte() { if (curbuf >= lenbuf) { curbuf = 0; try { lenbuf = in.read(buffer); } catch (IOException e) { throw new InputMismatchException(); } if (lenbuf <= 0) return false; } return true; } private int readByte() { if (hasNextByte()) return buffer[curbuf++]; else return -1; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private void skip() { while (hasNextByte() && isSpaceChar(buffer[curbuf])) curbuf++; } public boolean hasNext() { skip(); return hasNextByte(); } public String next() { if (!hasNext()) throw new NoSuchElementException(); StringBuilder sb = new StringBuilder(); int b = readByte(); while (!isSpaceChar(b)) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } public int nextInt() { if (!hasNext()) throw new NoSuchElementException(); int c = readByte(); while (isSpaceChar(c)) c = readByte(); boolean minus = false; if (c == '-') { minus = true; c = readByte(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res = res * 10 + c - '0'; c = readByte(); } while (!isSpaceChar(c)); return (minus) ? -res : res; } public long nextLong() { if (!hasNext()) throw new NoSuchElementException(); int c = readByte(); while (isSpaceChar(c)) c = readByte(); boolean minus = false; if (c == '-') { minus = true; c = readByte(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res = res * 10 + c - '0'; c = readByte(); } while (!isSpaceChar(c)); return (minus) ? -res : res; } public double nextDouble() { return Double.parseDouble(next()); } public int[] nextIntArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public double[] nextDoubleArray(int n) { double[] a = new double[n]; for (int i = 0; i < n; i++) a[i] = nextDouble(); return a; } public long[] nextLongArray(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } public char[][] nextCharMap(int n, int m) { char[][] map = new char[n][m]; for (int i = 0; i < n; i++) map[i] = next().toCharArray(); return map; } } }
Java
["5\n\n1003004\n\n4 1\n\n1 2 1\n\n179572007\n\n4 2\n\n2 7 3\n\n2 7 4\n\n111\n\n2 1\n\n2 2 6\n\n0000\n\n1 2\n\n1 4 0\n\n1 4 1\n\n484\n\n1 5\n\n2 2 0\n\n2 3 7\n\n1 2 5\n\n3 3 8\n\n2 2 6"]
3 seconds
["2 4\n1 5\n1 2\n-1 -1\n1 2\n-1 -1\n1 3\n1 3\n-1 -1\n-1 -1\n-1 -1"]
NoteConsider the first test case of example inputs. In this test case $$$n=7$$$, $$$s=$$$"1003004", $$$w=4$$$ and one query $$$l_1=1$$$, $$$r_1=2$$$, $$$k_1=1$$$. Note that $$$v(1,2)=10$$$. We need to find a pair of substrings of length $$$4$$$ such that $$$v(L_1, L_1+3)\cdot10+v(L_2,L_2+3)$$$ has a remainder of $$$k_1=1$$$ when divided by $$$9$$$. The values $$$L_1=2, L_2=4$$$ actually satisfy all the requirements: $$$v(L_1, L_1+w-1)=v(2,5)=30$$$, $$$v(L_2, L_2+w-1)=v(4,7)=3004$$$. Indeed, $$$30\cdot10+3004=3304$$$, which has a remainder of $$$1$$$ when divided by $$$9$$$. It can be shown that $$$L_1=2$$$ is the minimum possible value, and $$$L_2=4$$$ is the minimum possible with $$$L_1=2$$$.
Java 11
standard input
[ "hashing", "math" ]
b67870dcffa7bad682ef980dacd1f3db
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — number of input test cases. The first line of each test case contains a string $$$s$$$, which contains only the characters 0-9 and has a length $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$). The second line contains two integers $$$w, m$$$ ($$$1 \le w &lt; n, 1 \le m \le 2 \cdot 10^5$$$), where $$$n$$$ — is the length of the given string $$$s$$$. The number $$$w$$$ denotes the lengths of the substrings being searched for, and $$$m$$$ is the number of queries to be processed. The following $$$m$$$ lines contain integers $$$l_i, r_i, k_i$$$ ($$$1 \le l_i \le r_i \le n$$$, $$$0 \le k_i \le 8$$$) — $$$i$$$th query parameters. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$. It is also guaranteed that the sum of $$$m$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,900
For each request, print in a separate line: left borders of the required substrings: $$$L_1$$$ and $$$L_2$$$; -1 -1 otherwise, if there is no solution. If there are several solutions, minimize $$$L_1$$$ first, and minimize $$$L_2$$$ second.
standard output
PASSED
80d27304cd9e78f5436c7ff6b0a94423
train_110.jsonl
1662993300
Given the string $$$s$$$ of decimal digits (0-9) of length $$$n$$$.A substring is a sequence of consecutive characters of a string. The substring of this string is defined by a pair of indexes — with its left and right ends. So, each pair of indexes ($$$l, r$$$), where $$$1 \le l \le r \le n$$$, corresponds to a substring of the string $$$s$$$. We will define as $$$v(l,r)$$$ the numeric value of the corresponding substring (leading zeros are allowed in it).For example, if $$$n=7$$$, $$$s=$$$"1003004", then $$$v(1,3)=100$$$, $$$v(2,3)=0$$$ and $$$v(2,7)=3004$$$.You are given $$$n$$$, $$$s$$$ and an integer $$$w$$$ ($$$1 \le w &lt; n$$$).You need to process $$$m$$$ queries, each of which is characterized by $$$3$$$ numbers $$$l_i, r_i, k_i$$$ ($$$1 \le l_i \le r_i \le n; 0 \le k_i \le 8$$$).The answer to the $$$i$$$th query is such a pair of substrings of length $$$w$$$ that if we denote them as $$$(L_1, L_1+w-1)$$$ and $$$(L_2, L_2+w-1)$$$, then: $$$L_1 \ne L_2$$$, that is, the substrings are different; the remainder of dividing a number $$$v(L_1, L_1+w-1) \cdot v(l_i, r_i) + v(L_2, L_2 + w - 1)$$$ by $$$9$$$ is equal to $$$k_i$$$. If there are many matching substring pairs, then find a pair where $$$L_1$$$ is as small as possible. If there are many matching pairs in this case, then minimize $$$L_2$$$.Note that the answer may not exist.
256 megabytes
import java.io.*; import java.util.*; public class new1{ static int mod = 998244353; public static void main(String[] args) throws IOException{ BufferedWriter output = new BufferedWriter(new OutputStreamWriter(System.out)); FastReader s = new FastReader(); int t = s.nextInt(); for(int z = 1; z <= t; z++) { String str = s.next(); int n = str.length(); int w = s.nextInt(); ArrayList<Integer>[] aList = new ArrayList[9]; for(int i = 0; i < 9; i++) { ArrayList<Integer> list = new ArrayList<Integer>(); aList[i] = list; } int[] prefix = new int[n + 1]; for(int i = 0; i < n; i++) { prefix[i + 1] = prefix[i] + str.charAt(i) - '0'; } int j = 0; int sum = 0; for(int i = 0; i < n; i++) { while(j - i < w) { // if(i == 2) System.out.println(j); sum = sum + str.charAt(j) - '0'; j++; } aList[sum % 9].add(i); sum = sum - str.charAt(i) + '0'; //System.out.println(i + " " + j); if(j >= n) break; } int q = s.nextInt(); for(int i = 0; i < q; i++) { int l = s.nextInt(); int r = s.nextInt(); int k = s.nextInt(); int rem1 = (prefix[r] - prefix[l - 1]) % 9; int ans1 = Integer.MAX_VALUE; int ans2 = Integer.MAX_VALUE; for(int j1 = 0; j1 < 9; j1++) { for(int k1 = 0; k1 < 9; k1++) { if(j1 == k1 && aList[j1].size() < 2) continue; if(j1 != k1 && (aList[j1].size() < 1 || aList[k1].size() < 1)) continue; if(((j1 * rem1) % 9 + k1) % 9 != k) continue; int a1 = Integer.MAX_VALUE; int a2 = Integer.MAX_VALUE; if(j1 == k1) { a1 = aList[j1].get(0); a2 = aList[j1].get(1); } else { a1= aList[j1].get(0); a2 = aList[k1].get(0); } if(a1 < ans1) { ans1 = a1; ans2 = a2; } else if(a1 == ans1) { ans2 = Math.min(ans2, a2); } } } if(ans1 == Integer.MAX_VALUE) { ans1 = -2; ans2 = -2; } ans1++; ans2++; output.write(ans1 + " " + ans2 + "\n"); } } output.flush(); } } class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; }}
Java
["5\n\n1003004\n\n4 1\n\n1 2 1\n\n179572007\n\n4 2\n\n2 7 3\n\n2 7 4\n\n111\n\n2 1\n\n2 2 6\n\n0000\n\n1 2\n\n1 4 0\n\n1 4 1\n\n484\n\n1 5\n\n2 2 0\n\n2 3 7\n\n1 2 5\n\n3 3 8\n\n2 2 6"]
3 seconds
["2 4\n1 5\n1 2\n-1 -1\n1 2\n-1 -1\n1 3\n1 3\n-1 -1\n-1 -1\n-1 -1"]
NoteConsider the first test case of example inputs. In this test case $$$n=7$$$, $$$s=$$$"1003004", $$$w=4$$$ and one query $$$l_1=1$$$, $$$r_1=2$$$, $$$k_1=1$$$. Note that $$$v(1,2)=10$$$. We need to find a pair of substrings of length $$$4$$$ such that $$$v(L_1, L_1+3)\cdot10+v(L_2,L_2+3)$$$ has a remainder of $$$k_1=1$$$ when divided by $$$9$$$. The values $$$L_1=2, L_2=4$$$ actually satisfy all the requirements: $$$v(L_1, L_1+w-1)=v(2,5)=30$$$, $$$v(L_2, L_2+w-1)=v(4,7)=3004$$$. Indeed, $$$30\cdot10+3004=3304$$$, which has a remainder of $$$1$$$ when divided by $$$9$$$. It can be shown that $$$L_1=2$$$ is the minimum possible value, and $$$L_2=4$$$ is the minimum possible with $$$L_1=2$$$.
Java 11
standard input
[ "hashing", "math" ]
b67870dcffa7bad682ef980dacd1f3db
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — number of input test cases. The first line of each test case contains a string $$$s$$$, which contains only the characters 0-9 and has a length $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$). The second line contains two integers $$$w, m$$$ ($$$1 \le w &lt; n, 1 \le m \le 2 \cdot 10^5$$$), where $$$n$$$ — is the length of the given string $$$s$$$. The number $$$w$$$ denotes the lengths of the substrings being searched for, and $$$m$$$ is the number of queries to be processed. The following $$$m$$$ lines contain integers $$$l_i, r_i, k_i$$$ ($$$1 \le l_i \le r_i \le n$$$, $$$0 \le k_i \le 8$$$) — $$$i$$$th query parameters. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$. It is also guaranteed that the sum of $$$m$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,900
For each request, print in a separate line: left borders of the required substrings: $$$L_1$$$ and $$$L_2$$$; -1 -1 otherwise, if there is no solution. If there are several solutions, minimize $$$L_1$$$ first, and minimize $$$L_2$$$ second.
standard output
PASSED
21db5c4422f30b062e2c4d397c733d08
train_110.jsonl
1662993300
Given the string $$$s$$$ of decimal digits (0-9) of length $$$n$$$.A substring is a sequence of consecutive characters of a string. The substring of this string is defined by a pair of indexes — with its left and right ends. So, each pair of indexes ($$$l, r$$$), where $$$1 \le l \le r \le n$$$, corresponds to a substring of the string $$$s$$$. We will define as $$$v(l,r)$$$ the numeric value of the corresponding substring (leading zeros are allowed in it).For example, if $$$n=7$$$, $$$s=$$$"1003004", then $$$v(1,3)=100$$$, $$$v(2,3)=0$$$ and $$$v(2,7)=3004$$$.You are given $$$n$$$, $$$s$$$ and an integer $$$w$$$ ($$$1 \le w &lt; n$$$).You need to process $$$m$$$ queries, each of which is characterized by $$$3$$$ numbers $$$l_i, r_i, k_i$$$ ($$$1 \le l_i \le r_i \le n; 0 \le k_i \le 8$$$).The answer to the $$$i$$$th query is such a pair of substrings of length $$$w$$$ that if we denote them as $$$(L_1, L_1+w-1)$$$ and $$$(L_2, L_2+w-1)$$$, then: $$$L_1 \ne L_2$$$, that is, the substrings are different; the remainder of dividing a number $$$v(L_1, L_1+w-1) \cdot v(l_i, r_i) + v(L_2, L_2 + w - 1)$$$ by $$$9$$$ is equal to $$$k_i$$$. If there are many matching substring pairs, then find a pair where $$$L_1$$$ is as small as possible. If there are many matching pairs in this case, then minimize $$$L_2$$$.Note that the answer may not exist.
256 megabytes
//Some of the methods are copied from GeeksforGeeks Website import java.util.*; import java.lang.*; import java.io.*; @SuppressWarnings("unchecked") public class F_Kirei_and_the_Linear_Function { //static Scanner sc=new Scanner(System.in); //static Reader sc=new Reader(); static FastReader sc=new FastReader(System.in); static long mod = (long)(1e9)+ 7; static int max_num=(int)1e5+5; static List<Integer> gr[]; public static void main (String[] args) throws java.lang.Exception { //try{ /* out.println("Case #"+tt+": "+ans ); gr=new ArrayList[n]; for(int i=0;i<n;i++) gr[i]=new ArrayList<>(); while(l<=r) { int m=l+(r-l)/2; if(val(m)) { ans=m; l=m+1; } else r=m-1; } Collections.sort(al,Collections.reverseOrder()); StringBuilder sb=new StringBuilder(""); sb.append(cur); sb=sb.reverse(); String rev=sb.toString(); map.put(a[i],map.getOrDefault(a[i],0)+1); map.putIfAbsent(x,new ArrayList<>()); long n=sc.nextLong(); String s=sc.next(); char a[]=s.toCharArray(); */ int t = sc.nextInt(); for(int tt=1;tt<=t;tt++) { String s=sc.next(); char a[]=s.toCharArray(); int w=sc.nextInt(); int m=sc.nextInt(); int n=s.length(); int p[]=new int[n]; p[0]=(a[0]-'0')%9; for(int i=1;i<n;i++) p[i]=(p[i-1]+(a[i]-'0'))%9; List<Integer> map[]=new ArrayList[9]; for(int i=0;i<9;i++) map[i]=new ArrayList<>(); for(int i=0;i<n;i++) { int l=i; int r=l+w-1; if(r>=n) break; int val=p[r]; if(l!=0) val=(val-p[l-1]+9)%9; map[val].add(i); } while(m-->0) { int l=sc.nextInt()-1; int r=sc.nextInt()-1; int k=sc.nextInt(); int ans1=int_max,ans2=int_max; //(a*b)+c=k -> c=k-(a*b) int b=p[r]; if(l!=0) b=(b-p[l-1]+9)%9; for(int left=0;left<9;left++) { List<Integer> al1=map[left]; int si=al1.size(); int ab=(left*b)%9; int right=(k-ab+9)%9; if(si==0) continue; if(left==right) { if(si>=2) { int cur1=al1.get(0)+1,cur2=al1.get(1)+1; if(cur1<ans1) { ans1=cur1; ans2=cur2; } else if(cur1==ans1) { ans1=cur1; ans2=cur2; } } } else { List<Integer> al2=map[right]; if(al2.size()==0) continue; int cur1=al1.get(0)+1,cur2=al2.get(0)+1; if(cur1<ans1) { ans1=cur1; ans2=cur2; } else if(cur1==ans1) { ans1=cur1; ans2=cur2; } } } if(ans1==int_max) { ans1=-1; ans2=-1; } out.println(ans1+" "+ans2); } } out.flush(); out.close(); // } // catch(Exception e) // {} } /* ...SOLUTION ENDS HERE...........SOLUTION ENDS HERE... */ static void flag(boolean flag) { out.println(flag ? "YES" : "NO"); out.flush(); } /* Map<Long,Long> map=new HashMap<>(); for(int i=0;i<n;i++) { if(!map.containsKey(a[i])) map.put(a[i],1); else map.replace(a[i],map.get(a[i])+1); } Set<Map.Entry<Long,Long>> hmap=map.entrySet(); for(Map.Entry<Long,Long> data : hmap) { } Iterator<Integer> itr = set.iterator(); while(itr.hasNext()) { int val=itr.next(); } */ // static class Pair // { // int x,y; // Pair(int x,int y) // { // this.x=x; // this.y=y; // } // } // Arrays.sort(p, new Comparator<Pair>() // { // @Override // public int compare(Pair o1,Pair o2) // { // if(o1.x>o2.x) return 1; // else if(o1.x==o2.x) // { // if(o1.y>o2.y) return 1; // else return -1; // } // else return -1; // }}); static void print(int a[]) { int n=a.length; for(int i=0;i<n;i++) { out.print(a[i]+" "); } out.println(); out.flush(); } static void print(long a[]) { int n=a.length; for(int i=0;i<n;i++) { out.print(a[i]+" "); } out.println(); out.flush(); } static void print_int(ArrayList<Integer> al) { int si=al.size(); for(int i=0;i<si;i++) { out.print(al.get(i)+" "); } out.println(); out.flush(); } static void print_long(ArrayList<Long> al) { int si=al.size(); for(int i=0;i<si;i++) { out.print(al.get(i)+" "); } out.println(); out.flush(); } static void pn(int x) { out.println(x); out.flush(); } static void pn(long x) { out.println(x); out.flush(); } static void pn(String x) { out.println(x); out.flush(); } static int LowerBound(int a[], int x) { int l=-1,r=a.length; while(l+1<r) { int m=(l+r)>>>1; if(a[m]>=x) r=m; else l=m; } return r; } static int UpperBound(int a[], int x) {// x is the key or target value int l=-1,r=a.length; while(l+1<r) { int m=(l+r)>>>1; if(a[m]<=x) l=m; else r=m; } return l+1; } static void DFS(ArrayList<Integer> graph[],boolean[] visited, int u) { visited[u]=true; int v=0; for(int i=0;i<graph[u].size();i++) { v=graph[u].get(i); if(!visited[v]) DFS(graph,visited,v); } } static boolean[] prime(int num) { boolean[] bool = new boolean[num]; for (int i = 0; i< bool.length; i++) { bool[i] = true; } for (int i = 2; i< Math.sqrt(num); i++) { if(bool[i] == true) { for(int j = (i*i); j<num; j = j+i) { bool[j] = false; } } } if(num >= 0) { bool[0] = false; bool[1] = false; } return bool; } static long nCr(long a,long b,long mod) { return (((fact[(int)a] * modInverse(fact[(int)b],mod))%mod * modInverse(fact[(int)(a - b)],mod))%mod + mod)%mod; } static long fact[]=new long[max_num]; static void fact_fill() { fact[0]=1l; for(int i=1;i<max_num;i++) { fact[i]=(fact[i-1]*(long)i); if(fact[i]>=mod) fact[i]%=mod; } } static long modInverse(long a, long m) { return power(a, m - 2, m); } static long power(long x, long y, long m) { if (y == 0) return 1; long p = power(x, y / 2, m) % m; p = (long)((p * (long)p) % m); if (y % 2 == 0) return p; else return (long)((x * (long)p) % m); } static long sum_array(int a[]) { int n=a.length; long sum=0; for(int i=0;i<n;i++) sum+=a[i]; return sum; } static long sum_array(long a[]) { int n=a.length; long sum=0; for(int i=0;i<n;i++) sum+=a[i]; return sum; } 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 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 reverse_array(int a[]) { int n=a.length; int i,t; for (i = 0; i < n / 2; i++) { t = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = t; } } static void reverse_array(long a[]) { int n=a.length; int i; long t; for (i = 0; i < n / 2; i++) { t = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = t; } } static long gcd(long a, long b) { if (a == 0) return b; return gcd(b%a, a); } static int gcd(int a, int b) { if (a == 0) return b; return gcd(b%a, a); } static 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; } } static class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } static PrintWriter out=new PrintWriter(System.out); static int int_max=Integer.MAX_VALUE; static int int_min=Integer.MIN_VALUE; static long long_max=Long.MAX_VALUE; static long long_min=Long.MIN_VALUE; } // Thank You !
Java
["5\n\n1003004\n\n4 1\n\n1 2 1\n\n179572007\n\n4 2\n\n2 7 3\n\n2 7 4\n\n111\n\n2 1\n\n2 2 6\n\n0000\n\n1 2\n\n1 4 0\n\n1 4 1\n\n484\n\n1 5\n\n2 2 0\n\n2 3 7\n\n1 2 5\n\n3 3 8\n\n2 2 6"]
3 seconds
["2 4\n1 5\n1 2\n-1 -1\n1 2\n-1 -1\n1 3\n1 3\n-1 -1\n-1 -1\n-1 -1"]
NoteConsider the first test case of example inputs. In this test case $$$n=7$$$, $$$s=$$$"1003004", $$$w=4$$$ and one query $$$l_1=1$$$, $$$r_1=2$$$, $$$k_1=1$$$. Note that $$$v(1,2)=10$$$. We need to find a pair of substrings of length $$$4$$$ such that $$$v(L_1, L_1+3)\cdot10+v(L_2,L_2+3)$$$ has a remainder of $$$k_1=1$$$ when divided by $$$9$$$. The values $$$L_1=2, L_2=4$$$ actually satisfy all the requirements: $$$v(L_1, L_1+w-1)=v(2,5)=30$$$, $$$v(L_2, L_2+w-1)=v(4,7)=3004$$$. Indeed, $$$30\cdot10+3004=3304$$$, which has a remainder of $$$1$$$ when divided by $$$9$$$. It can be shown that $$$L_1=2$$$ is the minimum possible value, and $$$L_2=4$$$ is the minimum possible with $$$L_1=2$$$.
Java 11
standard input
[ "hashing", "math" ]
b67870dcffa7bad682ef980dacd1f3db
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — number of input test cases. The first line of each test case contains a string $$$s$$$, which contains only the characters 0-9 and has a length $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$). The second line contains two integers $$$w, m$$$ ($$$1 \le w &lt; n, 1 \le m \le 2 \cdot 10^5$$$), where $$$n$$$ — is the length of the given string $$$s$$$. The number $$$w$$$ denotes the lengths of the substrings being searched for, and $$$m$$$ is the number of queries to be processed. The following $$$m$$$ lines contain integers $$$l_i, r_i, k_i$$$ ($$$1 \le l_i \le r_i \le n$$$, $$$0 \le k_i \le 8$$$) — $$$i$$$th query parameters. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$. It is also guaranteed that the sum of $$$m$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,900
For each request, print in a separate line: left borders of the required substrings: $$$L_1$$$ and $$$L_2$$$; -1 -1 otherwise, if there is no solution. If there are several solutions, minimize $$$L_1$$$ first, and minimize $$$L_2$$$ second.
standard output
PASSED
02aa7f54495840db4bd23107d3938c24
train_110.jsonl
1662993300
Given the string $$$s$$$ of decimal digits (0-9) of length $$$n$$$.A substring is a sequence of consecutive characters of a string. The substring of this string is defined by a pair of indexes — with its left and right ends. So, each pair of indexes ($$$l, r$$$), where $$$1 \le l \le r \le n$$$, corresponds to a substring of the string $$$s$$$. We will define as $$$v(l,r)$$$ the numeric value of the corresponding substring (leading zeros are allowed in it).For example, if $$$n=7$$$, $$$s=$$$"1003004", then $$$v(1,3)=100$$$, $$$v(2,3)=0$$$ and $$$v(2,7)=3004$$$.You are given $$$n$$$, $$$s$$$ and an integer $$$w$$$ ($$$1 \le w &lt; n$$$).You need to process $$$m$$$ queries, each of which is characterized by $$$3$$$ numbers $$$l_i, r_i, k_i$$$ ($$$1 \le l_i \le r_i \le n; 0 \le k_i \le 8$$$).The answer to the $$$i$$$th query is such a pair of substrings of length $$$w$$$ that if we denote them as $$$(L_1, L_1+w-1)$$$ and $$$(L_2, L_2+w-1)$$$, then: $$$L_1 \ne L_2$$$, that is, the substrings are different; the remainder of dividing a number $$$v(L_1, L_1+w-1) \cdot v(l_i, r_i) + v(L_2, L_2 + w - 1)$$$ by $$$9$$$ is equal to $$$k_i$$$. If there are many matching substring pairs, then find a pair where $$$L_1$$$ is as small as possible. If there are many matching pairs in this case, then minimize $$$L_2$$$.Note that the answer may not exist.
256 megabytes
import java.io.*; import java.util.*; public class Main { static int mod = 998244353; //static int mod = (int)1e9+7; static boolean[] prime = new boolean[1]; static void yes() throws Exception { print("Yes"); } static void no() throws Exception { print("No"); } static int[][] dir1 = new int[][]{{0, 1}, {0, -1}, {1, 0}, {-1, 0}}; static int[][] dir2 = new int[][]{{0, 1}, {0, -1}, {1, 0}, {-1, 0}, {1, 1}, {1, -1}, {-1, 1}, {-1, -1}}; static int inf = 0x3f3f3f3f; static { for (int i = 2; i < prime.length; i++) prime[i] = true; for (int i = 2; i < prime.length; i++) { if (prime[i]) { for (int k = 2; i * k < prime.length; k++) { prime[i * k] = false; } } } } static class DSU { int[] fa; DSU(int n) { fa = new int[n]; for (int i = 0; i < n; i++) fa[i] = i; } int find(int t) { if (t != fa[t]) fa[t] = find(fa[t]); return fa[t]; } void join(int x, int y) { x = find(x); y = find(y); fa[x] = y; } } static List<Integer>[] lists; static void init(int n) { lists = new List[n]; for(int i = 0; i< n;i++){ lists[i] = new ArrayList<>(); } } static class LCA{ int[] dep; int[][] fa; int[] log; boolean[] v; public LCA(int n){ dep = new int[n+5]; log = new int[n+5]; fa = new int[n+5][31]; v = new boolean[n+5]; for (int i = 2; i <= n; ++i) { log[i] = log[i/2] + 1; } dfs(1,0); } private void dfs(int cur, int pre){ if(v[cur]) return; v[cur] = true; dep[cur] = dep[pre]+1; fa[cur][0] = pre; for (int i = 1; i <= log[dep[cur]]; ++i) { fa[cur][i] = fa[fa[cur][i - 1]][i - 1]; } for(int i : lists[cur]){ dfs(i,cur); } } private int lca(int a, int b){ if(dep[a] > dep[b]){ int t = a; a = b; b = t; } while (dep[a] != dep[b]){ b = fa[b][log[dep[b] - dep[a]]]; } if(a == b) return a; for (int k = log[dep[a]]; k >= 0; k--) { if (fa[a][k] != fa[b][k]) { a = fa[a][k]; b = fa[b][k]; } } return fa[a][0]; } } static BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); static long gcd(long a, long b) { return b == 0 ? a : gcd(b, a % b); } static long lcm(long a, long b) { return a * b / gcd(a, b); } static int get() throws Exception { String ss = bf.readLine(); if (ss.contains(" ")) ss = ss.substring(0, ss.indexOf(" ")); return Integer.parseInt(ss); } static long getx() throws Exception { String ss = bf.readLine(); if (ss.contains(" ")) ss = ss.substring(0, ss.indexOf(" ")); return Long.parseLong(ss); } static int[] getint() throws Exception { String[] s = bf.readLine().split(" "); int[] a = new int[s.length]; for (int i = 0; i < a.length; i++) { a[i] = Integer.parseInt(s[i]); } return a; } static long[] getlong() throws Exception { String[] s = bf.readLine().split(" "); long[] a = new long[s.length]; for (int i = 0; i < a.length; i++) { a[i] = Long.parseLong(s[i]); } return a; } static String getstr() throws Exception { return bf.readLine(); } static void println() throws Exception { bw.write("\n"); } static void print(int a) throws Exception { bw.write(a + "\n"); } static void print(long a) throws Exception { bw.write(a + "\n"); } static void print(String a) throws Exception { bw.write(a + "\n"); } static void print(int[] a) throws Exception { for (int i : a) { bw.write(i + " "); } println(); } static void print(long[] a) throws Exception { for (long i : a) { bw.write(i + " "); } println(); } static void print(int[][] a) throws Exception { for (int i[] : a) print(i); } static void print(long[][] a) throws Exception { for (long[] i : a) print(i); } static void print(char[] a) throws Exception { for (char i : a) { bw.write(i + ""); } println(); } static long pow(long a, long b) { long ans = 1; while (b > 0) { if ((b & 1) == 1) { ans *= a; } a *= a; b >>= 1; } return ans; } static int powmod(long a, long b, int mod) { long ans = 1; while (b > 0) { if ((b & 1) == 1) { ans = ans * a % mod; } a = a * a % mod; b >>= 1; } return (int) ans; } static void sort(int[] a) { int n = a.length; Integer[] b = new Integer[n]; for (int i = 0; i < n; i++) b[i] = a[i]; Arrays.sort(b); for (int i = 0; i < n; i++) a[i] = b[i]; } static void sort(long[] a) { int n = a.length; Long[] b = new Long[n]; for (int i = 0; i < n; i++) b[i] = a[i]; Arrays.sort(b); for (int i = 0; i < n; i++) a[i] = b[i]; } static void resort(int[] a) { int n = a.length; Integer[] b = new Integer[n]; for (int i = 0; i < n; i++) b[i] = a[i]; Arrays.sort(b); for (int i = 0; i < n; i++) a[i] = b[n - 1 - i]; } static void resort(long[] a) { int n = a.length; Long[] b = new Long[n]; for (int i = 0; i < n; i++) b[i] = a[i]; Arrays.sort(b); for (int i = 0; i < n; i++) a[i] = b[n - 1 - i]; } 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 max(int[] a) { int max = a[0]; for (int i : a) max = max(max, i); return max; } static int min(int[] a) { int min = a[0]; for (int i : a) min = min(min, i); return min; } static long max(long[] a) { long max = a[0]; for (long i : a) max = max(max, i); return max; } static long min(long[] a) { long min = a[0]; for (long i : a) min = min(min, i); return min; } static int abs(int a) { return Math.abs(a); } static long abs(long a) { return Math.abs(a); } static int[] getarr(List<Integer> list) { int n = list.size(); int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = list.get(i); return a; } public static void main(String[] args) throws Exception { int T = 1; T = get(); while (T-- > 0) { String s = getstr(); int n = s.length(); int[] p = getint(); int w = p[0], m = p[1]; int[] pre = new int[n+1]; for(int i = 1;i <= n;i++){ pre[i] = pre[i-1]+(s.charAt(i-1)-'0'); } List<Integer>[] f = new List[9]; for(int i = 0;i < 9;i++) f[i] = new ArrayList<>(); for(int i = 0;i+w <= n;i++){ f[(pre[i+w]-pre[i])%9].add(i); } while (m-- > 0){ p = getint(); int l = p[0], r = p[1], k = p[2]; int v = (pre[r]-pre[l-1])%9; int x = n, y = n; for(int i = 0;i < 9;i++){ if(f[i].size() > 1 && (i*v+i)%9 == k){ if(x > f[i].get(0)){ x = f[i].get(0); y = f[i].get(1); } } for(int j = 0;j < 9;j++){ if(j != i && f[i].size() > 0 && f[j].size() > 0 && (i*v+j)%9 == k){ if(x > f[i].get(0)){ x = f[i].get(0); y = f[j].get(0); } } } } if(x == n) print(new int[]{-1,-1}); else{ print(new int[]{x+1,y+1}); } } } bw.flush(); } static char get(int x){ return (char)(x+'a'); } }
Java
["5\n\n1003004\n\n4 1\n\n1 2 1\n\n179572007\n\n4 2\n\n2 7 3\n\n2 7 4\n\n111\n\n2 1\n\n2 2 6\n\n0000\n\n1 2\n\n1 4 0\n\n1 4 1\n\n484\n\n1 5\n\n2 2 0\n\n2 3 7\n\n1 2 5\n\n3 3 8\n\n2 2 6"]
3 seconds
["2 4\n1 5\n1 2\n-1 -1\n1 2\n-1 -1\n1 3\n1 3\n-1 -1\n-1 -1\n-1 -1"]
NoteConsider the first test case of example inputs. In this test case $$$n=7$$$, $$$s=$$$"1003004", $$$w=4$$$ and one query $$$l_1=1$$$, $$$r_1=2$$$, $$$k_1=1$$$. Note that $$$v(1,2)=10$$$. We need to find a pair of substrings of length $$$4$$$ such that $$$v(L_1, L_1+3)\cdot10+v(L_2,L_2+3)$$$ has a remainder of $$$k_1=1$$$ when divided by $$$9$$$. The values $$$L_1=2, L_2=4$$$ actually satisfy all the requirements: $$$v(L_1, L_1+w-1)=v(2,5)=30$$$, $$$v(L_2, L_2+w-1)=v(4,7)=3004$$$. Indeed, $$$30\cdot10+3004=3304$$$, which has a remainder of $$$1$$$ when divided by $$$9$$$. It can be shown that $$$L_1=2$$$ is the minimum possible value, and $$$L_2=4$$$ is the minimum possible with $$$L_1=2$$$.
Java 11
standard input
[ "hashing", "math" ]
b67870dcffa7bad682ef980dacd1f3db
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — number of input test cases. The first line of each test case contains a string $$$s$$$, which contains only the characters 0-9 and has a length $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$). The second line contains two integers $$$w, m$$$ ($$$1 \le w &lt; n, 1 \le m \le 2 \cdot 10^5$$$), where $$$n$$$ — is the length of the given string $$$s$$$. The number $$$w$$$ denotes the lengths of the substrings being searched for, and $$$m$$$ is the number of queries to be processed. The following $$$m$$$ lines contain integers $$$l_i, r_i, k_i$$$ ($$$1 \le l_i \le r_i \le n$$$, $$$0 \le k_i \le 8$$$) — $$$i$$$th query parameters. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$. It is also guaranteed that the sum of $$$m$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,900
For each request, print in a separate line: left borders of the required substrings: $$$L_1$$$ and $$$L_2$$$; -1 -1 otherwise, if there is no solution. If there are several solutions, minimize $$$L_1$$$ first, and minimize $$$L_2$$$ second.
standard output
PASSED
743441fb6af352e01b39a6acab77ff2e
train_110.jsonl
1662993300
Given the string $$$s$$$ of decimal digits (0-9) of length $$$n$$$.A substring is a sequence of consecutive characters of a string. The substring of this string is defined by a pair of indexes — with its left and right ends. So, each pair of indexes ($$$l, r$$$), where $$$1 \le l \le r \le n$$$, corresponds to a substring of the string $$$s$$$. We will define as $$$v(l,r)$$$ the numeric value of the corresponding substring (leading zeros are allowed in it).For example, if $$$n=7$$$, $$$s=$$$"1003004", then $$$v(1,3)=100$$$, $$$v(2,3)=0$$$ and $$$v(2,7)=3004$$$.You are given $$$n$$$, $$$s$$$ and an integer $$$w$$$ ($$$1 \le w &lt; n$$$).You need to process $$$m$$$ queries, each of which is characterized by $$$3$$$ numbers $$$l_i, r_i, k_i$$$ ($$$1 \le l_i \le r_i \le n; 0 \le k_i \le 8$$$).The answer to the $$$i$$$th query is such a pair of substrings of length $$$w$$$ that if we denote them as $$$(L_1, L_1+w-1)$$$ and $$$(L_2, L_2+w-1)$$$, then: $$$L_1 \ne L_2$$$, that is, the substrings are different; the remainder of dividing a number $$$v(L_1, L_1+w-1) \cdot v(l_i, r_i) + v(L_2, L_2 + w - 1)$$$ by $$$9$$$ is equal to $$$k_i$$$. If there are many matching substring pairs, then find a pair where $$$L_1$$$ is as small as possible. If there are many matching pairs in this case, then minimize $$$L_2$$$.Note that the answer may not exist.
256 megabytes
import java.io.*; import java.util.*; public class Kirei_and_the_Linear_Function { static FastScanner fs; static FastWriter fw; static boolean checkOnlineJudge = System.getProperty("ONLINE_JUDGE") == null; private static final int[][] kdir = new int[][]{{-1, 2}, {-2, 1}, {-2, -1}, {-1, -2}, {1, -2}, {2, -1}, {2, 1}, {1, 2}}; private static final int[][] dir = new int[][]{{-1, 0}, {1, 0}, {0, 1}, {0, -1}}; private static final int iMax = Integer.MAX_VALUE, iMin = Integer.MIN_VALUE; private static final long lMax = Long.MAX_VALUE, lMin = Long.MIN_VALUE; private static final int mod1 = (int) (1e9 + 7); private static final int mod2 = 998244353; public static void main(String[] args) throws IOException { fs = new FastScanner(); fw = new FastWriter(); int t = 1; t = fs.nextInt(); for (int tt = 1; tt <= t; tt++) { // fw.out.print("Case #" + tt + ": "); solve(); } fw.out.close(); } private static void solve() { String str = fs.nextLine(); int n = str.length(); int w = fs.nextInt(), m = fs.nextInt(); int[] prefix_rem = new int[n + 1]; for (int i = 0; i < n; i++) { int d = str.charAt(i) - '0'; prefix_rem[i + 1] = (prefix_rem[i] + d) % 9; } List<List<Integer>> list = new ArrayList<>(); for (int i = 0; i <= 10; i++) list.add(new ArrayList<>()); for (int i = w; i <= n; i++) { int num = (prefix_rem[i] - prefix_rem[i - w] + 9) % 9; list.get(num).add(i - w + 1); } while (m-- > 0) { int l = fs.nextInt(), r = fs.nextInt(), k = fs.nextInt(); int xx = (prefix_rem[r] - prefix_rem[l - 1] + 9) % 9; int[] ans = new int[]{-1, -1}; for (int i = 0; i <= 8; i++) { for (int j = 0; j <= 8; j++) { int lhs = (((i * xx) % 9) + j) % 9; if (lhs != k) continue; if (i == j) { if (list.get(i).size() <= 1) continue; int ff = list.get(i).get(0), ss = list.get(i).get(1); util(ans, ff, ss); } else { if (list.get(i).size() == 0 || list.get(j).size() == 0) continue; int ff = list.get(i).get(0), ss = list.get(j).get(0); util(ans, ff, ss); } } } fw.out.println(ans[0] + " " + ans[1]); } } private static void util(int[] ans, int ff, int ss) { if (ans[0] == -1 || ans[0] > ff) { ans[0] = ff; ans[1] = ss; return; } if (ans[0] == ff && ans[1] > ss) { ans[1] = ss; } } private static class UnionFind { private final int[] parent; private final int[] rank; UnionFind(int n) { parent = new int[n + 5]; rank = new int[n + 5]; for (int i = 0; i <= n; i++) { parent[i] = i; rank[i] = 0; } } private int find(int i) { if (parent[i] == i) return i; return parent[i] = find(parent[i]); } private void union(int a, int b) { a = find(a); b = find(b); if (a != b) { if (rank[a] < rank[b]) { int temp = a; a = b; b = temp; } parent[b] = a; if (rank[a] == rank[b]) rank[a]++; } } } private static class SCC { private final int n; private final List<List<Integer>> adjList; SCC(int _n, List<List<Integer>> _adjList) { n = _n; adjList = _adjList; } private List<List<Integer>> getSCC() { List<List<Integer>> ans = new ArrayList<>(); Stack<Integer> stack = new Stack<>(); boolean[] vis = new boolean[n]; for (int i = 0; i < n; i++) { if (!vis[i]) dfs(i, adjList, vis, stack); } vis = new boolean[n]; List<List<Integer>> rev_adjList = rev_graph(n, adjList); while (!stack.isEmpty()) { int curr = stack.pop(); if (!vis[curr]) { List<Integer> scc_list = new ArrayList<>(); dfs2(curr, rev_adjList, vis, scc_list); ans.add(scc_list); } } return ans; } private void dfs(int curr, List<List<Integer>> adjList, boolean[] vis, Stack<Integer> stack) { vis[curr] = true; for (int x : adjList.get(curr)) { if (!vis[x]) dfs(x, adjList, vis, stack); } stack.add(curr); } private void dfs2(int curr, List<List<Integer>> adjList, boolean[] vis, List<Integer> scc_list) { vis[curr] = true; scc_list.add(curr); for (int x : adjList.get(curr)) { if (!vis[x]) dfs2(x, adjList, vis, scc_list); } } } private static List<List<Integer>> rev_graph(int n, List<List<Integer>> adjList) { List<List<Integer>> ans = new ArrayList<>(); for (int i = 0; i < n; i++) ans.add(new ArrayList<>()); for (int i = 0; i < n; i++) { for (int x : adjList.get(i)) { ans.get(x).add(i); } } return ans; } private static class Calc_nCr { private final long[] fact; private final long[] invfact; private final int p; Calc_nCr(int n, int prime) { fact = new long[n + 5]; invfact = new long[n + 5]; p = prime; fact[0] = 1; for (int i = 1; i <= n; i++) { fact[i] = (i * fact[i - 1]) % p; } invfact[n] = pow_with_mod(fact[n], p - 2, p); for (int i = n - 1; i >= 0; i--) { invfact[i] = (invfact[i + 1] * (i + 1)) % p; } } private long nCr(int n, int r) { if (r > n || n < 0 || r < 0) return 0; return (((fact[n] * invfact[r]) % p) * invfact[n - r]) % p; } } private static int random_between_two_numbers(int l, int r) { Random ran = new Random(); return ran.nextInt(r - l) + l; } private static long gcd(long a, long b) { return (b == 0 ? a : gcd(b, a % b)); } private static long lcm(long a, long b) { return ((a * b) / gcd(a, b)); } private static long pow(long a, long b) { long result = 1; while (b > 0) { if ((b & 1L) == 1) { result = (result * a); } a = (a * a); b >>= 1; } return result; } private static long pow_with_mod(long a, long b, int mod) { long result = 1; while (b > 0) { if ((b & 1L) == 1) { result = (result * a) % mod; } a = (a * a) % mod; b >>= 1; } return result; } private static long ceilDiv(long a, long b) { return ((a + b - 1) / b); } private static long getMin(long... args) { long min = lMax; for (long arg : args) min = Math.min(min, arg); return min; } private static long getMax(long... args) { long max = lMin; for (long arg : args) max = Math.max(max, arg); return max; } private static boolean isPalindrome(String s, int l, int r) { int i = l, j = r; while (j - i >= 1) { if (s.charAt(i) != s.charAt(j)) return false; i++; j--; } return true; } private static List<Integer> primes(int n) { boolean[] primeArr = new boolean[n + 5]; Arrays.fill(primeArr, true); for (int i = 2; (i * i) <= n; i++) { if (primeArr[i]) { for (int j = i * i; j <= n; j += i) { primeArr[j] = false; } } } List<Integer> primeList = new ArrayList<>(); for (int i = 2; i <= n; i++) { if (primeArr[i]) primeList.add(i); } return primeList; } private static int noOfSetBits(long x) { int cnt = 0; while (x != 0) { x = x & (x - 1); cnt++; } return cnt; } private static int sumOfDigits(long num) { int cnt = 0; while (num > 0) { cnt += (num % 10); num /= 10; } return cnt; } private static int noOfDigits(long num) { int cnt = 0; while (num > 0) { cnt++; num /= 10; } return cnt; } private static boolean isPerfectSquare(long num) { long sqrt = (long) Math.sqrt(num); return ((sqrt * sqrt) == num); } private static class Pair<U, V> { private final U first; private final V second; @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Pair<?, ?> pair = (Pair<?, ?>) o; return first.equals(pair.first) && second.equals(pair.second); } @Override public int hashCode() { return Objects.hash(first, second); } @Override public String toString() { return "(" + first + ", " + second + ")"; } private Pair(U ff, V ss) { this.first = ff; this.second = ss; } } private static void randomizeIntArr(int[] arr, int n) { Random r = new Random(); for (int i = (n - 1); i > 0; i--) { int j = r.nextInt(i + 1); swapInIntArr(arr, i, j); } } private static void randomizeLongArr(long[] arr, int n) { Random r = new Random(); for (int i = (n - 1); i > 0; i--) { int j = r.nextInt(i + 1); swapInLongArr(arr, i, j); } } private static void swapInIntArr(int[] arr, int a, int b) { int temp = arr[a]; arr[a] = arr[b]; arr[b] = temp; } private static void swapInLongArr(long[] arr, int a, int b) { long temp = arr[a]; arr[a] = arr[b]; arr[b] = temp; } private static int[] readIntArray(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) arr[i] = fs.nextInt(); return arr; } private static long[] readLongArray(int n) { long[] arr = new long[n]; for (int i = 0; i < n; i++) arr[i] = fs.nextLong(); return arr; } private static List<Integer> readIntList(int n) { List<Integer> list = new ArrayList<>(); for (int i = 0; i < n; i++) list.add(fs.nextInt()); return list; } private static List<Long> readLongList(int n) { List<Long> list = new ArrayList<>(); for (int i = 0; i < n; i++) list.add(fs.nextLong()); return list; } private static class FastScanner { BufferedReader br; StringTokenizer st; FastScanner() throws IOException { if (checkOnlineJudge) this.br = new BufferedReader(new FileReader("src/input.txt")); else this.br = new BufferedReader(new InputStreamReader(System.in)); this.st = new StringTokenizer(""); } public String next() { while (!st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException err) { err.printStackTrace(); } } return st.nextToken(); } public String nextLine() { if (st.hasMoreTokens()) { return st.nextToken("").trim(); } try { return br.readLine().trim(); } catch (IOException err) { err.printStackTrace(); } return ""; } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } } private static class FastWriter { PrintWriter out; FastWriter() throws IOException { if (checkOnlineJudge) out = new PrintWriter(new FileWriter("src/output.txt")); else out = new PrintWriter(System.out); } } }
Java
["5\n\n1003004\n\n4 1\n\n1 2 1\n\n179572007\n\n4 2\n\n2 7 3\n\n2 7 4\n\n111\n\n2 1\n\n2 2 6\n\n0000\n\n1 2\n\n1 4 0\n\n1 4 1\n\n484\n\n1 5\n\n2 2 0\n\n2 3 7\n\n1 2 5\n\n3 3 8\n\n2 2 6"]
3 seconds
["2 4\n1 5\n1 2\n-1 -1\n1 2\n-1 -1\n1 3\n1 3\n-1 -1\n-1 -1\n-1 -1"]
NoteConsider the first test case of example inputs. In this test case $$$n=7$$$, $$$s=$$$"1003004", $$$w=4$$$ and one query $$$l_1=1$$$, $$$r_1=2$$$, $$$k_1=1$$$. Note that $$$v(1,2)=10$$$. We need to find a pair of substrings of length $$$4$$$ such that $$$v(L_1, L_1+3)\cdot10+v(L_2,L_2+3)$$$ has a remainder of $$$k_1=1$$$ when divided by $$$9$$$. The values $$$L_1=2, L_2=4$$$ actually satisfy all the requirements: $$$v(L_1, L_1+w-1)=v(2,5)=30$$$, $$$v(L_2, L_2+w-1)=v(4,7)=3004$$$. Indeed, $$$30\cdot10+3004=3304$$$, which has a remainder of $$$1$$$ when divided by $$$9$$$. It can be shown that $$$L_1=2$$$ is the minimum possible value, and $$$L_2=4$$$ is the minimum possible with $$$L_1=2$$$.
Java 11
standard input
[ "hashing", "math" ]
b67870dcffa7bad682ef980dacd1f3db
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — number of input test cases. The first line of each test case contains a string $$$s$$$, which contains only the characters 0-9 and has a length $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$). The second line contains two integers $$$w, m$$$ ($$$1 \le w &lt; n, 1 \le m \le 2 \cdot 10^5$$$), where $$$n$$$ — is the length of the given string $$$s$$$. The number $$$w$$$ denotes the lengths of the substrings being searched for, and $$$m$$$ is the number of queries to be processed. The following $$$m$$$ lines contain integers $$$l_i, r_i, k_i$$$ ($$$1 \le l_i \le r_i \le n$$$, $$$0 \le k_i \le 8$$$) — $$$i$$$th query parameters. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$. It is also guaranteed that the sum of $$$m$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,900
For each request, print in a separate line: left borders of the required substrings: $$$L_1$$$ and $$$L_2$$$; -1 -1 otherwise, if there is no solution. If there are several solutions, minimize $$$L_1$$$ first, and minimize $$$L_2$$$ second.
standard output
PASSED
98ff91457fd885b5d30258a2f8e71ba8
train_110.jsonl
1662993300
Given the string $$$s$$$ of decimal digits (0-9) of length $$$n$$$.A substring is a sequence of consecutive characters of a string. The substring of this string is defined by a pair of indexes — with its left and right ends. So, each pair of indexes ($$$l, r$$$), where $$$1 \le l \le r \le n$$$, corresponds to a substring of the string $$$s$$$. We will define as $$$v(l,r)$$$ the numeric value of the corresponding substring (leading zeros are allowed in it).For example, if $$$n=7$$$, $$$s=$$$"1003004", then $$$v(1,3)=100$$$, $$$v(2,3)=0$$$ and $$$v(2,7)=3004$$$.You are given $$$n$$$, $$$s$$$ and an integer $$$w$$$ ($$$1 \le w &lt; n$$$).You need to process $$$m$$$ queries, each of which is characterized by $$$3$$$ numbers $$$l_i, r_i, k_i$$$ ($$$1 \le l_i \le r_i \le n; 0 \le k_i \le 8$$$).The answer to the $$$i$$$th query is such a pair of substrings of length $$$w$$$ that if we denote them as $$$(L_1, L_1+w-1)$$$ and $$$(L_2, L_2+w-1)$$$, then: $$$L_1 \ne L_2$$$, that is, the substrings are different; the remainder of dividing a number $$$v(L_1, L_1+w-1) \cdot v(l_i, r_i) + v(L_2, L_2 + w - 1)$$$ by $$$9$$$ is equal to $$$k_i$$$. If there are many matching substring pairs, then find a pair where $$$L_1$$$ is as small as possible. If there are many matching pairs in this case, then minimize $$$L_2$$$.Note that the answer may not exist.
256 megabytes
import java.io.*; import java.util.*; public class Main { public static int INF = 0x3f3f3f3f, mod = 1000000007, mod9 = 998244353; public static void main(String args[]){ try { PrintWriter o = new PrintWriter(System.out); boolean multiTest = true; // init if(multiTest) { int t = fReader.nextInt(), loop = 0; while (loop < t) {loop++;solve(o);} } else solve(o); o.close(); } catch (Exception e) {e.printStackTrace();} } static List<Integer>[] modLi; static int[] preSum; static void solve(PrintWriter o) { try { String s = fReader.nextString(); int w = fReader.nextInt(), m = fReader.nextInt(); int[] l = new int[m]; int[] r = new int[m]; int[] k = new int[m]; modLi = new ArrayList[9]; for(int i=0;i<9;i++) modLi[i] = new ArrayList<>(); preSum = new int[s.length()+1]; precalc(s, w); for(int i=0;i<m;i++) { l[i] = fReader.nextInt(); r[i] = fReader.nextInt(); k[i] = fReader.nextInt(); int v = (preSum[r[i]] - preSum[l[i]-1]) % 9; int[] res = new int[2]; Arrays.fill(res, INF); for(int a=0;a<9;a++) { int mul = a*v%9; int b = (k[i]-mul+9) % 9; if(modLi[a].size() == 0 || modLi[b].size() == 0) continue; if(a != b) { int[] temp = new int[]{modLi[a].get(0), modLi[b].get(0)}; compareAndAssign(res, temp); } else if(a == b && modLi[a].size() >= 2) { int[] temp = new int[]{modLi[a].get(0), modLi[a].get(1)}; compareAndAssign(res, temp); } } if(res[0] != INF && res[1] != INF) o.println((res[0]+1) + " " + (res[1]+1)); else o.println(-1 + " " + -1); } } catch (Exception e) { e.printStackTrace(); } } static void precalc(String s, int w) { for(int i=1;i<=s.length();i++) preSum[i] = preSum[i-1] + (s.charAt(i-1)-'0'); for(int i=0;i<=s.length()-w;i++) modLi[(preSum[i+w] - preSum[i]) % 9].add(i); } static void compareAndAssign(int[] origin, int[] temp) { if(temp[0] <= origin[0]) { if(temp[0] == origin[0]) { if(temp[1] < origin[1]) { origin[1] = temp[1]; } } else { origin[0] = temp[0]; origin[1] = temp[1]; } } } public static int upper_bound(List<Integer> a, int val){ int l = 0, r = a.size(); while(l < r){ int mid = l + (r - l) / 2; if(a.get(mid) <= val) l = mid + 1; else r = mid; } return l; } public static int lower_bound(List<Integer> a, int val){ int l = 0, r = a.size(); while(l < r){ int mid = l + (r - l) / 2; if(a.get(mid) < val) l = mid + 1; else r = mid; } return l; } 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 / gcd(a,b)*b; } public static boolean isPrime(long x){ boolean ok = true; for(long i=2;i<=Math.sqrt(x);i++){ if(x % i == 0){ ok = false; break; } } return ok; } public static void reverse(int[] array){ reverse(array, 0 , array.length-1); } public static void reverse(int[] array, int left, int right) { if (array != null) { int i = left; for(int j = right; j > i; ++i) { int tmp = array[j]; array[j] = array[i]; array[i] = tmp; --j; } } } public static long qpow(long a, long n){ long ret = 1l; while(n > 0){ if((n & 1) == 1){ ret = ret * a % mod; } n >>= 1; a = a * a % mod; } return ret; } public static class DSU { int[] parent; int[] size; int n; public DSU(int n){ this.n = n; parent = new int[n]; size = new int[n]; for(int i=0;i<n;i++){ parent[i] = i; size[i] = 1; } } public int find(int p){ while(parent[p] != p){ parent[p] = parent[parent[p]]; p = parent[p]; } return p; } public void union(int p, int q){ int root_p = find(p); int root_q = find(q); if(root_p == root_q) return; if(size[root_p] >= size[root_q]){ parent[root_q] = root_p; size[root_p] += size[root_q]; size[root_q] = 0; } else{ parent[root_p] = root_q; size[root_q] += size[root_p]; size[root_p] = 0; } n--; } public int getTotalComNum(){ return n; } public int getSize(int i){ return size[find(i)]; } } public static class FenWick { int n; long[] tree; public FenWick(int n){ this.n = n; tree = new long[n+1]; } private void add(int x, long val){ while(x <= n){ tree[x] += val; x += x&-x; } } private long query(int x){ long ret = 0l; while(x > 0){ ret += tree[x]; x -= x&-x; } return ret; } } public static class fReader { private static BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); private static StringTokenizer tokenizer = new StringTokenizer(""); private static String next() throws IOException{ while(!tokenizer.hasMoreTokens()){tokenizer = new StringTokenizer(reader.readLine());} return tokenizer.nextToken(); } public static int nextInt() throws IOException {return Integer.parseInt(next());} public static Long nextLong() throws IOException {return Long.parseLong(next());} public static double nextDouble() throws IOException {return Double.parseDouble(next());} public static char nextChar() throws IOException {return next().toCharArray()[0];} public static String nextString() throws IOException {return next();} public static String nextLine() throws IOException {return reader.readLine();} } }
Java
["5\n\n1003004\n\n4 1\n\n1 2 1\n\n179572007\n\n4 2\n\n2 7 3\n\n2 7 4\n\n111\n\n2 1\n\n2 2 6\n\n0000\n\n1 2\n\n1 4 0\n\n1 4 1\n\n484\n\n1 5\n\n2 2 0\n\n2 3 7\n\n1 2 5\n\n3 3 8\n\n2 2 6"]
3 seconds
["2 4\n1 5\n1 2\n-1 -1\n1 2\n-1 -1\n1 3\n1 3\n-1 -1\n-1 -1\n-1 -1"]
NoteConsider the first test case of example inputs. In this test case $$$n=7$$$, $$$s=$$$"1003004", $$$w=4$$$ and one query $$$l_1=1$$$, $$$r_1=2$$$, $$$k_1=1$$$. Note that $$$v(1,2)=10$$$. We need to find a pair of substrings of length $$$4$$$ such that $$$v(L_1, L_1+3)\cdot10+v(L_2,L_2+3)$$$ has a remainder of $$$k_1=1$$$ when divided by $$$9$$$. The values $$$L_1=2, L_2=4$$$ actually satisfy all the requirements: $$$v(L_1, L_1+w-1)=v(2,5)=30$$$, $$$v(L_2, L_2+w-1)=v(4,7)=3004$$$. Indeed, $$$30\cdot10+3004=3304$$$, which has a remainder of $$$1$$$ when divided by $$$9$$$. It can be shown that $$$L_1=2$$$ is the minimum possible value, and $$$L_2=4$$$ is the minimum possible with $$$L_1=2$$$.
Java 11
standard input
[ "hashing", "math" ]
b67870dcffa7bad682ef980dacd1f3db
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — number of input test cases. The first line of each test case contains a string $$$s$$$, which contains only the characters 0-9 and has a length $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$). The second line contains two integers $$$w, m$$$ ($$$1 \le w &lt; n, 1 \le m \le 2 \cdot 10^5$$$), where $$$n$$$ — is the length of the given string $$$s$$$. The number $$$w$$$ denotes the lengths of the substrings being searched for, and $$$m$$$ is the number of queries to be processed. The following $$$m$$$ lines contain integers $$$l_i, r_i, k_i$$$ ($$$1 \le l_i \le r_i \le n$$$, $$$0 \le k_i \le 8$$$) — $$$i$$$th query parameters. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$. It is also guaranteed that the sum of $$$m$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,900
For each request, print in a separate line: left borders of the required substrings: $$$L_1$$$ and $$$L_2$$$; -1 -1 otherwise, if there is no solution. If there are several solutions, minimize $$$L_1$$$ first, and minimize $$$L_2$$$ second.
standard output
PASSED
5215a249e83a18198bd6ca156989e4c6
train_110.jsonl
1662993300
Given the string $$$s$$$ of decimal digits (0-9) of length $$$n$$$.A substring is a sequence of consecutive characters of a string. The substring of this string is defined by a pair of indexes — with its left and right ends. So, each pair of indexes ($$$l, r$$$), where $$$1 \le l \le r \le n$$$, corresponds to a substring of the string $$$s$$$. We will define as $$$v(l,r)$$$ the numeric value of the corresponding substring (leading zeros are allowed in it).For example, if $$$n=7$$$, $$$s=$$$"1003004", then $$$v(1,3)=100$$$, $$$v(2,3)=0$$$ and $$$v(2,7)=3004$$$.You are given $$$n$$$, $$$s$$$ and an integer $$$w$$$ ($$$1 \le w &lt; n$$$).You need to process $$$m$$$ queries, each of which is characterized by $$$3$$$ numbers $$$l_i, r_i, k_i$$$ ($$$1 \le l_i \le r_i \le n; 0 \le k_i \le 8$$$).The answer to the $$$i$$$th query is such a pair of substrings of length $$$w$$$ that if we denote them as $$$(L_1, L_1+w-1)$$$ and $$$(L_2, L_2+w-1)$$$, then: $$$L_1 \ne L_2$$$, that is, the substrings are different; the remainder of dividing a number $$$v(L_1, L_1+w-1) \cdot v(l_i, r_i) + v(L_2, L_2 + w - 1)$$$ by $$$9$$$ is equal to $$$k_i$$$. If there are many matching substring pairs, then find a pair where $$$L_1$$$ is as small as possible. If there are many matching pairs in this case, then minimize $$$L_2$$$.Note that the answer may not exist.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Random; import java.util.StringTokenizer; import java.util.concurrent.ThreadLocalRandom; /* */ public class CF { private static void sport(String s, int[][] q, int w) { int n = s.length(); int m = q.length; int[] p = new int[n + 1]; for (int i = 1; i < n + 1; i++) { p[i] = p[i - 1] + (s.charAt(i - 1) - '0'); } int[][] a = new int[9][2]; for (int[] ints : a) { Arrays.fill(ints, -1); } List<Integer>[] list = new ArrayList[10]; for (int i = 0; i < 10; i++) { list[i] = new ArrayList<>(); } for (int i = 0; i + w <= n; i++) { int val = p[i + w - 1 + 1] - p[i]; list[val % 9].add(i); } for (int i = 0; i < 9; i++) { if (list[i] != null && !list[i].isEmpty()) { a[i][0] = list[i].get(0); } if (list[i] != null && list[i].size() > 1) { a[i][1] = list[i].get(1); } } for (int i = 0; i < m; i++) { int li = q[i][0]; int ri = q[i][1]; int k = q[i][2]; int val = (p[ri + 1] - p[li]) % 9; int[] ans = new int[] {-1, -1}; for (int j = 0; j < 9; j++) { for (int l = 0; l < 9; l++) { for (int o = 0; o < 2; o++) { for (int r = 0; r < 2; r++) { if (a[j][o] != -1 && a[l][r] != -1) { int res = (j * val + l) % 9; if (res == k && a[j][o] != a[l][r]) { if (ans[0] == -1 || ans[0] > a[j][o]) { ans[0] = a[j][o]; ans[1] = a[l][r]; } else if (ans[0] == a[j][o]) { ans[1] = Math.min(ans[1], a[l][r]); } } } } } } } if (ans[0] == -1) { System.out.println(ans[0] + " " + ans[1]); } else { System.out.println((ans[0] + 1) + " " + (ans[1] + 1)); } } } static void shuffleArray(int[] ar) { // If running on Java 6 or older, use `new Random()` on RHS here Random rnd = ThreadLocalRandom.current(); for (int i = ar.length - 1; i > 0; i--) { int index = rnd.nextInt(i + 1); // Simple swap int a = ar[index]; ar[index] = ar[i]; ar[i] = a; } } public static void main(String[] args) { FastScanner sc = new FastScanner(); int t = sc.nextInt(); for (int i = 0; i < t; i++) { String s = sc.next(); int w = sc.nextInt(); int m = sc.nextInt(); int[][] q = new int[m][3]; for (int j = 0; j < m; j++) { q[j] = new int[] {sc.nextInt() - 1, sc.nextInt() - 1, sc.nextInt()}; } sport(s, q, w); } } // 1 2 3 4 5 6 | 2 static void swap(int[] a, int i, int j) { int t = a[i]; a[i] = a[j]; a[j] = t; } static class BIT { // The size of the array holding the Fenwick tree values final int N; // This array contains the Fenwick tree ranges private long[] tree; // Create an empty Fenwick Tree with 'sz' parameter zero based. public BIT(int sz) { tree = new long[(N = sz + 1)]; } // Construct a Fenwick tree with an initial set of values. // The 'values' array MUST BE ONE BASED meaning values[0] // does not get used, O(n) construction. public BIT(long[] values) { if (values == null) { throw new IllegalArgumentException("Values array cannot be null!"); } N = values.length; values[0] = 0L; // Make a clone of the values array since we manipulate // the array in place destroying all its original content. tree = values.clone(); for (int i = 1; i < N; i++) { int parent = i + lsb(i); if (parent < N) { tree[parent] += tree[i]; } } } // Returns the value of the least significant bit (LSB) // lsb(108) = lsb(0b1101100) = 0b100 = 4 // lsb(104) = lsb(0b1101000) = 0b1000 = 8 // lsb(96) = lsb(0b1100000) = 0b100000 = 32 // lsb(64) = lsb(0b1000000) = 0b1000000 = 64 private static int lsb(int i) { // Isolates the lowest one bit value return i & -i; // An alternative method is to use the Java's built in method // return Integer.lowestOneBit(i); } // Computes the prefix sum from [1, i], O(log(n)) private long prefixSum(int i) { long sum = 0L; while (i != 0) { sum += tree[i]; i &= ~lsb(i); // Equivalently, i -= lsb(i); } return sum; } // Returns the sum of the interval [left, right], O(log(n)) public long sum(int left, int right) { if (right < left) { throw new IllegalArgumentException("Make sure right >= left"); } return prefixSum(right) - prefixSum(left - 1); } // Get the value at index i public long get(int i) { return sum(i, i); } // Add 'v' to index 'i', O(log(n)) public void add(int i, long v) { while (i < N) { tree[i] += v; i += lsb(i); } } // Set index i to be equal to v, O(log(n)) public void set(int i, long v) { add(i, v - sum(i, i)); } @Override public String toString() { return java.util.Arrays.toString(tree); } } static class FastScanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long[] readArrayLong(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) { a[i] = nextLong(); } return a; } int[] readArrayInt(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } } }
Java
["5\n\n1003004\n\n4 1\n\n1 2 1\n\n179572007\n\n4 2\n\n2 7 3\n\n2 7 4\n\n111\n\n2 1\n\n2 2 6\n\n0000\n\n1 2\n\n1 4 0\n\n1 4 1\n\n484\n\n1 5\n\n2 2 0\n\n2 3 7\n\n1 2 5\n\n3 3 8\n\n2 2 6"]
3 seconds
["2 4\n1 5\n1 2\n-1 -1\n1 2\n-1 -1\n1 3\n1 3\n-1 -1\n-1 -1\n-1 -1"]
NoteConsider the first test case of example inputs. In this test case $$$n=7$$$, $$$s=$$$"1003004", $$$w=4$$$ and one query $$$l_1=1$$$, $$$r_1=2$$$, $$$k_1=1$$$. Note that $$$v(1,2)=10$$$. We need to find a pair of substrings of length $$$4$$$ such that $$$v(L_1, L_1+3)\cdot10+v(L_2,L_2+3)$$$ has a remainder of $$$k_1=1$$$ when divided by $$$9$$$. The values $$$L_1=2, L_2=4$$$ actually satisfy all the requirements: $$$v(L_1, L_1+w-1)=v(2,5)=30$$$, $$$v(L_2, L_2+w-1)=v(4,7)=3004$$$. Indeed, $$$30\cdot10+3004=3304$$$, which has a remainder of $$$1$$$ when divided by $$$9$$$. It can be shown that $$$L_1=2$$$ is the minimum possible value, and $$$L_2=4$$$ is the minimum possible with $$$L_1=2$$$.
Java 11
standard input
[ "hashing", "math" ]
b67870dcffa7bad682ef980dacd1f3db
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — number of input test cases. The first line of each test case contains a string $$$s$$$, which contains only the characters 0-9 and has a length $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$). The second line contains two integers $$$w, m$$$ ($$$1 \le w &lt; n, 1 \le m \le 2 \cdot 10^5$$$), where $$$n$$$ — is the length of the given string $$$s$$$. The number $$$w$$$ denotes the lengths of the substrings being searched for, and $$$m$$$ is the number of queries to be processed. The following $$$m$$$ lines contain integers $$$l_i, r_i, k_i$$$ ($$$1 \le l_i \le r_i \le n$$$, $$$0 \le k_i \le 8$$$) — $$$i$$$th query parameters. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$. It is also guaranteed that the sum of $$$m$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,900
For each request, print in a separate line: left borders of the required substrings: $$$L_1$$$ and $$$L_2$$$; -1 -1 otherwise, if there is no solution. If there are several solutions, minimize $$$L_1$$$ first, and minimize $$$L_2$$$ second.
standard output
PASSED
8dcdf0018c0ec66cd6179214a57a2311
train_110.jsonl
1662993300
Given the string $$$s$$$ of decimal digits (0-9) of length $$$n$$$.A substring is a sequence of consecutive characters of a string. The substring of this string is defined by a pair of indexes — with its left and right ends. So, each pair of indexes ($$$l, r$$$), where $$$1 \le l \le r \le n$$$, corresponds to a substring of the string $$$s$$$. We will define as $$$v(l,r)$$$ the numeric value of the corresponding substring (leading zeros are allowed in it).For example, if $$$n=7$$$, $$$s=$$$"1003004", then $$$v(1,3)=100$$$, $$$v(2,3)=0$$$ and $$$v(2,7)=3004$$$.You are given $$$n$$$, $$$s$$$ and an integer $$$w$$$ ($$$1 \le w &lt; n$$$).You need to process $$$m$$$ queries, each of which is characterized by $$$3$$$ numbers $$$l_i, r_i, k_i$$$ ($$$1 \le l_i \le r_i \le n; 0 \le k_i \le 8$$$).The answer to the $$$i$$$th query is such a pair of substrings of length $$$w$$$ that if we denote them as $$$(L_1, L_1+w-1)$$$ and $$$(L_2, L_2+w-1)$$$, then: $$$L_1 \ne L_2$$$, that is, the substrings are different; the remainder of dividing a number $$$v(L_1, L_1+w-1) \cdot v(l_i, r_i) + v(L_2, L_2 + w - 1)$$$ by $$$9$$$ is equal to $$$k_i$$$. If there are many matching substring pairs, then find a pair where $$$L_1$$$ is as small as possible. If there are many matching pairs in this case, then minimize $$$L_2$$$.Note that the answer may not exist.
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 SolutionF { public static void main(String[] args) throws Exception { out = new PrintWriter(new BufferedOutputStream(System.out)); sc = new FastReader(); int test = sc.nextInt(); for (int t = 1; t <= test; t++) { solve(t); } out.close(); } private static void solve(int t) { char[] arr = sc.next().toCharArray(); int n = arr.length; int substringLength = sc.nextInt(); int queries = sc.nextInt(); int[] prefixSum = new int[n + 1]; for (int i = 0; i < n; i++) { prefixSum[i + 1] = prefixSum[i] + (arr[i] - '0'); } Map<Integer, List<Integer>> remainderIndices = new HashMap<>(); for (int i = 0; i < 9; i++) { remainderIndices.put(i, new ArrayList<>()); } for (int i = 0; i + substringLength - 1 < n; i++) { int remainder = (prefixSum[i + substringLength] - prefixSum[i]) % 9; remainderIndices.get(remainder).add(i); } for (int i = 0; i < queries; i++) { int l = sc.nextInt(); int r = sc.nextInt(); int remainderRequired = sc.nextInt(); // (v1 * v3 + v2) % 9 == k int v3 = (prefixSum[r] - prefixSum[l - 1]) % 9; int[] startIndices = new int[2]; Arrays.fill(startIndices, n); for (int v1 = 0; v1 < 9; v1++) { for (int v2 = 0; v2 < 9; v2++) { if (remainderIndices.get(v1).size() > 0 && remainderIndices.get(v2).size() > 0 && (v1 * v3 + v2) % 9 == remainderRequired) { int x = n, y = n; if (v1 == v2) { if (remainderIndices.get(v1).size() > 1) { x = remainderIndices.get(v1).get(0); y = remainderIndices.get(v1).get(1); } }else { x = remainderIndices.get(v1).get(0); y = remainderIndices.get(v2).get(0); } if (x < startIndices[0]) { startIndices[0] = x; startIndices[1] = y; }else if (x == startIndices[0] && y < startIndices[1]) { startIndices[1] = y; } } } } if (startIndices[0] == n) { out.println(-1 + " " + -1); }else { out.println((startIndices[0] + 1) + " " + (startIndices[1] + 1)); } } } 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
["5\n\n1003004\n\n4 1\n\n1 2 1\n\n179572007\n\n4 2\n\n2 7 3\n\n2 7 4\n\n111\n\n2 1\n\n2 2 6\n\n0000\n\n1 2\n\n1 4 0\n\n1 4 1\n\n484\n\n1 5\n\n2 2 0\n\n2 3 7\n\n1 2 5\n\n3 3 8\n\n2 2 6"]
3 seconds
["2 4\n1 5\n1 2\n-1 -1\n1 2\n-1 -1\n1 3\n1 3\n-1 -1\n-1 -1\n-1 -1"]
NoteConsider the first test case of example inputs. In this test case $$$n=7$$$, $$$s=$$$"1003004", $$$w=4$$$ and one query $$$l_1=1$$$, $$$r_1=2$$$, $$$k_1=1$$$. Note that $$$v(1,2)=10$$$. We need to find a pair of substrings of length $$$4$$$ such that $$$v(L_1, L_1+3)\cdot10+v(L_2,L_2+3)$$$ has a remainder of $$$k_1=1$$$ when divided by $$$9$$$. The values $$$L_1=2, L_2=4$$$ actually satisfy all the requirements: $$$v(L_1, L_1+w-1)=v(2,5)=30$$$, $$$v(L_2, L_2+w-1)=v(4,7)=3004$$$. Indeed, $$$30\cdot10+3004=3304$$$, which has a remainder of $$$1$$$ when divided by $$$9$$$. It can be shown that $$$L_1=2$$$ is the minimum possible value, and $$$L_2=4$$$ is the minimum possible with $$$L_1=2$$$.
Java 11
standard input
[ "hashing", "math" ]
b67870dcffa7bad682ef980dacd1f3db
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — number of input test cases. The first line of each test case contains a string $$$s$$$, which contains only the characters 0-9 and has a length $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$). The second line contains two integers $$$w, m$$$ ($$$1 \le w &lt; n, 1 \le m \le 2 \cdot 10^5$$$), where $$$n$$$ — is the length of the given string $$$s$$$. The number $$$w$$$ denotes the lengths of the substrings being searched for, and $$$m$$$ is the number of queries to be processed. The following $$$m$$$ lines contain integers $$$l_i, r_i, k_i$$$ ($$$1 \le l_i \le r_i \le n$$$, $$$0 \le k_i \le 8$$$) — $$$i$$$th query parameters. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$. It is also guaranteed that the sum of $$$m$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,900
For each request, print in a separate line: left borders of the required substrings: $$$L_1$$$ and $$$L_2$$$; -1 -1 otherwise, if there is no solution. If there are several solutions, minimize $$$L_1$$$ first, and minimize $$$L_2$$$ second.
standard output
PASSED
29d4544f6594f7944a6f11aff8e53bee
train_110.jsonl
1662993300
Given the string $$$s$$$ of decimal digits (0-9) of length $$$n$$$.A substring is a sequence of consecutive characters of a string. The substring of this string is defined by a pair of indexes — with its left and right ends. So, each pair of indexes ($$$l, r$$$), where $$$1 \le l \le r \le n$$$, corresponds to a substring of the string $$$s$$$. We will define as $$$v(l,r)$$$ the numeric value of the corresponding substring (leading zeros are allowed in it).For example, if $$$n=7$$$, $$$s=$$$"1003004", then $$$v(1,3)=100$$$, $$$v(2,3)=0$$$ and $$$v(2,7)=3004$$$.You are given $$$n$$$, $$$s$$$ and an integer $$$w$$$ ($$$1 \le w &lt; n$$$).You need to process $$$m$$$ queries, each of which is characterized by $$$3$$$ numbers $$$l_i, r_i, k_i$$$ ($$$1 \le l_i \le r_i \le n; 0 \le k_i \le 8$$$).The answer to the $$$i$$$th query is such a pair of substrings of length $$$w$$$ that if we denote them as $$$(L_1, L_1+w-1)$$$ and $$$(L_2, L_2+w-1)$$$, then: $$$L_1 \ne L_2$$$, that is, the substrings are different; the remainder of dividing a number $$$v(L_1, L_1+w-1) \cdot v(l_i, r_i) + v(L_2, L_2 + w - 1)$$$ by $$$9$$$ is equal to $$$k_i$$$. If there are many matching substring pairs, then find a pair where $$$L_1$$$ is as small as possible. If there are many matching pairs in this case, then minimize $$$L_2$$$.Note that the answer may not exist.
256 megabytes
import java.io.*; import java.util.Arrays; import java.util.*; import java.util.StringTokenizer; public class copy { static int log=30; static int[][] ancestor; static int[] depth; static void sieveOfEratosthenes(int n, ArrayList<Integer> arr) { boolean prime[] = new boolean[n + 1]; for (int i = 0; i <= n; i++) prime[i] = true; for (int p = 2; p * p <= n; p++) { // If prime[p] is not changed, then it is a // prime if (prime[p]) { // Update all multiples of p for (int i = p * p; i <= n; i += p) prime[i] = false; } } // Print all prime numbers for (int i = 2; i <= n; i++) { if (prime[i]) { arr.add(i); } } } public static long fac(long N, long mod) { if (N == 0) return 1; if(N==1) return 1; return ((N % mod) * (fac(N - 1, mod) % mod)) % mod; } static long power(long x, long y, long p) { // Initialize result long res = 1; // Update x if it is more than or // equal to p x = x % p; while (y > 0) { // If y is odd, multiply x // with result if (y % 2 == 1) res = (res * x) % p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return res; } // Returns n^(-1) mod p static long modInverse(long n, long p) { return power(n, p - 2, p); } // Returns nCr % p using Fermat's // little theorem. static long nCrModPFermat(int n, int r, long p,long[] fac) { if (n < r) return 0; // Base case if (r == 0) return 1; return ((fac[n] % p * (modInverse(fac[r], p) % p)) % p * (modInverse(fac[n-r], p) % p)) % p; } public static int find(int[] parent, int x) { if (parent[x] == x) return x; return find(parent, parent[x]); } public static void merge(int[] parent, int[] rank, int x, int y,int[] child) { int x1 = find(parent, x); int y1 = find(parent, y); if (rank[x1] > rank[y1]) { parent[y1] = x1; child[x1]+=child[y1]; } else if (rank[y1] > rank[x1]) { parent[x1] = y1; child[y1]+=child[x1]; } else { parent[y1] = x1; child[x1]+=child[y1]; rank[x1]++; } } public static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } static int power(int x, int y, int p) { int res = 1; x = x % p; while (y > 0) { if (y % 2 == 1) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return res; } // Returns n^(-1) mod p static int modInverse(int n, int p) { return power(n, p - 2, p); } // Returns nCr % p using Fermat's // little theorem. static int nCrModPFermat(int n, int r, int p,int[] fac) { if (n<r) return 0; // Base case if (r == 0) return 1; // Fill factorial array so that we // can find all factorial of r, n // and n-r // int[] fac = new int[n + 1]; // fac[0] = 1; // // for (int i = 1; i <= n; i++) // fac[i] = fac[i - 1] * i % p; return (fac[n] * modInverse(fac[r], p) % p * modInverse(fac[n - r], p) % p) % p; } public static long[][] ncr(int n,int r) { long[][] dp=new long[n+1][r+1]; for(int i=0;i<=n;i++) dp[i][0]=1; for(int i=1;i<=n;i++) { for(int j=1;j<=r;j++) { if(j>i) continue; dp[i][j]=dp[i-1][j-1]+dp[i-1][j]; } } return dp; } public static boolean prime(long N) { int c=0; for(int i=2;i*i<=N;i++) { if(N%i==0) ++c; } return c==0; } public static int sparse_ancestor_table(ArrayList<ArrayList<Integer>> arr,int x,int parent,int[] child) { int c=0; for(int i:arr.get(x)) { if(i!=parent) { // System.out.println(i+" hello "+x); depth[i]=depth[x]+1; ancestor[i][0]=x; // if(i==2) // System.out.println(parent+" hello"); for(int j=1;j<log;j++) ancestor[i][j]=ancestor[ancestor[i][j-1]][j-1]; c+=sparse_ancestor_table(arr,i,x,child); } } child[x]=1+c; return child[x]; } public static int lca(int x,int y) { if(depth[x]<depth[y]) { int temp=x; x=y; y=temp; } x=get_kth_ancestor(depth[x]-depth[y],x); if(x==y) return x; // System.out.println(x+" "+y); for(int i=log-1;i>=0;i--) { if(ancestor[x][i]!=ancestor[y][i]) { x=ancestor[x][i]; y=ancestor[y][i]; } } return ancestor[x][0]; } public static int get_kth_ancestor(int K,int x) { if(K==0) return x; int node=x; for(int i=0;i<log;i++) { if(K%2!=0) { node=ancestor[node][i]; } K/=2; } return node; } public static ArrayList<Integer> primeFactors(int n) { // Print the number of 2s that divide n ArrayList<Integer> factors=new ArrayList<>(); if(n%2==0) factors.add(2); while (n%2==0) { n /= 2; } // n must be odd at this point. So we can // skip one element (Note i = i +2) for (int i = 3; i <= Math.sqrt(n); i+= 2) { // While i divides n, print i and divide n if(n%i==0) factors.add(i); while (n%i == 0) { n /= i; } } // This condition is to handle the case when // n is a prime number greater than 2 if (n > 2) { factors.add(n); } return factors; } static long ans=1,mod=1000000007; public static void recur(long X,long N,int index,ArrayList<Integer> temp) { // System.out.println(X); if(index==temp.size()) { System.out.println(X); ans=((ans%mod)*(X%mod))%mod; return; } for(int i=0;i<=60;i++) { if(X*Math.pow(temp.get(index),i)<=N) recur(X*(long)Math.pow(temp.get(index),i),N,index+1,temp); else break; } } public static int upper(ArrayList<Integer> temp,int X) { int l=0,r=temp.size()-1; while(l<=r) { int mid=(l+r)/2; if(temp.get(mid)==X) return mid; // System.out.println(mid+" "+temp.get(mid)); if(temp.get(mid)<X) l=mid+1; else { if(mid-1>=0 && temp.get(mid-1)>=X) r=mid-1; else return mid; } } return -1; } public static int lower(ArrayList<Integer> temp,int X) { int l=0,r=temp.size()-1; while(l<=r) { int mid=(l+r)/2; if(temp.get(mid)==X) return mid; // System.out.println(mid+" "+temp.get(mid)); if(temp.get(mid)>X) r=mid-1; else { if(mid+1<temp.size() && temp.get(mid+1)<=X) l=mid+1; else return mid; } } return -1; } public static int[] check(String shelf,int[][] queries) { int[] arr=new int[queries.length]; ArrayList<Integer> indices=new ArrayList<>(); for(int i=0;i<shelf.length();i++) { char ch=shelf.charAt(i); if(ch=='|') indices.add(i); } for(int i=0;i<queries.length;i++) { int x=queries[i][0]-1; int y=queries[i][1]-1; int left=upper(indices,x); int right=lower(indices,y); if(left<=right && left!=-1 && right!=-1) { arr[i]=indices.get(right)-indices.get(left)+1-(right-left+1); } else arr[i]=0; } return arr; } static boolean check; public static void check(ArrayList<ArrayList<Integer>> arr,int x,int[] color,boolean[] visited) { visited[x]=true; PriorityQueue<Integer> pq=new PriorityQueue<>(); for(int i:arr.get(x)) { if(color[i]<color[x]) pq.add(color[i]); if(color[i]==color[x]) check=false; if(!visited[i]) check(arr,i,color,visited); } int start=1; while(pq.size()>0) { int temp=pq.poll(); if(temp==start) ++start; else break; } if(start!=color[x]) check=false; } static boolean cycle; public static void cycle(boolean[] stack,boolean[] visited,int x,ArrayList<ArrayList<Integer>> arr) { if(stack[x]) { cycle=true; return; } visited[x]=true; for(int i:arr.get(x)) { if(!visited[x]) { cycle(stack,visited,i,arr); } } stack[x]=false; } public static int check(char[][] ch,int x,int y) { int cnt=0; int c=0; int N=ch.length; int x1=x,y1=y; while(c<ch.length) { if(ch[x][y]=='1') ++cnt; // if(x1==0 && y1==3) // System.out.println(x+" "+y+" "+cnt); x=(x+1)%N; y=(y+1)%N; ++c; } return cnt; } public static void s(char[][] arr,int x) { char start=arr[arr.length-1][x]; for(int i=arr.length-1;i>0;i--) { arr[i][x]=arr[i-1][x]; } arr[0][x]=start; } public static void shuffle(char[][] arr,int x,int down) { int N= arr.length; down%=N; char[] store=new char[N-down]; for(int i=0;i<N-down;i++) store[i]=arr[i][x]; for(int i=0;i<arr.length;i++) { if(i<down) { // Printing rightmost // kth elements arr[i][x]=arr[N + i - down][x]; } else { // Prints array after // 'k' elements arr[i][x]=store[i-down]; } } } public static String form(int C1,char ch1,char ch2) { char ch=ch1; String s=""; for(int i=1;i<=C1;i++) { s+=ch; if(ch==ch1) ch=ch2; else ch=ch1; } return s; } public static void printArray(long[] arr) { for(int i=0;i<arr.length;i++) System.out.print(arr[i]+" "); System.out.println(); } public static boolean check(long mid,long[] arr,long K) { long[] arr1=Arrays.copyOfRange(arr,0,arr.length); long ans=0; for(int i=0;i<arr1.length-1;i++) { if(arr1[i]+arr1[i+1]>=mid) { long check=(arr1[i]+arr1[i+1])/mid; // if(mid==5) // System.out.println(check); long left=check*mid; left-=arr1[i]; if(left>=0) arr1[i+1]-=left; ans+=check; } // if(mid==5) // printArray(arr1); } // if(mid==5) // System.out.println(ans); ans+=arr1[arr1.length-1]/mid; return ans>=K; } public static long search(long sum,long[] arr,long K) { long l=1,r=sum/K; while(l<=r) { long mid=(l+r)/2; if(check(mid,arr,K)) { if(mid+1<=sum/K && check(mid+1,arr,K)) l=mid+1; else return mid; } else r=mid-1; } return -1; } public static void primeFactors(int n,HashSet<Integer> hp) { // Print the number of 2s that divide n ArrayList<Integer> factors=new ArrayList<>(); if(n%2==0) hp.add(2); while (n%2==0) { n /= 2; } // n must be odd at this point. So we can // skip one element (Note i = i +2) for (int i = 3; i <= Math.sqrt(n); i+= 2) { // While i divides n, print i and divide n if(n%i==0) hp.add(i); while (n%i == 0) { n /= i; } } // This condition is to handle the case when // n is a prime number greater than 2 if (n > 2) { hp.add(n); } } public static boolean check(String s) { HashSet<Character> hp=new HashSet<>(); char ch=s.charAt(0); for(int i=1;i<s.length();i++) { // System.out.println(hp+" "+s.charAt(i)); if(hp.contains(s.charAt(i))) { // System.out.println(i); // System.out.println(hp); // System.out.println(s.charAt(i)); return false; } if(s.charAt(i)!=ch) { hp.add(ch); ch=s.charAt(i); } } return true; } public static int check_end(String[] arr,boolean[] st,char ch) { for(int i=0;i<arr.length;i++) { if(ch==arr[i].charAt(0) && !st[i] && ch==arr[i].charAt(arr[i].length()-1)) return i; } for(int i=0;i<arr.length;i++) { if(ch==arr[i].charAt(0) && !st[i]) return i; } return -1; } public static int check_start(String[] arr,boolean[] st,char ch) { for(int i=0;i<arr.length;i++) { // if(ch=='B') // { // if(!st[i]) // System.out.println(arr[i]+" hello"); // } if(ch==arr[i].charAt(arr[i].length()-1) && !st[i] && ch==arr[i].charAt(0)) return i; } for(int i=0;i<arr.length;i++) { // if(ch=='B') // { // if(!st[i]) // System.out.println(arr[i]+" hello"); // } if(ch==arr[i].charAt(arr[i].length()-1) && !st[i]) return i; } return -1; } public static boolean palin(int N) { String s=""; while(N>0) { s+=N%10; N/=10; } int l=0,r=s.length()-1; while(l<=r) { if(s.charAt(l)!=s.charAt(r)) return false; ++l; --r; } return true; } public static boolean check(long org_s,long org_d,long org_n,long check_ele) { if(check_ele<org_s) return false; if((check_ele-org_s)%org_d!=0) return false; long num=(check_ele-org_s)/org_d; // if(check_ele==5) // System.out.println(num+" "+org_n); return num+1<=org_n; } public static long check(long c,long c_diff,long mod,long b_start,long c_start, long c_end,long b_end,long b_diff) { // System.out.println(c); long max=Math.max(c,b_diff); long min=Math.min(c,b_diff); long lcm=(max/gcd(max,min))*min; // System.out.println(lcm); // System.out.println(c); // System.out.println(c_diff); // if(b_diff>c) // { long start_point=c_diff/c-c_diff/lcm; // System.out.println(start_point); // } // else // { // start_point=c_diff/b_diff-c_diff/c; // } // System.out.println(c+" "+start_point); return (start_point%mod*start_point%mod)%mod; } public static boolean check_bounds(int x, int y, int N, int M) { return x>=0 && x<N && y>=0 && y<M; } static boolean found=false; public static void check(int x,int y,int[][] arr,boolean status[][]) { if(arr[x][y]==9) { found=true; return; } status[x][y]=true; if(check_bounds(x-1,y, arr.length,arr[0].length)&& !status[x-1][y]) check(x-1,y,arr,status); if(check_bounds(x+1,y, arr.length,arr[0].length)&& !status[x+1][y]) check(x+1,y,arr,status); if(check_bounds(x,y-1, arr.length,arr[0].length)&& !status[x][y-1]) check(x,y-1,arr,status); if(check_bounds(x,y+1, arr.length,arr[0].length)&& !status[x][y+1]) check(x,y+1,arr,status); } public static int check(String s1,String s2,int M) { int ans=0; for(int i=0;i<M;i++) { ans+=Math.abs(s1.charAt(i)-s2.charAt(i)); } return ans; } public static int check(int[][] arr,int dir1,int dir2,int x1,int y1) { int sum=0,N=arr.length,M=arr[0].length; int x=x1+dir1,y=y1+dir2; while(x<N && x>=0 && y<M && y>=0) { sum+=arr[x][y]; x=x+dir1; y+=dir2; } return sum; } public static int check(long[] pref,long X,int N) { if(X>pref[N-1]) return -1; // System.out.println(pref[0]); if(X<=pref[0]) return 1; int l=0,r=N-1; while(l<=r) { int mid=(l+r)/2; if(pref[mid]>=X) { if(mid-1>=0 && pref[mid-1]<X) return mid+1; else r=mid-1; } else l=mid+1; } return -1; } private static long mergeAndCount(long[] arr, int l, int m, int r) { // Left subarray long[] left = Arrays.copyOfRange(arr, l, m + 1); // Right subarray long[] right = Arrays.copyOfRange(arr, m + 1, r + 1); int i = 0, j = 0, k = l;long swaps = 0; while (i < left.length && j < right.length) { if (left[i] < right[j]) arr[k++] = left[i++]; else { arr[k++] = right[j++]; swaps += (m + 1) - (l + i); } } while (i < left.length) arr[k++] = left[i++]; while (j < right.length) arr[k++] = right[j++]; return swaps; } // Merge sort function private static long mergeSortAndCount(long[] arr, int l, int r) { // Keeps track of the inversion count at a // particular node of the recursion tree long count = 0; if (l < r) { int m = (l + r) / 2; // Total inversion count = left subarray count // + right subarray count + merge count // Left subarray count count += mergeSortAndCount(arr, l, m); // Right subarray count count += mergeSortAndCount(arr, m + 1, r); // Merge count count += mergeAndCount(arr, l, m, r); } return count; } public static long check(long L,long R) { long ans=0; for(int i=1;i<=Math.pow(10,8);i++) { long A=i*(long)i; if(A<L) continue; long upper=(long)Math.floor(Math.sqrt(A-L)); long lower=(long)Math.ceil(Math.sqrt(Math.max(A-R,0))); if(upper>=lower) ans+=upper-lower+1; } return ans; } public static int check(ArrayList<ArrayList<Integer>> arr,int x,int parent,int[]store) { int index=0; ArrayList<Integer> temp=arr.get(x); for(int i:temp) { if(i!=parent) { index+=check(arr,i,x,store); } } store[x]=index; return index+1; } public static void finans(int[][] store,ArrayList<ArrayList<Integer>> arr,int x,int parent) { // ++delete; // System.out.println(x); if(store[x][0]==0 && store[x][1]==0) return; if(store[x][0]!=0 && store[x][1]==0) { ++delete; ans+=store[x][0]; return; } if(store[x][0]==0 && store[x][1]!=0) { ++delete; ans+=store[x][1]; return; } ArrayList<Integer> temp=arr.get(x); if(store[x][0]!=0 && store[x][1]!=0) { ++delete; if(store[x][0]>store[x][1]) { ans+=store[x][0]; for(int i=temp.size()-1;i>=0;i--) { if(temp.get(i)!=parent) { finans(store,arr,temp.get(i),x); break; } } } else { ans+=store[x][1]; for(int i=0;i<temp.size();i++) { if(temp.get(i)!=parent) { finans(store,arr,temp.get(i),x); break; } } } } } public static int dfs(ArrayList<ArrayList<Integer>> arr,int x,int parent,int[] store) { int index1=-1,index2=-1; for(int i=0;i<arr.get(x).size();i++) { if(arr.get(x).get(i)!=parent) { if(index1==-1) { index1=i; } else index2=i; } } if(index1==-1) { return 0; } if(index2==-1) { return store[arr.get(x).get(index1)]; } // System.out.println(x); // System.out.println();; return Math.max(store[arr.get(x).get(index1)]+dfs(arr,arr.get(x).get(index2),x,store),store[arr.get(x).get(index2)]+dfs(arr,arr.get(x).get(index1),x,store)); } static int delete=0; public static boolean bounds(int x,int y,int N,int M) { return x>=0 && x<N && y>=0 && y<M; } public static int gcd_check(ArrayList<Integer> temp,char[] ch, int[] arr) { ArrayList<Integer> ini=new ArrayList<>(temp); for(int i=0;i<temp.size();i++) { for(int j=0;j<temp.size();j++) { int req=temp.get(j); temp.set(j,arr[req-1]); } boolean status=true; for(int j=0;j<temp.size();j++) { if(ch[ini.get(j)-1]!=ch[temp.get(j)-1]) status=false; } if(status) return i+1; } return temp.size(); } static long LcmOfArray(int[] arr, int idx) { // lcm(a,b) = (a*b/gcd(a,b)) if (idx == arr.length - 1){ return arr[idx]; } int a = arr[idx]; long b = LcmOfArray(arr, idx+1); return (a*b/gcd(a,b)); // } public static boolean check(ArrayList<Integer> arr,int sum) { for(int i=0;i<arr.size();i++) { for(int j=i+1;j<arr.size();j++) { for(int k=j+1;k<arr.size();k++) { if(arr.get(i)+arr.get(j)+arr.get(k)==sum) return true; } } } return false; } // Returns true if str1 is smaller than str2. static boolean isSmaller(String str1, String str2) { // Calculate lengths of both string int n1 = str1.length(), n2 = str2.length(); if (n1 < n2) return true; if (n2 < n1) return false; for (int i = 0; i < n1; i++) if (str1.charAt(i) < str2.charAt(i)) return true; else if (str1.charAt(i) > str2.charAt(i)) return false; return false; } public static int check(List<String> history) { int[][] arr=new int[history.size()][history.get(0).length()]; for(int i=0;i<arr.length;i++) { for(int j=0;j<arr[0].length;j++) { arr[i][j]=history.get(i).charAt(j)-48; } } for(int i=0;i<arr.length;i++) Arrays.sort(arr[i]); int sum=0; for(int i=0;i<arr[0].length;i++) { int max=0; for(int j=0;j<arr.length;j++) max=Math.max(max,arr[j][i]); sum+=max; } return sum; } // Function for find difference of larger numbers static String findDiff(String str1, String str2) { // Before proceeding further, make sure str1 // is not smaller if (isSmaller(str1, str2)) { String t = str1; str1 = str2; str2 = t; } // Take an empty string for storing result String str = ""; // Calculate length of both string int n1 = str1.length(), n2 = str2.length(); // Reverse both of strings str1 = new StringBuilder(str1).reverse().toString(); str2 = new StringBuilder(str2).reverse().toString(); int carry = 0; // Run loop till small string length // and subtract digit of str1 to str2 for (int i = 0; i < n2; i++) { // Do school mathematics, compute difference of // current digits int sub = ((int)(str1.charAt(i) - '0') - (int)(str2.charAt(i) - '0') - carry); // If subtraction is less then zero // we add then we add 10 into sub and // take carry as 1 for calculating next step if (sub < 0) { sub = sub + 10; carry = 1; } else carry = 0; str += (char)(sub + '0'); } // subtract remaining digits of larger number for (int i = n2; i < n1; i++) { int sub = ((int)(str1.charAt(i) - '0') - carry); // if the sub value is -ve, then make it // positive if (sub < 0) { sub = sub + 10; carry = 1; } else carry = 0; str += (char)(sub + '0'); } // reverse resultant string return new StringBuilder(str).reverse().toString(); } static int nCr(int n, int r) { return fact(n) / (fact(r) * fact(n - r)); } // Returns factorial of n static int fact(int n) { int res = 1; for (int i = 2; i <= n; i++) res = res * i; return res; } public static void fill(int[][] dp,int[] arr,int N) { for(int i=1;i<=N;i++) dp[i][0]=arr[i]; for (int j = 1; j <= dp[0].length; j++) for (int i = 1; i + (1 << j) <= N; i++) dp[i][j] = Math.max(dp[i][j-1], dp[i + (1 << (j - 1))][j - 1]); } static int start=0; // static boolean status; public static void dfs(ArrayList<ArrayList<Integer>> arr,int[] A,int[] B,int x,int time,int parent,int K,int coins) { if(time>K) return; ans=Math.max(ans,coins); for(int i:arr.get(x)) { if(i!=parent) { dfs(arr,A,B,i,time+1,x,K,coins); dfs(arr,A,B,i,time+1+B[i],x,K,coins+A[i]); } } } public static boolean dfs_diameter(ArrayList<ArrayList<Integer>> arr,int x,int parent,int node1,int node2,int[] child) { boolean status=false; for(int i:arr.get(x)) { if(i!=parent) { boolean ch=dfs_diameter(arr,i,x,node1,node2,child); status= status || ch; if(!ch && x==node1) ans+=child[i]; child[x]+=child[i]; } } child[x]+=1; return status || (x==node2); } public static boolean check_avai(int x,int y,int sx,int sy,int di) { // if(x==4 && y==4) // System.out.println((Math.abs(x-sx)+Math.abs(y-sy))<=di); return (Math.abs(x-sx)+Math.abs(y-sy))<=di; } public static int lower_index(ArrayList<Integer> arr, int x) { // System.out.println(x+" MC"); int l=0,r=arr.size()-1; while(l<=r) { int mid=(l+r)/2; if(arr.get(mid)<x) l=mid+1; else { if(mid-1>=0 && arr.get(mid-1)>= x) r=mid-1; else return mid; } } return -1; } public static int higher_index(ArrayList<Integer> arr, int x) { int l=0,r=arr.size()-1; while(l<=r) { int mid=(l+r)/2; if(arr.get(mid)>x) r=mid-1; else { if(mid+1<arr.size() && arr.get(mid+1)<=x ) l=mid+1; else return mid; } } return -1; } static int time; static void bridgeUtil(int u, boolean visited[], int disc[], int low[], int parent[],ArrayList<ArrayList<Integer>> adj,HashMap<Integer,Integer> hp) { // Mark the current node as visited visited[u] = true; // Initialize discovery time and low value disc[u] = low[u] = ++time; // Go through all vertices adjacent to this Iterator<Integer> i = adj.get(u).iterator(); while (i.hasNext()) { int v = i.next(); // v is current adjacent of u // If v is not visited yet, then make it a child // of u in DFS tree and recur for it. // If v is not visited yet, then recur for it if (!visited[v]) { parent[v] = u; bridgeUtil(v, visited, disc, low, parent,adj,hp); // Check if the subtree rooted with v has a // connection to one of the ancestors of u low[u] = Math.min(low[u], low[v]); // If the lowest vertex reachable from subtree // under v is below u in DFS tree, then u-v is // a bridge if (low[v] < disc[u]) { hp.put(u,v); hp.put(v,u); } } // Update low value of u for parent function calls. else if (v != parent[u]) low[u] = Math.min(low[u], disc[v]); } } static int r; static int b; public static void traverse(ArrayList<ArrayList<Integer>> arr,int x,int parent,int[][] dp,int[] level,int K) { if(parent!=-1) level[x]=level[parent]+1; dp[x][0] += 1; for (int i : arr.get(x)) { if(i!=parent) { traverse(arr,i,x,dp,level,K); for(int j=1;j<=K;j++) dp[x][j]+=dp[i][j-1]; } } } static long fin_ans; public static void calc_pairs(ArrayList<ArrayList<Integer>> arr,int x,int parent,int[][] dp,int[] level,int K,int[][] total) { if(parent!=-1) { // fin_ans+=dp[parent][K-1]-dp[x][K-2]; total[x][1]+=1; for(int i=2;i<=K;i++) total[x][i]+=total[parent][i-1]-dp[x][i-2]; // dp[x][K]+=dp[parent][K-1]-dp[x][K-2]; } fin_ans+=total[x][K]; // System.out.println(fin_ans+" "+x); for(int i:arr.get(x)) { if(i!=parent) { calc_pairs(arr,i,x,dp,level,K,total); } } } static int[] Sub_String_sol(int n,int q,String s,int[][] queries) { ArrayList<ArrayList<Integer>> arr=new ArrayList<>(); for(int i=0;i<26;i++) arr.add(new ArrayList<>()); for(int i=0;i<n;i++) { arr.get(s.charAt(i)-97).add(i); } int[] ans=new int[q]; for(int i=0;i<q;i++) { int l=queries[i][0]-1; int r=queries[i][1]-1; int cnt=0; for(int j=0;j<26;j++) { int index1=lower_index(arr.get(j),l); int index2=higher_index(arr.get(j),r); if(index1!=-1 && index2!=-1) { int ele=index2-index1+1; cnt+=((ele)*(ele-1))/2+ele; } } ans[i]=cnt; } return ans; } static int KMPSearch(int[] pat, int[] txt) { int M = pat.length; int N = txt.length; // create lps[] that will hold the longest // prefix suffix values for pattern int lps[] = new int[M]; int j = 0; // index for pat[] // Preprocess the pattern (calculate lps[] // array) computeLPSArray(pat, M, lps); int i = 0; // index for txt[] while ((N - i) >= (M - j)) { if (pat[j] == txt[i]) { j++; i++; } if (j == M) { return i-j; } // mismatch after j matches else if (i < N && pat[j] != txt[i]) { // Do not match lps[0..lps[j-1]] characters, // they will match anyway if (j != 0) j = lps[j - 1]; else i = i + 1; } } return -1; } static void computeLPSArray(int[] pat, int M, int lps[]) { // length of the previous longest prefix suffix int len = 0; int i = 1; lps[0] = 0; // lps[0] is always 0 // the loop calculates lps[i] for i = 1 to M-1 while (i < M) { if (pat[i] == pat[len]) { len++; lps[i] = len; i++; } else // (pat[i] != pat[len]) { // This is tricky. Consider the example. // AAACAAAA and i = 7. The idea is similar // to search step. if (len != 0) { len = lps[len - 1]; // Also, note that we do not increment // i here } else // if (len == 0) { lps[i] = len; i++; } } } } public static long fill(ArrayList<Integer> trees,ArrayList<Integer> wells,long[] before_x) { int l=0,r=0; long mod=(long)1e9+7; long[] pref_dist=new long[before_x.length]; int[] cnt=new int[before_x.length]; while(l<trees.size() && r<wells.size()) { if(trees.get(l)<=wells.get(r)) { before_x[r]=(before_x[r]%mod+power(wells.get(r)-trees.get(l),2,mod)%mod)%mod; pref_dist[r]=(pref_dist[r]%mod+(wells.get(r)-trees.get(l))%mod)%mod; cnt[r]+=1; ++l; } else ++r; } for(int i=1;i<before_x.length;i++) { before_x[i]=(before_x[i]%mod+((before_x[i-1]%mod+(cnt[i-1]%mod*power(wells.get(i)-wells.get(i-1),2,mod)%mod)%mod)%mod+(2%mod*((wells.get(i)-wells.get(i-1))%mod*(pref_dist[i-1])%mod)%mod)%mod)%mod%mod); pref_dist[i]=(pref_dist[i]%mod+(pref_dist[i-1]%mod+(cnt[i-1]%mod*(long)(wells.get(i)-wells.get(i-1))%mod)%mod)%mod)%mod; cnt[i]+=cnt[i-1]; } // for(int i=0;i<before_x.length;i++) // System.out.print(before_x[i]+" "); // System.out.println(); long ans=0; for(int i=0;i<before_x.length;i++) ans=(ans%mod+ before_x[i]%mod)%mod; return ans; } public static long fill_after(ArrayList<Integer> trees,ArrayList<Integer> wells,long[] before_x) { int l=trees.size()-1,r=wells.size()-1; long mod=(long)1e9+7; long[] pref_dist=new long[before_x.length]; int[] cnt=new int[before_x.length]; while(l>=0 && r>=0) { if(trees.get(l)>=wells.get(r)) { before_x[r]=(before_x[r]%mod+power(wells.get(r)-trees.get(l),2,mod)%mod)%mod; pref_dist[r]=(pref_dist[r]%mod+(trees.get(l)-wells.get(r))%mod)%mod; cnt[r]+=1; --l; } else --r; } for(int i=before_x.length-2;i>=0;i--) { before_x[i]=(before_x[i]%mod+((before_x[i+1]%mod+(cnt[i+1]%mod*power(wells.get(i)-wells.get(i+1),2,mod)%mod)%mod)%mod+(2%mod*((wells.get(i+1)-wells.get(i))%mod*(pref_dist[i+1])%mod)%mod)%mod)%mod%mod); pref_dist[i]=(pref_dist[i]%mod+(pref_dist[i+1]%mod+(cnt[i+1]%mod*(long)(wells.get(i+1)-wells.get(i))%mod)%mod)%mod)%mod; cnt[i]+=cnt[i+1]; } // for(int i=0;i<before_x.length;i++) // System.out.print(before_x[i]+" "); // System.out.println(); long ans=0; for(int i=0;i<before_x.length;i++) ans=(ans%mod+ before_x[i]%mod)%mod; return ans; } public static ArrayList<ArrayList<Integer>> graph_form(int N) { ArrayList<ArrayList<Integer>> arr=new ArrayList<>(); for(int i=0;i<N;i++) arr.add(new ArrayList<>()); return arr; } public static boolean check(int[] A,int mid) { for(int i=0;i<A.length;i++) { if(A[i]!=A[i%mid]) return false; } return true; } public static boolean check(int[] A) { ArrayList<Integer> arr=new ArrayList<>(); for(int i=2;i*i<=A.length;i++) { if(A.length%i==0) { arr.add(i); arr.add(A.length/i); } } boolean status=false; for(int i:arr) { status =status || check(A,i); } return status; } public static void main(String[] args) throws IOException{ Reader.init(System.in); // BufferedWriter output = new BufferedWriter(new FileWriter("C:/Users/asus/Downloads/arre_hoja.txt")); BufferedWriter output = new BufferedWriter(new OutputStreamWriter(System.out)); // HashSet<Integer> hp=new HashSet<>(); int T=Reader.nextInt(); for(int m=1;m<=T;m++) { String s=Reader.next(); int w=Reader.nextInt(); int q=Reader.nextInt(); int N=s.length(); int[] prev=new int[N+1]; for(int i=1;i<=N;i++) prev[i]=s.charAt(i-1)-48; for(int i=1;i<=N;i++) prev[i]+=prev[i-1]; HashMap<Integer,ArrayList<Integer>> hp=new HashMap<>(); for(int i=0;i<9;i++) hp.put(i,new ArrayList<>()); for(int i=1;i+w-1<=N;i++) { int forward=i+w-1; int req=(prev[forward]-prev[i-1])%9; hp.get(req).add(i); } for(int i=1;i<=q;i++) { int l=Reader.nextInt(); int r=Reader.nextInt(); int rem=Reader.nextInt(); int sum=prev[r]-prev[l-1]; int l1=Integer.MAX_VALUE,l2=Integer.MAX_VALUE; for(int j=0;j<=8;j++) { for(int k=0;k<=8;k++) { // System.out.println((j*(sum%9))%9+k); if(((j*(sum%9))%9+k%9)%9==rem && hp.get(j).size()>0 && hp.get(k).size()>0) { if(j==k ) { if(hp.get(j).size()>=2) { if (hp.get(j).get(0) < l1) { l1 = hp.get(j).get(0); l2 = hp.get(k).get(1); } else if (hp.get(j).get(0) == l1) { l2 = Math.min(l2, hp.get(k).get(1)); } } continue; } if(hp.get(j).get(0)<l1) { l1=hp.get(j).get(0); l2=hp.get(k).get(0); } else if(hp.get(j).get(0)==l1) { l2=Math.min(l2,hp.get(k).get(0)); } } } } if(l1==Integer.MAX_VALUE && l2==Integer.MAX_VALUE) output.write(-1+" "+-1+"\n"); else output.write(l1+" "+l2+"\n"); } } // output.close(); output.flush(); } } class Reader { static BufferedReader reader; static StringTokenizer tokenizer; static void init(InputStream input) { reader = new BufferedReader( new InputStreamReader(input)); tokenizer = new StringTokenizer(""); } static String next() throws IOException { while (!tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer( reader.readLine()); } return tokenizer.nextToken(); } 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()); } } class TreeNode { int data; TreeNode left; TreeNode right; TreeNode(int data) { left=null; right=null; this.data=data; } } class div { int x; int y; div(int x,int y) { this.x=x; this.y=y; // this.coins=coins; } } class kar implements Comparator<div> { public int compare(div o1,div o2) { if (o1.x < o2.x) return -1; else if (o1.x > o2.x) return 1; else { if (o1.y < o2.y) return -1; else if (o1.y > o2.y) return 1; else return 0; } } } class trie_node { trie_node[] arr; trie_node() { arr=new trie_node[26]; } public static void insert(trie_node root,String s) { trie_node tmp=root; for(int i=0;i<s.length();i++) { if(tmp.arr[s.charAt(i)-97]!=null) { tmp=tmp.arr[s.charAt(i)-97]; } else { tmp.arr[s.charAt(i)-97]=new trie_node(); tmp=tmp.arr[s.charAt(i)-97]; } } } public static boolean search(trie_node root,String s) { trie_node tmp=root; for(int i=0;i<s.length();i++) { if(tmp.arr[s.charAt(i)-97]!=null) { tmp=tmp.arr[s.charAt(i)-97]; } else { return false; } } return true; } }
Java
["5\n\n1003004\n\n4 1\n\n1 2 1\n\n179572007\n\n4 2\n\n2 7 3\n\n2 7 4\n\n111\n\n2 1\n\n2 2 6\n\n0000\n\n1 2\n\n1 4 0\n\n1 4 1\n\n484\n\n1 5\n\n2 2 0\n\n2 3 7\n\n1 2 5\n\n3 3 8\n\n2 2 6"]
3 seconds
["2 4\n1 5\n1 2\n-1 -1\n1 2\n-1 -1\n1 3\n1 3\n-1 -1\n-1 -1\n-1 -1"]
NoteConsider the first test case of example inputs. In this test case $$$n=7$$$, $$$s=$$$"1003004", $$$w=4$$$ and one query $$$l_1=1$$$, $$$r_1=2$$$, $$$k_1=1$$$. Note that $$$v(1,2)=10$$$. We need to find a pair of substrings of length $$$4$$$ such that $$$v(L_1, L_1+3)\cdot10+v(L_2,L_2+3)$$$ has a remainder of $$$k_1=1$$$ when divided by $$$9$$$. The values $$$L_1=2, L_2=4$$$ actually satisfy all the requirements: $$$v(L_1, L_1+w-1)=v(2,5)=30$$$, $$$v(L_2, L_2+w-1)=v(4,7)=3004$$$. Indeed, $$$30\cdot10+3004=3304$$$, which has a remainder of $$$1$$$ when divided by $$$9$$$. It can be shown that $$$L_1=2$$$ is the minimum possible value, and $$$L_2=4$$$ is the minimum possible with $$$L_1=2$$$.
Java 11
standard input
[ "hashing", "math" ]
b67870dcffa7bad682ef980dacd1f3db
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — number of input test cases. The first line of each test case contains a string $$$s$$$, which contains only the characters 0-9 and has a length $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$). The second line contains two integers $$$w, m$$$ ($$$1 \le w &lt; n, 1 \le m \le 2 \cdot 10^5$$$), where $$$n$$$ — is the length of the given string $$$s$$$. The number $$$w$$$ denotes the lengths of the substrings being searched for, and $$$m$$$ is the number of queries to be processed. The following $$$m$$$ lines contain integers $$$l_i, r_i, k_i$$$ ($$$1 \le l_i \le r_i \le n$$$, $$$0 \le k_i \le 8$$$) — $$$i$$$th query parameters. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$. It is also guaranteed that the sum of $$$m$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,900
For each request, print in a separate line: left borders of the required substrings: $$$L_1$$$ and $$$L_2$$$; -1 -1 otherwise, if there is no solution. If there are several solutions, minimize $$$L_1$$$ first, and minimize $$$L_2$$$ second.
standard output
PASSED
012ec50b51656109c8d7cbbb4e6f8cfb
train_110.jsonl
1662993300
Given the string $$$s$$$ of decimal digits (0-9) of length $$$n$$$.A substring is a sequence of consecutive characters of a string. The substring of this string is defined by a pair of indexes — with its left and right ends. So, each pair of indexes ($$$l, r$$$), where $$$1 \le l \le r \le n$$$, corresponds to a substring of the string $$$s$$$. We will define as $$$v(l,r)$$$ the numeric value of the corresponding substring (leading zeros are allowed in it).For example, if $$$n=7$$$, $$$s=$$$"1003004", then $$$v(1,3)=100$$$, $$$v(2,3)=0$$$ and $$$v(2,7)=3004$$$.You are given $$$n$$$, $$$s$$$ and an integer $$$w$$$ ($$$1 \le w &lt; n$$$).You need to process $$$m$$$ queries, each of which is characterized by $$$3$$$ numbers $$$l_i, r_i, k_i$$$ ($$$1 \le l_i \le r_i \le n; 0 \le k_i \le 8$$$).The answer to the $$$i$$$th query is such a pair of substrings of length $$$w$$$ that if we denote them as $$$(L_1, L_1+w-1)$$$ and $$$(L_2, L_2+w-1)$$$, then: $$$L_1 \ne L_2$$$, that is, the substrings are different; the remainder of dividing a number $$$v(L_1, L_1+w-1) \cdot v(l_i, r_i) + v(L_2, L_2 + w - 1)$$$ by $$$9$$$ is equal to $$$k_i$$$. If there are many matching substring pairs, then find a pair where $$$L_1$$$ is as small as possible. If there are many matching pairs in this case, then minimize $$$L_2$$$.Note that the answer may not exist.
256 megabytes
// package c1729; // // Codeforces Round #820 (Div. 3) 2022-09-12 07:35 // F. Kirei and the Linear Function // https://codeforces.com/contest/1729/problem/F // time limit per test 3 seconds; memory limit per test 256 megabytes // public class Pseudo for 'Source should satisfy regex [^{}]*public\s+(final)?\s*class\s+(\w+).*' // // Given the string s of decimal digits (0-9) of length n. // // A substring is a sequence of consecutive characters of a string. The substring of this string is // defined by a pair of indexes -- with its left and right ends. So, each pair of indexes (l, r), // where 1 <= l <= r <= n, corresponds to a substring of the string s. We will define as v(l,r) the // numeric value of the corresponding substring (leading zeros are allowed in it). // // For example, if n=7, s="1003004", then v(1,3)=100, v(2,3)=0 and v(2,7)=3004. // // You are given n, s and an integer w (1 <= w < n). // // You need to process m queries, each of which is characterized by 3 numbers l_i, r_i, k_i (1 <= // l_i <= r_i <= n; 0 <= k_i <= 8). // // The answer to the ith query is such a pair of substrings of length w that if we denote them as // (L_1, L_1+w-1) and (L_2, L_2+w-1), then: // * L_1 != L_2, that is, the substrings are different; // * the remainder of dividing a number v(L_1, L_1+w-1) * v(l_i, r_i) + v(L_2, L_2 + w - 1) by 9 is // equal to k_i. // // If there are many matching substring pairs, then find a pair where L_1 is as small as possible. // If there are many matching pairs in this case, then minimize L_2. // // Note that the answer may not exist. // // Input // // The first line contains a single integer t (1 <= t <= 10^4)-- number of input test cases. // // The first line of each test case contains a string s, which contains only the characters 0-9 and // has a length n (2 <= n <= 2 * 10^5). // // The second line contains two integers w, m (1 <= w < n, 1 <= m <= 2 * 10^5), where n -- is the // length of the given string s. The number w denotes the lengths of the substrings being searched // for, and m is the number of queries to be processed. // // The following m lines contain integers l_i, r_i, k_i (1 <= l_i <= r_i <= n, 0 <= k_i <= 8)-- ith // query parameters. // // It is guaranteed that the sum of n over all test cases does not exceed 2 * 10^5. It is also // guaranteed that the sum of m over all test cases does not exceed 2 * 10^5. // // Output // // For each request, print in a separate line: // * left borders of the required substrings: L_1 and L_2; // * -1 -1 otherwise, if there is no solution. // // If there are several solutions, minimize L_1 first, and minimize L_2 second. // // Example /* input: 5 1003004 4 1 1 2 1 179572007 4 2 2 7 3 2 7 4 111 2 1 2 2 6 0000 1 2 1 4 0 1 4 1 484 1 5 2 2 0 2 3 7 1 2 5 3 3 8 2 2 6 output: 2 4 1 5 1 2 -1 -1 1 2 -1 -1 1 3 1 3 -1 -1 -1 -1 -1 -1 */ // Note // // Consider the first test case of example inputs. In this test case n=7, s="1003004", w=4 and one // query l_1=1, r_1=2, k_1=1. Note that v(1,2)=10. We need to find a pair of substrings of length 4 // such that v(L_1, L_1+3)*10+v(L_2,L_2+3) has a remainder of k_1=1 when divided by 9. The values // L_1=2, L_2=4 actually satisfy all the requirements: v(L_1, L_1+w-1)=v(2,5)=30, v(L_2, // L_2+w-1)=v(4,7)=3004. Indeed, 30*10+3004=3304, which has a remainder of 1 when divided by 9. It // can be shown that L_1=2 is the minimum possible value, and L_2=4 is the minimum possible with // L_1=2. // import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.InputStreamReader; import java.lang.invoke.MethodHandles; import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.StringTokenizer; public class C1729F { static final int MOD = 998244353; static final Random RAND = new Random(); static int[][] solve(String s, int w, int[][] queries) { int n = s.length(); int q = queries.length; int[][] ans = new int[q][2]; int[] presum = new int[n]; for (int i = 0; i < n; i++) { int v = s.charAt(i) - '0'; presum[i] = (v + (i == 0 ? 0 : presum[i-1])) % 9; } List<Integer>[] idxes = new ArrayList[9]; for (int i = 0; i < 9; i++) { idxes[i] = new ArrayList<>(); } for (int i = 0; i <= n - w; i++) { int v = (9 + presum[i+w-1] - (i == 0 ? 0 : presum[i-1])) % 9; idxes[v].add(i); } final int imax = 1000000; for (int i = 0; i < q; i++) { int l = queries[i][0]; int r = queries[i][1]; int k = queries[i][2]; int x = (9 + presum[r] - (l == 0 ? 0 : presum[l-1])) % 9; int l1 = imax; int l2 = imax; for (int v1 = 0; v1 < 9; v1++) { for (int v2 = 0; v2 < 9; v2++) { if ((v1 * x + v2) % 9 != k || idxes[v1].isEmpty() || idxes[v2].isEmpty()) { continue; } if (v1 == v2) { if (idxes[v1].size() == 1) { continue; } if (l1 > idxes[v1].get(0) || (l1 == idxes[v1].get(0) && l2 > idxes[v1].get(1))) { l1 = idxes[v1].get(0); l2 = idxes[v1].get(1); } } else { if (l1 > idxes[v1].get(0) || (l1 == idxes[v1].get(0) && l2 > idxes[v2].get(0))) { l1 = idxes[v1].get(0); l2 = idxes[v2].get(0); } } } } ans[i][0] = l1 >= imax ? -1 : l1 + 1; ans[i][1] = l2 >= imax ? -1 : l2 + 1; } return ans; } static boolean test = false; static void doTest() { if (!test) { return; } long t0 = System.currentTimeMillis(); System.out.format("%d msec\n", System.currentTimeMillis() - t0); System.exit(0); } public static void main(String[] args) { doTest(); MyScanner in = new MyScanner(); int T = in.nextInt(); for (int t = 1; t <= T; t++) { String s = in.next(); int w = in.nextInt(); int m = in.nextInt(); int[][] queries = new int[m][3]; for (int i = 0; i < m; i++) { queries[i][0] = in.nextInt() - 1; queries[i][1] = in.nextInt() - 1; queries[i][2] = in.nextInt(); } int[][] ans = solve(s, w, queries); output(ans); } } static void output(int[][] a) { StringBuilder sb = new StringBuilder(); for (int[] v : a) { sb.append(v[0]); sb.append(' '); sb.append(v[1]); sb.append('\n'); if (sb.length() > 4000) { System.out.print(sb.toString()); sb.setLength(0); } } System.out.print(sb.toString()); } static void myAssert(boolean cond) { if (!cond) { throw new RuntimeException("Unexpected"); } } static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { try { final String USERDIR = System.getProperty("user.dir"); String cname = MethodHandles.lookup().lookupClass().getCanonicalName().replace(".MyScanner", ""); cname = cname.lastIndexOf('.') > 0 ? cname.substring(cname.lastIndexOf('.') + 1) : cname; final File fin = new File(USERDIR + "/io/c" + cname.substring(1,5) + "/" + cname + ".in"); br = new BufferedReader(new InputStreamReader(fin.exists() ? new FileInputStream(fin) : System.in)); } catch (Exception e) { br = new BufferedReader(new InputStreamReader(System.in)); } } public String next() { try { while (st == null || !st.hasMoreElements()) { st = new StringTokenizer(br.readLine()); } return st.nextToken(); } catch (Exception e) { throw new RuntimeException(e); } } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } }
Java
["5\n\n1003004\n\n4 1\n\n1 2 1\n\n179572007\n\n4 2\n\n2 7 3\n\n2 7 4\n\n111\n\n2 1\n\n2 2 6\n\n0000\n\n1 2\n\n1 4 0\n\n1 4 1\n\n484\n\n1 5\n\n2 2 0\n\n2 3 7\n\n1 2 5\n\n3 3 8\n\n2 2 6"]
3 seconds
["2 4\n1 5\n1 2\n-1 -1\n1 2\n-1 -1\n1 3\n1 3\n-1 -1\n-1 -1\n-1 -1"]
NoteConsider the first test case of example inputs. In this test case $$$n=7$$$, $$$s=$$$"1003004", $$$w=4$$$ and one query $$$l_1=1$$$, $$$r_1=2$$$, $$$k_1=1$$$. Note that $$$v(1,2)=10$$$. We need to find a pair of substrings of length $$$4$$$ such that $$$v(L_1, L_1+3)\cdot10+v(L_2,L_2+3)$$$ has a remainder of $$$k_1=1$$$ when divided by $$$9$$$. The values $$$L_1=2, L_2=4$$$ actually satisfy all the requirements: $$$v(L_1, L_1+w-1)=v(2,5)=30$$$, $$$v(L_2, L_2+w-1)=v(4,7)=3004$$$. Indeed, $$$30\cdot10+3004=3304$$$, which has a remainder of $$$1$$$ when divided by $$$9$$$. It can be shown that $$$L_1=2$$$ is the minimum possible value, and $$$L_2=4$$$ is the minimum possible with $$$L_1=2$$$.
Java 11
standard input
[ "hashing", "math" ]
b67870dcffa7bad682ef980dacd1f3db
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — number of input test cases. The first line of each test case contains a string $$$s$$$, which contains only the characters 0-9 and has a length $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$). The second line contains two integers $$$w, m$$$ ($$$1 \le w &lt; n, 1 \le m \le 2 \cdot 10^5$$$), where $$$n$$$ — is the length of the given string $$$s$$$. The number $$$w$$$ denotes the lengths of the substrings being searched for, and $$$m$$$ is the number of queries to be processed. The following $$$m$$$ lines contain integers $$$l_i, r_i, k_i$$$ ($$$1 \le l_i \le r_i \le n$$$, $$$0 \le k_i \le 8$$$) — $$$i$$$th query parameters. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$. It is also guaranteed that the sum of $$$m$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,900
For each request, print in a separate line: left borders of the required substrings: $$$L_1$$$ and $$$L_2$$$; -1 -1 otherwise, if there is no solution. If there are several solutions, minimize $$$L_1$$$ first, and minimize $$$L_2$$$ second.
standard output
PASSED
104830cd6742599212619cacba1edce0
train_110.jsonl
1662993300
Given the string $$$s$$$ of decimal digits (0-9) of length $$$n$$$.A substring is a sequence of consecutive characters of a string. The substring of this string is defined by a pair of indexes — with its left and right ends. So, each pair of indexes ($$$l, r$$$), where $$$1 \le l \le r \le n$$$, corresponds to a substring of the string $$$s$$$. We will define as $$$v(l,r)$$$ the numeric value of the corresponding substring (leading zeros are allowed in it).For example, if $$$n=7$$$, $$$s=$$$"1003004", then $$$v(1,3)=100$$$, $$$v(2,3)=0$$$ and $$$v(2,7)=3004$$$.You are given $$$n$$$, $$$s$$$ and an integer $$$w$$$ ($$$1 \le w &lt; n$$$).You need to process $$$m$$$ queries, each of which is characterized by $$$3$$$ numbers $$$l_i, r_i, k_i$$$ ($$$1 \le l_i \le r_i \le n; 0 \le k_i \le 8$$$).The answer to the $$$i$$$th query is such a pair of substrings of length $$$w$$$ that if we denote them as $$$(L_1, L_1+w-1)$$$ and $$$(L_2, L_2+w-1)$$$, then: $$$L_1 \ne L_2$$$, that is, the substrings are different; the remainder of dividing a number $$$v(L_1, L_1+w-1) \cdot v(l_i, r_i) + v(L_2, L_2 + w - 1)$$$ by $$$9$$$ is equal to $$$k_i$$$. If there are many matching substring pairs, then find a pair where $$$L_1$$$ is as small as possible. If there are many matching pairs in this case, then minimize $$$L_2$$$.Note that the answer may not exist.
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; public final class Main { FastReader s; // PrintWriter out ; public static void main(String[] args) throws java.lang.Exception { new Main().run(); } void run() { // out = new PrintWriter(new OutputStreamWriter(System.out)); s = new FastReader(); solve(); } StringBuffer sb; void solve() { sb = new StringBuffer(); for (int T = s.nextInt(); T > 0; T--) { start(); } System.out.print(sb); } void start() { char [] sa = s.nextLine().toCharArray(); int n = sa.length; int [] x = new int[n+1]; int sum = 0; for(int i = 0; i<n; i++) { sum += (sa[i]-'0'); x[i+1] = sum; } int m = s.nextInt(); int total = s.nextInt(); HashMap<Integer,ArrayList<Integer>> map = new HashMap<>(); for(int i = 0; i<9; i++) map.put(i,new ArrayList<>()); for(int i = m; i<=n; i++) map.get((x[i] - x[i-m])%9).add(i-m+1); while(total-- > 0) { int l = s.nextInt(); int r = s.nextInt(); int k = s.nextInt(); int z = x[r] - x[l-1]; z = z%9; int l1 = (int)1e9, r1 = (int)1e9; for(int i=0;i<9;i++) { if(map.get(i).size() == 0) continue; int y = (i*z)%9; if(map.get(i).size() > 1) { if((y+i)%9 == k) { if(l1 > map.get(i).get(0)) { l1 = map.get(i).get(0); r1 = map.get(i).get(1); } else if(l1 == map.get(i).get(0)) { r1 = Math.min(r1, map.get(i).get(1)); } } } for(int j=0; j<9; j++) { if(i == j) continue; if(map.get(j).size() == 0) continue; if((y+j)%9 == k) { if(l1 > map.get(i).get(0)) { l1 = map.get(i).get(0); r1 = map.get(j).get(0); } else if(l1 == map.get(i).get(0)) { r1 = Math.min(r1, map.get(j).get(0)); } } } } if(l1 == 1e9) { sb.append("-1 -1\n"); } else { sb.append(l1+" "+r1+"\n"); } } } void swap(int arr[], int i, int j) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } class Pair { int x; int y; // String hash; public Pair(int x, int y) { this.x = x; this.y = y; // this.hash = x+" "+y; } @Override public String toString() { return ("{ x = " + this.x + " , " + "y = " + this.y + " }"); } @Override public boolean equals(Object ob) { if (this == ob) return true; if (ob == null || this.getClass() != ob.getClass()) return false; Pair p = (Pair) ob; return (p.x == this.x) && (p.y == this.y); } // @Override // public int hashCode() // { // return hash.hashCode(); // } } class LongPair { long x; long y; // String hash; public LongPair(long x, long y) { this.x = x; this.y = y; // this.hash = x+" "+y; } @Override public String toString() { return ("{ x = " + this.x + " , " + "y = " + this.y + " }"); } @Override public boolean equals(Object ob) { if (this == ob) return true; if (ob == null || this.getClass() != ob.getClass()) return false; LongPair p = (LongPair) ob; return (p.x == this.x) && (p.y == this.y); } // @Override // public int hashCode() // { // return hash.hashCode(); // } } class SegmentTree { int[] tree; int n; public SegmentTree(int[] nums) { if (nums.length > 0) { n = nums.length; tree = new int[n * 2]; buildTree(nums); } } private void buildTree(int[] nums) { for (int i = n, j = 0; i < 2 * n; i++, j++) tree[i] = nums[j]; for (int i = n - 1; i > 0; --i) tree[i] = tree[i * 2] + tree[i * 2 + 1]; } void update(int pos, int val) { pos += n; tree[pos] = val; while (pos > 0) { int left = pos; int right = pos; if (pos % 2 == 0) { right = pos + 1; } else { left = pos - 1; } // parent is updated after child is updated tree[pos / 2] = tree[left] + tree[right]; pos /= 2; } } public int sumRange(int l, int r) { // get leaf with value 'l' l += n; // get leaf with value 'r' r += n; int sum = 0; while (l <= r) { if ((l % 2) == 1) { sum += tree[l]; l++; } if ((r % 2) == 0) { sum += tree[r]; r--; } l /= 2; r /= 2; } return sum; } } int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } long power(long x, long y, long p) { long res = 1; x = x % p; while (y > 0) { if ((y & 1) > 0) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return res; } int find(int dsu[], int i) { if (dsu[i] == i) return i; dsu[i] = find(dsu, dsu[i]); return dsu[i]; } void union(int dsu[], int i, int j) { int a = find(dsu, i); int b = find(dsu, j); dsu[a] = b; } 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 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 String sort(String s) { Character ch[] = new Character[s.length()]; for (int i = 0; i < s.length(); i++) { ch[i] = s.charAt(i); } Arrays.sort(ch); StringBuffer st = new StringBuffer(""); for (int i = 0; i < s.length(); i++) { st.append(ch[i]); } return st.toString(); } // long array input public long[] longArr(int len) { // long arr input long[] arr = new long[len]; String[] strs = s.nextLine().trim().split("\\s+"); for (int i = 0; i < len; i++) { arr[i] = Long.parseLong(strs[i]); } return arr; } // int arr input public int[] intArr(int len) { // long arr input int[] arr = new int[len]; String[] strs = s.nextLine().trim().split("\\s+"); for (int i = 0; i < len; i++) { arr[i] = Integer.parseInt(strs[i]); } return arr; } public void printArray(int[] A) { System.out.println(Arrays.toString(A)); } public void printArray(long[] A) { System.out.println(Arrays.toString(A)); } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["5\n\n1003004\n\n4 1\n\n1 2 1\n\n179572007\n\n4 2\n\n2 7 3\n\n2 7 4\n\n111\n\n2 1\n\n2 2 6\n\n0000\n\n1 2\n\n1 4 0\n\n1 4 1\n\n484\n\n1 5\n\n2 2 0\n\n2 3 7\n\n1 2 5\n\n3 3 8\n\n2 2 6"]
3 seconds
["2 4\n1 5\n1 2\n-1 -1\n1 2\n-1 -1\n1 3\n1 3\n-1 -1\n-1 -1\n-1 -1"]
NoteConsider the first test case of example inputs. In this test case $$$n=7$$$, $$$s=$$$"1003004", $$$w=4$$$ and one query $$$l_1=1$$$, $$$r_1=2$$$, $$$k_1=1$$$. Note that $$$v(1,2)=10$$$. We need to find a pair of substrings of length $$$4$$$ such that $$$v(L_1, L_1+3)\cdot10+v(L_2,L_2+3)$$$ has a remainder of $$$k_1=1$$$ when divided by $$$9$$$. The values $$$L_1=2, L_2=4$$$ actually satisfy all the requirements: $$$v(L_1, L_1+w-1)=v(2,5)=30$$$, $$$v(L_2, L_2+w-1)=v(4,7)=3004$$$. Indeed, $$$30\cdot10+3004=3304$$$, which has a remainder of $$$1$$$ when divided by $$$9$$$. It can be shown that $$$L_1=2$$$ is the minimum possible value, and $$$L_2=4$$$ is the minimum possible with $$$L_1=2$$$.
Java 11
standard input
[ "hashing", "math" ]
b67870dcffa7bad682ef980dacd1f3db
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — number of input test cases. The first line of each test case contains a string $$$s$$$, which contains only the characters 0-9 and has a length $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$). The second line contains two integers $$$w, m$$$ ($$$1 \le w &lt; n, 1 \le m \le 2 \cdot 10^5$$$), where $$$n$$$ — is the length of the given string $$$s$$$. The number $$$w$$$ denotes the lengths of the substrings being searched for, and $$$m$$$ is the number of queries to be processed. The following $$$m$$$ lines contain integers $$$l_i, r_i, k_i$$$ ($$$1 \le l_i \le r_i \le n$$$, $$$0 \le k_i \le 8$$$) — $$$i$$$th query parameters. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$. It is also guaranteed that the sum of $$$m$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,900
For each request, print in a separate line: left borders of the required substrings: $$$L_1$$$ and $$$L_2$$$; -1 -1 otherwise, if there is no solution. If there are several solutions, minimize $$$L_1$$$ first, and minimize $$$L_2$$$ second.
standard output
PASSED
41317f8b5380c61c157fce4bf4b65884
train_110.jsonl
1662993300
Given the string $$$s$$$ of decimal digits (0-9) of length $$$n$$$.A substring is a sequence of consecutive characters of a string. The substring of this string is defined by a pair of indexes — with its left and right ends. So, each pair of indexes ($$$l, r$$$), where $$$1 \le l \le r \le n$$$, corresponds to a substring of the string $$$s$$$. We will define as $$$v(l,r)$$$ the numeric value of the corresponding substring (leading zeros are allowed in it).For example, if $$$n=7$$$, $$$s=$$$"1003004", then $$$v(1,3)=100$$$, $$$v(2,3)=0$$$ and $$$v(2,7)=3004$$$.You are given $$$n$$$, $$$s$$$ and an integer $$$w$$$ ($$$1 \le w &lt; n$$$).You need to process $$$m$$$ queries, each of which is characterized by $$$3$$$ numbers $$$l_i, r_i, k_i$$$ ($$$1 \le l_i \le r_i \le n; 0 \le k_i \le 8$$$).The answer to the $$$i$$$th query is such a pair of substrings of length $$$w$$$ that if we denote them as $$$(L_1, L_1+w-1)$$$ and $$$(L_2, L_2+w-1)$$$, then: $$$L_1 \ne L_2$$$, that is, the substrings are different; the remainder of dividing a number $$$v(L_1, L_1+w-1) \cdot v(l_i, r_i) + v(L_2, L_2 + w - 1)$$$ by $$$9$$$ is equal to $$$k_i$$$. If there are many matching substring pairs, then find a pair where $$$L_1$$$ is as small as possible. If there are many matching pairs in this case, then minimize $$$L_2$$$.Note that the answer may not exist.
256 megabytes
import javax.swing.*; import java.awt.*; import java.io.*; import java.lang.reflect.Array; import java.util.*; import java.util.List; import java.util.concurrent.atomic.AtomicReferenceFieldUpdater; public class Main { static long mod = 1000000007; static boolean LOCAL = System.getProperty("ONLINE_JUDGE") == null; static PrintWriter out; static Sca in; public static void main(String[] args) throws FileNotFoundException { InputStream is = LOCAL ? new FileInputStream("input.txt") : System.in; OutputStream os = LOCAL ? new FileOutputStream("output.txt") : System.out; in = new Sca(is); out = new PrintWriter(os); int t = in.nextInt(); int test = 1; while (t-- > 0) { char[] s = in.nextc(); int w = in.nextInt(); int m = in.nextInt(); int n = s.length; int[] pref = new int[n]; for (int i = 0; i < s.length; i++) { pref[i] = s[i] - '0'; if (i > 0) { pref[i] += pref[i - 1]; } } int[] ws = new int[n]; int[] id = new int[10]; int[] id2 = new int[10]; for (int i = 0; i + w - 1 < n; i++) { ws[i] = (pref[i + w - 1] - ((i - 1 < 0) ? 0 : pref[i - 1])) % 9; if (id[ws[i]] == 0) { id[ws[i]] = i + 1; } else if (id2[ws[i]] == 0) { id2[ws[i]] = i + 1; } } for (int i = 0; i < m; i++) { int ansl = Integer.MAX_VALUE; int ansr = Integer.MAX_VALUE; int l = in.nextInt(); int r = in.nextInt(); int k = in.nextInt(); int sum = (pref[r - 1] - (l - 2 < 0 ? 0 : pref[l - 2])) % 9; for (int f = 0; f < 9; f++) { for (int se = 0; se < 9; se++) { if ((f * sum + se) % 9 == k && id[f] != 0 && id[se] != 0 && (id[f] != id[se] || (id[f] == id[se] && id2[se] != 0))) { int second = id[se]; if ((id[f] == id[se] && id2[se] != 0)) { second = id2[se]; } if (id[f] < ansl) { ansl = id[f]; ansr = second; } else if (id[f] == ansl && id[se] < ansr) { ansl = id[f]; ansr = second; } } } } if (ansl != Integer.MAX_VALUE) { out.printf("%d %d\n", ansl, ansr); } else { out.println("-1 -1"); } } test++; } out.close(); } static class Sca { BufferedReader br; StringTokenizer st; public Sca(InputStream io) { br = new BufferedReader(new InputStreamReader(io)); } public String line() { String result = ""; try { result = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return result; } public String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public char[] nextc() { return next().toCharArray(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } static class MultisetTree<T> { int size = 0; TreeMap<T, Integer> mp = new TreeMap<>(); List<T> getSortedArray() { List<T> res = new ArrayList<>(); for (T key : mp.keySet()) { int cnt = mp.get(key); for (int i = 0; i < cnt; i++) { res.add(key); } } return res; } void add(T x) { mp.merge(x, 1, Integer::sum); size++; } List<T> getElems() { List<T> res = new ArrayList<>(); for (T k : mp.keySet()) { int c = mp.get(k); for (int i = 0; i < c; i++) { res.add(k); } } return res; } boolean remove(T x) { if (mp.containsKey(x)) { mp.merge(x, -1, Integer::sum); if (mp.get(x) == 0) { mp.remove(x); } size--; return true; } return false; } T next(T x) { return mp.ceilingKey(x); } boolean contains(T x) { return mp.containsKey(x); } T greatest() { return mp.lastKey(); } T smallest() { return mp.firstKey(); } int size() { return size; } int diffSize() { return mp.size(); } } }
Java
["5\n\n1003004\n\n4 1\n\n1 2 1\n\n179572007\n\n4 2\n\n2 7 3\n\n2 7 4\n\n111\n\n2 1\n\n2 2 6\n\n0000\n\n1 2\n\n1 4 0\n\n1 4 1\n\n484\n\n1 5\n\n2 2 0\n\n2 3 7\n\n1 2 5\n\n3 3 8\n\n2 2 6"]
3 seconds
["2 4\n1 5\n1 2\n-1 -1\n1 2\n-1 -1\n1 3\n1 3\n-1 -1\n-1 -1\n-1 -1"]
NoteConsider the first test case of example inputs. In this test case $$$n=7$$$, $$$s=$$$"1003004", $$$w=4$$$ and one query $$$l_1=1$$$, $$$r_1=2$$$, $$$k_1=1$$$. Note that $$$v(1,2)=10$$$. We need to find a pair of substrings of length $$$4$$$ such that $$$v(L_1, L_1+3)\cdot10+v(L_2,L_2+3)$$$ has a remainder of $$$k_1=1$$$ when divided by $$$9$$$. The values $$$L_1=2, L_2=4$$$ actually satisfy all the requirements: $$$v(L_1, L_1+w-1)=v(2,5)=30$$$, $$$v(L_2, L_2+w-1)=v(4,7)=3004$$$. Indeed, $$$30\cdot10+3004=3304$$$, which has a remainder of $$$1$$$ when divided by $$$9$$$. It can be shown that $$$L_1=2$$$ is the minimum possible value, and $$$L_2=4$$$ is the minimum possible with $$$L_1=2$$$.
Java 11
standard input
[ "hashing", "math" ]
b67870dcffa7bad682ef980dacd1f3db
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — number of input test cases. The first line of each test case contains a string $$$s$$$, which contains only the characters 0-9 and has a length $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$). The second line contains two integers $$$w, m$$$ ($$$1 \le w &lt; n, 1 \le m \le 2 \cdot 10^5$$$), where $$$n$$$ — is the length of the given string $$$s$$$. The number $$$w$$$ denotes the lengths of the substrings being searched for, and $$$m$$$ is the number of queries to be processed. The following $$$m$$$ lines contain integers $$$l_i, r_i, k_i$$$ ($$$1 \le l_i \le r_i \le n$$$, $$$0 \le k_i \le 8$$$) — $$$i$$$th query parameters. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$. It is also guaranteed that the sum of $$$m$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,900
For each request, print in a separate line: left borders of the required substrings: $$$L_1$$$ and $$$L_2$$$; -1 -1 otherwise, if there is no solution. If there are several solutions, minimize $$$L_1$$$ first, and minimize $$$L_2$$$ second.
standard output
PASSED
738b179169a556cb5c072c282ce362b8
train_110.jsonl
1662993300
Given the string $$$s$$$ of decimal digits (0-9) of length $$$n$$$.A substring is a sequence of consecutive characters of a string. The substring of this string is defined by a pair of indexes — with its left and right ends. So, each pair of indexes ($$$l, r$$$), where $$$1 \le l \le r \le n$$$, corresponds to a substring of the string $$$s$$$. We will define as $$$v(l,r)$$$ the numeric value of the corresponding substring (leading zeros are allowed in it).For example, if $$$n=7$$$, $$$s=$$$"1003004", then $$$v(1,3)=100$$$, $$$v(2,3)=0$$$ and $$$v(2,7)=3004$$$.You are given $$$n$$$, $$$s$$$ and an integer $$$w$$$ ($$$1 \le w &lt; n$$$).You need to process $$$m$$$ queries, each of which is characterized by $$$3$$$ numbers $$$l_i, r_i, k_i$$$ ($$$1 \le l_i \le r_i \le n; 0 \le k_i \le 8$$$).The answer to the $$$i$$$th query is such a pair of substrings of length $$$w$$$ that if we denote them as $$$(L_1, L_1+w-1)$$$ and $$$(L_2, L_2+w-1)$$$, then: $$$L_1 \ne L_2$$$, that is, the substrings are different; the remainder of dividing a number $$$v(L_1, L_1+w-1) \cdot v(l_i, r_i) + v(L_2, L_2 + w - 1)$$$ by $$$9$$$ is equal to $$$k_i$$$. If there are many matching substring pairs, then find a pair where $$$L_1$$$ is as small as possible. If there are many matching pairs in this case, then minimize $$$L_2$$$.Note that the answer may not exist.
256 megabytes
import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.BitSet; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.PriorityQueue; import java.util.TreeSet; public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); Solution solver = new Solution(); boolean multipleTC = true; int testCount = multipleTC ? Integer.parseInt(in.next()) : 1; for (int i = 1; i <= testCount; i++) solver.solve(in, out, i); out.close(); } static class Solution { PrintWriter out; InputReader in; private static final long mod = (long) 1e9 + 7; public void solve(InputReader in, PrintWriter out, int test) { this.out = out; this.in = in; String s = n(); int n = s.length(); int[] arr = new int[n]; int sum = 0; int prod = 1; for (int i = 0; i < n; i++) { sum += (prod * (s.charAt(i) - '0')) % 9; sum %= 9; arr[i] = sum; prod *= 10; prod %= 9; } int w = ni(), m = ni(); HashMap<Integer, TreeSet<Integer>> map = new HashMap<>(); for (int i = 0; i <= n - w; i++) { int currSum = arr[i + w - 1]; if (i != 0) currSum -= arr[i - 1]; currSum += 9; currSum %= 9; TreeSet<Integer> set = map.getOrDefault(currSum, new TreeSet<>()); set.add(i); map.put(currSum, set); } // out.println(map); while(m-- > 0) { int li = ni() - 1; int ri = ni() - 1; int ki = ni(); int lRVal = arr[ri]; if (li != 0) lRVal -= arr[li - 1]; lRVal += 9; lRVal %= 9; // // pn(lRVal); int L = -2, R = -2; for (int i = 0; i < 9; i++) { TreeSet<Integer> currSet = map.getOrDefault(i, new TreeSet<>()); if (currSet.size() == 0) continue; int x = currSet.pollFirst(); map.put(i, currSet); int req = ki - ((i * lRVal) % 9) + 9; req %= 9; // pn(i + " " + req); TreeSet<Integer> reqSet = map.getOrDefault(req, new TreeSet<>()); if (reqSet.size() != 0) { if (L == -2) { L = x; R = reqSet.first(); } else if (x < L) { L = x; R = reqSet.first(); } else if (x == L){ if (reqSet.first() < R) { R = reqSet.first(); } } } currSet.add(x); map.put(i, currSet); } pn((L + 1) + " " + (R + 1)); } } final static Comparator<Pair> com = (o1, o2) -> { if (o1.u != o2.u) return Integer.compare(o1.u, o2.u); else return Integer.compare(o1.v, o2.v); }; final static Comparator<Pair> com1 = (o1, o2) -> { if (o1.u != o2.u) return Integer.compare(o2.u, o1.u); else return Integer.compare(o1.v, o2.v); }; static class Pair { int u; int v; Pair(int u, int v) { this.u = u; this.v = v; } } String n() { return in.next(); } int ni() { return in.nextInt(); } long nl() { return in.nextLong(); } void pn(long zx) { out.println(zx); } void pn(String sz) { out.println(sz); } void pn(double dx) { out.println(dx); } int gcd(int a, int b) { if (a == 0) return b; return gcd(b%a, a); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new UnknownError(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new UnknownError(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public String next() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuffer res = new StringBuffer(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } }
Java
["5\n\n1003004\n\n4 1\n\n1 2 1\n\n179572007\n\n4 2\n\n2 7 3\n\n2 7 4\n\n111\n\n2 1\n\n2 2 6\n\n0000\n\n1 2\n\n1 4 0\n\n1 4 1\n\n484\n\n1 5\n\n2 2 0\n\n2 3 7\n\n1 2 5\n\n3 3 8\n\n2 2 6"]
3 seconds
["2 4\n1 5\n1 2\n-1 -1\n1 2\n-1 -1\n1 3\n1 3\n-1 -1\n-1 -1\n-1 -1"]
NoteConsider the first test case of example inputs. In this test case $$$n=7$$$, $$$s=$$$"1003004", $$$w=4$$$ and one query $$$l_1=1$$$, $$$r_1=2$$$, $$$k_1=1$$$. Note that $$$v(1,2)=10$$$. We need to find a pair of substrings of length $$$4$$$ such that $$$v(L_1, L_1+3)\cdot10+v(L_2,L_2+3)$$$ has a remainder of $$$k_1=1$$$ when divided by $$$9$$$. The values $$$L_1=2, L_2=4$$$ actually satisfy all the requirements: $$$v(L_1, L_1+w-1)=v(2,5)=30$$$, $$$v(L_2, L_2+w-1)=v(4,7)=3004$$$. Indeed, $$$30\cdot10+3004=3304$$$, which has a remainder of $$$1$$$ when divided by $$$9$$$. It can be shown that $$$L_1=2$$$ is the minimum possible value, and $$$L_2=4$$$ is the minimum possible with $$$L_1=2$$$.
Java 11
standard input
[ "hashing", "math" ]
b67870dcffa7bad682ef980dacd1f3db
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — number of input test cases. The first line of each test case contains a string $$$s$$$, which contains only the characters 0-9 and has a length $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$). The second line contains two integers $$$w, m$$$ ($$$1 \le w &lt; n, 1 \le m \le 2 \cdot 10^5$$$), where $$$n$$$ — is the length of the given string $$$s$$$. The number $$$w$$$ denotes the lengths of the substrings being searched for, and $$$m$$$ is the number of queries to be processed. The following $$$m$$$ lines contain integers $$$l_i, r_i, k_i$$$ ($$$1 \le l_i \le r_i \le n$$$, $$$0 \le k_i \le 8$$$) — $$$i$$$th query parameters. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$. It is also guaranteed that the sum of $$$m$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,900
For each request, print in a separate line: left borders of the required substrings: $$$L_1$$$ and $$$L_2$$$; -1 -1 otherwise, if there is no solution. If there are several solutions, minimize $$$L_1$$$ first, and minimize $$$L_2$$$ second.
standard output
PASSED
cb863bece4bcca10eddbda95fa57f332
train_110.jsonl
1662993300
Given the string $$$s$$$ of decimal digits (0-9) of length $$$n$$$.A substring is a sequence of consecutive characters of a string. The substring of this string is defined by a pair of indexes — with its left and right ends. So, each pair of indexes ($$$l, r$$$), where $$$1 \le l \le r \le n$$$, corresponds to a substring of the string $$$s$$$. We will define as $$$v(l,r)$$$ the numeric value of the corresponding substring (leading zeros are allowed in it).For example, if $$$n=7$$$, $$$s=$$$"1003004", then $$$v(1,3)=100$$$, $$$v(2,3)=0$$$ and $$$v(2,7)=3004$$$.You are given $$$n$$$, $$$s$$$ and an integer $$$w$$$ ($$$1 \le w &lt; n$$$).You need to process $$$m$$$ queries, each of which is characterized by $$$3$$$ numbers $$$l_i, r_i, k_i$$$ ($$$1 \le l_i \le r_i \le n; 0 \le k_i \le 8$$$).The answer to the $$$i$$$th query is such a pair of substrings of length $$$w$$$ that if we denote them as $$$(L_1, L_1+w-1)$$$ and $$$(L_2, L_2+w-1)$$$, then: $$$L_1 \ne L_2$$$, that is, the substrings are different; the remainder of dividing a number $$$v(L_1, L_1+w-1) \cdot v(l_i, r_i) + v(L_2, L_2 + w - 1)$$$ by $$$9$$$ is equal to $$$k_i$$$. If there are many matching substring pairs, then find a pair where $$$L_1$$$ is as small as possible. If there are many matching pairs in this case, then minimize $$$L_2$$$.Note that the answer may not exist.
256 megabytes
/*========================================================================== * AUTHOR: RonWonWon * CREATED: 14.09.2022 16:34:46 /*==========================================================================*/ import java.io.*; import java.util.*; public class F { public static void main(String[] args) throws IOException { /* in.ini(); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("output.txt"))); */ long startTime = System.nanoTime(); int t = in.nextInt(), T = 1; while(t-->0) { char ch[] = in.next().toCharArray(); int n = ch.length; int w = in.nextInt(), m = in.nextInt(); int v[] = new int[n]; v[0] = ch[0]-'0'; for(int i=1;i<n;i++) v[i] = v[i-1] + (ch[i]-'0'); Map<Integer,List<Integer>> map = new HashMap<>(); for(int i=0;i<=n-w;i++){ int val = v[i+w-1] - (i-1>-1?v[i-1]:0); val %= 9; if(!map.containsKey(val)) map.put(val,new ArrayList<>()); map.get(val).add(i+1); } while(m-->0){ int l = in.nextInt()-1, r = in.nextInt()-1, k = in.nextInt(); int mul = (v[r] - (l-1>-1?v[l-1]:0))%9; int ii = -1, jj = -1; String mn = ""; for(int i=0;i<9;i++){ for(int j=0;j<9;j++){ if(map.containsKey(i)==false||map.containsKey(j)==false) continue; if(i==j) if(map.get(i).size()<2) continue; if(((i*mul)%9+j)%9==k){ int zero = 0; int x = map.get(i).get(zero); if(i==j) zero = 1; int y = map.get(j).get(zero); if(ii==-1){ ii = x; jj = y; } else if(ii>x){ ii = x; jj = y; } } } } out.println(ii+" "+jj); } //out.println("Case #"+T+": "+ans); T++; } /* startTime = System.nanoTime() - startTime; System.err.println("Time: "+(startTime/1000000)); */ out.flush(); } static FastScanner in = new FastScanner(); static PrintWriter out = new PrintWriter(System.out); static int oo = Integer.MAX_VALUE; static long ooo = Long.MAX_VALUE; static class FastScanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); void ini() throws FileNotFoundException { br = new BufferedReader(new FileReader("input.txt")); } String next() { while(!st.hasMoreTokens()) try { st = new StringTokenizer(br.readLine()); } catch(IOException e) {} return st.nextToken(); } String nextLine(){ try{ return br.readLine(); } catch(IOException e) { } return ""; } int nextInt() { return Integer.parseInt(next()); } 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[] readArrayL(int n) { long a[] = new long[n]; for(int i=0;i<n;i++) a[i] = nextLong(); return a; } double nextDouble() { return Double.parseDouble(next()); } double[] readArrayD(int n) { double a[] = new double[n]; for(int i=0;i<n;i++) a[i] = nextDouble(); return a; } } static final Random random = new Random(); static void ruffleSort(int[] a){ int n = a.length; for(int i=0;i<n;i++){ int j = random.nextInt(n), temp = a[j]; a[j] = a[i]; a[i] = temp; } Arrays.sort(a); } static void ruffleSortL(long[] a){ int n = a.length; for(int i=0;i<n;i++){ int j = random.nextInt(n); long temp = a[j]; a[j] = a[i]; a[i] = temp; } Arrays.sort(a); } }
Java
["5\n\n1003004\n\n4 1\n\n1 2 1\n\n179572007\n\n4 2\n\n2 7 3\n\n2 7 4\n\n111\n\n2 1\n\n2 2 6\n\n0000\n\n1 2\n\n1 4 0\n\n1 4 1\n\n484\n\n1 5\n\n2 2 0\n\n2 3 7\n\n1 2 5\n\n3 3 8\n\n2 2 6"]
3 seconds
["2 4\n1 5\n1 2\n-1 -1\n1 2\n-1 -1\n1 3\n1 3\n-1 -1\n-1 -1\n-1 -1"]
NoteConsider the first test case of example inputs. In this test case $$$n=7$$$, $$$s=$$$"1003004", $$$w=4$$$ and one query $$$l_1=1$$$, $$$r_1=2$$$, $$$k_1=1$$$. Note that $$$v(1,2)=10$$$. We need to find a pair of substrings of length $$$4$$$ such that $$$v(L_1, L_1+3)\cdot10+v(L_2,L_2+3)$$$ has a remainder of $$$k_1=1$$$ when divided by $$$9$$$. The values $$$L_1=2, L_2=4$$$ actually satisfy all the requirements: $$$v(L_1, L_1+w-1)=v(2,5)=30$$$, $$$v(L_2, L_2+w-1)=v(4,7)=3004$$$. Indeed, $$$30\cdot10+3004=3304$$$, which has a remainder of $$$1$$$ when divided by $$$9$$$. It can be shown that $$$L_1=2$$$ is the minimum possible value, and $$$L_2=4$$$ is the minimum possible with $$$L_1=2$$$.
Java 8
standard input
[ "hashing", "math" ]
b67870dcffa7bad682ef980dacd1f3db
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — number of input test cases. The first line of each test case contains a string $$$s$$$, which contains only the characters 0-9 and has a length $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$). The second line contains two integers $$$w, m$$$ ($$$1 \le w &lt; n, 1 \le m \le 2 \cdot 10^5$$$), where $$$n$$$ — is the length of the given string $$$s$$$. The number $$$w$$$ denotes the lengths of the substrings being searched for, and $$$m$$$ is the number of queries to be processed. The following $$$m$$$ lines contain integers $$$l_i, r_i, k_i$$$ ($$$1 \le l_i \le r_i \le n$$$, $$$0 \le k_i \le 8$$$) — $$$i$$$th query parameters. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$. It is also guaranteed that the sum of $$$m$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,900
For each request, print in a separate line: left borders of the required substrings: $$$L_1$$$ and $$$L_2$$$; -1 -1 otherwise, if there is no solution. If there are several solutions, minimize $$$L_1$$$ first, and minimize $$$L_2$$$ second.
standard output
PASSED
4fe5a56cbec144bcc27fda83b33a723d
train_110.jsonl
1662993300
Given the string $$$s$$$ of decimal digits (0-9) of length $$$n$$$.A substring is a sequence of consecutive characters of a string. The substring of this string is defined by a pair of indexes — with its left and right ends. So, each pair of indexes ($$$l, r$$$), where $$$1 \le l \le r \le n$$$, corresponds to a substring of the string $$$s$$$. We will define as $$$v(l,r)$$$ the numeric value of the corresponding substring (leading zeros are allowed in it).For example, if $$$n=7$$$, $$$s=$$$"1003004", then $$$v(1,3)=100$$$, $$$v(2,3)=0$$$ and $$$v(2,7)=3004$$$.You are given $$$n$$$, $$$s$$$ and an integer $$$w$$$ ($$$1 \le w &lt; n$$$).You need to process $$$m$$$ queries, each of which is characterized by $$$3$$$ numbers $$$l_i, r_i, k_i$$$ ($$$1 \le l_i \le r_i \le n; 0 \le k_i \le 8$$$).The answer to the $$$i$$$th query is such a pair of substrings of length $$$w$$$ that if we denote them as $$$(L_1, L_1+w-1)$$$ and $$$(L_2, L_2+w-1)$$$, then: $$$L_1 \ne L_2$$$, that is, the substrings are different; the remainder of dividing a number $$$v(L_1, L_1+w-1) \cdot v(l_i, r_i) + v(L_2, L_2 + w - 1)$$$ by $$$9$$$ is equal to $$$k_i$$$. If there are many matching substring pairs, then find a pair where $$$L_1$$$ is as small as possible. If there are many matching pairs in this case, then minimize $$$L_2$$$.Note that the answer may not exist.
256 megabytes
/*========================================================================== * AUTHOR: RonWonWon * CREATED: 14.09.2022 16:34:46 /*==========================================================================*/ import java.io.*; import java.util.*; public class F { public static void main(String[] args) throws IOException { /* in.ini(); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("output.txt"))); */ long startTime = System.nanoTime(); int t = in.nextInt(), T = 1; while(t-->0) { char ch[] = in.next().toCharArray(); int n = ch.length; int w = in.nextInt(), m = in.nextInt(); int v[] = new int[n]; v[0] = ch[0]-'0'; for(int i=1;i<n;i++) v[i] = v[i-1] + (ch[i]-'0'); Map<Integer,PriorityQueue<Integer>> map = new HashMap<>(); for(int i=0;i<=n-w;i++){ int val = v[i+w-1] - (i-1>-1?v[i-1]:0); val %= 9; if(!map.containsKey(val)) map.put(val,new PriorityQueue<>()); map.get(val).add(i+1); } while(m-->0){ int l = in.nextInt()-1, r = in.nextInt()-1, k = in.nextInt(); int mul = (v[r] - (l-1>-1?v[l-1]:0))%9; int ii = -1, jj = -1; String mn = ""; for(int i=0;i<9;i++){ for(int j=0;j<9;j++){ if(map.containsKey(i)==false||map.containsKey(j)==false) continue; if(i==j) if(map.get(i).size()<2) continue; if(((i*mul)%9+j)%9==k){ int x = map.get(i).poll(), y = map.get(j).poll(); if(ii==-1){ ii = x; jj = y; } else if(ii>x){ ii = x; jj = y; } map.get(i).add(x); map.get(j).add(y); } } } out.println(ii+" "+jj); } //out.println("Case #"+T+": "+ans); T++; } /* startTime = System.nanoTime() - startTime; System.err.println("Time: "+(startTime/1000000)); */ out.flush(); } static FastScanner in = new FastScanner(); static PrintWriter out = new PrintWriter(System.out); static int oo = Integer.MAX_VALUE; static long ooo = Long.MAX_VALUE; static class FastScanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); void ini() throws FileNotFoundException { br = new BufferedReader(new FileReader("input.txt")); } String next() { while(!st.hasMoreTokens()) try { st = new StringTokenizer(br.readLine()); } catch(IOException e) {} return st.nextToken(); } String nextLine(){ try{ return br.readLine(); } catch(IOException e) { } return ""; } int nextInt() { return Integer.parseInt(next()); } 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[] readArrayL(int n) { long a[] = new long[n]; for(int i=0;i<n;i++) a[i] = nextLong(); return a; } double nextDouble() { return Double.parseDouble(next()); } double[] readArrayD(int n) { double a[] = new double[n]; for(int i=0;i<n;i++) a[i] = nextDouble(); return a; } } static final Random random = new Random(); static void ruffleSort(int[] a){ int n = a.length; for(int i=0;i<n;i++){ int j = random.nextInt(n), temp = a[j]; a[j] = a[i]; a[i] = temp; } Arrays.sort(a); } static void ruffleSortL(long[] a){ int n = a.length; for(int i=0;i<n;i++){ int j = random.nextInt(n); long temp = a[j]; a[j] = a[i]; a[i] = temp; } Arrays.sort(a); } }
Java
["5\n\n1003004\n\n4 1\n\n1 2 1\n\n179572007\n\n4 2\n\n2 7 3\n\n2 7 4\n\n111\n\n2 1\n\n2 2 6\n\n0000\n\n1 2\n\n1 4 0\n\n1 4 1\n\n484\n\n1 5\n\n2 2 0\n\n2 3 7\n\n1 2 5\n\n3 3 8\n\n2 2 6"]
3 seconds
["2 4\n1 5\n1 2\n-1 -1\n1 2\n-1 -1\n1 3\n1 3\n-1 -1\n-1 -1\n-1 -1"]
NoteConsider the first test case of example inputs. In this test case $$$n=7$$$, $$$s=$$$"1003004", $$$w=4$$$ and one query $$$l_1=1$$$, $$$r_1=2$$$, $$$k_1=1$$$. Note that $$$v(1,2)=10$$$. We need to find a pair of substrings of length $$$4$$$ such that $$$v(L_1, L_1+3)\cdot10+v(L_2,L_2+3)$$$ has a remainder of $$$k_1=1$$$ when divided by $$$9$$$. The values $$$L_1=2, L_2=4$$$ actually satisfy all the requirements: $$$v(L_1, L_1+w-1)=v(2,5)=30$$$, $$$v(L_2, L_2+w-1)=v(4,7)=3004$$$. Indeed, $$$30\cdot10+3004=3304$$$, which has a remainder of $$$1$$$ when divided by $$$9$$$. It can be shown that $$$L_1=2$$$ is the minimum possible value, and $$$L_2=4$$$ is the minimum possible with $$$L_1=2$$$.
Java 8
standard input
[ "hashing", "math" ]
b67870dcffa7bad682ef980dacd1f3db
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — number of input test cases. The first line of each test case contains a string $$$s$$$, which contains only the characters 0-9 and has a length $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$). The second line contains two integers $$$w, m$$$ ($$$1 \le w &lt; n, 1 \le m \le 2 \cdot 10^5$$$), where $$$n$$$ — is the length of the given string $$$s$$$. The number $$$w$$$ denotes the lengths of the substrings being searched for, and $$$m$$$ is the number of queries to be processed. The following $$$m$$$ lines contain integers $$$l_i, r_i, k_i$$$ ($$$1 \le l_i \le r_i \le n$$$, $$$0 \le k_i \le 8$$$) — $$$i$$$th query parameters. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$. It is also guaranteed that the sum of $$$m$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,900
For each request, print in a separate line: left borders of the required substrings: $$$L_1$$$ and $$$L_2$$$; -1 -1 otherwise, if there is no solution. If there are several solutions, minimize $$$L_1$$$ first, and minimize $$$L_2$$$ second.
standard output
PASSED
a849cda3a59faa3bbce17ce58439b9c2
train_110.jsonl
1662993300
Given the string $$$s$$$ of decimal digits (0-9) of length $$$n$$$.A substring is a sequence of consecutive characters of a string. The substring of this string is defined by a pair of indexes — with its left and right ends. So, each pair of indexes ($$$l, r$$$), where $$$1 \le l \le r \le n$$$, corresponds to a substring of the string $$$s$$$. We will define as $$$v(l,r)$$$ the numeric value of the corresponding substring (leading zeros are allowed in it).For example, if $$$n=7$$$, $$$s=$$$"1003004", then $$$v(1,3)=100$$$, $$$v(2,3)=0$$$ and $$$v(2,7)=3004$$$.You are given $$$n$$$, $$$s$$$ and an integer $$$w$$$ ($$$1 \le w &lt; n$$$).You need to process $$$m$$$ queries, each of which is characterized by $$$3$$$ numbers $$$l_i, r_i, k_i$$$ ($$$1 \le l_i \le r_i \le n; 0 \le k_i \le 8$$$).The answer to the $$$i$$$th query is such a pair of substrings of length $$$w$$$ that if we denote them as $$$(L_1, L_1+w-1)$$$ and $$$(L_2, L_2+w-1)$$$, then: $$$L_1 \ne L_2$$$, that is, the substrings are different; the remainder of dividing a number $$$v(L_1, L_1+w-1) \cdot v(l_i, r_i) + v(L_2, L_2 + w - 1)$$$ by $$$9$$$ is equal to $$$k_i$$$. If there are many matching substring pairs, then find a pair where $$$L_1$$$ is as small as possible. If there are many matching pairs in this case, then minimize $$$L_2$$$.Note that the answer may not exist.
256 megabytes
import java.io.*; import java.util.*; public class Main { static InputReader sc; static PrintWriter out; private static final int maxn = (int)(1e5 + 7); public static void solve() throws Exception { char[] str = sc.next().toCharArray(); int w = sc.nextInt(), q = sc.nextInt(); int[] v = new int[str.length + 1]; for(int i = 0; i < str.length; i ++ ) { v[i + 1] = str[i] - '0'; v[i + 1] += v[i]; } Vector<Vector<Integer>> ve = new Vector<Vector<Integer>>(); for(int i = 0; i < 9; i ++ ) { ve.addElement(new Vector<Integer>()); } for(int i = w; i < v.length; i ++ ) { int l = i - w; int md = (v[i] - v[l]) % 9; ve.get(md).addElement(l + 1); } while(q -- > 0) { int l = sc.nextInt(), r = sc.nextInt(), k = sc.nextInt(); int t = (v[r] - v[l - 1]) % 9; int a = Integer.MAX_VALUE, b = Integer.MAX_VALUE; for(int i = 0; i < 9; i ++ ) { for(int j = 0; j < 9; j ++ ) { int ta = Integer.MAX_VALUE, tb = Integer.MAX_VALUE; if((i * t + j) % 9 == k) { if(ve.get(i).size() > 0 && ve.get(j).size() > 0) { if(i == j) { if(ve.get(i).size() == 1) continue; ta = ve.get(i).get(0); tb = ve.get(i).get(1); }else { ta = ve.get(i).get(0); tb = ve.get(j).get(0); } } if(ta < a) { a = ta; b = tb; }else if(ta == a && tb < b) { b = tb; } } } } if(a == Integer.MAX_VALUE) { a = -1; b = -1; } out.println(a + " " + b); } } public static void prepare() throws Exception { sc = new InputReader(System.in); out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); } public static void main(String[] args) throws Exception { prepare(); int T = 1; T = sc.nextInt(); while(T -- > 0) { solve(); } out.flush(); return ; } static class InputReader { BufferedReader br; public InputReader(InputStream stream) { br = new BufferedReader(new InputStreamReader(stream)); } public int nextInt() throws IOException { int c = br.read(); while (c <= 32) { c = br.read(); } boolean negative = false; if (c == '-') { negative = true; c = br.read(); } int x = 0; while (c > 32) { x = x * 10 + c - '0'; c = br.read(); } return negative ? -x : x; } public long nextLong() throws IOException { int c = br.read(); while (c <= 32) { c = br.read(); } boolean negative = false; if (c == '-') { negative = true; c = br.read(); } long x = 0; while (c > 32) { x = x * 10 + c - '0'; c = br.read(); } return negative ? -x : x; } public String next() throws IOException { int c = br.read(); while (c <= 32) { c = br.read(); } StringBuilder sb = new StringBuilder(); while (c > 32) { sb.append((char) c); c = br.read(); } return sb.toString(); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } } static class os extends PrintStream { private final BufferedWriter writer; public os(OutputStream out) { super(out); writer=new BufferedWriter(new OutputStreamWriter(out)); } public void write(int b) { try { out.write(b); } catch (IOException e) { e.printStackTrace(); } } public void write(byte buf[], int off, int len) { try { out.write(buf, off, len); } catch (IOException e) { e.printStackTrace(); } } private void write(char buf[]) { try { writer.write(buf); } catch (IOException e) { e.printStackTrace(); } } private void write(String s) { try { writer.write(s); } catch (IOException e) { e.printStackTrace(); } } private void newLine() { try { writer.newLine(); } catch (IOException e) { e.printStackTrace(); } } } }
Java
["5\n\n1003004\n\n4 1\n\n1 2 1\n\n179572007\n\n4 2\n\n2 7 3\n\n2 7 4\n\n111\n\n2 1\n\n2 2 6\n\n0000\n\n1 2\n\n1 4 0\n\n1 4 1\n\n484\n\n1 5\n\n2 2 0\n\n2 3 7\n\n1 2 5\n\n3 3 8\n\n2 2 6"]
3 seconds
["2 4\n1 5\n1 2\n-1 -1\n1 2\n-1 -1\n1 3\n1 3\n-1 -1\n-1 -1\n-1 -1"]
NoteConsider the first test case of example inputs. In this test case $$$n=7$$$, $$$s=$$$"1003004", $$$w=4$$$ and one query $$$l_1=1$$$, $$$r_1=2$$$, $$$k_1=1$$$. Note that $$$v(1,2)=10$$$. We need to find a pair of substrings of length $$$4$$$ such that $$$v(L_1, L_1+3)\cdot10+v(L_2,L_2+3)$$$ has a remainder of $$$k_1=1$$$ when divided by $$$9$$$. The values $$$L_1=2, L_2=4$$$ actually satisfy all the requirements: $$$v(L_1, L_1+w-1)=v(2,5)=30$$$, $$$v(L_2, L_2+w-1)=v(4,7)=3004$$$. Indeed, $$$30\cdot10+3004=3304$$$, which has a remainder of $$$1$$$ when divided by $$$9$$$. It can be shown that $$$L_1=2$$$ is the minimum possible value, and $$$L_2=4$$$ is the minimum possible with $$$L_1=2$$$.
Java 8
standard input
[ "hashing", "math" ]
b67870dcffa7bad682ef980dacd1f3db
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — number of input test cases. The first line of each test case contains a string $$$s$$$, which contains only the characters 0-9 and has a length $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$). The second line contains two integers $$$w, m$$$ ($$$1 \le w &lt; n, 1 \le m \le 2 \cdot 10^5$$$), where $$$n$$$ — is the length of the given string $$$s$$$. The number $$$w$$$ denotes the lengths of the substrings being searched for, and $$$m$$$ is the number of queries to be processed. The following $$$m$$$ lines contain integers $$$l_i, r_i, k_i$$$ ($$$1 \le l_i \le r_i \le n$$$, $$$0 \le k_i \le 8$$$) — $$$i$$$th query parameters. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$. It is also guaranteed that the sum of $$$m$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,900
For each request, print in a separate line: left borders of the required substrings: $$$L_1$$$ and $$$L_2$$$; -1 -1 otherwise, if there is no solution. If there are several solutions, minimize $$$L_1$$$ first, and minimize $$$L_2$$$ second.
standard output
PASSED
3a1e29ab8e0d3dde73d86fab8098c38d
train_110.jsonl
1662993300
Given the string $$$s$$$ of decimal digits (0-9) of length $$$n$$$.A substring is a sequence of consecutive characters of a string. The substring of this string is defined by a pair of indexes — with its left and right ends. So, each pair of indexes ($$$l, r$$$), where $$$1 \le l \le r \le n$$$, corresponds to a substring of the string $$$s$$$. We will define as $$$v(l,r)$$$ the numeric value of the corresponding substring (leading zeros are allowed in it).For example, if $$$n=7$$$, $$$s=$$$"1003004", then $$$v(1,3)=100$$$, $$$v(2,3)=0$$$ and $$$v(2,7)=3004$$$.You are given $$$n$$$, $$$s$$$ and an integer $$$w$$$ ($$$1 \le w &lt; n$$$).You need to process $$$m$$$ queries, each of which is characterized by $$$3$$$ numbers $$$l_i, r_i, k_i$$$ ($$$1 \le l_i \le r_i \le n; 0 \le k_i \le 8$$$).The answer to the $$$i$$$th query is such a pair of substrings of length $$$w$$$ that if we denote them as $$$(L_1, L_1+w-1)$$$ and $$$(L_2, L_2+w-1)$$$, then: $$$L_1 \ne L_2$$$, that is, the substrings are different; the remainder of dividing a number $$$v(L_1, L_1+w-1) \cdot v(l_i, r_i) + v(L_2, L_2 + w - 1)$$$ by $$$9$$$ is equal to $$$k_i$$$. If there are many matching substring pairs, then find a pair where $$$L_1$$$ is as small as possible. If there are many matching pairs in this case, then minimize $$$L_2$$$.Note that the answer may not exist.
256 megabytes
import java.io.*; import java.util.*; public class Main { static InputReader sc; static PrintWriter out; private static final int maxn = (int)(1e5 + 7); public static void solve() throws Exception { char[] str = sc.next().toCharArray(); int w = sc.nextInt(), q = sc.nextInt(); int[] v = new int[str.length + 1]; for(int i = 0; i < str.length; i ++ ) { v[i + 1] = str[i] - '0'; v[i + 1] += v[i]; } Vector<Vector<Integer>> ve = new Vector<Vector<Integer>>(); for(int i = 0; i < 9; i ++ ) { ve.addElement(new Vector<Integer>()); } for(int i = w; i < v.length; i ++ ) { int l = i - w; int md = (v[i] - v[l]) % 9; ve.get(md).addElement(l + 1); } while(q -- > 0) { int l = sc.nextInt(), r = sc.nextInt(), k = sc.nextInt(); int t = (v[r] - v[l - 1]) % 9; int a = Integer.MAX_VALUE, b = Integer.MAX_VALUE; for(int i = 0; i < 9; i ++ ) { for(int j = 0; j < 9; j ++ ) { int ta = Integer.MAX_VALUE, tb = Integer.MAX_VALUE; if((i * t + j) % 9 == k) { if(ve.get(i).size() > 0 && ve.get(j).size() > 0) { if(i == j) { if(ve.get(i).size() == 1) continue; ta = ve.get(i).get(0); tb = ve.get(i).get(1); }else { ta = ve.get(i).get(0); tb = ve.get(j).get(0); } } if(ta < a) { a = ta; b = tb; }else if(ta == a && tb < b) { b = tb; } } } } if(a == Integer.MAX_VALUE) { a = -1; b = -1; } out.println(a + " " + b); out.flush(); } } public static void prepare() throws Exception { out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); sc = new InputReader(System.in); } public static void main(String[] args) throws Exception { prepare(); int T = 1; T = sc.nextInt(); while(T -- > 0) { solve(); } return ; } static class InputReader { BufferedReader br; public InputReader(InputStream stream) { br = new BufferedReader(new InputStreamReader(stream)); } public int nextInt() throws IOException { int c = br.read(); while (c <= 32) { c = br.read(); } boolean negative = false; if (c == '-') { negative = true; c = br.read(); } int x = 0; while (c > 32) { x = x * 10 + c - '0'; c = br.read(); } return negative ? -x : x; } public long nextLong() throws IOException { int c = br.read(); while (c <= 32) { c = br.read(); } boolean negative = false; if (c == '-') { negative = true; c = br.read(); } long x = 0; while (c > 32) { x = x * 10 + c - '0'; c = br.read(); } return negative ? -x : x; } public String next() throws IOException { int c = br.read(); while (c <= 32) { c = br.read(); } StringBuilder sb = new StringBuilder(); while (c > 32) { sb.append((char) c); c = br.read(); } return sb.toString(); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } } static class os extends PrintStream { private final BufferedWriter writer; public os(OutputStream out) { super(out); writer=new BufferedWriter(new OutputStreamWriter(out)); } public void write(int b) { try { out.write(b); } catch (IOException e) { e.printStackTrace(); } } public void write(byte buf[], int off, int len) { try { out.write(buf, off, len); } catch (IOException e) { e.printStackTrace(); } } private void write(char buf[]) { try { writer.write(buf); } catch (IOException e) { e.printStackTrace(); } } private void write(String s) { try { writer.write(s); } catch (IOException e) { e.printStackTrace(); } } private void newLine() { try { writer.newLine(); } catch (IOException e) { e.printStackTrace(); } } } }
Java
["5\n\n1003004\n\n4 1\n\n1 2 1\n\n179572007\n\n4 2\n\n2 7 3\n\n2 7 4\n\n111\n\n2 1\n\n2 2 6\n\n0000\n\n1 2\n\n1 4 0\n\n1 4 1\n\n484\n\n1 5\n\n2 2 0\n\n2 3 7\n\n1 2 5\n\n3 3 8\n\n2 2 6"]
3 seconds
["2 4\n1 5\n1 2\n-1 -1\n1 2\n-1 -1\n1 3\n1 3\n-1 -1\n-1 -1\n-1 -1"]
NoteConsider the first test case of example inputs. In this test case $$$n=7$$$, $$$s=$$$"1003004", $$$w=4$$$ and one query $$$l_1=1$$$, $$$r_1=2$$$, $$$k_1=1$$$. Note that $$$v(1,2)=10$$$. We need to find a pair of substrings of length $$$4$$$ such that $$$v(L_1, L_1+3)\cdot10+v(L_2,L_2+3)$$$ has a remainder of $$$k_1=1$$$ when divided by $$$9$$$. The values $$$L_1=2, L_2=4$$$ actually satisfy all the requirements: $$$v(L_1, L_1+w-1)=v(2,5)=30$$$, $$$v(L_2, L_2+w-1)=v(4,7)=3004$$$. Indeed, $$$30\cdot10+3004=3304$$$, which has a remainder of $$$1$$$ when divided by $$$9$$$. It can be shown that $$$L_1=2$$$ is the minimum possible value, and $$$L_2=4$$$ is the minimum possible with $$$L_1=2$$$.
Java 8
standard input
[ "hashing", "math" ]
b67870dcffa7bad682ef980dacd1f3db
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — number of input test cases. The first line of each test case contains a string $$$s$$$, which contains only the characters 0-9 and has a length $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$). The second line contains two integers $$$w, m$$$ ($$$1 \le w &lt; n, 1 \le m \le 2 \cdot 10^5$$$), where $$$n$$$ — is the length of the given string $$$s$$$. The number $$$w$$$ denotes the lengths of the substrings being searched for, and $$$m$$$ is the number of queries to be processed. The following $$$m$$$ lines contain integers $$$l_i, r_i, k_i$$$ ($$$1 \le l_i \le r_i \le n$$$, $$$0 \le k_i \le 8$$$) — $$$i$$$th query parameters. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$. It is also guaranteed that the sum of $$$m$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,900
For each request, print in a separate line: left borders of the required substrings: $$$L_1$$$ and $$$L_2$$$; -1 -1 otherwise, if there is no solution. If there are several solutions, minimize $$$L_1$$$ first, and minimize $$$L_2$$$ second.
standard output
PASSED
9c8ec58583a50345e403c0c2222f290b
train_110.jsonl
1662993300
Given the string $$$s$$$ of decimal digits (0-9) of length $$$n$$$.A substring is a sequence of consecutive characters of a string. The substring of this string is defined by a pair of indexes — with its left and right ends. So, each pair of indexes ($$$l, r$$$), where $$$1 \le l \le r \le n$$$, corresponds to a substring of the string $$$s$$$. We will define as $$$v(l,r)$$$ the numeric value of the corresponding substring (leading zeros are allowed in it).For example, if $$$n=7$$$, $$$s=$$$"1003004", then $$$v(1,3)=100$$$, $$$v(2,3)=0$$$ and $$$v(2,7)=3004$$$.You are given $$$n$$$, $$$s$$$ and an integer $$$w$$$ ($$$1 \le w &lt; n$$$).You need to process $$$m$$$ queries, each of which is characterized by $$$3$$$ numbers $$$l_i, r_i, k_i$$$ ($$$1 \le l_i \le r_i \le n; 0 \le k_i \le 8$$$).The answer to the $$$i$$$th query is such a pair of substrings of length $$$w$$$ that if we denote them as $$$(L_1, L_1+w-1)$$$ and $$$(L_2, L_2+w-1)$$$, then: $$$L_1 \ne L_2$$$, that is, the substrings are different; the remainder of dividing a number $$$v(L_1, L_1+w-1) \cdot v(l_i, r_i) + v(L_2, L_2 + w - 1)$$$ by $$$9$$$ is equal to $$$k_i$$$. If there are many matching substring pairs, then find a pair where $$$L_1$$$ is as small as possible. If there are many matching pairs in this case, then minimize $$$L_2$$$.Note that the answer may not exist.
256 megabytes
import java.io.*; import java.util.*; public class Main { static InputReader sc; public static void solve() throws Exception { char[] str = sc.next().toCharArray(); int w = sc.nextInt(), q = sc.nextInt(); int[] v = new int[str.length + 1]; for(int i = 0; i < str.length; i ++ ) { v[i + 1] = str[i] - '0'; v[i + 1] += v[i]; } Vector<Vector<Integer>> ve = new Vector<Vector<Integer>>(); for(int i = 0; i < 9; i ++ ) { ve.addElement(new Vector<Integer>()); } for(int i = w; i < v.length; i ++ ) { int l = i - w; int md = (v[i] - v[l]) % 9; ve.get(md).addElement(l + 1); } while(q -- > 0) { int l = sc.nextInt(), r = sc.nextInt(), k = sc.nextInt(); int t = (v[r] - v[l - 1]) % 9; int a = Integer.MAX_VALUE, b = Integer.MAX_VALUE; for(int i = 0; i < 9; i ++ ) { for(int j = 0; j < 9; j ++ ) { int ta = Integer.MAX_VALUE, tb = Integer.MAX_VALUE; if((i * t + j) % 9 == k) { if(ve.get(i).size() > 0 && ve.get(j).size() > 0) { if(i == j) { if(ve.get(i).size() == 1) continue; ta = ve.get(i).get(0); tb = ve.get(i).get(1); }else { ta = ve.get(i).get(0); tb = ve.get(j).get(0); } } if(ta < a) { a = ta; b = tb; }else if(ta == a && tb < b) { b = tb; } } } } if(a == Integer.MAX_VALUE) { a = -1; b = -1; } System.out.println(a + " " + b); } } public static void prepare() throws Exception { } public static void main(String[] args) throws Exception { System.setOut(new os(System.out)); sc = new InputReader(System.in); int T = 1; T = sc.nextInt(); prepare(); while(T -- > 0) { solve(); } return ; } static class InputReader { BufferedReader br; public InputReader(InputStream stream) { br = new BufferedReader(new InputStreamReader(stream)); } public int nextInt() throws IOException { int c = br.read(); while (c <= 32) { c = br.read(); } boolean negative = false; if (c == '-') { negative = true; c = br.read(); } int x = 0; while (c > 32) { x = x * 10 + c - '0'; c = br.read(); } return negative ? -x : x; } public long nextLong() throws IOException { int c = br.read(); while (c <= 32) { c = br.read(); } boolean negative = false; if (c == '-') { negative = true; c = br.read(); } long x = 0; while (c > 32) { x = x * 10 + c - '0'; c = br.read(); } return negative ? -x : x; } public String next() throws IOException { int c = br.read(); while (c <= 32) { c = br.read(); } StringBuilder sb = new StringBuilder(); while (c > 32) { sb.append((char) c); c = br.read(); } return sb.toString(); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } } static class os extends PrintStream { private final BufferedWriter writer; public os(OutputStream out) { super(out); writer=new BufferedWriter(new OutputStreamWriter(out)); } public void write(int b) { try { out.write(b); } catch (IOException e) { e.printStackTrace(); } } public void write(byte buf[], int off, int len) { try { out.write(buf, off, len); } catch (IOException e) { e.printStackTrace(); } } private void write(char buf[]) { try { writer.write(buf); } catch (IOException e) { e.printStackTrace(); } } private void write(String s) { try { writer.write(s); } catch (IOException e) { e.printStackTrace(); } } private void newLine() { try { writer.newLine(); } catch (IOException e) { e.printStackTrace(); } } } }
Java
["5\n\n1003004\n\n4 1\n\n1 2 1\n\n179572007\n\n4 2\n\n2 7 3\n\n2 7 4\n\n111\n\n2 1\n\n2 2 6\n\n0000\n\n1 2\n\n1 4 0\n\n1 4 1\n\n484\n\n1 5\n\n2 2 0\n\n2 3 7\n\n1 2 5\n\n3 3 8\n\n2 2 6"]
3 seconds
["2 4\n1 5\n1 2\n-1 -1\n1 2\n-1 -1\n1 3\n1 3\n-1 -1\n-1 -1\n-1 -1"]
NoteConsider the first test case of example inputs. In this test case $$$n=7$$$, $$$s=$$$"1003004", $$$w=4$$$ and one query $$$l_1=1$$$, $$$r_1=2$$$, $$$k_1=1$$$. Note that $$$v(1,2)=10$$$. We need to find a pair of substrings of length $$$4$$$ such that $$$v(L_1, L_1+3)\cdot10+v(L_2,L_2+3)$$$ has a remainder of $$$k_1=1$$$ when divided by $$$9$$$. The values $$$L_1=2, L_2=4$$$ actually satisfy all the requirements: $$$v(L_1, L_1+w-1)=v(2,5)=30$$$, $$$v(L_2, L_2+w-1)=v(4,7)=3004$$$. Indeed, $$$30\cdot10+3004=3304$$$, which has a remainder of $$$1$$$ when divided by $$$9$$$. It can be shown that $$$L_1=2$$$ is the minimum possible value, and $$$L_2=4$$$ is the minimum possible with $$$L_1=2$$$.
Java 8
standard input
[ "hashing", "math" ]
b67870dcffa7bad682ef980dacd1f3db
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — number of input test cases. The first line of each test case contains a string $$$s$$$, which contains only the characters 0-9 and has a length $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$). The second line contains two integers $$$w, m$$$ ($$$1 \le w &lt; n, 1 \le m \le 2 \cdot 10^5$$$), where $$$n$$$ — is the length of the given string $$$s$$$. The number $$$w$$$ denotes the lengths of the substrings being searched for, and $$$m$$$ is the number of queries to be processed. The following $$$m$$$ lines contain integers $$$l_i, r_i, k_i$$$ ($$$1 \le l_i \le r_i \le n$$$, $$$0 \le k_i \le 8$$$) — $$$i$$$th query parameters. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$. It is also guaranteed that the sum of $$$m$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,900
For each request, print in a separate line: left borders of the required substrings: $$$L_1$$$ and $$$L_2$$$; -1 -1 otherwise, if there is no solution. If there are several solutions, minimize $$$L_1$$$ first, and minimize $$$L_2$$$ second.
standard output
PASSED
0926f76b3a18c055565f866a34f54fd3
train_110.jsonl
1662993300
Given the string $$$s$$$ of decimal digits (0-9) of length $$$n$$$.A substring is a sequence of consecutive characters of a string. The substring of this string is defined by a pair of indexes — with its left and right ends. So, each pair of indexes ($$$l, r$$$), where $$$1 \le l \le r \le n$$$, corresponds to a substring of the string $$$s$$$. We will define as $$$v(l,r)$$$ the numeric value of the corresponding substring (leading zeros are allowed in it).For example, if $$$n=7$$$, $$$s=$$$"1003004", then $$$v(1,3)=100$$$, $$$v(2,3)=0$$$ and $$$v(2,7)=3004$$$.You are given $$$n$$$, $$$s$$$ and an integer $$$w$$$ ($$$1 \le w &lt; n$$$).You need to process $$$m$$$ queries, each of which is characterized by $$$3$$$ numbers $$$l_i, r_i, k_i$$$ ($$$1 \le l_i \le r_i \le n; 0 \le k_i \le 8$$$).The answer to the $$$i$$$th query is such a pair of substrings of length $$$w$$$ that if we denote them as $$$(L_1, L_1+w-1)$$$ and $$$(L_2, L_2+w-1)$$$, then: $$$L_1 \ne L_2$$$, that is, the substrings are different; the remainder of dividing a number $$$v(L_1, L_1+w-1) \cdot v(l_i, r_i) + v(L_2, L_2 + w - 1)$$$ by $$$9$$$ is equal to $$$k_i$$$. If there are many matching substring pairs, then find a pair where $$$L_1$$$ is as small as possible. If there are many matching pairs in this case, then minimize $$$L_2$$$.Note that the answer may not exist.
256 megabytes
import java.io.*; import java.util.*; public class Main { private static void solve(String s, int w, int m, int[][] queries){ int n = s.length(); int[] prefix = new int[n + 1]; for(int i = 1; i <= n; i++){ prefix[i] = (prefix[i-1] + (s.charAt(i-1) - '0')) % 9; } Map<Integer, List<Integer>> indices = new HashMap<>(); for(int i = 0; i < 9; i++){ indices.put(i, new ArrayList<>()); } for(int end = w; end <= n; end++){ int start = end - w + 1; int diff = prefix[end] - prefix[end - w] + 9; int mod = diff % 9; if(indices.get(mod).size() > 2){ continue; } indices.get(mod).add(start); } for(int[] q: queries){ int resL1 = Integer.MAX_VALUE, resL2 = Integer.MAX_VALUE; int l = q[0], r = q[1], k = q[2]; int v = (prefix[r] - prefix[l-1] + 90) % 9; for(int a = 0; a < 9; a++){ int c = (k - ((v * a) % 9) + 900) % 9; List<Integer> aList = indices.get(a); List<Integer> cList = indices.get(c); if(aList.size() > 0 && cList.size() > 0){ int L1, L2; if(a == c){ L1 = aList.get(0); L2 = aList.size() >= 2? aList.get(1): -1; } else{ L1 = aList.get(0); L2 = cList.get(0); } if(L1 != -1 && L2 != -1){ if(L1 < resL1){ resL1 = L1; resL2 = L2; } else if(resL1 == L1 && L2 < resL2){ resL2 = L2; } } } } if(resL1 == Integer.MAX_VALUE || resL2 == Integer.MAX_VALUE){ out.println("-1 -1"); } else{ out.println(resL1 + " " + resL2); } } } public static void main(String[] args){ MyScanner scanner = new MyScanner(); int numOfTests = scanner.nextInt(); for(int i = 1; i <= numOfTests; i++){ String s = scanner.nextLine(); int w = scanner.nextInt(); int m = scanner.nextInt(); int[][] queries = new int[m][3]; for(int j = 0; j < m; j++){ queries[j][0] = scanner.nextInt(); queries[j][1] = scanner.nextInt(); queries[j][2] = scanner.nextInt(); } solve(s, w, m, queries); } out.close(); } private static void printResult(int caseIdx, boolean res){ out.println("Case #"+caseIdx+": "+ (res?"YES":"NO")); } 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; } } }
Java
["5\n\n1003004\n\n4 1\n\n1 2 1\n\n179572007\n\n4 2\n\n2 7 3\n\n2 7 4\n\n111\n\n2 1\n\n2 2 6\n\n0000\n\n1 2\n\n1 4 0\n\n1 4 1\n\n484\n\n1 5\n\n2 2 0\n\n2 3 7\n\n1 2 5\n\n3 3 8\n\n2 2 6"]
3 seconds
["2 4\n1 5\n1 2\n-1 -1\n1 2\n-1 -1\n1 3\n1 3\n-1 -1\n-1 -1\n-1 -1"]
NoteConsider the first test case of example inputs. In this test case $$$n=7$$$, $$$s=$$$"1003004", $$$w=4$$$ and one query $$$l_1=1$$$, $$$r_1=2$$$, $$$k_1=1$$$. Note that $$$v(1,2)=10$$$. We need to find a pair of substrings of length $$$4$$$ such that $$$v(L_1, L_1+3)\cdot10+v(L_2,L_2+3)$$$ has a remainder of $$$k_1=1$$$ when divided by $$$9$$$. The values $$$L_1=2, L_2=4$$$ actually satisfy all the requirements: $$$v(L_1, L_1+w-1)=v(2,5)=30$$$, $$$v(L_2, L_2+w-1)=v(4,7)=3004$$$. Indeed, $$$30\cdot10+3004=3304$$$, which has a remainder of $$$1$$$ when divided by $$$9$$$. It can be shown that $$$L_1=2$$$ is the minimum possible value, and $$$L_2=4$$$ is the minimum possible with $$$L_1=2$$$.
Java 8
standard input
[ "hashing", "math" ]
b67870dcffa7bad682ef980dacd1f3db
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — number of input test cases. The first line of each test case contains a string $$$s$$$, which contains only the characters 0-9 and has a length $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$). The second line contains two integers $$$w, m$$$ ($$$1 \le w &lt; n, 1 \le m \le 2 \cdot 10^5$$$), where $$$n$$$ — is the length of the given string $$$s$$$. The number $$$w$$$ denotes the lengths of the substrings being searched for, and $$$m$$$ is the number of queries to be processed. The following $$$m$$$ lines contain integers $$$l_i, r_i, k_i$$$ ($$$1 \le l_i \le r_i \le n$$$, $$$0 \le k_i \le 8$$$) — $$$i$$$th query parameters. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$. It is also guaranteed that the sum of $$$m$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,900
For each request, print in a separate line: left borders of the required substrings: $$$L_1$$$ and $$$L_2$$$; -1 -1 otherwise, if there is no solution. If there are several solutions, minimize $$$L_1$$$ first, and minimize $$$L_2$$$ second.
standard output
PASSED
62472b0ab5137a9a61dff181f6aab145
train_110.jsonl
1662993300
Given the string $$$s$$$ of decimal digits (0-9) of length $$$n$$$.A substring is a sequence of consecutive characters of a string. The substring of this string is defined by a pair of indexes — with its left and right ends. So, each pair of indexes ($$$l, r$$$), where $$$1 \le l \le r \le n$$$, corresponds to a substring of the string $$$s$$$. We will define as $$$v(l,r)$$$ the numeric value of the corresponding substring (leading zeros are allowed in it).For example, if $$$n=7$$$, $$$s=$$$"1003004", then $$$v(1,3)=100$$$, $$$v(2,3)=0$$$ and $$$v(2,7)=3004$$$.You are given $$$n$$$, $$$s$$$ and an integer $$$w$$$ ($$$1 \le w &lt; n$$$).You need to process $$$m$$$ queries, each of which is characterized by $$$3$$$ numbers $$$l_i, r_i, k_i$$$ ($$$1 \le l_i \le r_i \le n; 0 \le k_i \le 8$$$).The answer to the $$$i$$$th query is such a pair of substrings of length $$$w$$$ that if we denote them as $$$(L_1, L_1+w-1)$$$ and $$$(L_2, L_2+w-1)$$$, then: $$$L_1 \ne L_2$$$, that is, the substrings are different; the remainder of dividing a number $$$v(L_1, L_1+w-1) \cdot v(l_i, r_i) + v(L_2, L_2 + w - 1)$$$ by $$$9$$$ is equal to $$$k_i$$$. If there are many matching substring pairs, then find a pair where $$$L_1$$$ is as small as possible. If there are many matching pairs in this case, then minimize $$$L_2$$$.Note that the answer may not exist.
256 megabytes
import java.util.*; import java.io.*; public class codeforces1729F{ public static void main (String[] args) throws IOException { FastReader in = new FastReader(); PrintWriter pw = new PrintWriter(System.out); int numCases = in.nextInt(); while (numCases-->0) { String s = in.next(); int len = s.length(); int [] prefix = new int [len+1]; prefix[0] = 0; for (int i = 0; i<len;i++) { prefix[i+1] = prefix[i] + s.charAt(i)-'0'; } ArrayList<Integer>[] pairs = new ArrayList[9]; for (int i = 0; i<9;i++) { pairs[i] = new ArrayList<>(); } int w = in.nextInt(); int m = in.nextInt(); for (int i = w; i<=len;i++) { int mod = (prefix[i]-prefix[i-w]) % 9; pairs[mod].add(i-w+1); } for (int i = 0; i<9;i++) { Collections.sort(pairs[i]); } while (m-->0) { int l = in.nextInt()-1; int r = in.nextInt(); int k = in.nextInt(); int v = (prefix[r]-prefix[l]) % 9; int ans1 = Integer.MAX_VALUE, ans2 = Integer.MAX_VALUE; for (int a = 0; a<9;a++) { for (int b = 0; b<9;b++) { if ((a*v + b)%9==k) { if (a==b) { if (pairs[a].size()>=2) { if (ans1>pairs[a].get(0) || (pairs[a].get(0)==ans1 && ans2>pairs[a].get(1))) { ans1 = pairs[a].get(0); ans2 = pairs[a].get(1); } } } else { if (pairs[a].size()>0 && pairs[b].size()>0) { if (ans1>pairs[a].get(0) || (pairs[a].get(0)==ans1 && ans2>pairs[b].get(0))) { ans1 = pairs[a].get(0); ans2 = pairs[b].get(0); } } } } } } if (ans1!=Integer.MAX_VALUE) pw.println(ans1+" "+ans2); else pw.println("-1 -1"); } } pw.close(); } static class FastReader { StringTokenizer st; BufferedReader br; 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 s = ""; while (st == null || st.hasMoreElements()) { try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } } return s; } } }
Java
["5\n\n1003004\n\n4 1\n\n1 2 1\n\n179572007\n\n4 2\n\n2 7 3\n\n2 7 4\n\n111\n\n2 1\n\n2 2 6\n\n0000\n\n1 2\n\n1 4 0\n\n1 4 1\n\n484\n\n1 5\n\n2 2 0\n\n2 3 7\n\n1 2 5\n\n3 3 8\n\n2 2 6"]
3 seconds
["2 4\n1 5\n1 2\n-1 -1\n1 2\n-1 -1\n1 3\n1 3\n-1 -1\n-1 -1\n-1 -1"]
NoteConsider the first test case of example inputs. In this test case $$$n=7$$$, $$$s=$$$"1003004", $$$w=4$$$ and one query $$$l_1=1$$$, $$$r_1=2$$$, $$$k_1=1$$$. Note that $$$v(1,2)=10$$$. We need to find a pair of substrings of length $$$4$$$ such that $$$v(L_1, L_1+3)\cdot10+v(L_2,L_2+3)$$$ has a remainder of $$$k_1=1$$$ when divided by $$$9$$$. The values $$$L_1=2, L_2=4$$$ actually satisfy all the requirements: $$$v(L_1, L_1+w-1)=v(2,5)=30$$$, $$$v(L_2, L_2+w-1)=v(4,7)=3004$$$. Indeed, $$$30\cdot10+3004=3304$$$, which has a remainder of $$$1$$$ when divided by $$$9$$$. It can be shown that $$$L_1=2$$$ is the minimum possible value, and $$$L_2=4$$$ is the minimum possible with $$$L_1=2$$$.
Java 8
standard input
[ "hashing", "math" ]
b67870dcffa7bad682ef980dacd1f3db
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — number of input test cases. The first line of each test case contains a string $$$s$$$, which contains only the characters 0-9 and has a length $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$). The second line contains two integers $$$w, m$$$ ($$$1 \le w &lt; n, 1 \le m \le 2 \cdot 10^5$$$), where $$$n$$$ — is the length of the given string $$$s$$$. The number $$$w$$$ denotes the lengths of the substrings being searched for, and $$$m$$$ is the number of queries to be processed. The following $$$m$$$ lines contain integers $$$l_i, r_i, k_i$$$ ($$$1 \le l_i \le r_i \le n$$$, $$$0 \le k_i \le 8$$$) — $$$i$$$th query parameters. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$. It is also guaranteed that the sum of $$$m$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,900
For each request, print in a separate line: left borders of the required substrings: $$$L_1$$$ and $$$L_2$$$; -1 -1 otherwise, if there is no solution. If there are several solutions, minimize $$$L_1$$$ first, and minimize $$$L_2$$$ second.
standard output
PASSED
e0870dc005461de0d271e0b763a86ff6
train_110.jsonl
1662993300
Given the string $$$s$$$ of decimal digits (0-9) of length $$$n$$$.A substring is a sequence of consecutive characters of a string. The substring of this string is defined by a pair of indexes — with its left and right ends. So, each pair of indexes ($$$l, r$$$), where $$$1 \le l \le r \le n$$$, corresponds to a substring of the string $$$s$$$. We will define as $$$v(l,r)$$$ the numeric value of the corresponding substring (leading zeros are allowed in it).For example, if $$$n=7$$$, $$$s=$$$"1003004", then $$$v(1,3)=100$$$, $$$v(2,3)=0$$$ and $$$v(2,7)=3004$$$.You are given $$$n$$$, $$$s$$$ and an integer $$$w$$$ ($$$1 \le w &lt; n$$$).You need to process $$$m$$$ queries, each of which is characterized by $$$3$$$ numbers $$$l_i, r_i, k_i$$$ ($$$1 \le l_i \le r_i \le n; 0 \le k_i \le 8$$$).The answer to the $$$i$$$th query is such a pair of substrings of length $$$w$$$ that if we denote them as $$$(L_1, L_1+w-1)$$$ and $$$(L_2, L_2+w-1)$$$, then: $$$L_1 \ne L_2$$$, that is, the substrings are different; the remainder of dividing a number $$$v(L_1, L_1+w-1) \cdot v(l_i, r_i) + v(L_2, L_2 + w - 1)$$$ by $$$9$$$ is equal to $$$k_i$$$. If there are many matching substring pairs, then find a pair where $$$L_1$$$ is as small as possible. If there are many matching pairs in this case, then minimize $$$L_2$$$.Note that the answer may not exist.
256 megabytes
import java.io.*; import java.util.*; public class p2 { BufferedReader br; StringTokenizer st; BufferedWriter bw; public static void main(String[] args)throws Exception { new p2().run(); } void run()throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); bw=new BufferedWriter(new OutputStreamWriter(System.out)); solve(); } void solve() throws IOException { int t=ni(); while(t-->0) { char c[]=nac(); int n=c.length; int w=ni(); int m=ni(); data2[] d=dataArray2(m); int rem[]=new int[n-w+1]; int x=0; for(int i=-1;++i<w;) x+=c[i]-48; x%=9; rem[0]=x; for(int i=w-1;++i<n;) { x-=c[i-w]-48; x+=c[i]-48; while(x<0) x+=9; while(x>=9) x-=9; rem[i-w+1]=x; } int ans[][]=new int[9][2]; int a1[]=new int[9]; for(int i=-1;++i<n-w+1;) { int y=rem[i]; int ind=a1[y]; if(ind<2) { ans[y][ind]=i+1; a1[y]++; } } int n1=n; int count=0; while(n1>0) { count++; n1/=2; } int sum[][]=new int[count][]; int m1=0; int l=n/2; sum[m1]=new int[l]; for(int j=-1;++j<l;) sum[m1][j]=(c[2*j]+c[2*j+1]-96)%9; // for(int j=-1;++j<l;) // System.out.print(sum[m1][j]+" "); // System.out.println(); m1++; for(int i=-1;++i<count-1;) { l=l/2; sum[m1]=new int[l]; for(int j=-1;++j<l;) sum[m1][j]=(sum[m1-1][2*j]+sum[m1-1][2*j+1])%9; // for(int j=-1;++j<l;) // System.out.print(sum[m1][j]+" "); // System.out.println(); m1++; } // for(int i=-1;++i<n-w+1;) // System.out.print(rem[i]+" "); // System.out.println(); for(int i=-1;++i<m;) { x=0; int y1=d[i].a; int y2=d[i].b; int k=0; int ma=0; if(y1%2==0) ma+=c[y1-1]-48; if(y2%2==1) ma+=c[y2-1]-48; y1=y1/2+1; y2/=2; ma%=9; while(y1<=y2) { if(y1%2==0) ma+=sum[k][y1-1]; if(y2%2==1) ma+=sum[k][y2-1]; ma%=9; // System.out.println("m="+ma); y1=y1/2+1; y2/=2; k++; } // System.out.println("ma="+ma); int j=-1; data[] d1=new data[18]; int d2=0; for(;++j<9;) { int z1=j; int z=j*ma; z%=9; int zz=d[i].k; zz-=z; if(zz<0) zz+=9; int z2=zz; if(z1==z2) { if(a1[z1]>1) d1[d2++]=new data(ans[z1][0], ans[z1][1]); } else { if(a1[z1]>0 && a1[z2]>0) d1[d2++]=new data(ans[z1][0], ans[z2][0]); } } if(d2==0) bw.write("-1 -1\n"); else { Arrays.sort(d1,0,d2, (aa1,b1)-> (aa1.a-b1.a==0)?(aa1.b-aa1.b):(aa1.a-b1.a)); bw.write(d1[0].a+" "+d1[0].b+"\n"); // k=-1; // for(;++k<d2;) // bw.write("=="+d1[k].a+" "+d1[k].b+"\n"); } } } bw.flush(); } /////////////////////////////////////// FOR INPUT /////////////////////////////////////// public static class data2 { int a,b,k; public data2(int a, int b, int x) { this.a=a; this.b=b; k=x; } } public data2[] dataArray2(int n) { data2 d[]=new data2[n]; for(int i=-1;++i<n;) d[i]=new data2(ni(), ni(), ni()); return d; } public static class data { int a,b; public data(int a, int b) { this.a=a; this.b=b; } } public data[] dataArray(int n) { data d[]=new data[n]; for(int i=-1;++i<n;) d[i]=new data(ni(), ni()); return d; } int[] nai(int n) { int a[]=new int[n]; for(int i=-1;++i<n;)a[i]=ni(); return a;} Integer[] naI(int n) { Integer a[]=new Integer[n]; for(int i=-1;++i<n;)a[i]=ni(); return a;} long[] nal(int n) { long a[]=new long[n]; for(int i=-1;++i<n;)a[i]=nl(); return a;} char[] nac() {char c[]=nextLine().toCharArray(); return c;} char [][] nmc(int n) {char c[][]=new char[n][]; for(int i=-1;++i<n;)c[i]=nac(); return c;} int[][] nmi(int r, int c) {int a[][]=new int[r][c]; for(int i=-1;++i<r;)a[i]=nai(c); return a;} String next() { while (st == null || !st.hasMoreElements()) { try {st = new StringTokenizer(br.readLine());} catch (IOException e) {e.printStackTrace();} } return st.nextToken(); } int ni() { return Integer.parseInt(next()); } byte nb() { return Byte.parseByte(next()); } short ns() { return Short.parseShort(next()); } long nl() { return Long.parseLong(next()); } double nd() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try {str = br.readLine();} catch (IOException e) {e.printStackTrace();} return str; } }
Java
["5\n\n1003004\n\n4 1\n\n1 2 1\n\n179572007\n\n4 2\n\n2 7 3\n\n2 7 4\n\n111\n\n2 1\n\n2 2 6\n\n0000\n\n1 2\n\n1 4 0\n\n1 4 1\n\n484\n\n1 5\n\n2 2 0\n\n2 3 7\n\n1 2 5\n\n3 3 8\n\n2 2 6"]
3 seconds
["2 4\n1 5\n1 2\n-1 -1\n1 2\n-1 -1\n1 3\n1 3\n-1 -1\n-1 -1\n-1 -1"]
NoteConsider the first test case of example inputs. In this test case $$$n=7$$$, $$$s=$$$"1003004", $$$w=4$$$ and one query $$$l_1=1$$$, $$$r_1=2$$$, $$$k_1=1$$$. Note that $$$v(1,2)=10$$$. We need to find a pair of substrings of length $$$4$$$ such that $$$v(L_1, L_1+3)\cdot10+v(L_2,L_2+3)$$$ has a remainder of $$$k_1=1$$$ when divided by $$$9$$$. The values $$$L_1=2, L_2=4$$$ actually satisfy all the requirements: $$$v(L_1, L_1+w-1)=v(2,5)=30$$$, $$$v(L_2, L_2+w-1)=v(4,7)=3004$$$. Indeed, $$$30\cdot10+3004=3304$$$, which has a remainder of $$$1$$$ when divided by $$$9$$$. It can be shown that $$$L_1=2$$$ is the minimum possible value, and $$$L_2=4$$$ is the minimum possible with $$$L_1=2$$$.
Java 8
standard input
[ "hashing", "math" ]
b67870dcffa7bad682ef980dacd1f3db
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — number of input test cases. The first line of each test case contains a string $$$s$$$, which contains only the characters 0-9 and has a length $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$). The second line contains two integers $$$w, m$$$ ($$$1 \le w &lt; n, 1 \le m \le 2 \cdot 10^5$$$), where $$$n$$$ — is the length of the given string $$$s$$$. The number $$$w$$$ denotes the lengths of the substrings being searched for, and $$$m$$$ is the number of queries to be processed. The following $$$m$$$ lines contain integers $$$l_i, r_i, k_i$$$ ($$$1 \le l_i \le r_i \le n$$$, $$$0 \le k_i \le 8$$$) — $$$i$$$th query parameters. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$. It is also guaranteed that the sum of $$$m$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,900
For each request, print in a separate line: left borders of the required substrings: $$$L_1$$$ and $$$L_2$$$; -1 -1 otherwise, if there is no solution. If there are several solutions, minimize $$$L_1$$$ first, and minimize $$$L_2$$$ second.
standard output
PASSED
c1d152ff660debf5c85629473e76a229
train_110.jsonl
1662993300
Given the string $$$s$$$ of decimal digits (0-9) of length $$$n$$$.A substring is a sequence of consecutive characters of a string. The substring of this string is defined by a pair of indexes — with its left and right ends. So, each pair of indexes ($$$l, r$$$), where $$$1 \le l \le r \le n$$$, corresponds to a substring of the string $$$s$$$. We will define as $$$v(l,r)$$$ the numeric value of the corresponding substring (leading zeros are allowed in it).For example, if $$$n=7$$$, $$$s=$$$"1003004", then $$$v(1,3)=100$$$, $$$v(2,3)=0$$$ and $$$v(2,7)=3004$$$.You are given $$$n$$$, $$$s$$$ and an integer $$$w$$$ ($$$1 \le w &lt; n$$$).You need to process $$$m$$$ queries, each of which is characterized by $$$3$$$ numbers $$$l_i, r_i, k_i$$$ ($$$1 \le l_i \le r_i \le n; 0 \le k_i \le 8$$$).The answer to the $$$i$$$th query is such a pair of substrings of length $$$w$$$ that if we denote them as $$$(L_1, L_1+w-1)$$$ and $$$(L_2, L_2+w-1)$$$, then: $$$L_1 \ne L_2$$$, that is, the substrings are different; the remainder of dividing a number $$$v(L_1, L_1+w-1) \cdot v(l_i, r_i) + v(L_2, L_2 + w - 1)$$$ by $$$9$$$ is equal to $$$k_i$$$. If there are many matching substring pairs, then find a pair where $$$L_1$$$ is as small as possible. If there are many matching pairs in this case, then minimize $$$L_2$$$.Note that the answer may not exist.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.PriorityQueue; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.TreeSet; public class F { static ArrayList<Integer>adj[]; static int[]vis; public static void main(String[]args) throws IOException { Scanner sc=new Scanner(System.in); PrintWriter out=new PrintWriter(System.out); int t=sc.nextInt(); a:while(t-->0) { char []c=sc.next().toCharArray(); int[]sums=new int[c.length]; sums[0]=(c[0]-'0')%9; for(int i=1;i<c.length;i++) { int cur=(c[i]-'0')%9; sums[i]=cur+sums[i-1]; sums[i]%=9; } int w=sc.nextInt(),m=sc.nextInt(); ArrayList<Integer>arr[]=new ArrayList[9]; for(int i=0;i<arr.length;i++)arr[i]=new ArrayList<Integer>(); arr[sums[w-1]].add(0); for(int i=w;i<c.length;i++) { int x=sums[i]-sums[i-w]; if(x<0)x+=9; if(arr[x].size()<2) arr[x].add(i-w+1); } while(m-->0) { int l=sc.nextInt()-1,r=sc.nextInt()-1,k=sc.nextInt(); int s=sums[r]-(l==0?0:sums[l-1]); if(s<0)s+=9; int[]ans=new int[] {c.length,c.length}; for(int i=0;i<9;i++) { for(int j=0;j<9;j++) { if(i==j) { if(arr[i].size()>=2&& valid(i,s,j,k)){ ans=mn(ans,new int[] {arr[i].get(0),arr[i].get(1)}); ans=mn(ans,new int[] {arr[i].get(1),arr[i].get(0)}); } }else { if(arr[i].size()>0&&arr[j].size()>0&&valid(i,s,j,k)) { ans=mn(ans,new int[] {arr[i].get(0),arr[j].get(0)}); // ans=mn(ans,new int[] {arr[j].get(0),arr[i].get(0)}); } } } } if(ans[0]==c.length)out.println("-1 -1"); else out.println((ans[0]+1)+" "+(ans[1]+1)); } } out.close(); } private static int[] mn(int[] ans, int[] is) { if(ans[0]<is[0])return ans; if(is[0]<ans[0])return is; return ans[1]<is[1]?ans:is; } private static boolean valid(int i, int s, int j, int k) { return (i*s+j)%9 == k; } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));} public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public boolean hasNext() {return st.hasMoreTokens();} public int nextInt() throws IOException {return Integer.parseInt(next());} public double nextDouble() throws IOException {return Double.parseDouble(next());} public long nextLong() throws IOException {return Long.parseLong(next());} public String nextLine() throws IOException {return br.readLine();} public boolean ready() throws IOException {return br.ready(); } } }
Java
["5\n\n1003004\n\n4 1\n\n1 2 1\n\n179572007\n\n4 2\n\n2 7 3\n\n2 7 4\n\n111\n\n2 1\n\n2 2 6\n\n0000\n\n1 2\n\n1 4 0\n\n1 4 1\n\n484\n\n1 5\n\n2 2 0\n\n2 3 7\n\n1 2 5\n\n3 3 8\n\n2 2 6"]
3 seconds
["2 4\n1 5\n1 2\n-1 -1\n1 2\n-1 -1\n1 3\n1 3\n-1 -1\n-1 -1\n-1 -1"]
NoteConsider the first test case of example inputs. In this test case $$$n=7$$$, $$$s=$$$"1003004", $$$w=4$$$ and one query $$$l_1=1$$$, $$$r_1=2$$$, $$$k_1=1$$$. Note that $$$v(1,2)=10$$$. We need to find a pair of substrings of length $$$4$$$ such that $$$v(L_1, L_1+3)\cdot10+v(L_2,L_2+3)$$$ has a remainder of $$$k_1=1$$$ when divided by $$$9$$$. The values $$$L_1=2, L_2=4$$$ actually satisfy all the requirements: $$$v(L_1, L_1+w-1)=v(2,5)=30$$$, $$$v(L_2, L_2+w-1)=v(4,7)=3004$$$. Indeed, $$$30\cdot10+3004=3304$$$, which has a remainder of $$$1$$$ when divided by $$$9$$$. It can be shown that $$$L_1=2$$$ is the minimum possible value, and $$$L_2=4$$$ is the minimum possible with $$$L_1=2$$$.
Java 8
standard input
[ "hashing", "math" ]
b67870dcffa7bad682ef980dacd1f3db
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — number of input test cases. The first line of each test case contains a string $$$s$$$, which contains only the characters 0-9 and has a length $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$). The second line contains two integers $$$w, m$$$ ($$$1 \le w &lt; n, 1 \le m \le 2 \cdot 10^5$$$), where $$$n$$$ — is the length of the given string $$$s$$$. The number $$$w$$$ denotes the lengths of the substrings being searched for, and $$$m$$$ is the number of queries to be processed. The following $$$m$$$ lines contain integers $$$l_i, r_i, k_i$$$ ($$$1 \le l_i \le r_i \le n$$$, $$$0 \le k_i \le 8$$$) — $$$i$$$th query parameters. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$. It is also guaranteed that the sum of $$$m$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,900
For each request, print in a separate line: left borders of the required substrings: $$$L_1$$$ and $$$L_2$$$; -1 -1 otherwise, if there is no solution. If there are several solutions, minimize $$$L_1$$$ first, and minimize $$$L_2$$$ second.
standard output
PASSED
2410bfbf08cf3b441d49caa0b86253c4
train_110.jsonl
1662993300
Given the string $$$s$$$ of decimal digits (0-9) of length $$$n$$$.A substring is a sequence of consecutive characters of a string. The substring of this string is defined by a pair of indexes — with its left and right ends. So, each pair of indexes ($$$l, r$$$), where $$$1 \le l \le r \le n$$$, corresponds to a substring of the string $$$s$$$. We will define as $$$v(l,r)$$$ the numeric value of the corresponding substring (leading zeros are allowed in it).For example, if $$$n=7$$$, $$$s=$$$"1003004", then $$$v(1,3)=100$$$, $$$v(2,3)=0$$$ and $$$v(2,7)=3004$$$.You are given $$$n$$$, $$$s$$$ and an integer $$$w$$$ ($$$1 \le w &lt; n$$$).You need to process $$$m$$$ queries, each of which is characterized by $$$3$$$ numbers $$$l_i, r_i, k_i$$$ ($$$1 \le l_i \le r_i \le n; 0 \le k_i \le 8$$$).The answer to the $$$i$$$th query is such a pair of substrings of length $$$w$$$ that if we denote them as $$$(L_1, L_1+w-1)$$$ and $$$(L_2, L_2+w-1)$$$, then: $$$L_1 \ne L_2$$$, that is, the substrings are different; the remainder of dividing a number $$$v(L_1, L_1+w-1) \cdot v(l_i, r_i) + v(L_2, L_2 + w - 1)$$$ by $$$9$$$ is equal to $$$k_i$$$. If there are many matching substring pairs, then find a pair where $$$L_1$$$ is as small as possible. If there are many matching pairs in this case, then minimize $$$L_2$$$.Note that the answer may not exist.
256 megabytes
import java.io.*; import java.util.*; public class MainClass { public static long mod = 1000_000_000 + 7; public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); int testCases = in.nextInt(); while (testCases-- > 0) { String s = in.next(); int n = s.length(); int w = in.nextInt(); int m = in.nextInt(); Map<Integer, List<Integer>> remVsL1 = new HashMap<>(); List<Integer> list = new ArrayList<>(); list.add(0); int curr = 0; for (int i = 1; i <= n; i++) { curr = (curr + (s.charAt(i - 1) - '0') + 9) % 9; if (i - w >= 0) { int x = list.get(i - w); int rem = (curr - x + 9) % 9; remVsL1.putIfAbsent(rem, new ArrayList<>()); remVsL1.get(rem).add(i - w + 1); } list.add(curr); } for (int i = 0; i < m; i++) { int l = in.nextInt(); int r = in.nextInt(); int k = in.nextInt(); long l1 = Integer.MAX_VALUE; long l2 = Integer.MAX_VALUE; int vlr = (list.get(r) - list.get(l - 1) + 9) % 9; for (int j = 0; j < 9; j++) { if (!remVsL1.containsKey(j)) { continue; } for (int o = 0; o < 9; o++) { if (!remVsL1.containsKey(o)) { continue; } if ((j * vlr) % 9 == (k - o + 9) % 9) { if (j == o && remVsL1.get(j).size() >= 2) { int x = remVsL1.get(j).get(0); int y = remVsL1.get(j).get(1); if (l1 > x) { l1 = x; l2 = y; } else if (l1 == x) { l2 = Math.min(l2, y); } } else if (j != o) { int x = remVsL1.get(j).get(0); int y = remVsL1.get(o).get(0); if (l1 > x) { l1 = x; l2 = y; } else if (l1 == x) { l2 = Math.min(l2, y); } } } } } if (l1 == Integer.MAX_VALUE) { l1 = -1; l2 = -1; } out.println(l1 + " " + l2); } } out.close(); } static class DisjointUnionSets { int[] rank, parent; int n; public DisjointUnionSets(int n) { rank = new int[n]; parent = new int[n]; this.n = n; makeSet(); } void makeSet() { for (int i = 0; i < n; i++) { rank[i] = 1; parent[i] = i; } } int find(int x) { if (parent[x] != x) { parent[x] = find(parent[x]); } return parent[x]; } int getRank(int x) { return rank[find(x)]; } void union(int x, int y) { int xRoot = find(x), yRoot = find(y); if (xRoot == yRoot) return; if (rank[xRoot] < rank[yRoot]) { parent[xRoot] = yRoot; rank[yRoot] = rank[xRoot] + rank[yRoot]; } else { parent[yRoot] = xRoot; rank[xRoot] = rank[xRoot] + rank[yRoot]; } } } public static int gcd(int a, int b) { if (b == 0) return a; else if (a == 0) return b; else if (b < a) return gcd(b, a % b); return gcd(a % b, b); } public static long maxNum(long... x) { long ans = -9223372036854775808L; for (long p : x) { ans = Math.max(p, ans); } return ans; } public static int maxNum(int... x) { int ans = -2147483648; for (int p : x) { ans = Math.max(p, ans); } return ans; } public static long modPower(long x, long m, long mod) { long ans = 1; while (m > 0) { if (m % 2 == 1) { ans = (ans * x) % mod; } x = (x * x) % mod; m = m / 2; } return ans; } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } public static class Pair<K extends Comparable<K>, V extends Comparable<V>> implements Comparable<Pair<K, V>> { private K p1; private V p2; public Pair(K p1, V p2) { this.p1 = p1; this.p2 = p2; } public K getP1() { return p1; } public void setP1(K p1) { this.p1 = p1; } public V getP2() { return p2; } public void setP2(V p2) { this.p2 = p2; } @Override public int compareTo(Pair<K, V> o) { if (p1.compareTo(o.getP1()) == 0) { return p2.compareTo(o.getP2()); } return p1.compareTo(o.getP1()); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Pair<?, ?> pair = (Pair<?, ?>) o; return Objects.equals(p1, pair.p1) && Objects.equals(p2, pair.p2); } @Override public int hashCode() { return Objects.hash(p1, p2); } } static <T extends Comparable<T>> int lowerbound(List<T> arr, T element) { int size = arr.size(); if (element.compareTo(arr.get(size - 1)) >= 0) return -1; if (element.compareTo(arr.get(0)) < 0) return 0; int low = 0; int high = size - 1; while (low < high) { int mid = (low + high) / 2; if (element.compareTo(arr.get(mid)) >= 0) { low = mid + 1; } else { high = mid; } } return low; } // static classes for segment tree public static class SegmentTree { private SegmentTreeNode head; public SegmentTree(int start, int end) { head = new SegmentTreeNode(start, end); } public SegmentTreeNode getHead() { return head; } public void setHead(SegmentTreeNode head) { this.head = head; } } public static class SegmentTreeNode { private int start; private int end; private SegmentTreeNode leftChildNode; private SegmentTreeNode rightChildNode; private long value; private List<SegmentTreeUpdateObject> pendingUpdates = new ArrayList<>(); public SegmentTreeNode(int start, int end) { this.start = start; this.end = end; if (end - start >= 1) { int middle = start + (end - start) / 2; leftChildNode = new SegmentTreeNode(start, middle); rightChildNode = new SegmentTreeNode(middle + 1, end); } } public SegmentTreeNode getLeftChildNode() { return leftChildNode; } public void setLeftChildNode(SegmentTreeNode leftChildNode) { this.leftChildNode = leftChildNode; } public SegmentTreeNode getRightChildNode() { return rightChildNode; } public void setRightChildNode(SegmentTreeNode rightChildNode) { this.rightChildNode = rightChildNode; } public long getValue() { return value; } public void setValue(long value) { this.value = value; } public List<SegmentTreeUpdateObject> getPendingUpdates() { return pendingUpdates; } public void addPendingUpdates(SegmentTreeUpdateObject pendingUpdate) { pendingUpdate.applyUpdate(this); this.pendingUpdates.add(pendingUpdate); } public int getStart() { return start; } public void setStart(int start) { this.start = start; } public int getEnd() { return end; } public void setEnd(int end) { this.end = end; } public void updateChildren() { for (SegmentTreeUpdateObject updateObject : pendingUpdates) { if (updateObject.shouldApply(leftChildNode)) { leftChildNode.addPendingUpdates(updateObject.getNewInstance(leftChildNode.getStart(), leftChildNode.getEnd())); } } for (SegmentTreeUpdateObject updateObject : pendingUpdates) { if (updateObject.shouldApply(rightChildNode)) { rightChildNode.addPendingUpdates(updateObject.getNewInstance(rightChildNode.getStart(), rightChildNode.getEnd())); } } pendingUpdates = new ArrayList<>(); } public long query(int start, int end) { if (start == this.getStart() && end == this.getEnd()) { return value; } else { long ans = 0; this.updateChildren(); if (start <= leftChildNode.getEnd()) { ans += leftChildNode.query(start, Math.min(end, leftChildNode.getEnd())); } if (end >= rightChildNode.getStart()) { ans += rightChildNode.query(Math.max(rightChildNode.getStart(), start), end); } return ans; } } } // change as per need public static class SegmentTreeUpdateObject { private int start; private int end; private int startValue; private long value; public int getStart() { return start; } public void setStart(int start) { this.start = start; } public int getEnd() { return end; } public void setEnd(int end) { this.end = end; } public long getValue() { return value; } public void setValue(long value) { this.value = value; } public int getStartValue() { return startValue; } public void setStartValue(int startValue) { this.startValue = startValue; } public void applyUpdate(SegmentTreeNode node) { node.setValue(node.getValue() + this.value); } public boolean shouldApply(SegmentTreeNode node) { int currentStart = this.getStart(); int currentEnd = this.getEnd(); int tmpStart = Math.max(node.getStart(), currentStart); int tmpEnd = Math.min(node.getEnd(), currentEnd); return tmpStart <= tmpEnd; } public SegmentTreeUpdateObject getNewInstance(int start, int end) { int currentStart = this.getStart(); int currentEnd = this.getEnd(); int currentStartValue = this.getStartValue(); long currentValue; if (start > currentStart) { currentStartValue += (start - currentStart); } start = Math.max(start, currentStart); end = Math.min(end, currentEnd); if (start > end) { return null; } currentValue = ((long) (end - start + 2) * (end - start + 1)) / 2 + (long) (currentStartValue - 1) * (end - start + 1); SegmentTreeUpdateObject segmentTreeUpdateObjectTemp = new SegmentTreeUpdateObject(); segmentTreeUpdateObjectTemp.setEnd(end); segmentTreeUpdateObjectTemp.setStart(start); segmentTreeUpdateObjectTemp.setValue(currentValue); segmentTreeUpdateObjectTemp.setStartValue(currentStartValue); return segmentTreeUpdateObjectTemp; } @Override public String toString() { return "SegmentTreeUpdateObject{" + "start=" + start + ", end=" + end + ", startValue=" + startValue + ", value=" + value + '}'; } } }
Java
["5\n\n1003004\n\n4 1\n\n1 2 1\n\n179572007\n\n4 2\n\n2 7 3\n\n2 7 4\n\n111\n\n2 1\n\n2 2 6\n\n0000\n\n1 2\n\n1 4 0\n\n1 4 1\n\n484\n\n1 5\n\n2 2 0\n\n2 3 7\n\n1 2 5\n\n3 3 8\n\n2 2 6"]
3 seconds
["2 4\n1 5\n1 2\n-1 -1\n1 2\n-1 -1\n1 3\n1 3\n-1 -1\n-1 -1\n-1 -1"]
NoteConsider the first test case of example inputs. In this test case $$$n=7$$$, $$$s=$$$"1003004", $$$w=4$$$ and one query $$$l_1=1$$$, $$$r_1=2$$$, $$$k_1=1$$$. Note that $$$v(1,2)=10$$$. We need to find a pair of substrings of length $$$4$$$ such that $$$v(L_1, L_1+3)\cdot10+v(L_2,L_2+3)$$$ has a remainder of $$$k_1=1$$$ when divided by $$$9$$$. The values $$$L_1=2, L_2=4$$$ actually satisfy all the requirements: $$$v(L_1, L_1+w-1)=v(2,5)=30$$$, $$$v(L_2, L_2+w-1)=v(4,7)=3004$$$. Indeed, $$$30\cdot10+3004=3304$$$, which has a remainder of $$$1$$$ when divided by $$$9$$$. It can be shown that $$$L_1=2$$$ is the minimum possible value, and $$$L_2=4$$$ is the minimum possible with $$$L_1=2$$$.
Java 8
standard input
[ "hashing", "math" ]
b67870dcffa7bad682ef980dacd1f3db
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — number of input test cases. The first line of each test case contains a string $$$s$$$, which contains only the characters 0-9 and has a length $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$). The second line contains two integers $$$w, m$$$ ($$$1 \le w &lt; n, 1 \le m \le 2 \cdot 10^5$$$), where $$$n$$$ — is the length of the given string $$$s$$$. The number $$$w$$$ denotes the lengths of the substrings being searched for, and $$$m$$$ is the number of queries to be processed. The following $$$m$$$ lines contain integers $$$l_i, r_i, k_i$$$ ($$$1 \le l_i \le r_i \le n$$$, $$$0 \le k_i \le 8$$$) — $$$i$$$th query parameters. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$. It is also guaranteed that the sum of $$$m$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,900
For each request, print in a separate line: left borders of the required substrings: $$$L_1$$$ and $$$L_2$$$; -1 -1 otherwise, if there is no solution. If there are several solutions, minimize $$$L_1$$$ first, and minimize $$$L_2$$$ second.
standard output
PASSED
6f41f01fcdc3b960e0fc4b6c4fe79daa
train_110.jsonl
1662993300
Given the string $$$s$$$ of decimal digits (0-9) of length $$$n$$$.A substring is a sequence of consecutive characters of a string. The substring of this string is defined by a pair of indexes — with its left and right ends. So, each pair of indexes ($$$l, r$$$), where $$$1 \le l \le r \le n$$$, corresponds to a substring of the string $$$s$$$. We will define as $$$v(l,r)$$$ the numeric value of the corresponding substring (leading zeros are allowed in it).For example, if $$$n=7$$$, $$$s=$$$"1003004", then $$$v(1,3)=100$$$, $$$v(2,3)=0$$$ and $$$v(2,7)=3004$$$.You are given $$$n$$$, $$$s$$$ and an integer $$$w$$$ ($$$1 \le w &lt; n$$$).You need to process $$$m$$$ queries, each of which is characterized by $$$3$$$ numbers $$$l_i, r_i, k_i$$$ ($$$1 \le l_i \le r_i \le n; 0 \le k_i \le 8$$$).The answer to the $$$i$$$th query is such a pair of substrings of length $$$w$$$ that if we denote them as $$$(L_1, L_1+w-1)$$$ and $$$(L_2, L_2+w-1)$$$, then: $$$L_1 \ne L_2$$$, that is, the substrings are different; the remainder of dividing a number $$$v(L_1, L_1+w-1) \cdot v(l_i, r_i) + v(L_2, L_2 + w - 1)$$$ by $$$9$$$ is equal to $$$k_i$$$. If there are many matching substring pairs, then find a pair where $$$L_1$$$ is as small as possible. If there are many matching pairs in this case, then minimize $$$L_2$$$.Note that the answer may not exist.
256 megabytes
import java.util.*; public class F { static int[] cumsum; public static void main(String args[]) { Scanner scan = new Scanner(System.in); int T = scan.nextInt(); for (int ca=1;ca <= T;ca++) { String str = scan.next(); int n = str.length(); int[] a = new int[n]; int w = scan.nextInt(); int m = scan.nextInt(); for (int i=0;i < n;i++) { a[i] = str.charAt(i) - '0'; } cumsum = new int[n]; cumsum[0] = a[0] % 9; for (int i=1;i < n;i++) { cumsum[i] = (cumsum[i-1] + a[i]) % 9; } ArrayList<Integer>[] al = new ArrayList[9]; for (int i=0;i < al.length;i++) al[i] = new ArrayList<Integer>(); for (int i=0;i + w - 1 < n;i++) { int val = v(i, i+w-1); al[val].add(i + 1); } // Handle queries for (int q=0;q< m;q++) { int l = scan.nextInt(); int r = scan.nextInt(); int k = scan.nextInt(); int val = v(l-1, r-1); int L1 = 999999999; int L2 = 999999999; for (int v1=0;v1 <= 8;v1++) { for (int v2=0;v2 <= 8;v2++) { if ((v1 * val + v2) % 9 != k) continue; // Do we have such a v1 and v2? if (v1 == v2 && al[v1].size() >= 2) { int tmpL1 = al[v1].get(0); int tmpL2 = al[v1].get(1); if (tmpL1 < L1 || (tmpL1 == L1 && tmpL2 < L2)) { L1 = tmpL1; L2 = tmpL2; } } else if (v1 != v2 && al[v1].size() > 0 && al[v2].size() > 0) { int tmpL1 = al[v1].get(0); int tmpL2 = al[v2].get(0); if (tmpL1 < L1 || (tmpL1 == L1 && tmpL2 < L2)) { L1 = tmpL1; L2 = tmpL2; } } } } if (L1 == 999999999) L1 = -1; if (L2 == 999999999) L2 = -1; System.out.println(L1 + " " + L2); } } } // Inclusive public static int v(int l, int r) { if (l == 0) return cumsum[r]; return (cumsum[r] - cumsum[l-1] + 9) % 9; } }
Java
["5\n\n1003004\n\n4 1\n\n1 2 1\n\n179572007\n\n4 2\n\n2 7 3\n\n2 7 4\n\n111\n\n2 1\n\n2 2 6\n\n0000\n\n1 2\n\n1 4 0\n\n1 4 1\n\n484\n\n1 5\n\n2 2 0\n\n2 3 7\n\n1 2 5\n\n3 3 8\n\n2 2 6"]
3 seconds
["2 4\n1 5\n1 2\n-1 -1\n1 2\n-1 -1\n1 3\n1 3\n-1 -1\n-1 -1\n-1 -1"]
NoteConsider the first test case of example inputs. In this test case $$$n=7$$$, $$$s=$$$"1003004", $$$w=4$$$ and one query $$$l_1=1$$$, $$$r_1=2$$$, $$$k_1=1$$$. Note that $$$v(1,2)=10$$$. We need to find a pair of substrings of length $$$4$$$ such that $$$v(L_1, L_1+3)\cdot10+v(L_2,L_2+3)$$$ has a remainder of $$$k_1=1$$$ when divided by $$$9$$$. The values $$$L_1=2, L_2=4$$$ actually satisfy all the requirements: $$$v(L_1, L_1+w-1)=v(2,5)=30$$$, $$$v(L_2, L_2+w-1)=v(4,7)=3004$$$. Indeed, $$$30\cdot10+3004=3304$$$, which has a remainder of $$$1$$$ when divided by $$$9$$$. It can be shown that $$$L_1=2$$$ is the minimum possible value, and $$$L_2=4$$$ is the minimum possible with $$$L_1=2$$$.
Java 8
standard input
[ "hashing", "math" ]
b67870dcffa7bad682ef980dacd1f3db
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — number of input test cases. The first line of each test case contains a string $$$s$$$, which contains only the characters 0-9 and has a length $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$). The second line contains two integers $$$w, m$$$ ($$$1 \le w &lt; n, 1 \le m \le 2 \cdot 10^5$$$), where $$$n$$$ — is the length of the given string $$$s$$$. The number $$$w$$$ denotes the lengths of the substrings being searched for, and $$$m$$$ is the number of queries to be processed. The following $$$m$$$ lines contain integers $$$l_i, r_i, k_i$$$ ($$$1 \le l_i \le r_i \le n$$$, $$$0 \le k_i \le 8$$$) — $$$i$$$th query parameters. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$. It is also guaranteed that the sum of $$$m$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,900
For each request, print in a separate line: left borders of the required substrings: $$$L_1$$$ and $$$L_2$$$; -1 -1 otherwise, if there is no solution. If there are several solutions, minimize $$$L_1$$$ first, and minimize $$$L_2$$$ second.
standard output
PASSED
dd242f23eae73fe659b7aa87bbff52e4
train_110.jsonl
1662993300
Given the string $$$s$$$ of decimal digits (0-9) of length $$$n$$$.A substring is a sequence of consecutive characters of a string. The substring of this string is defined by a pair of indexes — with its left and right ends. So, each pair of indexes ($$$l, r$$$), where $$$1 \le l \le r \le n$$$, corresponds to a substring of the string $$$s$$$. We will define as $$$v(l,r)$$$ the numeric value of the corresponding substring (leading zeros are allowed in it).For example, if $$$n=7$$$, $$$s=$$$"1003004", then $$$v(1,3)=100$$$, $$$v(2,3)=0$$$ and $$$v(2,7)=3004$$$.You are given $$$n$$$, $$$s$$$ and an integer $$$w$$$ ($$$1 \le w &lt; n$$$).You need to process $$$m$$$ queries, each of which is characterized by $$$3$$$ numbers $$$l_i, r_i, k_i$$$ ($$$1 \le l_i \le r_i \le n; 0 \le k_i \le 8$$$).The answer to the $$$i$$$th query is such a pair of substrings of length $$$w$$$ that if we denote them as $$$(L_1, L_1+w-1)$$$ and $$$(L_2, L_2+w-1)$$$, then: $$$L_1 \ne L_2$$$, that is, the substrings are different; the remainder of dividing a number $$$v(L_1, L_1+w-1) \cdot v(l_i, r_i) + v(L_2, L_2 + w - 1)$$$ by $$$9$$$ is equal to $$$k_i$$$. If there are many matching substring pairs, then find a pair where $$$L_1$$$ is as small as possible. If there are many matching pairs in this case, then minimize $$$L_2$$$.Note that the answer may not exist.
256 megabytes
import java.io.*; import java.util.*; public class CodeForces { /*-------------------------------------------EDITING CODE STARTS HERE-------------------------------------------*/ static class SegTree{ int [] segTree; public SegTree(int n ,char[] arr){ segTree = new int[n*4]; build(0,n-1,0,arr); } private void build(int stL, int stR, int stI, char[] arr){ if(stL == stR){ segTree[stI] = (arr[stL] - '0'); return; } int mid = (stL+stR)/2; build(stL,mid,2*stI+1,arr); build(mid+1,stR,2*stI+2,arr); segTree[stI] = (segTree[2*stI+1] + segTree[2*stI+2]) % 9; } private int get(int stL, int stR, int stI,int qL, int qR){ if(qL > stR || qR < stL)return 0; if(qL <= stL && qR >= stR)return segTree[stI]; int mid = (stL+stR)/2; return ( get(stL,mid,2*stI+1,qL,qR) + get(mid+1,stR,2*stI+2,qL,qR)) % 9; } } public static void solve(int tCase) throws IOException { char[] str = sc.next().toCharArray(); int n =str.length; int w =sc.nextInt(); List<Integer> [] remainer =new ArrayList[9]; for(int i=0;i<9;i++)remainer[i] = new ArrayList<>(); SegTree segTree = new SegTree(n,str); for(int i=0;i<=n-w;i++){ int rem = segTree.get(0,n-1,0,i,i+w-1); if(remainer[rem].size() < 2)remainer[rem].add(i); // out.println(rem+" "+i+" "+(i+w-1)); } // out.println(Arrays.toString(remStart)); int q = sc.nextInt(); for(int i=0;i<q;i++){ int l = sc.nextInt()-1; int r = sc.nextInt()-1; int k = sc.nextInt(); int l1 = n*10; int l2 = n*10; int yoo = segTree.get(0,n-1,0,l,r); for(int rF = 0;rF < 9;rF ++){ if(remainer[rF].size() == 0)continue; for(int rS = 0;rS < 9; rS ++){ if(remainer[rS].size() == 0)continue; int rem = (rF*yoo + rS) % 9; if(rem == k){ int ll1 = remainer[rF].get(0); int ll2 = remainer[rS].get(0); if(ll1 == ll2){ if(remainer[rS].size() < 2)continue; ll2 = remainer[rS].get(1); } if(ll1 < l1){ l1 = ll1; l2 = ll2; } } } } if(l1 < n && l2 < n){ out.println((l1+1)+" "+(l2+1)); }else out.println("-1 -1"); } } public static void main(String[] args) throws IOException { openIO(); int testCase = 1; testCase = sc.nextInt(); for (int i = 1; i <= testCase; i++) solve(i); closeIO(); } /*-------------------------------------------EDITING CODE ENDS HERE-------------------------------------------*/ /*--------------------------------------HELPER FUNCTIONS STARTS HERE-----------------------------------------*/ public static int mod = (int) 1e9 + 7; // public static int mod = 998244353; public static int inf_int = (int)1e9; public static long inf_long = (long)2e15; public static void _sort(int[] arr, boolean isAscending) { int n = arr.length; List<Integer> list = new ArrayList<>(); for (int ele : arr) list.add(ele); Collections.sort(list); if (!isAscending) Collections.reverse(list); for (int i = 0; i < n; i++) arr[i] = list.get(i); } public static void _sort(long[] arr, boolean isAscending) { int n = arr.length; List<Long> list = new ArrayList<>(); for (long ele : arr) list.add(ele); Collections.sort(list); if (!isAscending) Collections.reverse(list); for (int i = 0; i < n; i++) arr[i] = list.get(i); } // time : O(1), space : O(1) public static int _digitCount(long num,int base){ // this will give the # of digits needed for a number num in format : base return (int)(1 + Math.log(num)/Math.log(base)); } // time for pre-computation of factorial and inverse-factorial table : O(nlog(mod)) public static long[] factorial , inverseFact; public static void _ncr_precompute(int n){ factorial = new long[n+1]; inverseFact = new long[n+1]; factorial[0] = inverseFact[0] = 1; for (int i = 1; i <=n; i++) { factorial[i] = (factorial[i - 1] * i) % mod; inverseFact[i] = _modExpo(factorial[i], mod - 2); } } // time of factorial calculation after pre-computation is O(1) public static int _ncr(int n,int r){ if(r > n)return 0; return (int)(factorial[n] * inverseFact[r] % mod * inverseFact[n - r] % mod); } public static int _npr(int n,int r){ if(r > n)return 0; return (int)(factorial[n] * inverseFact[n - r] % mod); } // euclidean algorithm time O(max (loga ,logb)) public static long _gcd(long a, long b) { while (a>0){ long x = a; a = b % a; b = x; } return b; } // lcm(a,b) * gcd(a,b) = a * b public static long _lcm(long a, long b) { return (a / _gcd(a, b)) * b; } // binary exponentiation time O(logn) public static long _modExpo(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; } // function to find a/b under modulo mod. time : O(logn) public static long _modInv(long a,long b){ return (a * _modExpo(b,mod-2)) % mod; } //sieve or 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) if(firstDivisor[j]==j)firstDivisor[j] = i; return firstDivisor; } static class Pair<K, V>{ K ff; V ss; public Pair(K ff, V ss) { this.ff = ff; this.ss = ss; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || this.getClass() != o.getClass()) return false; Pair<?, ?> pair = (Pair<?, ?>) o; return ff.equals(pair.ff) && ss.equals(pair.ss); } @Override public int hashCode() { return Objects.hash(ff, ss); } @Override public String toString(){ return ff.toString()+" "+ss.toString(); } } /*--------------------------------------HELPER FUNCTIONS ENDS HERE-----------------------------------------*/ /*-------------------------------------------FAST INPUT STARTS HERE---------------------------------------------*/ static FastestReader sc; static PrintWriter out; private static void openIO() throws IOException { sc = new FastestReader(); out = new PrintWriter(System.out); } 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'); return neg?-ret: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'); return neg?-ret: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); return neg?-ret:ret; } public String nextLine() throws IOException { final byte[] buf = new byte[(1<<10)]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') { break; } buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } 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 ---------------------------------------------*/ } /** Some points to keep in mind : * 1. don't use Arrays.sort(primitive data type array) * 2. try to make the parameters of a recursive function as less as possible, * more use static variables. * 3. If n = 5000, then O(n^2 logn) need atleast 4 sec to work * 4. dp[2][n] works faster than dp[n][2] * 5. if split wrt 1 char use '\\' before char: .split("\\."); * 6. check proper data types, like take long if n <=1e18; * **/
Java
["5\n\n1003004\n\n4 1\n\n1 2 1\n\n179572007\n\n4 2\n\n2 7 3\n\n2 7 4\n\n111\n\n2 1\n\n2 2 6\n\n0000\n\n1 2\n\n1 4 0\n\n1 4 1\n\n484\n\n1 5\n\n2 2 0\n\n2 3 7\n\n1 2 5\n\n3 3 8\n\n2 2 6"]
3 seconds
["2 4\n1 5\n1 2\n-1 -1\n1 2\n-1 -1\n1 3\n1 3\n-1 -1\n-1 -1\n-1 -1"]
NoteConsider the first test case of example inputs. In this test case $$$n=7$$$, $$$s=$$$"1003004", $$$w=4$$$ and one query $$$l_1=1$$$, $$$r_1=2$$$, $$$k_1=1$$$. Note that $$$v(1,2)=10$$$. We need to find a pair of substrings of length $$$4$$$ such that $$$v(L_1, L_1+3)\cdot10+v(L_2,L_2+3)$$$ has a remainder of $$$k_1=1$$$ when divided by $$$9$$$. The values $$$L_1=2, L_2=4$$$ actually satisfy all the requirements: $$$v(L_1, L_1+w-1)=v(2,5)=30$$$, $$$v(L_2, L_2+w-1)=v(4,7)=3004$$$. Indeed, $$$30\cdot10+3004=3304$$$, which has a remainder of $$$1$$$ when divided by $$$9$$$. It can be shown that $$$L_1=2$$$ is the minimum possible value, and $$$L_2=4$$$ is the minimum possible with $$$L_1=2$$$.
Java 8
standard input
[ "hashing", "math" ]
b67870dcffa7bad682ef980dacd1f3db
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — number of input test cases. The first line of each test case contains a string $$$s$$$, which contains only the characters 0-9 and has a length $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$). The second line contains two integers $$$w, m$$$ ($$$1 \le w &lt; n, 1 \le m \le 2 \cdot 10^5$$$), where $$$n$$$ — is the length of the given string $$$s$$$. The number $$$w$$$ denotes the lengths of the substrings being searched for, and $$$m$$$ is the number of queries to be processed. The following $$$m$$$ lines contain integers $$$l_i, r_i, k_i$$$ ($$$1 \le l_i \le r_i \le n$$$, $$$0 \le k_i \le 8$$$) — $$$i$$$th query parameters. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$. It is also guaranteed that the sum of $$$m$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,900
For each request, print in a separate line: left borders of the required substrings: $$$L_1$$$ and $$$L_2$$$; -1 -1 otherwise, if there is no solution. If there are several solutions, minimize $$$L_1$$$ first, and minimize $$$L_2$$$ second.
standard output
PASSED
e456b5566dcc13f3a8b7f4c11a0eba7d
train_110.jsonl
1662993300
Given the string $$$s$$$ of decimal digits (0-9) of length $$$n$$$.A substring is a sequence of consecutive characters of a string. The substring of this string is defined by a pair of indexes — with its left and right ends. So, each pair of indexes ($$$l, r$$$), where $$$1 \le l \le r \le n$$$, corresponds to a substring of the string $$$s$$$. We will define as $$$v(l,r)$$$ the numeric value of the corresponding substring (leading zeros are allowed in it).For example, if $$$n=7$$$, $$$s=$$$"1003004", then $$$v(1,3)=100$$$, $$$v(2,3)=0$$$ and $$$v(2,7)=3004$$$.You are given $$$n$$$, $$$s$$$ and an integer $$$w$$$ ($$$1 \le w &lt; n$$$).You need to process $$$m$$$ queries, each of which is characterized by $$$3$$$ numbers $$$l_i, r_i, k_i$$$ ($$$1 \le l_i \le r_i \le n; 0 \le k_i \le 8$$$).The answer to the $$$i$$$th query is such a pair of substrings of length $$$w$$$ that if we denote them as $$$(L_1, L_1+w-1)$$$ and $$$(L_2, L_2+w-1)$$$, then: $$$L_1 \ne L_2$$$, that is, the substrings are different; the remainder of dividing a number $$$v(L_1, L_1+w-1) \cdot v(l_i, r_i) + v(L_2, L_2 + w - 1)$$$ by $$$9$$$ is equal to $$$k_i$$$. If there are many matching substring pairs, then find a pair where $$$L_1$$$ is as small as possible. If there are many matching pairs in this case, then minimize $$$L_2$$$.Note that the answer may not exist.
256 megabytes
import java.io.*; import java.util.*; /* 1 1003004 4 1 1 2 1 */ public class F{ static FastReader sc=null; public static void main(String[] args) { sc=new FastReader(); int t=sc.nextInt(); PrintWriter out=new PrintWriter(System.out); for(int tt=0;tt<t;tt++) { char a[]=sc.next().toCharArray(); int n=a.length; int w=sc.nextInt(),m=sc.nextInt(); int cs[]=new int[n+1]; for(int i=0;i<n;i++)cs[i+1]=cs[i]+a[i]-'0'; int first[]=new int[9],second[]=new int[9]; Arrays.fill(first, -1); Arrays.fill(second, -1); for(int i=0;i+w<=n;i++) { int sum=(cs[i+w]-cs[i])%9; if(first[sum]==-1)first[sum]=i; else if(second[sum]==-1)second[sum]=i; } // print(first); // print(second); while(m-->0) { int li=sc.nextInt()-1,ri=sc.nextInt(),k=sc.nextInt(); int s2=(cs[ri]-cs[li])%9; //System.out.println(s2); int L1=n,L2=n; for(int s1=0;s1<9;s1++) { if(first[s1]==-1)continue; for(int s3=0;s3<9;s3++) { int c1=first[s1],c2=first[s3]; if(c1==c2)c2=second[s3]; if(c2==-1)continue; int sum=s1*s2+s3; if(sum%9==k) { //now we have to combine if(c1<L1) { L1=c1; L2=c2; } else if(c1==L1 && L2<c2) { L2=c2; } } } } if(L1==n) { L1=-2; L2=-2; } out.println((L1+1)+" "+(L2+1)); } } out.close(); } static int[] ruffleSort(int a[]) { ArrayList<Integer> al=new ArrayList<>(); for(int i:a)al.add(i); Collections.sort(al); for(int i=0;i<a.length;i++)a[i]=al.get(i); return a; } static void print(int a[]) { for(int e:a) { System.out.print(e+" "); } System.out.println(); } static class FastReader{ StringTokenizer st=new StringTokenizer(""); BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); 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()); } int[] readArray(int n) { int a[]=new int[n]; for(int i=0;i<n;i++)a[i]=sc.nextInt(); return a; } } }
Java
["5\n\n1003004\n\n4 1\n\n1 2 1\n\n179572007\n\n4 2\n\n2 7 3\n\n2 7 4\n\n111\n\n2 1\n\n2 2 6\n\n0000\n\n1 2\n\n1 4 0\n\n1 4 1\n\n484\n\n1 5\n\n2 2 0\n\n2 3 7\n\n1 2 5\n\n3 3 8\n\n2 2 6"]
3 seconds
["2 4\n1 5\n1 2\n-1 -1\n1 2\n-1 -1\n1 3\n1 3\n-1 -1\n-1 -1\n-1 -1"]
NoteConsider the first test case of example inputs. In this test case $$$n=7$$$, $$$s=$$$"1003004", $$$w=4$$$ and one query $$$l_1=1$$$, $$$r_1=2$$$, $$$k_1=1$$$. Note that $$$v(1,2)=10$$$. We need to find a pair of substrings of length $$$4$$$ such that $$$v(L_1, L_1+3)\cdot10+v(L_2,L_2+3)$$$ has a remainder of $$$k_1=1$$$ when divided by $$$9$$$. The values $$$L_1=2, L_2=4$$$ actually satisfy all the requirements: $$$v(L_1, L_1+w-1)=v(2,5)=30$$$, $$$v(L_2, L_2+w-1)=v(4,7)=3004$$$. Indeed, $$$30\cdot10+3004=3304$$$, which has a remainder of $$$1$$$ when divided by $$$9$$$. It can be shown that $$$L_1=2$$$ is the minimum possible value, and $$$L_2=4$$$ is the minimum possible with $$$L_1=2$$$.
Java 8
standard input
[ "hashing", "math" ]
b67870dcffa7bad682ef980dacd1f3db
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — number of input test cases. The first line of each test case contains a string $$$s$$$, which contains only the characters 0-9 and has a length $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$). The second line contains two integers $$$w, m$$$ ($$$1 \le w &lt; n, 1 \le m \le 2 \cdot 10^5$$$), where $$$n$$$ — is the length of the given string $$$s$$$. The number $$$w$$$ denotes the lengths of the substrings being searched for, and $$$m$$$ is the number of queries to be processed. The following $$$m$$$ lines contain integers $$$l_i, r_i, k_i$$$ ($$$1 \le l_i \le r_i \le n$$$, $$$0 \le k_i \le 8$$$) — $$$i$$$th query parameters. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$. It is also guaranteed that the sum of $$$m$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,900
For each request, print in a separate line: left borders of the required substrings: $$$L_1$$$ and $$$L_2$$$; -1 -1 otherwise, if there is no solution. If there are several solutions, minimize $$$L_1$$$ first, and minimize $$$L_2$$$ second.
standard output
PASSED
f37f2e3a0ab874db024fa1a058a15dc7
train_110.jsonl
1662993300
Given the string $$$s$$$ of decimal digits (0-9) of length $$$n$$$.A substring is a sequence of consecutive characters of a string. The substring of this string is defined by a pair of indexes — with its left and right ends. So, each pair of indexes ($$$l, r$$$), where $$$1 \le l \le r \le n$$$, corresponds to a substring of the string $$$s$$$. We will define as $$$v(l,r)$$$ the numeric value of the corresponding substring (leading zeros are allowed in it).For example, if $$$n=7$$$, $$$s=$$$"1003004", then $$$v(1,3)=100$$$, $$$v(2,3)=0$$$ and $$$v(2,7)=3004$$$.You are given $$$n$$$, $$$s$$$ and an integer $$$w$$$ ($$$1 \le w &lt; n$$$).You need to process $$$m$$$ queries, each of which is characterized by $$$3$$$ numbers $$$l_i, r_i, k_i$$$ ($$$1 \le l_i \le r_i \le n; 0 \le k_i \le 8$$$).The answer to the $$$i$$$th query is such a pair of substrings of length $$$w$$$ that if we denote them as $$$(L_1, L_1+w-1)$$$ and $$$(L_2, L_2+w-1)$$$, then: $$$L_1 \ne L_2$$$, that is, the substrings are different; the remainder of dividing a number $$$v(L_1, L_1+w-1) \cdot v(l_i, r_i) + v(L_2, L_2 + w - 1)$$$ by $$$9$$$ is equal to $$$k_i$$$. If there are many matching substring pairs, then find a pair where $$$L_1$$$ is as small as possible. If there are many matching pairs in this case, then minimize $$$L_2$$$.Note that the answer may not exist.
256 megabytes
import java.util.*; import java.io.*; // res.append("Case #"+(p+1)+": "+hh+" \n"); ////*************************************************************************** /* public class E_Gardener_and_Tree implements Runnable{ public static void main(String[] args) throws Exception { new Thread(null, new E_Gardener_and_Tree(), "E_Gardener_and_Tree", 1<<28).start(); } public void run(){ WRITE YOUR CODE HERE!!!! JUST WRITE EVERYTHING HERE WHICH YOU WRITE IN MAIN!!! } } */ /////************************************************************************** public class F_Kirei_and_the_Linear_Function{ public static void main(String[] args) { FastScanner s= new FastScanner(); PrintWriter out=new PrintWriter(System.out); //end of program //out.println(answer); //out.close(); StringBuilder res = new StringBuilder(); int t=s.nextInt(); int p=0; while(p<t){ String str=s.nextToken(); int n=str.length(); long array[]= new long[n]; long nice[]= new long[n]; long yet=0; for(int i=0;i<n;i++){ char ch=str.charAt(i); long a=(ch-'0'); array[i]=a; yet=(yet*10L)+array[i]; yet=yet%9; nice[i]=yet; } int w=s.nextInt(); int m=s.nextInt(); long first[]= new long[10]; long second[]= new long[10]; for(int i=0;i<10;i++){ first[i]=-1; second[i]=-1; } for(int i=0;i<n;i++){ int index=i+w-1; if(index>=n){ break; } long hh=nice[index]; if(i-1>=0){ hh-=nice[i-1]; } hh+=9L; hh=hh%9L; if(first[(int)hh]==-1){ first[(int)hh]=i; } else if(second[(int)hh]==-1){ second[(int)hh]=i; } else{ // } } for(int i=0;i<m;i++){ int l=s.nextInt(); int r=s.nextInt(); int k=s.nextInt(); l--; r--; long rem=nice[r]; if(l-1>=0){ rem-=(nice[(l-1)]); } rem+=9L; rem=(rem%9L); long alpha=-1; long beta=-1; for(int j=0;j<9;j++){ if(first[j]==-1){ continue; } if(alpha!=-1 && first[j]>alpha){ continue; } long hh=rem*j; hh=hh%9L; long yoyo=k-hh+9L; yoyo=yoyo%9L; if(yoyo==j){ if(second[(int)j]!=-1){ alpha=first[j]; beta=second[j]; } } else{ if(first[(int)yoyo]!=-1){ alpha=first[j]; beta=first[(int)yoyo]; } } } if(alpha!=-1){ alpha++; beta++; } res.append(alpha+" "+beta+"\n"); } p++;} out.println(res); out.close(); } static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(String s) { try { br = new BufferedReader(new FileReader(s)); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String nextToken() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(nextToken()); } long nextLong() { return Long.parseLong(nextToken()); } double nextDouble() { return Double.parseDouble(nextToken()); } } static long modpower(long x, long y, long p) { long res = 1; // Initialize result x = x % p; // Update x if it is more than or // equal to p if (x == 0) return 0; // In case x is divisible by p; while (y > 0) { // If y is odd, multiply x with result if ((y & 1) != 0) res = (res * x) % p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return res; } // SIMPLE POWER FUNCTION=> static long power(long x, long y) { long res = 1; // Initialize result while (y > 0) { // If y is odd, multiply x with result if ((y & 1) != 0) res = res * x; // y must be even now y = y >> 1; // y = y/2 x = x * x; // Change x to x^2 } return res; } }
Java
["5\n\n1003004\n\n4 1\n\n1 2 1\n\n179572007\n\n4 2\n\n2 7 3\n\n2 7 4\n\n111\n\n2 1\n\n2 2 6\n\n0000\n\n1 2\n\n1 4 0\n\n1 4 1\n\n484\n\n1 5\n\n2 2 0\n\n2 3 7\n\n1 2 5\n\n3 3 8\n\n2 2 6"]
3 seconds
["2 4\n1 5\n1 2\n-1 -1\n1 2\n-1 -1\n1 3\n1 3\n-1 -1\n-1 -1\n-1 -1"]
NoteConsider the first test case of example inputs. In this test case $$$n=7$$$, $$$s=$$$"1003004", $$$w=4$$$ and one query $$$l_1=1$$$, $$$r_1=2$$$, $$$k_1=1$$$. Note that $$$v(1,2)=10$$$. We need to find a pair of substrings of length $$$4$$$ such that $$$v(L_1, L_1+3)\cdot10+v(L_2,L_2+3)$$$ has a remainder of $$$k_1=1$$$ when divided by $$$9$$$. The values $$$L_1=2, L_2=4$$$ actually satisfy all the requirements: $$$v(L_1, L_1+w-1)=v(2,5)=30$$$, $$$v(L_2, L_2+w-1)=v(4,7)=3004$$$. Indeed, $$$30\cdot10+3004=3304$$$, which has a remainder of $$$1$$$ when divided by $$$9$$$. It can be shown that $$$L_1=2$$$ is the minimum possible value, and $$$L_2=4$$$ is the minimum possible with $$$L_1=2$$$.
Java 8
standard input
[ "hashing", "math" ]
b67870dcffa7bad682ef980dacd1f3db
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — number of input test cases. The first line of each test case contains a string $$$s$$$, which contains only the characters 0-9 and has a length $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$). The second line contains two integers $$$w, m$$$ ($$$1 \le w &lt; n, 1 \le m \le 2 \cdot 10^5$$$), where $$$n$$$ — is the length of the given string $$$s$$$. The number $$$w$$$ denotes the lengths of the substrings being searched for, and $$$m$$$ is the number of queries to be processed. The following $$$m$$$ lines contain integers $$$l_i, r_i, k_i$$$ ($$$1 \le l_i \le r_i \le n$$$, $$$0 \le k_i \le 8$$$) — $$$i$$$th query parameters. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$. It is also guaranteed that the sum of $$$m$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,900
For each request, print in a separate line: left borders of the required substrings: $$$L_1$$$ and $$$L_2$$$; -1 -1 otherwise, if there is no solution. If there are several solutions, minimize $$$L_1$$$ first, and minimize $$$L_2$$$ second.
standard output
PASSED
a487640ef140d0355367edfcb713a1f7
train_110.jsonl
1662993300
Given the string $$$s$$$ of decimal digits (0-9) of length $$$n$$$.A substring is a sequence of consecutive characters of a string. The substring of this string is defined by a pair of indexes — with its left and right ends. So, each pair of indexes ($$$l, r$$$), where $$$1 \le l \le r \le n$$$, corresponds to a substring of the string $$$s$$$. We will define as $$$v(l,r)$$$ the numeric value of the corresponding substring (leading zeros are allowed in it).For example, if $$$n=7$$$, $$$s=$$$"1003004", then $$$v(1,3)=100$$$, $$$v(2,3)=0$$$ and $$$v(2,7)=3004$$$.You are given $$$n$$$, $$$s$$$ and an integer $$$w$$$ ($$$1 \le w &lt; n$$$).You need to process $$$m$$$ queries, each of which is characterized by $$$3$$$ numbers $$$l_i, r_i, k_i$$$ ($$$1 \le l_i \le r_i \le n; 0 \le k_i \le 8$$$).The answer to the $$$i$$$th query is such a pair of substrings of length $$$w$$$ that if we denote them as $$$(L_1, L_1+w-1)$$$ and $$$(L_2, L_2+w-1)$$$, then: $$$L_1 \ne L_2$$$, that is, the substrings are different; the remainder of dividing a number $$$v(L_1, L_1+w-1) \cdot v(l_i, r_i) + v(L_2, L_2 + w - 1)$$$ by $$$9$$$ is equal to $$$k_i$$$. If there are many matching substring pairs, then find a pair where $$$L_1$$$ is as small as possible. If there are many matching pairs in this case, then minimize $$$L_2$$$.Note that the answer may not exist.
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.StringTokenizer; /** * @author Nervose.Wu * @date 2022/10/3 12:27 */ public final class S820F { public static void main(String[] args) { MyScanner sc = new MyScanner(); PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); for (int testNo = sc.nextInt(); testNo > 0; testNo--) { String str = sc.next(); int rangeLen = sc.nextInt(); //preSum[i]表示[0,i)的和 int[] preSum = new int[str.length() + 1]; for (int i = 0; i < str.length(); i++) { preSum[i + 1] = preSum[i] + (str.charAt(i) - '0'); } //余数为0-8的前两小的Left位置 int[][] dict = new int[9][2]; for (int i = 0; i + rangeLen - 1 < str.length(); i++) { int mod = (preSum[i + rangeLen] - preSum[i]) % 9; if (dict[mod][0] == 0) { dict[mod][0] = i + 1; } else if (dict[mod][1] == 0) { dict[mod][1] = i + 1; } } for (int nTests = sc.nextInt(); nTests > 0; nTests--) { int left=sc.nextInt(); int right=sc.nextInt(); int k=sc.nextInt(); int mult=(preSum[right]-preSum[left-1])%9; int start1=-1; int start2=-1; for(int i=0;i<=8;i++){ if(dict[i][0]!=0&&(start1==-1||dict[i][0]<start1)){ int mod2=(((k-i*mult)%9)+9)%9; int index=i==mod2?1:0; if(dict[mod2][index]!=0){ start1=dict[i][0]; start2=dict[mod2][index]; } } } out.println(start1+" "+start2); } } out.close(); } public static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine(){ String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["5\n\n1003004\n\n4 1\n\n1 2 1\n\n179572007\n\n4 2\n\n2 7 3\n\n2 7 4\n\n111\n\n2 1\n\n2 2 6\n\n0000\n\n1 2\n\n1 4 0\n\n1 4 1\n\n484\n\n1 5\n\n2 2 0\n\n2 3 7\n\n1 2 5\n\n3 3 8\n\n2 2 6"]
3 seconds
["2 4\n1 5\n1 2\n-1 -1\n1 2\n-1 -1\n1 3\n1 3\n-1 -1\n-1 -1\n-1 -1"]
NoteConsider the first test case of example inputs. In this test case $$$n=7$$$, $$$s=$$$"1003004", $$$w=4$$$ and one query $$$l_1=1$$$, $$$r_1=2$$$, $$$k_1=1$$$. Note that $$$v(1,2)=10$$$. We need to find a pair of substrings of length $$$4$$$ such that $$$v(L_1, L_1+3)\cdot10+v(L_2,L_2+3)$$$ has a remainder of $$$k_1=1$$$ when divided by $$$9$$$. The values $$$L_1=2, L_2=4$$$ actually satisfy all the requirements: $$$v(L_1, L_1+w-1)=v(2,5)=30$$$, $$$v(L_2, L_2+w-1)=v(4,7)=3004$$$. Indeed, $$$30\cdot10+3004=3304$$$, which has a remainder of $$$1$$$ when divided by $$$9$$$. It can be shown that $$$L_1=2$$$ is the minimum possible value, and $$$L_2=4$$$ is the minimum possible with $$$L_1=2$$$.
Java 8
standard input
[ "hashing", "math" ]
b67870dcffa7bad682ef980dacd1f3db
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — number of input test cases. The first line of each test case contains a string $$$s$$$, which contains only the characters 0-9 and has a length $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$). The second line contains two integers $$$w, m$$$ ($$$1 \le w &lt; n, 1 \le m \le 2 \cdot 10^5$$$), where $$$n$$$ — is the length of the given string $$$s$$$. The number $$$w$$$ denotes the lengths of the substrings being searched for, and $$$m$$$ is the number of queries to be processed. The following $$$m$$$ lines contain integers $$$l_i, r_i, k_i$$$ ($$$1 \le l_i \le r_i \le n$$$, $$$0 \le k_i \le 8$$$) — $$$i$$$th query parameters. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$. It is also guaranteed that the sum of $$$m$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,900
For each request, print in a separate line: left borders of the required substrings: $$$L_1$$$ and $$$L_2$$$; -1 -1 otherwise, if there is no solution. If there are several solutions, minimize $$$L_1$$$ first, and minimize $$$L_2$$$ second.
standard output
PASSED
467cddb86a089478dec558240de8a187
train_110.jsonl
1662993300
Given the string $$$s$$$ of decimal digits (0-9) of length $$$n$$$.A substring is a sequence of consecutive characters of a string. The substring of this string is defined by a pair of indexes — with its left and right ends. So, each pair of indexes ($$$l, r$$$), where $$$1 \le l \le r \le n$$$, corresponds to a substring of the string $$$s$$$. We will define as $$$v(l,r)$$$ the numeric value of the corresponding substring (leading zeros are allowed in it).For example, if $$$n=7$$$, $$$s=$$$"1003004", then $$$v(1,3)=100$$$, $$$v(2,3)=0$$$ and $$$v(2,7)=3004$$$.You are given $$$n$$$, $$$s$$$ and an integer $$$w$$$ ($$$1 \le w &lt; n$$$).You need to process $$$m$$$ queries, each of which is characterized by $$$3$$$ numbers $$$l_i, r_i, k_i$$$ ($$$1 \le l_i \le r_i \le n; 0 \le k_i \le 8$$$).The answer to the $$$i$$$th query is such a pair of substrings of length $$$w$$$ that if we denote them as $$$(L_1, L_1+w-1)$$$ and $$$(L_2, L_2+w-1)$$$, then: $$$L_1 \ne L_2$$$, that is, the substrings are different; the remainder of dividing a number $$$v(L_1, L_1+w-1) \cdot v(l_i, r_i) + v(L_2, L_2 + w - 1)$$$ by $$$9$$$ is equal to $$$k_i$$$. If there are many matching substring pairs, then find a pair where $$$L_1$$$ is as small as possible. If there are many matching pairs in this case, then minimize $$$L_2$$$.Note that the answer may not exist.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class Main { public static void main(String[] args) { FastScanner input = new FastScanner(); int tc = input.nextInt(); work: while (tc-- > 0) { char a[] = input.next().toCharArray(); int w = input.nextInt(); int q = input.nextInt(); int pre[] =new int[a.length]; for (int i = 0; i < a.length; i++) { if(i==0) { pre[i]= a[i]-'0'; } else { pre[i]+=pre[i-1]; pre[i]+=(a[i]-'0'); } } // System.out.println(Arrays.toString(pre)); HashMap<Integer,TreeSet<Integer>> map = new HashMap<>(); int serial=1; for (int i = w-1; i <a.length; i++,serial++) { int now = 0; if(i-w<0) { now = pre[i]; } else { now = pre[i]-pre[i-w]; } if(map.containsKey(now%9)) { if(map.get(now%9).size()<2) { map.get(now%9).add(serial); } }else { TreeSet<Integer> set = new TreeSet<>(); set.add(serial); map.put(now%9, set); } } // System.out.println(map); StringBuilder result = new StringBuilder(); for (int iii = 0; iii < q; iii++) { int l = input.nextInt()-1; int r = input.nextInt()-1; int k = input.nextInt(); int l1 = Integer.MAX_VALUE; int l2 = Integer.MAX_VALUE; for (int i = 0; i <=8; i++) { for (int j = 0; j <=8; j++) { if(i==j&&map.containsKey(j)&&map.get(j).size()==2) { int nowk = ((pre[r]-((l==0)?0:pre[l-1])%9)*i+j)%9; if(nowk==k&&map.get(j).first()<=l1) { if(map.get(j).first()<l1) { l1 = map.get(j).first(); l2 = map.get(j).last(); } else if(l1==map.get(j).first()&&l2>map.get(j).last()) { l2 = map.get(j).last(); } } } else if(i!=j&&map.containsKey(i)&&map.containsKey(j)) { int nowk = ((pre[r]-((l==0)?0:pre[l-1])%9)*i+j)%9; if(nowk==k&&l1>=map.get(i).first()) { if(map.get(i).first()<l1) { l1 = map.get(i).first(); l2 = map.get(j).first(); } else if(l1==map.get(i).first()&&l2>map.get(j).first()) { l2 = map.get(j).first(); } } } } } if(l1!=Integer.MAX_VALUE&&l2!=Integer.MAX_VALUE) result.append(l1+" "+l2+"\n"); else { result.append("-1 -1\n"); } } System.out.println(result); } } static class FastScanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() throws IOException { return br.readLine(); } } }
Java
["5\n\n1003004\n\n4 1\n\n1 2 1\n\n179572007\n\n4 2\n\n2 7 3\n\n2 7 4\n\n111\n\n2 1\n\n2 2 6\n\n0000\n\n1 2\n\n1 4 0\n\n1 4 1\n\n484\n\n1 5\n\n2 2 0\n\n2 3 7\n\n1 2 5\n\n3 3 8\n\n2 2 6"]
3 seconds
["2 4\n1 5\n1 2\n-1 -1\n1 2\n-1 -1\n1 3\n1 3\n-1 -1\n-1 -1\n-1 -1"]
NoteConsider the first test case of example inputs. In this test case $$$n=7$$$, $$$s=$$$"1003004", $$$w=4$$$ and one query $$$l_1=1$$$, $$$r_1=2$$$, $$$k_1=1$$$. Note that $$$v(1,2)=10$$$. We need to find a pair of substrings of length $$$4$$$ such that $$$v(L_1, L_1+3)\cdot10+v(L_2,L_2+3)$$$ has a remainder of $$$k_1=1$$$ when divided by $$$9$$$. The values $$$L_1=2, L_2=4$$$ actually satisfy all the requirements: $$$v(L_1, L_1+w-1)=v(2,5)=30$$$, $$$v(L_2, L_2+w-1)=v(4,7)=3004$$$. Indeed, $$$30\cdot10+3004=3304$$$, which has a remainder of $$$1$$$ when divided by $$$9$$$. It can be shown that $$$L_1=2$$$ is the minimum possible value, and $$$L_2=4$$$ is the minimum possible with $$$L_1=2$$$.
Java 8
standard input
[ "hashing", "math" ]
b67870dcffa7bad682ef980dacd1f3db
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — number of input test cases. The first line of each test case contains a string $$$s$$$, which contains only the characters 0-9 and has a length $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$). The second line contains two integers $$$w, m$$$ ($$$1 \le w &lt; n, 1 \le m \le 2 \cdot 10^5$$$), where $$$n$$$ — is the length of the given string $$$s$$$. The number $$$w$$$ denotes the lengths of the substrings being searched for, and $$$m$$$ is the number of queries to be processed. The following $$$m$$$ lines contain integers $$$l_i, r_i, k_i$$$ ($$$1 \le l_i \le r_i \le n$$$, $$$0 \le k_i \le 8$$$) — $$$i$$$th query parameters. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$. It is also guaranteed that the sum of $$$m$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,900
For each request, print in a separate line: left borders of the required substrings: $$$L_1$$$ and $$$L_2$$$; -1 -1 otherwise, if there is no solution. If there are several solutions, minimize $$$L_1$$$ first, and minimize $$$L_2$$$ second.
standard output
PASSED
095d6347e51480e3150a001c10afab0d
train_110.jsonl
1662993300
Given the string $$$s$$$ of decimal digits (0-9) of length $$$n$$$.A substring is a sequence of consecutive characters of a string. The substring of this string is defined by a pair of indexes — with its left and right ends. So, each pair of indexes ($$$l, r$$$), where $$$1 \le l \le r \le n$$$, corresponds to a substring of the string $$$s$$$. We will define as $$$v(l,r)$$$ the numeric value of the corresponding substring (leading zeros are allowed in it).For example, if $$$n=7$$$, $$$s=$$$"1003004", then $$$v(1,3)=100$$$, $$$v(2,3)=0$$$ and $$$v(2,7)=3004$$$.You are given $$$n$$$, $$$s$$$ and an integer $$$w$$$ ($$$1 \le w &lt; n$$$).You need to process $$$m$$$ queries, each of which is characterized by $$$3$$$ numbers $$$l_i, r_i, k_i$$$ ($$$1 \le l_i \le r_i \le n; 0 \le k_i \le 8$$$).The answer to the $$$i$$$th query is such a pair of substrings of length $$$w$$$ that if we denote them as $$$(L_1, L_1+w-1)$$$ and $$$(L_2, L_2+w-1)$$$, then: $$$L_1 \ne L_2$$$, that is, the substrings are different; the remainder of dividing a number $$$v(L_1, L_1+w-1) \cdot v(l_i, r_i) + v(L_2, L_2 + w - 1)$$$ by $$$9$$$ is equal to $$$k_i$$$. If there are many matching substring pairs, then find a pair where $$$L_1$$$ is as small as possible. If there are many matching pairs in this case, then minimize $$$L_2$$$.Note that the answer may not exist.
256 megabytes
import java.util.HashMap; import java.util.Map; import java.util.Scanner; public class Test { public static void main(String[] args) { Scanner in = new Scanner(System.in); int t = in.nextInt(); for (int ii = 0; ii < t; ii++) { String s = in.next(); int w = in.nextInt(); int m = in.nextInt(); int n = s.length(); int[] a = new int[n + 1]; for (int i = 1; i <= n; i++) { a[i] = s.charAt(i - 1) - '0'; } for (int i = 1; i <= n; i++) { a[i] = a[i] + a[i - 1]; } Map<Integer, Integer> map1 = new HashMap<>(); Map<Integer, Integer> map2 = new HashMap<>(); for (int i = 1; i <= n - w + 1; i++) { int k = (a[i + w - 1] - a[i - 1]) % 9; if (!map1.containsKey(k)) { map1.put(k, i); } else if (!map2.containsKey(k)) { map2.put(k, i); } } for (int i = 0; i < m; i++) { int l = in.nextInt(); int r = in.nextInt(); int k = in.nextInt(); int v = (a[r] - a[l - 1]) % 9; int min1 = Integer.MAX_VALUE; int min2 = Integer.MAX_VALUE; for (int i1 = 0; i1 < 9; i1++) { for (int i2 = 0; i2 < 9; i2++) { if(i1 == i2) { if((i1 * v + i2) % 9 == k && map1.containsKey(i1) && map2.containsKey(i2)) { if(map1.get(i1) < min1 || map1.get(i1) == min1 && map2.get(i2) < min2) { min1 = map1.get(i1); min2 = map2.get(i2); } } } else { if((i1 * v + i2) % 9 == k && map1.containsKey(i1) && map1.containsKey(i2)) { if(map1.get(i1) < min1 || map1.get(i1) == min1 && map1.get(i2) < min2) { min1 = map1.get(i1); min2 = map1.get(i2); } } } } } if(min1 != Integer.MAX_VALUE) { System.out.println(min1 + " " + min2); } else { System.out.println("-1 -1"); } } } } }
Java
["5\n\n1003004\n\n4 1\n\n1 2 1\n\n179572007\n\n4 2\n\n2 7 3\n\n2 7 4\n\n111\n\n2 1\n\n2 2 6\n\n0000\n\n1 2\n\n1 4 0\n\n1 4 1\n\n484\n\n1 5\n\n2 2 0\n\n2 3 7\n\n1 2 5\n\n3 3 8\n\n2 2 6"]
3 seconds
["2 4\n1 5\n1 2\n-1 -1\n1 2\n-1 -1\n1 3\n1 3\n-1 -1\n-1 -1\n-1 -1"]
NoteConsider the first test case of example inputs. In this test case $$$n=7$$$, $$$s=$$$"1003004", $$$w=4$$$ and one query $$$l_1=1$$$, $$$r_1=2$$$, $$$k_1=1$$$. Note that $$$v(1,2)=10$$$. We need to find a pair of substrings of length $$$4$$$ such that $$$v(L_1, L_1+3)\cdot10+v(L_2,L_2+3)$$$ has a remainder of $$$k_1=1$$$ when divided by $$$9$$$. The values $$$L_1=2, L_2=4$$$ actually satisfy all the requirements: $$$v(L_1, L_1+w-1)=v(2,5)=30$$$, $$$v(L_2, L_2+w-1)=v(4,7)=3004$$$. Indeed, $$$30\cdot10+3004=3304$$$, which has a remainder of $$$1$$$ when divided by $$$9$$$. It can be shown that $$$L_1=2$$$ is the minimum possible value, and $$$L_2=4$$$ is the minimum possible with $$$L_1=2$$$.
Java 8
standard input
[ "hashing", "math" ]
b67870dcffa7bad682ef980dacd1f3db
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — number of input test cases. The first line of each test case contains a string $$$s$$$, which contains only the characters 0-9 and has a length $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$). The second line contains two integers $$$w, m$$$ ($$$1 \le w &lt; n, 1 \le m \le 2 \cdot 10^5$$$), where $$$n$$$ — is the length of the given string $$$s$$$. The number $$$w$$$ denotes the lengths of the substrings being searched for, and $$$m$$$ is the number of queries to be processed. The following $$$m$$$ lines contain integers $$$l_i, r_i, k_i$$$ ($$$1 \le l_i \le r_i \le n$$$, $$$0 \le k_i \le 8$$$) — $$$i$$$th query parameters. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$. It is also guaranteed that the sum of $$$m$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,900
For each request, print in a separate line: left borders of the required substrings: $$$L_1$$$ and $$$L_2$$$; -1 -1 otherwise, if there is no solution. If there are several solutions, minimize $$$L_1$$$ first, and minimize $$$L_2$$$ second.
standard output
PASSED
99a2bfd51bdc962c0bce1b3cf22b72b2
train_110.jsonl
1662993300
Given the string $$$s$$$ of decimal digits (0-9) of length $$$n$$$.A substring is a sequence of consecutive characters of a string. The substring of this string is defined by a pair of indexes — with its left and right ends. So, each pair of indexes ($$$l, r$$$), where $$$1 \le l \le r \le n$$$, corresponds to a substring of the string $$$s$$$. We will define as $$$v(l,r)$$$ the numeric value of the corresponding substring (leading zeros are allowed in it).For example, if $$$n=7$$$, $$$s=$$$"1003004", then $$$v(1,3)=100$$$, $$$v(2,3)=0$$$ and $$$v(2,7)=3004$$$.You are given $$$n$$$, $$$s$$$ and an integer $$$w$$$ ($$$1 \le w &lt; n$$$).You need to process $$$m$$$ queries, each of which is characterized by $$$3$$$ numbers $$$l_i, r_i, k_i$$$ ($$$1 \le l_i \le r_i \le n; 0 \le k_i \le 8$$$).The answer to the $$$i$$$th query is such a pair of substrings of length $$$w$$$ that if we denote them as $$$(L_1, L_1+w-1)$$$ and $$$(L_2, L_2+w-1)$$$, then: $$$L_1 \ne L_2$$$, that is, the substrings are different; the remainder of dividing a number $$$v(L_1, L_1+w-1) \cdot v(l_i, r_i) + v(L_2, L_2 + w - 1)$$$ by $$$9$$$ is equal to $$$k_i$$$. If there are many matching substring pairs, then find a pair where $$$L_1$$$ is as small as possible. If there are many matching pairs in this case, then minimize $$$L_2$$$.Note that the answer may not exist.
256 megabytes
import java.io.*; import java.util.*; public class F { public static void main(String[] args) { FastScanner fs=new FastScanner(); PrintWriter out = new PrintWriter(System.out); int T = fs.nextInt(); for (int tt=0; tt<T; tt++) { String s = fs.next(); int n = s.length(); int w = fs.nextInt(); int m = fs.nextInt(); // preprocess int[] psum = new int[n+1]; for(int i=0; i<n; i++) { psum[i+1] = psum[i]+Character.getNumericValue(s.charAt(i)); // if(psum[i+1]>=10) { // psum[i+1] = psum[i+1]%10+1; // } } HashMap<Integer,List<Integer>> hm = new HashMap<>(); for(int i=w; i<=n; i++) { int cur = psum[i]-psum[i-w]; cur = cur%9; List<Integer> lst = hm.getOrDefault(cur, new ArrayList<>()); if(lst.size()==2) continue; lst.add(i-w+1); hm.put(cur, lst); } HashMap<Integer,List<Integer>> resMap = new HashMap<>(); for(int qq=0; qq<m; qq++) { int l = fs.nextInt(); int r = fs.nextInt(); int q = fs.nextInt(); List<Integer> res = new ArrayList<>(); for(int a: hm.keySet()) { int mul = psum[r]-psum[l-1]; mul = mul*a; mul = mul%9; int rem = mul>q ? q+9-mul : q-mul; if(rem==a) { if(hm.get(a).size()==2) { res = compare(hm.get(a), res); } } else { if(hm.get(rem) !=null && hm.get(rem).size()>0) { List<Integer> tmpList = new ArrayList<>(); tmpList.add(hm.get(a).get(0)); tmpList.add(hm.get(rem).get(0)); res = compare(tmpList, res); } } } if(res.size()==0) { out.println("-1 -1"); } else { out.println(res.get(0)+" "+res.get(1)); } } } out.close(); } static List<Integer> compare(List<Integer> l1, List<Integer> l2) { ArrayList<Integer> res = new ArrayList<>(); if(l2.size()==0 || l1.get(0)<l2.get(0)) { res.addAll(l1); } else if(l2.get(0)<l1.get(0)) { res.addAll(l2); } else { if(l1.get(1)<l2.get(1)) { res.addAll(l1); } else { res.addAll(l2); } } return res; } static final Random random=new Random(); static void ruffleSort(int[] a) { int n=a.length;//shuffle, then sort for (int i=0; i<n; i++) { int oi=random.nextInt(n), temp=a[oi]; a[oi]=a[i]; a[i]=temp; } Arrays.sort(a); } static 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()); } int[] readArray(int n) { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } } }
Java
["5\n\n1003004\n\n4 1\n\n1 2 1\n\n179572007\n\n4 2\n\n2 7 3\n\n2 7 4\n\n111\n\n2 1\n\n2 2 6\n\n0000\n\n1 2\n\n1 4 0\n\n1 4 1\n\n484\n\n1 5\n\n2 2 0\n\n2 3 7\n\n1 2 5\n\n3 3 8\n\n2 2 6"]
3 seconds
["2 4\n1 5\n1 2\n-1 -1\n1 2\n-1 -1\n1 3\n1 3\n-1 -1\n-1 -1\n-1 -1"]
NoteConsider the first test case of example inputs. In this test case $$$n=7$$$, $$$s=$$$"1003004", $$$w=4$$$ and one query $$$l_1=1$$$, $$$r_1=2$$$, $$$k_1=1$$$. Note that $$$v(1,2)=10$$$. We need to find a pair of substrings of length $$$4$$$ such that $$$v(L_1, L_1+3)\cdot10+v(L_2,L_2+3)$$$ has a remainder of $$$k_1=1$$$ when divided by $$$9$$$. The values $$$L_1=2, L_2=4$$$ actually satisfy all the requirements: $$$v(L_1, L_1+w-1)=v(2,5)=30$$$, $$$v(L_2, L_2+w-1)=v(4,7)=3004$$$. Indeed, $$$30\cdot10+3004=3304$$$, which has a remainder of $$$1$$$ when divided by $$$9$$$. It can be shown that $$$L_1=2$$$ is the minimum possible value, and $$$L_2=4$$$ is the minimum possible with $$$L_1=2$$$.
Java 8
standard input
[ "hashing", "math" ]
b67870dcffa7bad682ef980dacd1f3db
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — number of input test cases. The first line of each test case contains a string $$$s$$$, which contains only the characters 0-9 and has a length $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$). The second line contains two integers $$$w, m$$$ ($$$1 \le w &lt; n, 1 \le m \le 2 \cdot 10^5$$$), where $$$n$$$ — is the length of the given string $$$s$$$. The number $$$w$$$ denotes the lengths of the substrings being searched for, and $$$m$$$ is the number of queries to be processed. The following $$$m$$$ lines contain integers $$$l_i, r_i, k_i$$$ ($$$1 \le l_i \le r_i \le n$$$, $$$0 \le k_i \le 8$$$) — $$$i$$$th query parameters. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$. It is also guaranteed that the sum of $$$m$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,900
For each request, print in a separate line: left borders of the required substrings: $$$L_1$$$ and $$$L_2$$$; -1 -1 otherwise, if there is no solution. If there are several solutions, minimize $$$L_1$$$ first, and minimize $$$L_2$$$ second.
standard output