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
421dea4d2765aa39167528ce530de417
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 < 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.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.InputMismatchException; import java.io.IOException; import java.util.ArrayList; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Sparsh Sanchorawala */ 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); FKireiAndTheLinearFunction solver = new FKireiAndTheLinearFunction(); solver.solve(1, in, out); out.close(); } static class FKireiAndTheLinearFunction { public void solve(int testNumber, InputReader s, PrintWriter w) { int t = s.nextInt(); while (t-- > 0) { char[] a = s.next().toCharArray(); int n = a.length; int l = s.nextInt(), m = s.nextInt(); int mod = 9; ArrayList<Integer>[] adj = new ArrayList[mod]; for (int i = 0; i < mod; i++) adj[i] = new ArrayList<>(); int[] pre = new int[n]; pre[0] = (a[0] - '0') % mod; for (int i = 1; i < n; i++) pre[i] = (pre[i - 1] * 10 + (a[i] - '0')) % mod; int[] ten = new int[n + 1]; ten[0] = 1; for (int i = 1; i <= n; i++) ten[i] = ten[i - 1] * 10 % mod; for (int i = 0; i < n - l + 1; i++) { int v = pre[i + l - 1]; if (i - 1 >= 0) v = (v - (pre[i - 1] * ten[l]) % mod + mod) % mod; // w.println(i + " - " + v); adj[v].add(i); } // // for (int i = 0; i < mod; i++) // w.println(i + ": " + (adj[i].size() > 0 ? adj[i].get(0) : -1) + " " + (adj[i].size() > 1 ? adj[i].get(1) : -1)); while (m-- > 0) { // v1 * v2 + v3 = int li = s.nextInt() - 1, ri = s.nextInt() - 1, ki = s.nextInt(); int v = pre[ri]; if (li - 1 >= 0) v = (v - (pre[li - 1] * ten[ri - li + 1]) % mod + mod) % mod; // w.println(m + "// " + v); int[] best = new int[2]; Arrays.fill(best, -1); for (int i = 0; i < mod; i++) { if (adj[i].size() == 0) continue; int l1 = adj[i].get(0); if (adj[i].size() > 1 && (i * v + i) % mod == ki) { int l2 = adj[i].get(1); if (best[0] == -1 || l1 < best[0] || (l1 == best[0] && l2 < best[1])) { best[0] = l1; best[1] = l2; } } for (int j = 0; j < mod; j++) { if (adj[j].size() == 0 || i == j) continue; int l2 = adj[j].get(0); if ((i * v + j) % mod != ki) continue; // w.println(i + " " + j + " mmm " + l1 + " " + l2 + " ^^"); if (best[0] == -1 || l1 < best[0] || (l1 == best[0] && l2 < best[1])) { best[0] = l1; best[1] = l2; } } } if (best[0] == -1) w.println("-1 -1"); else w.println((best[0] + 1) + " " + (best[1] + 1)); } } } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String nextString() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { if (Character.isValidCodePoint(c)) { res.appendCodePoint(c); } c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return nextString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
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
b49c38bf2342dc789e0938e9e676c11d
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.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Random; import java.util.StringTokenizer; /* 1 1003004 4 1 1 2 1 */ 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++) { char[] line=fs.next().toCharArray(); int[] cs=new int[line.length+1]; for (int i=1; i<=line.length; i++) cs[i]=cs[i-1]+(line[i-1]-'0'); int substringLen=fs.nextInt(); int nQ=fs.nextInt(); int[][] hit1=new int[9][]; int[][] hit2=new int[9][]; // System.out.println(Arrays.toString(cs)); for (int end=substringLen-1; end<line.length; end++) { int total=(cs[end+1]-cs[end+1-substringLen])%9; int start=end+1-substringLen; if (hit1[total]==null) { hit1[total]=new int[] {start, end}; } else if (hit2[total]==null) { hit2[total]=new int[] {start, end}; } } for (int qq=0; qq<nQ; qq++) { int left=fs.nextInt()-1, right=fs.nextInt()-1, modVal=fs.nextInt(); int scalar=(cs[right+1]-cs[left])%9; int ansl=-1, ansl2=-1; for (int v1=0; v1<9; v1++) { for (int v2=0; v2<9; v2++) { if ((v1*scalar+v2)%9!=modVal) continue; if (hit1[v1] == null) continue; if (hit1[v2] == null) continue; if (v1==v2 && hit2[v1]==null) continue; // System.out.println("Considering "+v1+" "+v2); int l1=hit1[v1][0]; int l2=v1==v2?hit2[v2][0]:hit1[v2][0]; if (ansl==-1 || ansl>l1 || (ansl==l1 &&ansl2>l2)) { ansl=l1; ansl2=l2; // System.out.println("Got "+l1+" "+l2); } } } //TODO: print stuff not 0-based! if (ansl==-1) { out.println(ansl+" "+ansl2); } else { out.println(ansl+1+" "+(ansl2+1)); } } } out.close(); } static final Random random=new Random(); static final int mod=1_000_000_007; static void ruffleSort(int[] a) { int n=a.length;//shuffle, then sort for (int i=0; i<n; i++) { int oi=random.nextInt(n), temp=a[oi]; a[oi]=a[i]; a[i]=temp; } Arrays.sort(a); } static long add(long a, long b) { return (a+b)%mod; } static long sub(long a, long b) { return ((a-b)%mod+mod)%mod; } static long mul(long a, long b) { return (a*b)%mod; } static long exp(long base, long exp) { if (exp==0) return 1; long half=exp(base, exp/2); if (exp%2==0) return mul(half, half); return mul(half, mul(half, base)); } static long[] factorials=new long[2_000_001]; static long[] invFactorials=new long[2_000_001]; static void precompFacts() { factorials[0]=invFactorials[0]=1; for (int i=1; i<factorials.length; i++) factorials[i]=mul(factorials[i-1], i); invFactorials[factorials.length-1]=exp(factorials[factorials.length-1], mod-2); for (int i=invFactorials.length-2; i>=0; i--) invFactorials[i]=mul(invFactorials[i+1], i+1); } static long nCk(int n, int k) { return mul(factorials[n], mul(invFactorials[k], invFactorials[n-k])); } static void sort(int[] a) { ArrayList<Integer> l=new ArrayList<>(); for (int i:a) l.add(i); Collections.sort(l); for (int i=0; i<a.length; i++) a[i]=l.get(i); } static class FastScanner { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readArray(int n) { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } long nextLong() { return Long.parseLong(next()); } } }
Java
["5\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
b93cf8b219d8bd01c6d3c98635f878d9
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 kg.my_algorithms.Codeforces; /* If you can't Calculate, then Stimulate */ import java.util.*; import java.io.*; public class Solution { public static void main(String[] args) throws IOException { FastReader fr = new FastReader(); BufferedWriter output = new BufferedWriter(new OutputStreamWriter(System.out)); StringBuilder sb = new StringBuilder(); int testCases = fr.nextInt(); for(int test=1;test<=testCases;test++){ String s = fr.next(); 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'); int windowLength = fr.nextInt(); int queries = fr.nextInt(); List<List<Integer>> map = new ArrayList<>(); for(int i=0;i<=8;i++) map.add(new ArrayList<>()); // System.out.println("window length= " + windowLength); for(int i=1;i<=n-windowLength+1;i++){ int sum = prefix[i+windowLength-1]- prefix[i-1]; map.get(sum%9).add(i); } // System.out.println(map); for(int query=1;query<=queries;query++){ int left = fr.nextInt(); int right = fr.nextInt(); int k = fr.nextInt(); int sum = prefix[right]-prefix[left-1]; int multiplier = sum%9; Queue<Pair> answer = new PriorityQueue<>((p1,p2)->{ if(p1.first==p2.first) return p1.second-p2.second; return p1.first-p2.first; }); for(int a=0;a<9;a++){ for(int b=0;b<9;b++){ if((a*multiplier+b)%9==k){ if(a==b) { if(map.get(a).size()>=2) { answer.offer(new Pair(map.get(a).get(0),map.get(b).get(1))); } } else if(map.get(a).size()>=1 && map.get(b).size()>=1) { answer.offer(new Pair(map.get(a).get(0),map.get(b).get(0))); } } } } if(answer.isEmpty()) sb.append("-1 -1\n"); else { Pair p = answer.remove(); sb.append(p.first).append(" ").append(p.second).append("\n"); } } } output.write(sb.toString()); output.flush(); } } class Pair{ int first; int second; public Pair(int first, int second) { this.first = first; this.second = second; } } //Fast Input 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
["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
6d9fa60837cb34e5d55e6e0b769decad
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.lang.reflect.Array; import java.util.*; public class Main { static Main2 admin = new Main2(); public static void main(String[] args) { admin.start(); } } class Main2 { //---------------------------------INPUT READER-----------------------------------------// public BufferedReader br; StringTokenizer st = new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine());} catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int ni() { return Integer.parseInt(next()); } long nl() { return Long.parseLong(next()); } double nd() { return Double.parseDouble(next()); } String ns() { return next(); } int[] na(long n) {int[]ret=new int[(int)n]; for(int i=0;i<n;i++) ret[i]=ni(); return ret;} long[] nal(long n) {long[]ret=new long[(int)n]; for(int i=0;i<n;i++) ret[i]=nl(); return ret;} Integer[] nA(long n) {Integer[]ret=new Integer[(int)n]; for(int i=0;i<n;i++) ret[i]=ni(); return ret;} Long[] nAl(long n) {Long[]ret=new Long[(int)n]; for(int i=0;i<n;i++) ret[i]=nl(); return ret;} //--------------------------------------PRINTER------------------------------------------// PrintWriter w; void p(int i) {w.println(i);} void p(long l) {w.println(l);} void p(double d) {w.println(d);} void p(String s) { w.println(s);} void pr(int i) {w.print(i);} void pr(long l) {w.print(l);} void pr(double d) {w.print(d);} void pr(String s) { w.print(s);} void pl() {w.println();} //--------------------------------------VARIABLES-----------------------------------------// long lma = Long.MAX_VALUE, lmi = Long.MIN_VALUE; int ima = Integer.MAX_VALUE, imi = Integer.MIN_VALUE; long mod = 1000000007; { w = new PrintWriter(System.out); br = new BufferedReader(new InputStreamReader(System.in)); try {if(new File(System.getProperty("user.dir")).getName().equals("Main_CP")) { w = new PrintWriter(new OutputStreamWriter(new FileOutputStream("output.txt"))); br = new BufferedReader(new InputStreamReader(new FileInputStream("input.txt")));} } catch (Exception ignore) { } } //----------------------START---------------------// void start() { int t = ni(); while(t-- > 0) solve(); w.close(); } int[] make (char[] strr) { int n = strr.length; int[] ret = new int[n]; for(int i = 0; i < n; i++) ret[i] = strr[i] - '0'; return ret; } int sum (int[] arr, int i, int j) { return (arr[j] - ((i == 0) ? 0 : arr[i-1]) + 18) % 9; } void solve() { String str = ns(); char[] strr = str.toCharArray(); int[] arr = make(strr); int n = arr.length; int w = ni(), q = ni(); int[][] st = new int[9][2]; for(int i = 0; i < 9; i++) { Arrays.fill(st[i], ima); } for(int i = 1; i < n; i++) { arr[i] += arr[i - 1]; arr[i] %= 9; } for(int i = 0; i < n; i++) { int j = i + w - 1; if(j >= n) break; int sum = sum(arr, i, j); if(st[sum][0] == ima) st[sum][0] = i; else if(st[sum][1] == ima) st[sum][1] = i; } while(q-- > 0) { int l = ni() - 1, r = ni() - 1; int c_sum = sum(arr, l, r) % 9; int k = ni(); int l1 = -2, l2 = -2; for(int i = 0; i < 9; i++) { for(int j = 0; j < 9; j++) { if(((i * c_sum) % 9 + j) % 9 == k) { int ll1 = st[i][0]; int ll2 = (i == j) ? st[i][1] : st[j][0]; if(ll1 == ima || ll2 == ima) continue; if(l1 == -2 || l1 > ll1 || (l1 == ll1 && l2 > ll2)) { l1 = ll1; l2 = ll2; } } } } p((l1 + 1) +" "+ (l2 + 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
d35dde59e4afe5acad56818d08b3d20f
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.Comparator; import java.util.List; import java.util.StringTokenizer; public class E { static final long mod = (long) 1e9 + 7l; private static void solve(int t){ String str = fs.next(); int n = str.length(); int w = fs.nextInt(); int m = fs.nextInt(); //preprocess int [] ps = new int[n+1]; for (int i = 0; i < n; i++) { ps[i+1] = ps[i]+str.charAt(i)-'0'; } List<Integer>[] adj = new ArrayList[9]; for (int i = 0; i < adj.length; i++) adj[i] = new ArrayList<>(); for (int i = 0; i+w <= n; i++) { int x = (ps[i+w] - ps[i])%9; adj[x].add(i); } //queries while(m-- >0){ int l =fs.nextInt(); int r =fs.nextInt(); int k = fs.nextInt(); int x = (ps[r]-ps[l-1])%9; int ans[] = new int[2]; ans[0] = Integer.MAX_VALUE; ans[1] = Integer.MAX_VALUE; // (ax+b)%9 = k for (int a = 0; a < 9; a++) { //same remainder of a and b in ax+b by 9 if(adj[a].size()>1 && (a*x+a)%9==k){ ans = findMin(ans, adj[a].get(0), adj[a].get(1)); } //different remainder of a and b in ax+b by 9 for (int b = 0; b < 9; b++) { if(a!=b && !adj[a].isEmpty() && !adj[b].isEmpty() && (a*x+b)%9==k){ ans = findMin(ans, adj[a].get(0), adj[b].get(0)); } } } if(ans[0]==Integer.MAX_VALUE)out.println("-1 -1"); else out.println((ans[0]+1)+" "+(ans[1]+1)); } } private static int[] findMin(int[] ans, int a, int b) { if(ans[0]>a || (ans[0]==a && ans[1]>b)){ return new int[]{a,b}; } return ans; } static class Pair implements Comparable<Pair> { int a; int b; Pair(int a, int b) { this.a = a; this.b = b; } public int compareTo(Pair p) { if (a != p.a) return a - p.a; return p.b - b; } @Override public String toString() { return "Pair{" + "a=" + a + ", b=" + b + '}'; } } private static int[] sortByCollections(int[] arr, boolean reverse) { ArrayList<Integer> ls = new ArrayList<>(arr.length); for (int i = 0; i < arr.length; i++) { ls.add(arr[i]); } if(reverse)Collections.sort(ls, Comparator.reverseOrder()); else Collections.sort(ls); for (int i = 0; i < arr.length; i++) { arr[i] = ls.get(i); } return arr; } public static void main(String[] args) { fs = new FastScanner(); out = new PrintWriter(System.out); long s = System.currentTimeMillis(); int t = fs.nextInt(); for (int i = 1; i <= t; i++) solve(t); out.close(); // System.err.println( System.currentTimeMillis() - s + "ms" ); } static boolean DEBUG = true; static PrintWriter out; static FastScanner fs; static void trace(Object... o) { if (!DEBUG) return; System.err.println(Arrays.deepToString(o)); } static void pl(Object o) { out.println(o); } static void p(Object o) { out.print(o); } static long gcd(long a, long b) { return (b == 0) ? a : gcd(b, a % b); } static int gcd(int a, int b) { return (b == 0) ? a : gcd(b, a % b); } static void sieveOfEratosthenes(int n, int factors[]) { factors[1] = 1; for (int p = 2; p * p <= n; p++) { if (factors[p] == 0) { factors[p] = p; for (int i = p * p; i <= n; i += p) factors[i] = p; } } } static long mul(long a, long b) { return a * b % mod; } static long fact(int x) { long ans = 1; for (int i = 2; i <= x; i++) ans = mul(ans, i); return ans; } static long fastPow(long base, long exp) { if (exp == 0) return 1; long half = fastPow(base, exp / 2); if (exp % 2 == 0) return mul(half, half); return mul(half, mul(half, base)); } static long modInv(long x) { return fastPow(x, mod - 2); } static long nCk(int n, int k) { return mul(fact(n), mul(modInv(fact(k)), modInv(fact(n - k)))); } static class FastScanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); public String next() { while (!st.hasMoreElements()) try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } long nextLong() { return Long.parseLong(next()); } } static class _Scanner { InputStream is; _Scanner(InputStream is) { this.is = is; } byte[] bb = new byte[1 << 15]; int k, l; byte getc() throws IOException { if (k >= l) { k = 0; l = is.read(bb); if (l < 0) return -1; } return bb[k++]; } byte skip() throws IOException { byte b; while ((b = getc()) <= 32) ; return b; } int nextInt() throws IOException { int n = 0; for (byte b = skip(); b > 32; b = getc()) n = n * 10 + b - '0'; return n; } } }
Java
["5\n\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
0817e738b6d05e88e9166757f9bd9b44
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.HashMap; import java.util.LinkedList; import java.util.TreeSet; public class Main { static InputReader in; static OutputWriter out; public static void main(String[] args) throws Exception { in=new InputReader(System.in); out=new OutputWriter(System.out); int T=in.nextInt(); while(T-->0) { char[] str=(" "+in.next()).toCharArray(); int[] pre=new int[str.length]; for(int i=1;i<str.length;i++) pre[i]=pre[i-1]+str[i]-'0'; int w=in.nextInt(); int m=in.nextInt(); HashMap<Integer,TreeSet<Integer>> map=new HashMap<>(); for(int i=w;i<str.length;i++) { int t=(pre[i]-pre[i-w])%9; if(!map.containsKey(t)) map.put(t,new TreeSet<>()); map.get(t).add(i); } while(m-->0) { int l=in.nextInt(); int r=in.nextInt(); int k=in.nextInt(); int a=(pre[r]-pre[l-1])%9; int ans1=Integer.MAX_VALUE,ans2=Integer.MAX_VALUE; for(int i=0;i<=9;i++) { for(int j=0;j<=9;j++) { int temp1=Integer.MAX_VALUE; int temp2=Integer.MAX_VALUE; if((i*a+j)%9==k) { if(i!=j) { if(map.containsKey(i) && map.containsKey(j)) { temp1=map.get(i).first()-w+1; temp2=map.get(j).first()-w+1; } } else { if(map.containsKey(i) && map.get(i).size()>1) { temp1=map.get(i).first()-w+1; temp2=map.get(j).higher(map.get(i).first())-w+1; } } } if(temp1<ans1) { ans1=temp1; ans2=temp2; } else if(temp1==ans1) { if(temp2<ans2) { ans1=temp1; ans2=temp2; } } } } if(ans1==Integer.MAX_VALUE) { ans1=-1; ans2=-1; } out.println(ans1+" "+ans2); } } out.flush(); } static class InputReader { private final 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 OutputWriter { private final BufferedWriter writer; public OutputWriter(OutputStream out) { writer=new BufferedWriter(new OutputStreamWriter(out)); } public void print(String str) { try { writer.write(str); } catch (IOException e) { e.printStackTrace(); } } public void print(Object obj) { print(String.valueOf(obj)); } public void println(String str) { print(str+"\n"); } public void println() { print('\n'); } public void println(Object obj) { println(String.valueOf(obj)); } public void flush() { try { writer.flush(); } 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
c61c61e465bec8be35dfd16f11cec8d6
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 codeforces.round820div3; import java.io.*; import java.util.*; import static java.lang.Math.*; public class F { static InputReader in; static PrintWriter out; public static void main(String[] args) { //initReaderPrinter(true); initReaderPrinter(false); solve(in.nextInt()); //solve(1); } /* General tips 1. It is ok to fail, but it is not ok to fail for the same mistakes over and over! 2. Train smarter, not harder! 3. If you find an answer and want to return immediately, don't forget to flush before return! */ /* Read before practice 1. Set a timer based on a problem's difficulty level: 45 minutes at your current target practice level; 2. During a problem solving session, focus! Do not switch problems or even worse switch to do something else; 3. If fail to solve within timer limit, read editorials to get as little help as possible to get yourself unblocked; 4. If after reading the entire editorial and other people's code but still can not solve, move this problem to to-do list and re-try in the future. 5. Keep a practice log about new thinking approaches, good tricks, bugs; Review regularly; 6. Also try this new approach suggested by um_nik: Solve with no intention to read editorial. If getting stuck, skip it and solve other similar level problems. Wait for 1 week then try to solve again. Only read editorial after you solved a problem. 7. Remember to also submit in the original problem link (if using gym) so that the 1 v 1 bot knows which problems I have solved already. 8. Form the habit of writing down an implementable solution idea before coding! You've taken enough hits during contests because you rushed to coding! */ /* Read before contests and lockout 1 v 1 Mistakes you've made in the past contests: 1. Tried to solve without going through given test examples -> wasting time on solving a different problem than asked; 2. Rushed to coding without getting a comprehensive sketch of your solution -> implementation bugs and WA; Write down your idea step by step, no need to rush. It is always better to have all the steps considered before hand! Think about all the past contests that you have failed because slow implementation and implementation bugs! This will be greatly reduced if you take your time to get a thorough idea steps! 3. Forgot about possible integer overflow; When stuck: 1. Understand problem statements? Walked through test examples? 2. Take a step back and think about other approaches? 3. Check rank board to see if you can skip to work on a possibly easier problem? 4. If none of the above works, take a guess? */ static void solve(int testCnt) { for (int testNumber = 0; testNumber < testCnt; testNumber++) { char[] s = in.next().toCharArray(); int n = s.length, w = in.nextInt(), m = in.nextInt(); int[] minIdx = new int[9], secondMinIdx = new int[9]; Arrays.fill(minIdx, -1); Arrays.fill(secondMinIdx, -1); int[] prefix = new int[n]; prefix[0] = (s[0] - '0') % 9; for(int i = 1; i < n; i++) { prefix[i] = (prefix[i - 1] * 10 + (s[i] - '0')) % 9; } for(int i = 0; i + w <= s.length; i++) { int v = (prefix[i + w - 1] - (i > 0 ? prefix[i - 1] : 0) + 9) % 9; if(minIdx[v] < 0) { minIdx[v] = i; } else if(secondMinIdx[v] < 0) { secondMinIdx[v] = i; } } for(int i = 0; i < m; i++) { int l = in.nextInt() - 1, r = in.nextInt() - 1, k = in.nextInt(); int v = (prefix[r] - (l > 0 ? prefix[l - 1] : 0) + 9) % 9; int ans1 = n, ans2 = n; for(int d1 = 0; d1 <= 8; d1++) { if(minIdx[d1] >= 0) { for(int d2 = 0; d2 <= 8; d2++) { if(minIdx[d2] >= 0) { if((d1 * v + d2) % 9 == k) { int p1 = n, p2 = n; if(d1 != d2) { p1 = minIdx[d1]; p2 = minIdx[d2]; } else if(secondMinIdx[d1] >= 0){ p1 = minIdx[d1]; p2 = secondMinIdx[d1]; } if(p1 < ans1) { ans1 = p1; ans2 = p2; } else if(p1 == ans1) { if(p2 < ans2) { ans2 = p2; } } } } } } } if(ans1 < n) { out.println((ans1 + 1) + " " + (ans2 + 1)); } else { out.println((-1) + " " + (-1)); } } } out.close(); } static void initReaderPrinter(boolean test) { if (test) { try { in = new InputReader(new FileInputStream("src/input.in")); out = new PrintWriter(new FileOutputStream("src/output.out")); } catch (IOException e) { e.printStackTrace(); } } else { in = new InputReader(System.in); out = new PrintWriter(System.out); } } static class InputReader { BufferedReader br; StringTokenizer st; InputReader(InputStream stream) { try { br = new BufferedReader(new InputStreamReader(stream), 32768); } catch (Exception e) { e.printStackTrace(); } } 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(); } catch (IOException e) { e.printStackTrace(); } return str; } Integer[] nextIntArray(int n) { Integer[] a = new Integer[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } int[] nextIntArrayPrimitive(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } int[] nextIntArrayPrimitiveOneIndexed(int n) { int[] a = new int[n + 1]; for (int i = 1; i <= n; i++) a[i] = nextInt(); return a; } Long[] nextLongArray(int n) { Long[] a = new Long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } long[] nextLongArrayPrimitive(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } long[] nextLongArrayPrimitiveOneIndexed(int n) { long[] a = new long[n + 1]; for (int i = 1; i <= n; i++) a[i] = nextLong(); return a; } String[] nextStringArray(int n) { String[] g = new String[n]; for (int i = 0; i < n; i++) g[i] = next(); return g; } List<Integer>[] readGraphOneIndexed(int n, int m) { List<Integer>[] adj = new List[n + 1]; for (int i = 0; i <= n; i++) { adj[i] = new ArrayList<>(); } for (int i = 0; i < m; i++) { int u = nextInt(); int v = nextInt(); adj[u].add(v); adj[v].add(u); } return adj; } List<Integer>[] readGraphZeroIndexed(int n, int m) { List<Integer>[] adj = new List[n]; for (int i = 0; i < n; i++) { adj[i] = new ArrayList<>(); } for (int i = 0; i < m; i++) { int u = nextInt() - 1; int v = nextInt() - 1; adj[u].add(v); adj[v].add(u); } return adj; } /* A more efficient way of building an undirected graph using int[] instead of ArrayList to store each node's neighboring nodes. 1-indexed. */ int[][] buildUndirectedGraph(int nodeCnt, int edgeCnt) { int[] end1 = new int[edgeCnt], end2 = new int[edgeCnt]; int[] edgeCntForEachNode = new int[nodeCnt + 1], idxForEachNode = new int[nodeCnt + 1]; for (int i = 0; i < edgeCnt; i++) { int u = in.nextInt(), v = in.nextInt(); edgeCntForEachNode[u]++; edgeCntForEachNode[v]++; end1[i] = u; end2[i] = v; } int[][] adj = new int[nodeCnt + 1][]; for (int i = 1; i <= nodeCnt; i++) { adj[i] = new int[edgeCntForEachNode[i]]; } for (int i = 0; i < edgeCnt; i++) { adj[end1[i]][idxForEachNode[end1[i]]] = end2[i]; idxForEachNode[end1[i]]++; adj[end2[i]][idxForEachNode[end2[i]]] = end1[i]; idxForEachNode[end2[i]]++; } return adj; } /* A more efficient way of building an undirected weighted graph using int[] instead of ArrayList to store each node's neighboring nodes. 1-indexed. */ int[][][] buildUndirectedWeightedGraph(int nodeCnt, int edgeCnt) { int[] end1 = new int[edgeCnt], end2 = new int[edgeCnt], weight = new int[edgeCnt]; int[] edgeCntForEachNode = new int[nodeCnt + 1], idxForEachNode = new int[nodeCnt + 1]; for (int i = 0; i < edgeCnt; i++) { int u = in.nextInt(), v = in.nextInt(), w = in.nextInt(); edgeCntForEachNode[u]++; edgeCntForEachNode[v]++; end1[i] = u; end2[i] = v; weight[i] = w; } int[][][] adj = new int[nodeCnt + 1][][]; for (int i = 1; i <= nodeCnt; i++) { adj[i] = new int[edgeCntForEachNode[i]][2]; } for (int i = 0; i < edgeCnt; i++) { adj[end1[i]][idxForEachNode[end1[i]]][0] = end2[i]; adj[end1[i]][idxForEachNode[end1[i]]][1] = weight[i]; idxForEachNode[end1[i]]++; adj[end2[i]][idxForEachNode[end2[i]]][0] = end1[i]; adj[end2[i]][idxForEachNode[end2[i]]][1] = weight[i]; idxForEachNode[end2[i]]++; } return adj; } /* A more efficient way of building a directed graph using int[] instead of ArrayList to store each node's neighboring nodes. 1-indexed. */ int[][] buildDirectedGraph(int nodeCnt, int edgeCnt) { int[] from = new int[edgeCnt], to = new int[edgeCnt]; int[] edgeCntForEachNode = new int[nodeCnt + 1], idxForEachNode = new int[nodeCnt + 1]; //from u to v: u -> v for (int i = 0; i < edgeCnt; i++) { int u = in.nextInt(), v = in.nextInt(); edgeCntForEachNode[u]++; from[i] = u; to[i] = v; } int[][] adj = new int[nodeCnt + 1][]; for (int i = 1; i <= nodeCnt; i++) { adj[i] = new int[edgeCntForEachNode[i]]; } for (int i = 0; i < edgeCnt; i++) { adj[from[i]][idxForEachNode[from[i]]] = to[i]; idxForEachNode[from[i]]++; } return adj; } /* A more efficient way of building a directed weighted graph using int[] instead of ArrayList to store each node's neighboring nodes. 1-indexed. */ int[][][] buildDirectedWeightedGraph(int nodeCnt, int edgeCnt) { int[] from = new int[edgeCnt], to = new int[edgeCnt], weight = new int[edgeCnt]; int[] edgeCntForEachNode = new int[nodeCnt + 1], idxForEachNode = new int[nodeCnt + 1]; //from u to v: u -> v for (int i = 0; i < edgeCnt; i++) { int u = in.nextInt(), v = in.nextInt(), w = in.nextInt(); edgeCntForEachNode[u]++; from[i] = u; to[i] = v; weight[i] = w; } int[][][] adj = new int[nodeCnt + 1][][]; for (int i = 1; i <= nodeCnt; i++) { adj[i] = new int[edgeCntForEachNode[i]][2]; } for (int i = 0; i < edgeCnt; i++) { adj[from[i]][idxForEachNode[from[i]]][0] = to[i]; adj[from[i]][idxForEachNode[from[i]]][1] = weight[i]; idxForEachNode[from[i]]++; } return adj; } } }
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
172cedf5485693208e3c001d8004f00c
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 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 FastReader s = new FastReader(); static PrintWriter out = new PrintWriter(System.out); private static int[] rai(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = s.nextInt(); } return arr; } private static int[][] rai(int n, int m) { int[][] arr = new int[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { arr[i][j] = s.nextInt(); } } return arr; } private static long[] ral(int n) { long[] arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = s.nextLong(); } return arr; } private static long[][] ral(int n, int m) { long[][] arr = new long[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { arr[i][j] = s.nextLong(); } } return arr; } private static int ri() { return s.nextInt(); } private static long rl() { return s.nextLong(); } private static String rs() { return s.next(); } static int gcd(int a, int b) { if (b == 0) { return a; } return gcd(b, a % b); } static long gcd(long a, long b) { if (b == 0) { return a; } return gcd(b, a % b); } static int MOD = (int) (1e9 + 7); public static void primeFactors(int n) { // Print the number of 2s that divide n while (n % 2 == 0) { System.out.print(2 + " "); n /= 2; } // n must be odd at this point. So we can // skip one element (Note i = i +2) for (int i = 3; i <= Math.sqrt(n); i += 2) { // While i divides n, print i and divide n while (n % i == 0) { System.out.print(i + " "); n /= i; } } // This condition is to handle the case whien // n is a prime number greater than 2 if (n > 2) System.out.print(n); System.out.println(); } static boolean isPrime(int val) { for (int i = 2; i <= Math.sqrt(val); i++) { if (val % i == 0) { return false; } } return true; } static long pow(long x, long y, long n) { if (y == 0) { return 1; } long val = pow(x, y / 2, n); if (y % 2 == 1) { return (((val * val) % n) * x) % n; } else { return (val * val) % n; } } public static void main(String[] args) { StringBuilder ans = new StringBuilder(); int t = ri(); // int t=1; while (t-- > 0) { String str=rs(); int n=str.length(); int[] arr=new int[n]; for(int i=0;i<n;i++) { arr[i] = Character.getNumericValue(str.charAt(i)); } // System.out.println(Arrays.toString(arr)); int[] prefSum =new int[n]; int sum =0 ; for(int i=0;i<n;i++) { sum+=arr[i]; prefSum[i] = sum; } // System.out.println(Arrays.toString(prefSum)); List<Integer>[] list = new ArrayList[9]; for(int i=0;i<9;i++) { list[i] = new ArrayList<>(); } int w = ri(); int m=ri(); for(int i=0;i<=n-w;i++) { int currSum = prefSum[i+w-1]; if(i>0) { currSum-=prefSum[i-1]; } currSum%=9; list[currSum].add(i+1); } // System.out.println(Arrays.toString(list)); for(int i=0;i<m;i++) { int l=ri()-1; int r=ri()-1; int k=ri(); int currSum = prefSum[r]; if(l>0) { currSum-=prefSum[l-1]; } currSum%=9; // System.out.println(currSum); boolean found = false; int l1=Integer.MAX_VALUE, l2=Integer.MIN_VALUE; for(int j=0;j<9;j++) { int val = currSum*j; val%=9; int req = (k>=val)?(k-val):(k-val+9); req%=9; // System.out.println(j+" "+val+" "+req); if(j==req) { if(list[j].size()>=2) { int val1 = Math.min(list[j].get(0), list[j].get(1)); int val2=Math.max(list[j].get(0), list[j].get(1)); if(val1<l1) { l1=val1; l2=val2; } else if(val1 == l1) { if(val2<l2) { l2=val2; } } // ans.append(list[val].get(0)).append(" ").append(list[val].get(1)).append("\n"); } } else { if(list[j].size()>0 && list[req].size()>0) { int val1 = list[j].get(0); int val2 = list[req].get(0); if (val1 < l1) { l1 = val1; l2 = val2; } else if (val1 == l1) { if (val2 < l2) { l2 = val2; } } } } } if(l1 == Integer.MAX_VALUE) { ans.append("-1 -1\n"); } else { ans.append(l1).append(" ").append(l2).append("\n"); } } } out.print(ans); 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 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
05c7f3790329e039c995ce77bef89535
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.HashMap; import java.util.TreeSet; public class Main { static InputReader sc; public static void main(String[] args) throws Exception { sc=new InputReader(System.in); int T=sc.nextInt(); while(T-->0) { char[] str=(" "+sc.next()).toCharArray(); int[] pre=new int[str.length]; for(int i=1;i<str.length;i++) pre[i]=pre[i-1]+str[i]-'0'; int w=sc.nextInt(); int m=sc.nextInt(); HashMap<Integer,TreeSet<Integer>> map=new HashMap<>(); for(int i=w;i<str.length;i++) { int t=(pre[i]-pre[i-w])%9; if(!map.containsKey(t)) map.put(t,new TreeSet<>()); map.get(t).add(i); } while(m-->0) { int l=sc.nextInt(); int r=sc.nextInt(); int k=sc.nextInt(); int a=(pre[r]-pre[l-1])%9; int ans1=Integer.MAX_VALUE,ans2=Integer.MAX_VALUE; for(int i=0;i<=9;i++) { for(int j=0;j<=9;j++) { int temp1=Integer.MAX_VALUE; int temp2=Integer.MAX_VALUE; if((i*a+j)%9==k) { if(i!=j) { if(map.containsKey(i) && map.containsKey(j)) { temp1=map.get(i).first()-w+1; temp2=map.get(j).first()-w+1; } } else { if(map.containsKey(i) && map.get(i).size()>1) { temp1=map.get(i).first()-w+1; temp2=map.get(j).higher(map.get(i).first())-w+1; } } } if(temp1<ans1) { ans1=temp1; ans2=temp2; } else if(temp1==ans1) { if(temp2<ans2) { ans1=temp1; ans2=temp2; } } } } if(ans1==Integer.MAX_VALUE) { ans1=-1; ans2=-1; } System.out.println(ans1+" "+ans2); } } } 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()); } } }
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
244e7e1cea25f787ac7b7f0cf5eab767
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 { static Scanner sc; static PrintWriter pw; static long Pow(long a, long e, long mod) // O(log e) { a %= mod; long res = 1l; while (e > 0) { if ((e & 1) == 1) res = (res * a) % mod; a = (a * a) % mod; e >>= 1l; } return res; } static long modinverse(long a, long mod) { return Pow(a, mod - 2, mod); } static long calc(int i, int j, int n, long[] pre) { long sum = pre[i]; if (j < n - 1) { sum -= pre[j + 1]; } if (sum < 0) sum += 9; sum %= 9; return sum; } public static void main(String[] args) throws Exception { pw = new PrintWriter(System.out); sc = new Scanner(System.in); int t = sc.nextInt(); for (int tc = 1; tc <= t; tc++) { char[] arr = sc.next().toCharArray(); int w = sc.nextInt(), m = sc.nextInt(); int n = arr.length; long[] pre = new long[n]; for (int i = n - 1; i >= 0; i--) { int cur = arr[i] - '0'; pre[i] = cur; if (i < n - 1) { pre[i] += pre[i + 1]; } pre[i] %= 9; } TreeSet<Integer>[] all = new TreeSet[9]; for (int i = 0; i < 9; i++) { all[i] = new TreeSet<>(); } for (int i = 0; i <= n - w; i++) { int val = (int) calc(i, i + w - 1, n, pre); if (all[val].size() >= 2) continue; all[val].add(i); } ArrayList<long[]> preAll = new ArrayList<>(); for (int i = 0; i < 9; i++) { while (!all[i].isEmpty()) { long cur = all[i].pollFirst(); long val = calc((int) cur, (int) cur + w - 1, n, pre); preAll.add(new long[] { cur, val }); } } while (m-- > 0) { int l = sc.nextInt() - 1, r = sc.nextInt() - 1; int k = sc.nextInt(); long val = calc(l, r, n, pre); long ansL = -2, ansR = -2; for (int i = 0; i < preAll.size(); i++) { for (int j = 0; j < preAll.size(); j++) { if (i == j) continue; long[] cur1 = preAll.get(i), cur2 = preAll.get(j); if ((val * cur1[1] + cur2[1]) % 9 == k) { if (ansL == -2 || ansL > cur1[0] || (ansL == cur1[0] && cur2[0] < ansR)) { ansL = cur1[0]; ansR = cur2[0]; } } } } pw.println(ansL + 1 + " " + (ansR + 1)); } } pw.flush(); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public Scanner(String r) throws Exception { br = new BufferedReader(new FileReader(new File(r))); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public long[] nextlongArray(int n) throws IOException { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } public Long[] nextLongArray(int n) throws IOException { Long[] a = new Long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } public int[] nextIntArray(int n) throws IOException { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public Integer[] nextIntegerArray(int n) throws IOException { Integer[] a = new Integer[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public boolean ready() throws IOException { return br.ready(); } } }
Java
["5\n\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
a375d70ee0579a148806c46aef054d17
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 Solution { public static boolean useInFile = false; public static boolean useOutFile = false; public static void main(String args[]) throws IOException { InOut inout = new InOut(); Resolver resolver = new Resolver(inout); // long time = System.currentTimeMillis(); resolver.solve(); // resolver.print("\n" + (System.currentTimeMillis() - time)); inout.flush(); } private static class Resolver { final long LONG_INF = (long) 1e18; final int INF = (int) (1e9 + 7); final int MOD = 998244353; long f[], inv[]; InOut inout; Resolver(InOut inout) { this.inout = inout; } void initF(int n, int mod) { f = new long[n + 1]; f[1] = 1; for (int i = 2; i <= n; i++) { f[i] = (f[i - 1] * i) % mod; } } void initInv(int n, int mod) { inv = new long[n + 1]; inv[n] = pow(f[n], mod - 2, mod); for (int i = inv.length - 2; i >= 0; i--) { inv[i] = inv[i + 1] * (i + 1) % mod; } } long cmn(int n, int m, int mod) { return f[n] * inv[m] % mod * inv[n - m] % mod; } int d[] = {0, -1, 0, 1, 0}; boolean legal(int r, int c, int n, int m) { return r >= 0 && r < n && c >= 0 && c < m; } int[] getBits(int n) { int b[] = new int[31]; for (int i = 0; i < 31; i++) { if ((n & (1 << i)) != 0) { b[i] = 1; } } return b; } private long ask1(long l, long r) throws IOException { format("? %d %d\n", l, r); flush(); return nextLong(25); } void solve() throws IOException { int tt = 1; boolean hvt = true; if (hvt) { tt = nextInt(); // tt = Integer.parseInt(nextLine()); } // initF(300001, MOD); // initInv(300001, MOD); // boolean pri[] = generatePrime(40000); for (int cs = 1; cs <= tt; cs++) { long rs = 0; boolean ok = true; // int n = nextInt(); char s[] = next((int) (2e5 + 5)).toCharArray(); int n = s.length; int a[] = new int[n + 1]; long sum[] = new long[n + 1]; for (int i = 1; i <= n; i++) { a[i] = s[i - 1] - '0'; sum[i] = a[i] + sum[i - 1]; } int w = nextInt(); int m = nextInt(); int idx[][] = new int[9][2]; int x = 0; for (int i = n - w + 2; i <= n; i++) { x = (x + a[i]) % 9; } for (int i = n - w + 1; i >= 1; i--) { x = (x + a[i]) % 9; idx[x][1] = idx[x][0]; idx[x][0] = i; x = (x + 9 - a[i + w - 1]) % 9; } for (int i = 0; i < m; i++) { if (i > 0) { print("\n"); } int l = nextInt(); int r = nextInt(); int k = nextInt(); int mul = (int) ((sum[r] - sum[l - 1]) % 9); ok = false; int L1 = n + 1; int L2 = n + 1; for (int j = 0; j < 9; j++) { for (int o = 0; o < 9; o++) { if ((j * mul + o) % 9 == k) { if (j == o) { if (idx[j][1] > 0) { if (L1 > idx[j][0] || L1 == idx[j][0] && L2 > idx[j][1]) { L1 = idx[j][0]; L2 = idx[j][1]; } ok = true; break; } } else if (idx[j][0] > 0 && idx[o][0] > 0){ if (L1 > idx[j][0] || L1 == idx[j][0] && L2 > idx[o][0]) { L1 = idx[j][0]; L2 = idx[o][0]; } ok = true; } } } } if (!ok) { print("-1 -1"); } else { print(L1 + " " + L2); } } // print(ok ? "Yes" : "No"); // print(a, 0, s - 1); // print("! " + rs); // format("Case #%d: %d", cs, rs); if (cs < tt) { format("\n"); // flush(); // format(" "); } // flush(); } } private void updateSegTree(int n, long l, SegmentTree lft) { long lazy; lazy = 1; for (int j = 1; j <= l; j++) { lazy = (lazy + cmn((int) l, j, INF)) % INF; lft.modify(1, j, j, lazy); } lft.modify(1, (int) (l + 1), n, lazy); } String next() throws IOException { return inout.next(); } String next(int n) throws IOException { return inout.next(n); } String nextLine() throws IOException { return inout.nextLine(); } int nextInt() throws IOException { return inout.nextInt(); } long nextLong(int n) throws IOException { return inout.nextLong(n); } int[] anInt(int i, int j) throws IOException { int a[] = new int[j + 1]; for (int k = i; k <= j; k++) { a[k] = nextInt(); } return a; } long[] anLong(int i, int j) throws IOException { long a[] = new long[j + 1]; for (int k = i; k <= j; k++) { a[k] = nextInt(); } return a; } long[] anLong(int i, int j, int len) throws IOException { long a[] = new long[j + 1]; for (int k = i; k <= j; k++) { a[k] = nextLong(len); } return a; } void print(long a[], int l, int r) { for (int i = l; i <= r; i++) { format("%s%d", i > l ? " " : "", a[i]); } } void print(int a[], int l, int r) { for (int i = l; i <= r; i++) { format("%s%d", i > l ? "\n" : "", a[i]); } } void print(String s) { inout.print(s, false); } void print(String s, boolean nextLine) { inout.print(s, nextLine); } void format(String format, Object... obj) { inout.format(format, obj); } void flush() { inout.flush(); } void swap(int a[], int i, int j) { a[i] ^= a[j]; a[j] ^= a[i]; a[i] ^= a[j]; } void swap(long a[], int i, int j) { a[i] ^= a[j]; a[j] ^= a[i]; a[i] ^= a[j]; } int getP(int x, int p[]) { if (p[x] == 0 || p[x] == x) { return x; } return p[x] = getP(p[x], p); } void union(int x, int y, int p[]) { if (x < y) { p[y] = x; } else { p[x] = y; } } boolean topSort() { int n = adj2.length - 1; int d[] = new int[n + 1]; for (int i = 1; i <= n; i++) { for (int j = 0; j < adj2[i].size(); j++) { d[adj2[i].get(j)[0]]++; } } List<Integer> list = new ArrayList<>(); for (int i = 1; i <= n; i++) { if (d[i] == 0) { list.add(i); } } for (int i = 0; i < list.size(); i++) { for (int j = 0; j < adj2[list.get(i)].size(); j++) { int t = adj2[list.get(i)].get(j)[0]; d[t]--; if (d[t] == 0) { list.add(t); } } } return list.size() == n; } class DSU { int[] f, siz; DSU(int n) { f = new int[n]; siz = new int[n]; Arrays.fill(siz, 1); } int leader(int x) { while (x != f[x]) x = f[x] = f[f[x]]; return x; } boolean same(int x, int y) { return leader(x) == leader(y); } boolean merge(int x, int y) { x = leader(x); y = leader(y); if (x == y) return false; siz[x] += siz[y]; f[y] = x; return true; } int size(int x) { return siz[leader(x)]; } } ; class SegmentTreeNode { long defaultVal = 0; int l, r; // long val = Integer.MAX_VALUE; long val = 0; long lazy = defaultVal; SegmentTreeNode(int l, int r) { this.l = l; this.r = r; } } class SegmentTree { SegmentTreeNode tree[]; long inf = Long.MIN_VALUE; long c[]; SegmentTree(int n) { assert n > 0; tree = new SegmentTreeNode[n * 3 + 1]; } void setAn(long cn[]) { c = cn; } SegmentTree build(int k, int l, int r) { if (l > r) { return this; } if (null == tree[k]) { tree[k] = new SegmentTreeNode(l, r); } if (l == r) { // tree[k].val = c[l]; return this; } int mid = (l + r) >> 1; build(k << 1, l, mid); build(k << 1 | 1, mid + 1, r); tree[k].val = (tree[k << 1].val + tree[k << 1 | 1].val) % MOD; // tree[k].val = Math.min(tree[k << 1].val, tree[k << 1 | 1].val); return this; } void pushDown(int k) { if (tree[k].l == tree[k].r) { return; } long lazy = tree[k].lazy; // tree[k << 1].val = ((c[tree[k << 1].l] - c[tree[k << 1].r + 1] + MOD) % MOD * lazy) % MOD; tree[k << 1].val += lazy; tree[k << 1].lazy += lazy; // tree[k << 1 | 1].val = ((c[tree[k << 1 | 1].l] - c[tree[k << 1 | 1].r + 1] + MOD) % MOD * lazy) % MOD; tree[k << 1 | 1].val += lazy; tree[k << 1 | 1].lazy += lazy; tree[k].lazy = 0; } void modify(int k, int l, int r, long change) { if (tree[k].l >= l && tree[k].r <= r) { // tree[k].val = ((c[tree[k].l] - c[tree[k].r + 1] + MOD) % MOD * val) % MOD; tree[k].val += change; tree[k].lazy += change; return; } int mid = (tree[k].l + tree[k].r) >> 1; if (tree[k].lazy != 0) { pushDown(k); } if (mid >= l) { modify(k << 1, l, r, change); } if (mid + 1 <= r) { modify(k << 1 | 1, l, r, change); } tree[k].val = (tree[k << 1].val + tree[k << 1 | 1].val) % MOD; // tree[k].val = Math.min(tree[k << 1].val, tree[k << 1 | 1].val); } long query(int k, int l, int r) { if (tree[k].l > r || tree[k].r < l) { return 0; } if (tree[k].lazy != 0) { pushDown(k); } if (tree[k].l >= l && tree[k].r <= r) { return tree[k].val; } long ans = (query(k << 1, l, r) + query(k << 1 | 1, l, r)) % MOD; if (tree[k].l < tree[k].r) { tree[k].val = (tree[k << 1].val + tree[k << 1 | 1].val) % MOD; // tree[k].val = Math.min(tree[k << 1].val, tree[k << 1 | 1].val); } return ans; } } class BitMap { boolean[] vis = new boolean[32]; List<Integer> g[]; void init() { for (int i = 0; i < 32; i++) { g = new List[32]; g[i] = new ArrayList<>(); } } void dfs(int p) { if (vis[p]) return; vis[p] = true; for (int it : g[p]) dfs(it); } boolean connected(int a[], int n) { int m = 0; for (int i = 0; i < n; i++) if (a[i] == 0) return false; for (int i = 0; i < n; i++) m |= a[i]; for (int i = 0; i < 31; i++) g[i].clear(); for (int i = 0; i < n; i++) { int last = -1; for (int j = 0; j < 31; j++) if ((a[i] & (1 << j)) > 0) { if (last != -1) { g[last].add(j); g[j].add(last); } last = j; } } Arrays.fill(vis, false); for (int j = 0; j < 31; j++) if (((1 << j) & m) > 0) { dfs(j); break; } for (int j = 0; j < 31; j++) if (((1 << j) & m) > 0 && !vis[j]) return false; return true; } } class BinaryIndexedTree { int n = 1; long C[]; BinaryIndexedTree(int sz) { while (n <= sz) { n <<= 1; } n = sz + 1; C = new long[n]; } int lowbit(int x) { return x & -x; } void add(int x, long val) { while (x < n) { C[x] += val; x += lowbit(x); } } long getSum(int x) { long res = 0; while (x > 0) { res += C[x]; x -= lowbit(x); } return res; } int binSearch(long sum) { if (sum == 0) { return 0; } int n = C.length; int mx = 1; while (mx < n) { mx <<= 1; } int res = 0; for (int i = mx / 2; i >= 1; i >>= 1) { if (C[res + i] < sum) { sum -= C[res + i]; res += i; } } return res + 1; } } static class TrieNode { int cnt = 0; TrieNode next[]; TrieNode() { next = new TrieNode[2]; } private void insert(TrieNode trie, int ch[], int i) { while (i < ch.length) { int idx = ch[i]; if (null == trie.next[idx]) { trie.next[idx] = new TrieNode(); } trie.cnt++; trie = trie.next[idx]; i++; } } private static int query(TrieNode trie) { if (null == trie) { return 0; } int ans[] = new int[2]; for (int i = 0; i < trie.next.length; i++) { if (null == trie.next[i]) { continue; } ans[i] = trie.next[i].cnt; } if (ans[0] == 0 && ans[0] == ans[1]) { return 0; } if (ans[0] == 0) { return query(trie.next[1]); } if (ans[1] == 0) { return query(trie.next[0]); } return Math.min(ans[0] - 1 + query(trie.next[1]), ans[1] - 1 + query(trie.next[0])); } } //Binary tree class TreeNode { int val; int tier = -1; TreeNode parent; TreeNode left; TreeNode right; TreeNode(int val) { this.val = val; } } //binary tree dfs void tierTree(TreeNode root) { if (null == root) { return; } if (null != root.parent) { root.tier = root.parent.tier + 1; } else { root.tier = 0; } tierTree(root.left); tierTree(root.right); } //LCA start TreeNode[][] lca; TreeNode[] tree; void lcaDfsTree(TreeNode root) { if (null == root) { return; } tree[root.val] = root; TreeNode nxt = root.parent; int idx = 0; while (null != nxt) { lca[root.val][idx] = nxt; nxt = lca[nxt.val][idx]; idx++; } lcaDfsTree(root.left); lcaDfsTree(root.right); } TreeNode lcaTree(TreeNode root, int n, TreeNode x, TreeNode y) throws IOException { if (null == root) { return null; } if (-1 == root.tier) { tree = new TreeNode[n + 1]; tierTree(root); } if (null == lca) { lca = new TreeNode[n + 1][31]; lcaDfsTree(root); } int z = Math.abs(x.tier - y.tier); int xx = x.tier > y.tier ? x.val : y.val; while (z > 0) { final int zz = z; int l = (int) BinSearch.bs(0, 31 , k -> zz < (1 << k)); xx = lca[xx][l].val; z -= 1 << l; } int yy = y.val; if (x.tier <= y.tier) { yy = x.val; } while (xx != yy) { final int xxx = xx; final int yyy = yy; int l = (int) BinSearch.bs(0, 31 , k -> (1 << k) <= tree[xxx].tier && lca[xxx][(int) k] != lca[yyy][(int) k]); xx = lca[xx][l].val; yy = lca[yy][l].val; } return tree[xx]; } //LCA end //graph List<Integer> adj[]; List<int[]> adj2[]; void initGraph(int n) throws IOException { initGraph(n, 0, false, false, 1, false); } void initGraph(int n, int m, boolean hasW, boolean directed, int type, boolean useInput) throws IOException { if (type == 1) { adj = new List[n + 1]; } else { adj2 = new List[n + 1]; } for (int i = 1; i <= n; i++) { if (type == 1) { adj[i] = new ArrayList<>(); } else { adj2[i] = new ArrayList<>(); } } if (!useInput) return; for (int i = 0; i < m; i++) { int f = nextInt(); int t = nextInt(); if (type == 1) { adj[f].add(t); if (!directed) { adj[t].add(f); } } else { int w = hasW ? nextInt() : 0; adj2[f].add(new int[]{t, w}); if (!directed) { adj2[t].add(new int[]{f, w}); } } } } void getDiv(Map<Integer, Integer> map, long n) { int sqrt = (int) Math.sqrt(n); for (int i = 2; i <= sqrt; i++) { int cnt = 0; while (n % i == 0) { cnt++; n /= i; } if (cnt > 0) { map.put(i, cnt); } } if (n > 1) { map.put((int) n, 1); } } boolean[] generatePrime(int n) { boolean p[] = new boolean[n + 1]; p[2] = true; for (int i = 3; i <= n; i += 2) { p[i] = true; } for (int i = 3; i <= Math.sqrt(n); i += 2) { if (!p[i]) { continue; } for (int j = i * i; j <= n; j += i << 1) { p[j] = false; } } return p; } boolean isPrime(long n) { //determines if n is a prime number int p[] = {2, 3, 5, 233, 331}; int pn = p.length; long s = 0, t = n - 1;//n - 1 = 2^s * t while ((t & 1) == 0) { t >>= 1; ++s; } for (int i = 0; i < pn; ++i) { if (n == p[i]) { return true; } long pt = pow(p[i], t, n); for (int j = 0; j < s; ++j) { long cur = llMod(pt, pt, n); if (cur == 1 && pt != 1 && pt != n - 1) { return false; } pt = cur; } if (pt != 1) { return false; } } return true; } long[] llAdd2(long a[], long b[], long mod) { long c[] = new long[2]; c[1] = (a[1] + b[1]) % (mod * mod); c[0] = (a[1] + b[1]) / (mod * mod) + a[0] + b[0]; return c; } long[] llMod2(long a, long b, long mod) { long x1 = a / mod; long y1 = a % mod; long x2 = b / mod; long y2 = b % mod; long c = (x1 * y2 + x2 * y1) / mod; c += x1 * x2; long d = (x1 * y2 + x2 * y1) % mod * mod + y1 * y2; return new long[]{c, d}; } long llMod(long a, long b, long mod) { if (a > mod || b > mod) { return (a * b - (long) ((double) a / mod * b + 0.5) * mod + mod) % mod; } return a * b % mod; // long r = 0; // a %= mod; // b %= mod; // while (b > 0) { // if ((b & 1) == 1) { // r = (r + a) % mod; // } // b >>= 1; // a = (a << 1) % mod; // } // return r; } long pow(long a, long n) { long ans = 1; while (n > 0) { if ((n & 1) == 1) { ans = ans * a; } a = a * a; n >>= 1; } return ans; } long pow(long a, long n, long mod) { long ans = 1; while (n > 0) { if ((n & 1) == 1) { ans = llMod(ans, a, mod); } a = llMod(a, a, mod); n >>= 1; } return ans; } private long[][] initC(int n) { long c[][] = new long[n][n]; for (int i = 0; i < n; i++) { c[i][0] = 1; } for (int i = 1; i < n; i++) { for (int j = 1; j <= i; j++) { c[i][j] = c[i - 1][j - 1] + c[i - 1][j]; } } return c; } /** * ps: n >= m, choose m from n; */ // private int cmn(long n, long m) { // if (m > n) { // n ^= m; // m ^= n; // n ^= m; // } // m = Math.min(m, n - m); // // long top = 1; // long bot = 1; // for (long i = n - m + 1; i <= n; i++) { // top = (top * i) % MOD; // } // for (int i = 1; i <= m; i++) { // bot = (bot * i) % MOD; // } // // return (int) ((top * pow(bot, MOD - 2, MOD)) % MOD); // } long[] exGcd(long a, long b) { if (b == 0) { return new long[]{a, 1, 0}; } long[] ans = exGcd(b, a % b); long x = ans[2]; long y = ans[1] - a / b * ans[2]; ans[1] = x; ans[2] = y; return ans; } long gcd(long a, long b) { if (a < b) { return gcd(b, a); } while (b != 0) { long tmp = a % b; a = b; b = tmp; } return a; } int[] unique(int a[], Map<Integer, Integer> idx) { int tmp[] = a.clone(); Arrays.sort(tmp); int j = 0; for (int i = 0; i < tmp.length; i++) { if (i == 0 || tmp[i] > tmp[i - 1]) { idx.put(tmp[i], j++); } } int rs[] = new int[j]; j = 0; for (int key : idx.keySet()) { rs[j++] = key; } Arrays.sort(rs); return rs; } boolean isEven(long n) { return (n & 1) == 0; } static class BinSearch { static long bs(long l, long r, IBinSearch sort) throws IOException { while (l < r) { long m = l + (r - l) / 2; if (sort.binSearchCmp(m)) { l = m + 1; } else { r = m; } } return l; } interface IBinSearch { boolean binSearchCmp(long k) throws IOException; } } } private static class InOut { private BufferedReader br; private StreamTokenizer st; private PrintWriter pw; InOut() throws FileNotFoundException { if (useInFile) { System.setIn(new FileInputStream("resources/inout/in.text")); } if (useOutFile) { System.setOut(new PrintStream("resources/inout/out.text")); } br = new BufferedReader(new InputStreamReader(System.in)); st = new StreamTokenizer(br); pw = new PrintWriter(new OutputStreamWriter(System.out)); st.ordinaryChar('\''); st.ordinaryChar('\"'); st.ordinaryChar('/'); } private boolean hasNext() throws IOException { return st.nextToken() != StreamTokenizer.TT_EOF; } private String next() throws IOException { if (st.nextToken() == StreamTokenizer.TT_EOF) { throw new IOException(); } return st.sval; } private String next(int n) throws IOException { return next(n, false); } private String next(int len, boolean isDigit) throws IOException { char ch[] = new char[len]; int cur = 0; char c; while ((c = (char) br.read()) == '\n' || c == '\r' || c == ' ' || c == '\t' || (isDigit && (c < '0' || c > '9') && c != '-' && c != '+')) ; do { ch[cur++] = c; } while (!((c = (char) br.read()) == '\n' || c == '\r' || c == ' ' || c == '\t') && (!isDigit || c >= '0' && c <= '9')); return String.valueOf(ch, 0, cur); } private int nextInt() throws IOException { if (st.nextToken() == StreamTokenizer.TT_EOF) { throw new IOException(); } return (int) st.nval; } private long nextLong(int n) throws IOException { return Long.parseLong(next(n, true)); } private double nextDouble() throws IOException { st.nextToken(); return st.nval; } private String[] nextSS(String reg) throws IOException { return br.readLine().split(reg); } private String nextLine() throws IOException { return br.readLine(); } private void print(String s, boolean newLine) { if (null != s) { pw.print(s); } if (newLine) { pw.println(); } } private void format(String format, Object... obj) { pw.format(format, obj); } private void flush() { pw.flush(); } } private static class FFT { double[] roots; int maxN; public FFT(int maxN) { this.maxN = maxN; initRoots(); } public long[] multiply(int[] a, int[] b) { int minSize = a.length + b.length - 1; int bits = 1; while (1 << bits < minSize) bits++; int N = 1 << bits; double[] aa = toComplex(a, N); double[] bb = toComplex(b, N); fftIterative(aa, false); fftIterative(bb, false); double[] c = new double[aa.length]; for (int i = 0; i < N; i++) { c[2 * i] = aa[2 * i] * bb[2 * i] - aa[2 * i + 1] * bb[2 * i + 1]; c[2 * i + 1] = aa[2 * i] * bb[2 * i + 1] + aa[2 * i + 1] * bb[2 * i]; } fftIterative(c, true); long[] ret = new long[minSize]; for (int i = 0; i < ret.length; i++) { ret[i] = Math.round(c[2 * i]); } return ret; } static double[] toComplex(int[] arr, int size) { double[] ret = new double[size * 2]; for (int i = 0; i < arr.length; i++) { ret[2 * i] = arr[i]; } return ret; } void initRoots() { roots = new double[2 * (maxN + 1)]; double ang = 2 * Math.PI / maxN; for (int i = 0; i <= maxN; i++) { roots[2 * i] = Math.cos(i * ang); roots[2 * i + 1] = Math.sin(i * ang); } } int bits(int N) { int ret = 0; while (1 << ret < N) ret++; if (1 << ret != N) throw new RuntimeException(); return ret; } void fftIterative(double[] array, boolean inv) { int bits = bits(array.length / 2); int N = 1 << bits; for (int from = 0; from < N; from++) { int to = Integer.reverse(from) >>> (32 - bits); if (from < to) { double tmpR = array[2 * from]; double tmpI = array[2 * from + 1]; array[2 * from] = array[2 * to]; array[2 * from + 1] = array[2 * to + 1]; array[2 * to] = tmpR; array[2 * to + 1] = tmpI; } } for (int n = 2; n <= N; n *= 2) { int delta = 2 * maxN / n; for (int from = 0; from < N; from += n) { int rootIdx = inv ? 2 * maxN : 0; double tmpR, tmpI; for (int arrIdx = 2 * from; arrIdx < 2 * from + n; arrIdx += 2) { tmpR = array[arrIdx + n] * roots[rootIdx] - array[arrIdx + n + 1] * roots[rootIdx + 1]; tmpI = array[arrIdx + n] * roots[rootIdx + 1] + array[arrIdx + n + 1] * roots[rootIdx]; array[arrIdx + n] = array[arrIdx] - tmpR; array[arrIdx + n + 1] = array[arrIdx + 1] - tmpI; array[arrIdx] += tmpR; array[arrIdx + 1] += tmpI; rootIdx += (inv ? -delta : delta); } } } if (inv) { for (int i = 0; i < array.length; i++) { array[i] /= N; } } } } }
Java
["5\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
1664d203befd1d02872642d312a36141
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.xml.stream.FactoryConfigurationError; import java.io.*; import java.util.*; public class Main { static FastScanner sc=new FastScanner(); static PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out)); static int []fac; static final int N=200100; public static void main(String[] args) { fac=new int[N]; fac[0]=1; for( int i=1;i<N;i++){ fac[i]=fac[i-1]*10%9; } sc=new FastScanner(); int t=sc.nextInt(); for( int i=0;i<t;i++){ solve(); } } static void solve(){ String s=sc.next(); int w,m; w=sc.nextInt(); m=sc.nextInt(); int cur=0; int prev[]=new int[s.length()]; prev[0]=(s.charAt(0)-'0')%9; for( int i=1;i<s.length();i++){ prev[i]=(prev[i-1]*10+(s.charAt(i)-'0'))%9; } Vector<Vector<Integer>>v=new Vector<Vector<Integer>>(); for( int i=0;i<9;i++){ v.add(new Vector<Integer>()); } for( int i=0;i+w-1<s.length();i++){ int x=(prev[i+w-1]+9-(i==0?0:prev[i-1])*fac[w-1]%9)%9; v.get(x).add(i); } for( int i=0;i<9;i++){ Collections.sort(v.elementAt(i)); } for( int i=0;i<m;i++){ int l,r,k; l=sc.nextInt(); r=sc.nextInt(); k=sc.nextInt(); --l;--r; int x=(prev[r]+9-(l==0?0:prev[l-1])*fac[r-l]%9)%9; int l1=s.length()+1,l2=s.length()+1; // for( int j=0;j<9;j++){ // // System.out.println(v.elementAt(j).elementAt(0)); // } // System.out.println(x); for( int j=0;j<9;j++){ for( int p=0;p<9;p++){ if((j*x+p)%9!=k) continue ; if(j!=p){ if(v.elementAt(j).size()==0||v.elementAt(p).size()==0) continue; else { int y=v.elementAt(j).elementAt(0)+1; int z=v.elementAt(p).elementAt(0)+1; if(y<l1){ l1=y; l2=z; } else if(y==l1){ l2=Math.min(l2,z); } } } else { if(v.elementAt(j).size()<2) continue; else { int y=v.elementAt(j).elementAt(0)+1; int z=v.elementAt(p).elementAt(1)+1; if(y<l1){ l1=y; l2=z; } else if(y==l1){ l2=Math.min(l2,z); } } } } } if(l1>s.length()) { out.printf("%d %d\n",-1,-1); } else{ out.printf("%d %d\n",l1,l2); } out.flush(); } } static class FastScanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } 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 17
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
90bef12451f06ca48cc6f213ff361da6
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 FastScanner sc; static int []fac; static final int N=200100; public static void main(String[] args) { fac=new int[N]; fac[0]=1; for( int i=1;i<N;i++){ fac[i]=fac[i-1]*10%9; } sc=new FastScanner(); int t=sc.nextInt(); for( int i=0;i<t;i++){ solve(); } } static void solve(){ String s=sc.next(); int w,m; w=sc.nextInt(); m=sc.nextInt(); int cur=0; int prev[]=new int[s.length()]; prev[0]=(s.charAt(0)-'0')%9; for( int i=1;i<s.length();i++){ prev[i]=(prev[i-1]*10+(s.charAt(i)-'0'))%9; } Vector<Vector<Integer>>v=new Vector<Vector<Integer>>(); for( int i=0;i<9;i++){ v.add(new Vector<Integer>()); } for( int i=0;i+w-1<s.length();i++){ int x=(prev[i+w-1]+9-(i==0?0:prev[i-1])*fac[w-1]%9)%9; v.get(x).add(i); } for( int i=0;i<9;i++){ Collections.sort(v.elementAt(i)); } for( int i=0;i<m;i++){ int l,r,k; l=sc.nextInt(); r=sc.nextInt(); k=sc.nextInt(); --l;--r; int x=(prev[r]+9-(l==0?0:prev[l-1])*fac[r-l]%9)%9; int l1=s.length()+1,l2=s.length()+1; // for( int j=0;j<9;j++){ // // System.out.println(v.elementAt(j).elementAt(0)); // } // System.out.println(x); for( int j=0;j<9;j++){ for( int p=0;p<9;p++){ if((j*x+p)%9!=k) continue ; if(j!=p){ if(v.elementAt(j).size()==0||v.elementAt(p).size()==0) continue; else { int y=v.elementAt(j).elementAt(0)+1; int z=v.elementAt(p).elementAt(0)+1; if(y<l1){ l1=y; l2=z; } else if(y==l1){ l2=Math.min(l2,z); } } } else { if(v.elementAt(j).size()<2) continue; else { int y=v.elementAt(j).elementAt(0)+1; int z=v.elementAt(p).elementAt(1)+1; if(y<l1){ l1=y; l2=z; } else if(y==l1){ l2=Math.min(l2,z); } } } } } PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out)); if(l1>s.length()) { out.printf("%d %d\n",-1,-1); out.flush(); } else{ out.printf("%d %d\n",l1,l2); out.flush(); } } } static class FastScanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } 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 17
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
8bcfedc0fcf5532571363afeac0a8192
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 { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int tc = Integer.parseInt(br.readLine()); StringBuilder sb = new StringBuilder(); while (tc-->0){ String s = br.readLine(); int n = s.length(); String[] secondLine = (br.readLine()).split(" "); int w = Integer.parseInt(secondLine[0]); int m = Integer.parseInt(secondLine[1]); int[] digits = new int[n]; int[] psum_digits = new int[n]; for(int i=0;i<n;i++){ digits[i] = (s.charAt(i) - '0'); psum_digits[i] = ((i==0)?0:psum_digits[i-1]) + digits[i]; } int[] remainder = new int[n]; for(int i=w-1;i<n;i++){ remainder[i] = (psum_digits[i] - (((i-w)<0)?0:psum_digits[i-w])) % 9; } HashMap<Integer, List<Integer>> rem_hash = new HashMap<>(); for(int i=w-1;i<n;i++){ int rem = remainder[i]; int l = i - w + 1; List<Integer> rem_list = rem_hash.getOrDefault(rem, new ArrayList<>()); rem_list.add(l); rem_hash.put(rem, rem_list); } for(int i=0;i<m;i++){ String[] query = (br.readLine()).split(" "); int l = Integer.parseInt(query[0]) - 1; int r = Integer.parseInt(query[1]) - 1; int k = Integer.parseInt(query[2]); int rem_lr = psum_digits[r] - (l==0?0:psum_digits[l-1]); rem_lr %= 9; int l1 = Integer.MAX_VALUE, l2 = Integer.MAX_VALUE; for(int r1=0;r1<9;r1++){ for(int r2=0;r2<9;r2++){ if((r1*rem_lr + r2) % 9 == k){ if(r1 == r2){ List<Integer> li = rem_hash.getOrDefault(r1, new ArrayList<>()); if(li.size() > 1){ int cl1 = li.get(0), cl2 = li.get(1); if(cl1 < l1){ l1 = cl1; l2 = cl2; } else if(cl1 == l1){ l2 = Math.min(l2, cl2); } } } else{ List<Integer> li1 = rem_hash.getOrDefault(r1, new ArrayList<>()); List<Integer> li2 = rem_hash.getOrDefault(r2, new ArrayList<>()); if(li1.size() > 0 && li2.size() > 0){ int cl1 = li1.get(0), cl2 = li2.get(0); if(cl1 < l1){ l1 = cl1; l2 = cl2; } else if(cl1 == l1){ l2 = Math.min(l2, cl2); } } } } } } if(l1 == Integer.MAX_VALUE || l2 == Integer.MAX_VALUE){ sb.append("-1 -1\n"); } else{ sb.append(l1+1).append(" ").append(l2 + 1).append("\n"); } } } System.out.println(sb); br.close(); } static class Soumit { final private int BUFFER_SIZE = 1 << 18; final private DataInputStream din; final private byte[] buffer; private PrintWriter pw; private int bufferPointer, bytesRead; StringTokenizer st; public Soumit() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Soumit(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public void streamOutput(String file) throws IOException { FileWriter fw = new FileWriter(file); BufferedWriter bw = new BufferedWriter(fw); pw = new PrintWriter(bw); } public void println(String a) { pw.println(a); } public void print(String a) { pw.print(a); } public String readLine() throws IOException { byte[] buf = new byte[3000064]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public void sort(int[] arr) { ArrayList<Integer> arlist = new ArrayList<>(); for (int i : arr) arlist.add(i); Collections.sort(arlist); for (int i = 0; i < arr.length; i++) arr[i] = arlist.get(i); } public void sort(long[] arr) { ArrayList<Long> arlist = new ArrayList<>(); for (long i : arr) arlist.add(i); Collections.sort(arlist); for (int i = 0; i < arr.length; i++) arr[i] = arlist.get(i); } public int[] nextIntArray(int n) throws IOException { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = nextInt(); } return arr; } public long[] nextLongArray(int n) throws IOException { long[] arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = nextLong(); } return arr; } public double[] nextDoubleArray(int n) throws IOException { double[] arr = new double[n]; for (int i = 0; i < n; i++) { arr[i] = nextDouble(); } return arr; } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { /*if (din == null) return;*/ if (din != null) din.close(); if (pw != null) pw.close(); } } }
Java
["5\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 17
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
f0d8194a43c3f685b43818844b6ca402
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 { 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(); int w = sc.nextInt(); int m = sc.nextInt(); int[] digits = new int[n]; int[] psum_digits = new int[n]; for(int i=0;i<n;i++){ digits[i] = (s.charAt(i) - '0'); psum_digits[i] = ((i==0)?0:psum_digits[i-1]) + digits[i]; } int[] remainder = new int[n]; for(int i=w-1;i<n;i++){ remainder[i] = (psum_digits[i] - (((i-w)<0)?0:psum_digits[i-w])) % 9; } HashMap<Integer, List<Integer>> rem_hash = new HashMap<>(); for(int i=w-1;i<n;i++){ int rem = remainder[i]; int l = i - w + 1; List<Integer> rem_list = rem_hash.getOrDefault(rem, new ArrayList<>()); rem_list.add(l); rem_hash.put(rem, rem_list); } for(int i=0;i<m;i++){ int l = sc.nextInt() - 1; int r = sc.nextInt() - 1; int k = sc.nextInt(); int rem_lr = psum_digits[r] - (l==0?0:psum_digits[l-1]); rem_lr %= 9; int l1 = Integer.MAX_VALUE, l2 = Integer.MAX_VALUE; for(int r1=0;r1<9;r1++){ for(int r2=0;r2<9;r2++){ if((r1*rem_lr + r2) % 9 == k){ if(r1 == r2){ List<Integer> li = rem_hash.getOrDefault(r1, new ArrayList<>()); if(li.size() > 1){ int cl1 = li.get(0), cl2 = li.get(1); if(cl1 < l1){ l1 = cl1; l2 = cl2; } else if(cl1 == l1){ l2 = Math.min(l2, cl2); } } } else{ List<Integer> li1 = rem_hash.getOrDefault(r1, new ArrayList<>()); List<Integer> li2 = rem_hash.getOrDefault(r2, new ArrayList<>()); if(li1.size() > 0 && li2.size() > 0){ int cl1 = li1.get(0), cl2 = li2.get(0); if(cl1 < l1){ l1 = cl1; l2 = cl2; } else if(cl1 == l1){ l2 = Math.min(l2, cl2); } } } } } } if(l1 == Integer.MAX_VALUE || l2 == Integer.MAX_VALUE){ sb.append("-1 -1\n"); } else{ sb.append(l1+1).append(" ").append(l2 + 1).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
["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 17
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
7972b98c181471022347326632061927
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 17
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
96be338191461ab09f8d93a1b1b3baf1
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 17
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
f7a61cbc5e0422c899db8f34210ad7ec
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.StringTokenizer; public class TaskF { 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(); int[] sums = new int[str.length()]; for (int i = 0; i < str.length(); i++) { char c = str.charAt(i); sums[i] = c - '0'; if (i > 0) { sums[i] += sums[i-1]; } } int w = reader.nextInt(); int m = reader.nextInt(); int[][] rem = new int[9][2]; for (int i = 0; i < 9; i++) { for (int j = 0; j < 2; j++) { rem[i][j] = -1; } } ArrayList<Integer> order = new ArrayList<>(); for (int i = 0; i < sums.length - w + 1; i++) { int s = sums[i + w - 1]; if (i > 0) { s -= sums[i - 1]; } int r = s % 9; if (rem[r][0] == -1) { rem[r][0] = i; order.add(r); } else if (rem[r][1] == -1) { rem[r][1] = i; } } loop: for (int i = 0; i < m; i++) { int l = reader.nextInt() - 1; int r = reader.nextInt() - 1; int k = reader.nextInt(); int s = sums[r]; if (l > 0) { s -= sums[l-1]; } int re = s % 9; for (Integer j : order) { int l1 = rem[j][0]; if (l1 != -1) { int h = k - (re * j); if (h < 0) { h += ((-h + 8) / 9) * 9; } int l2 = h == j ? rem[j][1] : rem[h][0]; if (l2 != -1) { System.out.println((l1+1) + " " + (l2+1)); continue loop; } } } System.out.println("-1 -1"); } } } 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
["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 17
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
ea51ba4864d27510c7e7085ed4fea223
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.StringTokenizer; public class codeforces_820_F { private static void solve(FastIOAdapter in, PrintWriter out) { char[] s = in.next().toCharArray(); int n = s.length; int w = in.nextInt(); int m = in.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = Integer.parseInt(String.valueOf(s[i])); } int[] pref = new int[n + 1]; for (int i = 0; i < n; i++) { pref[i + 1] = pref[i] + a[i]; } int[][] rems = new int[9][2]; for (int i = 0; i < 9; i++) { rems[i][0] = -1; rems[i][1] = -1; } for (int i = n - w; i >= 0; i--) { int rem = (pref[i + w] - pref[i]) % 9; rems[rem][1] = rems[rem][0]; rems[rem][0] = i; } for (int i = 0; i < m; i++) { int l = in.nextInt(); int r = in.nextInt(); int k = in.nextInt() + 9; int rem = (pref[r] - pref[l - 1]) % 9; int ans1 = Integer.MAX_VALUE, ans2 = Integer.MAX_VALUE; for (int j = 0; j < 9; j++) { for (int o = 0; o < 2; o++) { if (rems[j][o] != -1) { int jrem = (j * rem) % 9; int ind = (k - jrem) % 9; int other = (o + 1) % 2; int v = j != ind ? rems[ind][0] : rems[ind][other]; if (v != -1) { int cur1 = rems[j][o] + 1; int cur2 = v + 1; if (cur1 < ans1 || cur1 == ans1 && cur2 < ans2) { ans1 = cur1; ans2 = cur2; } } } } } if (ans1 == Integer.MAX_VALUE) out.println("-1 -1"); else out.println(ans1 + " " + ans2); } } 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
["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 17
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
ecc7b375dcd5dca2cde0b0f48156d48f
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
// Input : Pratik import java.io.*; import java.util.*; public class JavaDeveoper { final static boolean multipleTests = true; Input in; PrintWriter out; public JavaDeveoper() { in = new Input(System.in); out = new PrintWriter(System.out); } 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"); } JavaDeveoper solution = new JavaDeveoper(); 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; int w = in.nextInt(); int m = in.nextInt(); int[] a = new int[n + 1]; for (int i = 0; i < n; i++) a[i + 1] = s[i] - '0'; for (int i = 1; i < n + 1; i++) { a[i] += a[i - 1]; } List<Integer>[] position = new List[9]; for (int i = 0; i < 9; i++) position[i] = new ArrayList<>(); for (int end = w - 1; end < n; end++) { int temp = a[end + 1] - a[end + 1 - w]; temp %= 9; if (temp < 0) temp += 9; position[temp].add(end + 1 - w); } for (int i = 0; i < m; i++) { int l = in.nextInt() - 1; int r = in.nextInt() - 1; int k = in.nextInt(); int v = a[r + 1] - a[l]; v %= 9; int ans1 = n; int ans2 = n; for (int p = 0; p < 9; p++) { for (int q = 0; q < 9; q++) { if ((p * v + q - k) % 9 == 0) { if (p == q) { if (position[p].size() > 1) { if (position[p].get(0) < ans1) { ans1 = position[p].get(0); ans2 = position[p].get(1); } else if (position[p].get(0) == ans1 && position[p].get(1) < ans2) { ans2 = position[p].get(1); } } } else { if (position[p].size() > 0 && position[q].size() > 0) { if (position[p].get(0) < ans1) { ans1 = position[p].get(0); ans2 = position[q].get(0); } else if (position[p].get(0) == ans1 && position[q].get(0) < ans2) { ans2 = position[q].get(0); } } } } } } if (ans1 == n) out.println("-1 -1"); else { out.print(ans1 + 1); out.print(' '); out.println(ans2 + 1); } } } 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
["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 17
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
e3fa42b8a579adcda021328772251d5a
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.sql.Array; import java.util.*; import java.io.*; import java.math.BigInteger; import java.util.stream.IntStream; import java.util.stream.LongStream; 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(); label:for(int qqq = 1; qqq <= ttt; qqq++){ String s = cin.next(); int n = s.length(); int []prefix = new int [n + 1]; s = " " + s; char []arr = s.toCharArray(); ArrayList<Integer>[]pos = new ArrayList[11]; Arrays.setAll(pos,e -> new ArrayList<Integer>()); int w = cin.nextInt(); int m = cin.nextInt(); for(int i = 1; i <= n; i++){ prefix[i] = prefix[i - 1] + arr[i] - '0'; } for(int i = 1; i + w - 1 <= n; i++){//[i,i + w - 1] int temp = prefix[i + w - 1] - prefix[i - 1]; pos[temp % 9].add(i); } // out.println(Arrays.toString(prefix)); // for(int i = 0 ; i < 9;i++){ // out.println(i+"= "+pos[i]); // } for(int i = 0; i < m; i++){ long []ans = new long[2]; ans[0] = Long.MAX_VALUE; ans[1] = Long.MAX_VALUE; int l = cin.nextInt(); int r = cin.nextInt(); int k = cin.nextInt(); int val = (prefix[r] - prefix[l - 1]) % 9; for(int j = 0; j < 9; j++){ if(pos[j].isEmpty())continue; for(int q = 0; q < 9; q++){ if(pos[q].isEmpty())continue; if(((j * val) % 9 + q) % 9 != k)continue; if(q == j){ if(pos[j].size() >= 2){ // int size = pos[j].size(); int first = pos[j].get(0); int second = pos[j].get(1); if(first < ans[0]){ ans = new long[]{first,second}; }else if(first == ans[0] && second < ans[1]){ ans = new long[]{first,second}; } } }else{ int first = pos[j].get(0); int second = pos[q].get(0); if(first < ans[0]){ ans = new long[]{first,second}; }else if(first == ans[0] && second < ans[1]){ ans = new long[]{first,second}; } } } } if(ans[0] == Long.MAX_VALUE){ out.println("-1 -1"); }else{ out.println(ans[0] +" "+ans[1]); } } } 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
["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 17
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
1b71b050da21cc830ae1e8b40030f923
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 { final static boolean multipleTests = true; Input in; PrintWriter out; public F() { in = new Input(System.in); out = new PrintWriter(System.out); } public static void main(String[] args) { F solution = new F(); 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; int w = in.nextInt(); int m = in.nextInt(); int[] a = new int[n+1]; for (int i=0; i<n; i++) a[i+1] = s[i] - '0'; for (int i=1; i<n+1; i++) { a[i] += a[i-1]; } List<Integer>[] position = new List[9]; for (int i=0; i<9; i++) position[i] = new ArrayList<>(); for (int end=w-1; end<n; end++) { int temp = a[end+1] - a[end+1-w]; temp %= 9; if (temp < 0) temp += 9; position[temp].add(end + 1 - w); } for (int i=0; i<m; i++) { int l = in.nextInt() - 1; int r = in.nextInt() - 1; int k = in.nextInt(); int v = a[r+1] - a[l]; v %= 9; int ans1 = n; int ans2 = n; for (int p=0; p<9; p++) { for (int q=0; q<9; q++) { if ((p*v + q - k) % 9 == 0) { if (p == q) { if (position[p].size() > 1) { if (position[p].get(0) < ans1) { ans1 = position[p].get(0); ans2 = position[p].get(1); } else if (position[p].get(0) == ans1 && position[p].get(1) < ans2) { ans2 = position[p].get(1); } } } else { if (position[p].size() > 0 && position[q].size() > 0) { if (position[p].get(0) < ans1) { ans1 = position[p].get(0); ans2 = position[q].get(0); } else if (position[p].get(0) == ans1 && position[q].get(0) < ans2) { ans2 = position[q].get(0); } } } } } } if (ans1 == n) out.println("-1 -1"); else { out.print(ans1+1); out.print(' '); out.println(ans2+1); } } } 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
["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 17
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
b14383b1d70f4172dff11b5e360a5336
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.StringTokenizer; public class Template { FastScanner in; PrintWriter out; public void solve() throws IOException { int t = in.nextInt(); for (int cs = 0; cs < t; cs++) { String s = in.next(); // System.out.println("LENGTH: " + s.length() + " -> " + s); int w = in.nextInt(); int m = in.nextInt(); int[][] r = new int[9][2]; for (int i = 0; i < 9; i++) r[i][0] = r[i][1] = -1; int n = s.length(); int[] prefSum = new int[n]; prefSum[0] = s.charAt(0) - '0'; // System.out.println("LL: " + prefSum.length); for (int i = 1; i < n; i++) { prefSum[i] = prefSum[i - 1] + s.charAt(i) - '0'; } for (int i = 0; i <= n - w; i++) { int rsm = prefSum[i + w - 1]; if (i > 0) rsm -= prefSum[i - 1]; if (r[rsm % 9][0] == -1) r[rsm % 9][0] = i; else if (r[rsm % 9][1] == -1) r[rsm % 9][1] = i; } for (int i = 0; i < m; i++) { int li = in.nextInt() - 1; int ri = in.nextInt() - 1; int ki = in.nextInt(); int rsm = prefSum[ri]; if (li > 0) rsm -= prefSum[li - 1]; rsm %= 9; int mnL1 = Integer.MAX_VALUE; int mnL2 = Integer.MAX_VALUE; for (int r1 = 0; r1 < 9; r1++) for (int r2 = 0; r2 < 9; r2++) if ((r1 * rsm + r2) % 9 == ki) { int l1 = Integer.MAX_VALUE; int l2 = Integer.MAX_VALUE; if (r1 != r2 && r[r1][0] != -1 && r[r2][0] != -1) { l1 = r[r1][0]; l2 = r[r2][0]; } else if (r1 == r2 && r[r1][0] != -1 && r[r1][1] != -1) { l1 = r[r1][0]; l2 = r[r1][1]; } if (l1 < mnL1 || l1 == mnL1 && l2 < mnL2) { mnL1 = l1; mnL2 = l2; } } if (mnL1 == Integer.MAX_VALUE) System.out.println("-1 -1"); else System.out.println((mnL1 + 1) + " " + (mnL2 + 1)); } } } public void run() { try { in = new FastScanner(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); out.close(); } catch (IOException e) { e.printStackTrace(); } } class FastScanner { BufferedReader br; StringTokenizer st; FastScanner(Reader f) { br = new BufferedReader(f); } 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()); } } public static void main(String[] arg) { new Template().run(); } }
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 17
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
fa4b048caded922004edea3e245718fb
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.*; import java.math.*; import java.text.*; public class Main{ public static void main(String args[]) throws IOException{ Read sc=new Read(); int t=sc.nextInt(); for(int i=0;i<t;i++){ String s=sc.next(); int w=sc.nextInt();//长度 int m=sc.nextInt(); int preSum[]=new int[s.length()+1]; for(int j=1;j<=s.length();j++){ preSum[j]=(preSum[j-1]+s.charAt(j-1)-'0')%9; } int r1[]=new int[9]; int r2[]=new int[9]; Arrays.fill(r1,-1); Arrays.fill(r2,-1); for(int j=w;j<=s.length();j++){ int b=(preSum[j]-preSum[j-w]+9)%9; if(r1[b]==-1){ r1[b]=j-w+1; } else if(r2[b]==-1){ r2[b]=j-w+1; } } for(int j=0;j<m;j++){ int l=sc.nextInt(); int r=sc.nextInt(); int k=sc.nextInt(); int v=(preSum[r]-preSum[l-1]+9)%9; int ll1=-1,ll2=-1; for(int p=0;p<9;p++){ if(r1[p]!=-1){ int rr=(k+9-(v*p)%9)%9; if(rr==p){ if(r2[p]!=-1&&(ll1==-1||ll1>0&&ll1>r1[p])){ ll1=r1[p]; ll2=r2[p]; } } else{ if(r1[rr]!=-1&&(ll1==-1||ll1>0&&ll1>r1[p])){ ll1=r1[p]; ll2=r1[rr]; } } } } sc.println(ll1+" "+ll2); } } //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
["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 17
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
b8a594861be2763e19976988f9758056
train_110.jsonl
1662993300
This is an interactive problem.I want to play a game with you...We hid from you a cyclic graph of $$$n$$$ vertices ($$$3 \le n \le 10^{18}$$$). A cyclic graph is an undirected graph of $$$n$$$ vertices that form one cycle. Each vertex belongs to the cycle, i.e. the length of the cycle (the number of edges in it) is exactly $$$n$$$. The order of the vertices in the cycle is arbitrary.You can make queries in the following way: "? a b" where $$$1 \le a, b \le 10^{18}$$$ and $$$a \neq b$$$. In response to the query, the interactor outputs on a separate line the length of random of two paths from vertex $$$a$$$ to vertex $$$b$$$, or -1 if $$$\max(a, b) &gt; n$$$. The interactor chooses one of the two paths with equal probability. The length of the path —is the number of edges in it.You win if you guess the number of vertices in the hidden graph (number $$$n$$$) by making no more than $$$50$$$ queries.Note that the interactor is implemented in such a way that for any ordered pair $$$(a, b)$$$, it always returns the same value for query "? a b", no matter how many such queries. Note that the "? b a" query may be answered differently by the interactor.The vertices in the graph are randomly placed, and their positions are fixed in advance.Hacks are forbidden in this problem. The number of tests the jury has is $$$50$$$.
256 megabytes
import java.io.*; import java.util.*; public class Guess_the_Cycle_Size { 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() { int n = 2; while (true) { long resp = askQuery(1, n); if (resp == -1) { fw.out.println("! " + (n - 1)); return; } long resp2 = askQuery(n, 1); if (resp != resp2) { fw.out.println("! " + (resp + resp2)); return; } n++; } } private static long askQuery(int a, int b) { fw.out.println("? " + a + " " + b); fw.out.flush(); return fs.nextLong(); } 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
["1\n\n2\n\n-1"]
1 second
["? 1 2\n\n? 1 3\n\n? 1 4\n\n! 3"]
NoteIn the first example, the graph could look like this The lengths of the simple paths between all pairs of vertices in this case are $$$1$$$ or $$$2$$$. The first query finds out that one of the simple paths from vertex $$$1$$$ to vertex $$$2$$$ has a length of $$$1$$$. With the second query, we find out that one of the simple paths from vertex $$$1$$$ to vertex $$$3$$$ has length $$$2$$$. In the third query, we find out that vertex $$$4$$$ is not in the graph. Consequently, the size of the graph is $$$3$$$.
Java 11
standard input
[ "interactive", "probabilities" ]
8590f40e7509614694486165ee824587
null
1,800
null
standard output
PASSED
7372b78b8902c87dc48a94937cc491d3
train_110.jsonl
1662993300
This is an interactive problem.I want to play a game with you...We hid from you a cyclic graph of $$$n$$$ vertices ($$$3 \le n \le 10^{18}$$$). A cyclic graph is an undirected graph of $$$n$$$ vertices that form one cycle. Each vertex belongs to the cycle, i.e. the length of the cycle (the number of edges in it) is exactly $$$n$$$. The order of the vertices in the cycle is arbitrary.You can make queries in the following way: "? a b" where $$$1 \le a, b \le 10^{18}$$$ and $$$a \neq b$$$. In response to the query, the interactor outputs on a separate line the length of random of two paths from vertex $$$a$$$ to vertex $$$b$$$, or -1 if $$$\max(a, b) &gt; n$$$. The interactor chooses one of the two paths with equal probability. The length of the path —is the number of edges in it.You win if you guess the number of vertices in the hidden graph (number $$$n$$$) by making no more than $$$50$$$ queries.Note that the interactor is implemented in such a way that for any ordered pair $$$(a, b)$$$, it always returns the same value for query "? a b", no matter how many such queries. Note that the "? b a" query may be answered differently by the interactor.The vertices in the graph are randomly placed, and their positions are fixed in advance.Hacks are forbidden in this problem. The number of tests the jury has is $$$50$$$.
256 megabytes
// import java.io.*; // import java.util.*; // public class Q5{ // public static void main(String[] args) throws IOException { // BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); // long a = 1, b = 2; // long ans = 0; // int cnt = 24; // while (cnt-- > 0) { // System.out.println("? "+a+" "+b); // System.out.flush(); // long n = Long.parseLong(br.readLine()); // if (n == -1) { // System.out.println("! "+(b-1)); // System.out.flush(); // return; // } else { // System.out.println("? "+b+" "+a); // System.out.flush(); // long m = Long.parseLong(br.readLine()); // if (n != m) { // System.out.println("! "+(n+m)); // System.out.flush(); // return; // } else { // ans = n + m; // b++; // } // } // } // System.out.println("! " + ans); // System.out.flush(); // } // } import static java.lang.Math.*; import static java.lang.System.*; import java.io.*; import java.util.*; public class Q5{ public static void main(String[] args)throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(in)); int q=0; long a,b; int num = 2; while(q<50) { out.println("? 1 "+num); out.flush(); a = Long.parseLong(br.readLine()); q++; if(a == -1) { out.println("! " + (num-1)); break; } out.println("? "+num+" 1"); out.flush(); q++; b = Long.parseLong(br.readLine()); if(b == -1) { out.println("! " + (num-1)); break; } if(a != b) { out.println("! " + (a+b)); break; } num++; } } }
Java
["1\n\n2\n\n-1"]
1 second
["? 1 2\n\n? 1 3\n\n? 1 4\n\n! 3"]
NoteIn the first example, the graph could look like this The lengths of the simple paths between all pairs of vertices in this case are $$$1$$$ or $$$2$$$. The first query finds out that one of the simple paths from vertex $$$1$$$ to vertex $$$2$$$ has a length of $$$1$$$. With the second query, we find out that one of the simple paths from vertex $$$1$$$ to vertex $$$3$$$ has length $$$2$$$. In the third query, we find out that vertex $$$4$$$ is not in the graph. Consequently, the size of the graph is $$$3$$$.
Java 11
standard input
[ "interactive", "probabilities" ]
8590f40e7509614694486165ee824587
null
1,800
null
standard output
PASSED
859407ebd0be1b6bbdebbc2f7e0a4da4
train_110.jsonl
1662993300
This is an interactive problem.I want to play a game with you...We hid from you a cyclic graph of $$$n$$$ vertices ($$$3 \le n \le 10^{18}$$$). A cyclic graph is an undirected graph of $$$n$$$ vertices that form one cycle. Each vertex belongs to the cycle, i.e. the length of the cycle (the number of edges in it) is exactly $$$n$$$. The order of the vertices in the cycle is arbitrary.You can make queries in the following way: "? a b" where $$$1 \le a, b \le 10^{18}$$$ and $$$a \neq b$$$. In response to the query, the interactor outputs on a separate line the length of random of two paths from vertex $$$a$$$ to vertex $$$b$$$, or -1 if $$$\max(a, b) &gt; n$$$. The interactor chooses one of the two paths with equal probability. The length of the path —is the number of edges in it.You win if you guess the number of vertices in the hidden graph (number $$$n$$$) by making no more than $$$50$$$ queries.Note that the interactor is implemented in such a way that for any ordered pair $$$(a, b)$$$, it always returns the same value for query "? a b", no matter how many such queries. Note that the "? b a" query may be answered differently by the interactor.The vertices in the graph are randomly placed, and their positions are fixed in advance.Hacks are forbidden in this problem. The number of tests the jury has is $$$50$$$.
256 megabytes
import java.util.*; public class b implements Runnable{ static ContestScanner in = new ContestScanner(); static ContestPrinter out = new ContestPrinter(); public static void main(String[] args) { new Thread(null, new b(), "main", 1<<28).start(); } public void run() { // int tests = in.nextInt(); int tests = 1; for (int t = 0; t < tests; t++) { long ans = 3; for (int i = 0 ; i < 25 ; i++) { System.out.println("? " + (i+1) + " " + (i+2) ); long t1 = in.nextLong(); System.out.println("? " + (i+2) + " " + (i+1) ); long t2 = in.nextLong(); // if (t1 == -1 || t2 == -1) { // out.println("! " + (i+1)); // break; // } if (t1 != t2) { ans = t1+t2; break; } } out.println("! " + ans); } out.close(); } static class ContestScanner { private final java.io.InputStream in; private final byte[] buffer = new byte[1024]; private int ptr = 0; private int buflen = 0; private static final long LONG_MAX_TENTHS = 922337203685477580L; private static final int LONG_MAX_LAST_DIGIT = 7; private static final int LONG_MIN_LAST_DIGIT = 8; public ContestScanner(java.io.InputStream in){ this.in = in; } public ContestScanner(java.io.File file) throws java.io.FileNotFoundException { this(new java.io.BufferedInputStream(new java.io.FileInputStream(file))); } public ContestScanner(){ this(System.in); } private boolean hasNextByte() { if (ptr < buflen) { return true; }else{ ptr = 0; try { buflen = in.read(buffer); } catch (java.io.IOException e) { e.printStackTrace(); } if (buflen <= 0) { return false; } } return true; } private int readByte() { if (hasNextByte()) return buffer[ptr++]; else return -1; } private static boolean isPrintableChar(int c) { return 33 <= c && c <= 126; } public boolean hasNext() { while(hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++; return hasNextByte(); } public String next() { if (!hasNext()) throw new java.util.NoSuchElementException(); StringBuilder sb = new StringBuilder(); int b = readByte(); while(isPrintableChar(b)) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } public long nextLong() { if (!hasNext()) throw new java.util.NoSuchElementException(); long n = 0; boolean minus = false; int b = readByte(); if (b == '-') { minus = true; b = readByte(); } if (b < '0' || '9' < b) { throw new NumberFormatException(); } while (true) { if ('0' <= b && b <= '9') { int digit = b - '0'; if (n >= LONG_MAX_TENTHS) { if (n == LONG_MAX_TENTHS) { if (minus) { if (digit <= LONG_MIN_LAST_DIGIT) { n = -n * 10 - digit; b = readByte(); if (!isPrintableChar(b)) { return n; } else if (b < '0' || '9' < b) { throw new NumberFormatException( String.format("%d%s... is not number", n, Character.toString(b)) ); } } } else { if (digit <= LONG_MAX_LAST_DIGIT) { n = n * 10 + digit; b = readByte(); if (!isPrintableChar(b)) { return n; } else if (b < '0' || '9' < b) { throw new NumberFormatException( String.format("%d%s... is not number", n, Character.toString(b)) ); } } } } throw new ArithmeticException( String.format("%s%d%d... overflows long.", minus ? "-" : "", n, digit) ); } n = n * 10 + digit; }else if(b == -1 || !isPrintableChar(b)){ return minus ? -n : n; }else{ throw new NumberFormatException(); } b = readByte(); } } public int nextInt() { long nl = nextLong(); if (nl < Integer.MIN_VALUE || nl > Integer.MAX_VALUE) throw new NumberFormatException(); return (int) nl; } public double nextDouble() { return Double.parseDouble(next()); } public long[] nextLongArray(int length){ long[] array = new long[length]; for(int i=0; i<length; i++) array[i] = this.nextLong(); return array; } public long[] nextLongArray(int length, java.util.function.LongUnaryOperator map){ long[] array = new long[length]; for(int i=0; i<length; i++) array[i] = map.applyAsLong(this.nextLong()); return array; } public int[] nextIntArray(int length){ int[] array = new int[length]; for(int i=0; i<length; i++) array[i] = this.nextInt(); return array; } public int[] nextIntArray(int length, java.util.function.IntUnaryOperator map){ int[] array = new int[length]; for(int i=0; i<length; i++) array[i] = map.applyAsInt(this.nextInt()); return array; } public double[] nextDoubleArray(int length){ double[] array = new double[length]; for(int i=0; i<length; i++) array[i] = this.nextDouble(); return array; } public double[] nextDoubleArray(int length, java.util.function.DoubleUnaryOperator map){ double[] array = new double[length]; for(int i=0; i<length; i++) array[i] = map.applyAsDouble(this.nextDouble()); return array; } public long[][] nextLongMatrix(int height, int width){ long[][] mat = new long[height][width]; for(int h=0; h<height; h++) for(int w=0; w<width; w++){ mat[h][w] = this.nextLong(); } return mat; } public int[][] nextIntMatrix(int height, int width){ int[][] mat = new int[height][width]; for(int h=0; h<height; h++) for(int w=0; w<width; w++){ mat[h][w] = this.nextInt(); } return mat; } public double[][] nextDoubleMatrix(int height, int width){ double[][] mat = new double[height][width]; for(int h=0; h<height; h++) for(int w=0; w<width; w++){ mat[h][w] = this.nextDouble(); } return mat; } public char[][] nextCharMatrix(int height, int width){ char[][] mat = new char[height][width]; for(int h=0; h<height; h++){ String s = this.next(); for(int w=0; w<width; w++){ mat[h][w] = s.charAt(w); } } return mat; } } static class ContestPrinter extends java.io.PrintWriter{ public ContestPrinter(java.io.PrintStream stream){ super(stream); } public ContestPrinter(java.io.File file) throws java.io.FileNotFoundException{ super(new java.io.PrintStream(file)); } public ContestPrinter(){ super(System.out); } private static String dtos(double x, int n) { StringBuilder sb = new StringBuilder(); if(x < 0){ sb.append('-'); x = -x; } x += Math.pow(10, -n)/2; sb.append((long)x); sb.append("."); x -= (long)x; for(int i = 0;i < n;i++){ x *= 10; sb.append((int)x); x -= (int)x; } return sb.toString(); } @Override public void print(float f){ super.print(dtos(f, 20)); } @Override public void println(float f){ super.println(dtos(f, 20)); } @Override public void print(double d){ super.print(dtos(d, 20)); } @Override public void println(double d){ super.println(dtos(d, 20)); } public void printArray(int[] array, String separator){ int n = array.length; if(n==0){ super.println(); return; } for(int i=0; i<n-1; i++){ super.print(array[i]); super.print(separator); } super.println(array[n-1]); } public void printArray(int[] array){ this.printArray(array, " "); } public void printArray(int[] array, String separator, java.util.function.IntUnaryOperator map){ int n = array.length; if(n==0){ super.println(); return; } for(int i=0; i<n-1; i++){ super.print(map.applyAsInt(array[i])); super.print(separator); } super.println(map.applyAsInt(array[n-1])); } public void printArray(int[] array, java.util.function.IntUnaryOperator map){ this.printArray(array, " ", map); } public void printArray(long[] array, String separator){ int n = array.length; if(n==0){ super.println(); return; } for(int i=0; i<n-1; i++){ super.print(array[i]); super.print(separator); } super.println(array[n-1]); } public void printArray(long[] array){ this.printArray(array, " "); } public void printArray(long[] array, String separator, java.util.function.LongUnaryOperator map){ int n = array.length; if(n==0){ super.println(); return; } for(int i=0; i<n-1; i++){ super.print(map.applyAsLong(array[i])); super.print(separator); } super.println(map.applyAsLong(array[n-1])); } public void printArray(long[] array, java.util.function.LongUnaryOperator map){ this.printArray(array, " ", map); } public <T> void printArray(T[] array, String separator){ int n = array.length; if(n==0){ super.println(); return; } for(int i=0; i<n-1; i++){ super.print(array[i]); super.print(separator); } super.println(array[n-1]); } public <T> void printArray(T[] array){ this.printArray(array, " "); } public <T> void printArray(T[] array, String separator, java.util.function.UnaryOperator<T> map){ int n = array.length; if(n==0){ super.println(); return; } for(int i=0; i<n-1; i++){ super.print(map.apply(array[i])); super.print(separator); } super.println(map.apply(array[n-1])); } public <T> void printArray(T[] array, java.util.function.UnaryOperator<T> map){ this.printArray(array, " ", map); } } }
Java
["1\n\n2\n\n-1"]
1 second
["? 1 2\n\n? 1 3\n\n? 1 4\n\n! 3"]
NoteIn the first example, the graph could look like this The lengths of the simple paths between all pairs of vertices in this case are $$$1$$$ or $$$2$$$. The first query finds out that one of the simple paths from vertex $$$1$$$ to vertex $$$2$$$ has a length of $$$1$$$. With the second query, we find out that one of the simple paths from vertex $$$1$$$ to vertex $$$3$$$ has length $$$2$$$. In the third query, we find out that vertex $$$4$$$ is not in the graph. Consequently, the size of the graph is $$$3$$$.
Java 11
standard input
[ "interactive", "probabilities" ]
8590f40e7509614694486165ee824587
null
1,800
null
standard output
PASSED
549bf991b6d2e50658434e88a2d25244
train_110.jsonl
1662993300
This is an interactive problem.I want to play a game with you...We hid from you a cyclic graph of $$$n$$$ vertices ($$$3 \le n \le 10^{18}$$$). A cyclic graph is an undirected graph of $$$n$$$ vertices that form one cycle. Each vertex belongs to the cycle, i.e. the length of the cycle (the number of edges in it) is exactly $$$n$$$. The order of the vertices in the cycle is arbitrary.You can make queries in the following way: "? a b" where $$$1 \le a, b \le 10^{18}$$$ and $$$a \neq b$$$. In response to the query, the interactor outputs on a separate line the length of random of two paths from vertex $$$a$$$ to vertex $$$b$$$, or -1 if $$$\max(a, b) &gt; n$$$. The interactor chooses one of the two paths with equal probability. The length of the path —is the number of edges in it.You win if you guess the number of vertices in the hidden graph (number $$$n$$$) by making no more than $$$50$$$ queries.Note that the interactor is implemented in such a way that for any ordered pair $$$(a, b)$$$, it always returns the same value for query "? a b", no matter how many such queries. Note that the "? b a" query may be answered differently by the interactor.The vertices in the graph are randomly placed, and their positions are fixed in advance.Hacks are forbidden in this problem. The number of tests the jury has is $$$50$$$.
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.*; public class E_Guess_the_Cycle_Size { static long mod = Long.MAX_VALUE; public static void main(String[] args) { OutputStream outputStream = System.out; PrintWriter out = new PrintWriter(outputStream); FastReader f = new FastReader(); int t = 1; while(t-- > 0){ solve(f, out); } out.close(); } public static void solve(FastReader f, PrintWriter out) { for(int i = 2; i <= 26; i++) { out.println("? 1 " + i); out.flush(); long x = f.nextLong(); out.println("? " + i + " 1"); out.flush(); long y = f.nextLong(); if(x == -1) { out.println("! " + (i-1)); out.flush(); return; } else if(x != y) { out.println("! " + (x+y)); out.flush(); return; } } } // Sort an array public static void sort(int arr[]) { ArrayList<Integer> al = new ArrayList<>(); for(int i: arr) { al.add(i); } Collections.sort(al); for(int i = 0; i < arr.length; i++) { arr[i] = al.get(i); } } // Find all divisors of n public static void allDivisors(int n) { for(int i = 1; i*i <= n; i++) { if(n%i == 0) { System.out.println(i + " "); if(i != n/i) { System.out.println(n/i + " "); } } } } // Check if n is prime or not public static boolean isPrime(int n) { if(n < 1) return false; if(n == 2 || n == 3) return true; if(n % 2 == 0 || n % 3 == 0) return false; for(int i = 5; i*i <= n; i += 6) { if(n % i == 0 || n % (i+2) == 0) { return false; } } return true; } // Find gcd of a and b public static long gcd(long a, long b) { long dividend = a > b ? a : b; long divisor = a < b ? a : b; while(divisor > 0) { long reminder = dividend % divisor; dividend = divisor; divisor = reminder; } return dividend; } // Find lcm of a and b public static long lcm(long a, long b) { long lcm = gcd(a, b); long hcf = (a * b) / lcm; return hcf; } // Find factorial in O(n) time public static long fact(int n) { long res = 1; for(int i = 2; i <= n; i++) { res *= res * i; } return res; } // Find power in O(logb) time public static long power(long a, long b) { long res = 1; while(b > 0) { if((b&1) == 1) { res = (res * a)%mod; } a = (a * a)%mod; b >>= 1; } return res; } // Find nCr public static long nCr(int n, int r) { if(r < 0 || r > n) { return 0; } long ans = fact(n) / (fact(r) * fact(n-r)); return ans; } // Find nPr public static long nPr(int n, int r) { if(r < 0 || r > n) { return 0; } long ans = fact(n) / fact(r); return ans; } // sort all characters of a string public static String sortString(String inputString) { char tempArray[] = inputString.toCharArray(); Arrays.sort(tempArray); return new String(tempArray); } // User defined class for fast I/O 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(); } boolean hasNext() { if (st != null && st.hasMoreTokens()) { return true; } String tmp; try { br.mark(1000); tmp = br.readLine(); if (tmp == null) { return false; } br.reset(); } catch (IOException e) { return false; } return true; } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } float nextFloat() { return Float.parseFloat(next()); } boolean nextBoolean() { return Boolean.parseBoolean(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } int[] nextArray(int n) { int[] a = new int[n]; for(int i=0; i<n; i++) { a[i] = nextInt(); } return a; } } } /** Dec Char Dec Char Dec Char Dec Char --------- --------- --------- ---------- 0 NUL (null) 32 SPACE 64 @ 96 ` 1 SOH (start of heading) 33 ! 65 A 97 a 2 STX (start of text) 34 " 66 B 98 b 3 ETX (end of text) 35 # 67 C 99 c 4 EOT (end of transmission) 36 $ 68 D 100 d 5 ENQ (enquiry) 37 % 69 E 101 e 6 ACK (acknowledge) 38 & 70 F 102 f 7 BEL (bell) 39 ' 71 G 103 g 8 BS (backspace) 40 ( 72 H 104 h 9 TAB (horizontal tab) 41 ) 73 I 105 i 10 LF (NL line feed, new line) 42 * 74 J 106 j 11 VT (vertical tab) 43 + 75 K 107 k 12 FF (NP form feed, new page) 44 , 76 L 108 l 13 CR (carriage return) 45 - 77 M 109 m 14 SO (shift out) 46 . 78 N 110 n 15 SI (shift in) 47 / 79 O 111 o 16 DLE (data link escape) 48 0 80 P 112 p 17 DC1 (device control 1) 49 1 81 Q 113 q 18 DC2 (device control 2) 50 2 82 R 114 r 19 DC3 (device control 3) 51 3 83 S 115 s 20 DC4 (device control 4) 52 4 84 T 116 t 21 NAK (negative acknowledge) 53 5 85 U 117 u 22 SYN (synchronous idle) 54 6 86 V 118 v 23 ETB (end of trans. block) 55 7 87 W 119 w 24 CAN (cancel) 56 8 88 X 120 x 25 EM (end of medium) 57 9 89 Y 121 y 26 SUB (substitute) 58 : 90 Z 122 z 27 ESC (escape) 59 ; 91 [ 123 { 28 FS (file separator) 60 < 92 \ 124 | 29 GS (group separator) 61 = 93 ] 125 } 30 RS (record separator) 62 > 94 ^ 126 ~ 31 US (unit separator) 63 ? 95 _ 127 DEL */ // (a/b)%mod == (a * moduloInverse(b)) % mod; // moduloInverse(b) = power(b, mod-2);
Java
["1\n\n2\n\n-1"]
1 second
["? 1 2\n\n? 1 3\n\n? 1 4\n\n! 3"]
NoteIn the first example, the graph could look like this The lengths of the simple paths between all pairs of vertices in this case are $$$1$$$ or $$$2$$$. The first query finds out that one of the simple paths from vertex $$$1$$$ to vertex $$$2$$$ has a length of $$$1$$$. With the second query, we find out that one of the simple paths from vertex $$$1$$$ to vertex $$$3$$$ has length $$$2$$$. In the third query, we find out that vertex $$$4$$$ is not in the graph. Consequently, the size of the graph is $$$3$$$.
Java 11
standard input
[ "interactive", "probabilities" ]
8590f40e7509614694486165ee824587
null
1,800
null
standard output
PASSED
6106c37bc95061d6e775d9c5ae4e2a0b
train_110.jsonl
1662993300
This is an interactive problem.I want to play a game with you...We hid from you a cyclic graph of $$$n$$$ vertices ($$$3 \le n \le 10^{18}$$$). A cyclic graph is an undirected graph of $$$n$$$ vertices that form one cycle. Each vertex belongs to the cycle, i.e. the length of the cycle (the number of edges in it) is exactly $$$n$$$. The order of the vertices in the cycle is arbitrary.You can make queries in the following way: "? a b" where $$$1 \le a, b \le 10^{18}$$$ and $$$a \neq b$$$. In response to the query, the interactor outputs on a separate line the length of random of two paths from vertex $$$a$$$ to vertex $$$b$$$, or -1 if $$$\max(a, b) &gt; n$$$. The interactor chooses one of the two paths with equal probability. The length of the path —is the number of edges in it.You win if you guess the number of vertices in the hidden graph (number $$$n$$$) by making no more than $$$50$$$ queries.Note that the interactor is implemented in such a way that for any ordered pair $$$(a, b)$$$, it always returns the same value for query "? a b", no matter how many such queries. Note that the "? b a" query may be answered differently by the interactor.The vertices in the graph are randomly placed, and their positions are fixed in advance.Hacks are forbidden in this problem. The number of tests the jury has is $$$50$$$.
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<>(); ArrayList<HashSet<Long>> arr=new ArrayList<>(); boolean status=false; for(int i=2;i<=26;i++) { arr.add(new HashSet<>()); System.out.println("? "+1+" "+i); long X=Reader.nextLong(); if(X==-1) { status=true; System.out.println("! "+(i-1)); break; } System.out.println("? "+(i)+" "+(1)); long X1=Reader.nextLong(); arr.get(i-2).add(X); arr.get(i-2).add(X1); } if(!status) { for (int i = 0; i < 25; i++) { if (arr.get(i).size() == 2) { ArrayList<Long> ch = new ArrayList<>(arr.get(i)); System.out.println("! " + (ch.get(0) + ch.get(1))); status = true; break; } } if (!status) { ArrayList<Long> ch=new ArrayList<>(arr.get(0)); System.out.println("! "+(ch.get(0)*2)); } } // 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
["1\n\n2\n\n-1"]
1 second
["? 1 2\n\n? 1 3\n\n? 1 4\n\n! 3"]
NoteIn the first example, the graph could look like this The lengths of the simple paths between all pairs of vertices in this case are $$$1$$$ or $$$2$$$. The first query finds out that one of the simple paths from vertex $$$1$$$ to vertex $$$2$$$ has a length of $$$1$$$. With the second query, we find out that one of the simple paths from vertex $$$1$$$ to vertex $$$3$$$ has length $$$2$$$. In the third query, we find out that vertex $$$4$$$ is not in the graph. Consequently, the size of the graph is $$$3$$$.
Java 11
standard input
[ "interactive", "probabilities" ]
8590f40e7509614694486165ee824587
null
1,800
null
standard output
PASSED
775b223db7ed1b9fc3f29522ccf8e68c
train_110.jsonl
1662993300
This is an interactive problem.I want to play a game with you...We hid from you a cyclic graph of $$$n$$$ vertices ($$$3 \le n \le 10^{18}$$$). A cyclic graph is an undirected graph of $$$n$$$ vertices that form one cycle. Each vertex belongs to the cycle, i.e. the length of the cycle (the number of edges in it) is exactly $$$n$$$. The order of the vertices in the cycle is arbitrary.You can make queries in the following way: "? a b" where $$$1 \le a, b \le 10^{18}$$$ and $$$a \neq b$$$. In response to the query, the interactor outputs on a separate line the length of random of two paths from vertex $$$a$$$ to vertex $$$b$$$, or -1 if $$$\max(a, b) &gt; n$$$. The interactor chooses one of the two paths with equal probability. The length of the path —is the number of edges in it.You win if you guess the number of vertices in the hidden graph (number $$$n$$$) by making no more than $$$50$$$ queries.Note that the interactor is implemented in such a way that for any ordered pair $$$(a, b)$$$, it always returns the same value for query "? a b", no matter how many such queries. Note that the "? b a" query may be answered differently by the interactor.The vertices in the graph are randomly placed, and their positions are fixed in advance.Hacks are forbidden in this problem. The number of tests the jury has is $$$50$$$.
256 megabytes
import java.io.*; import java.util.*; public class new1{ static int mod = 998244353; static FastReader s = new FastReader(); public static long ask(int a, int b) { System.out.println("? " + a + " " + b); System.out.flush(); long aa = s.nextLong(); return aa; } public static void main(String[] args) throws IOException{ BufferedWriter output = new BufferedWriter(new OutputStreamWriter(System.out)); //FastReader s = new FastReader(); int t = 1;//s.nextInt(); for(int z = 1; z <= t; z++) { long ans = 3; int count = 0; for(int i = 2; i <= 51; i++) { if(count >= 50) break; long aa = ask(1, i); count++; if(aa == -1) { ans = i - 1; break; } if(count >= 50) break; long bb = ask(i, 1); count++; if(aa != bb ) { ans = aa + bb; break; } else ans = aa + bb; } System.out.println("! " + ans); //System.out.flush(); } //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
["1\n\n2\n\n-1"]
1 second
["? 1 2\n\n? 1 3\n\n? 1 4\n\n! 3"]
NoteIn the first example, the graph could look like this The lengths of the simple paths between all pairs of vertices in this case are $$$1$$$ or $$$2$$$. The first query finds out that one of the simple paths from vertex $$$1$$$ to vertex $$$2$$$ has a length of $$$1$$$. With the second query, we find out that one of the simple paths from vertex $$$1$$$ to vertex $$$3$$$ has length $$$2$$$. In the third query, we find out that vertex $$$4$$$ is not in the graph. Consequently, the size of the graph is $$$3$$$.
Java 11
standard input
[ "interactive", "probabilities" ]
8590f40e7509614694486165ee824587
null
1,800
null
standard output
PASSED
43dd7d42fe109df4634620cb16cb1356
train_110.jsonl
1662993300
This is an interactive problem.I want to play a game with you...We hid from you a cyclic graph of $$$n$$$ vertices ($$$3 \le n \le 10^{18}$$$). A cyclic graph is an undirected graph of $$$n$$$ vertices that form one cycle. Each vertex belongs to the cycle, i.e. the length of the cycle (the number of edges in it) is exactly $$$n$$$. The order of the vertices in the cycle is arbitrary.You can make queries in the following way: "? a b" where $$$1 \le a, b \le 10^{18}$$$ and $$$a \neq b$$$. In response to the query, the interactor outputs on a separate line the length of random of two paths from vertex $$$a$$$ to vertex $$$b$$$, or -1 if $$$\max(a, b) &gt; n$$$. The interactor chooses one of the two paths with equal probability. The length of the path —is the number of edges in it.You win if you guess the number of vertices in the hidden graph (number $$$n$$$) by making no more than $$$50$$$ queries.Note that the interactor is implemented in such a way that for any ordered pair $$$(a, b)$$$, it always returns the same value for query "? a b", no matter how many such queries. Note that the "? b a" query may be answered differently by the interactor.The vertices in the graph are randomly placed, and their positions are fixed in advance.Hacks are forbidden in this problem. The number of tests the jury has is $$$50$$$.
256 megabytes
/* In_The_Name_Of_Allah_The_Merciful */ import java.util.*; import java.io.*; public class Cp { PrintWriter out; FastReader sc; long[] m1= {(long)(1e9+7),998244353}; long mod=m1[1]; long maxlong=Long.MAX_VALUE; long minlong=Long.MIN_VALUE; StringBuilder sb; ArrayList<Integer> l; /****************************************************************************************** *****************************************************************************************/ public void sol(){ for(int i=3;i<28;i++){ System.out.println("? "+1+" "+i); System.out.flush(); long x=nl(); System.out.println("? "+i+" "+1); System.out.flush(); long y=nl(); if(x==-1||y==-1){ pl("! "+(i-1)); System.out.flush(); return; } if(x!=y){ pl("! "+(x+y)); System.out.flush(); return; } } } public static void main(String[] args) { Cp g=new Cp(); g.out=new PrintWriter(System.out); g.sc=new FastReader(); int t=1; //t=g.ni(); while(t-->0) g.sol(); g.out.flush(); } /**************************************************************************************** *****************************************************************************************/ 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 int ni(){ return sc.nextInt(); }public long nl(){ return sc.nextLong(); }public double nd(){ return sc.nextDouble(); }public char[] rl(){ return sc.nextLine().toCharArray(); }public String rl1(){ return sc.nextLine(); } public void pl(Object s){ out.println(s); } public void pr(Object s){ out.print(s); }public String next(){ return sc.next(); }public long abs(long x){ return Math.abs(x); } public int abs(int x){ return Math.abs(x); } public double abs(double x){ return Math.abs(x); }public long min(long x,long y){ return (long)Math.min(x,y); } public int min(int x,int y){ return (int)Math.min(x,y); } public double min(double x,double y){ return Math.min(x,y); }public long gcd(long a, long b) { if (a == 0) return b; return gcd(b % a, a); }public long lcm(long a, long b) { return (a / gcd(a, b)) * b; } void sort1(int[] a) { ArrayList<Integer> l = new ArrayList<>(); for (int i : a) { l.add(i); } Collections.sort(l,Collections.reverseOrder()); for (int i = 0; i < a.length; i++) { a[i] = l.get(i); } } 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); } }void sort(char[] a) { ArrayList<Character> l = new ArrayList<>(); for (char i : a) { l.add(i); } Collections.sort(l); for (int i = 0; i < a.length; i++) { a[i] = l.get(i); } }void sort1(char[] a) { ArrayList<Character> l = new ArrayList<>(); for (char i : a) { l.add(i); } Collections.sort(l,Collections.reverseOrder()); for (int i = 0; i < a.length; i++) { a[i] = l.get(i); } } 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); } }void sort1(long[] a) { ArrayList<Long> l = new ArrayList<>(); for (long i : a) { l.add(i); } Collections.sort(l,Collections.reverseOrder()); for (int i = 0; i < a.length; i++) { a[i] = l.get(i); } } void sort(double[] a) { ArrayList<Double> l = new ArrayList<>(); for (double i : a) { l.add(i); } Collections.sort(l); for (int i = 0; i < a.length; i++) { a[i] = l.get(i); } }long pow(long a,long b){ if(b==0){ return 1; }long p=pow(a,b/2); if(b%2==0) return mMultiplication(p,p)%mod; else return (mMultiplication(mMultiplication(p,p),a))%mod; } int swap(int a,int b){ return a; }long swap(long a,long b){ return a; }double swap(double a,double b){ return a; } boolean isPowerOfTwo (int x) { return x!=0 && ((x&(x-1)) == 0); }boolean isPowerOfTwo (long x) { return x!=0 && ((x&(x-1)) == 0); }public long max(long x,long y){ return (long)Math.max(x,y); } public int max(int x,int y){ return (int)Math.max(x,y); } public double max(double x,double y){ return Math.max(x,y); }long sqrt(long x){ return (long)Math.sqrt(x); }int sqrt(int x){ return (int)Math.sqrt(x); }void input(int[] ar,int n){ for(int i=0;i<n;i++)ar[i]=ni(); }void input(long[] ar,int n){ for(int i=0;i<n;i++)ar[i]=nl(); }void fill(int[] ar,int k){ Arrays.fill(ar,k); }void yes(){ pl("YES"); }void no(){ pl("NO"); } long c2(long n) { return (n*(n-1))/2; } long[] sieve(int n) { long[] k=new long[n+1]; boolean[] pr=new boolean[n+1]; for(int i=1;i<=n;i++){ k[i]=i; pr[i]=true; }for(int i=2;i<=n;i++){ if(pr[i]){ for(int j=i+i;j<=n;j+=i){ pr[j]=false; if(k[j]==j){ k[j]=i; } } } }return k; } int strSmall(int[] arr, int target) { int start = 0, end = arr.length-1; int ans = -1; while (start <= end) { int mid = (start + end) / 2; if (arr[mid] >= target) { end = mid - 1; } else { ans = mid; start = mid + 1; } } return ans; } int strSmall(ArrayList<Integer> arr, int target) { int start = 0, end = arr.size()-1; int ans = -1; while (start <= end) { int mid = (start + end) / 2; if (arr.get(mid) > target) { start = mid + 1; ans=start; } else { end = mid - 1; } } return ans; }long mMultiplication(long a,long b) { long res = 0; a %= mod; while (b > 0) { if ((b & 1) > 0) { res = (res + a) % mod; } a = (2 * a) % mod; b >>= 1; } return res; }long nCr(int n, int r ,long p) { if (n<r) return 0; if (r == 0) return 1; long[] fac = new long[n + 1]; fac[0] = 1; for (int i = 1; i <= n; i++) fac[i] = fac[i - 1] * i %p; return (fac[n] * modInverse(fac[r], p) % p * modInverse(fac[n - r], p) % p) % p; }long power(long x, long y, long p) { long res = 1; x = x % p; while (y > 0) { if (y % 2 == 1) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return res; }long modInverse(long n, long p) { return power(n, p - 2, p); } int[][] floydWarshall(int graph[][],int INF,int V) { int dist[][] = new int[V][V]; int i, j, k; for (i = 0; i < V; i++) for (j = 0; j < V; j++) dist[i][j] = graph[i][j]; for (k = 0; k < V; k++) { for (i = 0; i < V; i++) { for (j = 0; j < V; j++) { if (dist[i][k] + dist[k][j] < dist[i][j]) dist[i][j] = dist[i][k] + dist[k][j]; } } }return dist; } class minque { Deque<Long> q; minque(){ q=new ArrayDeque<Long>(); }public void add(long p){ while(!q.isEmpty()&&q.peekLast()>p)q.pollLast(); q.addLast(p); }public void remove(long p) { if(!q.isEmpty()&&q.getFirst()==p)q.removeFirst(); }public long min() { return q.getFirst(); } } int find(subset[] subsets, int i) { if (subsets[i].parent != i) subsets[i].parent = find(subsets, subsets[i].parent); return subsets[i].parent; }void Union(subset[] subsets, int x, int y) { int xroot = find(subsets, x); int yroot = find(subsets, y); if (subsets[xroot].rank < subsets[yroot].rank) { subsets[xroot].parent = yroot; } else if (subsets[yroot].rank < subsets[xroot].rank) { subsets[yroot].parent = xroot; } else { subsets[xroot].parent = yroot; subsets[yroot].rank++; } }class subset { int parent; int rank; }class pair<U extends Comparable<U>, V extends Comparable<V>> implements Comparable<pair<U, V>> { public U x; public V y; public pair(U x, V y) { this.x = x; this.y = y; } public int compareTo(pair<U, V> other) { int i = x.compareTo(other.x); if (i != 0) return i; return y.compareTo(other.y); } public String toString() { return x.toString() + " " + y.toString(); } @SuppressWarnings("unchecked") public boolean equals(Object obj){ if (this.getClass() != obj.getClass()) return false; pair<U, V> other = (pair<U, V>) obj; return x.equals(other.x) && y.equals(other.y); } public int hashCode(){ return 31 * x.hashCode() + y.hashCode(); } } }
Java
["1\n\n2\n\n-1"]
1 second
["? 1 2\n\n? 1 3\n\n? 1 4\n\n! 3"]
NoteIn the first example, the graph could look like this The lengths of the simple paths between all pairs of vertices in this case are $$$1$$$ or $$$2$$$. The first query finds out that one of the simple paths from vertex $$$1$$$ to vertex $$$2$$$ has a length of $$$1$$$. With the second query, we find out that one of the simple paths from vertex $$$1$$$ to vertex $$$3$$$ has length $$$2$$$. In the third query, we find out that vertex $$$4$$$ is not in the graph. Consequently, the size of the graph is $$$3$$$.
Java 11
standard input
[ "interactive", "probabilities" ]
8590f40e7509614694486165ee824587
null
1,800
null
standard output
PASSED
eeba8be1e8de521dd411b2c14168f7ad
train_110.jsonl
1662993300
This is an interactive problem.I want to play a game with you...We hid from you a cyclic graph of $$$n$$$ vertices ($$$3 \le n \le 10^{18}$$$). A cyclic graph is an undirected graph of $$$n$$$ vertices that form one cycle. Each vertex belongs to the cycle, i.e. the length of the cycle (the number of edges in it) is exactly $$$n$$$. The order of the vertices in the cycle is arbitrary.You can make queries in the following way: "? a b" where $$$1 \le a, b \le 10^{18}$$$ and $$$a \neq b$$$. In response to the query, the interactor outputs on a separate line the length of random of two paths from vertex $$$a$$$ to vertex $$$b$$$, or -1 if $$$\max(a, b) &gt; n$$$. The interactor chooses one of the two paths with equal probability. The length of the path —is the number of edges in it.You win if you guess the number of vertices in the hidden graph (number $$$n$$$) by making no more than $$$50$$$ queries.Note that the interactor is implemented in such a way that for any ordered pair $$$(a, b)$$$, it always returns the same value for query "? a b", no matter how many such queries. Note that the "? b a" query may be answered differently by the interactor.The vertices in the graph are randomly placed, and their positions are fixed in advance.Hacks are forbidden in this problem. The number of tests the jury has is $$$50$$$.
256 megabytes
import java.io.*; import java.util.*; public class E2 { static IOHandler sc = new IOHandler(); public static void main(String[] args) { // TODO Auto-generated method stub solve(0); } private static void solve(int t) { long min = 1; long a = 2; long b = 3; long result = 0; for (int i = 2; i < 25; ++i) { a = query(1, i); if (a == -1) { System.out.println("! " + (i - 1)); System.out.flush(); return; } b = query(i , 1); result = Math.max(result, 2*Math.min(a, b)); if (a != b) { System.out.println("! " + (a + b)); System.out.flush(); return; } } System.out.println("! " + (a + b)); System.out.flush(); } private static long query(long base, long num) { System.out.println("? " + base + " " + num); System.out.flush(); return sc.nextLong(); } 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
["1\n\n2\n\n-1"]
1 second
["? 1 2\n\n? 1 3\n\n? 1 4\n\n! 3"]
NoteIn the first example, the graph could look like this The lengths of the simple paths between all pairs of vertices in this case are $$$1$$$ or $$$2$$$. The first query finds out that one of the simple paths from vertex $$$1$$$ to vertex $$$2$$$ has a length of $$$1$$$. With the second query, we find out that one of the simple paths from vertex $$$1$$$ to vertex $$$3$$$ has length $$$2$$$. In the third query, we find out that vertex $$$4$$$ is not in the graph. Consequently, the size of the graph is $$$3$$$.
Java 11
standard input
[ "interactive", "probabilities" ]
8590f40e7509614694486165ee824587
null
1,800
null
standard output
PASSED
41c4150865035e783bad64d6af3525de
train_110.jsonl
1662993300
This is an interactive problem.I want to play a game with you...We hid from you a cyclic graph of $$$n$$$ vertices ($$$3 \le n \le 10^{18}$$$). A cyclic graph is an undirected graph of $$$n$$$ vertices that form one cycle. Each vertex belongs to the cycle, i.e. the length of the cycle (the number of edges in it) is exactly $$$n$$$. The order of the vertices in the cycle is arbitrary.You can make queries in the following way: "? a b" where $$$1 \le a, b \le 10^{18}$$$ and $$$a \neq b$$$. In response to the query, the interactor outputs on a separate line the length of random of two paths from vertex $$$a$$$ to vertex $$$b$$$, or -1 if $$$\max(a, b) &gt; n$$$. The interactor chooses one of the two paths with equal probability. The length of the path —is the number of edges in it.You win if you guess the number of vertices in the hidden graph (number $$$n$$$) by making no more than $$$50$$$ queries.Note that the interactor is implemented in such a way that for any ordered pair $$$(a, b)$$$, it always returns the same value for query "? a b", no matter how many such queries. Note that the "? b a" query may be answered differently by the interactor.The vertices in the graph are randomly placed, and their positions are fixed in advance.Hacks are forbidden in this problem. The number of tests the jury has is $$$50$$$.
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; public class Test { final static private FastReader fr = new FastReader(); final static private PrintWriter out = new PrintWriter(System.out) ; final static private int mod = (int)1e9 + 7; private static void solve() { int cnt = 0 ; TreeSet<Long> set = new TreeSet<>((a1, a2)->{ if(a1 >= a2) return -1 ; return 1 ; }) ; int i = 1, j = 2 ; while(true){ out.println("? "+ (i) +" "+ (j)); out.flush(); long len1 = fr.nextLong() ; if(len1 == -1) { out.println("! "+ (j-1)); return; } out.println("? "+ (j) +" "+ (i)); out.flush(); long len2 = fr.nextLong() ; cnt += 2 ; if(len1 == len2) { set.add(len1 + len1) ; i = j; j = i+1; } else { out.println("! " + (len1 + len2)); out.flush(); return; } if(cnt == 50) { break ; } } out.println("! "+ set.first()); out.flush(); } public static void main(String[] args) { int t = 1 ; //t = fr.nextInt() ; while (t-- > 0) { solve() ; } out.close() ; } private static long[] inputArr(int n){ long[] arr = new long[n] ; for (int i = 0 ;i < n ; i++) { arr[i] = fr.nextLong() ; } return arr; } private static void prefixSum(long[] arr) { for(int i = 1; i < arr.length; i++) arr[i] += arr[i-1] ; } private static void sort(int[] arr){ ArrayList<Integer> al = new ArrayList<>() ; for (int x : arr){ al.add(x) ; } Collections.sort(al); for (int i = 0 ; i < arr.length; i++){ arr[i] = al.get(i) ; } } private static void sort(long[] arr){ ArrayList<Long> al = new ArrayList<>() ; for (long x : arr){ al.add(x) ; } Collections.sort(al); for (int i = 0 ; i < arr.length; i++){ arr[i] = al.get(i) ; } } private static long getMax(long ... a) { long max = Long.MIN_VALUE ; for (long x : a) max = Math.max(x, max) ; return max ; } private static long getMin(long ... a) { long max = Long.MAX_VALUE ; for (long x : a) max = Math.min(x, max) ; return max ; } private static double fastPower(double a, long b) { double ans = 1 ; while (b > 0) { if ((b & 1) != 0) ans *= a ; a *= a ; b >>= 1 ; } return ans ; } private static long fastPower(long a, long b, long mod) { long ans = 1 ; while (b > 0) { if ((b&1) != 0) ans = (ans%mod * a%mod) %mod; b >>= 1 ; a = (a%mod * a%mod)%mod ; } return ans ; } private static int lower_bound(List<Integer> arr, int key) { int pos = Collections.binarySearch(arr, key) ; if (pos < 0) { pos = - (pos + 1) ; } return pos ; } private static int upper_bound(List<Integer> arr, int key) { int pos = Collections.binarySearch(arr, key); pos++ ; if (pos < 0) { pos = -(pos) ; } return pos ; } private static int upper_bound(int[] arr, int key) { int start = 0 , end = arr.length ; while (start < end) { int mid = start + ((end - start) >> 1) ; if (arr[mid] <= key) start = mid + 1 ; else end = mid ; } return start ; } private static int lower_bound(int[] arr, int key) { int start = 0 , end = arr.length; while (start < end) { int mid = start + ((end - start )>>1) ; if (arr[mid] >= key){ end = mid ; } else start = mid + 1 ; } return start ; } private static class Pair<T>{ T x ; T y ; Pair(T x, T y){ this.x = x ; this.y = y ; } @Override public int hashCode() { return super.hashCode(); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Pair pair = (Pair) o; return x == pair.x && y == pair.y; } } private static long gcd(long a, long b) { if (b == 0) return a ; return gcd(b, a%b) ; } private static long lcm(long a, long b) { return (a * b)/gcd(a, b); } private static boolean isPrime(int num) { if (num <= 2) return true ; for (int i = 2; i <= Math.sqrt(num); i++) { if (num%i == 0) return false ; } return true; } private static List<Long> seive(int n) { // all are false by default // false -> prime, true -> composite boolean[] nums = new boolean[n+1] ; for (int i = 2 ; i <= Math.sqrt(n); i++) { if (!nums[i]) { for (int j = i*i ; j <= n ; j += i) { nums[j] = true ; } } } ArrayList<Long>primes = new ArrayList<>() ; for (int i = 2 ; i <=n ; i++) { if (!nums[i]) primes.add((long) i) ; } return primes ; } private static boolean isVowel(char ch) { return ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u'; } private static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader( new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["1\n\n2\n\n-1"]
1 second
["? 1 2\n\n? 1 3\n\n? 1 4\n\n! 3"]
NoteIn the first example, the graph could look like this The lengths of the simple paths between all pairs of vertices in this case are $$$1$$$ or $$$2$$$. The first query finds out that one of the simple paths from vertex $$$1$$$ to vertex $$$2$$$ has a length of $$$1$$$. With the second query, we find out that one of the simple paths from vertex $$$1$$$ to vertex $$$3$$$ has length $$$2$$$. In the third query, we find out that vertex $$$4$$$ is not in the graph. Consequently, the size of the graph is $$$3$$$.
Java 11
standard input
[ "interactive", "probabilities" ]
8590f40e7509614694486165ee824587
null
1,800
null
standard output
PASSED
530fd6da329b173e6289291b86a9d054
train_110.jsonl
1662993300
This is an interactive problem.I want to play a game with you...We hid from you a cyclic graph of $$$n$$$ vertices ($$$3 \le n \le 10^{18}$$$). A cyclic graph is an undirected graph of $$$n$$$ vertices that form one cycle. Each vertex belongs to the cycle, i.e. the length of the cycle (the number of edges in it) is exactly $$$n$$$. The order of the vertices in the cycle is arbitrary.You can make queries in the following way: "? a b" where $$$1 \le a, b \le 10^{18}$$$ and $$$a \neq b$$$. In response to the query, the interactor outputs on a separate line the length of random of two paths from vertex $$$a$$$ to vertex $$$b$$$, or -1 if $$$\max(a, b) &gt; n$$$. The interactor chooses one of the two paths with equal probability. The length of the path —is the number of edges in it.You win if you guess the number of vertices in the hidden graph (number $$$n$$$) by making no more than $$$50$$$ queries.Note that the interactor is implemented in such a way that for any ordered pair $$$(a, b)$$$, it always returns the same value for query "? a b", no matter how many such queries. Note that the "? b a" query may be answered differently by the interactor.The vertices in the graph are randomly placed, and their positions are fixed in advance.Hacks are forbidden in this problem. The number of tests the jury has is $$$50$$$.
256 megabytes
import java.io.*; import java.util.*; public class E2 { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); long a = 1, b = 2; long ans = 0; int cnt = 24; while (cnt-- > 0) { System.out.println("? "+a+" "+b); System.out.flush(); long n = Long.parseLong(br.readLine()); if (n == -1) { System.out.println("! "+(b-1)); System.out.flush(); return; } else { System.out.println("? "+b+" "+a); System.out.flush(); long m = Long.parseLong(br.readLine()); if (n != m) { System.out.println("! "+(n+m)); System.out.flush(); return; } else { ans = n + m; b++; } } } System.out.println("! " + ans); System.out.flush(); } }
Java
["1\n\n2\n\n-1"]
1 second
["? 1 2\n\n? 1 3\n\n? 1 4\n\n! 3"]
NoteIn the first example, the graph could look like this The lengths of the simple paths between all pairs of vertices in this case are $$$1$$$ or $$$2$$$. The first query finds out that one of the simple paths from vertex $$$1$$$ to vertex $$$2$$$ has a length of $$$1$$$. With the second query, we find out that one of the simple paths from vertex $$$1$$$ to vertex $$$3$$$ has length $$$2$$$. In the third query, we find out that vertex $$$4$$$ is not in the graph. Consequently, the size of the graph is $$$3$$$.
Java 11
standard input
[ "interactive", "probabilities" ]
8590f40e7509614694486165ee824587
null
1,800
null
standard output
PASSED
f710e10042ebaa69b9ea8250fdbb5501
train_110.jsonl
1662993300
This is an interactive problem.I want to play a game with you...We hid from you a cyclic graph of $$$n$$$ vertices ($$$3 \le n \le 10^{18}$$$). A cyclic graph is an undirected graph of $$$n$$$ vertices that form one cycle. Each vertex belongs to the cycle, i.e. the length of the cycle (the number of edges in it) is exactly $$$n$$$. The order of the vertices in the cycle is arbitrary.You can make queries in the following way: "? a b" where $$$1 \le a, b \le 10^{18}$$$ and $$$a \neq b$$$. In response to the query, the interactor outputs on a separate line the length of random of two paths from vertex $$$a$$$ to vertex $$$b$$$, or -1 if $$$\max(a, b) &gt; n$$$. The interactor chooses one of the two paths with equal probability. The length of the path —is the number of edges in it.You win if you guess the number of vertices in the hidden graph (number $$$n$$$) by making no more than $$$50$$$ queries.Note that the interactor is implemented in such a way that for any ordered pair $$$(a, b)$$$, it always returns the same value for query "? a b", no matter how many such queries. Note that the "? b a" query may be answered differently by the interactor.The vertices in the graph are randomly placed, and their positions are fixed in advance.Hacks are forbidden in this problem. The number of tests the jury has is $$$50$$$.
256 megabytes
import java.util.*; import java.io.*; public class E1729{ static FastScanner fs = null; public static void main(String[] args) { fs = new FastScanner(); PrintWriter out = new PrintWriter(System.out); int t = 1; while(t-->0){ long ans = (long)0; for(int i=2;i<=26;i++){ System.out.println("? "+i+" "+"1"); System.out.flush(); long a = fs.nextLong(); if(a==-(long)1){ ans = (long)(i-1); break; } System.out.println("? "+"1"+" "+i); System.out.flush(); long b = fs.nextLong(); if(a!=b){ ans = (long)(a+b); break; } } System.out.println("! "+ans); } out.close(); } static void sort(int[] a) { ArrayList<Integer> l=new ArrayList<>(); for (int i:a) l.add(i); Collections.sort(l); for (int i=0; i<a.length; i++) a[i]=l.get(i); } static class FastScanner { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readArray(int n) { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } } }
Java
["1\n\n2\n\n-1"]
1 second
["? 1 2\n\n? 1 3\n\n? 1 4\n\n! 3"]
NoteIn the first example, the graph could look like this The lengths of the simple paths between all pairs of vertices in this case are $$$1$$$ or $$$2$$$. The first query finds out that one of the simple paths from vertex $$$1$$$ to vertex $$$2$$$ has a length of $$$1$$$. With the second query, we find out that one of the simple paths from vertex $$$1$$$ to vertex $$$3$$$ has length $$$2$$$. In the third query, we find out that vertex $$$4$$$ is not in the graph. Consequently, the size of the graph is $$$3$$$.
Java 11
standard input
[ "interactive", "probabilities" ]
8590f40e7509614694486165ee824587
null
1,800
null
standard output
PASSED
e37bcfb73b2fb04e0118b77a1b6e0e1d
train_110.jsonl
1662993300
This is an interactive problem.I want to play a game with you...We hid from you a cyclic graph of $$$n$$$ vertices ($$$3 \le n \le 10^{18}$$$). A cyclic graph is an undirected graph of $$$n$$$ vertices that form one cycle. Each vertex belongs to the cycle, i.e. the length of the cycle (the number of edges in it) is exactly $$$n$$$. The order of the vertices in the cycle is arbitrary.You can make queries in the following way: "? a b" where $$$1 \le a, b \le 10^{18}$$$ and $$$a \neq b$$$. In response to the query, the interactor outputs on a separate line the length of random of two paths from vertex $$$a$$$ to vertex $$$b$$$, or -1 if $$$\max(a, b) &gt; n$$$. The interactor chooses one of the two paths with equal probability. The length of the path —is the number of edges in it.You win if you guess the number of vertices in the hidden graph (number $$$n$$$) by making no more than $$$50$$$ queries.Note that the interactor is implemented in such a way that for any ordered pair $$$(a, b)$$$, it always returns the same value for query "? a b", no matter how many such queries. Note that the "? b a" query may be answered differently by the interactor.The vertices in the graph are randomly placed, and their positions are fixed in advance.Hacks are forbidden in this problem. The number of tests the jury has is $$$50$$$.
256 megabytes
/** * Created by Himanshu **/ import java.util.*; import java.io.*; public class E1729 { static final int ALPHABET_SIZE = 26; static Reader s = new Reader(); public static void main(String[] args) throws IOException { long start = 1L , end = (long) (1e17) * 5L; // while (true) { // long val = query(start,end); // if (val == -1) { // end /= 10; // if (end <= start) { // end = start*10 - 1L; // break; // } // } else { // start = end; // if (end == (long) (1e17) * 5L) end = (long)(1e18); // else end = end*10L - 1L; // break; // } // } // long prev = end; // while (start < end) { // long val = query(start,end); // if (val == -1) { // prev = end; // end = start + (end-start)/2L; // } else { // start = end; // end = start + (prev-start)/2L; // } // } // System.out.println("! " + start); // System.out.flush(); long ans = 0L; for (int i=0;i<50;i+=2) { long val = query(i+1,i+2); if (val == -1) { val = query(i,i+1); if (val == -1) ans = i; else ans = i+1; break; } long val2 = query(i+2,i+1); if (val2 != val) { ans += val2+val; break; } } System.out.println("! " + ans); System.out.flush(); } private static long query(long start , long end) { System.out.println("? " + start + " " + end); System.out.flush(); return s.l(); } public static void shuffle(long[] arr) { int n = arr.length; Random rand = new Random(); for (int i = 0; i < n; i++) { long temp = arr[i]; int randomPos = i + rand.nextInt(n - i); arr[i] = arr[randomPos]; arr[randomPos] = temp; } } private static long phi(long n) { long result = n; for (long i = 2; i * i <= n; i++) { if (n % i == 0) { while (n % i == 0) n /= i; result -= result / i; } } if (n > 1) result -= result / n; return result; } private static int gcd(int a, int b) { if(b == 0) return a; return gcd(b,a%b); } public static long nCr(long[] fact, long[] inv, int n, int r, long mod) { if (n < r) return 0; return ((fact[n] * inv[n - r]) % mod * inv[r]) % mod; } private static void factorials(long[] fact, long[] inv, long mod, int n) { fact[0] = 1; inv[0] = 1; for (int i = 1; i <= n; ++i) { fact[i] = (fact[i - 1] * i) % mod; inv[i] = power(fact[i], mod - 2, mod); } } private static long power(long a, long n, long p) { long result = 1; while (n > 0) { if (n % 2 == 0) { a = (a * a) % p; n /= 2; } else { result = (result * a) % p; n--; } } return result; } private static long power(long a, long n) { long result = 1; while (n > 0) { if (n % 2 == 0) { a = (a * a); n /= 2; } else { result = (result * a); n--; } } return result; } private static long query(long[] tree, int in, int start, int end, int l, int r) { if (start >= l && r >= end) return tree[in]; if (end < l || start > r) return 0; int mid = (start + end) / 2; long x = query(tree, 2 * in, start, mid, l, r); long y = query(tree, 2 * in + 1, mid + 1, end, l, r); return x + y; } private static void update(int[] arr, long[] tree, int in, int start, int end, int idx, int val) { if (start == end) { tree[in] = val; arr[idx] = val; return; } int mid = (start + end) / 2; if (idx > mid) update(arr, tree, 2 * in + 1, mid + 1, end, idx, val); else update(arr, tree, 2 * in, start, mid, idx, val); tree[in] = tree[2 * in] + tree[2 * in + 1]; } private static void build(int[] arr, long[] tree, int in, int start, int end) { if (start == end) { tree[in] = arr[start]; return; } int mid = (start + end) / 2; build(arr, tree, 2 * in, start, mid); build(arr, tree, 2 * in + 1, mid + 1, end); tree[in] = (tree[2 * in + 1] + tree[2 * in]); } static class Reader { private InputStream mIs; private byte[] buf = new byte[1024]; private int curChar, numChars; public Reader() { this(System.in); } public Reader(InputStream is) { mIs = is; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = mIs.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public String s() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public long l() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int i() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public double d() throws IOException { return Double.parseDouble(s()); } public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } public int[] arr(int n) { int[] ret = new int[n]; for (int i = 0; i < n; i++) { ret[i] = i(); } return ret; } public long[] arrLong(int n) { long[] ret = new long[n]; for (int i = 0; i < n; i++) { ret[i] = l(); } return ret; } } static class TrieNode { TrieNode[] children = new TrieNode[ALPHABET_SIZE]; boolean isLeaf; boolean isPalindrome; public TrieNode() { isLeaf = false; isPalindrome = false; for (int i = 0; i < ALPHABET_SIZE; i++) children[i] = null; } } // static class pairLong implements Comparator<pairLong> { // long first, second; // // pairLong() { // } // // pairLong(long first, long second) { // this.first = first; // this.second = second; // } // // @Override // public int compare(pairLong p1, pairLong p2) { // if (p1.first == p2.first) { // if(p1.second > p2.second) return 1; // else return -1; // } // if(p1.first > p2.first) return 1; // else return -1; // } // } // static class pair implements Comparator<pair> { // int first, second; // // pair() { // } // // pair(int first, int second) { // this.first = first; // this.second = second; // } // // @Override // public int compare(pair p1, pair p2) { // if (p1.first == p2.first) return p1.second - p2.second; // return p1.first - p2.first; // } // } }
Java
["1\n\n2\n\n-1"]
1 second
["? 1 2\n\n? 1 3\n\n? 1 4\n\n! 3"]
NoteIn the first example, the graph could look like this The lengths of the simple paths between all pairs of vertices in this case are $$$1$$$ or $$$2$$$. The first query finds out that one of the simple paths from vertex $$$1$$$ to vertex $$$2$$$ has a length of $$$1$$$. With the second query, we find out that one of the simple paths from vertex $$$1$$$ to vertex $$$3$$$ has length $$$2$$$. In the third query, we find out that vertex $$$4$$$ is not in the graph. Consequently, the size of the graph is $$$3$$$.
Java 11
standard input
[ "interactive", "probabilities" ]
8590f40e7509614694486165ee824587
null
1,800
null
standard output
PASSED
22c7a33608bd437764ea9b7a206c3fc1
train_110.jsonl
1662993300
This is an interactive problem.I want to play a game with you...We hid from you a cyclic graph of $$$n$$$ vertices ($$$3 \le n \le 10^{18}$$$). A cyclic graph is an undirected graph of $$$n$$$ vertices that form one cycle. Each vertex belongs to the cycle, i.e. the length of the cycle (the number of edges in it) is exactly $$$n$$$. The order of the vertices in the cycle is arbitrary.You can make queries in the following way: "? a b" where $$$1 \le a, b \le 10^{18}$$$ and $$$a \neq b$$$. In response to the query, the interactor outputs on a separate line the length of random of two paths from vertex $$$a$$$ to vertex $$$b$$$, or -1 if $$$\max(a, b) &gt; n$$$. The interactor chooses one of the two paths with equal probability. The length of the path —is the number of edges in it.You win if you guess the number of vertices in the hidden graph (number $$$n$$$) by making no more than $$$50$$$ queries.Note that the interactor is implemented in such a way that for any ordered pair $$$(a, b)$$$, it always returns the same value for query "? a b", no matter how many such queries. Note that the "? b a" query may be answered differently by the interactor.The vertices in the graph are randomly placed, and their positions are fixed in advance.Hacks are forbidden in this problem. The number of tests the jury has is $$$50$$$.
256 megabytes
import java.io.*; import java.util.*; public class Main { static FastScanner fs; public static void main(String[] args) { fs=new FastScanner(); PrintWriter out = new PrintWriter(System.out); /****** CODE STARTS HERE *****/ //-------------------------------------------------------------------------------------------------------- out.println("! "+compute()); out.close(); } static long compute() { for(int n=2; n<=26; n++) { long a = ask(1, n); long b = ask(n, 1); if(a != b)return a+b; if(a==-1)return n-1; }return -1; } static long ask(long a, long b) { System.out.println("? "+a+" "+b); System.out.flush(); return fs.nextLong(); } //****** CODE ENDS HERE ***** //---------------------------------------------------------------------------------------------------------------- int ceil(int a, int b) { return (a + b - 1) / 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); } //----------- FastScanner class for faster input--------------------------- static class FastScanner { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readArray(int n) { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } long nextLong() { return Long.parseLong(next()); } } }
Java
["1\n\n2\n\n-1"]
1 second
["? 1 2\n\n? 1 3\n\n? 1 4\n\n! 3"]
NoteIn the first example, the graph could look like this The lengths of the simple paths between all pairs of vertices in this case are $$$1$$$ or $$$2$$$. The first query finds out that one of the simple paths from vertex $$$1$$$ to vertex $$$2$$$ has a length of $$$1$$$. With the second query, we find out that one of the simple paths from vertex $$$1$$$ to vertex $$$3$$$ has length $$$2$$$. In the third query, we find out that vertex $$$4$$$ is not in the graph. Consequently, the size of the graph is $$$3$$$.
Java 11
standard input
[ "interactive", "probabilities" ]
8590f40e7509614694486165ee824587
null
1,800
null
standard output
PASSED
21042cfa74cd1e278c98b11bf7f8cfaf
train_110.jsonl
1662993300
This is an interactive problem.I want to play a game with you...We hid from you a cyclic graph of $$$n$$$ vertices ($$$3 \le n \le 10^{18}$$$). A cyclic graph is an undirected graph of $$$n$$$ vertices that form one cycle. Each vertex belongs to the cycle, i.e. the length of the cycle (the number of edges in it) is exactly $$$n$$$. The order of the vertices in the cycle is arbitrary.You can make queries in the following way: "? a b" where $$$1 \le a, b \le 10^{18}$$$ and $$$a \neq b$$$. In response to the query, the interactor outputs on a separate line the length of random of two paths from vertex $$$a$$$ to vertex $$$b$$$, or -1 if $$$\max(a, b) &gt; n$$$. The interactor chooses one of the two paths with equal probability. The length of the path —is the number of edges in it.You win if you guess the number of vertices in the hidden graph (number $$$n$$$) by making no more than $$$50$$$ queries.Note that the interactor is implemented in such a way that for any ordered pair $$$(a, b)$$$, it always returns the same value for query "? a b", no matter how many such queries. Note that the "? b a" query may be answered differently by the interactor.The vertices in the graph are randomly placed, and their positions are fixed in advance.Hacks are forbidden in this problem. The number of tests the jury has is $$$50$$$.
256 megabytes
import java.io.*; import java.util.Comparator; import java.util.PriorityQueue; public class Main { static class Pair{ long n1, n2; long dist; Pair(long n1, long n2, long d) { this.n1= Math.min(n1, n2); this.n2 = Math.max(n1, n2); dist = d; } } public static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); public static PriorityQueue<Pair> pq; public static long min = 2, max = 1000000000000000001L; public static void main(String[] args) throws IOException { BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); pq = new PriorityQueue<>(new Comparator<Pair>() { @Override public int compare(Pair o1, Pair o2) { return Long.compare(o1.dist, o2.dist); } }); question(1, 2); pq.offer(new Pair(1, 2, getLength())); long next = 3; while(true) { check(pq.peek(), next++); } } public static void question(long n1, long n2) { System.out.printf("? %d %d\n", Math.min(n1, n2), Math.max(n1, n2)); } public static long getLength() throws IOException{ return Long.parseLong(br.readLine()); } public static void check(Pair p, long n) throws IOException { question(p.n1, n); long n1 = getLength(); if (n1 == -1) { System.out.println("! "+(n-1)); System.exit(0); } question(p.n2, n); long n2 = getLength(); pq.offer(new Pair(p.n1, n, n1)); pq.offer(new Pair(p.n2, n, n2)); long sum = n1 + n2 + p.dist; if (sum >= max || sum <= min) return; if (sum == max -1) { System.out.println("! "+sum); System.exit(0); } question(1, sum); long a = getLength(); min = Math.max(min, a); if (a < 0) { max = Math.min(max, sum); } else { pq.offer(new Pair(1, sum, a)); question(1, sum+1); a = getLength(); pq.offer(new Pair(1, sum+1, a)); if (a < 0) { System.out.println("! "+sum); System.exit(0); } else { min = Math.max(min, a); min = Math.max(min, sum); } } } }
Java
["1\n\n2\n\n-1"]
1 second
["? 1 2\n\n? 1 3\n\n? 1 4\n\n! 3"]
NoteIn the first example, the graph could look like this The lengths of the simple paths between all pairs of vertices in this case are $$$1$$$ or $$$2$$$. The first query finds out that one of the simple paths from vertex $$$1$$$ to vertex $$$2$$$ has a length of $$$1$$$. With the second query, we find out that one of the simple paths from vertex $$$1$$$ to vertex $$$3$$$ has length $$$2$$$. In the third query, we find out that vertex $$$4$$$ is not in the graph. Consequently, the size of the graph is $$$3$$$.
Java 11
standard input
[ "interactive", "probabilities" ]
8590f40e7509614694486165ee824587
null
1,800
null
standard output
PASSED
a91219dc3baff497380fef5a6b0c9536
train_110.jsonl
1662993300
This is an interactive problem.I want to play a game with you...We hid from you a cyclic graph of $$$n$$$ vertices ($$$3 \le n \le 10^{18}$$$). A cyclic graph is an undirected graph of $$$n$$$ vertices that form one cycle. Each vertex belongs to the cycle, i.e. the length of the cycle (the number of edges in it) is exactly $$$n$$$. The order of the vertices in the cycle is arbitrary.You can make queries in the following way: "? a b" where $$$1 \le a, b \le 10^{18}$$$ and $$$a \neq b$$$. In response to the query, the interactor outputs on a separate line the length of random of two paths from vertex $$$a$$$ to vertex $$$b$$$, or -1 if $$$\max(a, b) &gt; n$$$. The interactor chooses one of the two paths with equal probability. The length of the path —is the number of edges in it.You win if you guess the number of vertices in the hidden graph (number $$$n$$$) by making no more than $$$50$$$ queries.Note that the interactor is implemented in such a way that for any ordered pair $$$(a, b)$$$, it always returns the same value for query "? a b", no matter how many such queries. Note that the "? b a" query may be answered differently by the interactor.The vertices in the graph are randomly placed, and their positions are fixed in advance.Hacks are forbidden in this problem. The number of tests the jury has is $$$50$$$.
256 megabytes
/* package codechef; // don't place package name! */ import java.util.*; import java.io.*; /* Name of the class has to be "Main" only if the class is public. */ public class Codechef { public static void main (String[] args) throws IOException { BufferedReader f=new BufferedReader(new InputStreamReader(System.in)); // PrintWriter out=new PrintWriter(System.out); for(int i=2;i<=26;i++){ System.out.println("? 1 "+i); System.out.flush(); long x=Long.parseLong(f.readLine()); System.out.println("? "+i+" 1"); System.out.flush(); long y=Long.parseLong(f.readLine()); if(x!=y){ System.out.println("! "+(x+y)); System.out.flush(); break; } else if(x==-1){ System.out.println("! "+ (i-1)); System.out.flush(); break; } } f.close(); } }
Java
["1\n\n2\n\n-1"]
1 second
["? 1 2\n\n? 1 3\n\n? 1 4\n\n! 3"]
NoteIn the first example, the graph could look like this The lengths of the simple paths between all pairs of vertices in this case are $$$1$$$ or $$$2$$$. The first query finds out that one of the simple paths from vertex $$$1$$$ to vertex $$$2$$$ has a length of $$$1$$$. With the second query, we find out that one of the simple paths from vertex $$$1$$$ to vertex $$$3$$$ has length $$$2$$$. In the third query, we find out that vertex $$$4$$$ is not in the graph. Consequently, the size of the graph is $$$3$$$.
Java 11
standard input
[ "interactive", "probabilities" ]
8590f40e7509614694486165ee824587
null
1,800
null
standard output
PASSED
6f79bcf5dfdfef28b7cb826b0dc26110
train_110.jsonl
1662993300
This is an interactive problem.I want to play a game with you...We hid from you a cyclic graph of $$$n$$$ vertices ($$$3 \le n \le 10^{18}$$$). A cyclic graph is an undirected graph of $$$n$$$ vertices that form one cycle. Each vertex belongs to the cycle, i.e. the length of the cycle (the number of edges in it) is exactly $$$n$$$. The order of the vertices in the cycle is arbitrary.You can make queries in the following way: "? a b" where $$$1 \le a, b \le 10^{18}$$$ and $$$a \neq b$$$. In response to the query, the interactor outputs on a separate line the length of random of two paths from vertex $$$a$$$ to vertex $$$b$$$, or -1 if $$$\max(a, b) &gt; n$$$. The interactor chooses one of the two paths with equal probability. The length of the path —is the number of edges in it.You win if you guess the number of vertices in the hidden graph (number $$$n$$$) by making no more than $$$50$$$ queries.Note that the interactor is implemented in such a way that for any ordered pair $$$(a, b)$$$, it always returns the same value for query "? a b", no matter how many such queries. Note that the "? b a" query may be answered differently by the interactor.The vertices in the graph are randomly placed, and their positions are fixed in advance.Hacks are forbidden in this problem. The number of tests the jury has is $$$50$$$.
256 megabytes
//codeforces //package someAlgorithms; import java.util.*; import java.io.*; import java.lang.*; import java.io.File; public class Main { static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); public static void main(String[] args) throws IOException{ // String[] strNums = br.readLine().split(" "); // int t=Integer.parseInt(strNums[0]); // int ot=t; // FileWriter fw = new FileWriter("C:\\Users\\Lenovo\\Desktop\\output.txt"); // fw.write(""); // fw.close(); // while(t-->0) { //todo // String[] strNums1 = br.readLine().split(" "); // long n=Long.parseLong(strNums1[0]); // long b=Long.parseLong(strNums1[1]); // long c=Long.parseLong(strNums1[2]); // long c=Long.parseLong(strNums1[3]); // long d=Long.parseLong(strNums1[4]); // String str = br.readLine(); // String str2 = br.readLine(); // Long[] arr = new Long[(int)n]; // StringTokenizer tk = new StringTokenizer(br.readLine().trim()); // for(int i=0;i<n;i++) { // arr[i]=Long.parseLong(tk.nextToken()); // } // String[] strNums0 = br.readLine().split(" "); int i=2; while(i<27) { System.out.println("? "+1+" "+i); System.out.flush(); String[] strNums1 = br.readLine().split(" "); long a=Long.parseLong(strNums1[0]); System.out.println("? "+i+" "+1); System.out.flush(); String[] strNums2 = br.readLine().split(" "); long b=Long.parseLong(strNums2[0]); if(a!=b) { System.out.println("! "+(a+b)); System.out.flush(); break; } if(a==-1 || b==-1) { System.out.println("! "+(i-1)); System.out.flush(); break; } i++; // if(i<27) { // String[] strNums = br.readLine().split(" "); // } } // } } } /* bw.write(n+""); bw.newLine(); bw.flush(); System.out.println("Case #"+(ot-t)+":"+" YES"); FileWriter myWriter = new FileWriter("C:\\Users\\Lenovo\\Desktop\\output.txt",true); myWriter.write("Case #"+(ot-t)+": "+"YES"+"\n"); myWriter.close(); */ //class Pair{ // public long a=0; // public long b=0; // public Pair(long val,long id){ // this.a=val; // this.b=id; // } // //} //class Pair{ // public char val; // public long id; // public Pair(char val,long id){ // this.val=val; // this.id=id; // } // //} //class Node{ // public int val; //// public Node left=null; //// public Node right=null; // ArrayList<Node> children = new ArrayList<>(); // //} //class Comp implements Comparator<Pair>{ // public int compare(Pair p1,Pair p2) { // if(p1.val<p2.val) { // return -1; // } // if(p1.val>p2.val){ // return 1; // } // else return 0; //MUST WRITE THIS RETURN 0 FOR EQUAL CASE SINCE GIVE RUNTIME ERROR IN SOME COMPLIERS // } //} //sort [[a1,b1],[a2,b2]...] on basis of a1,a2.... since comparator compare run of each value of passed array! //class Comp implements Comparator<int[]>{ // public int compare(int[] p1,int[] p2) { // if(p1[0]<p2[0]) { // return -1; // } // if(p1[0]>p2[0]){ // return 1; // } // else return 0; // } //} //if take gcd of whole array the take default gcd=0 and keep doing gcd of 2 elements of array! //public static int gcd(int a, int b){ // if(b==0){ // return a; // } // return gcd(b,a%b); //} // //ArrayList<Long>[] adjlist = new ArrayList[(int)n+1]; //array of arraylist //for(int i=0;i<n;i++) { // String[] strNums2 = br.readLine().split(" "); // long a=Long.parseLong(strNums2[0]); // long b=Long.parseLong(strNums2[1]); // // adjlist[(int)a].add(b); // adjlist[(int)b].add(a); //} //int[][] vis = new int[(int)n+1][(int)n+1]; //OR can make list of list :- //List<List<Integer>> adjlist = new ArrayList<>(); //for(int i=0;i<n;i++){ // adjlist.add(new ArrayList<>()); //} //OR 1-D vis array //int[] vis = new int[(int)n+1]; /* Long[] arr = new Long[(int)n]; StringTokenizer tk = new StringTokenizer(br.readLine().trim()); for(int i=0;i<n;i++) { arr[i]=Long.parseLong(tk.nextToken()); } Long[][] arr = new Long[(int)n][(int)m]; for(int i=0;i<n;i++) { String[] strNums2 = br.readLine().split(" "); for(int j=0;j<m;j++) { arr[i][j]=Long.parseLong(strNums2[j]); } } 4 4 4 3 2 4 4 4 3 Main m = new Main(); //no need since pair class main class ne niche banao Pair p = m.new Pair(i,i+1); li.add(p); */ //double num = 3.9634; //double onum=num; //num = (double)((int)(num*100))/100; //double down = (num); //float up =(float) down; //if take up as double then will get large value when add (3.96+0.01)!! //if(down<onum) { // up=(float)down+(float)0.01; //// System.out.println(((float)3.96+(float)0.01)); //// System.out.println(3.96+0.01);//here both double, so output double , so here get large output other than 3.97!! //} ////in c++ 3.96+0.01 is by default 3.97 but in java need to type cast to float to get this output!! //System.out.println(down +" "+up); /* #include <iostream> #include <string> #include<vector> #include<queue> #include<utility> #include<limits.h> #include <unordered_set> #include<algorithm> using namespace std; */
Java
["1\n\n2\n\n-1"]
1 second
["? 1 2\n\n? 1 3\n\n? 1 4\n\n! 3"]
NoteIn the first example, the graph could look like this The lengths of the simple paths between all pairs of vertices in this case are $$$1$$$ or $$$2$$$. The first query finds out that one of the simple paths from vertex $$$1$$$ to vertex $$$2$$$ has a length of $$$1$$$. With the second query, we find out that one of the simple paths from vertex $$$1$$$ to vertex $$$3$$$ has length $$$2$$$. In the third query, we find out that vertex $$$4$$$ is not in the graph. Consequently, the size of the graph is $$$3$$$.
Java 11
standard input
[ "interactive", "probabilities" ]
8590f40e7509614694486165ee824587
null
1,800
null
standard output
PASSED
05f69df5cc7886ffbda66c32461f870e
train_110.jsonl
1662993300
This is an interactive problem.I want to play a game with you...We hid from you a cyclic graph of $$$n$$$ vertices ($$$3 \le n \le 10^{18}$$$). A cyclic graph is an undirected graph of $$$n$$$ vertices that form one cycle. Each vertex belongs to the cycle, i.e. the length of the cycle (the number of edges in it) is exactly $$$n$$$. The order of the vertices in the cycle is arbitrary.You can make queries in the following way: "? a b" where $$$1 \le a, b \le 10^{18}$$$ and $$$a \neq b$$$. In response to the query, the interactor outputs on a separate line the length of random of two paths from vertex $$$a$$$ to vertex $$$b$$$, or -1 if $$$\max(a, b) &gt; n$$$. The interactor chooses one of the two paths with equal probability. The length of the path —is the number of edges in it.You win if you guess the number of vertices in the hidden graph (number $$$n$$$) by making no more than $$$50$$$ queries.Note that the interactor is implemented in such a way that for any ordered pair $$$(a, b)$$$, it always returns the same value for query "? a b", no matter how many such queries. Note that the "? b a" query may be answered differently by the interactor.The vertices in the graph are randomly placed, and their positions are fixed in advance.Hacks are forbidden in this problem. The number of tests the jury has is $$$50$$$.
256 megabytes
import java.io.*; import java.util.*; import java.lang.*; public final class Solution{ static StringTokenizer st; static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); static int pi(String s) { return Integer.parseInt(s);} static long pl(String s) { return Long.parseLong(s);} static double pd(String s) { return Double.parseDouble(s);} static String is(int no) { return Integer.toString(no);} static String ls(long no) { return Long.toString(no);} static String ds(double no) { return Double.toString(no);} public static void main(String[] args) throws IOException{ long prev = 2; for (int i = 2; i <= 26; i++) { bw.write("? " + is(1) + " " + is(i) + "\n"); bw.flush(); long ip1 = pl(br.readLine()); bw.write("? " + is(i) + " " + is(1) + "\n"); bw.flush(); long ip2 = pl(br.readLine()); if(ip1 == -1) { break;} else if (ip1 == ip2) { prev = 1l * i;} else { prev = 1l * ip1 + ip2; break;} } bw.write("! "+ ls(prev) + "\n"); bw.flush(); } }
Java
["1\n\n2\n\n-1"]
1 second
["? 1 2\n\n? 1 3\n\n? 1 4\n\n! 3"]
NoteIn the first example, the graph could look like this The lengths of the simple paths between all pairs of vertices in this case are $$$1$$$ or $$$2$$$. The first query finds out that one of the simple paths from vertex $$$1$$$ to vertex $$$2$$$ has a length of $$$1$$$. With the second query, we find out that one of the simple paths from vertex $$$1$$$ to vertex $$$3$$$ has length $$$2$$$. In the third query, we find out that vertex $$$4$$$ is not in the graph. Consequently, the size of the graph is $$$3$$$.
Java 11
standard input
[ "interactive", "probabilities" ]
8590f40e7509614694486165ee824587
null
1,800
null
standard output
PASSED
c0b5c2f29b80191d16c930afeddc694c
train_110.jsonl
1662993300
This is an interactive problem.I want to play a game with you...We hid from you a cyclic graph of $$$n$$$ vertices ($$$3 \le n \le 10^{18}$$$). A cyclic graph is an undirected graph of $$$n$$$ vertices that form one cycle. Each vertex belongs to the cycle, i.e. the length of the cycle (the number of edges in it) is exactly $$$n$$$. The order of the vertices in the cycle is arbitrary.You can make queries in the following way: "? a b" where $$$1 \le a, b \le 10^{18}$$$ and $$$a \neq b$$$. In response to the query, the interactor outputs on a separate line the length of random of two paths from vertex $$$a$$$ to vertex $$$b$$$, or -1 if $$$\max(a, b) &gt; n$$$. The interactor chooses one of the two paths with equal probability. The length of the path —is the number of edges in it.You win if you guess the number of vertices in the hidden graph (number $$$n$$$) by making no more than $$$50$$$ queries.Note that the interactor is implemented in such a way that for any ordered pair $$$(a, b)$$$, it always returns the same value for query "? a b", no matter how many such queries. Note that the "? b a" query may be answered differently by the interactor.The vertices in the graph are randomly placed, and their positions are fixed in advance.Hacks are forbidden in this problem. The number of tests the jury has is $$$50$$$.
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 SolutionE { public static void main(String[] args) throws Exception { out = new PrintWriter(new BufferedOutputStream(System.out)); sc = new FastReader(); int test = 1; for (int t = 1; t <= test; t++) { solve(t); } out.close(); } private static void solve(int t) { for (int i = 1; ; i++) { for (int j = 1; j < i; j++) { out.println("? " + i + " " + j); out.flush(); long x = sc.nextLong(); out.println("? " + j + " " + i); out.flush(); long y = sc.nextLong(); if (x == -1 || y == -1) { out.println("! " + (i - 1)); out.flush(); return; } if (x != y) { out.println("! " + (x + y)); out.flush(); return; } } } } 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
["1\n\n2\n\n-1"]
1 second
["? 1 2\n\n? 1 3\n\n? 1 4\n\n! 3"]
NoteIn the first example, the graph could look like this The lengths of the simple paths between all pairs of vertices in this case are $$$1$$$ or $$$2$$$. The first query finds out that one of the simple paths from vertex $$$1$$$ to vertex $$$2$$$ has a length of $$$1$$$. With the second query, we find out that one of the simple paths from vertex $$$1$$$ to vertex $$$3$$$ has length $$$2$$$. In the third query, we find out that vertex $$$4$$$ is not in the graph. Consequently, the size of the graph is $$$3$$$.
Java 11
standard input
[ "interactive", "probabilities" ]
8590f40e7509614694486165ee824587
null
1,800
null
standard output
PASSED
af43548943d75ae1f563390e33f0a3bc
train_110.jsonl
1662993300
This is an interactive problem.I want to play a game with you...We hid from you a cyclic graph of $$$n$$$ vertices ($$$3 \le n \le 10^{18}$$$). A cyclic graph is an undirected graph of $$$n$$$ vertices that form one cycle. Each vertex belongs to the cycle, i.e. the length of the cycle (the number of edges in it) is exactly $$$n$$$. The order of the vertices in the cycle is arbitrary.You can make queries in the following way: "? a b" where $$$1 \le a, b \le 10^{18}$$$ and $$$a \neq b$$$. In response to the query, the interactor outputs on a separate line the length of random of two paths from vertex $$$a$$$ to vertex $$$b$$$, or -1 if $$$\max(a, b) &gt; n$$$. The interactor chooses one of the two paths with equal probability. The length of the path —is the number of edges in it.You win if you guess the number of vertices in the hidden graph (number $$$n$$$) by making no more than $$$50$$$ queries.Note that the interactor is implemented in such a way that for any ordered pair $$$(a, b)$$$, it always returns the same value for query "? a b", no matter how many such queries. Note that the "? b a" query may be answered differently by the interactor.The vertices in the graph are randomly placed, and their positions are fixed in advance.Hacks are forbidden in this problem. The number of tests the jury has is $$$50$$$.
256 megabytes
import java.io.*; import java.math.*; import java.util.*; // @author : Dinosparton public class test { static class Pair{ long x; long y; Pair(long x,long y){ this.x = x; this.y = y; } } static class Compare { void compare(Pair arr[], int n) { // Comparator to sort the pair according to second element Arrays.sort(arr, new Comparator<Pair>() { @Override public int compare(Pair p1, Pair p2) { if(p1.x!=p2.x) { return (int)(p1.x - p2.x); } else { return (int)(p1.y - p2.y); } } }); // for (int i = 0; i < n; i++) { // System.out.print(arr[i].x + " " + arr[i].y + " "); // } // System.out.println(); } } static class Scanner { BufferedReader br; StringTokenizer st; public Scanner() { br = new BufferedReader( new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } public static void main(String args[]) throws Exception { Scanner sc = new Scanner(); StringBuilder res = new StringBuilder(); int tc = 1; while(tc-->0) { for(int i=2;i<27;i++) { System.out.println("? 1 "+i); System.out.flush(); long x = sc.nextLong(); System.out.println("? "+i+" 1"); System.out.flush(); long y = sc.nextLong(); if(x==-1 || y==-1) { System.out.println("! "+(i-1)); return; } if(x!=y) { System.out.println("! "+(x+y)); return; } } } // System.out.println(res); } }
Java
["1\n\n2\n\n-1"]
1 second
["? 1 2\n\n? 1 3\n\n? 1 4\n\n! 3"]
NoteIn the first example, the graph could look like this The lengths of the simple paths between all pairs of vertices in this case are $$$1$$$ or $$$2$$$. The first query finds out that one of the simple paths from vertex $$$1$$$ to vertex $$$2$$$ has a length of $$$1$$$. With the second query, we find out that one of the simple paths from vertex $$$1$$$ to vertex $$$3$$$ has length $$$2$$$. In the third query, we find out that vertex $$$4$$$ is not in the graph. Consequently, the size of the graph is $$$3$$$.
Java 11
standard input
[ "interactive", "probabilities" ]
8590f40e7509614694486165ee824587
null
1,800
null
standard output
PASSED
8f9b4d6a42ff0a15e5cfd4fe69ff5e03
train_110.jsonl
1662993300
This is an interactive problem.I want to play a game with you...We hid from you a cyclic graph of $$$n$$$ vertices ($$$3 \le n \le 10^{18}$$$). A cyclic graph is an undirected graph of $$$n$$$ vertices that form one cycle. Each vertex belongs to the cycle, i.e. the length of the cycle (the number of edges in it) is exactly $$$n$$$. The order of the vertices in the cycle is arbitrary.You can make queries in the following way: "? a b" where $$$1 \le a, b \le 10^{18}$$$ and $$$a \neq b$$$. In response to the query, the interactor outputs on a separate line the length of random of two paths from vertex $$$a$$$ to vertex $$$b$$$, or -1 if $$$\max(a, b) &gt; n$$$. The interactor chooses one of the two paths with equal probability. The length of the path —is the number of edges in it.You win if you guess the number of vertices in the hidden graph (number $$$n$$$) by making no more than $$$50$$$ queries.Note that the interactor is implemented in such a way that for any ordered pair $$$(a, b)$$$, it always returns the same value for query "? a b", no matter how many such queries. Note that the "? b a" query may be answered differently by the interactor.The vertices in the graph are randomly placed, and their positions are fixed in advance.Hacks are forbidden in this problem. The number of tests the jury has is $$$50$$$.
256 megabytes
import java.io.PrintWriter; import java.util.Scanner; public class E { public static void main(String[] args) { Scanner sc = new Scanner(System.in); PrintWriter pw = new PrintWriter(System.out); int first = 1; int second = 2; for (int i = 0; i < 25; i++) { pw.println("? " + first + " " + second); pw.flush(); long dist = sc.nextLong(); if (dist == -1) { pw.println("! " + (second - 1)); break; } pw.println("? " + second + " " + first); pw.flush(); long dist2 = sc.nextLong(); if (dist != dist2) { pw.println("! " + (dist + dist2)); break; } second++; } sc.close(); pw.close(); } }
Java
["1\n\n2\n\n-1"]
1 second
["? 1 2\n\n? 1 3\n\n? 1 4\n\n! 3"]
NoteIn the first example, the graph could look like this The lengths of the simple paths between all pairs of vertices in this case are $$$1$$$ or $$$2$$$. The first query finds out that one of the simple paths from vertex $$$1$$$ to vertex $$$2$$$ has a length of $$$1$$$. With the second query, we find out that one of the simple paths from vertex $$$1$$$ to vertex $$$3$$$ has length $$$2$$$. In the third query, we find out that vertex $$$4$$$ is not in the graph. Consequently, the size of the graph is $$$3$$$.
Java 11
standard input
[ "interactive", "probabilities" ]
8590f40e7509614694486165ee824587
null
1,800
null
standard output
PASSED
4720f64c833de41c50d619dbac5eff5f
train_110.jsonl
1662993300
This is an interactive problem.I want to play a game with you...We hid from you a cyclic graph of $$$n$$$ vertices ($$$3 \le n \le 10^{18}$$$). A cyclic graph is an undirected graph of $$$n$$$ vertices that form one cycle. Each vertex belongs to the cycle, i.e. the length of the cycle (the number of edges in it) is exactly $$$n$$$. The order of the vertices in the cycle is arbitrary.You can make queries in the following way: "? a b" where $$$1 \le a, b \le 10^{18}$$$ and $$$a \neq b$$$. In response to the query, the interactor outputs on a separate line the length of random of two paths from vertex $$$a$$$ to vertex $$$b$$$, or -1 if $$$\max(a, b) &gt; n$$$. The interactor chooses one of the two paths with equal probability. The length of the path —is the number of edges in it.You win if you guess the number of vertices in the hidden graph (number $$$n$$$) by making no more than $$$50$$$ queries.Note that the interactor is implemented in such a way that for any ordered pair $$$(a, b)$$$, it always returns the same value for query "? a b", no matter how many such queries. Note that the "? b a" query may be answered differently by the interactor.The vertices in the graph are randomly placed, and their positions are fixed in advance.Hacks are forbidden in this problem. The number of tests the jury has is $$$50$$$.
256 megabytes
//package com.rajan.codeforces.contests.contest820; import java.io.*; public class ProblemE { public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out)); boolean ansFound = false; long n = 3L; while (!ansFound) { writer.write(String.format("? %d %d\n", 1L, n)); writer.flush(); long input = Long.parseLong(reader.readLine()); if (input == -1) { writer.write("! " + (n - 1) + "\n"); writer.flush(); return; } writer.write(String.format("? %d %d\n", n, 1L)); writer.flush(); long input1 = Long.parseLong(reader.readLine()); if (input != input1) { writer.write("! " + (input + input1) + "\n"); writer.flush(); return; } else { n++; } } writer.write(String.format("! %d\n", 3)); writer.flush(); } }
Java
["1\n\n2\n\n-1"]
1 second
["? 1 2\n\n? 1 3\n\n? 1 4\n\n! 3"]
NoteIn the first example, the graph could look like this The lengths of the simple paths between all pairs of vertices in this case are $$$1$$$ or $$$2$$$. The first query finds out that one of the simple paths from vertex $$$1$$$ to vertex $$$2$$$ has a length of $$$1$$$. With the second query, we find out that one of the simple paths from vertex $$$1$$$ to vertex $$$3$$$ has length $$$2$$$. In the third query, we find out that vertex $$$4$$$ is not in the graph. Consequently, the size of the graph is $$$3$$$.
Java 11
standard input
[ "interactive", "probabilities" ]
8590f40e7509614694486165ee824587
null
1,800
null
standard output
PASSED
8578953f6833905dd291b85b23842907
train_110.jsonl
1662993300
This is an interactive problem.I want to play a game with you...We hid from you a cyclic graph of $$$n$$$ vertices ($$$3 \le n \le 10^{18}$$$). A cyclic graph is an undirected graph of $$$n$$$ vertices that form one cycle. Each vertex belongs to the cycle, i.e. the length of the cycle (the number of edges in it) is exactly $$$n$$$. The order of the vertices in the cycle is arbitrary.You can make queries in the following way: "? a b" where $$$1 \le a, b \le 10^{18}$$$ and $$$a \neq b$$$. In response to the query, the interactor outputs on a separate line the length of random of two paths from vertex $$$a$$$ to vertex $$$b$$$, or -1 if $$$\max(a, b) &gt; n$$$. The interactor chooses one of the two paths with equal probability. The length of the path —is the number of edges in it.You win if you guess the number of vertices in the hidden graph (number $$$n$$$) by making no more than $$$50$$$ queries.Note that the interactor is implemented in such a way that for any ordered pair $$$(a, b)$$$, it always returns the same value for query "? a b", no matter how many such queries. Note that the "? b a" query may be answered differently by the interactor.The vertices in the graph are randomly placed, and their positions are fixed in advance.Hacks are forbidden in this problem. The number of tests the jury has is $$$50$$$.
256 megabytes
import java.util.*; import java.io.*; public class Main { public static Scanner obj = new Scanner(System.in); public static PrintWriter out = new PrintWriter(System.out); public static void solve() { for(int i=1;;i++) { for(int j=1;j<i;j++) { System.out.println("? "+i+" "+j); System.out.flush(); long v1=obj.nextLong(); System.out.println("? "+j+" "+i); System.out.flush(); long v2=obj.nextLong(); if(v1==-1 || v2==-1) { System.out.println("! "+(i-1)); System.out.flush(); return; } else if(v1!=v2) { System.out.println("! "+(v1+v2)); System.out.flush(); return; } } } } public static void main(String[] args) { solve(); } }
Java
["1\n\n2\n\n-1"]
1 second
["? 1 2\n\n? 1 3\n\n? 1 4\n\n! 3"]
NoteIn the first example, the graph could look like this The lengths of the simple paths between all pairs of vertices in this case are $$$1$$$ or $$$2$$$. The first query finds out that one of the simple paths from vertex $$$1$$$ to vertex $$$2$$$ has a length of $$$1$$$. With the second query, we find out that one of the simple paths from vertex $$$1$$$ to vertex $$$3$$$ has length $$$2$$$. In the third query, we find out that vertex $$$4$$$ is not in the graph. Consequently, the size of the graph is $$$3$$$.
Java 11
standard input
[ "interactive", "probabilities" ]
8590f40e7509614694486165ee824587
null
1,800
null
standard output
PASSED
55521dc024372ea1b1cb0ec208b4413a
train_110.jsonl
1662993300
This is an interactive problem.I want to play a game with you...We hid from you a cyclic graph of $$$n$$$ vertices ($$$3 \le n \le 10^{18}$$$). A cyclic graph is an undirected graph of $$$n$$$ vertices that form one cycle. Each vertex belongs to the cycle, i.e. the length of the cycle (the number of edges in it) is exactly $$$n$$$. The order of the vertices in the cycle is arbitrary.You can make queries in the following way: "? a b" where $$$1 \le a, b \le 10^{18}$$$ and $$$a \neq b$$$. In response to the query, the interactor outputs on a separate line the length of random of two paths from vertex $$$a$$$ to vertex $$$b$$$, or -1 if $$$\max(a, b) &gt; n$$$. The interactor chooses one of the two paths with equal probability. The length of the path —is the number of edges in it.You win if you guess the number of vertices in the hidden graph (number $$$n$$$) by making no more than $$$50$$$ queries.Note that the interactor is implemented in such a way that for any ordered pair $$$(a, b)$$$, it always returns the same value for query "? a b", no matter how many such queries. Note that the "? b a" query may be answered differently by the interactor.The vertices in the graph are randomly placed, and their positions are fixed in advance.Hacks are forbidden in this problem. The number of tests the jury has is $$$50$$$.
256 megabytes
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.StreamTokenizer; import java.io.UnsupportedEncodingException; import java.math.BigInteger; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Deque; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.Map.Entry; import java.util.PriorityQueue; import java.util.Queue; import java.util.Random; import java.util.Scanner; import java.util.Stack; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.TreeSet; public class Main { public static void main(String[]args) throws IOException { new Main().run(); } File input=new File("D:\\test\\input.txt"); void run() throws IOException{ // new solve().setIO(input, System.out).run(); new solve().setIO(System.in,System.out).run(); } class solve extends ioTask{ // StreamTokenizer st = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in))); // int in() throws IOException { // st.nextToken(); // return (int)st.nval; // } // long inl() throws IOException { // st.nextToken(); // return (long)st.nval; // } // double ind()throws IOException { // st.nextToken(); // return st.nval; // } // String ins() throws IOException { // st.nextToken(); // return st.sval; // } int n,m,i,j,mx,k,tmp,u,v,w,t; long l,r; long q(long a,long b) throws IOException { out.println("? "+a+" "+b); out.flush(); return in.inl(); } void ans(long a) { out.println("! "+a); out.close(); } void run()throws IOException { long i=4; while(true){ l=q(1,i); if(l==-1) { ans(i-1); return; } r=q(i,1); if(l!=r) { ans(l+r); return; } i++; } // out.close(); } } class In{ private StringTokenizer in=new StringTokenizer(""); private InputStream is; private BufferedReader bf; public In(File file) throws IOException { is=new FileInputStream(file); init(); } public In(InputStream is) throws IOException { this.is=is; init(); } private void init() throws IOException { bf=new BufferedReader(new InputStreamReader(is)); } boolean hasNext() throws IOException { return in.hasMoreTokens()||bf.ready(); } String ins() throws IOException { while(!in.hasMoreTokens()) { in=new StringTokenizer(bf.readLine()); } return in.nextToken(); } int in() throws IOException { return Integer.parseInt(ins()); } long inl() throws IOException { return Long.parseLong(ins()); } double ind() throws IOException { return Double.parseDouble(ins()); } String line() throws IOException { return bf.readLine(); } } class Out{ PrintWriter out; private OutputStream os; private void init() { out=new PrintWriter(new BufferedWriter(new OutputStreamWriter(os))); } public Out(File file) throws IOException { os=new FileOutputStream(file); init(); } public Out(OutputStream os) throws IOException { this.os=os; init(); } } class graph{ int[]to,nxt,head; int[]w; int cnt; void init(int n) { cnt=2; for(int i=1;i<=n;i++) { head[i]=0; } } public graph(int n,int m) { to=new int[m+1]; nxt=new int[m+1]; head=new int[n+1]; w=new int[m+1]; cnt=2; } void add(int u,int v,int l) { to[cnt]=v; nxt[cnt]=head[u]; w[cnt]=l; head[u]=cnt++; } } abstract class ioTask{ In in; PrintWriter out; public ioTask setIO(File in,File out) throws IOException{ this.in=new In(in); this.out=new Out(out).out; return this; } public ioTask setIO(File in,OutputStream out) throws IOException{ this.in=new In(in); this.out=new Out(out).out; return this; } public ioTask setIO(InputStream in,OutputStream out) throws IOException{ this.in=new In(in); this.out=new Out(out).out; return this; } public ioTask setIO(InputStream in,File out) throws IOException{ this.in=new In(in); this.out=new Out(out).out; return this; } void run()throws IOException{ } } }
Java
["1\n\n2\n\n-1"]
1 second
["? 1 2\n\n? 1 3\n\n? 1 4\n\n! 3"]
NoteIn the first example, the graph could look like this The lengths of the simple paths between all pairs of vertices in this case are $$$1$$$ or $$$2$$$. The first query finds out that one of the simple paths from vertex $$$1$$$ to vertex $$$2$$$ has a length of $$$1$$$. With the second query, we find out that one of the simple paths from vertex $$$1$$$ to vertex $$$3$$$ has length $$$2$$$. In the third query, we find out that vertex $$$4$$$ is not in the graph. Consequently, the size of the graph is $$$3$$$.
Java 11
standard input
[ "interactive", "probabilities" ]
8590f40e7509614694486165ee824587
null
1,800
null
standard output
PASSED
b29c1a7c689d93aa504e5e5770f4ac91
train_110.jsonl
1662993300
This is an interactive problem.I want to play a game with you...We hid from you a cyclic graph of $$$n$$$ vertices ($$$3 \le n \le 10^{18}$$$). A cyclic graph is an undirected graph of $$$n$$$ vertices that form one cycle. Each vertex belongs to the cycle, i.e. the length of the cycle (the number of edges in it) is exactly $$$n$$$. The order of the vertices in the cycle is arbitrary.You can make queries in the following way: "? a b" where $$$1 \le a, b \le 10^{18}$$$ and $$$a \neq b$$$. In response to the query, the interactor outputs on a separate line the length of random of two paths from vertex $$$a$$$ to vertex $$$b$$$, or -1 if $$$\max(a, b) &gt; n$$$. The interactor chooses one of the two paths with equal probability. The length of the path —is the number of edges in it.You win if you guess the number of vertices in the hidden graph (number $$$n$$$) by making no more than $$$50$$$ queries.Note that the interactor is implemented in such a way that for any ordered pair $$$(a, b)$$$, it always returns the same value for query "? a b", no matter how many such queries. Note that the "? b a" query may be answered differently by the interactor.The vertices in the graph are randomly placed, and their positions are fixed in advance.Hacks are forbidden in this problem. The number of tests the jury has is $$$50$$$.
256 megabytes
import java.util.*; import java.io.*; import static java.lang.Math.*; public class Main { public static void main(String[] args) { new MainClass().execute(); } } class MainClass extends PrintWriter { MainClass() { super(System.out, true); } boolean cases = false; // Solution void solveIt(int testCaseNo) { for (int i = 1; i <= 7; ++i) { for (int j = i + 1; j <= 7; ++j) { System.out.println("? " + i + " " + j); System.out.flush(); long x = sc.nextLong(); System.out.println("? " + j + " " + i); System.out.flush(); long y = sc.nextLong(); if (x == -1) { System.out.println("! " + (max(i, j) - 1)); System.out.flush(); return; } if (x != y) { System.out.println("! " + (x + y)); System.out.flush(); return; } } } } void solve() { int caseNo = 1; if (cases) for (int T = sc.nextInt(); T > 1; T--, caseNo++) { solveIt(caseNo); } solveIt(caseNo); } void execute() { long S = System.currentTimeMillis(); is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes()); out = new PrintWriter(System.out); this.sc = new FastIO(); solve(); out.flush(); long G = System.currentTimeMillis(); sc.tr(G - S + "ms"); } class FastIO { private boolean endOfFile() { if (bufferLength == -1) return true; int lptr = ptrbuf; while (lptr < bufferLength) { // _|_ if (!isThisTheSpaceCharacter(inputBufffferBigBoi[lptr++])) return false; } try { is.mark(1000); while (true) { int b = is.read(); if (b == -1) { is.reset(); return true; } else if (!isThisTheSpaceCharacter(b)) { is.reset(); return false; } } } catch (IOException e) { return true; } } private byte[] inputBufffferBigBoi = new byte[1024]; int bufferLength = 0, ptrbuf = 0; private int justReadTheByte() { if (bufferLength == -1) throw new InputMismatchException(); if (ptrbuf >= bufferLength) { ptrbuf = 0; try { bufferLength = is.read(inputBufffferBigBoi); } catch (IOException e) { throw new InputMismatchException(); } if (bufferLength <= 0) return -1; } return inputBufffferBigBoi[ptrbuf++]; } private boolean isThisTheSpaceCharacter(int c) { return !(c >= 33 && c <= 126); } private int skipItBishhhhhhh() { int b; while ((b = justReadTheByte()) != -1 && isThisTheSpaceCharacter(b)); return b; } private double nextDouble() { return Double.parseDouble(next()); } private char nextChar() { return (char) skipItBishhhhhhh(); } private String next() { int b = skipItBishhhhhhh(); StringBuilder sb = new StringBuilder(); while (!(isThisTheSpaceCharacter(b))) { sb.appendCodePoint(b); b = justReadTheByte(); } return sb.toString(); } private char[] readCharArray(int n) { char[] buf = new char[n]; int b = skipItBishhhhhhh(), p = 0; while (p < n && !(isThisTheSpaceCharacter(b))) { buf[p++] = (char) b; b = justReadTheByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private char[][] readCharMatrix(int n, int m) { char[][] map = new char[n][]; for (int i = 0; i < n; i++) map[i] = readCharArray(m); return map; } private int[] readIntArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } private long[] readLongArray(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } private int nextInt() { int num = 0, b; boolean minus = false; while ((b = justReadTheByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if (b == '-') { minus = true; b = justReadTheByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = justReadTheByte(); } } private long nextLong() { long num = 0; int b; boolean minus = false; while ((b = justReadTheByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if (b == '-') { minus = true; b = justReadTheByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = justReadTheByte(); } } private void tr(Object... o) { if (INPUT.length() != 0) System.out.println(Arrays.deepToString(o)); } } InputStream is; PrintWriter out; String INPUT = ""; final int ima = Integer.MAX_VALUE, imi = Integer.MIN_VALUE; final long lma = Long.MAX_VALUE, lmi = Long.MIN_VALUE; final long mod = (long) 1e9 + 7; FastIO sc; } // And I wish you could sing along, But this song is a joke, and the melody I // wrote, wrong
Java
["1\n\n2\n\n-1"]
1 second
["? 1 2\n\n? 1 3\n\n? 1 4\n\n! 3"]
NoteIn the first example, the graph could look like this The lengths of the simple paths between all pairs of vertices in this case are $$$1$$$ or $$$2$$$. The first query finds out that one of the simple paths from vertex $$$1$$$ to vertex $$$2$$$ has a length of $$$1$$$. With the second query, we find out that one of the simple paths from vertex $$$1$$$ to vertex $$$3$$$ has length $$$2$$$. In the third query, we find out that vertex $$$4$$$ is not in the graph. Consequently, the size of the graph is $$$3$$$.
Java 11
standard input
[ "interactive", "probabilities" ]
8590f40e7509614694486165ee824587
null
1,800
null
standard output
PASSED
bfda9e6b1963c92e3173e416125d5e64
train_110.jsonl
1662993300
This is an interactive problem.I want to play a game with you...We hid from you a cyclic graph of $$$n$$$ vertices ($$$3 \le n \le 10^{18}$$$). A cyclic graph is an undirected graph of $$$n$$$ vertices that form one cycle. Each vertex belongs to the cycle, i.e. the length of the cycle (the number of edges in it) is exactly $$$n$$$. The order of the vertices in the cycle is arbitrary.You can make queries in the following way: "? a b" where $$$1 \le a, b \le 10^{18}$$$ and $$$a \neq b$$$. In response to the query, the interactor outputs on a separate line the length of random of two paths from vertex $$$a$$$ to vertex $$$b$$$, or -1 if $$$\max(a, b) &gt; n$$$. The interactor chooses one of the two paths with equal probability. The length of the path —is the number of edges in it.You win if you guess the number of vertices in the hidden graph (number $$$n$$$) by making no more than $$$50$$$ queries.Note that the interactor is implemented in such a way that for any ordered pair $$$(a, b)$$$, it always returns the same value for query "? a b", no matter how many such queries. Note that the "? b a" query may be answered differently by the interactor.The vertices in the graph are randomly placed, and their positions are fixed in advance.Hacks are forbidden in this problem. The number of tests the jury has is $$$50$$$.
256 megabytes
//package com.company; import java.io.*; import java.util.*; public class Main{ static final Random random = new Random(); static boolean[] primecheck; static ArrayList<Integer>[] adj; static int[] vis; static int[] parent; static int[] rank; static int[] fact; static int[] invFact; static int[] ft; static int mod = (int)1e9 + 7; public static void main(String[] args) throws IOException { // FileReader f = new FileReader("C:\\Users\\Downloads" + // "\\watering_well_chapter_2_input.txt"); OutputStream outputStream = System.out; FastReader in = new FastReader(); // Reader in = new Reader(); PrintWriter out = new PrintWriter(outputStream); // PROBLEM solver = new PROBLEM(); int t = 1; // t = in.ni(); for (int i = 0; i < t; i++) { // out.print("Case #" + (i+1) + ": "); // solver.solve(in, out); PROBLEM.solve(in, out); } out.close(); } static class PROBLEM { public static void solve(FastReader in, PrintWriter out) throws IOException { int cnt = 0, cur = 2; long pos = 0; while(cnt<50){ out.println("? 1 " + cur); out.flush(); long a = in.nl(); out.println("? " + cur + " 1"); out.flush(); long b = in.nl(); if(a == -1){ out.println("! " + (cur-1)); return; } if(a != b){ out.println("! " + (a+b)); return; }else{ pos = 2L*a; } cnt+=2; cur++; out.flush(); } out.println("! " + pos); out.flush(); } } static long ans = 0; static int[] w, b; static void dfs(int i, int p, char[] c){ vis[i] = 1; if(c[i] == 'B') b[i] = 1; else w[i] = 1; for(int j : adj[i]){ if(j == p) continue; if(vis[j] == 0){ dfs(j, i, c); w[i] += w[j]; b[i] += b[j]; } } if(w[i] == b[i]){ ans++; } } static int findLower(int[] a, int x){ int l = 0, r = a.length-1; while(l<=r){ int mid = l + (r-l)/2; if(a[mid]>=x) r = mid-1; else l = mid+1; } return l; } static int findHigher(int[] a, int x){ int l = 0, r = a.length-1; while(l<=r){ int mid = l + (r-l)/2; if(a[mid]<=x) l = mid+1; else r = mid-1; } return r; } static void graph(int n, int e, FastReader in) throws IOException { adj = new ArrayList[n+1]; vis = new int[n+1]; for (int i = 0; i < n + 1; i++){ adj[i] = new ArrayList<>(); } for (int i = 0; i < e; i++) { int a = in.ni(), b = in.ni(); adj[a].add(b); adj[b].add(a); } } static int[] dx = {0, 0, 1, -1, 0, 0}, dy = {1, -1, 0, 0, 0, 0}, dz = {0, 0, 0, 0, 1, -1}; static int lower_bound(int array[], int key) { int index = Arrays.binarySearch(array, key); // If key is not present in the array if (index < 0) { // Index specify the position of the key // when inserted in the sorted array // so the element currently present at // this position will be the lower bound return Math.abs(index) - 1; } // If key is present in the array // we move leftwards to find its first occurrence else { // Decrement the index to find the first // occurrence of the key // while (index > 0) { // // // If previous value is same // if (array[index - 1] == key) // index--; // // // Previous value is different which means // // current index is the first occurrence of // // the key // else // return index; // } return index; } } static int upper_bound(int arr[], int key) { int index = Arrays.binarySearch(arr, key); int n = arr.length; // If key is not present in the array if (index < 0) { // Index specify the position of the key // when inserted in the sorted array // so the element currently present at // this position will be the upper bound return Math.abs(index) - 1; } // If key is present in the array // we move rightwards to find next greater value else { // Increment the index until value is equal to // key // while (index < n) { // // // If current value is same // if (arr[index] == key) // index++; // // // Current value is different which means // // it is the greater than the key // else { // return index; // } // } return index; } } static int getKthElement(int k){ int l = 0, r = ft.length-1, el = Integer.MAX_VALUE; while(l <= r){ int mid = l+r>>1; if(sumFenwick(ft, mid) >= k){ el = Math.min(el, mid); r = mid-1; }else l = mid+1; } return el; } static int rangeFenwick(int[] ft, int i, int j){ return sumFenwick(ft, j) - sumFenwick(ft, i); } static int sumFenwick(int[] ft, int i){ int sum = 0; for(; i>0; i&=~(i&-i)) sum+=ft[i]; return sum; } static void addFenwick(int[] ft, int i, int x){ int n = ft.length; for(; i<n; i+=i&-i) ft[i] += x; } static void combi(){ fact = new int[200001]; fact[0] = 1; invFact = new int[200001]; invFact[0] = 1; for (int i = 1; i < fact.length; i++) { fact[i] = (int)(((long)fact[i-1]%mod * i%mod) % mod); invFact[i] = (int)fast_pow(fact[i], mod-2); } } static int nCk(int n, int k){ return (int)((long)fact[n] * invFact[k]%mod * invFact[n-k]%mod)%mod; } static String reverse(String s){ char[] ch = s.toCharArray(); for (int j = 0; j < ch.length / 2; j++) { char temp = ch[j]; ch[j] = ch[ch.length-j-1]; ch[ch.length-j-1] = temp; } return String.valueOf(ch); } static int[][] matrixMul(int[][] a, int[][] m){ if(a[0].length == m.length) { int[][] b = new int[a.length][m.length]; for (int i = 0; i < m.length; i++) { for (int j = 0; j < m.length; j++) { int sum = 0; for (int k = 0; k < m.length; k++) { sum += m[i][k] * m[k][j]; } b[i][j] = sum; } } return b; } return null; } // static void dfs(int i, int d){ // vis[i] = 1; // for(int j : adj[i]){ // if (vis[j] == 0) dfs(j, d+1); // } // } static int find(int u){ if(u == parent[u]) return u; return parent[u] = find(parent[u]); } static void union(int u, int v){ int a = find(u), b = find(v); if(a == b) return; if(rank[a] > rank[b]) parent[b] = a; else if(rank[a] < rank[b]) parent[a] = b; else{ parent[b] = a; rank[a]++; } } static void dsu(int n){ parent = new int[n]; rank = new int[n]; for (int i = 0; i < parent.length; i++) { parent[i] = i; rank[i] = 1; } } static boolean isPalindrome(char[] s){ boolean b = true; for (int i = 0; i < s.length / 2; i++) { if(s[i] != s[s.length-1-i]){ b = false; break; } } return b; } static void yn(boolean b, PrintWriter out){ if(b) out.println("YES"); else out.println("NO"); } static void pa(int[] a, PrintWriter out){ for (int j : a) out.print(j + " "); out.println(); } static void pa(long[] a, PrintWriter out){ for (long j : a) out.print(j + " "); out.println(); } public static void sortByColumn(int arr[][], int col) { // Using built-in sort function Arrays.sort Arrays.sort(arr, new Comparator<>() { @Override // Compare values according to columns public int compare(final int[] entry1, final int[] entry2) { // To sort in descending order revert // the '>' Operator if (entry1[col] > entry2[col]) return 1; else return -1; } }); // End of function call sort(). } static boolean isPoT(long n){ return ((n&(n-1)) == 0); } static long sigmaK(long k){ return (k*(k+1))/2; } static void swap(int[] a, int l, int r) { int temp = a[l]; a[l] = a[r]; a[r] = temp; } static int binarySearch(int[] a, int l, int r, int x){ if(r>=l){ int mid = l + (r-l)/2; if(a[mid] == x) return mid; if(a[mid] > x) return binarySearch(a, l, mid-1, x); else return binarySearch(a,mid+1, r, x); } return -1; } static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } static long lcm(long a, long b){ return (a / gcd(a, b)) * b; } static int ceil(int a, int b){ return (a+b-1)/b; } static long ceil(long a, long b){ return (a+b-1)/b; } static boolean isSquare(double a) { boolean isSq = false; double b = Math.sqrt(a); double c = Math.sqrt(a) - Math.floor(b); if (c == 0) isSq = true; return isSq; } static long fast_pow(long a, long b) { //Jeel bhai OP if(b == 0) return 1L; long val = fast_pow(a, b / 2); if(b % 2 == 0) return val * val % mod; else return val * val % mod * a % mod; } // 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){ // // int ans = Integer.compare(x, o.x); // if(o.x == x) ans = Integer.compare(y, o.y); // // return ans; // //// int ans = Integer.compare(y, o.y); //// if(o.y == y) ans = Integer.compare(x, o.x); //// //// return ans; // } // } static class Tuple implements Comparable<Tuple>{ int x, y, z; Tuple(int x, int y, int z){ this.x = x; this.y = y; this.z = z; } public int compareTo(Tuple o){ int ans = Integer.compare(x, o.x); if(o.x == x) ans = Integer.compare(y, o.y); return ans; } } public static class Pair<U extends Comparable<U>, V extends Comparable<V>, W extends Comparable<W>> implements Comparable<Pair<U, V, W>> { public U x; public V y; public W z; public Pair(U x, V y, W z) { this.x = x; this.y = y; this.z = z; } public int hashCode() { return (x == null ? 0 : x.hashCode() * 31) + (y == null ? 0 : y.hashCode()); } public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Pair<U, V, W> p = (Pair<U, V, W>) o; return (x == null ? p.x == null : x.equals(p.x)) && (y == null ? p.y == null : y.equals(p.y)); } public int compareToX(Pair<U, V, W> b) { int cmpU = x.compareTo(b.x); return cmpU != 0 ? cmpU : y.compareTo(b.y); } public int compareToY(Pair<U, V, W> b) { int cmpU = b.y.compareTo(y); // sorts acc. to y in desc. order........ return cmpU != 0 ? cmpU : x.compareTo(b.x); // y.compareTo(b.y) -> for ascending } public String toString() { return String.format("(%s, %s)", x.toString(), y.toString()); } @Override public int compareTo(Pair<U, V, W> o) { return 0; } } 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 nline(int n) throws IOException { byte[] buf = new byte[n+1]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') { if (cnt != 0) { break; } else { continue; } } buf[cnt++] = (byte)c; } return new String(buf, 0, cnt); } public int ni() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') { c = read(); } boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nl() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nd() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } public int[] ra(int size) throws IOException { int[] array = new int[size]; for (int i = 0; i < size; i++) array[i] = ni(); return array; } } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } public FastReader(FileReader f) { br = new BufferedReader(f); } 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()); } long nl() { return Long.parseLong(next()); } double nd() { return Double.parseDouble(next()); } char nc() { return next().charAt(0); } boolean nb() { return !(ni() == 0); } // boolean nextBoolean(){return Boolean.parseBoolean(next());} String nline() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } public int[] ra(int size) { int[] array = new int[size]; for (int i = 0; i < size; i++) array[i] = ni(); return array; } public long[] ral(int size) { long[] array = new long[size]; for (int i = 0; i < size; i++) array[i] = nl(); return array; } } 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); } public static void Sieve(int n) { Arrays.fill(primecheck, true); primecheck[0] = false; primecheck[1] = false; for (int i = 2; i * i < n + 1; i++) { if (primecheck[i]) { for (int j = i * 2; j < n + 1; j += i) { primecheck[j] = false; } } } } }
Java
["1\n\n2\n\n-1"]
1 second
["? 1 2\n\n? 1 3\n\n? 1 4\n\n! 3"]
NoteIn the first example, the graph could look like this The lengths of the simple paths between all pairs of vertices in this case are $$$1$$$ or $$$2$$$. The first query finds out that one of the simple paths from vertex $$$1$$$ to vertex $$$2$$$ has a length of $$$1$$$. With the second query, we find out that one of the simple paths from vertex $$$1$$$ to vertex $$$3$$$ has length $$$2$$$. In the third query, we find out that vertex $$$4$$$ is not in the graph. Consequently, the size of the graph is $$$3$$$.
Java 11
standard input
[ "interactive", "probabilities" ]
8590f40e7509614694486165ee824587
null
1,800
null
standard output
PASSED
5312d2c7cb315f5976679b359aeedb9b
train_110.jsonl
1662993300
This is an interactive problem.I want to play a game with you...We hid from you a cyclic graph of $$$n$$$ vertices ($$$3 \le n \le 10^{18}$$$). A cyclic graph is an undirected graph of $$$n$$$ vertices that form one cycle. Each vertex belongs to the cycle, i.e. the length of the cycle (the number of edges in it) is exactly $$$n$$$. The order of the vertices in the cycle is arbitrary.You can make queries in the following way: "? a b" where $$$1 \le a, b \le 10^{18}$$$ and $$$a \neq b$$$. In response to the query, the interactor outputs on a separate line the length of random of two paths from vertex $$$a$$$ to vertex $$$b$$$, or -1 if $$$\max(a, b) &gt; n$$$. The interactor chooses one of the two paths with equal probability. The length of the path —is the number of edges in it.You win if you guess the number of vertices in the hidden graph (number $$$n$$$) by making no more than $$$50$$$ queries.Note that the interactor is implemented in such a way that for any ordered pair $$$(a, b)$$$, it always returns the same value for query "? a b", no matter how many such queries. Note that the "? b a" query may be answered differently by the interactor.The vertices in the graph are randomly placed, and their positions are fixed in advance.Hacks are forbidden in this problem. The number of tests the jury has is $$$50$$$.
256 megabytes
//Some of the methods are copied from GeeksforGeeks Website import java.util.*; import java.lang.*; import java.io.*; @SuppressWarnings("unchecked") public class E_Guess_the_Cycle_Size { //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 = 1;//sc.nextInt(); for(int tt=1;tt<=t;tt++) { // long a=1,b=2; // Set<Long> set=new HashSet<>(); // long lim=50; // for(long i=1;i<=lim;i++) // { // out.println("? "+a+" "+b); // out.flush(); // long len=sc.nextLong(); // set.add(len); // if(set.size()==2) // break; // } // // long ans=0; // if(x!=-1 && y!=-1) // ans=x+y; // else // { // if(x!=-1) ans=2*x; // else ans=2*y; // } // out.println("! "+ans); // out.flush(); // System.exit(0); long a=0,b=0; String ans=""; long lim=7l; for(long x=1;x<=lim;x++) { boolean flag=false; for(long y=x+1;y<=lim;y++) { String outt="? "+x+" "+y; out.println(outt); out.flush(); long first=sc.nextLong(); Set<Long> set=new HashSet<>(); String out2="? "+y+" "+x; out.println(out2); out.flush(); long second=sc.nextLong(); // long x=-1,y=-1; // for(long e : set) // { // if(x==-1) // x=e; // else // y=e; // } if(first!=second) { flag=true; long res=first+second; ans="! "+res; flag=true; break; } else if(first==-1) { long res=Math.max(x,y); res--; ans="! "+res; flag=true; break; } } if(flag) break; } out.println(ans); out.flush();; } 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
["1\n\n2\n\n-1"]
1 second
["? 1 2\n\n? 1 3\n\n? 1 4\n\n! 3"]
NoteIn the first example, the graph could look like this The lengths of the simple paths between all pairs of vertices in this case are $$$1$$$ or $$$2$$$. The first query finds out that one of the simple paths from vertex $$$1$$$ to vertex $$$2$$$ has a length of $$$1$$$. With the second query, we find out that one of the simple paths from vertex $$$1$$$ to vertex $$$3$$$ has length $$$2$$$. In the third query, we find out that vertex $$$4$$$ is not in the graph. Consequently, the size of the graph is $$$3$$$.
Java 11
standard input
[ "interactive", "probabilities" ]
8590f40e7509614694486165ee824587
null
1,800
null
standard output
PASSED
e6f4e71c362556966ce0715052b98d56
train_110.jsonl
1662993300
This is an interactive problem.I want to play a game with you...We hid from you a cyclic graph of $$$n$$$ vertices ($$$3 \le n \le 10^{18}$$$). A cyclic graph is an undirected graph of $$$n$$$ vertices that form one cycle. Each vertex belongs to the cycle, i.e. the length of the cycle (the number of edges in it) is exactly $$$n$$$. The order of the vertices in the cycle is arbitrary.You can make queries in the following way: "? a b" where $$$1 \le a, b \le 10^{18}$$$ and $$$a \neq b$$$. In response to the query, the interactor outputs on a separate line the length of random of two paths from vertex $$$a$$$ to vertex $$$b$$$, or -1 if $$$\max(a, b) &gt; n$$$. The interactor chooses one of the two paths with equal probability. The length of the path —is the number of edges in it.You win if you guess the number of vertices in the hidden graph (number $$$n$$$) by making no more than $$$50$$$ queries.Note that the interactor is implemented in such a way that for any ordered pair $$$(a, b)$$$, it always returns the same value for query "? a b", no matter how many such queries. Note that the "? b a" query may be answered differently by the interactor.The vertices in the graph are randomly placed, and their positions are fixed in advance.Hacks are forbidden in this problem. The number of tests the jury has is $$$50$$$.
256 megabytes
import java.io.*; import java.util.*; public class C820P5 { public static void main(String[] args) { MyScanner sc = new MyScanner(); out = new PrintWriter(new BufferedOutputStream(System.out)); long min = -1; long count = 0; boolean tf = true; for (int i = 2; i < 50; i++) { if (tf) { for (int j = 1; j < i; j++) { System.out.println("? " + j + " " + i); System.out.flush(); long num1 = sc.nextLong(); System.out.println("? " + i + " " + j); System.out.flush(); long num2 = sc.nextLong(); if (num2 == -1) { min = Math.max(i, j) - 1; tf = false; break; } if (num1 != num2) { min = num1 + num2; tf = false; break; } count++; if (count == 50) { min = num2; tf = false; break; } } } else break; } end: out.println("! " + (min)); // Start writing your solution here. ------------------------------------- /* * int n = sc.nextInt(); // read input as integer long k = sc.nextLong(); // * read input as long double d = sc.nextDouble(); // read input as double String * str = sc.next(); // read input as String String s = sc.nextLine(); // read * whole line as String * * int result = 3*n; out.println(result); // print via PrintWriter */ // Stop writing your solution here. ------------------------------------- out.close(); } // -----------PrintWriter for faster output--------------------------------- public static PrintWriter out; // -----------MyScanner class for faster input---------- public static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } // -------------------------------------------------------- }
Java
["1\n\n2\n\n-1"]
1 second
["? 1 2\n\n? 1 3\n\n? 1 4\n\n! 3"]
NoteIn the first example, the graph could look like this The lengths of the simple paths between all pairs of vertices in this case are $$$1$$$ or $$$2$$$. The first query finds out that one of the simple paths from vertex $$$1$$$ to vertex $$$2$$$ has a length of $$$1$$$. With the second query, we find out that one of the simple paths from vertex $$$1$$$ to vertex $$$3$$$ has length $$$2$$$. In the third query, we find out that vertex $$$4$$$ is not in the graph. Consequently, the size of the graph is $$$3$$$.
Java 11
standard input
[ "interactive", "probabilities" ]
8590f40e7509614694486165ee824587
null
1,800
null
standard output
PASSED
f47f365ccc3131fac652aa70df994d5a
train_110.jsonl
1662993300
This is an interactive problem.I want to play a game with you...We hid from you a cyclic graph of $$$n$$$ vertices ($$$3 \le n \le 10^{18}$$$). A cyclic graph is an undirected graph of $$$n$$$ vertices that form one cycle. Each vertex belongs to the cycle, i.e. the length of the cycle (the number of edges in it) is exactly $$$n$$$. The order of the vertices in the cycle is arbitrary.You can make queries in the following way: "? a b" where $$$1 \le a, b \le 10^{18}$$$ and $$$a \neq b$$$. In response to the query, the interactor outputs on a separate line the length of random of two paths from vertex $$$a$$$ to vertex $$$b$$$, or -1 if $$$\max(a, b) &gt; n$$$. The interactor chooses one of the two paths with equal probability. The length of the path —is the number of edges in it.You win if you guess the number of vertices in the hidden graph (number $$$n$$$) by making no more than $$$50$$$ queries.Note that the interactor is implemented in such a way that for any ordered pair $$$(a, b)$$$, it always returns the same value for query "? a b", no matter how many such queries. Note that the "? b a" query may be answered differently by the interactor.The vertices in the graph are randomly placed, and their positions are fixed in advance.Hacks are forbidden in this problem. The number of tests the jury has is $$$50$$$.
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.ArrayDeque; 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) { StringTokenizer st = new StringTokenizer(input.readLine()); final int n = Integer.parseInt(st.nextToken()), m = Integer.parseInt(st.nextToken()); final int[][] es = readArray2DInt(m, m, input); final int f = Integer.parseInt(input.readLine()); final int[] fs = readArrayInt(f, input); final int k = Integer.parseInt(input.readLine()); final int[] ks = readArrayInt(k, input); out.println(calc(n, m, es, f, fs, k, ks)); Q--; }*/ final int m = 26; for (long i=2;i<=m;++i){ out.println("? 1 " + i); out.flush(); long v = Long.parseLong(input.readLine()); if (v==-1){ out.println("! " + (i-1)); break; }else { out.println("? " + i + " 1"); out.flush(); long v2 = Long.parseLong(input.readLine()); if (v != v2){ out.println("! " + (v + v2)); break; } } } out.close(); // close the output file } private static int calc(final int n, final int m, final int[][] es, final int f, final int[] fs, final int k, final int[] ks) { int[] dist = new int[n+1], passBy = new int[n+1]; Arrays.fill(dist, n+1); ArrayList<Integer>[] als = new ArrayList[n+1], ffs = new ArrayList[n+1], canRide = new ArrayList[f+1]; final boolean[][] path = new boolean[1<<k][n+1]; boolean[] noCar = new boolean[f+1], seen = new boolean[n+1]; for (int i=1;i<=n;++i){ als[i] = new ArrayList<>(); ffs[i] = new ArrayList<>(); } for (int i=1;i<=f;++i){ canRide[i] = new ArrayList<>(); } for (int[] e : es){ als[e[0]].add(e[1]); als[e[1]].add(e[0]); } for (int i=0;i<f;++i){ ffs[fs[i]].add(i+1); } for (int i=0;i<k;++i){ passBy[fs[ks[i]-1]] += 1 << i; noCar[ks[i]] = true; } ArrayDeque<Integer> ll = new ArrayDeque<>(); ll.add(1); seen[1] = true; dist[1] = 0; while (!ll.isEmpty()){ final int x = ll.poll(); if (passBy[x] > 0){ path[passBy[x]][x] = true; } for (int a : als[x]){ if (dist[a] >= dist[x]+1){ for (int i=1;i<path.length;++i){ if (path[i][x]){ path[passBy[a] | i][a] = true; } } if (!seen[a]){ dist[a] = dist[x] + 1; seen[a] = true; ll.add(a); } } } } for (int i=2;i<=n;++i){ for (int j=1;j<path.length;++j){ if (path[j][i]) { for (int a : ffs[i]) { canRide[a].add(j); } } } } Integer[][] dp = new Integer[1<<k][f+1]; Arrays.fill(dp[(1<<k)-1], 0); return todo(dp, 0, 1, canRide, noCar, k); } private static int todo(Integer[][] dp, int state, int idx, ArrayList<Integer>[] canRide, boolean[] noCar, final int k){ if (idx >= canRide.length){ int res = 0; for (int i=0;i<k;++i){ if ((state & (1<<i)) == 0){ res++; } } return res; } if (dp[state][idx] != null){ return dp[state][idx]; } if (noCar[idx] || canRide[idx].isEmpty()){ dp[state][idx] = todo(dp, state, idx+1, canRide, noCar, k); }else { for (int a : canRide[idx]){ int t = todo(dp, state|a, idx+1, canRide, noCar, k); if (dp[state][idx]==null || dp[state][idx]>t){ dp[state][idx] = t; } } } return dp[state][idx]; } private static void printArray(long[] ns, final PrintWriter out){ for (int i=0;i<ns.length;++i){ out.print(ns[i]); if (i+1<ns.length)out.print(" "); else out.println(); } } private static void printArrayInt(int[] ns, final PrintWriter out){ for (int i=0;i<ns.length;++i){ out.print(ns[i]); if (i+1<ns.length)out.print(" "); else out.println(); } } private static void printArrayVertical(long[] ns, final PrintWriter out){ for (long a : ns){ out.println(a); } } private static void printArrayVerticalInt(int[] ns, final PrintWriter out){ for (int a : ns){ out.println(a); } } private static void printArray2D(long[][] ns, final int len, final PrintWriter out){ int cnt = 0; for (long[] kk : ns){ cnt++; if (cnt > len)break; for (int i=0;i<kk.length;++i){ out.print(kk[i]); if (i+1<kk.length)out.print(" "); else out.println(); } } } private static void printArray2DInt(int[][] ns, final int len, final PrintWriter out){ int cnt = 0; for (int[] kk : ns){ cnt++; if (cnt > len)break; for (int i=0;i<kk.length;++i){ out.print(kk[i]); if (i+1<kk.length)out.print(" "); else out.println(); } } } private static long[] readArray(final int n, final BufferedReader input) throws IOException{ long[] ns = new long[n]; StringTokenizer st = new StringTokenizer(input.readLine()); for (int i=0;i<n;++i){ ns[i] = Long.parseLong(st.nextToken()); } return ns; } private static int[] readArrayInt(final int n, final BufferedReader input) throws IOException{ int[] ns = new int[n]; StringTokenizer st = new StringTokenizer(input.readLine()); for (int i=0;i<n;++i){ ns[i] = Integer.parseInt(st.nextToken()); } return ns; } private static long[] readArrayVertical(final int n, final BufferedReader input) throws IOException{ long[] ns = new long[n]; for (int i=0;i<n;++i){ ns[i] = Long.parseLong(input.readLine()); } return ns; } private static int[] readArrayVerticalInt(final int n, final BufferedReader input) throws IOException{ int[] ns = new int[n]; for (int i=0;i<n;++i){ ns[i] = Integer.parseInt(input.readLine()); } return ns; } private static long[][] readArray2D(final int n, final int len, final BufferedReader input) throws IOException{ long[][] ns = new long[len][]; for (int i=0;i<n;++i){ StringTokenizer st = new StringTokenizer(input.readLine()); ArrayList<Long> al = new ArrayList<>(); while (st.hasMoreTokens()){ al.add(Long.parseLong(st.nextToken())); } long[] kk = new long[al.size()]; for (int j=0;j<kk.length;++j){ kk[j] = al.get(j); } ns[i] = kk; } return ns; } private static int[][] readArray2DInt(final int n, final int len, final BufferedReader input) throws IOException{ int[][] ns = new int[len][]; for (int i=0;i<n;++i){ StringTokenizer st = new StringTokenizer(input.readLine()); ArrayList<Integer> al = new ArrayList<>(); while (st.hasMoreTokens()){ al.add(Integer.parseInt(st.nextToken())); } int[] kk = new int[al.size()]; for (int j=0;j<kk.length;++j){ kk[j] = al.get(j); } ns[i] = kk; } return ns; } 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
["1\n\n2\n\n-1"]
1 second
["? 1 2\n\n? 1 3\n\n? 1 4\n\n! 3"]
NoteIn the first example, the graph could look like this The lengths of the simple paths between all pairs of vertices in this case are $$$1$$$ or $$$2$$$. The first query finds out that one of the simple paths from vertex $$$1$$$ to vertex $$$2$$$ has a length of $$$1$$$. With the second query, we find out that one of the simple paths from vertex $$$1$$$ to vertex $$$3$$$ has length $$$2$$$. In the third query, we find out that vertex $$$4$$$ is not in the graph. Consequently, the size of the graph is $$$3$$$.
Java 11
standard input
[ "interactive", "probabilities" ]
8590f40e7509614694486165ee824587
null
1,800
null
standard output
PASSED
2bcaf1d1ab2f71e1e7d7ffd3af6da70d
train_110.jsonl
1662993300
This is an interactive problem.I want to play a game with you...We hid from you a cyclic graph of $$$n$$$ vertices ($$$3 \le n \le 10^{18}$$$). A cyclic graph is an undirected graph of $$$n$$$ vertices that form one cycle. Each vertex belongs to the cycle, i.e. the length of the cycle (the number of edges in it) is exactly $$$n$$$. The order of the vertices in the cycle is arbitrary.You can make queries in the following way: "? a b" where $$$1 \le a, b \le 10^{18}$$$ and $$$a \neq b$$$. In response to the query, the interactor outputs on a separate line the length of random of two paths from vertex $$$a$$$ to vertex $$$b$$$, or -1 if $$$\max(a, b) &gt; n$$$. The interactor chooses one of the two paths with equal probability. The length of the path —is the number of edges in it.You win if you guess the number of vertices in the hidden graph (number $$$n$$$) by making no more than $$$50$$$ queries.Note that the interactor is implemented in such a way that for any ordered pair $$$(a, b)$$$, it always returns the same value for query "? a b", no matter how many such queries. Note that the "? b a" query may be answered differently by the interactor.The vertices in the graph are randomly placed, and their positions are fixed in advance.Hacks are forbidden in this problem. The number of tests the jury has is $$$50$$$.
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.ArrayDeque; 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) { StringTokenizer st = new StringTokenizer(input.readLine()); final int n = Integer.parseInt(st.nextToken()), m = Integer.parseInt(st.nextToken()); final int[][] es = readArray2DInt(m, m, input); final int f = Integer.parseInt(input.readLine()); final int[] fs = readArrayInt(f, input); final int k = Integer.parseInt(input.readLine()); final int[] ks = readArrayInt(k, input); out.println(calc(n, m, es, f, fs, k, ks)); Q--; }*/ final long m = 26; for (long i=2;i<=m;++i){ out.println("? 1 " + i); out.flush(); long v = Long.parseLong(input.readLine()); if (v==-1){ out.println("! " + (i-1)); break; }else { out.println("? " + i + " 1"); out.flush(); long v2 = Long.parseLong(input.readLine()); if (v != v2){ out.println("! " + (v + v2)); break; } } } out.close(); // close the output file } private static int calc(final int n, final int m, final int[][] es, final int f, final int[] fs, final int k, final int[] ks) { int[] dist = new int[n+1], passBy = new int[n+1]; Arrays.fill(dist, n+1); ArrayList<Integer>[] als = new ArrayList[n+1], ffs = new ArrayList[n+1], canRide = new ArrayList[f+1]; final boolean[][] path = new boolean[1<<k][n+1]; boolean[] noCar = new boolean[f+1], seen = new boolean[n+1]; for (int i=1;i<=n;++i){ als[i] = new ArrayList<>(); ffs[i] = new ArrayList<>(); } for (int i=1;i<=f;++i){ canRide[i] = new ArrayList<>(); } for (int[] e : es){ als[e[0]].add(e[1]); als[e[1]].add(e[0]); } for (int i=0;i<f;++i){ ffs[fs[i]].add(i+1); } for (int i=0;i<k;++i){ passBy[fs[ks[i]-1]] += 1 << i; noCar[ks[i]] = true; } ArrayDeque<Integer> ll = new ArrayDeque<>(); ll.add(1); seen[1] = true; dist[1] = 0; while (!ll.isEmpty()){ final int x = ll.poll(); if (passBy[x] > 0){ path[passBy[x]][x] = true; } for (int a : als[x]){ if (dist[a] >= dist[x]+1){ for (int i=1;i<path.length;++i){ if (path[i][x]){ path[passBy[a] | i][a] = true; } } if (!seen[a]){ dist[a] = dist[x] + 1; seen[a] = true; ll.add(a); } } } } for (int i=2;i<=n;++i){ for (int j=1;j<path.length;++j){ if (path[j][i]) { for (int a : ffs[i]) { canRide[a].add(j); } } } } Integer[][] dp = new Integer[1<<k][f+1]; Arrays.fill(dp[(1<<k)-1], 0); return todo(dp, 0, 1, canRide, noCar, k); } private static int todo(Integer[][] dp, int state, int idx, ArrayList<Integer>[] canRide, boolean[] noCar, final int k){ if (idx >= canRide.length){ int res = 0; for (int i=0;i<k;++i){ if ((state & (1<<i)) == 0){ res++; } } return res; } if (dp[state][idx] != null){ return dp[state][idx]; } if (noCar[idx] || canRide[idx].isEmpty()){ dp[state][idx] = todo(dp, state, idx+1, canRide, noCar, k); }else { for (int a : canRide[idx]){ int t = todo(dp, state|a, idx+1, canRide, noCar, k); if (dp[state][idx]==null || dp[state][idx]>t){ dp[state][idx] = t; } } } return dp[state][idx]; } private static void printArray(long[] ns, final PrintWriter out){ for (int i=0;i<ns.length;++i){ out.print(ns[i]); if (i+1<ns.length)out.print(" "); else out.println(); } } private static void printArrayInt(int[] ns, final PrintWriter out){ for (int i=0;i<ns.length;++i){ out.print(ns[i]); if (i+1<ns.length)out.print(" "); else out.println(); } } private static void printArrayVertical(long[] ns, final PrintWriter out){ for (long a : ns){ out.println(a); } } private static void printArrayVerticalInt(int[] ns, final PrintWriter out){ for (int a : ns){ out.println(a); } } private static void printArray2D(long[][] ns, final int len, final PrintWriter out){ int cnt = 0; for (long[] kk : ns){ cnt++; if (cnt > len)break; for (int i=0;i<kk.length;++i){ out.print(kk[i]); if (i+1<kk.length)out.print(" "); else out.println(); } } } private static void printArray2DInt(int[][] ns, final int len, final PrintWriter out){ int cnt = 0; for (int[] kk : ns){ cnt++; if (cnt > len)break; for (int i=0;i<kk.length;++i){ out.print(kk[i]); if (i+1<kk.length)out.print(" "); else out.println(); } } } private static long[] readArray(final int n, final BufferedReader input) throws IOException{ long[] ns = new long[n]; StringTokenizer st = new StringTokenizer(input.readLine()); for (int i=0;i<n;++i){ ns[i] = Long.parseLong(st.nextToken()); } return ns; } private static int[] readArrayInt(final int n, final BufferedReader input) throws IOException{ int[] ns = new int[n]; StringTokenizer st = new StringTokenizer(input.readLine()); for (int i=0;i<n;++i){ ns[i] = Integer.parseInt(st.nextToken()); } return ns; } private static long[] readArrayVertical(final int n, final BufferedReader input) throws IOException{ long[] ns = new long[n]; for (int i=0;i<n;++i){ ns[i] = Long.parseLong(input.readLine()); } return ns; } private static int[] readArrayVerticalInt(final int n, final BufferedReader input) throws IOException{ int[] ns = new int[n]; for (int i=0;i<n;++i){ ns[i] = Integer.parseInt(input.readLine()); } return ns; } private static long[][] readArray2D(final int n, final int len, final BufferedReader input) throws IOException{ long[][] ns = new long[len][]; for (int i=0;i<n;++i){ StringTokenizer st = new StringTokenizer(input.readLine()); ArrayList<Long> al = new ArrayList<>(); while (st.hasMoreTokens()){ al.add(Long.parseLong(st.nextToken())); } long[] kk = new long[al.size()]; for (int j=0;j<kk.length;++j){ kk[j] = al.get(j); } ns[i] = kk; } return ns; } private static int[][] readArray2DInt(final int n, final int len, final BufferedReader input) throws IOException{ int[][] ns = new int[len][]; for (int i=0;i<n;++i){ StringTokenizer st = new StringTokenizer(input.readLine()); ArrayList<Integer> al = new ArrayList<>(); while (st.hasMoreTokens()){ al.add(Integer.parseInt(st.nextToken())); } int[] kk = new int[al.size()]; for (int j=0;j<kk.length;++j){ kk[j] = al.get(j); } ns[i] = kk; } return ns; } 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
["1\n\n2\n\n-1"]
1 second
["? 1 2\n\n? 1 3\n\n? 1 4\n\n! 3"]
NoteIn the first example, the graph could look like this The lengths of the simple paths between all pairs of vertices in this case are $$$1$$$ or $$$2$$$. The first query finds out that one of the simple paths from vertex $$$1$$$ to vertex $$$2$$$ has a length of $$$1$$$. With the second query, we find out that one of the simple paths from vertex $$$1$$$ to vertex $$$3$$$ has length $$$2$$$. In the third query, we find out that vertex $$$4$$$ is not in the graph. Consequently, the size of the graph is $$$3$$$.
Java 11
standard input
[ "interactive", "probabilities" ]
8590f40e7509614694486165ee824587
null
1,800
null
standard output
PASSED
fbde656591cd602a3a7fb5283084e5cf
train_110.jsonl
1662993300
This is an interactive problem.I want to play a game with you...We hid from you a cyclic graph of $$$n$$$ vertices ($$$3 \le n \le 10^{18}$$$). A cyclic graph is an undirected graph of $$$n$$$ vertices that form one cycle. Each vertex belongs to the cycle, i.e. the length of the cycle (the number of edges in it) is exactly $$$n$$$. The order of the vertices in the cycle is arbitrary.You can make queries in the following way: "? a b" where $$$1 \le a, b \le 10^{18}$$$ and $$$a \neq b$$$. In response to the query, the interactor outputs on a separate line the length of random of two paths from vertex $$$a$$$ to vertex $$$b$$$, or -1 if $$$\max(a, b) &gt; n$$$. The interactor chooses one of the two paths with equal probability. The length of the path —is the number of edges in it.You win if you guess the number of vertices in the hidden graph (number $$$n$$$) by making no more than $$$50$$$ queries.Note that the interactor is implemented in such a way that for any ordered pair $$$(a, b)$$$, it always returns the same value for query "? a b", no matter how many such queries. Note that the "? b a" query may be answered differently by the interactor.The vertices in the graph are randomly placed, and their positions are fixed in advance.Hacks are forbidden in this problem. The number of tests the jury has is $$$50$$$.
256 megabytes
import java.util.*; public class e { public static void main(String[] args) { Scanner in = new Scanner(System.in); long ans = 3; for (int i = 2; i <= 25; i++) { System.out.printf("? 1 %d\n", i); System.out.flush(); long a = in.nextLong(); System.out.printf("? %d 1\n", i); System.out.flush(); long b = in.nextLong(); if (a == -1) { ans = i - 1; break; } if (a != b) { ans = a + b; break; } } System.out.println("! " + ans); } }
Java
["1\n\n2\n\n-1"]
1 second
["? 1 2\n\n? 1 3\n\n? 1 4\n\n! 3"]
NoteIn the first example, the graph could look like this The lengths of the simple paths between all pairs of vertices in this case are $$$1$$$ or $$$2$$$. The first query finds out that one of the simple paths from vertex $$$1$$$ to vertex $$$2$$$ has a length of $$$1$$$. With the second query, we find out that one of the simple paths from vertex $$$1$$$ to vertex $$$3$$$ has length $$$2$$$. In the third query, we find out that vertex $$$4$$$ is not in the graph. Consequently, the size of the graph is $$$3$$$.
Java 11
standard input
[ "interactive", "probabilities" ]
8590f40e7509614694486165ee824587
null
1,800
null
standard output
PASSED
98dcb31d74f86beba0a06de1cf4eabaa
train_110.jsonl
1662993300
This is an interactive problem.I want to play a game with you...We hid from you a cyclic graph of $$$n$$$ vertices ($$$3 \le n \le 10^{18}$$$). A cyclic graph is an undirected graph of $$$n$$$ vertices that form one cycle. Each vertex belongs to the cycle, i.e. the length of the cycle (the number of edges in it) is exactly $$$n$$$. The order of the vertices in the cycle is arbitrary.You can make queries in the following way: "? a b" where $$$1 \le a, b \le 10^{18}$$$ and $$$a \neq b$$$. In response to the query, the interactor outputs on a separate line the length of random of two paths from vertex $$$a$$$ to vertex $$$b$$$, or -1 if $$$\max(a, b) &gt; n$$$. The interactor chooses one of the two paths with equal probability. The length of the path —is the number of edges in it.You win if you guess the number of vertices in the hidden graph (number $$$n$$$) by making no more than $$$50$$$ queries.Note that the interactor is implemented in such a way that for any ordered pair $$$(a, b)$$$, it always returns the same value for query "? a b", no matter how many such queries. Note that the "? b a" query may be answered differently by the interactor.The vertices in the graph are randomly placed, and their positions are fixed in advance.Hacks are forbidden in this problem. The number of tests the jury has is $$$50$$$.
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(); long ans = 0; for(int i =2;i<=27;i++){ System.out.println("? "+1+" "+i); System.out.flush(); long x = in.readLong(); System.out.println("? "+i+" "+1); System.out.flush(); long y = in.readLong(); if(x == -1){ ans = i-1; break; }else if(x != y){ans = x+y;break;} } System.out.println("! "+ans); } 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
["1\n\n2\n\n-1"]
1 second
["? 1 2\n\n? 1 3\n\n? 1 4\n\n! 3"]
NoteIn the first example, the graph could look like this The lengths of the simple paths between all pairs of vertices in this case are $$$1$$$ or $$$2$$$. The first query finds out that one of the simple paths from vertex $$$1$$$ to vertex $$$2$$$ has a length of $$$1$$$. With the second query, we find out that one of the simple paths from vertex $$$1$$$ to vertex $$$3$$$ has length $$$2$$$. In the third query, we find out that vertex $$$4$$$ is not in the graph. Consequently, the size of the graph is $$$3$$$.
Java 11
standard input
[ "interactive", "probabilities" ]
8590f40e7509614694486165ee824587
null
1,800
null
standard output
PASSED
55a4bf27596d758dc680219d7de15639
train_110.jsonl
1662993300
This is an interactive problem.I want to play a game with you...We hid from you a cyclic graph of $$$n$$$ vertices ($$$3 \le n \le 10^{18}$$$). A cyclic graph is an undirected graph of $$$n$$$ vertices that form one cycle. Each vertex belongs to the cycle, i.e. the length of the cycle (the number of edges in it) is exactly $$$n$$$. The order of the vertices in the cycle is arbitrary.You can make queries in the following way: "? a b" where $$$1 \le a, b \le 10^{18}$$$ and $$$a \neq b$$$. In response to the query, the interactor outputs on a separate line the length of random of two paths from vertex $$$a$$$ to vertex $$$b$$$, or -1 if $$$\max(a, b) &gt; n$$$. The interactor chooses one of the two paths with equal probability. The length of the path —is the number of edges in it.You win if you guess the number of vertices in the hidden graph (number $$$n$$$) by making no more than $$$50$$$ queries.Note that the interactor is implemented in such a way that for any ordered pair $$$(a, b)$$$, it always returns the same value for query "? a b", no matter how many such queries. Note that the "? b a" query may be answered differently by the interactor.The vertices in the graph are randomly placed, and their positions are fixed in advance.Hacks are forbidden in this problem. The number of tests the jury has is $$$50$$$.
256 megabytes
import java.util.Scanner; public class guess_cycle { public static void main(String[] args) { solve(); } public static void solve(){ Scanner sc = new Scanner(System.in); for(int i=2; i<27; i++){ System.out.println("? " + 1 + " " + i); long x = sc.nextLong(); System.out.println("? " + i + " " + 1); long y = sc.nextLong(); if(x == -1 || y == -1){ System.out.println("! " + (i-1)); return; } if(x != y){ System.out.println("! " + (x+y)); return; } } } }
Java
["1\n\n2\n\n-1"]
1 second
["? 1 2\n\n? 1 3\n\n? 1 4\n\n! 3"]
NoteIn the first example, the graph could look like this The lengths of the simple paths between all pairs of vertices in this case are $$$1$$$ or $$$2$$$. The first query finds out that one of the simple paths from vertex $$$1$$$ to vertex $$$2$$$ has a length of $$$1$$$. With the second query, we find out that one of the simple paths from vertex $$$1$$$ to vertex $$$3$$$ has length $$$2$$$. In the third query, we find out that vertex $$$4$$$ is not in the graph. Consequently, the size of the graph is $$$3$$$.
Java 11
standard input
[ "interactive", "probabilities" ]
8590f40e7509614694486165ee824587
null
1,800
null
standard output
PASSED
a586187803359bb94eabe71844069e63
train_110.jsonl
1662993300
This is an interactive problem.I want to play a game with you...We hid from you a cyclic graph of $$$n$$$ vertices ($$$3 \le n \le 10^{18}$$$). A cyclic graph is an undirected graph of $$$n$$$ vertices that form one cycle. Each vertex belongs to the cycle, i.e. the length of the cycle (the number of edges in it) is exactly $$$n$$$. The order of the vertices in the cycle is arbitrary.You can make queries in the following way: "? a b" where $$$1 \le a, b \le 10^{18}$$$ and $$$a \neq b$$$. In response to the query, the interactor outputs on a separate line the length of random of two paths from vertex $$$a$$$ to vertex $$$b$$$, or -1 if $$$\max(a, b) &gt; n$$$. The interactor chooses one of the two paths with equal probability. The length of the path —is the number of edges in it.You win if you guess the number of vertices in the hidden graph (number $$$n$$$) by making no more than $$$50$$$ queries.Note that the interactor is implemented in such a way that for any ordered pair $$$(a, b)$$$, it always returns the same value for query "? a b", no matter how many such queries. Note that the "? b a" query may be answered differently by the interactor.The vertices in the graph are randomly placed, and their positions are fixed in advance.Hacks are forbidden in this problem. The number of tests the jury has is $$$50$$$.
256 megabytes
import java.io.*; import java.util.*; import java.util.Map.Entry; import static java.lang.Math.*; /** * * * @author adnan **/ @SuppressWarnings("unchecked") public class CodeForces { final static String no = "NO"; final static String yes = "YES"; final static int maxV = Integer.MAX_VALUE; final static int minV = Integer.MIN_VALUE; final static int mod = (int) (1e9 + 7); static public PrintWriter pw = new PrintWriter(System.out); static public IO sc = new IO(); static Scanner fc = new Scanner(System.in); public static void main(String[] args) { solve(); pw.flush(); } ////////////////////////////////////////////////////////////////////////// private static void solve() { long lf = 3; long rg = (long)1e13; while(rg - lf > 1) { long mid = lf + (rg - lf)/2; long resp = ask(1, mid); if (resp == -1) { rg = mid; } else { lf = mid; long rresp = ask(mid, 1); if(rresp != resp) { System.out.println('!' +" "+(resp + rresp)); return; } } } if(ask(1, rg) == -1) rg--; System.out.println("! "+rg); } private static long ask(long a, long b) { System.out.println('?' + " " + a +" " + b); long reply = sc.nextLong(); return reply; } /////////////////////////////////////////////////////////////////////////// static void debug(int[] ar) { for (var x : ar) { pw.print(x + " "); } pw.println(); } static class Three { int x, y, z; public Three(int x, int y, int z) { this.x = x; this.y = y; this.z = z; } } static int floorPowerOf2(int n) { int p = (int) (Math.log(n) / Math.log(2)); return (int) Math.pow(2, p); } static int ceilPowerOf2(int n) { int p = (int) (Math.log(n) / Math.log(2)); return (int) Math.pow(2, p + 1); } static List<Integer> printDivisors(int n) { List<Integer> sl = new ArrayList<>(); for (int i = 1; i <= Math.sqrt(n); i++) { if (n % i == 0) { if (n / i == i) sl.add(i); else { sl.add(i); sl.add(n / i); } } } return sl; } static int max(int... val) { int res = Integer.MIN_VALUE; for (int i : val) { res = Math.max(i, res); } return res; } static class Pair { int x, y, z; Pair(int x, int y) { this.x = x; this.y = y; } Pair(int x, int y, int z) { this.x = x; this.y = y; this.z = z; } } static int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a); } static long gcd(long a, long b) { if (a == 0) return b; return gcd(b % a, a); } /* * lcm/gcd * * * * * * * */ static long lcm(long a, long b) { return (a / gcd(a, b)) * b; } static void sort(int[] arr) { Random rand = new Random(); int n = arr.length; for (int i = 0; i < n; i++) { int idx = rand.nextInt(n); if (idx == i) continue; arr[i] ^= arr[idx]; arr[idx] ^= arr[i]; arr[i] ^= arr[idx]; } Arrays.sort(arr); } static void sort(long[] arr) { Random rand = new Random(); int n = arr.length; for (int i = 0; i < n; i++) { int idx = rand.nextInt(n); if (idx == i) continue; arr[i] ^= arr[idx]; arr[idx] ^= arr[i]; arr[i] ^= arr[idx]; } Arrays.sort(arr); } static void sortDec(int[] arr) { Random rand = new Random(); int n = arr.length; for (int i = 0; i < n; i++) { int idx = rand.nextInt(n); if (idx == i) continue; arr[i] ^= arr[idx]; arr[idx] ^= arr[i]; arr[i] ^= arr[idx]; } Arrays.sort(arr); int l = 0; int r = n - 1; while (l < r) { arr[l] ^= arr[r]; arr[r] ^= arr[l]; arr[l] ^= arr[r]; l++; r--; } } static void sortDec(long[] arr) { Random rand = new Random(); int n = arr.length; for (int i = 0; i < n; i++) { int idx = rand.nextInt(n); if (idx == i) continue; arr[i] ^= arr[idx]; arr[idx] ^= arr[i]; arr[i] ^= arr[idx]; } Arrays.sort(arr); int l = 0; int r = n - 1; while (l < r) { arr[l] ^= arr[r]; arr[r] ^= arr[l]; arr[l] ^= arr[r]; l++; r--; } } static class IO { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } long nextLong() { return Long.parseLong(next()); } long[] longArray(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()); } } class SegmentTree { int[] tree; SegmentTree(int n) { tree = new int[n]; } void build(int[] arr, int node, int start, int end) { if (start == end) { tree[node] = arr[start]; } else { int mid = (start + end) / 2; build(arr, 2 * node + 1, start, mid); build(arr, 2 * node + 2, mid + 1, end); tree[node] = tree[2 * node + 1] + tree[2 * node + 2]; } } void update(int[] arr, int node, int index, int val, int start, int end) { if (start == end) { tree[node] += val; arr[start] += val; } else { int mid = (start + end) / 2; if (start <= index && index <= mid) { update(arr, 2 * node + 1, index, val, start, mid); } else { update(arr, 2 * node + 2, index, val, mid + 1, end); } tree[node] = tree[2 * node + 1] + tree[2 * node + 2]; } } int query(int node, int start, int end, int left, int right) { if (right < start || end < left) { return 0; } if (left <= start && end <= right) { return tree[node]; } int mid = (start + end) / 2; int p1 = query(2 * node + 1, start, mid, left, right); int p2 = query(2 * node + 2, mid + 1, end, left, right); return p1 + p2; } } }
Java
["1\n\n2\n\n-1"]
1 second
["? 1 2\n\n? 1 3\n\n? 1 4\n\n! 3"]
NoteIn the first example, the graph could look like this The lengths of the simple paths between all pairs of vertices in this case are $$$1$$$ or $$$2$$$. The first query finds out that one of the simple paths from vertex $$$1$$$ to vertex $$$2$$$ has a length of $$$1$$$. With the second query, we find out that one of the simple paths from vertex $$$1$$$ to vertex $$$3$$$ has length $$$2$$$. In the third query, we find out that vertex $$$4$$$ is not in the graph. Consequently, the size of the graph is $$$3$$$.
Java 11
standard input
[ "interactive", "probabilities" ]
8590f40e7509614694486165ee824587
null
1,800
null
standard output
PASSED
32cd888361ff69d4799e2712f6e23fc3
train_110.jsonl
1662993300
This is an interactive problem.I want to play a game with you...We hid from you a cyclic graph of $$$n$$$ vertices ($$$3 \le n \le 10^{18}$$$). A cyclic graph is an undirected graph of $$$n$$$ vertices that form one cycle. Each vertex belongs to the cycle, i.e. the length of the cycle (the number of edges in it) is exactly $$$n$$$. The order of the vertices in the cycle is arbitrary.You can make queries in the following way: "? a b" where $$$1 \le a, b \le 10^{18}$$$ and $$$a \neq b$$$. In response to the query, the interactor outputs on a separate line the length of random of two paths from vertex $$$a$$$ to vertex $$$b$$$, or -1 if $$$\max(a, b) &gt; n$$$. The interactor chooses one of the two paths with equal probability. The length of the path —is the number of edges in it.You win if you guess the number of vertices in the hidden graph (number $$$n$$$) by making no more than $$$50$$$ queries.Note that the interactor is implemented in such a way that for any ordered pair $$$(a, b)$$$, it always returns the same value for query "? a b", no matter how many such queries. Note that the "? b a" query may be answered differently by the interactor.The vertices in the graph are randomly placed, and their positions are fixed in advance.Hacks are forbidden in this problem. The number of tests the jury has is $$$50$$$.
256 megabytes
import java.util.Scanner; public class E { public static void main(String[] args) { Scanner sc = new Scanner(System.in); // long lef = 1, right = (long) 1e18; // long ans = 0; // while(lef<=right){ // long mid = lef+right>>1; // String que = "? "+1 + " "+ mid; // System.out.println(que); // System.out.flush(); // long n = sc.nextLong(); // if(n==-1){ // right = mid-1; // continue; // } // if(n>mid-1){ // ans = n+mid-1; // break; // } // if(lef==right){ // ans = lef; // break; // } // lef = mid; // } // System.out.println(ans); long min = -1; long count = 0; boolean tf = true; for (int i = 2; i < 50; i++) { if (tf) { for (int j = 1; j < i; j++) { System.out.println("? " + j + " " + i); System.out.flush(); long num1 = sc.nextLong(); System.out.println("? " + i + " " + j); System.out.flush(); long num2 = sc.nextLong(); if (num2 == -1) { min = Math.max(i, j) - 1; tf = false; break; } if (num1 != num2) { min = num1 + num2; tf = false; break; } count++; if (count == 50) { min = num2; tf = false; break; } } } else break; } System.out.println("! " + (min)); } }
Java
["1\n\n2\n\n-1"]
1 second
["? 1 2\n\n? 1 3\n\n? 1 4\n\n! 3"]
NoteIn the first example, the graph could look like this The lengths of the simple paths between all pairs of vertices in this case are $$$1$$$ or $$$2$$$. The first query finds out that one of the simple paths from vertex $$$1$$$ to vertex $$$2$$$ has a length of $$$1$$$. With the second query, we find out that one of the simple paths from vertex $$$1$$$ to vertex $$$3$$$ has length $$$2$$$. In the third query, we find out that vertex $$$4$$$ is not in the graph. Consequently, the size of the graph is $$$3$$$.
Java 11
standard input
[ "interactive", "probabilities" ]
8590f40e7509614694486165ee824587
null
1,800
null
standard output
PASSED
40a4d38df3d47c8a3ffe9f486c3523b9
train_110.jsonl
1662993300
This is an interactive problem.I want to play a game with you...We hid from you a cyclic graph of $$$n$$$ vertices ($$$3 \le n \le 10^{18}$$$). A cyclic graph is an undirected graph of $$$n$$$ vertices that form one cycle. Each vertex belongs to the cycle, i.e. the length of the cycle (the number of edges in it) is exactly $$$n$$$. The order of the vertices in the cycle is arbitrary.You can make queries in the following way: "? a b" where $$$1 \le a, b \le 10^{18}$$$ and $$$a \neq b$$$. In response to the query, the interactor outputs on a separate line the length of random of two paths from vertex $$$a$$$ to vertex $$$b$$$, or -1 if $$$\max(a, b) &gt; n$$$. The interactor chooses one of the two paths with equal probability. The length of the path —is the number of edges in it.You win if you guess the number of vertices in the hidden graph (number $$$n$$$) by making no more than $$$50$$$ queries.Note that the interactor is implemented in such a way that for any ordered pair $$$(a, b)$$$, it always returns the same value for query "? a b", no matter how many such queries. Note that the "? b a" query may be answered differently by the interactor.The vertices in the graph are randomly placed, and their positions are fixed in advance.Hacks are forbidden in this problem. The number of tests the jury has is $$$50$$$.
256 megabytes
//Utilities import java.io.*; import java.util.*; public class Main { public static void main(String[] args) throws IOException { long x, y; boolean found = false; for (int i = 1; i <= 25; i++) { System.out.println("? " + 1 + " " + (i+1)); System.out.flush(); x = in.lscan(); System.out.println("? " + (i+1) + " " + 1); System.out.flush(); y = in.lscan(); if (x == -1) { System.out.println("! " + i); System.out.flush(); found = true; break; } else { if (x != y) { System.out.println("! " + (x+y)); System.out.flush(); found = true; break; } } } if (!found) { System.out.println("Error"); } out.close(); } static INPUT in = new INPUT(System.in); static PrintWriter out = new PrintWriter(System.out); private static class INPUT { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar, numChars; public INPUT (InputStream stream) { this.stream = stream; } public INPUT (String file) throws IOException { this.stream = new FileInputStream (file); } public int cscan () throws IOException { if (curChar >= numChars) { curChar = 0; numChars = stream.read (buf); } if (numChars == -1) return numChars; return buf[curChar++]; } public int iscan () throws IOException { int c = cscan (), sgn = 1; while (space (c)) c = cscan (); if (c == '-') { sgn = -1; c = cscan (); } int res = 0; do { res = (res << 1) + (res << 3); res += c - '0'; c = cscan (); } while (!space (c)); return res * sgn; } public String sscan () throws IOException { int c = cscan (); while (space (c)) c = cscan (); StringBuilder res = new StringBuilder (); do { res.appendCodePoint (c); c = cscan (); } while (!space (c)); return res.toString (); } public double dscan () throws IOException { int c = cscan (), sgn = 1; while (space (c)) c = cscan (); if (c == '-') { sgn = -1; c = cscan (); } double res = 0; while (!space (c) && c != '.') { if (c == 'e' || c == 'E') return res * UTILITIES.fast_pow (10, iscan ()); res *= 10; res += c - '0'; c = cscan (); } if (c == '.') { c = cscan (); double m = 1; while (!space (c)) { if (c == 'e' || c == 'E') return res * UTILITIES.fast_pow (10, iscan ()); m /= 10; res += (c - '0') * m; c = cscan (); } } return res * sgn; } public long lscan () throws IOException { int c = cscan (), sgn = 1; while (space (c)) c = cscan (); if (c == '-') { sgn = -1; c = cscan (); } long res = 0; do { res = (res << 1) + (res << 3); res += c - '0'; c = cscan (); } while (!space (c)); return res * sgn; } public boolean space (int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } public static class UTILITIES { static final double EPS = 10e-6; public static void sort(int[] a, boolean increasing) { ArrayList<Integer> arr = new ArrayList<Integer>(); int n = a.length; for (int i = 0; i < n; i++) { arr.add(a[i]); } Collections.sort(arr); for (int i = 0; i < n; i++) { if (increasing) { a[i] = arr.get(i); } else { a[i] = arr.get(n-1-i); } } } public static void sort(long[] a, boolean increasing) { ArrayList<Long> arr = new ArrayList<Long>(); int n = a.length; for (int i = 0; i < n; i++) { arr.add(a[i]); } Collections.sort(arr); for (int i = 0; i < n; i++) { if (increasing) { a[i] = arr.get(i); } else { a[i] = arr.get(n-1-i); } } } public static void sort(double[] a, boolean increasing) { ArrayList<Double> arr = new ArrayList<Double>(); int n = a.length; for (int i = 0; i < n; i++) { arr.add(a[i]); } Collections.sort(arr); for (int i = 0; i < n; i++) { if (increasing) { a[i] = arr.get(i); } else { a[i] = arr.get(n-1-i); } } } public static int lower_bound (int[] arr, int x) { int low = 0, high = arr.length, mid = -1; while (low < high) { mid = (low + high) / 2; if (arr[mid] >= x) high = mid; else low = mid + 1; } return low; } public static int upper_bound (int[] arr, int x) { int low = 0, high = arr.length, mid = -1; while (low < high) { mid = (low + high) / 2; if (arr[mid] > x) high = mid; else low = mid + 1; } return low; } public static void updateMap(HashMap<Integer, Integer> map, int key, int v) { if (!map.containsKey(key)) { map.put(key, v); } else { map.put(key, map.get(key) + v); } if (map.get(key) == 0) { map.remove(key); } } public static long gcd (long a, long b) { return b == 0 ? a : gcd (b, a % b); } public static long lcm (long a, long b) { return a * b / gcd (a, b); } public static long fast_pow_mod (long b, long x, int mod) { if (x == 0) return 1; if (x == 1) return b; if (x % 2 == 0) return fast_pow_mod (b * b % mod, x / 2, mod) % mod; return b * fast_pow_mod (b * b % mod, x / 2, mod) % mod; } public static long fast_pow (long b, long x) { if (x == 0) return 1; if (x == 1) return b; if (x % 2 == 0) return fast_pow (b * b, x / 2); return b * fast_pow (b * b, x / 2); } public static long choose (long n, long k) { k = Math.min (k, n - k); long val = 1; for (int i = 0; i < k; ++i) val = val * (n - i) / (i + 1); return val; } public static long permute (int n, int k) { if (n < k) return 0; long val = 1; for (int i = 0; i < k; ++i) val = (val * (n - i)); return val; } // start of permutation and lower/upper bound template public static void nextPermutation(int[] nums) { //find first decreasing digit int mark = -1; for (int i = nums.length - 1; i > 0; i--) { if (nums[i] > nums[i - 1]) { mark = i - 1; break; } } if (mark == -1) { reverse(nums, 0, nums.length - 1); return; } int idx = nums.length-1; for (int i = nums.length-1; i >= mark+1; i--) { if (nums[i] > nums[mark]) { idx = i; break; } } swap(nums, mark, idx); reverse(nums, mark + 1, nums.length - 1); } public static void swap(int[] nums, int i, int j) { int t = nums[i]; nums[i] = nums[j]; nums[j] = t; } public static void reverse(int[] nums, int i, int j) { while (i < j) { swap(nums, i, j); i++; j--; } } static int lower_bound (int[] arr, int hi, int cmp) { int low = 0, high = hi, mid = -1; while (low < high) { mid = (low + high) / 2; if (arr[mid] >= cmp) high = mid; else low = mid + 1; } return low; } static int upper_bound (int[] arr, int hi, int cmp) { int low = 0, high = hi, mid = -1; while (low < high) { mid = (low + high) / 2; if (arr[mid] > cmp) high = mid; else low = mid + 1; } return low; } // end of permutation and lower/upper bound template } }
Java
["1\n\n2\n\n-1"]
1 second
["? 1 2\n\n? 1 3\n\n? 1 4\n\n! 3"]
NoteIn the first example, the graph could look like this The lengths of the simple paths between all pairs of vertices in this case are $$$1$$$ or $$$2$$$. The first query finds out that one of the simple paths from vertex $$$1$$$ to vertex $$$2$$$ has a length of $$$1$$$. With the second query, we find out that one of the simple paths from vertex $$$1$$$ to vertex $$$3$$$ has length $$$2$$$. In the third query, we find out that vertex $$$4$$$ is not in the graph. Consequently, the size of the graph is $$$3$$$.
Java 11
standard input
[ "interactive", "probabilities" ]
8590f40e7509614694486165ee824587
null
1,800
null
standard output
PASSED
3585f3d7c16e65ada97c72635cf421dd
train_110.jsonl
1662993300
This is an interactive problem.I want to play a game with you...We hid from you a cyclic graph of $$$n$$$ vertices ($$$3 \le n \le 10^{18}$$$). A cyclic graph is an undirected graph of $$$n$$$ vertices that form one cycle. Each vertex belongs to the cycle, i.e. the length of the cycle (the number of edges in it) is exactly $$$n$$$. The order of the vertices in the cycle is arbitrary.You can make queries in the following way: "? a b" where $$$1 \le a, b \le 10^{18}$$$ and $$$a \neq b$$$. In response to the query, the interactor outputs on a separate line the length of random of two paths from vertex $$$a$$$ to vertex $$$b$$$, or -1 if $$$\max(a, b) &gt; n$$$. The interactor chooses one of the two paths with equal probability. The length of the path —is the number of edges in it.You win if you guess the number of vertices in the hidden graph (number $$$n$$$) by making no more than $$$50$$$ queries.Note that the interactor is implemented in such a way that for any ordered pair $$$(a, b)$$$, it always returns the same value for query "? a b", no matter how many such queries. Note that the "? b a" query may be answered differently by the interactor.The vertices in the graph are randomly placed, and their positions are fixed in advance.Hacks are forbidden in this problem. The number of tests the jury has is $$$50$$$.
256 megabytes
import java.util.*; import java.io.*; public class Main { private static final void solve() throws IOException { ou.println("? 1 2").flush(); long x = nl(); ou.println("? 2 1").flush(); long xx = nl(); if (x != xx) { ou.print("! ").println(x + xx).flush(); return; } var rand = new Random(); for (int n = 3; n < 27; n++) { int top = rand.nextInt(n - 1) + 1; ou.print("? ").print(top).print(" ").print(n).newLine().flush(); long z1 = nl(); if (z1 == -1) { ou.print("! ").println(n - 1).flush(); return; } ou.print("? ").print(n).print(" ").print(top).newLine().flush(); long z2 = nl(); if (z1 != z2) { ou.print("! ").println(z1 + z2).flush(); return; } } ou.print("! ").println(x + x).flush(); } public static void main(String[] args) throws IOException { // for (int i = 0, t = ni(); i < t; i++) solve(); ou.flush(); } private static final int ni() throws IOException { return sc.nextInt(); } private static final int[] ni(int n) throws IOException { return sc.nextIntArray(n); } private static final long nl() throws IOException { return sc.nextLong(); } private static final long[] nl(int n) throws IOException { return sc.nextLongArray(n); } private static final String ns() throws IOException { return sc.next(); } private static final ContestInputStream sc = new ContestInputStream(); private static final ContestOutputStream ou = new ContestOutputStream(); } final class ContestInputStream extends FilterInputStream { protected final byte[] buf; protected int pos = 0; protected int lim = 0; private final char[] cbuf; public ContestInputStream() { super(System.in); this.buf = new byte[1 << 13]; this.cbuf = new char[1 << 20]; } boolean hasRemaining() throws IOException { if (pos < lim) return true; lim = in.read(buf); pos = 0; return lim > 0; } final int remaining() throws IOException { if (pos >= lim) { lim = in.read(buf); pos = 0; } return lim - pos; } @Override public final int available() throws IOException { if (pos < lim) return lim - pos + in.available(); return in.available(); } @Override public final long skip(long n) throws IOException { if (pos < lim) { int rem = lim - pos; if (n < rem) { pos += n; return n; } pos = lim; return rem; } return in.skip(n); } @Override public final int read() throws IOException { if (hasRemaining()) return buf[pos++]; return -1; } @Override public final int read(byte[] b, int off, int len) throws IOException { if (pos < lim) { int rem = Math.min(lim - pos, len); for (int i = 0; i < rem; i++) b[off + i] = buf[pos + i]; pos += rem; return rem; } return in.read(b, off, len); } public final char[] readToken() throws IOException { int cpos = 0; int rem; byte b; l: while ((rem = remaining()) > 0) { for (int i = 0; i < rem; i++) { b = buf[pos + i]; if (b <= 0x20) { pos += i + 1; cpos += i; if (b == 0x0d && hasRemaining() && buf[pos] == 0x0a) pos++; break l; } cbuf[cpos + i] = (char) b; } pos += rem; cpos += rem; } char[] arr = new char[cpos]; for (int i = 0; i < cpos; i++) arr[i] = cbuf[i]; return arr; } public final int readToken(char[] cbuf, int off) throws IOException { int cpos = off; int rem; byte b; l: while ((rem = remaining()) > 0) { for (int i = 0; i < rem; i++) { b = buf[pos + i]; if (b <= 0x20) { pos += i + 1; cpos += i; if (b == 0x0d && hasRemaining() && buf[pos] == 0x0a) pos++; break l; } cbuf[cpos + i] = (char) b; } pos += rem; cpos += rem; } return cpos - off; } public final int readToken(char[] cbuf) throws IOException { return readToken(cbuf, 0); } public final String next() throws IOException { int cpos = 0; int rem; byte b; l: while ((rem = remaining()) > 0) { for (int i = 0; i < rem; i++) { b = buf[pos + i]; if (b <= 0x20) { pos += i + 1; cpos += i; if (b == 0x0d && hasRemaining() && buf[pos] == 0x0a) pos++; break l; } cbuf[cpos + i] = (char) b; } pos += rem; cpos += rem; } return String.valueOf(cbuf, 0, cpos); } public final char[] nextCharArray() throws IOException { return readToken(); } public final int nextInt() throws IOException { if (!hasRemaining()) return 0; int value = 0; byte b = buf[pos++]; if (b == 0x2d) { while (hasRemaining() && (b = buf[pos++]) > 0x20) value = value * 10 - b + 0x30; } else { do { value = value * 10 + b - 0x30; } while (hasRemaining() && (b = buf[pos++]) > 0x20); } if (b == 0x0d && hasRemaining() && buf[pos] == 0x0a) pos++; return value; } public final long nextLong() throws IOException { if (!hasRemaining()) return 0L; long value = 0L; byte b = buf[pos++]; if (b == 0x2d) { while (hasRemaining() && (b = buf[pos++]) > 0x20) value = value * 10 - b + 0x30; } else { do { value = value * 10 + b - 0x30; } while (hasRemaining() && (b = buf[pos++]) > 0x20); } if (b == 0x0d && hasRemaining() && buf[pos] == 0x0a) pos++; return value; } public final float nextFloat() throws IOException { return Float.parseFloat(next()); } public final double nextDouble() throws IOException { return Double.parseDouble(next()); } public final boolean[] nextBooleanArray(char ok) throws IOException { char[] s = readToken(); int n = s.length; boolean[] t = new boolean[n]; for (int i = 0; i < n; i++) t[i] = s[i] == ok; return t; } public final boolean[][] nextBooleanMatrix(int h, int w, char ok) throws IOException { boolean[][] s = new boolean[h][]; for (int i = 0; i < h; i++) { char[] t = readToken(); int n = t.length; s[i] = new boolean[n]; for (int j = 0; j < n; j++) s[i][j] = t[j] == ok; } return s; } public final String[] nextStringArray(int len) throws IOException { String[] arr = new String[len]; for (int i = 0; i < len; i++) arr[i] = next(); return arr; } public final int[] nextIntArray(int len) throws IOException { int[] arr = new int[len]; for (int i = 0; i < len; i++) arr[i] = nextInt(); return arr; } public final int[] nextIntArray(int len, java.util.function.IntUnaryOperator map) throws IOException { int[] arr = new int[len]; for (int i = 0; i < len; i++) arr[i] = map.applyAsInt(nextInt()); return arr; } public final long[] nextLongArray(int len, java.util.function.LongUnaryOperator map) throws IOException { long[] arr = new long[len]; for (int i = 0; i < len; i++) arr[i] = map.applyAsLong(nextLong()); return arr; } public final int[][] nextIntMatrix(int h, int w) throws IOException { int[][] arr = new int[h][w]; for (int i = 0; i < h; i++) for (int j = 0; j < w; j++) arr[i][j] = nextInt(); return arr; } public final int[][] nextIntMatrix(int h, int w, java.util.function.IntUnaryOperator map) throws IOException { int[][] arr = new int[h][w]; for (int i = 0; i < h; i++) for (int j = 0; j < w; j++) arr[i][j] = map.applyAsInt(nextInt()); return arr; } public final long[] nextLongArray(int len) throws IOException { long[] arr = new long[len]; for (int i = 0; i < len; i++) arr[i] = nextLong(); return arr; } public final long[][] nextLongMatrix(int h, int w) throws IOException { long[][] arr = new long[h][w]; for (int i = 0; i < h; i++) for (int j = 0; j < w; j++) arr[i][j] = nextLong(); return arr; } public final float[] nextFloatArray(int len) throws IOException { float[] arr = new float[len]; for (int i = 0; i < len; i++) arr[i] = nextFloat(); return arr; } public final double[] nextDoubleArray(int len) throws IOException { double[] arr = new double[len]; for (int i = 0; i < len; i++) arr[i] = nextDouble(); return arr; } public final char[][] nextCharMatrix(int h, int w) throws IOException { char[][] arr = new char[h][]; for (int i = 0; i < h; i++) arr[i] = readToken(); return arr; } public final void nextThrow() throws IOException { next(); return; } public final void nextThrow(int n) throws IOException { for (int i = 0; i < n; i++) nextThrow(); return; } } final class ContestOutputStream extends FilterOutputStream implements Appendable { protected final byte[] buf; protected int pos = 0; public ContestOutputStream() { super(System.out); this.buf = new byte[1 << 13]; } @Override public void flush() throws IOException { out.write(buf, 0, pos); pos = 0; out.flush(); } void put(byte b) throws IOException { if (pos >= buf.length) flush(); buf[pos++] = b; } int remaining() throws IOException { if (pos >= buf.length) flush(); return buf.length - pos; } @Override public void write(int b) throws IOException { put((byte) b); } @Override public void write(byte[] b, int off, int len) throws IOException { int o = off; int l = len; while (l > 0) { int rem = Math.min(remaining(), l); for (int i = 0; i < rem; i++) buf[pos + i] = b[o + i]; pos += rem; o += rem; l -= rem; } } @Override public ContestOutputStream append(char c) throws IOException { put((byte) c); return this; } @Override public ContestOutputStream append(CharSequence csq, int start, int end) throws IOException { int off = start; int len = end - start; while (len > 0) { int rem = Math.min(remaining(), len); for (int i = 0; i < rem; i++) buf[pos + i] = (byte) csq.charAt(off + i); pos += rem; off += rem; len -= rem; } return this; } @Override public ContestOutputStream append(CharSequence csq) throws IOException { return append(csq, 0, csq.length()); } public ContestOutputStream append(char[] arr, int off, int len) throws IOException { int o = off; int l = len; while (l > 0) { int rem = Math.min(remaining(), l); for (int i = 0; i < rem; i++) buf[pos + i] = (byte) arr[o + i]; pos += rem; o += rem; l -= rem; } return this; } public ContestOutputStream print(char[] arr) throws IOException { return append(arr, 0, arr.length).newLine(); } public ContestOutputStream print(boolean value) throws IOException { if (value) return append("o"); return append("x"); } public ContestOutputStream println(boolean value) throws IOException { if (value) return append("o\n"); return append("x\n"); } public ContestOutputStream print(boolean[][] value) throws IOException { final int n = value.length, m = value[0].length; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) print(value[i][j]); newLine(); } return this; } public ContestOutputStream print(int value) throws IOException { return append(String.valueOf(value)); } public ContestOutputStream println(int value) throws IOException { return append(String.valueOf(value)).newLine(); } public ContestOutputStream print(long value) throws IOException { return append(String.valueOf(value)); } public ContestOutputStream println(long value) throws IOException { return append(String.valueOf(value)).newLine(); } public ContestOutputStream print(float value) throws IOException { return append(String.valueOf(value)); } public ContestOutputStream println(float value) throws IOException { return append(String.valueOf(value)).newLine(); } public ContestOutputStream print(double value) throws IOException { return append(String.valueOf(value)); } public ContestOutputStream println(double value) throws IOException { return append(String.valueOf(value)).newLine(); } public ContestOutputStream print(char value) throws IOException { return append(String.valueOf(value)); } public ContestOutputStream println(char value) throws IOException { return append(String.valueOf(value)).newLine(); } public ContestOutputStream print(String value) throws IOException { return append(String.valueOf(value)); } public ContestOutputStream println(String value) throws IOException { return append(String.valueOf(value)).newLine(); } public ContestOutputStream print(Object value) throws IOException { return append(String.valueOf(value)); } public ContestOutputStream println(Object value) throws IOException { return append(String.valueOf(value)).newLine(); } public ContestOutputStream printYN(boolean yes) throws IOException { if (yes) return println("Yes"); return println("No"); } public ContestOutputStream printAB(boolean yes) throws IOException { if (yes) return println("Alice"); return println("Bob"); } public ContestOutputStream print(CharSequence[] arr) throws IOException { if (arr.length > 0) { append(arr[0]); for (int i = 1; i < arr.length; i++) append('\u0020').append(arr[i]); } return this; } public ContestOutputStream print(int[] arr) throws IOException { if (arr.length > 0) { print(arr[0]); for (int i = 1; i < arr.length; i++) append('\u0020').print(arr[i]); } newLine(); return this; } public ContestOutputStream println(int[] arr) throws IOException { for (int i : arr) print(i).newLine(); return this; } public ContestOutputStream print(boolean[] arr) throws IOException { if (arr.length > 0) { print(arr[0]); for (int i = 1; i < arr.length; i++) append('\u0020').print(arr[i]); } newLine(); return this; } public ContestOutputStream print(long[] arr) throws IOException { if (arr.length > 0) { print(arr[0]); for (int i = 1; i < arr.length; i++) append('\u0020').print(arr[i]); } newLine(); return this; } public ContestOutputStream println(long[] arr) throws IOException { for (long i : arr) print(i).newLine(); return this; } public ContestOutputStream print(float[] arr) throws IOException { if (arr.length > 0) { print(arr[0]); for (int i = 1; i < arr.length; i++) append('\u0020').print(arr[i]); } return this; } public ContestOutputStream println(float[] arr) throws IOException { for (float i : arr) print(i).newLine(); return this; } public ContestOutputStream print(double[] arr) throws IOException { if (arr.length > 0) { print(arr[0]); for (int i = 1; i < arr.length; i++) append('\u0020').print(arr[i]); } return newLine(); } public ContestOutputStream println(double[] arr) throws IOException { for (double i : arr) print(i).newLine(); return this; } public ContestOutputStream print(Object[] arr) throws IOException { if (arr.length > 0) { print(arr[0]); for (int i = 1; i < arr.length; i++) append('\u0020').print(arr[i]); } return newLine(); } public ContestOutputStream print(java.util.ArrayList<?> arr) throws IOException { if (!arr.isEmpty()) { final int n = arr.size(); print(arr.get(0)); for (int i = 1; i < n; i++) print(" ").print(arr.get(i)); } return newLine(); } public ContestOutputStream println(java.util.ArrayList<?> arr) throws IOException { final int n = arr.size(); for (int i = 0; i < n; i++) println(arr.get(i)); return this; } public ContestOutputStream println(Object[] arr) throws IOException { for (Object i : arr) print(i).newLine(); return this; } public ContestOutputStream newLine() throws IOException { return append(System.lineSeparator()); } public ContestOutputStream endl() throws IOException { newLine().flush(); return this; } public ContestOutputStream print(int[][] arr) throws IOException { for (int[] i : arr) print(i); return this; } public ContestOutputStream print(long[][] arr) throws IOException { for (long[] i : arr) print(i); return this; } public ContestOutputStream print(char[][] arr) throws IOException { for (char[] i : arr) print(i); return this; } public ContestOutputStream print(Object[][] arr) throws IOException { for (Object[] i : arr) print(i); return this; } public ContestOutputStream println() throws IOException { return newLine(); } }
Java
["1\n\n2\n\n-1"]
1 second
["? 1 2\n\n? 1 3\n\n? 1 4\n\n! 3"]
NoteIn the first example, the graph could look like this The lengths of the simple paths between all pairs of vertices in this case are $$$1$$$ or $$$2$$$. The first query finds out that one of the simple paths from vertex $$$1$$$ to vertex $$$2$$$ has a length of $$$1$$$. With the second query, we find out that one of the simple paths from vertex $$$1$$$ to vertex $$$3$$$ has length $$$2$$$. In the third query, we find out that vertex $$$4$$$ is not in the graph. Consequently, the size of the graph is $$$3$$$.
Java 11
standard input
[ "interactive", "probabilities" ]
8590f40e7509614694486165ee824587
null
1,800
null
standard output
PASSED
7a659894f011fdcd4749d3742890a03c
train_110.jsonl
1662993300
This is an interactive problem.I want to play a game with you...We hid from you a cyclic graph of $$$n$$$ vertices ($$$3 \le n \le 10^{18}$$$). A cyclic graph is an undirected graph of $$$n$$$ vertices that form one cycle. Each vertex belongs to the cycle, i.e. the length of the cycle (the number of edges in it) is exactly $$$n$$$. The order of the vertices in the cycle is arbitrary.You can make queries in the following way: "? a b" where $$$1 \le a, b \le 10^{18}$$$ and $$$a \neq b$$$. In response to the query, the interactor outputs on a separate line the length of random of two paths from vertex $$$a$$$ to vertex $$$b$$$, or -1 if $$$\max(a, b) &gt; n$$$. The interactor chooses one of the two paths with equal probability. The length of the path —is the number of edges in it.You win if you guess the number of vertices in the hidden graph (number $$$n$$$) by making no more than $$$50$$$ queries.Note that the interactor is implemented in such a way that for any ordered pair $$$(a, b)$$$, it always returns the same value for query "? a b", no matter how many such queries. Note that the "? b a" query may be answered differently by the interactor.The vertices in the graph are randomly placed, and their positions are fixed in advance.Hacks are forbidden in this problem. The number of tests the jury has is $$$50$$$.
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); for (int i = 4; i <= 100; i++) { out.println("? "+1+" "+i); out.flush(); long x = sc.nextLong(); out.println("? "+i+" "+1); out.flush(); long y = sc.nextLong(); if (x == -1) { out.println("! "+(i - 1)); out.flush(); break; }else if(x != y) { out.println("! "+(x + y)); out.flush(); break; } } } 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; } } } //StringAlgorithm.methodで使う class StringAlgorithm { private static int[] saNaive(int[] s) { int n = s.length; Integer[] _sa = new Integer[n]; for (int i = 0; i < n; i++) { _sa[i] = i; } java.util.Arrays.sort(_sa, (l, r) -> { while (l < n && r < n) { if (s[l] != s[r]) return s[l] - s[r]; l++; r++; } return -(l - r); }); int[] sa = new int[n]; for (int i = 0; i < n; i++) { sa[i] = _sa[i]; } return sa; } private static int[] saDoubling(int[] s) { int n = s.length; Integer[] _sa = new Integer[n]; for (int i = 0; i < n; i++) { _sa[i] = i; } int[] rnk = s; int[] tmp = new int[n]; for (int k = 1; k < n; k *= 2) { final int _k = k; final int[] _rnk = rnk; java.util.Comparator<Integer> cmp = (x, y) -> { if (_rnk[x] != _rnk[y]) return _rnk[x] - _rnk[y]; int rx = x + _k < n ? _rnk[x + _k] : -1; int ry = y + _k < n ? _rnk[y + _k] : -1; return rx - ry; }; java.util.Arrays.sort(_sa, cmp); tmp[_sa[0]] = 0; for (int i = 1; i < n; i++) { tmp[_sa[i]] = tmp[_sa[i - 1]] + (cmp.compare(_sa[i - 1], _sa[i]) < 0 ? 1 : 0); } int[] buf = tmp; tmp = rnk; rnk = buf; } int[] sa = new int[n]; for (int i = 0; i < n; i++) { sa[i] = _sa[i]; } return sa; } private static final int THRESHOLD_NAIVE = 10; private static final int THRESHOLD_DOUBLING = 40; private static int[] sais(int[] s, int upper) { int n = s.length; if (n == 0) return new int[0]; if (n == 1) return new int[]{0}; if (n == 2) { if (s[0] < s[1]) { return new int[]{0, 1}; } else { return new int[]{1, 0}; } } if (n < THRESHOLD_NAIVE) { return saNaive(s); } if (n < THRESHOLD_DOUBLING) { return saDoubling(s); } int[] sa = new int[n]; boolean[] ls = new boolean[n]; for (int i = n - 2; i >= 0; i--) { ls[i] = s[i] == s[i + 1] ? ls[i + 1] : s[i] < s[i + 1]; } int[] sumL = new int[upper + 1]; int[] sumS = new int[upper + 1]; for (int i = 0; i < n; i++) { if (ls[i]) { sumL[s[i] + 1]++; } else { sumS[s[i]]++; } } for (int i = 0; i <= upper; i++) { sumS[i] += sumL[i]; if (i < upper) sumL[i + 1] += sumS[i]; } java.util.function.Consumer<int[]> induce = lms -> { java.util.Arrays.fill(sa, -1); int[] buf = new int[upper + 1]; System.arraycopy(sumS, 0, buf, 0, upper + 1); for (int d : lms) { if (d == n) continue; sa[buf[s[d]]++] = d; } System.arraycopy(sumL, 0, buf, 0, upper + 1); sa[buf[s[n - 1]]++] = n - 1; for (int i = 0; i < n; i++) { int v = sa[i]; if (v >= 1 && !ls[v - 1]) { sa[buf[s[v - 1]]++] = v - 1; } } System.arraycopy(sumL, 0, buf, 0, upper + 1); for (int i = n - 1; i >= 0; i--) { int v = sa[i]; if (v >= 1 && ls[v - 1]) { sa[--buf[s[v - 1] + 1]] = v - 1; } } }; int[] lmsMap = new int[n + 1]; java.util.Arrays.fill(lmsMap, -1); int m = 0; for (int i = 1; i < n; i++) { if (!ls[i - 1] && ls[i]) { lmsMap[i] = m++; } } int[] lms = new int[m]; { int p = 0; for (int i = 1; i < n; i++) { if (!ls[i - 1] && ls[i]) { lms[p++] = i; } } } induce.accept(lms); if (m > 0) { int[] sortedLms = new int[m]; { int p = 0; for (int v : sa) { if (lmsMap[v] != -1) { sortedLms[p++] = v; } } } int[] recS = new int[m]; int recUpper = 0; recS[lmsMap[sortedLms[0]]] = 0; for (int i = 1; i < m; i++) { int l = sortedLms[i - 1], r = sortedLms[i]; int endL = (lmsMap[l] + 1 < m) ? lms[lmsMap[l] + 1] : n; int endR = (lmsMap[r] + 1 < m) ? lms[lmsMap[r] + 1] : n; boolean same = true; if (endL - l != endR - r) { same = false; } else { while (l < endL && s[l] == s[r]) { l++; r++; } if (l == n || s[l] != s[r]) same = false; } if (!same) { recUpper++; } recS[lmsMap[sortedLms[i]]] = recUpper; } int[] recSA = sais(recS, recUpper); for (int i = 0; i < m; i++) { sortedLms[i] = lms[recSA[i]]; } induce.accept(sortedLms); } return sa; } public static int[] suffixArray(int[] s, int upper) { assert (0 <= upper); for (int d : s) { assert (0 <= d && d <= upper); } return sais(s, upper); } public static int[] suffixArray(int[] s) { int n = s.length; Integer[] idx = new Integer[n]; for (int i = 0; i < n; i++) { idx[i] = i; } java.util.Arrays.sort(idx, (l, r) -> s[l] - s[r]); int[] s2 = new int[n]; int now = 0; for (int i = 0; i < n; i++) { if (i > 0 && s[idx[i - 1]] != s[idx[i]]) { now++; } s2[idx[i]] = now; } return sais(s2, now); } public static int[] suffixArray(char[] s) { int n = s.length; int[] s2 = new int[n]; for (int i = 0; i < n; i++) { s2[i] = s[i]; } return sais(s2, 255); } public static int[] suffixArray(java.lang.String s) { return suffixArray(s.toCharArray()); } public static int[] lcpArray(int[] s, int[] sa) { int n = s.length; assert (n >= 1); int[] rnk = new int[n]; for (int i = 0; i < n; i++) { rnk[sa[i]] = i; } int[] lcp = new int[n - 1]; int h = 0; for (int i = 0; i < n; i++) { if (h > 0) h--; if (rnk[i] == 0) { continue; } int j = sa[rnk[i] - 1]; for (; j + h < n && i + h < n; h++) { if (s[j + h] != s[i + h]) break; } lcp[rnk[i] - 1] = h; } return lcp; } public static int[] lcpArray(char[] s, int[] sa) { int n = s.length; int[] s2 = new int[n]; for (int i = 0; i < n; i++) { s2[i] = s[i]; } return lcpArray(s2, sa); } public static int[] lcpArray(java.lang.String s, int[] sa) { return lcpArray(s.toCharArray(), sa); } public static int[] zAlgorithm(int[] s) { int n = s.length; if (n == 0) return new int[0]; int[] z = new int[n]; for (int i = 1, j = 0; i < n; i++) { int k = j + z[j] <= i ? 0 : Math.min(j + z[j] - i, z[i - j]); while (i + k < n && s[k] == s[i + k]) k++; z[i] = k; if (j + z[j] < i + z[i]) j = i; } z[0] = n; return z; } public static int[] zAlgorithm(char[] s) { int n = s.length; if (n == 0) return new int[0]; int[] z = new int[n]; for (int i = 1, j = 0; i < n; i++) { int k = j + z[j] <= i ? 0 : Math.min(j + z[j] - i, z[i - j]); while (i + k < n && s[k] == s[i + k]) k++; z[i] = k; if (j + z[j] < i + z[i]) j = i; } z[0] = n; return z; } public static int[] zAlgorithm(String s) { return zAlgorithm(s.toCharArray()); } }
Java
["1\n\n2\n\n-1"]
1 second
["? 1 2\n\n? 1 3\n\n? 1 4\n\n! 3"]
NoteIn the first example, the graph could look like this The lengths of the simple paths between all pairs of vertices in this case are $$$1$$$ or $$$2$$$. The first query finds out that one of the simple paths from vertex $$$1$$$ to vertex $$$2$$$ has a length of $$$1$$$. With the second query, we find out that one of the simple paths from vertex $$$1$$$ to vertex $$$3$$$ has length $$$2$$$. In the third query, we find out that vertex $$$4$$$ is not in the graph. Consequently, the size of the graph is $$$3$$$.
Java 11
standard input
[ "interactive", "probabilities" ]
8590f40e7509614694486165ee824587
null
1,800
null
standard output
PASSED
1f97caa6bb77d2550116adb8f8c448d4
train_110.jsonl
1662993300
This is an interactive problem.I want to play a game with you...We hid from you a cyclic graph of $$$n$$$ vertices ($$$3 \le n \le 10^{18}$$$). A cyclic graph is an undirected graph of $$$n$$$ vertices that form one cycle. Each vertex belongs to the cycle, i.e. the length of the cycle (the number of edges in it) is exactly $$$n$$$. The order of the vertices in the cycle is arbitrary.You can make queries in the following way: "? a b" where $$$1 \le a, b \le 10^{18}$$$ and $$$a \neq b$$$. In response to the query, the interactor outputs on a separate line the length of random of two paths from vertex $$$a$$$ to vertex $$$b$$$, or -1 if $$$\max(a, b) &gt; n$$$. The interactor chooses one of the two paths with equal probability. The length of the path —is the number of edges in it.You win if you guess the number of vertices in the hidden graph (number $$$n$$$) by making no more than $$$50$$$ queries.Note that the interactor is implemented in such a way that for any ordered pair $$$(a, b)$$$, it always returns the same value for query "? a b", no matter how many such queries. Note that the "? b a" query may be answered differently by the interactor.The vertices in the graph are randomly placed, and their positions are fixed in advance.Hacks are forbidden in this problem. The number of tests the jury has is $$$50$$$.
256 megabytes
import java.io.*; import java.util.*; /** * @author atulanand */ public class Solution { static class Result { BufferedReader br; public Result(BufferedReader br) throws IOException { this.br = br; long res = solve(); System.out.printf("! %d\n", res); } public long solve() throws IOException { for (int i = 2; i <= 26; i++) { long x = ask(1, i); long y = ask(i, 1); if (x == -1) { return (long) (i - 1); } if (x != y) { return x + y; } } assert(false); return 0L; } private long ask(int a, int b) throws IOException { System.out.printf("? %d %d\n", a, b); long x = Long.parseLong(br.readLine()); System.out.flush(); return x; } } public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); Result result = new Result(br); } public static char[] inputCharArrayW(BufferedReader br) throws IOException { String[] spec = inputString(br).split(""); char[] arr = new char[spec.length]; for (int i = 0; i < spec.length; i++) arr[i] = spec[i].toCharArray()[0]; return arr; } public static char[][] inputCharGrid(BufferedReader br, int rows) throws IOException { char[][] grid = new char[rows][]; for (int i = 0; i < grid.length; i++) { grid[i] = inputString(br).toCharArray(); } return grid; } public static int[][] inputIntGrid(BufferedReader br, int rows) throws IOException { int[][] grid = new int[rows][]; for (int i = 0; i < grid.length; i++) { grid[i] = inputIntArray(br); } return grid; } public static char[] inputCharArray(BufferedReader br) throws IOException { return inputString(br).toCharArray(); } public static String inputString(BufferedReader br) throws IOException { return br.readLine().trim(); } public static int inputInt(BufferedReader br) throws IOException { return Integer.parseInt(inputString(br)); } public static long inputLong(BufferedReader br) throws IOException { return Long.parseLong(inputString(br)); } public static int[] inputIntArray(BufferedReader br) throws IOException { String[] spec = inputString(br).split(" "); int[] arr = new int[spec.length]; for (int i = 0; i < spec.length; i++) arr[i] = Integer.parseInt(spec[i]); return arr; } public static int[] inputIntArrayW(BufferedReader br) throws IOException { String[] spec = inputString(br).split(""); int[] arr = new int[spec.length]; for (int i = 0; i < spec.length; i++) arr[i] = Integer.parseInt(spec[i]); return arr; } public static long[] inputLongArray(BufferedReader br) throws IOException { String[] spec = inputString(br).split(" "); long[] arr = new long[spec.length]; for (int i = 0; i < spec.length; i++) arr[i] = Long.parseLong(spec[i]); return arr; } private String stringify(char[] chs) { StringBuilder sb = new StringBuilder(); for (char ch : chs) { sb.append(ch); } return sb.toString(); } }
Java
["1\n\n2\n\n-1"]
1 second
["? 1 2\n\n? 1 3\n\n? 1 4\n\n! 3"]
NoteIn the first example, the graph could look like this The lengths of the simple paths between all pairs of vertices in this case are $$$1$$$ or $$$2$$$. The first query finds out that one of the simple paths from vertex $$$1$$$ to vertex $$$2$$$ has a length of $$$1$$$. With the second query, we find out that one of the simple paths from vertex $$$1$$$ to vertex $$$3$$$ has length $$$2$$$. In the third query, we find out that vertex $$$4$$$ is not in the graph. Consequently, the size of the graph is $$$3$$$.
Java 11
standard input
[ "interactive", "probabilities" ]
8590f40e7509614694486165ee824587
null
1,800
null
standard output
PASSED
03fc4dcc16b081800b5649b27ac7e69d
train_110.jsonl
1662993300
This is an interactive problem.I want to play a game with you...We hid from you a cyclic graph of $$$n$$$ vertices ($$$3 \le n \le 10^{18}$$$). A cyclic graph is an undirected graph of $$$n$$$ vertices that form one cycle. Each vertex belongs to the cycle, i.e. the length of the cycle (the number of edges in it) is exactly $$$n$$$. The order of the vertices in the cycle is arbitrary.You can make queries in the following way: "? a b" where $$$1 \le a, b \le 10^{18}$$$ and $$$a \neq b$$$. In response to the query, the interactor outputs on a separate line the length of random of two paths from vertex $$$a$$$ to vertex $$$b$$$, or -1 if $$$\max(a, b) &gt; n$$$. The interactor chooses one of the two paths with equal probability. The length of the path —is the number of edges in it.You win if you guess the number of vertices in the hidden graph (number $$$n$$$) by making no more than $$$50$$$ queries.Note that the interactor is implemented in such a way that for any ordered pair $$$(a, b)$$$, it always returns the same value for query "? a b", no matter how many such queries. Note that the "? b a" query may be answered differently by the interactor.The vertices in the graph are randomly placed, and their positions are fixed in advance.Hacks are forbidden in this problem. The number of tests the jury has is $$$50$$$.
256 megabytes
import java.util.*; public class Codeforces{ public static void main(String[] args) { Scanner cs = new Scanner(System.in); long result = 3; for(int i=1;i<=25;i++) { System.out.println("? "+i+" "+(i+1)); long val=cs.nextLong(); System.out.println("? "+(i+1)+" "+i); long val1=cs.nextLong(); if(val!=val1) { result=val+val1; break; } } System.out.println("! "+result); System.out.flush(); } }
Java
["1\n\n2\n\n-1"]
1 second
["? 1 2\n\n? 1 3\n\n? 1 4\n\n! 3"]
NoteIn the first example, the graph could look like this The lengths of the simple paths between all pairs of vertices in this case are $$$1$$$ or $$$2$$$. The first query finds out that one of the simple paths from vertex $$$1$$$ to vertex $$$2$$$ has a length of $$$1$$$. With the second query, we find out that one of the simple paths from vertex $$$1$$$ to vertex $$$3$$$ has length $$$2$$$. In the third query, we find out that vertex $$$4$$$ is not in the graph. Consequently, the size of the graph is $$$3$$$.
Java 11
standard input
[ "interactive", "probabilities" ]
8590f40e7509614694486165ee824587
null
1,800
null
standard output
PASSED
84f02f8cf7220b9c467258c66fb5a010
train_110.jsonl
1662993300
This is an interactive problem.I want to play a game with you...We hid from you a cyclic graph of $$$n$$$ vertices ($$$3 \le n \le 10^{18}$$$). A cyclic graph is an undirected graph of $$$n$$$ vertices that form one cycle. Each vertex belongs to the cycle, i.e. the length of the cycle (the number of edges in it) is exactly $$$n$$$. The order of the vertices in the cycle is arbitrary.You can make queries in the following way: "? a b" where $$$1 \le a, b \le 10^{18}$$$ and $$$a \neq b$$$. In response to the query, the interactor outputs on a separate line the length of random of two paths from vertex $$$a$$$ to vertex $$$b$$$, or -1 if $$$\max(a, b) &gt; n$$$. The interactor chooses one of the two paths with equal probability. The length of the path —is the number of edges in it.You win if you guess the number of vertices in the hidden graph (number $$$n$$$) by making no more than $$$50$$$ queries.Note that the interactor is implemented in such a way that for any ordered pair $$$(a, b)$$$, it always returns the same value for query "? a b", no matter how many such queries. Note that the "? b a" query may be answered differently by the interactor.The vertices in the graph are randomly placed, and their positions are fixed in advance.Hacks are forbidden in this problem. The number of tests the jury has is $$$50$$$.
256 megabytes
// LARGEST SQUARE // package com.company /* * @author :: Yuvraj Singh * CS UNDERGRAD AT IT GGV BILASPUR */ import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.*; import static java.lang.Math.*; import static java.lang.System.out; public class Main { // Solution here void solve() { int n = in.nextInt(); long[] x = longArr(n); long[] y = longArr(n); ArrayList<Long> diff = new ArrayList<>(); for(int i=0; i<n; i++){ diff.add(y[i] - x[i]); } Collections.sort(diff); int i=0, j=n-1; long ans = 0; if(diff.get(i) >= 0){ sb.append(1).append("\n"); return; } if(diff.get(j) <= 0){ sb.append(0).append("\n"); return; } while(i<j){ if(abs(diff.get(i)) <= diff.get(j)){ ans++; i++; j--; }else{ i++; } } sb.append(ans).append("\n"); } void start(){ sb= new StringBuffer(); int t= in.nextInt(); for(int i=1;i<=t;i++) { solve(); } out.print(sb); } // Starter Code static FastReader in; StringBuffer sb; public static void main(String[] args) { // new Main().run(); in = new FastReader(); long x,y; for(int i=1;i<=7;++i) for(int j=i+1;j<=7;++j) { out.println("? " + i + " " + j); x = in.nextLong(); out.println("? " + j + " " + i); y = in.nextLong(); if(x==-1) { out.println("! " + (max(i, j) - 1)); return; } if(x!=y) { out.println("! " + (x+y)); return; } } } void run(){ in= new FastReader(); start(); } long nCr(int n, int r) { if (r > n) return 0; long m = 1000000007; long[] inv = new long[r + 1]; inv[0] = 1; if(r+1>=2) inv[1] = 1; for (int i = 2; i <= r; i++) { inv[i] = m - (m / i) * inv[(int) (m % i)] % m; } long ans = 1; for (int i = 2; i <= r; i++) { ans = (int) (((ans % m) * (inv[i] % m)) % m); } for (int i = n; i >= (n - r + 1); i--) { ans = (int) (((ans % m) * (i % m)) % m); } return ans; } int lower_bound(ArrayList<Integer> a, int x) { // x is the target value or key int l=-1,r=a.size(); while(l+1<r) { int m=(l+r)>>>1; if(a.get(m)>=x) r=m; else l=m; } return r; } void bubbleSort(int[] arr){ int n= arr.length; for(int i=n-1; i>0; i--){ for(int j=0; j<i; j++){ if(arr[i] < arr[j]){ swap(arr, i, j); } } } } void swap(int[] arr, int i, int j){ int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } long numberOfWays(long n, long k) { // Base Cases if (n == 0) return 1; if (k == 0) return 1; if (n >= (int)Math.pow(2, k)) { int curr_val = (int)Math.pow(2, k); return numberOfWays(n - curr_val, k) + numberOfWays(n, k - 1); } else return numberOfWays(n, k - 1); } boolean palindrome(String s){ int i=0, j= s.length()-1; while(i<j){ if(s.charAt(i)!=s.charAt(j)) return false; i++; j--; } return true; } int call(int[] A, int N, int K) { int i = 0, j = 0, sum = 0; int maxLen = Integer.MIN_VALUE; while (j < N) { sum += A[j]; if (sum < K) { j++; } else if (sum == K) { maxLen = Math.max(maxLen, j-i+1); j++; } else if (sum > K) { while (sum > K) { sum -= A[i]; i++; } if(sum == K){ maxLen = Math.max(maxLen, j-i+1); } j++; } } return maxLen; } int largestNum(int n) { int num = 0; // Iterate through all possible values for (int i = 0; i <= 32; i++) { // Multiply the number by 2 i times int x = (1 << i); if ((x - 1) >= n) num = (1 << i) - 1; else break; } // Return the final result return num; } static boolean isPrime(int n) { // Corner case if (n <= 1) return false; // Check from 2 to n-1 for (int i = 2; i <= sqrt(n); i++) if (n % i == 0) return false; return true; } // Useful Functions // void swap(int[] arr, int i , int j) { // int tmp = arr[i]; // i = j; // j = tmp; // } int call(int i,int j, int[][] mat, int[][] dp){ int m= mat.length; int n= mat[0].length; if(i>=m || j>=n){ return Integer.MIN_VALUE; } if(i==m-1 && j==n-1){ return mat[i][j]; } if(dp[i][j] != -1){ return dp[i][j]; } return dp[i][j] = max(call(i+1, j, mat, dp), call(i, j+1, mat, dp)) + mat[i][j]; } int util(int i,int j, int[][] mat, int[][] dp){ int m= mat.length; int n= mat[0].length; if(i>=m || j>=n){ return Integer.MAX_VALUE; } if(i==m-1 && j==n-1){ return mat[i][j]; } if(dp[i][j] != -1){ return dp[i][j]; } return dp[i][j] = min(util(i+1, j, mat, dp), util(i, j+1, mat, dp)) + mat[i][j]; } long power(long x, long y, long p) { long res = 1; x = x % p; while (y > 0) { if (y % 2 == 1) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return res; } int lower_bound(long[] a, long x) { // x is the target value or key 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; } int upper_bound(ArrayList<Integer> arr, int key) { int i=0, j=arr.size()-1; if(j==-1){ return 0; } if (arr.get(j)<=key) return j+1; if(arr.get(i)>key) return i; while (i<j){ int mid= (i+j)/2; if(arr.get(mid)<=key){ i= mid+1; }else{ j=mid; } } return i; } void sort(long[] A){ int n = A.length; Random rnd = new Random(); for(int i=0; i<n; ++i){ long tmp = A[i]; int randomPos = i + rnd.nextInt(n-i); A[i] = A[randomPos]; A[randomPos] = tmp; } Arrays.sort(A); } int[] intArr(int n){ int[] res= new int[n]; for(int i=0;i<n;i++){ res[i]= in.nextInt(); } return res; } long[] longArr(int n){ long[] res= new long[n]; for(int i=0;i<n;i++){ res[i]= in.nextLong(); } return res; } // // sieve of eratosthenes code for precomputing whether numbers are prime or not up to MAX_VALUE long MAX= 100000000; int[] precomp; void sieve(){ long n= MAX; precomp = new int[(int) (n+1)]; boolean[] prime = new boolean[(int) (n+1)]; for(int i=0;i<=n;i++) prime[i] = true; for(long p = 2; p*p <=n; p++) { // If prime[p] is not changed, then it is a prime if(prime[(int) p]) { // Update all multiples of p for(long i = p*p; i <= n; i += p) prime[(int) i] = false; } } // Print all prime numbers for(long i = 2; i <= n; i++) { if(prime[(int) i]) precomp[(int) i]= 1; } } long REVERSE(long N) { // code here long rev=0; long org= N; while (N!=0){ long d= N%10; rev = rev*10 +d; N /= 10; } return rev; } long sumOfDigits(String n){ long sum= 0; for (char c: n.toCharArray()){ sum += Integer.parseInt(String.valueOf(c)); } return sum; } long[] revArray(long[] arr) { int n= arr.length; int i=0, j=n-1; while (i<j){ long temp= arr[i]; arr[i]= arr[j]; arr[j]= temp; i++; j--; } return arr; } long gcd(long a, long b){ if (b==0) return a; return gcd(b, a%b); } long lcm(long a,long b){ return (a*b)/gcd(a,b); } static class Pair implements Comparable<Pair>{ long first; long second; Pair(long x, long y){ this.first=x; this.second=y; } @Override public int compareTo(Pair o) { return 0; } } // static class Compare { // static void compare(ArrayList<Pair> arr, int n) { // arr.sort(new Comparator<Pair>() { // @Override // public int compare(Pair p1, Pair p2) { // return (int) (p2.first - p1.first); // } // }); // } // } 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 (Exception e){ e.printStackTrace(); } } return st.nextToken(); } int nextInt(){ return Integer.parseInt(next()); } long nextLong(){ return Long.parseLong(next()); } double nextDouble(){ return Double.parseDouble(next()); } float nextFloat(){ return Float.parseFloat(next()); } String nextLine(){ String str=""; try{ str=br.readLine(); }catch (Exception e){ e.printStackTrace(); } return str; } } }
Java
["1\n\n2\n\n-1"]
1 second
["? 1 2\n\n? 1 3\n\n? 1 4\n\n! 3"]
NoteIn the first example, the graph could look like this The lengths of the simple paths between all pairs of vertices in this case are $$$1$$$ or $$$2$$$. The first query finds out that one of the simple paths from vertex $$$1$$$ to vertex $$$2$$$ has a length of $$$1$$$. With the second query, we find out that one of the simple paths from vertex $$$1$$$ to vertex $$$3$$$ has length $$$2$$$. In the third query, we find out that vertex $$$4$$$ is not in the graph. Consequently, the size of the graph is $$$3$$$.
Java 11
standard input
[ "interactive", "probabilities" ]
8590f40e7509614694486165ee824587
null
1,800
null
standard output
PASSED
d0da11a75e163491bfacf2d85f893fd8
train_110.jsonl
1662993300
This is an interactive problem.I want to play a game with you...We hid from you a cyclic graph of $$$n$$$ vertices ($$$3 \le n \le 10^{18}$$$). A cyclic graph is an undirected graph of $$$n$$$ vertices that form one cycle. Each vertex belongs to the cycle, i.e. the length of the cycle (the number of edges in it) is exactly $$$n$$$. The order of the vertices in the cycle is arbitrary.You can make queries in the following way: "? a b" where $$$1 \le a, b \le 10^{18}$$$ and $$$a \neq b$$$. In response to the query, the interactor outputs on a separate line the length of random of two paths from vertex $$$a$$$ to vertex $$$b$$$, or -1 if $$$\max(a, b) &gt; n$$$. The interactor chooses one of the two paths with equal probability. The length of the path —is the number of edges in it.You win if you guess the number of vertices in the hidden graph (number $$$n$$$) by making no more than $$$50$$$ queries.Note that the interactor is implemented in such a way that for any ordered pair $$$(a, b)$$$, it always returns the same value for query "? a b", no matter how many such queries. Note that the "? b a" query may be answered differently by the interactor.The vertices in the graph are randomly placed, and their positions are fixed in advance.Hacks are forbidden in this problem. The number of tests the jury has is $$$50$$$.
256 megabytes
import java.io.*; import java.util.*; public class E{ public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st; PrintWriter pw = new PrintWriter(System.out); for(int i = 2; i < 27; i++){ pw.println("? 1 " + i); pw.flush(); st = new StringTokenizer(br.readLine()); long n = Long.parseLong(st.nextToken()); if(n == 0){ pw.println("! 0"); pw.flush(); break; } if(n == -1){ pw.println("! " + (i-1)); pw.flush(); break; } pw.println("? " + i + " 1"); pw.flush(); st = new StringTokenizer(br.readLine()); long m = Long.parseLong(st.nextToken()); if(n == 0){ pw.println("! 0"); pw.flush(); break; } if(n != m){ pw.println("! " + (n + m)); pw.flush(); break; } } } }
Java
["1\n\n2\n\n-1"]
1 second
["? 1 2\n\n? 1 3\n\n? 1 4\n\n! 3"]
NoteIn the first example, the graph could look like this The lengths of the simple paths between all pairs of vertices in this case are $$$1$$$ or $$$2$$$. The first query finds out that one of the simple paths from vertex $$$1$$$ to vertex $$$2$$$ has a length of $$$1$$$. With the second query, we find out that one of the simple paths from vertex $$$1$$$ to vertex $$$3$$$ has length $$$2$$$. In the third query, we find out that vertex $$$4$$$ is not in the graph. Consequently, the size of the graph is $$$3$$$.
Java 11
standard input
[ "interactive", "probabilities" ]
8590f40e7509614694486165ee824587
null
1,800
null
standard output
PASSED
b17065c02faaf53de27890e033d9fb12
train_110.jsonl
1662993300
This is an interactive problem.I want to play a game with you...We hid from you a cyclic graph of $$$n$$$ vertices ($$$3 \le n \le 10^{18}$$$). A cyclic graph is an undirected graph of $$$n$$$ vertices that form one cycle. Each vertex belongs to the cycle, i.e. the length of the cycle (the number of edges in it) is exactly $$$n$$$. The order of the vertices in the cycle is arbitrary.You can make queries in the following way: "? a b" where $$$1 \le a, b \le 10^{18}$$$ and $$$a \neq b$$$. In response to the query, the interactor outputs on a separate line the length of random of two paths from vertex $$$a$$$ to vertex $$$b$$$, or -1 if $$$\max(a, b) &gt; n$$$. The interactor chooses one of the two paths with equal probability. The length of the path —is the number of edges in it.You win if you guess the number of vertices in the hidden graph (number $$$n$$$) by making no more than $$$50$$$ queries.Note that the interactor is implemented in such a way that for any ordered pair $$$(a, b)$$$, it always returns the same value for query "? a b", no matter how many such queries. Note that the "? b a" query may be answered differently by the interactor.The vertices in the graph are randomly placed, and their positions are fixed in advance.Hacks are forbidden in this problem. The number of tests the jury has is $$$50$$$.
256 megabytes
import java.io.PrintWriter; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); PrintWriter pw = new PrintWriter(System.out); int first = 1; int second = 2; for (int i = 0; i < 25; i++) { pw.println("? " + first + " " + second); pw.flush(); long dist = sc.nextLong(); if (dist == -1) { pw.println("! " + (second - 1)); break; } pw.println("? " + second + " " + first); pw.flush(); long dist2 = sc.nextLong(); if (dist != dist2) { pw.println("! " + (dist + dist2)); break; } second++; } sc.close(); pw.close(); } }
Java
["1\n\n2\n\n-1"]
1 second
["? 1 2\n\n? 1 3\n\n? 1 4\n\n! 3"]
NoteIn the first example, the graph could look like this The lengths of the simple paths between all pairs of vertices in this case are $$$1$$$ or $$$2$$$. The first query finds out that one of the simple paths from vertex $$$1$$$ to vertex $$$2$$$ has a length of $$$1$$$. With the second query, we find out that one of the simple paths from vertex $$$1$$$ to vertex $$$3$$$ has length $$$2$$$. In the third query, we find out that vertex $$$4$$$ is not in the graph. Consequently, the size of the graph is $$$3$$$.
Java 11
standard input
[ "interactive", "probabilities" ]
8590f40e7509614694486165ee824587
null
1,800
null
standard output
PASSED
c34f9ab1e507e8a033fc7cede6c8ea9b
train_110.jsonl
1662993300
This is an interactive problem.I want to play a game with you...We hid from you a cyclic graph of $$$n$$$ vertices ($$$3 \le n \le 10^{18}$$$). A cyclic graph is an undirected graph of $$$n$$$ vertices that form one cycle. Each vertex belongs to the cycle, i.e. the length of the cycle (the number of edges in it) is exactly $$$n$$$. The order of the vertices in the cycle is arbitrary.You can make queries in the following way: "? a b" where $$$1 \le a, b \le 10^{18}$$$ and $$$a \neq b$$$. In response to the query, the interactor outputs on a separate line the length of random of two paths from vertex $$$a$$$ to vertex $$$b$$$, or -1 if $$$\max(a, b) &gt; n$$$. The interactor chooses one of the two paths with equal probability. The length of the path —is the number of edges in it.You win if you guess the number of vertices in the hidden graph (number $$$n$$$) by making no more than $$$50$$$ queries.Note that the interactor is implemented in such a way that for any ordered pair $$$(a, b)$$$, it always returns the same value for query "? a b", no matter how many such queries. Note that the "? b a" query may be answered differently by the interactor.The vertices in the graph are randomly placed, and their positions are fixed in advance.Hacks are forbidden in this problem. The number of tests the jury has is $$$50$$$.
256 megabytes
import java.util.*; import java.io.*; public class E1729 { static final int ALPHABET_SIZE = 26; static Reader s = new Reader(); public static void main(String[] args) throws IOException { long start = 1L , end = (long) (1e17) * 5L; long ans = 0L; for (int i=0;i<50;i+=2) { long val = query(i+1,i+2); if (val == -1) { val = query(i,i+1); if (val == -1) ans = i; else ans = i+1; break; } long val2 = query(i+2,i+1); if (val2 != val) { ans += val2+val; break; } } System.out.println("! " + ans); System.out.flush(); } private static long query(long start , long end) { System.out.println("? " + start + " " + end); System.out.flush(); return s.l(); } public static void shuffle(long[] arr) { int n = arr.length; Random rand = new Random(); for (int i = 0; i < n; i++) { long temp = arr[i]; int randomPos = i + rand.nextInt(n - i); arr[i] = arr[randomPos]; arr[randomPos] = temp; } } private static long phi(long n) { long result = n; for (long i = 2; i * i <= n; i++) { if (n % i == 0) { while (n % i == 0) n /= i; result -= result / i; } } if (n > 1) result -= result / n; return result; } private static int gcd(int a, int b) { if(b == 0) return a; return gcd(b,a%b); } public static long nCr(long[] fact, long[] inv, int n, int r, long mod) { if (n < r) return 0; return ((fact[n] * inv[n - r]) % mod * inv[r]) % mod; } private static void factorials(long[] fact, long[] inv, long mod, int n) { fact[0] = 1; inv[0] = 1; for (int i = 1; i <= n; ++i) { fact[i] = (fact[i - 1] * i) % mod; inv[i] = power(fact[i], mod - 2, mod); } } private static long power(long a, long n, long p) { long result = 1; while (n > 0) { if (n % 2 == 0) { a = (a * a) % p; n /= 2; } else { result = (result * a) % p; n--; } } return result; } private static long power(long a, long n) { long result = 1; while (n > 0) { if (n % 2 == 0) { a = (a * a); n /= 2; } else { result = (result * a); n--; } } return result; } private static long query(long[] tree, int in, int start, int end, int l, int r) { if (start >= l && r >= end) return tree[in]; if (end < l || start > r) return 0; int mid = (start + end) / 2; long x = query(tree, 2 * in, start, mid, l, r); long y = query(tree, 2 * in + 1, mid + 1, end, l, r); return x + y; } private static void update(int[] arr, long[] tree, int in, int start, int end, int idx, int val) { if (start == end) { tree[in] = val; arr[idx] = val; return; } int mid = (start + end) / 2; if (idx > mid) update(arr, tree, 2 * in + 1, mid + 1, end, idx, val); else update(arr, tree, 2 * in, start, mid, idx, val); tree[in] = tree[2 * in] + tree[2 * in + 1]; } private static void build(int[] arr, long[] tree, int in, int start, int end) { if (start == end) { tree[in] = arr[start]; return; } int mid = (start + end) / 2; build(arr, tree, 2 * in, start, mid); build(arr, tree, 2 * in + 1, mid + 1, end); tree[in] = (tree[2 * in + 1] + tree[2 * in]); } static class Reader { private InputStream mIs; private byte[] buf = new byte[1024]; private int curChar, numChars; public Reader() { this(System.in); } public Reader(InputStream is) { mIs = is; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = mIs.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public String s() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public long l() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int i() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public double d() throws IOException { return Double.parseDouble(s()); } public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } public int[] arr(int n) { int[] ret = new int[n]; for (int i = 0; i < n; i++) { ret[i] = i(); } return ret; } public long[] arrLong(int n) { long[] ret = new long[n]; for (int i = 0; i < n; i++) { ret[i] = l(); } return ret; } } static class TrieNode { TrieNode[] children = new TrieNode[ALPHABET_SIZE]; boolean isLeaf; boolean isPalindrome; public TrieNode() { isLeaf = false; isPalindrome = false; for (int i = 0; i < ALPHABET_SIZE; i++) children[i] = null; } } }
Java
["1\n\n2\n\n-1"]
1 second
["? 1 2\n\n? 1 3\n\n? 1 4\n\n! 3"]
NoteIn the first example, the graph could look like this The lengths of the simple paths between all pairs of vertices in this case are $$$1$$$ or $$$2$$$. The first query finds out that one of the simple paths from vertex $$$1$$$ to vertex $$$2$$$ has a length of $$$1$$$. With the second query, we find out that one of the simple paths from vertex $$$1$$$ to vertex $$$3$$$ has length $$$2$$$. In the third query, we find out that vertex $$$4$$$ is not in the graph. Consequently, the size of the graph is $$$3$$$.
Java 11
standard input
[ "interactive", "probabilities" ]
8590f40e7509614694486165ee824587
null
1,800
null
standard output
PASSED
a1f878441872d60edfd33fcedb529574
train_110.jsonl
1662993300
This is an interactive problem.I want to play a game with you...We hid from you a cyclic graph of $$$n$$$ vertices ($$$3 \le n \le 10^{18}$$$). A cyclic graph is an undirected graph of $$$n$$$ vertices that form one cycle. Each vertex belongs to the cycle, i.e. the length of the cycle (the number of edges in it) is exactly $$$n$$$. The order of the vertices in the cycle is arbitrary.You can make queries in the following way: "? a b" where $$$1 \le a, b \le 10^{18}$$$ and $$$a \neq b$$$. In response to the query, the interactor outputs on a separate line the length of random of two paths from vertex $$$a$$$ to vertex $$$b$$$, or -1 if $$$\max(a, b) &gt; n$$$. The interactor chooses one of the two paths with equal probability. The length of the path —is the number of edges in it.You win if you guess the number of vertices in the hidden graph (number $$$n$$$) by making no more than $$$50$$$ queries.Note that the interactor is implemented in such a way that for any ordered pair $$$(a, b)$$$, it always returns the same value for query "? a b", no matter how many such queries. Note that the "? b a" query may be answered differently by the interactor.The vertices in the graph are randomly placed, and their positions are fixed in advance.Hacks are forbidden in this problem. The number of tests the jury has is $$$50$$$.
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.Collections; import java.util.Random; import java.util.Scanner; import java.util.StringTokenizer; import java.util.TreeSet; /* 12 23 31 */ public class E { public static void main(String[] args) { Scanner fs=new Scanner(System.in); for (int i=2; true; i++) { System.out.println("? 1 "+i); long a=fs.nextLong(); if (a==-1) { System.out.println("! "+(i-1)); return; } System.out.println("? "+i+" 1"); long b=fs.nextLong(); if (a!=b) { System.out.println("! "+(a+b)); return; } } } static final Random random=new Random(); static final int mod=1_000_000_007; static void ruffleSort(int[] a) { int n=a.length;//shuffle, then sort for (int i=0; i<n; i++) { int oi=random.nextInt(n), temp=a[oi]; a[oi]=a[i]; a[i]=temp; } Arrays.sort(a); } static long add(long a, long b) { return (a+b)%mod; } static long sub(long a, long b) { return ((a-b)%mod+mod)%mod; } static long mul(long a, long b) { return (a*b)%mod; } static long exp(long base, long exp) { if (exp==0) return 1; long half=exp(base, exp/2); if (exp%2==0) return mul(half, half); return mul(half, mul(half, base)); } static long[] factorials=new long[2_000_001]; static long[] invFactorials=new long[2_000_001]; static void precompFacts() { factorials[0]=invFactorials[0]=1; for (int i=1; i<factorials.length; i++) factorials[i]=mul(factorials[i-1], i); invFactorials[factorials.length-1]=exp(factorials[factorials.length-1], mod-2); for (int i=invFactorials.length-2; i>=0; i--) invFactorials[i]=mul(invFactorials[i+1], i+1); } static long nCk(int n, int k) { return mul(factorials[n], mul(invFactorials[k], invFactorials[n-k])); } static void sort(int[] a) { ArrayList<Integer> l=new ArrayList<>(); for (int i:a) l.add(i); Collections.sort(l); for (int i=0; i<a.length; i++) a[i]=l.get(i); } static class FastScanner { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readArray(int n) { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } long nextLong() { return Long.parseLong(next()); } } }
Java
["1\n\n2\n\n-1"]
1 second
["? 1 2\n\n? 1 3\n\n? 1 4\n\n! 3"]
NoteIn the first example, the graph could look like this The lengths of the simple paths between all pairs of vertices in this case are $$$1$$$ or $$$2$$$. The first query finds out that one of the simple paths from vertex $$$1$$$ to vertex $$$2$$$ has a length of $$$1$$$. With the second query, we find out that one of the simple paths from vertex $$$1$$$ to vertex $$$3$$$ has length $$$2$$$. In the third query, we find out that vertex $$$4$$$ is not in the graph. Consequently, the size of the graph is $$$3$$$.
Java 11
standard input
[ "interactive", "probabilities" ]
8590f40e7509614694486165ee824587
null
1,800
null
standard output
PASSED
e7c1a502bf1b7366b536d0e833508ebb
train_110.jsonl
1662993300
This is an interactive problem.I want to play a game with you...We hid from you a cyclic graph of $$$n$$$ vertices ($$$3 \le n \le 10^{18}$$$). A cyclic graph is an undirected graph of $$$n$$$ vertices that form one cycle. Each vertex belongs to the cycle, i.e. the length of the cycle (the number of edges in it) is exactly $$$n$$$. The order of the vertices in the cycle is arbitrary.You can make queries in the following way: "? a b" where $$$1 \le a, b \le 10^{18}$$$ and $$$a \neq b$$$. In response to the query, the interactor outputs on a separate line the length of random of two paths from vertex $$$a$$$ to vertex $$$b$$$, or -1 if $$$\max(a, b) &gt; n$$$. The interactor chooses one of the two paths with equal probability. The length of the path —is the number of edges in it.You win if you guess the number of vertices in the hidden graph (number $$$n$$$) by making no more than $$$50$$$ queries.Note that the interactor is implemented in such a way that for any ordered pair $$$(a, b)$$$, it always returns the same value for query "? a b", no matter how many such queries. Note that the "? b a" query may be answered differently by the interactor.The vertices in the graph are randomly placed, and their positions are fixed in advance.Hacks are forbidden in this problem. The number of tests the jury has is $$$50$$$.
256 megabytes
import java.util.*; public class gh{ public static void main(String[] args) { Scanner sc=new Scanner(System.in); long result=3; for(int i=1;i<=25;i++) { System.out.println("? "+i+" "+(i+1)); long val=sc.nextLong(); System.out.println("? "+(i+1)+" "+i); long val1=sc.nextLong(); if(val!=val1) { result=val+val1; break; } } System.out.println("! "+result); System.out.flush(); } }
Java
["1\n\n2\n\n-1"]
1 second
["? 1 2\n\n? 1 3\n\n? 1 4\n\n! 3"]
NoteIn the first example, the graph could look like this The lengths of the simple paths between all pairs of vertices in this case are $$$1$$$ or $$$2$$$. The first query finds out that one of the simple paths from vertex $$$1$$$ to vertex $$$2$$$ has a length of $$$1$$$. With the second query, we find out that one of the simple paths from vertex $$$1$$$ to vertex $$$3$$$ has length $$$2$$$. In the third query, we find out that vertex $$$4$$$ is not in the graph. Consequently, the size of the graph is $$$3$$$.
Java 11
standard input
[ "interactive", "probabilities" ]
8590f40e7509614694486165ee824587
null
1,800
null
standard output
PASSED
e636ae0d2d487b4bc226ae599d8e3f60
train_110.jsonl
1662993300
This is an interactive problem.I want to play a game with you...We hid from you a cyclic graph of $$$n$$$ vertices ($$$3 \le n \le 10^{18}$$$). A cyclic graph is an undirected graph of $$$n$$$ vertices that form one cycle. Each vertex belongs to the cycle, i.e. the length of the cycle (the number of edges in it) is exactly $$$n$$$. The order of the vertices in the cycle is arbitrary.You can make queries in the following way: "? a b" where $$$1 \le a, b \le 10^{18}$$$ and $$$a \neq b$$$. In response to the query, the interactor outputs on a separate line the length of random of two paths from vertex $$$a$$$ to vertex $$$b$$$, or -1 if $$$\max(a, b) &gt; n$$$. The interactor chooses one of the two paths with equal probability. The length of the path —is the number of edges in it.You win if you guess the number of vertices in the hidden graph (number $$$n$$$) by making no more than $$$50$$$ queries.Note that the interactor is implemented in such a way that for any ordered pair $$$(a, b)$$$, it always returns the same value for query "? a b", no matter how many such queries. Note that the "? b a" query may be answered differently by the interactor.The vertices in the graph are randomly placed, and their positions are fixed in advance.Hacks are forbidden in this problem. The number of tests the jury has is $$$50$$$.
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 = false; // 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 void solve(PrintWriter o) { try { for(int i=1;i<50;i++) { for(int j=1;j<i;j++) { o.println("? " + i + " " + j);o.flush(); long rs1 = fReader.nextLong(); o.println("? " + j + " " + i);o.flush(); long rs2 = fReader.nextLong(); if(rs1 == -1 || rs2 == -1) { o.println("! " + (i-1));o.flush(); return; } if(rs1 != rs2) { o.println("! " + (rs1+rs2));o.flush(); return; } } } } catch (Exception e) { e.printStackTrace(); } } 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 Node implements Comparable<Node> { Long fst; Integer snd; public Node(Long fst, Integer snd) { this.fst = fst; this.snd = snd; } @Override public int hashCode() { int prime = 31, res = 1; res = prime*res + fst.hashCode(); res = prime*res + snd.hashCode(); return res; } @Override public boolean equals(Object obj) { if(obj instanceof Node) { return fst.equals(((Node) obj).fst) && snd.equals(((Node) obj).snd); } return false; } @Override public int compareTo(Node node) { int result = Long.compare(fst, node.fst); return result == 0 ? Integer.compare(snd, node.snd) : result; } } 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
["1\n\n2\n\n-1"]
1 second
["? 1 2\n\n? 1 3\n\n? 1 4\n\n! 3"]
NoteIn the first example, the graph could look like this The lengths of the simple paths between all pairs of vertices in this case are $$$1$$$ or $$$2$$$. The first query finds out that one of the simple paths from vertex $$$1$$$ to vertex $$$2$$$ has a length of $$$1$$$. With the second query, we find out that one of the simple paths from vertex $$$1$$$ to vertex $$$3$$$ has length $$$2$$$. In the third query, we find out that vertex $$$4$$$ is not in the graph. Consequently, the size of the graph is $$$3$$$.
Java 11
standard input
[ "interactive", "probabilities" ]
8590f40e7509614694486165ee824587
null
1,800
null
standard output
PASSED
ff9899a7c86f540aedd7faea8568508c
train_110.jsonl
1662993300
This is an interactive problem.I want to play a game with you...We hid from you a cyclic graph of $$$n$$$ vertices ($$$3 \le n \le 10^{18}$$$). A cyclic graph is an undirected graph of $$$n$$$ vertices that form one cycle. Each vertex belongs to the cycle, i.e. the length of the cycle (the number of edges in it) is exactly $$$n$$$. The order of the vertices in the cycle is arbitrary.You can make queries in the following way: "? a b" where $$$1 \le a, b \le 10^{18}$$$ and $$$a \neq b$$$. In response to the query, the interactor outputs on a separate line the length of random of two paths from vertex $$$a$$$ to vertex $$$b$$$, or -1 if $$$\max(a, b) &gt; n$$$. The interactor chooses one of the two paths with equal probability. The length of the path —is the number of edges in it.You win if you guess the number of vertices in the hidden graph (number $$$n$$$) by making no more than $$$50$$$ queries.Note that the interactor is implemented in such a way that for any ordered pair $$$(a, b)$$$, it always returns the same value for query "? a b", no matter how many such queries. Note that the "? b a" query may be answered differently by the interactor.The vertices in the graph are randomly placed, and their positions are fixed in advance.Hacks are forbidden in this problem. The number of tests the jury has is $$$50$$$.
256 megabytes
import java.util.*; public class Main { public static void ask(int a, int b) { System.out.print('?'); System.out.print(' '); System.out.print(a); System.out.print(' '); System.out.println(b); System.out.flush(); } public static Boolean check(long n){ return n == -1; } public static Boolean check2(long n,long m){ return n != m; } public static void main(String[] args) { Scanner sin = new Scanner(System.in); int t = 1; //t = sin.nextInt(); while(t > 0) { t -= 1; long n,m; for(int i = 1;i < 8; ++i){ for(int j = i + 1; j < 8; ++j){ ask(i,j); n = sin.nextLong(); ask(j,i); m = sin.nextLong(); if(check(n)){ long ans = Math.max(i,j) - 1; System.out.print('!'); System.out.print(' '); System.out.println(ans); System.out.flush(); return; } if(check2(n,m)){ long ans = n + m; System.out.print('!'); System.out.print(' '); System.out.println(ans); System.out.flush(); return; } } } } } }
Java
["1\n\n2\n\n-1"]
1 second
["? 1 2\n\n? 1 3\n\n? 1 4\n\n! 3"]
NoteIn the first example, the graph could look like this The lengths of the simple paths between all pairs of vertices in this case are $$$1$$$ or $$$2$$$. The first query finds out that one of the simple paths from vertex $$$1$$$ to vertex $$$2$$$ has a length of $$$1$$$. With the second query, we find out that one of the simple paths from vertex $$$1$$$ to vertex $$$3$$$ has length $$$2$$$. In the third query, we find out that vertex $$$4$$$ is not in the graph. Consequently, the size of the graph is $$$3$$$.
Java 11
standard input
[ "interactive", "probabilities" ]
8590f40e7509614694486165ee824587
null
1,800
null
standard output
PASSED
40f846539cded39613350a7b0742d556
train_110.jsonl
1662993300
This is an interactive problem.I want to play a game with you...We hid from you a cyclic graph of $$$n$$$ vertices ($$$3 \le n \le 10^{18}$$$). A cyclic graph is an undirected graph of $$$n$$$ vertices that form one cycle. Each vertex belongs to the cycle, i.e. the length of the cycle (the number of edges in it) is exactly $$$n$$$. The order of the vertices in the cycle is arbitrary.You can make queries in the following way: "? a b" where $$$1 \le a, b \le 10^{18}$$$ and $$$a \neq b$$$. In response to the query, the interactor outputs on a separate line the length of random of two paths from vertex $$$a$$$ to vertex $$$b$$$, or -1 if $$$\max(a, b) &gt; n$$$. The interactor chooses one of the two paths with equal probability. The length of the path —is the number of edges in it.You win if you guess the number of vertices in the hidden graph (number $$$n$$$) by making no more than $$$50$$$ queries.Note that the interactor is implemented in such a way that for any ordered pair $$$(a, b)$$$, it always returns the same value for query "? a b", no matter how many such queries. Note that the "? b a" query may be answered differently by the interactor.The vertices in the graph are randomly placed, and their positions are fixed in advance.Hacks are forbidden in this problem. The number of tests the jury has is $$$50$$$.
256 megabytes
import java.io.*; import java.util.*; public class E { public static void main(String[] args) throws IOException{ FastScanner fs = new FastScanner(); int tt = 1; while(tt-- > 0) { long a, b; for (int i = 1; i <= 7; ++i) { for (int j = i + 1; j <= 7; ++j) { System.out.println("? " + i + " " + j); a = fs.nextLong(); System.out.println( "? " + j + ' ' + i); b = fs.nextLong(); if (a == -1) { System.out.println( "! " + (Math.max(i, j) - 1)); return; } if (a != b) { System.out.println("! " + (a + b)); return; } } } } } public static int gcd(int a, int b) { if(b == 0) return a; return gcd(b, 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 class FastScanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readArray(int n) { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } long[] 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()); } double nextDouble() { return Double.parseDouble(next()); } } }
Java
["1\n\n2\n\n-1"]
1 second
["? 1 2\n\n? 1 3\n\n? 1 4\n\n! 3"]
NoteIn the first example, the graph could look like this The lengths of the simple paths between all pairs of vertices in this case are $$$1$$$ or $$$2$$$. The first query finds out that one of the simple paths from vertex $$$1$$$ to vertex $$$2$$$ has a length of $$$1$$$. With the second query, we find out that one of the simple paths from vertex $$$1$$$ to vertex $$$3$$$ has length $$$2$$$. In the third query, we find out that vertex $$$4$$$ is not in the graph. Consequently, the size of the graph is $$$3$$$.
Java 11
standard input
[ "interactive", "probabilities" ]
8590f40e7509614694486165ee824587
null
1,800
null
standard output
PASSED
d8be4f91777fa84759a6cd1fad64c37b
train_110.jsonl
1662993300
This is an interactive problem.I want to play a game with you...We hid from you a cyclic graph of $$$n$$$ vertices ($$$3 \le n \le 10^{18}$$$). A cyclic graph is an undirected graph of $$$n$$$ vertices that form one cycle. Each vertex belongs to the cycle, i.e. the length of the cycle (the number of edges in it) is exactly $$$n$$$. The order of the vertices in the cycle is arbitrary.You can make queries in the following way: "? a b" where $$$1 \le a, b \le 10^{18}$$$ and $$$a \neq b$$$. In response to the query, the interactor outputs on a separate line the length of random of two paths from vertex $$$a$$$ to vertex $$$b$$$, or -1 if $$$\max(a, b) &gt; n$$$. The interactor chooses one of the two paths with equal probability. The length of the path —is the number of edges in it.You win if you guess the number of vertices in the hidden graph (number $$$n$$$) by making no more than $$$50$$$ queries.Note that the interactor is implemented in such a way that for any ordered pair $$$(a, b)$$$, it always returns the same value for query "? a b", no matter how many such queries. Note that the "? b a" query may be answered differently by the interactor.The vertices in the graph are randomly placed, and their positions are fixed in advance.Hacks are forbidden in this problem. The number of tests the jury has is $$$50$$$.
256 megabytes
// package c1729; // // Codeforces Round #820 (Div. 3) 2022-09-12 07:35 // E. Guess the Cycle Size // https://codeforces.com/contest/1729/problem/E // time limit per test 1 second; memory limit per test 256 megabytes // public class Pseudo for 'Source should satisfy regex [^{}]*public\s+(final)?\s*class\s+(\w+).*' // // . // // We hid from you a cyclic graph of n vertices (3 <= n <= 10^{18}). A cyclic graph is an undirected // graph of n vertices that form one cycle. // // You can make queries in the following way: // * "? a b" where 1 <= a, b <= 10^{18} and a != b. In response to the query, the interactor // outputs on a separate line the length of random of two paths from vertex a to vertex b, or -1 // if \max(a, b) > n. The interactor chooses one of the two paths with . The length of the // path--is the number of edges in it. // // You win if you guess the number of vertices in the hidden graph (number n) by making no more than // 50 queries. // // Note that the interactor is implemented in such a way that for any ordered pair (a, b), it always // returns the same value for query "? a b", no matter how many such queries. Note that the "? b a" // query may be answered differently by the interactor. // // The vertices in the graph are randomly placed, and their positions are fixed in advance. // // Hacks are forbidden in this problem. The number of tests the jury has is 50. // // Input // // // Output // // You can make no more than 50 of queries. To make a query, output on a separate line: // * "? a b", where 1 <= a, b <= 10^{18} and a != b. In response to the query, the interactor will // output on a separate line the length of a random simple path from vertex a to vertex b (not to // be confused with the path from b to a), or -1 if \max(a, b) > n. The interactor chooses one of // the two paths with . // // If your program gets a number 0 as a result of a query, it means that the verdict for your // solution is already defined as "" (for example, you made more than 50 queries or made an invalid // query). In this case, your program should terminate immediately. Otherwise, in this scenario you // may get a random verdict "", "" or some other verdict instead of "". // // The answer, like queries, print on a separate line. The output of the answer is not counted as a // query when counting them. To print it, use the following format: // * "! n": the expected size of the hidden graph (3 <= n <= 10^{18}). // // After that, your program should terminate. // // After the output of the next query, be sure to use stream cleaning functions so that some of your // output is not left in some buffer. For example, in C++ you should use function flush(stdout), in // Java call System.out.flush(), in Pascal flush(output) and stdout.flush() for Python. // // Note that the interactor is implemented in such a way that for any ordered pair (a, b), it always // returns the same value for query "? a b", no matter how many such queries. Note that the "? b a" // query may be answered differently by the interactor. // // The vertices in the graph are randomly placed, and their positions are fixed in advance. // // Hacks are forbidden in this problem. The number of tests the jury has is 50.</div> // // Example /* input: 1 2 -1 output: ? 1 2 ? 1 3 ? 1 4 ! 3 */ // Note // // In the first example, the graph could look like this // https://espresso.codeforces.com/b7cf9de84753f42c1a57e0737594ca63b7b9a4c6.png // // The lengths of the simple paths between all pairs of vertices in this case are 1 or 2. // * The first query finds out that one of the simple paths from vertex 1 to vertex 2 has a length // of 1. // * With the second query, we find out that one of the simple paths from vertex 1 to vertex 3 has // length 2. // * In the third query, we find out that vertex 4 is not in the graph. Consequently, the size of // the graph is 3. // import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.InputStreamReader; import java.lang.invoke.MethodHandles; import java.util.Random; import java.util.StringTokenizer; public class C1729E { static final int MOD = 998244353; static final Random RAND = new Random(); static long solve(Judge judge, MyScanner in) { int m = getMagnitude(judge, in); // number of nodes is between [2^m, w^(m+1)] if (m == 1) { // n must be 3 answer(3); return 3; } // System.err.format(" m:%d\n", m); long maxv = 1L << m; while (true) { long a = getRandom(maxv); long b = getRandom(maxv); while (b == a) { b = getRandom(maxv); } long r1 = ask(a, b, judge, in); long r2 = ask(b, a, judge, in); if (r1 != r2) { answer(r1 + r2); return r1 + r2; } } } // Get random position number in [1, maxv] where maxv <= 1e18 static long getRandom(long maxv) { long v = RAND.nextInt(1 << 30); v = (v << 30) + RAND.nextInt(1 << 30); return 1 + (v % maxv); } static int getMagnitude(Judge judge, MyScanner in) { int lo = 1; int hi = 59; int ans = 0; while (lo <= hi) { int mid = lo + (hi-lo)/2; long r = ask(1, (1L << mid), judge, in); if (r < 0) { hi = mid - 1; } else { ans = mid; lo = mid + 1; } } return ans; } static long ask(long a, long b, Judge judge, MyScanner in) { if (in != null) { System.out.format("? %d %d\n", a, b); System.out.flush(); return in.nextLong(); } else { return judge.ask(a, b); } } static void answer(long v) { System.out.format("! %d\n", v); System.out.flush(); } static class Judge { final long max = (long) (1e18 + 1); long n; int numAsk = 0; public Judge() { long v = RAND.nextInt(); v = (v << 30) + RAND.nextInt(); n = Math.max(3, v % max); System.out.format("Created Judge %d\n", n); } long ask(long a, long b) { numAsk++; long min = Math.min(a, b); long max = Math.max(a, b); long ans = max > n ? -1 : RAND.nextBoolean() ? max - min : n + min - max; System.err.format(" %3d ask %d %d -> %d\n", numAsk, a, b, ans); return ans; } } static boolean test = false; static void doTest() { if (!test) { return; } long t0 = System.currentTimeMillis(); for (int t = 0; t < 20; t++) { Judge judge = new Judge(); long ans = solve(judge, null); myAssert(ans == judge.n); } System.out.format("%d msec\n", System.currentTimeMillis() - t0); System.exit(0); } public static void main(String[] args) { doTest(); MyScanner in = new MyScanner(); solve(null, in); } static void output(int[] a) { if (a == null) { System.out.println("-1"); return; } StringBuilder sb = new StringBuilder(); for (int v : a) { sb.append(v); sb.append(' '); if (sb.length() > 4000) { System.out.print(sb.toString()); sb.setLength(0); } } System.out.println(sb.toString()); } static void myAssert(boolean cond) { if (!cond) { throw new RuntimeException("Unexpected"); } } static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { try { final String USERDIR = System.getProperty("user.dir"); String cname = MethodHandles.lookup().lookupClass().getCanonicalName().replace(".MyScanner", ""); cname = cname.lastIndexOf('.') > 0 ? cname.substring(cname.lastIndexOf('.') + 1) : cname; final File fin = new File(USERDIR + "/io/c" + cname.substring(1,5) + "/" + cname + ".in"); br = new BufferedReader(new InputStreamReader(fin.exists() ? new FileInputStream(fin) : System.in)); } catch (Exception e) { br = new BufferedReader(new InputStreamReader(System.in)); } } public String next() { try { while (st == null || !st.hasMoreElements()) { st = new StringTokenizer(br.readLine()); } return st.nextToken(); } catch (Exception e) { throw new RuntimeException(e); } } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } }
Java
["1\n\n2\n\n-1"]
1 second
["? 1 2\n\n? 1 3\n\n? 1 4\n\n! 3"]
NoteIn the first example, the graph could look like this The lengths of the simple paths between all pairs of vertices in this case are $$$1$$$ or $$$2$$$. The first query finds out that one of the simple paths from vertex $$$1$$$ to vertex $$$2$$$ has a length of $$$1$$$. With the second query, we find out that one of the simple paths from vertex $$$1$$$ to vertex $$$3$$$ has length $$$2$$$. In the third query, we find out that vertex $$$4$$$ is not in the graph. Consequently, the size of the graph is $$$3$$$.
Java 11
standard input
[ "interactive", "probabilities" ]
8590f40e7509614694486165ee824587
null
1,800
null
standard output
PASSED
3054cffd14b44ac322327b8edf9378bf
train_110.jsonl
1662993300
This is an interactive problem.I want to play a game with you...We hid from you a cyclic graph of $$$n$$$ vertices ($$$3 \le n \le 10^{18}$$$). A cyclic graph is an undirected graph of $$$n$$$ vertices that form one cycle. Each vertex belongs to the cycle, i.e. the length of the cycle (the number of edges in it) is exactly $$$n$$$. The order of the vertices in the cycle is arbitrary.You can make queries in the following way: "? a b" where $$$1 \le a, b \le 10^{18}$$$ and $$$a \neq b$$$. In response to the query, the interactor outputs on a separate line the length of random of two paths from vertex $$$a$$$ to vertex $$$b$$$, or -1 if $$$\max(a, b) &gt; n$$$. The interactor chooses one of the two paths with equal probability. The length of the path —is the number of edges in it.You win if you guess the number of vertices in the hidden graph (number $$$n$$$) by making no more than $$$50$$$ queries.Note that the interactor is implemented in such a way that for any ordered pair $$$(a, b)$$$, it always returns the same value for query "? a b", no matter how many such queries. Note that the "? b a" query may be answered differently by the interactor.The vertices in the graph are randomly placed, and their positions are fixed in advance.Hacks are forbidden in this problem. The number of tests the jury has is $$$50$$$.
256 megabytes
// No sorcery shall prevail. // import java.util.*; import java.io.*; public class _InVoker_ { //Variables static long mod = 1000000007; static long mod2 = 998244353; static FastReader inp= new FastReader(); static PrintWriter out= new PrintWriter(System.out); public static void main(String args[]) { _InVoker_ g=new _InVoker_(); g.main(); out.close(); } //Main void main() { for(int i=0;i<25;i++) { long x=query(1,i+3); long y=query(i+3,1); if (x==-1 || y==-1) { out.println("! "+(i+2)); break; } if (x!=y) { out.println("! "+(x+y)); break; } } } long query(long a, long b) { System.out.println("? "+ a+" "+ b); return inp.nextLong(); } /********************************************************************************************************************************************************************************************************* * ti;. .:,:i: :,;;itt;. fDDEDDEEEEEEKEEEEEKEEEEEEEEEEEEEEEEE###WKKKKKKKKKKKKKKKKKKKKWWWWWWWWWWWWWWWWWWW#WWWWWKKKKKEE :,:. f::::. .,ijLGDDDDDDDEEEEEEE* *ti;. .:,:i: .:,;itt;: GLDEEGEEEEEEEEEEEEEEEEEEDEEEEEEEEEEE#W#WEKKKKKKKKKKKKKKKKKKKKKKKWWWWWWWWWWWWWWWWWWWWWWKKKKKKG. .::. f:,...,ijLGDDDDDDDDEEEEEE * *ti;. .:,:i: :,;;iti, :fDDEEEEEEEEEEEEEEEKEEEEDEEEEEEEEEEEW##WEEEKKKKKKKKKKKKKKKKKKKKKWWWWWWWWWWWWWWWWWWWWWWWKKKKKKEG .::. .f,::,ijLGDDDDDDDDEEEEEE * *ti;. .:,:i: .,,;iti;. LDDEEEEEEEEEEKEEEEWEEEDDEEEEEEEEEEE#WWWEEEEEKKKKKKKKKKKKKKKKKKKKKKKKKWWWWWWWWWWWWWWWWWWWKKKKKEDj .::. .:L;;ijfGDDDDDDDDDEEEEE * *ti;. .:,:i: .:,;;iii:LLDEEEEEEEEEEEKEEEEEEEEDEEEEEEEEEEEW#WWEEEEEEEKKKKKKKKKKKKKKKKKKKKKKKKKWWKWWWWWWWWWWWWWWKKKKKKKEL .::. .:;LijLGGDDDDDDDDEEEEE * *ti;. .:,:;: :,;;ittfDEEEEEEEEEEEEEEEEKEEEGEEEEEEEEEEEKWWWEEEEEEEEEKKKKKKKKKKKKKKKKKKKKKKKKKKWWWWWWWWWWWWWWWKKKKKKKELj .::. :,;jffGGDDDDDDDDDEEEE * *ti;. .:,:i: .,;;tGGDEEEEEEEEEEEKEEEKEEEDEEEEEEEEEEEEWWWEEEEEEEEEEEEKKKKKKKKKKKKKKKKKKKKKKKKKKWWWWWWKWWWWWWKKKKKKKEEL .::. .:;itDGGDDDDDDDDDEEEE * *ti;. .:::;: :;ifDEEEEEEEEEEEEKEEEKEEEEEEEEEEEEEEEWWWEEEEEEEEEEEEEEKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKW#WWWKKKKKKKKEEf .::. :,itfGEDDDDDDDDDDDEE * *ti;. .:::;: :GGEEEEEEEEEEEKEKEEKEEEEEEEEEEEEEEEEWWEEEEEEEEEEEEEEEEEKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKW#WKKKKKKKKKEEDG .::. .,;jfLGKDLDDDDDDEEDD * *ti;. .:::;: fDEEEEEEKKKKKKKKKEKEEEEEEEEEEEEEEE#WEEEEEEEEEEEEEEEEEEKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKW#KKKKKKKKKKEEf .:::. .,;tfLGDEDDDDDDDDEEE * *ti;. :::;: fDEEEEEEKKKKKKKKKKWKEEEEEEEEEEEEEEEWKEEEEEEEEEEEEEEEEEEEEKEKKKKKKKKKKKKKKKKKKKKKKKKKKKKW##KKKKKKKKKEEft :::. .,;tfLGDDDKDDDDDDDDD * *ti;. .::;: fDEEEEEEKKKKKKKWKKKKKEEEEEEEEEEEEE#WEEWEEEEEDEEDEEEEEEEEEEEEKKKKKKKKKKKKKKKKKKKKKKKKKKKKW#WKKKKKKKKEEGG :,:. .,;tfLGGDDDKDDDDDDDD * *ti;. .:.;: tGDEEEEKKKKKKKKKKKKKKKKKEEEEEEEEEEEWEEKWEEEEEEEDEEEEEEEEEEEEEEKEKKKKKKKKKKKKKKKKKKKKKKKKKKWWWKKKKKKKEEDf :::. .,;tfLGGDDDDEDDDDDDD * *ti;. .::;: fDEEEEEKKKKKKKKKKKWKKKKKKKKEEEEEEEWWEEWEEEEEEEEEEEEEEEEEEEEEEEEEEKKKKKKKKKKKKKKKKKKKKKKKKKW##KKKKKKKEEEft.::. .,;tfLGGDDDDDDEDDDDD * *ti;. .:.;: tGDEEEKKKKKKKKKKKKKKKKKKKKKKEKEEEEE#EEWWEEEEEEEEEEEEEEEEEEEEEEEEEEEEKKKKKKKKKKKKKKKKKKKKKKKKW#WKKKKKKEEEGD:::. .,;tfLGGDDDDDDDEDDDD * *ti;. .:.,. LDEEEEKKKKKKKKKKWKWKKKKKKKKKKKKEEEKWEKW#EEEEEEEEEEEEEEEEKEEEEEEEEEEEEEEEKKKKKKKKKKKKKKKKKKKKW##KKKKKKEEEEf,,:. .,;tfLGGDDDDDDDDEDDD * *ti;. ..:.,. LGDEEEEKKKKKKKKKKWKKKKKKKKKKKKKKKKKWEEW#WEEEEEEEEEEEEEEEKEEEEEEEEEEEEEEEEEEEKEKKKKKKKKKKKKKKKK##KKKKKEEEEEfi;,. .,;tfLGGDDDDDDDDDKDD * *tt;. .:.,: jDEEEEKKKKKKKKKKWWKKKKKKKKKKKKKKKKKWKE#WWEEEEEEEEEEEEEEWEEEEEEEEEEEEEEEEEEEEEEEKKKKKKKKKKKKKKKKWWKKKKEEEEDfG;,: .,;tfLGGDDDDDDDDDDKD * *tii,. .:.,. tGDEEEEKKKKKKKKKKWWWKKKKKKKKKKKKKKKWKKWWWKEEEEEEEEEEEEEKEEEEEEEEEEEEEEEEEEEEEEEEEEEEEKKKKKKKKKKKW#KKKKEEEEDGGi;,. .,;tfLGGDDDDDDDDDDDE * *ti;;,:. .:.,: fDEEEEKKKKKKKKKKKWKKKKKKKKKKKKKKKKKWEK#WWKEEEEEEEEEEEEDEEEEEEEEEEEEEEGEEEEEEEEEEEEEEEEEEEKKKKKKKWWKKEEEEEEDDf;;;,. .,;tfLGGDDDDDDDDDDDD * *tii;,,:.. ...,. ;LEEEEEKKKKKKWKKKKWKKKKKKKKKKKKKKKKKEKKW#WEEEEEEEEEEEEEjEEEEEEEEEKEEEEGEEEEEEEEEKEEEEEEEEEEEEEEEEE#WKEEEEEEDDf;;;;,: .,itfLGGDDDDDDDDDDDD * *ti;,,,,,:. ...,. LDEEEEKKKKKKKKKKKWWWKKKKKKKKKKKKKKKWKK#W#WEEEEEEEEEEEDDLEEEEEEEEEWEEEEDEEEEEEEEEKEEEEEEEEEEEEEEEEEWWEEEEEEEDDfj,,,,,:. .,itfGGGDDDDDDDDDDDD * *tii,,,,::::. ...,: .fDEEEEKKKKKKWKKKKWWWKKKKKKKKKKKKKKKEKKW#WWEEEEEEEEEEEKiKEEKEEEEEEWEEEEDEEEEEEEEEEEEEEEEEEEEEEEEEEEWWEEEEEEEDDLD:::,,,:. .,ijfGGGDDDDDDDDDDDD * *ti;:::::::::.. .:.,: LDEEEEKKKKKKKWKKKKWWKKKKKKKKKKKKKKKKtKKWWWWKEEEEEEEEEDiiDEEEEEEEEWWEEEEEEDEEEEEEEEEEEEEEEEEEEEEEEEEEWKEEEEEDDDGL:. .:,,,: .,ijLGGGDDDDDDDDDDDD * *tt;. .::::::::.. ...,: :fDEEEKKKKKKKKKKKKWW#KKKKKKKKKKKKKKKKfKKWWWWKEEEEEEEEDti,DEKEEEEEEWWEEEDEEEEEEEEEKEEEEEEEEEEEEEDEEEEE#WEEEEEGGDGf:. .:,;,:. .,ijLGGDDDDDDDDDDDDD * *tt;. .:::::::.. ...,: GDEEEKKKKKKKKWKKKKWWWKKKWKKKKKKKWWWKDEKLWWWWKKEEEEEEDEi,LDEEEEEEEEWWEEEEEEEEEEEEEEEEEEEEEEEEEDEDEEEEEW#EEEEDDDDGf,. :,,,:...,ijLGGGDDDDDDDDDDDD * *tt;. .....::::.. ...,: fDEEEKKKKKKKKWKKKKWWWWKKKWKKKKKKKKKKfWKiWWW#KKEEEEEEEi;.EDfEEEDEEiWWEEEEEEEEEEEEDGKEEEEEEEEEEDEEEEEEEWWEEEEDDDGGLi. .,;,:::,ijLGGGDDDDDDDDDDDD * *tt;. ....:::::. ...,. iDEEEEKKKKKKKKWKKWKWWWWWKKWWWKKKKKKKKtWKt#WWWKKEEEEEDji..DDKDDEDEGiWKEEEEEEEEEEDDEjEEEEEEEEEEEDEEEEEEEKWKEEDDDDGGff. .:,;,,;ijLGGGDDDDDDDDDDDD * *tt;. ....::::.. .:.,: .LDEEEKKKKKKKKKKKKWWWWKWWWWWWWWWWKKKKWtKKiDWWWKKKEEEEKi:..DEDDDDDDiiWKEEEEEEEEEEDDEijDEEEEEKEEEEEEEEEEEEWWEEGDDDGGLG. .:,;;iijLGGGDDDDDDDDDDDD * *tt;. .....:::.. ...,. .fEEEEKKKKKKKKWKKKKWWWWWWWWWWWWWWKWKKKiKDiLWWWWKEEEEEi,..fD:DDDDDti;WEEEEEEEEEEKDDi:iDDEEEEWEEEEEEEEEEEE#WEEGDDDDGGG. :,iitjLGGGDDDDDDDDDDDD * *tti. .....:::.. ...,. GDEEEKKKKKKKKKWKKKWWW#WWWWWWWWWWWKWKKjiEjitWWWKKWEEEDi...DDLDDDDji;;WEEEEEEEEEEEDEj.iDDEEEEWEEEEEEEEEEEEWWEEDDDDDDGf. .,;tjfLGGDDDDDDDDDDDD * *tti. ....::::.. ...,. fEEEKKKKKKKKKKKKKKKW#WWWWWWWWWWWWWWWWtiEiiiWWWKKEWKEi....D.EDDDEi;.fWEEEEEEEEEEDDfL.;EDDEEEWEEEEEEEEEEEEWWEEEDDDDDGf. :;ijfLGGDDDDDDDDDDDD * *tti. ....::::.. ...,. LDEEEKKKKKKKKKKKKKKWWWWWWWWWWWWWWWW####WKiiiWWWKKKEEK,...:E:DDDEii..GWEEEEEEEEDWDDiL.,KDDEEEWEEEEEEEEEEEEWWKEEDDDDDGf: .,itfLGGDDDDDDDDDDDD * *tti. .....:::.. ...,. fDEEEKKKKKKKKKWKKKKWWWWWWWWWWWWW########WLiiWWWKKKEEjD...G,DDDDi;...EWEEEEEEEEDKDEii..LDDEEEWEEEEEEEEEEEEWWWEEDDDDDGfi .,;tfLGGGDDDDDDDDDDD * *tti. .....:::.. ...,. iGEEEKKKKKKKKKKWKKKKWWWWWWWWWWWW###########KiWWWKKEEE,.D..D.DDDii:...KKEEEEEEEEEDDj:...tEDEEEWEEEEEEEEEEEEWWWEEEDDDDDLL .,;tjLLGGDDDDDDDDDDD * *tti. ....::::......:. LEEEKKKKKKKKKKWWKKKWWW#KWWWWWWWW#####W####W##KWWKKEEL..:D.jjDDi;,....KKEEEEEEEDfDDi...:iKDEEEWKEEEEEEEEEEEWWWEEEEDDDDLG .,;tjLLGGDDDDDDDDDDD * *tti. ...::::::..,. :GEEEKKKKKKKKKKKKWWWWW##WWWWWWWWW##WKWK#W#W####WWKEEK.....G.DDti,.....KKEEEEEEDWGDf.,...iKDEEEWWEEEEEEEEEEEW#WEEEEEDDDGL .,;tjLLGGDDDDDDDDDDD * *tti. ....::::::,. GDEEKKKKKKKKKKKKKWWWW###WWWWWWWWWW#WWWK###W#####WKEKK.....jDDL;;......KKEEEEEEEEEDi.f...;KDEEEWWEEEEEEEEEEEWWWWEEEEEDDGf .,;tjLLGGDDDDDDDDDDD * *tti. ....:::,,. .LEEEKKKKKWKKKKKWWWWWW###WWWWWWWWWW#WWKW#WW##W#WWWKEKD:....:DD:;......;KEEEEEEEKiDD..f...,KKEEEWWEEEEEEEEEEEWWWWEEEEEDDDf .:;tjLLGGGDDDDDDDDDD * *tti. ...::,,,:. GDEEKKKKKKKKKKKKWWWWWWW#WWWWWWWWWWW#KjKWWWWWWWWWWWWEK.j,..;fD.;.......fKEEEEEDKG:Di..,....DKEEEWWEEEEEEKEKKKWWWWEEEEEEDDf .:;tjLLGGDDDDDDDDDDD * *jti. ...::,,,,:. .fEEEKKKKKWKKKKKKWWWWWWW#WWWWWWWWWWK#KKKWWWWWWWWWWWWWK..f:.:G.,:.......EKEEEEEKK;:E:.......fKEEEWWKEKEKKKKKKKW#WWEEEEEEDDf: .,;tfLLGGDDDDDDDDDDD * *tti. ...:,,,;;,: iDEEKKKKKWKKKKKKKWWWWWWW#WWWWWWWWWWK#WDKWWKKWWWWWWWWWE..;G:G..,........KKEEEEEKi.Gi..:.....tKEEKWWWKKKKKKKKKKW##WKEEEEEEDfi .,;tfLLGGGDDDDDDDDDD * *tti. ....::,,;;;,LEEKKKKKKWKKKKKWWWWWWW###WWWWWWWWWWKWWDKWEEEWKKWWWWWKKj.:LG..;.........EKEEEEKG;.G...;.....;KKEKWWWKKKKKKKKKKW##WWKEEEEEDfL .,;tfLGGGDDDDDDDDDDD * *jti. ...::::,;ijDEEKKKKKWKKKKKKWKWWWWW##WWWWWWWWWWWKK#KKGDGDWEEWKKWKKGE,.i;.:.........:EKEEEKE;.:L...j.....,KWEKWWWKKKKKKKKKK####WKKEEEEDLG .,;tfLGGGGDDDDDDDDDD * *jti. ...:...,,;GEEKKKKKWWKKKKKWWWWWWWW###WWWWWWWWWKKKWWKiLGGEDEDEKGKKiEG..;...........jKEEEKK;:.G....,.....:KKEWWWWKKKKKKKWKK####WKKKKEEEGL .,;tfLGGGGDDDDDDDDDD * *jti. ...:. .:,GEEKKKKKWKKKKKWWWWWWWW####WWWWWWWWWKKKWWKii;fDLGDK: EEi:E:.............EKEEKK;;..L...........KKKWWWWKKKKKKKWKK####WKKKWKEEDf .,;tfGGGGDDDDDDDDDDD * *jti. ...:. ,EEKKKKKWWKKKKKWWWWWWWWW###WWWWWWWWKKKKfWWLt;i,. fi EG..D:.............EKEKK;;..t....:.......KWKWWWWKKKKKKKWKK####WKKKWEEEDf:. .,;tfGGGGDDDDDDDDDDD * *jti. ...:. GEEKKKKKWKKKKKWWWWWWWWW####WWWWWWWKKKKKt;KKEfff .;t.................KKKKi;:..GtGGfG.......KWWWWWWKKKKKKKWKK###WWWKKKKEEEf,,: .,;tfGGGGDDDDDDDDDDD * *jti. ...:. GEKKKKKWWKKKKKWWWWWWWWWW##WWWWWWWKKKKKKt;EiKKKK, ...t................jEKKG;;..,.....,LGi....KWWWWWWKKKKKKWKKKW####WKKKKKEEL,,,:. .,;tfGGGDDDDDDDDDDDD * *jti. ...:. .GEEKKKKKWKKKKKWWWWWWWWWW###WWWWWWWKKKKKKtiE::tGG........................EEEj;;...,.........:D..DKWWWWWWKKKKK#KKW###W#WKKKKKEEfj:,,,:. .,;tfGGGDDDDDDDDDDDD * *jti. ...:. DEKKKKKWWKKKKKWWWWWWWWW####WWWWWWWKKKKKKiiE:::.::.......................EEi;;...j.....f......:iDKWWWWWWKKKKK#WW######WKKKKKEELG :,,,,:. .,;tfGGGDDDDDDDDDDDD * *jti. ...:. fEEKKKKWWKKKKWWWWWWWWWWW###WWWWWWWWKKKKKK;tE::..........................DD;.;,.::......;........EWWWWWWWKKKKW#WW#####WWKKKWKKELG .:,,,:::,;tfGGGDDDDDDDDDDDD * *jti. ...:. .DEKEKKKWWKKKKWWWWWWWWWWW###WWWWWWWWKKKKKE,iD::..........................D..,;.,;tLffi...........DWDWWWW#KKKWWWWW#####W#KKKWKEEGL .:,;,,,;tfGGGDDDDDDDDDDDD * *jti. ...:. ;EEKKKKWWKKKKKWWWWWW#WWWW####WWWWWWKKKKKEL:iD:..........................j ..;..;;:.....i,........DKtWWWWWKKWWWWWW#####WWWKKKEKEDf .:,;;;itfGGGDDDDDDDDDDDD * *jti. ...:. DEKKKKKWWKKKKWWWWWWW#WWWW####WWWWWWKKKKKEj:iG...............................:....................GKiWWWWWKKWW#WWW######WWKKKKKEEf .,;iitfGGGDDDDDDDDDDDD * *jti. ...:.:EKKKKKWWKKKKKWWWWWWW#WWW#####WWWWWKWKKKKEi:if:.................................iEKEKKKKKKDj......DKiWWWWWKWK##WW#######WWKKK:KEEL .:;itfGGGDDDDDDDDDDDD * *jji. ...:,DEEKKKWWWKWKKWWWWWWWWWWWW#####WWWWWWWKKKKEi:it..................................j. KKKKKKKKKKKf..DKiWWWWWKWW##WW#######WWKKK,KEEf .,;tfGGGDDDDDDDDDDDD * *jji. ..L:iDEEKKKWWKKKKKWWWWWWWWWWWW#####WWWWWKWKKKKKi.i;.................................. . KKKWWWWWWWWK..DGiWWWWWKK##WWW#####W#WWKKKjEKEL, .:;tfGGGDDDDDDDDDDDD * *jji. .f:::EEEKKKWWWKKKKKWWWWWWWWWWWW#####WWWWWKWKKKKK;.i,.................................:: KKEKWWWWWWfWK..EiiWWWWWKWW#WW##########KKKD,KELj .:;tfGGDDDDDDDDDDDDD * *jji. .t::::,DEEKKKWWKKKKWWWWWWWWW#WWWW#####WWWWKKWKKKEK;.i:.................................GDDEEEKKKWWWWWtWWD.E;iWWWWWW###WW#########WWKKK.EEDG .:;tfGGGDDDDDDDDDDDD * *jji. . j..::::EKEKKKWWWKKKKWWWWWWWWW#WWW######WWWWKKWKKKEK;.t:.................................ELLEDDEEEWWWWEtWK,.KiiWWWWWW###W##########WWKKK:EEEG .;tjfLLGDDDDDDDDDDDDDDD * *jji. i.::::::,EEEKKWWWKKKKKWWWWWWWWW#WWW#####WWWWWKWKKKKEE,.t..................................DfiEGDDDEEKKKttKWG.KiiWWWWW##WWW##########WWKKK:fEEL ,fGGGDDDDDDDDEEEDDDDDDDDDD * *jji. .;:..:::::DEEEKKWWWKKKKKWWWWWWWWW#WWWW####WWWWWWWKKKKED,.t..................................ifjDDGGEGDKK.ttKKE.DiWWWWW###WW##########WWWKKK:.KELiLGGGGDDDDDDDDDDDDEEEDDDDDDD * *jji. i.:.::::::,KEEKKWWWKKKKKKWWWWWWWWW#WWWW####WWWWWWWKKKKEL:.j..................................GGf,;ifLLED .iiKKi:fWWWWWW##W#W##########WWWKKK:.KKLGGDDDDDDDDDDDDDDDDEDDEEDDDDD * *jji. .j:.::::::::EEEKKKWWWKKKKKKWWWWWWWW##WWW#####WWWWWWWKKKKKf:.f..................................:EEfftf .,. ;iE,..jWWWWWWW###W############WWKKK,:KKGDDDDDDDDDDDDDDDDDDDDDDDEDDDD * *jji. .:.::::::::,,EEEKKWWWKKKKKKKWWWWWWWW##WWW#####WWWWWWWKKKKKt..G....................................EEELL; .j....tKWWWWWWW################WWWKKtfGKGEDDDDDDDDDDDDDDDDDDDDDDDEEDD * *jji. :...:::::::,,jEEKKWWWWKKKKKKWWWWWWWWW##KWW#####KWWWWWWKKKKEi..D....................................:jEEE.........;KKWWWWWWWW#WW##W##########WWKKDLGKEKDDDDDDDDDDDDDDDDDDDDDDDDDED * *jji. i:.::::::::,,,EEEKKWWWWKKKKKWWWWWWWWWW##WWW#####WWWWWWWKKKKKi..D......................................:::::......,KKKWWWWWWWWW#####W########WWWKKKGGKKEGGGGGGGGDDDDDDDDDDDDDDDDDDE * *jji. i..:::::::::,,tEEKKWWWWKKKKKWWWWWWWWWWW##WW######WWWWWWWKKKKKi..D......................................::::......:EKKKWWWWWWWWWWW##WW########W#WKKWGGKKGGGGGGGGGGGGGGGDDDDDDDDDDDDD * *jji. .:::::::::::,,,EEEKKWWWWKKKKKWWWWWWWWWWW##WW#####WWWWWWWWKKKKKi..D....................................:::::::::..tELii;KWWWWWWWWWW##WW######WWWWWWKWGGGKGGGGGGGGGGGGGGGGGGGGGGGGGGDG * *jjt. :.::::::::,,,,fEEKKWWWWKKKKKKWWWWWWWWWW###WW####WWWWWWW#WKKKKKi..D....................................:::::::.:.,;;;;;;,KKWWWWWWWWW#WW########WWWKKWGGGKGGGGGGGGGGGGGGGGGGGGGGGGGGGG * *jji. ;.::::::::,,,,;EEEKWWWWWKKKKKWWWWWWWWWWWW##WW###WKWWWWWK#WKKKKKi..G......................................:::::::,;;;;:...KKKWWWWWWWWWKWW#######WWWWKKGLGKDGGGGGGLLGGGGGGGGGGGGGGGGGGG * *jjt. f.:::::::::,,,,fEEKKWWWWWKKKKKWWWWWWWWWWW###WW##WKKWWWWWW#WKKKKK;.jt........i.............................:::::::;j;;....:E.KKKWWWWWWWKWW#####W#WWWWKKLLGWEEGGGGGLGGGGGGGGGGGGGGGGGGGG * *jjt. ...:::::::,,,,,;DEEKWWWWWKKKKKWWWWWWWWWWWW####WWWKKKWWWWWWWWKKKKK;.E;.........t.............................:::::ii;;.....D...KKWWWWWWWKWW#####WWEWWWKKGGGEKKGGGGGLGGGGGGGGGGGGGLGGGGGG * *fji. ;.:::::::,,,,,;LEEKKWWWWWKKKKKWWWWWWWWWWWW####KWKKKKWWWWWWWWKKKKKi.D;..........j.............................:::tt;,.....:.....KKWWWWWWKWWWW##WWWGWWWKKGGGGKEGGGGGGGGGGGGGGGGGGGLLGGGGL * *fji. t::::::::,,,,,,;EEEKWWWWWKKKKKKKWWWWWWWWWWW##WKWKKKKKWWWWWWWWKKKKKi:D;............j...........................::LL;,.............KKWWWWWKWWWWWWWWWGWWWKKGGGGKGGGGGGGGGGGGGGGGGGGGLLGGGGL * *fjt: .:::::::,,,,,,,DEEKWWWWWWKKKKKKKWWWWWWWWWWWWKKWKKKKKKWWWWK#WWKKKKWitE;........... ............................:G;;:...............KKKWWKKWWWWWWWWWGWWWKKGGGGWGGGGGGGGGGGGGGGGGGGGGGGGGGL * *fjji;:. .f:::::::,,,,,,,;EEEKWWWWWWKKKKKKWWWWWWWWWWWKKKKKKKKKKKWWKWWWWWKKKKWGKD;........................................L;;..................DKKWKKWWWWWWWWWGWWWKKDGGGKDGGGGGGGGGGGGGGGGGGGGGGGGGG * *fjjtii;,:. :::::::,,,,,,,;EEEKWWWWWWKKKKKKWWWWWWWWWWKKKKKKKKKKKKWWWWWW#WWKKKKWiEj;......................................:i,;....,...............;KKEKWWWWWWWWWGKWWKKDDGGDEGGGDGGGGGDGGGGGGGGGGGGGGGG * *fjtiiiii;;:. j::::::,,,,,,,;;EEEKWWWWW#KKKKKWWWWWWWWWKKKKKKWKKKKKKKWWWWWWWWWKKKKWtEL;:....................................;;;:...,;j................:KEEWWWWWWWWWDDWWKKDDDDDKDDDDDDDDDDDDDDDGGGGGGGGGGG * *fjti;;iiii;;,:::::::,,,,,,,,;EEEKWWWWWWWKKKKWWWWWWWWKKKKKKKWKKKKKKKWWWWWWW#W#KKKKWEEii;...................................f;:....,;L...................EEKWWWWWWWWDDWWKKDDDDDKEDDDDDDDDDDDDDDDDDDDDDGGGG * *fjt,,,;;;;ii;f::::::,,,,,,,;;EEKWWWWWWWKKKKKWWWKWWKKKKKKKKKKKKKKKKKWWWWWWW#W#KKKKWKEij;:...............................:G;,.....,;f....................:tKKWWWWWWWDDWWKKDDDDDKKDDDDDDDDDDDDDDDDDDDDDDDDD * *jjt. ..:,;;;;,::::,,,,,,,,;;GEEWWWWWWWWKKKKWKKWKKKKKKKKKKKKKKKKKKKKWWWWWWW#W#KKKKWEDi;j;............................,Li;L;;;..,;;f........................KKKKWWWKDDWWKKDDDGDKKGGGGGGGGDGDDDDDDDDDDDDDDD * *fjt. .:,,,:::::,,,,,,,;;;EEKWWWWWWWKKKKKKWKKKKKKKKKKKKKKKKKKKKKWKKKWKW##W#KKKKWEti;;G;........................tEEEL;;;;;;;;;;L..........................DKKKKKEDDWWKEDGftiLE;;;;itjLGGGGGGDDDDDDDDDDD * *fjt. .j::::,,,,,,,;;;DEEWWWWWWWWKKKKWKKKKKKKKKKKKKKKKKKKKKKKWKKWWWK##W#KKKKKEii;;;L;...................iDEEEEEEKKi;j;;;;jD.....:......................,KKKKDGGEKKE:::::;E::::::::::,tLGGDDDDDDDDDD * *fjt. .;:::,,,,,,,;;;;EEKWWWWWWWWKWKKKKKKKKKKKKKKKWKKKKKKKKKKWKKWWWW#WW#KKKKKKii;;;;f;.............:tDEEEEEKKKKKKKKEti;;;L...............................EEKf;:iKKE::::::E::::::::::::::ifDDDDDDDDD * *fjt: :::,,,,,,,,;;;DEEWWWWWWWWWEKKKKKKKKKKKKKKKKKKKKKKKKKKWWKKWWWW####KKKKKEiii;;;;f,.........iDEEEEKKKKKKKKKKKKKKKf;iG......i..........................fK::::KKE::::::E::::::::::::::::,tGGDDDDD * *fjt: t:::,,,,,,;;;;iDEKWWWWWWKEKKKKKKKKKKKKKKKKKKKKKKKKKKKKWWKKWWWW####WKKKKLiii;;;;;L,....,Li;EDEEEEKKKKKKKKKKKKKKKKiG......;:...........................:i:::KKE:::::,E,::::::::::::::::::iGDDDD * *jjt. f::,,,,,,,;;;;GEEWWWWKEEKEKKKKKKKKKKKKKKKKWKKKKKKKKKKKWWKWWWWW###WWKKKKiii;;;;;;;G,;L;;iiEEEEEEEKKKKKKKKKKKKKWWKE......;t.........:....................j::KEE:,::,,D,,::::,,,,,,:::::::::tDDD * *fjt:. ,::,,,,,,,;;;;EEWWKEEEEEEKKKKKKKKKKKKKKKKWKKKKKKKKKKKWWKKWWWWW#W#KKKKKKiiiiii;;;;;i;;iiiEEKEEKKWKKKKKKKWKKKKKWWWGi;...;t......,;;;;,....................:,EEE,,,,,,D,,,,,,,,,,,,,,,,::,::::tG * *fjt:. ,::,,,,,,,;;;;DEKEEEEEEEEKKKKKKKKKKKKKKKKKKKKKKKKKKKKKWWWWWWWWW#W#KKKKKKiiiii;;i;;;;;iiiKKKEKKKKWWKWWWWWWKKKKWWWWW;;;:;L.....;;;;;;;;;....................,KEE,,,,,,E,,,,,,,,,,,,,,,,,,,,,,,,; * *fjt:. f:,,,,,,,;;;;jEDEEEEEEEEEKKKKKKKKKKKKKKKKKKKKKKKKKKKKKWWWWWWWW#W##KKKKKKiiiiiiii;i;;iiiEKKKKKKKKWKWWWWWWWWKKKWWWWWKi;;i.....,jEEfGi;;;;;...................EED,,,,,,E,,,,,,,,,,,,,,,,,,,,,,,,, * *fjt:. .f::,,,,,,;;jEEDEEEEEEEEEEKKKKKKKKKKKKKKKWKKKKKKKKKKKKKWWWKWWWWW###KKKKKLiiiiiiiiiiiiiiEEKKKKKKKKWWWWWWWWWWWWKWWWWWWGi;i;,..;jDDDKEGi;;;;;;:................EED,,,,,,D,,,,,,,,,,,,,,,,,,,,,,,,, * *fjt:. .. ;::,,,,,;;EDDEEEEEEEEEEKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKWWKKW#WW####KWKKKiiiiiiiiiiiiijKKKKKKKKKKWWWWWWWWWWWWWWWWWWWWWt;i;;;;i;DDDDDDGi;;;;;;;;:.............EDf;,,,;,G;;;;;;;;;;;;;;;,,,,,,,,,, * *fjt:......:,,,,,,;LDDDEEEEEEEEEEEKKKKKKKKKKKKKKKKWKKKKKKKKKKKKKWWWWKWWWW####KKKKKiiiiiiiiiiijKEKKWKKKKKKKWWWWWWWWWWWWWWWWWWWWWWiLiii;i;DEEEEDDE;i;;;;;;;;;:..........EDi,;;;;;L;;;;;;;;;;;;;;;;;;,,,,,,, * *fjt:......:,,,,,;EDDDEEKEEEEEEEEEKKKKKKKKKKKKKKKWKKKKKKKKKKKKKKWWWWKKWWW##W#KWKKWEiiiiiijGKKKKKWWKKKKKKKKWWWWWWWWWWWWWWWWWWWWWWKi;iiiiDDEEEEEEDEi;;;;;;;;;;;;;,:.....ED;;;;;;;j;;;;;;;;;;;;;;;;;;;;;;;,, * *fjt:.....t,,,,,;DDDDEEEKEEEEEEEEKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKWWWKKKWWWW##WKWKKWKiiiKKKKKKKKKWWKKKKKKKKWWWWWWWWWWWWWWW#WWWWWWWWWiiiiifLEEEEEEEEDi;i;;;;;;;;;;;;.....DD;;;;;;;i;;;;;;;;;;;;;;;;;;;;;;;;; * *fjt:.....G,,,,,GDDDEEEEEEEEEEEEKKKKKKKKKKKKKKKKWKKKKKKKKKKKKKKKWWWKKKWWW###WKWKKWKitKKKKKKKKKWKKKKKKKKKKWWWWWWWWWWWWWW###WWWWWWWWEiiiiiiiEEEEEEEEDGiiii;;;;;;;;;.....GD;;;;;;;i;;;;;;;;;;;;;;;;;;;;;;;;; * *fjt:.....L,,,,;GDDDEEEEEEEEEEKEKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKWWWWWDGWWW###KKWWKWKKKKKKKKKKKKKKKKKKKKKKKWWWWWWWWWWWWW####WWWWWWWWWiiiiiiiiEEEEEEEEEEDi;i;;;;;;;;.....Lj;;;;;;i;iiiiii;;;;;;ii;;;;;;;;;;; * ***********************************************************************************************************************************************************************************************************/ void sort(int a[]) { ArrayList<Integer> list=new ArrayList<>(); for(int x: a) list.add(x); Collections.sort(list); for(int i=0;i<a.length;i++) a[i]=list.get(i); } void sort(long a[]) { ArrayList<Long> list=new ArrayList<>(); for(long x: a) list.add(x); Collections.sort(list); for(int i=0;i<a.length;i++) a[i]=list.get(i); } void ruffleSort(int a[]) { Random rand=new Random(); int n=a.length; for(int i=0;i<n;i++) { int j=rand.nextInt(n); int temp=a[i]; a[i]=a[j]; a[j]=temp; } Arrays.sort(a); } void ruffleSort(long a[]) { Random rand=new Random(); int n=a.length; for(int i=0;i<n;i++) { int j=rand.nextInt(n); long temp=a[i]; a[i]=a[j]; a[j]=temp; } Arrays.sort(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 s=""; try { s=br.readLine(); } catch (IOException e) { e.printStackTrace(); } return s; } } long fact[]; long invFact[]; void init(int n) { fact=new long[n+1]; invFact=new long[n+1]; fact[0]=1; for(int i=1;i<=n;i++) { fact[i]=mul(i,fact[i-1]); } invFact[n]=power(fact[n],mod-2); for(int i=n-1;i>=0;i--) { invFact[i]=mul(invFact[i+1],i+1); } } long modInv(long x) { return power(x,mod-2); } long nCr(int n, int r) { if(n<r || r<0) return 0; return mul(fact[n],mul(invFact[r],invFact[n-r])); } long mul(long a, long b) { return a*b%mod; } long add(long a, long b) { return (a+b)%mod; } long power(long x, long y) { long gg=1; while(y>0) { if(y%2==1) gg=mul(gg,x); x=mul(x,x); y/=2; } return gg; } // Functions static long gcd(long a, long b) { return b==0?a:gcd(b,a%b); } static int gcd(int a, int b) { return b==0?a:gcd(b,a%b); } void print(int a[]) { int n=a.length; for(int i=0;i<n;i++) out.print(a[i]+" "); out.println(); } void print(long a[]) { int n=a.length; for(int i=0;i<n;i++) out.print(a[i]+" "); out.println(); } //Input Arrays static void input(long a[], int n) { for(int i=0;i<n;i++) { a[i]=inp.nextLong(); } } static void input(int a[], int n) { for(int i=0;i<n;i++) { a[i]=inp.nextInt(); } } static void input(String s[],int n) { for(int i=0;i<n;i++) { s[i]=inp.next(); } } static void input(int a[][], int n, int m) { for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { a[i][j]=inp.nextInt(); } } } static void input(long a[][], int n, int m) { for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { a[i][j]=inp.nextLong(); } } } }
Java
["1\n\n2\n\n-1"]
1 second
["? 1 2\n\n? 1 3\n\n? 1 4\n\n! 3"]
NoteIn the first example, the graph could look like this The lengths of the simple paths between all pairs of vertices in this case are $$$1$$$ or $$$2$$$. The first query finds out that one of the simple paths from vertex $$$1$$$ to vertex $$$2$$$ has a length of $$$1$$$. With the second query, we find out that one of the simple paths from vertex $$$1$$$ to vertex $$$3$$$ has length $$$2$$$. In the third query, we find out that vertex $$$4$$$ is not in the graph. Consequently, the size of the graph is $$$3$$$.
Java 11
standard input
[ "interactive", "probabilities" ]
8590f40e7509614694486165ee824587
null
1,800
null
standard output
PASSED
b25cf6e90a19d95eaf08913b0fb42498
train_110.jsonl
1662993300
This is an interactive problem.I want to play a game with you...We hid from you a cyclic graph of $$$n$$$ vertices ($$$3 \le n \le 10^{18}$$$). A cyclic graph is an undirected graph of $$$n$$$ vertices that form one cycle. Each vertex belongs to the cycle, i.e. the length of the cycle (the number of edges in it) is exactly $$$n$$$. The order of the vertices in the cycle is arbitrary.You can make queries in the following way: "? a b" where $$$1 \le a, b \le 10^{18}$$$ and $$$a \neq b$$$. In response to the query, the interactor outputs on a separate line the length of random of two paths from vertex $$$a$$$ to vertex $$$b$$$, or -1 if $$$\max(a, b) &gt; n$$$. The interactor chooses one of the two paths with equal probability. The length of the path —is the number of edges in it.You win if you guess the number of vertices in the hidden graph (number $$$n$$$) by making no more than $$$50$$$ queries.Note that the interactor is implemented in such a way that for any ordered pair $$$(a, b)$$$, it always returns the same value for query "? a b", no matter how many such queries. Note that the "? b a" query may be answered differently by the interactor.The vertices in the graph are randomly placed, and their positions are fixed in advance.Hacks are forbidden in this problem. The number of tests the jury has is $$$50$$$.
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 E{ 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 //for all the cases bro!! - should be simple enough no?? //playing with probablity at this point for sure long ans = 3; for(int i = 1; i <= 25; i++){ System.out.println("? " + (i + 1) + " " + (i + 2)); long val1 = sc.nextLong(); System.out.println("? " + (i + 2) + " " + (i + 1)); long val2 = sc.nextLong(); if(val1 == -1){ ans = i + 1; break; } if(val1 != val2){ ans = val1 + val2; break; }else{ ans = val1 + val2; } } System.out.println("! " + ans); 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
["1\n\n2\n\n-1"]
1 second
["? 1 2\n\n? 1 3\n\n? 1 4\n\n! 3"]
NoteIn the first example, the graph could look like this The lengths of the simple paths between all pairs of vertices in this case are $$$1$$$ or $$$2$$$. The first query finds out that one of the simple paths from vertex $$$1$$$ to vertex $$$2$$$ has a length of $$$1$$$. With the second query, we find out that one of the simple paths from vertex $$$1$$$ to vertex $$$3$$$ has length $$$2$$$. In the third query, we find out that vertex $$$4$$$ is not in the graph. Consequently, the size of the graph is $$$3$$$.
Java 11
standard input
[ "interactive", "probabilities" ]
8590f40e7509614694486165ee824587
null
1,800
null
standard output
PASSED
21ed757cf6c5a72d0c41789b9469b59a
train_110.jsonl
1662993300
This is an interactive problem.I want to play a game with you...We hid from you a cyclic graph of $$$n$$$ vertices ($$$3 \le n \le 10^{18}$$$). A cyclic graph is an undirected graph of $$$n$$$ vertices that form one cycle. Each vertex belongs to the cycle, i.e. the length of the cycle (the number of edges in it) is exactly $$$n$$$. The order of the vertices in the cycle is arbitrary.You can make queries in the following way: "? a b" where $$$1 \le a, b \le 10^{18}$$$ and $$$a \neq b$$$. In response to the query, the interactor outputs on a separate line the length of random of two paths from vertex $$$a$$$ to vertex $$$b$$$, or -1 if $$$\max(a, b) &gt; n$$$. The interactor chooses one of the two paths with equal probability. The length of the path —is the number of edges in it.You win if you guess the number of vertices in the hidden graph (number $$$n$$$) by making no more than $$$50$$$ queries.Note that the interactor is implemented in such a way that for any ordered pair $$$(a, b)$$$, it always returns the same value for query "? a b", no matter how many such queries. Note that the "? b a" query may be answered differently by the interactor.The vertices in the graph are randomly placed, and their positions are fixed in advance.Hacks are forbidden in this problem. The number of tests the jury has is $$$50$$$.
256 megabytes
import java.io.*; import java.lang.reflect.Array; import java.math.BigInteger; import java.util.*; public class Main { static PrintWriter w = new PrintWriter(new BufferedOutputStream(System.out)); public static void main(String[] args) throws IOException { FastScanner f = new FastScanner(); for (int i = 2; i <= 26; i++) { w.println("? " + 1 + " " + i); w.flush(); long a = f.nextLong(); if (a == -1) { w.println("! " + (i - 1)); w.flush(); break; } w.println("? " + i + " " + 1); w.flush(); long b = f.nextLong(); if (a != b) { w.println("! " + (a + b)); w.flush(); break; } } } private static class FastScanner { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; private FastScanner() throws IOException { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } private short nextShort() throws IOException { short ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do ret = (short) (ret * 10 + c - '0'); while ((c = read()) >= '0' && c <= '9'); if (neg) return (short) -ret; return ret; } private int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do ret = ret * 10 + c - '0'; while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do ret = ret * 10 + c - '0'; while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } private char nextChar() throws IOException { byte c = read(); while (c <= ' ') c = read(); return (char) c; } private String nextString() throws IOException { StringBuilder ret = new StringBuilder(); byte c = read(); while (c <= ' ') c = read(); do { ret.append((char) c); } while ((c = read()) > ' '); return ret.toString(); } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } } }
Java
["1\n\n2\n\n-1"]
1 second
["? 1 2\n\n? 1 3\n\n? 1 4\n\n! 3"]
NoteIn the first example, the graph could look like this The lengths of the simple paths between all pairs of vertices in this case are $$$1$$$ or $$$2$$$. The first query finds out that one of the simple paths from vertex $$$1$$$ to vertex $$$2$$$ has a length of $$$1$$$. With the second query, we find out that one of the simple paths from vertex $$$1$$$ to vertex $$$3$$$ has length $$$2$$$. In the third query, we find out that vertex $$$4$$$ is not in the graph. Consequently, the size of the graph is $$$3$$$.
Java 8
standard input
[ "interactive", "probabilities" ]
8590f40e7509614694486165ee824587
null
1,800
null
standard output
PASSED
ca98b221cbe3a19e87b32f0b84d2c624
train_110.jsonl
1662993300
This is an interactive problem.I want to play a game with you...We hid from you a cyclic graph of $$$n$$$ vertices ($$$3 \le n \le 10^{18}$$$). A cyclic graph is an undirected graph of $$$n$$$ vertices that form one cycle. Each vertex belongs to the cycle, i.e. the length of the cycle (the number of edges in it) is exactly $$$n$$$. The order of the vertices in the cycle is arbitrary.You can make queries in the following way: "? a b" where $$$1 \le a, b \le 10^{18}$$$ and $$$a \neq b$$$. In response to the query, the interactor outputs on a separate line the length of random of two paths from vertex $$$a$$$ to vertex $$$b$$$, or -1 if $$$\max(a, b) &gt; n$$$. The interactor chooses one of the two paths with equal probability. The length of the path —is the number of edges in it.You win if you guess the number of vertices in the hidden graph (number $$$n$$$) by making no more than $$$50$$$ queries.Note that the interactor is implemented in such a way that for any ordered pair $$$(a, b)$$$, it always returns the same value for query "? a b", no matter how many such queries. Note that the "? b a" query may be answered differently by the interactor.The vertices in the graph are randomly placed, and their positions are fixed in advance.Hacks are forbidden in this problem. The number of tests the jury has is $$$50$$$.
256 megabytes
import java.io.*; import java.lang.reflect.Array; import java.math.BigInteger; import java.util.*; public class Main { static PrintWriter w = new PrintWriter(new BufferedOutputStream(System.out)); public static void main(String[] args) throws IOException { FastScanner f = new FastScanner(); for (int i = 2; i <= 26; i++) { w.println("? " + 1 + " " + i); w.flush(); long a = f.nextLong(); if (a == -1) { w.println("! " + (i - 1)); w.flush(); w.close(); break; } w.println("? " + i + " " + 1); w.flush(); long b = f.nextLong(); if (a != b) { w.println("! " + (a + b)); w.flush(); w.close(); break; } } } private static class FastScanner { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; private FastScanner() throws IOException { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } private short nextShort() throws IOException { short ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do ret = (short) (ret * 10 + c - '0'); while ((c = read()) >= '0' && c <= '9'); if (neg) return (short) -ret; return ret; } private int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do ret = ret * 10 + c - '0'; while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do ret = ret * 10 + c - '0'; while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } private char nextChar() throws IOException { byte c = read(); while (c <= ' ') c = read(); return (char) c; } private String nextString() throws IOException { StringBuilder ret = new StringBuilder(); byte c = read(); while (c <= ' ') c = read(); do { ret.append((char) c); } while ((c = read()) > ' '); return ret.toString(); } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } } }
Java
["1\n\n2\n\n-1"]
1 second
["? 1 2\n\n? 1 3\n\n? 1 4\n\n! 3"]
NoteIn the first example, the graph could look like this The lengths of the simple paths between all pairs of vertices in this case are $$$1$$$ or $$$2$$$. The first query finds out that one of the simple paths from vertex $$$1$$$ to vertex $$$2$$$ has a length of $$$1$$$. With the second query, we find out that one of the simple paths from vertex $$$1$$$ to vertex $$$3$$$ has length $$$2$$$. In the third query, we find out that vertex $$$4$$$ is not in the graph. Consequently, the size of the graph is $$$3$$$.
Java 8
standard input
[ "interactive", "probabilities" ]
8590f40e7509614694486165ee824587
null
1,800
null
standard output
PASSED
31b27ac188fc2455d903b557754ec545
train_110.jsonl
1662993300
This is an interactive problem.I want to play a game with you...We hid from you a cyclic graph of $$$n$$$ vertices ($$$3 \le n \le 10^{18}$$$). A cyclic graph is an undirected graph of $$$n$$$ vertices that form one cycle. Each vertex belongs to the cycle, i.e. the length of the cycle (the number of edges in it) is exactly $$$n$$$. The order of the vertices in the cycle is arbitrary.You can make queries in the following way: "? a b" where $$$1 \le a, b \le 10^{18}$$$ and $$$a \neq b$$$. In response to the query, the interactor outputs on a separate line the length of random of two paths from vertex $$$a$$$ to vertex $$$b$$$, or -1 if $$$\max(a, b) &gt; n$$$. The interactor chooses one of the two paths with equal probability. The length of the path —is the number of edges in it.You win if you guess the number of vertices in the hidden graph (number $$$n$$$) by making no more than $$$50$$$ queries.Note that the interactor is implemented in such a way that for any ordered pair $$$(a, b)$$$, it always returns the same value for query "? a b", no matter how many such queries. Note that the "? b a" query may be answered differently by the interactor.The vertices in the graph are randomly placed, and their positions are fixed in advance.Hacks are forbidden in this problem. The number of tests the jury has is $$$50$$$.
256 megabytes
import java.io.BufferedOutputStream; import java.io.DataInputStream; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayDeque; public class dd { public static void main(String[] args) throws IOException { FastScanner scan = new FastScanner(); PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); long ans = 0; for (int i = 2; i <= 26; i++) { System.out.println("? " + 1 + " " + i); long a = scan.nextLong(); System.out.println("? " + i + " " + 1); long b = scan.nextLong(); if (a == -1) { ans = i - 1; break; } if (a != b) { ans = a + b; break; } } System.out.println("! " + ans); out.close(); } private static class FastScanner { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; private FastScanner() throws IOException { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } private short nextShort() throws IOException { short ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do ret = (short) (ret * 10 + c - '0'); while ((c = read()) >= '0' && c <= '9'); if (neg) return (short) -ret; return ret; } private int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do ret = ret * 10 + c - '0'; while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do ret = ret * 10 + c - '0'; while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } private char nextChar() throws IOException { byte c = read(); while (c <= ' ') c = read(); return (char) c; } private String nextString() throws IOException { StringBuilder ret = new StringBuilder(); byte c = read(); while (c <= ' ') c = read(); do { ret.append((char) c); } while ((c = read()) > ' '); return ret.toString(); } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } } }
Java
["1\n\n2\n\n-1"]
1 second
["? 1 2\n\n? 1 3\n\n? 1 4\n\n! 3"]
NoteIn the first example, the graph could look like this The lengths of the simple paths between all pairs of vertices in this case are $$$1$$$ or $$$2$$$. The first query finds out that one of the simple paths from vertex $$$1$$$ to vertex $$$2$$$ has a length of $$$1$$$. With the second query, we find out that one of the simple paths from vertex $$$1$$$ to vertex $$$3$$$ has length $$$2$$$. In the third query, we find out that vertex $$$4$$$ is not in the graph. Consequently, the size of the graph is $$$3$$$.
Java 8
standard input
[ "interactive", "probabilities" ]
8590f40e7509614694486165ee824587
null
1,800
null
standard output
PASSED
2bfb78991396fb36979fd52cbd779cb8
train_110.jsonl
1662993300
This is an interactive problem.I want to play a game with you...We hid from you a cyclic graph of $$$n$$$ vertices ($$$3 \le n \le 10^{18}$$$). A cyclic graph is an undirected graph of $$$n$$$ vertices that form one cycle. Each vertex belongs to the cycle, i.e. the length of the cycle (the number of edges in it) is exactly $$$n$$$. The order of the vertices in the cycle is arbitrary.You can make queries in the following way: "? a b" where $$$1 \le a, b \le 10^{18}$$$ and $$$a \neq b$$$. In response to the query, the interactor outputs on a separate line the length of random of two paths from vertex $$$a$$$ to vertex $$$b$$$, or -1 if $$$\max(a, b) &gt; n$$$. The interactor chooses one of the two paths with equal probability. The length of the path —is the number of edges in it.You win if you guess the number of vertices in the hidden graph (number $$$n$$$) by making no more than $$$50$$$ queries.Note that the interactor is implemented in such a way that for any ordered pair $$$(a, b)$$$, it always returns the same value for query "? a b", no matter how many such queries. Note that the "? b a" query may be answered differently by the interactor.The vertices in the graph are randomly placed, and their positions are fixed in advance.Hacks are forbidden in this problem. The number of tests the jury has is $$$50$$$.
256 megabytes
//some updates in import stuff import static java.lang.Math.max; import static java.lang.Math.min; import static java.lang.Math.abs; import java.util.*; import java.io.*; import java.math.*; //key points learned //max space ever that could be alloted in a program to pass in cf //int[][] prefixSum = new int[201][200_005]; -> not a single array more!!! //never allocate memory again again to such bigg array, it will give memory exceeded for sure //believe in your fucking solution and keep improving it!!! (sometimes) ///common mistakes // didn't read the question properly public class Main { public static void main(String[] args) throws IOException { FastScanner sc = new FastScanner(); //pretty important for sure - PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); //dope shit output for sure long ans = 3; for (int i = 2; i <= 26; i++) { System.out.println("? " + (1) + " " + (i)); long val1 = sc.nextLong(); System.out.println("? " + (i) + " " + (1)); long val2 = sc.nextLong(); if (val1 == -1) { ans = i - 1; break; } if (val1 != val2) { ans = val1 + val2; break; } } System.out.println("! " + ans); out.close(); } private static class FastScanner { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; private FastScanner() throws IOException { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } private short nextShort() throws IOException { short ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do ret = (short) (ret * 10 + c - '0'); while ((c = read()) >= '0' && c <= '9'); if (neg) return (short) -ret; return ret; } private int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do ret = ret * 10 + c - '0'; while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do ret = ret * 10 + c - '0'; while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } private char nextChar() throws IOException { byte c = read(); while (c <= ' ') c = read(); return (char) c; } private String nextString() throws IOException { StringBuilder ret = new StringBuilder(); byte c = read(); while (c <= ' ') c = read(); do { ret.append((char) c); } while ((c = read()) > ' '); return ret.toString(); } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } } }
Java
["1\n\n2\n\n-1"]
1 second
["? 1 2\n\n? 1 3\n\n? 1 4\n\n! 3"]
NoteIn the first example, the graph could look like this The lengths of the simple paths between all pairs of vertices in this case are $$$1$$$ or $$$2$$$. The first query finds out that one of the simple paths from vertex $$$1$$$ to vertex $$$2$$$ has a length of $$$1$$$. With the second query, we find out that one of the simple paths from vertex $$$1$$$ to vertex $$$3$$$ has length $$$2$$$. In the third query, we find out that vertex $$$4$$$ is not in the graph. Consequently, the size of the graph is $$$3$$$.
Java 8
standard input
[ "interactive", "probabilities" ]
8590f40e7509614694486165ee824587
null
1,800
null
standard output
PASSED
83caa6d9d3e289be664509a707d37d04
train_110.jsonl
1662993300
This is an interactive problem.I want to play a game with you...We hid from you a cyclic graph of $$$n$$$ vertices ($$$3 \le n \le 10^{18}$$$). A cyclic graph is an undirected graph of $$$n$$$ vertices that form one cycle. Each vertex belongs to the cycle, i.e. the length of the cycle (the number of edges in it) is exactly $$$n$$$. The order of the vertices in the cycle is arbitrary.You can make queries in the following way: "? a b" where $$$1 \le a, b \le 10^{18}$$$ and $$$a \neq b$$$. In response to the query, the interactor outputs on a separate line the length of random of two paths from vertex $$$a$$$ to vertex $$$b$$$, or -1 if $$$\max(a, b) &gt; n$$$. The interactor chooses one of the two paths with equal probability. The length of the path —is the number of edges in it.You win if you guess the number of vertices in the hidden graph (number $$$n$$$) by making no more than $$$50$$$ queries.Note that the interactor is implemented in such a way that for any ordered pair $$$(a, b)$$$, it always returns the same value for query "? a b", no matter how many such queries. Note that the "? b a" query may be answered differently by the interactor.The vertices in the graph are randomly placed, and their positions are fixed in advance.Hacks are forbidden in this problem. The number of tests the jury has is $$$50$$$.
256 megabytes
/* Goal: Become better in CP! Key: Consistency and Discipline Desire: SDE @ Google USA Motto: Do what i Love <=> Love what i do If you don't use your brain 100%, it deteriorates gradually */ import java.util.*; import java.io.*; import java.math.*; public class Coder { static StringBuffer str=new StringBuffer(); static BufferedReader bf; static PrintWriter pw; // Java is not = but it is equals() // C++ = does not work here always static void solve(int te) throws Exception{ long ans=3; for(int mid=2;mid<27;mid++){ System.out.println("? "+1+" "+mid); System.out.flush(); long d=Long.parseLong(bf.readLine().trim()); if(d!=-1){ System.out.println("? "+mid+" "+1); System.out.flush(); long e=Long.parseLong(bf.readLine().trim()); if(e!=d){ ans=d+e; break; } }else{ ans=mid-1; break; } } str.append("! ").append(ans); } public static void main(String[] args) throws java.lang.Exception { boolean lenv=false; if(lenv){ bf = new BufferedReader( new FileReader("input.txt")); pw=new PrintWriter(new BufferedWriter(new FileWriter("output.txt"))); }else{ bf = new BufferedReader(new InputStreamReader(System.in)); pw = new PrintWriter(new OutputStreamWriter(System.out)); } // int q1 = Integer.parseInt(bf.readLine().trim()); // for(int te=1;te<=q1;te++) { // solve(te); // } solve(1); pw.print(str); pw.flush(); // System.out.println(str); } }
Java
["1\n\n2\n\n-1"]
1 second
["? 1 2\n\n? 1 3\n\n? 1 4\n\n! 3"]
NoteIn the first example, the graph could look like this The lengths of the simple paths between all pairs of vertices in this case are $$$1$$$ or $$$2$$$. The first query finds out that one of the simple paths from vertex $$$1$$$ to vertex $$$2$$$ has a length of $$$1$$$. With the second query, we find out that one of the simple paths from vertex $$$1$$$ to vertex $$$3$$$ has length $$$2$$$. In the third query, we find out that vertex $$$4$$$ is not in the graph. Consequently, the size of the graph is $$$3$$$.
Java 8
standard input
[ "interactive", "probabilities" ]
8590f40e7509614694486165ee824587
null
1,800
null
standard output
PASSED
279700b4d713f4909dedfea002247af7
train_110.jsonl
1662993300
This is an interactive problem.I want to play a game with you...We hid from you a cyclic graph of $$$n$$$ vertices ($$$3 \le n \le 10^{18}$$$). A cyclic graph is an undirected graph of $$$n$$$ vertices that form one cycle. Each vertex belongs to the cycle, i.e. the length of the cycle (the number of edges in it) is exactly $$$n$$$. The order of the vertices in the cycle is arbitrary.You can make queries in the following way: "? a b" where $$$1 \le a, b \le 10^{18}$$$ and $$$a \neq b$$$. In response to the query, the interactor outputs on a separate line the length of random of two paths from vertex $$$a$$$ to vertex $$$b$$$, or -1 if $$$\max(a, b) &gt; n$$$. The interactor chooses one of the two paths with equal probability. The length of the path —is the number of edges in it.You win if you guess the number of vertices in the hidden graph (number $$$n$$$) by making no more than $$$50$$$ queries.Note that the interactor is implemented in such a way that for any ordered pair $$$(a, b)$$$, it always returns the same value for query "? a b", no matter how many such queries. Note that the "? b a" query may be answered differently by the interactor.The vertices in the graph are randomly placed, and their positions are fixed in advance.Hacks are forbidden in this problem. The number of tests the jury has is $$$50$$$.
256 megabytes
/* Goal: Become better in CP! Key: Consistency and Discipline Desire: SDE @ Google USA Motto: Do what i Love <=> Love what i do If you don't use your brain 100%, it deteriorates gradually */ import java.util.*; import java.io.*; import java.math.*; public class Coder { static StringBuffer str=new StringBuffer(); static BufferedReader bf; static PrintWriter pw; // Java is not = but it is equals() // C++ = does not work here always static void solve(int te) throws Exception{ long ans=3; for(int mid=2;mid<27;mid++){ System.out.println("? "+1+" "+mid); System.out.flush(); long d=Long.parseLong(bf.readLine().trim()); if(d!=-1){ System.out.println("? "+mid+" "+1); System.out.flush(); long e=Long.parseLong(bf.readLine().trim()); if(e!=d){ ans=d+e; break; } }else{ ans=mid-1; break; } } str.append("! ").append(ans).append("\n"); } public static void main(String[] args) throws java.lang.Exception { boolean lenv=false; if(lenv){ bf = new BufferedReader( new FileReader("input.txt")); pw=new PrintWriter(new BufferedWriter(new FileWriter("output.txt"))); }else{ bf = new BufferedReader(new InputStreamReader(System.in)); pw = new PrintWriter(new OutputStreamWriter(System.out)); } // int q1 = Integer.parseInt(bf.readLine().trim()); // for(int te=1;te<=q1;te++) { // solve(te); // } solve(1); pw.print(str); pw.flush(); // System.out.println(str); } }
Java
["1\n\n2\n\n-1"]
1 second
["? 1 2\n\n? 1 3\n\n? 1 4\n\n! 3"]
NoteIn the first example, the graph could look like this The lengths of the simple paths between all pairs of vertices in this case are $$$1$$$ or $$$2$$$. The first query finds out that one of the simple paths from vertex $$$1$$$ to vertex $$$2$$$ has a length of $$$1$$$. With the second query, we find out that one of the simple paths from vertex $$$1$$$ to vertex $$$3$$$ has length $$$2$$$. In the third query, we find out that vertex $$$4$$$ is not in the graph. Consequently, the size of the graph is $$$3$$$.
Java 8
standard input
[ "interactive", "probabilities" ]
8590f40e7509614694486165ee824587
null
1,800
null
standard output
PASSED
4fdc64f9c5f0689e89a7056d8e58bcc0
train_110.jsonl
1662993300
This is an interactive problem.I want to play a game with you...We hid from you a cyclic graph of $$$n$$$ vertices ($$$3 \le n \le 10^{18}$$$). A cyclic graph is an undirected graph of $$$n$$$ vertices that form one cycle. Each vertex belongs to the cycle, i.e. the length of the cycle (the number of edges in it) is exactly $$$n$$$. The order of the vertices in the cycle is arbitrary.You can make queries in the following way: "? a b" where $$$1 \le a, b \le 10^{18}$$$ and $$$a \neq b$$$. In response to the query, the interactor outputs on a separate line the length of random of two paths from vertex $$$a$$$ to vertex $$$b$$$, or -1 if $$$\max(a, b) &gt; n$$$. The interactor chooses one of the two paths with equal probability. The length of the path —is the number of edges in it.You win if you guess the number of vertices in the hidden graph (number $$$n$$$) by making no more than $$$50$$$ queries.Note that the interactor is implemented in such a way that for any ordered pair $$$(a, b)$$$, it always returns the same value for query "? a b", no matter how many such queries. Note that the "? b a" query may be answered differently by the interactor.The vertices in the graph are randomly placed, and their positions are fixed in advance.Hacks are forbidden in this problem. The number of tests the jury has is $$$50$$$.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Set; import java.util.TreeSet; public class Main { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); Set<Long> set = new TreeSet<>(); for(int i = 4; i < 4 + 25; i++) { long[] result = new long[2]; for (int j = 0; j < 2; j++) { System.out.println("? " + (j == 0 ? "1 " + i : i + " 1")); System.out.flush(); result[j] = Long.parseLong(br.readLine()); } if (result[0] == -1) { System.out.println("! " + (i - 1)); return; } else { if (result[0] != result[1]) { System.out.println("! " + (result[0] + result[1])); return; } } } } }
Java
["1\n\n2\n\n-1"]
1 second
["? 1 2\n\n? 1 3\n\n? 1 4\n\n! 3"]
NoteIn the first example, the graph could look like this The lengths of the simple paths between all pairs of vertices in this case are $$$1$$$ or $$$2$$$. The first query finds out that one of the simple paths from vertex $$$1$$$ to vertex $$$2$$$ has a length of $$$1$$$. With the second query, we find out that one of the simple paths from vertex $$$1$$$ to vertex $$$3$$$ has length $$$2$$$. In the third query, we find out that vertex $$$4$$$ is not in the graph. Consequently, the size of the graph is $$$3$$$.
Java 8
standard input
[ "interactive", "probabilities" ]
8590f40e7509614694486165ee824587
null
1,800
null
standard output
PASSED
45a73843429bc83c4058643f86fda67d
train_110.jsonl
1662993300
This is an interactive problem.I want to play a game with you...We hid from you a cyclic graph of $$$n$$$ vertices ($$$3 \le n \le 10^{18}$$$). A cyclic graph is an undirected graph of $$$n$$$ vertices that form one cycle. Each vertex belongs to the cycle, i.e. the length of the cycle (the number of edges in it) is exactly $$$n$$$. The order of the vertices in the cycle is arbitrary.You can make queries in the following way: "? a b" where $$$1 \le a, b \le 10^{18}$$$ and $$$a \neq b$$$. In response to the query, the interactor outputs on a separate line the length of random of two paths from vertex $$$a$$$ to vertex $$$b$$$, or -1 if $$$\max(a, b) &gt; n$$$. The interactor chooses one of the two paths with equal probability. The length of the path —is the number of edges in it.You win if you guess the number of vertices in the hidden graph (number $$$n$$$) by making no more than $$$50$$$ queries.Note that the interactor is implemented in such a way that for any ordered pair $$$(a, b)$$$, it always returns the same value for query "? a b", no matter how many such queries. Note that the "? b a" query may be answered differently by the interactor.The vertices in the graph are randomly placed, and their positions are fixed in advance.Hacks are forbidden in this problem. The number of tests the jury has is $$$50$$$.
256 megabytes
import java.io.*; import java.util.*; public class Main { static Main2 admin = new Main2(); public static void main(String[] args) { admin.start(); } } class Main2 { //---------------------------------INPUT READER-----------------------------------------// public BufferedReader br; StringTokenizer st = new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine());} catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int ni() { return Integer.parseInt(next()); } long nl() { return Long.parseLong(next()); } double nd() { return Double.parseDouble(next()); } String ns() { return next(); } int[] na(long n) {int[]ret=new int[(int)n]; for(int i=0;i<n;i++) ret[i]=ni(); return ret;} long[] nal(long n) {long[]ret=new long[(int)n]; for(int i=0;i<n;i++) ret[i]=nl(); return ret;} Integer[] nA(long n) {Integer[]ret=new Integer[(int)n]; for(int i=0;i<n;i++) ret[i]=ni(); return ret;} Long[] nAl(long n) {Long[]ret=new Long[(int)n]; for(int i=0;i<n;i++) ret[i]=nl(); return ret;} //--------------------------------------PRINTER------------------------------------------// PrintWriter w; void p(int i) {w.println(i);} void p(long l) {w.println(l);} void p(double d) {w.println(d);} void p(String s) { w.println(s);} void pr(int i) {w.print(i);} void pr(long l) {w.print(l);} void pr(double d) {w.print(d);} void pr(String s) { w.print(s);} void pl() {w.println();} //--------------------------------------VARIABLES-----------------------------------------// long lma = Long.MAX_VALUE, lmi = Long.MIN_VALUE; int ima = Integer.MAX_VALUE, imi = Integer.MIN_VALUE; long mod = 1000000007; { w = new PrintWriter(System.out, true); br = new BufferedReader(new InputStreamReader(System.in)); // try {if(new File(System.getProperty("user.dir")).getName().equals("Main_CP")) { // w = new PrintWriter(new OutputStreamWriter(new FileOutputStream("output.txt"))); // br = new BufferedReader(new InputStreamReader(new FileInputStream("input.txt")));} // } catch (Exception ignore) { } } //----------------------START---------------------// void start() { // int t = ni(); while(t-- > 0) solve(); w.close(); } long check(long mid, long r) { p("? "+mid+" "+r); return nl(); } void solve() { for(int i = 2; i < 27; i++) { long a = check(1, i); long b = check(i, 1); if(a == -1) { p("! "+(i-1)); return; } if(a != b) { long ans = a + b; p("! "+ans); return; } } long last = ((long) 1e18) + 1; p("! "+last); } }
Java
["1\n\n2\n\n-1"]
1 second
["? 1 2\n\n? 1 3\n\n? 1 4\n\n! 3"]
NoteIn the first example, the graph could look like this The lengths of the simple paths between all pairs of vertices in this case are $$$1$$$ or $$$2$$$. The first query finds out that one of the simple paths from vertex $$$1$$$ to vertex $$$2$$$ has a length of $$$1$$$. With the second query, we find out that one of the simple paths from vertex $$$1$$$ to vertex $$$3$$$ has length $$$2$$$. In the third query, we find out that vertex $$$4$$$ is not in the graph. Consequently, the size of the graph is $$$3$$$.
Java 8
standard input
[ "interactive", "probabilities" ]
8590f40e7509614694486165ee824587
null
1,800
null
standard output
PASSED
d1d108844e542c5a1a6ed9df3b6e8c5d
train_110.jsonl
1662993300
This is an interactive problem.I want to play a game with you...We hid from you a cyclic graph of $$$n$$$ vertices ($$$3 \le n \le 10^{18}$$$). A cyclic graph is an undirected graph of $$$n$$$ vertices that form one cycle. Each vertex belongs to the cycle, i.e. the length of the cycle (the number of edges in it) is exactly $$$n$$$. The order of the vertices in the cycle is arbitrary.You can make queries in the following way: "? a b" where $$$1 \le a, b \le 10^{18}$$$ and $$$a \neq b$$$. In response to the query, the interactor outputs on a separate line the length of random of two paths from vertex $$$a$$$ to vertex $$$b$$$, or -1 if $$$\max(a, b) &gt; n$$$. The interactor chooses one of the two paths with equal probability. The length of the path —is the number of edges in it.You win if you guess the number of vertices in the hidden graph (number $$$n$$$) by making no more than $$$50$$$ queries.Note that the interactor is implemented in such a way that for any ordered pair $$$(a, b)$$$, it always returns the same value for query "? a b", no matter how many such queries. Note that the "? b a" query may be answered differently by the interactor.The vertices in the graph are randomly placed, and their positions are fixed in advance.Hacks are forbidden in this problem. The number of tests the jury has is $$$50$$$.
256 megabytes
import java.io.*; import java.util.*; public class GuessTheCycleSize { public static void solve(FastIO io) { for (int guess = 2; ; ++guess) { long ab = query(io, 1, guess); if (ab < 0) { answer(io, guess - 1); return; } long ba = query(io, guess, 1); if (ab != ba) { answer(io, ab + ba); return; } } } private static long query(FastIO io, long a, long b) { io.println('?', a, b); io.flush(); return io.nextLong(); } private static void answer(FastIO io, long x) { io.println('!', x); io.flush(); } public static class FastIO { private InputStream reader; private PrintWriter writer; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public FastIO(InputStream r, OutputStream w) { reader = r; writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(w))); } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = reader.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public String nextString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } // TODO: read this byte-by-byte like the other read functions. public double nextDouble() { return Double.parseDouble(nextString()); } public int[] nextIntArray(int n) { return nextIntArray(n, 0); } public int[] nextIntArray(int n, int off) { int[] arr = new int[n + off]; for (int i = 0; i < n; i++) { arr[i + off] = nextInt(); } return arr; } public long[] nextLongArray(int n) { return nextLongArray(n, 0); } public long[] nextLongArray(int n, int off) { long[] arr = new long[n + off]; for (int i = 0; i < n; i++) { arr[i + off] = nextLong(); } return arr; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) { writer.print(' '); } writer.print(objects[i]); } } public void println(Object... objects) { print(objects); writer.println(); } public void printArray(int[] arr) { for (int i = 0; i < arr.length; i++) { if (i != 0) { writer.print(' '); } writer.print(arr[i]); } } public void printArray(long[] arr) { for (int i = 0; i < arr.length; i++) { if (i != 0) { writer.print(' '); } writer.print(arr[i]); } } public void printlnArray(int[] arr) { printArray(arr); writer.println(); } public void printlnArray(long[] arr) { printArray(arr); writer.println(); } public void printf(String format, Object... args) { print(String.format(format, args)); } public void flush() { writer.flush(); } } public static void main(String[] args) { FastIO io = new FastIO(System.in, System.out); solve(io); io.flush(); } }
Java
["1\n\n2\n\n-1"]
1 second
["? 1 2\n\n? 1 3\n\n? 1 4\n\n! 3"]
NoteIn the first example, the graph could look like this The lengths of the simple paths between all pairs of vertices in this case are $$$1$$$ or $$$2$$$. The first query finds out that one of the simple paths from vertex $$$1$$$ to vertex $$$2$$$ has a length of $$$1$$$. With the second query, we find out that one of the simple paths from vertex $$$1$$$ to vertex $$$3$$$ has length $$$2$$$. In the third query, we find out that vertex $$$4$$$ is not in the graph. Consequently, the size of the graph is $$$3$$$.
Java 8
standard input
[ "interactive", "probabilities" ]
8590f40e7509614694486165ee824587
null
1,800
null
standard output
PASSED
71f10dd9564b14d395d56c2e612a77ea
train_110.jsonl
1662993300
This is an interactive problem.I want to play a game with you...We hid from you a cyclic graph of $$$n$$$ vertices ($$$3 \le n \le 10^{18}$$$). A cyclic graph is an undirected graph of $$$n$$$ vertices that form one cycle. Each vertex belongs to the cycle, i.e. the length of the cycle (the number of edges in it) is exactly $$$n$$$. The order of the vertices in the cycle is arbitrary.You can make queries in the following way: "? a b" where $$$1 \le a, b \le 10^{18}$$$ and $$$a \neq b$$$. In response to the query, the interactor outputs on a separate line the length of random of two paths from vertex $$$a$$$ to vertex $$$b$$$, or -1 if $$$\max(a, b) &gt; n$$$. The interactor chooses one of the two paths with equal probability. The length of the path —is the number of edges in it.You win if you guess the number of vertices in the hidden graph (number $$$n$$$) by making no more than $$$50$$$ queries.Note that the interactor is implemented in such a way that for any ordered pair $$$(a, b)$$$, it always returns the same value for query "? a b", no matter how many such queries. Note that the "? b a" query may be answered differently by the interactor.The vertices in the graph are randomly placed, and their positions are fixed in advance.Hacks are forbidden in this problem. The number of tests the jury has is $$$50$$$.
256 megabytes
import java.io.*; import java.util.*; public class GuessTheCycleSize { public static void solve(FastIO io) { for (int guess = 2; ; ++guess) { long ab = query(io, 1, guess); if (ab < 0) { answer(io, guess - 1); return; } long ba = query(io, guess, 1); if (ab != ba) { answer(io, ab + ba); return; } } } private static long query(FastIO io, long a, long b) { io.println('?', a, b); io.flush(); return io.nextLong(); } private static void answer(FastIO io, long x) { io.println('!', x); io.flush(); } public static class CountMap<T> extends HashMap<T, Long> { private static final long serialVersionUID = -1169361115679860426L; public long getCount(T k) { return getOrDefault(k, 0L); } public void increment(T k, int v) { long next = getCount(k) + v; if (next == 0) { remove(k); } else { put(k, next); } } } public static class BinarySearch { // Finds the left-most value that satisfies the IntCheck in the range [L, R). // It will return R if the nothing in the range satisfies the check. public static int firstThat(int L, int R, IntCheck check) { while (L < R) { int M = (L >> 1) + (R >> 1) + (L & R & 1); if (check.valid(M)) { R = M; } else { L = M + 1; } } return L; } // Finds the right-most value that satisfies the IntCheck in the range [L, R). // It will return L - 1 if nothing in the range satisfies the check. public static int lastThat(int L, int R, IntCheck check) { int firstValue = firstThat(L, R, new IntCheck() { @Override public boolean valid(int value) { return !check.valid(value); } }); return firstValue - 1; } // Finds the left-most value that satisfies the LongCheck in the range [L, R). public static long firstThat(long L, long R, LongCheck check) { while (L < R) { long M = (L >> 1) + (R >> 1) + (L & R & 1); if (check.valid(M)) { R = M; } else { L = M + 1; } } return L; } // Finds the right-most value that satisfies the IntCheck in the range [L, R). // It will return L - 1 if nothing in the range satisfies the check. public static long lastThat(long L, long R, LongCheck check) { long firstValue = firstThat(L, R, new LongCheck() { @Override public boolean valid(long value) { return !check.valid(value); } }); return firstValue - 1; } public static interface LongCheck { public boolean valid(long value); } public static interface IntCheck { public boolean valid(int value); } } public static class FastIO { private InputStream reader; private PrintWriter writer; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public FastIO(InputStream r, OutputStream w) { reader = r; writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(w))); } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = reader.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public String nextString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } // TODO: read this byte-by-byte like the other read functions. public double nextDouble() { return Double.parseDouble(nextString()); } public int[] nextIntArray(int n) { return nextIntArray(n, 0); } public int[] nextIntArray(int n, int off) { int[] arr = new int[n + off]; for (int i = 0; i < n; i++) { arr[i + off] = nextInt(); } return arr; } public long[] nextLongArray(int n) { return nextLongArray(n, 0); } public long[] nextLongArray(int n, int off) { long[] arr = new long[n + off]; for (int i = 0; i < n; i++) { arr[i + off] = nextLong(); } return arr; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) { writer.print(' '); } writer.print(objects[i]); } } public void println(Object... objects) { print(objects); writer.println(); } public void printArray(int[] arr) { for (int i = 0; i < arr.length; i++) { if (i != 0) { writer.print(' '); } writer.print(arr[i]); } } public void printArray(long[] arr) { for (int i = 0; i < arr.length; i++) { if (i != 0) { writer.print(' '); } writer.print(arr[i]); } } public void printlnArray(int[] arr) { printArray(arr); writer.println(); } public void printlnArray(long[] arr) { printArray(arr); writer.println(); } public void printf(String format, Object... args) { print(String.format(format, args)); } public void flush() { writer.flush(); } } public static void main(String[] args) { FastIO io = new FastIO(System.in, System.out); solve(io); io.flush(); } }
Java
["1\n\n2\n\n-1"]
1 second
["? 1 2\n\n? 1 3\n\n? 1 4\n\n! 3"]
NoteIn the first example, the graph could look like this The lengths of the simple paths between all pairs of vertices in this case are $$$1$$$ or $$$2$$$. The first query finds out that one of the simple paths from vertex $$$1$$$ to vertex $$$2$$$ has a length of $$$1$$$. With the second query, we find out that one of the simple paths from vertex $$$1$$$ to vertex $$$3$$$ has length $$$2$$$. In the third query, we find out that vertex $$$4$$$ is not in the graph. Consequently, the size of the graph is $$$3$$$.
Java 8
standard input
[ "interactive", "probabilities" ]
8590f40e7509614694486165ee824587
null
1,800
null
standard output
PASSED
bb90044e80859f5e1ab93234b304edae
train_110.jsonl
1662993300
This is an interactive problem.I want to play a game with you...We hid from you a cyclic graph of $$$n$$$ vertices ($$$3 \le n \le 10^{18}$$$). A cyclic graph is an undirected graph of $$$n$$$ vertices that form one cycle. Each vertex belongs to the cycle, i.e. the length of the cycle (the number of edges in it) is exactly $$$n$$$. The order of the vertices in the cycle is arbitrary.You can make queries in the following way: "? a b" where $$$1 \le a, b \le 10^{18}$$$ and $$$a \neq b$$$. In response to the query, the interactor outputs on a separate line the length of random of two paths from vertex $$$a$$$ to vertex $$$b$$$, or -1 if $$$\max(a, b) &gt; n$$$. The interactor chooses one of the two paths with equal probability. The length of the path —is the number of edges in it.You win if you guess the number of vertices in the hidden graph (number $$$n$$$) by making no more than $$$50$$$ queries.Note that the interactor is implemented in such a way that for any ordered pair $$$(a, b)$$$, it always returns the same value for query "? a b", no matter how many such queries. Note that the "? b a" query may be answered differently by the interactor.The vertices in the graph are randomly placed, and their positions are fixed in advance.Hacks are forbidden in this problem. The number of tests the jury has is $$$50$$$.
256 megabytes
import java.io.*; import java.math.*; import java.util.*; public class GuessTheCycleSize { private static final int GUESSES = 30; private static final int MAX_QUERIES = 50; private static final long N_MAX = 1_000_000_000_000_000_000L; private static final Random RNG = new Random(); public static void solve(FastIO io) { ArrayList<Long> diffs = new ArrayList<>(); CountMap<Long> cm = new CountMap<>(); long guessPairs = MAX_QUERIES >> 1; for (int g = 0; g < guessPairs; ++g) { int guess = g + 2; long ab = query(io, 1, guess); if (ab < 0) { answer(io, guess - 1); return; } long ba = query(io, guess, 1); if (ab != ba) { answer(io, ab + ba); return; } } answer(io, -1); } private static long query(FastIO io, long a, long b) { io.println('?', a, b); io.flush(); return io.nextLong(); } private static void answer(FastIO io, long x) { io.println('!', x); io.flush(); } public static class CountMap<T> extends HashMap<T, Long> { private static final long serialVersionUID = -1169361115679860426L; public long getCount(T k) { return getOrDefault(k, 0L); } public void increment(T k, int v) { long next = getCount(k) + v; if (next == 0) { remove(k); } else { put(k, next); } } } public static class BinarySearch { // Finds the left-most value that satisfies the IntCheck in the range [L, R). // It will return R if the nothing in the range satisfies the check. public static int firstThat(int L, int R, IntCheck check) { while (L < R) { int M = (L >> 1) + (R >> 1) + (L & R & 1); if (check.valid(M)) { R = M; } else { L = M + 1; } } return L; } // Finds the right-most value that satisfies the IntCheck in the range [L, R). // It will return L - 1 if nothing in the range satisfies the check. public static int lastThat(int L, int R, IntCheck check) { int firstValue = firstThat(L, R, new IntCheck() { @Override public boolean valid(int value) { return !check.valid(value); } }); return firstValue - 1; } // Finds the left-most value that satisfies the LongCheck in the range [L, R). public static long firstThat(long L, long R, LongCheck check) { while (L < R) { long M = (L >> 1) + (R >> 1) + (L & R & 1); if (check.valid(M)) { R = M; } else { L = M + 1; } } return L; } // Finds the right-most value that satisfies the IntCheck in the range [L, R). // It will return L - 1 if nothing in the range satisfies the check. public static long lastThat(long L, long R, LongCheck check) { long firstValue = firstThat(L, R, new LongCheck() { @Override public boolean valid(long value) { return !check.valid(value); } }); return firstValue - 1; } public static interface LongCheck { public boolean valid(long value); } public static interface IntCheck { public boolean valid(int value); } } public static class FastIO { private InputStream reader; private PrintWriter writer; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public FastIO(InputStream r, OutputStream w) { reader = r; writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(w))); } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = reader.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public String nextString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } // TODO: read this byte-by-byte like the other read functions. public double nextDouble() { return Double.parseDouble(nextString()); } public int[] nextIntArray(int n) { return nextIntArray(n, 0); } public int[] nextIntArray(int n, int off) { int[] arr = new int[n + off]; for (int i = 0; i < n; i++) { arr[i + off] = nextInt(); } return arr; } public long[] nextLongArray(int n) { return nextLongArray(n, 0); } public long[] nextLongArray(int n, int off) { long[] arr = new long[n + off]; for (int i = 0; i < n; i++) { arr[i + off] = nextLong(); } return arr; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) { writer.print(' '); } writer.print(objects[i]); } } public void println(Object... objects) { print(objects); writer.println(); } public void printArray(int[] arr) { for (int i = 0; i < arr.length; i++) { if (i != 0) { writer.print(' '); } writer.print(arr[i]); } } public void printArray(long[] arr) { for (int i = 0; i < arr.length; i++) { if (i != 0) { writer.print(' '); } writer.print(arr[i]); } } public void printlnArray(int[] arr) { printArray(arr); writer.println(); } public void printlnArray(long[] arr) { printArray(arr); writer.println(); } public void printf(String format, Object... args) { print(String.format(format, args)); } public void flush() { writer.flush(); } } public static void main(String[] args) { FastIO io = new FastIO(System.in, System.out); solve(io); io.flush(); } }
Java
["1\n\n2\n\n-1"]
1 second
["? 1 2\n\n? 1 3\n\n? 1 4\n\n! 3"]
NoteIn the first example, the graph could look like this The lengths of the simple paths between all pairs of vertices in this case are $$$1$$$ or $$$2$$$. The first query finds out that one of the simple paths from vertex $$$1$$$ to vertex $$$2$$$ has a length of $$$1$$$. With the second query, we find out that one of the simple paths from vertex $$$1$$$ to vertex $$$3$$$ has length $$$2$$$. In the third query, we find out that vertex $$$4$$$ is not in the graph. Consequently, the size of the graph is $$$3$$$.
Java 8
standard input
[ "interactive", "probabilities" ]
8590f40e7509614694486165ee824587
null
1,800
null
standard output
PASSED
6ea375c38ee7784bf9518c19525e217f
train_110.jsonl
1662993300
This is an interactive problem.I want to play a game with you...We hid from you a cyclic graph of $$$n$$$ vertices ($$$3 \le n \le 10^{18}$$$). A cyclic graph is an undirected graph of $$$n$$$ vertices that form one cycle. Each vertex belongs to the cycle, i.e. the length of the cycle (the number of edges in it) is exactly $$$n$$$. The order of the vertices in the cycle is arbitrary.You can make queries in the following way: "? a b" where $$$1 \le a, b \le 10^{18}$$$ and $$$a \neq b$$$. In response to the query, the interactor outputs on a separate line the length of random of two paths from vertex $$$a$$$ to vertex $$$b$$$, or -1 if $$$\max(a, b) &gt; n$$$. The interactor chooses one of the two paths with equal probability. The length of the path —is the number of edges in it.You win if you guess the number of vertices in the hidden graph (number $$$n$$$) by making no more than $$$50$$$ queries.Note that the interactor is implemented in such a way that for any ordered pair $$$(a, b)$$$, it always returns the same value for query "? a b", no matter how many such queries. Note that the "? b a" query may be answered differently by the interactor.The vertices in the graph are randomly placed, and their positions are fixed in advance.Hacks are forbidden in this problem. The number of tests the jury has is $$$50$$$.
256 megabytes
import java.io.*; import java.math.*; import java.util.*; public class GuessTheCycleSize { private static final int GUESSES = 30; private static final int MAX_QUERIES = 50; private static final long N_MAX = 1_000_000_000_000_000_000L; private static final Random RNG = new Random(); public static void solve(FastIO io) { // long lowerBound = N_MAX; // for (int g = 0; g < GUESSES; ++g) { // long upper = lowerBound - 1; // long guess = RNG.nextLong() % upper; // if (guess < 0) { // guess += upper; // } // guess += 2; // // long result = query(io, 1, guess); // lowerBound = Math.min(lowerBound, guess); // } ArrayList<Long> sames = new ArrayList<>(); ArrayList<Long> diffs = new ArrayList<>(); CountMap<Long> cm = new CountMap<>(); long guessPairs = MAX_QUERIES >> 1; for (int g = 0; g < guessPairs; ++g) { int guess = g + 2; long ab = query(io, 1, guess); if (ab < 0) { answer(io, guess - 1); return; } long ba = query(io, guess, 1); if (ab != ba) { answer(io, ab + ba); return; } sames.add(ab + ba); } Collections.sort(sames); answer(io, Math.max(3, sames.get(sames.size() >> 1))); // if (!diffs.isEmpty()) { // answer(io, diffs.get(0)); // } else { // answer(io, sames.get(0)); // } // long upperBound = Math.min(N_MAX, lowerBound); // while (upperBound < N_MAX) { // // } // upperBound = Math.min(upperBound, N_MAX); } private static long query(FastIO io, long a, long b) { io.println('?', a, b); io.flush(); return io.nextLong(); } private static void answer(FastIO io, long x) { io.println('!', x); io.flush(); } public static class CountMap<T> extends HashMap<T, Long> { private static final long serialVersionUID = -1169361115679860426L; public long getCount(T k) { return getOrDefault(k, 0L); } public void increment(T k, int v) { long next = getCount(k) + v; if (next == 0) { remove(k); } else { put(k, next); } } } public static class BinarySearch { // Finds the left-most value that satisfies the IntCheck in the range [L, R). // It will return R if the nothing in the range satisfies the check. public static int firstThat(int L, int R, IntCheck check) { while (L < R) { int M = (L >> 1) + (R >> 1) + (L & R & 1); if (check.valid(M)) { R = M; } else { L = M + 1; } } return L; } // Finds the right-most value that satisfies the IntCheck in the range [L, R). // It will return L - 1 if nothing in the range satisfies the check. public static int lastThat(int L, int R, IntCheck check) { int firstValue = firstThat(L, R, new IntCheck() { @Override public boolean valid(int value) { return !check.valid(value); } }); return firstValue - 1; } // Finds the left-most value that satisfies the LongCheck in the range [L, R). public static long firstThat(long L, long R, LongCheck check) { while (L < R) { long M = (L >> 1) + (R >> 1) + (L & R & 1); if (check.valid(M)) { R = M; } else { L = M + 1; } } return L; } // Finds the right-most value that satisfies the IntCheck in the range [L, R). // It will return L - 1 if nothing in the range satisfies the check. public static long lastThat(long L, long R, LongCheck check) { long firstValue = firstThat(L, R, new LongCheck() { @Override public boolean valid(long value) { return !check.valid(value); } }); return firstValue - 1; } public static interface LongCheck { public boolean valid(long value); } public static interface IntCheck { public boolean valid(int value); } } public static class FastIO { private InputStream reader; private PrintWriter writer; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public FastIO(InputStream r, OutputStream w) { reader = r; writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(w))); } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = reader.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public String nextString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } // TODO: read this byte-by-byte like the other read functions. public double nextDouble() { return Double.parseDouble(nextString()); } public int[] nextIntArray(int n) { return nextIntArray(n, 0); } public int[] nextIntArray(int n, int off) { int[] arr = new int[n + off]; for (int i = 0; i < n; i++) { arr[i + off] = nextInt(); } return arr; } public long[] nextLongArray(int n) { return nextLongArray(n, 0); } public long[] nextLongArray(int n, int off) { long[] arr = new long[n + off]; for (int i = 0; i < n; i++) { arr[i + off] = nextLong(); } return arr; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) { writer.print(' '); } writer.print(objects[i]); } } public void println(Object... objects) { print(objects); writer.println(); } public void printArray(int[] arr) { for (int i = 0; i < arr.length; i++) { if (i != 0) { writer.print(' '); } writer.print(arr[i]); } } public void printArray(long[] arr) { for (int i = 0; i < arr.length; i++) { if (i != 0) { writer.print(' '); } writer.print(arr[i]); } } public void printlnArray(int[] arr) { printArray(arr); writer.println(); } public void printlnArray(long[] arr) { printArray(arr); writer.println(); } public void printf(String format, Object... args) { print(String.format(format, args)); } public void flush() { writer.flush(); } } public static void main(String[] args) { FastIO io = new FastIO(System.in, System.out); solve(io); io.flush(); } }
Java
["1\n\n2\n\n-1"]
1 second
["? 1 2\n\n? 1 3\n\n? 1 4\n\n! 3"]
NoteIn the first example, the graph could look like this The lengths of the simple paths between all pairs of vertices in this case are $$$1$$$ or $$$2$$$. The first query finds out that one of the simple paths from vertex $$$1$$$ to vertex $$$2$$$ has a length of $$$1$$$. With the second query, we find out that one of the simple paths from vertex $$$1$$$ to vertex $$$3$$$ has length $$$2$$$. In the third query, we find out that vertex $$$4$$$ is not in the graph. Consequently, the size of the graph is $$$3$$$.
Java 8
standard input
[ "interactive", "probabilities" ]
8590f40e7509614694486165ee824587
null
1,800
null
standard output
PASSED
7205807f6998fb361b3620866956cf3a
train_110.jsonl
1662993300
This is an interactive problem.I want to play a game with you...We hid from you a cyclic graph of $$$n$$$ vertices ($$$3 \le n \le 10^{18}$$$). A cyclic graph is an undirected graph of $$$n$$$ vertices that form one cycle. Each vertex belongs to the cycle, i.e. the length of the cycle (the number of edges in it) is exactly $$$n$$$. The order of the vertices in the cycle is arbitrary.You can make queries in the following way: "? a b" where $$$1 \le a, b \le 10^{18}$$$ and $$$a \neq b$$$. In response to the query, the interactor outputs on a separate line the length of random of two paths from vertex $$$a$$$ to vertex $$$b$$$, or -1 if $$$\max(a, b) &gt; n$$$. The interactor chooses one of the two paths with equal probability. The length of the path —is the number of edges in it.You win if you guess the number of vertices in the hidden graph (number $$$n$$$) by making no more than $$$50$$$ queries.Note that the interactor is implemented in such a way that for any ordered pair $$$(a, b)$$$, it always returns the same value for query "? a b", no matter how many such queries. Note that the "? b a" query may be answered differently by the interactor.The vertices in the graph are randomly placed, and their positions are fixed in advance.Hacks are forbidden in this problem. The number of tests the jury has is $$$50$$$.
256 megabytes
//package kg.my_algorithms.Codeforces; /* If you can't Calculate, then Stimulate */ import java.util.*; import java.io.*; public class Solution { public static void main(String[] args) throws IOException { FastReader fr = new FastReader(); // BufferedWriter output = new BufferedWriter(new OutputStreamWriter(System.out)); // StringBuilder sb = new StringBuilder(); // output.write(sb.toString()); // output.flush(); for(int i=1;i<=25;i++){ long path1 = helper(1,i+1,fr); long path2 = helper(i+1,1,fr); if(path2!=path1){ System.out.println("! " + (path1+path2)); break; } if(path1==-1) { System.out.println("! 4"); break; } } System.out.flush(); } private static long helper(long a, long b, FastReader fr){ System.out.println("? "+a+" " + b); long res = fr.nextLong(); return res; } } //Fast Input 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
["1\n\n2\n\n-1"]
1 second
["? 1 2\n\n? 1 3\n\n? 1 4\n\n! 3"]
NoteIn the first example, the graph could look like this The lengths of the simple paths between all pairs of vertices in this case are $$$1$$$ or $$$2$$$. The first query finds out that one of the simple paths from vertex $$$1$$$ to vertex $$$2$$$ has a length of $$$1$$$. With the second query, we find out that one of the simple paths from vertex $$$1$$$ to vertex $$$3$$$ has length $$$2$$$. In the third query, we find out that vertex $$$4$$$ is not in the graph. Consequently, the size of the graph is $$$3$$$.
Java 8
standard input
[ "interactive", "probabilities" ]
8590f40e7509614694486165ee824587
null
1,800
null
standard output
PASSED
92fccd2f418670dacedeb9c48bae0142
train_110.jsonl
1662993300
This is an interactive problem.I want to play a game with you...We hid from you a cyclic graph of $$$n$$$ vertices ($$$3 \le n \le 10^{18}$$$). A cyclic graph is an undirected graph of $$$n$$$ vertices that form one cycle. Each vertex belongs to the cycle, i.e. the length of the cycle (the number of edges in it) is exactly $$$n$$$. The order of the vertices in the cycle is arbitrary.You can make queries in the following way: "? a b" where $$$1 \le a, b \le 10^{18}$$$ and $$$a \neq b$$$. In response to the query, the interactor outputs on a separate line the length of random of two paths from vertex $$$a$$$ to vertex $$$b$$$, or -1 if $$$\max(a, b) &gt; n$$$. The interactor chooses one of the two paths with equal probability. The length of the path —is the number of edges in it.You win if you guess the number of vertices in the hidden graph (number $$$n$$$) by making no more than $$$50$$$ queries.Note that the interactor is implemented in such a way that for any ordered pair $$$(a, b)$$$, it always returns the same value for query "? a b", no matter how many such queries. Note that the "? b a" query may be answered differently by the interactor.The vertices in the graph are randomly placed, and their positions are fixed in advance.Hacks are forbidden in this problem. The number of tests the jury has is $$$50$$$.
256 megabytes
/*========================================================================== * AUTHOR: RonWonWon * CREATED: 12.09.2022 19:59:11 /*==========================================================================*/ import java.io.*; import java.util.*; public class E { public static void main(String[] args) throws IOException { long ans = 0; for(int i=2;i<=26;i++){ out.println("? 1 "+i); out.flush(); long x = -1, y = -1, z = 0; z = in.nextLong(); if(z==-1){ ans = i-1; break; } x = z; out.println("? "+i+" "+1); out.flush(); z = in.nextLong(); y = z; if(x!=y){ ans = x+y; break; } } out.println("! "+ans); 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
["1\n\n2\n\n-1"]
1 second
["? 1 2\n\n? 1 3\n\n? 1 4\n\n! 3"]
NoteIn the first example, the graph could look like this The lengths of the simple paths between all pairs of vertices in this case are $$$1$$$ or $$$2$$$. The first query finds out that one of the simple paths from vertex $$$1$$$ to vertex $$$2$$$ has a length of $$$1$$$. With the second query, we find out that one of the simple paths from vertex $$$1$$$ to vertex $$$3$$$ has length $$$2$$$. In the third query, we find out that vertex $$$4$$$ is not in the graph. Consequently, the size of the graph is $$$3$$$.
Java 8
standard input
[ "interactive", "probabilities" ]
8590f40e7509614694486165ee824587
null
1,800
null
standard output
PASSED
773db135a9cb248b76127eecd0dd1965
train_110.jsonl
1662993300
This is an interactive problem.I want to play a game with you...We hid from you a cyclic graph of $$$n$$$ vertices ($$$3 \le n \le 10^{18}$$$). A cyclic graph is an undirected graph of $$$n$$$ vertices that form one cycle. Each vertex belongs to the cycle, i.e. the length of the cycle (the number of edges in it) is exactly $$$n$$$. The order of the vertices in the cycle is arbitrary.You can make queries in the following way: "? a b" where $$$1 \le a, b \le 10^{18}$$$ and $$$a \neq b$$$. In response to the query, the interactor outputs on a separate line the length of random of two paths from vertex $$$a$$$ to vertex $$$b$$$, or -1 if $$$\max(a, b) &gt; n$$$. The interactor chooses one of the two paths with equal probability. The length of the path —is the number of edges in it.You win if you guess the number of vertices in the hidden graph (number $$$n$$$) by making no more than $$$50$$$ queries.Note that the interactor is implemented in such a way that for any ordered pair $$$(a, b)$$$, it always returns the same value for query "? a b", no matter how many such queries. Note that the "? b a" query may be answered differently by the interactor.The vertices in the graph are randomly placed, and their positions are fixed in advance.Hacks are forbidden in this problem. The number of tests the jury has is $$$50$$$.
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(); for (int i = 2; true; i++) { System.out.println("? 1 " + i); long first = input.nextLong(); if (first == -1) { System.out.println("! " + (i - 1)); return; } System.out.println("? " + i + " 1"); long last = input.nextLong(); if (first != last) { System.out.println("! " + (first + last)); return; } } } 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
["1\n\n2\n\n-1"]
1 second
["? 1 2\n\n? 1 3\n\n? 1 4\n\n! 3"]
NoteIn the first example, the graph could look like this The lengths of the simple paths between all pairs of vertices in this case are $$$1$$$ or $$$2$$$. The first query finds out that one of the simple paths from vertex $$$1$$$ to vertex $$$2$$$ has a length of $$$1$$$. With the second query, we find out that one of the simple paths from vertex $$$1$$$ to vertex $$$3$$$ has length $$$2$$$. In the third query, we find out that vertex $$$4$$$ is not in the graph. Consequently, the size of the graph is $$$3$$$.
Java 8
standard input
[ "interactive", "probabilities" ]
8590f40e7509614694486165ee824587
null
1,800
null
standard output
PASSED
7178ebc70740f49329f462a00d7cfe7f
train_110.jsonl
1662993300
This is an interactive problem.I want to play a game with you...We hid from you a cyclic graph of $$$n$$$ vertices ($$$3 \le n \le 10^{18}$$$). A cyclic graph is an undirected graph of $$$n$$$ vertices that form one cycle. Each vertex belongs to the cycle, i.e. the length of the cycle (the number of edges in it) is exactly $$$n$$$. The order of the vertices in the cycle is arbitrary.You can make queries in the following way: "? a b" where $$$1 \le a, b \le 10^{18}$$$ and $$$a \neq b$$$. In response to the query, the interactor outputs on a separate line the length of random of two paths from vertex $$$a$$$ to vertex $$$b$$$, or -1 if $$$\max(a, b) &gt; n$$$. The interactor chooses one of the two paths with equal probability. The length of the path —is the number of edges in it.You win if you guess the number of vertices in the hidden graph (number $$$n$$$) by making no more than $$$50$$$ queries.Note that the interactor is implemented in such a way that for any ordered pair $$$(a, b)$$$, it always returns the same value for query "? a b", no matter how many such queries. Note that the "? b a" query may be answered differently by the interactor.The vertices in the graph are randomly placed, and their positions are fixed in advance.Hacks are forbidden in this problem. The number of tests the jury has is $$$50$$$.
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(); for (int i=2; true; i++) { System.out.println("? 1 "+i); long a=input.nextLong(); if (a==-1) { System.out.println("! "+(i-1)); return; } System.out.println("? "+i+" 1"); long b=input.nextLong(); if (a!=b) { System.out.println("! "+(a+b)); return; } } } 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
["1\n\n2\n\n-1"]
1 second
["? 1 2\n\n? 1 3\n\n? 1 4\n\n! 3"]
NoteIn the first example, the graph could look like this The lengths of the simple paths between all pairs of vertices in this case are $$$1$$$ or $$$2$$$. The first query finds out that one of the simple paths from vertex $$$1$$$ to vertex $$$2$$$ has a length of $$$1$$$. With the second query, we find out that one of the simple paths from vertex $$$1$$$ to vertex $$$3$$$ has length $$$2$$$. In the third query, we find out that vertex $$$4$$$ is not in the graph. Consequently, the size of the graph is $$$3$$$.
Java 8
standard input
[ "interactive", "probabilities" ]
8590f40e7509614694486165ee824587
null
1,800
null
standard output
PASSED
4e9753fd12d87a32b7abb75513d9effb
train_110.jsonl
1662993300
This is an interactive problem.I want to play a game with you...We hid from you a cyclic graph of $$$n$$$ vertices ($$$3 \le n \le 10^{18}$$$). A cyclic graph is an undirected graph of $$$n$$$ vertices that form one cycle. Each vertex belongs to the cycle, i.e. the length of the cycle (the number of edges in it) is exactly $$$n$$$. The order of the vertices in the cycle is arbitrary.You can make queries in the following way: "? a b" where $$$1 \le a, b \le 10^{18}$$$ and $$$a \neq b$$$. In response to the query, the interactor outputs on a separate line the length of random of two paths from vertex $$$a$$$ to vertex $$$b$$$, or -1 if $$$\max(a, b) &gt; n$$$. The interactor chooses one of the two paths with equal probability. The length of the path —is the number of edges in it.You win if you guess the number of vertices in the hidden graph (number $$$n$$$) by making no more than $$$50$$$ queries.Note that the interactor is implemented in such a way that for any ordered pair $$$(a, b)$$$, it always returns the same value for query "? a b", no matter how many such queries. Note that the "? b a" query may be answered differently by the interactor.The vertices in the graph are randomly placed, and their positions are fixed in advance.Hacks are forbidden in this problem. The number of tests the jury has is $$$50$$$.
256 megabytes
import java.io.*; import java.security.cert.X509CRL; import java.util.*; import java.lang.*; import java.util.stream.Collector; import java.util.stream.Collectors; @SuppressWarnings("unused") public class Main { static InputStream is; static PrintWriter out; //static String INPUT = "in.txt"; static String INPUT = ""; static String OUTPUT = ""; //global const //private final static long BASE = 998244353L; private final static int ALPHABET = (int)('z') - (int)('a') + 1; private final static long BASE = 1000000007l; private final static int INF_I = 1000000000; private final static long INF_L = 10000000000000000l; private final static int MAXN = 200100; private final static int MAXK = 31; private final static int[] DX = {-1,0,1,0}; private final static int[] DY = {0,1,0,-1}; private static boolean inside(int x, int y, int N, int M) { return (0<=x && x<N && 0<=y && y<M); } private static int toInt(char ch) { return (int)ch; } private static char toChar(int i) { return (char)i; } private static void ask(long a, long b) { out.println("? " + a + " " + b); out.flush(); } //global static void solve() { int ntest = 1; //int ntest = readInt(); for (int test=0;test<ntest;test++) { long r = 3l; long ans=-1; while (ans == -1) { ask(1l,r); long sz = readLong(); if (sz == -1) { ans = r-1; break; } for (long l=2l;l<r; l++) { ask(l,r); long sz1 = readLong(); ask(r,l); long sz2 = readLong(); if (sz1 != sz2) { ans = sz1 + sz2; break; } } r+=1l; } out.println("! " + ans); out.flush(); } } public static void main(String[] args) throws Exception { long S = System.currentTimeMillis(); if (INPUT=="") { is = System.in; } else { File file = new File(INPUT); is = new FileInputStream(file); } if (OUTPUT == "") out = new PrintWriter(System.out); else out = new PrintWriter(OUTPUT); solve(); out.flush(); long G = System.currentTimeMillis(); } private static class MultiSet<T extends Comparable<T>> { private TreeSet<T> set; private Map<T, Integer> count; public MultiSet() { this.set = new TreeSet<>(); this.count = new HashMap<>(); } public void add(T x) { this.set.add(x); int o = this.count.getOrDefault(x, 0); this.count.put(x, o+1); } public void remove(T x) { int o = this.count.getOrDefault(x, 0); if (o==0) return; this.count.put(x, o-1); if (o==1) this.set.remove(x); } public void removeAll(T x) { int o = this.count.getOrDefault(x, 0); if (o==0) return; this.count.put(x, 0); this.set.remove(x); } public T first() { return this.set.first(); } public T last() { return this.set.last(); } public int getCount(T x) { return this.count.getOrDefault(x, 0); } public int size() { int res = 0; for (T x: this.set) res += this.count.get(x); return res; } } private static class Point<T extends Number & Comparable<T>> implements Comparable<Point<T>> { private T x; private T y; public Point(T x, T y) { this.x = x; this.y = y; } public T getX() {return x;} public T getY() {return y;} @Override public int compareTo(Point<T> o) { int cmp = x.compareTo(o.getX()); if (cmp==0) return y.compareTo(o.getY()); return cmp; } } private static class ClassComparator<T extends Comparable<T>> implements Comparator<T> { public ClassComparator() {} @Override public int compare(T a, T b) { return a.compareTo(b); } } private static class ListComparator<T extends Comparable<T>> implements Comparator<List<T>> { public ListComparator() {} @Override public int compare(List<T> o1, List<T> o2) { for (int i = 0; i < Math.min(o1.size(), o2.size()); i++) { int c = o1.get(i).compareTo(o2.get(i)); if (c != 0) { return c; } } return Integer.compare(o1.size(), o2.size()); } } private static boolean eof() { if(lenbuf == -1)return true; int lptr = ptrbuf; while(lptr < lenbuf)if(!isSpaceChar(inbuf[lptr++]))return false; try { is.mark(1000); while(true){ int b = is.read(); if(b == -1){ is.reset(); return true; }else if(!isSpaceChar(b)){ is.reset(); return false; } } } catch (IOException e) { return true; } } private static byte[] inbuf = new byte[1024]; static int lenbuf = 0, ptrbuf = 0; private static int readByte() { if(lenbuf == -1)throw new InputMismatchException(); if(ptrbuf >= lenbuf){ ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if(lenbuf <= 0)return -1; } return inbuf[ptrbuf++]; } private static boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } // private static boolean isSpaceChar(int c) { return !(c >= 32 && c <= 126); } private static int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; } private static double readDouble() { return Double.parseDouble(readString()); } private static char readChar() { return (char)skip(); } private static String readString() { int b = skip(); StringBuilder sb = new StringBuilder(); while(!(isSpaceChar(b))){ sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private static char[] readChar(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while(p < n && !(isSpaceChar(b))){ buf[p++] = (char)b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private static char[][] readTable(int n, int m) { char[][] map = new char[n][]; for(int i = 0;i < n;i++)map[i] = readChar(m); return map; } private static int[] readIntArray(int n) { int[] a = new int[n]; for(int i = 0;i < n;i++)a[i] = readInt(); return a; } private static long[] readLongArray(int n) { long[] a = new long[n]; for (int i=0;i<n;i++) a[i] = readLong(); return a; } private static int readInt() { int num = 0, b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private static long readLong() { long num = 0; int b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private static void tr(Object... o) { if(INPUT.length() != 0)System.out.println(Arrays.deepToString(o)); } }
Java
["1\n\n2\n\n-1"]
1 second
["? 1 2\n\n? 1 3\n\n? 1 4\n\n! 3"]
NoteIn the first example, the graph could look like this The lengths of the simple paths between all pairs of vertices in this case are $$$1$$$ or $$$2$$$. The first query finds out that one of the simple paths from vertex $$$1$$$ to vertex $$$2$$$ has a length of $$$1$$$. With the second query, we find out that one of the simple paths from vertex $$$1$$$ to vertex $$$3$$$ has length $$$2$$$. In the third query, we find out that vertex $$$4$$$ is not in the graph. Consequently, the size of the graph is $$$3$$$.
Java 8
standard input
[ "interactive", "probabilities" ]
8590f40e7509614694486165ee824587
null
1,800
null
standard output
PASSED
635c92c5d5ddd666e416215985386839
train_110.jsonl
1662993300
This is an interactive problem.I want to play a game with you...We hid from you a cyclic graph of $$$n$$$ vertices ($$$3 \le n \le 10^{18}$$$). A cyclic graph is an undirected graph of $$$n$$$ vertices that form one cycle. Each vertex belongs to the cycle, i.e. the length of the cycle (the number of edges in it) is exactly $$$n$$$. The order of the vertices in the cycle is arbitrary.You can make queries in the following way: "? a b" where $$$1 \le a, b \le 10^{18}$$$ and $$$a \neq b$$$. In response to the query, the interactor outputs on a separate line the length of random of two paths from vertex $$$a$$$ to vertex $$$b$$$, or -1 if $$$\max(a, b) &gt; n$$$. The interactor chooses one of the two paths with equal probability. The length of the path —is the number of edges in it.You win if you guess the number of vertices in the hidden graph (number $$$n$$$) by making no more than $$$50$$$ queries.Note that the interactor is implemented in such a way that for any ordered pair $$$(a, b)$$$, it always returns the same value for query "? a b", no matter how many such queries. Note that the "? b a" query may be answered differently by the interactor.The vertices in the graph are randomly placed, and their positions are fixed in advance.Hacks are forbidden in this problem. The number of tests the jury has is $$$50$$$.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Random; public class TaskE { public static Random random = new Random(); public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); System.out.println("? 1 200"); System.out.flush(); long resp = Long.parseLong(reader.readLine()); long answer; if (resp != -1) { // more than 200 nodes, get by bforce answer = getByBforce(reader); } else { // 200 or less nodes, get by binary division answer = getByBinaryDivision(reader); } System.out.println("! " + answer); System.out.flush(); reader.close(); } private static int getByBinaryDivision(BufferedReader reader) throws IOException { int lastExisting = 3, firstNonExisting = 200; int attemptCount = 0; while (firstNonExisting - lastExisting > 1 && attemptCount <= 49) { attemptCount++; int attempt = (firstNonExisting + lastExisting) / 2; System.out.println("? 3 " + attempt); System.out.flush(); long resp = Long.parseLong(reader.readLine()); if (resp == -1) { firstNonExisting = attempt; } else { lastExisting = attempt; } } return lastExisting; } private static long getByBforce(BufferedReader reader) throws IOException { long v1 = 0, v2 = 0; for (int start = 1; start <= 23; start++) { int end = start + 50; System.out.println("? " + start + " " + end); System.out.flush(); v1 = Long.parseLong(reader.readLine()); System.out.println("? " + end + " " + start); System.out.flush(); v2 = Long.parseLong(reader.readLine()); if (v1 != v2) { return v1 + v2; } } return v1 + 50; } }
Java
["1\n\n2\n\n-1"]
1 second
["? 1 2\n\n? 1 3\n\n? 1 4\n\n! 3"]
NoteIn the first example, the graph could look like this The lengths of the simple paths between all pairs of vertices in this case are $$$1$$$ or $$$2$$$. The first query finds out that one of the simple paths from vertex $$$1$$$ to vertex $$$2$$$ has a length of $$$1$$$. With the second query, we find out that one of the simple paths from vertex $$$1$$$ to vertex $$$3$$$ has length $$$2$$$. In the third query, we find out that vertex $$$4$$$ is not in the graph. Consequently, the size of the graph is $$$3$$$.
Java 8
standard input
[ "interactive", "probabilities" ]
8590f40e7509614694486165ee824587
null
1,800
null
standard output
PASSED
f55c927b93eb894874f3649c02b7957c
train_110.jsonl
1662993300
This is an interactive problem.I want to play a game with you...We hid from you a cyclic graph of $$$n$$$ vertices ($$$3 \le n \le 10^{18}$$$). A cyclic graph is an undirected graph of $$$n$$$ vertices that form one cycle. Each vertex belongs to the cycle, i.e. the length of the cycle (the number of edges in it) is exactly $$$n$$$. The order of the vertices in the cycle is arbitrary.You can make queries in the following way: "? a b" where $$$1 \le a, b \le 10^{18}$$$ and $$$a \neq b$$$. In response to the query, the interactor outputs on a separate line the length of random of two paths from vertex $$$a$$$ to vertex $$$b$$$, or -1 if $$$\max(a, b) &gt; n$$$. The interactor chooses one of the two paths with equal probability. The length of the path —is the number of edges in it.You win if you guess the number of vertices in the hidden graph (number $$$n$$$) by making no more than $$$50$$$ queries.Note that the interactor is implemented in such a way that for any ordered pair $$$(a, b)$$$, it always returns the same value for query "? a b", no matter how many such queries. Note that the "? b a" query may be answered differently by the interactor.The vertices in the graph are randomly placed, and their positions are fixed in advance.Hacks are forbidden in this problem. The number of tests the jury has is $$$50$$$.
256 megabytes
import java.io.File; import java.math.BigInteger; import java.util.Scanner; public class Main { public static void main(String[] args) { BigInteger curNode = new BigInteger("2"); BigInteger val1 = new BigInteger("-1"); BigInteger val2 = new BigInteger("-1"); Scanner scanner = new Scanner(System.in); while(true) { System.out.printf("? %d %d%n", 1, curNode); System.out.flush(); val1 = scanner.nextBigInteger(); if (val1.compareTo(new BigInteger("0")) == 0) { return; } if (val1.compareTo(new BigInteger("-1")) == 0) { System.out.printf("! %d%n", curNode.subtract(new BigInteger("1"))); System.out.flush(); return; } System.out.printf("? %d %d%n", curNode, 1); System.out.flush(); val2 = scanner.nextBigInteger(); if (val2.equals(BigInteger.ZERO)) { return; } if (val1.compareTo(val2) != 0) { System.out.printf("! %d%n", val1.add(val2)); System.out.flush(); return; } curNode = curNode.add(BigInteger.ONE); } } }
Java
["1\n\n2\n\n-1"]
1 second
["? 1 2\n\n? 1 3\n\n? 1 4\n\n! 3"]
NoteIn the first example, the graph could look like this The lengths of the simple paths between all pairs of vertices in this case are $$$1$$$ or $$$2$$$. The first query finds out that one of the simple paths from vertex $$$1$$$ to vertex $$$2$$$ has a length of $$$1$$$. With the second query, we find out that one of the simple paths from vertex $$$1$$$ to vertex $$$3$$$ has length $$$2$$$. In the third query, we find out that vertex $$$4$$$ is not in the graph. Consequently, the size of the graph is $$$3$$$.
Java 8
standard input
[ "interactive", "probabilities" ]
8590f40e7509614694486165ee824587
null
1,800
null
standard output
PASSED
ae074ba49acd43a1ebbb581b3d0e6732
train_110.jsonl
1662993300
This is an interactive problem.I want to play a game with you...We hid from you a cyclic graph of $$$n$$$ vertices ($$$3 \le n \le 10^{18}$$$). A cyclic graph is an undirected graph of $$$n$$$ vertices that form one cycle. Each vertex belongs to the cycle, i.e. the length of the cycle (the number of edges in it) is exactly $$$n$$$. The order of the vertices in the cycle is arbitrary.You can make queries in the following way: "? a b" where $$$1 \le a, b \le 10^{18}$$$ and $$$a \neq b$$$. In response to the query, the interactor outputs on a separate line the length of random of two paths from vertex $$$a$$$ to vertex $$$b$$$, or -1 if $$$\max(a, b) &gt; n$$$. The interactor chooses one of the two paths with equal probability. The length of the path —is the number of edges in it.You win if you guess the number of vertices in the hidden graph (number $$$n$$$) by making no more than $$$50$$$ queries.Note that the interactor is implemented in such a way that for any ordered pair $$$(a, b)$$$, it always returns the same value for query "? a b", no matter how many such queries. Note that the "? b a" query may be answered differently by the interactor.The vertices in the graph are randomly placed, and their positions are fixed in advance.Hacks are forbidden in this problem. The number of tests the jury has is $$$50$$$.
256 megabytes
import java.util.*; public class Main{ static Scanner sc = new Scanner(System.in); public static void main(String[] args) { for(int i = 4; i <= 28; ++i){ System.out.println("? 1 " + i); System.out.flush(); long v1 = sc.nextLong(); System.out.println("? " + i + " 1"); System.out.flush(); long v2 = sc.nextLong(); if(v1 == -1){ System.out.println("! " + (i - 1)); return; } if(v1 != v2){ System.out.println("! " + (v1 + v2)); return; } } } }
Java
["1\n\n2\n\n-1"]
1 second
["? 1 2\n\n? 1 3\n\n? 1 4\n\n! 3"]
NoteIn the first example, the graph could look like this The lengths of the simple paths between all pairs of vertices in this case are $$$1$$$ or $$$2$$$. The first query finds out that one of the simple paths from vertex $$$1$$$ to vertex $$$2$$$ has a length of $$$1$$$. With the second query, we find out that one of the simple paths from vertex $$$1$$$ to vertex $$$3$$$ has length $$$2$$$. In the third query, we find out that vertex $$$4$$$ is not in the graph. Consequently, the size of the graph is $$$3$$$.
Java 8
standard input
[ "interactive", "probabilities" ]
8590f40e7509614694486165ee824587
null
1,800
null
standard output
PASSED
e5b4054a66d0b245a78ddbcc14a0d6ad
train_110.jsonl
1662993300
This is an interactive problem.I want to play a game with you...We hid from you a cyclic graph of $$$n$$$ vertices ($$$3 \le n \le 10^{18}$$$). A cyclic graph is an undirected graph of $$$n$$$ vertices that form one cycle. Each vertex belongs to the cycle, i.e. the length of the cycle (the number of edges in it) is exactly $$$n$$$. The order of the vertices in the cycle is arbitrary.You can make queries in the following way: "? a b" where $$$1 \le a, b \le 10^{18}$$$ and $$$a \neq b$$$. In response to the query, the interactor outputs on a separate line the length of random of two paths from vertex $$$a$$$ to vertex $$$b$$$, or -1 if $$$\max(a, b) &gt; n$$$. The interactor chooses one of the two paths with equal probability. The length of the path —is the number of edges in it.You win if you guess the number of vertices in the hidden graph (number $$$n$$$) by making no more than $$$50$$$ queries.Note that the interactor is implemented in such a way that for any ordered pair $$$(a, b)$$$, it always returns the same value for query "? a b", no matter how many such queries. Note that the "? b a" query may be answered differently by the interactor.The vertices in the graph are randomly placed, and their positions are fixed in advance.Hacks are forbidden in this problem. The number of tests the jury has is $$$50$$$.
256 megabytes
import java.math.BigInteger; import java.util.*; import java.io.*; public class Vaibhav { static long bit[]; static boolean prime[]; static class Pair implements Comparable<Pair> { long x; int y; Pair(long x, int y) { this.x = x; this.y = y; } public int compareTo(Pair o){ return (int)(this.x-o.x); } } static int st[]; //array to store segment tree // A utility function to get minimum of two numbers static int minVal(int x, int y) { return (x < y) ? x : y; } // A utility function to get the middle index from corner // indexes. static int getMid(int s, int e) { return s + (e - s) / 2; } /* A recursive function to get the minimum value in a given range of array indexes. The following are parameters for this function. st --> Pointer to segment tree index --> Index of current node in the segment tree. Initially 0 is passed as root is always at index 0 ss & se --> Starting and ending indexes of the segment represented by current node, i.e., st[index] qs & qe --> Starting and ending indexes of query range */ static int RMQUtil(int ss, int se, int qs, int qe, int index) { // If segment of this node is a part of given range, then // return the min of the segment if (qs <= ss && qe >= se) return st[index]; // If segment of this node is outside the given range if (se < qs || ss > qe) return Integer.MAX_VALUE; // If a part of this segment overlaps with the given range int mid = getMid(ss, se); return minVal(RMQUtil(ss, mid, qs, qe, 2 * index + 1), RMQUtil(mid + 1, se, qs, qe, 2 * index + 2)); } // Return minimum of elements in range from index qs (query // start) to qe (query end). It mainly uses RMQUtil() static int RMQ(int n, int qs, int qe) { // Check for erroneous input values if (qs < 0 || qe > n - 1 || qs > qe) { // System.out.println("Invalid Input"); return -1; } return RMQUtil(0, n - 1, qs, qe, 0); } // A recursive function that constructs Segment Tree for // array[ss..se]. si is index of current node in segment tree st static int constructSTUtil(int arr[], int ss, int se, int si) { // If there is one element in array, store it in current // node of segment tree and return if (ss == se) { st[si] = arr[ss]; return arr[ss]; } // If there are more than one elements, then recur for left and // right subtrees and store the minimum of two values in this node int mid = getMid(ss, se); st[si] = minVal(constructSTUtil(arr, ss, mid, si * 2 + 1), constructSTUtil(arr, mid + 1, se, si * 2 + 2)); return st[si]; } /* Function to construct segment tree from given array. This function allocates memory for segment tree and calls constructSTUtil() to fill the allocated memory */ static void constructST(int arr[], int n) { // Allocate memory for segment tree //Height of segment tree int x = (int) (Math.ceil(Math.log(n) / Math.log(2))); //Maximum size of segment tree int max_size = 2 * (int) Math.pow(2, x) - 1; st = new int[max_size]; // allocate memory // Fill the allocated memory st constructSTUtil(arr, 0, n - 1, 0); } static long power(long x, long y, long p) { if (y == 0) return 1; if (x == 0) return 0; long res = 1l; x = x % p; while (y > 0) { if (y % 2 == 1) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return res; } static long power(long x, long y) { if (y == 0) return 1; if (x == 0) return 0; long res = 1; while (y > 0) { if (y % 2 == 1) res = (res * x); y = y >> 1; x = (x * x); } return res; } static void sort(long[] a) { ArrayList<Long> l = new ArrayList<>(); for (long i : a) l.add(i); Collections.sort(l); for (int i = 0; i < a.length; i++) a[i] = l.get(i); } static class FastScanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } double nextDouble() { return Double.parseDouble(next()); } int[] readArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } long[] readlongArray(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } long nextLong() { return Long.parseLong(next()); } } static void sieveOfEratosthenes(int n) { prime = new boolean[n + 1]; for (int i = 0; i <= n; i++) prime[i] = true; for (int p = 2; p * p <= n; p++) { if (prime[p] == true) { for (int i = p * p; i <= n; i += p) prime[i] = false; } } } public static int log2(int x) { return (int) (Math.log(x) / Math.log(2)); } static int binomialCoeff(int n, int r) { if (r > n) return 0; long m = 1000000007; long inv[] = new long[r + 1]; inv[0] = 1; if(r+1>=2) inv[1] = 1; // Getting the modular inversion // for all the numbers // from 2 to r with respect to m // here m = 1000000007 for (int i = 2; i <= r; i++) { inv[i] = m - (m / i) * inv[(int) (m % i)] % m; } int ans = 1; // for 1/(r!) part for (int i = 2; i <= r; i++) { ans = (int) (((ans % m) * (inv[i] % m)) % m); } // for (n)*(n-1)*(n-2)*...*(n-r+1) part for (int i = n; i >= (n - r + 1); i--) { ans = (int) (((ans % m) * (i % m)) % m); } return ans; } public static long gcd(long a, long b) { if (b == 0) { return a; } return gcd(b, a % b); } static BigInteger bi(String str) { return new BigInteger(str); } // Author - vaibhav_1710 static FastScanner fs = null; static long ans; static long mod=998244353; static ArrayList<Integer> al[]; static int dp[][][]; static int cntbig; static int cntless; static HashSet<Long> h; static int a[]; public static void main(String[] args) { fs = new FastScanner(); PrintWriter out = new PrintWriter(System.out); int t =1; outer: while (t-- > 0 ){ for(int i=4;i<=28;i++){ long x = query(1,i); long y = query(i,1); if(x == -1){ out.println("! "+(i-1)); continue outer; } if(x!=y){ out.println("! "+(x+y)); continue outer; } } } out.close(); } public static long query(int a,int b){ System.out.println("? "+a+" "+b); System.out.flush(); long v = fs.nextLong(); return v; } }
Java
["1\n\n2\n\n-1"]
1 second
["? 1 2\n\n? 1 3\n\n? 1 4\n\n! 3"]
NoteIn the first example, the graph could look like this The lengths of the simple paths between all pairs of vertices in this case are $$$1$$$ or $$$2$$$. The first query finds out that one of the simple paths from vertex $$$1$$$ to vertex $$$2$$$ has a length of $$$1$$$. With the second query, we find out that one of the simple paths from vertex $$$1$$$ to vertex $$$3$$$ has length $$$2$$$. In the third query, we find out that vertex $$$4$$$ is not in the graph. Consequently, the size of the graph is $$$3$$$.
Java 8
standard input
[ "interactive", "probabilities" ]
8590f40e7509614694486165ee824587
null
1,800
null
standard output
PASSED
8b423757255bc7d5f32f4c876d61c01d
train_110.jsonl
1662993300
This is an interactive problem.I want to play a game with you...We hid from you a cyclic graph of $$$n$$$ vertices ($$$3 \le n \le 10^{18}$$$). A cyclic graph is an undirected graph of $$$n$$$ vertices that form one cycle. Each vertex belongs to the cycle, i.e. the length of the cycle (the number of edges in it) is exactly $$$n$$$. The order of the vertices in the cycle is arbitrary.You can make queries in the following way: "? a b" where $$$1 \le a, b \le 10^{18}$$$ and $$$a \neq b$$$. In response to the query, the interactor outputs on a separate line the length of random of two paths from vertex $$$a$$$ to vertex $$$b$$$, or -1 if $$$\max(a, b) &gt; n$$$. The interactor chooses one of the two paths with equal probability. The length of the path —is the number of edges in it.You win if you guess the number of vertices in the hidden graph (number $$$n$$$) by making no more than $$$50$$$ queries.Note that the interactor is implemented in such a way that for any ordered pair $$$(a, b)$$$, it always returns the same value for query "? a b", no matter how many such queries. Note that the "? b a" query may be answered differently by the interactor.The vertices in the graph are randomly placed, and their positions are fixed in advance.Hacks are forbidden in this problem. The number of tests the jury has is $$$50$$$.
256 megabytes
import java.io.*; import java.util.*; public class Solution { public static boolean useInFile = false; public static boolean useOutFile = false; public static void main(String args[]) throws IOException { InOut inout = new InOut(); Resolver resolver = new Resolver(inout); // long time = System.currentTimeMillis(); resolver.solve(); // resolver.print("\n" + (System.currentTimeMillis() - time)); inout.flush(); } private static class Resolver { final long LONG_INF = (long) 1e18; final int INF = (int) (1e9 + 7); final int MOD = 998244353; long f[], inv[]; InOut inout; Resolver(InOut inout) { this.inout = inout; } void initF(int n, int mod) { f = new long[n + 1]; f[1] = 1; for (int i = 2; i <= n; i++) { f[i] = (f[i - 1] * i) % mod; } } void initInv(int n, int mod) { inv = new long[n + 1]; inv[n] = pow(f[n], mod - 2, mod); for (int i = inv.length - 2; i >= 0; i--) { inv[i] = inv[i + 1] * (i + 1) % mod; } } long cmn(int n, int m, int mod) { return f[n] * inv[m] % mod * inv[n - m] % mod; } int d[] = {0, -1, 0, 1, 0}; boolean legal(int r, int c, int n, int m) { return r >= 0 && r < n && c >= 0 && c < m; } int[] getBits(int n) { int b[] = new int[31]; for (int i = 0; i < 31; i++) { if ((n & (1 << i)) != 0) { b[i] = 1; } } return b; } private long ask1(long l, long r) throws IOException { format("? %d %d\n", l, r); flush(); return nextLong(25); } void solve() throws IOException { int tt = 1; boolean hvt = false; if (hvt) { tt = nextInt(); // tt = Integer.parseInt(nextLine()); } // initF(300001, MOD); // initInv(300001, MOD); // boolean pri[] = generatePrime(40000); for (int cs = 1; cs <= tt; cs++) { long rs = 0; boolean ok = true; // int n = nextInt(); long x = 4; for (int i = 0; i < 25; i++) { long b = ask1(1, x); if (b == -1) { rs = x - 1; break; } long c = ask1(x, 1); if (b != c) { rs = b + c; break; } x = Math.max(b + 2, x + 1); } if (rs == 0) rs = x; // print(ok ? "Yes" : "No"); // print(a, 0, s - 1); print("! " + rs); // format("Case #%d: %d", cs, rs); if (cs < tt) { format("\n"); // flush(); // format(" "); } // flush(); } } private void updateSegTree(int n, long l, SegmentTree lft) { long lazy; lazy = 1; for (int j = 1; j <= l; j++) { lazy = (lazy + cmn((int) l, j, INF)) % INF; lft.modify(1, j, j, lazy); } lft.modify(1, (int) (l + 1), n, lazy); } String next() throws IOException { return inout.next(); } String next(int n) throws IOException { return inout.next(n); } String nextLine() throws IOException { return inout.nextLine(); } int nextInt() throws IOException { return inout.nextInt(); } long nextLong(int n) throws IOException { return inout.nextLong(n); } int[] anInt(int i, int j) throws IOException { int a[] = new int[j + 1]; for (int k = i; k <= j; k++) { a[k] = nextInt(); } return a; } long[] anLong(int i, int j) throws IOException { long a[] = new long[j + 1]; for (int k = i; k <= j; k++) { a[k] = nextInt(); } return a; } long[] anLong(int i, int j, int len) throws IOException { long a[] = new long[j + 1]; for (int k = i; k <= j; k++) { a[k] = nextLong(len); } return a; } void print(long a[], int l, int r) { for (int i = l; i <= r; i++) { format("%s%d", i > l ? " " : "", a[i]); } } void print(int a[], int l, int r) { for (int i = l; i <= r; i++) { format("%s%d", i > l ? "\n" : "", a[i]); } } void print(String s) { inout.print(s, false); } void print(String s, boolean nextLine) { inout.print(s, nextLine); } void format(String format, Object... obj) { inout.format(format, obj); } void flush() { inout.flush(); } void swap(int a[], int i, int j) { a[i] ^= a[j]; a[j] ^= a[i]; a[i] ^= a[j]; } void swap(long a[], int i, int j) { a[i] ^= a[j]; a[j] ^= a[i]; a[i] ^= a[j]; } int getP(int x, int p[]) { if (p[x] == 0 || p[x] == x) { return x; } return p[x] = getP(p[x], p); } void union(int x, int y, int p[]) { if (x < y) { p[y] = x; } else { p[x] = y; } } boolean topSort() { int n = adj2.length - 1; int d[] = new int[n + 1]; for (int i = 1; i <= n; i++) { for (int j = 0; j < adj2[i].size(); j++) { d[adj2[i].get(j)[0]]++; } } List<Integer> list = new ArrayList<>(); for (int i = 1; i <= n; i++) { if (d[i] == 0) { list.add(i); } } for (int i = 0; i < list.size(); i++) { for (int j = 0; j < adj2[list.get(i)].size(); j++) { int t = adj2[list.get(i)].get(j)[0]; d[t]--; if (d[t] == 0) { list.add(t); } } } return list.size() == n; } class DSU { int[] f, siz; DSU(int n) { f = new int[n]; siz = new int[n]; Arrays.fill(siz, 1); } int leader(int x) { while (x != f[x]) x = f[x] = f[f[x]]; return x; } boolean same(int x, int y) { return leader(x) == leader(y); } boolean merge(int x, int y) { x = leader(x); y = leader(y); if (x == y) return false; siz[x] += siz[y]; f[y] = x; return true; } int size(int x) { return siz[leader(x)]; } } ; class SegmentTreeNode { long defaultVal = 0; int l, r; // long val = Integer.MAX_VALUE; long val = 0; long lazy = defaultVal; SegmentTreeNode(int l, int r) { this.l = l; this.r = r; } } class SegmentTree { SegmentTreeNode tree[]; long inf = Long.MIN_VALUE; long c[]; SegmentTree(int n) { assert n > 0; tree = new SegmentTreeNode[n * 3 + 1]; } void setAn(long cn[]) { c = cn; } SegmentTree build(int k, int l, int r) { if (l > r) { return this; } if (null == tree[k]) { tree[k] = new SegmentTreeNode(l, r); } if (l == r) { // tree[k].val = c[l]; return this; } int mid = (l + r) >> 1; build(k << 1, l, mid); build(k << 1 | 1, mid + 1, r); tree[k].val = (tree[k << 1].val + tree[k << 1 | 1].val) % MOD; // tree[k].val = Math.min(tree[k << 1].val, tree[k << 1 | 1].val); return this; } void pushDown(int k) { if (tree[k].l == tree[k].r) { return; } long lazy = tree[k].lazy; // tree[k << 1].val = ((c[tree[k << 1].l] - c[tree[k << 1].r + 1] + MOD) % MOD * lazy) % MOD; tree[k << 1].val += lazy; tree[k << 1].lazy += lazy; // tree[k << 1 | 1].val = ((c[tree[k << 1 | 1].l] - c[tree[k << 1 | 1].r + 1] + MOD) % MOD * lazy) % MOD; tree[k << 1 | 1].val += lazy; tree[k << 1 | 1].lazy += lazy; tree[k].lazy = 0; } void modify(int k, int l, int r, long change) { if (tree[k].l >= l && tree[k].r <= r) { // tree[k].val = ((c[tree[k].l] - c[tree[k].r + 1] + MOD) % MOD * val) % MOD; tree[k].val += change; tree[k].lazy += change; return; } int mid = (tree[k].l + tree[k].r) >> 1; if (tree[k].lazy != 0) { pushDown(k); } if (mid >= l) { modify(k << 1, l, r, change); } if (mid + 1 <= r) { modify(k << 1 | 1, l, r, change); } tree[k].val = (tree[k << 1].val + tree[k << 1 | 1].val) % MOD; // tree[k].val = Math.min(tree[k << 1].val, tree[k << 1 | 1].val); } long query(int k, int l, int r) { if (tree[k].l > r || tree[k].r < l) { return 0; } if (tree[k].lazy != 0) { pushDown(k); } if (tree[k].l >= l && tree[k].r <= r) { return tree[k].val; } long ans = (query(k << 1, l, r) + query(k << 1 | 1, l, r)) % MOD; if (tree[k].l < tree[k].r) { tree[k].val = (tree[k << 1].val + tree[k << 1 | 1].val) % MOD; // tree[k].val = Math.min(tree[k << 1].val, tree[k << 1 | 1].val); } return ans; } } class BitMap { boolean[] vis = new boolean[32]; List<Integer> g[]; void init() { for (int i = 0; i < 32; i++) { g = new List[32]; g[i] = new ArrayList<>(); } } void dfs(int p) { if (vis[p]) return; vis[p] = true; for (int it : g[p]) dfs(it); } boolean connected(int a[], int n) { int m = 0; for (int i = 0; i < n; i++) if (a[i] == 0) return false; for (int i = 0; i < n; i++) m |= a[i]; for (int i = 0; i < 31; i++) g[i].clear(); for (int i = 0; i < n; i++) { int last = -1; for (int j = 0; j < 31; j++) if ((a[i] & (1 << j)) > 0) { if (last != -1) { g[last].add(j); g[j].add(last); } last = j; } } Arrays.fill(vis, false); for (int j = 0; j < 31; j++) if (((1 << j) & m) > 0) { dfs(j); break; } for (int j = 0; j < 31; j++) if (((1 << j) & m) > 0 && !vis[j]) return false; return true; } } class BinaryIndexedTree { int n = 1; long C[]; BinaryIndexedTree(int sz) { while (n <= sz) { n <<= 1; } n = sz + 1; C = new long[n]; } int lowbit(int x) { return x & -x; } void add(int x, long val) { while (x < n) { C[x] += val; x += lowbit(x); } } long getSum(int x) { long res = 0; while (x > 0) { res += C[x]; x -= lowbit(x); } return res; } int binSearch(long sum) { if (sum == 0) { return 0; } int n = C.length; int mx = 1; while (mx < n) { mx <<= 1; } int res = 0; for (int i = mx / 2; i >= 1; i >>= 1) { if (C[res + i] < sum) { sum -= C[res + i]; res += i; } } return res + 1; } } static class TrieNode { int cnt = 0; TrieNode next[]; TrieNode() { next = new TrieNode[2]; } private void insert(TrieNode trie, int ch[], int i) { while (i < ch.length) { int idx = ch[i]; if (null == trie.next[idx]) { trie.next[idx] = new TrieNode(); } trie.cnt++; trie = trie.next[idx]; i++; } } private static int query(TrieNode trie) { if (null == trie) { return 0; } int ans[] = new int[2]; for (int i = 0; i < trie.next.length; i++) { if (null == trie.next[i]) { continue; } ans[i] = trie.next[i].cnt; } if (ans[0] == 0 && ans[0] == ans[1]) { return 0; } if (ans[0] == 0) { return query(trie.next[1]); } if (ans[1] == 0) { return query(trie.next[0]); } return Math.min(ans[0] - 1 + query(trie.next[1]), ans[1] - 1 + query(trie.next[0])); } } //Binary tree class TreeNode { int val; int tier = -1; TreeNode parent; TreeNode left; TreeNode right; TreeNode(int val) { this.val = val; } } //binary tree dfs void tierTree(TreeNode root) { if (null == root) { return; } if (null != root.parent) { root.tier = root.parent.tier + 1; } else { root.tier = 0; } tierTree(root.left); tierTree(root.right); } //LCA start TreeNode[][] lca; TreeNode[] tree; void lcaDfsTree(TreeNode root) { if (null == root) { return; } tree[root.val] = root; TreeNode nxt = root.parent; int idx = 0; while (null != nxt) { lca[root.val][idx] = nxt; nxt = lca[nxt.val][idx]; idx++; } lcaDfsTree(root.left); lcaDfsTree(root.right); } TreeNode lcaTree(TreeNode root, int n, TreeNode x, TreeNode y) throws IOException { if (null == root) { return null; } if (-1 == root.tier) { tree = new TreeNode[n + 1]; tierTree(root); } if (null == lca) { lca = new TreeNode[n + 1][31]; lcaDfsTree(root); } int z = Math.abs(x.tier - y.tier); int xx = x.tier > y.tier ? x.val : y.val; while (z > 0) { final int zz = z; int l = (int) BinSearch.bs(0, 31 , k -> zz < (1 << k)); xx = lca[xx][l].val; z -= 1 << l; } int yy = y.val; if (x.tier <= y.tier) { yy = x.val; } while (xx != yy) { final int xxx = xx; final int yyy = yy; int l = (int) BinSearch.bs(0, 31 , k -> (1 << k) <= tree[xxx].tier && lca[xxx][(int) k] != lca[yyy][(int) k]); xx = lca[xx][l].val; yy = lca[yy][l].val; } return tree[xx]; } //LCA end //graph List<Integer> adj[]; List<int[]> adj2[]; void initGraph(int n) throws IOException { initGraph(n, 0, false, false, 1, false); } void initGraph(int n, int m, boolean hasW, boolean directed, int type, boolean useInput) throws IOException { if (type == 1) { adj = new List[n + 1]; } else { adj2 = new List[n + 1]; } for (int i = 1; i <= n; i++) { if (type == 1) { adj[i] = new ArrayList<>(); } else { adj2[i] = new ArrayList<>(); } } if (!useInput) return; for (int i = 0; i < m; i++) { int f = nextInt(); int t = nextInt(); if (type == 1) { adj[f].add(t); if (!directed) { adj[t].add(f); } } else { int w = hasW ? nextInt() : 0; adj2[f].add(new int[]{t, w}); if (!directed) { adj2[t].add(new int[]{f, w}); } } } } void getDiv(Map<Integer, Integer> map, long n) { int sqrt = (int) Math.sqrt(n); for (int i = 2; i <= sqrt; i++) { int cnt = 0; while (n % i == 0) { cnt++; n /= i; } if (cnt > 0) { map.put(i, cnt); } } if (n > 1) { map.put((int) n, 1); } } boolean[] generatePrime(int n) { boolean p[] = new boolean[n + 1]; p[2] = true; for (int i = 3; i <= n; i += 2) { p[i] = true; } for (int i = 3; i <= Math.sqrt(n); i += 2) { if (!p[i]) { continue; } for (int j = i * i; j <= n; j += i << 1) { p[j] = false; } } return p; } boolean isPrime(long n) { //determines if n is a prime number int p[] = {2, 3, 5, 233, 331}; int pn = p.length; long s = 0, t = n - 1;//n - 1 = 2^s * t while ((t & 1) == 0) { t >>= 1; ++s; } for (int i = 0; i < pn; ++i) { if (n == p[i]) { return true; } long pt = pow(p[i], t, n); for (int j = 0; j < s; ++j) { long cur = llMod(pt, pt, n); if (cur == 1 && pt != 1 && pt != n - 1) { return false; } pt = cur; } if (pt != 1) { return false; } } return true; } long[] llAdd2(long a[], long b[], long mod) { long c[] = new long[2]; c[1] = (a[1] + b[1]) % (mod * mod); c[0] = (a[1] + b[1]) / (mod * mod) + a[0] + b[0]; return c; } long[] llMod2(long a, long b, long mod) { long x1 = a / mod; long y1 = a % mod; long x2 = b / mod; long y2 = b % mod; long c = (x1 * y2 + x2 * y1) / mod; c += x1 * x2; long d = (x1 * y2 + x2 * y1) % mod * mod + y1 * y2; return new long[]{c, d}; } long llMod(long a, long b, long mod) { if (a > mod || b > mod) { return (a * b - (long) ((double) a / mod * b + 0.5) * mod + mod) % mod; } return a * b % mod; // long r = 0; // a %= mod; // b %= mod; // while (b > 0) { // if ((b & 1) == 1) { // r = (r + a) % mod; // } // b >>= 1; // a = (a << 1) % mod; // } // return r; } long pow(long a, long n) { long ans = 1; while (n > 0) { if ((n & 1) == 1) { ans = ans * a; } a = a * a; n >>= 1; } return ans; } long pow(long a, long n, long mod) { long ans = 1; while (n > 0) { if ((n & 1) == 1) { ans = llMod(ans, a, mod); } a = llMod(a, a, mod); n >>= 1; } return ans; } private long[][] initC(int n) { long c[][] = new long[n][n]; for (int i = 0; i < n; i++) { c[i][0] = 1; } for (int i = 1; i < n; i++) { for (int j = 1; j <= i; j++) { c[i][j] = c[i - 1][j - 1] + c[i - 1][j]; } } return c; } /** * ps: n >= m, choose m from n; */ // private int cmn(long n, long m) { // if (m > n) { // n ^= m; // m ^= n; // n ^= m; // } // m = Math.min(m, n - m); // // long top = 1; // long bot = 1; // for (long i = n - m + 1; i <= n; i++) { // top = (top * i) % MOD; // } // for (int i = 1; i <= m; i++) { // bot = (bot * i) % MOD; // } // // return (int) ((top * pow(bot, MOD - 2, MOD)) % MOD); // } long[] exGcd(long a, long b) { if (b == 0) { return new long[]{a, 1, 0}; } long[] ans = exGcd(b, a % b); long x = ans[2]; long y = ans[1] - a / b * ans[2]; ans[1] = x; ans[2] = y; return ans; } long gcd(long a, long b) { if (a < b) { return gcd(b, a); } while (b != 0) { long tmp = a % b; a = b; b = tmp; } return a; } int[] unique(int a[], Map<Integer, Integer> idx) { int tmp[] = a.clone(); Arrays.sort(tmp); int j = 0; for (int i = 0; i < tmp.length; i++) { if (i == 0 || tmp[i] > tmp[i - 1]) { idx.put(tmp[i], j++); } } int rs[] = new int[j]; j = 0; for (int key : idx.keySet()) { rs[j++] = key; } Arrays.sort(rs); return rs; } boolean isEven(long n) { return (n & 1) == 0; } static class BinSearch { static long bs(long l, long r, IBinSearch sort) throws IOException { while (l < r) { long m = l + (r - l) / 2; if (sort.binSearchCmp(m)) { l = m + 1; } else { r = m; } } return l; } interface IBinSearch { boolean binSearchCmp(long k) throws IOException; } } } private static class InOut { private BufferedReader br; private StreamTokenizer st; private PrintWriter pw; InOut() throws FileNotFoundException { if (useInFile) { System.setIn(new FileInputStream("resources/inout/in.text")); } if (useOutFile) { System.setOut(new PrintStream("resources/inout/out.text")); } br = new BufferedReader(new InputStreamReader(System.in)); st = new StreamTokenizer(br); pw = new PrintWriter(new OutputStreamWriter(System.out)); st.ordinaryChar('\''); st.ordinaryChar('\"'); st.ordinaryChar('/'); } private boolean hasNext() throws IOException { return st.nextToken() != StreamTokenizer.TT_EOF; } private String next() throws IOException { if (st.nextToken() == StreamTokenizer.TT_EOF) { throw new IOException(); } return st.sval; } private String next(int n) throws IOException { return next(n, false); } private String next(int len, boolean isDigit) throws IOException { char ch[] = new char[len]; int cur = 0; char c; while ((c = (char) br.read()) == '\n' || c == '\r' || c == ' ' || c == '\t' || (isDigit && (c < '0' || c > '9') && c != '-' && c != '+')) ; do { ch[cur++] = c; } while (!((c = (char) br.read()) == '\n' || c == '\r' || c == ' ' || c == '\t') && (!isDigit || c >= '0' && c <= '9')); return String.valueOf(ch, 0, cur); } private int nextInt() throws IOException { if (st.nextToken() == StreamTokenizer.TT_EOF) { throw new IOException(); } return (int) st.nval; } private long nextLong(int n) throws IOException { return Long.parseLong(next(n, true)); } private double nextDouble() throws IOException { st.nextToken(); return st.nval; } private String[] nextSS(String reg) throws IOException { return br.readLine().split(reg); } private String nextLine() throws IOException { return br.readLine(); } private void print(String s, boolean newLine) { if (null != s) { pw.print(s); } if (newLine) { pw.println(); } } private void format(String format, Object... obj) { pw.format(format, obj); } private void flush() { pw.flush(); } } private static class FFT { double[] roots; int maxN; public FFT(int maxN) { this.maxN = maxN; initRoots(); } public long[] multiply(int[] a, int[] b) { int minSize = a.length + b.length - 1; int bits = 1; while (1 << bits < minSize) bits++; int N = 1 << bits; double[] aa = toComplex(a, N); double[] bb = toComplex(b, N); fftIterative(aa, false); fftIterative(bb, false); double[] c = new double[aa.length]; for (int i = 0; i < N; i++) { c[2 * i] = aa[2 * i] * bb[2 * i] - aa[2 * i + 1] * bb[2 * i + 1]; c[2 * i + 1] = aa[2 * i] * bb[2 * i + 1] + aa[2 * i + 1] * bb[2 * i]; } fftIterative(c, true); long[] ret = new long[minSize]; for (int i = 0; i < ret.length; i++) { ret[i] = Math.round(c[2 * i]); } return ret; } static double[] toComplex(int[] arr, int size) { double[] ret = new double[size * 2]; for (int i = 0; i < arr.length; i++) { ret[2 * i] = arr[i]; } return ret; } void initRoots() { roots = new double[2 * (maxN + 1)]; double ang = 2 * Math.PI / maxN; for (int i = 0; i <= maxN; i++) { roots[2 * i] = Math.cos(i * ang); roots[2 * i + 1] = Math.sin(i * ang); } } int bits(int N) { int ret = 0; while (1 << ret < N) ret++; if (1 << ret != N) throw new RuntimeException(); return ret; } void fftIterative(double[] array, boolean inv) { int bits = bits(array.length / 2); int N = 1 << bits; for (int from = 0; from < N; from++) { int to = Integer.reverse(from) >>> (32 - bits); if (from < to) { double tmpR = array[2 * from]; double tmpI = array[2 * from + 1]; array[2 * from] = array[2 * to]; array[2 * from + 1] = array[2 * to + 1]; array[2 * to] = tmpR; array[2 * to + 1] = tmpI; } } for (int n = 2; n <= N; n *= 2) { int delta = 2 * maxN / n; for (int from = 0; from < N; from += n) { int rootIdx = inv ? 2 * maxN : 0; double tmpR, tmpI; for (int arrIdx = 2 * from; arrIdx < 2 * from + n; arrIdx += 2) { tmpR = array[arrIdx + n] * roots[rootIdx] - array[arrIdx + n + 1] * roots[rootIdx + 1]; tmpI = array[arrIdx + n] * roots[rootIdx + 1] + array[arrIdx + n + 1] * roots[rootIdx]; array[arrIdx + n] = array[arrIdx] - tmpR; array[arrIdx + n + 1] = array[arrIdx + 1] - tmpI; array[arrIdx] += tmpR; array[arrIdx + 1] += tmpI; rootIdx += (inv ? -delta : delta); } } } if (inv) { for (int i = 0; i < array.length; i++) { array[i] /= N; } } } } }
Java
["1\n\n2\n\n-1"]
1 second
["? 1 2\n\n? 1 3\n\n? 1 4\n\n! 3"]
NoteIn the first example, the graph could look like this The lengths of the simple paths between all pairs of vertices in this case are $$$1$$$ or $$$2$$$. The first query finds out that one of the simple paths from vertex $$$1$$$ to vertex $$$2$$$ has a length of $$$1$$$. With the second query, we find out that one of the simple paths from vertex $$$1$$$ to vertex $$$3$$$ has length $$$2$$$. In the third query, we find out that vertex $$$4$$$ is not in the graph. Consequently, the size of the graph is $$$3$$$.
Java 8
standard input
[ "interactive", "probabilities" ]
8590f40e7509614694486165ee824587
null
1,800
null
standard output
PASSED
38f9b9c382b7b91320a9ea9fd8a65619
train_110.jsonl
1662993300
This is an interactive problem.I want to play a game with you...We hid from you a cyclic graph of $$$n$$$ vertices ($$$3 \le n \le 10^{18}$$$). A cyclic graph is an undirected graph of $$$n$$$ vertices that form one cycle. Each vertex belongs to the cycle, i.e. the length of the cycle (the number of edges in it) is exactly $$$n$$$. The order of the vertices in the cycle is arbitrary.You can make queries in the following way: "? a b" where $$$1 \le a, b \le 10^{18}$$$ and $$$a \neq b$$$. In response to the query, the interactor outputs on a separate line the length of random of two paths from vertex $$$a$$$ to vertex $$$b$$$, or -1 if $$$\max(a, b) &gt; n$$$. The interactor chooses one of the two paths with equal probability. The length of the path —is the number of edges in it.You win if you guess the number of vertices in the hidden graph (number $$$n$$$) by making no more than $$$50$$$ queries.Note that the interactor is implemented in such a way that for any ordered pair $$$(a, b)$$$, it always returns the same value for query "? a b", no matter how many such queries. Note that the "? b a" query may be answered differently by the interactor.The vertices in the graph are randomly placed, and their positions are fixed in advance.Hacks are forbidden in this problem. The number of tests the jury has is $$$50$$$.
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.Collections; import java.util.Random; import java.util.Scanner; import java.util.StringTokenizer; import java.util.TreeSet; /* 12 23 31 */ public class E { public static void main(String[] args) { Scanner fs=new Scanner(System.in); for (int i=2; true; i++) { System.out.println("? 1 "+i); long a=fs.nextLong(); if (a==-1) { System.out.println("! "+(i-1)); return; } System.out.println("? "+i+" 1"); long b=fs.nextLong(); if (a!=b) { System.out.println("! "+(a+b)); return; } } } static final Random random=new Random(); static final int mod=1_000_000_007; static void ruffleSort(int[] a) { int n=a.length;//shuffle, then sort for (int i=0; i<n; i++) { int oi=random.nextInt(n), temp=a[oi]; a[oi]=a[i]; a[i]=temp; } Arrays.sort(a); } static long add(long a, long b) { return (a+b)%mod; } static long sub(long a, long b) { return ((a-b)%mod+mod)%mod; } static long mul(long a, long b) { return (a*b)%mod; } static long exp(long base, long exp) { if (exp==0) return 1; long half=exp(base, exp/2); if (exp%2==0) return mul(half, half); return mul(half, mul(half, base)); } static long[] factorials=new long[2_000_001]; static long[] invFactorials=new long[2_000_001]; static void precompFacts() { factorials[0]=invFactorials[0]=1; for (int i=1; i<factorials.length; i++) factorials[i]=mul(factorials[i-1], i); invFactorials[factorials.length-1]=exp(factorials[factorials.length-1], mod-2); for (int i=invFactorials.length-2; i>=0; i--) invFactorials[i]=mul(invFactorials[i+1], i+1); } static long nCk(int n, int k) { return mul(factorials[n], mul(invFactorials[k], invFactorials[n-k])); } static void sort(int[] a) { ArrayList<Integer> l=new ArrayList<>(); for (int i:a) l.add(i); Collections.sort(l); for (int i=0; i<a.length; i++) a[i]=l.get(i); } static class FastScanner { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readArray(int n) { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } long nextLong() { return Long.parseLong(next()); } } }
Java
["1\n\n2\n\n-1"]
1 second
["? 1 2\n\n? 1 3\n\n? 1 4\n\n! 3"]
NoteIn the first example, the graph could look like this The lengths of the simple paths between all pairs of vertices in this case are $$$1$$$ or $$$2$$$. The first query finds out that one of the simple paths from vertex $$$1$$$ to vertex $$$2$$$ has a length of $$$1$$$. With the second query, we find out that one of the simple paths from vertex $$$1$$$ to vertex $$$3$$$ has length $$$2$$$. In the third query, we find out that vertex $$$4$$$ is not in the graph. Consequently, the size of the graph is $$$3$$$.
Java 8
standard input
[ "interactive", "probabilities" ]
8590f40e7509614694486165ee824587
null
1,800
null
standard output
PASSED
21bd5dd1b10c29f834c67a2ebbef26d8
train_110.jsonl
1662993300
This is an interactive problem.I want to play a game with you...We hid from you a cyclic graph of $$$n$$$ vertices ($$$3 \le n \le 10^{18}$$$). A cyclic graph is an undirected graph of $$$n$$$ vertices that form one cycle. Each vertex belongs to the cycle, i.e. the length of the cycle (the number of edges in it) is exactly $$$n$$$. The order of the vertices in the cycle is arbitrary.You can make queries in the following way: "? a b" where $$$1 \le a, b \le 10^{18}$$$ and $$$a \neq b$$$. In response to the query, the interactor outputs on a separate line the length of random of two paths from vertex $$$a$$$ to vertex $$$b$$$, or -1 if $$$\max(a, b) &gt; n$$$. The interactor chooses one of the two paths with equal probability. The length of the path —is the number of edges in it.You win if you guess the number of vertices in the hidden graph (number $$$n$$$) by making no more than $$$50$$$ queries.Note that the interactor is implemented in such a way that for any ordered pair $$$(a, b)$$$, it always returns the same value for query "? a b", no matter how many such queries. Note that the "? b a" query may be answered differently by the interactor.The vertices in the graph are randomly placed, and their positions are fixed in advance.Hacks are forbidden in this problem. The number of tests the jury has is $$$50$$$.
256 megabytes
//package kg.my_algorithms.Codeforces; /* If you can't Calculate, then Stimulate */ import java.util.*; import java.io.*; public class Solution { public static void main(String[] args) throws IOException { FastReader fr = new FastReader(); // BufferedWriter output = new BufferedWriter(new OutputStreamWriter(System.out)); // StringBuilder sb = new StringBuilder(); // output.write(sb.toString()); // output.flush(); for(int i=1;i<=25;i++){ long path1 = helper(1,i+1,fr); long path2 = helper(i+1,1,fr); if(path2!=path1){ System.out.println("! " + (path1+path2)); break; } if(path1==-1) { System.out.println("! 4"); break; } } System.out.flush(); } private static long helper(long a, long b, FastReader fr){ System.out.println("? "+a+" " + b); long res = fr.nextLong(); return res; } } //Fast Input 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
["1\n\n2\n\n-1"]
1 second
["? 1 2\n\n? 1 3\n\n? 1 4\n\n! 3"]
NoteIn the first example, the graph could look like this The lengths of the simple paths between all pairs of vertices in this case are $$$1$$$ or $$$2$$$. The first query finds out that one of the simple paths from vertex $$$1$$$ to vertex $$$2$$$ has a length of $$$1$$$. With the second query, we find out that one of the simple paths from vertex $$$1$$$ to vertex $$$3$$$ has length $$$2$$$. In the third query, we find out that vertex $$$4$$$ is not in the graph. Consequently, the size of the graph is $$$3$$$.
Java 8
standard input
[ "interactive", "probabilities" ]
8590f40e7509614694486165ee824587
null
1,800
null
standard output
PASSED
28cd8e66c1e37a1920cdc55adcf03120
train_110.jsonl
1662993300
This is an interactive problem.I want to play a game with you...We hid from you a cyclic graph of $$$n$$$ vertices ($$$3 \le n \le 10^{18}$$$). A cyclic graph is an undirected graph of $$$n$$$ vertices that form one cycle. Each vertex belongs to the cycle, i.e. the length of the cycle (the number of edges in it) is exactly $$$n$$$. The order of the vertices in the cycle is arbitrary.You can make queries in the following way: "? a b" where $$$1 \le a, b \le 10^{18}$$$ and $$$a \neq b$$$. In response to the query, the interactor outputs on a separate line the length of random of two paths from vertex $$$a$$$ to vertex $$$b$$$, or -1 if $$$\max(a, b) &gt; n$$$. The interactor chooses one of the two paths with equal probability. The length of the path —is the number of edges in it.You win if you guess the number of vertices in the hidden graph (number $$$n$$$) by making no more than $$$50$$$ queries.Note that the interactor is implemented in such a way that for any ordered pair $$$(a, b)$$$, it always returns the same value for query "? a b", no matter how many such queries. Note that the "? b a" query may be answered differently by the interactor.The vertices in the graph are randomly placed, and their positions are fixed in advance.Hacks are forbidden in this problem. The number of tests the jury has is $$$50$$$.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; public class C { public static void main(String[] args) { FastScanner sc = new FastScanner(); long ans = 3; for (int i = 2; i < 26; i++) { System.out.println("? " + (i + 1) + " " + (i + 2)); long res1 = sc.nextLong(); if (res1 == -1) { System.out.println("! " + (i + 1)); return; } System.out.println("? " + (i + 2) + " " + (i + 1)); long res2 = sc.nextLong(); if (res1 != res2) { System.out.println("! " + (res1 + res2)); return; } ans = res1 + res2; } System.out.println("! " + ans); } public static class Pair implements Comparable<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; } @Override public int compareTo(Pair o) { return Integer.compare(this.a, o.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()); } int[] readArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } long nextLong() { return Long.parseLong(next()); } } }
Java
["1\n\n2\n\n-1"]
1 second
["? 1 2\n\n? 1 3\n\n? 1 4\n\n! 3"]
NoteIn the first example, the graph could look like this The lengths of the simple paths between all pairs of vertices in this case are $$$1$$$ or $$$2$$$. The first query finds out that one of the simple paths from vertex $$$1$$$ to vertex $$$2$$$ has a length of $$$1$$$. With the second query, we find out that one of the simple paths from vertex $$$1$$$ to vertex $$$3$$$ has length $$$2$$$. In the third query, we find out that vertex $$$4$$$ is not in the graph. Consequently, the size of the graph is $$$3$$$.
Java 8
standard input
[ "interactive", "probabilities" ]
8590f40e7509614694486165ee824587
null
1,800
null
standard output