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
|
39e41a4bc0793fe587b7a8b0f45c8ff5
|
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 40 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 Div2.C;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class GuessingTheGreatest {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
int u = 0;
int v = n - 1;
while (u < v) {
System.out.format("? %d %d\n", u + 1, v + 1);
int res = Integer.parseInt(br.readLine());
res--;
if (v - u == 1) {
if(res==u)
u++;
else
v--;
} else {
int mid = (u + v) / 2;
if (res <= mid) {
System.out.format("? %d %d\n", u + 1, mid + 1);
int res1 = Integer.parseInt(br.readLine());
res1--;
if (res == res1) {
v = mid;
} else
u = mid + 1;
} else {
System.out.format("? %d %d\n", mid + 1, v + 1);
int res1 = Integer.parseInt(br.readLine());
res1--;
if (res == res1) {
u = mid;
} else
v = mid - 1;
}
}
}
System.out.format("! %d\n", u + 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"
] |
b3e8fe76706ba17cb285c75459508334
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,600
| null |
standard output
| |
PASSED
|
c9fc47f7fcb5eec27c5bb5b8a2252a10
|
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 40 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 Main{
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[] nextArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = nextInt();
return a;
}
long[] nextArray(long n) {
long[] a = new long[(int) n];
for (int i = 0; i < n; i++) a[i] = nextLong();
return a;
}
long nextLong() {
return Long.parseLong(next());
}
}
static class FastWriter extends PrintWriter {
FastWriter(){
super(System.out);
}
void println(int[] array) {
for(int i=0; i<array.length; i++) {
print(array[i]+" ");
}
println();
}
void println(long [] array) {
for(int i=0; i<array.length; i++) {
print(array[i]+" ");
}
println();
}
}
static int MOD=998244353;
public static void main(String[] args) throws IOException {
FastScanner in = new FastScanner();
FastWriter out = new FastWriter();
//int t=in.nextInt();
int t=1;
while (t-->0){
int n=in.nextInt();
out.println("? 1 "+n);
out.flush();
int pos=in.nextInt();
int pos1=n;
if(pos!=1){
out.println("? 1 "+pos);
out.flush();
pos1=in.nextInt();
}
int i=1,j=n;
if(pos==pos1){
j=pos;
while (i+1<j){
int mid=(i+j)/2;
out.println("? "+mid+" "+pos);
out.flush();
pos1=in.nextInt();
if(pos==pos1){
i=mid;
}else {
j=mid;
}
}
out.println("! "+i);
out.flush();
}else {
i=pos;
while (i+1<j){
int mid=(i+j)/2;
out.println("? "+pos+" "+mid);
out.flush();
pos1=in.nextInt();
if(pos==pos1){
j=mid;
}else {
i=mid;
}
}
out.println("! "+j);
out.flush();
}
}
out.close();
}
static boolean check(int[] a){
for (int i = 0; i < a.length - 1; i++) {
if(a[i]!=a[i+1]){
return false;
}
}
return true;
}
//Arrays.sort(a, (o1, o2) -> (o1[0] - o2[0]));
static int subarray_lessthan_k(int[] A,int n,int k){
int s=0,e=0,sum=0,cnt=0;
while(e<n){
sum+=A[e];
while(s<=e&&sum>k){
sum-=A[s++];
}
cnt+=e-s+1;
e++;
}
return cnt;
}
static int totalPrimeFactors(int n) {
int cnt=0;
while (n%2==0) {
cnt++;
n /= 2;
}
int num= (int) Math.sqrt(n);
for (int i = 3; i <= num; i+= 2) {
while (n%i == 0) {
cnt++;
n /= i;
num=(int)Math.sqrt(n);
}
}
if (n > 2){
cnt++;
}
return cnt;
}
static char get(int i){
return (char)(i+'a');
}
static boolean distinct(int num){
HashSet<Integer> set=new HashSet<>();
int len=String.valueOf(num).length();
while (num!=0){
set.add(num%10);
num/=10;
}
return set.size()==len;
}
static int maxSubArraySum(int a[],int st,int en) {
int max_s = Integer.MIN_VALUE, max_e = 0,ind=0,ind1=1;
for (int i = st; i <= en; i++) {
max_e+= a[i];
if (max_s < max_e){
max_s = max_e;
ind=ind1;
}
if (max_e < 0){
max_e = 0;
ind1=i+1;
}
}
if(st==0){
return max_s;
}
if(ind==1){
return a[0]+2*max_s;
}else {
return 2*max_s+maxSubArraySum(a,0,ind-1);
}
//return max_s;
}
static void segmentedSieve(ArrayList<Integer> res,int low, int high) {
if(low < 2){
low = 2;
}
ArrayList<Integer> prime = new ArrayList<>();
simpleSieve(high, prime);
boolean[] mark = new boolean[high - low + 1];
for (int i = 0; i < mark.length; i++){
mark[i] = true;
}
for (int i = 0; i < prime.size(); i++) {
int loLim = (low / prime.get(i)) * prime.get(i);
if (loLim < low){
loLim += prime.get(i);
}
if (loLim == prime.get(i)){
loLim += prime.get(i);
}
for (int j = loLim; j <= high; j += prime.get(i)) {
mark[j - low] = false;
}
}
for (int i = low; i <= high; i++) {
if (mark[i - low]){
res.add(i);
}
}
}
static void simpleSieve(int limit, ArrayList<Integer> prime) {
int bound = (int)Math.sqrt(limit);
boolean[] mark = new boolean[bound + 1];
for (int i = 0; i <= bound; i++){
mark[i] = true;
}
for (int i = 2; i * i <= bound; i++) {
if (mark[i]) {
for (int j = i * i; j <= bound; j += i){
mark[j] = false;
}
}
}
for (int i = 2; i <= bound; i++) {
if (mark[i]){
prime.add(i);
}
}
}
static int highestPowerOf2(int n) {
if (n < 1){ return 0; }
int res = 1;
for (int i = 0; i < 8 * Integer.BYTES; i++) {
int curr = 1 << i;
if (curr > n){ break; }
res = curr;
}
return res;
}
static int reduceFraction(int x, int y) {
int d= gcd(x, y);
return x/d+y/d;
}
static boolean subset(int[] ar,int n,int sum){
if(sum==0){
return true;
}
if(n<0||sum<0){
return false;
}
return subset(ar,n-1,sum)||subset(ar,n-1,sum-ar[n]);
}
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 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 lcm(long a, long b) {
return (a * b) / gcd(a, b);
}
static int lcm(int a, int b) {
return (a * b) / gcd(a, b);
}
static boolean isPowerOfTwo(long n) {
if(n==0){
return false;
}
while (n%2==0){
n/=2;
}
return n==1;
}
static boolean isPerfectSquare(int x){
if (x >= 0) {
int sr = (int)Math.sqrt(x);
return ((sr * sr) == x);
}
return false;
}
static int lower_bound(int[] arr, int x) {
int low_limit = 0, high_limit = arr.length, mid;
while (low_limit < high_limit) {
mid = (low_limit + high_limit) / 2;
if (arr[mid] >= x){
high_limit = mid;
}else{
low_limit = mid + 1;
}
}
return low_limit;
}
static int upper_bound(int[] arr, int x) {
int low_limit = 0, high_limit = arr.length, mid;
while (low_limit < high_limit) {
mid = (low_limit + high_limit) / 2;
if (arr[mid] > x){
high_limit = mid;
}else{
low_limit = mid + 1;
}
}
return low_limit;
}
static int binarySearch(int[] ar,int n,int num){
int low=0,high=n-1;
while (low<=high){
int mid=(low+high)/2;
if(ar[mid]==num){
return mid;
}else if(ar[mid]>num){
high=mid-1;
}else {
low=mid+1;
}
}
return -1;
}
static int fib(int n) {
long F[][] = new long[][]{{1,1},{1,0}};
if (n == 0){
return 0;
}
power(F, n-1);
return (int)F[0][0];
}
static void multiply(long F[][], long M[][]) {
long x = (F[0][0]*M[0][0])%1000000007 + (F[0][1]*M[1][0])%1000000007;
long y = (F[0][0]*M[0][1])%1000000007 + (F[0][1]*M[1][1])%1000000007;
long z = (F[1][0]*M[0][0])%1000000007 + (F[1][1]*M[1][0])%1000000007;
long w = (F[1][0]*M[0][1])%1000000007 + (F[1][1]*M[1][1])%1000000007;
F[0][0] = x%1000000007;
F[0][1] = y%1000000007;
F[1][0] = z%1000000007;
F[1][1] = w%1000000007;
}
static void power(long F[][], int n) {
if( n == 0 || n == 1){
return;
}
long M[][] = new long[][]{{1,1},{1,0}};
power(F, n/2);
multiply(F, F);
if (n%2 != 0){
multiply(F, M);
}
}
}
|
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"
] |
b3e8fe76706ba17cb285c75459508334
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,600
| null |
standard output
| |
PASSED
|
30bc9cd673ff25b5e2afc80c650eaf09
|
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 40 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 C1 {
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());
solve(f, out, 0, n-1, -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;
}
public static void solve(BufferedReader f, PrintWriter out, int l, int r, int pos) throws IOException{
if(l == r) {
out.println("! " + (l + 1));
return;
}
if(pos == -1){
pos = query(f, out, l, r);
}
int mid = (l+r)/2;
if(pos <= mid){
int npos = query(f, out, l, mid);
if(pos == npos) {
solve(f, out, l, mid, pos);
}else{
solve(f, out, mid+1, r, -1);
}
}else{
int npos = query(f, out, mid+1, r);
if(pos == npos) {
solve(f, out, mid+1, r, pos);
}else {
solve(f, out, l, mid, -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"
] |
b3e8fe76706ba17cb285c75459508334
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,600
| null |
standard output
| |
PASSED
|
a876a787d6dd8fbdedfd0abbe0ca0332
|
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 40 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.*;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class First {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskA solver = new TaskA();
//int a = 1;
int t;
//t = in.nextInt();
t = 1;
while (t > 0) {
//out.print("Case #"+(a++)+": ");
solver.call(in,out);
t--;
}
out.close();
}
static class TaskA {
public void call(InputReader in, PrintWriter out) {
int n;
n = in.nextInt();
int l, r, mid, a = 0, b = 0;
l = 1;
r = n;
Map<String, Integer> map = new HashMap<>();
while(true){
if(r-l<=2){
break;
}
mid = (l + r) / 2;
if(map.getOrDefault(l+" "+r, 0)==0) {
System.out.println("? " + l + " " + r);
a = in.nextInt();
System.out.flush();
map.put(l+" "+r, a);
}
else{
a = map.get(l+" "+r);
}
if(a<=mid){
if(map.getOrDefault(l+" "+mid, 0)==0) {
System.out.println("? " + l + " " + mid);
b = in.nextInt();
System.out.flush();
map.put(l+" "+mid, b);
}
else{
b = map.get(l+" "+mid);
}
if(b==a){
r = mid;
}
else{
l = mid+1;
}
}
else{
if(map.getOrDefault((mid+1) + " "+r , 0)==0) {
System.out.println("? " + (mid + 1) + " " + r);
b = in.nextInt();
System.out.flush();
map.put((mid+1)+" "+r , b);
}
else{
b = map.get((mid+1)+" "+r);
}
if(b==a){
l = mid+1;
}
else{
r = mid;
}
}
}
if(map.getOrDefault(l+" "+r, 0)==0) {
System.out.println("? " + l + " " + r);
a = in.nextInt();
System.out.flush();
map.put(l+" "+r, a);
}
else{
a = map.get(l+" "+r);
}
if(r-l==1){
if(l==a){
out.println("! "+r);
}
else{
out.println("! "+l);
}
}
else{
if(a==(l+r)/2){
if(map.getOrDefault((l+r)/2+" "+r,0)==0) {
System.out.println("? " + (l + r) / 2 + " " + r);
b = in.nextInt();
System.out.flush();
map.put((l+r)/2+" "+r,b);
}
else{
b = map.get((l+r)/2+" "+r);
}
if(b==a){
out.println("! "+r);
}
else{
out.println("! "+l);
}
return;
}
if(a==r){
if(map.getOrDefault(l+" "+(l+r)/2,0)==0) {
System.out.println("? " + l + " " + (l + r) / 2);
b = in.nextInt();
System.out.flush();
map.put(l+" "+(l+r)/2, b);
}
else{
b = map.get(l+" "+(l+r)/2);
}
if(b==l){
out.println("! "+(l+r)/2);
}
else{
out.println("! "+l);
}
}
else{
int c;
if(map.getOrDefault((l+r)/2+" "+r,0)==0) {
System.out.println("? " + (l + r) / 2 + " " + r);
c = in.nextInt();
System.out.flush();
map.put((l+r)/2+" "+r,c);
}
else{
c = map.get((l+r)/2+" "+r);
}
if(c==r){
out.println("! "+(l+r)/2);
}
else{
out.println("! "+r);
}
}
}
}
}
static int gcd(int a, int b)
{
if (a == 0)
return b;
return gcd(b % a, a);
}
static int lcm(int a, int b)
{
return (a / gcd(a, b)) * b;
}
static class answer implements Comparable<answer>{
int a;
int b;
public answer(int a, int b) {
this.a = a;
this.b = b;
}
@Override
public int compareTo(answer o) {
return o.a - this.a;
}
@Override
public boolean equals(Object o){
if(o instanceof answer){
answer c = (answer)o;
return a == c.a && b == c.b;
}
return false;
}
}
static class answer1 implements Comparable<answer1>{
int a, b, c;
public answer1(int a, int b, int c) {
this.a = a;
this.b = b;
this.c = c;
}
@Override
public int compareTo(answer1 o) {
return this.a - o.a;
}
}
static long gcd(long a, long b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
static void sort(long[] a) {
ArrayList<Long> l=new ArrayList<>();
for (long i:a) l.add(i);
Collections.sort(l);
for (int i=0; i<a.length; i++) a[i]=l.get(i);
}
static final Random random=new Random();
static void shuffleSort(int[] a) {
int n=a.length;
for (int i=0; i<n; i++) {
int oi=random.nextInt(n), temp=a[oi];
a[oi]=a[i]; a[i]=temp;
}
Arrays.sort(a);
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong(){
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
}
|
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"
] |
b3e8fe76706ba17cb285c75459508334
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,600
| null |
standard output
| |
PASSED
|
8ff02311818260a78fa051153ad435dd
|
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 40 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.*;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class First {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskA solver = new TaskA();
//int a = 1;
int t;
//t = in.nextInt();
t = 1;
while (t > 0) {
//out.print("Case #"+(a++)+": ");
solver.call(in,out);
t--;
}
out.close();
}
static class TaskA {
public void call(InputReader in, PrintWriter out) {
int n;
n = in.nextInt();
int l, r, mid, a, b;
l = 1;
r = n;
while(true){
if(r-l<=2){
break;
}
mid = (l+r)/2;
System.out.println("? "+l+" "+r);
a = in.nextInt();
System.out.flush();
if(a<=mid){
System.out.println("? "+l+" "+ mid);
b = in.nextInt();
System.out.flush();
if(b==a){
r = mid;
}
else{
l = mid+1;
}
}
else{
System.out.println("? "+(mid+1)+" "+ r);
b = in.nextInt();
System.out.flush();
if(b==a){
l = mid+1;
}
else{
r = mid;
}
}
}
System.out.println("? "+l+" "+r);
a = in.nextInt();
System.out.flush();
if(r-l==1){
if(l==a){
out.println("! "+r);
}
else{
out.println("! "+l);
}
}
else{
if(a==(l+r)/2){
System.out.println("? "+(l+r)/2+" "+r);
b = in.nextInt();
System.out.flush();
if(b==a){
out.println("! "+r);
}
else{
out.println("! "+l);
}
return;
}
if(a==r){
System.out.println("? "+l+" "+(l+r)/2);
b = in.nextInt();
System.out.flush();
if(b==l){
out.println("! "+(l+r)/2);
}
else{
out.println("! "+l);
}
}
else{
System.out.println("? "+(l+r)/2+" "+r);
int c = in.nextInt();
System.out.flush();
if(c==r){
out.println("! "+(l+r)/2);
}
else{
out.println("! "+r);
}
}
}
}
}
static int gcd(int a, int b)
{
if (a == 0)
return b;
return gcd(b % a, a);
}
static int lcm(int a, int b)
{
return (a / gcd(a, b)) * b;
}
static class answer implements Comparable<answer>{
int a;
int b;
public answer(int a, int b) {
this.a = a;
this.b = b;
}
@Override
public int compareTo(answer o) {
return o.a - this.a;
}
@Override
public boolean equals(Object o){
if(o instanceof answer){
answer c = (answer)o;
return a == c.a && b == c.b;
}
return false;
}
}
static class answer1 implements Comparable<answer1>{
int a, b, c;
public answer1(int a, int b, int c) {
this.a = a;
this.b = b;
this.c = c;
}
@Override
public int compareTo(answer1 o) {
return this.a - o.a;
}
}
static long gcd(long a, long b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
static void sort(long[] a) {
ArrayList<Long> l=new ArrayList<>();
for (long i:a) l.add(i);
Collections.sort(l);
for (int i=0; i<a.length; i++) a[i]=l.get(i);
}
static final Random random=new Random();
static void shuffleSort(int[] a) {
int n=a.length;
for (int i=0; i<n; i++) {
int oi=random.nextInt(n), temp=a[oi];
a[oi]=a[i]; a[i]=temp;
}
Arrays.sort(a);
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong(){
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
}
|
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"
] |
b3e8fe76706ba17cb285c75459508334
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,600
| null |
standard output
| |
PASSED
|
d8849ec148c1a39f177f72df222bfd5b
|
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 40 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 BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
static PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
static int n;
static Scanner sca = new Scanner(System.in);
public static void main(String[] args) throws Exception {
int n = sca.nextInt();
int l = 0;
int r = n;
while(r-l>1) {
int m = (l+r)/2;
int smax = ask(l,r-1);
if(smax<m) {
if(ask(l,m-1)==smax) {
r = m;
}else {
l = m;
}
}else {
if(ask(m,r-1)==smax) {
l = m;
}else {
r = m;
}
}
}
System.out.println("! "+r);
}
static int ask(int l, int r) throws Exception {
if(l>=r) return -1;
System.out.println("? "+(l+1)+" "+(r+1));
int a = sca.nextInt();
return a-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"
] |
b3e8fe76706ba17cb285c75459508334
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,600
| null |
standard output
| |
PASSED
|
3fdc8a837ed89a428333f7c1349eb670
|
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 40 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 GuessingTheGreatestEasyVersion {
public static void main(String[] args) throws IOException {
Scanner in = new Scanner(System.in);
int N = in.nextInt();
int l = 1, r = N;
while (l < r) {
System.out.println("? " + l + " " + r);
System.out.flush();
int i = in.nextInt();
int mid = (l + r + 1) / 2;
if (i < mid) {
if (l + 1 == mid) {
l = mid;
} else {
System.out.println("? " + l + " " + (mid - 1));
System.out.flush();
int j = in.nextInt();
if (j == i) {
r = mid - 1;
} else {
l = mid;
}
}
} else {
if (mid == r) {
r = mid - 1;
} else {
System.out.println("? " + mid + " " + r);
System.out.flush();
int j = in.nextInt();
if (j == i) {
l = mid;
} else {
r = mid - 1;
}
}
}
}
System.out.println("! " + 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 8
|
standard input
|
[
"binary search",
"interactive"
] |
b3e8fe76706ba17cb285c75459508334
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,600
| null |
standard output
| |
PASSED
|
7fb06d7201f3cbde573d8c120cb2ce9e
|
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 40 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"
] |
b3e8fe76706ba17cb285c75459508334
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,600
| null |
standard output
| |
PASSED
|
a4ac08ecc0e6fb94e6d0650266bbac44
|
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 40 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.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.TreeMap;
public class Main implements Runnable {
int n, m;
static boolean use_n_tests = false;
int N = -1;
long mod = 1000000007;
void solve(FastScanner in, PrintWriter out, int testNumber) {
n = in.nextInt();
out.println("! " + rec(0, n, -1));
}
int rec(int l, int r, int p) {
if (r - l <= 1) {
return r;
}
int bigPos = p;
if (p == -1) {
bigPos = ask(l, r - 1);
}
int mid = (l + r) / 2;
if (bigPos < mid) {
int left = ask(l, mid - 1);
if (left == bigPos) {
return rec(l, mid, left);
} else {
return rec(mid, r, -1);
}
} else {
int right = ask(mid, r - 1);
if (right == bigPos) {
return rec(mid, r, right);
} else {
return rec(l, mid, -1);
}
}
}
// ****************************** template code ***********
int ask(int l, int r) {
if (l >= r) {
return -1;
}
System.out.printf("? %d %d\n", l + 1, r + 1);
System.out.flush();
return in.nextInt() - 1;
}
static int stack_size = 1 << 27;
class Mod {
long mod;
Mod(long mod) {
this.mod = mod;
}
long add(long a, long b) {
a = mod(a);
b = mod(b);
return (a + b) % mod;
}
long sub(long a, long b) {
a = mod(a);
b = mod(b);
return (a - b + mod) % mod;
}
long mul(long a, long b) {
a = mod(a);
b = mod(b);
return a * b % mod;
}
long div(long a, long b) {
a = mod(a);
b = mod(b);
return (a * inv(b)) % mod;
}
public long inv(long r) {
if (r == 1)
return 1;
return ((mod - mod / r) * inv(mod % r)) % mod;
}
private long mod(long a) {
return a % mod;
}
}
class Coeff {
long mod;
long[][] C;
long[] fact;
boolean cycleWay = false;
Coeff(int n, long mod) {
this.mod = mod;
fact = new long[n + 1];
fact[0] = 1;
for (int i = 1; i <= n; i++) {
fact[i] = i;
fact[i] %= mod;
fact[i] *= fact[i - 1];
fact[i] %= mod;
}
}
Coeff(int n, int m, long mod) {
// n > m
cycleWay = true;
this.mod = mod;
C = new long[n + 1][m + 1];
for (int i = 0; i <= n; i++) {
for (int j = 0; j <= Math.min(i, m); j++) {
if (j == 0 || j == i) {
C[i][j] = 1;
} else {
C[i][j] = C[i - 1][j - 1] + C[i - 1][j];
C[i][j] %= mod;
}
}
}
}
public long C(int n, int m) {
if (cycleWay) {
return C[n][m];
}
return fC(n, m);
}
private long fC(int n, int m) {
return (fact[n] * inv(fact[n - m] * fact[m] % mod)) % mod;
}
private long inv(long r) {
if (r == 1)
return 1;
return ((mod - mod / r) * inv(mod % r)) % mod;
}
}
class Pair {
int first;
int second;
public int getFirst() {
return first;
}
public int getSecond() {
return second;
}
}
class MultisetTree<T> {
int size = 0;
TreeMap<T, Integer> mp = new TreeMap<>();
void add(T x) {
mp.merge(x, 1, Integer::sum);
size++;
}
void remove(T x) {
if (mp.containsKey(x)) {
mp.merge(x, -1, Integer::sum);
if (mp.get(x) == 0) {
mp.remove(x);
}
size--;
}
}
boolean contains(T x) {
return mp.containsKey(x);
}
T greatest() {
return mp.lastKey();
}
T smallest() {
return mp.firstKey();
}
int size() {
return size;
}
int diffSize() {
return mp.size();
}
}
class Multiset<T> {
int size = 0;
Map<T, Integer> mp = new HashMap<>();
void add(T x) {
mp.merge(x, 1, Integer::sum);
size++;
}
boolean contains(T x) {
return mp.containsKey(x);
}
void remove(T x) {
if (mp.containsKey(x)) {
mp.merge(x, -1, Integer::sum);
if (mp.get(x) == 0) {
mp.remove(x);
}
size--;
}
}
int size() {
return size;
}
int diffSize() {
return mp.size();
}
}
static class Range {
int l, r;
int id;
public int getL() {
return l;
}
public int getR() {
return r;
}
public Range(int l, int r, int id) {
this.l = l;
this.r = r;
this.id = id;
}
}
static class Array {
static Range[] readRanges(int n, FastScanner in) {
Range[] result = new Range[n];
for (int i = 0; i < n; i++) {
result[i] = new Range(in.nextInt(), in.nextInt(), i);
}
return result;
}
static List<List<Integer>> intInit2D(int n) {
List<List<Integer>> res = new ArrayList<>();
for (int i = 0; i < n; i++) {
res.add(new ArrayList<>());
}
return res;
}
static boolean isSorted(Integer[] a) {
for (int i = 0; i < a.length - 1; i++) {
if (a[i] > a[i + 1]) {
return false;
}
}
return true;
}
static public long sum(int[] a) {
long sum = 0;
for (int x : a) {
sum += x;
}
return sum;
}
static public long sum(long[] a) {
long sum = 0;
for (long x : a) {
sum += x;
}
return sum;
}
static public long sum(Integer[] a) {
long sum = 0;
for (int x : a) {
sum += x;
}
return sum;
}
static public int min(Integer[] a) {
int mn = Integer.MAX_VALUE;
for (int x : a) {
mn = Math.min(mn, x);
}
return mn;
}
static public int min(int[] a) {
int mn = Integer.MAX_VALUE;
for (int x : a) {
mn = Math.min(mn, x);
}
return mn;
}
static public int max(Integer[] a) {
int mx = Integer.MIN_VALUE;
for (int x : a) {
mx = Math.max(mx, x);
}
return mx;
}
static public int max(int[] a) {
int mx = Integer.MIN_VALUE;
for (int x : a) {
mx = Math.max(mx, x);
}
return mx;
}
static public int[] readint(int n, FastScanner in) {
int[] out = new int[n];
for (int i = 0; i < out.length; i++) {
out[i] = in.nextInt();
}
return out;
}
}
class Graph {
List<List<Integer>> graph;
Graph(int n) {
create(n);
}
void create(int n) {
List<List<Integer>> graph = new ArrayList<>();
for (int i = 0; i < n; i++) {
graph.add(new ArrayList<>());
}
this.graph = graph;
}
void readBi(int m, FastScanner in) {
for (int i = 0; i < m; i++) {
int v = in.nextInt() - 1;
int u = in.nextInt() - 1;
graph.get(v).add(u);
graph.get(u).add(v);
}
}
}
class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(InputStream io) {
br = new BufferedReader(new InputStreamReader(io));
}
public String line() {
String result = "";
try {
result = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
public String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public int[] nextArray(int n) {
int[] res = new int[n];
for (int i = 0; i < n; i++) {
res[i] = in.nextInt();
}
return res;
}
public long[] nextArrayL(int n) {
long[] res = new long[n];
for (int i = 0; i < n; i++) {
res[i] = in.nextLong();
}
return res;
}
public Long[] nextArrayL2(int n) {
Long[] res = new Long[n];
for (int i = 0; i < n; i++) {
res[i] = in.nextLong();
}
return res;
}
public Integer[] nextArray2(int n) {
Integer[] res = new Integer[n];
for (int i = 0; i < n; i++) {
res[i] = in.nextInt();
}
return res;
}
public long nextLong() {
return Long.parseLong(next());
}
}
void run_t_tests() {
int t = in.nextInt();
int i = 0;
while (t-- > 0) {
solve(in, out, i++);
}
}
void run_one() {
solve(in, out, -1);
}
@Override
public void run() {
in = new FastScanner(System.in);
out = new PrintWriter(System.out);
if (use_n_tests) {
run_t_tests();
} else {
run_one();
}
out.close();
}
static FastScanner in;
static PrintWriter out;
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(null, new Main(), "", stack_size);
thread.start();
thread.join();
}
}
|
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"
] |
b3e8fe76706ba17cb285c75459508334
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,600
| null |
standard output
| |
PASSED
|
7763e7d70d42e50259a1ad47efc0bf47
|
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 40 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
|
//I AM THE CREED
/* //I AM THE CREED
/* package codechef; // don't place package name! */
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.util.*;
import java.awt.Point;
public class Main{
static final Random random=new Random();
public static void main(String[] args) throws IOException
{
Scanner input=new Scanner(System.in);
int n=input.nextInt();
System.out.println("? "+1+" "+n);
System.out.flush();
int secondIndex=input.nextInt();
int left=1;
int right=secondIndex-1;
//Binary search in the left direction from the secondGreatest element
if(right>=left){
while(right!=left){
int mid=left+((right-left)/2);
System.out.println("? "+(secondIndex-mid)+" "+(secondIndex));
System.out.flush();
int curr=input.nextInt();
if(curr==secondIndex){
right=mid;
continue;
}
left=mid+1;
}
System.out.println("? "+(secondIndex-right)+" "+(secondIndex));
System.out.flush();
int candidate=input.nextInt();
if(candidate==secondIndex){
System.out.println("! "+(secondIndex-right));
System.out.flush();
return;
}
}
left=1;
right=n-secondIndex;
//Binary search in the right direction from the secondGreatest element
while(right!=left){
int mid=left+((right-left)/2);
System.out.println("? "+(secondIndex)+" "+(secondIndex+mid));
System.out.flush();
int curr=input.nextInt();
if(curr==secondIndex){
right=mid;
continue;
}
left=mid+1;
}
System.out.println("! "+(secondIndex+right));
System.out.flush();
}
static long pow(long num, long exp, long mod){
long ans=1;
for(int i=1;i<=exp;i++){
ans=(ans*num)%mod;
}
return ans;
}
static boolean isPrime(int n)
{
// Check if number is less than
// equal to 1
if (n <= 1)
return false;
// Check if number is 2
else if (n == 2)
return true;
// Check if n is a multiple of 2
else if (n % 2 == 0)
return false;
// If not, then just check the odds
for (int i = 3; i <= Math.sqrt(n); i += 2)
{
if (n % i == 0)
return false;
}
return true;
}
static int gcd(int a, int b)
{
if (a == 0)
return b;
return gcd(b % a, a);
}
// method to return LCM of two numbers
static int lcm(int a, int b)
{
return (a / gcd(a, b)) * b;
}
public static void sort(long[][] arr) {
//Sort an array (immune to quicksort TLE)
Random rgen = new Random();
for (int i = 0; i < arr.length; i++) {
int randomPosition = rgen.nextInt(arr.length);
long[] temp = arr[i];
arr[i] = arr[randomPosition];
arr[randomPosition] = temp;
}
Arrays.sort(arr, new Comparator<long[]>() {
@Override
public int compare(long[] a, long[] b) {
if (a[0] > b[0])
return 1;
else if (a[0] < b[0])
return -1;
else
return 0;
}
});
}
//Credits to SecondThread(https://codeforces.com/profile/SecondThread) for this tempelate.
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 8
|
standard input
|
[
"binary search",
"interactive"
] |
b3e8fe76706ba17cb285c75459508334
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,600
| null |
standard output
| |
PASSED
|
f124f6265ebd1eae4b24ac51adaee91b
|
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 40 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
|
//I AM THE CREED
/* //I AM THE CREED
/* package codechef; // don't place package name! */
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.util.*;
import java.awt.Point;
public class Main{
static final Random random=new Random();
public static void main(String[] args) throws IOException
{
Scanner input=new Scanner(System.in);
int n=input.nextInt();
System.out.println("? "+1+" "+n);
System.out.flush();
int secondIndex=input.nextInt();
int left=1;
int right=secondIndex-1;
if(right>=left){
while(right!=left){
int mid=left+((right-left)/2);
System.out.println("? "+(secondIndex-mid)+" "+(secondIndex));
System.out.flush();
int curr=input.nextInt();
if(curr==secondIndex){
right=mid;
continue;
}
left=mid+1;
}
System.out.println("? "+(secondIndex-right)+" "+(secondIndex));
System.out.flush();
int candidate=input.nextInt();
if(candidate==secondIndex){
System.out.println("! "+(secondIndex-right));
System.out.flush();
return;
}
}
left=1;
right=n-secondIndex;
while(right!=left){
int mid=left+((right-left)/2);
System.out.println("? "+(secondIndex)+" "+(secondIndex+mid));
System.out.flush();
int curr=input.nextInt();
if(curr==secondIndex){
right=mid;
continue;
}
left=mid+1;
}
System.out.println("! "+(secondIndex+right));
System.out.flush();
}
static long pow(long num, long exp, long mod){
long ans=1;
for(int i=1;i<=exp;i++){
ans=(ans*num)%mod;
}
return ans;
}
static boolean isPrime(int n)
{
// Check if number is less than
// equal to 1
if (n <= 1)
return false;
// Check if number is 2
else if (n == 2)
return true;
// Check if n is a multiple of 2
else if (n % 2 == 0)
return false;
// If not, then just check the odds
for (int i = 3; i <= Math.sqrt(n); i += 2)
{
if (n % i == 0)
return false;
}
return true;
}
static int gcd(int a, int b)
{
if (a == 0)
return b;
return gcd(b % a, a);
}
// method to return LCM of two numbers
static int lcm(int a, int b)
{
return (a / gcd(a, b)) * b;
}
public static void sort(long[][] arr) {
//Sort an array (immune to quicksort TLE)
Random rgen = new Random();
for (int i = 0; i < arr.length; i++) {
int randomPosition = rgen.nextInt(arr.length);
long[] temp = arr[i];
arr[i] = arr[randomPosition];
arr[randomPosition] = temp;
}
Arrays.sort(arr, new Comparator<long[]>() {
@Override
public int compare(long[] a, long[] b) {
if (a[0] > b[0])
return 1;
else if (a[0] < b[0])
return -1;
else
return 0;
}
});
}
//Credits to SecondThread(https://codeforces.com/profile/SecondThread) for this tempelate.
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 8
|
standard input
|
[
"binary search",
"interactive"
] |
b3e8fe76706ba17cb285c75459508334
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,600
| null |
standard output
| |
PASSED
|
d6ffb75654dc1d4d385b1a0901aef17b
|
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 40 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;
public class Solution {
private static boolean TESTS = false;
private final Input in;
private final PrintStream out;
public Solution(final Input in, final PrintStream out) {
this.in = in;
this.out = out;
}
public void solve() {
for (int test = 1, tests = TESTS ? in.nextInt() : 1; test <= tests; test++) {
final int n = in.nextInt();
int l = 1;
int r = n;
while (l < r) {
final int i = query(l, r);
final int m = (l + r) >>> 1;
final int ql = i <= m ? l : m + 1;
final int qr = i <= m ? m : r;
final int j = (ql == qr) ? -1 : query(ql, qr);
if (i == j) {
l = ql;
r = qr;
} else {
l = i <= m ? m + 1 : l;
r = i <= m ? r : m;
}
}
out.println("! " + l);
out.flush();
}
}
private int query(final int l, final int r) {
out.println("? " + l + " " + r);
out.flush();
return in.nextInt();
}
public static void main(final String[] args) {
final Input in = new Input();
final PrintStream out = new PrintStream(new BufferedOutputStream(System.out));
try {
new Solution(in, out).solve();
} finally {
out.flush();
}
}
private static final class Input {
private final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
private StringTokenizer tokenizer = new StringTokenizer("");
public String nextString() {
try {
while (!tokenizer.hasMoreTokens()) {
final String line = reader.readLine();
tokenizer = new StringTokenizer(line, " ");
}
return tokenizer.nextToken();
} catch (final IOException e) {
throw new RuntimeException(e);
}
}
public int nextInt() {
return Integer.parseInt(nextString());
}
public long nextLong() {
return Long.parseLong(nextString());
}
public double nextDouble() {
return Double.parseDouble(nextString());
}
public int[] nextInts(final int size) {
final int[] array = new int[size];
for (int i = 0; i < size; i++) {
array[i] = nextInt();
}
return array;
}
public long[] nextLongs(final int size) {
final long[] array = new long[size];
for (int i = 0; i < size; i++) {
array[i] = nextLong();
}
return array;
}
public double[] nextDoubles(final int size) {
final double[] array = new double[size];
for (int i = 0; i < size; i++) {
array[i] = nextDouble();
}
return array;
}
}
}
|
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"
] |
b3e8fe76706ba17cb285c75459508334
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,600
| null |
standard output
| |
PASSED
|
078b615be100ce738060eb5293d4569c
|
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 40 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
{
FastReader fr=new FastReader();
int n=fr.nextInt();
System.out.println("? "+1+" "+n);
System.out.flush();
int smax=fr.nextInt();//idx
int l=1;
int r=smax-1;
int ans=-1;
int idx=0;
while(l<=r) {
int m=(l+r)/2;
if(m==smax) {
idx=-1;
}
else {
System.out.println("? "+m+" "+smax);
System.out.flush();
idx=fr.nextInt();
}
if(idx==smax) {
ans=m;
l=m+1;
}
else
r=m-1;
}
if(ans!=-1) {
System.out.println("! "+ans);
}
else {
l=smax+1;
r=n;
idx=0;
while(l<=r) {
int m=(l+r)/2;
if(m==smax) {
idx=-1;
}
else {
System.out.println("? "+smax+" "+m);
System.out.flush();
idx=fr.nextInt();
}
if(idx==smax) {
r=m-1;
ans=m;
}
else
l=m+1;
}
System.out.println("! "+ans);
}
}
}
// 1 2 3 4 5
// 5 1 4 2 3
// 2
///1 2
class Pair{
int x;
int y;
Pair(int x,int y){
this.x=x;
this.y=y;
}
}
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"
] |
b3e8fe76706ba17cb285c75459508334
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,600
| null |
standard output
| |
PASSED
|
7e10692e40f576d397838561f6e51fc5
|
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 40 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"
] |
b3e8fe76706ba17cb285c75459508334
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,600
| null |
standard output
| |
PASSED
|
8d932cf557003c8e142d222593b465b4
|
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 40 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"
] |
b3e8fe76706ba17cb285c75459508334
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,600
| null |
standard output
| |
PASSED
|
62ccc12d2dddd60fb38b4660fd50473f
|
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 40 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 GuessingtheGreatest {
static Scanner input=new Scanner(System.in);
public static void main(String[] args) {
response();
}
public static void response() {
int n=input.nextInt();
int l=1;
while(l!=n) {
System.out.println("? "+l+" "+n);
System.out.flush();
int temp1=input.nextInt();
if(n-l==1) {
if(l==temp1) {
System.out.println("! "+n);
System.out.flush();
return;
}
else {
System.out.println("! "+l);
System.out.flush();
return;
}
}
int mid=(l+n)/2;
if(temp1>=mid) {
System.out.println("? "+mid+" "+n);
System.out.flush();
int temp2=input.nextInt();
if(temp2!=temp1)
n=mid-1;
else
l=mid;
}
else {
System.out.println("? "+l+" "+mid);
System.out.flush();
int temp2=input.nextInt();
if(temp2!=temp1)
l=mid+1;
else
n=mid;
}
}
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"
] |
b3e8fe76706ba17cb285c75459508334
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,600
| null |
standard output
| |
PASSED
|
98a034e0c1f87a5e93fc8ad1ca748fde
|
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 40 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"
] |
b3e8fe76706ba17cb285c75459508334
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,600
| null |
standard output
| |
PASSED
|
d058b8c3fbb75758bbdbc5704cb25c36
|
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 40 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
|
// No sorcery shall prevail. //
import java.util.*;
import java.io.*;
public class InVoker {
//Variables
static long mod = 1000000007;
static long mod2 = 998244353;
static FastReader inp= new FastReader();
static PrintWriter out= new PrintWriter(System.out);
public static void main(String args[]) {
InVoker g=new InVoker();
g.main();
out.close();
}
//Main
void main() {
int n=inp.nextInt();
int l=1,r=n;
int prev=query(l,r);
while(l+1<r) {
int mid=l+r>>1;
int x=query(l,mid);
int y=query(mid,r);
if(x==prev) {
r=mid;
prev=x;
}else if(y==prev){
l=mid;
prev=y;
}else {
if(prev>=mid) {
r=mid;
prev=x;
}else {
l=mid;
prev=y;
}
}
}
if(l==r) System.out.println("! "+l);
else System.out.println(query(l,r)==l?"! "+r:"! "+l);
}
int query(int l, int r) {
System.out.println("? "+l+" "+r);
return inp.nextInt();
}
/*********************************************************************************************************************************************************************************************************
* ti;. .:,:i: :,;;itt;. fDDEDDEEEEEEKEEEEEKEEEEEEEEEEEEEEEEE###WKKKKKKKKKKKKKKKKKKKKWWWWWWWWWWWWWWWWWWW#WWWWWKKKKKEE :,:. f::::. .,ijLGDDDDDDDEEEEEEE*
*ti;. .:,:i: .:,;itt;: GLDEEGEEEEEEEEEEEEEEEEEEDEEEEEEEEEEE#W#WEKKKKKKKKKKKKKKKKKKKKKKKWWWWWWWWWWWWWWWWWWWWWWKKKKKKG. .::. f:,...,ijLGDDDDDDDDEEEEEE *
*ti;. .:,:i: :,;;iti, :fDDEEEEEEEEEEEEEEEKEEEEDEEEEEEEEEEEW##WEEEKKKKKKKKKKKKKKKKKKKKKWWWWWWWWWWWWWWWWWWWWWWWKKKKKKEG .::. .f,::,ijLGDDDDDDDDEEEEEE *
*ti;. .:,:i: .,,;iti;. LDDEEEEEEEEEEKEEEEWEEEDDEEEEEEEEEEE#WWWEEEEEKKKKKKKKKKKKKKKKKKKKKKKKKWWWWWWWWWWWWWWWWWWWKKKKKEDj .::. .:L;;ijfGDDDDDDDDDEEEEE *
*ti;. .:,:i: .:,;;iii:LLDEEEEEEEEEEEKEEEEEEEEDEEEEEEEEEEEW#WWEEEEEEEKKKKKKKKKKKKKKKKKKKKKKKKKWWKWWWWWWWWWWWWWWKKKKKKKEL .::. .:;LijLGGDDDDDDDDEEEEE *
*ti;. .:,:;: :,;;ittfDEEEEEEEEEEEEEEEEKEEEGEEEEEEEEEEEKWWWEEEEEEEEEKKKKKKKKKKKKKKKKKKKKKKKKKKWWWWWWWWWWWWWWWKKKKKKKELj .::. :,;jffGGDDDDDDDDDEEEE *
*ti;. .:,:i: .,;;tGGDEEEEEEEEEEEKEEEKEEEDEEEEEEEEEEEEWWWEEEEEEEEEEEEKKKKKKKKKKKKKKKKKKKKKKKKKKWWWWWWKWWWWWWKKKKKKKEEL .::. .:;itDGGDDDDDDDDDEEEE *
*ti;. .:::;: :;ifDEEEEEEEEEEEEKEEEKEEEEEEEEEEEEEEEWWWEEEEEEEEEEEEEEKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKW#WWWKKKKKKKKEEf .::. :,itfGEDDDDDDDDDDDEE *
*ti;. .:::;: :GGEEEEEEEEEEEKEKEEKEEEEEEEEEEEEEEEEWWEEEEEEEEEEEEEEEEEKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKW#WKKKKKKKKKEEDG .::. .,;jfLGKDLDDDDDDEEDD *
*ti;. .:::;: fDEEEEEEKKKKKKKKKEKEEEEEEEEEEEEEEE#WEEEEEEEEEEEEEEEEEEKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKW#KKKKKKKKKKEEf .:::. .,;tfLGDEDDDDDDDDEEE *
*ti;. :::;: fDEEEEEEKKKKKKKKKKWKEEEEEEEEEEEEEEEWKEEEEEEEEEEEEEEEEEEEEKEKKKKKKKKKKKKKKKKKKKKKKKKKKKKW##KKKKKKKKKEEft :::. .,;tfLGDDDKDDDDDDDDD *
*ti;. .::;: fDEEEEEEKKKKKKKWKKKKKEEEEEEEEEEEEE#WEEWEEEEEDEEDEEEEEEEEEEEEKKKKKKKKKKKKKKKKKKKKKKKKKKKKW#WKKKKKKKKEEGG :,:. .,;tfLGGDDDKDDDDDDDD *
*ti;. .:.;: tGDEEEEKKKKKKKKKKKKKKKKKEEEEEEEEEEEWEEKWEEEEEEEDEEEEEEEEEEEEEEKEKKKKKKKKKKKKKKKKKKKKKKKKKKWWWKKKKKKKEEDf :::. .,;tfLGGDDDDEDDDDDDD *
*ti;. .::;: fDEEEEEKKKKKKKKKKKWKKKKKKKKEEEEEEEWWEEWEEEEEEEEEEEEEEEEEEEEEEEEEEKKKKKKKKKKKKKKKKKKKKKKKKKW##KKKKKKKEEEft.::. .,;tfLGGDDDDDDEDDDDD *
*ti;. .:.;: tGDEEEKKKKKKKKKKKKKKKKKKKKKKEKEEEEE#EEWWEEEEEEEEEEEEEEEEEEEEEEEEEEEEKKKKKKKKKKKKKKKKKKKKKKKKW#WKKKKKKEEEGD:::. .,;tfLGGDDDDDDDEDDDD *
*ti;. .:.,. LDEEEEKKKKKKKKKKWKWKKKKKKKKKKKKEEEKWEKW#EEEEEEEEEEEEEEEEKEEEEEEEEEEEEEEEKKKKKKKKKKKKKKKKKKKKW##KKKKKKEEEEf,,:. .,;tfLGGDDDDDDDDEDDD *
*ti;. ..:.,. LGDEEEEKKKKKKKKKKWKKKKKKKKKKKKKKKKKWEEW#WEEEEEEEEEEEEEEEKEEEEEEEEEEEEEEEEEEEKEKKKKKKKKKKKKKKKK##KKKKKEEEEEfi;,. .,;tfLGGDDDDDDDDDKDD *
*tt;. .:.,: jDEEEEKKKKKKKKKKWWKKKKKKKKKKKKKKKKKWKE#WWEEEEEEEEEEEEEEWEEEEEEEEEEEEEEEEEEEEEEEKKKKKKKKKKKKKKKKWWKKKKEEEEDfG;,: .,;tfLGGDDDDDDDDDDKD *
*tii,. .:.,. tGDEEEEKKKKKKKKKKWWWKKKKKKKKKKKKKKKWKKWWWKEEEEEEEEEEEEEKEEEEEEEEEEEEEEEEEEEEEEEEEEEEEKKKKKKKKKKKW#KKKKEEEEDGGi;,. .,;tfLGGDDDDDDDDDDDE *
*ti;;,:. .:.,: fDEEEEKKKKKKKKKKKWKKKKKKKKKKKKKKKKKWEK#WWKEEEEEEEEEEEEDEEEEEEEEEEEEEEGEEEEEEEEEEEEEEEEEEEKKKKKKKWWKKEEEEEEDDf;;;,. .,;tfLGGDDDDDDDDDDDD *
*tii;,,:.. ...,. ;LEEEEEKKKKKKWKKKKWKKKKKKKKKKKKKKKKKEKKW#WEEEEEEEEEEEEEjEEEEEEEEEKEEEEGEEEEEEEEEKEEEEEEEEEEEEEEEEE#WKEEEEEEDDf;;;;,: .,itfLGGDDDDDDDDDDDD *
*ti;,,,,,:. ...,. LDEEEEKKKKKKKKKKKWWWKKKKKKKKKKKKKKKWKK#W#WEEEEEEEEEEEDDLEEEEEEEEEWEEEEDEEEEEEEEEKEEEEEEEEEEEEEEEEEWWEEEEEEEDDfj,,,,,:. .,itfGGGDDDDDDDDDDDD *
*tii,,,,::::. ...,: .fDEEEEKKKKKKWKKKKWWWKKKKKKKKKKKKKKKEKKW#WWEEEEEEEEEEEKiKEEKEEEEEEWEEEEDEEEEEEEEEEEEEEEEEEEEEEEEEEEWWEEEEEEEDDLD:::,,,:. .,ijfGGGDDDDDDDDDDDD *
*ti;:::::::::.. .:.,: LDEEEEKKKKKKKWKKKKWWKKKKKKKKKKKKKKKKtKKWWWWKEEEEEEEEEDiiDEEEEEEEEWWEEEEEEDEEEEEEEEEEEEEEEEEEEEEEEEEEWKEEEEEDDDGL:. .:,,,: .,ijLGGGDDDDDDDDDDDD *
*tt;. .::::::::.. ...,: :fDEEEKKKKKKKKKKKKWW#KKKKKKKKKKKKKKKKfKKWWWWKEEEEEEEEDti,DEKEEEEEEWWEEEDEEEEEEEEEKEEEEEEEEEEEEEDEEEEE#WEEEEEGGDGf:. .:,;,:. .,ijLGGDDDDDDDDDDDDD *
*tt;. .:::::::.. ...,: GDEEEKKKKKKKKWKKKKWWWKKKWKKKKKKKWWWKDEKLWWWWKKEEEEEEDEi,LDEEEEEEEEWWEEEEEEEEEEEEEEEEEEEEEEEEEDEDEEEEEW#EEEEDDDDGf,. :,,,:...,ijLGGGDDDDDDDDDDDD *
*tt;. .....::::.. ...,: fDEEEKKKKKKKKWKKKKWWWWKKKWKKKKKKKKKKfWKiWWW#KKEEEEEEEi;.EDfEEEDEEiWWEEEEEEEEEEEEDGKEEEEEEEEEEDEEEEEEEWWEEEEDDDGGLi. .,;,:::,ijLGGGDDDDDDDDDDDD *
*tt;. ....:::::. ...,. iDEEEEKKKKKKKKWKKWKWWWWWKKWWWKKKKKKKKtWKt#WWWKKEEEEEDji..DDKDDEDEGiWKEEEEEEEEEEDDEjEEEEEEEEEEEDEEEEEEEKWKEEDDDDGGff. .:,;,,;ijLGGGDDDDDDDDDDDD *
*tt;. ....::::.. .:.,: .LDEEEKKKKKKKKKKKKWWWWKWWWWWWWWWWKKKKWtKKiDWWWKKKEEEEKi:..DEDDDDDDiiWKEEEEEEEEEEDDEijDEEEEEKEEEEEEEEEEEEWWEEGDDDGGLG. .:,;;iijLGGGDDDDDDDDDDDD *
*tt;. .....:::.. ...,. .fEEEEKKKKKKKKWKKKKWWWWWWWWWWWWWWKWKKKiKDiLWWWWKEEEEEi,..fD:DDDDDti;WEEEEEEEEEEKDDi:iDDEEEEWEEEEEEEEEEEE#WEEGDDDDGGG. :,iitjLGGGDDDDDDDDDDDD *
*tti. .....:::.. ...,. GDEEEKKKKKKKKKWKKKWWW#WWWWWWWWWWWKWKKjiEjitWWWKKWEEEDi...DDLDDDDji;;WEEEEEEEEEEEDEj.iDDEEEEWEEEEEEEEEEEEWWEEDDDDDDGf. .,;tjfLGGDDDDDDDDDDDD *
*tti. ....::::.. ...,. fEEEKKKKKKKKKKKKKKKW#WWWWWWWWWWWWWWWWtiEiiiWWWKKEWKEi....D.EDDDEi;.fWEEEEEEEEEEDDfL.;EDDEEEWEEEEEEEEEEEEWWEEEDDDDDGf. :;ijfLGGDDDDDDDDDDDD *
*tti. ....::::.. ...,. LDEEEKKKKKKKKKKKKKKWWWWWWWWWWWWWWWW####WKiiiWWWKKKEEK,...:E:DDDEii..GWEEEEEEEEDWDDiL.,KDDEEEWEEEEEEEEEEEEWWKEEDDDDDGf: .,itfLGGDDDDDDDDDDDD *
*tti. .....:::.. ...,. fDEEEKKKKKKKKKWKKKKWWWWWWWWWWWWW########WLiiWWWKKKEEjD...G,DDDDi;...EWEEEEEEEEDKDEii..LDDEEEWEEEEEEEEEEEEWWWEEDDDDDGfi .,;tfLGGGDDDDDDDDDDD *
*tti. .....:::.. ...,. iGEEEKKKKKKKKKKWKKKKWWWWWWWWWWWW###########KiWWWKKEEE,.D..D.DDDii:...KKEEEEEEEEEDDj:...tEDEEEWEEEEEEEEEEEEWWWEEEDDDDDLL .,;tjLLGGDDDDDDDDDDD *
*tti. ....::::......:. LEEEKKKKKKKKKKWWKKKWWW#KWWWWWWWW#####W####W##KWWKKEEL..:D.jjDDi;,....KKEEEEEEEDfDDi...:iKDEEEWKEEEEEEEEEEEWWWEEEEDDDDLG .,;tjLLGGDDDDDDDDDDD *
*tti. ...::::::..,. :GEEEKKKKKKKKKKKKWWWWW##WWWWWWWWW##WKWK#W#W####WWKEEK.....G.DDti,.....KKEEEEEEDWGDf.,...iKDEEEWWEEEEEEEEEEEW#WEEEEEDDDGL .,;tjLLGGDDDDDDDDDDD *
*tti. ....::::::,. GDEEKKKKKKKKKKKKKWWWW###WWWWWWWWWW#WWWK###W#####WKEKK.....jDDL;;......KKEEEEEEEEEDi.f...;KDEEEWWEEEEEEEEEEEWWWWEEEEEDDGf .,;tjLLGGDDDDDDDDDDD *
*tti. ....:::,,. .LEEEKKKKKWKKKKKWWWWWW###WWWWWWWWWW#WWKW#WW##W#WWWKEKD:....:DD:;......;KEEEEEEEKiDD..f...,KKEEEWWEEEEEEEEEEEWWWWEEEEEDDDf .:;tjLLGGGDDDDDDDDDD *
*tti. ...::,,,:. GDEEKKKKKKKKKKKKWWWWWWW#WWWWWWWWWWW#KjKWWWWWWWWWWWWEK.j,..;fD.;.......fKEEEEEDKG:Di..,....DKEEEWWEEEEEEKEKKKWWWWEEEEEEDDf .:;tjLLGGDDDDDDDDDDD *
*jti. ...::,,,,:. .fEEEKKKKKWKKKKKKWWWWWWW#WWWWWWWWWWK#KKKWWWWWWWWWWWWWK..f:.:G.,:.......EKEEEEEKK;:E:.......fKEEEWWKEKEKKKKKKKW#WWEEEEEEDDf: .,;tfLLGGDDDDDDDDDDD *
*tti. ...:,,,;;,: iDEEKKKKKWKKKKKKKWWWWWWW#WWWWWWWWWWK#WDKWWKKWWWWWWWWWE..;G:G..,........KKEEEEEKi.Gi..:.....tKEEKWWWKKKKKKKKKKW##WKEEEEEEDfi .,;tfLLGGGDDDDDDDDDD *
*tti. ....::,,;;;,LEEKKKKKKWKKKKKWWWWWWW###WWWWWWWWWWKWWDKWEEEWKKWWWWWKKj.:LG..;.........EKEEEEKG;.G...;.....;KKEKWWWKKKKKKKKKKW##WWKEEEEEDfL .,;tfLGGGDDDDDDDDDDD *
*jti. ...::::,;ijDEEKKKKKWKKKKKKWKWWWWW##WWWWWWWWWWWKK#KKGDGDWEEWKKWKKGE,.i;.:.........:EKEEEKE;.:L...j.....,KWEKWWWKKKKKKKKKK####WKKEEEEDLG .,;tfLGGGGDDDDDDDDDD *
*jti. ...:...,,;GEEKKKKKWWKKKKKWWWWWWWW###WWWWWWWWWKKKWWKiLGGEDEDEKGKKiEG..;...........jKEEEKK;:.G....,.....:KKEWWWWKKKKKKKWKK####WKKKKEEEGL .,;tfLGGGGDDDDDDDDDD *
*jti. ...:. .:,GEEKKKKKWKKKKKWWWWWWWW####WWWWWWWWWKKKWWKii;fDLGDK: EEi:E:.............EKEEKK;;..L...........KKKWWWWKKKKKKKWKK####WKKKWKEEDf .,;tfGGGGDDDDDDDDDDD *
*jti. ...:. ,EEKKKKKWWKKKKKWWWWWWWWW###WWWWWWWWKKKKfWWLt;i,. fi EG..D:.............EKEKK;;..t....:.......KWKWWWWKKKKKKKWKK####WKKKWEEEDf:. .,;tfGGGGDDDDDDDDDDD *
*jti. ...:. GEEKKKKKWKKKKKWWWWWWWWW####WWWWWWWKKKKKt;KKEfff .;t.................KKKKi;:..GtGGfG.......KWWWWWWKKKKKKKWKK###WWWKKKKEEEf,,: .,;tfGGGGDDDDDDDDDDD *
*jti. ...:. GEKKKKKWWKKKKKWWWWWWWWWW##WWWWWWWKKKKKKt;EiKKKK, ...t................jEKKG;;..,.....,LGi....KWWWWWWKKKKKKWKKKW####WKKKKKEEL,,,:. .,;tfGGGDDDDDDDDDDDD *
*jti. ...:. .GEEKKKKKWKKKKKWWWWWWWWWW###WWWWWWWKKKKKKtiE::tGG........................EEEj;;...,.........:D..DKWWWWWWKKKKK#KKW###W#WKKKKKEEfj:,,,:. .,;tfGGGDDDDDDDDDDDD *
*jti. ...:. DEKKKKKWWKKKKKWWWWWWWWW####WWWWWWWKKKKKKiiE:::.::.......................EEi;;...j.....f......:iDKWWWWWWKKKKK#WW######WKKKKKEELG :,,,,:. .,;tfGGGDDDDDDDDDDDD *
*jti. ...:. fEEKKKKWWKKKKWWWWWWWWWWW###WWWWWWWWKKKKKK;tE::..........................DD;.;,.::......;........EWWWWWWWKKKKW#WW#####WWKKKWKKELG .:,,,:::,;tfGGGDDDDDDDDDDDD *
*jti. ...:. .DEKEKKKWWKKKKWWWWWWWWWWW###WWWWWWWWKKKKKE,iD::..........................D..,;.,;tLffi...........DWDWWWW#KKKWWWWW#####W#KKKWKEEGL .:,;,,,;tfGGGDDDDDDDDDDDD *
*jti. ...:. ;EEKKKKWWKKKKKWWWWWW#WWWW####WWWWWWKKKKKEL:iD:..........................j ..;..;;:.....i,........DKtWWWWWKKWWWWWW#####WWWKKKEKEDf .:,;;;itfGGGDDDDDDDDDDDD *
*jti. ...:. DEKKKKKWWKKKKWWWWWWW#WWWW####WWWWWWKKKKKEj:iG...............................:....................GKiWWWWWKKWW#WWW######WWKKKKKEEf .,;iitfGGGDDDDDDDDDDDD *
*jti. ...:.:EKKKKKWWKKKKKWWWWWWW#WWW#####WWWWWKWKKKKEi:if:.................................iEKEKKKKKKDj......DKiWWWWWKWK##WW#######WWKKK:KEEL .:;itfGGGDDDDDDDDDDDD *
*jji. ...:,DEEKKKWWWKWKKWWWWWWWWWWWW#####WWWWWWWKKKKEi:it..................................j. KKKKKKKKKKKf..DKiWWWWWKWW##WW#######WWKKK,KEEf .,;tfGGGDDDDDDDDDDDD *
*jji. ..L:iDEEKKKWWKKKKKWWWWWWWWWWWW#####WWWWWKWKKKKKi.i;.................................. . KKKWWWWWWWWK..DGiWWWWWKK##WWW#####W#WWKKKjEKEL, .:;tfGGGDDDDDDDDDDDD *
*jji. .f:::EEEKKKWWWKKKKKWWWWWWWWWWWW#####WWWWWKWKKKKK;.i,.................................:: KKEKWWWWWWfWK..EiiWWWWWKWW#WW##########KKKD,KELj .:;tfGGDDDDDDDDDDDDD *
*jji. .t::::,DEEKKKWWKKKKWWWWWWWWW#WWWW#####WWWWKKWKKKEK;.i:.................................GDDEEEKKKWWWWWtWWD.E;iWWWWWW###WW#########WWKKK.EEDG .:;tfGGGDDDDDDDDDDDD *
*jji. . j..::::EKEKKKWWWKKKKWWWWWWWWW#WWW######WWWWKKWKKKEK;.t:.................................ELLEDDEEEWWWWEtWK,.KiiWWWWWW###W##########WWKKK:EEEG .;tjfLLGDDDDDDDDDDDDDDD *
*jji. i.::::::,EEEKKWWWKKKKKWWWWWWWWW#WWW#####WWWWWKWKKKKEE,.t..................................DfiEGDDDEEKKKttKWG.KiiWWWWW##WWW##########WWKKK:fEEL ,fGGGDDDDDDDDEEEDDDDDDDDDD *
*jji. .;:..:::::DEEEKKWWWKKKKKWWWWWWWWW#WWWW####WWWWWWWKKKKED,.t..................................ifjDDGGEGDKK.ttKKE.DiWWWWW###WW##########WWWKKK:.KELiLGGGGDDDDDDDDDDDDEEEDDDDDDD *
*jji. i.:.::::::,KEEKKWWWKKKKKKWWWWWWWWW#WWWW####WWWWWWWKKKKEL:.j..................................GGf,;ifLLED .iiKKi:fWWWWWW##W#W##########WWWKKK:.KKLGGDDDDDDDDDDDDDDDDEDDEEDDDDD *
*jji. .j:.::::::::EEEKKKWWWKKKKKKWWWWWWWW##WWW#####WWWWWWWKKKKKf:.f..................................:EEfftf .,. ;iE,..jWWWWWWW###W############WWKKK,:KKGDDDDDDDDDDDDDDDDDDDDDDDEDDDD *
*jji. .:.::::::::,,EEEKKWWWKKKKKKKWWWWWWWW##WWW#####WWWWWWWKKKKKt..G....................................EEELL; .j....tKWWWWWWW################WWWKKtfGKGEDDDDDDDDDDDDDDDDDDDDDDDEEDD *
*jji. :...:::::::,,jEEKKWWWWKKKKKKWWWWWWWWW##KWW#####KWWWWWWKKKKEi..D....................................:jEEE.........;KKWWWWWWWW#WW##W##########WWKKDLGKEKDDDDDDDDDDDDDDDDDDDDDDDDDED *
*jji. i:.::::::::,,,EEEKKWWWWKKKKKWWWWWWWWWW##WWW#####WWWWWWWKKKKKi..D......................................:::::......,KKKWWWWWWWWW#####W########WWWKKKGGKKEGGGGGGGGDDDDDDDDDDDDDDDDDDE *
*jji. i..:::::::::,,tEEKKWWWWKKKKKWWWWWWWWWWW##WW######WWWWWWWKKKKKi..D......................................::::......:EKKKWWWWWWWWWWW##WW########W#WKKWGGKKGGGGGGGGGGGGGGGDDDDDDDDDDDDD *
*jji. .:::::::::::,,,EEEKKWWWWKKKKKWWWWWWWWWWW##WW#####WWWWWWWWKKKKKi..D....................................:::::::::..tELii;KWWWWWWWWWW##WW######WWWWWWKWGGGKGGGGGGGGGGGGGGGGGGGGGGGGGGDG *
*jjt. :.::::::::,,,,fEEKKWWWWKKKKKKWWWWWWWWWW###WW####WWWWWWW#WKKKKKi..D....................................:::::::.:.,;;;;;;,KKWWWWWWWWW#WW########WWWKKWGGGKGGGGGGGGGGGGGGGGGGGGGGGGGGGG *
*jji. ;.::::::::,,,,;EEEKWWWWWKKKKKWWWWWWWWWWWW##WW###WKWWWWWK#WKKKKKi..G......................................:::::::,;;;;:...KKKWWWWWWWWWKWW#######WWWWKKGLGKDGGGGGGLLGGGGGGGGGGGGGGGGGGG *
*jjt. f.:::::::::,,,,fEEKKWWWWWKKKKKWWWWWWWWWWW###WW##WKKWWWWWW#WKKKKK;.jt........i.............................:::::::;j;;....:E.KKKWWWWWWWKWW#####W#WWWWKKLLGWEEGGGGGLGGGGGGGGGGGGGGGGGGGG *
*jjt. ...:::::::,,,,,;DEEKWWWWWKKKKKWWWWWWWWWWWW####WWWKKKWWWWWWWWKKKKK;.E;.........t.............................:::::ii;;.....D...KKWWWWWWWKWW#####WWEWWWKKGGGEKKGGGGGLGGGGGGGGGGGGGLGGGGGG *
*fji. ;.:::::::,,,,,;LEEKKWWWWWKKKKKWWWWWWWWWWWW####KWKKKKWWWWWWWWKKKKKi.D;..........j.............................:::tt;,.....:.....KKWWWWWWKWWWW##WWWGWWWKKGGGGKEGGGGGGGGGGGGGGGGGGGLLGGGGL *
*fji. t::::::::,,,,,,;EEEKWWWWWKKKKKKKWWWWWWWWWWW##WKWKKKKKWWWWWWWWKKKKKi:D;............j...........................::LL;,.............KKWWWWWKWWWWWWWWWGWWWKKGGGGKGGGGGGGGGGGGGGGGGGGGLLGGGGL *
*fjt: .:::::::,,,,,,,DEEKWWWWWWKKKKKKKWWWWWWWWWWWWKKWKKKKKKWWWWK#WWKKKKWitE;........... ............................:G;;:...............KKKWWKKWWWWWWWWWGWWWKKGGGGWGGGGGGGGGGGGGGGGGGGGGGGGGGL *
*fjji;:. .f:::::::,,,,,,,;EEEKWWWWWWKKKKKKWWWWWWWWWWWKKKKKKKKKKKWWKWWWWWKKKKWGKD;........................................L;;..................DKKWKKWWWWWWWWWGWWWKKDGGGKDGGGGGGGGGGGGGGGGGGGGGGGGGG *
*fjjtii;,:. :::::::,,,,,,,;EEEKWWWWWWKKKKKKWWWWWWWWWWKKKKKKKKKKKKWWWWWW#WWKKKKWiEj;......................................:i,;....,...............;KKEKWWWWWWWWWGKWWKKDDGGDEGGGDGGGGGDGGGGGGGGGGGGGGGG *
*fjtiiiii;;:. j::::::,,,,,,,;;EEEKWWWWW#KKKKKWWWWWWWWWKKKKKKWKKKKKKKWWWWWWWWWKKKKWtEL;:....................................;;;:...,;j................:KEEWWWWWWWWWDDWWKKDDDDDKDDDDDDDDDDDDDDDGGGGGGGGGGG *
*fjti;;iiii;;,:::::::,,,,,,,,;EEEKWWWWWWWKKKKWWWWWWWWKKKKKKKWKKKKKKKWWWWWWW#W#KKKKWEEii;...................................f;:....,;L...................EEKWWWWWWWWDDWWKKDDDDDKEDDDDDDDDDDDDDDDDDDDDDGGGG *
*fjt,,,;;;;ii;f::::::,,,,,,,;;EEKWWWWWWWKKKKKWWWKWWKKKKKKKKKKKKKKKKKWWWWWWW#W#KKKKWKEij;:...............................:G;,.....,;f....................:tKKWWWWWWWDDWWKKDDDDDKKDDDDDDDDDDDDDDDDDDDDDDDDD *
*jjt. ..:,;;;;,::::,,,,,,,,;;GEEWWWWWWWWKKKKWKKWKKKKKKKKKKKKKKKKKKKKWWWWWWW#W#KKKKWEDi;j;............................,Li;L;;;..,;;f........................KKKKWWWKDDWWKKDDDGDKKGGGGGGGGDGDDDDDDDDDDDDDDD *
*fjt. .:,,,:::::,,,,,,,;;;EEKWWWWWWWKKKKKKWKKKKKKKKKKKKKKKKKKKKKWKKKWKW##W#KKKKWEti;;G;........................tEEEL;;;;;;;;;;L..........................DKKKKKEDDWWKEDGftiLE;;;;itjLGGGGGGDDDDDDDDDDD *
*fjt. .j::::,,,,,,,;;;DEEWWWWWWWWKKKKWKKKKKKKKKKKKKKKKKKKKKKKWKKWWWK##W#KKKKKEii;;;L;...................iDEEEEEEKKi;j;;;;jD.....:......................,KKKKDGGEKKE:::::;E::::::::::,tLGGDDDDDDDDDD *
*fjt. .;:::,,,,,,,;;;;EEKWWWWWWWWKWKKKKKKKKKKKKKKKWKKKKKKKKKKWKKWWWW#WW#KKKKKKii;;;;f;.............:tDEEEEEKKKKKKKKEti;;;L...............................EEKf;:iKKE::::::E::::::::::::::ifDDDDDDDDD *
*fjt: :::,,,,,,,,;;;DEEWWWWWWWWWEKKKKKKKKKKKKKKKKKKKKKKKKKKWWKKWWWW####KKKKKEiii;;;;f,.........iDEEEEKKKKKKKKKKKKKKKf;iG......i..........................fK::::KKE::::::E::::::::::::::::,tGGDDDDD *
*fjt: t:::,,,,,,;;;;iDEKWWWWWWKEKKKKKKKKKKKKKKKKKKKKKKKKKKKKWWKKWWWW####WKKKKLiii;;;;;L,....,Li;EDEEEEKKKKKKKKKKKKKKKKiG......;:...........................:i:::KKE:::::,E,::::::::::::::::::iGDDDD *
*jjt. f::,,,,,,,;;;;GEEWWWWKEEKEKKKKKKKKKKKKKKKKWKKKKKKKKKKKWWKWWWWW###WWKKKKiii;;;;;;;G,;L;;iiEEEEEEEKKKKKKKKKKKKKWWKE......;t.........:....................j::KEE:,::,,D,,::::,,,,,,:::::::::tDDD *
*fjt:. ,::,,,,,,,;;;;EEWWKEEEEEEKKKKKKKKKKKKKKKKWKKKKKKKKKKKWWKKWWWWW#W#KKKKKKiiiiii;;;;;i;;iiiEEKEEKKWKKKKKKKWKKKKKWWWGi;...;t......,;;;;,....................:,EEE,,,,,,D,,,,,,,,,,,,,,,,::,::::tG *
*fjt:. ,::,,,,,,,;;;;DEKEEEEEEEEKKKKKKKKKKKKKKKKKKKKKKKKKKKKKWWWWWWWWW#W#KKKKKKiiiii;;i;;;;;iiiKKKEKKKKWWKWWWWWWKKKKWWWWW;;;:;L.....;;;;;;;;;....................,KEE,,,,,,E,,,,,,,,,,,,,,,,,,,,,,,,; *
*fjt:. f:,,,,,,,;;;;jEDEEEEEEEEEKKKKKKKKKKKKKKKKKKKKKKKKKKKKKWWWWWWWW#W##KKKKKKiiiiiiii;i;;iiiEKKKKKKKKWKWWWWWWWWKKKWWWWWKi;;i.....,jEEfGi;;;;;...................EED,,,,,,E,,,,,,,,,,,,,,,,,,,,,,,,, *
*fjt:. .f::,,,,,,;;jEEDEEEEEEEEEEKKKKKKKKKKKKKKKWKKKKKKKKKKKKKWWWKWWWWW###KKKKKLiiiiiiiiiiiiiiEEKKKKKKKKWWWWWWWWWWWWKWWWWWWGi;i;,..;jDDDKEGi;;;;;;:................EED,,,,,,D,,,,,,,,,,,,,,,,,,,,,,,,, *
*fjt:. .. ;::,,,,,;;EDDEEEEEEEEEEKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKWWKKW#WW####KWKKKiiiiiiiiiiiiijKKKKKKKKKKWWWWWWWWWWWWWWWWWWWWWt;i;;;;i;DDDDDDGi;;;;;;;;:.............EDf;,,,;,G;;;;;;;;;;;;;;;,,,,,,,,,, *
*fjt:......:,,,,,,;LDDDEEEEEEEEEEEKKKKKKKKKKKKKKKKWKKKKKKKKKKKKKWWWWKWWWW####KKKKKiiiiiiiiiiijKEKKWKKKKKKKWWWWWWWWWWWWWWWWWWWWWWiLiii;i;DEEEEDDE;i;;;;;;;;;:..........EDi,;;;;;L;;;;;;;;;;;;;;;;;;,,,,,,, *
*fjt:......:,,,,,;EDDDEEKEEEEEEEEEKKKKKKKKKKKKKKKWKKKKKKKKKKKKKKWWWWKKWWW##W#KWKKWEiiiiiijGKKKKKWWKKKKKKKKWWWWWWWWWWWWWWWWWWWWWWKi;iiiiDDEEEEEEDEi;;;;;;;;;;;;;,:.....ED;;;;;;;j;;;;;;;;;;;;;;;;;;;;;;;,, *
*fjt:.....t,,,,,;DDDDEEEKEEEEEEEEKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKWWWKKKWWWW##WKWKKWKiiiKKKKKKKKKWWKKKKKKKKWWWWWWWWWWWWWWW#WWWWWWWWWiiiiifLEEEEEEEEDi;i;;;;;;;;;;;;.....DD;;;;;;;i;;;;;;;;;;;;;;;;;;;;;;;;; *
*fjt:.....G,,,,,GDDDEEEEEEEEEEEEKKKKKKKKKKKKKKKKWKKKKKKKKKKKKKKKWWWKKKWWW###WKWKKWKitKKKKKKKKKWKKKKKKKKKKWWWWWWWWWWWWWW###WWWWWWWWEiiiiiiiEEEEEEEEDGiiii;;;;;;;;;.....GD;;;;;;;i;;;;;;;;;;;;;;;;;;;;;;;;; *
*fjt:.....L,,,,;GDDDEEEEEEEEEEKEKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKWWWWWDGWWW###KKWWKWKKKKKKKKKKKKKKKKKKKKKKKWWWWWWWWWWWWW####WWWWWWWWWiiiiiiiiEEEEEEEEEEDi;i;;;;;;;;.....Lj;;;;;;i;iiiiii;;;;;;ii;;;;;;;;;;; *
***********************************************************************************************************************************************************************************************************/
void sort(int a[]) {
ArrayList<Integer> list=new ArrayList<>();
for(int x: a) list.add(x);
Collections.sort(list);
for(int i=0;i<a.length;i++) a[i]=list.get(i);
}
void sort(long a[]) {
ArrayList<Long> list=new ArrayList<>();
for(long x: a) list.add(x);
Collections.sort(list);
for(int i=0;i<a.length;i++) a[i]=list.get(i);
}
void ruffleSort(int a[]) {
Random rand=new Random();
int n=a.length;
for(int i=0;i<n;i++) {
int j=rand.nextInt(n);
int temp=a[i];
a[i]=a[j];
a[j]=temp;
}
Arrays.sort(a);
}
void ruffleSort(long a[]) {
Random rand=new Random();
int n=a.length;
for(int i=0;i<n;i++) {
int j=rand.nextInt(n);
long temp=a[i];
a[i]=a[j];
a[j]=temp;
}
Arrays.sort(a);
}
static long gcd(long a, long b) {
return b==0?a:gcd(b,a%b);
}
long fact[];
long invFact[];
void init(int n) {
fact=new long[n+1];
invFact=new long[n+1];
fact[0]=1;
for(int i=1;i<=n;i++) {
fact[i]=mul(i,fact[i-1]);
}
invFact[n]=power(fact[n],mod-2);
for(int i=n-1;i>=0;i--) {
invFact[i]=mul(invFact[i+1],i+1);
}
}
long nCr(int n, int r) {
if(n<r || r<0) return 0;
return mul(fact[n],mul(invFact[r],invFact[n-r]));
}
long add(long a, long b) {
return (a+b)%mod;
}
long mul(long a, long b) {
return a*b%mod;
}
long power(long x, long y) {
long gg=1;
while(y>0) {
if(y%2==1) gg=mul(gg,x);
x=mul(x,x);
y/=2;
}
return gg;
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st==null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
}
catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String s="";
try {
s=br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return s;
}
}
// Functions
static int gcd(int a, int b) {
return b==0?a:gcd(b,a%b);
}
void print(int a[]) {
int n=a.length;
for(int i=0;i<n;i++) out.print(a[i]+" ");
out.println();
}
void print(long a[]) {
int n=a.length;
for(int i=0;i<n;i++) out.print(a[i]+" ");
}
//Input Arrays
static void input(long a[], int n) {
for(int i=0;i<n;i++) {
a[i]=inp.nextLong();
}
}
static void input(int a[], int n) {
for(int i=0;i<n;i++) {
a[i]=inp.nextInt();
}
}
static void input(String s[],int n) {
for(int i=0;i<n;i++) {
s[i]=inp.next();
}
}
static void input(int a[][], int n, int m) {
for(int i=0;i<n;i++) {
for(int j=0;j<m;j++) {
a[i][j]=inp.nextInt();
}
}
}
static void input(long a[][], int n, int m) {
for(int i=0;i<n;i++) {
for(int j=0;j<m;j++) {
a[i][j]=inp.nextLong();
}
}
}
}
|
Java
|
["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"
] |
b3e8fe76706ba17cb285c75459508334
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,600
| null |
standard output
| |
PASSED
|
74806841db666f206fe6389c07fe550c
|
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 40 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.io.PrintWriter;
import java.util.StringTokenizer;
public class Solution1486C1 {
public static void main(String[] args) {
InputReader in = new InputReader(System.in);
PrintWriter out = new PrintWriter(System.out);
Solver1486C1 solver = new Solver1486C1();
solver.solve(0, in, out);
out.close();
}
static class Solver1486C1 {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
int l = 1, r = n;
int ind = -1;
out.println("? " + l + " " + r);
out.flush();
int res = in.nextInt();
if (r - l == 1) {
if (r == res) {
ind = l;
} else {
ind = r;
}
} else {
while (l < r) {
if (r - l == 1) {
out.println("? " + l + " " + r);
out.flush();
res = in.nextInt();
if (r == res) {
ind = l;
} else {
ind = r;
}
break;
} else {
int mid = (l + r) / 2;
if (res <= mid) {
out.println("? " + l + " " + mid);
out.flush();
} else {
if (r != mid + 1) {
out.println("? " + (mid + 1) + " " + r);
out.flush();
} else {
r = mid;
continue;
}
}
int tmp = in.nextInt();
if (res <= mid) {
if (tmp == res) {
r = mid;
} else {
l = mid + 1;
if (r - l > 1) {
out.println("? " + l + " " + r);
out.flush();
res = in.nextInt();
}
}
} else {
if (tmp == res) {
l = mid + 1;
} else {
r = mid;
if (r - l > 1) {
out.println("? " + l + " " + r);
out.flush();
res = in.nextInt();
}
}
}
if (l == r) {
ind = l;
}
}
}
}
out.println("! " + ind);
out.flush();
}
}
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());
}
}
}
|
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"
] |
b3e8fe76706ba17cb285c75459508334
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,600
| null |
standard output
| |
PASSED
|
3961ca36ece16df06c6276a0ceac6dc9
|
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 40 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.math.BigInteger;
import java.util.*;
import java.util.concurrent.TimeUnit;
public class c1486 implements Runnable{
public static void main(String[] args) {
try{
new Thread(null, new c1486(), "process", 1<<26).start();
}
catch(Exception e){
System.out.println(e);
}
}
public void run() {
FastReader scan = new FastReader();
PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out), true);
//PrintWriter out = new PrintWriter("file.out");
Task solver = new Task();
//int t = scan.nextInt();
int t = 1;
for(int i = 1; i <= t; i++) solver.solve(i, scan, out);
out.close();
}
static class Task {
static final int oo = Integer.MAX_VALUE;
static final long OO = Long.MAX_VALUE;
public void solve(int testNumber, FastReader sc, PrintWriter out) {
int N = sc.nextInt();
int secondMax = -1;
int L = 1, R = N;
while(L < R-2) {
int M = (L+R)/2;
if(secondMax == -1) {
out.println("? " + L + " " + R);
secondMax = sc.nextInt();
}
if(secondMax <= M) {
out.println("? " + L + " " + M);
int q = sc.nextInt();
if(q == secondMax) {
R = M;
} else {
secondMax = -1;
L = M+1;
}
} else {
out.println("? " + (M+1) + " " + R);
int q = sc.nextInt();
if(q == secondMax) {
L=M+1;
} else {
secondMax = -1;
R=M;
}
}
}
if(L != R-1) {
out.println("? " + L + " " + R);
int q = sc.nextInt();
if(q == L) {
L++;
out.println("? " + L + " " + R);
if(sc.nextInt() == L) {
out.println("! "+ R);
} else {
out.println("! " + L);
}
} else if (q == R) {
R--;
out.println("? " + L + " " + R);
if(sc.nextInt() == L) {
out.println("! "+ R);
} else {
out.println("! " + L);
}
} else {
out.println("? " + L + " " + (L+1));
int q2 = sc.nextInt();
if(q == q2) {
out.println("! "+ L);
} else {
out.println("! " + R);
}
}
} else {
out.println("? " + L + " " + R);
if(sc.nextInt() == L) {
out.println("! "+ R);
} else {
out.println("! " + L);
}
}
}
}
static long modInverse(long N, long MOD) {
return binpow(N, MOD - 2, MOD);
}
static long modDivide(long a, long b, long MOD) {
a %= MOD;
return (binpow(b, MOD-2, MOD) * a) % MOD;
}
static long binpow(long a, long b, long m) {
a %= m;
long res = 1;
while (b > 0) {
if ((b & 1) == 1)
res = res * a % m;
a = a * a % m;
b >>= 1;
}
return res;
}
static int[] reverse(int a[])
{
int[] b = new int[a.length];
for (int i = 0, j = a.length; i < a.length; i++, j--) {
b[j - 1] = a[i];
}
return b;
}
static long[] reverse(long a[])
{
long[] b = new long[a.length];
for (int i = 0, j = a.length; i < a.length; i++, j--) {
b[j - 1] = a[i];
}
return b;
}
static void shuffle(Object[] a) {
Random get = new Random();
for (int i = 0; i < a.length; i++) {
int r = get.nextInt(a.length);
Object temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
static void shuffle(int[] a) {
Random get = new Random();
for (int i = 0; i < a.length; i++) {
int r = get.nextInt(a.length);
int temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
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 class tup implements Comparable<tup>, Comparator<tup>{
int a, b;
tup(int a,int b){
this.a=a;
this.b=b;
}
public tup() {
}
@Override
public int compareTo(tup o){
return Integer.compare(b,o.b);
}
@Override
public int compare(tup o1, tup o2) {
return Integer.compare(o1.b, o2.b);
}
@Override
public int hashCode() {
return Objects.hash(a, b);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
tup other = (tup) obj;
return a==other.a && b==other.b;
}
@Override
public String toString() {
return a + " " + b;
}
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
public FastReader(String s) throws FileNotFoundException {
br = new BufferedReader(new FileReader(new File(s)));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
int[] readArray(int size) {
int[] a = new int[size];
for(int i = 0; i < size; i++) {
a[i] = nextInt();
}
return a;
}
long[] readLongArray(int size) {
long[] a = new long[size];
for(int i = 0; i < size; i++) {
a[i] = nextLong();
}
return a;
}
}
static void dbg(int[] arr) {
System.out.println(Arrays.toString(arr));
}
static void dbg(long[] arr) {
System.out.println(Arrays.toString(arr));
}
static void dbg(boolean[] arr) {
System.out.println(Arrays.toString(arr));
}
static void dbg(Object... args) {
for (Object arg : args)
System.out.print(arg + " ");
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 8
|
standard input
|
[
"binary search",
"interactive"
] |
b3e8fe76706ba17cb285c75459508334
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,600
| null |
standard output
| |
PASSED
|
a30bef7b18284531dc00636d053a5fb6
|
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 40 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"
] |
b3e8fe76706ba17cb285c75459508334
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,600
| null |
standard output
| |
PASSED
|
0a57537666256acdbfc84c5906c90593
|
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 40 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"
] |
b3e8fe76706ba17cb285c75459508334
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,600
| null |
standard output
| |
PASSED
|
e211285fcbe3823de086221fff45efd7
|
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 40 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"
] |
b3e8fe76706ba17cb285c75459508334
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,600
| null |
standard output
| |
PASSED
|
baa544e9f6ef824f2ce0485378f9c96a
|
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 40 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 Guessing_the_greatest {
static StringBuilder sb;
static dsu dsu;
static long fact[];
static long mod = (int) (1e9);
static void solve() {
int n = i();
int lo = 1;
int hi = n+1;
while(lo+1 < hi){
int mid = lo + (hi-lo)/2;
int idx = index(lo,hi-1);
if(idx < mid){
int left2max = index(lo,mid-1);
if(left2max == idx){
hi = mid;
}else{
lo = mid;
}
}else{
int right2max = index(mid,hi-1);
if(right2max == idx){
lo = mid;
}else{
hi = mid;
}
}
}
sb.append("! "+(hi-1)+"\n");
}
static int index(int lo,int hi){
if(lo == hi){
return -1;
}
System.out.println("? "+lo+" "+hi);
System.out.flush();
int idx = i();
return idx;
}
public static void main(String[] args) {
sb = new StringBuilder();
int test = 1;
// test = i();
while (test-- > 0) {
solve();
}
System.out.println(sb);
}
/*
* fact=new long[(int)1e6+10]; fact[0]=fact[1]=1; for(int i=2;i<fact.length;i++)
* { fact[i]=((long)(i%mod)1L(long)(fact[i-1]%mod))%mod; }
*/
//**************NCR%P******************
static long ncr(int n, int r) {
if (r > n)
return (long) 0;
long res = fact[n] % mod;
// System.out.println(res);
res = ((long) (res % mod) * (long) (p(fact[r], mod - 2) % mod)) % mod;
res = ((long) (res % mod) * (long) (p(fact[n - r], mod - 2) % mod)) % mod;
// System.out.println(res);
return res;
}
static long p(long x, long y)// POWER FXN //
{
if (y == 0)
return 1;
long res = 1;
while (y > 0) {
if (y % 2 == 1) {
res = (res * x) % mod;
y--;
}
x = (x * x) % mod;
y = y / 2;
}
return res;
}
//**************END******************
// *************Disjoint set
// union*********//
static class dsu {
int parent[];
dsu(int n) {
parent = new int[n];
for (int i = 0; i < n; i++)
parent[i] = -1;
}
int find(int a) {
if (parent[a] < 0)
return a;
else {
int x = find(parent[a]);
parent[a] = x;
return x;
}
}
void merge(int a, int b) {
a = find(a);
b = find(b);
if (a == b)
return;
parent[b] = a;
}
}
//**************PRIME FACTORIZE **********************************//
static TreeMap<Integer, Integer> prime(long n) {
TreeMap<Integer, Integer> h = new TreeMap<>();
long num = n;
for (int i = 2; i <= Math.sqrt(num); i++) {
if (n % i == 0) {
int nt = 0;
while (n % i == 0) {
n = n / i;
nt++;
}
h.put(i, nt);
}
}
if (n != 1)
h.put((int) n, 1);
return h;
}
//****CLASS PAIR ************************************************
static class Pair implements Comparable<Pair> {
int x;
int y;
Pair(int x, int y) {
this.x = x;
this.y = y;
}
public int compareTo(Pair o) {
return (int) (this.y - o.y);
}
}
//****CLASS PAIR **************************************************
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 Int() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String String() {
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 String();
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0)
writer.print(' ');
writer.print(objects[i]);
}
}
public void printLine(Object... objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
public void flush() {
writer.flush();
}
}
static InputReader in = new InputReader(System.in);
static OutputWriter out = new OutputWriter(System.out);
public static long[] sort(long[] a2) {
int n = a2.length;
ArrayList<Long> l = new ArrayList<>();
for (long i : a2)
l.add(i);
Collections.sort(l);
for (int i = 0; i < l.size(); i++)
a2[i] = l.get(i);
return a2;
}
public static int[] sort(int[] a2) {
int n = a2.length;
ArrayList<Integer> l = new ArrayList<>();
for (int i : a2)
l.add(i);
Collections.sort(l);
for (int i = 0; i < l.size(); i++)
a2[i] = l.get(i);
return a2;
}
public static long pow(long x, long y) {
long res = 1;
while (y > 0) {
if (y % 2 != 0) {
res = (res * x);// % modulus;
y--;
}
x = (x * x);// % modulus;
y = y / 2;
}
return res;
}
//GCD___+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
public static long gcd(long x, long y) {
if (x == 0)
return y;
else
return gcd(y % x, x);
}
// ******LOWEST COMMON MULTIPLE
// *********************************************
public static long lcm(long x, long y) {
return (x * (y / gcd(x, y)));
}
//INPUT PATTERN********************************************************
public static int i() {
return in.Int();
}
public static long l() {
String s = in.String();
return Long.parseLong(s);
}
public static String s() {
return in.String();
}
public static int[] readArrayi(int n) {
int A[] = new int[n];
for (int i = 0; i < n; i++) {
A[i] = i();
}
return A;
}
public static long[] readArray(long n) {
long A[] = new long[(int) n];
for (int i = 0; i < n; i++) {
A[i] = l();
}
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"
] |
b3e8fe76706ba17cb285c75459508334
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,600
| null |
standard output
| |
PASSED
|
93a0a9f9383b76f5952a46c3d278001a
|
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 40 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) {
FastReader f = new FastReader();
StringBuffer sb=new StringBuffer();
int n=f.nextInt();
int l=1,r=n;
while(l<r)
{
System.out.println("? "+l+" "+r);
int idx=f.nextInt();
int mid=(l+r)/2;
if(idx<mid)
{
System.out.println("? "+l+" "+mid);
int sec=f.nextInt();
if(idx==sec)
r=mid;
else
l=mid;
if(r-l == 1)
{
if(r==sec)
{
r=l;
break;
}
else if(l==sec)
break;
}
}
else
{
System.out.println("? "+mid+" "+r);
int sec=f.nextInt();
if(idx==sec)
l=mid;
else
r=mid;
if(r-l == 1)
{
if(r==sec)
{
r=l;
break;
}
else if(l==sec)
break;
}
}
}
System.out.println("! "+r);
}
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"
] |
b3e8fe76706ba17cb285c75459508334
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,600
| null |
standard output
| |
PASSED
|
440859651192d8a3cafe04757375f2e4
|
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 40 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();
int l=1,r=n;
while(l<r)
{
int mid=(l+r)/2;
System.out.println("? "+l+" "+r);
System.out.flush();
int p=input.nextInt();
if(p<=mid)
{
int l1=l,r1=mid;
if(l1==r1)
{
l=mid+1;
}
else
{
System.out.println("? "+l+" "+mid);
System.out.flush();
int p1=input.nextInt();
if(p==p1)
{
r=mid;
}
else
{
l=mid+1;
}
}
}
else
{
int l1=mid+1;
int r1=r;
if(l1==r1)
{
r=mid;
}
else
{
System.out.println("? "+(mid+1)+" "+r);
System.out.flush();
int p1=input.nextInt();
if(p1==p)
{
l=mid+1;
}
else
{
r=mid;
}
}
}
}
System.out.println("! "+l);
}
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"
] |
b3e8fe76706ba17cb285c75459508334
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,600
| null |
standard output
| |
PASSED
|
3bc69ce453afd2cbc6310ae1e07bd20c
|
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 40 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"
] |
b3e8fe76706ba17cb285c75459508334
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,600
| null |
standard output
| |
PASSED
|
03533505d4e7abeb1039c04e7db209a6
|
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 40 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.lang.*;
public class Main implements Runnable {
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private 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);
}
}
public static void main(String args[]) throws Exception {
new Thread(null, new Main(), "Main", 1 << 27).start();
}
static class Pair {
int f;
int s;
int p;
PrintWriter w;
// int t;
Pair(int f, int s) {
// Pair(int f,int s, PrintWriter w){
this.f = f;
this.s = s;
// this.p = p;
// this.w = w;
// this.t = t;
}
public static Comparator<Pair> wc = new Comparator<Pair>() {
public int compare(Pair e1, Pair e2) {
// 1 for swap
if (Math.abs(e1.f) - Math.abs(e2.f) != 0) {
// e1.w.println("**"+e1.f+" "+e2.f);
return (Math.abs(e1.f) - Math.abs(e2.f));
} else {
// e1.w.println("##"+e1.f+" "+e2.f);
return (Math.abs(e1.s) - Math.abs(e2.s));
}
}
};
}
public static ArrayList<Integer> sieve(int N) {
int i, j, flag;
ArrayList<Integer> p = new ArrayList<Integer>();
for (i = 1; i < N; i++) {
if (i == 1 || i == 0)
continue;
flag = 1;
for (j = 2; j <= i / 2; ++j) {
if (i % j == 0) {
flag = 0;
break;
}
}
if (flag == 1) {
p.add(i);
}
}
return p;
}
public static long gcd(long a, long b) {
if (b == 0)
return a;
else
return gcd(b, a % b);
}
//// recursive dfs
public static int dfs(int s, ArrayList<Integer>[] g, long[] dist, boolean[] v, PrintWriter w, int p) {
v[s] = true;
int ans = 1;
// int n = dist.length - 1;
int t = g[s].size();
// int max = 1;
for (int i = 0; i < t; i++) {
int x = g[s].get(i);
if (!v[x]) {
// dist[x] = dist[s] + 1;
ans = Math.min(ans, dfs(x, g, dist, v, w, s));
} else if (x != p) {
// w.println("* " + s + " " + x + " " + p);
ans = 0;
}
}
// max = Math.max(max,(n-p));
return ans;
}
//// iterative BFS
public static int bfs(int s, ArrayList<Integer>[] g, long[] dist, boolean[] b, PrintWriter w, int p) {
b[s] = true;
int siz = 1;
// dist--;
Queue<Integer> q = new LinkedList<>();
q.add(s);
while (q.size() != 0) {
int i = q.poll();
Iterator<Integer> it = g[i].listIterator();
int z = 0;
while (it.hasNext()) {
z = it.next();
if (!b[z]) {
b[z] = true;
// dist--;
dist[z] = dist[i] + 1;
// siz++;
q.add(z);
} else if (z != p) {
siz = 0;
}
}
}
return siz;
}
public static int lower(int key, int[] a) {
int l = 0;
int r = a.length - 1;
int res = 0;
while (l <= r) {
int mid = (l + r) / 2;
if (a[mid] <= key) {
l = mid + 1;
res = mid + 1;
} else {
r = mid - 1;
}
}
return res;
}
public static long power(long x, long y, long m) {
if (y == 0)
return 1;
long p = power(x, y / 2, m) % m;
p = (p * p) % m;
if (y % 2 == 0)
return p;
else
return (x * p) % m;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////
// code here
int[] parent;
int[] dist;
int[] height;
boolean[] vis;
ArrayList<Integer>[] g;
int[] c;
public void run() {
InputReader sc = new InputReader(System.in);
PrintWriter w = new PrintWriter(System.out);
int defaultValue = 0;
int mod = 1000000007;
int oo = (int) 1e9;
int test = 1;
// test = sc.nextInt();
while (test-- > 0) {
int n = sc.nextInt();
int l = 1;
int r = n + 1;
int m = 0;
int sm = 0;
while (l < r - 1) {
int mid = (l + r) / 2;
w.println("? " + l + " " + (r - 1));
w.flush();
m = sc.nextInt();
if (m < mid) {
if (l < mid - 1) {
w.println("? " + l + " " + (mid - 1));
w.flush();
sm = sc.nextInt();
if (sm == m) {
r = mid;
} else {
l = mid;
}
} else {
l = mid;
}
} else {
if (mid < r - 1) {
w.println("? " + mid + " " + (r - 1));
w.flush();
sm = sc.nextInt();
if (sm == m) {
l = mid;
} else {
r = mid;
}
} else {
r = mid;
}
}
}
w.println("! " + (r - 1));
}
w.flush();
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"
] |
b3e8fe76706ba17cb285c75459508334
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,600
| null |
standard output
| |
PASSED
|
7aa762c81628afc6ced68cec0937f83c
|
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 40 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 PrintWriter pw;
static Scanner sc;
static long ceildiv(long x, long y) { return (x+y-1)/y; }
static int mod(long x, int m) { return (int)((x%m+m)%m); }
static void put(HashMap<Integer, Integer> map, Integer p){if(map.containsKey(p)) map.replace(p, map.get(p)+1); else map.put(p, 1); }
static void rem(TreeMap<Integer, Integer> map, Integer p){ if(map.get(p)==1) map.remove(p);else map.replace(p, map.get(p)-1); }
static void printf(double x, int dig){ String s="%."+dig+"f"; pw.printf(s, x); }
static int Int(boolean x){ return x?1:0; }
static final int inf=(int)1e9, mod=998244353;
static final long infL=inf*1l*inf;
static final double eps=1e-9;
public static long gcd(long x, long y) { return y==0? x: gcd(y, x%y); }
public static void main(String[] args) throws Exception {
sc = new Scanner(System.in);
pw = new PrintWriter(System.out);
// int t = sc.nextInt();
// while (t-- > 0)
testcase();
pw.close();
}
static int ask(int l, int r) throws IOException{
pw.println("? "+(l+1)+ " "+(r+1));
pw.flush();
return sc.nextInt()-1;
}
static void testcase() throws IOException {
int n=sc.nextInt();
int prev=ask(0, n-1);
int st=0, end=n-1;
while(end-st>=3){
int mid=(st+end)/2;
int x;
if(prev<=mid){
x=ask(st, mid);
if(x==prev){
end=mid;
}else{
st=mid+1;
prev=ask(mid+1, end);
}
}else{
x=ask(mid+1, end);
if(x==prev){
st=mid+1;
}else{
end=mid;
prev=ask(st, mid);
}
}
}
if(end==st+1){
out(prev==end ? st: end);
}else{
int x=prev;
if(x==st+1){
x=ask(st, st+1);
if(x==prev)
out(st);
else
out(end);
}else if(x==st){
x=ask(st+1, end);
if(x==st+1)
out(end);
else
out(st+1);
}else{
x=ask(st, st+1);
if(x==st+1)
out(st);
else
out(st+1);
}
}
}
static void out(int x){
pw.println("! "+(x+1));
}
static void printArr(int[] arr) {
for (int i = 0; i < arr.length; i++)
pw.print(arr[i] + " ");
pw.println();
}
static void printArr(long[] arr) {
for (int i = 0; i < arr.length; i++)
pw.print(arr[i] + " ");
pw.println();
}
static void printArr(double[] arr) {
for (int i = 0; i < arr.length; i++)
pw.print(arr[i] + " ");
pw.println();
}
static void printArr(Integer[] arr) {
for (int i = 0; i < arr.length; i++)
pw.print(arr[i] + " ");
pw.println();
}
static void printArr(ArrayList list) {
for (int i = 0; i < list.size(); i++)
pw.print(list.get(i)+" ");
pw.println();
}
static void printArr(boolean[] arr) {
StringBuilder sb=new StringBuilder();
for(boolean b: arr)
sb.append(Int(b));
pw.println(sb);
}
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 {
return Double.parseDouble(next());
}
public int[] nextDigits() throws IOException{
String s=nextLine();
int[] arr=new int[s.length()];
for(int i=0; i<arr.length; i++)
arr[i]=s.charAt(i)-'0';
return arr;
}
public int[] nextArr(int n) throws IOException {
int[] arr = new int[n];
for (int i = 0; i < arr.length; i++)
arr[i] = nextInt();
return arr;
}
public Integer[] nextsort(int n) throws IOException{
Integer[] arr=new Integer[n];
for(int i=0; i<n; i++)
arr[i]=nextInt();
return arr;
}
public Pair nextPair() throws IOException{
return new Pair(nextInt(), nextInt());
}
public long[] nextLongArr(int n) throws IOException{
long[] arr=new long[n];
for (int i = 0; i < n; i++)
arr[i]=sc.nextLong();
return arr;
}
public Pair[] nextPairArr(int n) throws IOException{
Pair[] arr=new Pair[n];
for(int i=0; i<n; i++)
arr[i]=nextPair();
return arr;
}
public boolean ready() throws IOException {
return br.ready();
}
}
static class Pair implements Comparable<Pair>{
int x;
int y;
public Pair(int x, int y) {
this.x=x;
this.y=y;
}
public boolean contains(int a){
return x==a || y==a;
}
public int hashCode() {
return (this.x*1000000000+this.y);
}
public int compareTo(Pair p){
if(x==p.x)
return y-p.y;
return x-p.x;
}
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (this.getClass() != obj.getClass()) {
return false;
}
Pair p = (Pair) obj;
return this.x==p.x && this.y==p.y;
}
public Pair clone(){
return new Pair(x, y);
}
public String toString(){
return this.x+" "+this.y;
}
public void add(Pair p){
x+=p.x;
y+=p.y;
}
public Pair negative(){
return new Pair(-x, -y);
}
}
static class LP implements Comparable<LP>{
long x, y;
public LP(long a, long b){
x=a;
y=b;
}
public void add(LP p){
x+=p.x;
y+=p.y;
}
public boolean equals(LP p){
return p.x==x && y==p.y;
}
public String toString(){
return this.x+" "+this.y;
}
public int compareTo(LP p){
int a=Long.compare(x, p.x);
if(a!=0)
return a;
return Long.compare(y, p.y);
}
}
static class Triple implements Comparable<Triple>{
int x, y, z;
public Triple(int a, int b, int c){
x=a;
y=b;
z=c;
}
public int compareTo(Triple t){
if(this.y!=t.y)
return y-t.y;
return x-t.x;
}
public String toString(){
return x+" "+y+" "+z;
}
}
// static class MaxSegmentTree{
// int n;
// long[] tree;
// public MaxSegmentTree(int len, long[] arr){
// n=len;
// build(0, 0, n-1, arr);
// }
// public void build(int i, int l, int r, long[] arr){
// if(l==r){
// tree[i]=arr[l];
// return;
// }
// int mid=(l+r)/2, left=2*i+1, right=2*i+2;
// build(left, l, mid, arr);
// build(right, mid+1, r, arr);
// tree[i]=Math.max(left, right);
// }
// public int query(int i){
// return query(0, 0, n-1, 0, i);
// }
// public int query(int node, int i, int j, int l, int r){
// if(l>j || r<i)
// return -1;
//
// }
// }
static class SegmentTree {
int n, size[];
long[] tree;
public SegmentTree(int len) {
n = len;
tree=new long[2*n-1];
size=new int[2*n-1];
}
public void set(int i, long x){
i+=n-1;
tree[i]=x;
size[i]++;
i=(i-1)/2;
while(true){
size[i]++;
tree[i]=tree[i*2+1] + tree[i*2+2];
if(i==0)
break;
i=(i-1)/2;
}
}
public long query(int x){
return query(0, 0, n-1, x+1, n-1);
}
public long query(int node, int i, int j, int l, int r){
if(j<l || i>r)
return 0;
if(i>=l && j<=r)
return tree[node];
int mid=(i+j)/2, left=node*2+1, right=node*2+2;
return query(left, i, mid, l, r) + query(right, mid+1, j, l, r);
}
public int size(int idx){
return size(0, 0, n-1, idx+1, n-1);
}
public int size(int node, int i, int j, int l, int r){
if(i>r || j<l)
return 0;
if(i>=l && j<=r)
return size[node];
int mid=(i+j)/2, left=node*2+1, right=node*2+2;
return size(left, i, mid, l, r)+size(right, mid+1, j, 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 8
|
standard input
|
[
"binary search",
"interactive"
] |
b3e8fe76706ba17cb285c75459508334
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,600
| null |
standard output
| |
PASSED
|
6f2b37452ac46eb460ec0b08603ed284
|
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 40 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
|
/*
* akshaygupta26
*/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
import java.util.Random;
import java.util.Arrays;
import java.util.StringTokenizer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Collections;
public class D
{
static FastReader sc=new FastReader();
static HashMap<Integer,HashMap<Integer,Integer>> map=new HashMap<>();
public static void main(String[] args)
{
StringBuffer ans=new StringBuffer();
int test=1;
while(test-->0)
{
int n=sc.nextInt();
int low =1;
int high=n;
while(low!=high) {
if(high-low == 1) {
int index =query(low,high);
if(index == low) low=high;
break;
}
int index =query(low,high);
int mid = (low+high)/2;
if(index>mid) {
int index2 =query(mid,high);
if(index == index2) {
low=mid;
continue;
}
else {
high=mid;
if(index2 == mid) high--;
continue;
}
}
else if(index<mid) {
int index2 =query(low,mid);
if(index == index2) {
high=mid;
continue;
}
else {
low=mid;
if(index2 == mid) low++;
continue;
}
}
else if(index == mid) {
int index2 =query(mid,high);
if(index2 == index) {
low=mid+1;
continue;
}
else {
high=mid-1;
continue;
}
}
}
System.out.println("! "+low);
System.out.flush();
}
System.out.print(ans);
}
static int query(int l,int r) {
if(map.containsKey(l) && map.get(l).containsKey(r)) {
return map.get(l).get(r);
}
System.out.println("? "+l+" "+r);
System.out.flush();
int n =sc.nextInt();
if(!map.containsKey(l)) {
map.put(l,new HashMap<Integer,Integer>());
}
map.get(l).put(r,n);
return n;
}
static final Random random=new Random();
static void ruffleSort(int[] a) {
int n=a.length;//shuffle, then sort
for (int i=0; i<n; i++) {
int oi=random.nextInt(n), temp=a[oi];
a[oi]=a[i]; a[i]=temp;
}
Arrays.sort(a);
}
static void ruffleSort(long[] a) {
int n=a.length;//shuffle, then sort
for (int i=0; i<n; i++) {
int oi=random.nextInt(n);
long temp=a[oi];
a[oi]=a[i]; a[i]=temp;
}
Arrays.sort(a);
}
static 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"
] |
b3e8fe76706ba17cb285c75459508334
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,600
| null |
standard output
| |
PASSED
|
ea52cb234c21ef2b4be9554f861809fc
|
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 40 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
|
/*
* akshaygupta26
*/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
import java.util.Random;
import java.util.Arrays;
import java.util.StringTokenizer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Collections;
public class C
{
public static void main(String[] args)
{
FastReader sc=new FastReader();
StringBuffer ans=new StringBuffer();
int test=1;
while(test-->0)
{
int n=sc.nextInt();
int low =1;
int high =n;
System.out.println("? "+low+" "+high);
int index =sc.nextInt();//2nd highest
System.out.flush();
while(low != high) {
if(high-low == 1) {
if(index == low) low=high;
break;
}
int mid = (low+high)/2;
System.out.println("? "+low+" "+mid);
System.out.flush();
int index2 =sc.nextInt();
if(index2 == index) {
high =mid;
continue;
}
System.out.println("? "+mid+" "+high);
System.out.flush();
int index3 =sc.nextInt();
if(index3 == index) {
low =mid;
continue;
}
if(index>mid) {
index=index2;
high=mid;
}
else if(index<mid) {
index=index3;
low=mid;
}
}
ans.append("! "+low+"\n");
}
System.out.print(ans);
}
static final Random random=new Random();
static void ruffleSort(int[] a) {
int n=a.length;//shuffle, then sort
for (int i=0; i<n; i++) {
int oi=random.nextInt(n), temp=a[oi];
a[oi]=a[i]; a[i]=temp;
}
Arrays.sort(a);
}
static void ruffleSort(long[] a) {
int n=a.length;//shuffle, then sort
for (int i=0; i<n; i++) {
int oi=random.nextInt(n);
long temp=a[oi];
a[oi]=a[i]; a[i]=temp;
}
Arrays.sort(a);
}
static 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"
] |
b3e8fe76706ba17cb285c75459508334
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,600
| null |
standard output
| |
PASSED
|
b13c21e6207cbc225dc352fcc12bddf0
|
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 40 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 long mod=1000000007l;
static int max=Integer.MAX_VALUE,min=Integer.MIN_VALUE;
static long maxl=Long.MAX_VALUE,minl=Long.MIN_VALUE;
static BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
static StringTokenizer st;
static StringBuilder sb;
// static public void main(String[] args)throws Exception
// {
// st=new StringTokenizer(br.readLine());
// int t=i();
// sb=new StringBuilder(1000000);
// o:
// while(t-->0)
// {
// int n=i();
// for(int x=0;x<n;x++)
// {
// int a=i();
// int b=i();
// }
// }
// p(sb);
// }
static public void main(String[] args)throws Exception
{
st=new StringTokenizer(br.readLine());
int n=i();
int i=1;
int j=n;
pl("? "+i+" "+j);
System.out.flush();
int in=i();
while(i<=j)
{
int m=(i+j)/2;
if(j-i==1)
{
if(in==i)
{
pl("! "+j);
return;
}
pl("! "+i);
return;
}
else if(j-i==2)
{
pl("? "+(i+1)+" "+j);
System.out.flush();
int aa=i();
pl("? "+(i)+" "+(j-1));
System.out.flush();
int bb=i();
HashSet<Integer> h=new HashSet<>(3);
h.add(i);
h.add(i+1);
h.add(i+2);
h.remove(aa);
h.remove(bb);
h.remove(in);
for(int e:h)
{
pl("! "+e);
return;
}
}
else
{
pl("? "+(i)+" "+m);
System.out.flush();
int aa=i();
pl("? "+(m+1)+" "+j);
System.out.flush();
int bb=i();
if(aa==in)
{
j=m;
}
else if(bb==in)
{
i=m+1;
}
else
{
if(in>=i&&in<=m)
{
in=bb;
i=m+1;
}
else
{
in=aa;
j=m;
}
}
}
}
}
static int[] so(int ar[])
{
Integer r[]=new Integer[ar.length];
for(int x=0;x<ar.length;x++)r[x]=ar[x];
Arrays.sort(r);
for(int x=0;x<ar.length;x++)ar[x]=r[x];
return ar;
}
static long[] so(long ar[])
{
Long r[]=new Long[ar.length];
for(int x=0;x<ar.length;x++)r[x]=ar[x];
Arrays.sort(r);
for(int x=0;x<ar.length;x++)ar[x]=r[x];
return ar;
}
static char[] so(char ar[])
{
Character r[]=new Character[ar.length];
for(int x=0;x<ar.length;x++)r[x]=ar[x];
Arrays.sort(r);
for(int x=0;x<ar.length;x++)ar[x]=r[x];
return ar;
}
static void s(String s){sb.append(s);}
static void s(int s){sb.append(s);}
static void s(long s){sb.append(s);}
static void s(char s){sb.append(s);}
static void s(double s){sb.append(s);}
static void ss(){sb.append(' ');}
static void sl(String s){sb.append(s);sb.append("\n");}
static void sl(int s){sb.append(s);sb.append("\n");}
static void sl(long s){sb.append(s);sb.append("\n");}
static void sl(char s){sb.append(s);sb.append("\n");}
static void sl(double s){sb.append(s);sb.append("\n");}
static void sl(){sb.append("\n");}
static int max(int ...a){int m=a[0];for(int e:a)m=(m>=e)?m:e;return m;}
static int min(int ...a){int m=a[0];for(int e:a)m=(m<=e)?m:e;return m;}
static int abs(int a){return Math.abs(a);}
static long max(long ...a){long m=a[0];for(long e:a)m=(m>=e)?m:e;return m;}
static long min(long ...a){long m=a[0];for(long e:a)m=(m<=e)?m:e;return m;}
static long abs(long a){return Math.abs(a);}
static int sq(int a){return (int)Math.sqrt(a);}
static long sq(long a){return (long)Math.sqrt(a);}
static long gcd(long a,long b){return b==0l?a:gcd(b,a%b);}
static boolean pa(String s,int i,int j)
{
while(i<j)if(s.charAt(i++)!=s.charAt(j--))return false;
return true;
}
static int ncr(int n,int c,long m)
{
long a=1l;
for(int x=n-c+1;x<=n;x++)a=((a*x)%m);
long b=1l;
for(int x=2;x<=c;x++)b=((b*x)%m);
return (int)((a*(mul((int)b,m-2,m)%m))%m);
}
static boolean[] si(int n)
{
boolean bo[]=new boolean[n+1];
bo[0]=true;bo[1]=true;
for(int x=4;x<=n;x+=2)bo[x]=true;
for(int x=3;x*x<=n;x+=2)
{
if(!bo[x])
{
int vv=(x<<1);
for(int y=x*x;y<=n;y+=vv)bo[y]=true;
}
}
return bo;
}
static int[] fac(int n)
{
int bo[]=new int[n+1];
for(int x=1;x<=n;x++)for(int y=x;y<=n;y+=x)bo[y]++;
return bo;
}
static long mul(long a,long b,long m)
{
long r=1l;
a%=m;
while(b>0)
{
if((b&1)==1)r=(r*a)%m;
b>>=1;
a=(a*a)%m;
}
return r;
}
static int i()throws IOException
{
if(!st.hasMoreTokens())st=new StringTokenizer(br.readLine());
return Integer.parseInt(st.nextToken());
}
static long l()throws IOException
{
if(!st.hasMoreTokens())st=new StringTokenizer(br.readLine());
return Long.parseLong(st.nextToken());
}
static String s()throws IOException
{
if(!st.hasMoreTokens())st=new StringTokenizer(br.readLine());
return st.nextToken();
}
static double d()throws IOException
{
if(!st.hasMoreTokens())st=new StringTokenizer(br.readLine());
return Double.parseDouble(st.nextToken());
}
static void p(Object p){System.out.print(p);}
static void p(String p){System.out.print(p);}
static void p(int p){System.out.print(p);}
static void p(double p){System.out.print(p);}
static void p(long p){System.out.print(p);}
static void p(char p){System.out.print(p);}
static void p(boolean p){System.out.print(p);}
static void pl(Object p){System.out.println(p);}
static void pl(String p){System.out.println(p);}
static void pl(int p){System.out.println(p);}
static void pl(char p){System.out.println(p);}
static void pl(double p){System.out.println(p);}
static void pl(long p){System.out.println(p);}
static void pl(boolean p){System.out.println(p);}
static void pl(){System.out.println();}
static void s(int a[])
{
for(int e:a)
{
sb.append(e);
sb.append(' ');
}
sb.append("\n");
}
static void s(long a[])
{
for(long e:a)
{
sb.append(e);
sb.append(' ');
}
sb.append("\n");
}
static void s(int ar[][])
{
for(int a[]:ar)
{
for(int e:a)
{
sb.append(e);
sb.append(' ');
}
sb.append("\n");
}
}
static void s(char a[])
{
for(char e:a)
{
sb.append(e);
sb.append(' ');
}
sb.append("\n");
}
static void s(char ar[][])
{
for(char a[]:ar)
{
for(char e:a)
{
sb.append(e);
sb.append(' ');
}
sb.append("\n");
}
}
static int[] ari(int n)throws IOException
{
int ar[]=new int[n];
if(!st.hasMoreTokens())st=new StringTokenizer(br.readLine());
for(int x=0;x<n;x++)ar[x]=Integer.parseInt(st.nextToken());
return ar;
}
static int[][] ari(int n,int m)throws IOException
{
int ar[][]=new int[n][m];
for(int x=0;x<n;x++)
{
if(!st.hasMoreTokens())st=new StringTokenizer(br.readLine());
for(int y=0;y<m;y++)ar[x][y]=Integer.parseInt(st.nextToken());
}
return ar;
}
static long[] arl(int n)throws IOException
{
long ar[]=new long[n];
if(!st.hasMoreTokens())st=new StringTokenizer(br.readLine());
for(int x=0;x<n;x++) ar[x]=Long.parseLong(st.nextToken());
return ar;
}
static long[][] arl(int n,int m)throws IOException
{
long ar[][]=new long[n][m];
for(int x=0;x<n;x++)
{
if(!st.hasMoreTokens())st=new StringTokenizer(br.readLine());
for(int y=0;y<m;y++)ar[x][y]=Long.parseLong(st.nextToken());
}
return ar;
}
static String[] ars(int n)throws IOException
{
String ar[]=new String[n];
if(!st.hasMoreTokens())st=new StringTokenizer(br.readLine());
for(int x=0;x<n;x++) ar[x]=st.nextToken();
return ar;
}
static double[] ard(int n)throws IOException
{
double ar[]=new double[n];
if(!st.hasMoreTokens())st=new StringTokenizer(br.readLine());
for(int x=0;x<n;x++)ar[x]=Double.parseDouble(st.nextToken());
return ar;
}
static double[][] ard(int n,int m)throws IOException
{
double ar[][]=new double[n][m];
for(int x=0;x<n;x++)
{
if(!st.hasMoreTokens())st=new StringTokenizer(br.readLine());
for(int y=0;y<m;y++)ar[x][y]=Double.parseDouble(st.nextToken());
}
return ar;
}
static char[] arc(int n)throws IOException
{
char ar[]=new char[n];
if(!st.hasMoreTokens())st=new StringTokenizer(br.readLine());
for(int x=0;x<n;x++)ar[x]=st.nextToken().charAt(0);
return ar;
}
static char[][] arc(int n,int m)throws IOException
{
char ar[][]=new char[n][m];
for(int x=0;x<n;x++)
{
String s=br.readLine();
for(int y=0;y<m;y++)ar[x][y]=s.charAt(y);
}
return ar;
}
static void p(int ar[])
{
StringBuilder sb=new StringBuilder(2*ar.length);
for(int a:ar)
{
sb.append(a);
sb.append(' ');
}
System.out.println(sb);
}
static void p(int ar[][])
{
StringBuilder sb=new StringBuilder(2*ar.length*ar[0].length);
for(int a[]:ar)
{
for(int aa:a)
{
sb.append(aa);
sb.append(' ');
}
sb.append("\n");
}
p(sb);
}
static void p(long ar[])
{
StringBuilder sb=new StringBuilder(2*ar.length);
for(long a:ar)
{
sb.append(a);
sb.append(' ');
}
System.out.println(sb);
}
static void p(long ar[][])
{
StringBuilder sb=new StringBuilder(2*ar.length*ar[0].length);
for(long a[]:ar)
{
for(long aa:a)
{
sb.append(aa);
sb.append(' ');
}
sb.append("\n");
}
p(sb);
}
static void p(String ar[])
{
int c=0;
for(String s:ar)c+=s.length()+1;
StringBuilder sb=new StringBuilder(c);
for(String a:ar)
{
sb.append(a);
sb.append(' ');
}
System.out.println(sb);
}
static void p(double ar[])
{
StringBuilder sb=new StringBuilder(2*ar.length);
for(double a:ar)
{
sb.append(a);
sb.append(' ');
}
System.out.println(sb);
}
static void p(double ar[][])
{
StringBuilder sb=new StringBuilder(2*ar.length*ar[0].length);
for(double a[]:ar)
{
for(double aa:a)
{
sb.append(aa);
sb.append(' ');
}
sb.append("\n");
}
p(sb);
}
static void p(char ar[])
{
StringBuilder sb=new StringBuilder(2*ar.length);
for(char aa:ar)
{
sb.append(aa);
sb.append(' ');
}
System.out.println(sb);
}
static void p(char ar[][])
{
StringBuilder sb=new StringBuilder(2*ar.length*ar[0].length);
for(char a[]:ar)
{
for(char aa:a)
{
sb.append(aa);
sb.append(' ');
}
sb.append("\n");
}
p(sb);
}
}
|
Java
|
["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"
] |
b3e8fe76706ba17cb285c75459508334
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,600
| null |
standard output
| |
PASSED
|
c7bf03c8437d4a7e43420c2f8b994e77
|
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 40 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 com.company;
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) {
Main main = new Main();
main.solve();
}
public void solve() {
Scanner in = null;
PrintWriter out = null;
try {
in = new Scanner(new File("input.txt"));
out = new PrintWriter(new File("output.txt"));
throw new FileNotFoundException();
}
catch (FileNotFoundException e) {
in = new Scanner(System.in);
out = new PrintWriter(System.out);
}
int n = in.nextInt();
out.println("? " + 1 + " " + n);
out.flush();
int maxi = in.nextInt() - 1;
int ans = find(0, n, maxi, in, out) + 1;
out.println("! " + ans);
out.flush();
out.close();
}
private int find(int l, int r, int maxi, Scanner in, PrintWriter out) {
if (l + 2 == r) {
return maxi == l ? l + 1 : l;
}
if (l + 3 == r) {
int ll = l + 1;
int lll = ll + 1;
out.println("? " + ll + " " + lll);
out.flush();
int newmaxi = in.nextInt() - 1;
if (maxi == l) {
if (newmaxi == maxi) {
return l + 1;
} else {
return l + 2;
}
} else if (maxi == l + 1) {
if (newmaxi == maxi) {
return l;
} else {
return l + 2;
}
} else {
if (newmaxi == l) {
return l + 1;
} else {
return l;
}
}
}
int pivot = (l + r) / 2;
int ll = l + 1;
int pp = pivot + 1;
if (maxi < pivot) {
out.println("? " + ll + " " + pivot);
out.flush();
int newmaxi = in.nextInt() - 1;
if (maxi == newmaxi) { //max is in the same
return find(l, pivot, newmaxi, in, out);
} else {
out.println("? " + pp + " " + r);
out.flush();
int secondmaxi = in.nextInt() - 1;
return find(pivot, r, secondmaxi, in, out);
}
} else {
out.println("? " + pp + " " + r);
out.flush();
int newmaxi = in.nextInt() - 1;
if (maxi == newmaxi) { //max is in the same
return find(pivot, r, newmaxi, in, out);
} else {
out.println("? " + ll + " " + pivot);
out.flush();
int secondmaxi = in.nextInt() - 1;
return find(l, pivot, secondmaxi, in, 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"
] |
b3e8fe76706ba17cb285c75459508334
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,600
| null |
standard output
| |
PASSED
|
949c824e236b2d5a48c65f832903f615
|
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 40 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 A implements Runnable {
public void run() {
long startTime = System.nanoTime();
int n = nextInt();
int[] f = new int[31];
f[1] = 2;
f[2] = 3;
for (int i = 3; i <= 24; i++) {
f[i] = f[i - 1] + f[i - 2];
}
int ind = -1;
int from = 0, to = n;
while (to - from > 1) {
if (ind == -1) {
ind = ask(from, to);
continue;
}
if (to - from == 2) {
if (ind == from) {
from++;
} else {
to--;
}
continue;
}
if (to - from == 3) {
int a = from, b = from + 1, c = from + 2;
int res = 0;
if (ind == a) {
res = b + c - ask(b, c + 1);
}
if (ind == b) {
int t = ask(a, b + 1);
res = t == b ? a : c;
}
if (ind == c) {
res = a + b - ask(a, b + 1);
}
from = res;
to = res + 1;
continue;
}
int x = 0;
while (f[x + 1] < to - from) {
x++;
}
x = f[x];
if (from + x > ind) {
int t = ask(from, from + x);
if (t == ind) {
to = from + x;
} else {
from = from + x;
ind = -1;
}
} else {
int t = ask(to - x, to);
if (t != ind) {
to = to - x;
ind = -1;
} else {
from = to - x;
}
}
}
println("! " + to);
if (fileIOMode) {
System.out.println((System.nanoTime() - startTime) / 1e9);
}
out.close();
}
private int ask(int a, int b) {
println("? " + (a + 1) + " " + b);
return nextInt() - 1;
}
//-----------------------------------------------------------------------------------
private static boolean fileIOMode;
private static BufferedReader in;
private static PrintWriter out;
private static StringTokenizer tokenizer;
public static void main(String[] args) throws Exception {
fileIOMode = args.length > 0 && args[0].equals("!");
if (fileIOMode) {
in = new BufferedReader(new FileReader("a.in"));
out = new PrintWriter("a.out");
} else {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
}
tokenizer = new StringTokenizer("");
new Thread(new A()).start();
}
private static String nextLine() {
try {
return in.readLine();
} catch (IOException e) {
return null;
}
}
private static String nextToken() {
while (!tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(nextLine());
}
return tokenizer.nextToken();
}
private static int nextInt() {
return Integer.parseInt(nextToken());
}
private static long nextLong() {
return Long.parseLong(nextToken());
}
private static double nextDouble() {
return Double.parseDouble(nextToken());
}
private static BigInteger nextBigInteger() {
return new BigInteger(nextToken());
}
private static void print(Object o) {
if (fileIOMode) {
System.out.print(o);
}
out.print(o);
}
private static void println(Object o) {
if (fileIOMode) {
System.out.println(o);
}
out.println(o);
out.flush();
}
private static void printf(String s, Object... o) {
if (fileIOMode) {
System.out.printf(s, o);
}
out.printf(s, 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"
] |
b3e8fe76706ba17cb285c75459508334
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,600
| null |
standard output
| |
PASSED
|
8bbae4905eddce5383da6202f274c53c
|
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 40 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.math.BigInteger;
import java.util.*;
public class abc {
static int[] arr;
static int firstOcc(int n, int key) {
if (n == arr.length) return -1;
else {
if (arr[n] == key) return n;
int i = firstOcc(n + 1, key);
if (i == -1) return -1;
else
return i;
}
}
static int lastOcc(int n, int key) {
if (n == arr.length) return -1;
int i = lastOcc(n + 1, key);
if (i == -1) {
if (arr[n] == key) {
return n;
} else
return -1;
} else return i;
}
static long fastpower(long a, long n) {
if (n == 0) return 1;
else {
long i = fastpower(a, n / 2);
i *= i;
if ((n & 1) == 1) i *= a;
return i;
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int s=1,e=n;
while(s!=e)
{
int midle=(s+e)/2;
int a,c,b;
System.out.println("? "+s+" "+e+" ");System.out.flush();
a= sc.nextInt();
if(s==e-1)
{
if(s==a)
s++;
else
e--;
}
else if(midle>=a)
{
System.out.println("? "+s+" "+midle+" ");System.out.flush();
b= sc.nextInt();;
if(a==b)
{
e=midle;
}
else
s=midle;
}
else {
System.out.println("? " + midle + " " + e + " ");System.out.flush();
b=sc.nextInt();
if(a!=b)e=midle;
else
s=midle;
}
}
System.out.println("! "+e);
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"
] |
b3e8fe76706ba17cb285c75459508334
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,600
| null |
standard output
| |
PASSED
|
a38f70bfd4d3f852f3701ae8fd7b7907
|
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 40 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"
] |
b3e8fe76706ba17cb285c75459508334
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,600
| null |
standard output
| |
PASSED
|
ae27ae18755b92e3571742917fa6120e
|
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 40 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 A {
static FastScanner fs;
public static void main(String[] args) {
fs=new FastScanner();
// int t = fs.nextInt();
// while (t-->0)
solve();
}
public static void solve() {
int n = fs.nextInt();
int lo = 1;
int hi = n;
System.out.println("? "+lo+" "+hi);
System.out.flush();
int sh = fs.nextInt();
int check = -1;
if (lo!=sh) {
System.out.println("? " + lo + " " + sh);
System.out.flush();
check = fs.nextInt();
}
if (sh!=check) {
lo=sh;
for (hi++; lo < hi; ) {
int mid = lo + (hi - lo) / 2;
if (sh!=mid) {
System.out.println("? " + sh + " " + mid);
System.out.flush();
int ch = fs.nextInt();
if (sh==ch) hi = mid;
else lo = mid + 1;
}
else lo=mid+1;
}
System.out.println("! "+lo);
}
else {
hi=sh;
for (--lo; lo < hi; ) {
int mid = lo+(hi-lo+1)/2;
if (mid!=sh) {
System.out.println("? " + mid + " " + sh);
System.out.flush();
int ch = fs.nextInt();
if (sh == ch) lo = mid;
else hi = mid - 1;
}
else hi=mid-1;
}
System.out.println("! "+lo);
}
}
static class pair {
long v, i;
pair(long a, long b) {
v=a; i=b;
}
}
static void ruffleSort(int[] a) {
int n=a.length;//shuffle, then sort
for (int i=0; i<n; i++) {
int oi=random.nextInt(n), temp=a[oi];
a[oi]=a[i]; a[i]=temp;
}
Arrays.sort(a);
}
static final Random random=new Random();
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 int[] reverse(int[] a) {
int n=a.length;
int[] res=new int[n];
for (int i=0; i<n; i++) res[i]=a[n-1-i];
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"
] |
b3e8fe76706ba17cb285c75459508334
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,600
| null |
standard output
| |
PASSED
|
7e84af4297515a3ee744ff8a03a09563
|
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 40 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.math.BigInteger;
import java.util.*;
public class TaskA {
public static void main(String[] args) {
InputReader in = new InputReader(System.in);
PrintWriter out = new PrintWriter(System.out);
Task solver = new Task();
solver.solve(in, out);
out.close();
}
// main solver
static class Task {
Scanner sc = new Scanner(System.in);
public void solve(InputReader in, PrintWriter out) {
int t = 1;
for (int i = 0; i < t; i++){
solveOne(in, out);
}
}
private int query(int l, int r){
System.out.println("? " + l + " " + r);
System.out.flush();
int pos = sc.nextInt();
return pos;
}
private void solveOne(InputReader in, PrintWriter out) {
int n = sc.nextInt();
int l = 1, r = n;
while (l < r-1){
int mid = (l+r)>>1;
int pos = query(l, r);
if (pos<=mid){
int x = query(l, mid);
if (x==pos){
r = mid;
}
else{
l = mid;
}
}
else{
int x = query(mid, r);
if (x==pos){
l = mid;
}
else{
r = mid;
}
}
}
if (l !=r && query(l,r)==l){
l = r;
}
System.out.println("! " + l);
}
}
static class Point{
public int x,y,z, ID;
public Point(int x, int y, int z, int ID){
this.x = x;
this.y = y;
this.z = z;
this.ID = ID;
}
@Override
public String toString() {
return "[" + x + " " + y + " " + z + " " + ID + "]";
}
}
static class SortByX implements Comparator<Point>{
@Override
public int compare(Point p1, Point p2) {
return Integer.compare(p1.x, p2.x);
}
}
static class SortByY implements Comparator<Point>{
@Override
public int compare(Point p1, Point p2) {
if (p1.y != p2.y) return Integer.compare(p1.y, p2.y);
if (p1.z > p2.z) return -1;
return 1;
}
}
// fast input reader class;
static class InputReader {
BufferedReader br;
StringTokenizer st;
public InputReader(InputStream stream) {
br = new BufferedReader(new InputStreamReader(stream));
}
public String nextToken() {
while (st == null || !st.hasMoreTokens()) {
String line = null;
try {
line = br.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
if (line == null) {
return null;
}
st = new StringTokenizer(line);
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(nextToken());
}
public long nextLong(){
return Long.parseLong(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 8
|
standard input
|
[
"binary search",
"interactive"
] |
b3e8fe76706ba17cb285c75459508334
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,600
| null |
standard output
| |
PASSED
|
4326d2658ea75c942124f340323f3578
|
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 40 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 com.company;
import java.sql.SQLOutput;
import java.util.*;
import java.lang.*;
import java.io.*;
//****Use Integer Wrapper Class for Arrays.sort()****
public class HM3 {
static PrintWriter out=new PrintWriter(new OutputStreamWriter(System.out));
public static void main(String[] Args)throws Exception{
FastReader scan=new FastReader(System.in);
int t=1;
// t=scan.nextInt();
while(t-->0){
int n=scan.nextInt();
int l=1;
int r=n;
while(r-l>1){
query(l,r);
int val=scan.nextInt();
int mid=(l+r)/2;
if(val>=mid){
query(mid,r);
int valmid=scan.nextInt();
if(val==valmid) {
l=mid;
}else{
r=mid-1;
}
}else{
query(l,mid);
int valmid=scan.nextInt();
if(val==valmid) {
r=mid;
}else{
l=mid+1;
}
}
}
if(l==r) {
out.println("! " + l);
}else{
query(l,r);
int val=scan.nextInt();
out.println("! "+(val==l?r:l));
}
}
out.flush();
out.close();
}
static void query(int l,int r){
out.println("? "+l+" "+r);
out.flush();
}
static class FastReader {
byte[] buf = new byte[2048];
int index, total;
InputStream in;
FastReader(InputStream is) {
in = is;
}
int scan() throws IOException {
if (index >= total) {
index = 0;
total = in.read(buf);
if (total <= 0) {
return -1;
}
}
return buf[index++];
}
String next() throws IOException {
int c;
for (c = scan(); c <= 32; c = scan()) ;
StringBuilder sb = new StringBuilder();
for (; c > 32; c = scan()) {
sb.append((char) c);
}
return sb.toString();
}
int nextInt() throws IOException {
int c, val = 0;
for (c = scan(); c <= 32; c = scan()) ;
boolean neg = c == '-';
if (c == '-' || c == '+') {
c = scan();
}
for (; c >= '0' && c <= '9'; c = scan()) {
val = (val << 3) + (val << 1) + (c & 15);
}
return neg ? -val : val;
}
long nextLong() throws IOException {
int c;
long val = 0;
for (c = scan(); c <= 32; c = scan()) ;
boolean neg = c == '-';
if (c == '-' || c == '+') {
c = scan();
}
for (; c >= '0' && c <= '9'; c = scan()) {
val = (val << 3) + (val << 1) + (c & 15);
}
return neg ? -val : val;
}
}
}
|
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"
] |
b3e8fe76706ba17cb285c75459508334
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,600
| null |
standard output
| |
PASSED
|
a50cd0e39d0a811f1c2c376557003568
|
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 40 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"
] |
b3e8fe76706ba17cb285c75459508334
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,600
| null |
standard output
| |
PASSED
|
172cb4a06a9c9027f3966687d6d00b9d
|
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 40 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"
] |
b3e8fe76706ba17cb285c75459508334
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,600
| null |
standard output
| |
PASSED
|
ae722c59bc1c5cb3780e93795d21eb93
|
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 40 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"
] |
b3e8fe76706ba17cb285c75459508334
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,600
| null |
standard output
| |
PASSED
|
8635125a3e4af29dbbcbbed7bba544dc
|
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 40 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 C1486 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int N = in.nextInt();
System.out.println("? 1 " + N);
System.out.flush();
int second = in.nextInt();
int low = -1;
int high = -1;
if (second != 1) {
System.out.println("? 1 " + second);
System.out.flush();
int answer = in.nextInt();
if (answer == second) {
low = 1;
high = second-1;
}
}
if (second != N) {
System.out.println("? " + second + " " + N);
System.out.flush();
int answer = in.nextInt();
if (answer == second) {
low = second+1;
high = N;
}
}
while (low != high) {
int mid = (low + high + ((low < second) ? 1 : 0))/2;
if (mid < second) {
System.out.println("? " + mid + " " + second);
} else {
System.out.println("? " + second + " " + mid);
}
System.out.flush();
int answer = in.nextInt();
if (mid < second) {
if (answer == second) {
low = mid;
} else {
high = mid-1;
}
} else {
if (answer == second) {
high = mid;
} else {
low = mid+1;
}
}
}
System.out.println("! " + low);
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"
] |
b3e8fe76706ba17cb285c75459508334
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,600
| null |
standard output
| |
PASSED
|
e469780127ce6e69507f8096250469ca
|
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 40 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 codeforces1486C1 {
static PrintWriter pw;
public static void main(String[] args) throws Exception {
FastScanner in = new FastScanner();
pw = new PrintWriter(System.out);
int n = in.nextInt();
int low = 1;
int high = n;
while (low<high)
{
if (low+1==high)
{
print(low,high);
int a = in.nextInt();
if (a==low) pw.println("! "+high);
else pw.println("! "+low);
break;
}
print(low,high);
int a = in.nextInt();
int mid = (low+high)/2;
if (a>=mid)
{
print(mid,high);
int next = in.nextInt();
if (next==a) low = mid;
else high = mid;
}
else
{
print(low,mid);
int next = in.nextInt();
if (next==a) high = mid;
else low = mid;
}
}
//pw.println("! "+low);
pw.close();
}
static void print (int a, int b)
{
pw.println("? "+a+" "+b);
pw.flush();
}
private static class FastScanner {
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
private FastScanner() throws IOException {
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
private short nextShort() throws IOException {
short ret = 0;
byte c = read();
while (c <= ' ') c = read();
boolean neg = (c == '-');
if (neg) c = read();
do ret = (short) (ret * 10 + c - '0');
while ((c = read()) >= '0' && c <= '9');
if (neg) return (short) -ret;
return ret;
}
private int nextInt() throws IOException {
int ret = 0;
byte c = read();
while (c <= ' ') c = read();
boolean neg = (c == '-');
if (neg) c = read();
do ret = ret * 10 + c - '0';
while ((c = read()) >= '0' && c <= '9');
if (neg) return -ret;
return ret;
}
public long nextLong() throws IOException {
long ret = 0;
byte c = read();
while (c <= ' ') c = read();
boolean neg = (c == '-');
if (neg) c = read();
do ret = ret * 10 + c - '0';
while ((c = read()) >= '0' && c <= '9');
if (neg) return -ret;
return ret;
}
private char nextChar() throws IOException {
byte c = read();
while (c <= ' ') c = read();
return (char) c;
}
private String nextString() throws IOException {
StringBuilder ret = new StringBuilder();
byte c = read();
while (c <= ' ') c = read();
do {
ret.append((char) c);
} while ((c = read()) > ' ');
return ret.toString();
}
private void fillBuffer() throws IOException {
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1) buffer[0] = -1;
}
private byte read() throws IOException {
if (bufferPointer == bytesRead) fillBuffer();
return buffer[bufferPointer++];
}
}
}
|
Java
|
["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"
] |
b3e8fe76706ba17cb285c75459508334
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,600
| null |
standard output
| |
PASSED
|
8549e7f2daaa8aaf019e31318d589d42
|
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 40 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"
] |
b3e8fe76706ba17cb285c75459508334
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,600
| null |
standard output
| |
PASSED
|
16c278e165609a4270663ee4c44e5e4a
|
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 40 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.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.TreeMap;
/* This is not mine code ...I used this code for testing */
public class Main implements Runnable {
int n, m;
static boolean use_n_tests = false;
int N = -1;
long mod = 1000000007;
void solve(FastScanner in, PrintWriter out, int testNumber) {
n = in.nextInt();
out.println("! " + rec(0, n, -1));
}
int rec(int l, int r, int p) {
if (r - l <= 1) {
return r;
}
int bigPos = p;
if (p == -1) {
bigPos = ask(l, r - 1);
}
int mid = (l + r) / 2;
if (bigPos < mid) {
int left = ask(l, mid - 1);
if (left == bigPos) {
return rec(l, mid, left);
} else {
return rec(mid, r, -1);
}
} else {
int right = ask(mid, r - 1);
if (right == bigPos) {
return rec(mid, r, right);
} else {
return rec(l, mid, -1);
}
}
}
// ****************************** template code ***********
int ask(int l, int r) {
if (l >= r) {
return -1;
}
System.out.printf("? %d %d\n", l + 1, r + 1);
System.out.flush();
return in.nextInt() - 1;
}
static int stack_size = 1 << 27;
class Mod {
long mod;
Mod(long mod) {
this.mod = mod;
}
long add(long a, long b) {
a = mod(a);
b = mod(b);
return (a + b) % mod;
}
long sub(long a, long b) {
a = mod(a);
b = mod(b);
return (a - b + mod) % mod;
}
long mul(long a, long b) {
a = mod(a);
b = mod(b);
return a * b % mod;
}
long div(long a, long b) {
a = mod(a);
b = mod(b);
return (a * inv(b)) % mod;
}
public long inv(long r) {
if (r == 1)
return 1;
return ((mod - mod / r) * inv(mod % r)) % mod;
}
private long mod(long a) {
return a % mod;
}
}
class Coeff {
long mod;
long[][] C;
long[] fact;
boolean cycleWay = false;
Coeff(int n, long mod) {
this.mod = mod;
fact = new long[n + 1];
fact[0] = 1;
for (int i = 1; i <= n; i++) {
fact[i] = i;
fact[i] %= mod;
fact[i] *= fact[i - 1];
fact[i] %= mod;
}
}
Coeff(int n, int m, long mod) {
// n > m
cycleWay = true;
this.mod = mod;
C = new long[n + 1][m + 1];
for (int i = 0; i <= n; i++) {
for (int j = 0; j <= Math.min(i, m); j++) {
if (j == 0 || j == i) {
C[i][j] = 1;
} else {
C[i][j] = C[i - 1][j - 1] + C[i - 1][j];
C[i][j] %= mod;
}
}
}
}
public long C(int n, int m) {
if (cycleWay) {
return C[n][m];
}
return fC(n, m);
}
private long fC(int n, int m) {
return (fact[n] * inv(fact[n - m] * fact[m] % mod)) % mod;
}
private long inv(long r) {
if (r == 1)
return 1;
return ((mod - mod / r) * inv(mod % r)) % mod;
}
}
class Pair {
int first;
int second;
public int getFirst() {
return first;
}
public int getSecond() {
return second;
}
}
class MultisetTree<T> {
int size = 0;
TreeMap<T, Integer> mp = new TreeMap<>();
void add(T x) {
mp.merge(x, 1, Integer::sum);
size++;
}
void remove(T x) {
if (mp.containsKey(x)) {
mp.merge(x, -1, Integer::sum);
if (mp.get(x) == 0) {
mp.remove(x);
}
size--;
}
}
boolean contains(T x) {
return mp.containsKey(x);
}
T greatest() {
return mp.lastKey();
}
T smallest() {
return mp.firstKey();
}
int size() {
return size;
}
int diffSize() {
return mp.size();
}
}
class Multiset<T> {
int size = 0;
Map<T, Integer> mp = new HashMap<>();
void add(T x) {
mp.merge(x, 1, Integer::sum);
size++;
}
boolean contains(T x) {
return mp.containsKey(x);
}
void remove(T x) {
if (mp.containsKey(x)) {
mp.merge(x, -1, Integer::sum);
if (mp.get(x) == 0) {
mp.remove(x);
}
size--;
}
}
int size() {
return size;
}
int diffSize() {
return mp.size();
}
}
static class Range {
int l, r;
int id;
public int getL() {
return l;
}
public int getR() {
return r;
}
public Range(int l, int r, int id) {
this.l = l;
this.r = r;
this.id = id;
}
}
static class Array {
static Range[] readRanges(int n, FastScanner in) {
Range[] result = new Range[n];
for (int i = 0; i < n; i++) {
result[i] = new Range(in.nextInt(), in.nextInt(), i);
}
return result;
}
static List<List<Integer>> intInit2D(int n) {
List<List<Integer>> res = new ArrayList<>();
for (int i = 0; i < n; i++) {
res.add(new ArrayList<>());
}
return res;
}
static boolean isSorted(Integer[] a) {
for (int i = 0; i < a.length - 1; i++) {
if (a[i] > a[i + 1]) {
return false;
}
}
return true;
}
static public long sum(int[] a) {
long sum = 0;
for (int x : a) {
sum += x;
}
return sum;
}
static public long sum(long[] a) {
long sum = 0;
for (long x : a) {
sum += x;
}
return sum;
}
static public long sum(Integer[] a) {
long sum = 0;
for (int x : a) {
sum += x;
}
return sum;
}
static public int min(Integer[] a) {
int mn = Integer.MAX_VALUE;
for (int x : a) {
mn = Math.min(mn, x);
}
return mn;
}
static public int min(int[] a) {
int mn = Integer.MAX_VALUE;
for (int x : a) {
mn = Math.min(mn, x);
}
return mn;
}
static public int max(Integer[] a) {
int mx = Integer.MIN_VALUE;
for (int x : a) {
mx = Math.max(mx, x);
}
return mx;
}
static public int max(int[] a) {
int mx = Integer.MIN_VALUE;
for (int x : a) {
mx = Math.max(mx, x);
}
return mx;
}
static public int[] readint(int n, FastScanner in) {
int[] out = new int[n];
for (int i = 0; i < out.length; i++) {
out[i] = in.nextInt();
}
return out;
}
}
class Graph {
List<List<Integer>> graph;
Graph(int n) {
create(n);
}
void create(int n) {
List<List<Integer>> graph = new ArrayList<>();
for (int i = 0; i < n; i++) {
graph.add(new ArrayList<>());
}
this.graph = graph;
}
void readBi(int m, FastScanner in) {
for (int i = 0; i < m; i++) {
int v = in.nextInt() - 1;
int u = in.nextInt() - 1;
graph.get(v).add(u);
graph.get(u).add(v);
}
}
}
class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(InputStream io) {
br = new BufferedReader(new InputStreamReader(io));
}
public String line() {
String result = "";
try {
result = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
public String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public int[] nextArray(int n) {
int[] res = new int[n];
for (int i = 0; i < n; i++) {
res[i] = in.nextInt();
}
return res;
}
public long[] nextArrayL(int n) {
long[] res = new long[n];
for (int i = 0; i < n; i++) {
res[i] = in.nextLong();
}
return res;
}
public Long[] nextArrayL2(int n) {
Long[] res = new Long[n];
for (int i = 0; i < n; i++) {
res[i] = in.nextLong();
}
return res;
}
public Integer[] nextArray2(int n) {
Integer[] res = new Integer[n];
for (int i = 0; i < n; i++) {
res[i] = in.nextInt();
}
return res;
}
public long nextLong() {
return Long.parseLong(next());
}
}
void run_t_tests() {
int t = in.nextInt();
int i = 0;
while (t-- > 0) {
solve(in, out, i++);
}
}
void run_one() {
solve(in, out, -1);
}
@Override
public void run() {
in = new FastScanner(System.in);
out = new PrintWriter(System.out);
if (use_n_tests) {
run_t_tests();
} else {
run_one();
}
out.close();
}
static FastScanner in;
static PrintWriter out;
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(null, new Main(), "", stack_size);
thread.start();
thread.join();
}
}
|
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"
] |
b3e8fe76706ba17cb285c75459508334
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,600
| null |
standard output
| |
PASSED
|
de8739a06f45ea132b78db2117954f64
|
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 40 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.text.*;
import java.util.*;
import java.util.function.*;
/**
* Provide prove of correctness before implementation. Implementation can cost a lot of time.
* Anti test that prove that it's wrong.
* <p>
* Do not confuse i j k g indexes, upTo and length. Do extra methods!!! Write more informative names to simulation
* <p>
* Will program ever exceed limit?
* Try all approaches with prove of correctness if task is not obvious.
* If you are given formula/rule: Try to play with it.
* Analytic solution/Hardcoded solution/Constructive/Greedy/DP/Math/Brute force/Symmetric data
* Number theory
* Game theory (optimal play) that consider local and global strategy.
* Start writing the hardest code first
*/
public class Stage001_050_CF1486_C1_C2 {
final boolean ONLINE_JUDGE = java.lang.System.getProperty("ONLINE_JUDGE") != null;
final boolean ANTI_TEST_FINDER_MODE = false;
final Random r = new Random(42);
Interactor interactor = ONLINE_JUDGE ? new CFInteractor() : new MockInteractor();
//log2 (10^5) + 1
private int solveOne(int testCase, int n) {
interactor.setUp(n);
//[..........second.........first...........]
int secondIndex = interactor.getSecondMaximum(1, n);
int len = upperBound(0, n, delta -> {
int l = Math.max(1, secondIndex - delta);
int r = Math.min(secondIndex + delta, n);
return secondIndex != interactor.getSecondMaximum(l, r);
}
);
//[ 3 2 1 secondInd 1 2 3 n - 1]
// ^ ^
int l = Math.max(1, secondIndex - len) - 1;
int r = Math.min(secondIndex + len, n) + 1;
if (1 <= l) {
if(interactor.getSecondMaximum(l, secondIndex) == secondIndex){
interactor.printMaximumIndex(l);
} else {
interactor.printMaximumIndex(r);
}
}
else if(r <= n) {
if(interactor.getSecondMaximum(secondIndex, r) == secondIndex){
interactor.printMaximumIndex(r);
} else interactor.printMaximumIndex(l);
}// else {
// throw new RuntimeException("wtf");
// }
return 0;
}
interface Interactor {
void setUp(int n);
void printMaximumIndex(int i);
int getSecondMaximum(int l, int r);
}
class CFInteractor implements Interactor {
public void setUp(int n) {
}
public void printMaximumIndex(int i) {
System.out.printf("! %d\n", i);
System.out.flush();
}
public int getSecondMaximum(int l, int r) {
System.out.printf("? %d %d\n", l, r);
System.out.flush();
return nextInt();
}
}
class MockInteractor implements Interactor {
int[] a;
int n;
int maxInd;
int tries;
//Random r = new Random();
public void setUp(int n) {
tries = 0;
a = new int[n + 1];
this.n = n;
// for (int i = 1; i <= n; i++) {
// a[i] = nextInt();
// }
for (int i = 1; i <= n; i++) {
a[i] = i;
}
for (int i = 1; i <= n; i++) {
int j = 1 + r.nextInt(n);
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
int max = Integer.MIN_VALUE;
for (int i = 1; i <= n; i++) {
if (a[i] > max) {
max = a[i];
maxInd = i;
}
}
System.out.println(Arrays.toString(a));
//maxInd = getSecondMaximum(1, n);
}
public void printMaximumIndex(int i) {
if (i != maxInd) {
throw new RuntimeException();
} else {
System.out.printf("OK %d\n", i);
}
}
public int getSecondMaximum(int l, int r) {
if(tries + 1 > 20) {
throw new RuntimeException("LIMIT");
}
tries++;
int max = Integer.MIN_VALUE;
//int lMaxInd = -1;
for (int i = l; i <= r; i++) {
if (a[i] > max) {
max = a[i];
// lMaxInd = i;
}
}
int max_ = Integer.MIN_VALUE;
int lMaxInd_ = -1;
for (int i = l; i <= r; i++) {
if (a[i] > max_ && a[i] != max) {
max_ = a[i];
lMaxInd_ = i;
}
}
return lMaxInd_;
}
}
private int upperBound(int inclusiveLeft, int exclusiveRight, Predicate<Integer> predicate) {
while (exclusiveRight - inclusiveLeft > 1) {
int middle = inclusiveLeft + (exclusiveRight - inclusiveLeft) / 2;
if (predicate.test(middle)) {
inclusiveLeft = middle;
} else {
exclusiveRight = middle;
}
}
return inclusiveLeft;
}
private int lowerBound(int exclusiveLeft, int inclusiveRight, Predicate<Integer> predicate) {
while (inclusiveRight - exclusiveLeft > 1) {
int middle = exclusiveLeft + (inclusiveRight - exclusiveLeft) / 2;
if (predicate.test(middle)) {
inclusiveRight = middle;
} else {
exclusiveLeft = middle;
}
}
return inclusiveRight;
}
private int solveOneNaive(int testCase) {
return 0;
}
private void solve() {
if (ANTI_TEST_FINDER_MODE) {
int t = 100_000;
for (int testCase = 0; testCase < t; testCase++) {
// int expected = solveOneNaive(testCase);
int actual = solveOne(testCase, 10);
// if (expected != actual) {
// throw new AssertionRuntimeException(
// this.getClass().getSimpleName(),
// testCase,
// expected,
// actual);
// }
}
} else {
int t = 1;//nextInt();
for (int testCase = 0; testCase < t; testCase++) {
int n = nextInt();
solveOne(testCase, n);
}
}
}
class AssertionRuntimeException extends RuntimeException {
AssertionRuntimeException(String testName,
int testCase,
Object expected,
Object actual, Object... input) {
super("Testcase: " + testCase + "\n expected = " + expected + ",\n actual = " + actual + ",\n " + Arrays.deepToString(input));
}
}
private void assertThat(boolean b) {
if (!b) throw new RuntimeException();
}
private void assertThat(boolean b, String s) {
if (!b) throw new RuntimeException(s);
}
private int assertThatInt(long a) {
assertThat(Integer.MIN_VALUE <= a && a <= Integer.MAX_VALUE,
"Integer overflow long = [" + a + "]" + " int = [" + (int) a + "]");
return (int) a;
}
void _______debug(String str, Object... os) {
if (!ONLINE_JUDGE) {
System.out.println(MessageFormat.format(str, os));
System.out.flush();
}
}
void _______debug(Object o) {
if (!ONLINE_JUDGE) {
_______debug("{0}", String.valueOf(o));
}
}
private int nextInt() {
return System.in.readInt();
}
private long nextLong() {
return System.in.readLong();
}
private String nextString() {
return System.in.readString();
}
private int[] nextIntArr(int n) {
return System.in.readIntArray(n);
}
private long[] nextLongArr(int n) {
return System.in.readLongArray(n);
}
public static void main(String[] args) {
new Stage001_050_CF1486_C1_C2().run();
}
static class System {
private static FastInputStream in;
private static FastPrintStream out;
}
private void run() {
// final long startTime = java.lang.System.currentTimeMillis();
final boolean USE_IO = ONLINE_JUDGE;
if (USE_IO) {
System.in = new FastInputStream(java.lang.System.in);
System.out = new FastPrintStream(java.lang.System.out);
solve();
System.out.flush();
} else {
final String nameIn = "input.txt";
final String nameOut = "output.txt";
try {
System.in = new FastInputStream(new FileInputStream(nameIn));
System.out = new FastPrintStream(new PrintStream(nameOut));
solve();
System.out.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
// final long endTime = java.lang.System.currentTimeMillis();
// _______debug("Execution time: {0}", endTime - startTime);
}
private static class FastPrintStream {
private static final int BUF_SIZE = 8192;
private final byte[] buf = new byte[BUF_SIZE];
private final OutputStream out;
private int ptr = 0;
private FastPrintStream() {
this(java.lang.System.out);
}
public FastPrintStream(OutputStream os) {
this.out = os;
}
public FastPrintStream(String path) {
try {
this.out = new FileOutputStream(path);
} catch (FileNotFoundException e) {
throw new RuntimeException("FastWriter");
}
}
public FastPrintStream print(byte b) {
buf[ptr++] = b;
if (ptr == BUF_SIZE) innerFlush();
return this;
}
public FastPrintStream print(char c) {
return print((byte) c);
}
public FastPrintStream print(char[] s) {
for (char c : s) {
buf[ptr++] = (byte) c;
if (ptr == BUF_SIZE) innerFlush();
}
return this;
}
public FastPrintStream print(String s) {
s.chars().forEach(c -> {
buf[ptr++] = (byte) c;
if (ptr == BUF_SIZE) innerFlush();
});
return this;
}
//can be optimized
public FastPrintStream print0(char[] s) {
if (ptr + s.length < BUF_SIZE) {
for (char c : s) {
buf[ptr++] = (byte) c;
}
} else {
for (char c : s) {
buf[ptr++] = (byte) c;
if (ptr == BUF_SIZE) innerFlush();
}
}
return this;
}
//can be optimized
public FastPrintStream print0(String s) {
if (ptr + s.length() < BUF_SIZE) {
for (int i = 0; i < s.length(); i++) {
buf[ptr++] = (byte) s.charAt(i);
}
} else {
for (int i = 0; i < s.length(); i++) {
buf[ptr++] = (byte) s.charAt(i);
if (ptr == BUF_SIZE) innerFlush();
}
}
return this;
}
private static int countDigits(int l) {
if (l >= 1000000000) return 10;
if (l >= 100000000) return 9;
if (l >= 10000000) return 8;
if (l >= 1000000) return 7;
if (l >= 100000) return 6;
if (l >= 10000) return 5;
if (l >= 1000) return 4;
if (l >= 100) return 3;
if (l >= 10) return 2;
return 1;
}
public FastPrintStream print(int x) {
if (x == Integer.MIN_VALUE) {
return print((long) x);
}
if (ptr + 12 >= BUF_SIZE) innerFlush();
if (x < 0) {
print((byte) '-');
x = -x;
}
int d = countDigits(x);
for (int i = ptr + d - 1; i >= ptr; i--) {
buf[i] = (byte) ('0' + x % 10);
x /= 10;
}
ptr += d;
return this;
}
private static int countDigits(long l) {
if (l >= 1000000000000000000L) return 19;
if (l >= 100000000000000000L) return 18;
if (l >= 10000000000000000L) return 17;
if (l >= 1000000000000000L) return 16;
if (l >= 100000000000000L) return 15;
if (l >= 10000000000000L) return 14;
if (l >= 1000000000000L) return 13;
if (l >= 100000000000L) return 12;
if (l >= 10000000000L) return 11;
if (l >= 1000000000L) return 10;
if (l >= 100000000L) return 9;
if (l >= 10000000L) return 8;
if (l >= 1000000L) return 7;
if (l >= 100000L) return 6;
if (l >= 10000L) return 5;
if (l >= 1000L) return 4;
if (l >= 100L) return 3;
if (l >= 10L) return 2;
return 1;
}
public FastPrintStream print(long x) {
if (x == Long.MIN_VALUE) {
return print("" + x);
}
if (ptr + 21 >= BUF_SIZE) innerFlush();
if (x < 0) {
print((byte) '-');
x = -x;
}
int d = countDigits(x);
for (int i = ptr + d - 1; i >= ptr; i--) {
buf[i] = (byte) ('0' + x % 10);
x /= 10;
}
ptr += d;
return this;
}
public FastPrintStream print(double x, int precision) {
if (x < 0) {
print('-');
x = -x;
}
x += Math.pow(10, -precision) / 2;
print((long) x).print(".");
x -= (long) x;
for (int i = 0; i < precision; i++) {
x *= 10;
print((char) ('0' + (int) x));
x -= (int) x;
}
return this;
}
public FastPrintStream println(char c) {
return print(c).println();
}
public FastPrintStream println(int x) {
return print(x).println();
}
public FastPrintStream println(long x) {
return print(x).println();
}
public FastPrintStream println(String x) {
return print(x).println();
}
public FastPrintStream println(Object x) {
return print(x.toString()).println();
}
public FastPrintStream println(double x, int precision) {
return print(x, precision).println();
}
public FastPrintStream println() {
return print((byte) '\n');
}
public FastPrintStream printf(String format, Object... args) {
return print(String.format(format, args));
}
private void innerFlush() {
try {
out.write(buf, 0, ptr);
ptr = 0;
} catch (IOException e) {
throw new RuntimeException("innerFlush");
}
}
public void flush() {
innerFlush();
try {
out.flush();
} catch (IOException e) {
throw new RuntimeException("flush");
}
}
}
private static class FastInputStream {
private boolean finished = false;
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public FastInputStream(InputStream stream) {
this.stream = stream;
}
public double[] readDoubleArray(int size) {
double[] array = new double[size];
for (int i = 0; i < size; i++) {
array[i] = readDouble();
}
return array;
}
public String[] readStringArray(int size) {
String[] array = new String[size];
for (int i = 0; i < size; i++) {
array[i] = readString();
}
return array;
}
public char[] readCharArray(int size) {
char[] array = new char[size];
for (int i = 0; i < size; i++) {
array[i] = readCharacter();
}
return array;
}
public String readText() {
StringBuilder result = new StringBuilder();
while (true) {
int character = read();
if (character == '\r') {
continue;
}
if (character == -1) {
break;
}
result.append((char) character);
}
return result.toString();
}
public long[] readLongArray(int size) {
long[] array = new long[size];
for (int i = 0; i < size; i++) {
array[i] = readLong();
}
return array;
}
public int[] readIntArray(int size) {
int[] array = new int[size];
for (int i = 0; i < size; i++) {
array[i] = readInt();
}
return array;
}
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 peek() {
if (numChars == -1) {
return -1;
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
return -1;
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar];
}
public int peekNonWhitespace() {
while (isWhitespace(peek())) {
read();
}
return peek();
}
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 long readLong() {
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 String readString() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
if (Character.isValidCodePoint(c)) {
res.appendCodePoint(c);
}
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public char[] readStringAsCharArray() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
if (Character.isValidCodePoint(c)) {
res.appendCodePoint(c);
}
c = read();
} while (!isSpaceChar(c));
char[] resArr = new char[res.length()];
res.getChars(0, res.length(), resArr, 0);
return resArr;
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private String readLine0() {
StringBuilder buf = new StringBuilder();
int c = read();
while (c != '\n' && c != -1) {
if (c != '\r') {
buf.appendCodePoint(c);
}
c = read();
}
return buf.toString();
}
public String readLine() {
String s = readLine0();
while (s.trim().length() == 0) {
s = readLine0();
}
return s;
}
public String readLine(boolean ignoreEmptyLines) {
if (ignoreEmptyLines) {
return readLine();
} else {
return readLine0();
}
}
public char readCharacter() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
return (char) c;
}
public double readDouble() {
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, readInt());
}
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, readInt());
}
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public boolean isExhausted() {
int value;
while (isSpaceChar(value = peek()) && value != -1) {
read();
}
return value == -1;
}
public String next() {
return readString();
}
public SpaceCharFilter getFilter() {
return filter;
}
public void setFilter(SpaceCharFilter filter) {
this.filter = filter;
}
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 17
|
standard input
|
[
"binary search",
"interactive"
] |
b3e8fe76706ba17cb285c75459508334
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,600
| null |
standard output
| |
PASSED
|
b7beaaabb9e1e0a0f0f1d6e2b6184797
|
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 40 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.text.*;
import java.util.*;
import java.util.function.*;
/**
* Provide prove of correctness before implementation. Implementation can cost a lot of time.
* Anti test that prove that it's wrong.
* <p>
* Do not confuse i j k g indexes, upTo and length. Do extra methods!!! Write more informative names to simulation
* <p>
* Will program ever exceed limit?
* Try all approaches with prove of correctness if task is not obvious.
* If you are given formula/rule: Try to play with it.
* Analytic solution/Hardcoded solution/Constructive/Greedy/DP/Math/Brute force/Symmetric data
* Number theory
* Game theory (optimal play) that consider local and global strategy.
* Start writing the hardest code first
*/
public class Stage001_050_CF1486_C1_C2 {
final boolean ONLINE_JUDGE = java.lang.System.getProperty("ONLINE_JUDGE") != null;
final boolean ANTI_TEST_FINDER_MODE = false;
//final Random random = new Random(42);
Interactor interactor = ONLINE_JUDGE ? new CFInteractor() : new MockInteractor();
private int solveOne(int testCase) {
int n = nextInt();
interactor.setUp(n);
//[..........second.........first...........]
int secondIndex = interactor.getSecondMaximum(1, n);
int r = lowerBound(1, n + 1, (Integer ind) -> secondIndex == interactor.getSecondMaximum(1, ind));
int l = upperBound(0, n, (Integer ind) -> secondIndex == interactor.getSecondMaximum(ind, n));
interactor.printMaximumIndex(r == secondIndex ? l : r);
return 0;
}
interface Interactor {
void setUp(int n);
void printMaximumIndex(int i);
int getSecondMaximum(int l, int r);
}
class CFInteractor implements Interactor {
public void setUp(int n) {
}
public void printMaximumIndex(int i) {
System.out.printf("! %d\n", i);
System.out.flush();
}
public int getSecondMaximum(int l, int r) {
System.out.printf("? %d %d\n", l, r);
System.out.flush();
return nextInt();
}
}
class MockInteractor implements Interactor {
int[] a;
int n;
int maxInd;
Random r = new Random();
public void setUp(int n) {
a = new int[n + 1];
this.n = n;
for (int i = 1; i <= n; i++) {
a[i] = nextInt();
}
for (int i = 1; i <= n; i++) {
a[i] = i;
}
for (int i = 1; i <= n; i++) {
int j = 1 + r.nextInt(n);
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
int max = Integer.MIN_VALUE;
for (int i = 1; i <= n; i++) {
if (a[i] > max) {
max = a[i];
maxInd = i;
}
}
maxInd = getSecondMaximum(1, n);
}
public void printMaximumIndex(int i) {
if(i != maxInd) {
throw new RuntimeException();
} else {
System.out.printf("OK %d\n", i);
}
}
public int getSecondMaximum(int l, int r) {
int max = Integer.MIN_VALUE;
//int lMaxInd = -1;
for (int i = l; i <= r; i++) {
if (a[i] > max) {
max = a[i];
// lMaxInd = i;
}
}
int max_ = Integer.MIN_VALUE;
int lMaxInd_ = -1;
for (int i = l; i <= r; i++) {
if (a[i] > max_ && a[i] != max) {
max_ = a[i];
lMaxInd_ = i;
}
}
return lMaxInd_;
}
}
private int upperBound(int inclusiveLeft, int exclusiveRight, Predicate<Integer> predicate) {
while (exclusiveRight - inclusiveLeft > 1) {
int middle = inclusiveLeft + (exclusiveRight - inclusiveLeft) / 2;
if (predicate.test(middle)) {
inclusiveLeft = middle;
} else {
exclusiveRight = middle;
}
}
return inclusiveLeft;
}
private int lowerBound(int exclusiveLeft, int inclusiveRight, Predicate<Integer> predicate) {
while (inclusiveRight - exclusiveLeft > 1) {
int middle = exclusiveLeft + (inclusiveRight - exclusiveLeft) / 2;
if (predicate.test(middle)) {
inclusiveRight = middle;
} else {
exclusiveLeft = middle;
}
}
return inclusiveRight;
}
private int solveOneNaive(int testCase) {
return 0;
}
private void solve() {
if (ANTI_TEST_FINDER_MODE) {
int t = 100_000;
for (int testCase = 0; testCase < t; testCase++) {
int expected = solveOneNaive(testCase);
int actual = solveOne(testCase);
if (expected != actual) {
throw new AssertionRuntimeException(
this.getClass().getSimpleName(),
testCase,
expected,
actual);
}
}
} else {
int t = 1;//nextInt();
for (int testCase = 0; testCase < t; testCase++) {
solveOne(testCase);
}
}
}
class AssertionRuntimeException extends RuntimeException {
AssertionRuntimeException(String testName,
int testCase,
Object expected,
Object actual, Object... input) {
super("Testcase: " + testCase + "\n expected = " + expected + ",\n actual = " + actual + ",\n " + Arrays.deepToString(input));
}
}
private void assertThat(boolean b) {
if (!b) throw new RuntimeException();
}
private void assertThat(boolean b, String s) {
if (!b) throw new RuntimeException(s);
}
private int assertThatInt(long a) {
assertThat(Integer.MIN_VALUE <= a && a <= Integer.MAX_VALUE,
"Integer overflow long = [" + a + "]" + " int = [" + (int) a + "]");
return (int) a;
}
void _______debug(String str, Object... os) {
if (!ONLINE_JUDGE) {
System.out.println(MessageFormat.format(str, os));
System.out.flush();
}
}
void _______debug(Object o) {
if (!ONLINE_JUDGE) {
_______debug("{0}", String.valueOf(o));
}
}
private int nextInt() {
return System.in.readInt();
}
private long nextLong() {
return System.in.readLong();
}
private String nextString() {
return System.in.readString();
}
private int[] nextIntArr(int n) {
return System.in.readIntArray(n);
}
private long[] nextLongArr(int n) {
return System.in.readLongArray(n);
}
public static void main(String[] args) {
new Stage001_050_CF1486_C1_C2().run();
}
static class System {
private static FastInputStream in;
private static FastPrintStream out;
}
private void run() {
// final long startTime = java.lang.System.currentTimeMillis();
final boolean USE_IO = ONLINE_JUDGE;
if (USE_IO) {
System.in = new FastInputStream(java.lang.System.in);
System.out = new FastPrintStream(java.lang.System.out);
solve();
System.out.flush();
} else {
final String nameIn = "input.txt";
final String nameOut = "output.txt";
try {
System.in = new FastInputStream(new FileInputStream(nameIn));
System.out = new FastPrintStream(new PrintStream(nameOut));
solve();
System.out.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
// final long endTime = java.lang.System.currentTimeMillis();
// _______debug("Execution time: {0}", endTime - startTime);
}
private static class FastPrintStream {
private static final int BUF_SIZE = 8192;
private final byte[] buf = new byte[BUF_SIZE];
private final OutputStream out;
private int ptr = 0;
private FastPrintStream() {
this(java.lang.System.out);
}
public FastPrintStream(OutputStream os) {
this.out = os;
}
public FastPrintStream(String path) {
try {
this.out = new FileOutputStream(path);
} catch (FileNotFoundException e) {
throw new RuntimeException("FastWriter");
}
}
public FastPrintStream print(byte b) {
buf[ptr++] = b;
if (ptr == BUF_SIZE) innerFlush();
return this;
}
public FastPrintStream print(char c) {
return print((byte) c);
}
public FastPrintStream print(char[] s) {
for (char c : s) {
buf[ptr++] = (byte) c;
if (ptr == BUF_SIZE) innerFlush();
}
return this;
}
public FastPrintStream print(String s) {
s.chars().forEach(c -> {
buf[ptr++] = (byte) c;
if (ptr == BUF_SIZE) innerFlush();
});
return this;
}
//can be optimized
public FastPrintStream print0(char[] s) {
if (ptr + s.length < BUF_SIZE) {
for (char c : s) {
buf[ptr++] = (byte) c;
}
} else {
for (char c : s) {
buf[ptr++] = (byte) c;
if (ptr == BUF_SIZE) innerFlush();
}
}
return this;
}
//can be optimized
public FastPrintStream print0(String s) {
if (ptr + s.length() < BUF_SIZE) {
for (int i = 0; i < s.length(); i++) {
buf[ptr++] = (byte) s.charAt(i);
}
} else {
for (int i = 0; i < s.length(); i++) {
buf[ptr++] = (byte) s.charAt(i);
if (ptr == BUF_SIZE) innerFlush();
}
}
return this;
}
private static int countDigits(int l) {
if (l >= 1000000000) return 10;
if (l >= 100000000) return 9;
if (l >= 10000000) return 8;
if (l >= 1000000) return 7;
if (l >= 100000) return 6;
if (l >= 10000) return 5;
if (l >= 1000) return 4;
if (l >= 100) return 3;
if (l >= 10) return 2;
return 1;
}
public FastPrintStream print(int x) {
if (x == Integer.MIN_VALUE) {
return print((long) x);
}
if (ptr + 12 >= BUF_SIZE) innerFlush();
if (x < 0) {
print((byte) '-');
x = -x;
}
int d = countDigits(x);
for (int i = ptr + d - 1; i >= ptr; i--) {
buf[i] = (byte) ('0' + x % 10);
x /= 10;
}
ptr += d;
return this;
}
private static int countDigits(long l) {
if (l >= 1000000000000000000L) return 19;
if (l >= 100000000000000000L) return 18;
if (l >= 10000000000000000L) return 17;
if (l >= 1000000000000000L) return 16;
if (l >= 100000000000000L) return 15;
if (l >= 10000000000000L) return 14;
if (l >= 1000000000000L) return 13;
if (l >= 100000000000L) return 12;
if (l >= 10000000000L) return 11;
if (l >= 1000000000L) return 10;
if (l >= 100000000L) return 9;
if (l >= 10000000L) return 8;
if (l >= 1000000L) return 7;
if (l >= 100000L) return 6;
if (l >= 10000L) return 5;
if (l >= 1000L) return 4;
if (l >= 100L) return 3;
if (l >= 10L) return 2;
return 1;
}
public FastPrintStream print(long x) {
if (x == Long.MIN_VALUE) {
return print("" + x);
}
if (ptr + 21 >= BUF_SIZE) innerFlush();
if (x < 0) {
print((byte) '-');
x = -x;
}
int d = countDigits(x);
for (int i = ptr + d - 1; i >= ptr; i--) {
buf[i] = (byte) ('0' + x % 10);
x /= 10;
}
ptr += d;
return this;
}
public FastPrintStream print(double x, int precision) {
if (x < 0) {
print('-');
x = -x;
}
x += Math.pow(10, -precision) / 2;
print((long) x).print(".");
x -= (long) x;
for (int i = 0; i < precision; i++) {
x *= 10;
print((char) ('0' + (int) x));
x -= (int) x;
}
return this;
}
public FastPrintStream println(char c) {
return print(c).println();
}
public FastPrintStream println(int x) {
return print(x).println();
}
public FastPrintStream println(long x) {
return print(x).println();
}
public FastPrintStream println(String x) {
return print(x).println();
}
public FastPrintStream println(Object x) {
return print(x.toString()).println();
}
public FastPrintStream println(double x, int precision) {
return print(x, precision).println();
}
public FastPrintStream println() {
return print((byte) '\n');
}
public FastPrintStream printf(String format, Object... args) {
return print(String.format(format, args));
}
private void innerFlush() {
try {
out.write(buf, 0, ptr);
ptr = 0;
} catch (IOException e) {
throw new RuntimeException("innerFlush");
}
}
public void flush() {
innerFlush();
try {
out.flush();
} catch (IOException e) {
throw new RuntimeException("flush");
}
}
}
private static class FastInputStream {
private boolean finished = false;
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public FastInputStream(InputStream stream) {
this.stream = stream;
}
public double[] readDoubleArray(int size) {
double[] array = new double[size];
for (int i = 0; i < size; i++) {
array[i] = readDouble();
}
return array;
}
public String[] readStringArray(int size) {
String[] array = new String[size];
for (int i = 0; i < size; i++) {
array[i] = readString();
}
return array;
}
public char[] readCharArray(int size) {
char[] array = new char[size];
for (int i = 0; i < size; i++) {
array[i] = readCharacter();
}
return array;
}
public String readText() {
StringBuilder result = new StringBuilder();
while (true) {
int character = read();
if (character == '\r') {
continue;
}
if (character == -1) {
break;
}
result.append((char) character);
}
return result.toString();
}
public long[] readLongArray(int size) {
long[] array = new long[size];
for (int i = 0; i < size; i++) {
array[i] = readLong();
}
return array;
}
public int[] readIntArray(int size) {
int[] array = new int[size];
for (int i = 0; i < size; i++) {
array[i] = readInt();
}
return array;
}
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 peek() {
if (numChars == -1) {
return -1;
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
return -1;
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar];
}
public int peekNonWhitespace() {
while (isWhitespace(peek())) {
read();
}
return peek();
}
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 long readLong() {
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 String readString() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
if (Character.isValidCodePoint(c)) {
res.appendCodePoint(c);
}
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public char[] readStringAsCharArray() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
if (Character.isValidCodePoint(c)) {
res.appendCodePoint(c);
}
c = read();
} while (!isSpaceChar(c));
char[] resArr = new char[res.length()];
res.getChars(0, res.length(), resArr, 0);
return resArr;
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private String readLine0() {
StringBuilder buf = new StringBuilder();
int c = read();
while (c != '\n' && c != -1) {
if (c != '\r') {
buf.appendCodePoint(c);
}
c = read();
}
return buf.toString();
}
public String readLine() {
String s = readLine0();
while (s.trim().length() == 0) {
s = readLine0();
}
return s;
}
public String readLine(boolean ignoreEmptyLines) {
if (ignoreEmptyLines) {
return readLine();
} else {
return readLine0();
}
}
public char readCharacter() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
return (char) c;
}
public double readDouble() {
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, readInt());
}
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, readInt());
}
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public boolean isExhausted() {
int value;
while (isSpaceChar(value = peek()) && value != -1) {
read();
}
return value == -1;
}
public String next() {
return readString();
}
public SpaceCharFilter getFilter() {
return filter;
}
public void setFilter(SpaceCharFilter filter) {
this.filter = filter;
}
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 17
|
standard input
|
[
"binary search",
"interactive"
] |
b3e8fe76706ba17cb285c75459508334
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,600
| null |
standard output
| |
PASSED
|
a301afcef0898e8c02295ba413a018f2
|
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 40 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 GuessingTheGreatest_Hard {
public static void main(String[] args) throws IOException {
Soumit sc = new Soumit();
int n = sc.nextInt();
System.out.println("? 1 "+n);
System.out.flush();
int smax_ind = sc.nextInt();
if(n == 2){
if(smax_ind == 1){
System.out.println("! 2");
}
else{
System.out.println("! 1");
}
System.exit(0);
}
if(smax_ind == 1){
int l = smax_ind + 1;
int r = n;
while(l < r){
int mid = (l + r) / 2;
System.out.println("? "+smax_ind+" "+mid);
System.out.flush();
int ind = sc.nextInt();
if(ind == smax_ind){
r = mid;
}
else{
l = mid + 1;
}
}
System.out.println("! "+l);
System.exit(0);
}
System.out.println("? 1 "+smax_ind);
System.out.flush();
int ind = sc.nextInt();
int l, r;
if(ind == smax_ind){
l = 1; r = smax_ind - 1;
while(l < r){
int mid = (l + r + 1) / 2;
System.out.println("? "+mid+" "+smax_ind);
System.out.flush();
ind = sc.nextInt();
if(ind == smax_ind){
l = mid;
}
else{
r = mid - 1;
}
}
}
else{
l = smax_ind + 1;
r = n;
while(l < r){
int mid = (l + r) / 2;
System.out.println("? "+smax_ind+" "+mid);
System.out.flush();
ind = sc.nextInt();
if(ind == smax_ind){
r = mid;
}
else{
l = mid + 1;
}
}
}
System.out.println("! "+l);
sc.close();
}
static class Soumit {
final private int BUFFER_SIZE = 1 << 18;
final private DataInputStream din;
final private byte[] buffer;
private PrintWriter pw;
private int bufferPointer, bytesRead;
StringTokenizer st;
public Soumit() {
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Soumit(String file_name) throws IOException {
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public void streamOutput(String file) throws IOException {
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
pw = new PrintWriter(bw);
}
public void println(String a) {
pw.println(a);
}
public void print(String a) {
pw.print(a);
}
public String readLine() throws IOException {
byte[] buf = new byte[3000064]; // line length
int cnt = 0, c;
while ((c = read()) != -1) {
if (c == '\n')
break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public void sort(int[] arr) {
ArrayList<Integer> arlist = new ArrayList<>();
for (int i : arr)
arlist.add(i);
Collections.sort(arlist);
for (int i = 0; i < arr.length; i++)
arr[i] = arlist.get(i);
}
public void sort(long[] arr) {
ArrayList<Long> arlist = new ArrayList<>();
for (long i : arr)
arlist.add(i);
Collections.sort(arlist);
for (int i = 0; i < arr.length; i++)
arr[i] = arlist.get(i);
}
public int[] nextIntArray(int n) throws IOException {
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = nextInt();
}
return arr;
}
public long[] nextLongArray(int n) throws IOException {
long[] arr = new long[n];
for (int i = 0; i < n; i++) {
arr[i] = nextLong();
}
return arr;
}
public double[] nextDoubleArray(int n) throws IOException {
double[] arr = new double[n];
for (int i = 0; i < n; i++) {
arr[i] = nextDouble();
}
return arr;
}
public int nextInt() throws IOException {
int ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException {
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException {
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (c == '.') {
while ((c = read()) >= '0' && c <= '9') {
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException {
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException {
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException {
/*if (din == null)
return;*/
if (din != null) din.close();
if (pw != null) pw.close();
}
}
}
|
Java
|
["5\n\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 17
|
standard input
|
[
"binary search",
"interactive"
] |
b3e8fe76706ba17cb285c75459508334
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,600
| null |
standard output
| |
PASSED
|
4949f2a7e8657939bc09e72b0052b732
|
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.Random;
import java.util.StringTokenizer;
public class TaskC {
static long mod = (long) (1000000000+7);
public static void main(String[] args) {
// TODO Auto-generated method stub
FastReader sc = new FastReader();
PrintWriter out = new PrintWriter(System.out);
int test = 1;
while(test-->0) {
int n = sc.nextInt();
int size = 1;
while(size<n)
size *= 2;
out.println("? "+ 1 + " " + n);
out.flush();
int maxpos = sc.nextInt();
int currpos = 0;
if(n==2) {
out.print(maxpos== 1 ? "! "+2 : "! "+1);
continue;
}
if(maxpos!=1) {
out.println("? "+ 1 + " " + maxpos);
out.flush();
currpos = sc.nextInt();
} else {
currpos = -1;
}
if(currpos==maxpos) {
int k = 0;
for(int b = size;b>=1;b/=2) {
if(k+b<maxpos && isAns(k+b, maxpos, maxpos, out, sc))k+=b;
}
while(k+1<maxpos && isAns(k+1, maxpos, maxpos, out, sc))k++;
out.println("! "+k);
} else {
int k = maxpos;
for(int b = size;b>=1;b/=2) {
if(k+b<=n && !isAns(maxpos, k+b, maxpos, out, sc))k+=b;
}
while(k+1<=n && !isAns(maxpos, k+1, maxpos, out, sc))k++;
k++;
out.println("! "+k);
}
}
out.close();
}
static boolean isAns(int l, int r, int maxpos, PrintWriter out, FastReader sc) {
out.println("?"+" "+(l)+" "+r);
out.flush();
int t = sc.nextInt();
return t==maxpos;
}
static void shuffleArray(long[] arr){
int n = arr.length;
Random rnd = new Random();
for(int i=0; i<n; ++i){
long tmp = arr[i];
int randomPos = i + rnd.nextInt(n-i);
arr[i] = arr[randomPos];
arr[randomPos] = tmp;
}
}
static class FastReader {
StringTokenizer st;
BufferedReader br;
public FastReader() {
br = new BufferedReader(
new InputStreamReader(System.in));
}
String next() {
while(st==null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String s = "";
while(st==null || st.hasMoreElements()) {
try {
s = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
}
return s;
}
}
}
|
Java
|
["5\n\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
|
bd056ccd8ccf29f530a92e7767073478
|
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 GuessingTheGreatestHard {
MyScanner scanner = new MyScanner();
private int solve(int n) {
// if (n == 2) { // 1, 2
// int secMax = ask(0, 1);
// if (secMax == 0) return 1;
// else return 0;
// }
int start = 0, end = n - 1;
int secMax = ask(start, end);
boolean maxIsRight = secMax == 0 || secMax != end && ask(secMax, end) == secMax;
if (maxIsRight) {// Guess Right
while (start <= end) {
int mid = start + (end - start) / 2;
if (mid == 0 || ask(0, mid) != secMax) {
start = mid + 1;
}
else {
end = mid - 1;
}
}
return start;
}
else {
start = 0;
end = n - 1;
while (start <= end) {
int mid = start + (end - start) / 2;
if (mid == n - 1 || ask(mid, n - 1) != secMax) {
end = mid - 1;
}
else {
start = mid + 1;
}
}
return end;
}
}
// private int ask(int l, int r) {
//// int[] arr = {23, 81, 16, 91, 13, 98, 64, 12, 19, 99, 8, 33, 35, 27, 29, 51, 68, 58, 86, 93, 50, 96, 17, 22, 4, 78, 76, 44, 74, 89, 24, 90, 38, 80, 85, 59, 70, 53, 49, 87, 65, 83, 69, 10, 56, 32, 11, 88, 31, 100, 79, 46, 48, 75, 7, 72, 36, 97, 21, 62, 95, 1, 92, 18, 52, 54, 66, 2, 47, 84, 15, 42, 73, 39, 26, 5, 77, 14, 6, 30, 71, 9, 55, 57, 41, 40, 60, 20, 25, 43, 45, 28, 34, 37, 3, 67, 82, 94, 61, 63};
//// int[] arr = {5,1,4,2,3};
// int[] arr = {1, 2};
// int first = -1, second = -1;
// for (int i = l; i <= r; i++) {
// if (first == -1 || arr[i] > arr[first]) {
// second = first;
// first = i;
// }
// else if (second == -1 || arr[i] > arr[second]) {
// second = i;
// }
// }
// return second;
// }
private int ask(int l, int r) {
System.out.println("? " + (l + 1) + " " + (r + 1));
System.out.flush();
int ans = scanner.nextInt();
return ans - 1;
}
private void print(int n) {
System.out.println("! " + (n + 1));
System.out.flush();
}
public static void main(String[] args) {
GuessingTheGreatestHard test = new GuessingTheGreatestHard();
// int t = test.scanner.nextInt();
// for (int i = 0; i < t; i++) {
int n = test.scanner.nextInt();
int ans = test.solve(n);
test.print(ans);
// }
}
class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
int[] nextIntArray(int len) {
int[] arr = new int[len];
for (int i = 0; i < len; i++) {
arr[i] = nextInt();
}
return arr;
}
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
|
140d1133b031c3b420aa33827cd7cc8e
|
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 GuessingTheGreatestHard {
MyScanner scanner = new MyScanner();
private int solve(int n) {
if (n == 2) {
int secMax = ask(0, 1);
if (secMax == 0) return 1;
else return 0;
}
int start = 0, end = n - 1;
int secMax = ask(start, end);
boolean maxIsRight = secMax == 0 || secMax != end && ask(secMax, end) == secMax;
if (maxIsRight) {// Guess Right
while (start <= end) {
int mid = start + (end - start) / 2;
// if (mid == 0) break;
int val = ask(0, mid); // Right
if (val == secMax) {
end = mid - 1;
}
else {
start = mid + 1;
}
}
return start;
}
else {
start = 0;
end = n - 1;
while (start <= end) {
int mid = start + (end - start) / 2;
// if (mid == n - 1) break;
int val = ask(mid, n - 1);
if (val == secMax) {
start = mid + 1;
}
else {
end = mid - 1;
}
}
return end;
}
}
// private int ask(int l, int r) {
//// int[] arr = {23, 81, 16, 91, 13, 98, 64, 12, 19, 99, 8, 33, 35, 27, 29, 51, 68, 58, 86, 93, 50, 96, 17, 22, 4, 78, 76, 44, 74, 89, 24, 90, 38, 80, 85, 59, 70, 53, 49, 87, 65, 83, 69, 10, 56, 32, 11, 88, 31, 100, 79, 46, 48, 75, 7, 72, 36, 97, 21, 62, 95, 1, 92, 18, 52, 54, 66, 2, 47, 84, 15, 42, 73, 39, 26, 5, 77, 14, 6, 30, 71, 9, 55, 57, 41, 40, 60, 20, 25, 43, 45, 28, 34, 37, 3, 67, 82, 94, 61, 63};
//// int[] arr = {5,1,4,2,3};
// int[] arr = {1, 2};
// int first = -1, second = -1;
// for (int i = l; i <= r; i++) {
// if (first == -1 || arr[i] > arr[first]) {
// second = first;
// first = i;
// }
// else if (second == -1 || arr[i] > arr[second]) {
// second = i;
// }
// }
// return second;
// }
private int ask(int l, int r) {
System.out.println("? " + (l + 1) + " " + (r + 1));
System.out.flush();
int ans = scanner.nextInt();
return ans - 1;
}
private void print(int n) {
System.out.println("! " + (n + 1));
System.out.flush();
}
public static void main(String[] args) {
GuessingTheGreatestHard test = new GuessingTheGreatestHard();
// int t = test.scanner.nextInt();
// for (int i = 0; i < t; i++) {
int n = test.scanner.nextInt();
int ans = test.solve(n);
test.print(ans);
// }
}
class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
int[] nextIntArray(int len) {
int[] arr = new int[len];
for (int i = 0; i < len; i++) {
arr[i] = nextInt();
}
return arr;
}
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
|
f35e099391176010973c5c9bd4518183
|
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 GuessingTheGreatestHard {
MyScanner scanner = new MyScanner();
private int solve(int n) {
if (n == 2) {
int secMax = ask(0, 1);
if (secMax == 0) return 1;
else return 0;
}
int start = 0, end = n - 1;
int secMax = ask(start, end);
boolean maxIsRight = secMax == 0 || secMax != end && ask(secMax, end) == secMax;
if (maxIsRight) {
// Guess Right
while (start <= end) {
int mid = start + (end - start) / 2;
if (mid == 0) break;
int val = ask(0, mid);
if (val == secMax) {
end = mid - 1;
}
else {
start = mid + 1;
}
}
return start;
}
else {
start = 0;
end = n - 1;
while (start <= end) {
int mid = start + (end - start) / 2;
if (mid == n - 1) break;
int val = ask(mid, n - 1);
if (val == secMax) {
start = mid + 1;
}
else {
end = mid - 1;
}
}
return end;
}
}
// private int ask(int l, int r) {
//// int[] arr = {23, 81, 16, 91, 13, 98, 64, 12, 19, 99, 8, 33, 35, 27, 29, 51, 68, 58, 86, 93, 50, 96, 17, 22, 4, 78, 76, 44, 74, 89, 24, 90, 38, 80, 85, 59, 70, 53, 49, 87, 65, 83, 69, 10, 56, 32, 11, 88, 31, 100, 79, 46, 48, 75, 7, 72, 36, 97, 21, 62, 95, 1, 92, 18, 52, 54, 66, 2, 47, 84, 15, 42, 73, 39, 26, 5, 77, 14, 6, 30, 71, 9, 55, 57, 41, 40, 60, 20, 25, 43, 45, 28, 34, 37, 3, 67, 82, 94, 61, 63};
//// int[] arr = {5,1,4,2,3};
// int[] arr = {1, 2};
// int first = -1, second = -1;
// for (int i = l; i <= r; i++) {
// if (first == -1 || arr[i] > arr[first]) {
// second = first;
// first = i;
// }
// else if (second == -1 || arr[i] > arr[second]) {
// second = i;
// }
// }
// return second;
// }
private int ask(int l, int r) {
System.out.println("? " + (l + 1) + " " + (r + 1));
System.out.flush();
int ans = scanner.nextInt();
return ans - 1;
}
private void print(int n) {
System.out.println("! " + (n + 1));
System.out.flush();
}
public static void main(String[] args) {
GuessingTheGreatestHard test = new GuessingTheGreatestHard();
// int t = test.scanner.nextInt();
// for (int i = 0; i < t; i++) {
int n = test.scanner.nextInt();
int ans = test.solve(n);
test.print(ans);
// }
}
class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
int[] nextIntArray(int len) {
int[] arr = new int[len];
for (int i = 0; i < len; i++) {
arr[i] = nextInt();
}
return arr;
}
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
|
71306d07a6bda08c8ba8679c4838cd09
|
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;
public class Problem {
private static BufferedReader reader;
private static int ask(int l, int r) throws IOException {
if (l==r) return -1;
System.out.println("? "+(l+1)+" "+(r+1));
int res = Integer.parseInt(reader.readLine());
return res - 1;
}
public static void main(String[] args) throws IOException {
reader = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(reader.readLine());
int secMax = ask(0, n-1);
if (secMax==0 || ask(secMax, n-1)==secMax) {
int l = secMax, r = n-1;
while (l+1<r) {
int mid = (l+r)/2;
int x = ask(secMax, mid);
if (x==secMax) r = mid;
else l = mid;
}
System.out.println("! "+(r+1));
} else {
int l = 0, r = secMax;
while (l+1<r) {
int mid = (l+r)/2;
int x = ask(mid, secMax);
if (x==secMax) l = mid;
else r = mid;
}
System.out.println("! "+(l+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
|
6b1e76354db42178442bed4d7db54af9
|
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;
public class Main {
private static BufferedReader reader;
private static int ask(int l, int r) throws IOException {
if (l>=r) return -1;
System.out.println("? " + (l+1) + " " + (r+1));
int x = Integer.parseInt(reader.readLine());
return x - 1;
}
public static void main(String[] args) throws IOException {
reader = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(reader.readLine());
int x = ask(0, n-1);
if (x==0 || ask(0, x)!=x) { //right part
int l = x, r = n-1;
while (l+1<r) {
int mid = (l+r)/2;
int y = ask(x, mid);
if (y==x) r = mid;
else l = mid;
}
System.out.println("! "+(r+1));
} else { // left part
int l = 0, r = x;
while (l+1<r) {
int mid = (l+r)/2;
int y = ask(mid, x);
if (y==x) l = mid;
else r = mid;
}
System.out.println("! "+(l+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
|
fd6beedc231c1ea2e8a255f59cee3176
|
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.FileInputStream;
import java.io.IOException;
import java.util.*;
public class Main {
static class point {
long val, time, t3;
point(long val, long time, int t3) {
this.val = val;
this.time = time;
this.t3 = t3;
}
}
static class Reader {
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader()
{
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Reader(String file_name) throws IOException
{
din = new DataInputStream(
new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException
{
byte[] buf = new byte[64]; // line length
int cnt = 0, c;
while ((c = read()) != -1) {
if (c == '\n') {
if (cnt != 0) {
break;
}
else {
continue;
}
}
buf[cnt++] = (byte)c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException
{
int ret = 0;
byte c = read();
while (c <= ' ') {
c = read();
}
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException
{
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException
{
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (c == '.') {
while ((c = read()) >= '0' && c <= '9') {
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException
{
bytesRead = din.read(buffer, bufferPointer = 0,
BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException
{
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException
{
if (din == null)
return;
din.close();
}
}
static class comp implements Comparator<point> {
public int compare(point a, point b) {
if (a.val == b.val) {
return Long.compare(b.time, a.time);
}
return Long.compare(a.val, b.val);
}
}
static class TreeNode {
int val;
TreeNode left,right;
TreeNode(int val){
this.val=val;left=null;right=null;
}
}
static TreeNode maxx(int start,int end,int[] arr){
if(start>end){
return null;
}
int ind=0;
int max=-1;
for(int j=start;j<=end;j++){
if(arr[j]>max){
max=arr[j];
ind=j;
}
}
TreeNode jj=new TreeNode(arr[ind]);
jj.left=maxx(start,ind-1,arr);
jj.right=maxx(ind+1,end,arr);
return jj;
}
static void dfs(TreeNode root,int dep){
if(root==null){
return;
}
ans[hashMap.get(root.val)]=dep;
dfs(root.left,dep+1);
dfs(root.right,dep+1);
}
static int[] ans;
static HashMap<Integer,Integer> hashMap;
static class pont{
int val,index;
pont(int val,int index){
this.val=val;
this.index=index;
}
}
static class compr implements Comparator<pont>{
public int compare(pont a,pont b){
return a.val-b.val;
}
}
static class poin{
int src;
long val;
poin(int src,long val){
this.src=src;
this.val=val;
}
}
public static void main(String[] args) throws IOException {
Scanner s = new Scanner(System.in);
int n=s.nextInt();
int low=1,high=n;
System.out.println("? "+low+" "+high );
System.out.println();
System.out.flush();
int secondmaxindex=s.nextInt();
if(low==secondmaxindex){
System.out.println("? "+secondmaxindex+" "+high );
System.out.println();
System.out.flush();
int secondmax2=s.nextInt();
if(secondmax2!=secondmaxindex){
high=secondmaxindex-1;
low=1;
int ans=low;
while(low<=high){
int mid=(low)+(high-low)/2;
if(mid==secondmaxindex){
break;
}
System.out.println("? "+mid+" "+secondmaxindex );
System.out.println();
System.out.flush();
int inpu=s.nextInt();
if(inpu==secondmaxindex){
ans=mid;
low=mid+1;
}else{
high=mid-1;
}
}
System.out.println("! "+" "+ans);
System.out.flush();
}else{
low=secondmaxindex+1;
high=n;
int ans=high;
while(low<=high){
int mid=(low)+(high-low)/2;
if(mid==secondmaxindex){
break;
}
System.out.println("? "+secondmaxindex+" "+mid);
System.out.println();
System.out.flush();
int inpu=s.nextInt();
if(inpu==secondmaxindex){
ans=mid;
high=mid-1;
}else{
low=mid+1;
}
}
System.out.println("! "+" "+ans);
System.out.flush();
}
}
else{
System.out.println("? "+low+" "+secondmaxindex );
System.out.println();
System.out.flush();
int secondmax2=s.nextInt();
if(secondmax2==secondmaxindex){
high=secondmaxindex-1;
low=1;
int ans=low;
while(low<=high){
int mid=(low)+(high-low)/2;
if(mid==secondmaxindex){
break;
}
System.out.println("? "+mid+" "+secondmaxindex );
System.out.println();
System.out.flush();
int inpu=s.nextInt();
if(inpu==secondmaxindex){
ans=mid;
low=mid+1;
}else{
high=mid-1;
}
}
System.out.println("! "+" "+ans);
System.out.flush();
}else{
low=secondmaxindex+1;
high=n;
int ans=high;
while(low<=high){
int mid=(low)+(high-low)/2;
if(mid==secondmaxindex){
break;
}
System.out.println("? "+secondmaxindex+" "+mid);
System.out.println();
System.out.flush();
int inpu=s.nextInt();
if(inpu==secondmaxindex){
ans=mid;
high=mid-1;
}else{
low=mid+1;
}
}
System.out.println("! "+" "+ans);
System.out.flush();
}
}
// int t=s.nextInt();
// int t=1;
// for(int jj=0;jj<t;jj++){
// int n=s.nextInt();
// HashMap<Integer,HashMap<Integer,Integer>> has=new HashMap<>();
// int m=s.nextInt();
// int x=s.nextInt();
// int y=s.nextInt();
// long[] ti=new long[m];
// long[] ki=new long[m];
// HashMap<Integer,HashSet<Integer>> hash=new HashMap<>();
// for(int i=0;i<=n;i++){
// has.put(i,new HashMap<>());
// hash.put(i,new HashSet<>());
// }
// for(int i=0;i<m;i++){
// int a=s.nextInt();
// int b=s.nextInt();
//// if(has.get(a)==null){
//// has.put(a,new HashMap<>());
//// }
//// if(has.get(b)==null){
//// has.put(b,new HashMap<>());
//// }
// has.get(a).put(b,i);
// has.get(b).put(a,i);
// ti[i]=s.nextLong();
// ki[i]=s.nextLong();
// }
//
// long[] vis=new long[n+1];
// Arrays.fill(vis,Long.MAX_VALUE);
// vis[x]=0;
// Queue<poin> qu=new LinkedList<>();
// qu.add(new poin(x,0));
// long ans=Long.MAX_VALUE;
// while(!qu.isEmpty()){
// poin te=qu.poll();
// if(te.src==y){
// ans=Math.min(ans,te.val);continue;
// }
// for(Integer v:has.get(te.src).keySet()){
// long ll=(ki[has.get(te.src).get(v)]+(te.val%ki[has.get(te.src).get(v)]))%ki[has.get(te.src).get(v)]+ti[has.get(te.src).get(v)];
//// if(te.val>ki[has.get(te.src).get(v)]){
//// long ij=(long)Math.ceil((double)te.val/(double)ki[has.get(te.src).get(v)]);
//// ll=(long)((long)ij*(long)ki[has.get(te.src).get(v)]);
//// }else{
//// // long ij=(long)Math.ceil((double)ki[has.get(te.src).get(v)]/(double)te.val);
//// if(te.val==0){
//// ll=0;
//// }else{
//// ll=(long)((long)(long)ki[has.get(te.src).get(v)]);}
//// }
//// ll=(long)((long)ll+(long)ti[has.get(te.src).get(v)]);
//// long ll= (long)Math.max((long)((long)te.val+(long)ti[has.get(te.src).get(v)]), (long)((long)ki[has.get(te.src).get(v)]*(long)Math.floor((double)ki[has.get(te.src).get(v)]/(double)(te.val+ti[has.get(te.src).get(v)]))));
//// if( !hash.get(v).contains(te.src) ){
//// vis[v]=ll;
//// hash.get(v).add(te.src);
//// qu.add(new poin( v,vis[v]));
//// }
// if(vis[v]>=ll){
// vis[v]=ll;
//// hash.get(v).add(te.src);
// qu.add(new poin( v,vis[v]));
//
// }
// }
// }
// if(ans==Long.MAX_VALUE){
// System.out.println(-1);
// }else{
// 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 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
|
5197ab3c870fdc5fdda84f53e6d4e5bb
|
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 MainC {
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public boolean hasNext() {
try {
String string = reader.readLine();
if (string == null) {
return false;
}
tokenizer = new StringTokenizer(string);
return tokenizer.hasMoreTokens();
} catch (IOException e) {
return false;
}
}
}
static InputReader in = new InputReader(System.in);
static PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
public static void main(String[] args) {
solve();
}
static int answer;
static void solve() {
int n = in.nextInt();
dg1(1, n);
}
static void dg1 (int start, int end) {
int secIndex = query(start, end);
if (start + 1 == end) {
answer = secIndex == start ? end : start;
a(answer);
return;
}
boolean flag = false;
if (secIndex == 1) {
flag = true;
}
int temp = 0;
if (!flag) temp = query(start, secIndex);
int low, high, mid;
if (flag || temp != secIndex) {
low = secIndex; high = end;
while(low + 1 < high) {
mid = ((low + high)/2);
if (secIndex == query(secIndex, mid)) high = mid;
else low = mid;
}
a(high);
} else {
low = 1; high = secIndex;
while(low + 1 < high) {
mid = ((low + high)/2);
if (secIndex == query(mid, secIndex)) low = mid;
else high = mid;
}
a(low);
}
}
static int query (int s, int e) {
System.out.println("? " + s + " " + e);
System.out.flush();
return in.nextInt();
}
static void a (int index) {
System.out.println("! " + index);
}
}
|
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
|
629fea3c1fe10d868b7fdc8ac191909b
|
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
|
/*
* akshaygupta26
*/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
import java.util.Random;
import java.util.Arrays;
import java.util.StringTokenizer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Collections;
public class D
{
static FastReader sc=new FastReader();
static HashMap<Integer,HashMap<Integer,Integer>> map=new HashMap<>();
public static void main(String[] args)
{
StringBuffer ans=new StringBuffer();
int test=1;
while(test-->0)
{
int n=sc.nextInt();
int secondHighest =query(1,n);
int res=0;
int left =query(1,secondHighest);
if(left == secondHighest) {
int low =1;
int high=secondHighest-1;
res =low;
while(low<=high) {
int mid = (low+high)/2;
int poss =query(mid,secondHighest);
if(poss == secondHighest) {
low=mid+1;
res=mid;
}
else {
high=mid-1;
}
}
}
else {
int low=secondHighest+1;
int high=n;
res=low;
while(low<=high) {
int mid = (low+high)/2;
int poss =query(secondHighest,mid);
if(poss == secondHighest) {
high=mid-1;
res=mid;
}
else {
low=mid+1;
}
}
}
ans.append("! "+res+"\n");
}
System.out.print(ans);
}
static int query(int l,int r) {
if(l == r)
return -1;
if(map.containsKey(l) && map.get(l).containsKey(r)) {
return map.get(l).get(r);
}
System.out.println("? "+l+" "+r);
int n =sc.nextInt();
System.out.flush();
if(!map.containsKey(l)) {
map.put(l,new HashMap<Integer,Integer>());
}
map.get(l).put(r,n);
return n;
}
static final Random random=new Random();
static void ruffleSort(int[] a) {
int n=a.length;//shuffle, then sort
for (int i=0; i<n; i++) {
int oi=random.nextInt(n), temp=a[oi];
a[oi]=a[i]; a[i]=temp;
}
Arrays.sort(a);
}
static void ruffleSort(long[] a) {
int n=a.length;//shuffle, then sort
for (int i=0; i<n; i++) {
int oi=random.nextInt(n);
long temp=a[oi];
a[oi]=a[i]; a[i]=temp;
}
Arrays.sort(a);
}
static 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
|
29a289fea5a6adf464d7ee9c8a32c166
|
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 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
|
df48168e3559c79ffa9ef82794a14f3c
|
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 Main{
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[] nextArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = nextInt();
return a;
}
long[] nextArray(long n) {
long[] a = new long[(int) n];
for (int i = 0; i < n; i++) a[i] = nextLong();
return a;
}
long nextLong() {
return Long.parseLong(next());
}
}
static class FastWriter extends PrintWriter {
FastWriter(){
super(System.out);
}
void println(int[] array) {
for(int i=0; i<array.length; i++) {
print(array[i]+" ");
}
println();
}
void println(long [] array) {
for(int i=0; i<array.length; i++) {
print(array[i]+" ");
}
println();
}
}
static int MOD=998244353;
public static void main(String[] args) throws IOException {
FastScanner in = new FastScanner();
FastWriter out = new FastWriter();
//int t=in.nextInt();
int t=1;
while (t-->0){
int n=in.nextInt();
out.println("? 1 "+n);
out.flush();
int pos=in.nextInt();
int pos1=n;
if(pos!=1){
out.println("? 1 "+pos);
out.flush();
pos1=in.nextInt();
}
int i=1,j=n;
if(pos==pos1){
j=pos;
while (i+1<j){
int mid=(i+j)/2;
out.println("? "+mid+" "+pos);
out.flush();
pos1=in.nextInt();
if(pos==pos1){
i=mid;
}else {
j=mid;
}
}
out.println("! "+i);
out.flush();
}else {
i=pos;
while (i+1<j){
int mid=(i+j)/2;
out.println("? "+pos+" "+mid);
out.flush();
pos1=in.nextInt();
if(pos==pos1){
j=mid;
}else {
i=mid;
}
}
out.println("! "+j);
out.flush();
}
}
out.close();
}
static boolean check(int[] a){
for (int i = 0; i < a.length - 1; i++) {
if(a[i]!=a[i+1]){
return false;
}
}
return true;
}
//Arrays.sort(a, (o1, o2) -> (o1[0] - o2[0]));
static int subarray_lessthan_k(int[] A,int n,int k){
int s=0,e=0,sum=0,cnt=0;
while(e<n){
sum+=A[e];
while(s<=e&&sum>k){
sum-=A[s++];
}
cnt+=e-s+1;
e++;
}
return cnt;
}
static int totalPrimeFactors(int n) {
int cnt=0;
while (n%2==0) {
cnt++;
n /= 2;
}
int num= (int) Math.sqrt(n);
for (int i = 3; i <= num; i+= 2) {
while (n%i == 0) {
cnt++;
n /= i;
num=(int)Math.sqrt(n);
}
}
if (n > 2){
cnt++;
}
return cnt;
}
static char get(int i){
return (char)(i+'a');
}
static boolean distinct(int num){
HashSet<Integer> set=new HashSet<>();
int len=String.valueOf(num).length();
while (num!=0){
set.add(num%10);
num/=10;
}
return set.size()==len;
}
static int maxSubArraySum(int a[],int st,int en) {
int max_s = Integer.MIN_VALUE, max_e = 0,ind=0,ind1=1;
for (int i = st; i <= en; i++) {
max_e+= a[i];
if (max_s < max_e){
max_s = max_e;
ind=ind1;
}
if (max_e < 0){
max_e = 0;
ind1=i+1;
}
}
if(st==0){
return max_s;
}
if(ind==1){
return a[0]+2*max_s;
}else {
return 2*max_s+maxSubArraySum(a,0,ind-1);
}
//return max_s;
}
static void segmentedSieve(ArrayList<Integer> res,int low, int high) {
if(low < 2){
low = 2;
}
ArrayList<Integer> prime = new ArrayList<>();
simpleSieve(high, prime);
boolean[] mark = new boolean[high - low + 1];
for (int i = 0; i < mark.length; i++){
mark[i] = true;
}
for (int i = 0; i < prime.size(); i++) {
int loLim = (low / prime.get(i)) * prime.get(i);
if (loLim < low){
loLim += prime.get(i);
}
if (loLim == prime.get(i)){
loLim += prime.get(i);
}
for (int j = loLim; j <= high; j += prime.get(i)) {
mark[j - low] = false;
}
}
for (int i = low; i <= high; i++) {
if (mark[i - low]){
res.add(i);
}
}
}
static void simpleSieve(int limit, ArrayList<Integer> prime) {
int bound = (int)Math.sqrt(limit);
boolean[] mark = new boolean[bound + 1];
for (int i = 0; i <= bound; i++){
mark[i] = true;
}
for (int i = 2; i * i <= bound; i++) {
if (mark[i]) {
for (int j = i * i; j <= bound; j += i){
mark[j] = false;
}
}
}
for (int i = 2; i <= bound; i++) {
if (mark[i]){
prime.add(i);
}
}
}
static int highestPowerOf2(int n) {
if (n < 1){ return 0; }
int res = 1;
for (int i = 0; i < 8 * Integer.BYTES; i++) {
int curr = 1 << i;
if (curr > n){ break; }
res = curr;
}
return res;
}
static int reduceFraction(int x, int y) {
int d= gcd(x, y);
return x/d+y/d;
}
static boolean subset(int[] ar,int n,int sum){
if(sum==0){
return true;
}
if(n<0||sum<0){
return false;
}
return subset(ar,n-1,sum)||subset(ar,n-1,sum-ar[n]);
}
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 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 lcm(long a, long b) {
return (a * b) / gcd(a, b);
}
static int lcm(int a, int b) {
return (a * b) / gcd(a, b);
}
static boolean isPowerOfTwo(long n) {
if(n==0){
return false;
}
while (n%2==0){
n/=2;
}
return n==1;
}
static boolean isPerfectSquare(int x){
if (x >= 0) {
int sr = (int)Math.sqrt(x);
return ((sr * sr) == x);
}
return false;
}
static int lower_bound(int[] arr, int x) {
int low_limit = 0, high_limit = arr.length, mid;
while (low_limit < high_limit) {
mid = (low_limit + high_limit) / 2;
if (arr[mid] >= x){
high_limit = mid;
}else{
low_limit = mid + 1;
}
}
return low_limit;
}
static int upper_bound(int[] arr, int x) {
int low_limit = 0, high_limit = arr.length, mid;
while (low_limit < high_limit) {
mid = (low_limit + high_limit) / 2;
if (arr[mid] > x){
high_limit = mid;
}else{
low_limit = mid + 1;
}
}
return low_limit;
}
static int binarySearch(int[] ar,int n,int num){
int low=0,high=n-1;
while (low<=high){
int mid=(low+high)/2;
if(ar[mid]==num){
return mid;
}else if(ar[mid]>num){
high=mid-1;
}else {
low=mid+1;
}
}
return -1;
}
static int fib(int n) {
long F[][] = new long[][]{{1,1},{1,0}};
if (n == 0){
return 0;
}
power(F, n-1);
return (int)F[0][0];
}
static void multiply(long F[][], long M[][]) {
long x = (F[0][0]*M[0][0])%1000000007 + (F[0][1]*M[1][0])%1000000007;
long y = (F[0][0]*M[0][1])%1000000007 + (F[0][1]*M[1][1])%1000000007;
long z = (F[1][0]*M[0][0])%1000000007 + (F[1][1]*M[1][0])%1000000007;
long w = (F[1][0]*M[0][1])%1000000007 + (F[1][1]*M[1][1])%1000000007;
F[0][0] = x%1000000007;
F[0][1] = y%1000000007;
F[1][0] = z%1000000007;
F[1][1] = w%1000000007;
}
static void power(long F[][], int n) {
if( n == 0 || n == 1){
return;
}
long M[][] = new long[][]{{1,1},{1,0}};
power(F, n/2);
multiply(F, F);
if (n%2 != 0){
multiply(F, M);
}
}
}
|
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
|
9144417b05a2aa6beab4af8a2d7efdfd
|
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.text.*;
public class Main implements Runnable {
FastScanner sc;
PrintWriter pw;
final class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner() {
try {
br = new BufferedReader(new InputStreamReader(System.in));
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
e.printStackTrace();
}
}
public long nlo() {
return Long.parseLong(next());
}
public String next() {
if (st.hasMoreTokens()) return st.nextToken();
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
e.printStackTrace();
}
return st.nextToken();
}
public int ni() {
return Integer.parseInt(next());
}
public String nli() {
String line = "";
if (st.hasMoreTokens()) line = st.nextToken();
else try {
return br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
while (st.hasMoreTokens()) line += " " + st.nextToken();
return line;
}
public double nd() {
return Double.parseDouble(next());
}
}
public static void main(String[] args) throws Exception
{
new Thread(null,new Main(),"codeforces",1<<28).start();
}
public void run()
{
// sc=new FastScanner();
//pw=new PrintWriter(System.out);
try{
solve();
}
catch(Exception e)
{
;
// pw.println(e);
}
//pw.flush();
//pw.close();
}
public long gcd(long a,long b)
{
return b==0L?a:gcd(b,a%b);
}
public long ppow(long a,long b,long mod)
{
if(b==0L)
return 1L;
long tmp=1;
while(b>1L)
{
if((b&1L)==1L)
tmp*=a;
a*=a;
a%=mod;
tmp%=mod;
b>>=1;
}
return (tmp*a)%mod;
}
public long pow(long a,long b)
{
if(b==0L)
return 1L;
long tmp=1;
while(b>1L)
{
if((b&1L)==1)
tmp*=a;
a*=a;
b>>=1;
}
return (tmp*a);
}
public int gcd(int x,int y)
{
return y==0?x:gcd(y,x%y);
}
//////////////////////////////////
///////////// LOGIC ///////////
////////////////////////////////
public void solve() throws Exception{
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
System.out.println("? "+1+" "+n);
int m=sc.nextInt();
if(m!=1&&m!=n){
System.out.println("? 1 "+m);
int x=sc.nextInt();
if(x==m)
System.out.println("! "+f(1,m,sc));
else
System.out.println("! "+g(m,n,sc));
}
else if(m==1)
System.out.println("! "+g(1,n,sc));
else
System.out.println("! "+f(1,n,sc));
}
public int f(int s,int e,Scanner sc){
int ans=s;
int val=e;
e--;
while(s<=e){
int m=(s+e)/2;
System.out.println("? "+m+" "+val);
int x=sc.nextInt();
if(x==val){
ans=m;
s=m+1;
}
else
e=m-1;
}
return ans;
}
public int g(int s,int e,Scanner sc){
int ans=s;
int val=s;
s++;
while(s<=e){
int m=(s+e)/2;
System.out.println("? "+val+" "+m);
int x=sc.nextInt();
if(x==val){
ans=m;
e=m-1;
}
else
s=m+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
|
e1781b02f93ec75611af66c5d809540c
|
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 CA2 {
static FastScanner sc = new FastScanner();
public static void main(String[] args) {
PrintWriter out = new PrintWriter(System.out);
int n = sc.nextInt();
out.println("! " + solve(n));
out.close();
}
static int query(int l, int r) {
if(r == l)
return -1;
System.out.println("? " + l + " " + r);
System.out.flush();
int q = sc.nextInt();
return q;
}
static int solve(int n) {
int smax = query(1, n);
if(smax == 1 || query(1,smax) != smax) {
int l = smax;
int r = n;
while(r-l > 1) {
int m = l + (r-l)/2;
if(query(smax, m) == smax)
r = m;
else
l = m;
}
return r;
} else {
int l = 1;
int r = smax;
while(r-l > 1) {
int m = l + (r-l)/2;
if(query(m, smax) == smax) {
l = m;
} else {
r = m;
}
}
return l;
}
}
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();
}
public String nextLine() {
try {
return br.readLine();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
int nextInt() {
return Integer.parseInt(next());
}
int[] readArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
long 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
|
2aee81ceb08f2170c96f21bdff898649
|
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 {
static FastScanner sc = new FastScanner();
public static void main(String[] args) {
PrintWriter out = new PrintWriter(System.out);
int n = sc.nextInt();
out.println("! " + solve(n));
out.close();
}
static int query(int l, int r) {
if(r == l)
return -1;
System.out.println("? " + l + " " + r);
System.out.flush();
int q = sc.nextInt();
return q;
}
static int solve(int n) {
int smax = query(1, n);
if(smax == 1 || query(1,smax) != smax) {
int l = smax;
int r = n;
while(r-l > 1) {
int m = l + (r-l)/2;
if(query(smax, m) == smax)
r = m;
else
l = m;
}
return r;
} else {
int l = 1;
int r = smax;
while(r-l > 1) {
int m = l + (r-l)/2;
if(query(m, smax) == smax) {
l = m;
} else {
r = m;
}
}
return l;
}
}
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();
}
public String nextLine() {
try {
return br.readLine();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
int nextInt() {
return Integer.parseInt(next());
}
int[] readArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
long 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
|
5f436ffe24133f7fcc9c7dc50b6582b8
|
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.LinkedBlockingDeque;
import javax.print.attribute.IntegerSyntax;
import javax.sql.rowset.spi.SyncResolver;
import java.io.*;
import java.nio.channels.NonReadableChannelException;
import java.text.DateFormatSymbols;
import static java.lang.System.*;
public class CpTemp{
static FastScanner fs = null;
static ArrayList<Integer> al[];
static HashMap<Long,Long> hm;
static long fy;
static long fx;
static long ix;
static long iy;
static long prex[];
static long prey[];
public static void main(String[] args) {
fs = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
int t= 1;
outer:
while (t-- > 0) {
int n = fs.nextInt();
int smax = ask(0,n-1);
int g = ask(0,smax);
int ans = -1;
if(g != smax){
int l = smax;
int r = n-1;
while(l+1<r){
int mid = (l+r)/2;
if(ask(smax,mid) == smax){
r = mid;
}else{
l = mid;
}
}
out.println("! "+(r+1));
}else{
int l=0;
int r = smax;
while(l+1<r){
int mid = (l+r+1)/2;
if(ask(mid,smax) == smax){
ans = mid;
l = mid;
}else{
r = mid;
}
}
out.println("! "+(l+1));
}
}
out.close();
}
public static int ask(int st,int end){
if(st>=end) {
return -1;
}
out.println("? "+(st+1)+" "+(end+1));
int g = fs.nextInt();
out.flush();
return g-1;
}
static long bit[]; // '1' index based array
public static void update(long bit[],int i,int x){
for(;i<bit.length;i+=(i&(-i))){
bit[i] += x;
}
}
public static long sum(int i){
long sum=0;
for(;i>0 ;i -= (i&(-i))){
sum += bit[i];
}
return sum;
}
static class Pair implements Comparable<Pair> {
int x;
int y;
Pair(int x, int y) {
this.x = x;
this.y = y;
}
public int compareTo(Pair o){
return this.y-o.y;
}
}
static class Pair1 implements Comparable<Pair1> {
int x;
int y;
int z;
Pair1(int x, int y,int z) {
this.x = x;
this.y = y;
this.z = z;
}
public int compareTo(Pair1 o){
return this.z-o.z;
}
}
static int power(int x, int y, int p) {
if (y == 0)
return 1;
if (x == 0)
return 0;
int res = 1;
x = x % p;
while (y > 0) {
if (y % 2 == 1)
res = (res * x) % p;
y = y >> 1;
x = (x * x) % p;
}
return res;
}
static long power(long x, long y) {
if (y == 0)
return 1;
if (x == 0)
return 0;
long res = 1;
while (y > 0) {
if (y % 2 == 1)
res = (res * x);
y = y >> 1;
x = (x * x);
}
return res;
}
static void sort(long[] a) {
ArrayList<Long> l = new ArrayList<>();
for (long i : a) l.add(i);
Collections.sort(l);
for (int i = 0; i < a.length; i++) a[i] = l.get(i);
}
static class FastScanner {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer("");
String next() {
while (!st.hasMoreTokens())
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
int[] readArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = nextInt();
return a;
}
long[] readlongArray(int n){
long[] a = new long[n];
for (int i = 0; i < n; i++) a[i] = nextLong();
return a;
}
long nextLong() {
return Long.parseLong(next());
}
}
static boolean prime[];
static void sieveOfEratosthenes(int n) {
prime = new boolean[n + 1];
for (int i = 0; i <= n; i++)
prime[i] = true;
for (int p = 2; p * p <= n; p++) {
// If prime[p] is not changed, then it is a
// prime
if (prime[p] == true) {
// Update all multiples of p
for (int i = p * p; i <= n; i += p)
prime[i] = false;
}
}
}
public static int log2(int x) {
return (int) (Math.log(x) / Math.log(2));
}
public static long gcd(long a, long b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
static long nCk(int n, int k) {
long res = 1;
for (int i = n - k + 1; i <= n; ++i)
res *= i;
for (int i = 2; i <= k; ++i)
res /= i;
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
|
b2fb83d24a7fdd74d059b72b0747a3ea
|
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 final class Solution {
static PrintWriter out = new PrintWriter(System.out);
static FastReader in = new FastReader();
static long mod = (long) 1e9 + 7;
static Pair[] moves = new Pair[]{new Pair(-1, 0), new Pair(1, 0), new Pair(0, -1), new Pair(0, 1)};
public static void main(String[] args) {
int t = 1;
out:
while (t-- > 0) {
int n = i();
int i1 = ask(0, n - 1);
int i2 = i1 > 0 ? ask(0, i1) : -1;
if (i1 == i2) {
int l = 0;
int r = i1 - 1;
while (l < r) {
int m = (l + r + 1) / 2;
if (ask(m, i1) == i1) {
l = m;
} else {
r = m - 1;
}
}
out.println("! " + (l + 1));
out.flush();
} else {
int l = i1 + 1;
int r = n - 1;
while (l < r) {
int m = (l + r) / 2;
if (ask(i1, m) == i1) {
r = m;
} else {
l = m + 1;
}
}
out.println("! " + (l + 1));
out.flush();
}
}
out.flush();
}
static int ask(int l, int r) {
out.println("? " + (l + 1) + " " + (r + 1));
out.flush();
return i() - 1;
}
static boolean isPS(double number) {
double sqrt = Math.sqrt(number);
return ((sqrt - Math.floor(sqrt)) == 0);
}
static int sd(long i) {
int d = 0;
while (i > 0) {
d += i % 10;
i = i / 10;
}
return d;
}
static int[] leastPrime;
static void sieveLinear(int N) {
int[] primes = new int[N];
int idx = 0;
leastPrime = new int[N + 1];
for (int i = 2; i <= N; i++) {
if (leastPrime[i] == 0) {
primes[idx++] = i;
leastPrime[i] = i;
}
int curLP = leastPrime[i];
for (int j = 0; j < idx; j++) {
int p = primes[j];
if (p > curLP || (long) p * i > N) {
break;
} else {
leastPrime[p * i] = p;
}
}
}
}
static int lower(long A[], long x) {
int l = -1, r = A.length;
while (r - l > 1) {
int m = (l + r) / 2;
if (A[m] >= x) {
r = m;
} else {
l = m;
}
}
return r;
}
static int upper(long A[], long x) {
int l = -1, r = A.length;
while (r - l > 1) {
int m = (l + r) / 2;
if (A[m] <= x) {
l = m;
} else {
r = m;
}
}
return l;
}
static void swap(int A[], int a, int b) {
int t = A[a];
A[a] = A[b];
A[b] = t;
}
static int lowerBound(int A[], int low, int high, int x) {
if (low > high) {
if (x >= A[high]) {
return A[high];
}
}
int mid = (low + high) / 2;
if (A[mid] == x) {
return A[mid];
}
if (mid > 0 && A[mid - 1] <= x && x < A[mid]) {
return A[mid - 1];
}
if (x < A[mid]) {
return lowerBound(A, low, mid - 1, x);
}
return lowerBound(A, mid + 1, high, x);
}
static long pow(long a, long b) {
long pow = 1;
long x = a;
while (b != 0) {
if ((b & 1) != 0) {
pow = (pow * x) % mod;
}
x = (x * x) % mod;
b /= 2;
}
return pow;
}
static boolean isPrime(long N) {
if (N <= 1) {
return false;
}
if (N <= 3) {
return true;
}
if (N % 2 == 0 || N % 3 == 0) {
return false;
}
for (int i = 5; i * i <= N; i = i + 6) {
if (N % i == 0 || N % (i + 2) == 0) {
return false;
}
}
return true;
}
static void print(char A[]) {
for (char c : A) {
out.print(c);
}
out.println();
}
static void print(boolean A[]) {
for (boolean c : A) {
out.print(c + " ");
}
out.println();
}
static void print(int A[]) {
for (int c : A) {
out.print(c + " ");
}
out.println();
}
static void print(long A[]) {
for (long i : A) {
out.print(i + " ");
}
out.println();
}
static void print(List<Integer> A) {
for (int a : A) {
out.print(a + " ");
}
}
static void printYes() {
out.println("YES");
}
static void printNo() {
out.println("NO");
}
static int i() {
return in.nextInt();
}
static long l() {
return in.nextLong();
}
static String s() {
return in.nextLine();
}
static int[] input(int N) {
int A[] = new int[N];
for (int i = 0; i < N; i++) {
A[i] = in.nextInt();
}
return A;
}
static long[] inputLong(int N) {
long A[] = new long[N];
for (int i = 0; i < A.length; i++) {
A[i] = in.nextLong();
}
return A;
}
static int GCD(int a, int b) {
if (b == 0) {
return a;
} else {
return GCD(b, a % b);
}
}
static long GCD(long a, long b) {
if (b == 0) {
return a;
} else {
return GCD(b, a % b);
}
}
}
class BIT {
int n;
int[] tree;
public BIT(int n) {
this.n = n;
this.tree = new int[n + 1];
}
public static int lowbit(int x) {
return x & (-x);
}
public void update(int x) {
while (x <= n) {
++tree[x];
x += lowbit(x);
}
}
public int query(int x) {
int ans = 0;
while (x > 0) {
ans += tree[x];
x -= lowbit(x);
}
return ans;
}
public int query(int x, int y) {
return query(y) - query(x - 1);
}
}
class SegmentTree {
long[] t;
public SegmentTree(int n) {
t = new long[n + n];
Arrays.fill(t, Long.MIN_VALUE);
}
public long get(int i) {
return t[i + t.length / 2];
}
public void add(int i, long value) {
i += t.length / 2;
t[i] = value;
for (; i > 1; i >>= 1) {
t[i >> 1] = Math.max(t[i], t[i ^ 1]);
}
}
// max[a, b]
public long max(int a, int b) {
long res = Long.MIN_VALUE;
for (a += t.length / 2, b += t.length / 2; a <= b; a = (a + 1) >> 1, b = (b - 1) >> 1) {
if ((a & 1) != 0) {
res = Math.max(res, t[a]);
}
if ((b & 1) == 0) {
res = Math.max(res, t[b]);
}
}
return res;
}
}
class Pair {
int i, j;
Pair(int i, int j) {
this.i = i;
this.j = j;
}
}
class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
|
Java
|
["5\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
|
aa4f947d70c93e11fe0f2336e0c1395e
|
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.math.BigInteger;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
PrintWriter out = new PrintWriter(outputStream);
InputReader in = new InputReader(inputStream);
// for(int i=4;i<=4;i++) {
// InputStream uinputStream = new FileInputStream("timeline.in");
//String f = i+".in";
//InputStream uinputStream = new FileInputStream(f);
// InputReader in = new InputReader(uinputStream);
// PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("timeline.out")));
// }
Task t = new Task();
t.solve(in, out);
out.close();
}
static class Task{
public void solve(InputReader in, PrintWriter out) throws IOException {
int c = in.nextInt();
System.out.println("? 1 "+c);
System.out.flush();
int snd = in.nextInt();
if(c==2) {
if(snd==1) {
System.out.println("! 2");
System.out.flush();
}else {
System.out.println("! 1");
System.out.flush();
}
return;
}
int t = c;
if(snd!=1) {
System.out.println("? 1 "+snd);
System.out.flush();
t = in.nextInt();
}
if(t==snd) {
int l = 1;
int r = snd-1;
while(l<r-1) {
int mid = (l+r)/2;
System.out.println("? "+mid+" "+snd);
System.out.flush();
int nxt = in.nextInt();
if(nxt==snd) {
l = mid;
}else {
r = mid;
}
}
System.out.println("? "+r+" "+snd);
System.out.flush();
int tmp = in.nextInt();
if(tmp==snd) {
System.out.println("! "+r);
}else {
System.out.println("! "+l);
}
}else {
int l = snd+1;
int r = c;
while(l<r-1) {
int mid = (l+r)/2;
System.out.println("? "+snd+" "+mid);
System.out.flush();
int nxt = in.nextInt();
if(nxt==snd) {
r = mid;
}else {
l = mid;
}
}
System.out.println("? "+snd+" "+l);
System.out.flush();
int tmp = in.nextInt();
if(tmp==snd) {
System.out.println("! "+l);
}else {
System.out.println("! "+r);
}
}
}
private static int combx(int n, int k) {
int comb[][] = new int[n+1][n+1];
for(int i = 0; i <=n; i ++){
comb[i][0] = comb[i][i] = 1;
for(int j = 1; j < i; j++){
comb[i][j] = comb[i-1][j] + comb[i-1][j-1];
comb[i][j] %= 1000000007;
}
}
return comb[n][k];
}
class trie_node{
boolean end;
int val;
int lvl;
trie_node zero;
trie_node one;
public trie_node() {
zero = null;
one = null;
end = false;
val = -1;
lvl = -1;
}
}
class trie{
trie_node root = new trie_node();
public void build(int x, int sz) {
trie_node cur = root;
for(int i=sz;i>=0;i--) {
int v = (x&(1<<i))==0?0:1;
if(v==0&&cur.zero==null) {
cur.zero = new trie_node();
}
if(v==1&&cur.one==null) {
cur.one = new trie_node();
}
cur.lvl = i;
if(i==0) {
cur.end = true;
cur.val = x;
}else {
if(v==0)
cur = cur.zero;
else
cur = cur.one;
cur.val = v;
cur.lvl = i;
}
}
}
int search(int num, int limit, trie_node r, int lvl) {
if(r==null) return -1;
if(r.end) return r.val;
int f = -1;
int num_val = (num&1<<lvl)==0?0:1;
int limit_val = (limit&1<<lvl)==0?0:1;
if(limit_val==1) {
if(num_val==0) {
int t = search(num,limit,r.one,lvl-1);
if(t>f) return t;
t = search(num,limit,r.zero,lvl-1);
if(t>f) return t;
}else {
int t = search(num,limit,r.zero,lvl-1);
if(t>f) return t;
t = search(num,limit,r.one,lvl-1);
if(t>f) return t;
}
}else {
int t = search(num,limit,r.zero,lvl-1);
if(t>f) return t;
}
return f;
}
}
public int[] maximizeXor(int[] nums, int[][] queries) {
int m = queries.length;
int ret[] = new int[m];
trie t = new trie();
int sz = 5;
for(int i:nums) t.build(i,sz);
int p = 0;
for(int x[]:queries) {
if(p==1) {
Dumper.print("here");
}
ret[p++] = t.search(x[0], x[1], t.root, sz);
}
return ret;
}
class edge implements Comparable<edge>{
int id,f,t; int len;
public edge(int a, int b, int c, int d) {
f=a;t=b;len=c;id=d;
}
@Override
public int compareTo(edge t) {
if(this.len-t.len>0) return 1;
else if(this.len-t.len<0) return -1;
return 0;
}
}
static class lca_naive{
int n;
ArrayList<edge>[] g;
int lvl[];
int pare[];
int dist[];
public lca_naive(int t, ArrayList<edge>[] x) {
n=t;
g=x;
lvl = new int[n];
pare = new int[n];
dist = new int[n];
}
void pre_process() {
dfs(0,-1,g,lvl,pare,dist);
}
void dfs(int cur, int pre, ArrayList<edge>[] g, int lvl[], int pare[], int dist[]) {
for(edge nxt_edge:g[cur]) {
if(nxt_edge.t!=pre) {
lvl[nxt_edge.t] = lvl[cur]+1;
dist[nxt_edge.t] = dist[cur]+nxt_edge.len;
pare[nxt_edge.t] = cur;
dfs(nxt_edge.t,cur,g,lvl,pare,dist);
}
}
}
public int work(int p, int q) {
int a = p;
int b = q;
while(lvl[p]<lvl[q]) q = pare[q];
while(lvl[p]>lvl[q]) p = pare[p];
while(p!=q){p = pare[p]; q = pare[q];}
int c = p;
return dist[a]+dist[b]-dist[c]*2;
}
}
static class lca_binary_lifting{
int n;
ArrayList<edge>[] g;
int lvl[];
int pare[];
int dist[];
int table[][];
public lca_binary_lifting(int a, ArrayList<edge>[] t) {
n = a;
g = t;
lvl = new int[n];
pare = new int[n];
dist = new int[n];
table = new int[20][n];
}
void pre_process() {
dfs(0,-1,g,lvl,pare,dist);
for(int i=0;i<20;i++) {
for(int j=0;j<n;j++) {
if(i==0) table[0][j] = pare[j];
else table[i][j] = table[i-1][table[i-1][j]];
}
}
}
void dfs(int cur, int pre, ArrayList<edge>[] g, int lvl[], int pare[], int dist[]) {
for(edge nxt_edge:g[cur]) {
if(nxt_edge.t!=pre) {
lvl[nxt_edge.t] = lvl[cur]+1;
dist[nxt_edge.t] = dist[cur]+nxt_edge.len;
pare[nxt_edge.t] = cur;
dfs(nxt_edge.t,cur,g,lvl,pare,dist);
}
}
}
public int work(int p, int q) {
int a = p;
int b = q;
if(lvl[p]>lvl[q]) {
int tmp = p;
p=q;
q=tmp;
}
for(int i=19;i>=0;i--) {
if(lvl[table[i][q]]>=lvl[p]) q=table[i][q];
}
if(p==q) return p;// return dist[a]+dist[b]-dist[p]*2;
for(int i=19;i>=0;i--) {
if(table[i][p]!=table[i][q]) {
p = table[i][p];
q = table[i][q];
}
}
return table[0][p];
//return dist[a]+dist[b]-dist[table[0][p]]*2;
}
}
static class lca_sqrt_root{
int n;
ArrayList<edge>[] g;
int lvl[];
int pare[];
int dist[];
int jump[];
int sz;
public lca_sqrt_root(int a, ArrayList<edge>[] b) {
n=a;
g=b;
lvl = new int[n];
pare = new int[n];
dist = new int[n];
jump = new int[n];
sz = (int) Math.sqrt(n);
}
void pre_process() {
dfs(0,-1,g,lvl,pare,dist,jump);
}
void dfs(int cur, int pre, ArrayList<edge>[] g, int lvl[], int pare[], int dist[], int[] jump) {
for(edge nxt_edge:g[cur]) {
if(nxt_edge.t!=pre) {
lvl[nxt_edge.t] = lvl[cur]+1;
dist[nxt_edge.t] = dist[cur]+nxt_edge.len;
pare[nxt_edge.t] = cur;
if(lvl[nxt_edge.t]%sz==0) {
jump[nxt_edge.t] = cur;
}else {
jump[nxt_edge.t] = jump[cur];
}
dfs(nxt_edge.t,cur,g,lvl,pare,dist,jump);
}
}
}
int work(int p, int q) {
int a = p; int b = q;
if(lvl[p]>lvl[q]) {
int tmp = p;
p=q;
q=tmp;
}
while(jump[p]!=jump[q]) {
if(lvl[p]>lvl[q]) p = jump[p];
else q = jump[q];
}
while(p!=q) {
if(lvl[p]>lvl[q]) p = pare[p];
else q = pare[q];
}
return dist[a]+dist[b]-dist[p]*2;
}
}
// class edge implements Comparable<edge>{
// int f,t,len;
// public edge(int a, int b, int c) {
// f=a;t=b;len=c;
// }
// @Override
// public int compareTo(edge t) {
// return t.len-this.len;
// }
// }
class pair implements Comparable<pair>{
int idx,lvl;
public pair(int a, int b) {
idx = a;
lvl = b;
}
@Override
public int compareTo(pair t) {
return t.lvl-this.lvl;
}
}
static class lca_RMQ{
int n;
ArrayList<edge>[] g;
int lvl[];
int dist[];
int tour[];
int tour_rank[];
int first_occ[];
int c;
sgt s;
public lca_RMQ(int a, ArrayList<edge>[] b) {
n=a;
g=b;
c=0;
lvl = new int[n];
dist = new int[n];
tour = new int[2*n];
tour_rank = new int[2*n];
first_occ = new int[n];
Arrays.fill(first_occ, -1);
}
void pre_process() {
tour[c++] = 0;
dfs(0,-1);
for(int i=0;i<2*n;i++) {
tour_rank[i] = lvl[tour[i]];
if(first_occ[tour[i]]==-1) first_occ[tour[i]] = i;
}
s = new sgt(0,2*n,tour_rank);
}
void dfs(int cur, int pre) {
for(edge nxt_edge:g[cur]) {
if(nxt_edge.t!=pre) {
lvl[nxt_edge.t] = lvl[cur]+1;
dist[nxt_edge.t] = dist[cur]+nxt_edge.len;
tour[c++] = nxt_edge.t;
dfs(nxt_edge.t,cur);
tour[c++] = cur;
}
}
}
int work(int p,int q) {
int a = Math.max(first_occ[p], first_occ[q]);
int b = Math.min(first_occ[p], first_occ[q]);
int idx = s.query_min_idx(b, a+1);
//Dumper.print(a+" "+b+" "+idx);
int c = tour[idx];
return dist[p]+dist[q]-dist[c]*2;
}
}
static class sgt{
sgt lt;
sgt rt;
int l,r;
int sum, max, min, lazy;
int min_idx;
public sgt(int L, int R, int arr[]) {
l=L;r=R;
if(l==r-1) {
sum = max = min = arr[l];
lazy = 0;
min_idx = l;
return;
}
lt = new sgt(l, l+r>>1, arr);
rt = new sgt(l+r>>1, r, arr);
pop_up();
}
void pop_up() {
this.sum = lt.sum + rt.sum;
this.max = Math.max(lt.max, rt.max);
this.min = Math.min(lt.min, rt.min);
if(lt.min<rt.min)
this.min_idx = lt.min_idx;
else if(lt.min>rt.min) this.min_idx = rt.min_idx;
else this.min = Math.min(lt.min_idx, rt.min_idx);
}
void push_down() {
if(this.lazy!=0) {
lt.sum+=lazy;
rt.sum+=lazy;
lt.max+=lazy;
lt.min+=lazy;
rt.max+=lazy;
rt.min+=lazy;
lt.lazy+=this.lazy;
rt.lazy+=this.lazy;
this.lazy = 0;
}
}
void change(int L, int R, int v) {
if(R<=l||r<=L) return;
if(L<=l&&r<=R) {
this.max+=v;
this.min+=v;
this.sum+=v*(r-l);
this.lazy+=v;
return;
}
push_down();
lt.change(L, R, v);
rt.change(L, R, v);
pop_up();
}
int query_max(int L, int R) {
if(L<=l&&r<=R) return this.max;
if(r<=L||R<=l) return Integer.MIN_VALUE;
push_down();
return Math.max(lt.query_max(L, R), rt.query_max(L, R));
}
int query_min(int L, int R) {
if(L<=l&&r<=R) return this.min;
if(r<=L||R<=l) return Integer.MAX_VALUE;
push_down();
return Math.min(lt.query_min(L, R), rt.query_min(L, R));
}
int query_sum(int L, int R) {
if(L<=l&&r<=R) return this.sum;
if(r<=L||R<=l) return 0;
push_down();
return lt.query_sum(L, R) + rt.query_sum(L, R);
}
int query_min_idx(int L, int R) {
if(L<=l&&r<=R) return this.min_idx;
if(r<=L||R<=l) return Integer.MAX_VALUE;
int a = lt.query_min_idx(L, R);
int b = rt.query_min_idx(L, R);
int aa = lt.query_min(L, R);
int bb = rt.query_min(L, R);
if(aa<bb) return a;
else if(aa>bb) return b;
return Math.min(a,b);
}
}
List<List<Integer>> convert(int arr[][]){
int n = arr.length;
List<List<Integer>> ret = new ArrayList<>();
for(int i=0;i<n;i++) {
ArrayList<Integer> tmp = new ArrayList<Integer>();
for(int j=0;j<arr[i].length;j++) tmp.add(arr[i][j]);
ret.add(tmp);
}
return ret;
}
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
public int GCD(int a, int b) {
if (b==0) return a;
return GCD(b,a%b);
}
public long GCD(long a, long b) {
if (b==0) return a;
return GCD(b,a%b);
}
}
static class ArrayUtils {
static final long seed = System.nanoTime();
static final Random rand = new Random(seed);
public static void sort(int[] a) {
shuffle(a);
Arrays.sort(a);
}
public static void shuffle(int[] a) {
for (int i = 0; i < a.length; i++) {
int j = rand.nextInt(i + 1);
int t = a[i];
a[i] = a[j];
a[j] = t;
}
}
public static void sort(long[] a) {
shuffle(a);
Arrays.sort(a);
}
public static void shuffle(long[] a) {
for (int i = 0; i < a.length; i++) {
int j = rand.nextInt(i + 1);
long t = a[i];
a[i] = a[j];
a[j] = t;
}
}
}
static class BIT{
int arr[];
int n;
public BIT(int a) {
n=a;
arr = new int[n];
}
int sum(int p) {
int s=0;
while(p>0) {
s+=arr[p];
p-=p&(-p);
}
return s;
}
void add(int p, int v) {
while(p<n) {
arr[p]+=v;
p+=p&(-p);
}
}
}
static class DSU{
int[] arr;
int[] sz;
public DSU(int n) {
arr = new int[n];
sz = new int[n];
for(int i=0;i<n;i++) arr[i] = i;
Arrays.fill(sz, 1);
}
public int find(int a) {
if(arr[a]!=a) arr[a] = find(arr[a]);
return arr[a];
}
public void union(int a, int b) {
int x = find(a);
int y = find(b);
if(x==y) return;
arr[y] = x;
sz[x] += sz[y];
}
public int size(int x) {
return sz[find(x)];
}
}
static class MinHeap<Key> implements Iterable<Key> {
private int maxN;
private int n;
private int[] pq;
private int[] qp;
private Key[] keys;
private Comparator<Key> comparator;
public MinHeap(int capacity){
if (capacity < 0) throw new IllegalArgumentException();
this.maxN = capacity;
n=0;
pq = new int[maxN+1];
qp = new int[maxN+1];
keys = (Key[]) new Object[capacity+1];
Arrays.fill(qp, -1);
}
public MinHeap(int capacity, Comparator<Key> c){
if (capacity < 0) throw new IllegalArgumentException();
this.maxN = capacity;
n=0;
pq = new int[maxN+1];
qp = new int[maxN+1];
keys = (Key[]) new Object[capacity+1];
Arrays.fill(qp, -1);
comparator = c;
}
public boolean isEmpty() { return n==0; }
public int size() { return n; }
public boolean contains(int i) {
if (i < 0 || i >= maxN) throw new IllegalArgumentException();
return qp[i] != -1;
}
public int peekIdx() {
if (n == 0) throw new NoSuchElementException("Priority queue underflow");
return pq[1];
}
public Key peek(){
if(isEmpty()) throw new NoSuchElementException("Priority queue underflow");
return keys[pq[1]];
}
public int poll(){
if(isEmpty()) throw new NoSuchElementException("Priority queue underflow");
int min = pq[1];
exch(1,n--);
down(1);
assert min==pq[n+1];
qp[min] = -1;
keys[min] = null;
pq[n+1] = -1;
return min;
}
public void update(int i, Key key) {
if (i < 0 || i >= maxN) throw new IllegalArgumentException();
if (!contains(i)) {
this.add(i, key);
}else {
keys[i] = key;
up(qp[i]);
down(qp[i]);
}
}
private void add(int i, Key x){
if (i < 0 || i >= maxN) throw new IllegalArgumentException();
if (contains(i)) throw new IllegalArgumentException("index is already in the priority queue");
n++;
qp[i] = n;
pq[n] = i;
keys[i] = x;
up(n);
}
private void up(int k){
while(k>1&&less(k,k/2)){
exch(k,k/2);
k/=2;
}
}
private void down(int k){
while(2*k<=n){
int j=2*k;
if(j<n&&less(j+1,j)) j++;
if(less(k,j)) break;
exch(k,j);
k=j;
}
}
public boolean less(int i, int j){
if (comparator == null) {
return ((Comparable<Key>) keys[pq[i]]).compareTo(keys[pq[j]]) < 0;
}
else {
return comparator.compare(keys[pq[i]], keys[pq[j]]) < 0;
}
}
public void exch(int i, int j){
int swap = pq[i];
pq[i] = pq[j];
pq[j] = swap;
qp[pq[i]] = i;
qp[pq[j]] = j;
}
@Override
public Iterator<Key> iterator() {
// TODO Auto-generated method stub
return null;
}
}
private static class InputReader
{
private InputStream stream;
private byte[] buf = new byte[1024];
private int zcurChar;
private int znumChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream)
{
this.stream = stream;
}
public int read()
{
if (znumChars == -1)
throw new InputMismatchException();
if (zcurChar >= znumChars)
{
zcurChar = 0;
try
{
znumChars = stream.read(buf);
} catch (IOException e)
{
throw new InputMismatchException();
}
if (znumChars <= 0)
return -1;
}
return buf[zcurChar++];
}
public int nextInt()
{
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
int res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String nextString()
{
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
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 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 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 nextString();
}
public interface SpaceCharFilter
{
public boolean isSpaceChar(int ch);
}
public int[] readIntArray(int n) {
int[] ret = new int[n];
for (int i = 0; i < n; i++) {
ret[i] = nextInt();
}
return ret;
}
}
static class Dumper {
static void print_int_arr(int[] arr) {
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
System.out.println("---------------------");
}
static void print_char_arr(char[] arr) {
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
System.out.println("---------------------");
}
static void print_double_arr(double[] arr) {
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
System.out.println("---------------------");
}
static void print_2d_arr(int[][] arr, int x, int y) {
for (int i = 0; i < x; i++) {
for (int j = 0; j < y; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
System.out.println();
System.out.println("---------------------");
}
static void print_2d_arr(boolean[][] arr, int x, int y) {
for (int i = 0; i < x; i++) {
for (int j = 0; j < y; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
System.out.println();
System.out.println("---------------------");
}
static void print(Object o) {
System.out.println(o.toString());
}
static void getc() {
System.out.println("here");
}
}
}
|
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
|
1029c6291be7a8933d93d672c4f8f97a
|
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 Scanner scammer = new Scanner(System.in);
public static int querry(int left, int right, boolean rite){
if(left == right)
return rite ? right + 1 : left - 1;
System.out.print("? ");
System.out.print(left);
System.out.print(" ");
System.out.println(right);
System.out.flush();
return scammer.nextInt();
}
public static void solve(boolean right, int smax, int n){
int p = right ? smax : 1, k = right ? n : smax, mid = (p + k) >> 1;
while(p <= k){
mid = (p + k) >> 1;
int outcome = right ? querry(smax, mid, true) : querry(mid, smax, false);
if(outcome == smax){
if(right)
k = mid - 1;
else
p = mid + 1;
}
else{
if(right)
p = ++mid;
else
k = --mid;
}
}
System.out.print("! ");
System.out.println(mid);
System.out.flush();
}
public static void solve_small(int n){
int x = querry(1, n, false);
System.out.printf("! %d\n", x == 1 ? 2 : 1);
System.out.flush();
}
public static void main(String[] args) {
int n = scammer.nextInt();
int smax = querry(1, n, false);
if(n < 3) {
solve_small(n);
return;
}
boolean right = false;
int drugi_max = querry(1, smax, false);
if(drugi_max != smax)
right = true;
solve(right, smax, n);
}
}
|
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
|
291047f22d9dc6d9d2899aa6cc70d711
|
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 {
public static void main(String[] args) throws Exception {
int n = i();
out.println("? 1 " + n);
out.flush();
int sec = i();
int sectemp = 0;
if (sec!=1) {
out.println("? 1 " + sec);
out.flush();
sectemp = i();
}
if (sec==sectemp && sectemp!=0) {
int front = 1; int end = sec-1;
while (end!=front) {
int mid = (int) Math.ceil((front+end)/2.0);
out.println("? " + mid + " " + sec);
out.flush();
int temp = i();
if (temp==sec) front = mid;
else end = mid-1;
}
out.println("! " + front);
}
else {
int front = sec+1; int end = n;
while (end!=front) {
int mid = (front+end)/2;
out.println("? " + sec + " " + mid);
out.flush();
int temp = i();
if (temp==sec) end = mid;
else front = mid+1;
}
out.println("! " + front);
}
in.close();
out.close();
}
static BufferedReader in;
static StringTokenizer st = new StringTokenizer("");
static PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
// static PrintWriter out;
/*
* static { try { in = Files.newBufferedReader(Paths.get("haybales.in")); out =
* new PrintWriter(new BufferedWriter(new FileWriter("haybales.out"))); } catch
* (Exception e) { in = new BufferedReader(new InputStreamReader(System.in)); }
* }
*/
static {
in = new BufferedReader(new InputStreamReader(System.in));
}
static void check() throws Exception {
while (!st.hasMoreTokens())
st = new StringTokenizer(in.readLine());
}
static String s() throws Exception {
check();
return st.nextToken();
}
static int i() throws Exception {
return Integer.parseInt(s());
}
static long l() throws Exception {
return Long.parseLong(s());
}
static double d() throws Exception {
return Double.parseDouble(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 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
|
557248660c5fbc25f0d45ecf0294e64d
|
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 {
private static Scanner cin;
private static int query(long l, long r) {
System.out.println("? " + l + " " + r);
System.out.flush();
return cin.nextInt();
}
public static void main(String[] args) {
cin = new Scanner(System.in);
int n = cin.nextInt();
int now = query(1, n), l, r;
if (now != 1 && query(1, now) == now) {
l = 1;
r = now - 1;
while (l < r) {
int mid = (l + r) >> 1;
if (query(mid + 1, now) == now) {
l = mid + 1;
} else {
r = mid;
}
}
} else {
l = now + 1;
r = n;
while (l < r) {
int mid = (l + r) >> 1;
if (query(now, mid) == now) {
r = mid;
} else {
l = mid + 1;
}
}
}
System.out.println("! " + 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 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
|
74b06601c2225e5368c1d52d2e42a667
|
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;
public class C2 {
public static boolean check(int l, int r, int v, BufferedReader in) throws IOException {
System.out.printf("? %d %d\n", l, r);
System.out.flush();
int ans = Integer.parseInt(in.readLine());
return ans == v;
}
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(in.readLine());
System.out.printf("? %d %d\n", 1, n);
System.out.flush();
int pos = Integer.parseInt(in.readLine());
int l, r;
if(pos > 1 && check(1, pos, pos, in)){
l = 1;
r = pos;
while(l < r){
int mid = (l + r + 1) >> 1;
if(mid < pos && check(mid, pos, pos, in)) l = mid;
else r = mid - 1;
}
System.out.printf("! %d\n", l);
System.out.flush();
} else{
l = pos;
r = n;
while (l < r) {
int mid = (l + r) >> 1;
if (pos < mid && check(pos, mid, pos, in)) r = mid;
else l = mid + 1;
}
System.out.printf("! %d\n", 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
|
89d48627528862611e01fbdfc80bbf04
|
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 GuessingTheGreatest {
public static void main(String[] args) throws IOException {
Scanner in = new Scanner(System.in);
int N = in.nextInt();
System.out.println("? 1 " + N);
System.out.flush();
int m = in.nextInt();
boolean left = false;
if (m > 1) {
System.out.println("? 1 " + m);
System.out.flush();
if (in.nextInt() == m) {
left = true;
}
}
if (left) {
System.out.println("! " + search1(in, 1, m, m));
} else {
System.out.println("! " + search2(in, m, m, N));
}
}
public static int search1(Scanner in, int l, int r, int m) {
if (l >= r) {
if (l > r) {
return -1;
}
if (l == m) {
return -1;
}
System.out.println("? " + l + " " + m);
System.out.flush();
if (in.nextInt() == m) {
return l;
}
return -1;
}
int mid = (l + r + 1) / 2;
if (mid == m) {
return search1(in, l, mid - 1, m);
}
System.out.println("? " + mid + " " + m);
System.out.flush();
if (in.nextInt() == m) {
int n = search1(in, mid + 1, r, m);
if (n != -1) {
return n;
}
return mid;
}
return search1(in, l, mid - 1, m);
}
public static int search2(Scanner in, int m, int l, int r) {
if (l >= r) {
if (l > r) {
return -1;
}
if (l == m) {
return -1;
}
System.out.println("? " + m + " " + l);
System.out.flush();
if (in.nextInt() == m) {
return l;
}
return -1;
}
int mid = (l + r + 1) / 2;
if (mid == m) {
return search2(in, m, mid + 1, r);
}
System.out.println("? " + m + " " + mid);
System.out.flush();
if (in.nextInt() == m) {
int n = search2(in, m, l, mid - 1);
if (n != -1) {
return n;
}
return mid;
}
return search2(in, m, mid + 1, 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 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
|
e80579a377a7ac42348f0c1f17f2ad46
|
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;
public class Solution {
private static boolean TESTS = false;
private final Input in;
private final PrintStream out;
public Solution(final Input in, final PrintStream out) {
this.in = in;
this.out = out;
}
public void solve() {
for (int test = 1, tests = TESTS ? in.nextInt() : 1; test <= tests; test++) {
final int n = in.nextInt();
final int max = query(1, n);
final boolean left = max != 1 && query(1, max) == max;
int i = -1;
if (left) {
int l = 1;
int r = max - 1;
while (l <= r) {
final int m = (l + r) >>> 1;
if (query(m, max) == max) {
l = m + 1;
i = m;
} else {
r = m - 1;
}
}
} else {
int l = max + 1;
int r = n;
while (l <= r) {
final int m = (l + r) >>> 1;
if (query(max, m) == max) {
r = m - 1;
i = m;
} else {
l = m + 1;
}
}
}
out.println("! " + i);
out.flush();
}
}
private int query(final int l, final int r) {
out.println("? " + l + " " + r);
out.flush();
return in.nextInt();
}
public static void main(final String[] args) {
final Input in = new Input();
final PrintStream out = new PrintStream(new BufferedOutputStream(System.out));
try {
new Solution(in, out).solve();
} finally {
out.flush();
}
}
private static final class Input {
private final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
private StringTokenizer tokenizer = new StringTokenizer("");
public String nextString() {
try {
while (!tokenizer.hasMoreTokens()) {
final String line = reader.readLine();
tokenizer = new StringTokenizer(line, " ");
}
return tokenizer.nextToken();
} catch (final IOException e) {
throw new RuntimeException(e);
}
}
public int nextInt() {
return Integer.parseInt(nextString());
}
public long nextLong() {
return Long.parseLong(nextString());
}
public double nextDouble() {
return Double.parseDouble(nextString());
}
public int[] nextInts(final int size) {
final int[] array = new int[size];
for (int i = 0; i < size; i++) {
array[i] = nextInt();
}
return array;
}
public long[] nextLongs(final int size) {
final long[] array = new long[size];
for (int i = 0; i < size; i++) {
array[i] = nextLong();
}
return array;
}
public double[] nextDoubles(final int size) {
final double[] array = new double[size];
for (int i = 0; i < size; i++) {
array[i] = nextDouble();
}
return array;
}
}
}
|
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
|
4d81aa830db8940966cf735db34042b8
|
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.lang.reflect.Type;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.*;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;
import java.util.concurrent.locks.LockSupport;
public class Main {
static class Task {
public static String roundS(double result, int scale) {
String fmt = String.format("%%.%df", scale);
return String.format(fmt, result);
// DecimalFormat df = new DecimalFormat("0.000000");
// double result = Double.parseDouble(df.format(result));
}
int rt(int x) {
if (x != fa[x]) {
int to = rt(fa[x]);
dp[x] ^= dp[fa[x]];
fa[x] = to;
return to;
}
return x;
}
void combine(int x, int y, int val) {
int rt1 = rt(x);
int rt2 = rt(y);
if (rt1 == rt2) return;
fa[rt1] = rt2;
dp[rt1] = dp[x] ^ dp[y] ^ val;
g--;
}
int fa[], dp[];
int g;
static int MAXN = 10000;
static Random rd = new Random(348957438574659L);
static int[] ch[],val,size,rnd,cnt;
static int len=0,rt=0;
// return new node, the node below s
static int rotate(int s,int d){
// child
int x=ch[s][d^1];
// give me grandson
ch[s][d^1] = ch[x][d];
// child become father
ch[x][d]=s;
// update size, update new son first
update(s);
update(x);
return x;
}
static void update(int s){
size[s] = size[ch[s][0]] + size[ch[s][1]] + cnt[s];
}
// 0 for left, 1 for right
static int cmp(int x,int num) {
if (val[x] == num) return -1;
return num < val[x] ? 0 : 1;
}
static int insert(int s,int num) {
if(s==0){
s=++len;
val[s]=num;size[s]=1;rnd[s]=rd.nextInt();cnt[s] = 1;
}else{
int d=cmp(s,num);
if(d!=-1) {
ch[s][d]=insert(ch[s][d],num);
// father's random should be greater
if(rnd[s]<rnd[ch[s][d]]) {
s=rotate(s,d^1);
}else {
update(s);
}
}else{
++cnt[s];++size[s];
}
}
return s;
}
static int del(int s,int num) {
int d = cmp(s, num);
if (d != -1) {
ch[s][d] = del(ch[s][d], num);
update(s);
}else if (ch[s][0] * ch[s][1] == 0) {
if(--cnt[s]==0){
s = ch[s][0] + ch[s][1];
}
} else {
int k = rnd[ch[s][0]] < rnd[ch[s][1]] ? 0 : 1;
// k points to smaller random value,then bigger one up
s = rotate(s, k);
// now the node with value num become the child
ch[s][k] = del(ch[s][k], num);
update(s);
}
return s;
}
static int getKth(int s, int k){
int lz = size[ch[s][0]];
if(k>=lz+1&&k<=lz+cnt[s]){
return val[s];
}else if(k<=lz){
return getKth(ch[s][0], k);
}else{
return getKth(ch[s][1], k-lz-cnt[s]);
}
}
static int getRank(int s,int value){
if(s==0)return 1;
if(value==val[s])return size[ch[s][0]] + 1;
if(value<val[s])return getRank(ch[s][0],value);
return getRank(ch[s][1],value)+size[ch[s][0]] + cnt[s];
}
static int getPre(int data){
int ans= -1;
int p=rt;
while(p>0){
if(data>val[p]){
if(ans==-1 || val[p]>val[ans])
ans=p;
p=ch[p][1];
}
else p=ch[p][0];
}
return ans!=-1?val[ans]:(-2147483647);
}
static int getNext(int data){
int ans= -1;
int p=rt;
while(p>0){
if(data<val[p]){
if(ans==-1 || val[p]<val[ans])
ans=p;
p=ch[p][0];
}
else p=ch[p][1];
}
return ans!=-1?val[ans]:2147483647;
}
static boolean find(int s,int num){
while(s!=0){
int d=cmp(s,num);
if(d==-1) return true;
else s=ch[s][d];
}
return false;
}
static int ans = -10000000;
static boolean findX(int s,int num){
while(s!=0){
if(val[s]<=num){
ans = num;
}
int d=cmp(s,num);
if(d==-1) return true;
else {
s = ch[s][d];
}
}
return false;
}
long gcd(long a,long b){
if(b==0) return a;
return gcd(b,a%b);
}
void linear_sort(int arr[]){
int d = 65536;
ArrayDeque bucket[] = new ArrayDeque[d];
for(int j=0;j<d;++j){
bucket[j] = new ArrayDeque();
}
for(int u:arr){
bucket[u%d].offer(u);
}
int pos = 0;
for(int j=0;j<d;++j){
while(bucket[j].size()>0) {
arr[pos++] = (int)bucket[j].pollFirst();
}
}
for(int u:arr){
bucket[u/d].offer(u);
}
pos = 0;
for(int j=0;j<d;++j){
while(bucket[j].size()>0) {
arr[pos++] = (int)bucket[j].pollFirst();
}
}
}
public void solve(int testNumber, InputReader in, PrintWriter out) {
// int a[] = {4,3,2,45,1,2,3,4,56,7,2,1,2};
// linear_sort(a);
// for(int u:a){
// out.println(u);
// }
int t = 1;
//
//
outer:for(int j=0;j<t;++j){
int n = in.nextInt();
int l = 1;
int r = n;
out.println("? " + l + " " + r);
out.flush();
int pos = in.nextInt();
boolean right = true;
if(pos!=1) {
out.println("? " + 1 + " " + pos);
out.flush();
int pos1 = in.nextInt();
if (pos1 == pos) {
// left
right = false;
}
}
int lo = 0 ;int hi = 0;
if(right){
lo = pos+1;
hi = r;
while(lo<hi){
int mi = lo+hi>>1;
out.println("? " + pos + " " + mi);
out.flush();
int pp = in.nextInt();
if(pp==pos){
hi = mi;
}else{
lo = mi + 1;
}
}
}else{
lo = 1;
hi = pos-1;
while(lo<hi){
int mi = (lo+hi+1)>>1;
out.println("? " + mi + " " + pos);
out.flush();
int pp = in.nextInt();
if(pp==pos){
lo = mi;
}else{
hi = mi-1;
}
}
}
out.println("! "+lo);
out.flush();
}
// while(true) {
// int n = in.nextInt();
//
// int m =in.nextInt();
//
// fa = new int[n];
// dp = new int[n];
// for(int i=0;i<n;++i){
// fa[i] = i;
// }
// g = n;
// int c = 0;
// int as[] = new int[n];
// int bs[] = new int[n];
// char xs[] = new char[n];
//
// int at = -1;
// Set<Integer> st = new HashSet<>();
//
// for (int i = 0; i < n; ++i) {
// String line = in.next();
// int p = 0;
// int a = 0;
// while(Character.isDigit(line.charAt(p))){
// a = a*10 + (line.charAt(p)-'0'); p++;
// }
// char x = line.charAt(p++);
//
// int b = 0;
// while(p<line.length()){
// b = b*10 + (line.charAt(p)-'0'); p++;
// }
//
// as[i] = a;
// xs[i] = x;
// bs[i] = b;
//
// if(x=='='){
// int r1 = rt(a); int r2 = rt(b);
// if(r1==r2){
// if(dp[a]!=dp[b]){
// c++;
// at = i;
// }
// }else {
// combine(a, b, 0);
// }
// }else if(x=='<'){
// int r1 = rt(a); int r2 = rt(b);
// if(r1==r2){
// if(dp[a]>=dp[b]){
// c++;
// at = i;
// }
// }else {
// combine(a, b, -1);
// }
// }else{
// int r1 = rt(a); int r2 = rt(b);
// if(r1==r2){
// if(dp[a]<=dp[b]){
// c++;
// at = i;
// }
// }else {
// combine(a, b, 1);
// }
// }
//
//
// }
// if(g==1||c>=2){
// out.println("Impossible");
// continue;
// }
//
//
// for(int xuan: st){
//
//
//
//
// }
//
//
//
//
//
//
// }
}
static long mul(long a, long b, long p)
{
long res=0,base=a;
while(b>0)
{
if((b&1L)>0)
res=(res+base)%p;
base=(base+base)%p;
b>>=1;
}
return res;
}
static long mod_pow(long k,long n,long p){
long res = 1L;
long temp = k%p;
while(n!=0L){
if((n&1L)==1L){
res = mul(res,temp,p);
}
temp = mul(temp,temp,p);
n = n>>1L;
}
return res%p;
}
public static double roundD(double result, int scale){
BigDecimal bg = new BigDecimal(result).setScale(scale, RoundingMode.UP);
return bg.doubleValue();
}
}
private static void solve() {
InputStream inputStream = System.in;
// InputStream inputStream = null;
// try {
// inputStream = new FileInputStream(new File("D:\\chrome_download\\travel_restrictions_input.txt"));
// } catch (FileNotFoundException e) {
// e.printStackTrace();
// }
OutputStream outputStream = System.out;
// OutputStream outputStream = null;
// File f = new File("D:\\chrome_download\\travel_restrictions_output.txt");
// try {
// f.createNewFile();
// } catch (IOException e) {
// e.printStackTrace();
// }
// try {
// outputStream = new FileOutputStream(f);
// } catch (FileNotFoundException e) {
// e.printStackTrace();
// }
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
Task task = new Task();
task.solve(1, in, out);
out.close();
}
public static void main(String[] args) {
// new Thread(null, () -> solve(), "1", (1 << 10 ) ).start();
solve();
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String nextLine() {
String line = null;
try {
line = reader.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
return line;
}
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 char nextChar() {
return next().charAt(0);
}
public int[] nextArray(int n) {
int res[] = new int[n];
for (int i = 0; i < n; ++i) {
res[i] = nextInt();
}
return res;
}
public long nextLong() {
return Long.parseLong(next());
}
public 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 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
|
9a5fcb9c6e651d12887f867ebdb4a11e
|
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
{
/*
HashMap<> map=new HashMap<>();
TreeMap<> map=new TreeMap<>();
map.put(p,map.getOrDefault(p,0)+1);
for(Map.Entry<> mx:map.entrySet()){
int v=mx.getValue(),k=mx.getKey();
}
ArrayList<Pair<Character,Integer>> l=new ArrayList<>();
ArrayList<> l=new ArrayList<>();
HashSet<> has=new HashSet<>();*/
PrintWriter out;
FastReader sc;
int mod=(int)(1e9+7);
int maxint= Integer.MAX_VALUE;
int minint= Integer.MIN_VALUE;
long maxlong=Long.MAX_VALUE;
long minlong=Long.MIN_VALUE;
public void sol(){
int testCase=1;
while(testCase-->0){
int n=ni(),l=1,r=n;
boolean f=true;
pl("? "+l+" "+r);
out.flush();
int p=ni(),a=0;
if(p!=1){
pl("? "+l+" "+p);
out.flush();
a=ni();
if(a!=p){
f=false;
}}else{
f=false;
}
if(f){
r=p;
while(r-l>1){
int mid=l+(r-l)/2;
pl("? "+mid+" "+p);
out.flush();
a=ni();
if(a==p){
l=mid;
}else{
r=mid-1;
}
}if(l==r){
pl("! "+l);
out.flush();
}else{
pl("? "+l+" "+r);
out.flush();
a=ni();
if(a==l)pl("! "+r);
else pl("! "+l);
out.flush();
}
}else{
l=p;
while(r-l>1){
int mid=l+(r-l)/2;
pl("? "+p+" "+mid);
out.flush();
a=ni();
if(a==p){
r=mid;
}else{
l=mid+1;
}
}if(l==r){
pl("! "+l);
out.flush();
}else{
pl("? "+l+" "+r);
out.flush();
a=ni();
if(a==l)pl("! "+r);
else pl("! "+l);
out.flush();
}
}
}
}
public static void main(String[] args)
{
Main g=new Main();
g.out=new PrintWriter(System.out);
g.sc=new FastReader();
g.sol();
g.out.flush();
}
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
} public int ni(){
return sc.nextInt();
}public long nl(){
return sc.nextLong();
}public double nd(){
return sc.nextDouble();
}public char[] rl(){
return sc.nextLine().toCharArray();
}public String rl1(){
return sc.nextLine();
}
public void pl(Object s){
out.println(s);
}public void ex(){
out.println();
}
public void pr(Object s){
out.print(s);
}public String next(){
return sc.next();
}public long abs(long x){
return Math.abs(x);
}
public int abs(int x){
return Math.abs(x);
}
public double abs(double x){
return Math.abs(x);
}
public long pow(long x,long y){
return (long)Math.pow(x,y);
}
public int pow(int x,int y){
return (int)Math.pow(x,y);
}
public double pow(double x,double y){
return Math.pow(x,y);
}public long min(long x,long y){
return (long)Math.min(x,y);
}
public int min(int x,int y){
return (int)Math.min(x,y);
}
public double min(double x,double y){
return Math.min(x,y);
}public static int gcd(int a, int 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);
}
}void sort(long[] a) {
ArrayList<Long> l = new ArrayList<>();
for (long i : a) {
l.add(i);
}
Collections.sort(l);
for (int i = 0; i < a.length; i++) {
a[i] = l.get(i);
}
}void sort(double[] a) {
ArrayList<Double> l = new ArrayList<>();
for (double i : a) {
l.add(i);
}
Collections.sort(l);
for (int i = 0; i < a.length; i++) {
a[i] = l.get(i);
}
}int swap(int a,int b){
return a;
}long swap(long a,long b){
return a;
}double swap(double a,double b){
return a;
}
boolean isPowerOfTwo (int x)
{
return x!=0 && ((x&(x-1)) == 0);
}boolean isPowerOfTwo (long x)
{
return x!=0 && ((x&(x-1)) == 0);
}public long max(long x,long y){
return (long)Math.max(x,y);
}
public int max(int x,int y){
return (int)Math.max(x,y);
}
public double max(double x,double y){
return Math.max(x,y);
}long sqrt(long x){
return (long)Math.sqrt(x);
}int sqrt(int x){
return (int)Math.sqrt(x);
}void input(int[] ar,int n){
for(int i=0;i<n;i++)ar[i]=ni();
}void input(long[] ar,int n){
for(int i=0;i<n;i++)ar[i]=nl();
}void fill(int[] ar,int k){
Arrays.fill(ar,k);
}void yes(){
pl("YES");
}void no(){
pl("NO");
}
int[] sieve(int n)
{
boolean prime[] = new boolean[n+1];
int[] k=new int[n+1];
for(int i=0;i<=n;i++) {
prime[i] = true;
k[i]=i;
}
for(int p = 2; p <=n; p++)
{
if(prime[p] == true)
{
// sieve[p]=p;
for(int i = p*2; i <= n; i += p) {
prime[i] = false;
// sieve[i]=p;
while(k[i]%(p*p)==0){
k[i]/=(p*p);
}
}
}
}return k;
}int strSmall(int[] arr, int target)
{
int start = 0, end = arr.length-1;
int ans = -1;
while (start <= end) {
int mid = (start + end) / 2;
if (arr[mid] >= target) {
end = mid - 1;
}
else {
ans = mid;
start = mid + 1;
}
}
return ans;
} int strSmall(ArrayList<Integer> arr, int target)
{
int start = 0, end = arr.size()-1;
int ans = -1;
while (start <= end) {
int mid = (start + end) / 2;
if (arr.get(mid) > target) {
start = mid + 1;
ans=start;
}
else {
end = mid - 1;
}
}
return ans;
}
// public static class Pair implements Comparable<Pair> {
// int x;
// int y;
// public Pair(int x, int 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);
// }
// }
}
|
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
|
6cbd6e2ffc97a83dd117d5059707314c
|
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.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Scanner;
public class Main {
static Scanner in = new Scanner(System.in);
// static Scanner in = new Scanner( new File("javain.txt"));
public static void main(String[] args) throws FileNotFoundException {
if(args.length > 0){
in = new Scanner( new File("javain.txt"));
}
int t = 1;
for(int i = 0; i < t; i++){
solve();
}
}
public static void solve(){
int n = in.nextInt();
int l = 1, r = n;
System.out.println("? " + l + " " + r);
System.out.flush();
int second = in.nextInt();
int ans;
if(second != 1){
System.out.println("? " + l + " " + second);
System.out.flush();
if(in.nextInt() == second){
r = second;
while(l < r - 1){
int mid = (l + r) / 2;
System.out.println("? " + mid + " " + second);
System.out.flush();
if(in.nextInt() == second){
l = mid ;
}else{
r = mid ;
}
}
System.out.println("! " + l);
return ;
}
}
l = second;
while(l < r - 1){
int mid = (l + r ) / 2;
System.out.println("? " + second + " " + mid);
System.out.flush();
if(in.nextInt() == second){
r = mid ;
}else{
l = mid ;
}
}
System.out.println("! " + 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 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
|
7cfc155444160d37edeff915b7a79116
|
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.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Formatter;
import java.util.Random;
/**
* Coder: SumitRaut
* Date: 27-02-2021 14:23
*/
public class Main {
public static void main(String[] args) throws IOException {
Fs = new FastReader();
out = new PrintWriter(System.out);
int n = Fs.nextInt();
out.println("? " + 1 + " " + n);
out.flush();
int id = Fs.nextInt();
boolean done=false;
int l=1,r=n;
if(id!=1) {
out.println("? "+1+" "+id);
out.flush();
if(Fs.nextInt()==id) {
done=true;
r=id-1;
while(l<r) {
int md=(l+r+1)>>1;
out.println("? "+md+" "+id);
out.flush();
int curif=Fs.nextInt();
if(curif==id) l=md;
else r=md-1;
}
}
}
if(!done) {
l=id+1;
while(l<r) {
int md=(l+r)>>1;
out.println("? "+id+" "+md);
out.flush();
int curif=Fs.nextInt();
if(curif==id) r=md;
else l=md+1;
}
}
out.print("! " + r);
out.flush();
out.close();
}
static PrintWriter out;
static FastReader Fs;
static final Random random = new Random();
static void ruffleSort(int[] a) {
int n = a.length;
for (int i = 0; i < n; ++i) {
int oi = random.nextInt(n), tmp = a[oi];
a[oi] = a[i];
a[i] = tmp;
}
Arrays.sort(a);
}
static class FastReader {
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public FastReader() {
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public FastReader(String file_name) throws IOException {
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String nextLine() throws IOException {
byte[] buf = new byte[64]; // 64 line length
int cnt = 0, c;
while ((c = read()) != -1) {
if (c == '\n') {
if (cnt != 0) {
break;
} else {
continue;
}
}
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public String next() throws IOException {
byte[] buf = new byte[64]; // 64 line length
int cnt = 0, c;
while ((c = read()) != -1) {
if (c == ' ' || c == '\n') {
if (cnt != 0) {
break;
} else {
continue;
}
}
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException {
int ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException {
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException {
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (c == '.') {
while ((c = read()) >= '0' && c <= '9') {
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
public int[] readArray(int n) throws IOException {
int[] a = new int[n];
for (int i = 0; i < n; ++i)
a[i] = nextInt();
return a;
}
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 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
|
b639401edafe3b2305c2543d82b8df91
|
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.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Stack;
import java.util.StringTokenizer;
import static java.lang.Math.*;
public class C {
static FastScanner sc;
static PrintWriter pw;
public static void main(String[] args) {
sc = new FastScanner();
pw = new PrintWriter(System.out);
int T = 1;
while (T-- > 0) {
solve();
}
pw.close();
}
static HashMap<Integer, HashMap<Integer, Integer>> rangeMap = new HashMap<>();
static void solve() {
int n = sc.nextInt();
int low = 1, high = n;
rangeMap.clear();
if(high - low > 1) {
int secondMax = getQuery(low, high);
if(secondMax != high) {
int secondMax2 = getQuery(secondMax, high);
if(secondMax2 == secondMax) {
low = secondMax + 1;
} else {
high = secondMax - 1;
}
} else {
high = secondMax - 1;
}
while(high - low > 1) {
int mid = (low + high) / 2;
int ind = getQuery(min(secondMax, mid), max(secondMax, mid));
if(ind == secondMax) {
if(mid > secondMax) {
high = mid;
} else {
low = mid;
}
} else {
if(mid > secondMax) {
low = mid + 1;
} else {
high = mid - 1;
}
}
}
}
int ans = -1;
if(high == low + 1) {
int notAnswer = getQuery(low, high);
ans = notAnswer == low ? high : low;
}else {
ans = low;
}
System.out.println("! "+ans);
}
static int getQuery(int low, int high) {
if(rangeMap.containsKey(low)) {
if(rangeMap.get(low).containsKey(high)) {
return rangeMap.get(low).get(high);
}
}
System.out.println("? "+low+" "+high);
int num = sc.nextInt();
HashMap<Integer, Integer> map = rangeMap.getOrDefault(low, new HashMap<>());
map.put(high, num);
rangeMap.put(low, map);
return num;
}
static int getMove(int low, int ind, int high) {
if(ind <= low) {
return 1;
}
int left = getQuery(low, ind);
if(high <= ind) {
return -1;
}
int right = getQuery(ind, high);
if(left == ind) {
return -1;
}
return 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 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 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
|
847fd622269b60a5e99b73537a0a203d
|
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.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Stack;
import java.util.StringTokenizer;
import static java.lang.Math.*;
public class C {
static FastScanner sc;
static PrintWriter pw;
public static void main(String[] args) {
sc = new FastScanner();
pw = new PrintWriter(System.out);
int T = 1;
while (T-- > 0) {
solve();
}
pw.close();
}
static HashMap<Integer, HashMap<Integer, Integer>> rangeMap = new HashMap<>();
static void solve() {
int n = sc.nextInt();
int low = 1, high = n;
rangeMap.clear();
boolean leftDir = false;
if(high - low > 1) {
int secondMax = getQuery(low, high);
if(secondMax != high) {
int secondMax2 = getQuery(secondMax, high);
if(secondMax2 == secondMax) {
low = secondMax + 1;
leftDir = true;
} else {
high = secondMax - 1;
}
} else {
high = secondMax - 1;
}
while(high - low > 1) {
int mid = (low + high) / 2;
int ind = getQuery(min(secondMax, mid), max(secondMax, mid));
if(ind == secondMax) {
if(leftDir) {
high = mid;
} else {
low = mid;
}
} else {
if(leftDir) {
low = mid + 1;
} else {
high = mid - 1;
}
}
}
}
int ans = -1;
if(high == low + 1) {
int notAnswer = getQuery(low, high);
ans = notAnswer == low ? high : low;
}else {
ans = low;
}
System.out.println("! "+ans);
}
static int getQuery(int low, int high) {
if(rangeMap.containsKey(low)) {
if(rangeMap.get(low).containsKey(high)) {
return rangeMap.get(low).get(high);
}
}
System.out.println("? "+low+" "+high);
int num = sc.nextInt();
HashMap<Integer, Integer> map = rangeMap.getOrDefault(low, new HashMap<>());
map.put(high, num);
rangeMap.put(low, map);
return num;
}
static int getMove(int low, int ind, int high) {
if(ind <= low) {
return 1;
}
int left = getQuery(low, ind);
if(high <= ind) {
return -1;
}
int right = getQuery(ind, high);
if(left == ind) {
return -1;
}
return 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 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 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
|
3a231cd6f018b7bc00596939a45e29e5
|
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 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 class Pair
{
int f,s;
Pair(int f,int s)
{
this.f=f;
this.s=s;
}
}
static FastReader fs=new FastReader();
public static int query(int l,int r)
{
if(l>=r)return 0;
System.out.println("? "+l+" "+r);
return fs.nextInt();
}
public static void main(String args[])
{
//FastReader fs=new FastReader();
PrintWriter pw=new PrintWriter(System.out);
int n=fs.nextInt();
int ind=query(1,n);
if(ind==1||query(1,ind)!=ind)
{
int l=ind,r=n;
while(r-l>1)
{
int mid=(l+r)/2;
int in=query(ind,mid);
if(in==ind)
r=mid;
else
l=mid;
}
pw.println("! "+r);
}
else
{
int l=1,r=ind;
while(r-l>1)
{
int mid=(l+r)/2;
int in=query(mid,ind);
if(in!=ind)
r=mid;
else
l=mid;
}
pw.println("! "+l);
}
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 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
|
8fd1f9a28d31f37970872342a2e632a0
|
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.math.BigInteger;
import java.util.*;
import java.util.concurrent.TimeUnit;
public class c1486 implements Runnable{
public static void main(String[] args) {
try{
new Thread(null, new c1486(), "process", 1<<26).start();
}
catch(Exception e){
System.out.println(e);
}
}
public void run() {
FastReader scan = new FastReader();
PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out), true);
//PrintWriter out = new PrintWriter("file.out");
Task solver = new Task();
//int t = scan.nextInt();
int t = 1;
for(int i = 1; i <= t; i++) solver.solve(i, scan, out);
out.close();
}
static class Task {
static final int oo = Integer.MAX_VALUE;
static final long OO = Long.MAX_VALUE;
public void solve(int testNumber, FastReader sc, PrintWriter out) {
int N = sc.nextInt();
out.println("? 1 " + N);
int secondMax = sc.nextInt();
boolean left = false;
if(secondMax == 1) {
left = false;
} else if (secondMax == N) {
left = true;
} else {
out.println("? 1 " + secondMax);
int t = sc.nextInt();
if(t == secondMax) {
left = true;
}
}
int L = 0, R = (N - secondMax);
if(left) {
R = secondMax - 1;
}
while(L < R - 1) {
int M = (L + R) / 2;
int qM = secondMax + M;
if(left) {
qM = secondMax - M;
}
out.println("? " + Math.min(qM, secondMax) + " " + Math.max(qM, secondMax));
int t = sc.nextInt();
if(t == secondMax) {
// within the range queried
R = M;
} else {
L = M+1;
}
}
if(L != R) {
if(left) {
int tL = secondMax - R;
int tR = secondMax - L;
L = tL; R = tR;
} else {
L = secondMax + L;
R = secondMax + R;
}
out.println("? " + L + " " + R);
if(sc.nextInt() == L) {
out.println("! "+ R);
} else {
out.println("! " + L);
}
return;
}
if(left)
out.println("! " + (secondMax - L));
else
out.println("! " + (secondMax + L));
}
}
static long modInverse(long N, long MOD) {
return binpow(N, MOD - 2, MOD);
}
static long modDivide(long a, long b, long MOD) {
a %= MOD;
return (binpow(b, MOD-2, MOD) * a) % MOD;
}
static long binpow(long a, long b, long m) {
a %= m;
long res = 1;
while (b > 0) {
if ((b & 1) == 1)
res = res * a % m;
a = a * a % m;
b >>= 1;
}
return res;
}
static int[] reverse(int a[])
{
int[] b = new int[a.length];
for (int i = 0, j = a.length; i < a.length; i++, j--) {
b[j - 1] = a[i];
}
return b;
}
static long[] reverse(long a[])
{
long[] b = new long[a.length];
for (int i = 0, j = a.length; i < a.length; i++, j--) {
b[j - 1] = a[i];
}
return b;
}
static void shuffle(Object[] a) {
Random get = new Random();
for (int i = 0; i < a.length; i++) {
int r = get.nextInt(a.length);
Object temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
static void shuffle(int[] a) {
Random get = new Random();
for (int i = 0; i < a.length; i++) {
int r = get.nextInt(a.length);
int temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
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 class tup implements Comparable<tup>, Comparator<tup>{
int a, b;
tup(int a,int b){
this.a=a;
this.b=b;
}
public tup() {
}
@Override
public int compareTo(tup o){
return Integer.compare(b,o.b);
}
@Override
public int compare(tup o1, tup o2) {
return Integer.compare(o1.b, o2.b);
}
@Override
public int hashCode() {
return Objects.hash(a, b);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
tup other = (tup) obj;
return a==other.a && b==other.b;
}
@Override
public String toString() {
return a + " " + b;
}
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
public FastReader(String s) throws FileNotFoundException {
br = new BufferedReader(new FileReader(new File(s)));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
int[] readArray(int size) {
int[] a = new int[size];
for(int i = 0; i < size; i++) {
a[i] = nextInt();
}
return a;
}
long[] readLongArray(int size) {
long[] a = new long[size];
for(int i = 0; i < size; i++) {
a[i] = nextLong();
}
return a;
}
}
static void dbg(int[] arr) {
System.out.println(Arrays.toString(arr));
}
static void dbg(long[] arr) {
System.out.println(Arrays.toString(arr));
}
static void dbg(boolean[] arr) {
System.out.println(Arrays.toString(arr));
}
static void dbg(Object... args) {
for (Object arg : args)
System.out.print(arg + " ");
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 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
|
d258806a1e45da77a550cc81fe225011
|
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 C {
static int ans = Integer.MAX_VALUE;
static String str = "";
static int[] dp;
public static void main(String[] args) throws IOException {
FastScanner fs=new FastScanner();
PrintWriter out = new PrintWriter(System.out);
// int T = 1;
// int T=fs.nextInt();
// for (int tt=0; tt<T; tt++) {
// }
int n = fs.nextInt();
System.out.println("? 1 "+n);
System.out.flush();
int last = fs.nextInt();
if (n==2) {
if (last==1) {
System.out.println("! 2");
}
else {
System.out.println("! 1");
}
}
else {
int cur = 0;
if (last==1) {
cur = last;
}
else {
System.out.println("? 1 "+last);
System.out.flush();
cur = fs.nextInt();
}
if (cur==last && cur!=1) {
int left = 1, right = cur-1, ans=-1;
while (left<=right) {
int mid = (left+right)/2;
System.out.println("? "+mid+" "+last);
System.out.flush();
int res = fs.nextInt();
if (res==last) {
ans=mid;
left=mid+1;
}
else {
right=mid-1;
}
}
System.out.println("! "+ans);
}
else {
int left = last+1, right = n, ans=-1;
while (left<=right) {
int mid = (left+right)/2;
System.out.println("? "+last+" "+mid);
System.out.flush();
int res = fs.nextInt();
if (res==last) {
ans=mid;
right=mid-1;
}
else {
left=mid+1;
}
}
System.out.println("! "+ans);
}
}
}
static final Random random=new Random();
static void ruffleSort(int[] a) {
int n=a.length;//shuffle, then sort
for (int i=0; i<n; i++) {
int oi=random.nextInt(n), temp=a[oi];
a[oi]=a[i]; a[i]=temp;
}
Arrays.sort(a);
}
static class FastScanner {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st=new StringTokenizer("");
String next() {
while (!st.hasMoreTokens())
try {
st=new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
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
|
bb7ac74d626446a6d55acc85ae29cc9f
|
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.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.*;
/**
* @author Mubtasim Shahriar
*/
public class Cr703A {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader sc = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
Solver solver = new Solver();
// int t = sc.nextInt();
int t = 1;
while (t-- != 0) {
solver.solve(sc, out);
}
out.close();
}
static class Solver {
public void solve(InputReader sc, PrintWriter out) {
int n = sc.nextInt();
int l = 1;
int r = n;
int secMaxAt = query(sc,l,r);
if(l+1==r) {
System.out.println("! " + (3-secMaxAt));
System.out.flush();
return;
}
if(secMaxAt==1) {
work(1,n,sc,true);
} else {
int leftAt = query(sc,1,secMaxAt);
if(leftAt==secMaxAt) {
work(1,secMaxAt,sc,false);
} else {
work(secMaxAt,n,sc,true);
}
}
}
private void work(int l, int r, InputReader sc, boolean searchRight) {
if(searchRight) {
int beLeft = l;
l++;
int at = -1;
while(l<=r) {
int mid = (l+r)>>1;
int secMax = query(sc,beLeft,mid);
if(secMax==beLeft) {
at = mid;
r = mid-1;
} else {
l = mid+1;
}
}
if(at==-1) throw new RuntimeException();
System.out.println("! " + at);
System.out.flush();
} else {
int beRight = r;
r--;
int at = -1;
while(l<=r) {
int mid = (l+r)>>1;
int secMax = query(sc,mid,beRight);
if(secMax==beRight) {
at = mid;
l = mid+1;
} else {
r = mid-1;
}
}
if(at==-1) throw new RuntimeException();
System.out.println("! " + at);
System.out.flush();
}
}
private void putt(HashMap<Integer, HashMap<Integer, Integer>> map, int f, int s, int val) {
if(!map.containsKey(f))map.put(f,new HashMap<>());
HashMap<Integer,Integer> sec = map.get(f);
if(!sec.containsKey(s)) sec.put(s,val);
}
private int gett(HashMap<Integer, HashMap<Integer, Integer>> map, int l, int r) {
if(!map.containsKey(l)) return -1;
HashMap<Integer,Integer> sec = map.get(l);
if(!sec.containsKey(r)) return -1;
return sec.get(r);
}
private int query(InputReader sc, int ql, int qr) {
System.out.println("? " + ql + " " + qr);
System.out.flush();
return sc.nextInt();
}
}
static class SegMax {
int leftMost, rightMost, mid;
boolean leaf;
int max;
int maxIdx;
SegMax lchild, rchild;
SegMax(int l, int r, int[] arr) {
leftMost = l;
rightMost = r;
mid = (l + r) >> 1;
leaf = l == r;
if (leaf) {
max = arr[l];
maxIdx = l;
} else {
lchild = new SegMax(l, mid, arr);
rchild = new SegMax(mid + 1, r, arr);
max = Math.max(lchild.max, rchild.max);
}
}
int query(int l, int r) {
if (l > rightMost || r < leftMost) return Integer.MIN_VALUE;
if (l <= leftMost && rightMost <= r) return max;
return Math.max(lchild.query(l, r), rchild.query(l, r));
}
}
static void sort(int[] arr) {
Random rand = new Random();
int n = arr.length;
for (int i = 0; i < n; i++) {
int idx = rand.nextInt(n);
if (idx == i) continue;
arr[i] ^= arr[idx];
arr[idx] ^= arr[i];
arr[i] ^= arr[idx];
}
Arrays.sort(arr);
}
static void sort(long[] arr) {
Random rand = new Random();
int n = arr.length;
for (int i = 0; i < n; i++) {
int idx = rand.nextInt(n);
if (idx == i) continue;
arr[i] ^= arr[idx];
arr[idx] ^= arr[i];
arr[i] ^= arr[idx];
}
Arrays.sort(arr);
}
static void sortDec(int[] arr) {
Random rand = new Random();
int n = arr.length;
for (int i = 0; i < n; i++) {
int idx = rand.nextInt(n);
if (idx == i) continue;
arr[i] ^= arr[idx];
arr[idx] ^= arr[i];
arr[i] ^= arr[idx];
}
Arrays.sort(arr);
int l = 0;
int r = n - 1;
while (l < r) {
arr[l] ^= arr[r];
arr[r] ^= arr[l];
arr[l] ^= arr[r];
l++;
r--;
}
}
static void sortDec(long[] arr) {
Random rand = new Random();
int n = arr.length;
for (int i = 0; i < n; i++) {
int idx = rand.nextInt(n);
if (idx == i) continue;
arr[i] ^= arr[idx];
arr[idx] ^= arr[i];
arr[i] ^= arr[idx];
}
Arrays.sort(arr);
int l = 0;
int r = n - 1;
while (l < r) {
arr[l] ^= arr[r];
arr[r] ^= arr[l];
arr[l] ^= arr[r];
l++;
r--;
}
}
static class InputReader {
private boolean finished = false;
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 peek() {
if (numChars == -1) {
return -1;
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
return -1;
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar];
}
public 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 String nextString() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
if (Character.isValidCodePoint(c)) {
res.appendCodePoint(c);
}
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private String readLine0() {
StringBuilder buf = new StringBuilder();
int c = read();
while (c != '\n' && c != -1) {
if (c != '\r') {
buf.appendCodePoint(c);
}
c = read();
}
return buf.toString();
}
public String readLine() {
String s = readLine0();
while (s.trim().length() == 0) {
s = readLine0();
}
return s;
}
public String readLine(boolean ignoreEmptyLines) {
if (ignoreEmptyLines) {
return readLine();
} else {
return readLine0();
}
}
public BigInteger readBigInteger() {
try {
return new BigInteger(nextString());
} catch (NumberFormatException e) {
throw new InputMismatchException();
}
}
public char nextCharacter() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
return (char) c;
}
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 boolean isExhausted() {
int value;
while (isSpaceChar(value = peek()) && value != -1) {
read();
}
return value == -1;
}
public String next() {
return nextString();
}
public SpaceCharFilter getFilter() {
return filter;
}
public void setFilter(SpaceCharFilter filter) {
this.filter = filter;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
public int[] nextIntArray(int n) {
int[] array = new int[n];
for (int i = 0; i < n; ++i) array[i] = nextInt();
return array;
}
public int[] nextSortedIntArray(int n) {
int array[] = nextIntArray(n);
Arrays.sort(array);
return array;
}
public int[] nextSumIntArray(int n) {
int[] array = new int[n];
array[0] = nextInt();
for (int i = 1; i < n; ++i) array[i] = array[i - 1] + nextInt();
return array;
}
public long[] nextLongArray(int n) {
long[] array = new long[n];
for (int i = 0; i < n; ++i) array[i] = nextLong();
return array;
}
public long[] nextSumLongArray(int n) {
long[] array = new long[n];
array[0] = nextInt();
for (int i = 1; i < n; ++i) array[i] = array[i - 1] + nextInt();
return array;
}
public long[] nextSortedLongArray(int n) {
long array[] = nextLongArray(n);
Arrays.sort(array);
return array;
}
}
}
|
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
|
eeab329588d304902cff37d589216d4f
|
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.*;
/**
*
* @Har_Har_Mahadev
*/
public class C {
private static long INF = 2000000000000000000L, M = 1000000007, MM = 998244353;
private static int N = 0;
public static void process() throws IOException {
int n = sc.nextInt();
int smax = ask(1, n);
int ans = 0;
if(smax == ask(1, smax)) {
int L = 1, U = smax - 1;
while(L <= U){
int m = (L + U) / 2;
if(ask(m,smax) == smax){
ans = m;
L = m + 1;
}
else{
U = m - 1;
}
}
}
else {
int L = smax + 1, U = n;
while(L <= U){
int m = (L + U) / 2;
if(ask(smax,m) == smax){
ans = m;
U = m - 1;
}
else{
L = m + 1;
}
}
}
pp(ans);
}
private static void pp(int i) {
println("! "+i);
}
private static int ask(int i, int n) throws IOException {
if(i == n)return -1;
pflush("? "+i+" "+n);
int val = sc.nextInt();
return val;
}
//=============================================================================
//--------------------------The End---------------------------------
//=============================================================================
static FastScanner sc;
static PrintWriter out;
public static void main(String[] args) throws IOException {
boolean oj = true;
if (oj) {
sc = new FastScanner();
out = new PrintWriter(System.out);
} else {
sc = new FastScanner(100);
out = new PrintWriter("output.txt");
}
int t = 1;
// t = sc.nextInt();
while (t-- > 0) {
process();
}
out.flush();
out.close();
}
static class Pair implements Comparable<Pair> {
int x, y;
Pair(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public int compareTo(Pair o) {
return Integer.compare(this.x, o.x);
}
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (!(o instanceof Pair)) return false;
// Pair key = (Pair) o;
// return x == key.x && y == key.y;
// }
//
// @Override
// public int hashCode() {
// int result = x;
// result = 31 * result + y;
// return result;
// }
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////
static void println(Object o) {
out.println(o);
}
static void println() {
out.println();
}
static void print(Object o) {
out.print(o);
}
static void pflush(Object o) {
out.println(o);
out.flush();
}
static int ceil(int x, int y) {
return (x % y == 0 ? x / y : (x / y + 1));
}
static long ceil(long x, long y) {
return (x % y == 0 ? x / y : (x / y + 1));
}
static int max(int x, int y) {
return Math.max(x, y);
}
static int min(int x, int y) {
return Math.min(x, y);
}
static int abs(int x) {
return Math.abs(x);
}
static long abs(long x) {
return Math.abs(x);
}
static int log2(int N) {
int result = (int) (Math.log(N) / Math.log(2));
return result;
}
static long max(long x, long y) {
return Math.max(x, y);
}
static long min(long x, long y) {
return Math.min(x, y);
}
public static int gcd(int a, int b) {
BigInteger b1 = BigInteger.valueOf(a);
BigInteger b2 = BigInteger.valueOf(b);
BigInteger gcd = b1.gcd(b2);
return gcd.intValue();
}
public static long gcd(long a, long b) {
BigInteger b1 = BigInteger.valueOf(a);
BigInteger b2 = BigInteger.valueOf(b);
BigInteger gcd = b1.gcd(b2);
return gcd.longValue();
}
public static long lcm(long a, long b) {
return (a * b) / gcd(a, b);
}
public static int lcm(int a, int b) {
return (a * b) / gcd(a, b);
}
public static int lower_bound(int[] arr, int x) {
int low = 0, high = arr.length, mid = -1;
while (low < high) {
mid = (low + high) / 2;
if (arr[mid] >= x)
high = mid;
else
low = mid + 1;
}
return low;
}
public static int upper_bound(int[] arr, int x) {
int low = 0, high = arr.length, mid = -1;
while (low < high) {
mid = (low + high) / 2;
if (arr[mid] > x)
high = mid;
else
low = mid + 1;
}
return low;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////
static class FastScanner {
BufferedReader br;
StringTokenizer st;
FastScanner() throws FileNotFoundException {
br = new BufferedReader(new InputStreamReader(System.in));
}
FastScanner(int a) throws FileNotFoundException {
br = new BufferedReader(new FileReader("input.txt"));
}
String next() throws IOException {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(next());
}
long nextLong() throws IOException {
return Long.parseLong(next());
}
double nextDouble() throws IOException {
return Double.parseDouble(next());
}
String nextLine() throws IOException {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
int[] readArray(int n) throws IOException {
int[] A = new int[n];
for (int i = 0; i != n; i++) {
A[i] = sc.nextInt();
}
return A;
}
long[] readArrayLong(int n) throws IOException {
long[] A = new long[n];
for (int i = 0; i != n; i++) {
A[i] = sc.nextLong();
}
return A;
}
}
static void ruffleSort(int[] a) {
Random get = new Random();
for (int i = 0; i < a.length; i++) {
int r = get.nextInt(a.length);
int temp = a[i];
a[i] = a[r];
a[r] = temp;
}
Arrays.sort(a);
}
static void ruffleSort(long[] a) {
Random get = new Random();
for (int i = 0; i < a.length; i++) {
int r = get.nextInt(a.length);
long temp = a[i];
a[i] = a[r];
a[r] = temp;
}
Arrays.sort(a);
}
}
|
Java
|
["5\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
|
b6d0c8572307c97e3f6209edda33de01
|
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 A {
static FastScanner fs;
public static void main(String[] args) {
fs=new FastScanner();
// int t = fs.nextInt();
// while (t-->0)
solve();
}
public static void solve() {
int n = fs.nextInt();
int lo = 1;
int hi = n;
System.out.println("? "+lo+" "+hi);
System.out.flush();
int sh = fs.nextInt();
int check = -1;
if (lo!=sh) {
System.out.println("? " + lo + " " + sh);
System.out.flush();
check = fs.nextInt();
}
if (sh!=check) {
lo=sh;
for (hi++; lo < hi; ) {
int mid = lo + (hi - lo) / 2;
if (sh!=mid) {
System.out.println("? " + sh + " " + mid);
System.out.flush();
int ch = fs.nextInt();
if (sh==ch) hi = mid;
else lo = mid + 1;
}
else lo=mid+1;
}
System.out.println("! "+lo);
}
else {
hi=sh;
for (--lo; lo < hi; ) {
int mid = lo+(hi-lo+1)/2;
if (mid!=sh) {
System.out.println("? " + mid + " " + sh);
System.out.flush();
int ch = fs.nextInt();
if (sh == ch) lo = mid;
else hi = mid - 1;
}
else hi=mid-1;
}
System.out.println("! "+lo);
}
}
static class pair {
long v, i;
pair(long a, long b) {
v=a; i=b;
}
}
static void ruffleSort(int[] a) {
int n=a.length;//shuffle, then sort
for (int i=0; i<n; i++) {
int oi=random.nextInt(n), temp=a[oi];
a[oi]=a[i]; a[i]=temp;
}
Arrays.sort(a);
}
static final Random random=new Random();
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 int[] reverse(int[] a) {
int n=a.length;
int[] res=new int[n];
for (int i=0; i<n; i++) res[i]=a[n-1-i];
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
|
6fc7c1b6053c2e665759c8a9d04e0b02
|
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.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.PrintWriter;
public class T1698C2 {
private static final T1698C2FastScanner in = new T1698C2FastScanner();
private static final PrintWriter out = new PrintWriter(System.out);
public static void main(String args[]) {
int n = in.nextInt();
int posSecMax = query(0, n-1);
int posMax = search(0, n-1, posSecMax);
answer(posMax);
out.flush();
}
private static int search(int leftMax, int rightMax, int posSecMax) {
int offsetFromLeft = (rightMax - leftMax) / 2;
int mid = leftMax + offsetFromLeft;
if (rightMax - leftMax == 1) {
int newPosSecMax = query(leftMax, rightMax);
if (newPosSecMax == leftMax) return rightMax;
else return leftMax;
}
else if (rightMax - leftMax == 2) {
if (posSecMax >= leftMax && posSecMax <= rightMax) { //и max и secondMax среди этих трёх
if (posSecMax == leftMax) {
return search(leftMax + 1, rightMax, posSecMax);
} else if (posSecMax == rightMax) {
return search(leftMax, leftMax + 1, posSecMax);
} else {
int newPosSecMax = query(leftMax, leftMax + 1);
if (newPosSecMax == posSecMax) {
return leftMax;
} else {
return rightMax;
}
}
} else if (posSecMax < leftMax) {
int posSecMaxLeftHalf = query(posSecMax, leftMax);
if (posSecMaxLeftHalf == posSecMax) {
return leftMax;
} else {
return search(leftMax+1, rightMax, posSecMax);
}
} else {
int posSecMaxRightHalf = query(rightMax, posSecMax);
if (posSecMaxRightHalf == posSecMax) {
return rightMax;
} else {
return search(leftMax, leftMax+1, posSecMax);
}
}
}
boolean isLeftHalf;
if (posSecMax >= leftMax && posSecMax <= mid) { // posSecMax внутри первой половины
int posNewSecMax = query(leftMax, mid);
isLeftHalf = (posNewSecMax == posSecMax) ? true : false; //max внутри первой половины
} else if (posSecMax >= mid + 1 && posSecMax <= rightMax) { // posSecMax внутри второй половины
int posNewSecMax = query(mid+1, rightMax);
isLeftHalf = (posNewSecMax == posSecMax) ? false : true; //max внутри второй половины
} else if (posSecMax < leftMax) { //posSecMax находится "левее" первой половины, поэтому её и рассматриваем на наличие max
int posNewSecMax = query(posSecMax, mid);
isLeftHalf = (posNewSecMax == posSecMax) ? true : false; //max внутри второй половины
} else { //posSecMax находится "правее" второй половины, поэтому её и рассматриваем на наличие max
int posNewSecMax = query(mid + 1, posSecMax);
isLeftHalf = (posNewSecMax == posSecMax) ? false : true; //max внутри второй половины
}
if (isLeftHalf) {
return search(leftMax, mid, posSecMax);
} else {
return search(mid+1, rightMax, posSecMax);
}
}
static int query(int l, int r) {
out.println("? " + (l + 1) + " " + (r + 1));
out.flush();
return (in.nextInt() - 1);
}
static void answer(int position) {
out.println("! " + (position + 1));
}
}
class T1698C2FastScanner {
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 T1698C2FastScanner() {
in = new BufferedInputStream(System.in, BS);
}
public T1698C2FastScanner(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;
}
}
}
|
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
|
5924016a5ba4587614726868d1dcf676
|
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 guessing {
//--------------------------INPUT READER--------------------------------//
static class fs {
public BufferedReader br;
StringTokenizer st = new StringTokenizer("");
public fs() { this(System.in); }
public fs(InputStream is) {
br = new BufferedReader(new InputStreamReader(is));
}
String next() {
while (!st.hasMoreTokens()) {
try { st = new StringTokenizer(br.readLine()); }
catch (IOException e) { e.printStackTrace(); }
}
return st.nextToken();
}
int ni() { return Integer.parseInt(next()); }
long nl() { return Long.parseLong(next()); }
double nd() { return Double.parseDouble(next()); }
String ns() { return next(); }
int[] na(long nn) {
int n = (int) nn;
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = ni();
return a;
}
long[] nal(long nn) {
int n = (int) nn;
long[] l = new long[n];
for(int i = 0; i < n; i++) l[i] = nl();
return l;
}
}
//-----------------------------------------------------------------------//
//---------------------------PRINTER-------------------------------------//
static class Printer {
static PrintWriter w;
public Printer() {this(System.out);}
public Printer(OutputStream os) {
w = new PrintWriter(os, true);
}
public void p(int i) {w.println(i);};
public void p(long l) {w.println(l);};
public void p(double d) {w.println(d);};
public void p(String s) { w.println(s);};
public void pr(int i) {w.print(i);};
public void pr(long l) {w.print(l);};
public void pr(double d) {w.print(d);};
public void pr(String s) { w.print(s);};
public void pl() {w.println();};
public void close() {w.close();};
}
//------------------------------------------------------------------------//
//--------------------------VARIABLES------------------------------------//
static fs sc = new fs();
static OutputStream outputStream = System.out;
static Printer w = new Printer(outputStream);
//-----------------------------------------------------------------------//
//--------------------------ADMIN_MODE-----------------------------------//
private static void ADMIN_MODE() throws IOException {
if (System.getProperty("ONLINE_JUDGE") == null) {
w = new Printer(new FileOutputStream("output.txt"));
sc = new fs(new FileInputStream("input.txt"));
}
}
//-----------------------------------------------------------------------//
//----------------------------START--------------------------------------//
public static void main(String[] args)
throws IOException {
// ADMIN_MODE();
//int t = sc.ni();while(t-->0)
solve();
w.close();
}
static void solve() throws IOException {
int n = sc.ni();
w.p("? "+1+" "+n);
int id = sc.ni();
if(n == 2) {
w.p("! "+(1==id?2:1));
return;
}
int id2 = -1;
if(id != 1) {
w.p("? " + 1 + " " + id);
id2 = sc.ni();
}
int l, r;
if(id == id2) {
l = 1; r = id;
while(l < r) {
int mid = (l+r)/2;
w.p("? "+mid+" "+id);
int q = sc.ni();
if(q == id) {
l = mid+1;
} else r = mid;
}
w.p("! "+(l-1));
} else {
l = id+1; r = n;
while(l < r) {
int mid = (l+r)/2;
w.p("? "+id+" "+mid);
int q = sc.ni();
if(q != id) {
l = mid+1;
} else r = mid;
}
w.p("! "+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 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
|
8fd04f4af5e93a638bdfa64f1b817170
|
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 {
private static Scanner cin;
private static int query(long l, long r) {
System.out.println("? " + l + " " + r);
System.out.flush();
return cin.nextInt();
}
public static void main(String[] args) {
cin = new Scanner(System.in);
int n = cin.nextInt();
int now = query(1, n), l, r;
if (now != 1 && query(1, now) == now) {
l = 1;
r = now - 1;
while (l < r) {
int mid = (l + r) >> 1;
if (query(mid + 1, now) == now) {
l = mid + 1;
} else {
r = mid;
}
}
} else {
l = now + 1;
r = n;
while (l < r) {
int mid = (l + r) >> 1;
if (query(now, mid) == now) {
r = mid;
} else {
l = mid + 1;
}
}
}
System.out.println("! " + 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 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
|
176f8b90ad36af005506572bd67e1604
|
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
|
/**
* BaZ :D
*/
import java.util.*;
import java.io.*;
import static java.lang.Math.*;
public class Main
{
static MyScanner scan;
static PrintWriter pw;
static long MOD = 1_000_000_007;
static long INF = 2_000_000_000_000_000_000L;
static long inf = 2_000_000_000;
public static void main(String[] args) {
new Thread(null, null, "BaZ", 1 << 27) {
public void run() {
try {
solve();
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
}.start();
}
static int n;
static void solve() throws java.lang.Exception {
//initIo(true, "");
initIo(false, "");
StringBuilder sb = new StringBuilder();
n = ni();
int p = ask(1,n);
boolean left = true;
if(p==1 || (p+1 <= n && ask(p, n) == p)) {
left = false;
}
int idx = p;
for(int i=16;i>=0;--i) {
int new_idx = idx;
if(left) {
new_idx-=(1<<i);
}
else {
new_idx+=(1<<i);
}
new_idx = min(n, new_idx);
new_idx = max(1, new_idx);
int cnt = max(new_idx,p) - min(new_idx,p) + 1;
// pl("idx: "+idx+" new_idx: "+new_idx+" cnt: "+cnt);
if(cnt > 1 && ask(min(new_idx, p), max(new_idx,p)) != p) {
idx = new_idx;
}
}
idx = (left ? idx - 1 : idx + 1);
pl("! "+idx);
pw.flush();
pw.close();
}
static int ask(int l, int r) throws IOException {
pl("? "+l+" "+r);
pw.flush();
return ni();
}
static void assert_in_range(String varName, int n, int l, int r) {
if (n >=l && n<=r) return;
System.out.println(varName + " is not in range. Actual: "+n+" l : "+l+" r: "+r);
System.exit(1);
}
static void assert_in_range(String varName, long n, long l, long r) {
if (n>=l && n<=r) return;
System.out.println(varName + " is not in range. Actual: "+n+" l : "+l+" r: "+r);
System.exit(1);
}
static void initIo(boolean isFileIO, String suffix) throws IOException {
scan = new MyScanner(isFileIO, suffix);
if(isFileIO) {
pw = new PrintWriter("/Users/amandeep/Desktop/output"+suffix+".txt");
}
else {
pw = new PrintWriter(System.out, true);
}
}
static int ni() throws IOException
{
return scan.nextInt();
}
static long nl() throws IOException
{
return scan.nextLong();
}
static double nd() throws IOException
{
return scan.nextDouble();
}
static String ne() throws IOException
{
return scan.next();
}
static String nel() throws IOException
{
return scan.nextLine();
}
static void pl()
{
pw.println();
}
static void p(Object o)
{
pw.print(o+" ");
}
static void pl(Object o)
{
pw.println(o);
}
static void psb(StringBuilder sb)
{
pw.print(sb);
}
static void pa(String arrayName, Object arr[])
{
pl(arrayName+" : ");
for(Object o : arr)
p(o);
pl();
}
static void pa(String arrayName, int arr[])
{
pl(arrayName+" : ");
for(int o : arr)
p(o);
pl();
}
static void pa(String arrayName, long arr[])
{
pl(arrayName+" : ");
for(long o : arr)
p(o);
pl();
}
static void pa(String arrayName, double arr[])
{
pl(arrayName+" : ");
for(double o : arr)
p(o);
pl();
}
static void pa(String arrayName, char arr[])
{
pl(arrayName+" : ");
for(char o : arr)
p(o);
pl();
}
static void pa(String arrayName, boolean arr[])
{
pl(arrayName+" : ");
for(boolean o : arr)
p(o);
pl();
}
static void pa(String listName, List list)
{
pl(listName+" : ");
for(Object o : list)
p(o);
pl();
}
static void pa(String arrayName, Object[][] arr) {
pl(arrayName+" : ");
for(int i=0;i<arr.length;++i) {
for(Object o : arr[i])
p(o);
pl();
}
}
static void pa(String arrayName, int[][] arr) {
pl(arrayName+" : ");
for(int i=0;i<arr.length;++i) {
for(int o : arr[i])
p(o);
pl();
}
}
static void pa(String arrayName, long[][] arr) {
pl(arrayName+" : ");
for(int i=0;i<arr.length;++i) {
for(long o : arr[i])
p(o);
pl();
}
}
static void pa(String arrayName, char[][] arr) {
pl(arrayName+" : ");
for(int i=0;i<arr.length;++i) {
for(char o : arr[i])
p(o);
pl();
}
}
static void pa(String arrayName, double[][] arr) {
pl(arrayName+" : ");
for(int i=0;i<arr.length;++i) {
for(double o : arr[i])
p(o);
pl();
}
}
static void pa(String arrayName, boolean[][] arr) {
pl(arrayName+" : ");
for(int i=0;i<arr.length;++i) {
for(boolean o : arr[i])
p(o);
pl();
}
}
static class MyScanner
{
BufferedReader br;
StringTokenizer st;
MyScanner(boolean readingFromFile, String suffix) throws IOException
{
if(readingFromFile) {
br = new BufferedReader(new FileReader("/Users/amandeep/Desktop/input"+suffix+".txt"));
}
else {
br = new BufferedReader(new InputStreamReader(System.in));
}
}
String nextLine()throws IOException
{
return br.readLine();
}
String next() throws IOException
{
if(st==null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
int nextInt() throws IOException
{
return Integer.parseInt(next());
}
long nextLong() throws IOException
{
return Long.parseLong(next());
}
double nextDouble() throws IOException
{
return Double.parseDouble(next());
}
}
}
|
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
|
82e205f1be1f80e34d7e423e6b41fe1b
|
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.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.TreeMap;
public class Main implements Runnable {
int n, m;
static boolean use_n_tests = false;
int N = -1;
long mod = 1000000007;
void solve(FastScanner in, PrintWriter out, int testNumber) {
n = in.nextInt();
out.println("! " + rec(0, n));
}
int rec(int l, int r) {
int bigPos = ask(l, r - 1);
int bigLeft = ask(l, bigPos);
int lf, rf;
int ans = -1;
if (bigPos == bigLeft) {
lf = 0;
rf = bigLeft;
while (lf <= rf) {
int mid = (lf + rf) / 2;
if (ask(mid, bigPos) == bigLeft) {
ans = mid;
lf = mid + 1;
} else {
rf = mid - 1;
}
}
} else {
lf = bigPos;
rf = r - 1;
while (lf <= rf) {
int mid = (lf + rf) / 2;
if (ask(bigPos, mid) == bigPos) {
ans = mid;
rf = mid - 1;
} else {
lf = mid + 1;
}
}
}
return (ans + 1);
}
// ****************************** template code ***********
int ask(int l, int r) {
if (l >= r) {
return -1;
}
System.out.printf("? %d %d\n", l + 1, r + 1);
System.out.flush();
return in.nextInt() - 1;
}
static int stack_size = 1 << 27;
class Mod {
long mod;
Mod(long mod) {
this.mod = mod;
}
long add(long a, long b) {
a = mod(a);
b = mod(b);
return (a + b) % mod;
}
long sub(long a, long b) {
a = mod(a);
b = mod(b);
return (a - b + mod) % mod;
}
long mul(long a, long b) {
a = mod(a);
b = mod(b);
return a * b % mod;
}
long div(long a, long b) {
a = mod(a);
b = mod(b);
return (a * inv(b)) % mod;
}
public long inv(long r) {
if (r == 1)
return 1;
return ((mod - mod / r) * inv(mod % r)) % mod;
}
private long mod(long a) {
return a % mod;
}
}
class Coeff {
long mod;
long[][] C;
long[] fact;
boolean cycleWay = false;
Coeff(int n, long mod) {
this.mod = mod;
fact = new long[n + 1];
fact[0] = 1;
for (int i = 1; i <= n; i++) {
fact[i] = i;
fact[i] %= mod;
fact[i] *= fact[i - 1];
fact[i] %= mod;
}
}
Coeff(int n, int m, long mod) {
// n > m
cycleWay = true;
this.mod = mod;
C = new long[n + 1][m + 1];
for (int i = 0; i <= n; i++) {
for (int j = 0; j <= Math.min(i, m); j++) {
if (j == 0 || j == i) {
C[i][j] = 1;
} else {
C[i][j] = C[i - 1][j - 1] + C[i - 1][j];
C[i][j] %= mod;
}
}
}
}
public long C(int n, int m) {
if (cycleWay) {
return C[n][m];
}
return fC(n, m);
}
private long fC(int n, int m) {
return (fact[n] * inv(fact[n - m] * fact[m] % mod)) % mod;
}
private long inv(long r) {
if (r == 1)
return 1;
return ((mod - mod / r) * inv(mod % r)) % mod;
}
}
class Pair {
int first;
int second;
public int getFirst() {
return first;
}
public int getSecond() {
return second;
}
}
class MultisetTree<T> {
int size = 0;
TreeMap<T, Integer> mp = new TreeMap<>();
void add(T x) {
mp.merge(x, 1, Integer::sum);
size++;
}
void remove(T x) {
if (mp.containsKey(x)) {
mp.merge(x, -1, Integer::sum);
if (mp.get(x) == 0) {
mp.remove(x);
}
size--;
}
}
boolean contains(T x) {
return mp.containsKey(x);
}
T greatest() {
return mp.lastKey();
}
T smallest() {
return mp.firstKey();
}
int size() {
return size;
}
int diffSize() {
return mp.size();
}
}
class Multiset<T> {
int size = 0;
Map<T, Integer> mp = new HashMap<>();
void add(T x) {
mp.merge(x, 1, Integer::sum);
size++;
}
boolean contains(T x) {
return mp.containsKey(x);
}
void remove(T x) {
if (mp.containsKey(x)) {
mp.merge(x, -1, Integer::sum);
if (mp.get(x) == 0) {
mp.remove(x);
}
size--;
}
}
int size() {
return size;
}
int diffSize() {
return mp.size();
}
}
static class Range {
int l, r;
int id;
public int getL() {
return l;
}
public int getR() {
return r;
}
public Range(int l, int r, int id) {
this.l = l;
this.r = r;
this.id = id;
}
}
static class Array {
static Range[] readRanges(int n, FastScanner in) {
Range[] result = new Range[n];
for (int i = 0; i < n; i++) {
result[i] = new Range(in.nextInt(), in.nextInt(), i);
}
return result;
}
static List<List<Integer>> intInit2D(int n) {
List<List<Integer>> res = new ArrayList<>();
for (int i = 0; i < n; i++) {
res.add(new ArrayList<>());
}
return res;
}
static boolean isSorted(Integer[] a) {
for (int i = 0; i < a.length - 1; i++) {
if (a[i] > a[i + 1]) {
return false;
}
}
return true;
}
static public long sum(int[] a) {
long sum = 0;
for (int x : a) {
sum += x;
}
return sum;
}
static public long sum(long[] a) {
long sum = 0;
for (long x : a) {
sum += x;
}
return sum;
}
static public long sum(Integer[] a) {
long sum = 0;
for (int x : a) {
sum += x;
}
return sum;
}
static public int min(Integer[] a) {
int mn = Integer.MAX_VALUE;
for (int x : a) {
mn = Math.min(mn, x);
}
return mn;
}
static public int min(int[] a) {
int mn = Integer.MAX_VALUE;
for (int x : a) {
mn = Math.min(mn, x);
}
return mn;
}
static public int max(Integer[] a) {
int mx = Integer.MIN_VALUE;
for (int x : a) {
mx = Math.max(mx, x);
}
return mx;
}
static public int max(int[] a) {
int mx = Integer.MIN_VALUE;
for (int x : a) {
mx = Math.max(mx, x);
}
return mx;
}
static public int[] readint(int n, FastScanner in) {
int[] out = new int[n];
for (int i = 0; i < out.length; i++) {
out[i] = in.nextInt();
}
return out;
}
}
class Graph {
List<List<Integer>> graph;
Graph(int n) {
create(n);
}
void create(int n) {
List<List<Integer>> graph = new ArrayList<>();
for (int i = 0; i < n; i++) {
graph.add(new ArrayList<>());
}
this.graph = graph;
}
void readBi(int m, FastScanner in) {
for (int i = 0; i < m; i++) {
int v = in.nextInt() - 1;
int u = in.nextInt() - 1;
graph.get(v).add(u);
graph.get(u).add(v);
}
}
}
class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(InputStream io) {
br = new BufferedReader(new InputStreamReader(io));
}
public String line() {
String result = "";
try {
result = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
public String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public int[] nextArray(int n) {
int[] res = new int[n];
for (int i = 0; i < n; i++) {
res[i] = in.nextInt();
}
return res;
}
public long[] nextArrayL(int n) {
long[] res = new long[n];
for (int i = 0; i < n; i++) {
res[i] = in.nextLong();
}
return res;
}
public Long[] nextArrayL2(int n) {
Long[] res = new Long[n];
for (int i = 0; i < n; i++) {
res[i] = in.nextLong();
}
return res;
}
public Integer[] nextArray2(int n) {
Integer[] res = new Integer[n];
for (int i = 0; i < n; i++) {
res[i] = in.nextInt();
}
return res;
}
public long nextLong() {
return Long.parseLong(next());
}
}
void run_t_tests() {
int t = in.nextInt();
int i = 0;
while (t-- > 0) {
solve(in, out, i++);
}
}
void run_one() {
solve(in, out, -1);
}
@Override
public void run() {
in = new FastScanner(System.in);
out = new PrintWriter(System.out);
if (use_n_tests) {
run_t_tests();
} else {
run_one();
}
out.close();
}
static FastScanner in;
static PrintWriter out;
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(null, new Main(), "", stack_size);
thread.start();
thread.join();
}
}
|
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
|
f87eace5b79aa90585a41174b0b8346c
|
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.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
// import java.math.BigInteger;
import java.util.*;
public class Solution {
public static void main(String[] args) {
int n = in.nextInt(), t = query(1, n), ind = 0;
if (query(1, t) == t) {
int lo = 1, hi = t-1;
while (lo <= hi) {
int mid = (lo + hi) >> 1;
if (query(mid, t) == t) {
lo = mid+1;
} else {
hi = mid-1;
}
}
ind = hi;
} else {
int lo = t+1, hi = n;
while (lo <= hi) {
int mid = (lo + hi) >> 1;
if (query(t, mid) == t) {
hi = mid-1;
} else {
lo = mid+1;
}
}
ind = lo;
}
out.println("! " + ind);
out.flush();
}
static int query(int l, int r) {
if (l == r) {
return 0;
}
out.println("? " + l + " " + r);
out.flush();
return in.nextInt();
}
// Handle I/O
static int MOD = (int) (1e9 + 7);
static FastScanner in = new FastScanner();
static PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
st = 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 Integer.parseInt(next());
}
int[] readIntArray(int size) {
int[] arr = new int[size];
for (int i = 0; i < size; i++) {
arr[i] = nextInt();
}
return arr;
}
long nextLong() {
return Long.parseLong(next());
}
long[] readLongArray(int size) {
long[] arr = new long[size];
for (int i = 0; i < size; i++) {
arr[i] = nextLong();
}
return arr;
}
double nextDouble() {
return Double.parseDouble(next());
}
double[] readDoubleArray(int size) {
double[] arr = new double[size];
for (int i = 0; i < size; i++) {
arr[i] = nextDouble();
}
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
|
36e8b54563440960e8c20b69d67e1eb1
|
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
|
/*******************************************************************************
* author : dante1
* created : 18/02/2021 23:12
*******************************************************************************/
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
// import java.math.BigInteger;
import java.util.*;
public class c1 {
public static void main(String[] args) {
int n = in.nextInt(), t = query(1, n), max_idx = 0;
if (t == query(1, t)) {
int lo = 1, hi = t-1;
while (lo <= hi) {
int mid = (lo + hi) >> 1;
if (t == query(mid, t)) {
max_idx = mid;
lo = mid+1;
} else {
hi = mid-1;
}
}
} else {
int lo = t+1, hi = n;
while (lo <= hi) {
int mid = (lo + hi) >> 1;
if (t == query(t, mid)) {
max_idx = mid;
hi = mid-1;
} else {
lo = mid+1;
}
}
}
out.println("! " + max_idx);
out.flush();
}
static int query(int l, int r) {
if (l == r) {
return 0;
}
out.println("? " + l + " " + r);
out.flush();
return in.nextInt();
}
// Handle I/O
static int MOD = (int) (1e9 + 7);
static FastScanner in = new FastScanner();
static PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
st = 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 Integer.parseInt(next());
}
int[] readIntArray(int size) {
int[] arr = new int[size];
for (int i = 0; i < size; i++) {
arr[i] = nextInt();
}
return arr;
}
long nextLong() {
return Long.parseLong(next());
}
long[] readLongArray(int size) {
long[] arr = new long[size];
for (int i = 0; i < size; i++) {
arr[i] = nextLong();
}
return arr;
}
double nextDouble() {
return Double.parseDouble(next());
}
double[] readDoubleArray(int size) {
double[] arr = new double[size];
for (int i = 0; i < size; i++) {
arr[i] = nextDouble();
}
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
|
5e0e787a185bdeda36c9051f87816d04
|
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 PrintWriter pw;
static Scanner sc;
static long ceildiv(long x, long y) { return (x+y-1)/y; }
static int mod(long x, int m) { return (int)((x%m+m)%m); }
static void put(HashMap<Integer, Integer> map, Integer p){if(map.containsKey(p)) map.replace(p, map.get(p)+1); else map.put(p, 1); }
static void rem(TreeMap<Integer, Integer> map, Integer p){ if(map.get(p)==1) map.remove(p);else map.replace(p, map.get(p)-1); }
static void printf(double x, int dig){ String s="%."+dig+"f"; pw.printf(s, x); }
static int Int(boolean x){ return x?1:0; }
static final int inf=(int)1e9, mod=998244353;
static final long infL=inf*1l*inf;
static final double eps=1e-9;
public static long gcd(long x, long y) { return y==0? x: gcd(y, x%y); }
public static void main(String[] args) throws Exception {
sc = new Scanner(System.in);
pw = new PrintWriter(System.out);
// int t = sc.nextInt();
// while (t-- > 0)
testcase();
pw.close();
}
static int ask(int l, int r) throws IOException{
pw.println("? "+(l+1)+ " "+(r+1));
pw.flush();
return sc.nextInt()-1;
}
static void testcase() throws IOException {
int n=sc.nextInt();
int x=ask(0, n-1), y=x==0? -1: ask(0, x);
if(y==x){
int st=1, end=x-1;
int ans=0;
while(st<=end){
int mid=(st+end)/2;
if(ask(mid, x)==x){
ans=mid;
st=mid+1;
}else{
end=mid-1;
}
}
out(ans);
}else{
int st=x+1, end=n-1;
int ans=n-1;
while(st<=end){
int mid=(st+end)/2;
if(ask(x, mid)==x){
ans=mid;
end=mid-1;
}else{
st=mid+1;
}
}
out(ans);
}
}
static void out(int x){
pw.println("! "+(x+1));
}
static void printArr(int[] arr) {
for (int i = 0; i < arr.length; i++)
pw.print(arr[i] + " ");
pw.println();
}
static void printArr(long[] arr) {
for (int i = 0; i < arr.length; i++)
pw.print(arr[i] + " ");
pw.println();
}
static void printArr(double[] arr) {
for (int i = 0; i < arr.length; i++)
pw.print(arr[i] + " ");
pw.println();
}
static void printArr(Integer[] arr) {
for (int i = 0; i < arr.length; i++)
pw.print(arr[i] + " ");
pw.println();
}
static void printArr(ArrayList list) {
for (int i = 0; i < list.size(); i++)
pw.print(list.get(i)+" ");
pw.println();
}
static void printArr(boolean[] arr) {
StringBuilder sb=new StringBuilder();
for(boolean b: arr)
sb.append(Int(b));
pw.println(sb);
}
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 {
return Double.parseDouble(next());
}
public int[] nextDigits() throws IOException{
String s=nextLine();
int[] arr=new int[s.length()];
for(int i=0; i<arr.length; i++)
arr[i]=s.charAt(i)-'0';
return arr;
}
public int[] nextArr(int n) throws IOException {
int[] arr = new int[n];
for (int i = 0; i < arr.length; i++)
arr[i] = nextInt();
return arr;
}
public Integer[] nextsort(int n) throws IOException{
Integer[] arr=new Integer[n];
for(int i=0; i<n; i++)
arr[i]=nextInt();
return arr;
}
public Pair nextPair() throws IOException{
return new Pair(nextInt(), nextInt());
}
public long[] nextLongArr(int n) throws IOException{
long[] arr=new long[n];
for (int i = 0; i < n; i++)
arr[i]=sc.nextLong();
return arr;
}
public Pair[] nextPairArr(int n) throws IOException{
Pair[] arr=new Pair[n];
for(int i=0; i<n; i++)
arr[i]=nextPair();
return arr;
}
public boolean ready() throws IOException {
return br.ready();
}
}
static class Pair implements Comparable<Pair>{
int x;
int y;
public Pair(int x, int y) {
this.x=x;
this.y=y;
}
public boolean contains(int a){
return x==a || y==a;
}
public int hashCode() {
return (this.x*1000000000+this.y);
}
public int compareTo(Pair p){
if(x==p.x)
return y-p.y;
return x-p.x;
}
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (this.getClass() != obj.getClass()) {
return false;
}
Pair p = (Pair) obj;
return this.x==p.x && this.y==p.y;
}
public Pair clone(){
return new Pair(x, y);
}
public String toString(){
return this.x+" "+this.y;
}
public void add(Pair p){
x+=p.x;
y+=p.y;
}
public Pair negative(){
return new Pair(-x, -y);
}
}
static class LP implements Comparable<LP>{
long x, y;
public LP(long a, long b){
x=a;
y=b;
}
public void add(LP p){
x+=p.x;
y+=p.y;
}
public boolean equals(LP p){
return p.x==x && y==p.y;
}
public String toString(){
return this.x+" "+this.y;
}
public int compareTo(LP p){
int a=Long.compare(x, p.x);
if(a!=0)
return a;
return Long.compare(y, p.y);
}
}
static class Triple implements Comparable<Triple>{
int x, y, z;
public Triple(int a, int b, int c){
x=a;
y=b;
z=c;
}
public int compareTo(Triple t){
if(this.y!=t.y)
return y-t.y;
return x-t.x;
}
public String toString(){
return x+" "+y+" "+z;
}
}
// static class MaxSegmentTree{
// int n;
// long[] tree;
// public MaxSegmentTree(int len, long[] arr){
// n=len;
// build(0, 0, n-1, arr);
// }
// public void build(int i, int l, int r, long[] arr){
// if(l==r){
// tree[i]=arr[l];
// return;
// }
// int mid=(l+r)/2, left=2*i+1, right=2*i+2;
// build(left, l, mid, arr);
// build(right, mid+1, r, arr);
// tree[i]=Math.max(left, right);
// }
// public int query(int i){
// return query(0, 0, n-1, 0, i);
// }
// public int query(int node, int i, int j, int l, int r){
// if(l>j || r<i)
// return -1;
//
// }
// }
static class SegmentTree {
int n, size[];
long[] tree;
public SegmentTree(int len) {
n = len;
tree=new long[2*n-1];
size=new int[2*n-1];
}
public void set(int i, long x){
i+=n-1;
tree[i]=x;
size[i]++;
i=(i-1)/2;
while(true){
size[i]++;
tree[i]=tree[i*2+1] + tree[i*2+2];
if(i==0)
break;
i=(i-1)/2;
}
}
public long query(int x){
return query(0, 0, n-1, x+1, n-1);
}
public long query(int node, int i, int j, int l, int r){
if(j<l || i>r)
return 0;
if(i>=l && j<=r)
return tree[node];
int mid=(i+j)/2, left=node*2+1, right=node*2+2;
return query(left, i, mid, l, r) + query(right, mid+1, j, l, r);
}
public int size(int idx){
return size(0, 0, n-1, idx+1, n-1);
}
public int size(int node, int i, int j, int l, int r){
if(i>r || j<l)
return 0;
if(i>=l && j<=r)
return size[node];
int mid=(i+j)/2, left=node*2+1, right=node*2+2;
return size(left, i, mid, l, r)+size(right, mid+1, j, 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 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
|
351be300840a15eba3497af2014ad011
|
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.lang.*;
public class Main{
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
solve(in, out);
out.close();
}
static int L,R,top,bottom;
static int cnt,edge;
public static void solve(InputReader sc, PrintWriter pw) {
// int t=sc.nextInt();
int t=1;
u:while(t-->0){
int n=sc.nextInt();
if(n==1){
pw.println(1);
continue u;
}
int l=1,r=n,m,p=1,a;
boolean flag=true;
p=ask(l,r,sc);
if(p==1||ask(1,p,sc)!=p){
l=p;
while(r-l>1){
m=(r-l)/2+l;
if(ask(p,m,sc)==p)
r=m;
else
l=m;
}
System.out.println("! "+r);
}
else{
r=p;
while(r-l>1){
m=(r-l)/2+l;
if(ask(m,p,sc)==p)
l=m;
else
r=m;
}
System.out.println("! "+l);
}
}
}
public static int ask(int l, int r,InputReader sc){
System.out.println("? "+l+" "+r);
System.out.flush();
return sc.nextInt();
}
public static void sort(long []arr){
ArrayList<Long> list=new ArrayList<>();
for(int i=0;i<arr.length;i++)
list.add(arr[i]);
Collections.sort(list);
for(int i=0;i<arr.length;i++)
arr[i]=list.get(i);
}
public static void swap(char []chrr, int i, int j){
char temp=chrr[i];
chrr[i]=chrr[j];
chrr[j]=temp;
}
public static int num(int n){
int a=0;
while(n>0){
a+=(n&1);
n>>=1;
}
return a;
}
static class Pair{
int a, b;
Pair(int a,int b){
this.a=a;
this.b=b;
}
}
// public int compareTo(Pair p){
// return (b-p.b);
// }
// public int hashCode(){
// int hashcode = (a+" "+b).hashCode();
// return hashcode;
// }
// public boolean equals(Object obj){
// if (obj instanceof Pair) {
// Pair p = (Pair) obj;
// return (p.a==this.a && p.b == this.b);
// }
// return false;
// }
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;
}
static int gcd(int a, int b) {
if (b == 0)
return a;
return a>b?gcd(b, a % b):gcd(a, b % a);
}
static long fast_pow(long base,long n,long M){
if(n==0)
return 1;
if(n==1)
return base;
long halfn=fast_pow(base,n/2,M);
if(n%2==0)
return ( halfn * halfn ) % M;
else
return ( ( ( halfn * halfn ) % M ) * base ) % M;
}
static long modInverse(long n,long M){
return fast_pow(n,M-2,M);
}
public static void feedArr(long []arr,InputReader sc){
for(int i=0;i<arr.length;i++)
arr[i]=sc.nextLong();
}
public static void feedArr(double []arr,InputReader sc){
for(int i=0;i<arr.length;i++)
arr[i]=sc.nextDouble();
}
public static void feedArr(int []arr,InputReader sc){
for(int i=0;i<arr.length;i++)
arr[i]=sc.nextInt();
}
public static void feedArr(String []arr,InputReader sc){
for(int i=0;i<arr.length;i++)
arr[i]=sc.next();
}
public static String printArr(int []arr){
StringBuilder sbr=new StringBuilder();
for(int i:arr)
sbr.append(i+" ");
return sbr.toString();
}
public static String printArr(long []arr){
StringBuilder sbr=new StringBuilder();
for(long i:arr)
sbr.append(i+" ");
return sbr.toString();
}
public static String printArr(String []arr){
StringBuilder sbr=new StringBuilder();
for(String i:arr)
sbr.append(i+" ");
return sbr.toString();
}
public static String printArr(double []arr){
StringBuilder sbr=new StringBuilder();
for(double i:arr)
sbr.append(i+" ");
return sbr.toString();
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
}
|
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
|
6ffab90b3b8d86dd2e2d038619a8754b
|
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
|
//I AM THE CREED
/* //I AM THE CREED
/* package codechef; // don't place package name! */
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.util.*;
import java.awt.Point;
public class Main{
static final Random random=new Random();
public static void main(String[] args) throws IOException
{
Scanner input=new Scanner(System.in);
int n=input.nextInt();
System.out.println("? "+1+" "+n);
System.out.flush();
int secondIndex=input.nextInt();
int left=1;
int right=secondIndex-1;
if(right>=left){
System.out.println("? "+(secondIndex-right)+" "+(secondIndex));
System.out.flush();
int index=input.nextInt();
if(secondIndex==index){
while(right!=left){
int mid=left+((right-left)/2);
System.out.println("? "+(secondIndex-mid)+" "+(secondIndex));
System.out.flush();
int curr=input.nextInt();
if(curr==secondIndex){
right=mid;
continue;
}
left=mid+1;
}
System.out.println("! "+(secondIndex-right));
System.out.flush();
return;
}
}
left=1;
right=n-secondIndex;
while(right!=left){
int mid=left+((right-left)/2);
System.out.println("? "+(secondIndex)+" "+(secondIndex+mid));
System.out.flush();
int curr=input.nextInt();
if(curr==secondIndex){
right=mid;
continue;
}
left=mid+1;
}
System.out.println("! "+(secondIndex+right));
System.out.flush();
}
static long pow(long num, long exp, long mod){
long ans=1;
for(int i=1;i<=exp;i++){
ans=(ans*num)%mod;
}
return ans;
}
static boolean isPrime(int n)
{
// Check if number is less than
// equal to 1
if (n <= 1)
return false;
// Check if number is 2
else if (n == 2)
return true;
// Check if n is a multiple of 2
else if (n % 2 == 0)
return false;
// If not, then just check the odds
for (int i = 3; i <= Math.sqrt(n); i += 2)
{
if (n % i == 0)
return false;
}
return true;
}
static int gcd(int a, int b)
{
if (a == 0)
return b;
return gcd(b % a, a);
}
// method to return LCM of two numbers
static int lcm(int a, int b)
{
return (a / gcd(a, b)) * b;
}
public static void sort(long[][] arr) {
//Sort an array (immune to quicksort TLE)
Random rgen = new Random();
for (int i = 0; i < arr.length; i++) {
int randomPosition = rgen.nextInt(arr.length);
long[] temp = arr[i];
arr[i] = arr[randomPosition];
arr[randomPosition] = temp;
}
Arrays.sort(arr, new Comparator<long[]>() {
@Override
public int compare(long[] a, long[] b) {
if (a[0] > b[0])
return 1;
else if (a[0] < b[0])
return -1;
else
return 0;
}
});
}
//Credits to SecondThread(https://codeforces.com/profile/SecondThread) for this tempelate.
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 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
|
751cc5c451ef0caa353d838bc368e1b5
|
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.*;
public class cf {
static PrintWriter pw = new PrintWriter(System.out);
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) throws IOException, InterruptedException {
int n = sc.nextInt();
pw.println("! " + bs(n));
pw.close();
}
static int bs(int n) throws IOException {
int ans = -1;
pw.println("? 1 " + n);
pw.flush();
int x = sc.nextInt() - 1;
boolean f = (x != 0);
if (f) {
pw.println("? 1 " + (x + 1));
pw.flush();
int y = sc.nextInt() - 1;
f &= (y == x);
}
if (f) {
int start = 0, end = x - 1;
while (start <= end) {
int mid = (start + end) / 2;
pw.println("? " + (mid + 1) + " " + (x + 1));
pw.flush();
int y = sc.nextInt() - 1;
if (y == x) {
ans = mid;
start = mid + 1;
} else {
end = mid - 1;
}
}
} else {
int start = x + 1, end = n - 1;
while (start <= end) {
int mid = (start + end) / 2;
pw.println("? " + (x + 1) + " " + (mid + 1));
pw.flush();
int y = sc.nextInt() - 1;
if (y == x) {
ans = mid;
end = mid - 1;
} else {
start = mid + 1;
}
}
}
return ans + 1;
}
public static class pair implements Comparable<pair> {
int x;
int y;
public pair(int x, int 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);
}
}
public 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 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();
}
}
}
|
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
|
b9092b24e831e5348dabdb379c163dc0
|
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 R703;
import java.io.*;
import java.math.*;
import java.util.*;
public class Q3 {
static int INF = (int)(1e9);
static long mod = (long)(1e9)+7;
static long mod2 = 998244353;
static long[] segtree;
static char[] curans;
static long ans;
static String S;
static ArrayList<Integer>[] graph;
static boolean[] vis;
static int[] a;
static int N;
static long K;
static long[] fact;
static ArrayList<Long> pos;
static ArrayList<Long> neg;
static long[] max;
static int[] dp;
public static void main(String[] args) { //Cash out
/**/
FastScanner I = new FastScanner(); //Input
OutPut O = new OutPut(); //Output
int N = I.nextInt();
O.pln("? " + 1 + " "+ N);
int index = I.nextInt();
int lo = index;
int hi = N;
int ans = 0;
if (index == N) {
lo = 1;
hi = index - 1;
while (lo <= hi) {
int mid = (lo + hi) / 2;
O.pln("? " + mid + " " + index);
int new_index = I.nextInt();
if (new_index == index) {
lo = mid + 1;
ans = max(ans,mid);
}else {
hi= mid - 1;
}
}
}else if (index == 1){
ans = N;
lo = index + 1;
while (lo <= hi) {
int mid = (lo + hi) / 2;
O.pln("? " + index + " " + mid);
int new_index = I.nextInt();
if (new_index == index) {
ans = min(ans,mid);
hi = mid - 1;
}else {
lo = mid + 1;
}
}
}else {
O.pln("? " + 1 + " "+ index);
int id2 = I.nextInt();
if (id2 == index) {
lo = 1;
hi = index - 1;
while (lo <= hi) {
int mid = (lo + hi) / 2;
O.pln("? " + mid + " " + index);
int new_index = I.nextInt();
if (new_index == index) {
ans = max(ans, mid);
lo = mid + 1;
}else {
hi= mid - 1;
}
}
}else {
lo = index + 1;
while (lo <= hi) {
ans = N;
int mid = (lo + hi) / 2;
O.pln("? " + index + " " + mid);
int new_index = I.nextInt();
if (new_index == index) {
ans = min(ans, mid);
hi = mid - 1;
}else {
lo = mid + 1;
}
}
}
}
O.pln("! " + ans);
}
public static double[][] matrix_exp(double[][] a, long exp, long mod) {
int R = a.length;
int C = a[0].length;
double[][] ans = new double[R][C];
boolean mult_yet = false;
while (exp > 0) {
if (exp % 2 == 1) {
if (!mult_yet) {
mult_yet = true;
for (int i = 0; i < R; i++) {
for (int j = 0; j < C; j++) {
ans[i][j] = a[i][j];
}
}
}else {
double[][] new_ans = mult(ans, a, mod);
for (int i = 0; i < R; i++) {
for (int j = 0; j < C; j++) {
ans[i][j] = new_ans[i][j];
}
}
}
}
double[][] new_a = mult(a, a, mod); // a = a^2 (binary exponentiation on matrices)
for (int i = 0; i < R; i++) {
for (int j = 0; j < C; j++) {
a[i][j] = new_a[i][j];
}
}
exp /= 2;
}
return ans;
}
public static double[][] mult(double[][] a, double[][] b, long mod) {
int r1 = a.length;
int c1 = a[0].length;
int r2 = b.length;
int c2 = b[0].length;
//Requires: c1 = r2
double[][] ans = new double[r1][c2];
for (int r = 0; r < r1; r++) {
for (int c = 0; c < c2; c++) {
//Dot product of (a[r])^T and b[c] (as vectors in R^n (n = c1 = r2))
double[] col_vector = new double[r2];
double[] row_vector = new double[c1];
for (int i = 0; i < r2; i++) {
col_vector[i] = b[i][c];
}
for (int i = 0; i < c1; i++) {
row_vector[i] = a[r][i];
}
ans[r][c] = dot_product(row_vector, col_vector, mod);
}
}
return ans;
}
public static double dot_product(double[] a, double[] b, long mod) {
double ans = 0;
int N = a.length; //Requires: a and b are both vectors in R^n
for (int i = 0; i < N; i++) {
ans += a[i] * b[i];
}
return ans;
}
public static double max(double a, double b) {return Math.max(a, b);}
public static double min(double a, double b) {return Math.min(a, b);}
public static long min(long a, long b) {return Math.min(a,b);}
public static long max(long a, long b) {return Math.max(a,b);}
public static int min(int a, int b) {return Math.min(a,b);}
public static int max(int a, int b) {return Math.max(a,b);}
public static long abs(long x) {return Math.abs(x);}
public static long abs(int x) {return Math.abs(x);}
public static long ceil(long num, long den) {long ans = num/den; if (num%den!=0)
ans++; return ans;}
public static long GCD(long a, long b) {
if (a==0||b==0) return max(a,b);
return GCD(min(a,b),max(a,b)%min(a,b));
}
public static long FastExp(long base, long exp, long mod) {
long ans=1;
while (exp>0) {
if (exp%2==1) ans*=base;
exp/=2;
base*=base;
base%=mod;
ans%=mod;
}
return ans;
}
public static long ModInv(long num,long mod) {return FastExp(num,mod-2,mod);}
public static int pop(long x) { //Returns number of bits within a number
int cnt = 0;
while (x>0) {
if (x%2==1) cnt++;
x/=2;
}
return cnt;
}
static class FastScanner {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st=new StringTokenizer("");
String next() {
while (!st.hasMoreTokens())
try {
st=new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
int nextInt() {return Integer.parseInt(next());}
long nextLong() {return Long.parseLong(next());};
double nextDouble() {return Double.parseDouble(next());}
}
static class OutPut{
PrintWriter w = new PrintWriter(System.out);
void pln(double x) {w.println(x);w.flush();}
void pln(boolean x) {w.println(x);w.flush();}
void pln(int x) {w.println(x);w.flush();}
void pln(long x) {w.println(x);w.flush();}
void pln(String x) {w.println(x);w.flush();}
void pln(char x) {w.println(x);w.flush();}
void pln(StringBuilder x) {w.println(x);w.flush();}
void pln(BigInteger x) {w.println(x);w.flush();}
void p(int x) {w.print(x);w.flush();}
void p(long x) {w.print(x);w.flush();}
void p(String x) {w.print(x);w.flush();}
void p(char x) {w.print(x);w.flush();}
void p(StringBuilder x) {w.print(x);w.flush();}
void p(BigInteger x) {w.print(x);w.flush();}
void p(double x) {w.print(x);w.flush();}
void p(boolean x) {w.print(x);w.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
|
3f3cc3be50b217b07613aa491f3e49fb
|
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.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Khater
*/
public class HH {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
Scanner in = new Scanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
C1GuessingTheGreatestEasyVersion solver = new C1GuessingTheGreatestEasyVersion();
solver.solve(1, in, out);
out.close();
}
static class C1GuessingTheGreatestEasyVersion {
int idx;
public void solve(int testNumber, Scanner sc, PrintWriter pw) {
int t = 1;
// t = sc.nextInt();
while (t-- > 0) {
int n = sc.nextInt();
idx = ask(1, n, sc, pw);
int b = ask(1,idx,sc,pw);
int ans =1;
if(b==idx) {
ans = bbs(1,idx,sc,pw);
}else {
ans = abs(idx,n,sc,pw);
}
pw.println("! "+ans);
}
}
int abs(int l, int r, Scanner sc, PrintWriter pw) {
if (l >= r-1) {
if(ask(idx, l, sc, pw)!=idx)
return r;
else return l;
}
int mid = (l+r)/2;
int b = ask(idx, mid, sc, pw);
if(b==idx)return abs(l,mid,sc,pw);
else return abs(mid+1,r,sc,pw);
}
int bbs(int l, int r, Scanner sc, PrintWriter pw) {
if (l >= r-1) {
if(ask(r, idx, sc, pw)==idx)
return r;
else return l;
}
int mid = (l+r)/2;
int a = ask(mid, idx, sc, pw);
if(a==idx)return bbs(mid,r,sc,pw);
else return bbs(l,mid-1,sc,pw);
}
int ask(int l, int r, Scanner sc, PrintWriter pw) {
if(l>=r) return -1;
pw.println("? " + l + " " + r);
pw.flush();
return sc.nextInt();
}
}
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() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
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
|
c82a851515c000f7a86e5588542588fc
|
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 class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
static FastReader s = new FastReader();
static PrintWriter out = new PrintWriter(System.out);
private static int[] rai(int n) {
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = s.nextInt();
}
return arr;
}
private static int[][] rai(int n, int m) {
int[][] arr = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
arr[i][j] = s.nextInt();
}
}
return arr;
}
private static long[] ral(int n) {
long[] arr = new long[n];
for (int i = 0; i < n; i++) {
arr[i] = s.nextLong();
}
return arr;
}
private static long[][] ral(int n, int m) {
long[][] arr = new long[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
arr[i][j] = s.nextLong();
}
}
return arr;
}
private static int ri() {
return s.nextInt();
}
private static long rl() {
return s.nextLong();
}
private static String rs() {
return s.next();
}
static long gcd(long a,long b)
{
if(b==0)
{
return a;
}
return gcd(b,a%b);
}
static boolean isPrime(int n) {
//check if n is a multiple of 2
if (n % 2 == 0) return false;
//if not, then just check the odds
for (int i = 3; i <= Math.sqrt(n); i += 2) {
if (n % i == 0)
return false;
}
return true;
}
static int MOD=1000000007;
static long mpow(long base,long pow)
{
long res=1;
while(pow>0)
{
if(pow%2==1)
{
res=(res*base)%MOD;
}
pow>>=1;
base=(base*base)%MOD;
}
return res;
}
static public int minimumSize(int[] nums, int m) {
PriorityQueue<Integer> pq=new PriorityQueue<>(Collections.reverseOrder());
for(int i:nums)
{
pq.add(i);
}
System.out.println(pq);
for(int i=0;i<m;i++)
{
int val=pq.remove();
if(val==1)
{
return 1;
}
int f=val/2;
int s=val-f;
pq.add(f);
pq.add(s);
System.out.println(pq);
}
return pq.remove();
}
public static void main(String[] args) {
// StringBuilder ans = new StringBuilder();
// int t = ri();
int t = 1;
while (t-- > 0)
{
int n=ri();
int l=1,r=n;
boolean f=false;
int count=0;
out.println("? 1 "+n);
out.flush();
count++;
int secMax=ri();
boolean before=false;
if(secMax==1)
{
l=2;
}
else if(secMax==n)
{
r=n-1;
before=true;
}
else
{
out.println("? 1 "+secMax);
out.flush();
count++;
int ind=ri();
if(ind==secMax)
{
r=secMax-1;
before=true;
}
else {
l=secMax+1;
}
}
int res=-1;
while(l<=r)
{
int mid=(l+r)/2;
if(before) {
out.println("? " + mid + " " +secMax);
out.flush();
count++;
int ind=ri();
if(ind==secMax)
{
res=mid;
l=mid+1;
}
else {
r=mid-1;
}
}
else
{
out.println("? " + secMax + " " +mid);
out.flush();
count++;
int ind=ri();
if(ind==secMax)
{
res=mid;
r=mid-1;
}
else {
l=mid+1;
}
}
}
out.println("! " + res);
out.flush();
// System.out.println(count);
}
// out.print(ans.toString());
// 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
|
276bad82bc3841c5b572fba0fba5d2bd
|
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.math.BigInteger;
import java.util.*;
public class TaskA {
public static void main(String[] args) {
InputReader in = new InputReader(System.in);
PrintWriter out = new PrintWriter(System.out);
Task solver = new Task();
solver.solve(in, out);
out.close();
}
// main solver
static class Task {
Scanner sc = new Scanner(System.in);
public void solve(InputReader in, PrintWriter out) {
int t = 1;
for (int i = 0; i < t; i++){
solveOne(in, out);
}
}
private int query(int l, int r){
System.out.println("? " + l + " " + r);
System.out.flush();
int pos = sc.nextInt();
return pos;
}
private void solveOne(InputReader in, PrintWriter out) {
int n = sc.nextInt();
int pos = query(1, n);
int beg = 1, end = n;
if (pos > 1){
if (query(1, pos) == pos){
end = pos;
}
else{
beg = pos;
}
}
else if (pos < n){
if (query(pos, n) == pos){
beg = pos;
}
else{
end = pos;
}
}
if (beg>=pos){
if (beg == pos) beg++;
while (beg < end - 1){
int mid = (beg + end) / 2;
int x = query(pos, mid);
if (x == pos){
end = mid;
}
else{
beg = mid;
}
}
if (end !=beg && query(pos, beg) != pos){
beg = end;
}
out.println("! " + beg);
}
else{
if (end == pos){
end--;
}
assert(end < pos);
while (beg < end - 1){
int mid = (beg + end) / 2;
int x = query(mid, pos);
if (x == pos){
beg = mid;
}
else{
end = mid;
}
}
if (end !=beg && query(end, pos) == pos){
beg = end;
}
out.println("! " + beg);
}
}
}
static class Point{
public int x,y,z, ID;
public Point(int x, int y, int z, int ID){
this.x = x;
this.y = y;
this.z = z;
this.ID = ID;
}
@Override
public String toString() {
return "[" + x + " " + y + " " + z + " " + ID + "]";
}
}
static class SortByX implements Comparator<Point>{
@Override
public int compare(Point p1, Point p2) {
return Integer.compare(p1.x, p2.x);
}
}
static class SortByY implements Comparator<Point>{
@Override
public int compare(Point p1, Point p2) {
if (p1.y != p2.y) return Integer.compare(p1.y, p2.y);
if (p1.z > p2.z) return -1;
return 1;
}
}
// fast input reader class;
static class InputReader {
BufferedReader br;
StringTokenizer st;
public InputReader(InputStream stream) {
br = new BufferedReader(new InputStreamReader(stream));
}
public String nextToken() {
while (st == null || !st.hasMoreTokens()) {
String line = null;
try {
line = br.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
if (line == null) {
return null;
}
st = new StringTokenizer(line);
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(nextToken());
}
public long nextLong(){
return Long.parseLong(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 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
|
0656dd5fa58316a027434d6e87d864df
|
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 C1486 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int N = in.nextInt();
System.out.println("? 1 " + N);
System.out.flush();
int second = in.nextInt();
int low = -1;
int high = -1;
if (second != 1) {
System.out.println("? 1 " + second);
System.out.flush();
int answer = in.nextInt();
if (answer == second) {
low = 1;
high = second-1;
}
}
if (second != N) {
System.out.println("? " + second + " " + N);
System.out.flush();
int answer = in.nextInt();
if (answer == second) {
low = second+1;
high = N;
}
}
while (low != high) {
int mid = (low + high + ((low < second) ? 1 : 0))/2;
if (mid < second) {
System.out.println("? " + mid + " " + second);
} else {
System.out.println("? " + second + " " + mid);
}
System.out.flush();
int answer = in.nextInt();
if (mid < second) {
if (answer == second) {
low = mid;
} else {
high = mid-1;
}
} else {
if (answer == second) {
high = mid;
} else {
low = mid+1;
}
}
}
System.out.println("! " + low);
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
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.