exec_outcome
stringclasses 1
value | code_uid
stringlengths 32
32
| file_name
stringclasses 111
values | prob_desc_created_at
stringlengths 10
10
| prob_desc_description
stringlengths 63
3.8k
| prob_desc_memory_limit
stringclasses 18
values | source_code
stringlengths 117
65.5k
| lang_cluster
stringclasses 1
value | prob_desc_sample_inputs
stringlengths 2
802
| prob_desc_time_limit
stringclasses 27
values | prob_desc_sample_outputs
stringlengths 2
796
| prob_desc_notes
stringlengths 4
3k
⌀ | lang
stringclasses 5
values | prob_desc_input_from
stringclasses 3
values | tags
listlengths 0
11
| src_uid
stringlengths 32
32
| prob_desc_input_spec
stringlengths 28
2.37k
⌀ | difficulty
int64 -1
3.5k
⌀ | prob_desc_output_spec
stringlengths 17
1.47k
⌀ | prob_desc_output_to
stringclasses 3
values | hidden_unit_tests
stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
PASSED
|
c9aa6ff1a54fb5e670328b11e2df4930
|
train_109.jsonl
|
1613658900
|
The only difference between the easy and the hard version is the limit to the number of queries.This is an interactive problem.There is an array $$$a$$$ of $$$n$$$ different numbers. In one query you can ask the position of the second maximum element in a subsegment $$$a[l..r]$$$. Find the position of the maximum element in the array in no more than 20 queries.A subsegment $$$a[l..r]$$$ is all the elements $$$a_l, a_{l + 1}, ..., a_r$$$. After asking this subsegment you will be given the position of the second maximum from this subsegment in the whole array.
|
256 megabytes
|
import java.io.*;
import java.util.*;
public class Main {
static BufferedReader bf;
static PrintWriter out;
static Scanner sc;
static StringTokenizer st;
static long mod = (long)(1e9+7);
static long mod2 = 998244353;
static long fact[] = new long[1001];
static long inverse[] = new long[1001];
public static void main (String[] args)throws IOException {
bf = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
sc = new Scanner(System.in);
// fact[0] = 1;
// inverse[0] = 1;
// for(int i = 1;i<fact.length;i++){
// fact[i] = (fact[i-1] * i)%mod;
// inverse[i] = binaryExpo(fact[i], mod-2);
// }
// int t = nextInt();
// while(t-->0){
solve();
// }
}
public static void solve() throws IOException{
int n = nextInt();
req(1,n);
int index = nextInt();
int left = 0;
if(index != 1){
req(1,index);
left= nextInt();
}
int l = -1;
int r = -1;
if((index != 1) && left == index){
l = 1;
r = index-1;
}
else{
l = index+1;
r = n;
}
int ans = -1;
while(l <= r){
int mid = (l + (r - l)/2);
if(mid < index){
req(mid,index);
int idx = nextInt();
if(idx == index){
ans = mid;
l = mid+1;
}
else{
r = mid-1;
}
}
else{
req(index,mid);
int idx = nextInt();
if(idx == index){
ans = mid;
r = mid-1;
}
else{
l = mid+1;
}
}
}
out.println("! " + ans);
out.flush();
}
public static void req(int l,int r){
out.println("? " + l + " " + r);
out.flush();
}
public static int[] bringSame(int u,int v ,int parent[][],int[]depth){
if(depth[u] < depth[v]){
int temp = u;
u = v;
v = temp;
}
int k = depth[u] - depth[v];
for(int i = 0;i<=18;i++){
if((k & (1<<i)) != 0){
u = parent[u][i];
}
}
return new int[]{u,v};
}
public static void findDepth(List<List<Integer>>list,int cur,int parent,int[]depth,int[][]p){
List<Integer>temp = list.get(cur);
p[cur][0] = parent;
for(int i = 0;i<temp.size();i++){
int next = temp.get(i);
if(next != parent){
depth[next] = depth[cur]+1;
findDepth(list,next,cur,depth,p);
}
}
}
public static int lca(int u, int v,int[][]parent){
if(u == v)return u;
for(int i = 18;i>=0;i--){
if(parent[u][i] != parent[v][i]){
u = parent[u][i];
v = parent[v][i];
}
}
return parent[u][0];
}
public static void plus(int node,int low,int high,int tlow,int thigh,int[]tree){
if(low >= tlow && high <= thigh){
tree[node]++;
return;
}
if(high < tlow || low > thigh)return;
int mid = (low + high)/2;
plus(node*2,low,mid,tlow,thigh,tree);
plus(node*2 + 1 , mid + 1, high,tlow, thigh,tree);
}
public static boolean allEqual(int[]arr,int x){
for(int i = 0;i<arr.length;i++){
if(arr[i] != x)return false;
}
return true;
}
public static long helper(StringBuilder sb){
return Long.parseLong(sb.toString());
}
public static int min(int node,int low,int high,int tlow,int thigh,int[][]tree){
if(low >= tlow&& high <= thigh)return tree[node][0];
if(high < tlow || low > thigh)return Integer.MAX_VALUE;
int mid = (low + high)/2;
// println(low+" "+high+" "+tlow+" "+thigh);
return Math.min(min(node*2,low,mid,tlow,thigh,tree) ,min(node*2+1,mid+1,high,tlow,thigh,tree));
}
public static int max(int node,int low,int high,int tlow,int thigh,int[][]tree){
if(low >= tlow && high <= thigh)return tree[node][1];
if(high < tlow || low > thigh)return Integer.MIN_VALUE;
int mid = (low + high)/2;
return Math.max(max(node*2,low,mid,tlow,thigh,tree) ,max(node*2+1,mid+1,high,tlow,thigh,tree));
}
public static long[] help(List<List<Integer>>list,int[][]range,int cur){
List<Integer>temp = list.get(cur);
if(temp.size() == 0)return new long[]{range[cur][1],1};
long sum = 0;
long count = 0;
for(int i = 0;i<temp.size();i++){
long []arr = help(list,range,temp.get(i));
sum += arr[0];
count += arr[1];
}
if(sum < range[cur][0]){
count++;
sum = range[cur][1];
}
return new long[]{sum,count};
}
public static long findSum(int node,int low, int high,int tlow,int thigh,long[]tree,long mod){
if(low >= tlow && high <= thigh)return tree[node]%mod;
if(low > thigh || high < tlow)return 0;
int mid = (low + high)/2;
return((findSum(node*2,low,mid,tlow,thigh,tree,mod) % mod) + (findSum(node*2+1,mid+1,high,tlow,thigh,tree,mod)))%mod;
}
public static boolean allzero(long[]arr){
for(int i =0 ;i<arr.length;i++){
if(arr[i]!=0)return false;
}
return true;
}
public static long count(long[][]dp,int i,int[]arr,int drank,long sum){
if(i == arr.length)return 0;
if(dp[i][drank]!=-1 && arr[i]+sum >=0)return dp[i][drank];
if(sum + arr[i] >= 0){
long count1 = 1 + count(dp,i+1,arr,drank+1,sum+arr[i]);
long count2 = count(dp,i+1,arr,drank,sum);
return dp[i][drank] = Math.max(count1,count2);
}
return dp[i][drank] = count(dp,i+1,arr,drank,sum);
}
public static void help(int[]arr,char[]signs,int l,int r){
if( l < r){
int mid = (l+r)/2;
help(arr,signs,l,mid);
help(arr,signs,mid+1,r);
merge(arr,signs,l,mid,r);
}
}
public static void merge(int[]arr,char[]signs,int l,int mid,int r){
int n1 = mid - l + 1;
int n2 = r - mid;
int[]a = new int[n1];
int []b = new int[n2];
char[]asigns = new char[n1];
char[]bsigns = new char[n2];
for(int i = 0;i<n1;i++){
a[i] = arr[i+l];
asigns[i] = signs[i+l];
}
for(int i = 0;i<n2;i++){
b[i] = arr[i+mid+1];
bsigns[i] = signs[i+mid+1];
}
int i = 0;
int j = 0;
int k = l;
boolean opp = false;
while(i<n1 && j<n2){
if(a[i] <= b[j]){
arr[k] = a[i];
if(opp){
if(asigns[i] == 'R'){
signs[k] = 'L';
}
else{
signs[k] = 'R';
}
}
else{
signs[k] = asigns[i];
}
i++;
k++;
}
else{
arr[k] = b[j];
int times = n1 - i;
if(times%2 == 1){
if(bsigns[j] == 'R'){
signs[k] = 'L';
}
else{
signs[k] = 'R';
}
}
else{
signs[k] = bsigns[j];
}
j++;
opp = !opp;
k++;
}
}
while(i<n1){
arr[k] = a[i];
if(opp){
if(asigns[i] == 'R'){
signs[k] = 'L';
}
else{
signs[k] = 'R';
}
}
else{
signs[k] = asigns[i];
}
i++;
k++;
}
while(j<n2){
arr[k] = b[j];
signs[k] = bsigns[j];
j++;
k++;
}
}
public static long nck(int n,int k){
return ((fact[n] * (inverse[n-k])%mod) * inverse[k])%mod;
}
public static long binaryExpo(long base,long expo){
if(expo == 0)return 1;
long val;
if(expo%2 == 1){
val = (binaryExpo(base, expo/2));
val = (val * val)%mod;
val = (val * base)%mod;
}
else{
val = binaryExpo(base, expo/2);
val = (val*val)%mod;
}
return (val%mod);
}
public static boolean isSorted(int[]arr){
for(int i =1;i<arr.length;i++){
if(arr[i] < arr[i-1]){
return false;
}
}
return true;
}
//function to find the topological sort of the a DAG
public static boolean hasCycle(int[]indegree,List<List<Integer>>list,int n,List<Integer>topo){
Queue<Integer>q = new LinkedList<>();
for(int i =1;i<indegree.length;i++){
if(indegree[i] == 0){
q.add(i);
topo.add(i);
}
}
while(!q.isEmpty()){
int cur = q.poll();
List<Integer>l = list.get(cur);
for(int i = 0;i<l.size();i++){
indegree[l.get(i)]--;
if(indegree[l.get(i)] == 0){
q.add(l.get(i));
topo.add(l.get(i));
}
}
}
if(topo.size() == n)return false;
return true;
}
// function to find the parent of any given node with path compression in DSU
public static int find(int val,int[]parent){
if(val == parent[val])return val;
return parent[val] = find(parent[val],parent);
}
// function to connect two components
public static void union(int[]rank,int[]parent,int u,int v){
int a = find(u,parent);
int b= find(v,parent);
if(a == b)return;
if(rank[a] == rank[b]){
parent[b] = a;
rank[a]++;
}
else{
if(rank[a] > rank[b]){
parent[b] = a;
}
else{
parent[a] = b;
}
}
}
//
public static int findN(int n){
int num = 1;
while(num < n){
num *=2;
}
return num;
}
// code for input
public static void print(String s ){
System.out.print(s);
}
public static void print(int num ){
System.out.print(num);
}
public static void print(long num ){
System.out.print(num);
}
public static void println(String s){
System.out.println(s);
}
public static void println(int num){
System.out.println(num);
}
public static void println(long num){
System.out.println(num);
}
public static void println(){
System.out.println();
}
public static int Int(String s){
return Integer.parseInt(s);
}
public static long Long(String s){
return Long.parseLong(s);
}
public static String[] nextStringArray()throws IOException{
return bf.readLine().split(" ");
}
public static String nextString()throws IOException{
return bf.readLine();
}
public static long[] nextLongArray(int n)throws IOException{
String[]str = bf.readLine().split(" ");
long[]arr = new long[n];
for(int i =0;i<n;i++){
arr[i] = Long.parseLong(str[i]);
}
return arr;
}
public static int[][] newIntMatrix(int r,int c)throws IOException{
int[][]arr = new int[r][c];
for(int i =0;i<r;i++){
String[]str = bf.readLine().split(" ");
for(int j =0;j<c;j++){
arr[i][j] = Integer.parseInt(str[j]);
}
}
return arr;
}
public static long[][] newLongMatrix(int r,int c)throws IOException{
long[][]arr = new long[r][c];
for(int i =0;i<r;i++){
String[]str = bf.readLine().split(" ");
for(int j =0;j<c;j++){
arr[i][j] = Long.parseLong(str[j]);
}
}
return arr;
}
static class pair{
int one;
int two;
pair(int one,int two){
this.one = one ;
this.two =two;
}
}
public static long gcd(long a,long b){
if(b == 0)return a;
return gcd(b,a%b);
}
public static long lcm(long a,long b){
return (a*b)/(gcd(a,b));
}
public static boolean isPalindrome(String s){
int i = 0;
int j = s.length()-1;
while(i<=j){
if(s.charAt(i) != s.charAt(j)){
return false;
}
i++;
j--;
}
return true;
}
// these functions are to calculate the number of smaller elements after self
public static void sort(int[]arr,int l,int r){
if(l < r){
int mid = (l+r)/2;
sort(arr,l,mid);
sort(arr,mid+1,r);
smallerNumberAfterSelf(arr, l, mid, r);
}
}
public static void smallerNumberAfterSelf(int[]arr,int l,int mid,int r){
int n1 = mid - l +1;
int n2 = r - mid;
int []a = new int[n1];
int[]b = new int[n2];
for(int i = 0;i<n1;i++){
a[i] = arr[l+i];
}
for(int i =0;i<n2;i++){
b[i] = arr[mid+i+1];
}
int i = 0;
int j =0;
int k = l;
while(i<n1 && j < n2){
if(a[i] < b[j]){
arr[k++] = a[i++];
}
else{
arr[k++] = b[j++];
}
}
while(i<n1){
arr[k++] = a[i++];
}
while(j<n2){
arr[k++] = b[j++];
}
}
public static String next(){
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(bf.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
static int nextInt() {
return Integer.parseInt(next());
}
static long nextLong() {
return Long.parseLong(next());
}
static double nextDouble() {
return Double.parseDouble(next());
}
static String nextLine(){
String str = "";
try {
str = bf.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
// use some math tricks it might help
// sometimes just try to think in straightforward plan in A and B problems don't always complecate the questions with thinking too much differently
// always use long number to do 10^9+7 modulo
// if a problem is related to binary string it could also be related to parenthesis
// *****try to use binary search(it is a very beautiful thing it can work in some of the very unexpected problems ) in the question it might work******
// try sorting
// try to think in opposite direction of question it might work in your way
// if a problem is related to maths try to relate some of the continuous subarray with variables like - > a+b+c+d or a,b,c,d in general
// if the question is to much related to left and/or right side of any element in an array then try monotonic stack it could work.
// in range query sums try to do binary search it could work
// analyse the time complexity of program thoroughly
// anylyse the test cases properly
// if we divide any number by 2 till it gets 1 then there will be (number - 1) operation required
// try to do the opposite operation of what is given in the problem
//think about the base cases properly
//If a question is related to numbers try prime factorisation or something related to number theory
// keep in mind unique strings
//you can calculate the number of inversion in O(n log n)
// in a matrix you could sometimes think about row and cols indenpendentaly.
// Try to think in more constructive(means a way to look through various cases of a problem) way.
// observe the problem carefully the answer could be hidden in the given test cases itself. (A, B , C);
// when we have equations like (a+b = N) and we have to find the max of (a*b) then the values near to the N/2 must be chosen as (a and b);
// give emphasis to the number of occurences of elements it might help.
// if a number is even then we can find the pair for each and every number in that range whose bitwise AND is zero.
// if a you find a problem related to the graph make a graph
// There is atleast one prime number between the interval [n , 3n/2];
// If a problem is related to maths then try to form an mathematical equation.
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 8
|
standard input
|
[
"binary search",
"interactive"
] |
eb660c470760117dfd0b95acc10eee3b
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,900
| null |
standard output
| |
PASSED
|
010c6fbbdf4f4cc40bb82699b319860d
|
train_109.jsonl
|
1613658900
|
The only difference between the easy and the hard version is the limit to the number of queries.This is an interactive problem.There is an array $$$a$$$ of $$$n$$$ different numbers. In one query you can ask the position of the second maximum element in a subsegment $$$a[l..r]$$$. Find the position of the maximum element in the array in no more than 20 queries.A subsegment $$$a[l..r]$$$ is all the elements $$$a_l, a_{l + 1}, ..., a_r$$$. After asking this subsegment you will be given the position of the second maximum from this subsegment in the whole array.
|
256 megabytes
|
import java.util.*;
// import java.util.concurrent.CountDownLatch;
// import javax.lang.model.element.QualifiedNameable;
// import javax.swing.ViewportLayout;
// import javax.swing.plaf.basic.BasicTreeUI.TreeCancelEditingAction;
// import javax.swing.plaf.metal.MetalComboBoxUI.MetalPropertyChangeListener;
// import javax.swing.text.html.HTMLDocument.HTMLReader.CharacterAction;
// import org.w3c.dom.Node;
import java.lang.*;
import java.math.BigInteger;
// import java.net.CookieHandler;
// import java.security.SecureRandomParameters;
// import java.security.cert.CollectionCertStoreParameters;
// import java.text.BreakIterator;
import java.io.*;
@SuppressWarnings("unchecked")
public class Main {
static FastReader in;
static PrintWriter out;
static int bit(long n) {
return (n == 0) ? 0 : (1 + bit(n & (n - 1)));
}
static void p(Object o) {
out.print(o);
}
static void pn(Object o) {
out.println(o);
}
static void pni(Object o) {
out.println(o);
out.flush();
}
static String n() throws Exception {
return in.next();
}
static String nln() throws Exception {
return in.nextLine();
}
static int ni() throws Exception {
return Integer.parseInt(in.next());
}
static long nl() throws Exception {
return Long.parseLong(in.next());
}
static double nd() throws Exception {
return Double.parseDouble(in.next());
}
static class FastReader {
static BufferedReader br;
static StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
public FastReader(String s) throws Exception {
br = new BufferedReader(new FileReader(s));
}
String next() throws Exception {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
throw new Exception(e.toString());
}
}
return st.nextToken();
}
String nextLine() throws Exception {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
throw new Exception(e.toString());
}
return str;
}
}
static long power(long a, long b) {
if (a == 0L)
return 0L;
if (b == 0)
return 1;
long val = power(a, b / 2);
val = val * val;
if ((b % 2) != 0)
val = val * a;
return val;
}
static long power(long a, long b, long mod) {
if (a == 0L)
return 0L;
if (b == 0)
return 1;
long val = power(a, b / 2L, mod) % mod;
val = (val * val) % mod;
if ((b % 2) != 0)
val = (val * a) % mod;
return val;
}
static ArrayList<Long> prime_factors(long n) {
ArrayList<Long> ans = new ArrayList<Long>();
while (n % 2 == 0) {
ans.add(2L);
n /= 2L;
}
for (long i = 3; i <= Math.sqrt(n); i++) {
while (n % i == 0) {
ans.add(i);
n /= i;
}
}
if (n > 2) {
ans.add(n);
}
return ans;
}
static void sort(ArrayList<Long> a) {
Collections.sort(a);
}
static void reverse_sort(ArrayList<Long> a) {
Collections.sort(a, Collections.reverseOrder());
}
static void swap(long[] a, int i, int j) {
long temp = a[i];
a[i] = a[j];
a[j] = temp;
}
static void swap(List<Long> a, int i, int j) {
long temp = a.get(i);
a.set(j, a.get(i));
a.set(j, temp);
}
static void sieve(boolean[] prime) {
int n = prime.length - 1;
Arrays.fill(prime, true);
for (int i = 2; i * i <= n; i++) {
if (prime[i]) {
for (int j = i * i; j <= n; j += i) {
prime[j] = false;
}
}
}
}
static long gcd(long a, long b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
public static void sort(long[] arr, int l, int r) {
if (l >= r)
return;
int mid = (l + r) / 2;
sort(arr, l, mid);
sort(arr, mid + 1, r);
merge(arr, l, mid, r);
}
public static void sort(int[] arr, int l, int r) {
if (l >= r)
return;
int mid = (l + r) / 2;
sort(arr, l, mid);
sort(arr, mid + 1, r);
merge(arr, l, mid, r);
}
static void merge(int[] arr, int l, int mid, int r) {
int[] left = new int[mid - l + 1];
int[] right = new int[r - mid];
for (int i = l; i <= mid; i++) {
left[i - l] = arr[i];
}
for (int i = mid + 1; i <= r; i++) {
right[i - (mid + 1)] = arr[i];
}
int left_start = 0;
int right_start = 0;
int left_length = mid - l + 1;
int right_length = r - mid;
int temp = l;
while (left_start < left_length && right_start < right_length) {
if (left[left_start] < right[right_start]) {
arr[temp] = left[left_start++];
} else {
arr[temp] = right[right_start++];
}
temp++;
}
while (left_start < left_length) {
arr[temp++] = left[left_start++];
}
while (right_start < right_length) {
arr[temp++] = right[right_start++];
}
}
static void merge(long[] arr, int l, int mid, int r) {
long[] left = new long[mid - l + 1];
long[] right = new long[r - mid];
for (int i = l; i <= mid; i++) {
left[i - l] = arr[i];
}
for (int i = mid + 1; i <= r; i++) {
right[i - (mid + 1)] = arr[i];
}
int left_start = 0;
int right_start = 0;
int left_length = mid - l + 1;
int right_length = r - mid;
int temp = l;
while (left_start < left_length && right_start < right_length) {
if (left[left_start] < right[right_start]) {
arr[temp] = left[left_start++];
} else {
arr[temp] = right[right_start++];
}
temp++;
}
while (left_start < left_length) {
arr[temp++] = left[left_start++];
}
while (right_start < right_length) {
arr[temp++] = right[right_start++];
}
}
static HashMap<Long, Integer> map_prime_factors(long n) {
HashMap<Long, Integer> map = new HashMap<>();
while (n % 2 == 0) {
map.put(2L, map.getOrDefault(2L, 0) + 1);
n /= 2L;
}
for (long i = 3; i <= Math.sqrt(n); i++) {
while (n % i == 0) {
map.put(i, map.getOrDefault(i, 0) + 1);
n /= i;
}
}
if (n > 2) {
map.put(n, map.getOrDefault(n, 0) + 1);
}
return map;
}
static long divisor(long n) {
long count = 0;
for (long i = 1L; i * i <= n; i++) {
if (n % i == 0) {
if (i == n / i)
count += i;
else {
count += i;
count += n / i;
}
}
}
return count;
}
// static void smallest_prime_factor(int n) {
// smallest_prime_factor[1] = 1;
// for (int i = 2; i <= n; i++) {
// if (smallest_prime_factor[i] == 0) {
// smallest_prime_factor[i] = i;
// for (int j = i * i; j <= n; j += i) {
// if (smallest_prime_factor[j] == 0) {
// smallest_prime_factor[j] = i;
// }
// }
// }
// }
// }
// static int[] smallest_prime_factor;
// static int count = 1;
// static int[] p = new int[100002];
// static long[] flat_tree = new long[300002];
// static int[] in_time = new int[1000002];
// static int[] out_time = new int[1000002];
// static long[] subtree_gcd = new long[100002];
// static int w = 0;
// static boolean poss = true;
/*
* (a^b^c)%mod
* Using fermats Little theorem
* x^(mod-1)=1(mod)
* so b^c can be written as b^c=x*(mod-1)+y
* then (a^(x*(mod-1)+y))%mod=(a^(x*(mod-1))*a^(y))mod
* the term (a^(x*(mod-1)))%mod=a^(mod-1)*a^(mod-1)
*
*/
// ---------------------------------------------------Segment_Tree----------------------------------------------------------------//
static class comparator implements Comparator<node> {
public int compare(node a, node b) {
return a.value - b.value > 0 ? 1 : -1;
}
}
static class Segment_Tree {
private long[] segment_tree;
public Segment_Tree(int n) {
this.segment_tree = new long[4 * n + 1];
}
void build(int index, int left, int right, int[] a) {
if (left == right) {
segment_tree[index] = a[left];
return;
}
int mid = (left + right) / 2;
build(2 * index + 1, left, mid, a);
build(2 * index + 2, mid + 1, right, a);
segment_tree[index] = segment_tree[2 * index + 1] + segment_tree[2 * index + 2];
}
long query(int index, int left, int right, int l, int r) {
if (left > right)
return 0;
if (left >= l && r >= right) {
return segment_tree[index];
}
if (l > right || left > r)
return 0;
int mid = (left + right) / 2;
return query(2 * index + 1, left, mid, l, r) + query(2 * index + 2, mid + 1, right, l, r);
}
void update(int index, int left, int right, int node, int val) {
if (left == right) {
segment_tree[index] += val;
return;
}
int mid = (left + right) / 2;
if (node <= mid)
update(2 * index + 1, left, mid, node, val);
else
update(2 * index + 2, mid + 1, right, node, val);
segment_tree[index] = segment_tree[2 * index + 1] + segment_tree[2 * index + 2];
}
}
// ------------------------------------------------------ DSU
// --------------------------------------------------------------------//
class dsu {
private int[] parent;
private int[] rank;
private int[] size;
public dsu(int n) {
this.parent = new int[n + 1];
this.rank = new int[n + 1];
this.size = new int[n + 1];
for (int i = 0; i <= n; i++) {
parent[i] = i;
rank[i] = 1;
size[i] = 1;
}
}
int findParent(int a) {
if (parent[a] == a)
return a;
else
return parent[a] = findParent(parent[a]);
}
void join(int a, int b) {
int parent_a = findParent(a);
int parent_b = findParent(b);
if (parent_a == parent_b)
return;
if (rank[parent_a] > rank[parent_b]) {
parent[parent_b] = parent_a;
size[parent_a] += size[parent_b];
} else if (rank[parent_a] < rank[parent_b]) {
parent[parent_a] = parent_b;
size[parent_b] += size[parent_a];
} else {
parent[parent_a] = parent_b;
size[parent_b] += size[parent_a];
rank[parent_b]++;
}
}
}
// ------------------------------------------------Comparable---------------------------------------------------------------------//
static class pair implements Comparable<pair> {
int a;
int b;
int dir;
public pair(int a, int b, int dir) {
this.a = a;
this.b = b;
this.dir = dir;
}
public int compareTo(pair p) {
// if (this.b == Integer.MIN_VALUE || p.b == Integer.MIN_VALUE)
// return (int) (this.index - p.index);
return (int) (this.a - p.a);
}
}
static class pair2 implements Comparable<pair2> {
long a;
int index;
public pair2(long a, int index) {
this.a = a;
this.index = index;
}
public int compareTo(pair2 p) {
return (int) (this.a - p.a);
}
}
static class node {
long value;
int index;
public node(long value, int index) {
this.value = value;
this.index = index;
}
}
// static int ans = 0;
static int ans = 0;
static int leaf = 0;
static boolean poss = true;
static int bottom = Integer.MAX_VALUE;
static int right = Integer.MAX_VALUE;
static int max_right;
static int max_bottom;
static long mod = 1000000007L;
int glo = 0;
static int[] dx = { 0, 0, -1, 1 };
static int[] dy = { 1, -1, 0, 0 };
public static void main(String[] args) throws Exception {
in = new FastReader();
out = new PrintWriter(System.out);
int tc = 1;
while (tc-- > 0) {
int n=ni();
pn("? 1 "+n);
out.flush();
int second=ni();
if(second!=1)pn("? 1 "+second);
if(second!=1)out.flush();
boolean left=((second!=1) &&(ni()==second) )?true:false;
if(left){
int l=1;
int r=second;
while(l+1<r){
int mid=l+(r-l)/2;
pn("? "+mid+" "+second);
out.flush();
int val=ni();
if(val==second)
{
l=mid;
}else r=mid;
}
pn("! "+l);
}else{
int l=second;
int r=n;
while(l+1<r){
int mid=l+(r-l)/2;
pn("? "+second+" "+mid);
out.flush();
int val=ni();
if(val==second)
{
r=mid;
}else l=mid;
}
pn("! "+r);
}
}
out.flush();
out.close();
}
static void dfs(int i, int j, int[][] c, boolean[][] visited) {
int n = c.length;
visited[i][j] = true;
for (int k = 0; k < 4; k++) {
int a = i + dx[k];
int b = j + dy[k];
if (a >= 0 && b >= 0 && a < n && b < n && !visited[a][b]) {
dfs(a, b, c, visited);
}
}
}
static void factorial(long[] fact, long[] fact_inv, int n, long mod) {
fact[0] = 1;
for (int i = 1; i < n; i++) {
fact[i] = (i * fact[i - 1]) % mod;
}
for (int i = 0; i < n; i++) {
fact_inv[i] = power(fact[i], mod - 2, mod);// (1/x)%m can be calculated by fermat's little theoram which is
// (x**(m-2))%m when m is prime
}
//(a^(b^c))%m is equal to, let res=(b^c)%(m-1) then (a^res)%m
//https://www.geeksforgeeks.org/find-power-power-mod-prime/?ref=rp
}
static void find(int i, int n, int[] row, int[] col, int[] d1, int[] d2) {
if (i >= n) {
ans++;
return;
}
for (int j = 0; j < n; j++) {
if (col[j] == 0 && d1[i - j + n - 1] == 0 && d2[i + j] == 0) {
col[j] = 1;
d1[i - j + n - 1] = 1;
d2[i + j] = 1;
find(i + 1, n, row, col, d1, d2);
col[j] = 0;
d1[i - j + n - 1] = 0;
d2[i + j] = 0;
}
}
}
static int answer(int l, int r, int[][] dp) {
if (l > r)
return 0;
if (l == r) {
dp[l][r] = 1;
return 1;
}
if (dp[l][r] != -1)
return dp[l][r];
int val = Integer.MIN_VALUE;
int mid = l + (r - l) / 2;
val = 1 + Math.max(answer(l, mid - 1, dp), answer(mid + 1, r, dp));
return dp[l][r] = val;
}
static TreeSet<Integer> ans(int n) {
TreeSet<Integer> set = new TreeSet<>();
for (int i = 1; i * i <= n; i++) {
if (n % i == 0) {
set.add(i);
set.add(n / i);
}
}
set.remove(1);
return set;
}
// static long find(String s, int i, int n, long[] dp) {
// // pn(i);
// if (i >= n)
// return 1L;
// if (s.charAt(i) == '0')
// return 0;
// if (i == n - 1)
// return 1L;
// if (dp[i] != -1)
// return dp[i];
// if (s.substring(i, i + 2).equals("10") || s.substring(i, i + 2).equals("20"))
// {
// return dp[i] = (find(s, i + 2, n, dp)) % mod;
// }
// if ((s.charAt(i) == '1' || (s.charAt(i) == '2' && s.charAt(i + 1) - '0' <=
// 6))
// && ((i + 2 < n ? (s.charAt(i + 2) != '0' ? true : false) : (i + 2 == n ? true
// : false)))) {
// return dp[i] = (find(s, i + 1, n, dp) + find(s, i + 2, n, dp)) % mod;
// } else
// return dp[i] = (find(s, i + 1, n, dp)) % mod;
static void print(int[] a) {
for (int i = 0; i < a.length; i++)
p(a[i] + " ");
pn("");
}
static long count(long n) {
long count = 0;
while (n != 0) {
count += n % 10;
n /= 10;
}
return count;
}
static void swap(int[] a, int i, int j) {
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
static int LcsOfPrefix(String a, String b) {
int i = 0;
int j = 0;
int count = 0;
while (i < a.length() && j < b.length()) {
if (a.charAt(i) == b.charAt(j)) {
j++;
count++;
}
i++;
}
return a.length() + b.length() - 2 * count;
}
static void reverse(int[] a, int n) {
for (int i = 0; i < n / 2; i++) {
int temp = a[i];
a[i] = a[n - i - 1];
a[n - i - 1] = temp;
}
}
static char get_char(int a) {
return (char) (a + 'a');
}
static int find1(int[] a, int val) {
int ans = -1;
int l = 0;
int r = a.length - 1;
while (l <= r) {
int mid = l + (r - l) / 2;
if (a[mid] <= val) {
l = mid + 1;
ans = mid;
} else
r = mid - 1;
}
return ans;
}
static int find2(int[] a, int val) {
int l = 0;
int r = a.length - 1;
int ans = -1;
while (l <= r) {
int mid = l + (r - l) / 2;
if (a[mid] <= val) {
ans = mid;
l = mid + 1;
} else
r = mid - 1;
}
return ans;
}
// static void dfs(List<List<Integer>> arr, int node, int parent, long[] val) {
// p[node] = parent;
// in_time[node] = count;
// flat_tree[count] = val[node];
// subtree_gcd[node] = val[node];
// count++;
// for (int adj : arr.get(node)) {
// if (adj == parent)
// continue;
// dfs(arr, adj, node, val);
// subtree_gcd[node] = gcd(subtree_gcd[adj], subtree_gcd[node]);
// }
// out_time[node] = count;
// flat_tree[count] = val[node];
// count++;
// }
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 8
|
standard input
|
[
"binary search",
"interactive"
] |
eb660c470760117dfd0b95acc10eee3b
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,900
| null |
standard output
| |
PASSED
|
0a5fece048154fd9c41d2681e851c032
|
train_109.jsonl
|
1613658900
|
The only difference between the easy and the hard version is the limit to the number of queries.This is an interactive problem.There is an array $$$a$$$ of $$$n$$$ different numbers. In one query you can ask the position of the second maximum element in a subsegment $$$a[l..r]$$$. Find the position of the maximum element in the array in no more than 20 queries.A subsegment $$$a[l..r]$$$ is all the elements $$$a_l, a_{l + 1}, ..., a_r$$$. After asking this subsegment you will be given the position of the second maximum from this subsegment in the whole array.
|
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.HashMap;
import java.util.HashSet;
import java.util.Random;
import java.util.Stack;
import java.util.StringTokenizer;
// CFPS -> CodeForcesProblemSet
public final class CFPS {
static FastReader fr = new FastReader();
static PrintWriter out = new PrintWriter(System.out);
static final int gigamod = 1000000007;
static int t = 1;
static double epsilon = 0.0000001;
static boolean[] isPrime;
static int[] smallestFactorOf;
@SuppressWarnings("unused")
public static void main(String[] args) {
OUTER:
for (int tc = 0; tc < t; tc++) {
int n = fr.nextInt();
int lptr = 0, rptr = n - 1;
// First, we will find the secondLargestIdx, which will be
// pivotal in solving the problem. (PUN INTENDED).
out.println("? 1 " + (n));
out.flush();
int slIdx = fr.nextInt() - 1;
// Now, we will reduce the search space once, just to ensure that
// slIdx does not belong to it.
if (lptr < slIdx) {
// We can consider [lptr, slIdx] for the query.
out.println("? 1 " + (slIdx + 1));
out.flush();
int slNew = fr.nextInt() - 1;
if (slNew == slIdx)
// This exact segment contains the max.
rptr = slIdx - 1;
else
lptr = slIdx + 1;
} else {
// We will have to consider [slIdx, rptr] for the query.
out.println("? " + (slIdx + 1) + " " + (rptr + 1));
out.flush();
int slNew = fr.nextInt() - 1;
if (slNew == slIdx)
// This segment contains the max.
lptr = slIdx + 1;
else
rptr = slIdx - 1;
}
while (lptr != rptr) {
if (rptr == lptr + 1) {
// [lptr, lptr + 1] is the search space.
out.println("? " + (lptr + 1) + " " + (lptr + 2));
out.flush();
int slNew = fr.nextInt() - 1;
if (slNew == lptr)
lptr = rptr;
else
rptr = lptr;
continue;
}
// out.println(lptr + " " + rptr);
// Now, we will try to shrink the search space.
if (rptr < slIdx) {
// [lptr, rptr] is on the left of slIdx.
int mid = lptr + (rptr - lptr) / 2;
// Now, we will query [mid, slIdx].
out.println("? " + (mid + 1) + " " + (slIdx + 1));
out.flush();
int slNew = fr.nextInt() - 1;
if (slNew == slIdx) {
// [mid, rptr] is the new search space.
lptr = mid;
}
else
// [mid, rptr] does not contain the max.
rptr = mid - 1;
} else if (lptr > slIdx) {
// [lptr, rptr] is on the right of slIdx.
int mid = lptr + (rptr - lptr) / 2;
// Now, we will query [slIdx, mid]
out.println("? " + (slIdx + 1) + " " + (mid + 1));
out.flush();
int slNew = fr.nextInt() - 1;
if (slNew == slIdx)
// [lptr, mid] is the new search space.
rptr = mid;
else
lptr = mid + 1;
}
}
out.println("! " + (lptr + 1));
}
out.close();
}
public static class FenwickTree {
long[] array; // 1-indexed array, In this array We save cumulative information to perform efficient range queries and updates
public FenwickTree(int size) {
array = new long[size + 1];
}
public long rsq(int ind) {
assert ind > 0;
long sum = 0;
while (ind > 0) {
sum += array[ind];
//Extracting the portion up to the first significant one of the binary representation of 'ind' and decrementing ind by that number
ind -= ind & (-ind);
}
return sum;
}
public long rsq(int a, int b) {
assert b >= a && a > 0 && b > 0;
return rsq(b) - rsq(a - 1);
}
public void update(int ind, long value) {
assert ind > 0;
while (ind < array.length) {
array[ind] += value;
//Extracting the portion up to the first significant one of the binary representation of 'ind' and incrementing ind by that number
ind += ind & (-ind);
}
}
public int size() {
return array.length - 1;
}
}
static int longestPrefixPalindromeLen(char[] s) {
int n = s.length;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++)
sb.append(s[i]);
StringBuilder sb2 = new StringBuilder(sb);
sb.append('^');
sb.append(sb2.reverse());
// out.println(sb.toString());
char[] newS = sb.toString().toCharArray();
int m = newS.length;
int[] pi = piCalcKMP(newS);
return pi[m - 1];
}
static int KMPNumOcc(char[] text, char[] pat) {
int n = text.length;
int m = pat.length;
char[] patPlusText = new char[n + m + 1];
for (int i = 0; i < m; i++)
patPlusText[i] = pat[i];
patPlusText[m] = '^'; // Seperator
for (int i = 0; i < n; i++)
patPlusText[m + i] = text[i];
int[] fullPi = piCalcKMP(patPlusText);
int answer = 0;
for (int i = 0; i < n + m + 1; i++)
if (fullPi[i] == m)
answer++;
return answer;
}
static int[] piCalcKMP(char[] s) {
int n = s.length;
int[] pi = new int[n];
for (int i = 1; i < n; i++) {
int j = pi[i - 1];
while (j > 0 && s[i] != s[j])
j = pi[j - 1];
if (s[i] == s[j])
j++;
pi[i] = j;
}
return pi;
}
static String toBinaryString(long num, int bits) {
StringBuilder sb = new StringBuilder(Long.toBinaryString(num));
sb.reverse();
for (int i = sb.length(); i < bits; i++)
sb.append('0');
return sb.reverse().toString();
}
// Manual implementation of RB-BST for C++ PBDS functionality.
// Modification required according to requirements.
public static final class RedBlackCountSet {
// Colors for Nodes:
private static final boolean RED = true;
private static final boolean BLACK = false;
// Pointer to the root:
private Node root;
// Public constructor:
public RedBlackCountSet() {
root = null;
}
// Node class for storing key value pairs:
private class Node {
long key;
long value;
Node left, right;
boolean color;
long size; // Size of the subtree rooted at that node.
public Node(long key, long value, boolean color) {
this.key = key;
this.value = value;
this.left = this.right = null;
this.color = color;
this.size = value;
}
}
/***** Invariant Maintenance functions: *****/
// When a temporary 4 node is formed:
private Node flipColors(Node node) {
node.left.color = node.right.color = BLACK;
node.color = RED;
return node;
}
// When there's a right leaning red link and it is not a 3 node:
private Node rotateLeft(Node node) {
Node rn = node.right;
node.right = rn.left;
rn.left = node;
rn.color = node.color;
node.color = RED;
return rn;
}
// When there are 2 red links in a row:
private Node rotateRight(Node node) {
Node ln = node.left;
node.left = ln.right;
ln.right = node;
ln.color = node.color;
node.color = RED;
return ln;
}
/***** Invariant Maintenance functions end *****/
// Public functions:
public void put(long key) {
root = put(root, key);
root.color = BLACK; // One of the invariants.
}
private Node put(Node node, long key) {
// Standard insertion procedure:
if (node == null)
return new Node(key, 1, RED);
// Recursing:
int cmp = Long.compare(key, node.key);
if (cmp < 0)
node.left = put(node.left, key);
else if (cmp > 0)
node.right = put(node.right, key);
else
node.value++;
// Invariant maintenance:
if (node.left != null && node.right != null) {
if (node.right.color = RED && node.left.color == BLACK)
node = rotateLeft(node);
if (node.left.color == RED && node.left.left.color == RED)
node = rotateRight(node);
if (node.left.color == RED && node.right.color == RED)
node = flipColors(node);
}
// Property maintenance:
node.size = node.value + size(node.left) + size(node.right);
return node;
}
private long size(Node node) {
if (node == null)
return 0;
else
return node.size;
}
public long rank(long key) {
return rank(root, key);
}
// Modify according to requirements.
private long rank(Node node, long key) {
if (node == null) return 0;
int cmp = Long.compare(key, node.key);
if (cmp < 0)
return rank(node.left, key);
else if (cmp > 0)
return node.value + size(node.left) + rank(node.right, key);
else
return node.value + size(node.left);
}
}
static long modDiv(long a, long b) {
return mod(a * power(b, gigamod - 2, gigamod));
}
static class SegTree {
// Setting up the parameters.
int n; // Size of the array
long[] sumTree;
long[] ogArr;
long[] maxTree;
long[] minTree;
boolean[] prpgtMarked; // For segment assignment operation with
// lazy updates
public static final int sumMode = 0;
public static final int maxMode = 1;
public static final int minMode = 2;
// Constructor
public SegTree(long[] arr, int mode) {
if (mode == sumMode) {
Arrays.fill(sumTree = new long[4 * (n = ((ogArr = arr.clone()).length))], -1);
buildSum(0, n - 1, 0);
} else if (mode == maxMode) {
Arrays.fill(maxTree = new long[4 * (n = ((ogArr = arr.clone()).length))], -1);
buildMax(0, n - 1, 0);
} else if (mode == minMode) {
Arrays.fill(minTree = new long[4 * (n = ((ogArr = arr.clone()).length))], Long.MAX_VALUE - 1);
buildMin(0, n - 1, 0);
}
prpgtMarked = new boolean[minTree.length];
}
/**********Code for sum***********/
/*********************************/
// Build the segment tree node-by-node
private long buildSum(int l, int r, int segIdx) {
return sumTree[segIdx] = (l == r) ? ogArr[l] :
(buildSum(l, l + (r - l) / 2, 2 * segIdx + 1)
+ buildSum((l + (r - l) / 2) + 1, r, 2 * segIdx + 2));
}
// Change a single element
public void changeForSum(int idx, long to) {
changeForSum(idx, to, 0, n - 1, 0);
}
private long changeForSum(int idx, long to, int l, int r, int segIdx) {
return sumTree[segIdx] =
((l == r) ? (ogArr[idx] = to) :
((0 * ((idx <= (l + (r - l) / 2))
? changeForSum(idx, to, l, l + (r - l) / 2, 2 * segIdx + 1)
: changeForSum(idx, to, (l + (r - l) / 2) + 1, r, 2 * segIdx + 2)))
+ sumTree[2 * segIdx + 1] + sumTree[2 * segIdx + 2]));
}
// Return the sum arr[l, r]
public long segSum(int l, int r) {
if (l > r) return 0;
return segSum(l, r, 0, n - 1, 0);
}
private long segSum(int segL, int segR, int l, int r, int segIdx) {
if (segL == l && segR == r)
return sumTree[segIdx];
if (segR <= l + (r - l) / 2)
return segSum(segL, segR, l, l + (r - l) / 2, 2 * segIdx + 1);
if (segL >= l + (r - l) / 2 + 1)
return segSum(segL, segR, l + (r - l) / 2 + 1, r, 2 * segIdx + 2);
return segSum(segL, l + (r - l) / 2, l, l + (r - l) / 2, 2 * segIdx + 1)
+ segSum(l + (r - l) / 2 + 1, segR, l + (r - l) / 2 + 1, r, 2 * segIdx + 2);
}
/********End of code for sum********/
/***********************************/
/*******Start of code for max*******/
/***********************************/
// Build the max tree node-by-node
private long buildMax(int l, int r, int segIdx) {
return maxTree[segIdx] = (l == r) ? ogArr[l] :
Math.max(buildMax(l, (l + (r - l) / 2), 2 * segIdx + 1),
buildMax(l + (r - l) / 2 + 1, r, 2 * segIdx + 2));
}
// Change a single element
public void changeForMax(int idx, long to) {
changeForMax(0, n - 1, idx, to, 0);
}
private long changeForMax(int l, int r, int idx, long to, int segIdx) {
return maxTree[segIdx] = (l == r && l == idx) ? (ogArr[idx] = to) :
Math.max(changeForMax(l, l + (r - l) / 2, idx, to, 2 * segIdx + 1),
changeForMax(l + (r - l) / 2 + 1, r, idx, to, 2 * segIdx + 2));
}
public long segMax(int segL, int segR) {
if (segL > segR) return 0;
return segMax(0, n - 1, segL, segR, 0);
}
private long segMax(int l, int r, int segL, int segR, int segIdx) {
int midL = l + (r - l) / 2;
if (segL == segR && segL == l)
return ogArr[segL];
if (segR <= midL)
return segMax(l, midL, segL, segR, 2 * segIdx + 1);
if (segL >= midL + 1)
return segMax(midL + 1, r, segL, segR, 2 * segIdx + 2);
return Math.max(segMax(l, midL, segL, midL, 2 * segIdx + 1),
segMax(midL + 1, r, midL + 1, segR, 2 * segIdx + 2));
}
/*******End of code for max*********/
/***********************************/
/*******Start of code for min*******/
/***********************************/
private long buildMin(int l, int r, int segIdx) {
return minTree[segIdx] = (l == r) ? ogArr[l] :
Math.min(buildMin(l, (l + (r - l) / 2), 2 * segIdx + 1),
buildMin(l + (r - l) / 2 + 1, r, 2 * segIdx + 2));
}
// Change a single element
public void pointUpdate(int idx, long to) {
pointUpdate(0, n - 1, idx, to, 0);
}
private long pointUpdate(int l, int r, int idx, long to, int segIdx) {
asmtPush(l, r, segIdx);
return minTree[segIdx] = (l == r && l == idx) ? (to) :
Math.min(pointUpdate(l, l + (r - l) / 2, idx, to, 2 * segIdx + 1),
pointUpdate(l + (r - l) / 2 + 1, r, idx, to, 2 * segIdx + 2));
}
// Change a whole segment
public void rangeUpdate(int segL, int segR, long to) {
rangeUpdate(0, n - 1, segL, segR, to, 0);
}
private long rangeUpdate(int l, int r, int segL, int segR, long to, int segIdx) {
asmtPush(l, r, segIdx); // Since we will obviously recurse.
if (l == segL && r == segR) {
prpgtMarked[segIdx] = true;
return minTree[segIdx] = to;
}
int midL = l + (r - l) / 2;
if (segR <= midL)
return minTree[segIdx] = rangeUpdate(l, midL, segL, segR, to, 2 * segIdx + 1);
if (segL >= midL + 1)
return minTree[segIdx] = rangeUpdate(midL + 1, r, segL, segR, to, 2 * segIdx + 2);
return minTree[segIdx] = Math.min(rangeUpdate(l, midL, segL, midL, to, 2 * segIdx + 1),
rangeUpdate(midL + 1, r, midL + 1, segR, to, 2 * segIdx + 2));
}
public long rangeMin(int segL, int segR) {
if (segL > segR) return 0;
return rangeMin(0, n - 1, segL, segR, 0);
}
private long rangeMin(int l, int r, int segL, int segR, int segIdx) {
asmtPush(l, r, segIdx);
int midL = l + (r - l) / 2;
if (segL == l && segR == r)
return minTree[segIdx];
if (segR <= midL)
return rangeMin(l, midL, segL, segR, 2 * segIdx + 1);
if (segL >= midL + 1)
return rangeMin(midL + 1, r, segL, segR, 2 * segIdx + 2);
return Math.min(rangeMin(l, midL, segL, midL, 2 * segIdx + 1),
rangeMin(midL + 1, r, midL + 1, segR, 2 * segIdx + 2));
}
/*******End of code for min*********/
/***********************************/
/*** Auxiliary functions for all modes ***/
// If it is determined that a whole segment has to be assigned some value
// 'v', all children are bound to have the exact value 'v'.
void asmtPush(int l, int r, int segIdx) {
if (!prpgtMarked[segIdx])
return;
int child1 = 2 * segIdx + 1, child2 = 2 * segIdx + 2;
if (child2 > 4 * n - 1)
child2 = child1;
if (child1 > 4 * n - 1)
return;
minTree[child1] = minTree[child2] = minTree[segIdx];
prpgtMarked[child1] = prpgtMarked[child2] = true;
prpgtMarked[segIdx] = false;
}
/*** Auxiliary functions for all modes end***/
public String toString() {
return CFPS.toString(minTree);
}
}
@SuppressWarnings("serial")
static class CountMap<T> extends HashMap<T, Integer>{
CountMap() {
}
CountMap(T[] arr) {
this.putCM(arr);
}
public Integer putCM(T key) {
if (super.containsKey(key)) {
return super.put(key, super.get(key) + 1);
} else {
return super.put(key, 1);
}
}
public Integer removeCM(T key) {
Integer count = super.get(key);
if (count == null) return -1;
if (count == 1)
return super.remove(key);
else
return super.put(key, super.get(key) - 1);
}
public Integer getCM(T key) {
Integer count = super.get(key);
if (count == null)
return 0;
return count;
}
public void putCM(T[] arr) {
for (T l : arr)
this.putCM(l);
}
}
static void coprimeGenerator(int m, int n, ArrayList<Point> coprimes, int limit, int numCoprimes) {
if (m > limit) return;
if (m <= limit && n <= limit)
coprimes.add(new Point(m, n));
if (coprimes.size() > numCoprimes) return;
coprimeGenerator(2 * m - n, m, coprimes, limit, numCoprimes);
coprimeGenerator(2 * m + n, m, coprimes, limit, numCoprimes);
coprimeGenerator(m + 2 * n, n, coprimes, limit, numCoprimes);
}
static long hash(long i) {
return (i * 2654435761L % gigamod);
}
static long hash2(long key) {
long h = Long.hashCode(key);
h ^= (h >>> 20) ^ (h >>> 12) ^ (h >>> 7) ^ (h >>> 4);
return h & (gigamod-1);
}
// Maps elements in a 2D matrix serially to elements in
// a 1D array.
static int mapTo1D(int row, int col, int n, int m) {
return row * m + col;
}
// Inverse of what the one above does.
static int[] mapTo2D(int idx, int n, int m) {
int[] rnc = new int[2];
rnc[0] = idx / m;
rnc[1] = idx % m;
return rnc;
}
static class Point implements Comparable<Point> {
long x;
long y;
long id;
Point() {
x = y = id = 0;
}
Point(Point p) {
this.x = p.x;
this.y = p.y;
this.id = p.id;
}
Point(long a, long b, long id) {
this.x = a;
this.y = b;
this.id = id;
}
Point(long a, long b) {
this.x = a;
this.y = b;
}
@Override
public int compareTo(Point o) {
if (this.x < o.x)
return -1;
if (this.x > o.x)
return 1;
if (this.y < o.y)
return -1;
if (this.y > o.y)
return 1;
return 0;
}
public boolean equals(Point that) {
return this.compareTo(that) == 0;
}
}
static double distance(Point p1, Point p2) {
return Math.sqrt(Math.pow(p2.y-p1.y, 2) + Math.pow(p2.x-p1.x, 2));
}
static HashMap<Integer, Integer> smolNumPrimeFactorization(int num) {
if (smallestFactorOf == null)
primeGenerator(2750132);
CountMap<Integer> fnps = new CountMap<>();
while (num != 1) {
fnps.putCM(smallestFactorOf[num]);
num /= smallestFactorOf[num];
}
return fnps;
}
// Returns map of factor and its power in the number.
static HashMap<Long, Integer> primeFactorization(long num) {
HashMap<Long, Integer> map = new HashMap<>();
while (num % 2 == 0) {
num /= 2;
Integer pwrCnt = map.get(2L);
map.put(2L, pwrCnt != null ? pwrCnt + 1 : 1);
}
for (long i = 3; i * i <= num; i += 2) {
while (num % i == 0) {
num /= i;
Integer pwrCnt = map.get(i);
map.put(i, pwrCnt != null ? pwrCnt + 1 : 1);
}
}
// If the number is prime, we have to add it to the
// map.
if (num != 1)
map.put(num, 1);
return map;
}
static HashSet<Long> divisors(long num) {
HashSet<Long> divisors = new HashSet<Long>();
divisors.add(1L);
divisors.add(num);
for (long i = 2; i * i <= num; i++) {
if (num % i == 0) {
divisors.add(num/i);
divisors.add(i);
}
}
return divisors;
}
// Returns the index of the first element
// larger than or equal to val.
static int bsearch(int[] arr, int val, int lo, int hi) {
int idx = -1;
while (lo <= hi) {
int mid = lo + (hi - lo)/2;
if (arr[mid] >= val) {
idx = mid;
hi = mid - 1;
} else
lo = mid + 1;
}
return idx;
}
static int bsearch(long[] arr, long val, int lo, int hi) {
int idx = -1;
while (lo <= hi) {
int mid = lo + (hi - lo)/2;
if (arr[mid] >= val) {
idx = mid;
hi = mid - 1;
} else
lo = mid + 1;
}
return idx;
}
// Returns the index of the last element
// smaller than or equal to val.
static int bsearch(long[] arr, long val, int lo, int hi, boolean sMode) {
int idx = -1;
while (lo <= hi) {
int mid = lo + (hi - lo)/2;
if (arr[mid] >= val) {
hi = mid - 1;
} else {
idx = mid;
lo = mid + 1;
}
}
return idx;
}
static int bsearch(int[] arr, long val, int lo, int hi, boolean sMode) {
int idx = -1;
while (lo <= hi) {
int mid = lo + (hi - lo)/2;
if (arr[mid] > val) {
hi = mid - 1;
} else {
idx = mid;
lo = mid + 1;
}
}
return idx;
}
static long factorial(long n) {
if (n <= 1)
return 1;
long factorial = 1;
for (int i = 1; i <= n; i++)
factorial = mod(factorial * i);
return factorial;
}
static long factorialInDivision(long a, long b) {
if (a == b)
return 1;
if (b < a) {
long temp = a;
a = b;
b = temp;
}
long factorial = 1;
for (long i = a + 1; i <= b; i++)
factorial = mod(factorial * i);
return factorial;
}
static long nCr(long n, long r, long[] fac) {
long p = 998244353;
// Base case
if (r == 0)
return 1;
// Fill factorial array so that we
// can find all factorial of r, n
// and n-r
/*long fac[] = new long[(int)n + 1];
fac[0] = 1;
for (int i = 1; i <= n; i++)
fac[i] = fac[i - 1] * i % p;*/
return (fac[(int)n] * modInverse(fac[(int)r], p) % p
* modInverse(fac[(int)n - (int)r], p) % p) % p;
}
static long modInverse(long n, long p) {
return power(n, p - 2, p);
}
static long power(long x, long y, long p) {
long res = 1; // Initialize result
x = x % p; // Update x if it is more than or
// equal to p
while (y > 0) {
// If y is odd, multiply x with result
if ((y & 1)==1)
res = (res * x) % p;
// y must be even now
y = y >> 1; // y = y/2
x = (x * x) % p;
}
return res;
}
static long nPr(long n, long r) {
return factorialInDivision(n, n - r);
}
static int logk(long n, long k) {
return (int)(Math.log(n) / Math.log(k));
}
// Sieve of Eratosthenes:
static boolean[] primeGenerator(int upto) {
isPrime = new boolean[upto + 1];
smallestFactorOf = new int[upto + 1];
Arrays.fill(smallestFactorOf, 1);
Arrays.fill(isPrime, true);
isPrime[1] = isPrime[0] = false;
for (long i = 2; i < upto + 1; i++)
if (isPrime[(int) i]) {
smallestFactorOf[(int) i] = (int) i;
// Mark all the multiples greater than or equal
// to the square of i to be false.
for (long j = i; j * i < upto + 1; j++) {
if (isPrime[(int) j * (int) i]) {
isPrime[(int) j * (int) i] = false;
smallestFactorOf[(int) j * (int) i] = (int) i;
}
}
}
return isPrime;
}
static long gcd(long a, long b) {
if (b == 0) {
return a;
} else {
return gcd(b, a % b);
}
}
static int gcd(int a, int b) {
if (b == 0) {
return a;
} else {
return gcd(b, a % b);
}
}
static long gcd(long[] arr) {
int n = arr.length;
long gcd = arr[0];
for (int i = 1; i < n; i++) {
gcd = gcd(gcd, arr[i]);
}
return gcd;
}
static int gcd(int[] arr) {
int n = arr.length;
int gcd = arr[0];
for (int i = 1; i < n; i++) {
gcd = gcd(gcd, arr[i]);
}
return gcd;
}
static long lcm(long[] arr) {
long lcm = arr[0];
int n = arr.length;
for (int i = 1; i < n; i++) {
lcm = (lcm * arr[i]) / gcd(lcm, arr[i]);
}
return lcm;
}
static long lcm(long a, long b) {
return (a * b)/gcd(a, b);
}
static boolean less(int a, int b) {
return a < b ? true : false;
}
static boolean isSorted(int[] a) {
for (int i = 1; i < a.length; i++) {
if (less(a[i], a[i - 1]))
return false;
}
return true;
}
static boolean isSorted(long[] a) {
for (int i = 1; i < a.length; i++) {
if (a[i] < a[i - 1])
return false;
}
return true;
}
static void swap(int[] a, int i, int j) {
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
static void swap(long[] a, int i, int j) {
long temp = a[i];
a[i] = a[j];
a[j] = temp;
}
static void swap(double[] a, int i, int j) {
double temp = a[i];
a[i] = a[j];
a[j] = temp;
}
static void swap(char[] a, int i, int j) {
char temp = a[i];
a[i] = a[j];
a[j] = temp;
}
static void sort(int[] arr) {
shuffleArray(arr, 0, arr.length - 1);
Arrays.sort(arr);
}
static void sort(char[] arr) {
shuffleArray(arr, 0, arr.length - 1);
Arrays.sort(arr);
}
static void sort(long[] arr) {
shuffleArray(arr, 0, arr.length - 1);
Arrays.sort(arr);
}
static void sort(double[] arr) {
shuffleArray(arr, 0, arr.length - 1);
Arrays.sort(arr);
}
static void reverseSort(int[] arr) {
shuffleArray(arr, 0, arr.length - 1);
Arrays.sort(arr);
int n = arr.length;
for (int i = 0; i < n/2; i++)
swap(arr, i, n - 1 - i);
}
static void reverseSort(char[] arr) {
shuffleArray(arr, 0, arr.length - 1);
Arrays.sort(arr);
int n = arr.length;
for (int i = 0; i < n/2; i++)
swap(arr, i, n - 1 - i);
}
static void reverse(char[] arr) {
int n = arr.length;
for (int i = 0; i < n / 2; i++)
swap(arr, i, n - 1 - i);
}
static void reverseSort(long[] arr) {
shuffleArray(arr, 0, arr.length - 1);
Arrays.sort(arr);
int n = arr.length;
for (int i = 0; i < n/2; i++)
swap(arr, i, n - 1 - i);
}
static void reverseSort(double[] arr) {
shuffleArray(arr, 0, arr.length - 1);
Arrays.sort(arr);
int n = arr.length;
for (int i = 0; i < n/2; i++)
swap(arr, i, n - 1 - i);
}
static void shuffleArray(long[] arr, int startPos, int endPos) {
Random rnd = new Random();
for (int i = startPos; i < endPos; ++i) {
long tmp = arr[i];
int randomPos = i + rnd.nextInt(endPos - i);
arr[i] = arr[randomPos];
arr[randomPos] = tmp;
}
}
static void shuffleArray(int[] arr, int startPos, int endPos) {
Random rnd = new Random();
for (int i = startPos; i < endPos; ++i) {
int tmp = arr[i];
int randomPos = i + rnd.nextInt(endPos - i);
arr[i] = arr[randomPos];
arr[randomPos] = tmp;
}
}
static void shuffleArray(double[] arr, int startPos, int endPos) {
Random rnd = new Random();
for (int i = startPos; i < endPos; ++i) {
double tmp = arr[i];
int randomPos = i + rnd.nextInt(endPos - i);
arr[i] = arr[randomPos];
arr[randomPos] = tmp;
}
}
private static void shuffleArray(char[] arr, int startPos, int endPos) {
Random rnd = new Random();
for (int i = startPos; i < endPos; ++i) {
char tmp = arr[i];
int randomPos = i + rnd.nextInt(endPos - i);
arr[i] = arr[randomPos];
arr[randomPos] = tmp;
}
}
static boolean isPrime(long n) {
if (n <= 1)
return false;
if (n <= 3)
return true;
if (n % 2 == 0 || n % 3 == 0)
return false;
for (long i = 5; i * i <= n; i = i + 6)
if (n % i == 0 || n % (i + 2) == 0)
return false;
return true;
}
static String toString(int[] dp) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < dp.length; i++)
sb.append(dp[i] + " ");
return sb.toString();
}
static String toString(boolean[] dp) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < dp.length; i++)
sb.append(dp[i] + " ");
return sb.toString();
}
static String toString(long[] dp) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < dp.length; i++)
sb.append(dp[i] + " ");
return sb.toString();
}
static String toString(char[] dp) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < dp.length; i++)
sb.append(dp[i] + "");
return sb.toString();
}
static String toString(int[][] dp) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < dp.length; i++) {
for (int j = 0; j < dp[i].length; j++) {
sb.append(dp[i][j] + " ");
}
sb.append('\n');
}
return sb.toString();
}
static String toString(long[][] dp) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < dp.length; i++) {
for (int j = 0; j < dp[i].length; j++) {
sb.append(dp[i][j] + " ");
}
sb.append('\n');
}
return sb.toString();
}
static String toString(double[][] dp) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < dp.length; i++) {
for (int j = 0; j < dp[i].length; j++) {
sb.append(dp[i][j] + " ");
}
sb.append('\n');
}
return sb.toString();
}
static String toString(char[][] dp) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < dp.length; i++) {
for (int j = 0; j < dp[i].length; j++) {
sb.append(dp[i][j] + " ");
}
sb.append('\n');
}
return sb.toString();
}
static long mod(long a, long m) {
return (a%m + m) % m;
}
static long mod(long num) {
return (num % gigamod + gigamod) % gigamod;
}
// Uses weighted quick-union with path compression.
static class UnionFind {
private int[] parent; // parent[i] = parent of i
private int[] size; // size[i] = number of sites in tree rooted at i
// Note: not necessarily correct if i is not a root node
private int count; // number of components
public UnionFind(int n) {
count = n;
parent = new int[n];
size = new int[n];
for (int i = 0; i < n; i++) {
parent[i] = i;
size[i] = 1;
}
}
// Number of connected components.
public int count() {
return count;
}
// Find the root of p.
public int find(int p) {
while (p != parent[p])
p = parent[p];
return p;
}
public boolean connected(int p, int q) {
return find(p) == find(q);
}
public int numConnectedTo(int node) {
return size[find(node)];
}
// Weighted union.
public void union(int p, int q) {
int rootP = find(p);
int rootQ = find(q);
if (rootP == rootQ) return;
// make smaller root point to larger one
if (size[rootP] < size[rootQ]) {
parent[rootP] = rootQ;
size[rootQ] += size[rootP];
}
else {
parent[rootQ] = rootP;
size[rootP] += size[rootQ];
}
count--;
}
public static int[] connectedComponents(UnionFind uf) {
// We can do this in nlogn.
int n = uf.size.length;
int[] compoColors = new int[n];
for (int i = 0; i < n; i++)
compoColors[i] = uf.find(i);
HashMap<Integer, Integer> oldToNew = new HashMap<>();
int newCtr = 0;
for (int i = 0; i < n; i++) {
int thisOldColor = compoColors[i];
Integer thisNewColor = oldToNew.get(thisOldColor);
if (thisNewColor == null)
thisNewColor = newCtr++;
oldToNew.put(thisOldColor, thisNewColor);
compoColors[i] = thisNewColor;
}
return compoColors;
}
}
static class UGraph {
// Adjacency list.
private HashSet<Integer>[] adj;
private static final String NEWLINE = "\n";
private int E;
public UGraph(int V) {
adj = (HashSet<Integer>[]) new HashSet[V];
E = 0;
for (int i = 0; i < V; i++)
adj[i] = new HashSet<Integer>();
}
public void addEdge(int from, int to) {
if (adj[from].contains(to)) return;
E++;
adj[from].add(to);
adj[to].add(from);
}
public HashSet<Integer> adj(int from) {
return adj[from];
}
public int degree(int v) {
return adj[v].size();
}
public int V() {
return adj.length;
}
public int E() {
return E;
}
public String toString() {
StringBuilder s = new StringBuilder();
s.append(V() + " vertices, " + E() + " edges " + NEWLINE);
for (int v = 0; v < V(); v++) {
s.append(v + ": ");
for (int w : adj[v]) {
s.append(w + " ");
}
s.append(NEWLINE);
}
return s.toString();
}
public static void dfsMark(int current, boolean[] marked, UGraph g) {
if (marked[current]) return;
marked[current] = true;
Iterable<Integer> adj = g.adj(current);
for (int adjc : adj)
dfsMark(adjc, marked, g);
}
public static void dfsMark(int current, int from, long[] distTo, boolean[] marked, UGraph g, ArrayList<Integer> endPoints) {
if (marked[current]) return;
marked[current] = true;
if (from != -1)
distTo[current] = distTo[from] + 1;
HashSet<Integer> adj = g.adj(current);
int alreadyMarkedCtr = 0;
for (int adjc : adj) {
if (marked[adjc]) alreadyMarkedCtr++;
dfsMark(adjc, current, distTo, marked, g, endPoints);
}
if (alreadyMarkedCtr == adj.size())
endPoints.add(current);
}
public static void bfsOrder(int current, UGraph g) {
}
public static void dfsMark(int current, int[] colorIds, int color, UGraph g) {
if (colorIds[current] != -1) return;
colorIds[current] = color;
Iterable<Integer> adj = g.adj(current);
for (int adjc : adj)
dfsMark(adjc, colorIds, color, g);
}
public static int[] connectedComponents(UGraph g) {
int n = g.V();
int[] componentId = new int[n];
Arrays.fill(componentId, -1);
int colorCtr = 0;
for (int i = 0; i < n; i++) {
if (componentId[i] != -1) continue;
dfsMark(i, componentId, colorCtr, g);
colorCtr++;
}
return componentId;
}
public static boolean hasCycle(UGraph ug) {
int n = ug.V();
boolean[] marked = new boolean[n];
boolean[] hasCycleFirst = new boolean[1];
for (int i = 0; i < n; i++) {
if (marked[i]) continue;
hcDfsMark(i, ug, marked, hasCycleFirst, -1);
}
return hasCycleFirst[0];
}
// Helper for hasCycle.
private static void hcDfsMark(int current, UGraph ug, boolean[] marked, boolean[] hasCycleFirst, int parent) {
if (marked[current]) return;
if (hasCycleFirst[0]) return;
marked[current] = true;
HashSet<Integer> adjc = ug.adj(current);
for (int adj : adjc) {
if (marked[adj] && adj != parent && parent != -1) {
hasCycleFirst[0] = true;
return;
}
hcDfsMark(adj, ug, marked, hasCycleFirst, current);
}
}
}
static class Digraph {
// Adjacency list.
private HashSet<Integer>[] adj;
private static final String NEWLINE = "\n";
private int E;
public Digraph(int V) {
adj = (HashSet<Integer>[]) new HashSet[V];
E = 0;
for (int i = 0; i < V; i++)
adj[i] = new HashSet<Integer>();
}
public void addEdge(int from, int to) {
if (adj[from].contains(to)) return;
E++;
adj[from].add(to);
}
public HashSet<Integer> adj(int from) {
return adj[from];
}
public int V() {
return adj.length;
}
public int E() {
return E;
}
public Digraph reversed() {
Digraph dg = new Digraph(V());
for (int i = 0; i < V(); i++)
for (int adjVert : adj(i)) dg.addEdge(adjVert, i);
return dg;
}
public String toString() {
StringBuilder s = new StringBuilder();
s.append(V() + " vertices, " + E() + " edges " + NEWLINE);
for (int v = 0; v < V(); v++) {
s.append(v + ": ");
for (int w : adj[v]) {
s.append(w + " ");
}
s.append(NEWLINE);
}
return s.toString();
}
public static int[] KosarajuSharirSCC(Digraph dg) {
int[] id = new int[dg.V()];
Digraph reversed = dg.reversed();
// Gotta perform topological sort on this one to get the stack.
Stack<Integer> revStack = Digraph.topologicalSort(reversed);
// Initializing id and idCtr.
id = new int[dg.V()];
int idCtr = -1;
// Creating a 'marked' array.
boolean[] marked = new boolean[dg.V()];
while (!revStack.isEmpty()) {
int vertex = revStack.pop();
if (!marked[vertex])
sccDFS(dg, vertex, marked, ++idCtr, id);
}
return id;
}
private static void sccDFS(Digraph dg, int source, boolean[] marked, int idCtr, int[] id) {
marked[source] = true;
id[source] = idCtr;
for (Integer adjVertex : dg.adj(source))
if (!marked[adjVertex]) sccDFS(dg, adjVertex, marked, idCtr, id);
}
public static Stack<Integer> topologicalSort(Digraph dg) {
// dg has to be a directed acyclic graph.
// We'll have to run dfs on the digraph and push the deepest nodes on stack first.
// We'll need a Stack<Integer> and a int[] marked.
Stack<Integer> topologicalStack = new Stack<Integer>();
boolean[] marked = new boolean[dg.V()];
// Calling dfs
for (int i = 0; i < dg.V(); i++)
if (!marked[i])
runDfs(dg, topologicalStack, marked, i);
return topologicalStack;
}
static void runDfs(Digraph dg, Stack<Integer> topologicalStack, boolean[] marked, int source) {
marked[source] = true;
for (Integer adjVertex : dg.adj(source))
if (!marked[adjVertex])
runDfs(dg, topologicalStack, marked, adjVertex);
topologicalStack.add(source);
}
}
static class FastReader {
private BufferedReader bfr;
private StringTokenizer st;
public FastReader() {
bfr = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
if (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(bfr.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
char nextChar() {
return next().toCharArray()[0];
}
String nextString() {
return next();
}
int[] nextIntArray(int n) {
int[] arr = new int[n];
for (int i = 0; i < n; i++)
arr[i] = nextInt();
return arr;
}
double[] nextDoubleArray(int n) {
double[] arr = new double[n];
for (int i = 0; i < arr.length; i++)
arr[i] = nextDouble();
return arr;
}
long[] nextLongArray(int n) {
long[] arr = new long[n];
for (int i = 0; i < n; i++)
arr[i] = nextLong();
return arr;
}
int[][] nextIntGrid(int n, int m) {
int[][] grid = new int[n][m];
for (int i = 0; i < n; i++) {
char[] line = fr.next().toCharArray();
for (int j = 0; j < m; j++)
grid[i][j] = line[j] - 48;
}
return grid;
}
}
}
// NOTES:
// ASCII VALUE OF 'A': 65
// ASCII VALUE OF 'a': 97
// Range of long: 9 * 10^18
// ASCII VALUE OF '0': 48
// Primes upto 'n' can be given by (n / (logn)).
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 8
|
standard input
|
[
"binary search",
"interactive"
] |
eb660c470760117dfd0b95acc10eee3b
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,900
| null |
standard output
| |
PASSED
|
9af93967053aff08f2ec32cc97aa9d03
|
train_109.jsonl
|
1613658900
|
The only difference between the easy and the hard version is the limit to the number of queries.This is an interactive problem.There is an array $$$a$$$ of $$$n$$$ different numbers. In one query you can ask the position of the second maximum element in a subsegment $$$a[l..r]$$$. Find the position of the maximum element in the array in no more than 20 queries.A subsegment $$$a[l..r]$$$ is all the elements $$$a_l, a_{l + 1}, ..., a_r$$$. After asking this subsegment you will be given the position of the second maximum from this subsegment in the whole array.
|
256 megabytes
|
import java.util.*;
import java.io.*;
////***************************************************************************
/* public class E_Gardener_and_Tree implements Runnable{
public static void main(String[] args) throws Exception {
new Thread(null, new E_Gardener_and_Tree(), "E_Gardener_and_Tree", 1<<28).start();
}
public void run(){
WRITE YOUR CODE HERE!!!!
JUST WRITE EVERYTHING HERE WHICH YOU WRITE IN MAIN!!!
}
}
*/
/////**************************************************************************
public class C2_Guessing_the_Greatest_hard_version_{
public static void main(String[] args) {
FastScanner s= new FastScanner();
//PrintWriter out=new PrintWriter(System.out);
//end of program
//out.println(answer);
//out.close();
StringBuilder res = new StringBuilder();
int n=s.nextInt();
long index= query(1,n);
int check=1;
if(index==1){
check=1;
}
else if(index==n){
check=-1;
}
else{
long a1=query(1,index);
//long a2=query(index,n);
if(a1==index){
check=-1;
}
else{
check=1;
}
}
if(check==1){
long start=index;
long end=n;
long mid=0;
while(start<end){
mid=(start+end)/2;
if(start+1==end){
break;
}
long a1=query(index,mid);
if(a1==index){
end=mid;
}
else{
start=mid;
}
}
System.out.println("! "+end+" \n");
System.out.println();
System.out.flush();
}
else{
long start=1;
long end=index;
long mid=0;
while(start<end){
mid=(start+end)/2;
if(start+1==end){
break;
}
long a1=query(mid,index);
if(a1==index){
start=mid;
}
else{
end=mid;
}
}
System.out.println("! "+start+" \n");
System.out.println();
System.out.flush();
}
}
private static long query(long l, long r) {
FastScanner s= new FastScanner();
System.out.println("? "+l+" "+r+" \n");
System.out.println();
System.out.flush();
long a=s.nextLong();
return a;
}
static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(String s) {
try {
br = new BufferedReader(new FileReader(s));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public FastScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String nextToken() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(nextToken());
}
long nextLong() {
return Long.parseLong(nextToken());
}
double nextDouble() {
return Double.parseDouble(nextToken());
}
}
static long modpower(long x, long y, long p)
{
long res = 1; // Initialize result
x = x % p; // Update x if it is more than or
// equal to p
if (x == 0)
return 0; // In case x is divisible by p;
while (y > 0)
{
// If y is odd, multiply x with result
if ((y & 1) != 0)
res = (res * x) % p;
// y must be even now
y = y >> 1; // y = y/2
x = (x * x) % p;
}
return res;
}
// SIMPLE POWER FUNCTION=>
static long power(long x, long y)
{
long res = 1; // Initialize result
while (y > 0)
{
// If y is odd, multiply x with result
if ((y & 1) != 0)
res = res * x;
// y must be even now
y = y >> 1; // y = y/2
x = x * x; // Change x to x^2
}
return res;
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 8
|
standard input
|
[
"binary search",
"interactive"
] |
eb660c470760117dfd0b95acc10eee3b
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,900
| null |
standard output
| |
PASSED
|
f1522b964b01e447561090fe641335e1
|
train_109.jsonl
|
1613658900
|
The only difference between the easy and the hard version is the limit to the number of queries.This is an interactive problem.There is an array $$$a$$$ of $$$n$$$ different numbers. In one query you can ask the position of the second maximum element in a subsegment $$$a[l..r]$$$. Find the position of the maximum element in the array in no more than 20 queries.A subsegment $$$a[l..r]$$$ is all the elements $$$a_l, a_{l + 1}, ..., a_r$$$. After asking this subsegment you will be given the position of the second maximum from this subsegment in the whole array.
|
256 megabytes
|
import java.io.*;
import java.util.*;
import java.math.*;
import java.math.BigInteger;
//import javafx.util.*;
public final class B
{
static StringBuilder ans=new StringBuilder();
static FastReader in=new FastReader();
static ArrayList<ArrayList<Integer>> g;
static long mod=1000000007;
static int D1[],D2[],par[];
static boolean set[];
static long INF=Long.MAX_VALUE;
public static void main(String args[])throws IOException
{
int N=i();
int index=ask(1,N);
if(index==N || index==1)
{
if(index==1)System.out.println("! "+f2(1,N,index));
else System.out.println("! "+f1(1,N,index));
}
else if(ask(1,index)==index)
{
System.out.println("! "+f1(1,index,index));
}
else System.out.println("! "+f2(index,N,index));
}
static int f1(int l,int r,int index)
{
while(r-l>1)
{
int m=(l+r)/2;
if(ask(m,index)==index)l=m;
else r=m;
}
return l;
}
static int f2(int l,int r,int index)
{
while(r-l>1)
{
int m=(l+r)/2;
if(ask(index,m)==index)r=m;
else l=m;
}
return r;
}
static long fact(long N)
{
long num=1L;
while(N>=1)
{
num=((num%mod)*(N%mod))%mod;
N--;
}
return num;
}
static boolean reverse(long A[],int l,int r)
{
while(l<r)
{
long t=A[l];
A[l]=A[r];
A[r]=t;
l++;
r--;
}
if(isSorted(A))return true;
else return false;
}
static boolean isSorted(long A[])
{
for(int i=1; i<A.length; i++)if(A[i]<A[i-1])return false;
return true;
}
static boolean isPalindrome(char X[],int l,int r)
{
while(l<r)
{
if(X[l]!=X[r])return false;
l++; r--;
}
return true;
}
static long min(long a,long b,long c)
{
return Math.min(a, Math.min(c, b));
}
static void print(int a)
{
System.out.println("! "+a);
}
static int ask(int a,int b)
{
System.out.println("? "+a+" "+b);
return i();
}
static int find(int a)
{
if(par[a]<0)return a;
return par[a]=find(par[a]);
}
static void union(int a,int b)
{
a=find(a);
b=find(b);
if(a!=b)
{
par[a]+=par[b]; //transfers the size
par[b]=a; //changes the parent
}
}
static void swap(char A[],int a,int b)
{
char ch=A[a];
A[a]=A[b];
A[b]=ch;
}
static void sort(long[] a) //check for long
{
ArrayList<Long> l=new ArrayList<>();
for (long i:a) l.add(i);
Collections.sort(l);
for (int i=0; i<a.length; i++) a[i]=l.get(i);
}
static void setGraph(int N)
{
g=new ArrayList<ArrayList<Integer>>();
for(int i=0; i<=N; i++)
{
g.add(new ArrayList<Integer>());
}
}
static long pow(long a,long b)
{
long mod=1000000007;
long pow=1;
long x=a;
while(b!=0)
{
if((b&1)!=0)pow=(pow*x)%mod;
x=(x*x)%mod;
b/=2;
}
return pow;
}
static long toggleBits(long x)//one's complement || Toggle bits
{
int n=(int)(Math.floor(Math.log(x)/Math.log(2)))+1;
return ((1<<n)-1)^x;
}
static int countBits(long a)
{
return (int)(Math.log(a)/Math.log(2)+1);
}
static void sort(int[] a) {
ArrayList<Integer> l=new ArrayList<>();
for (int i:a) l.add(i);
Collections.sort(l);
for (int i=0; i<a.length; i++) a[i]=l.get(i);
}
static boolean isPrime(long N)
{
if (N<=1) return false;
if (N<=3) return true;
if (N%2 == 0 || N%3 == 0) return false;
for (int i=5; i*i<=N; i=i+6)
if (N%i == 0 || N%(i+2) == 0)
return false;
return true;
}
static long GCD(long a,long b)
{
if(b==0)
{
return a;
}
else return GCD(b,a%b );
}
//Debugging Functions Starts
static void print(char A[])
{
for(char c:A)System.out.print(c+" ");
System.out.println();
}
static void print(boolean A[])
{
for(boolean c:A)System.out.print(c+" ");
System.out.println();
}
static void print(int A[])
{
for(int a:A)System.out.print(a+" ");
System.out.println();
}
static void print(long A[])
{
for(long i:A)System.out.print(i+ " ");
System.out.println();
}
static void print(ArrayList<Integer> A)
{
for(int a:A)System.out.print(a+" ");
System.out.println();
}
//Debugging Functions END
//----------------------
//IO FUNCTIONS STARTS
static HashMap<Integer,Integer> Hash(int A[])
{
HashMap<Integer,Integer> mp=new HashMap<>();
for(int a:A)
{
int f=mp.getOrDefault(a,0)+1;
mp.put(a, f);
}
return mp;
}
static int i()
{
return in.nextInt();
}
static long l()
{
return in.nextLong();
}
static int[] input(int N){
int A[]=new int[N];
for(int i=0; i<N; i++)
{
A[i]=in.nextInt();
}
return A;
}
static long[] inputLong(int N) {
long A[]=new long[N];
for(int i=0; i<A.length; i++)A[i]=in.nextLong();
return A;
}
//IO FUNCTIONS END
}
//class pair implements Comparable<pair>{
// int index; long a;
// pair(long a,int index)
// {
// this.a=a;
// this.index=index;
// }
// public int compareTo(pair X)
// {
// if(this.a>X.a)return 1;
// if(this.a==X.a)return this.index-X.index;
// return -1;
// }
//}
//Code For FastReader
//Code For FastReader
//Code For FastReader
//Code For FastReader
class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br=new BufferedReader(new InputStreamReader(System.in));
}
String next()
{
while(st==null || !st.hasMoreElements())
{
try
{
st=new StringTokenizer(br.readLine());
}
catch(IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
//gey
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str="";
try
{
str=br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 8
|
standard input
|
[
"binary search",
"interactive"
] |
eb660c470760117dfd0b95acc10eee3b
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,900
| null |
standard output
| |
PASSED
|
94dca4f4ac55ffd66fc3cf33827afc7c
|
train_109.jsonl
|
1613658900
|
The only difference between the easy and the hard version is the limit to the number of queries.This is an interactive problem.There is an array $$$a$$$ of $$$n$$$ different numbers. In one query you can ask the position of the second maximum element in a subsegment $$$a[l..r]$$$. Find the position of the maximum element in the array in no more than 20 queries.A subsegment $$$a[l..r]$$$ is all the elements $$$a_l, a_{l + 1}, ..., a_r$$$. After asking this subsegment you will be given the position of the second maximum from this subsegment in the whole array.
|
256 megabytes
|
import java.util.*;
import java.io.*;
public class C2 {
public static void main(String[] args) throws IOException{
BufferedReader f = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
int n = Integer.parseInt(f.readLine());
int s = query(f, out, 0, n-1);
boolean dir = query(f, out, 0, s) == s;
if(dir){
int l = 0;
int r = s;
while(r > l+1){
int mid = (l+r)/2;
if(query(f, out, mid, s) == s) {
l = mid;
}else{
r = mid;
}
}
out.println("! " + (l+1));
}else{
int l = s;
int r = n-1;
while(r > l+1){
int mid = (l+r)/2;
if(query(f, out, s, mid) == s) {
r = mid;
}else{
l = mid;
}
}
out.println("! " + (r+1));
}
out.close();
}
public static int query(BufferedReader f, PrintWriter out, int l, int r) throws IOException{
if(l == r) return -1;
out.println("? " + (l+1) + " " + (r+1));
out.flush();
return Integer.parseInt(f.readLine())-1;
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 8
|
standard input
|
[
"binary search",
"interactive"
] |
eb660c470760117dfd0b95acc10eee3b
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,900
| null |
standard output
| |
PASSED
|
79ea6f6fc6ea6383cb9167d08fc8d06f
|
train_109.jsonl
|
1613658900
|
The only difference between the easy and the hard version is the limit to the number of queries.This is an interactive problem.There is an array $$$a$$$ of $$$n$$$ different numbers. In one query you can ask the position of the second maximum element in a subsegment $$$a[l..r]$$$. Find the position of the maximum element in the array in no more than 20 queries.A subsegment $$$a[l..r]$$$ is all the elements $$$a_l, a_{l + 1}, ..., a_r$$$. After asking this subsegment you will be given the position of the second maximum from this subsegment in the whole array.
|
256 megabytes
|
import java.io.*;
import java.util.*;
public class Main {
public static void main(String args[])
{
FastReader input=new FastReader();
PrintWriter out=new PrintWriter(System.out);
int T=1;
while(T-->0)
{
int n=input.nextInt();
out.println("?"+" "+1+" "+n);
out.flush();
int in=input.nextInt();
char pos='r';
if(in==1)
{
pos='r';
}
else if(in==n)
{
pos='l';
}
else
{
out.println("? "+1+" "+in);
out.flush();
int in1=input.nextInt();
if(in1==in)
{
pos='l';
}
else
{
pos='r';
}
}
if(pos=='l')
{
int i=1;
int j=in;
while(i<j)
{
int mid=(i+j)/2;
out.println("? "+mid+" "+in);
out.flush();
int in1=input.nextInt();
if(in1==in)
{
i=mid+1;
}
else
{
j=mid;
}
}
out.println("!"+" "+(i-1));
}
else
{
int i=in+1;
int j=n;
while(i<j)
{
int mid=(i+j)/2;
out.println("? "+in+" "+mid);
out.flush();
int in1=input.nextInt();
if(in1==in)
{
j=mid;
}
else
{
i=mid+1;
}
}
out.println("!"+" "+(i));
}
}
out.close();
}
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str="";
try
{
str=br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 8
|
standard input
|
[
"binary search",
"interactive"
] |
eb660c470760117dfd0b95acc10eee3b
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,900
| null |
standard output
| |
PASSED
|
6626732f719194fa20c3832a4934b4b9
|
train_109.jsonl
|
1613658900
|
The only difference between the easy and the hard version is the limit to the number of queries.This is an interactive problem.There is an array $$$a$$$ of $$$n$$$ different numbers. In one query you can ask the position of the second maximum element in a subsegment $$$a[l..r]$$$. Find the position of the maximum element in the array in no more than 20 queries.A subsegment $$$a[l..r]$$$ is all the elements $$$a_l, a_{l + 1}, ..., a_r$$$. After asking this subsegment you will be given the position of the second maximum from this subsegment in the whole array.
|
256 megabytes
|
import java.lang.reflect.Array;
import java.text.DecimalFormat;
import java.util.*;
import java.io.*;
public class Equal {
static class pair implements Comparable<pair> {
int x;
int y;
public pair(int u, int v) {
this.x = u;
this.y = v;
}
@Override
public int compareTo(pair o) {
return o.x-x;
}
}
static int[][]mem=new int[1001][1001];
// static int dp(int n,int k){
// if(n>=mem.length)
// return 0;
// if(k<0||k>=mem.length)
// return 0;
// if(mem[n][k]!=-1)
// return mem[n][k];
// }
static String timeInc(String time,int h,int m){
String []s =time.split(":");
int i=0;
int hh=0;
int mm=0;
while (i<s[0].length()&&s[0].charAt(i)=='0'){
i++;
}
if(i<s[0].length())
hh=Integer.parseInt(s[0].substring(i));
i=0;
while (i<s[1].length()&&s[1].charAt(i)=='0'){
i++;
}
if(i<s[1].length())
mm=Integer.parseInt(s[1].substring(i));
mm++;
if(mm%m==0){
mm=0;
hh++;
if(hh%h==0)
hh=0;
}
String hs=""+hh;
while(hs.length()<2)
hs="0"+hs;
String ms=""+mm;
while (ms.length()<2)
ms="0"+ms;
return hs+":"+ms;
}
static boolean validMirror(String s,int h,int m){
HashSet<Character>hs=new HashSet<>();
hs.add('3');
hs.add('4');
hs.add('6');
hs.add('7');
hs.add('9');
for (int i = 0; i <s.length() ; i++) {
if(hs.contains(s.charAt(i))){
return false;
}
}
String mirrored="";
for (int i = s.length()-1; i >=0 ; i--) {
if(s.charAt(i)=='5'){
mirrored+="2";
continue;
}
if(s.charAt(i)=='2'){
mirrored+="5";
continue;
}
mirrored+=s.charAt(i);
}
int i=0;
int hh=0;
int mm=0;
String []s2 =mirrored.split(":");
while (i<s2[0].length()&&s2[0].charAt(i)=='0'){
i++;
}
if(i<s2[0].length())
hh=Integer.parseInt(s2[0].substring(i));
i=0;
while (i<s2[1].length()&&s2[1].charAt(i)=='0'){
i++;
}
if(i<s2[1].length())
mm=Integer.parseInt(s2[1].substring(i));
if(hh>=h||mm>=m)
return false;
return true;
}
public static void main(String[] args) throws IOException {
//BufferedReader br = new BufferedReader(new FileReader("name.in"));
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
PrintWriter out = new PrintWriter(System.out);
int n=Integer.parseInt(br.readLine());
boolean found=false;
int p=-1;
int q=0;
System.out.println("? 1 "+n);
int second=Integer.parseInt(br.readLine());
int beg=-1;
int end=-1;
if(second>1&&second!=n) {
System.out.println("? 1 " + second);
int before = Integer.parseInt(br.readLine());
if (before == second) {
beg = 1;
end = second;
} else {
beg = second;
end = n;
}
}
else{
beg=1;
end=n;
}
while(!found&&q<20){
int mid=(beg+end)>>1;
if(end-beg==1){
if(end<=second)
mid=end;
else
mid=beg;
if(end==second||beg==second){
found=true;
p=end+beg-second;
break;
}
}
if(mid>second){
System.out.println("? "+second+" "+mid);
}
else {
System.out.println("? "+mid+" "+second);
}
int x=Integer.parseInt(br.readLine());
if(end-beg==1){
found=true;
if(x==second)
p=mid;
else {
if(end<=second)
p=beg;
else p=end;
}
}
else {
if (x == second) {
if (mid < second) {
if(second-mid==1){
found=true;
p=mid;
}
beg = mid;
} else {
end = mid;
if(mid-second==1){
found=true;
p=mid;
}
}
} else {
if (mid < second) {
if(mid-beg==1){
found=true;
p=beg;
}
end = mid;
} else {
if(end-mid==1){
found=true;
p=end;
}
beg = mid;
}
}
}
q++;
}
System.out.println("! "+p);
out.flush();
out.close();
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 8
|
standard input
|
[
"binary search",
"interactive"
] |
eb660c470760117dfd0b95acc10eee3b
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,900
| null |
standard output
| |
PASSED
|
67690286a36634f083b021b769d144bd
|
train_109.jsonl
|
1613658900
|
The only difference between the easy and the hard version is the limit to the number of queries.This is an interactive problem.There is an array $$$a$$$ of $$$n$$$ different numbers. In one query you can ask the position of the second maximum element in a subsegment $$$a[l..r]$$$. Find the position of the maximum element in the array in no more than 20 queries.A subsegment $$$a[l..r]$$$ is all the elements $$$a_l, a_{l + 1}, ..., a_r$$$. After asking this subsegment you will be given the position of the second maximum from this subsegment in the whole array.
|
256 megabytes
|
import java.util.*;
import java.io.*;
public class Main {
static Scanner sc = new Scanner(System.in);
static PrintWriter out = new PrintWriter(System.out);
static BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
// long mod = 998244353;
// long mod = (long)1e9+7;
long mod = 998244353;
public static void main(String[] args) throws Exception {
Main main = new Main();
// int t = sc.nextInt();
int t = 1;
for(int i=1; i<=t; i++){
main.solve();
}
out.flush();
}
void solve() throws Exception {
int n = neInt();
out.println("? 1 "+n);
out.flush();
int secMax = neInt();
boolean inRight=true;
if(secMax>1){
out.println("? 1 "+secMax);
out.flush();
int temp = neInt();
if(temp==secMax){
inRight = false;
}
}
int co = inRight?1:-1;
int lo=1,hi;
if(inRight){
hi = n-secMax+1;
} else hi = secMax;
while(hi>lo+1){
int mid = (hi+lo)/2;
int idx = secMax+mid*co-co;
out.println("? "+Math.min(idx,secMax)+" "+Math.max(idx,secMax));
out.flush();
int temp = neInt();
if(temp==secMax) hi = mid;
else lo = mid;
}
int ans = secMax+hi*co-co;
out.println("! "+ans);
}
String neS(){
return sc.next();
}
int neInt(){
return Integer.parseInt(sc.next());
}
long neLong(){
return Long.parseLong(sc.next());
}
int paIn(String s){return Integer.parseInt(s);}
public int minimumLengthEncoding(String[] words) {
int n = words.length;
Arrays.sort(words, (o1, o2)->(o1.length()-o2.length()));
int ans = 0;
for(int i=0; i<n; i++){
boolean found = false;
for(int j=i+1; j<n && (!found); j++){
found |= words[j].endsWith(words[i]);
}
if(!found) ans += words[i].length()+1;
}
return ans;
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 8
|
standard input
|
[
"binary search",
"interactive"
] |
eb660c470760117dfd0b95acc10eee3b
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,900
| null |
standard output
| |
PASSED
|
76fd9d43f5decff608b51a611aac0208
|
train_109.jsonl
|
1613658900
|
The only difference between the easy and the hard version is the limit to the number of queries.This is an interactive problem.There is an array $$$a$$$ of $$$n$$$ different numbers. In one query you can ask the position of the second maximum element in a subsegment $$$a[l..r]$$$. Find the position of the maximum element in the array in no more than 20 queries.A subsegment $$$a[l..r]$$$ is all the elements $$$a_l, a_{l + 1}, ..., a_r$$$. After asking this subsegment you will be given the position of the second maximum from this subsegment in the whole array.
|
256 megabytes
|
import java.io.*;
import java.util.StringTokenizer;
import static java.lang.Double.parseDouble;
import static java.lang.Integer.compare;
import static java.lang.Integer.parseInt;
import static java.lang.Long.parseLong;
import static java.lang.System.in;
public class Main {
private static final int MOD = (int) (1E9 + 7);
static FastScanner scanner = new FastScanner(in);
public static void main(String[] args) throws IOException {
// Write your solution here
int t = 1;
//t = parseInt(scanner.nextLine());
while (t-- > 0) {
solve();
}
}
private static void solve() throws IOException {
int n = scanner.nextInt();
int secMax = query(1, n);
int ans = 0;
if (query(secMax, n) == secMax) {
int l = secMax + 1, r = n;
while (l <= r) {
int mid = (l + r) / 2;
if (query(secMax, mid) == secMax) {
ans = mid;
r = mid - 1;
} else {
l = mid + 1;
}
}
} else {
int l = 1, r = secMax - 1;
while (l <= r) {
int mid = (l + r) / 2;
if (query(mid, secMax) == secMax) {
ans = mid;
l = mid + 1;
} else {
r = mid - 1;
}
}
}
System.out.println("! " + ans);
}
private static int query(int l, int h) {
if(l == h) return -1;
System.out.println("? " + l + " " + h);
System.out.flush();
return scanner.nextInt();
}
private static class Pair implements Comparable<Pair> {
int index, value;
public Pair(int index, int value) {
this.index = index;
this.value = value;
}
public int compareTo(Pair o) {
if (value != o.value) return compare(value, o.value);
return compare(index, o.index);
}
@Override
public String toString() {
return "Pair{" +
"index=" + index +
", value=" + value +
'}';
}
}
static class FastScanner {
BufferedReader br;
StringTokenizer st;
FastScanner(File f) {
try {
br = new BufferedReader(new FileReader(f));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
FastScanner(InputStream f) {
br = new BufferedReader(new InputStreamReader(f));
}
String nextLine() {
try {
return br.readLine();
} catch (IOException e) {
return null;
}
}
String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return parseInt(next());
}
long nextLong() {
return parseLong(next());
}
double nextDouble() {
return parseDouble(next());
}
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 8
|
standard input
|
[
"binary search",
"interactive"
] |
eb660c470760117dfd0b95acc10eee3b
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,900
| null |
standard output
| |
PASSED
|
df18c9416bbde5a06cd757fdab97b6fa
|
train_109.jsonl
|
1613658900
|
The only difference between the easy and the hard version is the limit to the number of queries.This is an interactive problem.There is an array $$$a$$$ of $$$n$$$ different numbers. In one query you can ask the position of the second maximum element in a subsegment $$$a[l..r]$$$. Find the position of the maximum element in the array in no more than 20 queries.A subsegment $$$a[l..r]$$$ is all the elements $$$a_l, a_{l + 1}, ..., a_r$$$. After asking this subsegment you will be given the position of the second maximum from this subsegment in the whole array.
|
256 megabytes
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.InputMismatchException;
import java.util.*;
import java.io.*;
import java.lang.*;
public class Main{
public static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
private BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
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 String nextLine() {
String str = "";
try {
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
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 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 double nextDouble() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.') {
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
if (c == '.') {
c = read();
double m = 1;
while (!isSpaceChar(c)) {
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public String readString() {
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 boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public String next() {
return readString();
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
static long gcd(long a, long b){
if (a == 0)
return b;
return gcd(b % a, a);
}
static long lcm(long a, long b) {
return (a*b)/gcd(a, b);
}
public static void sortbyColumn(int arr[][], int col)
{
Arrays.sort(arr, new Comparator<int[]>() {
@Override
public int compare(final int[] entry1,
final int[] entry2) {
if (entry1[col] > entry2[col])
return 1;
else
return -1;
}
});
}
static long func(long a[],int size,int s){
long max1=a[s];
long maxc=a[s];
for(int i=s+1;i<size;i++){
maxc=Math.max(a[i],maxc+a[i]);
max1=Math.max(maxc,max1);
}
return max1;
}
public static 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 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> p = (Pair<U, V>) o;
return (x == null ? p.x == null : x.equals(p.x)) && (y == null ? p.y == null : y.equals(p.y));
}
public int compareTo(Pair<U, V> b) {
int cmpU = x.compareTo(b.x);
return cmpU != 0 ? cmpU : y.compareTo(b.y);
}
public String toString() {
return String.format("(%s, %s)", x.toString(), y.toString());
}
}
static class MultiSet<U extends Comparable<U>> {
public int sz = 0;
public TreeMap<U, Integer> t;
public MultiSet() {
t = new TreeMap<>();
}
public void add(U x) {
t.put(x, t.getOrDefault(x, 0) + 1);
sz++;
}
public void remove(U x) {
if (t.get(x) == 1) t.remove(x);
else t.put(x, t.get(x) - 1);
sz--;
}
}
static void shuffle(long[] a) {
Random get = new Random();
for (int i = 0; i < a.length; i++) {
int r = get.nextInt(a.length);
long temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
static long myceil(long a, long b){
return (a+b-1)/b;
}
static long C(long n,long r){
long count=0,temp=n;
long ans=1;
long num=n-r+1,div=1;
while(num<=n){
ans*=num;
//ans+=MOD;
ans%=MOD;
ans*=mypow(div,MOD-2);
//ans+=MOD;
ans%=MOD;
num++;
div++;
}
ans+=MOD;
return ans%MOD;
}
static long fact(long a){
long i,ans=1;
for(i=1;i<=a;i++){
ans*=i;
ans%=MOD;
}
return ans%=MOD;
}
static void sieve(int n){
is_sieve[0]=1;
is_sieve[1]=1;
int i,j,k;
for(i=2;i<n;i++){
if(is_sieve[i]==0){
sieve[i]=i;
tr.add(i);
for(j=i*i;j<n;j+=i){
if(j>n||j<0){
break;
}
is_sieve[j]=1;
sieve[j]=i;
}
}
}
}
static void calc(int n){
int i,j;
dp[n-1]=0;
if(n>1)
dp[n-2]=1;
for(i=n-3;i>=0;i--){
long ind=n-i-1;
dp[i]=((ind*(long)mypow(10,ind-1))%MOD+dp[i+1])%MOD;
}
}
static long mypow(long x,long y){
long temp;
if( y == 0)
return 1;
temp = mypow(x, y/2);
if (y%2 == 0)
return (temp*temp)%MOD;
else
return ((x*temp)%MOD*(temp)%MOD)%MOD;
}
static long dist[],dp[];
static int visited[],recStack[];
static ArrayList<Integer> adj[];
//static int dp[][][];
static int MOD=1000000007,max=0;
static char chm='#';
static int[] sieve,is_sieve;
static TreeSet<Integer> tr;
static int ask(int l,int r){
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter w = new PrintWriter(outputStream);
w.println("? "+(l+1)+" "+(r+1));
w.flush();
int ans=in.nextInt();
return ans-1;
}
public static void main(String args[]){
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter w = new PrintWriter(outputStream);
int t,i,j,tno=0,tte;
//t=in.nextInt();
t=1;
//tte=t;
while(t-->0){
int n,q,flag=0,ans=0;
n=in.nextInt();
int smax=ask(0,n-1);
if(smax==0||ask(0,smax)!=smax){
int l=smax,r=n-1;
while(r-l>1){
int m=(l+r)/2;
if(ask(smax,m)==smax){
r=m;
}else{
l=m;
}
}
w.println("! "+(r+1));
}else{
int l=0,r=smax;
while(r-l>1){
int m=(l+r)/2;
if(ask(m,smax)==smax){
l=m;
}else{
r=m;
}
}
w.println("! "+(l+1));
}
}
w.close();
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 8
|
standard input
|
[
"binary search",
"interactive"
] |
eb660c470760117dfd0b95acc10eee3b
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,900
| null |
standard output
| |
PASSED
|
227f67719df07e1eae2dc733a47c55c8
|
train_109.jsonl
|
1613658900
|
The only difference between the easy and the hard version is the limit to the number of queries.This is an interactive problem.There is an array $$$a$$$ of $$$n$$$ different numbers. In one query you can ask the position of the second maximum element in a subsegment $$$a[l..r]$$$. Find the position of the maximum element in the array in no more than 20 queries.A subsegment $$$a[l..r]$$$ is all the elements $$$a_l, a_{l + 1}, ..., a_r$$$. After asking this subsegment you will be given the position of the second maximum from this subsegment in the whole array.
|
256 megabytes
|
//package Current;
import java.util.*;
public class Main {
static final long mod = (long) 1e9 + 7;
static class pair {
int x, y;
public pair(int x, int y) {
this.x = x;
this.y = y;
}
}
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int t = 1;
// t = sc.nextInt();
while (t-- > 0) {
// Start code
int n = sc.nextInt();
int ans = 0;
int smax = ask(1, n, sc);
if (smax == 1 || ask(1, smax, sc) != smax) {
int l = smax + 1, r = n;
while (l <= r) {
int mid = l + (r - l) / 2;
int p = ask(smax, mid, sc);
if (p == smax) {
ans = mid;
r = mid - 1;
} else
l = mid + 1;
}
} else {
int l = 1, r = smax - 1;
while (l <= r) {
int mid = l + (r - l) / 2;
int p = ask(mid, smax, sc);
if (p == smax) {
ans = mid;
l = mid + 1;
} else
r = mid - 1;
}
}
println("! " + ans);
}
sc.close();
}
static int ask(int l, int r, Scanner sc) {
println("? " + l + " " + r);
System.out.flush();
int x = sc.nextInt();
return x;
}
static void print(Object o) {
System.out.print(o + " ");
}
static void println(Object o) {
System.out.println(o);
}
static void swap(int arr[], int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
static ArrayList<Long> factorial(int num) {
ArrayList<Long> fac = new ArrayList<>();
fac.add((long) 0);
fac.add((long) 1);
for (int i = 2; i < num; i++) {
fac.add((fac.get(i - 1) * i) % mod);
}
return fac;
}
static long ncr(long x, long y, ArrayList<Long> fac) {
if (y >= x)
return (long) 1;
long res = fac.get((int) x);
long z = (fac.get((int) y) * fac.get((int) (x - y))) % mod;
z = modInv(z);
res = (res * z) % mod;
return res;
}
static long modInv(long x) {
return modExpo(x, mod - 2);
}
static long modExpo(long x, long y) {
long res = 1;
x = x % mod;
while (y > 0) {
if (y % 2 == 1)
res = (res * x) % mod;
y = y / 2;
x = (x * x) % mod;
}
return res;
}
static int lowerBound(int n, long[] arr, long value) {
int res = (int) 1e7;
int l = 0, r = n - 1;
while (l <= r) {
int mid = l + (r - l) / 2;
if (arr[mid] >= value) {
res = mid;
r = mid - 1;
} else
l = mid + 1;
}
return res;
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 8
|
standard input
|
[
"binary search",
"interactive"
] |
eb660c470760117dfd0b95acc10eee3b
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,900
| null |
standard output
| |
PASSED
|
99979edb06719b8f97bb99811b4eac8f
|
train_109.jsonl
|
1613658900
|
The only difference between the easy and the hard version is the limit to the number of queries.This is an interactive problem.There is an array $$$a$$$ of $$$n$$$ different numbers. In one query you can ask the position of the second maximum element in a subsegment $$$a[l..r]$$$. Find the position of the maximum element in the array in no more than 20 queries.A subsegment $$$a[l..r]$$$ is all the elements $$$a_l, a_{l + 1}, ..., a_r$$$. After asking this subsegment you will be given the position of the second maximum from this subsegment in the whole array.
|
256 megabytes
|
import java.io.*;
import java.util.*;
import java.util.function.BiFunction;
public class C {
static FastReader reader = new FastReader();
static OutputWriter out = new OutputWriter(System.out);
static int ask(int l, int r) {
out.println("? " + l + " " + r);out.flush();
return reader.nextInt();
}
static int solve(int l, int r) {
if(l == r) {
return l;
}
if(l + 1 == r) {
return ask(l, r) == l ? r : l;
}
int t1 = ask(l, r);
if(t1 != r && ask(t1, r) == t1) {
//we are at left most point
l = t1 + 1;
while(l <= r) {
int m = (l + r) / 2;
int t2 = ask(t1, m);
if(t2 == t1) {
r = m - 1;
} else {
l = m + 1;
}
}//[1,2,4,3, 5]
return l;
} else {
r = t1 - 1;
while(l <= r) {
int m = (l + r) / 2;
int t2 = ask(m, t1);
if(t2 == t1) {
l = m + 1;
} else {
r = m - 1;
}
}
return r;
//we are at right most point
}
}
public static void main(String[] args) {
try {
int n = reader.nextInt();
int ans = solve(1, n);
out.println("! " + ans);
} finally {
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 static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(char[] array) {
writer.print(array);
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void print(int[] array) {
for (int i = 0; i < array.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(array[i]);
}
}
public void print(double[] array) {
for (int i = 0; i < array.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(array[i]);
}
}
public void print(long[] array) {
for (int i = 0; i < array.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(array[i]);
}
}
public void println(int[] array) {
print(array);
writer.println();
}
public void println(double[] array) {
print(array);
writer.println();
}
public void println(long[] array) {
print(array);
writer.println();
}
public void println() {
writer.println();
}
public void println(Object... objects) {
print(objects);
writer.println();
}
public void print(char i) {
writer.print(i);
}
public void println(char i) {
writer.println(i);
}
public void println(char[] array) {
writer.println(array);
}
public void printf(String format, Object... objects) {
writer.printf(format, objects);
}
public void close() {
writer.close();
}
public void flush() {
writer.flush();
}
public void print(long i) {
writer.print(i);
}
public void println(long i) {
writer.println(i);
}
public void print(int i) {
writer.print(i);
}
public void println(int i) {
writer.println(i);
}
public void separateLines(int[] array) {
for (int i : array) {
println(i);
}
}
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 8
|
standard input
|
[
"binary search",
"interactive"
] |
eb660c470760117dfd0b95acc10eee3b
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,900
| null |
standard output
| |
PASSED
|
7202fc148ce102afa753ac40a20a92b5
|
train_109.jsonl
|
1613658900
|
The only difference between the easy and the hard version is the limit to the number of queries.This is an interactive problem.There is an array $$$a$$$ of $$$n$$$ different numbers. In one query you can ask the position of the second maximum element in a subsegment $$$a[l..r]$$$. Find the position of the maximum element in the array in no more than 20 queries.A subsegment $$$a[l..r]$$$ is all the elements $$$a_l, a_{l + 1}, ..., a_r$$$. After asking this subsegment you will be given the position of the second maximum from this subsegment in the whole array.
|
256 megabytes
|
import java.io.*;
import java.util.*;
public class guessingthegreatesteasy {
public static void main(String[] args) throws IOException {
BufferedReader f = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(f.readLine());
int n = Integer.parseInt(st.nextToken());
System.out.println("? " + 1 + " " + n);
int secondMax = 0;
System.out.flush();
secondMax = Integer.parseInt(f.readLine());
boolean left = true;
if(secondMax > 1) {
System.out.println("? " + 1 + " " + secondMax);
System.out.flush();
left = Integer.parseInt(f.readLine()) == secondMax;
}
if(secondMax == 1 || !left) {
int low = secondMax;
int high = n;
while(high - low > 1) {
int mid = (low - high) / 2 + high;
System.out.println("? " + secondMax + " " + mid);
System.out.flush();
int secondSecondMax = Integer.parseInt(f.readLine());
if(secondSecondMax != secondMax) low = mid;
else high = mid;
}
System.out.println("! " + high);
}
else{
int high = secondMax;
int low = 1;
while(high - low > 1) {
int mid = (low - high) / 2 + high;
System.out.println("? " + mid + " " + secondMax);
System.out.flush();
int secondSecondMax = Integer.parseInt(f.readLine());
if(secondSecondMax != secondMax) high = mid;
else low = mid;
}
System.out.println("! " + low);
}
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 8
|
standard input
|
[
"binary search",
"interactive"
] |
eb660c470760117dfd0b95acc10eee3b
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,900
| null |
standard output
| |
PASSED
|
b59d48e856674851ad72da3fb5c59a4c
|
train_109.jsonl
|
1613658900
|
The only difference between the easy and the hard version is the limit to the number of queries.This is an interactive problem.There is an array $$$a$$$ of $$$n$$$ different numbers. In one query you can ask the position of the second maximum element in a subsegment $$$a[l..r]$$$. Find the position of the maximum element in the array in no more than 20 queries.A subsegment $$$a[l..r]$$$ is all the elements $$$a_l, a_{l + 1}, ..., a_r$$$. After asking this subsegment you will be given the position of the second maximum from this subsegment in the whole array.
|
256 megabytes
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class Practice {
public static void main(String[] args) throws Exception {
Scanner s = new Scanner(System.in);
int n = s.nextInt();
System.out.flush();
getAns(n, s);
}
private static void getAns(int n, Scanner s) {
// TODO Auto-generated method stub
int sec=call(0,n-1,s);
if(sec==0||call(0,sec,s)!=sec) {
int l=sec,r=n-1;
while(r-l>1) {
int m=(l+r)/2;
if(call(sec,m,s)!=sec) {
l=m;
}else {
r=m;
}
}System.out.println("! "+(r+1));
}else {
int l=0,r=sec;
while(r-l>1) {
int m=(l+r)/2;
if(call(m,sec,s)!=sec) {
r=m;
}else {
l=m;
}
}System.out.println("! "+(l+1));
}
}
private static int call(int l, int r,Scanner s) {
// TODO Auto-generated method stub
System.out.println("? "+(l+1)+" "+(r+1));
int sec=s.nextInt();
System.out.flush();
return sec-1;
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 8
|
standard input
|
[
"binary search",
"interactive"
] |
eb660c470760117dfd0b95acc10eee3b
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,900
| null |
standard output
| |
PASSED
|
e401a4b9a137c543d7f634bfc649faba
|
train_109.jsonl
|
1613658900
|
The only difference between the easy and the hard version is the limit to the number of queries.This is an interactive problem.There is an array $$$a$$$ of $$$n$$$ different numbers. In one query you can ask the position of the second maximum element in a subsegment $$$a[l..r]$$$. Find the position of the maximum element in the array in no more than 20 queries.A subsegment $$$a[l..r]$$$ is all the elements $$$a_l, a_{l + 1}, ..., a_r$$$. After asking this subsegment you will be given the position of the second maximum from this subsegment in the whole array.
|
256 megabytes
|
import java.io.*;
import java.util.*;
/*
polyakoff
*/
public class Main {
static FastReader in;
static PrintWriter out;
static Random rand = new Random();
static final int oo = (int) 1e9 + 10;
static final long OO = (long) 2e18 + 10;
static final int MOD = (int) 1e9 + 7;
static int ask(int l, int r) {
out.printf("? %d %d\n", l, r);
out.flush();
return in.nextInt();
}
static void solve() {
int n = in.nextInt();
int l = 1, r = n;
int second = ask(l, r);
while (true) {
if (r - l + 1 == 2) {
int first = second == l ? l + 1 : l;
out.printf("! %d\n", first);
out.flush();
return;
} else if (r - l + 1 == 3) {
int pos = ask(l, l + 1);
int first;
if (second != r)
first = pos == second ? (second == l ? l + 1 : l) : r;
else
first = pos == l ? l + 1 : l;
out.printf("! %d\n", first);
out.flush();
return;
}
int mid = (l + r) / 2;
if (second <= mid) {
int pos = ask(l, mid);
if (pos == second)
r = mid;
else {
int l2 = mid + 1, r2 = r;
while (l2 < r2) {
int mid2 = (l2 + r2) / 2;
if (ask(second, mid2) == second)
r2 = mid2;
else
l2 = mid2 + 1;
}
out.printf("! %d\n", l2);
out.flush();
return;
}
} else {
int pos = ask(mid + 1, r);
if (pos == second)
l = mid + 1;
else {
int l2 = l, r2 = mid;
while (l2 < r2) {
int mid2 = (l2 + r2) / 2;
if (ask(mid2 + 1, second) == second)
l2 = mid2 + 1;
else
r2 = mid2;
}
out.printf("! %d\n", l2);
out.flush();
return;
}
}
}
}
public static void main(String[] args) {
in = new FastReader();
out = new PrintWriter(System.out);
int T = 1;
// T = in.nextInt();
while (T-- > 0)
solve();
out.flush();
out.close();
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
FastReader() {
this(System.in);
}
FastReader(String file) throws FileNotFoundException {
this(new FileInputStream(file));
}
FastReader(InputStream is) {
br = new BufferedReader(new InputStreamReader(is));
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String next() {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(nextLine());
}
return st.nextToken();
}
String nextLine() {
String line;
try {
line = br.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
return line;
}
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 8
|
standard input
|
[
"binary search",
"interactive"
] |
eb660c470760117dfd0b95acc10eee3b
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,900
| null |
standard output
| |
PASSED
|
b052870c39aadff5e6e3457386c4f30b
|
train_109.jsonl
|
1613658900
|
The only difference between the easy and the hard version is the limit to the number of queries.This is an interactive problem.There is an array $$$a$$$ of $$$n$$$ different numbers. In one query you can ask the position of the second maximum element in a subsegment $$$a[l..r]$$$. Find the position of the maximum element in the array in no more than 20 queries.A subsegment $$$a[l..r]$$$ is all the elements $$$a_l, a_{l + 1}, ..., a_r$$$. After asking this subsegment you will be given the position of the second maximum from this subsegment in the whole array.
|
256 megabytes
|
import java.io.*;
import java.util.*;
import java.awt.*;
public class C
{
BufferedReader in;
PrintWriter ob;
StringTokenizer st;
public static void main(String[] args) throws IOException {
new C().run();
}
void run() throws IOException {
in=new BufferedReader(new InputStreamReader(System.in));
ob=new PrintWriter(System.out);
solve();
System.out.flush();
}
void solve() throws IOException {
int n = ni();
System.out.println("? 1 "+n);
int s_max_pos = ni();
int left_sec_max = 0;
if( s_max_pos != 1 ) {
System.out.println("? 1"+" "+s_max_pos);
left_sec_max = ni();
}
if( s_max_pos != 1 && left_sec_max == s_max_pos ) {
int left = 1, right = s_max_pos;
while( right - left > 1 ) {
int mid = left + (right - left)/2;
System.out.println("? "+mid+" "+s_max_pos);
int res = ni();
if ( res == s_max_pos )
left = mid;
else
right = mid - 1;
}
if( right == s_max_pos ) {
System.out.println("! "+left);
return;
}
System.out.println("? "+right+" "+s_max_pos);
int f = ni();
if( f == s_max_pos )
System.out.println("! "+right);
else
System.out.println("! "+left);
} else {
int left = s_max_pos, right = n;
while( right - left > 1 ) {
int mid = left + (right - left)/2;
System.out.println("? "+s_max_pos+" "+mid);
int res = ni();
if ( res == s_max_pos )
right = mid;
else
left = mid + 1;
}
if( left == s_max_pos ) {
System.out.println("! "+right);
return;
}
System.out.println("? "+s_max_pos+" "+left);
int f = ni();
if( f == s_max_pos )
System.out.println("! "+left);
else
System.out.println("! "+right);
}
}
String ns() throws IOException {
return nextToken();
}
long nl() throws IOException {
return Long.parseLong(nextToken());
}
int ni() throws IOException {
return Integer.parseInt(nextToken());
}
double nd() throws IOException {
return Double.parseDouble(nextToken());
}
String nextToken() throws IOException {
if(st==null || !st.hasMoreTokens())
st=new StringTokenizer(in.readLine());
return st.nextToken();
}
int[] nia(int start,int b) throws IOException {
int a[]=new int[b];
for(int i=start;i<b;i++)
a[i]=ni();
return a;
}
long[] nla(int start,int n) throws IOException {
long a[]=new long[n];
for (int i=start; i<n ;i++ ) {
a[i]=nl();
}
return a;
}
public void tr(Object... o) {
ob.println(Arrays.deepToString(o));
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 8
|
standard input
|
[
"binary search",
"interactive"
] |
eb660c470760117dfd0b95acc10eee3b
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,900
| null |
standard output
| |
PASSED
|
714c899693470612772cccc79242dbb1
|
train_109.jsonl
|
1613658900
|
The only difference between the easy and the hard version is the limit to the number of queries.This is an interactive problem.There is an array $$$a$$$ of $$$n$$$ different numbers. In one query you can ask the position of the second maximum element in a subsegment $$$a[l..r]$$$. Find the position of the maximum element in the array in no more than 20 queries.A subsegment $$$a[l..r]$$$ is all the elements $$$a_l, a_{l + 1}, ..., a_r$$$. After asking this subsegment you will be given the position of the second maximum from this subsegment in the whole array.
|
256 megabytes
|
import java.util.Scanner;
public class C {
static Scanner sc = new Scanner(System.in);
public static long ask(long l, long r) {
if(l >= r) return -1;
System.out.println("? " + l + " " + r);
long x = sc.nextLong();
return x;
}
public static void main(String[] args) {
long n = sc.nextLong();
long pos = ask(1, n);
if(ask(1, pos) == pos) {
long ini = 1, fin = pos;
while(ini < fin) {
long mid = (ini + fin + 1)/2;
if(ask(mid, n) == pos) {
ini = mid;
}
else {
fin = mid - 1;
}
}
System.out.println("! " + ini);
}
else {
long ini = pos, fin = n;
while(ini < fin) {
long mid = (ini + fin)/2;
if(ask(1, mid) == pos) {
fin = mid;
}
else {
ini = mid+1;
}
}
System.out.println("! " + ini);
}
sc.close();
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 8
|
standard input
|
[
"binary search",
"interactive"
] |
eb660c470760117dfd0b95acc10eee3b
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,900
| null |
standard output
| |
PASSED
|
486d4e9deb7d0f1605474a065f19bcca
|
train_109.jsonl
|
1613658900
|
The only difference between the easy and the hard version is the limit to the number of queries.This is an interactive problem.There is an array $$$a$$$ of $$$n$$$ different numbers. In one query you can ask the position of the second maximum element in a subsegment $$$a[l..r]$$$. Find the position of the maximum element in the array in no more than 20 queries.A subsegment $$$a[l..r]$$$ is all the elements $$$a_l, a_{l + 1}, ..., a_r$$$. After asking this subsegment you will be given the position of the second maximum from this subsegment in the whole array.
|
256 megabytes
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class C {
public static void main(String[] args) {
FastScanner fs = new FastScanner();
int t = 1;//fs.nextInt();
while (t-- > 0) {
int n = fs.nextInt();
int overall = query( 1, n, fs );
boolean left = false;
if (overall != 1) {
if (query( 1, overall, fs ) == overall) left = true;
}
if (left) {
int low = 1, high = overall - 1;
while (low <= high) {
int mid = (low + high) >> 1;
if (query( mid, overall, fs ) == overall) low = mid + 1;
else high = mid - 1;
}
System.out.println( "! " + high );
System.out.flush();
} else {
int low = overall + 1, high = n;
while (low <= high) {
int mid = (low + high) >> 1;
if (query( overall, mid, fs ) == overall) high = mid - 1;
else low = mid + 1;
}
System.out.println( "! " + low );
System.out.flush();
}
}
}
static int query(int low, int high, FastScanner fs) {
System.out.println( "? " + low + " " + high );
System.out.flush();
return fs.nextInt();
}
private 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() );
}
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 8
|
standard input
|
[
"binary search",
"interactive"
] |
eb660c470760117dfd0b95acc10eee3b
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,900
| null |
standard output
| |
PASSED
|
0f09c47526c46bd33122723eba1e8b69
|
train_109.jsonl
|
1613658900
|
The only difference between the easy and the hard version is the limit to the number of queries.This is an interactive problem.There is an array $$$a$$$ of $$$n$$$ different numbers. In one query you can ask the position of the second maximum element in a subsegment $$$a[l..r]$$$. Find the position of the maximum element in the array in no more than 20 queries.A subsegment $$$a[l..r]$$$ is all the elements $$$a_l, a_{l + 1}, ..., a_r$$$. After asking this subsegment you will be given the position of the second maximum from this subsegment in the whole array.
|
256 megabytes
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.HashMap;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.util.Map;
import java.io.BufferedReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastReader in = new FastReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
C1GuessingTheGreatestEasyVersion solver = new C1GuessingTheGreatestEasyVersion();
solver.solve(1, in, out);
out.close();
}
static class C1GuessingTheGreatestEasyVersion {
Map<String, Integer> map;
public void solve(int testNumber, FastReader in, PrintWriter out) {
map = new HashMap<>();
int n = in.nextInt();
int sed = query(1, n, in, out);
out.println("! " + cal(1, n, sed, in, out));
out.flush();
}
private int cal(int l, int r, int sed, FastReader in, PrintWriter out) {
if (l == r) {
return l;
}
//int p = query(l,r,in,out);
//if (l+1 == r) return p == l ? r : l;
int mid = (l + r) / 2;
if (sed <= mid) {
if (Math.min(sed, l) == mid) {
return cal(mid + 1, r, sed, in, out);
}
int lp = query(Math.min(sed, l), mid, in, out);
if (lp == sed) {
return cal(l, mid, sed, in, out);
} else {
return cal(mid + 1, r, sed, in, out);
}
} else {
if (mid + 1 == Math.max(r, sed)) {
return cal(l, mid, sed, in, out);
}
int rp = query(mid + 1, Math.max(r, sed), in, out);
if (rp == sed) {
return cal(mid + 1, r, sed, in, out);
} else {
return cal(l, mid, sed, in, out);
}
}
}
private int query(int l, int r, FastReader in, PrintWriter out) {
Integer num = map.get(l + "#" + r);
if (num != null) return num;
out.println("? " + l + " " + r);
out.flush();
num = in.nextInt();
map.put(l + "#" + r, num);
return num;
}
}
static class FastReader {
BufferedReader br;
StringTokenizer st = new StringTokenizer("");
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
public FastReader(InputStream in) {
br = new BufferedReader(new InputStreamReader(in));
}
public String next() {
while (st == null || (!st.hasMoreElements())) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 8
|
standard input
|
[
"binary search",
"interactive"
] |
eb660c470760117dfd0b95acc10eee3b
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,900
| null |
standard output
| |
PASSED
|
3ac47936f07e3052791133c76ce4b9fe
|
train_109.jsonl
|
1613658900
|
The only difference between the easy and the hard version is the limit to the number of queries.This is an interactive problem.There is an array $$$a$$$ of $$$n$$$ different numbers. In one query you can ask the position of the second maximum element in a subsegment $$$a[l..r]$$$. Find the position of the maximum element in the array in no more than 20 queries.A subsegment $$$a[l..r]$$$ is all the elements $$$a_l, a_{l + 1}, ..., a_r$$$. After asking this subsegment you will be given the position of the second maximum from this subsegment in the whole array.
|
256 megabytes
|
// 18-Feb-2021
import java.util.*;
import java.io.*;
public class C {
static class FastReader {
BufferedReader br;
StringTokenizer st;
private FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
int[] nextIntArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
int[] nextIntArrayOne(int n) {
int[] a = new int[n + 1];
for (int i = 1; i < n + 1; 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[] nextLongArrayOne(int n) {
long[] a = new long[n + 1];
for (int i = 1; i < n + 1; i++)
a[i] = nextLong();
return a;
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
static PrintWriter w = new PrintWriter(System.out);
static FastReader s = new FastReader();
public static void main(String[] args) {
int n = s.nextInt();
int ans = -1;
int maxInd = query(1,n);
if(maxInd == query(1,maxInd)) {
int l = 1, r = maxInd - 1;
while(l <= r) {
int mid = (l + r) / 2;
if(query(mid, maxInd) == maxInd) {
ans = mid;
l =mid + 1;
}else {
r = mid - 1;
}
}
}else {
int l = maxInd + 1, r = n;
while(l <= r) {
int mid = (l + r) / 2;
if(query(maxInd,mid) == maxInd) {
ans = mid;
r =mid - 1;
}else {
l = mid + 1;
}
}
}
w.println("! " + ans);
w.flush();
}
private static int query(int l, int r) {
if(l == r) return Integer.MIN_VALUE;
w.println("? "+ l +" " + r);
w.flush();
return s.nextInt();
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 8
|
standard input
|
[
"binary search",
"interactive"
] |
eb660c470760117dfd0b95acc10eee3b
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,900
| null |
standard output
| |
PASSED
|
ae91dde692f5296d1efc11246598a674
|
train_109.jsonl
|
1613658900
|
The only difference between the easy and the hard version is the limit to the number of queries.This is an interactive problem.There is an array $$$a$$$ of $$$n$$$ different numbers. In one query you can ask the position of the second maximum element in a subsegment $$$a[l..r]$$$. Find the position of the maximum element in the array in no more than 20 queries.A subsegment $$$a[l..r]$$$ is all the elements $$$a_l, a_{l + 1}, ..., a_r$$$. After asking this subsegment you will be given the position of the second maximum from this subsegment in the whole array.
|
256 megabytes
|
import javax.print.DocFlavor;
import javax.swing.text.html.parser.Entity;
import java.awt.*;
import java.io.*;
import java.lang.reflect.Array;
import java.util.*;
import java.util.List;
import java.util.stream.Collectors;
public class Main {
static FastScanner sc;
static PrintWriter pw;
static final long INF = 200000000000000l;
static final int MOD = 1000000007;
static final int N = 1005;
static int mul(int a, int b) {
return (int) ((a * 1l * b) % MOD);
}
public static int pow(int a, int n) {
int res = -1;
while(n != 0) {
if((n & 1) == 1) {
res = mul(res, a);
}
a = mul(a, a);
n >>= 1;
}
return res;
}
public static int inv(int a) {
return pow(a, MOD-2);
}
public static List<Integer> getPrimes() {
List<Integer> ans = new ArrayList<>();
boolean[] prime = new boolean[N];
Arrays.fill(prime, true);
prime[0] = prime[1] = false;
for(int i = 2; i < N; ++i) {
if(prime[i]) {
ans.add(i);
if (i * 1l * i <= N)
for (int j = i * i; j < N; j += i)
prime[j] = false;
}
}
return ans;
}
public static long gcd(long a, long b) {
if(b == 0) return a;
else return gcd(b, a % b);
}
public static class A {
long x;
long y;
A(long a, long b) {
this.x = a;
this.y = b;
}
}
public static void solve() throws IOException {
int n = sc.nextInt();
pw.println("? 1 " + n);
pw.flush();
int second = sc.nextInt();
int l = 0, r = 0;
boolean left = true;
if(second == n) {
left = false;
r = second;
l = 0;
} else if(second == 1) {
l = second;
r = n + 1;
} else {
pw.println("? " + second + " " + n);
pw.flush();
if(second == sc.nextInt() && second != n) {
l = second;
r = n + 1;
}
else {
r = second;
l = 0;
left = false;
}
}
while(r - l >= 2) {
int mid = (l + r) / 2;
if(left) {
pw.println("? " + second + " " + mid);
pw.flush();
int x = sc.nextInt();
if(x == second)
r = mid;
else l = mid;
} else {
pw.println("? " + mid + " " + second);
pw.flush();
int x = sc.nextInt();
if(x == second) l = mid;
else r = mid;
}
}
pw.println("! " + (left ? (l + 1) : (l)) );
}
public static void main(String[] args) throws IOException {
sc = new FastScanner(System.in);
pw = new PrintWriter(System.out);
int xx = 1;
while(xx > 0) {
solve();
xx--;
}
pw.close();
}
}
class FastScanner {
static StringTokenizer st = new StringTokenizer("");
static BufferedReader br;
public FastScanner(InputStream inputStream) {
br = new BufferedReader(new InputStreamReader(inputStream));
}
public String next() throws IOException {
while (!st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 8
|
standard input
|
[
"binary search",
"interactive"
] |
eb660c470760117dfd0b95acc10eee3b
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,900
| null |
standard output
| |
PASSED
|
5bd8c0f96c8931838309238e1ce0ae9d
|
train_109.jsonl
|
1613658900
|
The only difference between the easy and the hard version is the limit to the number of queries.This is an interactive problem.There is an array $$$a$$$ of $$$n$$$ different numbers. In one query you can ask the position of the second maximum element in a subsegment $$$a[l..r]$$$. Find the position of the maximum element in the array in no more than 20 queries.A subsegment $$$a[l..r]$$$ is all the elements $$$a_l, a_{l + 1}, ..., a_r$$$. After asking this subsegment you will be given the position of the second maximum from this subsegment in the whole array.
|
256 megabytes
|
import java.awt.*;
import java.io.*;
import java.lang.reflect.Array;
import java.util.*;
import java.util.List;
import java.util.concurrent.LinkedBlockingQueue;
public class Coding {
private static BufferedReader bi = new BufferedReader(new InputStreamReader(System.in));
private static BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out));
private static int[] po = new int[20];
public static void main(String[] args) {
try {
run();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void run() throws Exception {
InputModule inp = new InputModule();
OutputModule out = new OutputModule();
int t = 1;
while (t > 0) {
int n = inp.cinInt();
int l = 1, r = n;
int ans = l;
if (n == 2) {
writer.append("? " + l + " " + r + "\n");
writer.flush();
int idx = inp.cinInt();
if (idx == l) {
ans = r;
} else {
ans = l;
}
} else {
boolean right = true;
int prev = -1;
int st = -1, en = -1, sidx = -1;
while ((r - l > 1)) {
int idx;
if (prev == -1) {
writer.append("? " + l + " " + r + "\n");
writer.flush();
idx = inp.cinInt();
} else {
idx = prev;
}
int mid = (l + r) / 2;
if (idx <= mid) {
if (l == mid) {
st = mid + 1;
en = r;
sidx = idx;
break;
} else {
writer.append("? " + l + " " + mid + "\n");
writer.flush();
int idx2 = inp.cinInt();
prev = idx2;
if (idx == idx2) {
r = mid;
} else {
st = mid + 1;
en = r;
sidx = idx;
break;
}
}
} else {
if (r == (mid + 1)) {
st = l;
en = mid;
sidx = mid + 1;
right = false;
break;
} else {
writer.append("? " + (mid + 1) + " " + r + "\n");
writer.flush();
int idx2 = inp.cinInt();
prev = idx2;
if (idx == idx2) {
l = mid + 1;
} else {
st = l;
en = mid;
sidx = idx;
right = false;
break;
}
}
}
}
// System.out.println(st + " " + en + " " + sidx + " " + right);
if (st == -1) {
if (l == r) ans = l;
else {
writer.append("? " + l + " " + r + "\n");
writer.flush();
int idx = inp.cinInt();
if (idx == l) {
ans = r;
} else {
ans = l;
}
}
} else {
if (right) {
while (en - st > 1) {
int mi = (st + en) / 2;
writer.append("? " + sidx + " " + mi + "\n");
writer.flush();
int iddx = inp.cinInt();
if (iddx == sidx) {
en = mi;
} else {
st = mi+1;
}
}
} else {
while (en - st > 1) {
int mi = (st + en) / 2;
writer.append("? " + (mi+1) + " " + sidx + "\n");
writer.flush();
int iddx = inp.cinInt();
if (iddx == sidx) {
st = mi + 1;
} else {
en = mi;
}
}
}
if (st == en) ans = st;
else {
writer.append("? " + st + " " + en + "\n");
writer.flush();
int idx = inp.cinInt();
if (idx == st) {
ans = en;
} else {
ans = st;
}
}
}
}
writer.append("! " + ans + "\n");
writer.flush();
t--;
}
}
private static class InputModule {
private int cinInt() throws Exception {
return Integer.parseInt(bi.readLine().split(" ")[0].trim());
}
private long cinLong() throws Exception {
return Long.parseLong(bi.readLine().split(" ")[0].trim());
}
private Double cinDouble() throws Exception {
return Double.parseDouble(bi.readLine().split(" ")[0].trim());
}
private String cinString() throws Exception {
return bi.readLine();
}
private int[] cinIntArray(int n) throws Exception {
String input = bi.readLine();
String[] values = input.split(" ");
int[] ar = new int[n];
for (int i = 0; i < n; ++i) {
ar[i] = Integer.parseInt(values[i]);
}
return ar;
}
private int[] cinIntArray() throws Exception {
String input = bi.readLine();
String[] values = input.split(" ");
int[] ar = new int[values.length];
for (int i = 0; i < values.length; ++i) {
ar[i] = Integer.parseInt(values[i]);
}
return ar;
}
private long[] cinLongArray(int n) throws Exception {
String input = bi.readLine();
String[] values = input.split(" ");
long[] ar = new long[n];
for (int i = 0; i < n; ++i) {
ar[i] = Long.parseLong(values[i]);
}
return ar;
}
private String[] cinStringArray(int n) throws Exception {
return bi.readLine().split(" ");
}
}
private static class OutputModule {
private void printInt(int ans) throws Exception {
writer.append(ans + "\n");
writer.flush();
}
private void printLong(long ans) throws Exception {
writer.append(ans + "\n");
writer.flush();
}
private void printDouble(Double ans) throws Exception {
writer.append(String.format("%.10f", ans));
writer.append("\n");
writer.flush();
}
private void printString(String ans) throws Exception {
writer.append(ans + "\n");
writer.flush();
}
private void printIntArray(int[] ans) throws Exception {
for (int i = 0; i < ans.length; ++i) {
writer.append(ans[i] + " ");
}
writer.append("\n");
writer.flush();
}
private void printLongArray(long[] ans) throws Exception {
for (int i = 0; i < ans.length; ++i) {
writer.append(ans[i] + " ");
}
writer.append("\n");
writer.flush();
}
private void printIntList(List<Integer> list) throws Exception {
for (int i = 0; i < list.size(); ++i) {
writer.append(list.get(i) + " ");
}
writer.append("\n");
writer.flush();
}
private void printLongList(List<Long> list) throws Exception {
for (int i = 0; i < list.size(); ++i) {
writer.append(list.get(i) + " ");
}
writer.append("\n");
writer.flush();
}
private void printIntMatrix(int[][] mat, int n, int m) throws Exception {
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
writer.append(mat[i][j] + " ");
}
writer.append("\n");
}
writer.flush();
}
private void printLongMatrix(long[][] mat, int n, int m) throws Exception {
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
writer.append(mat[i][j] + " ");
}
writer.append("\n");
}
writer.flush();
}
private void printPoint(Point p) throws Exception {
writer.append(p.x + " " + p.y + "\n");
writer.flush();
}
private void printPoints(List<Point> p) throws Exception {
for (Point pp : p) {
writer.append(pp.x + " " + pp.y + "\n");
}
writer.flush();
}
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 8
|
standard input
|
[
"binary search",
"interactive"
] |
eb660c470760117dfd0b95acc10eee3b
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,900
| null |
standard output
| |
PASSED
|
c176b6a1e45dd0ee639ab68d4ae5ee91
|
train_109.jsonl
|
1613658900
|
The only difference between the easy and the hard version is the limit to the number of queries.This is an interactive problem.There is an array $$$a$$$ of $$$n$$$ different numbers. In one query you can ask the position of the second maximum element in a subsegment $$$a[l..r]$$$. Find the position of the maximum element in the array in no more than 20 queries.A subsegment $$$a[l..r]$$$ is all the elements $$$a_l, a_{l + 1}, ..., a_r$$$. After asking this subsegment you will be given the position of the second maximum from this subsegment in the whole array.
|
256 megabytes
|
import java.util.*;
import java.io.*;
public class Main {
static FastScanner sc = new FastScanner(System.in);
static PrintWriter pw = new PrintWriter(System.out);
static StringBuilder sb = new StringBuilder();
public static void main(String[] args) throws Exception {
int n = sc.nextInt();
System.out.println("? 1 " + n);
int center = sc.nextInt();
if (center == 1) {
int left = 1;
int right = n;
while (right - left > 1) {
int mid = (left + right) / 2;
System.out.println("? " + center + " " + mid);
int now = sc.nextInt();
if (center == now) {
right = mid;
} else {
left = mid;
}
}
System.out.println("! " + right);
} else if (center == n) {
int left = 1;
int right = n;
while (right - left > 1) {
int mid = (left + right) / 2;
System.out.println("? " + mid + " " + center);
int now = sc.nextInt();
if (center == now) {
left = mid;
} else {
right = mid;
}
}
System.out.println("! " + left);
} else {
System.out.println("? 1 " + center);
int now = sc.nextInt();
if (center == now) {
int left = 1;
int right = center;
while (right - left > 1) {
int mid = (left + right) / 2;
System.out.println("? " + mid + " " + center);
now = sc.nextInt();
if (center == now) {
left = mid;
} else {
right = mid;
}
}
System.out.println("! " + left);
} else {
int left = center;
int right = n;
while (right - left > 1) {
int mid = (left + right) / 2;
System.out.println("? " + center + " " + mid);
now = sc.nextInt();
if (center == now) {
right = mid;
} else {
left = mid;
}
}
System.out.println("! " + right);
}
}
}
static class GeekInteger {
public static void save_sort(int[] array) {
shuffle(array);
Arrays.sort(array);
}
public static int[] shuffle(int[] array) {
int n = array.length;
Random random = new Random();
for (int i = 0, j; i < n; i++) {
j = i + random.nextInt(n - i);
int randomElement = array[j];
array[j] = array[i];
array[i] = randomElement;
}
return array;
}
public static void save_sort(long[] array) {
shuffle(array);
Arrays.sort(array);
}
public static long[] shuffle(long[] array) {
int n = array.length;
Random random = new Random();
for (int i = 0, j; i < n; i++) {
j = i + random.nextInt(n - i);
long randomElement = array[j];
array[j] = array[i];
array[i] = randomElement;
}
return array;
}
}
}
class FastScanner {
private BufferedReader reader = null;
private StringTokenizer tokenizer = null;
public FastScanner(InputStream in) {
reader = new BufferedReader(new InputStreamReader(in));
tokenizer = null;
}
public String next() {
if (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public String nextLine() {
if (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
return reader.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken("\n");
}
public long nextLong() {
return Long.parseLong(next());
}
public int nextInt() {
return Integer.parseInt(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public String[] nextArray(int n) {
String[] a = new String[n];
for (int i = 0; i < n; i++)
a[i] = next();
return a;
}
public int[] nextIntArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
public long[] nextLongArray(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 8
|
standard input
|
[
"binary search",
"interactive"
] |
eb660c470760117dfd0b95acc10eee3b
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,900
| null |
standard output
| |
PASSED
|
342076fe85ede31ba9c01d6a5ccd3846
|
train_109.jsonl
|
1613658900
|
The only difference between the easy and the hard version is the limit to the number of queries.This is an interactive problem.There is an array $$$a$$$ of $$$n$$$ different numbers. In one query you can ask the position of the second maximum element in a subsegment $$$a[l..r]$$$. Find the position of the maximum element in the array in no more than 20 queries.A subsegment $$$a[l..r]$$$ is all the elements $$$a_l, a_{l + 1}, ..., a_r$$$. After asking this subsegment you will be given the position of the second maximum from this subsegment in the whole array.
|
256 megabytes
|
import java.io.BufferedReader;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class GuessingTheGreatest implements Closeable {
private InputReader in = new InputReader(System.in);
private PrintWriter out = new PrintWriter(System.out);
public void solve() {
int n = in.ni();
int pivot = ask(0, n - 1);
int left, right;
if (pivot > 0 && pivot < n - 1) {
int leftHalf = ask(0, pivot);
if (leftHalf == pivot) {
left = 0;
right = pivot - 1;
} else {
left = pivot + 1;
right = n - 1;
}
} else if (pivot == n - 1) {
left = 0;
right = n - 2;
} else {
left = 1;
right = n - 1;
}
int max;
if (pivot < left) {
max = n + 5;
while (left <= right) {
int mid = left + (right - left) / 2;
int response = ask(pivot, mid);
if (response == pivot) {
max = Math.min(max, mid);
right = mid - 1;
} else {
left = mid + 1;
}
}
} else {
max = -1;
while (left <= right) {
int mid = left + (right - left) / 2;
int response = ask(mid, pivot);
if (response == pivot) {
max = Math.max(mid, max);
left = mid + 1;
} else {
right = mid - 1;
}
}
}
answer(max);
}
private int ask(int left, int right) {
out.printf("? %d %d\n", left + 1, right + 1);
out.flush();
return in.ni() - 1;
}
private void answer(int idx) {
out.printf("! %d\n", idx + 1);
out.flush();
}
@Override
public void close() throws IOException {
in.close();
out.close();
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int ni() {
return Integer.parseInt(next());
}
public long nl() {
return Long.parseLong(next());
}
public void close() throws IOException {
reader.close();
}
}
public static void main(String[] args) throws IOException {
try (GuessingTheGreatest instance = new GuessingTheGreatest()) {
instance.solve();
}
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 8
|
standard input
|
[
"binary search",
"interactive"
] |
eb660c470760117dfd0b95acc10eee3b
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,900
| null |
standard output
| |
PASSED
|
c9d3127cc0055b58335f4646bdb4570d
|
train_109.jsonl
|
1613658900
|
The only difference between the easy and the hard version is the limit to the number of queries.This is an interactive problem.There is an array $$$a$$$ of $$$n$$$ different numbers. In one query you can ask the position of the second maximum element in a subsegment $$$a[l..r]$$$. Find the position of the maximum element in the array in no more than 20 queries.A subsegment $$$a[l..r]$$$ is all the elements $$$a_l, a_{l + 1}, ..., a_r$$$. After asking this subsegment you will be given the position of the second maximum from this subsegment in the whole array.
|
256 megabytes
|
import java.io.*;
import java.util.*;
public class C {
static BufferedReader br;
public static void main(String[] args) throws NumberFormatException, IOException {
// TODO Auto-generated method stub
br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
System.out.println("? " + 1 + " " + n);
System.out.flush();
int resp = Integer.parseInt(br.readLine());
if(n == 2) {
if(resp == 1)
System.out.println("! 2");
else
System.out.println("! 1");
System.out.flush();
}else {
boolean go = true;
if(resp == 1) {
go = false;
}
int x = 1;
int mv = resp;
if(go) {
System.out.println("? " + x + " " + mv);
System.out.flush();
resp = Integer.parseInt(br.readLine());
}
if(resp == mv && go) {
int l = 1;
int r = mv;
int mid;
while(r - l > 1) {
mid = (r + l) / 2;
System.out.println("? " + mid + " " + mv);
System.out.flush();
resp = Integer.parseInt(br.readLine());
if(resp == mv) {
l = mid;
}else {
r = mid;
}
}
System.out.println("? " + l + " " + r);
System.out.flush();
resp = Integer.parseInt(br.readLine());
if(resp == l)
System.out.println("! " + r);
else
System.out.println("! " + l);
System.out.flush();
}else {
int l = mv;
int r = n;
int mid;
while(r-l > 1) {
mid = (r + l)/2;
System.out.println("? " + mv + " " + mid);
System.out.flush();
resp = Integer.parseInt(br.readLine());
if(resp == mv) {
r = mid;
}else {
l = mid;
}
}
System.out.println("? " + l + " " + r);
System.out.flush();
resp = Integer.parseInt(br.readLine());
if(resp == l)
System.out.println("! " + r);
else
System.out.println("! " + l);
System.out.flush();
}
}
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 8
|
standard input
|
[
"binary search",
"interactive"
] |
eb660c470760117dfd0b95acc10eee3b
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,900
| null |
standard output
| |
PASSED
|
55f6470a0f38ee49d6fd0ea3e57f94dd
|
train_109.jsonl
|
1613658900
|
The only difference between the easy and the hard version is the limit to the number of queries.This is an interactive problem.There is an array $$$a$$$ of $$$n$$$ different numbers. In one query you can ask the position of the second maximum element in a subsegment $$$a[l..r]$$$. Find the position of the maximum element in the array in no more than 20 queries.A subsegment $$$a[l..r]$$$ is all the elements $$$a_l, a_{l + 1}, ..., a_r$$$. After asking this subsegment you will be given the position of the second maximum from this subsegment in the whole array.
|
256 megabytes
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) throws Exception {
Thread thread = new Thread(null, new TaskAdapter(), "", 1 << 27);
thread.start();
thread.join();
}
static class TaskAdapter implements Runnable {
@Override
public void run() {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastReader in = new FastReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
C1GuessingTheGreatestEasyVersion solver = new C1GuessingTheGreatestEasyVersion();
solver.solve(1, in, out);
out.close();
}
}
static class C1GuessingTheGreatestEasyVersion {
FastReader s;
PrintWriter w;
public void solve(int testNumber, FastReader s, PrintWriter w) {
int n = s.nextInt();
this.s = s;
this.w = w;
int min = query(1, n);
int mid = 1 + n >> 1;
if (n == 2) {
if (min == 1) w.println("! 2");
else w.println("! 1");
w.flush();
return;
}
int l = 1, r;
if (min == n) {
r = min - 1;
while (l <= r) {
mid = l + r >> 1;
int res = query(min - mid, min);
if (res == min) r = mid - 1;
else l = mid + 1;
}
++r;
w.println("! " + (min - r));
} else if (min == 1) {
r = n - min;
while (l <= r) {
mid = l + r >> 1;
int res = query(min, min + mid);
if (res == min) r = mid - 1;
else l = mid + 1;
}
++r;
w.println("! " + (min + r));
} else {
int minot = query(1, min);
if (minot == min) {
r = min - 1;
while (l <= r) {
mid = l + r >> 1;
int res = query(min - mid, min);
if (res == min) r = mid - 1;
else l = mid + 1;
}
++r;
w.println("! " + (min - r));
} else {
r = n - min;
while (l <= r) {
mid = l + r >> 1;
int res = query(min, min + mid);
if (res == min) r = mid - 1;
else l = mid + 1;
}
++r;
w.println("! " + (min + r));
}
}
w.flush();
}
int query(int l, int r) {
w.println("? " + l + " " + r);
w.flush();
return s.nextInt();
}
}
static class FastReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private FastReader.SpaceCharFilter filter;
public FastReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 8
|
standard input
|
[
"binary search",
"interactive"
] |
eb660c470760117dfd0b95acc10eee3b
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,900
| null |
standard output
| |
PASSED
|
6a3a1925f3afe3f4684f25192b25a298
|
train_109.jsonl
|
1613658900
|
The only difference between the easy and the hard version is the limit to the number of queries.This is an interactive problem.There is an array $$$a$$$ of $$$n$$$ different numbers. In one query you can ask the position of the second maximum element in a subsegment $$$a[l..r]$$$. Find the position of the maximum element in the array in no more than 20 queries.A subsegment $$$a[l..r]$$$ is all the elements $$$a_l, a_{l + 1}, ..., a_r$$$. After asking this subsegment you will be given the position of the second maximum from this subsegment in the whole array.
|
256 megabytes
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class C {
public int ask(IO io, int l, int r) throws IOException {
if (l == r) {
return r + 1;
}
io.println("? " + l + " " + r);
io.flush();
return io.nextInt();
}
public void run() throws IOException {
IO io = new IO();
int n = io.nextInt();
int d = ask(io, 1, n);
if (ask(io, 1, d) == d) {
int l = 1;
int r = d;
int m;
while (r - l > 1) {
m = (r + l) / 2;
if (ask(io, m, d) == d) {
l = m;
} else {
r = m;
}
}
io.println("! " + l);
io.flush();
} else {
int l = d;
int r = n;
int m;
while (r - l > 1) {
m = (r + l) / 2;
if (ask(io, d, m) == d) {
r = m;
} else {
l = m;
}
}
io.println("! " + r);
io.flush();
}
io.close();
}
public static void main(String[] args) throws IOException {
new C().run();
}
}
class IO {
public IO() {
br = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
}
BufferedReader br;
StringTokenizer in;
PrintWriter out;
public String nextToken() throws IOException {
while (in == null || !in.hasMoreTokens()) {
in = new StringTokenizer(br.readLine());
}
return in.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
public double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
public long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
public void print(String a) {
out.print(a);
}
public void println(String a) {
out.println(a);
}
public void close() {
out.close();
}
public void flush() {
out.flush();
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 8
|
standard input
|
[
"binary search",
"interactive"
] |
eb660c470760117dfd0b95acc10eee3b
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,900
| null |
standard output
| |
PASSED
|
28ae890820894e0f83286170bd2d7e07
|
train_109.jsonl
|
1613658900
|
The only difference between the easy and the hard version is the limit to the number of queries.This is an interactive problem.There is an array $$$a$$$ of $$$n$$$ different numbers. In one query you can ask the position of the second maximum element in a subsegment $$$a[l..r]$$$. Find the position of the maximum element in the array in no more than 20 queries.A subsegment $$$a[l..r]$$$ is all the elements $$$a_l, a_{l + 1}, ..., a_r$$$. After asking this subsegment you will be given the position of the second maximum from this subsegment in the whole array.
|
256 megabytes
|
//created by Whiplash99
import java.io.*;
import java.util.*;
public class C
{
private static int count;
private static void flush(){System.out.flush();}
private static void ask(int l, int r) throws Exception
{
count++; if(count>20) throw new Exception();
System.out.println("? "+l+" "+r);
flush();
}
private static void answer(int x)
{
System.out.println("! "+x);
flush();
}
public static void main(String[] args) throws Exception
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int i,N; count=0;
N=Integer.parseInt(br.readLine().trim());
ask(1,N);
int p=Integer.parseInt(br.readLine().trim());
boolean flag=true; int ans=0;
if(p>1)
{
ask(1,p); ans=p-1;
int tmp=Integer.parseInt(br.readLine().trim());
if(tmp==p)
{
flag=false;
int l=1,r=p-1,mid;
while (l<=r)
{
mid=(l+r)/2;
ask(mid,p);
tmp=Integer.parseInt(br.readLine().trim());
if(tmp==p)
{
ans=mid;
l=mid+1;
}
else r=mid-1;
}
}
}
if(flag)
{
int l=p+1,r=N,mid; ans=p+1;
while (l<=r)
{
mid=(l+r)/2;
ask(p,mid);
int tmp=Integer.parseInt(br.readLine().trim());
if(tmp==p)
{
ans=mid;
r=mid-1;
}
else l=mid+1;
}
}
answer(ans);
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 8
|
standard input
|
[
"binary search",
"interactive"
] |
eb660c470760117dfd0b95acc10eee3b
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,900
| null |
standard output
| |
PASSED
|
3aa28bb65599992fc7df0820f2f1affb
|
train_109.jsonl
|
1613658900
|
The only difference between the easy and the hard version is the limit to the number of queries.This is an interactive problem.There is an array $$$a$$$ of $$$n$$$ different numbers. In one query you can ask the position of the second maximum element in a subsegment $$$a[l..r]$$$. Find the position of the maximum element in the array in no more than 20 queries.A subsegment $$$a[l..r]$$$ is all the elements $$$a_l, a_{l + 1}, ..., a_r$$$. After asking this subsegment you will be given the position of the second maximum from this subsegment in the whole array.
|
256 megabytes
|
import java.io.*;
import java.util.*;
import java.util.function.BinaryOperator;
import java.util.stream.Collectors;
public class Main {
private final static long mod = 1000000007;
private final static int MAXN = 1000001;
private static long power(long x, long y, long m) {
long temp;
if (y == 0)
return 1;
temp = power(x, y / 2, m);
temp = (temp * temp) % m;
if (y % 2 == 0)
return temp;
else
return ((x % m) * temp) % m;
}
private static long power(long x, long y) {
return power(x, y, mod);
}
public int solve(int[] nums) {
Map<Pair<Integer,Integer>,Integer>dp=new HashMap<>();
int ans=0;
for(int i=1;i<nums.length;i++){
for(int j=i+1;j<nums.length;j++) {
Pair<Integer,Integer>prev=new Pair<>(nums[j]-nums[i],nums[i]);
Integer v=dp.get(prev);
Pair<Integer,Integer>curr=new Pair<>(nums[i],nums[j]);
if(v!=null){
dp.put(curr,Math.max(dp.get(prev),v+1));
}
else {
dp.put(curr, 2);
}
ans=Math.max(ans,dp.get(curr));
}
}
return ans;
}
private static long gcd(long a, long b) {
if (b == 0) return a;
return gcd(b, a % b);
}
static int nextPowerOf2(int a) {
return 1 << nextLog2(a);
}
static int nextLog2(int a) {
return (a == 0 ? 0 : 32 - Integer.numberOfLeadingZeros(a - 1));
}
private static long modInverse(long a, long m) {
long m0 = m;
long y = 0, x = 1;
if (m == 1)
return 0;
while (a > 1) {
long q = a / m;
long t = m;
m = a % m;
a = t;
t = y;
y = x - q * y;
x = t;
}
if (x < 0)
x += m0;
return x;
}
private static int[] getLogArr(int n) {
int arr[] = new int[n + 1];
for (int i = 1; i < n + 1; i++) {
arr[i] = (int) (Math.log(i) / Math.log(2) + 1e-10);
}
return arr;
}
private static int log[] = getLogArr(MAXN);
private static long getLRSpt(long st[][], int L, int R, BinaryOperator<Long> binaryOperator) {
int j = log[R - L + 1];
return binaryOperator.apply(st[L][j], st[R - (1 << j) + 1][j]);
}
private static long[][] getSparseTable(int array[], BinaryOperator<Long> binaryOperator) {
int k = log[array.length + 1] + 1;
long st[][] = new long[array.length + 1][k + 1];
for (int i = 0; i < array.length; i++)
st[i][0] = array[i];
for (int j = 1; j <= k; j++) {
for (int i = 0; i + (1 << j) <= array.length; i++) {
st[i][j] = binaryOperator.apply(st[i][j - 1], st[i + (1 << (j - 1))][j - 1]);
}
}
return st;
}
private static long getULDRSpt(long st[][][][], int U, int L,int D, int R, BinaryOperator<Long> binaryOperator) {
int k = log[D - U + 1];
int l = log[R - L + 1];
long a= binaryOperator.apply(st[U][L][k][l], st[D - (1 << k) + 1][R - (1 << l) + 1][k][l]);
long b= binaryOperator.apply(st[U][R - (1 << l) + 1][k][l], st[D - (1 << k) + 1][L][k][l]);
return binaryOperator.apply(a,b);
}
private static long[][][][] getSparseTable2D(int arr[][], BinaryOperator<Long>bo){
int n=arr.length;
int m=arr[0].length;
int k=log[n+1]+2;
int l=log[m+1]+2;
long st[][][][]=new long[n][m][k][l];
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
st[i][j][0][0]=arr[i][j];
}
}
for(int x=1;x<k;x++){
for(int y=1;y<l;y++){
for(int i=0;i+(1<<x)<=n;i++){
for(int j=0;j+(1<<y)<=m;j++){
st[i][j][x][y]=bo.apply(bo.apply(st[i][j][x - 1][y-1], st[i + (1 << (x - 1))][j][x - 1][y-1]),
bo.apply(st[i][j+(1 << (y - 1))][x - 1][y-1], st[i + (1 << (x - 1))][j+(1 << (y - 1))][x - 1][y-1]));
}
}
}
}
return st;
}
static class Subset {
int parent;
int rank;
@Override
public String toString() {
return "" + parent;
}
}
static int find(Subset[] Subsets, int i) {
if (Subsets[i].parent != i)
Subsets[i].parent = find(Subsets, Subsets[i].parent);
return Subsets[i].parent;
}
static 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++;
}
}
private static int maxx(Integer... a) {
return Collections.max(Arrays.asList(a));
}
private static int minn(Integer... a) {
return Collections.min(Arrays.asList(a));
}
private static long maxx(Long... a) {
return Collections.max(Arrays.asList(a));
}
private static long minn(Long... a) {
return Collections.min(Arrays.asList(a));
}
private static class Pair<T extends Comparable<T>, U extends Comparable<U>> implements Comparable<Pair<T, U>> {
T a;
U b;
public Pair(T a, U b) {
this.a = a;
this.b = b;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Pair pair = (Pair) o;
return a.equals(pair.a) &&
b.equals(pair.b);
}
@Override
public int hashCode() {
return Objects.hash(a, b);
}
@Override
public String toString() {
return "(" + a +
"," + b +
')';
}
@Override
public int compareTo(Pair<T, U> o) {
return (this.a.equals(o.a) ? this.b.equals(o.b) ? 0 : this.b.compareTo(o.b) : this.a.compareTo(o.a));
}
}
public static int upperBound(List<Integer> list, int value) {
int low = 0;
int high = list.size();
while (low < high) {
final int mid = (low + high) / 2;
if (value >= list.get(mid)) {
low = mid + 1;
} else {
high = mid;
}
}
return low;
}
private static int[] getLPSArray(String pattern) {
int i, j, n = pattern.length();
int[] lps = new int[pattern.length()];
lps[0] = 0;
for (i = 1, j = 0; i < n; ) {
if (pattern.charAt(i) == pattern.charAt(j)) {
lps[i++] = ++j;
} else if (j > 0) {
j = lps[j - 1];
} else {
lps[i++] = 0;
}
}
return lps;
}
private static List<Integer> findPattern(String text, String pattern) {
List<Integer> matchedIndexes = new ArrayList<>();
if (pattern.length() == 0) {
return matchedIndexes;
}
int[] lps = getLPSArray(pattern);
int i = 0, j = 0, n = text.length(), m = pattern.length();
while (i < n) {
if (text.charAt(i) == pattern.charAt(j)) {
i++;
j++;
}
if (j == m) {
matchedIndexes.add(i - j);
j = lps[j - 1];
}
if (i < n && text.charAt(i) != pattern.charAt(j)) {
if (j > 0) {
j = lps[j - 1];
} else {
i++;
}
}
}
return matchedIndexes;
}
private static long getLCM(long a, long b) {
return (Math.max(a, b) / gcd(a, b)) * Math.min(a, b);
}
static long fac[] = new long[2000005];
static long ifac[] = new long[2000005];
private static void preCompute(int n) {
fac = new long[n + 1];
ifac = new long[n + 1];
fac[0] = ifac[0] = fac[1] = ifac[1] = 1;
int i;
for (i = 2; i < n + 1; i++) {
fac[i] = (i * fac[i - 1]) % mod;
ifac[i] = (power(i, mod - 2) * ifac[i - 1]) % mod;
}
}
private static long C(int n, int r) {
if (n < 0 || r < 0) return 1;
if (r > n) return 1;
return (fac[n] * ((ifac[r] * ifac[n - r]) % mod)) % mod;
}
static long getSum(long BITree[], int index) {
long sum = 0;
index = index + 1;
while (index > 0) {
sum += BITree[index];
index -= index & (-index);
}
return sum;
}
public static void updateBIT(long BITree[], int index, long val) {
index = index + 1;
while (index <= BITree.length - 1) {
BITree[index] += val;
index += index & (-index);
}
}
long[] constructBITree(int arr[], int m) {
int n = arr.length;
long BITree[] = new long[m + 1];
for (int i = 1; i <= n; i++)
BITree[i] = 0;
for (int i = 0; i < n; i++)
updateBIT(BITree, i, arr[i]);
return BITree;
}
private static String getBinaryString(int a[], int l, int r){
if(l>r||l>a.length-1||r>a.length-1||l<0||r<0)return "";
StringBuilder sb = new StringBuilder();
int i=l;
while(i<=r&&a[i]==0)i++;
for (;i<=r;i++){
sb.append(a[i]);
}
return sb.toString();
}
private static int cmpBS(String a, String b){
if(a.length()==b.length()){
return a.compareTo(b);
}
else return a.length()-b.length();
}
public static int[] threeEqualParts(int[] A) {
int ans[]=new int[2];
ans[0]=ans[1]=-1;
int lo1=0,hi1=A.length-3,mid1,curr;
while (lo1<=hi1){
mid1=lo1+(hi1-lo1)/2;
int lo=mid1+1,hi=A.length-2,mid;
String leftS=getBinaryString(A,0,mid1);
String midS=getBinaryString(A,lo, hi);;
String rightS="";
while(lo<=hi){
mid=lo+(hi-lo)/2;
midS=getBinaryString(A,mid1+1, mid);
rightS=getBinaryString(A,mid+1,A.length-1);
if(midS.equals(rightS)&&leftS.equals(midS)){
ans[0]=mid1;
ans[1]=mid+1;
return ans;
}
else if(cmpBS(rightS,midS) < 0){
hi=mid-1;
}
else {
lo=mid+1;
}
//System.out.println(mid1+" "+lo+" "+hi);
}
if(cmpBS(leftS,midS) < 0) {
hi1=mid1-1;
}
else {
lo1=mid1+1;
}
}
return ans;
}
private static int upperBound(int a[], int l, int r, int x) {
if (l > r) return -1;
if (l == r) {
if (a[l] <= x) {
return -1;
} else {
return a[l];
}
}
int m = (l + r) / 2;
if (a[m] <= x) {
return upperBound(a, m + 1, r, x);
} else {
return upperBound(a, l, m, x);
}
}
private static void mul(long A[][], long B[][]) {
int i, j, k, n = A.length;
long C[][] = new long[n][n];
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
for (k = 0; k < n; k++) {
C[i][j] = (C[i][j] + (A[i][k] * B[k][j]) % mod) % mod;
}
}
}
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
A[i][j] = C[i][j];
}
}
}
private static void power(long A[][], long base[][], long n) {
if (n < 2) {
return;
}
power(A, base, n / 2);
mul(A, A);
if (n % 2 == 1) {
mul(A, base);
}
}
private static void print(int... a) {
System.out.println(Arrays.toString(a));
}
static void reverse(Integer a[], int l, int r) {
while (l < r) {
int t = a[l];
a[l] = a[r];
a[r] = t;
l++;
r--;
}
}
private static int cntBits(int n){
int cnt=0;
while(n>0){
cnt+=n%2;
n/=2;
}
return cnt;
}
public void rotate(Integer[] nums, int k) {
k = k % nums.length;
reverse(nums, 0, nums.length - k - 1);
reverse(nums, nums.length - k, nums.length - 1);
reverse(nums, 0, nums.length - 1);
}
private static boolean isSorted(int a[]) {
for (int i = 0; i < a.length - 1; i++) {
if (a[i] > a[i + 1]) return false;
}
return true;
}
private static int upperBound(long csum[], long val){
int lo=0,hi=csum.length-1,mid,ans=csum.length;
while(lo<=hi){
mid=lo+(hi-lo)/2;
if(csum[mid]<=val){
lo=mid+1;
}
else {
ans=mid;
hi=mid-1;
}
}
return ans;
}
private static int lowerBound(long csum[], long val){
int lo=0,hi=csum.length-1,mid,ans=-1;
while(lo<=hi){
mid=lo+(hi-lo)/2;
if(csum[mid]<val){
lo=mid+1;
ans=mid;
}
else {
hi=mid-1;
}
}
return ans;
}
public int countRangeSum(int[] nums, int lower, int upper) {
int i,j,k,n=nums.length,ans=0;
long csum[]=new long[n];
long prev=0;
for(i=0;i<n;i++){
csum[i]=prev+nums[i];
prev=csum[i];
}
Arrays.sort(csum);
ans=upperBound(csum, upper)-lowerBound(csum,lower)-1;
for(i=0;i<n;i++){
ans+=upperBound(csum, upper+csum[i])-lowerBound(csum,lower+csum[i])-1;
}
return ans;
}
private static String reverse(String s) {
if ("".equals(s)) return "";
return reverse(s.substring(1)) + s.charAt(0);
}
private static boolean isPrime(int n) {
if (n <= 1)
return false;
if (n <= 3)
return true;
if (n % 2 == 0 || n % 3 == 0)
return false;
for (int i = 5; i * i <= n; i = i + 6)
if (n % i == 0 || n % (i + 2) == 0)
return false;
return true;
}
private static Map<Integer, Integer> bit = new HashMap<>();
private static void update(int i, int val){
while(i<=1000000){
bit.put(i,bit.getOrDefault(i,0)+val);
i+=i&-i;
}
}
private static long get(int i){
long sum=0;
while (i>0){
sum+=bit.getOrDefault(i,0);
i-=i&-i;
}
return sum;
}
private static Set<Long> getDivisors(long n) {
Set<Long> divisors = new HashSet<>();
for (long i = 1; i <= Math.sqrt(n); i++) {
if (n % i == 0) {
divisors.add(i);
divisors.add(n / i);
}
}
return divisors;
}
private static int getMed(List<Integer> arrList, int offset, int limit) {
List<Integer> tmp=new ArrayList<>();
for(int i=0;i<limit&&i+offset<arrList.size();i++){
tmp.add(arrList.get(i+offset));
}
Collections.sort(tmp);
return tmp.get((tmp.size()-1)/2);
}
private static void trv(int a[],int l,int r, Map<Integer,Integer> map, int d){
if(r<l)return;
if(r==l){
map.put(l, d);
return;
}
int mx=0,mxi=-1;
for(int i=l;i<=r;i++) {
if(a[i]>mx){
mx=a[i];
mxi=i;
}
}
map.put(mxi,d);
trv(a,l,mxi-1,map,d+1);
trv(a,mxi+1,r,map,d+1);
}
private static Map<String, Integer> kv=new HashMap<>();
private static int get2nd(int l, int r,FastReader in,FastWriter out) throws Exception {
String key=String.format("%d %d",l,r);
if(kv.get(key)==null){
out.println("? "+key);
int v=in.nextInt();
kv.put(key,v);
}
return kv.get(key);
}
public static void main(String[] args) throws Exception {
long START_TIME = System.currentTimeMillis();
try (FastReader in = new FastReader();
FastWriter out = new FastWriter()) {
int n,t, i, j, m, ti, tidx, gm, l=1, r=2,k,q;
//for (t = in.nextInt(), tidx = 1; tidx <= t; tidx++)
{
//out.print(String.format("Case #%d: ", tidx));
long x = 0, y = 0, z = 0, sum = 0, bhc = 0, ans = 0,ans1=0,d,g,curr=0;
n=in.nextInt();
if(n==1){
out.println("! 1");
}
else {
int smi=get2nd(1,n,in,out);
l=1;
r=n;
if(r>smi&&smi>1){
int v=get2nd(1,smi,in,out);
if(v==smi){
r=smi;
}
else l=smi;
}
if(smi<r) {
int l1=smi+1;
int r1=r;
while (l1 <= r1) {
int mid = (l1 + r1) / 2;
int v = get2nd(smi,mid,in,out);
if (v == smi) {
r = mid;
r1=mid-1;
} else l1 = mid+1;
}
}
if(l<smi){
int l1=l;
int r1=smi-1;
while (l1 <= r1) {
int mid = (l1 + r1) / 2;
int v = get2nd(mid,smi,in,out);
if (v == smi) {
l = mid;
l1 = mid+1;
} else {
r1=mid-1;
}
}
}
out.println("! "+(smi==l?r:l));
}
}
if (args.length > 0 && "ex_time".equals(args[0])) {
out.print("\nTime taken: ");
out.println(System.currentTimeMillis() - START_TIME);
}
out.commit();
} catch (Exception e) {
e.printStackTrace();
}
}
public static class FastReader implements Closeable {
private BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
private StringTokenizer st;
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());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
int[] nextIntArr(int n) {
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = nextInt();
}
return arr;
}
Integer[] nextIntegerArr(int n) {
Integer[] arr = new Integer[n];
for (int i = 0; i < n; i++) {
arr[i] = nextInt();
}
return arr;
}
double[] nextDoubleArr(int n) {
double[] arr = new double[n];
for (int i = 0; i < n; i++) {
arr[i] = nextDouble();
}
return arr;
}
long[] nextLongArr(int n) {
long[] arr = new long[n];
for (int i = 0; i < n; i++) {
arr[i] = nextLong();
}
return arr;
}
List<Long> nextLongList(int n) {
List<Long> retList = new ArrayList<>();
for (int i = 0; i < n; i++) {
retList.add(nextLong());
}
return retList;
}
String[] nextStrArr(int n) {
String[] arr = new String[n];
for (int i = 0; i < n; i++) {
arr[i] = next();
}
return arr;
}
int[][] nextIntArr2(int n, int m) {
int[][] arr = new int[n][m];
for (int i = 0; i < n; i++) {
arr[i] = nextIntArr(m);
}
return arr;
}
long[][] nextLongArr2(int n, int m) {
long[][] arr = new long[n][m];
for (int i = 0; i < n; i++) {
arr[i] = nextLongArr(m);
}
return arr;
}
@Override
public void close() throws IOException {
br.close();
}
}
public static class FastWriter implements Closeable {
BufferedWriter bw;
StringBuilder sb = new StringBuilder();
List<String> list = new ArrayList<>();
Set<String> set = new HashSet<>();
public FastWriter() {
bw = new BufferedWriter(new OutputStreamWriter(System.out));
}
<T> void commit() throws IOException {
bw.write(sb.toString());
bw.flush();
sb = new StringBuilder();
}
public <T> void print(T obj) throws IOException {
sb.append(obj.toString());
commit();
}
public void println() throws IOException {
print("\n");
}
public <T> void println(T obj) throws IOException {
print(obj.toString() + "\n");
}
<T> void printArrLn(T[] arr) throws IOException {
for (int i = 0; i < arr.length - 1; i++) {
print(arr[i] + " ");
}
println(arr[arr.length - 1]);
}
<T> void printArr2(T[][] arr) throws IOException {
for (int j = 0; j < arr.length; j++) {
for (int i = 0; i < arr[j].length - 1; i++) {
print(arr[j][i] + " ");
}
println(arr[j][arr[j].length - 1]);
}
}
<T> void printColl(Collection<T> coll) throws IOException {
List<String> stringList = coll.stream().map(e -> ""+e).collect(Collectors.toList());
println(String.format("%s",String.join(" ", stringList)));
}
void printCharN(char c, int n) throws IOException {
for (int i = 0; i < n; i++) {
print(c);
}
}
void printIntArr2(int[][] arr) throws IOException {
for (int j = 0; j < arr.length; j++) {
for (int i = 0; i < arr[j].length - 1; i++) {
print(arr[j][i] + " ");
}
println(arr[j][arr[j].length - 1]);
}
}
@Override
public void close() throws IOException {
bw.close();
}
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 8
|
standard input
|
[
"binary search",
"interactive"
] |
eb660c470760117dfd0b95acc10eee3b
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,900
| null |
standard output
| |
PASSED
|
84e179ef2f7a73eab6aa261e33d7777c
|
train_109.jsonl
|
1613658900
|
The only difference between the easy and the hard version is the limit to the number of queries.This is an interactive problem.There is an array $$$a$$$ of $$$n$$$ different numbers. In one query you can ask the position of the second maximum element in a subsegment $$$a[l..r]$$$. Find the position of the maximum element in the array in no more than 20 queries.A subsegment $$$a[l..r]$$$ is all the elements $$$a_l, a_{l + 1}, ..., a_r$$$. After asking this subsegment you will be given the position of the second maximum from this subsegment in the whole array.
|
256 megabytes
|
import java.io.*;
import java.util.*;
public class C {
public static void main(String[] args) {
FastScanner in = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
int n = in.nextInt();
int low = 1, high = n;
out.println("? "+low+" "+high); out.flush();
int index = in.nextInt();
int left = 0;
if(index!=1){
out.println("? "+low+" "+index); out.flush();
left = in.nextInt();
}
if(n==2){
if(left==0) out.println("! "+n);
else out.println("! "+1);
}
else if(left==index){
low = 1; high = index-1;
while(low<=high){
int mid = (low+high)/2;
out.println("? "+mid+" "+index); out.flush();
int x = in.nextInt();
if(x==index) low = mid+1;
else high = mid-1;
}
out.println("! "+high);
}
else{
low = index+1; high = n;
while(low<=high){
int mid = (low+high)/2;
out.println("? "+index+" "+mid); out.flush();
int x = in.nextInt();
if(x==index) high = mid-1;
else low = mid+1;
}
out.println("! "+low);
}
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) {}
return st.nextToken();
}
String nextLine(){
try{ return br.readLine(); }
catch(IOException e) { } return "";
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
int[] readArray(int n) {
int a[] = new int[n];
for(int i=0;i<n;i++) a[i] = nextInt();
return a;
}
}
static final Random random = new Random();
static void ruffleSort(int[] a){
int n = a.length;
for(int i=0;i<n;i++){
int j = random.nextInt(n), temp = a[j];
a[j] = a[i]; a[i] = temp;
}
Arrays.sort(a);
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 8
|
standard input
|
[
"binary search",
"interactive"
] |
eb660c470760117dfd0b95acc10eee3b
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,900
| null |
standard output
| |
PASSED
|
b7054454051ca20e0c4508c9f6670854
|
train_109.jsonl
|
1613658900
|
The only difference between the easy and the hard version is the limit to the number of queries.This is an interactive problem.There is an array $$$a$$$ of $$$n$$$ different numbers. In one query you can ask the position of the second maximum element in a subsegment $$$a[l..r]$$$. Find the position of the maximum element in the array in no more than 20 queries.A subsegment $$$a[l..r]$$$ is all the elements $$$a_l, a_{l + 1}, ..., a_r$$$. After asking this subsegment you will be given the position of the second maximum from this subsegment in the whole array.
|
256 megabytes
|
import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.StringTokenizer;
import java.util.List;
import java.util.*;
public class realfast implements Runnable
{
private static final int INF = (int) 1e9;
// long in= 1000000007;
long fac[]= new long[1000001];
long inv[]=new long[1000001];
public void solve() throws IOException
{
Scanner in = new Scanner(System.in);
//int t = readInt();
int n = in.nextInt();
System.out.println("? "+1+" "+n);
System.out.flush();
int val = in.nextInt();
int pal=-1;
int nal=-1;
if(val!=1)
{
System.out.println("? "+1+" "+val);
System.out.flush();
pal = in.nextInt();
}
if(val!=n){
System.out.println("? "+(val)+" "+n);
System.out.flush();
nal = in.nextInt();
}
int left =0;
int right =0;
int ans =0;
if(nal==val)
{
left=val+1;
right=n;
ans=right;
while(left<=right)
{
int mid = left+(right-left)/2;
System.out.println("? "+val+" "+mid);
System.out.flush();
int pal1 = in.nextInt();
if(pal1==val)
{
ans= mid;
right=mid-1;
}
else
left=mid+1;
}
}
else
{
left=1;
right=val-1;
ans= left;
while(left<=right)
{
int mid = left+(right-left)/2;
System.out.println("? "+mid+" "+val);
System.out.flush();
int pal1=in.nextInt();
if(pal1==val)
{
ans=mid;
left=mid+1;
}
else
right=mid-1;
}
}
System.out.println("! "+ans);
//int ans =right;
//System.out.
}
public int value (int seg[], int left , int right ,int index, int l, int r)
{
if(left>right)
{
return -100000000;
}
if(right<l||left>r)
return -100000000;
if(left>=l&&right<=r)
return seg[index];
int mid = left+(right-left)/2;
int val = value(seg,left,mid,2*index+1,l,r);
int val2 = value(seg,mid+1,right,2*index+2,l,r);
return Math.max(val,val2);
}
public int gcd(int a , int b )
{
if(a<b)
{
int t =a;
a=b;
b=t;
}
if(a%b==0)
return b ;
return gcd(b,a%b);
}
public long pow(long n , long p,long m)
{
if(p==0)
return 1;
long val = pow(n,p/2,m);;
val= (val*val)%m;
if(p%2==0)
return val;
else
return (val*n)%m;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public static void main(String[] args) {
new Thread(null, new realfast(), "", 128 * (1L << 20)).start();
}
private static final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null;
private BufferedReader reader;
private StringTokenizer tokenizer;
private PrintWriter out;
@Override
public void run() {
try {
if (ONLINE_JUDGE || !new File("input.txt").exists()) {
reader = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
} else {
reader = new BufferedReader(new FileReader("input.txt"));
out = new PrintWriter("output.txt");
}
solve();
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
try {
reader.close();
} catch (IOException e) {
// nothing
}
out.close();
}
}
private String readString() throws IOException {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
return tokenizer.nextToken();
}
@SuppressWarnings("unused")
private int readInt() throws IOException {
return Integer.parseInt(readString());
}
@SuppressWarnings("unused")
private long readLong() throws IOException {
return Long.parseLong(readString());
}
@SuppressWarnings("unused")
private double readDouble() throws IOException {
return Double.parseDouble(readString());
}
}
class edge implements Comparable<edge>{
int u ;
int v;
edge(int u, int v)
{
this.u=u;
this.v=v;
}
public int compareTo(edge e)
{
return this.v-e.v;
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 8
|
standard input
|
[
"binary search",
"interactive"
] |
eb660c470760117dfd0b95acc10eee3b
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,900
| null |
standard output
| |
PASSED
|
46f8080a42715db7cf73d6461aee3869
|
train_109.jsonl
|
1613658900
|
The only difference between the easy and the hard version is the limit to the number of queries.This is an interactive problem.There is an array $$$a$$$ of $$$n$$$ different numbers. In one query you can ask the position of the second maximum element in a subsegment $$$a[l..r]$$$. Find the position of the maximum element in the array in no more than 20 queries.A subsegment $$$a[l..r]$$$ is all the elements $$$a_l, a_{l + 1}, ..., a_r$$$. After asking this subsegment you will be given the position of the second maximum from this subsegment in the whole array.
|
256 megabytes
|
import java.util.*;
import java.io.*;
public class C1486 {
static int n;
static Scanner sc;
static PrintWriter pw;
public static int query(int l, int r) throws IOException {
pw.printf("? %d %d%n", l, r);
pw.flush();
return sc.nextInt();
}
public static void ans(int idx) throws IOException {
pw.printf("! %d%n", idx);
pw.flush();
}
public static void main(String[] args) throws IOException {
sc = new Scanner(System.in);
pw = new PrintWriter(System.out);
n = sc.nextInt();
int s = query(1, n);
int lo = 2;
int hi = n;
int ans = 0;
boolean sFirst = false;
if (s == 1) {
sFirst = true;
} else {
int g = query(1, s);
if (g != s) {
sFirst = true;
}
}
if (sFirst) {
while (lo <= hi) {
int mid = lo + hi >> 1;
int q = query(1, mid);
if (q != s) {
lo = mid + 1;
} else {
ans = mid;
hi = mid - 1;
}
}
} else {
lo = 1;
hi = n - 1;
while (lo <= hi) {
int mid = lo + hi >> 1;
int q = query(mid, n);
if (q != s) {
hi = mid - 1;
} else {
ans = mid;
lo = mid + 1;
}
}
}
ans(ans);
pw.close();
}
static class Scanner {
BufferedReader br;
StringTokenizer st;
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public Scanner(FileReader f) {
br = new BufferedReader(f);
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public int[] nextIntArr(int n) throws IOException {
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = Integer.parseInt(next());
}
return arr;
}
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 8
|
standard input
|
[
"binary search",
"interactive"
] |
eb660c470760117dfd0b95acc10eee3b
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,900
| null |
standard output
| |
PASSED
|
91e2b82ff4e48c9a4b827ad184951e6a
|
train_109.jsonl
|
1613658900
|
The only difference between the easy and the hard version is the limit to the number of queries.This is an interactive problem.There is an array $$$a$$$ of $$$n$$$ different numbers. In one query you can ask the position of the second maximum element in a subsegment $$$a[l..r]$$$. Find the position of the maximum element in the array in no more than 20 queries.A subsegment $$$a[l..r]$$$ is all the elements $$$a_l, a_{l + 1}, ..., a_r$$$. After asking this subsegment you will be given the position of the second maximum from this subsegment in the whole array.
|
256 megabytes
|
import java.util.*;
import java.io.*;
public class EdA {
static long[] mods = {1000000007, 998244353, 1000000009};
static long mod = mods[0];
public static MyScanner sc;
public static PrintWriter out;
public static void main(String[] omkar) throws Exception{
// TODO Auto-generated method stub
sc = new MyScanner();
out = new PrintWriter(System.out);
// String input1 = bf.readLine().trim();
// String input2 = bf.readLine().trim();
// COMPARING INTEGER OBJECTS U DO DOT EQUALS NOT ==
int lr = 0;//-1 = left, 1= right;
int n = sc.nextInt();
out.println("? 1 " + n);
out.flush();
int pos = sc.nextInt();
if (pos == 1){
lr = 1;
}
else if (pos == n){
lr = -1;
}
else{
out.println("? 1 " + pos);
out.flush();
int left = sc.nextInt();
if (left == pos){
lr = -1;
}
else{
lr = 1;
}
}
if (lr == -1){
int l = 1;
int r = pos-1;
while(l < r){
int mid = (l+r+1)/2;
out.println("? " + mid + " " + pos);
out.flush();
int v = sc.nextInt();
if (v == pos){
l = mid;
}
else{
r = mid-1;
}
}
out.println("! " + l);
out.close();
}
else{
int l = pos+1;
int r = n;
while(l < r){
int mid = (l+r)/2;
out.println("? " + pos + " " + mid);
out.flush();
int v = sc.nextInt();
if (v == pos){
r = mid;
}
else{
l = mid+1;
}
}
out.println("! " + l);
out.close();
}
// for(int j = 0;j<array.length;j++){
// out.print(array[j] + " ");
// }
// out.println();
}
static class Pair implements Comparable<Pair>{
private int x;
private int y;
public Pair(int x, int y){
this.x = x;
this.y = y;
}
public int compareTo(Pair other){
return Integer.compare(x, other.x);
}
}
static class Pair2 implements Comparable<Pair2>{
private int x;
private int y;
public Pair2(int x, int y){
this.x = x;
this.y = y;
}
public int compareTo(Pair2 other){
return Integer.compare(y, other.y);
}
}
public static void sort(int[] array){
ArrayList<Integer> copy = new ArrayList<>();
for (int i : array)
copy.add(i);
Collections.sort(copy);
for(int i = 0;i<array.length;i++)
array[i] = copy.get(i);
}
static String[] readArrayString(int n){
String[] array = new String[n];
for(int j =0 ;j<n;j++)
array[j] = sc.next();
return array;
}
static int[] readArrayInt(int n){
int[] array = new int[n];
for(int j = 0;j<n;j++)
array[j] = sc.nextInt();
return array;
}
static int[] readArrayInt1(int n){
int[] array = new int[n+1];
for(int j = 1;j<=n;j++){
array[j] = sc.nextInt();
}
return array;
}
static long[] readArrayLong(int n){
long[] array = new long[n];
for(int j =0 ;j<n;j++)
array[j] = sc.nextLong();
return array;
}
static double[] readArrayDouble(int n){
double[] array = new double[n];
for(int j =0 ;j<n;j++)
array[j] = sc.nextDouble();
return array;
}
static int minIndex(int[] array){
int minValue = Integer.MAX_VALUE;
int minIndex = -1;
for(int j = 0;j<array.length;j++){
if (array[j] < minValue){
minValue = array[j];
minIndex = j;
}
}
return minIndex;
}
static int minIndex(long[] array){
long minValue = Long.MAX_VALUE;
int minIndex = -1;
for(int j = 0;j<array.length;j++){
if (array[j] < minValue){
minValue = array[j];
minIndex = j;
}
}
return minIndex;
}
static int minIndex(double[] array){
double minValue = Double.MAX_VALUE;
int minIndex = -1;
for(int j = 0;j<array.length;j++){
if (array[j] < minValue){
minValue = array[j];
minIndex = j;
}
}
return minIndex;
}
static long power(long x, long y){
if (y == 0)
return 1;
if (y%2 == 1)
return (x*power(x, y-1))%mod;
return power((x*x)%mod, y/2)%mod;
}
static void verdict(boolean a){
out.println(a ? "YES" : "NO");
}
public static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
}
catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try{
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
//StringJoiner sj = new StringJoiner(" ");
//sj.add(strings)
//sj.toString() gives string of those stuff w spaces or whatever that sequence is
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 8
|
standard input
|
[
"binary search",
"interactive"
] |
eb660c470760117dfd0b95acc10eee3b
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,900
| null |
standard output
| |
PASSED
|
94a747d05278e11bcdea1ff26f4139e3
|
train_109.jsonl
|
1613658900
|
The only difference between the easy and the hard version is the limit to the number of queries.This is an interactive problem.There is an array $$$a$$$ of $$$n$$$ different numbers. In one query you can ask the position of the second maximum element in a subsegment $$$a[l..r]$$$. Find the position of the maximum element in the array in no more than 20 queries.A subsegment $$$a[l..r]$$$ is all the elements $$$a_l, a_{l + 1}, ..., a_r$$$. After asking this subsegment you will be given the position of the second maximum from this subsegment in the whole array.
|
256 megabytes
|
import java.util.*;
import java.io.*;
public class Main {
public static void main(String[] args) throws Exception {
int n=sc.nextInt();
pw.println("? "+1+" "+n);
pw.flush();
int v=sc.nextInt();
int x=0;
if(v!=1) {
pw.println("? "+1+" "+v);
pw.flush();
x=sc.nextInt();
}
if(x==v&&v!=1) {
int low=1;
int high=v-1;
int mid=(low+high)/2;
while(low<=high) {
pw.println("? "+mid+" "+v);
pw.flush();
x=sc.nextInt();
if(x==v) {
low=mid+1;
}else {
high=mid-1;
}
mid=(low+high)/2;
}
pw.println("! "+high);
}else {
int low=v+1;
int high=n;
int mid=(low+high)/2;
while(low<=high) {
pw.println("? "+v+" "+mid);
pw.flush();
x=sc.nextInt();
if(x==v) {
high=mid-1;
}else {
low=mid+1;
}
mid=(low+high)/2;
}
pw.println("! "+low);
}
pw.close();
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public Scanner(FileReader r) {
br = new BufferedReader(r);
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public String nextLine() throws IOException {
return br.readLine();
}
public double nextDouble() throws IOException {
String x = next();
StringBuilder sb = new StringBuilder("0");
double res = 0, f = 1;
boolean dec = false, neg = false;
int start = 0;
if (x.charAt(0) == '-') {
neg = true;
start++;
}
for (int i = start; i < x.length(); i++)
if (x.charAt(i) == '.') {
res = Long.parseLong(sb.toString());
sb = new StringBuilder("0");
dec = true;
} else {
sb.append(x.charAt(i));
if (dec)
f *= 10;
}
res += Long.parseLong(sb.toString()) / f;
return res * (neg ? -1 : 1);
}
public long[] nextlongArray(int n) throws IOException {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
public Long[] nextLongArray(int n) throws IOException {
Long[] a = new Long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
public int[] nextIntArray(int n) throws IOException {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
public Integer[] nextIntegerArray(int n) throws IOException {
Integer[] a = new Integer[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
public boolean ready() throws IOException {
return br.ready();
}
}
static class pair implements Comparable<pair> {
long x;
long y;
public pair(long x, long y) {
this.x = x;
this.y = y;
}
public String toString() {
return x + " " + y;
}
public boolean equals(Object o) {
if (o instanceof pair) {
pair p = (pair) o;
return p.x == x && p.y == y;
}
return false;
}
public int hashCode() {
return new Double(x).hashCode() * 31 + new Double(y).hashCode();
}
public int compareTo(pair other) {
if (this.x == other.x) {
return Long.compare(this.y, other.y);
}
return Long.compare(this.x, other.x);
}
}
static class tuble implements Comparable<tuble> {
int x;
int y;
int z;
public tuble(int x, int y, int z) {
this.x = x;
this.y = y;
this.z = z;
}
public String toString() {
return x + " " + y + " " + z;
}
public int compareTo(tuble other) {
if (this.x == other.x) {
if (this.y == other.y) {
return this.z - other.z;
}
return this.y - other.y;
} else {
return this.x - other.x;
}
}
}
static long mod = 1000000007;
static Random rn = new Random();
static Scanner sc = new Scanner(System.in);
static PrintWriter pw = new PrintWriter(System.out);
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 8
|
standard input
|
[
"binary search",
"interactive"
] |
eb660c470760117dfd0b95acc10eee3b
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,900
| null |
standard output
| |
PASSED
|
53c5e887c6d83c435cd1a0a0e688b3c1
|
train_109.jsonl
|
1613658900
|
The only difference between the easy and the hard version is the limit to the number of queries.This is an interactive problem.There is an array $$$a$$$ of $$$n$$$ different numbers. In one query you can ask the position of the second maximum element in a subsegment $$$a[l..r]$$$. Find the position of the maximum element in the array in no more than 20 queries.A subsegment $$$a[l..r]$$$ is all the elements $$$a_l, a_{l + 1}, ..., a_r$$$. After asking this subsegment you will be given the position of the second maximum from this subsegment in the whole array.
|
256 megabytes
|
import java.util.*;
import javax.sound.midi.Track;
import java.io.*;
public class tr0 {
static PrintWriter out;
static StringBuilder sb;
static long mod = (long) 1e9 + 7;
static long inf = (long) 1e16;
static int n, m;
static ArrayList<Integer>[] ad;
static int[][] remove, add;
static int[][] memo, memo1[];
static boolean vis[];
static long[] f, inv, ncr[];
static HashMap<Integer, Integer> hm;
static int[] pre, suf, Smax[], Smin[];
static int idmax, idmin;
static ArrayList<Integer> av;
static HashMap<Integer, Integer> mm;
static boolean[] msks;
static int[] lazy[], lazyCount;
static int[] a, dist;
static char[][] g;
static int ave;
static ArrayList<Integer> gl;
static int[][] arr;
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
out = new PrintWriter(System.out);
int n = sc.nextInt();
int pos = query(1, n);
if (n == 2) {
System.out.println("! " + (n - pos + 1));
System.out.flush();
return;
}
int ans = 0;
if (pos != n) {
int l = query(pos, n);
if (l == pos) {
int sign = 1;
int dest = pos;
for (int p = 17; p >= 0; p--) {
if ((dest + sign * (1 << p)) <= n) {
dest += sign * (1 << p);
int q = query(pos, dest);
if (q == pos) {
ans = dest;
sign = -1;
} else {
sign = 1;
}
}
}
} else {
int sign = -1;
ans = pos;
int dest = pos;
for (int p = 17; p >= 0; p--) {
if ((dest + sign * (1 << p)) >= 1) {
dest += sign * (1 << p);
int q = query(dest, pos);
if (q == pos) {
ans = dest;
sign = 1;
} else {
sign = -1;
}
}
}
}
} else {
int sign = -1;
int dest = pos;
for (int p = 17; p >= 0; p--) {
if ((dest + sign * (1 << p)) >= 1) {
dest += sign * (1 << p);
int q = query(dest, pos);
if (q == pos) {
ans = dest;
sign = 1;
} else {
sign = -1;
}
}
}
}
System.out.println("! " + ans);
System.out.flush();
// out.flush(); 1 2 3
}
static int query(int l, int r) throws IOException {
Scanner sc1 = new Scanner(System.in);
System.out.println("? " + l + " " + r);
System.out.flush();
return sc1.nextInt();
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream system) {
br = new BufferedReader(new InputStreamReader(system));
}
public Scanner(String file) throws Exception {
br = new BufferedReader(new FileReader(file));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public String nextLine() throws IOException {
return br.readLine();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public char nextChar() throws IOException {
return next().charAt(0);
}
public Long nextLong() throws IOException {
return Long.parseLong(next());
}
public int[] nextArrInt(int n) throws IOException {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
public long[] nextArrLong(int n) throws IOException {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
public int[] nextArrIntSorted(int n) throws IOException {
int[] a = new int[n];
Integer[] a1 = new Integer[n];
for (int i = 0; i < n; i++)
a1[i] = nextInt();
Arrays.sort(a1);
for (int i = 0; i < n; i++)
a[i] = a1[1].intValue();
return a;
}
public long[] nextArrLongSorted(int n) throws IOException {
long[] a = new long[n];
Long[] a1 = new Long[n];
for (int i = 0; i < n; i++)
a1[i] = nextLong();
Arrays.sort(a1);
for (int i = 0; i < n; i++)
a[i] = a1[1].longValue();
return a;
}
public boolean ready() throws IOException {
return br.ready();
}
public void waitForInput() throws InterruptedException {
Thread.sleep(3000);
}
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 8
|
standard input
|
[
"binary search",
"interactive"
] |
eb660c470760117dfd0b95acc10eee3b
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,900
| null |
standard output
| |
PASSED
|
d3dacf9f6d87e8ebac68010b5ad887cc
|
train_109.jsonl
|
1613658900
|
The only difference between the easy and the hard version is the limit to the number of queries.This is an interactive problem.There is an array $$$a$$$ of $$$n$$$ different numbers. In one query you can ask the position of the second maximum element in a subsegment $$$a[l..r]$$$. Find the position of the maximum element in the array in no more than 20 queries.A subsegment $$$a[l..r]$$$ is all the elements $$$a_l, a_{l + 1}, ..., a_r$$$. After asking this subsegment you will be given the position of the second maximum from this subsegment in the whole array.
|
256 megabytes
|
//stan hu tao
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 x1486C1
{
public static void main(String hi[]) throws Exception
{
BufferedReader infile = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(infile.readLine());
int N = Integer.parseInt(st.nextToken());
System.out.println("? 1 "+N);
System.out.flush();
int middle = Integer.parseInt(infile.readLine());
int res = 0;
if(middle > 1)
{
System.out.println("? 1 "+middle);
System.out.flush();
int dex = Integer.parseInt(infile.readLine());
if(dex == middle)
{
int low = 1;
int high = middle-1;
while(low != high)
{
int mid = (low+high+1)/2;
System.out.println("? "+mid+" "+middle);
System.out.flush();
dex = Integer.parseInt(infile.readLine());
if(dex == middle)
low = mid;
else
high = mid-1;
}
res = low;
}
}
if(res == 0 && middle < N)
{
//should always be true
int low = middle+1;
int high = N;
while(low != high)
{
int mid = (low+high)/2;
System.out.println("? "+middle+" "+mid);
System.out.flush();
int dex = Integer.parseInt(infile.readLine());
if(dex == middle)
high = mid;
else
low = mid+1;
}
res = low;
}
System.out.println("! "+res);
System.out.flush();
}
public static int[] readArr(int N, BufferedReader infile, StringTokenizer st) throws Exception
{
int[] arr = new int[N];
st = new StringTokenizer(infile.readLine());
for(int i=0; i < N; i++)
arr[i] = Integer.parseInt(st.nextToken());
return arr;
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 8
|
standard input
|
[
"binary search",
"interactive"
] |
eb660c470760117dfd0b95acc10eee3b
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,900
| null |
standard output
| |
PASSED
|
d3bc4a52008d4a5f2ec21184dfcd4a05
|
train_109.jsonl
|
1613658900
|
The only difference between the easy and the hard version is the limit to the number of queries.This is an interactive problem.There is an array $$$a$$$ of $$$n$$$ different numbers. In one query you can ask the position of the second maximum element in a subsegment $$$a[l..r]$$$. Find the position of the maximum element in the array in no more than 20 queries.A subsegment $$$a[l..r]$$$ is all the elements $$$a_l, a_{l + 1}, ..., a_r$$$. After asking this subsegment you will be given the position of the second maximum from this subsegment in the whole array.
|
256 megabytes
|
import java.util.*;
import java.io.*;
public class Div708 {
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////// /////////
//////// /////////
//////// HHHH HHHH EEEEEEEEEEEEE MMMM MMMM OOOOOO SSSSSSS EEEEEEEEEEEEE /////////
//////// HHHH HHHH EEEEEEEEEEEEE MMMMMM MMMMMM OOO OOO SSSS SSS EEEEEEEEEEEEE /////////
//////// HHHH HHHH EEEEE MMMM MMM MMM MMMM OOO OOO SSSS SSS EEEEE /////////
//////// HHHH HHHH EEEEE MMMM MMMMMM MMMM OOO OOO SSSS EEEEE /////////
//////// HHHH HHHH EEEEE MMMM MMMM OOO OOO SSSSSSS EEEEE /////////
//////// HHHHHHHHHHHHHHHH EEEEEEEEEEE MMMM MMMM OOO OOO SSSSSS EEEEEEEEEEE /////////
//////// HHHHHHHHHHHHHHHH EEEEEEEEEEE MMMM MMMM OOO OOO SSSSSSS EEEEEEEEEEE /////////
//////// HHHH HHHH EEEEE MMMM MMMM OOO OOO SSSS EEEEE /////////
//////// HHHH HHHH EEEEE MMMM MMMM OOO OOO SSS SSSS EEEEE /////////
//////// HHHH HHHH EEEEEEEEEEEEE MMMM MMMM OOO OOO SSS SSSS EEEEEEEEEEEEE /////////
//////// HHHH HHHH EEEEEEEEEEEEE MMMM MMMM OOOOOO SSSSSSS EEEEEEEEEEEEE /////////
//////// /////////
//////// /////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static Scanner sc;
static int Query(int l, int r) throws IOException {
if (l == r)
return l;
System.out.println("? " + l + " " + r);
return sc.nextInt();
}
public static void main(String[] args) throws IOException {
sc = new Scanner(System.in);
PrintWriter pw = new PrintWriter(System.out);
int n = sc.nextInt();
int snd = Query(1, n);
int l = 1;
int r = n;
if (l != snd && r != snd) {
int v = Query(l, snd);
if (v == snd) {
r = snd;
} else l = snd;
}
if (l == snd) {
int ans = snd + 1;
while (l <= r) {
int mid = l + r >> 1;
int v = Query(snd, mid);
if (v != snd) {
ans = mid + 1;
l = mid + 1;
} else {
r = mid - 1;
}
}
System.out.println("! " + ans);
} else {
int ans = snd - 1;
while (l <= r) {
int mid = l + r >> 1;
int v = Query(mid, snd);
if (v != snd) {
ans = mid - 1;
r = mid - 1;
} else {
l = mid + 1;
}
}
System.out.println("! " + ans);
}
pw.flush();
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(FileReader r) {
br = new BufferedReader(r);
}
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int[] nextIntArr(int n) throws IOException {
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = nextInt();
}
return a;
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public String nextLine() throws IOException {
return br.readLine();
}
public double nextDouble() throws IOException {
String x = next();
StringBuilder sb = new StringBuilder("0");
double res = 0, f = 1;
boolean dec = false, neg = false;
int start = 0;
if (x.charAt(0) == '-') {
neg = true;
start++;
}
for (int i = start; i < x.length(); i++)
if (x.charAt(i) == '.') {
res = Long.parseLong(sb.toString());
sb = new StringBuilder("0");
dec = true;
} else {
sb.append(x.charAt(i));
if (dec)
f *= 10;
}
res += Long.parseLong(sb.toString()) / f;
return res * (neg ? -1 : 1);
}
public boolean ready() throws IOException {
return br.ready();
}
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 8
|
standard input
|
[
"binary search",
"interactive"
] |
eb660c470760117dfd0b95acc10eee3b
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,900
| null |
standard output
| |
PASSED
|
bb8a7340bcbb119ad429238c03456c39
|
train_109.jsonl
|
1613658900
|
The only difference between the easy and the hard version is the limit to the number of queries.This is an interactive problem.There is an array $$$a$$$ of $$$n$$$ different numbers. In one query you can ask the position of the second maximum element in a subsegment $$$a[l..r]$$$. Find the position of the maximum element in the array in no more than 20 queries.A subsegment $$$a[l..r]$$$ is all the elements $$$a_l, a_{l + 1}, ..., a_r$$$. After asking this subsegment you will be given the position of the second maximum from this subsegment in the whole array.
|
256 megabytes
|
import java.util.*;
public class C {
static Scanner sc;
public static void main(String[] args) {
sc = new Scanner(System.in);
int n = sc.nextInt();
System.out.printf("? %d %d\n", 1, n);
int m = sc.nextInt();
if(m > 1) {
System.out.printf("? %d %d\n", 1, m);
int r = sc.nextInt();
if(r == m) {
findmaxleft(m, n);
}
else {
findmaxright(m, n);
}
}
else {
findmaxright(1, n);
}
}
static void findmaxleft(int m, int n) {
int a = 1, b = m;
while(b - a > 1) {
int c = (a + b)/2;
System.out.printf("? %d %d\n", c, m);
int r = sc.nextInt();
if(r == m) a = c;
else b = c;
}
System.out.printf("! %d\n", a);
}
static void findmaxright(int m, int n) {
int a = m, b = n;
while(b - a > 1) {
int c = (a + b)/2;
System.out.printf("? %d %d\n", m, c);
int r = sc.nextInt();
if(r == m) b = c;
else a = c;
}
System.out.printf("! %d\n", b);
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 8
|
standard input
|
[
"binary search",
"interactive"
] |
eb660c470760117dfd0b95acc10eee3b
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,900
| null |
standard output
| |
PASSED
|
38b2c036c795f87d7b0807896c16b000
|
train_109.jsonl
|
1613658900
|
The only difference between the easy and the hard version is the limit to the number of queries.This is an interactive problem.There is an array $$$a$$$ of $$$n$$$ different numbers. In one query you can ask the position of the second maximum element in a subsegment $$$a[l..r]$$$. Find the position of the maximum element in the array in no more than 20 queries.A subsegment $$$a[l..r]$$$ is all the elements $$$a_l, a_{l + 1}, ..., a_r$$$. After asking this subsegment you will be given the position of the second maximum from this subsegment in the whole array.
|
256 megabytes
|
import java.util.*;
import java.io.*;
public class C_1486 {
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
PrintWriter pw = new PrintWriter(System.out);
int n = sc.nextInt();
pw.printf("? 1 %d\n", n);
pw.flush();
int max2 = sc.nextInt();
if(n == 2) {
pw.println("! " + (max2 == 1 ? 2 : 1));
} else {
int start, end;
if(max2 == 1) {
start = 2;
end = n;
} else if(max2 == n) {
start = 1;
end = n - 1;
} else {
pw.printf("? 1 %d\n", max2);
pw.flush();
int ans = sc.nextInt();
if(ans == max2) {
start = 1;
end = max2 - 1;
} else {
start = max2 + 1;
end = n;
}
}
while(start < end) {
int mid = (start + end) >> 1;
if(mid > max2) {
pw.printf("? %d %d\n", max2, mid);
pw.flush();
int ans = sc.nextInt();
if(ans == max2) {
end = mid;
} else {
start = mid + 1;
}
} else {
pw.printf("? %d %d\n", mid + 1, max2);
pw.flush();
int ans = sc.nextInt();
if(ans == max2) {
start = mid + 1;
} else {
end = mid;
}
}
}
pw.println("! " + start);
}
pw.flush();
}
public static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream system) {
br = new BufferedReader(new InputStreamReader(system));
}
public Scanner(String file) throws Exception {
br = new BufferedReader(new FileReader(file));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public String nextLine() throws IOException {
return br.readLine();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public char nextChar() throws IOException {
return next().charAt(0);
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public int[] nextIntArray(int n) throws IOException {
int[] array = new int[n];
for (int i = 0; i < n; i++)
array[i] = nextInt();
return array;
}
public Integer[] nextIntegerArray(int n) throws IOException {
Integer[] array = new Integer[n];
for (int i = 0; i < n; i++)
array[i] = new Integer(nextInt());
return array;
}
public long[] nextLongArray(int n) throws IOException {
long[] array = new long[n];
for (int i = 0; i < n; i++)
array[i] = nextLong();
return array;
}
public double[] nextDoubleArray(int n) throws IOException {
double[] array = new double[n];
for (int i = 0; i < n; i++)
array[i] = nextDouble();
return array;
}
public static int[] shuffle(int[] a) {
int n = a.length;
Random rand = new Random();
for (int i = 0; i < n; i++) {
int tmpIdx = rand.nextInt(n);
int tmp = a[i];
a[i] = a[tmpIdx];
a[tmpIdx] = tmp;
}
return a;
}
public boolean ready() throws IOException {
return br.ready();
}
public void waitForInput() throws InterruptedException {
Thread.sleep(3000);
}
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 8
|
standard input
|
[
"binary search",
"interactive"
] |
eb660c470760117dfd0b95acc10eee3b
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,900
| null |
standard output
| |
PASSED
|
f47491750ea38cf7594341a93f6d0c17
|
train_109.jsonl
|
1613658900
|
The only difference between the easy and the hard version is the limit to the number of queries.This is an interactive problem.There is an array $$$a$$$ of $$$n$$$ different numbers. In one query you can ask the position of the second maximum element in a subsegment $$$a[l..r]$$$. Find the position of the maximum element in the array in no more than 20 queries.A subsegment $$$a[l..r]$$$ is all the elements $$$a_l, a_{l + 1}, ..., a_r$$$. After asking this subsegment you will be given the position of the second maximum from this subsegment in the whole array.
|
256 megabytes
|
import java.io.*;
import java.util.*;
public class F {
static int query(int l, int r) throws IOException {
System.out.printf("? %d %d\n", l, r);
return sc.nextInt();
}
static Scanner sc = new Scanner();
public static void main(String[] args) throws IOException {
int n = sc.nextInt();
int scnd = query(1, n);
boolean left = scnd != 1 && query(1, scnd) == scnd;
int lo = 2, hi = left ? scnd : n - scnd + 1;
int ans = -1;
while (lo <= hi) {
int mid = lo + hi >> 1;
int x;
if (left)
x = query(scnd - mid + 1, scnd);
else
x = query(scnd, scnd + mid - 1);
if (x == scnd) {
ans = mid;
hi = mid - 1;
} else
lo = mid + 1;
}
if (left)
ans = scnd - ans + 1;
else
ans = scnd + ans - 1;
System.out.printf("! %d\n", ans);
}
static class Scanner {
BufferedReader br;
StringTokenizer st;
Scanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
Scanner(String fileName) throws FileNotFoundException {
br = new BufferedReader(new FileReader(fileName));
}
String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
String nextLine() throws IOException {
return br.readLine();
}
int nextInt() throws IOException {
return Integer.parseInt(next());
}
long nextLong() throws NumberFormatException, IOException {
return Long.parseLong(next());
}
double nextDouble() throws NumberFormatException, IOException {
return Double.parseDouble(next());
}
boolean ready() throws IOException {
return br.ready() || st.hasMoreTokens();
}
int[] nxtArr(int n) throws IOException {
int[] ans = new int[n];
for (int i = 0; i < n; i++)
ans[i] = nextInt();
return ans;
}
}
static void sort(int[] a) {
shuffle(a);
Arrays.sort(a);
}
static void shuffle(int[] a) {
int n = a.length;
Random rand = new Random();
for (int i = 0; i < n; i++) {
int tmpIdx = rand.nextInt(n);
int tmp = a[i];
a[i] = a[tmpIdx];
a[tmpIdx] = tmp;
}
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 8
|
standard input
|
[
"binary search",
"interactive"
] |
eb660c470760117dfd0b95acc10eee3b
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,900
| null |
standard output
| |
PASSED
|
9cc0b248a9a08710b866e564dfa468cb
|
train_109.jsonl
|
1613658900
|
The only difference between the easy and the hard version is the limit to the number of queries.This is an interactive problem.There is an array $$$a$$$ of $$$n$$$ different numbers. In one query you can ask the position of the second maximum element in a subsegment $$$a[l..r]$$$. Find the position of the maximum element in the array in no more than 20 queries.A subsegment $$$a[l..r]$$$ is all the elements $$$a_l, a_{l + 1}, ..., a_r$$$. After asking this subsegment you will be given the position of the second maximum from this subsegment in the whole array.
|
256 megabytes
|
import java.util.*;
public class Solve{
static Scanner sc=new Scanner(System.in);
public static void main(String[] args){
int n=sc.nextInt();
int l=0;
int r=n-1;
int sec=q(l+1,r+1);
if(q(l+1,sec+1)!=sec || sec==0)
{ // right
l=sec;r=n-1;
while(r-l>1)
{
int m=(l+r)/2;
if(q(sec+1,m+1)==sec)
{
r=m;
}
else
{
l=m;
}
}
r++;
System.out.println("! "+r);
}
else
{
//left
l=0;r=sec;
while(r-l>1)
{
int m=(l+r)/2;
if(q(m+1,sec+1)==sec)
{
l=m;
}
else
{
r=m;
}
}
l++;
System.out.println("! "+l);
}
}
static int q(int l,int r){
if(l>=r) return -1;
System.out.println("? "+l+" "+r);
System.out.flush();
return sc.nextInt()-1;
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
eb660c470760117dfd0b95acc10eee3b
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,900
| null |
standard output
| |
PASSED
|
48c7e6e83a72fea32415c3a102b2796f
|
train_109.jsonl
|
1613658900
|
The only difference between the easy and the hard version is the limit to the number of queries.This is an interactive problem.There is an array $$$a$$$ of $$$n$$$ different numbers. In one query you can ask the position of the second maximum element in a subsegment $$$a[l..r]$$$. Find the position of the maximum element in the array in no more than 20 queries.A subsegment $$$a[l..r]$$$ is all the elements $$$a_l, a_{l + 1}, ..., a_r$$$. After asking this subsegment you will be given the position of the second maximum from this subsegment in the whole array.
|
256 megabytes
|
import java.util.*;
public class Solve{
static Scanner sc=new Scanner(System.in);
public static void main(String[] args){
int n=sc.nextInt();
int l=0;
int r=n-1;
int sec=q(l+1,r+1);
if(q(l+1,sec+1)!=sec || sec==0)
{
l=sec;r=n-1;
while(r-l>1){
int m=(l+r)/2;
if(q(sec+1,m+1)==sec){
r=m;
}
else{
l=m;
}
}
r++;
System.out.println("! "+r);
}
else
{
//left
l=0;r=sec;
while(r-l>1){
int m=(l+r)/2;
if(q(m+1,sec+1)==sec){
l=m;
}
else{
r=m;
}
}
l++;
System.out.println("! "+l);
}
}
static int q(int l,int r){
if(l>=r) return -1;
System.out.println("? "+l+" "+r);
System.out.flush();
return sc.nextInt()-1;
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
eb660c470760117dfd0b95acc10eee3b
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,900
| null |
standard output
| |
PASSED
|
44556f972f048f5c237561bab6626f69
|
train_109.jsonl
|
1613658900
|
The only difference between the easy and the hard version is the limit to the number of queries.This is an interactive problem.There is an array $$$a$$$ of $$$n$$$ different numbers. In one query you can ask the position of the second maximum element in a subsegment $$$a[l..r]$$$. Find the position of the maximum element in the array in no more than 20 queries.A subsegment $$$a[l..r]$$$ is all the elements $$$a_l, a_{l + 1}, ..., a_r$$$. After asking this subsegment you will be given the position of the second maximum from this subsegment in the whole array.
|
256 megabytes
|
import java.io.*;
import java.util.*;
import java.math.*;
public class Main {
static int right(int max,int start,int end,int n) {
FastScanner f = new FastScanner();
if(end<start) {
return 1000000000;
}
else {
int mid=(start+end)/2;
System.out.println("? "+(max+1)+" "+(mid+1));
int place=f.nextInt()-1;
if(place==max) {
return Math.min(mid, right(max,start,mid-1,n));
}
else {
return right(max,mid+1,end,n);
}
}
}
static int left(int max,int start,int end) {
// System.out.println(start+" "+end);
FastScanner f = new FastScanner();
if(end<start) {
return -1000000000;
}
else {
int mid=(start+end)/2;
System.out.println("? "+(mid+1)+" "+(max+1));
int place=f.nextInt()-1;
if(place==max) {
return Math.max(mid, left(max,mid+1,end));
}
else {
return left(max,start,mid-1);
}
}
}
public static void main(String[] args) throws IOException
{
FastScanner f = new FastScanner();
int t=1;
// t=f.nextInt();
PrintWriter out=new PrintWriter(System.out);
int mod=1000000007;
while(t>0) {
t--;
int n=f.nextInt();
System.out.println("? "+1+" "+(n));
int ind=f.nextInt()-1;
if(ind==(n-1)) {
System.out.println("! "+(left(ind,0,ind-1)+1));
}
else if(ind==0) {
System.out.println("! "+(right(ind,ind+1,n-1,n)+1));
}
else {
System.out.println("? "+(ind+1)+" "+(n));
int place=f.nextInt()-1;
if(place==ind) {
System.out.println("! "+(right(ind,ind+1,n-1,n)+1));
}
else {
System.out.println("! "+(left(ind,0,ind-1)+1));
}
}
}
out.close();
}
static void sort(int [] a) {
ArrayList<Integer> q = new ArrayList<>();
for (int i: a) q.add(i);
Collections.sort(q);
for (int i = 0; i < a.length; i++) a[i] = q.get(i);
}
static 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());
}
long[] readLongArray(int n) {
long[] a=new long[n];
for (int i=0; i<n; i++) a[i]=nextLong();
return a;
}
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
eb660c470760117dfd0b95acc10eee3b
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,900
| null |
standard output
| |
PASSED
|
0af7ca6c92fa2ba94940385b7ae8d847
|
train_109.jsonl
|
1613658900
|
The only difference between the easy and the hard version is the limit to the number of queries.This is an interactive problem.There is an array $$$a$$$ of $$$n$$$ different numbers. In one query you can ask the position of the second maximum element in a subsegment $$$a[l..r]$$$. Find the position of the maximum element in the array in no more than 20 queries.A subsegment $$$a[l..r]$$$ is all the elements $$$a_l, a_{l + 1}, ..., a_r$$$. After asking this subsegment you will be given the position of the second maximum from this subsegment in the whole array.
|
256 megabytes
|
import java.io.*;
import java.util.*;
import java.math.*;
public class Main {
static int right(int max,int start,int end,int n) {
FastScanner f = new FastScanner();
if(end<start) {
return 1000000000;
}
else {
int mid=(start+end)/2;
System.out.println("? "+(max+1)+" "+(mid+1));
int place=f.nextInt()-1;
if(place==max) {
return Math.min(mid, right(max,start,mid-1,n));
}
else {
return right(max,mid+1,end,n);
}
}
}
static int left(int max,int start,int end) {
// System.out.println(start+" "+end);
FastScanner f = new FastScanner();
if(end<start) {
return 0;
}
else {
int mid=(start+end)/2;
System.out.println("? "+(mid+1)+" "+(max+1));
int place=f.nextInt()-1;
if(place==max) {
return Math.max(mid, left(max,mid+1,end));
}
else {
return left(max,start,mid-1);
}
}
}
public static void main(String[] args) throws IOException
{
FastScanner f = new FastScanner();
int t=1;
// t=f.nextInt();
PrintWriter out=new PrintWriter(System.out);
int mod=1000000007;
while(t>0) {
t--;
int n=f.nextInt();
System.out.println("? "+1+" "+(n));
int ind=f.nextInt()-1;
if(ind==(n-1)) {
System.out.println("! "+(left(ind,0,ind-1)+1));
}
else if(ind==0) {
System.out.println("! "+(right(ind,ind+1,n-1,n)+1));
}
else {
System.out.println("? "+(ind+1)+" "+(n));
int place=f.nextInt()-1;
if(place==ind) {
System.out.println("! "+(right(ind,ind+1,n-1,n)+1));
}
else {
System.out.println("! "+(left(ind,0,ind-1)+1));
}
}
}
out.close();
}
static void sort(int [] a) {
ArrayList<Integer> q = new ArrayList<>();
for (int i: a) q.add(i);
Collections.sort(q);
for (int i = 0; i < a.length; i++) a[i] = q.get(i);
}
static 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());
}
long[] readLongArray(int n) {
long[] a=new long[n];
for (int i=0; i<n; i++) a[i]=nextLong();
return a;
}
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
eb660c470760117dfd0b95acc10eee3b
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,900
| null |
standard output
| |
PASSED
|
c21cc507ec5d29f24733a3b36202bf3a
|
train_109.jsonl
|
1613658900
|
The only difference between the easy and the hard version is the limit to the number of queries.This is an interactive problem.There is an array $$$a$$$ of $$$n$$$ different numbers. In one query you can ask the position of the second maximum element in a subsegment $$$a[l..r]$$$. Find the position of the maximum element in the array in no more than 20 queries.A subsegment $$$a[l..r]$$$ is all the elements $$$a_l, a_{l + 1}, ..., a_r$$$. After asking this subsegment you will be given the position of the second maximum from this subsegment in the whole array.
|
256 megabytes
|
import java.io.*;
import java.util.*;
import java.math.*;
public class Main {
static int right(int max,int start,int end,int n) {
FastScanner f = new FastScanner();
if(end<start) {
return n-1;
}
else {
int mid=(start+end)/2;
System.out.println("? "+(max+1)+" "+(mid+1));
int place=f.nextInt()-1;
if(place==max) {
return Math.min(mid, right(max,start,mid-1,n));
}
else {
return right(max,mid+1,end,n);
}
}
}
static int left(int max,int start,int end) {
// System.out.println(start+" "+end);
FastScanner f = new FastScanner();
if(end<start) {
return 0;
}
else {
int mid=(start+end)/2;
System.out.println("? "+(mid+1)+" "+(max+1));
int place=f.nextInt()-1;
if(place==max) {
return Math.max(mid, left(max,mid+1,end));
}
else {
return left(max,start,mid-1);
}
}
}
public static void main(String[] args) throws IOException
{
FastScanner f = new FastScanner();
int t=1;
// t=f.nextInt();
PrintWriter out=new PrintWriter(System.out);
int mod=1000000007;
while(t>0) {
t--;
int n=f.nextInt();
System.out.println("? "+1+" "+(n));
int ind=f.nextInt()-1;
if(ind==(n-1)) {
System.out.println("! "+(left(ind,0,ind-1)+1));
}
else if(ind==0) {
System.out.println("! "+(right(ind,ind+1,n-1,n)+1));
}
else {
System.out.println("? "+(ind+1)+" "+(n));
int place=f.nextInt()-1;
if(place==ind) {
System.out.println("! "+(right(ind,ind+1,n-1,n)+1));
}
else {
System.out.println("! "+(left(ind,0,ind-1)+1));
}
}
}
out.close();
}
static void sort(int [] a) {
ArrayList<Integer> q = new ArrayList<>();
for (int i: a) q.add(i);
Collections.sort(q);
for (int i = 0; i < a.length; i++) a[i] = q.get(i);
}
static 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());
}
long[] readLongArray(int n) {
long[] a=new long[n];
for (int i=0; i<n; i++) a[i]=nextLong();
return a;
}
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
eb660c470760117dfd0b95acc10eee3b
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,900
| null |
standard output
| |
PASSED
|
65c073bd159736bd271ed480686a826b
|
train_109.jsonl
|
1613658900
|
The only difference between the easy and the hard version is the limit to the number of queries.This is an interactive problem.There is an array $$$a$$$ of $$$n$$$ different numbers. In one query you can ask the position of the second maximum element in a subsegment $$$a[l..r]$$$. Find the position of the maximum element in the array in no more than 20 queries.A subsegment $$$a[l..r]$$$ is all the elements $$$a_l, a_{l + 1}, ..., a_r$$$. After asking this subsegment you will be given the position of the second maximum from this subsegment in the whole array.
|
256 megabytes
|
import java.io.*;
import java.util.*;
public class CF {
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 fs = new FastReader();
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");
}
int n = fs.nextInt();
int smax = ask(1, n);
int ans = -1;
if(ask(1, smax) == smax) {
int l = 1, r = smax-1;
while(l <= r) {
int mid = (l+r)/2;
if(ask(mid, smax) == smax) {
ans = mid;
l = mid+1;
} else {
r = mid-1;
}
}
} else {
int l = smax+1, r = n;
while(l <= r) {
int mid = (l+r)/2;
if(ask(smax, mid) == smax) {
ans = mid;
r = mid-1;
} else {
l = mid+1;
}
}
}
System.out.println("! " + ans);
}
public static int ask(int l, int r) {
if(l == r) return -1;
System.out.println("? " + l + " " + r);
int inx = fs.nextInt();
System.out.flush();
return inx;
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
eb660c470760117dfd0b95acc10eee3b
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,900
| null |
standard output
| |
PASSED
|
278dfbbceca5bb020214fb66782d73ff
|
train_109.jsonl
|
1613658900
|
The only difference between the easy and the hard version is the limit to the number of queries.This is an interactive problem.There is an array $$$a$$$ of $$$n$$$ different numbers. In one query you can ask the position of the second maximum element in a subsegment $$$a[l..r]$$$. Find the position of the maximum element in the array in no more than 20 queries.A subsegment $$$a[l..r]$$$ is all the elements $$$a_l, a_{l + 1}, ..., a_r$$$. After asking this subsegment you will be given the position of the second maximum from this subsegment in the whole array.
|
256 megabytes
|
import java.io.*;
import java.util.*;
public class CF {
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 fs = new FastReader();
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");
}
int n = fs.nextInt();
int smax = ask(1, n);
if(ask(1, smax) == smax) {
int l = 1, r = smax;
while(l < r) {
int mid = (l+r+1)/2;
if(ask(mid, n) == smax) {
l = mid;
} else {
r = mid-1;
}
}
System.out.println("! " + l);
} else {
int l = smax, r = n;
while(l < r) {
int mid = (l+r)/2;
if(ask(1, mid) == smax) {
r = mid;
} else {
l = mid+1;
}
}
System.out.println("! "+ l);
}
}
public static int ask(int l, int r) {
if(l == r) return -1;
System.out.println("? " + l + " " + r);
int inx = fs.nextInt();
System.out.flush();
return inx;
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
eb660c470760117dfd0b95acc10eee3b
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,900
| null |
standard output
| |
PASSED
|
f4953807e72a6362f3f11471f9a9f0ed
|
train_109.jsonl
|
1613658900
|
The only difference between the easy and the hard version is the limit to the number of queries.This is an interactive problem.There is an array $$$a$$$ of $$$n$$$ different numbers. In one query you can ask the position of the second maximum element in a subsegment $$$a[l..r]$$$. Find the position of the maximum element in the array in no more than 20 queries.A subsegment $$$a[l..r]$$$ is all the elements $$$a_l, a_{l + 1}, ..., a_r$$$. After asking this subsegment you will be given the position of the second maximum from this subsegment in the whole array.
|
256 megabytes
|
import java.util.*;
import java.io.*;
import java.math.*;
import java.awt.geom.*;
import static java.lang.Math.*;
public class Solution implements Runnable {
long mod1 = (long) 1e9 + 7;
int mod2 = 998244353;
public void solve() throws Exception {
int n=sc.nextInt();
int start=1;
int end=n;
boolean right=false,left=false;
int smx=query(start, end);
if(smx==1) {
right=true;
}
else if(smx==n) left=true;
else if(query(smx,end)==smx) {
right=true;
}
else left=true;
if(right) {
start=smx;
end=n;
boolean flag=false;
int min=n;
while(start<end) {
int mid=(start+end)/2;
if(end-start==1) {
int q1=0;
if(smx<start) {
q1=query(smx,start);
}
if(q1==smx) {
min=Math.min(min, start);
}
min=Math.min(min, end);
break;
}
if(query(smx,mid)==smx) {
min=mid;
end=mid;
}
else {
start=mid;
}
}
print(min);
}
else {
start=1;
end=smx;
boolean flag=false;
int min=1;
while(start<end) {
int mid=(start+end)/2;
if(end-start==1) {
int q1=0;
if(smx<start) {
q1=query(end,smx);
}
if(q1==smx) {
min=Math.max(min, end);
}
min=Math.max(min, start);
break;
}
if(query(mid,smx)==smx) {
min=mid;
start=mid;
}
else {
end=mid;
}
}
print(min);
}
}
public void print(int x) {
System.out.println("! "+x);
System.out.flush();
}
public int query(int l,int r) throws Exception{
System.out.print("? "+l+" "+r);
System.out.println();
System.out.flush();
int x=sc.nextInt();
return x;
}
static long gcd(long a, long b) {
if (a == 0)
return b;
return gcd(b % a, a);
}
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 long ncr(int n, int r, long p) {
if (r > n)
return 0l;
if (r > n - r)
r = n - r;
long C[] = new long[r + 1];
C[0] = 1;
for (int i = 1; i <= n; i++) {
for (int j = Math.min(i, r); j > 0; j--)
C[j] = (C[j] + C[j - 1]) % p;
}
return C[r] % p;
}
void sieveOfEratosthenes(boolean prime[], int size) {
for (int i = 0; i < size; i++)
prime[i] = true;
for (int p = 2; p * p < size; p++) {
if (prime[p] == true) {
for (int i = p * p; i < size; i += p)
prime[i] = false;
}
}
}
static int LowerBound(int a[], int x) { // smallest index having value >= 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) {// biggest index having value <= x
int l = -1, r = a.length;
while (l + 1 < r) {
int m = (l + r) >>> 1;
if (a[m] <= x)
l = m;
else
r = m;
}
return l + 1;
}
public long power(long x, long y, long p) {
long res = 1;
// out.println(x+" "+y);
x = x % p;
if (x == 0)
return 0;
while (y > 0) {
if ((y & 1) == 1)
res = (res * x) % p;
y = y >> 1;
x = (x * x) % p;
}
return res;
}
static Throwable uncaught;
BufferedReader in;
FastScanner sc;
PrintWriter out;
@Override
public void run() {
try {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
sc = new FastScanner(in);
solve();
} catch (Throwable uncaught) {
Solution.uncaught = uncaught;
} finally {
out.close();
}
}
public static void main(String[] args) throws Throwable {
Thread thread = new Thread(null, new Solution(), "", (1 << 26));
thread.start();
thread.join();
if (Solution.uncaught != null) {
throw Solution.uncaught;
}
}
}
class FastScanner {
BufferedReader in;
StringTokenizer st;
public FastScanner(BufferedReader in) {
this.in = in;
}
public String nextToken() throws Exception {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(in.readLine());
}
return st.nextToken();
}
public int nextInt() throws Exception {
return Integer.parseInt(nextToken());
}
public int[] readArray(int n) throws Exception {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
public long nextLong() throws Exception {
return Long.parseLong(nextToken());
}
public double nextDouble() throws Exception {
return Double.parseDouble(nextToken());
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
eb660c470760117dfd0b95acc10eee3b
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,900
| null |
standard output
| |
PASSED
|
62163abea677b58aa629533d9f04512f
|
train_109.jsonl
|
1613658900
|
The only difference between the easy and the hard version is the limit to the number of queries.This is an interactive problem.There is an array $$$a$$$ of $$$n$$$ different numbers. In one query you can ask the position of the second maximum element in a subsegment $$$a[l..r]$$$. Find the position of the maximum element in the array in no more than 20 queries.A subsegment $$$a[l..r]$$$ is all the elements $$$a_l, a_{l + 1}, ..., a_r$$$. After asking this subsegment you will be given the position of the second maximum from this subsegment in the whole array.
|
256 megabytes
|
import java.util.*;
import java.io.*;
import java.math.*;
import java.awt.geom.*;
import static java.lang.Math.*;
public class Solution implements Runnable {
long mod1 = (long) 1e9 + 7;
int mod2 = 998244353;
public void solve() throws Exception {
int n=sc.nextInt();
int start=1;
int end=n;
boolean right=false,left=false;
int smx=query(start, end);
if(smx==1) {
right=true;
}
else if(smx==n) left=true;
else if(query(smx,end)==smx) {
right=true;
}
else left=true;
if(right) {
start=smx;
end=n;
boolean flag=false;
int min=n;
while(start+1<end) {
int mid=(start+end)/2;
if(end-start==1) {
min=Math.min(min, end);
break;
}
if(query(smx,mid)==smx) {
min=mid;
end=mid;
}
else {
start=mid;
}
}
print(min);
}
else {
start=1;
end=smx;
boolean flag=false;
int min=1;
while(start<end) {
int mid=(start+end)/2;
if(end-start==1) {
min=Math.max(min, start);
break;
}
if(query(mid,smx)==smx) {
min=mid;
start=mid;
}
else {
end=mid;
}
}
print(min);
}
}
public void print(int x) {
System.out.println("! "+x);
System.out.flush();
}
public int query(int l,int r) throws Exception{
System.out.print("? "+l+" "+r);
System.out.println();
System.out.flush();
int x=sc.nextInt();
return x;
}
static long gcd(long a, long b) {
if (a == 0)
return b;
return gcd(b % a, a);
}
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 long ncr(int n, int r, long p) {
if (r > n)
return 0l;
if (r > n - r)
r = n - r;
long C[] = new long[r + 1];
C[0] = 1;
for (int i = 1; i <= n; i++) {
for (int j = Math.min(i, r); j > 0; j--)
C[j] = (C[j] + C[j - 1]) % p;
}
return C[r] % p;
}
void sieveOfEratosthenes(boolean prime[], int size) {
for (int i = 0; i < size; i++)
prime[i] = true;
for (int p = 2; p * p < size; p++) {
if (prime[p] == true) {
for (int i = p * p; i < size; i += p)
prime[i] = false;
}
}
}
static int LowerBound(int a[], int x) { // smallest index having value >= 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) {// biggest index having value <= x
int l = -1, r = a.length;
while (l + 1 < r) {
int m = (l + r) >>> 1;
if (a[m] <= x)
l = m;
else
r = m;
}
return l + 1;
}
public long power(long x, long y, long p) {
long res = 1;
// out.println(x+" "+y);
x = x % p;
if (x == 0)
return 0;
while (y > 0) {
if ((y & 1) == 1)
res = (res * x) % p;
y = y >> 1;
x = (x * x) % p;
}
return res;
}
static Throwable uncaught;
BufferedReader in;
FastScanner sc;
PrintWriter out;
@Override
public void run() {
try {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
sc = new FastScanner(in);
solve();
} catch (Throwable uncaught) {
Solution.uncaught = uncaught;
} finally {
out.close();
}
}
public static void main(String[] args) throws Throwable {
Thread thread = new Thread(null, new Solution(), "", (1 << 26));
thread.start();
thread.join();
if (Solution.uncaught != null) {
throw Solution.uncaught;
}
}
}
class FastScanner {
BufferedReader in;
StringTokenizer st;
public FastScanner(BufferedReader in) {
this.in = in;
}
public String nextToken() throws Exception {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(in.readLine());
}
return st.nextToken();
}
public int nextInt() throws Exception {
return Integer.parseInt(nextToken());
}
public int[] readArray(int n) throws Exception {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
public long nextLong() throws Exception {
return Long.parseLong(nextToken());
}
public double nextDouble() throws Exception {
return Double.parseDouble(nextToken());
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
eb660c470760117dfd0b95acc10eee3b
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,900
| null |
standard output
| |
PASSED
|
1c0685ee7841dd9aa69b983e753bdcb7
|
train_109.jsonl
|
1613658900
|
The only difference between the easy and the hard version is the limit to the number of queries.This is an interactive problem.There is an array $$$a$$$ of $$$n$$$ different numbers. In one query you can ask the position of the second maximum element in a subsegment $$$a[l..r]$$$. Find the position of the maximum element in the array in no more than 20 queries.A subsegment $$$a[l..r]$$$ is all the elements $$$a_l, a_{l + 1}, ..., a_r$$$. After asking this subsegment you will be given the position of the second maximum from this subsegment in the whole array.
|
256 megabytes
|
import java.util.*;
import java.io.*;
import java.math.*;
import java.awt.geom.*;
import static java.lang.Math.*;
public class Solution implements Runnable {
long mod1 = (long) 1e9 + 7;
int mod2 = 998244353;
public void solve() throws Exception {
int n=sc.nextInt();
int start=1;
int end=n;
boolean right=false,left=false;
int smx=query(start, end);
if(smx==1) {
right=true;
}
else if(smx==n) left=true;
else if(query(smx,end)==smx) {
right=true;
}
else left=true;
if(right) {
start=smx;
end=n;
boolean flag=false;
int min=n;
while(start+1<end) {
int mid=(start+end)/2;
if(query(smx,mid)==smx) {
min=mid;
end=mid;
}
else {
start=mid;
}
}
print(min);
}
else {
start=1;
end=smx;
boolean flag=false;
int min=1;
while(start+1<end) {
int mid=(start+end)/2;
if(query(mid,smx)==smx) {
min=mid;
start=mid;
}
else {
end=mid;
}
}
print(min);
}
}
public void print(int x) {
System.out.println("! "+x);
System.out.flush();
}
public int query(int l,int r) throws Exception{
System.out.print("? "+l+" "+r);
System.out.println();
System.out.flush();
int x=sc.nextInt();
return x;
}
static long gcd(long a, long b) {
if (a == 0)
return b;
return gcd(b % a, a);
}
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 long ncr(int n, int r, long p) {
if (r > n)
return 0l;
if (r > n - r)
r = n - r;
long C[] = new long[r + 1];
C[0] = 1;
for (int i = 1; i <= n; i++) {
for (int j = Math.min(i, r); j > 0; j--)
C[j] = (C[j] + C[j - 1]) % p;
}
return C[r] % p;
}
void sieveOfEratosthenes(boolean prime[], int size) {
for (int i = 0; i < size; i++)
prime[i] = true;
for (int p = 2; p * p < size; p++) {
if (prime[p] == true) {
for (int i = p * p; i < size; i += p)
prime[i] = false;
}
}
}
static int LowerBound(int a[], int x) { // smallest index having value >= 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) {// biggest index having value <= x
int l = -1, r = a.length;
while (l + 1 < r) {
int m = (l + r) >>> 1;
if (a[m] <= x)
l = m;
else
r = m;
}
return l + 1;
}
public long power(long x, long y, long p) {
long res = 1;
// out.println(x+" "+y);
x = x % p;
if (x == 0)
return 0;
while (y > 0) {
if ((y & 1) == 1)
res = (res * x) % p;
y = y >> 1;
x = (x * x) % p;
}
return res;
}
static Throwable uncaught;
BufferedReader in;
FastScanner sc;
PrintWriter out;
@Override
public void run() {
try {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
sc = new FastScanner(in);
solve();
} catch (Throwable uncaught) {
Solution.uncaught = uncaught;
} finally {
out.close();
}
}
public static void main(String[] args) throws Throwable {
Thread thread = new Thread(null, new Solution(), "", (1 << 26));
thread.start();
thread.join();
if (Solution.uncaught != null) {
throw Solution.uncaught;
}
}
}
class FastScanner {
BufferedReader in;
StringTokenizer st;
public FastScanner(BufferedReader in) {
this.in = in;
}
public String nextToken() throws Exception {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(in.readLine());
}
return st.nextToken();
}
public int nextInt() throws Exception {
return Integer.parseInt(nextToken());
}
public int[] readArray(int n) throws Exception {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
public long nextLong() throws Exception {
return Long.parseLong(nextToken());
}
public double nextDouble() throws Exception {
return Double.parseDouble(nextToken());
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
eb660c470760117dfd0b95acc10eee3b
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,900
| null |
standard output
| |
PASSED
|
1ef7ff5d0062050777f1c642dfa9c41e
|
train_109.jsonl
|
1613658900
|
The only difference between the easy and the hard version is the limit to the number of queries.This is an interactive problem.There is an array $$$a$$$ of $$$n$$$ different numbers. In one query you can ask the position of the second maximum element in a subsegment $$$a[l..r]$$$. Find the position of the maximum element in the array in no more than 20 queries.A subsegment $$$a[l..r]$$$ is all the elements $$$a_l, a_{l + 1}, ..., a_r$$$. After asking this subsegment you will be given the position of the second maximum from this subsegment in the whole array.
|
256 megabytes
|
import java.io.*;
import java.util.InputMismatchException;
/**
* Created by Wilson on
* Feb. 08, 2021
*/
public class HardMaxelementInteractive {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
CSearchingLocalMinimum solver = new CSearchingLocalMinimum();
solver.solve(in, out);
out.close();
}
static class CSearchingLocalMinimum {
OutputWriter out;
InputReader in;
int query(int l,int r) {
out.printLine("?", l,r);
out.flush();
return in.readInt();
}
void writeOutput(int ans) {
out.printLine("!", ans);
out.flush();
}
public void solve(InputReader in, OutputWriter out) {
this.out = out;
this.in = in;
int n = in.readInt();
if (n == 1) {
writeOutput(1);
return;
}
//The idea here is to use the first divide the array into 2 halfs
//and checks which side of the array as the biggest element
//1)if first side has it, query b/w mid and smax always changing l and
//r, get the middle of l and r and then query for second largest b/w middle and smax(which is to the right)
//since l side always gets mid whenever new query is equal to smax, then we return the
//r whenever r-l <= 1
//2) if the second side has the biggest, always query between mid and smax (which is to left end of the
// first accepted part)
//here, r side always gets the mid whenever new query (mid, smax) returns value equal to smax
//then we return l whenever r - l <= 1
int l,r,smax,mid,ans;
smax = query(1, n);
if (smax == 1 || query(1, smax) != smax) {
l = smax; r = n;
while (r - l > 1) {
int m = (l + r) / 2;
if (query(smax, m) == smax) {
r = m;
} else {
l = m;
}
}
writeOutput(r);
} else {
l = 1; r = smax;
while (r - l > 1) {
int m = (l + r) / 2;
if (query(m, smax) == smax) {
l = m;
} else {
r = m;
}
}
writeOutput(l);
}
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void printLine(Object... objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
public void flush() {
writer.flush();
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private 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 readInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
eb660c470760117dfd0b95acc10eee3b
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,900
| null |
standard output
| |
PASSED
|
f3d243d60829e52d93f113d7de13f0b6
|
train_109.jsonl
|
1613658900
|
The only difference between the easy and the hard version is the limit to the number of queries.This is an interactive problem.There is an array $$$a$$$ of $$$n$$$ different numbers. In one query you can ask the position of the second maximum element in a subsegment $$$a[l..r]$$$. Find the position of the maximum element in the array in no more than 20 queries.A subsegment $$$a[l..r]$$$ is all the elements $$$a_l, a_{l + 1}, ..., a_r$$$. After asking this subsegment you will be given the position of the second maximum from this subsegment in the whole array.
|
256 megabytes
|
import java.io.*;
import java.util.InputMismatchException;
/**
* Created by Wilson on
* Feb. 08, 2021
*/
public class HardMaxelementInteractive {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
CSearchingLocalMinimum solver = new CSearchingLocalMinimum();
solver.solve(in, out);
out.close();
}
static class CSearchingLocalMinimum {
OutputWriter out;
InputReader in;
int query(int l,int r) {
out.printLine("?", l+1,r+1);
out.flush();
return in.readInt()-1;
}
void writeOutput(int ans) {
out.printLine("!", ans);
out.flush();
}
public void solve(InputReader in, OutputWriter out) {
this.out = out;
this.in = in;
int n = in.readInt();
if (n == 1) {
writeOutput(1);
return;
}
//The idea here is to use the first divide the array into 2 halfs
//and checks which side of the array as the biggest element
//1)if first side has it, query b/w mid and smax always changing l and
//r, get the middle of l and r and then query for second largest b/w middle and smax(which is to the right)
//since l side always gets mid whenever new query is equal to smax, then we return the
//r whenever r-l <= 1
//2) if the second side has the biggest, always query between mid and smax (which is to left end of the
// first accepted part)
//here, r side always gets the mid whenever new query (mid, smax) returns value equal to smax
//then we return l whenever r - l <= 1
int l,r,smax,mid,ans;
l =1;
r = n;
smax = query(0, n - 1);
if (smax == 0 || query(0, smax) != smax) {
l = smax; r = n - 1;
while (r - l > 1) {
int m = (l + r) / 2;
if (query(smax, m) == smax) {
r = m;
} else {
l = m;
}
}
writeOutput(r+1);
} else {
l = 0; r = smax;
while (r - l > 1) {
int m = (l + r) / 2;
if (query(m, smax) == smax) {
l = m;
} else {
r = m;
}
}
writeOutput(l+1);
}
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void printLine(Object... objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
public void flush() {
writer.flush();
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private 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 readInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
eb660c470760117dfd0b95acc10eee3b
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,900
| null |
standard output
| |
PASSED
|
c7a3521fb17ae796920708b5b8e0de04
|
train_109.jsonl
|
1613658900
|
The only difference between the easy and the hard version is the limit to the number of queries.This is an interactive problem.There is an array $$$a$$$ of $$$n$$$ different numbers. In one query you can ask the position of the second maximum element in a subsegment $$$a[l..r]$$$. Find the position of the maximum element in the array in no more than 20 queries.A subsegment $$$a[l..r]$$$ is all the elements $$$a_l, a_{l + 1}, ..., a_r$$$. After asking this subsegment you will be given the position of the second maximum from this subsegment in the whole array.
|
256 megabytes
|
import java.io.*;
import java.util.*;
import java.util.ArrayList;
import java.util.Arrays.*;
import static java.util.Collections.*;
import static java.lang.Math.*;
import static java.util.Arrays.*;
public class cf {
static final int SCAN_LINE_LENGTH = 100002;
private static final boolean thread = false;
@SuppressWarnings("all")
static final boolean HAS_TEST_CASES = (1 == 0) ? true : false;
static int n, a[], e[][], vis[], m, b[];
@SuppressWarnings("all")
private static Vector<Integer> adj[], v = new Vector<>();
@SuppressWarnings("unchecked")
static void solve() throws Exception {
n = ni();
int a = -1, l = 1, r = n, m;
m = get(l, r);
if (m != l && m == get(l, m)) {
r = m - 1;
a = r;
while (l <= r) {
int mid = (l + 1 + r) / 2;
if (r - l == 1) {
a = (get(l, r) == l) ? r : l;
break;
}
if (get(mid, m) == m) {
a = mid;
l = mid + 1;
} else
r = mid - 1;
}
} else {
l = m + 1;
a = l;
while (l <= r) {
int mid = (l + r) / 2;
if (r - l == 1) {
a = (get(l, r) == l) ? r : l;
break;
}
if (get(m, mid) == m) {
a = mid;
r = mid - 1;
} else
l = mid + 1;
}
}
pni("! " + a);
}
private static int get(int l, int r) throws IOException {
int m;
if (l >= r)
return -1;
pni("? " + l + " " + r);
m = ni();
return m;
}
public static void main(final String[] args) throws Exception {
if (!thread) {
final int testcases = HAS_TEST_CASES ? ni() : 1;
for (int i = 1; i <= testcases; i++) {
// pni(i + " t");
// out.print("Case #" + (i + 1) + ": ");
try {
solve();
} catch (final Exception e) {
// pni("idk Exception");
// e.printStackTrace(System.err);
// System.exit(0);
pni(i);
throw e;
}
}
out.flush();
}
r.close();
out.close();
}
@SuppressWarnings("all")
private static final int MOD = (int) (1e9 + 7), MOD_FFT = 998244353;
private static final Reader r = new Reader();
private static final PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
public static long[] enumPows(int a, int n, int mod) {
a %= mod;
long[] pows = new long[n + 1];
pows[0] = 1;
for (int i = 1; i <= n; i++)
pows[i] = pows[i - 1] * a % mod;
return pows;
}
@SuppressWarnings("all")
private static boolean eq(long a, long b) {
return Long.compare(a, b) == 0;
}
@SuppressWarnings("all")
private static ArrayList<Integer> seive(int n) {
ArrayList<Integer> p = new ArrayList<>();
int[] f = new int[n + 1];
for (int i = 2; i <= n; i++) {
if (f[i] == 1)
continue;
for (int j = i * i; j <= n && j < f.length; j += i) {
f[j] = 1;
}
}
for (int i = 2; i < f.length; i++) {
if (f[i] == 0)
p.add(i);
}
return p;
}
@SuppressWarnings("all")
private static void s(int[] a) {
Integer[] t = new Integer[a.length];
for (int i = 0; i < t.length; i++) {
t[i] = a[i];
}
sort(t);
for (int i = 0; i < t.length; i++) {
a[i] = t[i];
}
}
int pow(int a, int b, int m) {
int ans = 1;
while (b != 0) {
if ((b & 1) != 0)
ans = (ans * a) % m;
b /= 2;
a = (a * a) % m;
}
return ans;
}
int modinv(int k) {
return pow(k, MOD - 2, MOD);
}
@SuppressWarnings("all")
private static void swap(final int i, final int j) {
final int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
@SuppressWarnings("all")
private static boolean isMulOverflow(final long A, final long B) {
if (A == 0 || B == 0)
return false;
final long result = A * B;
if (A == result / B)
return true;
return false;
}
@SuppressWarnings("all")
private static int gcd(final int a, final int b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
@SuppressWarnings("all")
private static long gcd(final long a, final long b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
@SuppressWarnings("all")
private static class Pair<T, E> implements Comparable<Pair<T, E>> {
T fir;
E snd;
Pair() {
}
Pair(final T x, final E y) {
this.fir = x;
this.snd = y;
}
// @Override
// @SuppressWarnings("unchecked")
// public int compareTo(final Pair<T, E> o) {
// final int c = ((Comparable<T>) fir).compareTo(o.fir);
// return c != 0 ? c : ((Comparable<E>) snd).compareTo(o.snd);
// }
@Override
@SuppressWarnings("unchecked")
public int compareTo(final Pair<T, E> o) {
final int c = ((Comparable<T>) fir).compareTo(o.fir);
return c;
}
}
@SuppressWarnings("all")
private static class pi implements Comparable<pi> {
int fir, snd;
pi() {
}
pi(final int a, final int b) {
fir = a;
snd = b;
}
public int compareTo(final pi o) {
return fir == o.fir ? snd - o.snd : fir - o.fir;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + fir;
result = prime * result + snd;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
pi other = (pi) obj;
if (fir != other.fir)
return false;
if (snd != other.snd)
return false;
return true;
}
}
@SuppressWarnings("all")
private static <T> void checkV(final Vector<T> adj[], final int i) {
adj[i] = adj[i] == null ? new Vector<>() : adj[i];
}
@SuppressWarnings("all")
private static int[] na(final int n) throws Exception {
final int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = ni();
}
return a;
}
@SuppressWarnings("all")
private static int[] na1(final int n) throws Exception {
final int[] a = new int[n + 1];
for (int i = 1; i < a.length; i++) {
a[i] = ni();
}
return a;
}
@SuppressWarnings("all")
private static String n() throws IOException {
return r.readToken();
}
@SuppressWarnings("all")
private static char[] ns() throws IOException {
return r.readToken().toCharArray();
}
@SuppressWarnings("all")
private static String nln() throws IOException {
return r.readLine();
}
private static int ni() throws IOException {
return r.nextInt();
}
@SuppressWarnings("all")
private static long nl() throws IOException {
return r.nextLong();
}
@SuppressWarnings("all")
private static double nd() throws IOException {
return r.nextDouble();
}
@SuppressWarnings("all")
private static void p(final Object o) {
out.print(o);
}
@SuppressWarnings("all")
private static void pn(final Object o) {
out.println(o);
}
@SuppressWarnings("all")
private static void pn() {
out.println("");
}
@SuppressWarnings("all")
private static void pi(final Object o) {
out.print(o);
out.flush();
}
@SuppressWarnings("all")
private static void pni() {
out.println("");
out.flush();
}
private static void pni(final Object o) {
out.println(o);
out.flush();
}
private static class Reader {
private final int BUFFER_SIZE = 1 << 17;
private final DataInputStream din;
private final byte[] buffer;
private int bufferPointer, bytesRead;
// private StringTokenizer st;
public Reader() {
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
@SuppressWarnings("all")
public Reader(final String file_name) throws IOException {
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
final byte[] buf = new byte[SCAN_LINE_LENGTH];
public String readLine() throws IOException {
int cnt = 0;
int c;
o: while ((c = read()) != -1) {
if (c == '\n')
if (cnt == 0)
continue o;
else
break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public String readToken() throws IOException {
int cnt = 0;
int c;
o: while ((c = read()) != -1) {
if (!(c >= 33 && c <= 126))
if (cnt == 0)
continue o;
else
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();
final boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException {
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
final boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException {
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
final boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (c == '.') {
while ((c = read()) >= '0' && c <= '9') {
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException {
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException {
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException {
if (din == null)
return;
din.close();
}
}
// static {
// if (thread)
// new Thread(null, new Runnable() {
// @Override
// public void run() {
// try {
// final int testcases = HAS_TEST_CASES ? ni() : 1;
// for (int i = 1; i <= testcases; i++) {
// // out.print("Case #" + (i + 1) + ": ");
// try {
// solve();
// } catch (final ArrayIndexOutOfBoundsException e) {
// e.printStackTrace(System.err);
// System.exit(-1);
// } catch (final Exception e) {
// pni("idk Exception in solve");
// e.printStackTrace(System.err);
// System.exit(-1);
// }
// }
// out.flush();
// } catch (final Throwable t) {
// t.printStackTrace(System.err);
// System.exit(-1);
// }
// }
// }, "rec", (1L << 28)).start();
// }
@SuppressWarnings({ "all", })
private static <T> T deepCopy(final T old) {
try {
return (T) deepCopyObject(old);
} catch (final IOException | ClassNotFoundException e) {
e.printStackTrace(System.err);
System.exit(-1);
}
return null;
}
private static Object deepCopyObject(final Object oldObj) throws IOException, ClassNotFoundException {
ObjectOutputStream oos = null;
ObjectInputStream ois = null;
try {
final ByteArrayOutputStream bos = new ByteArrayOutputStream(); // A
oos = new ObjectOutputStream(bos); // B
// serialize and pass the object
oos.writeObject(oldObj); // C
oos.flush(); // D
final ByteArrayInputStream bin = new ByteArrayInputStream(bos.toByteArray()); // E
ois = new ObjectInputStream(bin); // F
// return the new object
return ois.readObject(); // G
} catch (final ClassNotFoundException e) {
pni("Exception in ObjectCloner = " + e);
throw (e);
} finally {
oos.close();
ois.close();
}
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
eb660c470760117dfd0b95acc10eee3b
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,900
| null |
standard output
| |
PASSED
|
bd083abd3cc55978ef6d25985841a286
|
train_109.jsonl
|
1613658900
|
The only difference between the easy and the hard version is the limit to the number of queries.This is an interactive problem.There is an array $$$a$$$ of $$$n$$$ different numbers. In one query you can ask the position of the second maximum element in a subsegment $$$a[l..r]$$$. Find the position of the maximum element in the array in no more than 20 queries.A subsegment $$$a[l..r]$$$ is all the elements $$$a_l, a_{l + 1}, ..., a_r$$$. After asking this subsegment you will be given the position of the second maximum from this subsegment in the whole array.
|
256 megabytes
|
import java.io.*;
import java.util.*;
public class D {
static class pair implements Comparable<pair> {
int f;
int s;
double th;
int id;
public pair() {
}
public pair(int a, int b, int c) {
f = a;
s = b;
th = (f * 1.00000) / (s * 1.00000);
id = c;
}
@Override
public int compareTo(pair o) {
// TODO Auto-generated method stub
if (this.th > o.th)
return -1;
if (this.th == o.th) {
return this.s - o.s;
} else
return 1;
}
}
static int mod = (int) 1e9 + 7;
static int ar[];
static Scanner sc = new Scanner(System.in);
static StringBuilder out = new StringBuilder();
static ArrayList<Integer> grEven[];
static ArrayList<Integer> grOdd[];
static void sort(int a[], int n) {
ArrayList<Integer> al = new ArrayList<>();
for (int i = 0; i < n; i++) {
al.add(a[i]);
}
Collections.sort(al);
for (int i = 0; i < n; i++) {
a[i] = al.get(i);
}
}
static void in(int a[], int n) throws IOException {
for (int i = 0; i < n; i++)
a[i] = sc.nextInt();
}
public static void main(String[] args) throws IOException {
int t = 1;// sc.nextInt();
while (t-- > 0) {
int n = sc.nextInt();
int l = 1;
int r = n;
int ans = 0;
System.out.println("? " + l + " " + r);
System.out.flush();
int max = sc.nextInt();
if (n == 2) {
if (max == 1)
System.out.println("! " + 2);
else
System.out.println("! " + 1);
continue;
}
if (max == 1) {
l = max + 1;
} else if (max == r) {
r = max - 1;
} else {
System.out.println("? " + l + " " + max);
System.out.flush();
if (sc.nextInt() == max) {
r = max - 1;
} else {
l = max + 1;
}
}
int cnt = 2;
if (max == l - 1) {
cnt++;
while (l <= r) {
cnt++;
int mid = (l + r) / 2;
System.out.println("? " + max + " " + mid);
System.out.flush();
int m1 = sc.nextInt();
if (m1 == max) {
r = mid - 1;
ans = mid;
} else {
l = mid + 1;
}
}
} else {
cnt++;
while (l <= r) {
int mid = (l + r) / 2;
System.out.println("? " + mid + " " + max);
System.out.flush();
int m1 = sc.nextInt();
if (m1 == max) {
l = mid + 1;
ans = mid;
} else {
r = mid - 1;
}
}
}
System.out.println("! " + ans);
}
System.out.println(out);
}
// static Reader sc=new Reader();
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();
}
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
eb660c470760117dfd0b95acc10eee3b
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,900
| null |
standard output
| |
PASSED
|
578ffe72772b0bc07ad3decea248b234
|
train_109.jsonl
|
1613658900
|
The only difference between the easy and the hard version is the limit to the number of queries.This is an interactive problem.There is an array $$$a$$$ of $$$n$$$ different numbers. In one query you can ask the position of the second maximum element in a subsegment $$$a[l..r]$$$. Find the position of the maximum element in the array in no more than 20 queries.A subsegment $$$a[l..r]$$$ is all the elements $$$a_l, a_{l + 1}, ..., a_r$$$. After asking this subsegment you will be given the position of the second maximum from this subsegment in the whole array.
|
256 megabytes
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.BufferedReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
C2GuessingTheGreatestHardVersion solver = new C2GuessingTheGreatestHardVersion();
solver.solve(1, in, out);
out.close();
}
static class C2GuessingTheGreatestHardVersion {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.nextInt();
int smax = q(0, n - 1, in);
int ans = 0;
if (smax > 0 && q(0, smax, in) == smax) {
int lo = 0, hi = smax - 1;
ans = lo;
while (lo <= hi) {
int mid = (lo + hi) / 2;
if (q(mid, smax, in) == smax) {
ans = mid;
lo = mid + 1;
} else {
hi = mid - 1;
}
}
} else {
int lo = smax + 1;
int hi = n - 1;
ans = hi;
while (lo <= hi) {
int mid = (lo + hi) / 2;
if (q(smax, mid, in) != smax) {
lo = mid + 1;
} else {
ans = mid;
hi = mid - 1;
}
}
}
System.out.println("! " + (ans + 1));
}
int q(int l, int r, InputReader in) {
System.out.println("? " + (l + 1) + " " + (r + 1));
return in.nextInt() - 1;
}
}
static class InputReader {
BufferedReader reader;
StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void close() {
writer.close();
}
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
eb660c470760117dfd0b95acc10eee3b
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,900
| null |
standard output
| |
PASSED
|
18d24cf15a7c7c9657eb8278c9b3f6f1
|
train_109.jsonl
|
1613658900
|
The only difference between the easy and the hard version is the limit to the number of queries.This is an interactive problem.There is an array $$$a$$$ of $$$n$$$ different numbers. In one query you can ask the position of the second maximum element in a subsegment $$$a[l..r]$$$. Find the position of the maximum element in the array in no more than 20 queries.A subsegment $$$a[l..r]$$$ is all the elements $$$a_l, a_{l + 1}, ..., a_r$$$. After asking this subsegment you will be given the position of the second maximum from this subsegment in the whole array.
|
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 Template {
public static void main(String[] args) throws Exception{
BufferedReader infile = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(infile.readLine());
int N = Integer.parseInt(st.nextToken());
System.out.println("? 1 " + N);
System.out.flush();
int secondLarge = Integer.parseInt(infile.readLine());
int ans = 0;
if(secondLarge > 1) {
// check left then
System.out.println("? 1 " + secondLarge);
System.out.flush();
int index = Integer.parseInt(infile.readLine());
if(index == secondLarge) {
// definitely we check left one
int start = 1;
int end = secondLarge- 1;
while(start < end) {
int mid = (start+end+1)/2;
System.out.println("? " + mid + " " + secondLarge);
System.out.flush();
index = Integer.parseInt(infile.readLine());
if(index == secondLarge) {
start = mid;
}
else {
end = mid-1;
}
}
ans = start;
}
}
if(ans == 0 && secondLarge < N) {
// then go for right
int start = secondLarge+1;
int end = N;
while(start < end) {
int mid = (start+end)/2;
System.out.println("? " + secondLarge + " " + mid);
System.out.flush();
int index = Integer.parseInt(infile.readLine());
if(index == secondLarge) {
end = mid;
}
else {
start = mid+1;
}
}
ans = start;
}
System.out.println("! " + ans);
System.out.flush();
}
public static int[] readArr(int N, BufferedReader infile, StringTokenizer st) throws Exception
{
int[] arr = new int[N];
st = new StringTokenizer(infile.readLine());
for(int i=0; i < N; i++)
arr[i] = Integer.parseInt(st.nextToken());
return arr;
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
eb660c470760117dfd0b95acc10eee3b
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,900
| null |
standard output
| |
PASSED
|
cc04fde564a68607817d3d9398fd6239
|
train_109.jsonl
|
1613658900
|
The only difference between the easy and the hard version is the limit to the number of queries.This is an interactive problem.There is an array $$$a$$$ of $$$n$$$ different numbers. In one query you can ask the position of the second maximum element in a subsegment $$$a[l..r]$$$. Find the position of the maximum element in the array in no more than 20 queries.A subsegment $$$a[l..r]$$$ is all the elements $$$a_l, a_{l + 1}, ..., a_r$$$. After asking this subsegment you will be given the position of the second maximum from this subsegment in the whole array.
|
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 Template {
public static void main(String[] args) throws Exception{
BufferedReader infile = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(infile.readLine());
int N = Integer.parseInt(st.nextToken());
System.out.println("? 1 " + N);
System.out.flush();
int middle = Integer.parseInt(infile.readLine());
int res = 0;
// check on left
if(middle > 1) {
System.out.println("? 1 " + middle);
System.out.flush();
int index = Integer.parseInt(infile.readLine());
if(index == middle) {
int start = 1;
int end = middle-1;
while(start != end) {
int mid = (start+end+1)/2;
System.out.println("? " + mid + " " + middle);
System.out.flush();
index = Integer.parseInt(infile.readLine());
if(index == middle) {
start = mid;
}
else {
end = mid-1;
}
}
res = start;
}
}
// otherwise check on right
if(res == 0 && middle < N) {
int start = middle+1;
int end = N;
while(start != end) {
int mid = (start+end)/2;
System.out.println("? " + middle + " " + mid);
System.out.flush();
int index = Integer.parseInt(infile.readLine());
if(index == middle) {
end = mid;
}
else {
start = mid+1;
}
}
res = start;
}
System.out.println("! " + res);
System.out.flush();
}
public static int[] readArr(int N, BufferedReader infile, StringTokenizer st) throws Exception
{
int[] arr = new int[N];
st = new StringTokenizer(infile.readLine());
for(int i=0; i < N; i++)
arr[i] = Integer.parseInt(st.nextToken());
return arr;
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
eb660c470760117dfd0b95acc10eee3b
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,900
| null |
standard output
| |
PASSED
|
31dda17ff565bc6bde6c603fb7e38deb
|
train_109.jsonl
|
1613658900
|
The only difference between the easy and the hard version is the limit to the number of queries.This is an interactive problem.There is an array $$$a$$$ of $$$n$$$ different numbers. In one query you can ask the position of the second maximum element in a subsegment $$$a[l..r]$$$. Find the position of the maximum element in the array in no more than 20 queries.A subsegment $$$a[l..r]$$$ is all the elements $$$a_l, a_{l + 1}, ..., a_r$$$. After asking this subsegment you will be given the position of the second maximum from this subsegment in the whole array.
|
256 megabytes
|
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.util.Arrays;
import java.util.Random;
import java.io.FileWriter;
import java.io.PrintWriter;
/*
Solution Created: 19:43:18 18/02/2021
Custom Competitive programming helper.
*/
public class Main {
public static void solve() {
int n = in.nextInt();
int second = ask(1, n);
boolean left = second!=1 && (ask(1,second)==second);
int ans;
if(left){
int l = 1, r = second-1;
ans = second-1;
while(l<=r){
int md = (l+r)/2;
if(ask(md, second)==second){
ans = md;
l = md+1;
}else r = md-1;
}
}else{
int l = second+1, r = n;
ans = second+1;
while(l<=r){
int md = (l+r)/2;
if(ask(second, md)==second){
ans = md;
r = md-1;
}else l = md+1;
}
}
found(ans);
}
static int ask(int l, int r){
out.println("? "+l+" "+r);
out.flush();
return in.nextInt();
}
static void found(int i){
out.println("! "+i);
out.flush();
}
public static void main(String[] args) {
in = new Reader();
out = new Writer();
int t = 1;
while(t-->0) solve();
out.exit();
}
static Reader in; static Writer out;
static class Reader {
static BufferedReader br;
static StringTokenizer st;
public Reader() {
this.br = new BufferedReader(new InputStreamReader(System.in));
}
public Reader(String f){
try {
this.br = new BufferedReader(new FileReader(f));
} catch (IOException e) {
e.printStackTrace();
}
}
public int[] na(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = nextInt();
return a;
}
public double[] nd(int n) {
double[] a = new double[n];
for (int i = 0; i < n; i++) a[i] = nextDouble();
return a;
}
public long[] nl(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++) a[i] = nextLong();
return a;
}
public char[] nca() {
return next().toCharArray();
}
public String[] ns(int n) {
String[] a = new String[n];
for (int i = 0; i < n; i++) a[i] = next();
return a;
}
public int nextInt() {
ensureNext();
return Integer.parseInt(st.nextToken());
}
public double nextDouble() {
ensureNext();
return Double.parseDouble(st.nextToken());
}
public Long nextLong() {
ensureNext();
return Long.parseLong(st.nextToken());
}
public String next() {
ensureNext();
return st.nextToken();
}
public String nextLine() {
try {
return br.readLine();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
private void ensureNext() {
if (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
static class Util{
private static Random random = new Random();
static long[] fact;
public static void initFactorial(int n, long mod) {
fact = new long[n+1];
fact[0] = 1;
for (int i = 1; i < n+1; i++) fact[i] = (fact[i - 1] * i) % mod;
}
public static long modInverse(long a, long MOD) {
long[] gcdE = gcdExtended(a, MOD);
if (gcdE[0] != 1) return -1; // Inverted doesn't exist
long x = gcdE[1];
return (x % MOD + MOD) % MOD;
}
public static long[] gcdExtended(long p, long q) {
if (q == 0) return new long[] { p, 1, 0 };
long[] vals = gcdExtended(q, p % q);
long tmp = vals[2];
vals[2] = vals[1] - (p / q) * vals[2];
vals[1] = tmp;
return vals;
}
public static long nCr(int n, int r, long MOD) {
if (r == 0) return 1;
return (fact[n] * modInverse(fact[r], MOD) % MOD * modInverse(fact[n - r], MOD) % MOD) % MOD;
}
public static long nCr(int n, int r) {
return (fact[n]/fact[r])/fact[n-r];
}
public static long nPr(int n, int r, long MOD) {
if (r == 0) return 1;
return (fact[n] * modInverse(fact[n - r], MOD) % MOD) % MOD;
}
public static long nPr(int n, int r) {
return fact[n]/fact[n-r];
}
public static boolean isPrime(int n) {
if (n <= 1) return false;
if (n <= 3) return true;
if (n % 2 == 0 || n % 3 == 0) return false;
for (int i = 5; i * i <= n; i = i + 6)
if (n % i == 0 || n % (i + 2) == 0)
return false;
return true;
}
public static boolean[] getSieve(int n) {
boolean[] isPrime = new boolean[n+1];
for (int i = 2; i <= n; i++) isPrime[i] = true;
for (int i = 2; i*i <= n; i++) if (isPrime[i])
for (int j = i; i*j <= n; j++) isPrime[i*j] = false;
return isPrime;
}
public static int gcd(int a, int b) {
int tmp = 0;
while(b != 0) {
tmp = b;
b = a%b;
a = tmp;
}
return a;
}
public static long gcd(long a, long b) {
long tmp = 0;
while(b != 0) {
tmp = b;
b = a%b;
a = tmp;
}
return a;
}
public static int random(int min, int max) {
return random.nextInt(max-min+1)+min;
}
public static void dbg(Object... o) {
System.out.println(Arrays.deepToString(o));
}
public static void reverse(int[] s, int l , int r) {
for(int i = l; i<=(l+r)/2; i++) {
int tmp = s[i];
s[i] = s[r+l-i];
s[r+l-i] = tmp;
}
}
public static void reverse(int[] s) {
reverse(s, 0, s.length-1);
}
public static void reverse(long[] s, int l , int r) {
for(int i = l; i<=(l+r)/2; i++) {
long tmp = s[i];
s[i] = s[r+l-i];
s[r+l-i] = tmp;
}
}
public static void reverse(long[] s) {
reverse(s, 0, s.length-1);
}
public static void reverse(float[] s, int l , int r) {
for(int i = l; i<=(l+r)/2; i++) {
float tmp = s[i];
s[i] = s[r+l-i];
s[r+l-i] = tmp;
}
}
public static void reverse(float[] s) {
reverse(s, 0, s.length-1);
}
public static void reverse(double[] s, int l , int r) {
for(int i = l; i<=(l+r)/2; i++) {
double tmp = s[i];
s[i] = s[r+l-i];
s[r+l-i] = tmp;
}
}
public static void reverse(double[] s) {
reverse(s, 0, s.length-1);
}
public static void reverse(char[] s, int l , int r) {
for(int i = l; i<=(l+r)/2; i++) {
char tmp = s[i];
s[i] = s[r+l-i];
s[r+l-i] = tmp;
}
}
public static void reverse(char[] s) {
reverse(s, 0, s.length-1);
}
public static <T> void reverse(T[] s, int l , int r) {
for(int i = l; i<=(l+r)/2; i++) {
T tmp = s[i];
s[i] = s[r+l-i];
s[r+l-i] = tmp;
}
}
public static <T> void reverse(T[] s) {
reverse(s, 0, s.length-1);
}
public static void shuffle(int[] s) {
for (int i = 0; i < s.length; ++i) {
int j = random.nextInt(i + 1);
int t = s[i];
s[i] = s[j];
s[j] = t;
}
}
public static void shuffle(long[] s) {
for (int i = 0; i < s.length; ++i) {
int j = random.nextInt(i + 1);
long t = s[i];
s[i] = s[j];
s[j] = t;
}
}
public static void shuffle(float[] s) {
for (int i = 0; i < s.length; ++i) {
int j = random.nextInt(i + 1);
float t = s[i];
s[i] = s[j];
s[j] = t;
}
}
public static void shuffle(double[] s) {
for (int i = 0; i < s.length; ++i) {
int j = random.nextInt(i + 1);
double t = s[i];
s[i] = s[j];
s[j] = t;
}
}
public static void shuffle(char[] s) {
for (int i = 0; i < s.length; ++i) {
int j = random.nextInt(i + 1);
char t = s[i];
s[i] = s[j];
s[j] = t;
}
}
public static <T> void shuffle(T[] s) {
for (int i = 0; i < s.length; ++i) {
int j = random.nextInt(i + 1);
T t = s[i];
s[i] = s[j];
s[j] = t;
}
}
public static void sortArray(int[] a) {
shuffle(a);
Arrays.sort(a);
}
public static void sortArray(long[] a) {
shuffle(a);
Arrays.sort(a);
}
public static void sortArray(float[] a) {
shuffle(a);
Arrays.sort(a);
}
public static void sortArray(double[] a) {
shuffle(a);
Arrays.sort(a);
}
public static void sortArray(char[] a) {
shuffle(a);
Arrays.sort(a);
}
public static <T extends Comparable<T>> void sortArray(T[] a) {
Arrays.sort(a);
}
}
static class Writer {
private PrintWriter pw;
public Writer(){
pw = new PrintWriter(System.out);
}
public Writer(String f){
try {
pw = new PrintWriter(new FileWriter(f));
} catch (IOException e) {
e.printStackTrace();
}
}
public void printArray(int[] a) {
for(int i = 0; i<a.length; i++) print(a[i]+" ");
}
public void printlnArray(int[] a) {
for(int i = 0; i<a.length; i++) print(a[i]+" ");
pw.println();
}
public void printArray(long[] a) {
for(int i = 0; i<a.length; i++) print(a[i]+" ");
}
public void printlnArray(long[] a) {
for(int i = 0; i<a.length; i++) print(a[i]+" ");
pw.println();
}
public void print(Object o) {
pw.print(o.toString());
}
public void println(Object o) {
pw.println(o.toString());
}
public void println() {
pw.println();
}
public void flush() {
pw.flush();
}
public void exit() {
pw.close();
}
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
eb660c470760117dfd0b95acc10eee3b
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,900
| null |
standard output
| |
PASSED
|
626161a2cf0dbc556602229d4a8e92ee
|
train_109.jsonl
|
1613658900
|
The only difference between the easy and the hard version is the limit to the number of queries.This is an interactive problem.There is an array $$$a$$$ of $$$n$$$ different numbers. In one query you can ask the position of the second maximum element in a subsegment $$$a[l..r]$$$. Find the position of the maximum element in the array in no more than 20 queries.A subsegment $$$a[l..r]$$$ is all the elements $$$a_l, a_{l + 1}, ..., a_r$$$. After asking this subsegment you will be given the position of the second maximum from this subsegment in the whole array.
|
256 megabytes
|
import java.awt.*;
import java.io.*;
import java.util.*;
import java.util.List;
public class Hell {
public static void main(String[] args) throws Exception {
FastReader sc = new FastReader();
int n=sc.nextInt();
System.out.println("? 1 "+n);
System.out.flush();
int x=sc.nextInt();
boolean f=false;
if (x!=1) {
f=true;
System.out.println("? 1 " + x);
}
System.out.flush();
int newX=-1;
if (f) newX = sc.nextInt();
if (newX==x){
int l=1, r=x;
int ans=-1;
while (l<=r){
int m=(l+r)/2;
if (m==x){
System.out.println("! "+(m-1));
System.out.flush();
return;
}
System.out.println("? "+m+" "+x);
System.out.flush();
newX=sc.nextInt();
if (newX==x){
ans=m;
l=m+1;
}else {
r=m-1;
}
}
System.out.println("! "+(ans));
System.out.flush();
}else {
int r=n,l=x;
int ans=-1;
while (l<=r){
int m=(l+r)/2;
if (m==x){
System.out.println("! "+(m+1));
System.out.flush();
return;
}
System.out.println("? "+x+" "+m);
System.out.flush();
newX=sc.nextInt();
if (newX==x){
r=m-1;
}else {
l=m+1;
}
}
System.out.println("! "+(l));
System.out.flush();
}
}
public static long maximumArea(int arr[]){
int n=arr.length;
long suf[]=new long[n];
suf[n-1]=arr[n-1];
for (int i=n-2;i>=0;i--){
suf[i]=arr[i]*(n-i);
}
for(int i=n-2;i>=0;i--){
suf[i]=Math.max(suf[i], suf[i+1]);
}
long ans=0;
for (int i=0;i<n-1;i++){
ans=Math.max((long) arr[i]*(i+1)+suf[i+1], ans);
}
return ans;
}
public static int[] itemsCollected(int t[]){
int n = t.length;
int i=0, j=n-1;
long sumi=0, sumj=0;
while (i<=j){
while (i<=j && sumi<=sumj){
sumi+=t[i];
i++;
}
while (i<=j && sumi>sumj){
sumj+=t[j];
j--;
}
}
return new int[]{i, n-j-1};
}
public static long minimumCost(int c[], int q[]){
PriorityQueue<Point> pq=new PriorityQueue<Point>(new Comparator<Point>() {
@Override
public int compare(Point o1, Point o2) {
return o1.c-o2.c;
}
});
int n=c.length;
long ans=0;
for (int i=0;i<n;i++){
pq.add(new Point(c[i], q[i]));
Point pop=pq.poll();
ans+=pop.c;
if (pop.q-1==0)continue;
pq.add(new Point(pop.c, pop.q-1));
}
return ans;
}
static class Point{
int c, q;
Point(int c, int q){
this.c=c;
this.q=q;
}
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
eb660c470760117dfd0b95acc10eee3b
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,900
| null |
standard output
| |
PASSED
|
b89bcd2c6131f19217c4762746a623a6
|
train_109.jsonl
|
1613658900
|
The only difference between the easy and the hard version is the limit to the number of queries.This is an interactive problem.There is an array $$$a$$$ of $$$n$$$ different numbers. In one query you can ask the position of the second maximum element in a subsegment $$$a[l..r]$$$. Find the position of the maximum element in the array in no more than 20 queries.A subsegment $$$a[l..r]$$$ is all the elements $$$a_l, a_{l + 1}, ..., a_r$$$. After asking this subsegment you will be given the position of the second maximum from this subsegment in the whole array.
|
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.HashMap;
import java.util.HashSet;
import java.util.Random;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.TreeMap;
// CFPS -> CodeForcesProblemSet
public final class CFPS {
static FastReader fr = new FastReader();
static PrintWriter out = new PrintWriter(System.out);
static final int gigamod = 1000000007;
static final int mod = 998244353;
static int t = 1;
static double epsilon = 0.00000001;
static boolean[] isPrime;
static int[] smallestFactorOf;
@SuppressWarnings("unused")
public static void main(String[] args) {
OUTER:
for (int tc = 0; tc < t; tc++) {
int n = fr.nextInt();
// Observations:
// 1. The task is to determine the maximum element from the array using the
// queries.
int smIdx = query(0, n - 1);
// first, we will find out whether the element lies on the left side or on the
// right
int lqsmIdx = -54;
if (smIdx != 0)
lqsmIdx = query(0, smIdx);
if (lqsmIdx == smIdx) {
// [0, smIdx] contains the largest element
// we will use binary search to find the largest index, the exclusion
// of which, changes smIdx
int lo = 0, hi = smIdx - 2;
int largest = -1;
while (lo <= hi) {
int mid = lo + (hi - lo) / 2;
// mid will be excluded
// [mid + 1, smIdx] is the range
int qsmIdx = query(mid + 1, smIdx);
if (qsmIdx == smIdx) {
// largest is not excluded yet, at mid
// we will exclude some larger idx
lo = mid + 1;
} else {
// largest got excluded at mid, it lies
// to the left of mid
hi = mid - 1;
largest = mid;
}
}
if (largest != -1)
out.println("! " + ++largest);
else
out.println("! " + (smIdx));
} else {
// [smIdx + 1, n - 1] contains the largest element
int lo = smIdx + 2, hi = n - 1;
int largest = n;
while (lo <= hi) {
int mid = lo + (hi - lo) / 2;
// mid will be excluded
// [smIdx, mid - 1] is the range
int qsmIdx = query(smIdx, mid - 1);
if (qsmIdx == smIdx) {
// largest is not excluded yet
hi = mid - 1;
} else {
lo = mid + 1;
largest = mid;
}
}
if (largest != n)
out.println("! " + ++largest);
else
out.println("! " + (smIdx + 2));
}
}
out.close();
}
static int query(int l, int r) {
out.println("? " + (l + 1) + " " + (r + 1));
out.flush();
return fr.nextInt() - 1;
}
static class LCA {
int[] height, first, segtree;
ArrayList<Integer> euler;
boolean[] visited;
int n;
LCA(UGraph ug, int root) {
n = ug.V();
height = new int[n];
first = new int[n];
euler = new ArrayList<>();
visited = new boolean[n];
dfs(ug, root, 0);
int m = euler.size();
segtree = new int[m * 4];
build(1, 0, m - 1);
}
void dfs(UGraph ug, int node, int h) {
visited[node] = true;
height[node] = h;
first[node] = euler.size();
euler.add(node);
for (int adj : ug.adj(node)) {
if (!visited[adj]) {
dfs(ug, adj, h + 1);
euler.add(node);
}
}
}
void build(int node, int b, int e) {
if (b == e) {
segtree[node] = euler.get(b);
} else {
int mid = (b + e) / 2;
build(node << 1, b, mid);
build(node << 1 | 1, mid + 1, e);
int l = segtree[node << 1], r = segtree[node << 1 | 1];
segtree[node] = (height[l] < height[r]) ? l : r;
}
}
int query(int node, int b, int e, int L, int R) {
if (b > R || e < L)
return -1;
if (b >= L && e <= R)
return segtree[node];
int mid = (b + e) >> 1;
int left = query(node << 1, b, mid, L, R);
int right = query(node << 1 | 1, mid + 1, e, L, R);
if (left == -1) return right;
if (right == -1) return left;
return height[left] < height[right] ? left : right;
}
int lca(int u, int v) {
int left = first[u], right = first[v];
if (left > right) {
int temp = left;
left = right;
right = temp;
}
return query(1, 0, euler.size() - 1, left, right);
}
}
static class FenwickTree {
long[] array; // 1-indexed array, In this array We save cumulative information to perform efficient range queries and updates
public FenwickTree(int size) {
array = new long[size + 1];
}
public long rsq(int ind) {
assert ind > 0;
long sum = 0;
while (ind > 0) {
sum += array[ind];
//Extracting the portion up to the first significant one of the binary representation of 'ind' and decrementing ind by that number
ind -= ind & (-ind);
}
return sum;
}
public long rsq(int a, int b) {
assert b >= a && a > 0 && b > 0;
return rsq(b) - rsq(a - 1);
}
public void update(int ind, long value) {
assert ind > 0;
while (ind < array.length) {
array[ind] += value;
//Extracting the portion up to the first significant one of the binary representation of 'ind' and incrementing ind by that number
ind += ind & (-ind);
}
}
public int size() {
return array.length - 1;
}
}
static boolean[] prefMatchesSuff(char[] s) {
int n = s.length;
boolean[] res = new boolean[n + 1];
int[] pi = prefixFunction(s);
res[0] = true;
for (int p = n; p != 0; p = pi[p])
res[p] = true;
return res;
}
static int[] prefixFunction(char[] s) {
int k = s.length;
int[] pfunc = new int[k + 1];
pfunc[0] = pfunc[1] = 0;
for (int i = 2; i <= k; i++) {
pfunc[i] = 0;
for (int p = pfunc[i - 1]; p != 0; p = pfunc[p])
if (s[p] == s[i - 1]) {
pfunc[i] = p + 1;
break;
}
if (pfunc[i] == 0 && s[i - 1] == s[0])
pfunc[i] = 1;
}
return pfunc;
}
static class Edge implements Comparable<Edge> {
int from, to;
long weight;
int id;
// int hash;
Edge(int fro, int t, long weigh, int i) {
from = fro;
to = t;
weight = weigh;
id = i;
// hash = Objects.hash(from, to, weight);
}
/*public int hashCode() {
return hash;
}*/
public int compareTo(Edge that) {
return Long.compare(this.id, that.id);
}
}
public static long[][] sparseTable(long[] a)
{
int n = a.length;
int b = 32-Integer.numberOfLeadingZeros(n);
long[][] ret = new long[b][];
for(int i = 0, l = 1;i < b;i++, l*=2) {
if(i == 0) {
ret[i] = a;
}else {
ret[i] = new long[n-l+1];
for(int j = 0;j < n-l+1;j++) {
ret[i][j] = Math.min(ret[i-1][j], ret[i-1][j+l/2]);
}
}
}
return ret;
}
public static long sparseRMQ(long[][] table, int l, int r)
{
// [a,b)
assert l <= r;
if(l >= r)return Integer.MAX_VALUE;
// 1:0, 2:1, 3:1, 4:2, 5:2, 6:2, 7:2, 8:3
int t = 31-Integer.numberOfLeadingZeros(r-l);
return Math.min(table[t][l], table[t][r-(1<<t)]);
}
static class Point implements Comparable<Point> {
long x;
long y;
long z;
long id;
// private int hashCode;
Point() {
x = z = y = 0;
// this.hashCode = Objects.hash(x, y, cost);
}
Point(Point p) {
this.x = p.x;
this.y = p.y;
this.z = p.z;
this.id = p.id;
// this.hashCode = Objects.hash(x, y, cost);
}
Point(long x, long y, long z, long id) {
this.x = x;
this.y = y;
this.z = z;
this.id = id;
// this.hashCode = Objects.hash(x, y, id);
}
Point(long a, long b) {
this.x = a;
this.y = b;
this.z = 0;
// this.hashCode = Objects.hash(a, b);
}
Point(long x, long y, long id) {
this.x = x;
this.y = y;
this.id = id;
}
@Override
public int compareTo(Point o) {
if (this.x < o.x)
return -1;
if (this.x > o.x)
return 1;
if (this.y < o.y)
return -1;
if (this.y > o.y)
return 1;
if (this.z < o.z)
return -1;
if (this.z > o.z)
return 1;
return 0;
}
@Override
public boolean equals(Object that) {
return this.compareTo((Point) that) == 0;
}
/*@Override
public int hashCode() {
return this.hashCode;
}*/
}
static class BinaryLift {
// FUNCTIONS: k-th ancestor and LCA in log(n)
int[] parentOf;
int maxJmpPow;
int[][] binAncestorOf;
int n;
int[] lvlOf;
// How this works?
// a. For every node, we store the b-ancestor for b in {1, 2, 4, 8, .. log(n)}.
// b. When we need k-ancestor, we represent 'k' in binary and for each set bit, we
// lift level in the tree.
public BinaryLift(UGraph tree) {
n = tree.V();
maxJmpPow = logk(n, 2) + 1;
parentOf = new int[n];
binAncestorOf = new int[n][maxJmpPow];
lvlOf = new int[n];
for (int i = 0; i < n; i++)
Arrays.fill(binAncestorOf[i], -1);
parentConstruct(0, -1, tree, 0);
binConstruct();
}
// TODO: Implement lvlOf[] initialization
public BinaryLift(int[] parentOf) {
this.parentOf = parentOf;
n = parentOf.length;
maxJmpPow = logk(n, 2) + 1;
binAncestorOf = new int[n][maxJmpPow];
lvlOf = new int[n];
for (int i = 0; i < n; i++)
Arrays.fill(binAncestorOf[i], -1);
UGraph tree = new UGraph(n);
for (int i = 1; i < n; i++)
tree.addEdge(i, parentOf[i]);
binConstruct();
parentConstruct(0, -1, tree, 0);
}
private void parentConstruct(int current, int from, UGraph tree, int depth) {
parentOf[current] = from;
lvlOf[current] = depth;
for (int adj : tree.adj(current))
if (adj != from)
parentConstruct(adj, current, tree, depth + 1);
}
private void binConstruct() {
for (int node = 0; node < n; node++)
for (int lvl = 0; lvl < maxJmpPow; lvl++)
binConstruct(node, lvl);
}
private int binConstruct(int node, int lvl) {
if (node < 0)
return -1;
if (lvl == 0)
return binAncestorOf[node][lvl] = parentOf[node];
if (node == 0)
return binAncestorOf[node][lvl] = -1;
if (binAncestorOf[node][lvl] != -1)
return binAncestorOf[node][lvl];
return binAncestorOf[node][lvl] = binConstruct(binConstruct(node, lvl - 1), lvl - 1);
}
// return ancestor which is 'k' levels above this one
public int ancestor(int node, int k) {
if (node < 0)
return -1;
if (node == 0)
if (k == 0) return node;
else return -1;
if (k > (1 << maxJmpPow) - 1)
return -1;
if (k == 0)
return node;
int ancestor = node;
int highestBit = Integer.highestOneBit(k);
while (k > 0 && ancestor != -1) {
ancestor = binAncestorOf[ancestor][logk(highestBit, 2)];
k -= highestBit;
highestBit = Integer.highestOneBit(k);
}
return ancestor;
}
public int lca(int u, int v) {
if (u == v)
return u;
// The invariant will be that 'u' is below 'v' initially.
if (lvlOf[u] < lvlOf[v]) {
int temp = u;
u = v;
v = temp;
}
// Equalizing the levels.
u = ancestor(u, lvlOf[u] - lvlOf[v]);
if (u == v)
return u;
// We will now raise level by largest fitting power of two until possible.
for (int power = maxJmpPow - 1; power > -1; power--)
if (binAncestorOf[u][power] != binAncestorOf[v][power]) {
u = binAncestorOf[u][power];
v = binAncestorOf[v][power];
}
return ancestor(u, 1);
}
}
static class DFSTree {
// NOTE: The thing is made keeping in mind that the whole
// input graph is connected.
UGraph tree;
UGraph backUG;
int hasBridge;
int n;
DFSTree(UGraph ug) {
this.n = ug.V();
tree = new UGraph(n);
hasBridge = -1;
backUG = new UGraph(n);
treeCalc(0, -1, new boolean[n], ug);
}
private void treeCalc(int current, int from, boolean[] marked, UGraph ug) {
if (marked[current]) {
// This is a backEdge.
backUG.addEdge(from, current);
return;
}
if (from != -1)
tree.addEdge(from, current);
marked[current] = true;
for (int adj : ug.adj(current))
if (adj != from)
treeCalc(adj, current, marked, ug);
}
public boolean hasBridge() {
if (hasBridge != -1)
return (hasBridge == 1);
// We have to determine the bridge.
bridgeFinder();
return (hasBridge == 1);
}
int[] levelOf;
int[] dp;
private void bridgeFinder() {
// Finding the level of each node.
levelOf = new int[n];
// Applying DP solution.
// dp[i] -> Highest level reachable from subtree of 'i' using
// some backEdge.
dp = new int[n];
Arrays.fill(dp, Integer.MAX_VALUE / 100);
dpDFS(0, -1, 0);
// Now, we will check each edge and determine whether its a
// bridge.
for (int i = 0; i < n; i++)
for (int adj : tree.adj(i)) {
// (i -> adj) is the edge.
if (dp[adj] > levelOf[i])
hasBridge = 1;
}
if (hasBridge != 1)
hasBridge = 0;
}
private int dpDFS(int current, int from, int lvl) {
levelOf[current] = lvl;
dp[current] = levelOf[current];
for (int back : backUG.adj(current))
dp[current] = Math.min(dp[current], levelOf[back]);
for (int adj : tree.adj(current))
if (adj != from)
dp[current] = Math.min(dp[current], dpDFS(adj, current, lvl + 1));
return dp[current];
}
}
static class UnionFind {
// Uses weighted quick-union with path compression.
private int[] parent; // parent[i] = parent of i
private int[] size; // size[i] = number of sites in tree rooted at i
// Note: not necessarily correct if i is not a root node
private int count; // number of components
public UnionFind(int n) {
count = n;
parent = new int[n];
size = new int[n];
for (int i = 0; i < n; i++) {
parent[i] = i;
size[i] = 1;
}
}
// Number of connected components.
public int count() {
return count;
}
// Find the root of p.
public int find(int p) {
while (p != parent[p])
p = parent[p];
return p;
}
public boolean connected(int p, int q) {
return find(p) == find(q);
}
public int numConnectedTo(int node) {
return size[find(node)];
}
// Weighted union.
public void union(int p, int q) {
int rootP = find(p);
int rootQ = find(q);
if (rootP == rootQ) return;
// make smaller root point to larger one
if (size[rootP] < size[rootQ]) {
parent[rootP] = rootQ;
size[rootQ] += size[rootP];
}
else {
parent[rootQ] = rootP;
size[rootP] += size[rootQ];
}
count--;
}
public static int[] connectedComponents(UnionFind uf) {
// We can do this in nlogn.
int n = uf.size.length;
int[] compoColors = new int[n];
for (int i = 0; i < n; i++)
compoColors[i] = uf.find(i);
HashMap<Integer, Integer> oldToNew = new HashMap<>();
int newCtr = 0;
for (int i = 0; i < n; i++) {
int thisOldColor = compoColors[i];
Integer thisNewColor = oldToNew.get(thisOldColor);
if (thisNewColor == null)
thisNewColor = newCtr++;
oldToNew.put(thisOldColor, thisNewColor);
compoColors[i] = thisNewColor;
}
return compoColors;
}
}
static class UGraph {
// Adjacency list.
private HashSet<Integer>[] adj;
private static final String NEWLINE = "\n";
private int E;
@SuppressWarnings("unchecked")
public UGraph(int V) {
adj = (HashSet<Integer>[]) new HashSet[V];
E = 0;
for (int i = 0; i < V; i++)
adj[i] = new HashSet<Integer>();
}
public void addEdge(int from, int to) {
if (adj[from].contains(to)) return;
E++;
adj[from].add(to);
adj[to].add(from);
}
public HashSet<Integer> adj(int from) {
return adj[from];
}
public int degree(int v) {
return adj[v].size();
}
public int V() {
return adj.length;
}
public int E() {
return E;
}
public String toString() {
StringBuilder s = new StringBuilder();
s.append(V() + " vertices, " + E() + " edges " + NEWLINE);
for (int v = 0; v < V(); v++) {
s.append(v + ": ");
for (int w : adj[v]) {
s.append(w + " ");
}
s.append(NEWLINE);
}
return s.toString();
}
public static void dfsMark(int current, boolean[] marked, UGraph g) {
if (marked[current]) return;
marked[current] = true;
Iterable<Integer> adj = g.adj(current);
for (int adjc : adj)
dfsMark(adjc, marked, g);
}
public static void dfsMark(int current, int from, long[] distTo, boolean[] marked, UGraph g, ArrayList<Integer> endPoints) {
if (marked[current]) return;
marked[current] = true;
if (from != -1)
distTo[current] = distTo[from] + 1;
HashSet<Integer> adj = g.adj(current);
int alreadyMarkedCtr = 0;
for (int adjc : adj) {
if (marked[adjc]) alreadyMarkedCtr++;
dfsMark(adjc, current, distTo, marked, g, endPoints);
}
if (alreadyMarkedCtr == adj.size())
endPoints.add(current);
}
public static void bfsOrder(int current, UGraph g) {
}
public static void dfsMark(int current, int[] colorIds, int color, UGraph g) {
if (colorIds[current] != -1) return;
colorIds[current] = color;
Iterable<Integer> adj = g.adj(current);
for (int adjc : adj)
dfsMark(adjc, colorIds, color, g);
}
public static int[] connectedComponents(UGraph g) {
int n = g.V();
int[] componentId = new int[n];
Arrays.fill(componentId, -1);
int colorCtr = 0;
for (int i = 0; i < n; i++) {
if (componentId[i] != -1) continue;
dfsMark(i, componentId, colorCtr, g);
colorCtr++;
}
return componentId;
}
public static boolean hasCycle(UGraph ug) {
int n = ug.V();
boolean[] marked = new boolean[n];
boolean[] hasCycleFirst = new boolean[1];
for (int i = 0; i < n; i++) {
if (marked[i]) continue;
hcDfsMark(i, ug, marked, hasCycleFirst, -1);
}
return hasCycleFirst[0];
}
// Helper for hasCycle.
private static void hcDfsMark(int current, UGraph ug, boolean[] marked, boolean[] hasCycleFirst, int parent) {
if (marked[current]) return;
if (hasCycleFirst[0]) return;
marked[current] = true;
HashSet<Integer> adjc = ug.adj(current);
for (int adj : adjc) {
if (marked[adj] && adj != parent && parent != -1) {
hasCycleFirst[0] = true;
return;
}
hcDfsMark(adj, ug, marked, hasCycleFirst, current);
}
}
}
static class Digraph {
// Adjacency list.
private HashSet<Integer>[] adj;
private static final String NEWLINE = "\n";
private int E;
@SuppressWarnings("unchecked")
public Digraph(int V) {
adj = (HashSet<Integer>[]) new HashSet[V];
E = 0;
for (int i = 0; i < V; i++)
adj[i] = new HashSet<Integer>();
}
public void addEdge(int from, int to) {
if (adj[from].contains(to)) return;
E++;
adj[from].add(to);
}
public HashSet<Integer> adj(int from) {
return adj[from];
}
public int V() {
return adj.length;
}
public int E() {
return E;
}
public Digraph reversed() {
Digraph dg = new Digraph(V());
for (int i = 0; i < V(); i++)
for (int adjVert : adj(i)) dg.addEdge(adjVert, i);
return dg;
}
public String toString() {
StringBuilder s = new StringBuilder();
s.append(V() + " vertices, " + E() + " edges " + NEWLINE);
for (int v = 0; v < V(); v++) {
s.append(v + ": ");
for (int w : adj[v]) {
s.append(w + " ");
}
s.append(NEWLINE);
}
return s.toString();
}
public static int[] KosarajuSharirSCC(Digraph dg) {
int[] id = new int[dg.V()];
Digraph reversed = dg.reversed();
// Gotta perform topological sort on this one to get the stack.
Stack<Integer> revStack = Digraph.topologicalSort(reversed);
// Initializing id and idCtr.
id = new int[dg.V()];
int idCtr = -1;
// Creating a 'marked' array.
boolean[] marked = new boolean[dg.V()];
while (!revStack.isEmpty()) {
int vertex = revStack.pop();
if (!marked[vertex])
sccDFS(dg, vertex, marked, ++idCtr, id);
}
return id;
}
private static void sccDFS(Digraph dg, int source, boolean[] marked, int idCtr, int[] id) {
marked[source] = true;
id[source] = idCtr;
for (Integer adjVertex : dg.adj(source))
if (!marked[adjVertex]) sccDFS(dg, adjVertex, marked, idCtr, id);
}
public static Stack<Integer> topologicalSort(Digraph dg) {
// dg has to be a directed acyclic graph.
// We'll have to run dfs on the digraph and push the deepest nodes on stack first.
// We'll need a Stack<Integer> and a int[] marked.
Stack<Integer> topologicalStack = new Stack<Integer>();
boolean[] marked = new boolean[dg.V()];
// Calling dfs
for (int i = 0; i < dg.V(); i++)
if (!marked[i])
runDfs(dg, topologicalStack, marked, i);
return topologicalStack;
}
static void runDfs(Digraph dg, Stack<Integer> topologicalStack, boolean[] marked, int source) {
marked[source] = true;
for (Integer adjVertex : dg.adj(source))
if (!marked[adjVertex])
runDfs(dg, topologicalStack, marked, adjVertex);
topologicalStack.add(source);
}
}
static class FastReader {
private BufferedReader bfr;
private StringTokenizer st;
public FastReader() {
bfr = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
if (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(bfr.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
char nextChar() {
return next().toCharArray()[0];
}
String nextString() {
return next();
}
int[] nextIntArray(int n) {
int[] arr = new int[n];
for (int i = 0; i < n; i++)
arr[i] = nextInt();
return arr;
}
double[] nextDoubleArray(int n) {
double[] arr = new double[n];
for (int i = 0; i < arr.length; i++)
arr[i] = nextDouble();
return arr;
}
long[] nextLongArray(int n) {
long[] arr = new long[n];
for (int i = 0; i < n; i++)
arr[i] = nextLong();
return arr;
}
int[][] nextIntGrid(int n, int m) {
int[][] grid = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++)
grid[i][j] = fr.nextInt();
}
return grid;
}
}
static class SegmentTree {
private Node[] heap;
private long[] array;
private int size;
public SegmentTree(long[] array) {
this.array = Arrays.copyOf(array, array.length);
//The max size of this array is about 2 * 2 ^ log2(n) + 1
size = (int) (2 * Math.pow(2.0, Math.floor((Math.log((double) array.length) / Math.log(2.0)) + 1)));
heap = new Node[size];
build(1, 0, array.length);
}
public int size() {
return array.length;
}
//Initialize the Nodes of the Segment tree
private void build(int v, int from, int size) {
heap[v] = new Node();
heap[v].from = from;
heap[v].to = from + size - 1;
if (size == 1) {
heap[v].sum = array[from];
heap[v].min = array[from];
heap[v].max = array[from];
} else {
//Build childs
build(2 * v, from, size / 2);
build(2 * v + 1, from + size / 2, size - size / 2);
heap[v].sum = heap[2 * v].sum + heap[2 * v + 1].sum;
//min = min of the children
heap[v].min = Math.min(heap[2 * v].min, heap[2 * v + 1].min);
heap[v].max = Math.max(heap[2 * v].max, heap[2 * v + 1].max);
}
}
public long rsq(int from, int to) {
return rsq(1, from, to);
}
private long rsq(int v, int from, int to) {
Node n = heap[v];
//If you did a range update that contained this node, you can infer the Sum without going down the tree
if (n.pendingVal != null && contains(n.from, n.to, from, to)) {
return (to - from + 1) * n.pendingVal;
}
if (contains(from, to, n.from, n.to)) {
return heap[v].sum;
}
if (intersects(from, to, n.from, n.to)) {
propagate(v);
long leftSum = rsq(2 * v, from, to);
long rightSum = rsq(2 * v + 1, from, to);
return leftSum + rightSum;
}
return 0;
}
public long rMinQ(int from, int to) {
return rMinQ(1, from, to);
}
private long rMinQ(int v, int from, int to) {
Node n = heap[v];
//If you did a range update that contained this node, you can infer the Min value without going down the tree
if (n.pendingVal != null && contains(n.from, n.to, from, to)) {
return n.pendingVal;
}
if (contains(from, to, n.from, n.to)) {
return heap[v].min;
}
if (intersects(from, to, n.from, n.to)) {
propagate(v);
long leftMin = rMinQ(2 * v, from, to);
long rightMin = rMinQ(2 * v + 1, from, to);
return Math.min(leftMin, rightMin);
}
return Integer.MAX_VALUE;
}
public long rMaxQ(int from, int to) {
return rMaxQ(1, from, to);
}
private long rMaxQ(int v, int from, int to) {
Node n = heap[v];
//If you did a range update that contained this node, you can infer the Min value without going down the tree
if (n.pendingVal != null && contains(n.from, n.to, from, to)) {
return n.pendingVal;
}
if (contains(from, to, n.from, n.to)) {
return heap[v].max;
}
if (intersects(from, to, n.from, n.to)) {
propagate(v);
long leftMax = rMaxQ(2 * v, from, to);
long rightMax = rMaxQ(2 * v + 1, from, to);
return Math.max(leftMax, rightMax);
}
return Integer.MIN_VALUE;
}
public void update(int from, int to, long value) {
update(1, from, to, value);
}
private void update(int v, int from, int to, long value) {
//The Node of the heap tree represents a range of the array with bounds: [n.from, n.to]
Node n = heap[v];
if (contains(from, to, n.from, n.to)) {
change(n, value);
}
if (n.size() == 1) return;
if (intersects(from, to, n.from, n.to)) {
propagate(v);
update(2 * v, from, to, value);
update(2 * v + 1, from, to, value);
n.sum = heap[2 * v].sum + heap[2 * v + 1].sum;
n.min = Math.min(heap[2 * v].min, heap[2 * v + 1].min);
n.max = Math.max(heap[2 * v].max, heap[2 * v + 1].max);
}
}
//Propagate temporal values to children
private void propagate(int v) {
Node n = heap[v];
if (n.pendingVal != null) {
change(heap[2 * v], n.pendingVal);
change(heap[2 * v + 1], n.pendingVal);
n.pendingVal = null; //unset the pending propagation value
}
}
//Save the temporal values that will be propagated lazily
private void change(Node n, long value) {
n.pendingVal = value;
n.sum = n.size() * value;
n.min = value;
n.max = value;
array[n.from] = value;
}
//Test if the range1 contains range2
private boolean contains(int from1, int to1, int from2, int to2) {
return from2 >= from1 && to2 <= to1;
}
//check inclusive intersection, test if range1[from1, to1] intersects range2[from2, to2]
private boolean intersects(int from1, int to1, int from2, int to2) {
return from1 <= from2 && to1 >= from2 // (.[..)..] or (.[...]..)
|| from1 >= from2 && from1 <= to2; // [.(..]..) or [..(..)..
}
//The Node class represents a partition range of the array.
static class Node {
long sum;
long min;
long max;
//Here we store the value that will be propagated lazily
Long pendingVal = null;
int from;
int to;
int size() {
return to - from + 1;
}
}
}
@SuppressWarnings("serial")
static class CountMap<T> extends TreeMap<T, Integer>{
CountMap() {
}
CountMap(T[] arr) {
this.putCM(arr);
}
public Integer putCM(T key) {
return super.put(key, super.getOrDefault(key, 0) + 1);
}
public Integer removeCM(T key) {
int count = super.getOrDefault(key, -1);
if (count == -1) return -1;
if (count == 1)
return super.remove(key);
else
return super.put(key, count - 1);
}
public Integer getCM(T key) {
return super.getOrDefault(key, 0);
}
public void putCM(T[] arr) {
for (T l : arr)
this.putCM(l);
}
}
static long dioGCD(long a, long b, long[] x0, long[] y0) {
if (b == 0) {
x0[0] = 1;
y0[0] = 0;
return a;
}
long[] x1 = new long[1], y1 = new long[1];
long d = dioGCD(b, a % b, x1, y1);
x0[0] = y1[0];
y0[0] = x1[0] - y1[0] * (a / b);
return d;
}
static boolean diophantine(long a, long b, long c, long[] x0, long[] y0, long[] g) {
g[0] = dioGCD(Math.abs(a), Math.abs(b), x0, y0);
if (c % g[0] > 0) {
return false;
}
x0[0] *= c / g[0];
y0[0] *= c / g[0];
if (a < 0) x0[0] = -x0[0];
if (b < 0) y0[0] = -y0[0];
return true;
}
static long[][] prod(long[][] mat1, long[][] mat2) {
int n = mat1.length;
long[][] prod = new long[n][n];
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
// determining prod[i][j]
// it will be the dot product of mat1[i][] and mat2[][i]
for (int k = 0; k < n; k++)
prod[i][j] += mat1[i][k] * mat2[k][j];
return prod;
}
static long[][] matExpo(long[][] mat, long power) {
int n = mat.length;
long[][] ans = new long[n][n];
if (power == 0)
return null;
if (power == 1)
return mat;
long[][] half = matExpo(mat, power / 2);
ans = prod(half, half);
if (power % 2 == 1) {
ans = prod(ans, mat);
}
return ans;
}
static int KMPNumOcc(char[] text, char[] pat) {
int n = text.length;
int m = pat.length;
char[] patPlusText = new char[n + m + 1];
for (int i = 0; i < m; i++)
patPlusText[i] = pat[i];
patPlusText[m] = '^'; // Seperator
for (int i = 0; i < n; i++)
patPlusText[m + i] = text[i];
int[] fullPi = piCalcKMP(patPlusText);
int answer = 0;
for (int i = 0; i < n + m + 1; i++)
if (fullPi[i] == m)
answer++;
return answer;
}
static int[] piCalcKMP(char[] s) {
int n = s.length;
int[] pi = new int[n];
for (int i = 1; i < n; i++) {
int j = pi[i - 1];
while (j > 0 && s[i] != s[j])
j = pi[j - 1];
if (s[i] == s[j])
j++;
pi[i] = j;
}
return pi;
}
static long hash(long key) {
long h = Long.hashCode(key);
h ^= (h >>> 20) ^ (h >>> 12) ^ (h >>> 7) ^ (h >>> 4);
return h & (gigamod-1);
}
static int mapTo1D(int row, int col, int n, int m) {
// Maps elements in a 2D matrix serially to elements in
// a 1D array.
return row * m + col;
}
static int[] mapTo2D(int idx, int n, int m) {
// Inverse of what the one above does.
int[] rnc = new int[2];
rnc[0] = idx / m;
rnc[1] = idx % m;
return rnc;
}
static boolean[] primeGenerator(int upto) {
// Sieve of Eratosthenes:
isPrime = new boolean[upto + 1];
smallestFactorOf = new int[upto + 1];
Arrays.fill(smallestFactorOf, 1);
Arrays.fill(isPrime, true);
isPrime[1] = isPrime[0] = false;
for (long i = 2; i < upto + 1; i++)
if (isPrime[(int) i]) {
smallestFactorOf[(int) i] = (int) i;
// Mark all the multiples greater than or equal
// to the square of i to be false.
for (long j = i; j * i < upto + 1; j++) {
if (isPrime[(int) j * (int) i]) {
isPrime[(int) j * (int) i] = false;
smallestFactorOf[(int) j * (int) i] = (int) i;
}
}
}
return isPrime;
}
static HashMap<Integer, Integer> smolNumPrimeFactorization(int num) {
if (smallestFactorOf == null)
primeGenerator(num + 1);
HashMap<Integer, Integer> fnps = new HashMap<>();
while (num != 1) {
fnps.put(smallestFactorOf[num], fnps.getOrDefault(smallestFactorOf[num], 0) + 1);
num /= smallestFactorOf[num];
}
return fnps;
}
static HashMap<Long, Integer> primeFactorization(long num) {
// Returns map of factor and its power in the number.
HashMap<Long, Integer> map = new HashMap<>();
while (num % 2 == 0) {
num /= 2;
Integer pwrCnt = map.get(2L);
map.put(2L, pwrCnt != null ? pwrCnt + 1 : 1);
}
for (long i = 3; i * i <= num; i += 2) {
while (num % i == 0) {
num /= i;
Integer pwrCnt = map.get(i);
map.put(i, pwrCnt != null ? pwrCnt + 1 : 1);
}
}
// If the number is prime, we have to add it to the
// map.
if (num != 1)
map.put(num, 1);
return map;
}
static HashSet<Long> divisors(long num) {
HashSet<Long> divisors = new HashSet<Long>();
divisors.add(1L);
divisors.add(num);
for (long i = 2; i * i <= num; i++) {
if (num % i == 0) {
divisors.add(num/i);
divisors.add(i);
}
}
return divisors;
}
static void coprimeGenerator(int m, int n, ArrayList<Point> coprimes, int limit, int numCoprimes) {
if (m > limit) return;
if (m <= limit && n <= limit)
coprimes.add(new Point(m, n));
if (coprimes.size() > numCoprimes) return;
coprimeGenerator(2 * m - n, m, coprimes, limit, numCoprimes);
coprimeGenerator(2 * m + n, m, coprimes, limit, numCoprimes);
coprimeGenerator(m + 2 * n, n, coprimes, limit, numCoprimes);
}
static int bsearch(int[] arr, int val, int lo, int hi) {
// Returns the index of the first element
// larger than or equal to val.
int idx = -1;
while (lo <= hi) {
int mid = lo + (hi - lo)/2;
if (arr[mid] >= val) {
idx = mid;
hi = mid - 1;
} else
lo = mid + 1;
}
return idx;
}
static int bsearch(long[] arr, long val, int lo, int hi) {
// Returns the index of the first element
// larger than or equal to val.
int idx = -1;
while (lo <= hi) {
int mid = lo + (hi - lo)/2;
if (arr[mid] >= val) {
idx = mid;
hi = mid - 1;
} else
lo = mid + 1;
}
return idx;
}
static int bsearch(long[] arr, long val, int lo, int hi, boolean sMode) {
// Returns the index of the last element
// smaller than or equal to val.
int idx = -1;
while (lo <= hi) {
int mid = lo + (hi - lo)/2;
if (arr[mid] > val) {
hi = mid - 1;
} else {
idx = mid;
lo = mid + 1;
}
}
return idx;
}
static int bsearch(int[] arr, long val, int lo, int hi, boolean sMode) {
int idx = -1;
while (lo <= hi) {
int mid = lo + (hi - lo)/2;
if (arr[mid] > val) {
hi = mid - 1;
} else {
idx = mid;
lo = mid + 1;
}
}
return idx;
}
static long nCr(long n, long r, long[] fac) { long p = mod; if (r == 0) return 1; return (fac[(int)n] * modInverse(fac[(int)r], p) % p * modInverse(fac[(int)n - (int)r], p) % p) % p; }
static long modInverse(long n, long p) { return power(n, p - 2, p); }
static long modDiv(long a, long b){return mod(a * power(b, gigamod - 2, gigamod));}
static long power(long x, long y, long p) { long res = 1; x = x % p; while (y > 0) { if ((y & 1)==1) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return res; }
static int logk(long n, long k) { return (int)(Math.log(n) / Math.log(k)); }
static long gcd(long a, long b) { if (b == 0) { return a; } else { return gcd(b, a % b); } } static int gcd(int a, int b) { if (b == 0) { return a; } else { return gcd(b, a % b); } } static long gcd(long[] arr) { int n = arr.length; long gcd = arr[0]; for (int i = 1; i < n; i++) { gcd = gcd(gcd, arr[i]); } return gcd; } static int gcd(int[] arr) { int n = arr.length; int gcd = arr[0]; for (int i = 1; i < n; i++) { gcd = gcd(gcd, arr[i]); } return gcd; } static long lcm(long[] arr) { long lcm = arr[0]; int n = arr.length; for (int i = 1; i < n; i++) { lcm = (lcm * arr[i]) / gcd(lcm, arr[i]); } return lcm; } static long lcm(long a, long b) { return (a * b)/gcd(a, b); } static boolean less(int a, int b) { return a < b ? true : false; } static boolean isSorted(int[] a) { for (int i = 1; i < a.length; i++) { if (less(a[i], a[i - 1])) return false; } return true; } static boolean isSorted(long[] a) { for (int i = 1; i < a.length; i++) { if (a[i] < a[i - 1]) return false; } return true; } static void swap(int[] a, int i, int j) { int temp = a[i]; a[i] = a[j]; a[j] = temp; } static void swap(long[] a, int i, int j) { long temp = a[i]; a[i] = a[j]; a[j] = temp; } static void swap(double[] a, int i, int j) { double temp = a[i]; a[i] = a[j]; a[j] = temp; } static void swap(char[] a, int i, int j) { char temp = a[i]; a[i] = a[j]; a[j] = temp; }
static void sort(int[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); } static void sort(char[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); } static void sort(long[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); } static void sort(double[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); } static void reverseSort(int[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); int n = arr.length; for (int i = 0; i < n/2; i++) swap(arr, i, n - 1 - i); } static void reverseSort(char[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); int n = arr.length; for (int i = 0; i < n/2; i++) swap(arr, i, n - 1 - i); } static void reverse(char[] arr) { int n = arr.length; for (int i = 0; i < n / 2; i++) swap(arr, i, n - 1 - i); } static void reverseSort(long[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); int n = arr.length; for (int i = 0; i < n/2; i++) swap(arr, i, n - 1 - i); } static void reverseSort(double[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); int n = arr.length; for (int i = 0; i < n/2; i++) swap(arr, i, n - 1 - i); }
static void shuffleArray(long[] arr, int startPos, int endPos) { Random rnd = new Random(); for (int i = startPos; i < endPos; ++i) { long tmp = arr[i]; int randomPos = i + rnd.nextInt(endPos - i); arr[i] = arr[randomPos]; arr[randomPos] = tmp; } } static void shuffleArray(int[] arr, int startPos, int endPos) { Random rnd = new Random(); for (int i = startPos; i < endPos; ++i) { int tmp = arr[i]; int randomPos = i + rnd.nextInt(endPos - i); arr[i] = arr[randomPos]; arr[randomPos] = tmp; } }
static void shuffleArray(double[] arr, int startPos, int endPos) { Random rnd = new Random(); for (int i = startPos; i < endPos; ++i) { double tmp = arr[i]; int randomPos = i + rnd.nextInt(endPos - i); arr[i] = arr[randomPos]; arr[randomPos] = tmp; } }
static void shuffleArray(char[] arr, int startPos, int endPos) { Random rnd = new Random(); for (int i = startPos; i < endPos; ++i) { char tmp = arr[i]; int randomPos = i + rnd.nextInt(endPos - i); arr[i] = arr[randomPos]; arr[randomPos] = tmp; } }
static boolean isPrime(long n) {if (n<=1)return false;if(n<=3)return true;if(n%2==0||n%3==0)return false;for(long i=5;i*i<=n;i=i+6)if(n%i==0||n%(i+2)==0)return false;return true;}
static String toString(int[] dp){StringBuilder sb=new StringBuilder();for(int i=0;i<dp.length;i++)sb.append(dp[i]+" ");return sb.toString();}
static String toString(boolean[] dp){StringBuilder sb=new StringBuilder();for(int i=0;i<dp.length;i++)sb.append(dp[i]+" ");return sb.toString();}
static String toString(long[] dp){StringBuilder sb=new StringBuilder();for(int i=0;i<dp.length;i++)sb.append(dp[i]+" ");return sb.toString();}
static String toString(char[] dp){StringBuilder sb=new StringBuilder();for(int i=0;i<dp.length;i++)sb.append(dp[i]+"");return sb.toString();}
static String toString(int[][] dp){StringBuilder sb=new StringBuilder();for(int i=0;i<dp.length;i++){for(int j=0;j<dp[i].length;j++){sb.append(dp[i][j]+" ");}sb.append('\n');}return sb.toString();}
static String toString(long[][] dp){StringBuilder sb=new StringBuilder();for(int i=0;i<dp.length;i++){for(int j=0;j<dp[i].length;j++) {sb.append(dp[i][j]+" ");}sb.append('\n');}return sb.toString();}
static String toString(double[][] dp){StringBuilder sb=new StringBuilder();for(int i = 0;i<dp.length;i++){for(int j = 0;j<dp[i].length;j++){sb.append(dp[i][j]+" ");}sb.append('\n');}return sb.toString();}
static String toString(char[][] dp){StringBuilder sb = new StringBuilder();for(int i = 0;i<dp.length;i++){for(int j = 0;j<dp[i].length;j++){sb.append(dp[i][j]+"");}sb.append('\n');}return sb.toString();}
static long mod(long a, long m){return(a%m+1000000L*m)%m;}
static long mod(long num){return(num%gigamod+gigamod)%gigamod;}
}
// NOTES:
// ASCII VALUE OF 'A': 65
// ASCII VALUE OF 'a': 97
// Range of long: 9 * 10^18
// ASCII VALUE OF '0': 48
// Primes upto 'n' can be given by (n / (logn)).
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
eb660c470760117dfd0b95acc10eee3b
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,900
| null |
standard output
| |
PASSED
|
786a8ea4dc2913466f380e5e45b70231
|
train_109.jsonl
|
1613658900
|
The only difference between the easy and the hard version is the limit to the number of queries.This is an interactive problem.There is an array $$$a$$$ of $$$n$$$ different numbers. In one query you can ask the position of the second maximum element in a subsegment $$$a[l..r]$$$. Find the position of the maximum element in the array in no more than 20 queries.A subsegment $$$a[l..r]$$$ is all the elements $$$a_l, a_{l + 1}, ..., a_r$$$. After asking this subsegment you will be given the position of the second maximum from this subsegment in the whole array.
|
256 megabytes
|
import java.io.*;
import java.util.*;
public class Codeforces {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
//int cases = Integer.parseInt(br.readLine());
//o:while(cases-- > 0) {
String[] str = br.readLine().split(" ");
int n = Integer.parseInt(str[0]);
int h2 = q(1, n);
int left = 1;
int right = h2;
boolean isleft = true;
if(h2 == 1 || q(1, h2) != h2) {
isleft = false;
left = h2;
right = n;
}
while(isleft && left+1 < right) {
int mid = left + (right - left)/2;
int rep = q(Math.min(mid, h2), Math.max(mid, h2));
if(rep == h2) {
left = mid;
}else {
right = mid;
}
}
while(!isleft && left+1 < right) {
int mid = left + (right - left)/2;
int rep = q(Math.min(mid, h2), Math.max(mid, h2));
if(rep == h2) {
right = mid;
}else {
left = mid;
}
}
if(isleft) {
System.out.println("! "+left);
}else{
System.out.println("! "+right);
}
//}
}
public static int q(int left, int right) throws IOException{
System.out.println("? "+left+" "+right);
System.out.flush();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int reply = Integer.parseInt(br.readLine());
return reply;
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
eb660c470760117dfd0b95acc10eee3b
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,900
| null |
standard output
| |
PASSED
|
3a4ac6df4d35c6d94daaa8e1b43d7415
|
train_109.jsonl
|
1613658900
|
The only difference between the easy and the hard version is the limit to the number of queries.This is an interactive problem.There is an array $$$a$$$ of $$$n$$$ different numbers. In one query you can ask the position of the second maximum element in a subsegment $$$a[l..r]$$$. Find the position of the maximum element in the array in no more than 20 queries.A subsegment $$$a[l..r]$$$ is all the elements $$$a_l, a_{l + 1}, ..., a_r$$$. After asking this subsegment you will be given the position of the second maximum from this subsegment in the whole array.
|
256 megabytes
|
import java.io.DataInputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Map;
import java.util.TreeMap;
public class Main {
private static void run() throws IOException {
int n = in.nextInt();
// TreeMap<Double, Integer> map = new TreeMap<>();
// for (int i = 1; i <= n; i++) {
// map.put(Math.random(), i);
// }
// a = new int[n];
// int index = 0;
// for (Map.Entry<Double, Integer> now : map.entrySet()) {
// a[index++] = now.getValue();
// }
//// print_array(a);
// System.err.flush();
query_with_second(1, n, query(1, n));
}
private static void query_with_second(int left, int right, int second) throws IOException {
if (left == right) {
out.printf("! %d \n", left);
out.flush();
// check(left);
return;
}
int mid = (left + right) >> 1;
if (second <= mid) {
int query_left = query(Math.min(left, second), mid);
if (query_left == second) {
query_with_second(left, mid, second);
} else {
query_with_second(mid + 1, right, second);
}
} else {
int query_right = query(mid + 1, Math.max(right, second));
if (query_right == second) {
query_with_second(mid + 1, right, second);
} else {
query_with_second(left, mid, second);
}
}
}
// static int[] a;
// static int count = 0;
//
// private static void check(int ans) {
// int[] tmp = new int[a.length];
// System.arraycopy(a, 0, tmp, 0, a.length);
// Arrays.sort(tmp);
// System.err.println(tmp[a.length - 1] + " " + a[ans - 1] + " " + (tmp[a.length - 1] == a[ans - 1]));
// System.err.println("count: " + count);
// System.err.flush();
// if (tmp[a.length - 1] != a[ans - 1] || count > 20) {
// System.exit(0);
// }
//
// count = 0;
// }
private static int query(int left, int right) throws IOException {
if (left == right) return -1;
out.printf("? %d %d\n", left, right);
out.flush();
return in.nextInt();
// count++;
// int[] tmp = new int[right - left + 1];
// for (int i = 0; i < right - left + 1; i++) {
// tmp[i] = a[left + i - 1];
// }
// Arrays.sort(tmp);
// for (int i = left; i <= right; i++) {
// if (a[i - 1] == tmp[right - left - 1]) {
// System.err.println("input: " + i);
// System.err.flush();
// return i;
// }
// }
// System.err.println("input error");
// System.err.flush();
// throw new RuntimeException();
}
public static void main(String[] args) throws IOException {
in = new Reader();
out = new PrintWriter(new OutputStreamWriter(System.out));
// int t = in.nextInt();
// for (int i = 0; i < t; i++) {
// }
run();
out.flush();
in.close();
out.close();
}
private static int gcd(int a, int b) {
if (a == 0 || b == 0)
return 0;
while (b != 0) {
int tmp;
tmp = a % b;
a = b;
b = tmp;
}
return a;
}
static final long mod = 1000000007;
static long pow_mod(long a, long b) {
long result = 1;
while (b != 0) {
if ((b & 1) != 0) result = (result * a) % mod;
a = (a * a) % mod;
b >>= 1;
}
return result;
}
private static long multiplied_mod(long... longs) {
long ans = 1;
for (long now : longs) {
ans = (ans * now) % mod;
}
return ans;
}
@SuppressWarnings("FieldCanBeLocal")
private static Reader in;
private static PrintWriter out;
private static void print_array(int[] array) {
for (int now : array) {
System.err.print(now);
System.err.print(' ');
}
System.err.println();
}
private static void print_array(long[] array) {
for (long now : array) {
out.print(now);
out.print(' ');
}
out.println();
}
static class Reader {
private static final int BUFFER_SIZE = 1 << 16;
private final DataInputStream din;
private final byte[] buffer;
private int bufferPointer, bytesRead;
Reader() {
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException {
final byte[] buf = new byte[1024]; // line length
int cnt = 0, c;
while ((c = read()) != -1) {
if (c == '\n') {
break;
}
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int nextSign() throws IOException {
byte c = read();
while ('+' != c && '-' != c) {
c = read();
}
return '+' == c ? 0 : 1;
}
private static boolean isSpaceChar(int c) {
return !(c >= 33 && c <= 126);
}
public int skip() throws IOException {
int b;
// noinspection ALL
while ((b = read()) != -1 && isSpaceChar(b)) {
;
}
return b;
}
public char nc() throws IOException {
return (char) skip();
}
public String next() throws IOException {
int b = skip();
final StringBuilder sb = new StringBuilder();
while (!isSpaceChar(b)) { // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = read();
}
return sb.toString();
}
public int nextInt() throws IOException {
int ret = 0;
byte c = read();
while (c <= ' ') {
c = read();
}
final boolean neg = c == '-';
if (neg) {
c = read();
}
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg) {
return -ret;
}
return ret;
}
public long nextLong() throws IOException {
long ret = 0;
byte c = read();
while (c <= ' ') {
c = read();
}
final boolean neg = c == '-';
if (neg) {
c = read();
}
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (neg) {
return -ret;
}
return ret;
}
public double nextDouble() throws IOException {
double ret = 0, div = 1;
byte c = read();
while (c <= ' ') {
c = read();
}
final boolean neg = c == '-';
if (neg) {
c = read();
}
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (c == '.') {
while ((c = read()) >= '0' && c <= '9') {
ret += (c - '0') / (div *= 10);
}
}
if (neg) {
return -ret;
}
return ret;
}
private void fillBuffer() throws IOException {
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1) {
buffer[0] = -1;
}
}
private byte read() throws IOException {
if (bufferPointer == bytesRead) {
fillBuffer();
}
return buffer[bufferPointer++];
}
public void close() throws IOException {
din.close();
}
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
eb660c470760117dfd0b95acc10eee3b
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,900
| null |
standard output
| |
PASSED
|
2da146aef2fe1ac1b76d4b98d7005856
|
train_109.jsonl
|
1613658900
|
The only difference between the easy and the hard version is the limit to the number of queries.This is an interactive problem.There is an array $$$a$$$ of $$$n$$$ different numbers. In one query you can ask the position of the second maximum element in a subsegment $$$a[l..r]$$$. Find the position of the maximum element in the array in no more than 20 queries.A subsegment $$$a[l..r]$$$ is all the elements $$$a_l, a_{l + 1}, ..., a_r$$$. After asking this subsegment you will be given the position of the second maximum from this subsegment in the whole array.
|
256 megabytes
|
import java.io.*;
import java.util.*;
@SuppressWarnings("unchecked")
public class GuessingTheGreatestHard implements Runnable {
void solve() throws IOException {
int l = 1, h = read.intNext();
int dmax = ask(l, h);
if (ask(l, dmax) == dmax) {
h = dmax;
while (h - l > 1) {
int m = (l + h) / 2;
if (ask(m, dmax) == dmax) {
l = m;
} else {
h = m;
}
}
int q = ask(l, h);
if (q == h) {
println("! " + l);
} else {
println("! " + h);
}
} else {
l = dmax;
while (h - l > 1) {
int m = (l + h) / 2;
if (ask(dmax, m) == dmax) {
h = m;
} else {
l = m;
}
}
int q = ask(l, h);
if (q == h) {
println("! " + l);
} else {
println("! " + h);
}
}
}
int ask(int l, int h) throws IOException {
if (l >= h) return -1;
System.out.println("? " + l + " " + h);
return read.intNext();
}
/************************************************************************************************************************************************/
public static void main(String[] args) throws IOException {
new Thread(null, new GuessingTheGreatestHard(), "1").start();
}
static PrintWriter out = new PrintWriter(System.out);
static Reader read = new Reader();
static StringBuilder sbr = new StringBuilder();
static int mod = (int) 1e9 + 7;
static int dmax = Integer.MAX_VALUE;
static long lmax = Long.MAX_VALUE;
static int dmin = Integer.MIN_VALUE;
static long lmin = Long.MIN_VALUE;
@Override
public void run() {
try {
solve();
out.close();
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
}
static class Reader {
private byte[] buf = new byte[1024];
private int index;
private InputStream in;
private int total;
public Reader() {
in = System.in;
}
public int scan() throws IOException {
if (total < 0)
throw new InputMismatchException();
if (index >= total) {
index = 0;
total = in.read(buf);
if (total <= 0)
return -1;
}
return buf[index++];
}
public int intNext() throws IOException {
int integer = 0;
int n = scan();
while (isWhiteSpace(n))
n = scan();
int neg = 1;
if (n == '-') {
neg = -1;
n = scan();
}
while (!isWhiteSpace(n)) {
if (n >= '0' && n <= '9') {
integer *= 10;
integer += n - '0';
n = scan();
} else throw new InputMismatchException();
}
return neg * integer;
}
public double doubleNext() throws IOException {
double doub = 0;
int n = scan();
while (isWhiteSpace(n))
n = scan();
int neg = 1;
if (n == '-') {
neg = -1;
n = scan();
}
while (!isWhiteSpace(n) && n != '.') {
if (n >= '0' && n <= '9') {
doub *= 10;
doub += n - '0';
n = scan();
} else throw new InputMismatchException();
}
if (n == '.') {
n = scan();
double temp = 1;
while (!isWhiteSpace(n)) {
if (n >= '0' && n <= '9') {
temp /= 10;
doub += (n - '0') * temp;
n = scan();
} else throw new InputMismatchException();
}
}
return doub * neg;
}
public String read() throws IOException {
StringBuilder sb = new StringBuilder();
int n = scan();
while (isWhiteSpace(n))
n = scan();
while (!isWhiteSpace(n)) {
sb.append((char) n);
n = scan();
}
return sb.toString();
}
private boolean isWhiteSpace(int n) {
if (n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1)
return true;
return false;
}
}
static void shuffle(int[] aa) {
int n = aa.length;
Random rand = new Random();
for (int i = 1; i < n; i++) {
int j = rand.nextInt(i + 1);
int tmp = aa[i];
aa[i] = aa[j];
aa[j] = tmp;
}
}
static void shuffle(int[][] aa) {
int n = aa.length;
Random rand = new Random();
for (int i = 1; i < n; i++) {
int j = rand.nextInt(i + 1);
int first = aa[i][0];
int second = aa[i][1];
aa[i][0] = aa[j][0];
aa[i][1] = aa[j][1];
aa[j][0] = first;
aa[j][1] = second;
}
}
static final class Comparators {
public static final Comparator<int[]> pairIntArr =
(x, y) -> x[0] == y[0] ? compare(x[1], y[1]) : compare(x[0], y[0]);
private static final int compare(final int x, final int y) {
return Integer.compare(x, y);
}
}
static void print(Object object) {
out.print(object);
}
static void println(Object object) {
out.println(object);
}
static int[] iArr(int len) {
return new int[len];
}
static long[] lArr(int len) {
return new long[len];
}
static long min(long a, long b) {
return Math.min(a, b);
}
static int min(int a, int b) {
return Math.min(a, b);
}
static long max(Long a, Long b) {
return Math.max(a, b);
}
static int max(int a, int b) {
return Math.max(a, b);
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
eb660c470760117dfd0b95acc10eee3b
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,900
| null |
standard output
| |
PASSED
|
07f5fcd77f5ad1f37d35d530924ff0cb
|
train_109.jsonl
|
1613658900
|
The only difference between the easy and the hard version is the limit to the number of queries.This is an interactive problem.There is an array $$$a$$$ of $$$n$$$ different numbers. In one query you can ask the position of the second maximum element in a subsegment $$$a[l..r]$$$. Find the position of the maximum element in the array in no more than 20 queries.A subsegment $$$a[l..r]$$$ is all the elements $$$a_l, a_{l + 1}, ..., a_r$$$. After asking this subsegment you will be given the position of the second maximum from this subsegment in the whole array.
|
256 megabytes
|
import java.util.*;
import java.io.*;
public class C2
{
public static class FastIO
{
BufferedReader br;
BufferedWriter bw, be;
StringTokenizer st;
public FastIO()
{
br = new BufferedReader(new InputStreamReader(System.in));
bw = new BufferedWriter(new OutputStreamWriter(System.out));
be = new BufferedWriter(new OutputStreamWriter(System.err));
st = new StringTokenizer("");
}
private void read() throws IOException
{
st = new StringTokenizer(br.readLine());
}
public String ns() throws IOException
{
while(!st.hasMoreTokens())
read();
return st.nextToken();
}
public int ni() throws IOException
{
return Integer.parseInt(ns());
}
public long nl() throws IOException
{
return Long.parseLong(ns());
}
public float nf() throws IOException
{
return Float.parseFloat(ns());
}
public double nd() throws IOException
{
return Double.parseDouble(ns());
}
public char nc() throws IOException
{
return ns().charAt(0);
}
public int[] nia(int n) throws IOException
{
int[] a = new int[n];
for(int i = 0; i < n; i++)
a[i] = ni();
return a;
}
public long[] nla(int n) throws IOException
{
long[] a = new long[n];
for(int i = 0; i < n; i++)
a[i] = nl();
return a;
}
public char[] nca() throws IOException
{
return f.ns().toCharArray();
}
public void out(String s) throws IOException
{
bw.write(s);
bw.flush();
}
public void flush() throws IOException
{
bw.flush();
be.flush();
}
public void err(String s) throws IOException
{
be.write(s);
be.flush();
}
}
static class Pair
{
int a, b;
Pair(int x, int y)
{
a = x;
b = y;
}
public int hashCode()
{
return a^b;
}
public boolean equals(Object obj)
{
Pair that = (Pair)obj;
return a == that.a && b == that.b;
}
}
static FastIO f;
static HashMap<Pair, Integer> h;
public static void main(String args[]) throws IOException
{
f = new FastIO();
int n, ans, smax;
h = new HashMap<>();
n = f.ni();
smax = getSMax(1, n);
ans = (n == 2) ? (smax == 1) ? 2 : 1 : (smax == 1 || (smax != n && smax == getSMax(smax, n))) ? getRB(smax+1, n, smax) : getLB(1, smax-1, smax);
f.out("! " + ans + "\n");
}
public static int getLB(int s, int e, int sm) throws IOException
{
if(e == s)
return s;
if(e == s+1)
return (getSMax(e, sm) == sm) ? e : s;
int mid = s + (e-s)/2;
int s1 = getSMax(mid+1, sm);
if(s1 == sm)
return getLB(mid+1, e, sm);
return getLB(s, mid, sm);
}
public static int getRB(int s, int e, int sm) throws IOException
{
if(e == s)
return s;
if(e == s+1)
return (getSMax(sm, s) == sm) ? s : e;
int mid = s + (e-s)/2;
int s1 = getSMax(sm, mid);
if(s1 == sm)
return getRB(s, mid, sm);
return getRB(mid+1, e, sm);
}
public static int getMax(int l, int r, int sm) throws IOException
{
if(r == l+1)
return (sm == l) ? r : l;
if(r == l+2)
{
int a = getMax(l, l+1, getSMax(l, l+1)), b = getMax(l+1, r, getSMax(l+1, r));
return (a == b || b == sm) ? a : b;
}
int mid = l + (r-l)/2;
if(sm <= mid)
{
int sm1 = getSMax(l, mid);
if(sm1 == sm)
return getMax(l, mid, sm1);
return getMax(mid+1, r, getSMax(mid+1, r));
}
else
{
int sm2 = getSMax(mid+1, r);
if(sm2 == sm)
return getMax(mid+1, r, sm2);
return getMax(l, mid, getSMax(l, mid));
}
}
public static int getSMax(int l, int r) throws IOException
{
Pair p = new Pair(l, r);
if(h.containsKey(p))
return h.get(p);
f.out("? " + l + " " + r + "\n");
int ans = f.ni();
h.put(p, ans);
return ans;
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
eb660c470760117dfd0b95acc10eee3b
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,900
| null |
standard output
| |
PASSED
|
78512d563b13354ac83aa58e285c9fc6
|
train_109.jsonl
|
1613658900
|
The only difference between the easy and the hard version is the limit to the number of queries.This is an interactive problem.There is an array $$$a$$$ of $$$n$$$ different numbers. In one query you can ask the position of the second maximum element in a subsegment $$$a[l..r]$$$. Find the position of the maximum element in the array in no more than 20 queries.A subsegment $$$a[l..r]$$$ is all the elements $$$a_l, a_{l + 1}, ..., a_r$$$. After asking this subsegment you will be given the position of the second maximum from this subsegment in the whole array.
|
256 megabytes
|
import static java.lang.Math.max;
import static java.lang.Math.min;
import static java.lang.Math.abs;
import java.io.*;
import java.util.*;
public class B
{
static int n;
static int[] arr;
static char[] s;
public static void main(String[] args) throws IOException
{
f = new Flash();
out = new PrintWriter(System.out);
int T = 1; //ni();
for(int tc = 1; tc <= T; tc++){
n = ni(); fn();
}
out.flush(); out.close();
}
static void fn()
{
//we cannot query [L, L] or [R, R]
int pos = query(1, n);
int left = 1;
if(pos > 1) left = query(1, pos);
int right = n;
if(pos < n) right = query(pos, n);
if(left == pos && pos > 1) {
int l = 1, r = pos-1;
while(l < r) {
int mid = l + (r - l + 1) / 2;
if(query(mid, pos) == pos) l = mid;
else r = mid - 1;
}
sop("! " + l);
}
else {
int l = pos+1, r = n;
while(l < r) {
int mid = l + (r - l) / 2;
if(query(pos, mid) == pos) r = mid;
else l = mid + 1;
}
sop("! " + l);
}
}
static int query(int l, int r) {
sop("? " + l + " " + r);
out.flush();
return ni();
}
static Flash f;
static PrintWriter out;
static final long mod = (long)1e9+7;
static final long inf = Long.MAX_VALUE;
static final int _inf = Integer.MAX_VALUE;
static final int maxN = (int)5e5+5;
static long[] fact, inv;
static void sort(int[] a){
List<Integer> A = new ArrayList<>();
for(int i : a) A.add(i);
Collections.sort(A);
for(int i = 0; i < A.size(); i++) a[i] = A.get(i);
}
static void sort(long[] a){
List<Long> A = new ArrayList<>();
for(long i : a) A.add(i);
Collections.sort(A);
for(int i = 0; i < A.size(); i++) a[i] = A.get(i);
}
static void print(int[] a){
StringBuilder sb = new StringBuilder();
for(int i = 0; i < a.length; i++) sb.append(a[i] + " ");
sop(sb);
}
static void print(long[] a){
StringBuilder sb = new StringBuilder();
for(int i = 0; i < a.length; i++) sb.append(a[i] + " ");
sop(sb);
}
static int swap(int itself, int dummy){return itself;}
static long swap(long itself, long dummy){return itself;}
static void sop(Object o){out.println(o);}
static int ni(){return f.ni();}
static long nl(){return f.nl();}
static double nd(){return f.nd();}
static String next(){return f.next();}
static String ns(){return f.ns();}
static char[] nc(){return f.nc();}
static int[] arr(int len){return f.arr(len);}
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 lcm(int a, int b){return (a*b)/gcd(a, b);}
static long lcm(long a, long b){return (a*b)/gcd(a, b);}
static class Flash
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer("");
String next(){
while(!st.hasMoreTokens()){
try{
st = new StringTokenizer(br.readLine());
}catch(IOException e){
e.printStackTrace();
}
}
return st.nextToken();
}
String ns(){
String s = new String();
try{
s = br.readLine().trim();
}catch(IOException e){
e.printStackTrace();
}
return s;
}
int[] arr(int n){
int[] a = new int[n];
for(int i = 0; i < n; i++) a[i] = ni();
return a;
}
char[] nc(){return ns().toCharArray();}
int ni(){return Integer.parseInt(next());}
long nl(){return Long.parseLong(next());}
double nd(){return Double.parseDouble(next());}
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
eb660c470760117dfd0b95acc10eee3b
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,900
| null |
standard output
| |
PASSED
|
56792dbec1d9d5217b8b4a8a7b30a43e
|
train_109.jsonl
|
1613658900
|
The only difference between the easy and the hard version is the limit to the number of queries.This is an interactive problem.There is an array $$$a$$$ of $$$n$$$ different numbers. In one query you can ask the position of the second maximum element in a subsegment $$$a[l..r]$$$. Find the position of the maximum element in the array in no more than 20 queries.A subsegment $$$a[l..r]$$$ is all the elements $$$a_l, a_{l + 1}, ..., a_r$$$. After asking this subsegment you will be given the position of the second maximum from this subsegment in the whole array.
|
256 megabytes
|
import java.util.*;
import java.io.*;
public class cf {
static Reader sc = new Reader();
// static Scanner sc = new Scanner(System.in);
static PrintWriter out = new PrintWriter(System.out);
public static void main(String[] args) {
int n = sc.nextInt();
int ans = -1;
int index = query(1, n);
if (index == 1 || query(1, index) != index) {
ans = n;
// binary search
int l = index, r = n;
while (l < r) {
int mid = l + (r - l) / 2;
if (l + 1 == r) {
if (l > index && query(index, l) == index) {
ans = l;
} else {
ans = r;
}
break;
}
if (index == mid)
break;
if (query(index, mid) == index) {
ans = mid;
r = mid;
} else {
l = mid;
}
}
} else {
ans = 1;
// binary search
int l = 1, r = index;
while (l < r) {
int mid = l + (r - l) / 2;
if (l + 1 == r) {
if (r < index && query(r, index) == index) {
ans = r;
} else {
ans = l;
}
break;
}
if (index == mid)
break;
if (query(mid, index) == index) {
ans = mid;
l = mid;
} else {
r = mid;
}
}
}
out.println("! " + ans);
out.close();
}
private static int query(int x, int y) {
out.println("? " + x + " " + y);
out.flush();
return sc.nextInt();
}
static class Reader {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer("");
String next() {
while (!st.hasMoreTokens())
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
eb660c470760117dfd0b95acc10eee3b
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,900
| null |
standard output
| |
PASSED
|
489c8a9ee001a1f90d7a7160e4db2131
|
train_109.jsonl
|
1613658900
|
The only difference between the easy and the hard version is the limit to the number of queries.This is an interactive problem.There is an array $$$a$$$ of $$$n$$$ different numbers. In one query you can ask the position of the second maximum element in a subsegment $$$a[l..r]$$$. Find the position of the maximum element in the array in no more than 20 queries.A subsegment $$$a[l..r]$$$ is all the elements $$$a_l, a_{l + 1}, ..., a_r$$$. After asking this subsegment you will be given the position of the second maximum from this subsegment in the whole array.
|
256 megabytes
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Random;
import java.util.StringTokenizer;
public final class C {
public static void main(String[] args) {
final FastScanner fs = new FastScanner();
final int n = fs.nextInt();
final int res1 = query(0, n - 1, fs);
final boolean left = query(0, res1, fs) == res1;
int lo, hi;
if (left) {
lo = 0;
hi = res1;
// upperBound
while (lo < hi) {
final int mid = lo + hi + 1 >>> 1;
if (query(mid, res1, fs) == res1) {
lo = mid;
} else {
hi = mid - 1;
}
}
} else {
lo = res1;
hi = n - 1;
// lowerBound
while (lo < hi) {
final int mid = lo + hi >>> 1;
if (query(res1, mid, fs) != res1) {
lo = mid + 1;
} else {
hi = mid;
}
}
}
System.out.println("! " + (lo + 1));
System.out.close();
}
private static int query(int low, int high, FastScanner fs) {
if (low == high) {
return -1;
}
low++;
high++;
System.out.println("? " + low + ' ' + high);
return fs.nextInt() - 1;
}
static final class Utils {
public static void shuffleSort(int[] x) {
shuffle(x);
Arrays.sort(x);
}
public static void shuffleSort(long[] x) {
shuffle(x);
Arrays.sort(x);
}
public static void shuffle(int[] x) {
final Random r = new Random();
for (int i = 0; i <= x.length - 2; i++) {
final int j = i + r.nextInt(x.length - i);
swap(x, i, j);
}
}
public static void shuffle(long[] x) {
final Random r = new Random();
for (int i = 0; i <= x.length - 2; i++) {
final int j = i + r.nextInt(x.length - i);
swap(x, i, j);
}
}
public static void swap(int[] x, int i, int j) {
final int t = x[i];
x[i] = x[j];
x[j] = t;
}
public static void swap(long[] x, int i, int j) {
final long t = x[i];
x[i] = x[j];
x[j] = t;
}
private Utils() {}
}
static class FastScanner {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer("");
private String next() {
while (!st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
//noinspection CallToPrintStackTrace
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
int[] nextIntArray(int n) {
final int[] a = new int[n];
for (int i = 0; i < n; i++) { a[i] = nextInt(); }
return a;
}
long[] nextLongArray(int n) {
final long[] a = new long[n];
for (int i = 0; i < n; i++) { a[i] = nextLong(); }
return a;
}
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
eb660c470760117dfd0b95acc10eee3b
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,900
| null |
standard output
| |
PASSED
|
6a6aa473b68ecb135f8cd6de7c6263ff
|
train_109.jsonl
|
1613658900
|
The only difference between the easy and the hard version is the limit to the number of queries.This is an interactive problem.There is an array $$$a$$$ of $$$n$$$ different numbers. In one query you can ask the position of the second maximum element in a subsegment $$$a[l..r]$$$. Find the position of the maximum element in the array in no more than 20 queries.A subsegment $$$a[l..r]$$$ is all the elements $$$a_l, a_{l + 1}, ..., a_r$$$. After asking this subsegment you will be given the position of the second maximum from this subsegment in the whole array.
|
256 megabytes
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Random;
import java.util.StringTokenizer;
public final class C1 {
public static void main(String[] args) {
final FastScanner fs = new FastScanner();
final int n = fs.nextInt();
final int res1 = query(0, n - 1, fs);
final int res2 = query(0, res1, fs);
int lo;
int hi;
if (res2 == res1) {
lo = 0;
hi = res1;
while (lo < hi) {
final int mid = lo + hi + 1 >>> 1;
if (query(mid, res1, fs) == res1) {
lo = mid;
} else {
hi = mid - 1;
}
}
} else {
lo = res1;
hi = n - 1;
while (lo < hi) {
final int mid = lo + hi >>> 1;
if (query(res1, mid, fs) != res1) {
lo = mid + 1;
} else {
hi = mid;
}
}
}
System.out.println("! " + (lo + 1));
System.out.close();
}
private static int query(int low, int high, FastScanner fs) {
if (low == high) {
return -1;
}
low++;
high++;
System.out.println("? " + low + ' ' + high);
return fs.nextInt() - 1;
}
static final class Utils {
public static void shuffleSort(int[] x) {
shuffle(x);
Arrays.sort(x);
}
public static void shuffleSort(long[] x) {
shuffle(x);
Arrays.sort(x);
}
public static void shuffle(int[] x) {
final Random r = new Random();
for (int i = 0; i <= x.length - 2; i++) {
final int j = i + r.nextInt(x.length - i);
swap(x, i, j);
}
}
public static void shuffle(long[] x) {
final Random r = new Random();
for (int i = 0; i <= x.length - 2; i++) {
final int j = i + r.nextInt(x.length - i);
swap(x, i, j);
}
}
public static void swap(int[] x, int i, int j) {
final int t = x[i];
x[i] = x[j];
x[j] = t;
}
public static void swap(long[] x, int i, int j) {
final long t = x[i];
x[i] = x[j];
x[j] = t;
}
private Utils() {}
}
static class FastScanner {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer("");
private String next() {
while (!st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
//noinspection CallToPrintStackTrace
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
int[] nextIntArray(int n) {
final int[] a = new int[n];
for (int i = 0; i < n; i++) { a[i] = nextInt(); }
return a;
}
long[] nextLongArray(int n) {
final long[] a = new long[n];
for (int i = 0; i < n; i++) { a[i] = nextLong(); }
return a;
}
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
eb660c470760117dfd0b95acc10eee3b
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,900
| null |
standard output
| |
PASSED
|
4dd362e68aaaf512ce74ff315d1c794f
|
train_109.jsonl
|
1613658900
|
The only difference between the easy and the hard version is the limit to the number of queries.This is an interactive problem.There is an array $$$a$$$ of $$$n$$$ different numbers. In one query you can ask the position of the second maximum element in a subsegment $$$a[l..r]$$$. Find the position of the maximum element in the array in no more than 20 queries.A subsegment $$$a[l..r]$$$ is all the elements $$$a_l, a_{l + 1}, ..., a_r$$$. After asking this subsegment you will be given the position of the second maximum from this subsegment in the whole array.
|
256 megabytes
|
import java.io.*;
import java.util.*;
import java.math.*;
public class Solution{
public static void main(String[] args) {
TaskA solver = new TaskA();
// int t = in.nextInt();
// for (int i = 1; i <= t ; i++) {
// solver.solve(i, in, out);
// }
solver.solve(1, in, out);
out.flush();
out.close();
}
static class TaskA {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n= in.nextInt();boolean isL=false;boolean isR=false;
int smax=query(1,n);
if(smax==1) {
isR=true;
}
else {
int x=query(1,smax);
if(x==smax) {
isL=true;
}
else {
isR=true;
}
}
if(isL) {
int l=1;int r=smax;
while(r>l) {
if(l==smax-1) {
System.out.println("! "+(l));return;
}
int mid=(r+l)/2;
int x=query(mid,smax);
if(x==smax) {
l=mid+1;
}
else {
r=mid;
}
}
System.out.println("! "+(l-1));return;
}
else {
int l=smax;int r=n;
while(r>l) {
if(r==smax+1) {
System.out.println("! "+(r));return;
}
int mid=(r+l)/2;
int x=query(smax,mid);
if(x==smax) {
r=mid;
}
else {
l=mid+1;
}
}
System.out.println("! "+(r));return;
}
}
}
static int query(int l,int r) {
System.out.println("? "+l+" "+r);
System.out.print ("\n");
int x=in.nextInt();
return x;
}
static boolean check(Pair[]arr,int mid,int n) {
int c=0;
for(int i=0;i<n;i++) {
if(mid-1-arr[i].first<=c&&c<=arr[i].second) {
c++;
}
}
return c>=mid;
}
static long sum(int[]arr) {
long s=0;
for(int x:arr) {
s+=x;
}
return s;
}
static long sum(long[]arr) {
long s=0;
for(long x:arr) {
s+=x;
}
return s;
}
static int gcd(int a, int b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
static void sort(int[] a) {
ArrayList<Integer> q = new ArrayList<>();
for (int i : a) q.add(i);
Collections.sort(q);
for (int i = 0; i < a.length; i++) a[i] = q.get(i);
}
static void sort(long[] a) {
ArrayList<Long> q = new ArrayList<>();
for (long i : a) q.add(i);
Collections.sort(q);
for (int i = 0; i < a.length; i++) a[i] = q.get(i);
}
static void println(int[][]arr) {
for(int i=0;i<arr.length;i++) {
for(int j=0;j<arr[0].length;j++) {
print(arr[i][j]+" ");
}
print("\n");
}
}
static void println(long[][]arr) {
for(int i=0;i<arr.length;i++) {
for(int j=0;j<arr[0].length;j++) {
print(arr[i][j]+" ");
}
print("\n");
}
}
static void println(int[]arr){
for(int i=0;i<arr.length;i++) {
print(arr[i]+" ");
}
print("\n");
}
static void println(long[]arr){
for(int i=0;i<arr.length;i++) {
print(arr[i]+" ");
}
print("\n");
}
static long[]input(int n){
long[]arr=new long[n];
for(int i=0;i<n;i++) {
arr[i]=in.nextInt();
}
return arr;
}
static long[]input(){
long n= in.nextInt();
long[]arr=new long[(int)n];
for(int i=0;i<n;i++) {
arr[i]=in.nextLong();
}
return arr;
}
////////////////////////////////////////////////////////
static class Pair {
long first;
long second;
Pair(long x, long y)
{
this.first = x;
this.second = y;
}
}
static void sortS(Pair arr[])
{
Arrays.sort(arr, new Comparator<Pair>() {
@Override public int compare(Pair p1, Pair p2)
{
return (int)(p1.second - p2.second);
}
});
}
static void sortF(Pair arr[])
{
Arrays.sort(arr, new Comparator<Pair>() {
@Override public int compare(Pair p1, Pair p2)
{
return (int)(p1.first - p2.first);
}
});
}
/////////////////////////////////////////////////////////////
static InputStream inputStream = System.in;
static OutputStream outputStream = System.out;
static InputReader in = new InputReader(inputStream);
static PrintWriter out = new PrintWriter(outputStream);
static void println(long c) {
out.println(c);
}
static void print(long c) {
out.print(c);
}
static void print(int c) {
out.print(c);
}
static void println(int x) {
out.println(x);
}
static void print(String s) {
out.print(s);
}
static void println(String s) {
out.println(s);
}
static void println(boolean b) {
out.println(b);
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
eb660c470760117dfd0b95acc10eee3b
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,900
| null |
standard output
| |
PASSED
|
f2b017bd4d6000e0be09525df5b0fbf5
|
train_109.jsonl
|
1613658900
|
The only difference between the easy and the hard version is the limit to the number of queries.This is an interactive problem.There is an array $$$a$$$ of $$$n$$$ different numbers. In one query you can ask the position of the second maximum element in a subsegment $$$a[l..r]$$$. Find the position of the maximum element in the array in no more than 20 queries.A subsegment $$$a[l..r]$$$ is all the elements $$$a_l, a_{l + 1}, ..., a_r$$$. After asking this subsegment you will be given the position of the second maximum from this subsegment in the whole array.
|
256 megabytes
|
import java.io.*;
public class Main {
public static int[] a = new int[]{0, 4, 3, 2, 1, 5};
public static void main(String[] args) throws Exception{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int testCase = Integer.parseInt(in.readLine().trim());
int l = 1;
int r = testCase;
int smax = seclarge(in, l, r);
if (smax == l) {
l++;
} else if (smax == r) {
r--;
} else {
int smax2 = seclarge(in, smax, r);
if (smax2 == smax) {
l = smax + 1;
} else {
r = smax - 1;
}
}
while (l + 1 < r) {
int m = l + (r - l)/2;
int smax2 = 0;
if (smax <= m) {
smax2 = seclarge(in, smax, m);
if (smax2 == smax) {
r = m;
} else {
l = m + 1;
}
} else {
smax2 = seclarge(in, m, smax);
if (smax2 == smax) {
l = m;
} else {
r = m - 1;
}
}
}
int largest = 0;
if (smax < l) {
largest = seclarge(in, smax, l) == smax ? l : r;
} else {
largest = seclarge(in, r, smax) == smax ? r : l;
}
System.out.println("! " + largest);
System.out.flush();
}
public static int seclarge(BufferedReader in, int l, int r) throws Exception{
System.out.println("? " + l + " " + r);
System.out.flush();
int sec = Integer.parseInt(in.readLine().trim());
return sec;
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
eb660c470760117dfd0b95acc10eee3b
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,900
| null |
standard output
| |
PASSED
|
4c8b93b0877a77391d74ea47d9912a76
|
train_109.jsonl
|
1613658900
|
The only difference between the easy and the hard version is the limit to the number of queries.This is an interactive problem.There is an array $$$a$$$ of $$$n$$$ different numbers. In one query you can ask the position of the second maximum element in a subsegment $$$a[l..r]$$$. Find the position of the maximum element in the array in no more than 20 queries.A subsegment $$$a[l..r]$$$ is all the elements $$$a_l, a_{l + 1}, ..., a_r$$$. After asking this subsegment you will be given the position of the second maximum from this subsegment in the whole array.
|
256 megabytes
|
import java.io.*;
import java.util.*;
public class Solution {
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader(String s) {
try {
br = new BufferedReader(new FileReader(s));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String nextToken() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(nextToken());
}
String nextLine() throws IOException {
return br.readLine();
}
long nextLong() {
return Long.parseLong(nextToken());
}
double nextDouble() {
return Double.parseDouble(nextToken());
}
float nextFloat() {
return Float.parseFloat(nextToken());
}
}
static FastReader f = new FastReader();
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static StringTokenizer st;
static StringBuilder sb = new StringBuilder();
private static final int mod = (int) (1e9 + 7);
static int MAX = 500005;
static long[] fact;
static int[] inputArray(int n) throws IOException {
int[] a = new int[n];
for(int i = 0 ; i < n ; i++) {
// a[i] = (int) (Math.random()*1e5 + 1);
a[i] = f.nextInt();
}
return a;
}
static long[] inputLongArray(int n) throws IOException {
long[] a = new long[n];
for(int i = 0 ; i < n ; i++) {
a[i] = f.nextLong();
// a[i] = (long) (Math.random() * 1e9 + 1);
}
return a;
}
static long gcd(long a , long b) {
if(a == 0 || b == 0) {
return Math.max(a , b);
}
//System.out.println("a - " + a + " b - " + b);
if(a % b == 0) {
return b;
}
return gcd(b , a % b);
}
static void initializeFact() {
fact = new long[MAX];
for(int i = 0 ; i < fact.length ; i++) {
if(i == 0) {
fact[i] = 1;
}
else {
fact[i] = fact[i-1] * i % mod;
}
}
}
static long longModulus(long x , long m) {
if(x < m) {
return x;
}
long d = x / m;
return x - d * m;
}
static boolean[] sieveOfEratosthenes(int n)
{
boolean[] isPrime = new boolean[n+1];
Arrays.fill(isPrime , true);
isPrime[0] = false;
isPrime[1] = false;
for(int i = 2; i * i <= n ; i++)
{
for(int j = 2 * i ; j <= n; j += i)
isPrime[j] = false;
}
return isPrime;
}
static long moduloInversePrime(long a) {
//System.out.println("modulo inverse of " + a + " -> " + ans);
return modPow(a , mod - 2);
}
static long mult(long a, long b)
{
return (a * b % mod);
}
static long modPow(long a, int step)
{
long ans = 1;
while(step != 0)
{
if((step & 1) != 0)
ans = mult(ans , a);
a = mult(a , a);
step >>= 1;
}
return ans;
}
static boolean isPrime(int n) {
if(n == 1) {
return false;
}
for(int i = 2 ; i <= Math.sqrt(n) ; i++) {
if(n % i == 0) {
return false;
}
}
return true;
}
static int query(int l , int r) {
System.out.println("? " + l + " " + r);
System.out.flush();
return f.nextInt();
}
public static void main(String[] args) throws IOException {
int t = 1;
for(int test = 0 ; test < t ; test++) {
int n = f.nextInt();
int l = 1, r = n;
int m = query(l, r);
boolean left = false;
if(m != 1) {
int x = query(l, m);
if(x == m) {
r = m - 1;
left = true;
}
else {
l = m + 1;
}
}
else {
l = 2;
}
int ans = -1;
while(l <= r) {
int mid = (l+r) / 2;
// System.out.println("l: " + l + ", r: " + r + ", mid: " + mid);
if(left) {
int q = query(mid, m);
if(q == m) {
ans = mid;
l = mid + 1;
}
else {
r = mid - 1;
}
}
else {
int q = query(m, mid);
if(q == m) {
ans = mid;
r = mid - 1;
}
else {
l = mid + 1;
}
}
}
System.out.println("! " + ans);
System.out.flush();
}
}
private static int split(int[] a, int l, int r, long[] preSum) {
int low = l, high = r - 1;
while(low <= high) {
int mid = (low + high) / 2;
if(preSum[mid+1] - preSum[l] == preSum[r+1] - preSum[mid+1]) {
return mid;
}
else if(preSum[mid+1] - preSum[l] > preSum[r+1] - preSum[mid+1]) {
high = mid - 1;
}
else {
low = mid + 1;
}
}
return -1;
}
}
/*
*/
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
eb660c470760117dfd0b95acc10eee3b
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,900
| null |
standard output
| |
PASSED
|
034b06b58dd0ac9ba2a6caeee50ac6d6
|
train_109.jsonl
|
1613658900
|
The only difference between the easy and the hard version is the limit to the number of queries.This is an interactive problem.There is an array $$$a$$$ of $$$n$$$ different numbers. In one query you can ask the position of the second maximum element in a subsegment $$$a[l..r]$$$. Find the position of the maximum element in the array in no more than 20 queries.A subsegment $$$a[l..r]$$$ is all the elements $$$a_l, a_{l + 1}, ..., a_r$$$. After asking this subsegment you will be given the position of the second maximum from this subsegment in the whole array.
|
256 megabytes
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class C {
void solve() throws IOException {
int n = nextInt();
int begin = 1;
int end = n;
/*
5 1 3 4 2
1 2 3 4 5
2 1 3
5 1 4 2 3
5 4 3 2 1
*/
writer.println("? " + begin + " " + end);
writer.flush();
int secMax = nextInt();
boolean beginChanging = true;
if (secMax == 1) {
begin = 2;
end = n;
beginChanging = false;
} else if (secMax == n) {
begin = 1;
end = secMax - 1;
} else {
writer.println("? " + 1 + " " + secMax);
writer.flush();
int leftSecMax = nextInt();
if (leftSecMax == secMax) {
begin = 1;
end = secMax - 1;
} else {
beginChanging = false;
begin = secMax + 1;
end = n;
}
}
if (beginChanging) {
int lastGood = 0;
while (begin <= end) {
int mid = begin + (end - begin) / 2;
writer.println("? " + mid + " " + secMax);
writer.flush();
int newSecMax = nextInt();
if (secMax == newSecMax) {
lastGood = mid;
begin = mid + 1;
} else {
end = mid - 1;
}
}
writer.println("! " + lastGood);
} else {
int lastGood = 0;
while (begin <= end) {
int mid = begin + (end - begin) / 2;
writer.println("? " + secMax + " " + mid);
writer.flush();
int newSecMax = nextInt();
if (newSecMax == secMax) {
lastGood = mid;
end = mid - 1;
} else {
begin = mid + 1;
}
}
writer.println("! " + lastGood);
}
}
String nextToken() throws IOException {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
return tokenizer.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
StringTokenizer tokenizer;
PrintWriter writer;
BufferedReader reader;
public void run() {
try {
writer = new PrintWriter(System.out);
reader = new BufferedReader(new InputStreamReader(System.in));
solve();
reader.close();
writer.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new C().run();
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
eb660c470760117dfd0b95acc10eee3b
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,900
| null |
standard output
| |
PASSED
|
d6ffb983be6e26cb0d1e0474db26706e
|
train_109.jsonl
|
1613658900
|
The only difference between the easy and the hard version is the limit to the number of queries.This is an interactive problem.There is an array $$$a$$$ of $$$n$$$ different numbers. In one query you can ask the position of the second maximum element in a subsegment $$$a[l..r]$$$. Find the position of the maximum element in the array in no more than 20 queries.A subsegment $$$a[l..r]$$$ is all the elements $$$a_l, a_{l + 1}, ..., a_r$$$. After asking this subsegment you will be given the position of the second maximum from this subsegment in the whole array.
|
256 megabytes
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class CodeForces {
public static void main(String[] args) {
// TODO Auto-generated method stub
FastScanner fs=new FastScanner();
int n=fs.nextInt();
int pos=solve(n);
System.out.println("! "+(pos+1));
// System.out.println("No of queery = "+count);
}
private static int solve(int n) {
int smallx=query(0,n-1);
if(smallx==0||query(0,smallx)!=smallx) {
int l=smallx,r=n-1;
while(r-l>1) {
int mid=(l+r)/2;
if(query(smallx,mid)==smallx) {
r=mid;
}
else l=mid;
}
return r;
}
else {
int l=0,r=smallx;
while(r-l>1) {
int mid=(l+r)/2;
if(query(mid,smallx)==smallx) {
l=mid;
}
else r=mid;
}
return l;
}
}
private static int query(int l,int r) {
if(l>=r)
return -1;
System.out.println("? "+(l+1)+" "+(r+1));
FastScanner fs=new FastScanner();
int pos=fs.nextInt();
return pos-1;
}
static void mysort(int[] a) {
//ruffle
int n=a.length;
Random r=new Random();
for (int i=0; i<a.length; i++) {
int oi=r.nextInt(n), temp=a[i];
a[i]=a[oi];
a[oi]=temp;
}
//then sort
Arrays.sort(a);
}
// Use this to input code since it is faster than a Scanner
static class FastScanner {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st=new StringTokenizer("");
String next() {
while (!st.hasMoreTokens())
try {
st=new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
int[] readArray(int n) {
int[] a=new int[n];
for (int i=0; i<n; i++) a[i]=nextInt();
return a;
}
long nextLong() {
return Long.parseLong(next());
}
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
eb660c470760117dfd0b95acc10eee3b
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,900
| null |
standard output
| |
PASSED
|
62098d7f6649049ae99a01475f85f6f4
|
train_109.jsonl
|
1613658900
|
The only difference between the easy and the hard version is the limit to the number of queries.This is an interactive problem.There is an array $$$a$$$ of $$$n$$$ different numbers. In one query you can ask the position of the second maximum element in a subsegment $$$a[l..r]$$$. Find the position of the maximum element in the array in no more than 20 queries.A subsegment $$$a[l..r]$$$ is all the elements $$$a_l, a_{l + 1}, ..., a_r$$$. After asking this subsegment you will be given the position of the second maximum from this subsegment in the whole array.
|
256 megabytes
|
// c1
import java.util.*;
// import java.lang.*;
import java.io.*;
// THIS TEMPLATE MADE BY AKSH BANSAL.
public class Solution {
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
public static void main(String[] args) throws IOException {
FastReader sc = new FastReader();
PrintWriter out = new PrintWriter(System.out);
// ________________________________
int n= sc.nextInt();
if(n==1){
out.println("! 1");
out.flush();
return;
}
int start = 1, end = n;
int pos = query(start, end, out, sc);
if(pos>1 && query(1,pos,out,sc)==pos){
end = pos-1;
}else{
start = pos+1;
}
while(start<end){
int mid = start+(end-start)/2;
if(start+1==end){
pos = query(start,end,out,sc);
if(pos==start){
start = end;
}
break;
}
// checking sub section
if(pos>=mid){
int cur = query(mid, pos, out, sc);
if(cur==pos){
start = mid;
}
else {
end = mid-1;
}
}
else{
int cur = query(pos, mid, out, sc);
if(cur==pos){
end = mid;
}
else {
start = mid+1;
}
}
}
out.println("! "+start);
out.flush();
}
private static int query(int start, int end, PrintWriter out, FastReader sc) {
out.println("? "+start+" "+end);
out.flush();
int res= sc.nextInt();
return res;
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
eb660c470760117dfd0b95acc10eee3b
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,900
| null |
standard output
| |
PASSED
|
99c47dc4a57585d46d7081ee4841c137
|
train_109.jsonl
|
1613658900
|
The only difference between the easy and the hard version is the limit to the number of queries.This is an interactive problem.There is an array $$$a$$$ of $$$n$$$ different numbers. In one query you can ask the position of the second maximum element in a subsegment $$$a[l..r]$$$. Find the position of the maximum element in the array in no more than 20 queries.A subsegment $$$a[l..r]$$$ is all the elements $$$a_l, a_{l + 1}, ..., a_r$$$. After asking this subsegment you will be given the position of the second maximum from this subsegment in the whole array.
|
256 megabytes
|
import java.util.*;
public class Q1486C {
static Scanner s = new Scanner(System.in);
public static void main(String args[])
{
int r = s.nextInt();
System.out.println("? 1 " + r);
System.out.flush();
int k = s.nextInt();
if(r==2)
{
System.out.println("! " + (3-k));
return;
}
if(k!=1)
{
System.out.println("? 1 " + k);
System.out.flush();
if(s.nextInt()==k) solvel(1,k-1,k);
else solver(k+1,r,k);
}
else solver(1,r,1);
}
public static void solvel(int l, int r, int k)
{
if(l==r)
{
System.out.println("! " + l);
return;
}
int m = (l+r+1)/2;
System.out.println("? " + m + " " + k);
System.out.flush();
if(s.nextInt()==k)
{
solvel(m,r,k);
}
else
{
solvel(l,m-1,k);
}
}
public static void solver(int l, int r, int k)
{
if(l==r)
{
System.out.println("! " + l);
return;
}
int m = (l+r)/2;
System.out.println("? " + k + " " + m);
System.out.flush();
if(s.nextInt()==k)
{
solver(l,m,k);
}
else
{
solver(m+1,r,k);
}
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
eb660c470760117dfd0b95acc10eee3b
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,900
| null |
standard output
| |
PASSED
|
045aeed6392a7eaeba45774544f7c5c8
|
train_109.jsonl
|
1613658900
|
The only difference between the easy and the hard version is the limit to the number of queries.This is an interactive problem.There is an array $$$a$$$ of $$$n$$$ different numbers. In one query you can ask the position of the second maximum element in a subsegment $$$a[l..r]$$$. Find the position of the maximum element in the array in no more than 20 queries.A subsegment $$$a[l..r]$$$ is all the elements $$$a_l, a_{l + 1}, ..., a_r$$$. After asking this subsegment you will be given the position of the second maximum from this subsegment in the whole array.
|
256 megabytes
|
import java.io.*;
import java.util.*;
public class GuessingTheGreatest2 {
static FastScanner fs;
static FastWriter fw;
static boolean checkOnlineJudge = System.getProperty("ONLINE_JUDGE") == null;
private static final int iMax = (int) (1e9), iMin = (int) (-1e9);
private static final long lMax = (int) (1e15), lMin = (int) (-1e15);
private static final int mod = (int) (1e9 + 7);
public static void main(String[] args) throws IOException {
fs = new FastScanner();
fw = new FastWriter();
int t = 1;
//t = fs.nextInt();
while (t-- > 0) {
solve();
}
fw.out.close();
}
private static void solve() {
int n = fs.nextInt();
int l = 1, r = n;
char side;
int idx = ask(1, n);
if (idx == 1) {
side = 'l';
} else if (idx == n) {
side = 'r';
} else {
int temp = ask(1, idx);
if (temp == idx) {
r = idx;
side = 'r';
} else {
l = idx;
side = 'l';
}
}
while (r - l > 1) {
int mid = l + ((r - l) / 2);
if (side == 'r') {
int temp = ask(mid, idx);
if (temp == idx)
l = mid;
else
r = mid;
} else {
int temp = ask(idx, mid);
if (temp == idx)
r = mid;
else
l = mid;
}
}
int temp = ask(l, r);
if (temp == l)
fw.out.println("! " + r);
else
fw.out.println("! " + l);
}
private static int ask(int l, int r) {
fw.out.println("? " + l + " " + r);
fw.out.flush();
return fs.nextInt();
}
private static class UnionFind {
private final int[] parent;
UnionFind(int n) {
parent = new int[n];
for (int i = 0; i < n; i++)
parent[i] = i;
}
private int getParent(int i) {
if (parent[i] == i)
return i;
return parent[i] = getParent(parent[i]);
}
private void unify(int i, int j) {
int p1 = getParent(i);
int p2 = getParent(j);
if (p1 != p2)
parent[p1] = p2;
}
}
private static int gcd(int a, int b) {
return (b == 0 ? a : gcd(b, a % b));
}
private static long pow(long a, long b) {
long result = 1;
while (b > 0) {
if ((b & 1L) == 1) {
result = (result * a) % mod;
}
a = (a * a) % mod;
b >>= 1;
}
return result;
}
private static int ceilDiv(int a, int b) {
return ((a + b - 1) / b);
}
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 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 <T> void randomizeArr(T[] arr, int n) {
Random r = new Random();
for (int i = (n - 1); i > 0; i--) {
int j = r.nextInt(i + 1);
swap(arr, i, j);
}
}
private static Integer[] readIntArray(int n) {
Integer[] arr = new Integer[n];
for (int i = 0; i < n; i++)
arr[i] = fs.nextInt();
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 <T> void swap(T[] arr, int i, int j) {
T temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
private static <T> void displayArr(T[] arr) {
for (T x : arr)
fw.out.print(x + " ");
fw.out.println();
}
private static <T> void displayList(List<T> list) {
for (T x : list)
fw.out.print(x + " ");
fw.out.println();
}
private static class FastScanner {
BufferedReader br;
StringTokenizer st;
FastScanner() throws IOException {
if (checkOnlineJudge)
this.br = new BufferedReader(new FileReader("src/input.txt"));
else
this.br = new BufferedReader(new InputStreamReader(System.in));
this.st = new StringTokenizer("");
}
public String next() {
while (!st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException err) {
err.printStackTrace();
}
}
return st.nextToken();
}
public String nextLine() {
if (st.hasMoreTokens()) {
return st.nextToken("").trim();
}
try {
return br.readLine().trim();
} catch (IOException err) {
err.printStackTrace();
}
return "";
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
private static class FastWriter {
PrintWriter out;
FastWriter() throws IOException {
if (checkOnlineJudge)
out = new PrintWriter(new FileWriter("src/output.txt"));
else
out = new PrintWriter(System.out);
}
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
eb660c470760117dfd0b95acc10eee3b
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,900
| null |
standard output
| |
PASSED
|
880fa225b71690a8d64c7f5215a9d1c5
|
train_109.jsonl
|
1613658900
|
The only difference between the easy and the hard version is the limit to the number of queries.This is an interactive problem.There is an array $$$a$$$ of $$$n$$$ different numbers. In one query you can ask the position of the second maximum element in a subsegment $$$a[l..r]$$$. Find the position of the maximum element in the array in no more than 20 queries.A subsegment $$$a[l..r]$$$ is all the elements $$$a_l, a_{l + 1}, ..., a_r$$$. After asking this subsegment you will be given the position of the second maximum from this subsegment in the whole array.
|
256 megabytes
|
/*
TO LEARN
2-euler tour
*/
/*
TO SOLVE
codeforces 722 kavi on pairing duty
*/
/*
bit manipulation shit
1-Computer Systems: A Programmer's Perspective
2-hacker's delight
3-(02-03-bits-ints)
4-machine-basics
5-Bits Manipulation tutorialspoint
*/
/*
TO WATCH
*/
import java.util.*;
import java.math.*;
import java.io.*;
import java.util.stream.Collectors;
public class B{
static FastScanner scan=new FastScanner();
public static PrintWriter out = new PrintWriter (new BufferedOutputStream(System.out));
static int ask(int l,int r)
{
System.out.println("? "+l+" "+r);
return scan.nextInt();
}
public static void main(String[] args) throws Exception
{
// scan=new FastScanner("D:\\usaco test data\\W.txt");
// out = new PrintWriter("D:\\usaco test data\\WW.txt");
/*
READING
3-Introduction to DP with Bitmasking codefoces
4-Bit Manipulation hackerearth
5-read more about mobious and inculsion-exclusion
*/
/*
if it has no Xs or Os then the answer is 0
*/
int tt=1;
//tt=scan.nextInt();
int T=1;
//System.out.println(8|9);
outer:while(tt-->0)
{
int n=scan.nextInt();
int idx=ask(1,n);
int second=-1,first=-1;
if(idx!=n)
first=ask(idx,n);
if(1!=idx) second=ask(1,idx);
int l=-1,r=-1;
if(first==idx)
{
l=idx;
r=n;
l++;
int ans=-1;
while(l<=r)
{
int mid=(l+r)/2;
int as=ask(idx,mid);
if(as==idx)
{
ans=mid;
r=mid-1;
}
else l=mid+1;
}
out.println("! "+ans);
}
else
{
l=1;
r=idx;
r--;
int ans=-1;
while(l<=r)
{
int mid=(l+r)/2;
int as=ask(mid,idx);
if(as==idx)
{
ans=mid;
l=mid+1;
}
else r=mid-1;
}
out.println("! "+ans);
}
}
out.close();
}
static long binexp(long a,long n)
{
if(n==0)
return 1;
long res=binexp(a,n/2);
if(n%2==1)
return res*res*a;
else
return res*res;
}
static long powMod(long base, long exp, long mod) {
if (base == 0 || base == 1) return base;
if (exp == 0) return 1;
if (exp == 1) return (base % mod+mod)%mod;
long R = (powMod(base, exp/2, mod) % mod+mod)%mod;
R *= R;
R %= mod;
if ((exp & 1) == 1) {
return (base * R % mod+mod)%mod;
}
else return (R %mod+mod)%mod;
}
static double dis(double x1,double y1,double x2,double y2)
{
return Math.sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2));
}
static long mod(long x,long y)
{
if(x<0)
x=x+(-x/y+1)*y;
return x%y;
}
public static long pow(long b, long e) {
long r = 1;
while (e > 0) {
if (e % 2 == 1) r = r * b ;
b = b * b;
e >>= 1;
}
return r;
}
private static void sort(long[] arr) {
List<Long> list = new ArrayList<>();
for (long object : arr) list.add(object);
Collections.sort(list);
//Collections.reverse(list);
for (int i = 0; i < list.size(); ++i) arr[i] = list.get(i);
}
private static void sort2(long[] arr) {
List<Long> list = new ArrayList<>();
for (Long object : arr) list.add(object);
Collections.sort(list);
Collections.reverse(list);
for (int i = 0; i < list.size(); ++i) arr[i] = list.get(i);
}
static class FastScanner
{
private int BS = 1 << 16;
private char NC = (char) 0;
private byte[] buf = new byte[BS];
private int bId = 0, size = 0;
private char c = NC;
private double cnt = 1;
private BufferedInputStream in;
public FastScanner() {
in = new BufferedInputStream(System.in, BS);
}
public FastScanner(String s) {
try {
in = new BufferedInputStream(new FileInputStream(new File(s)), BS);
} catch (Exception e) {
in = new BufferedInputStream(System.in, BS);
}
}
private char getChar() {
while (bId == size) {
try {
size = in.read(buf);
} catch (Exception e) {
return NC;
}
if (size == -1) return NC;
bId = 0;
}
return (char) buf[bId++];
}
public int nextInt() {
return (int) nextLong();
}
public int[] nextInts(int N) {
int[] res = new int[N];
for (int i = 0; i < N; i++) {
res[i] = (int) nextLong();
}
return res;
}
public long[] nextLongs(int N) {
long[] res = new long[N];
for (int i = 0; i < N; i++) {
res[i] = nextLong();
}
return res;
}
public long nextLong() {
cnt = 1;
boolean neg = false;
if (c == NC) c = getChar();
for (; (c < '0' || c > '9'); c = getChar()) {
if (c == '-') neg = true;
}
long res = 0;
for (; c >= '0' && c <= '9'; c = getChar()) {
res = (res << 3) + (res << 1) + c - '0';
cnt *= 10;
}
return neg ? -res : res;
}
public double nextDouble() {
double cur = nextLong();
return c != '.' ? cur : cur + nextLong() / cnt;
}
public double[] nextDoubles(int N) {
double[] res = new double[N];
for (int i = 0; i < N; i++) {
res[i] = nextDouble();
}
return res;
}
public String next() {
StringBuilder res = new StringBuilder();
while (c <= 32) c = getChar();
while (c > 32) {
res.append(c);
c = getChar();
}
return res.toString();
}
public String nextLine() {
StringBuilder res = new StringBuilder();
while (c <= 32) c = getChar();
while (c != '\n') {
res.append(c);
c = getChar();
}
return res.toString();
}
public boolean hasNext() {
if (c > 32) return true;
while (true) {
c = getChar();
if (c == NC) return false;
else if (c > 32) return true;
}
}
}
static class Pair implements Comparable<Pair>{
public long x, y,z;
public Pair(long x1, long y1,long z1) {
x=x1;
y=y1;
z=z1;
}
public Pair(long x1, long y1) {
x=x1;
y=y1;
}
@Override
public int hashCode() {
return (int)(x + 31 * y);
}
public String toString() {
return x + " " + y+" "+z;
}
@Override
public boolean equals(Object o){
if (o == this) return true;
if (o.getClass() != getClass()) return false;
Pair t = (Pair)o;
return t.x == x && t.y == y&&t.z==z;
}
public int compareTo(Pair o)
{
return (int)(z-o.z);
}
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
eb660c470760117dfd0b95acc10eee3b
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,900
| null |
standard output
| |
PASSED
|
dc9938aa6b7b91356b061aa85ec25da3
|
train_109.jsonl
|
1613658900
|
The only difference between the easy and the hard version is the limit to the number of queries.This is an interactive problem.There is an array $$$a$$$ of $$$n$$$ different numbers. In one query you can ask the position of the second maximum element in a subsegment $$$a[l..r]$$$. Find the position of the maximum element in the array in no more than 20 queries.A subsegment $$$a[l..r]$$$ is all the elements $$$a_l, a_{l + 1}, ..., a_r$$$. After asking this subsegment you will be given the position of the second maximum from this subsegment in the whole array.
|
256 megabytes
|
//https://codeforces.com/contest/1486/problem/C2
//C2. Guessing the Greatest (hard version)
import java.util.*;
import java.io.*;
public class CF_1486_C2{
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static PrintWriter pw = new PrintWriter(new OutputStreamWriter(System.out));
static int ask(int l, int r) throws Exception{
if(l==r)
return -1;
pw.print("? "+l+" "+r+"\n");
pw.flush();
return Integer.parseInt(br.readLine());
}
public static void main(String[] args) throws Exception{
int n = Integer.parseInt(br.readLine());
int l = 1, r = n;
int sm = ask(l, r);
if(sm==ask(l, sm))
r = sm-1;
else
l = sm+1;
while(r-l>1){
int mid = (r+l)>>1;
if(mid>sm){
if(ask(sm, mid)==sm)
r = mid;
else
l = mid+1;
}
else{
if(ask(mid, sm)==sm)
l = mid;
else
r = mid-1;
}
}
int ans = l;
if(r-l==1){
if(sm>r){
if(ask(r, sm)==sm)
ans = r;
else
ans = l;
}
else{
if(ask(sm, l)==sm)
ans = l;
else
ans = r;
}
}
pw.print("! "+ans);
pw.flush();
pw.close();
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
eb660c470760117dfd0b95acc10eee3b
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,900
| null |
standard output
| |
PASSED
|
0293554d38b5805c08a841e21596d726
|
train_109.jsonl
|
1613658900
|
The only difference between the easy and the hard version is the limit to the number of queries.This is an interactive problem.There is an array $$$a$$$ of $$$n$$$ different numbers. In one query you can ask the position of the second maximum element in a subsegment $$$a[l..r]$$$. Find the position of the maximum element in the array in no more than 20 queries.A subsegment $$$a[l..r]$$$ is all the elements $$$a_l, a_{l + 1}, ..., a_r$$$. After asking this subsegment you will be given the position of the second maximum from this subsegment in the whole array.
|
256 megabytes
|
/*input
*/
import java.util.*;
import java.lang.*;
import java.io.*;
public class Main
{
static PrintWriter out;
static int MOD = 1000000007;
static FastReader scan;
/*-------- I/O using short named function ---------*/
public static String ns(){return scan.next();}
public static int ni(){return scan.nextInt();}
public static long nl(){return scan.nextLong();}
public static double nd(){return scan.nextDouble();}
public static String nln(){return scan.nextLine();}
public static void p(Object o){out.print(o);}
public static void ps(Object o){out.print(o + " ");}
public static void pn(Object o){out.println(o);}
/*-------- for output of an array ---------------------*/
static void iPA(int arr []){
StringBuilder output = new StringBuilder();
for(int i=0; i<arr.length; i++)output.append(arr[i] + " ");out.println(output);
}
static void lPA(long arr []){
StringBuilder output = new StringBuilder();
for(int i=0; i<arr.length; i++)output.append(arr[i] + " ");out.println(output);
}
static void sPA(String arr []){
StringBuilder output = new StringBuilder();
for(int i=0; i<arr.length; i++)output.append(arr[i] + " ");out.println(output);
}
static void dPA(double arr []){
StringBuilder output = new StringBuilder();
for(int i=0; i<arr.length; i++)output.append(arr[i] + " ");out.println(output);
}
/*-------------- for input in an array ---------------------*/
static void iIA(int arr[]){
for(int i=0; i<arr.length; i++)arr[i] = ni();
}
static void lIA(long arr[]){
for(int i=0; i<arr.length; i++)arr[i] = nl();
}
static void sIA(String arr[]){
for(int i=0; i<arr.length; i++)arr[i] = ns();
}
static void dIA(double arr[]){
for(int i=0; i<arr.length; i++)arr[i] = nd();
}
/*------------ for taking input faster ----------------*/
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;
}
}
// Method to check if x is power of 2
static boolean isPowerOfTwo (int x) { return x!=0 && ((x&(x-1)) == 0);}
//Method to return lcm of two numbers
static int gcd(int a, int b){return a==0?b:gcd(b % a, a); }
//Method to count digit of a number
static int countDigit(long n){return (int)Math.floor(Math.log10(n) + 1);}
//Method for sorting
static void ruffle_sort(int[] a) {
//shandom_ruffle
Random r=new Random();
int n=a.length;
for (int i=0; i<n; i++) {
int oi=r.nextInt(n);
int temp=a[i];
a[i]=a[oi];
a[oi]=temp;
}
//sort
Arrays.sort(a);
}
//Method for checking if a number is prime or not
static boolean isPrime(int n) {
if (n <= 1) return false;
if (n <= 3) return true;
if (n % 2 == 0 || n % 3 == 0) return false;
for (int i = 5; i * i <= n; i = i + 6)
if (n % i == 0 || n % (i + 2) == 0)
return false;
return true;
}
public static void main (String[] args) throws java.lang.Exception
{
OutputStream outputStream =System.out;
out =new PrintWriter(outputStream);
scan =new FastReader();
//for fast output sometimes
StringBuilder sb = new StringBuilder();
int t = 1;
while(t-->0){
int n = ni();
int smax = askQuery(1, n);
if(smax == 1 || askQuery(1, smax) != smax){
int l = smax, r = n;
while(r - l > 1){
int mid = (l + r)/2;
if(askQuery(smax, mid) == smax){
r = mid;
}else{
l = mid;
}
}
pn("! " + r);
}else{
int l = 1, r = smax;
while(r - l > 1){
int mid = (l + r)/2;
if(askQuery(mid, smax) == smax){
l = mid;
}else{
r = mid;
}
}
pn("! " + l);
}
}
out.flush();
out.close();
}
static int askQuery(int l, int r){
pn("? " + l + " " + r);
out.flush();
return ni();
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
eb660c470760117dfd0b95acc10eee3b
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,900
| null |
standard output
| |
PASSED
|
ee39c86d4a1355d5e628d2d2fd8b1070
|
train_109.jsonl
|
1613658900
|
The only difference between the easy and the hard version is the limit to the number of queries.This is an interactive problem.There is an array $$$a$$$ of $$$n$$$ different numbers. In one query you can ask the position of the second maximum element in a subsegment $$$a[l..r]$$$. Find the position of the maximum element in the array in no more than 20 queries.A subsegment $$$a[l..r]$$$ is all the elements $$$a_l, a_{l + 1}, ..., a_r$$$. After asking this subsegment you will be given the position of the second maximum from this subsegment in the whole array.
|
256 megabytes
|
import java.io.*;
import java.util.*;
public class Solution
{
public static void main(String args[]) throws Exception
{
BufferedReader Rb = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.valueOf(Rb.readLine());
int l = 1, r = n;
System.out.println("? " + l + " " + r);
System.out.flush();
int pos = Integer.valueOf(Rb.readLine());
System.out.println("? " + (pos!=l?l:pos) + " " + (pos!=l?pos:r));
System.out.flush();
int n_pos = Integer.valueOf(Rb.readLine());
boolean flag = true;
if(n_pos == pos)
{
if(pos == l)
{l = pos + 1;}
else
{r = pos - 1; flag = false;}
}
else
{
if(pos == l)
{r = pos - 1; flag = false;}
else
{l = pos + 1;}
}
int last = -1;
while(l <= r)
{
int m = (l + r) / 2;
int s = (m < pos)?m:pos;
int e = (m < pos)?pos:m;
System.out.println("? " + s + " " + e);
System.out.flush();
n_pos = Integer.valueOf(Rb.readLine());
if(n_pos == pos)
{
last = m;
if(!flag)
{l = (l + r)/2 + 1;}
else
{r = (l + r)/2 - 1;}
}
else
{
if(flag)
{l = (l + r)/2 + 1;}
else
{r = (l + r)/2 - 1;}
}
}
System.out.println("! " + last);
System.out.flush();
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
eb660c470760117dfd0b95acc10eee3b
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,900
| null |
standard output
| |
PASSED
|
9c615e36ba3f6135a956c80322a3a0b3
|
train_109.jsonl
|
1613658900
|
The only difference between the easy and the hard version is the limit to the number of queries.This is an interactive problem.There is an array $$$a$$$ of $$$n$$$ different numbers. In one query you can ask the position of the second maximum element in a subsegment $$$a[l..r]$$$. Find the position of the maximum element in the array in no more than 20 queries.A subsegment $$$a[l..r]$$$ is all the elements $$$a_l, a_{l + 1}, ..., a_r$$$. After asking this subsegment you will be given the position of the second maximum from this subsegment in the whole array.
|
256 megabytes
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;
public class GuessingTheGreatestHard {
static FastScanner fs = new FastScanner();
static int query(int left, int right) {
System.out.println("? " + left + " " + right);
return fs.nextInt();
}
public static void main(String[] args) {
PrintWriter out = new PrintWriter(System.out);
int n = fs.nextInt();
int secondMax = query(1, n);
int left = 1, right = n;
if(secondMax == 1 || query(1, secondMax) != secondMax) {
left = secondMax;
right = n;
while(left + 1 < right) {
int mid = (left + right) / 2;
if(query(secondMax, mid) == secondMax)
right = mid;
else
left = mid;
}
} else {
left = 1;
right = secondMax;
while(left + 1 < right) {
int mid = (left + right) / 2;
if(query(mid, secondMax) == secondMax)
left = mid;
else
right = mid;
}
}
int myAns = query(left, right) == left ? right : left;
System.out.println("! " + myAns);
}
static void ruffleSort(int[] a) {
int n = a.length;
Random r = new Random();
for(int i = 0; i < a.length; ++i) {
int oi = r.nextInt(n), t = a[i];
a[i] = a[oi];
a[oi] = t;
}
Arrays.sort(a);
}
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\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
eb660c470760117dfd0b95acc10eee3b
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,900
| null |
standard output
| |
PASSED
|
06aaefedf0ab46f8a1ecf1d8b95f0184
|
train_109.jsonl
|
1613658900
|
The only difference between the easy and the hard version is the limit to the number of queries.This is an interactive problem.There is an array $$$a$$$ of $$$n$$$ different numbers. In one query you can ask the position of the second maximum element in a subsegment $$$a[l..r]$$$. Find the position of the maximum element in the array in no more than 20 queries.A subsegment $$$a[l..r]$$$ is all the elements $$$a_l, a_{l + 1}, ..., a_r$$$. After asking this subsegment you will be given the position of the second maximum from this subsegment in the whole array.
|
256 megabytes
|
import java.util.*;
import java.lang.*;
import java.io.*;
import java.math.BigInteger;
public class C
{
static Scanner in;
public static void main(String[] args) {
in = new Scanner(System.in);
int n = in.nextInt();
int l=1, r= n;
int s = query(l, r);
if(query(1, s) == s) {
l = 1; r = s-1;
while(l<r) {
int m = (l+r+1)/2;
if(query(m, s) == s) l = m;
else r = m-1;
}
solve(l);
} else {
l = s+1; r = n;
while(l<r) {
int m = (l+r)/2;
if(query(s, m) == s) r = m;
else l = m+1;
}
solve(l);
}
}
static int query(int l, int r) {
if(l>=r) return -1;
System.out.println("? " + l + " " + r);
System.out.flush();
return in.nextInt();
}
static void solve(int s) {
System.out.println("! " + s);
System.out.flush();
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
eb660c470760117dfd0b95acc10eee3b
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,900
| null |
standard output
| |
PASSED
|
fa886e682a579512869f47c28ca75a56
|
train_109.jsonl
|
1613658900
|
The only difference between the easy and the hard version is the limit to the number of queries.This is an interactive problem.There is an array $$$a$$$ of $$$n$$$ different numbers. In one query you can ask the position of the second maximum element in a subsegment $$$a[l..r]$$$. Find the position of the maximum element in the array in no more than 20 queries.A subsegment $$$a[l..r]$$$ is all the elements $$$a_l, a_{l + 1}, ..., a_r$$$. After asking this subsegment you will be given the position of the second maximum from this subsegment in the whole array.
|
256 megabytes
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Solution {
static Reader input;
public static void main(String[] args) throws IOException {
input = new Reader();
int n = input.nextInt();
int secondMax = ask(1, n), temp;
int max;
if(secondMax == n) {
max = leftBinarySearch(1, n-1, secondMax);
} else if(secondMax == 1) {
max = rightBinarySearch(2, n, secondMax);
} else {
temp = ask(secondMax, n);
if(temp != secondMax) {
max = leftBinarySearch(1, secondMax-1, secondMax);
} else {
max = rightBinarySearch(secondMax+1, n, secondMax);
}
}
System.out.println("! " + max);
}
static int leftBinarySearch(int l, int r, int secondMax) throws IOException {
int temp, middle, left = l, right = r, answer = l;
while(left <= right) {
middle = left+right>>1;
temp = ask(middle, secondMax);
if(temp == secondMax) {
answer = middle;
left = middle+1;
} else {
right = middle-1;
}
}
return answer;
}
static int rightBinarySearch(int l, int r, int secondMax) throws IOException {
int temp, middle, left = l, right = r, answer = r;
while(left <= right) {
middle = left+right>>1;
temp = ask(secondMax, middle);
if(temp == secondMax) {
answer = middle;
right = middle-1;
} else {
left = middle+1;
}
}
return answer;
}
static int ask(int l, int r) throws IOException {
System.out.println("? " + l + " " + r);
System.out.flush();
return input.nextInt();
}
static class Reader {
BufferedReader bufferedReader;
StringTokenizer string;
public Reader() {
InputStreamReader inr = new InputStreamReader(System.in);
bufferedReader = new BufferedReader(inr);
}
public String next() throws IOException {
while(string == null || ! string.hasMoreElements()) {
string = new StringTokenizer(bufferedReader.readLine());
}
return string.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public String nextLine() throws IOException {
return bufferedReader.readLine();
}
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
eb660c470760117dfd0b95acc10eee3b
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,900
| null |
standard output
| |
PASSED
|
4be74713a3a09e5566a712f754dcd408
|
train_109.jsonl
|
1613658900
|
The only difference between the easy and the hard version is the limit to the number of queries.This is an interactive problem.There is an array $$$a$$$ of $$$n$$$ different numbers. In one query you can ask the position of the second maximum element in a subsegment $$$a[l..r]$$$. Find the position of the maximum element in the array in no more than 20 queries.A subsegment $$$a[l..r]$$$ is all the elements $$$a_l, a_{l + 1}, ..., a_r$$$. After asking this subsegment you will be given the position of the second maximum from this subsegment in the whole array.
|
256 megabytes
|
import java.util.*;
import java.io.*;
import java.lang.*;
public class cf719 {
public static int query(int l,int r) throws Exception{
if(l>=r)return -1;
InputStreamReader ip=new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(ip);
System.out.println("? "+(l+1)+" "+(r+1));
int ans=Integer.parseInt(br.readLine());
return ans-1;
}
//For HardVersion the resulting number of queries is 2+⌈𝑙𝑜𝑔(base2)10^5⌉=19.
//For EasyVersion the resulting number of queries is 2⋅⌈𝑙𝑜𝑔2105⌉=34.
public static void HardVersion() throws Exception{
InputStreamReader ip=new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(ip);
int n =Integer.parseInt(br.readLine());
// String[] strs=(br.readLine()).trim().split(" ");
int l=0,r=n; //so that segment divide equally by mid [l,mid) [mid,r)
int smax=query(l, r-1); //segment max
int ans=0;
if(smax==0 || query(0, smax)!=smax){
l=smax; r=n-1; //Max lie in right segment
while((r-l)>1){
int mid=l+(r-l)/2;
if(query(smax,mid)==smax){
r=mid;
}else{
l=mid;
}
}
System.out.println("! "+(r+1)); //+r+" "
}else{
l=0; r=smax; //Max lie in left segment
while((r-l)>1){
int mid=l+(r-l)/2;
if(query(mid,smax)==smax){
l=mid;
}else{
r=mid;
}
}
System.out.println("! "+(l+1));
}
}
public static void EasyVersion() throws Exception{
InputStreamReader ip=new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(ip);
int n =Integer.parseInt(br.readLine());
// String[] strs=(br.readLine()).trim().split(" ");
int l=0,r=n; //so that segment divide equally by mid [l,mid) [mid,r)
int ans=0;
while((r-l)>1){ // query possible for segment of size >1
int mid=l+(r-l)/2;
int smax=query(l, r-1); //segment max
if(smax<mid){
if(query(l, mid-1)==smax){
r=mid;
}else{ l=mid; }
}else{
if(query(mid, r-1)==smax){
l=mid;
}else{
r=mid;
}
}
// System.out.println(l+" "+r);
}
System.out.println("! "+r); //+r+" "
}
//******************************************************************************************************************** */
public static void main(String[] args) throws Exception{
HardVersion();
}
public static void solve3() throws Exception{
InputStreamReader ip=new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(ip);
int t = Integer.parseInt(br.readLine());
StringBuilder asb=new StringBuilder();
while(t-->0){
int n =Integer.parseInt(br.readLine());
String[] strs=(br.readLine()).trim().split(" ");
// int n=Integer.parseInt(strs[0]),k=Integer.parseInt(strs[1]),r=Integer.parseInt(strs[2]),s=Integer.parseInt(strs[3]);
// String str=(br.readLine()).trim();
//Rearrange Given Expression- a𝑗−a𝑖=𝑗−𝑖 => aj-j == ai-i
int[] arr=new int[n];
HashMap<Integer,Integer> hm=new HashMap<>();
for(int i=0;i<n;i++){ arr[i]=Integer.parseInt(strs[i]);
hm.put((arr[i]-i), hm.getOrDefault((arr[i]-i), 0)+1); }
long ans=0;
for(int key:hm.keySet()){
long ct=hm.get(key);
ans+=(ct*(ct-1))/2;
}
// System.out.println(ans+" ct "+ct);
System.out.println(ans);
}
}
//******************************************************************************************************************** */
public static long modInverse1(long a, long m){
// int g = gcd(a, m);
// if(g!=1) {System.out.println("Inverse Doesnot Exist");}
return binexp(a, m - 2, m);
}
public static long binexp(long a, long b, long m){
if (b == 0)return 1;
long res = binexp(a, b / 2, m);
if (b % 2 == 1) return (( (res*res)%m )*a) % m;
else return (res*res)%m;
}
//binexp
public static long binexp(long a,long b){
if(b==0)return 1;
long res=binexp(a, b/2);
if(b%2==1){
return (((res*res))*a);
}else return (res*res);
}
//Comparator Interface
public static class comp implements Comparator<int[]>{
public int compare(int[] a,int[] b){
return a[0]-b[0];
}
}
//gcd using Euclid's Division Algorithm
public static long gcd(long a,long b){
if(b==0)return a;
else return gcd(b, a%b);
}
//check prime in root(n)
public static int isprime(int n){
for(int i=2;i<=Math.sqrt(n);i++){
if(n%i==0)return i;
}
return -1; //means n is prime
}
//SOE
static int[] sieve;
public static void SOE(int n){
sieve=new int[n+1];
// System.out.println("All prime number from 1 to n:-");
for(int x=2;x<=n;x++){
if(sieve[x]!=0){ //Not prime number
continue;
}
// System.out.print(x+" ");
for(int u=2*x;u<=n;u+=x){
sieve[u]=x;
}
}
//If sieve[i]=0 means 'i' is primr else 'i' is not prime
}
//sort
public static void sort(long[] arr) {
int n = arr.length;
for (int i = 0; i < n; i++) {
int idx = (int) Math.random() * n;
long temp = arr[i]; arr[i] = arr[idx]; arr[idx] = temp; //swap
}
Arrays.sort(arr);
}
public static void sort(int[] arr) {
int n = arr.length;
for (int i = 0; i < n; i++) {
int idx = (int) Math.random() * n;
int temp = arr[i]; arr[i] = arr[idx]; arr[idx] = temp; //swap
}
Arrays.sort(arr);
}
//1d print
public static void print(int[] dp) {
for (int val : dp) {
System.out.print(val + " ");
}
System.out.println();
}
public static void print(long[] dp) {//Method Overloading
for (long val : dp) {
System.out.print(val + " ");
}
System.out.println();
}
//2d print
public static void print(long[][] dp) {//Method Overloading
for (long[] a : dp) {
for (long val : a) {
System.out.print(val + " ");
}
System.out.println();
}
}
public static void print(int[][] dp) {
for (int[] a : dp) {
for (int val : a) {
System.out.print(val + " ");
}
System.out.println();
}
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
eb660c470760117dfd0b95acc10eee3b
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,900
| null |
standard output
| |
PASSED
|
cfb2527a128e02373c62ca80ddaf87ff
|
train_109.jsonl
|
1613658900
|
The only difference between the easy and the hard version is the limit to the number of queries.This is an interactive problem.There is an array $$$a$$$ of $$$n$$$ different numbers. In one query you can ask the position of the second maximum element in a subsegment $$$a[l..r]$$$. Find the position of the maximum element in the array in no more than 20 queries.A subsegment $$$a[l..r]$$$ is all the elements $$$a_l, a_{l + 1}, ..., a_r$$$. After asking this subsegment you will be given the position of the second maximum from this subsegment in the whole array.
|
256 megabytes
|
import java.util.*;
import java.io.*;
import java.lang.*;
public class cf719 {
public static int query(int l,int r) throws Exception{
if(l>=r)return -1;
InputStreamReader ip=new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(ip);
System.out.println("? "+(l+1)+" "+(r+1));
int ans=Integer.parseInt(br.readLine());
return ans-1;
}
public static void Hard() throws Exception{
InputStreamReader ip=new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(ip);
int n =Integer.parseInt(br.readLine());
// String[] strs=(br.readLine()).trim().split(" ");
int l=0,r=n; //so that segment divide equally by mid [l,mid) [mid,r)
int smax=query(l, r-1); //segment max
int ans=0;
if(smax==0 || query(0, smax)!=smax){
l=smax; r=n-1; //Max lie in right segment
while((r-l)>1){
int mid=l+(r-l)/2;
if(query(smax,mid)==smax){
r=mid;
}else{
l=mid;
}
}
System.out.println("! "+(r+1)); //+r+" "
}else{
l=0; r=smax; //Max lie in left segment
while((r-l)>1){
int mid=l+(r-l)/2;
if(query(mid,smax)==smax){
l=mid;
}else{
r=mid;
}
}
System.out.println("! "+(l+1));
}
}
public static void Easy() throws Exception{
InputStreamReader ip=new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(ip);
int n =Integer.parseInt(br.readLine());
// String[] strs=(br.readLine()).trim().split(" ");
int l=0,r=n; //so that segment divide equally by mid [l,mid) [mid,r)
int ans=0;
while((r-l)>1){ // query possible for segment of size >1
int mid=l+(r-l)/2;
// if(l==mid){ // last segment of size 2 This condition is mandatory otherwise loop goes in infinite loop
// if(query(l, r)==l){ ans=r;}
// else{ ans=l; } break;
// }
int smax=query(l, r-1); //segment max
if(smax<mid){
if(query(l, mid-1)==smax){
r=mid;
}else{ l=mid; }
}else{
if(query(mid, r-1)==smax){
l=mid;
}else{
r=mid;
}
}
// System.out.println(l+" "+r);
}
System.out.println("! "+r); //+r+" "
}
//******************************************************************************************************************** */
public static void main(String[] args) throws Exception{
Hard();
}
public static void solve3() throws Exception{
InputStreamReader ip=new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(ip);
int t = Integer.parseInt(br.readLine());
StringBuilder asb=new StringBuilder();
while(t-->0){
int n =Integer.parseInt(br.readLine());
String[] strs=(br.readLine()).trim().split(" ");
// int n=Integer.parseInt(strs[0]),k=Integer.parseInt(strs[1]),r=Integer.parseInt(strs[2]),s=Integer.parseInt(strs[3]);
// String str=(br.readLine()).trim();
//Rearrange Given Expression- a𝑗−a𝑖=𝑗−𝑖 => aj-j == ai-i
int[] arr=new int[n];
HashMap<Integer,Integer> hm=new HashMap<>();
for(int i=0;i<n;i++){ arr[i]=Integer.parseInt(strs[i]);
hm.put((arr[i]-i), hm.getOrDefault((arr[i]-i), 0)+1); }
long ans=0;
for(int key:hm.keySet()){
long ct=hm.get(key);
ans+=(ct*(ct-1))/2;
}
// System.out.println(ans+" ct "+ct);
System.out.println(ans);
}
}
//******************************************************************************************************************** */
public static long modInverse1(long a, long m){
// int g = gcd(a, m);
// if(g!=1) {System.out.println("Inverse Doesnot Exist");}
return binexp(a, m - 2, m);
}
public static long binexp(long a, long b, long m){
if (b == 0)return 1;
long res = binexp(a, b / 2, m);
if (b % 2 == 1) return (( (res*res)%m )*a) % m;
else return (res*res)%m;
}
//binexp
public static long binexp(long a,long b){
if(b==0)return 1;
long res=binexp(a, b/2);
if(b%2==1){
return (((res*res))*a);
}else return (res*res);
}
//Comparator Interface
public static class comp implements Comparator<int[]>{
public int compare(int[] a,int[] b){
return a[0]-b[0];
}
}
//gcd using Euclid's Division Algorithm
public static long gcd(long a,long b){
if(b==0)return a;
else return gcd(b, a%b);
}
//check prime in root(n)
public static int isprime(int n){
for(int i=2;i<=Math.sqrt(n);i++){
if(n%i==0)return i;
}
return -1; //means n is prime
}
//SOE
static int[] sieve;
public static void SOE(int n){
sieve=new int[n+1];
// System.out.println("All prime number from 1 to n:-");
for(int x=2;x<=n;x++){
if(sieve[x]!=0){ //Not prime number
continue;
}
// System.out.print(x+" ");
for(int u=2*x;u<=n;u+=x){
sieve[u]=x;
}
}
//If sieve[i]=0 means 'i' is primr else 'i' is not prime
}
//sort
public static void sort(long[] arr) {
int n = arr.length;
for (int i = 0; i < n; i++) {
int idx = (int) Math.random() * n;
long temp = arr[i]; arr[i] = arr[idx]; arr[idx] = temp; //swap
}
Arrays.sort(arr);
}
public static void sort(int[] arr) {
int n = arr.length;
for (int i = 0; i < n; i++) {
int idx = (int) Math.random() * n;
int temp = arr[i]; arr[i] = arr[idx]; arr[idx] = temp; //swap
}
Arrays.sort(arr);
}
//1d print
public static void print(int[] dp) {
for (int val : dp) {
System.out.print(val + " ");
}
System.out.println();
}
public static void print(long[] dp) {//Method Overloading
for (long val : dp) {
System.out.print(val + " ");
}
System.out.println();
}
//2d print
public static void print(long[][] dp) {//Method Overloading
for (long[] a : dp) {
for (long val : a) {
System.out.print(val + " ");
}
System.out.println();
}
}
public static void print(int[][] dp) {
for (int[] a : dp) {
for (int val : a) {
System.out.print(val + " ");
}
System.out.println();
}
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
eb660c470760117dfd0b95acc10eee3b
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,900
| null |
standard output
| |
PASSED
|
3d89019bec7646237b7ed3cf73055123
|
train_109.jsonl
|
1613658900
|
The only difference between the easy and the hard version is the limit to the number of queries.This is an interactive problem.There is an array $$$a$$$ of $$$n$$$ different numbers. In one query you can ask the position of the second maximum element in a subsegment $$$a[l..r]$$$. Find the position of the maximum element in the array in no more than 20 queries.A subsegment $$$a[l..r]$$$ is all the elements $$$a_l, a_{l + 1}, ..., a_r$$$. After asking this subsegment you will be given the position of the second maximum from this subsegment in the whole array.
|
256 megabytes
|
import java.util.Scanner;
public class D {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int mid = ask(1, n, sc);
if (mid < n && ask(mid, n, sc) == mid) {
solve(mid, n, false, sc, mid);
} else {
solve(1, mid, true, sc, mid);
}
}
public static void solve(int a, int b, boolean isRight, Scanner sc, int mid) {
int l = a, r = b;
if (isRight) r--;
else l++;
int ans = 0;
while (l <= r) {
int m = (l+r)/2;
// System.out.println("l, m, r: "+l+","+m+","+r);
if (isRight) {
int res = ask(m, b, sc);
// System.out.println("res: "+res);
if (res == mid) {
ans = m;
l = m+1;
} else
r = m-1;
} else {
int res = ask(a, m, sc);
// System.out.println("res: "+res);
if (res == mid) {
ans = m;
r = m-1;
} else
l = m+1;
}
}
System.out.println("! "+ans);
}
public static int ask(int l, int r, Scanner sc) {
System.out.println("? "+l+" "+r);
System.out.flush();
return sc.nextInt();
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
eb660c470760117dfd0b95acc10eee3b
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,900
| null |
standard output
| |
PASSED
|
e06562fa1e915b201b735a54ffc876ee
|
train_109.jsonl
|
1613658900
|
The only difference between the easy and the hard version is the limit to the number of queries.This is an interactive problem.There is an array $$$a$$$ of $$$n$$$ different numbers. In one query you can ask the position of the second maximum element in a subsegment $$$a[l..r]$$$. Find the position of the maximum element in the array in no more than 20 queries.A subsegment $$$a[l..r]$$$ is all the elements $$$a_l, a_{l + 1}, ..., a_r$$$. After asking this subsegment you will be given the position of the second maximum from this subsegment in the whole array.
|
256 megabytes
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class Main {
static class DisjointUnionSets {
int[] rank, parent;
int n;
// Constructor
public DisjointUnionSets(int n)
{
rank = new int[n];
parent = new int[n];
this.n = n;
makeSet();
}
// Creates n sets with single item in each
void makeSet()
{
for (int i = 0; i < n; i++) {
// Initially, all elements are in
// their own set.
parent[i] = i;
}
}
// Returns representative of x's set
int find(int x)
{
// Finds the representative of the set
// that x is an element of
if (parent[x] != x) {
// if x is not the parent of itself
// Then x is not the representative of
// his set,
parent[x] = find(parent[x]);
// so we recursively call Find on its parent
// and move i's node directly under the
// representative of this set
}
return parent[x];
}
// Unites the set that includes x and the set
// that includes x
void union(int x, int y)
{
// Find representatives of two sets
int xRoot = find(x), yRoot = find(y);
// Elements are in the same set, no need
// to unite anything.
if (xRoot == yRoot)
return;
// If x's rank is less than y's rank
if (rank[xRoot] < rank[yRoot])
// Then move x under y so that depth
// of tree remains less
parent[xRoot] = yRoot;
// Else if y's rank is less than x's rank
else if (rank[yRoot] < rank[xRoot])
// Then move y under x so that depth of
// tree remains less
parent[yRoot] = xRoot;
else // if ranks are the same
{
// Then move y under x (doesn't matter
// which one goes where)
parent[yRoot] = xRoot;
// And increment the result tree's
// rank by 1
rank[xRoot] = rank[xRoot] + 1;
}
}
}
static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine(){
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
static class HashMultiSet<T> implements Iterable<T>
{ private final HashMap<T,Integer> map;
private int size;
public HashMultiSet(){map=new HashMap<>(); size=0;}
public void clear(){map.clear(); size=0;}
public int size(){return size;}
public int setSize(){return map.size();}
public boolean contains(T a){return map.containsKey(a);}
public boolean isEmpty(){return size==0;}
public Integer get(T a){return map.getOrDefault(a,0);}
public void add(T a, int count)
{
int cur=get(a);map.put(a,cur+count); size+=count;
if(cur+count==0) map.remove(a);
}
public void addOne(T a){add(a,1);}
public void remove(T a, int count){add(a,Math.max(-get(a),-count));}
public void removeOne(T a){remove(a,1);}
public void removeAll(T a){remove(a,Integer.MAX_VALUE-10);}
public Iterator<T> iterator()
{
return new Iterator<>()
{
private final Iterator<T> iter = map.keySet().iterator();
private int count = 0; private T curElement;
public boolean hasNext(){return iter.hasNext()||count>0;}
public T next()
{
if(count==0)
{
curElement=iter.next();
count=get(curElement);
}
count--; return curElement;
}
};
}
}
private static long abs(long x){ if(x < 0) x*=-1l;return x; }
private static int abs(int x){ if(x < 0) x*=-1;return x; }
// public static int get(HashMap<Integer, Deque<Integer> > a, int key ){
// return a.get(key).getLast();
// }
// public static void removeLast (HashMap<Integer,Deque<Integer> > a, int key){
// if(a.containsKey(key)){
// a.get(key).removeLast();
// if(a.get(key).size() == 0) a.remove(key);
// }
// }
// public static void add(HashMap<Integer,Deque<Integer>> a, int key, int val){
// if(a.containsKey(key)){
// a.get(key).addLast(val);
// }else{
// Deque<Integer> b = new LinkedList<>();
// b.addLast(val);
// a.put(key,b);
// }
// }
private static int askRange(int l ,int r){
if(l == r) return l;
MyScanner sc = new MyScanner();
System.out.println("? "+l+" "+r);
System.out.flush();
return sc.nextInt();
}
private static int binr(int l ,int r,int v){
if(l > r) return Integer.MAX_VALUE;
int mid = (r+l) /2;
if(askRange(v,mid) == v){
int x = binr(l,mid-1,v);
return Math.min(x,mid);
}else{
int x = binr(mid+1,r,v);
return x;
}
}
private static int binl(int l,int r,int v){
if (l > r) return Integer.MIN_VALUE;
int mid = (l+r) /2;
if(askRange(mid,v) == v){
int x = binl(mid+1,r,v);
return Math.max(x,mid);
}else{
int x = binl(l,mid-1,v);
return x;
}
}
public static void main(String[] args) {
MyScanner sc = new MyScanner();
int n = sc.nextInt();
int v = askRange(1,n);
int v1 = askRange(v,n);
if(v == v1 && v != n){
System.out.println("! " +binr(v+1,n,v));
}else{
System.out.println("! "+binl(1,v-1,v));
}
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
eb660c470760117dfd0b95acc10eee3b
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,900
| null |
standard output
| |
PASSED
|
8fba1039c9eccaa33fe71b3cac378871
|
train_109.jsonl
|
1613658900
|
The only difference between the easy and the hard version is the limit to the number of queries.This is an interactive problem.There is an array $$$a$$$ of $$$n$$$ different numbers. In one query you can ask the position of the second maximum element in a subsegment $$$a[l..r]$$$. Find the position of the maximum element in the array in no more than 20 queries.A subsegment $$$a[l..r]$$$ is all the elements $$$a_l, a_{l + 1}, ..., a_r$$$. After asking this subsegment you will be given the position of the second maximum from this subsegment in the whole array.
|
256 megabytes
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
public class C2_Rnd703_Div2
{
static int n;
public static void main(String[] args) throws NumberFormatException, IOException
{
BufferedReader scan = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(System.out);
n = Integer.parseInt(scan.readLine());
int ans = solve(n, scan, out);
out.println("! " + (ans+1));
out.flush();
}
public static int parse(String num)
{
return Integer.parseInt(num);
}
public static int solve(int n, BufferedReader scan, PrintWriter out) throws IOException
{
int smax = query(0, n-1, scan, out);
if(smax == 0)
return binSearchRight(smax, scan, out);
else if(smax == n-1)
return binSearchLeft(smax, scan, out);
else if(query(0, smax, scan, out) == smax)
return binSearchLeft(smax, scan, out);
else
return binSearchRight(smax, scan, out);
}
public static int binSearchLeft(int smax, BufferedReader scan, PrintWriter out) throws IOException
{
int low = 1, high = smax - 1, mid;
int index = 0;
while(low <= high)
{
mid = (low + high) / 2;
// smax is in this range
if(sendQuery(mid, smax, scan, out) == smax)
{
low = mid + 1;
if(index < mid)
index = mid;
}
else
{
high = mid - 1;
}
}
return index;
}
// need to make sure this doesn't make a query of length 1
private static int binSearchRight(int smax, BufferedReader scan, PrintWriter out) throws IOException
{
int low = smax + 1, high = n - 2, mid;
int index = n - 1;
while(low <= high)
{
mid = (low + high) / 2;
// smax is in that range
if(sendQuery(mid, smax, scan, out) == smax)
{
high = mid - 1;
if(index > mid)
index = mid;
}
else
{
low = mid + 1;
}
}
return index;
}
private static int sendQuery(int a, int b, BufferedReader scan, PrintWriter out) throws IOException
{
if(a > b)
return query(b, a, scan, out);
else
return query(a, b, scan, out);
}
public static int query(int l, int r, BufferedReader scan, PrintWriter out) throws IOException
{
out.println("? " + (l+1) + " " + (r+1));
out.flush();
return parse(scan.readLine()) - 1;
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
eb660c470760117dfd0b95acc10eee3b
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,900
| null |
standard output
| |
PASSED
|
a8e79cf35441397f7e59bb38802cef69
|
train_109.jsonl
|
1613658900
|
The only difference between the easy and the hard version is the limit to the number of queries.This is an interactive problem.There is an array $$$a$$$ of $$$n$$$ different numbers. In one query you can ask the position of the second maximum element in a subsegment $$$a[l..r]$$$. Find the position of the maximum element in the array in no more than 20 queries.A subsegment $$$a[l..r]$$$ is all the elements $$$a_l, a_{l + 1}, ..., a_r$$$. After asking this subsegment you will be given the position of the second maximum from this subsegment in the whole array.
|
256 megabytes
|
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
import java.io.*;
import java.util.*;
public class CFEd {
public static void main(String[] args) {
Scanner us = new Scanner(System.in);
int n = us.nextInt();
ask(1, n);
int response = us.nextInt();
if(response == 1) {
searchRight(response, us, n);
}
else if(response == n) {
searchLeft(response, us);
}
else {
ask(1, response);
int res2 = us.nextInt();
if(res2 == response) {
searchLeft(response, us);
}
else {
searchRight(response, us, n);
}
}
}
static void ask(int i, int j) {
System.out.println("? " + i + " " + j);
System.out.flush();
}
static void searchLeft(int start, Scanner us) {
int ubnd = start - 1;
int lbnd = 1;
while(ubnd - lbnd > 1) {
int mid = (ubnd + lbnd)/2;
ask(mid, start);
int response = us.nextInt();
if(response == start) {
lbnd = mid;
}
else {
ubnd = mid - 1;
}
}
if(ubnd == lbnd) {
System.out.println("! " + ubnd);
}
else {
ask(ubnd, start);
int response = us.nextInt();
if(response == start) {
System.out.println("! " + ubnd);
}
else {
System.out.println("! " + lbnd);
}
}
}
static void searchRight(int start, Scanner us, int n) {
int ubnd = n;
int lbnd = start + 1;
while(ubnd - lbnd > 1) {
int mid = (ubnd + lbnd)/2;
ask(start, mid);
int response = us.nextInt();
if(response == start) {
ubnd = mid;
}
else {
lbnd = mid + 1;
}
}
if(ubnd == lbnd) {
System.out.println("! " + ubnd);
}
else {
ask(start, lbnd);
int response = us.nextInt();
if(response == start) {
System.out.println("! " + lbnd);
}
else {
System.out.println("! " + ubnd);
}
}
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
eb660c470760117dfd0b95acc10eee3b
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,900
| null |
standard output
| |
PASSED
|
b003e7e51359aa907fd0a33a55ff3b01
|
train_109.jsonl
|
1613658900
|
The only difference between the easy and the hard version is the limit to the number of queries.This is an interactive problem.There is an array $$$a$$$ of $$$n$$$ different numbers. In one query you can ask the position of the second maximum element in a subsegment $$$a[l..r]$$$. Find the position of the maximum element in the array in no more than 20 queries.A subsegment $$$a[l..r]$$$ is all the elements $$$a_l, a_{l + 1}, ..., a_r$$$. After asking this subsegment you will be given the position of the second maximum from this subsegment in the whole array.
|
256 megabytes
|
import java.io.*;
import java.util.*;
public class tank {
//static StringBuilder IO = new StringBuilder();
//static final Scanner scan = new Scanner(System.in);
static final FastScanner fs = new FastScanner();
public static void main(String[] args) {
// int t = fs.nextInt();
// while(t-->0){
// SLV();
// }
SLV();
//System.out.println(IO);
}
static void SLV(){
int n = fs.nextInt();
int smax = ask(1, n), ans;
if(smax == 1) {
ans = fn(2, n, 1);
}else if(smax == n){
ans = fn(1, n-1, n);
}else{
if(ask(1, smax) == smax){
ans = fn(1, smax - 1, smax);
}else ans = fn(smax + 1, n, smax);
}
System.out.println("! " + ans);
}
static int fn(int l ,int r, int smax){
int mid = (l + r)/2;
if(r == l) return l;
if(smax > r){
if(l == r-1){
if(ask(r, smax) == smax) return r;
else return l;
}
if(ask(mid , smax) == smax) return fn(mid, r, smax);
else return fn(l, mid - 1, smax);
}else{
if(l == r - 1){
if(ask(smax, l) == smax) return l;
else return r;
}
if(smax == ask(smax, mid)) return fn(l, mid, smax);
else return fn(mid + 1,r, smax);
}
}
static int ask(int l, int r){
if(l == r) return l;
System.out.println("? " + l + " " + r);
int num = fs.nextInt();
System.out.flush();
return num;
}
static class FastScanner {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st=new StringTokenizer("");
String next() {
while (!st.hasMoreTokens())
try {
st=new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
int[] readArray(int n) {
int[] a=new int[n];
for (int i=0; i<n; i++) a[i]=nextInt();
return a;
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
eb660c470760117dfd0b95acc10eee3b
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,900
| null |
standard output
| |
PASSED
|
f06170ea3badab724a5648976d47a03c
|
train_109.jsonl
|
1613658900
|
The only difference between the easy and the hard version is the limit to the number of queries.This is an interactive problem.There is an array $$$a$$$ of $$$n$$$ different numbers. In one query you can ask the position of the second maximum element in a subsegment $$$a[l..r]$$$. Find the position of the maximum element in the array in no more than 20 queries.A subsegment $$$a[l..r]$$$ is all the elements $$$a_l, a_{l + 1}, ..., a_r$$$. After asking this subsegment you will be given the position of the second maximum from this subsegment in the whole array.
|
256 megabytes
|
import java.util.Scanner;
public class Index {
static Scanner scan = new Scanner(System.in);
static int query(int l, int r) {
if(l>=r)return 0;
System.out.printf("? %d %d\n", l, r);
System.out.flush();
return scan.nextInt();
}
public static void main(String[] args) {
int l = 1, r = scan.nextInt(), mid, x;
int second_max = query(l, r);
while (l < r) {
mid = (l + r) / 2;
if (second_max <= mid) {
x = query(Math.min(l, second_max), mid);
if (x == second_max)
r = mid;
else
l = mid + 1;
} else {
x = query(mid + 1, Math.max(second_max, r));
if (x == second_max)
l = mid + 1;
else
r = mid;
}
}
System.out.printf("! %d\n", l);
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
eb660c470760117dfd0b95acc10eee3b
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,900
| null |
standard output
| |
PASSED
|
34b21000f7c478f4520c3c8da2608be0
|
train_109.jsonl
|
1613658900
|
The only difference between the easy and the hard version is the limit to the number of queries.This is an interactive problem.There is an array $$$a$$$ of $$$n$$$ different numbers. In one query you can ask the position of the second maximum element in a subsegment $$$a[l..r]$$$. Find the position of the maximum element in the array in no more than 20 queries.A subsegment $$$a[l..r]$$$ is all the elements $$$a_l, a_{l + 1}, ..., a_r$$$. After asking this subsegment you will be given the position of the second maximum from this subsegment in the whole array.
|
256 megabytes
|
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n=sc.nextInt();
System.out.println("? 1 "+n);
System.out.flush();
int x=sc.nextInt();
boolean f=false;
if (x!=1) {
f=true;
System.out.println("? 1 " + x);
}
System.out.flush();
int newX=-1;
if (f) newX = sc.nextInt();
if (newX==x){
int l=1, r=x;
int ans=-1;
while (l<=r){
int m=(l+r)/2;
if (m==x){
System.out.println("! "+(m-1));
System.out.flush();
return;
}
System.out.println("? "+m+" "+x);
System.out.flush();
newX=sc.nextInt();
if (newX==x){
ans=m;
l=m+1;
}else {
r=m-1;
}
}
System.out.println("! "+(ans));
System.out.flush();
}else {
int r=n,l=x;
int ans=-1;
while (l<=r){
int m=(l+r)/2;
if (m==x){
System.out.println("! "+(m+1));
System.out.flush();
return;
}
System.out.println("? "+x+" "+m);
System.out.flush();
newX=sc.nextInt();
if (newX==x){
r=m-1;
}else {
l=m+1;
}
}
System.out.println("! "+(l));
System.out.flush();
}
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
eb660c470760117dfd0b95acc10eee3b
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,900
| null |
standard output
| |
PASSED
|
fbf599dbfcacc1a1ab7eaa02158c974c
|
train_109.jsonl
|
1613658900
|
The only difference between the easy and the hard version is the limit to the number of queries.This is an interactive problem.There is an array $$$a$$$ of $$$n$$$ different numbers. In one query you can ask the position of the second maximum element in a subsegment $$$a[l..r]$$$. Find the position of the maximum element in the array in no more than 20 queries.A subsegment $$$a[l..r]$$$ is all the elements $$$a_l, a_{l + 1}, ..., a_r$$$. After asking this subsegment you will be given the position of the second maximum from this subsegment in the whole array.
|
256 megabytes
|
import java.util.*;
import java.io.*;
//My life seems to be a joke. But, one day I will conquer.
public class B{
public static Scanner sc = new Scanner(System.in);
public static int query(int l, int r)
{
if(l>=r)return -1;
System.out.println("? "+l+" "+r);
int a = sc.nextInt();
return a;
}
public static void main(String[] args)
{
FastScanner fs = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
int n = fs.nextInt();
int l = 1; int r = n;
int pos = query(l,r);
if(pos==1 || query(1,pos)!=pos)
{
int left = pos; int right = n;
while(left+1<right)
{
int mid = (left+right)/2;
if(query(pos,mid)==pos)
{
right = mid;
}
else{
left = mid;
}
}
System.out.println("! "+right);
}
else
{
int left = 1; int right = pos;
while(left+1<right)
{
int mid = (left+right)/2;
if(query(mid,pos)==pos)
{
left = mid;
}
else
{
right = mid;
}
}
System.out.println("! "+left);
}
out.close();
}
static class FastScanner {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st=new StringTokenizer("");
String next() {
while (!st.hasMoreTokens())
try {
st=new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
int[] readArray(int n) {
int[] a=new int[n];
for (int i=0; i<n; i++) a[i]=nextInt();
return a;
}
long nextLong() {
return Long.parseLong(next());
}
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
eb660c470760117dfd0b95acc10eee3b
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,900
| null |
standard output
| |
PASSED
|
5706ccef4ac2d203215fc656bed96eb9
|
train_109.jsonl
|
1613658900
|
The only difference between the easy and the hard version is the limit to the number of queries.This is an interactive problem.There is an array $$$a$$$ of $$$n$$$ different numbers. In one query you can ask the position of the second maximum element in a subsegment $$$a[l..r]$$$. Find the position of the maximum element in the array in no more than 20 queries.A subsegment $$$a[l..r]$$$ is all the elements $$$a_l, a_{l + 1}, ..., a_r$$$. After asking this subsegment you will be given the position of the second maximum from this subsegment in the whole array.
|
256 megabytes
|
import java.util.*;
import java.io.*;
public class Main {
static class Scan {
private byte[] buf=new byte[1024];
private int index;
private InputStream in;
private int total;
public Scan()
{
in=System.in;
}
public int scan()throws IOException
{
if(total<0)
throw new InputMismatchException();
if(index>=total)
{
index=0;
total=in.read(buf);
if(total<=0)
return -1;
}
return buf[index++];
}
public int scanInt()throws IOException
{
int integer=0;
int n=scan();
while(isWhiteSpace(n))
n=scan();
int neg=1;
if(n=='-')
{
neg=-1;
n=scan();
}
while(!isWhiteSpace(n))
{
if(n>='0'&&n<='9')
{
integer*=10;
integer+=n-'0';
n=scan();
}
else throw new InputMismatchException();
}
return neg*integer;
}
public double scanDouble()throws IOException
{
double doub=0;
int n=scan();
while(isWhiteSpace(n))
n=scan();
int neg=1;
if(n=='-')
{
neg=-1;
n=scan();
}
while(!isWhiteSpace(n)&&n!='.')
{
if(n>='0'&&n<='9')
{
doub*=10;
doub+=n-'0';
n=scan();
}
else throw new InputMismatchException();
}
if(n=='.')
{
n=scan();
double temp=1;
while(!isWhiteSpace(n))
{
if(n>='0'&&n<='9')
{
temp/=10;
doub+=(n-'0')*temp;
n=scan();
}
else throw new InputMismatchException();
}
}
return doub*neg;
}
public String scanString()throws IOException
{
StringBuilder sb=new StringBuilder();
int n=scan();
while(isWhiteSpace(n))
n=scan();
while(!isWhiteSpace(n))
{
sb.append((char)n);
n=scan();
}
return sb.toString();
}
private boolean isWhiteSpace(int n)
{
if(n==' '||n=='\n'||n=='\r'||n=='\t'||n==-1)
return true;
return false;
}
}
public static void sort(int arr[],int l,int r) { //sort(arr,0,n-1);
if(l==r) {
return;
}
int mid=(l+r)/2;
sort(arr,l,mid);
sort(arr,mid+1,r);
merge(arr,l,mid,mid+1,r);
}
public static void merge(int arr[],int l1,int r1,int l2,int r2) {
int tmp[]=new int[r2-l1+1];
int indx1=l1,indx2=l2;
//sorting the two halves using a tmp array
for(int i=0;i<tmp.length;i++) {
if(indx1>r1) {
tmp[i]=arr[indx2];
indx2++;
continue;
}
if(indx2>r2) {
tmp[i]=arr[indx1];
indx1++;
continue;
}
if(arr[indx1]<arr[indx2]) {
tmp[i]=arr[indx1];
indx1++;
continue;
}
tmp[i]=arr[indx2];
indx2++;
}
//Copying the elements of tmp into the main array
for(int i=0,j=l1;i<tmp.length;i++,j++) {
arr[j]=tmp[i];
}
}
public static void sort(long arr[],int l,int r) { //sort(arr,0,n-1);
if(l==r) {
return;
}
int mid=(l+r)/2;
sort(arr,l,mid);
sort(arr,mid+1,r);
merge(arr,l,mid,mid+1,r);
}
public static void merge(long arr[],int l1,int r1,int l2,int r2) {
long tmp[]=new long[r2-l1+1];
int indx1=l1,indx2=l2;
//sorting the two halves using a tmp array
for(int i=0;i<tmp.length;i++) {
if(indx1>r1) {
tmp[i]=arr[indx2];
indx2++;
continue;
}
if(indx2>r2) {
tmp[i]=arr[indx1];
indx1++;
continue;
}
if(arr[indx1]<arr[indx2]) {
tmp[i]=arr[indx1];
indx1++;
continue;
}
tmp[i]=arr[indx2];
indx2++;
}
//Copying the elements of tmp into the main array
for(int i=0,j=l1;i<tmp.length;i++,j++) {
arr[j]=tmp[i];
}
}
public static void main(String args[]) throws IOException {
Scan input=new Scan();
int n=input.scanInt();
if(n==1) {
System.out.println("! 1");
return;
}
System.out.println("? "+1+" "+n);
System.out.flush();
int indx=input.scanInt();
int ans=-1;
int lft=-1;
if(indx!=1) {
System.out.println("? "+1+" "+indx);
System.out.flush();
lft=input.scanInt();
}
int l,r;
//Right
if(lft!=indx) {
l=indx+1;
r=n;
while(l<=r) {
int mid=(l+r)/2;
System.out.println("? "+indx+" "+mid);
System.out.flush();
int idx=input.scanInt();
if(idx==indx) {
ans=mid;
r=mid-1;
}
else {
l=mid+1;
}
}
}
if(lft==indx) {
//left
l=1;
r=indx-1;
while(l<=r) {
int mid=(l+r)/2;
System.out.println("? "+mid+" "+indx);
System.out.flush();
int idx=input.scanInt();
if(idx==indx) {
ans=mid;
l=mid+1;
}
else {
r=mid-1;
}
}
}
System.out.println("! "+ans);
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
eb660c470760117dfd0b95acc10eee3b
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,900
| null |
standard output
| |
PASSED
|
8c6e20e0b7a3d6fca28df6a3d410d715
|
train_109.jsonl
|
1613658900
|
The only difference between the easy and the hard version is the limit to the number of queries.This is an interactive problem.There is an array $$$a$$$ of $$$n$$$ different numbers. In one query you can ask the position of the second maximum element in a subsegment $$$a[l..r]$$$. Find the position of the maximum element in the array in no more than 20 queries.A subsegment $$$a[l..r]$$$ is all the elements $$$a_l, a_{l + 1}, ..., a_r$$$. After asking this subsegment you will be given the position of the second maximum from this subsegment in the whole array.
|
256 megabytes
|
import java.io.*;
import java.util.*;
import java.math.*;
public class Solution{
public static void main(String[] args) {
TaskA solver = new TaskA();
// int t = in.nextInt();
// for (int i = 1; i <= t ; i++) {
// solver.solve(i, in, out);
// }
solver.solve(1, in, out);
out.flush();
out.close();
}
static class TaskA {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n= in.nextInt();boolean isL=false;boolean isR=false;
int smax=query(1,n);
if(smax==1) {
isR=true;
}
else {
int x=query(1,smax);
if(x==smax) {
isL=true;
}
else {
isR=true;
}
}
if(isL) {
int l=1;int r=smax;
while(r>l) {
if(l==smax-1) {
System.out.println("! "+(l));return;
}
int mid=(r+l)/2;
int x=query(mid,smax);
if(x==smax) {
l=mid+1;
}
else {
r=mid;
}
}
System.out.println("! "+(l-1));return;
}
else {
int l=smax;int r=n;
while(r>l) {
if(r==smax+1) {
System.out.println("! "+(r));return;
}
int mid=(r+l)/2;
int x=query(smax,mid);
if(x==smax) {
r=mid;
}
else {
l=mid+1;
}
}
System.out.println("! "+(r));return;
}
}
}
static int query(int l,int r) {
System.out.println("? "+l+" "+r);
System.out.print ("\n");
int x=in.nextInt();
return x;
}
static boolean check(Pair[]arr,int mid,int n) {
int c=0;
for(int i=0;i<n;i++) {
if(mid-1-arr[i].first<=c&&c<=arr[i].second) {
c++;
}
}
return c>=mid;
}
static long sum(int[]arr) {
long s=0;
for(int x:arr) {
s+=x;
}
return s;
}
static long sum(long[]arr) {
long s=0;
for(long x:arr) {
s+=x;
}
return s;
}
static int gcd(int a, int b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
static void sort(int[] a) {
ArrayList<Integer> q = new ArrayList<>();
for (int i : a) q.add(i);
Collections.sort(q);
for (int i = 0; i < a.length; i++) a[i] = q.get(i);
}
static void sort(long[] a) {
ArrayList<Long> q = new ArrayList<>();
for (long i : a) q.add(i);
Collections.sort(q);
for (int i = 0; i < a.length; i++) a[i] = q.get(i);
}
static void println(int[][]arr) {
for(int i=0;i<arr.length;i++) {
for(int j=0;j<arr[0].length;j++) {
print(arr[i][j]+" ");
}
print("\n");
}
}
static void println(long[][]arr) {
for(int i=0;i<arr.length;i++) {
for(int j=0;j<arr[0].length;j++) {
print(arr[i][j]+" ");
}
print("\n");
}
}
static void println(int[]arr){
for(int i=0;i<arr.length;i++) {
print(arr[i]+" ");
}
print("\n");
}
static void println(long[]arr){
for(int i=0;i<arr.length;i++) {
print(arr[i]+" ");
}
print("\n");
}
static long[]input(int n){
long[]arr=new long[n];
for(int i=0;i<n;i++) {
arr[i]=in.nextInt();
}
return arr;
}
static long[]input(){
long n= in.nextInt();
long[]arr=new long[(int)n];
for(int i=0;i<n;i++) {
arr[i]=in.nextLong();
}
return arr;
}
////////////////////////////////////////////////////////
static class Pair {
long first;
long second;
Pair(long x, long y)
{
this.first = x;
this.second = y;
}
}
static void sortS(Pair arr[])
{
Arrays.sort(arr, new Comparator<Pair>() {
@Override public int compare(Pair p1, Pair p2)
{
return (int)(p1.second - p2.second);
}
});
}
static void sortF(Pair arr[])
{
Arrays.sort(arr, new Comparator<Pair>() {
@Override public int compare(Pair p1, Pair p2)
{
return (int)(p1.first - p2.first);
}
});
}
/////////////////////////////////////////////////////////////
static InputStream inputStream = System.in;
static OutputStream outputStream = System.out;
static InputReader in = new InputReader(inputStream);
static PrintWriter out = new PrintWriter(outputStream);
static void println(long c) {
out.println(c);
}
static void print(long c) {
out.print(c);
}
static void print(int c) {
out.print(c);
}
static void println(int x) {
out.println(x);
}
static void print(String s) {
out.print(s);
}
static void println(String s) {
out.println(s);
}
static void println(boolean b) {
out.println(b);
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
eb660c470760117dfd0b95acc10eee3b
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,900
| null |
standard output
| |
PASSED
|
ed1f8929d3f8468ca750027982e162ef
|
train_109.jsonl
|
1613658900
|
The only difference between the easy and the hard version is the limit to the number of queries.This is an interactive problem.There is an array $$$a$$$ of $$$n$$$ different numbers. In one query you can ask the position of the second maximum element in a subsegment $$$a[l..r]$$$. Find the position of the maximum element in the array in no more than 20 queries.A subsegment $$$a[l..r]$$$ is all the elements $$$a_l, a_{l + 1}, ..., a_r$$$. After asking this subsegment you will be given the position of the second maximum from this subsegment in the whole array.
|
256 megabytes
|
/*
"Everything in the universe is balanced. Every disappointment
you face in life will be balanced by something good for you!
Keep going, never give up."
Just have Patience + 1...
*/
import java.util.*;
import java.lang.*;
import java.io.*;
public class Solution {
public static void main(String[] args) throws java.lang.Exception {
out = new PrintWriter(new BufferedOutputStream(System.out));
sc = new FastReader();
int test = 1;
for (int t = 1; t <= test; t++) {
solve();
}
out.close();
}
private static void solve() {
int n = sc.nextInt();
int smax = interact(0, n - 1);
if (smax == 0 || interact(0, smax) != smax) {
int l = smax, r = n - 1;
while (r - l > 1) {
int mid = (l + r) / 2;
if (interact(smax, mid) == smax) {
r = mid;
}else {
l = mid;
}
}
out.println("! " + (r + 1));
}else {
int l = 0, r = smax;
while (r - l > 1) {
int mid = (l + r) / 2;
if (interact(mid, smax) == smax) {
l = mid;
}else {
r = mid;
}
}
out.println("! " + (l + 1));
}
}
private static int interact(int l, int r) {
if (l >= r) {
return -1;
}
out.println("? " + (l + 1) + " " + (r + 1));
out.flush();
int index = sc.nextInt();
return index - 1;
}
public static FastReader sc;
public static PrintWriter out;
static class FastReader
{
BufferedReader br;
StringTokenizer str;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (str == null || !str.hasMoreElements())
{
try
{
str = new StringTokenizer(br.readLine());
}
catch (IOException lastMonthOfVacation)
{
lastMonthOfVacation.printStackTrace();
}
}
return str.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException lastMonthOfVacation)
{
lastMonthOfVacation.printStackTrace();
}
return str;
}
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
eb660c470760117dfd0b95acc10eee3b
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,900
| null |
standard output
| |
PASSED
|
497e598cd8560d002e7357b9bd19ba1f
|
train_109.jsonl
|
1613658900
|
The only difference between the easy and the hard version is the limit to the number of queries.This is an interactive problem.There is an array $$$a$$$ of $$$n$$$ different numbers. In one query you can ask the position of the second maximum element in a subsegment $$$a[l..r]$$$. Find the position of the maximum element in the array in no more than 20 queries.A subsegment $$$a[l..r]$$$ is all the elements $$$a_l, a_{l + 1}, ..., a_r$$$. After asking this subsegment you will be given the position of the second maximum from this subsegment in the whole array.
|
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.Random;
import java.util.StringTokenizer;
public class Solution {
static ArrayList<String> list;
public static void main(String[] args) {
PrintWriter out = new PrintWriter(System.out);
FastScanner fs = new FastScanner();
int ti = 1;
outer: while (ti-- > 0) {
int n = fs.nextInt();
int l = 0;
int r = n;
int s = ck(0, n - 1);
if (s == 0 || ck(0, s) != s) {
l = s;
r = n - 1;
while (r - l > 1) {
int m = (l + r) / 2;
if (ck(s, m) == s)
r = m;
else
l = m;
}
System.out.println("! " + (r + 1));
return;
} else {
l = 0;
r = s;
while (r - l > 1) {
int m = (l + r) / 2;
if (ck(m, s) == s)
l = m;
else
r = m;
}
System.out.println("! " + (l + 1));
return;
}
}
out.close();
}
private static int ck(int l, int r) {
if (l >= r)
return -1;
l++;
r++;
System.out.println("? " + l + " " + r);
FastScanner fs = new FastScanner();
int k = fs.nextInt();
return k - 1;
}
static final int mod = 1_000_000_007;
static void sort(long[] a) {
Random random = new Random();
int n = a.length;
for (int i = 0; i < n; i++) {
int oi = random.nextInt(n);
long temp = a[oi];
a[oi] = a[i];
a[i] = temp;
}
Arrays.sort(a);
}
static void sort(int[] a) {
Random random = new Random();
int n = a.length;
for (int i = 0; i < n; i++) {
int oi = random.nextInt(n), temp = a[oi];
a[oi] = a[i];
a[i] = temp;
}
Arrays.sort(a);
}
static long 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 boolean isPrime(int n) {
if (n <= 1)
return false;
else if (n == 2)
return true;
else if (n % 2 == 0)
return false;
for (int i = 3; i <= Math.sqrt(n); i += 2) {
if (n % i == 0)
return false;
}
return true;
}
static 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 long binpow(long a, long b, long m) {
a %= m;
long res = 1;
while (b > 0) {
if (b % 2 == 1)
res = res * a % m;
a = a * a % m;
b >>= 1;
}
return res;
}
static int divCount(int n) {
boolean hash[] = new boolean[n + 1];
Arrays.fill(hash, true);
for (int p = 2; p * p < n; p++)
if (hash[p] == true)
for (int i = p * 2; i < n; i += p)
hash[i] = false;
int total = 1;
for (int p = 2; p <= n; p++) {
if (hash[p]) {
int count = 0;
if (n % p == 0) {
while (n % p == 0) {
n = n / p;
count++;
}
total = total * (count + 1);
}
}
}
return total;
}
static class FastScanner {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer("");
String next() {
while (!st.hasMoreTokens())
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
int[] readArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
long nextLong() {
return Long.parseLong(next());
}
}
static class Pair {
int a;
int b;
public Pair(int a, int b) {
this.a = a;
this.b = b;
}
}
static class ST {
int leftmost, rightmost;
ST lChild, rChild;
int sum;
public ST(ST cur) {
this.leftmost = cur.leftmost;
this.rightmost = cur.rightmost;
this.lChild = cur.lChild;
this.rChild = cur.rChild;
}
public ST(int leftmost, int rightmost) {
this.leftmost = leftmost;
this.rightmost = rightmost;
if (leftmost != rightmost) {
int mid = (leftmost + rightmost) / 2;
lChild = new ST(leftmost, mid);
rChild = new ST(mid + 1, rightmost);
recalc();
}
}
void recalc() {
if (leftmost == rightmost)
return;
sum = lChild.sum + rChild.sum;
}
ST pointUpdate(int index, int val) {
if (leftmost == rightmost) {
ST cur = new ST(index, index);
cur.sum += 1;
return cur;
}
ST cur = new ST(this);
int mid = (leftmost + rightmost) / 2;
if (index <= mid) {
cur.lChild = lChild.pointUpdate(index, val);
} else
cur.rChild = rChild.pointUpdate(index, val);
cur.recalc();
return cur;
}
int rangeSum(int l, int r) {
if (l > rightmost || r < leftmost)
return 0;
if (l <= leftmost && r >= rightmost)
return sum;
return lChild.rangeSum(l, r) + rChild.rangeSum(l, r);
}
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
eb660c470760117dfd0b95acc10eee3b
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,900
| null |
standard output
| |
PASSED
|
328378c45afc83312e2ebc6183bc634d
|
train_109.jsonl
|
1613658900
|
The only difference between the easy and the hard version is the limit to the number of queries.This is an interactive problem.There is an array $$$a$$$ of $$$n$$$ different numbers. In one query you can ask the position of the second maximum element in a subsegment $$$a[l..r]$$$. Find the position of the maximum element in the array in no more than 20 queries.A subsegment $$$a[l..r]$$$ is all the elements $$$a_l, a_{l + 1}, ..., a_r$$$. After asking this subsegment you will be given the position of the second maximum from this subsegment in the whole array.
|
256 megabytes
|
import java.util.*;
import java.lang.*;
import java.io.*;
public class Main {
void solve() {
int n = in.nextInt();
int low = 1;
int high = n;
int secondLast = query(1, n);
if (secondLast == 1) {
low = 2;
} else if (secondLast == n) {
high = n - 1;
} else {
int onLeft = query(1, secondLast);
if (onLeft == secondLast) {
high = secondLast - 1;
} else {
low = secondLast + 1;
}
}
int res = 0;
while (low <= high) {
int mid = (low + high) / 2;
int l = secondLast;
int r = mid;
if (mid < secondLast) {
l = mid;
r = secondLast;
}
int val = query(l, r);
if (val != secondLast) {
if (r == secondLast) {
high = mid - 1;
} else {
low = mid + 1;
}
} else {
res = mid;
if (r == secondLast) {
low = mid + 1;
} else {
high = mid - 1;
}
}
}
System.out.println("! " + res);
}
int query(int l, int r) {
System.out.println("? " + l + " " + r);
int val = in.nextInt();
System.out.flush();
return val;
}
public static void main (String[] args) {
// It happens - Syed Mizbahuddin
Main sol = new Main();
int t = 1;
// t = in.nextInt();
while (t-- != 0) {
sol.solve();
}
System.out.print(out);
}
<T> void println(T[] s) {
if (err == null)return;
err.println(Arrays.toString(s));
}
<T> void println(T s) {
if (err == null)return;
err.println(s);
}
void println(int s) {
if (err == null)return;
err.println(s);
}
void println(int[] a) {
if (err == null)return;
println(Arrays.toString(a));
}
int[] array(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = in.nextInt();
}
return a;
}
int[] array1(int n) {
int[] a = new int[n + 1];
for (int i = 1; i <= n; i++) {
a[i] = in.nextInt();
}
return a;
}
int max(int[] a) {
int max = a[0];
for (int i = 0; i < a.length; i++)max = Math.max(max, a[i]);
return max;
}
int min(int[] a) {
int min = a[0];
for (int i = 0; i < a.length; i++)min = Math.min(min, a[i]);
return min;
}
int count(int[] a, int x) {
int count = 0;
for (int i = 0; i < a.length; i++)if (x == a[i])count++;
return count;
}
void printArray(int[] a) {
for (int ele : a)out.append(ele + " ");
out.append("\n");
}
static {
try {
// System.setIn(new FileInputStream("input.txt"));
// System.setOut(new PrintStream(new FileOutputStream("output.txt")));
// err = new PrintStream(new FileOutputStream("error.txt"));
} catch (Exception e) {}
}
static FastReader in;
static StringBuilder out;
static PrintStream err;
static String yes , no , endl;
final int MAX;
final int MIN;
int mod ;
Main() {
in = new FastReader();
out = new StringBuilder();
MAX = Integer.MAX_VALUE;
MIN = Integer.MIN_VALUE;
mod = (int)1e9 + 7;
yes = "YES\n";
no = "NO\n";
endl = "\n";
}
class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(
new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() { return Integer.parseInt(next()); }
long nextLong() { return Long.parseLong(next()); }
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
class Pair implements Comparable<Pair> {
int first , second;
Pair(int first, int second) {
this.first = first;
this.second = second;
}
public int compareTo(Pair b) {
return this.first - b.first;
}
public String toString() {
String s = "{ " + Integer.toString(first) + " , " + Integer.toString(second) + " }";
return s;
}
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
eb660c470760117dfd0b95acc10eee3b
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,900
| null |
standard output
| |
PASSED
|
8cbada4c6d2e0e7fc686fcecaaa2ecf3
|
train_109.jsonl
|
1613658900
|
The only difference between the easy and the hard version is the limit to the number of queries.This is an interactive problem.There is an array $$$a$$$ of $$$n$$$ different numbers. In one query you can ask the position of the second maximum element in a subsegment $$$a[l..r]$$$. Find the position of the maximum element in the array in no more than 20 queries.A subsegment $$$a[l..r]$$$ is all the elements $$$a_l, a_{l + 1}, ..., a_r$$$. After asking this subsegment you will be given the position of the second maximum from this subsegment in the whole array.
|
256 megabytes
|
import java.io.DataInputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Map;
import java.util.TreeMap;
public class Main {
private static void run() throws IOException {
int n = in.nextInt();
// TreeMap<Double, Integer> map = new TreeMap<>();
// for (int i = 1; i <= n; i++) {
// map.put(Math.random(), i);
// }
// a = new int[n];
// int index = 0;
// for (Map.Entry<Double, Integer> now : map.entrySet()) {
// a[index++] = now.getValue();
// }
//// print_array(a);
// System.err.flush();
query_with_second(1, n, query(1, n));
}
private static void query_with_second(int left, int right, int second) throws IOException {
if (left == right) {
out.printf("! %d \n", left);
out.flush();
// check(left);
return;
}
int mid = (left + right) >> 1;
if (second <= mid) {
int query_left = query(Math.min(left, second), mid);
if (query_left == second) {
query_with_second(left, mid, second);
} else {
query_with_second(mid + 1, right, second);
}
} else {
int query_right = query(mid + 1, Math.max(right, second));
if (query_right == second) {
query_with_second(mid + 1, right, second);
} else {
query_with_second(left, mid, second);
}
}
}
// static int[] a;
// static int count = 0;
//
// private static void check(int ans) {
// int[] tmp = new int[a.length];
// System.arraycopy(a, 0, tmp, 0, a.length);
// Arrays.sort(tmp);
// System.err.println(tmp[a.length - 1] + " " + a[ans - 1] + " " + (tmp[a.length - 1] == a[ans - 1]));
// System.err.println("count: " + count);
// System.err.flush();
// if (tmp[a.length - 1] != a[ans - 1] || count > 20) {
// System.exit(0);
// }
//
// count = 0;
// }
private static int query(int left, int right) throws IOException {
if (left == right) return -1;
out.printf("? %d %d\n", left, right);
out.flush();
return in.nextInt();
// count++;
// int[] tmp = new int[right - left + 1];
// for (int i = 0; i < right - left + 1; i++) {
// tmp[i] = a[left + i - 1];
// }
// Arrays.sort(tmp);
// for (int i = left; i <= right; i++) {
// if (a[i - 1] == tmp[right - left - 1]) {
// System.err.println("input: " + i);
// System.err.flush();
// return i;
// }
// }
// System.err.println("input error");
// System.err.flush();
// throw new RuntimeException();
}
public static void main(String[] args) throws IOException {
in = new Reader();
out = new PrintWriter(new OutputStreamWriter(System.out));
// int t = in.nextInt();
// for (int i = 0; i < t; i++) {
// }
run();
out.flush();
in.close();
out.close();
}
private static int gcd(int a, int b) {
if (a == 0 || b == 0)
return 0;
while (b != 0) {
int tmp;
tmp = a % b;
a = b;
b = tmp;
}
return a;
}
static final long mod = 1000000007;
static long pow_mod(long a, long b) {
long result = 1;
while (b != 0) {
if ((b & 1) != 0) result = (result * a) % mod;
a = (a * a) % mod;
b >>= 1;
}
return result;
}
private static long multiplied_mod(long... longs) {
long ans = 1;
for (long now : longs) {
ans = (ans * now) % mod;
}
return ans;
}
@SuppressWarnings("FieldCanBeLocal")
private static Reader in;
private static PrintWriter out;
private static void print_array(int[] array) {
for (int now : array) {
System.err.print(now);
System.err.print(' ');
}
System.err.println();
}
private static void print_array(long[] array) {
for (long now : array) {
out.print(now);
out.print(' ');
}
out.println();
}
static class Reader {
private static final int BUFFER_SIZE = 1 << 16;
private final DataInputStream din;
private final byte[] buffer;
private int bufferPointer, bytesRead;
Reader() {
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException {
final byte[] buf = new byte[1024]; // line length
int cnt = 0, c;
while ((c = read()) != -1) {
if (c == '\n') {
break;
}
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int nextSign() throws IOException {
byte c = read();
while ('+' != c && '-' != c) {
c = read();
}
return '+' == c ? 0 : 1;
}
private static boolean isSpaceChar(int c) {
return !(c >= 33 && c <= 126);
}
public int skip() throws IOException {
int b;
// noinspection ALL
while ((b = read()) != -1 && isSpaceChar(b)) {
;
}
return b;
}
public char nc() throws IOException {
return (char) skip();
}
public String next() throws IOException {
int b = skip();
final StringBuilder sb = new StringBuilder();
while (!isSpaceChar(b)) { // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = read();
}
return sb.toString();
}
public int nextInt() throws IOException {
int ret = 0;
byte c = read();
while (c <= ' ') {
c = read();
}
final boolean neg = c == '-';
if (neg) {
c = read();
}
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg) {
return -ret;
}
return ret;
}
public long nextLong() throws IOException {
long ret = 0;
byte c = read();
while (c <= ' ') {
c = read();
}
final boolean neg = c == '-';
if (neg) {
c = read();
}
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (neg) {
return -ret;
}
return ret;
}
public double nextDouble() throws IOException {
double ret = 0, div = 1;
byte c = read();
while (c <= ' ') {
c = read();
}
final boolean neg = c == '-';
if (neg) {
c = read();
}
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (c == '.') {
while ((c = read()) >= '0' && c <= '9') {
ret += (c - '0') / (div *= 10);
}
}
if (neg) {
return -ret;
}
return ret;
}
private void fillBuffer() throws IOException {
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1) {
buffer[0] = -1;
}
}
private byte read() throws IOException {
if (bufferPointer == bytesRead) {
fillBuffer();
}
return buffer[bufferPointer++];
}
public void close() throws IOException {
din.close();
}
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
eb660c470760117dfd0b95acc10eee3b
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,900
| null |
standard output
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.