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
|
1e7422c562f66ce201b05278747afb5b
|
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
|
//@author->.....future_me......//
//..............Learning.........//
/*Compete against yourself*/
import java.util.*;
import java.io.*;
import java.lang.*;
import java.math.BigInteger;
public class C {
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Code Starts <<<<<<<<<<<<<<<<<<<<<<<<<<<<< //
static FastReader sc = new FastReader();
static PrintWriter out = new PrintWriter(System.out);
public static void main(String[] args) throws Exception {
try {
// int t = sc.nextInt();
// while (t-- > 0)
C.go();
out.flush();
} catch (Exception e) {
return;
}
}
static void go() {
int n=sc.nextInt();
out.println("? "+1+" "+n);
out.flush();
int pos=sc.nextInt();
int l=1,r=n+1;
int ll=0;
int rr=0;
if(n==2) {
if(pos==1) {
out.println("!"+" "+ 2);
out.flush();
}else if (pos==2){
out.println("!"+" "+ 1);
out.flush();
}
return;
}
while(r-l>1) {
int mid=(r+l)/2;
int x=ask(l,r-1);
if(x<mid) {
int xx=ask(l,mid-1);
if(xx==x) {
r=mid;
}else {
l=mid;
}
}else {
int xx=ask(mid,r-1);
if(xx==x) {
l=mid;
}else {
r=mid;
}
}
}
out.println("! "+l);
out.flush();
}
static int ask(int l ,int r) {
if(l==r) {
return -1;
}
out.println("? "+l+" "+r);
out.flush();
int x=sc.nextInt();
return x;
}
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Code Ends <<<<<<<<<<<<<<<<<<<<<<<<<<<<< //
static int mod = (int) 1e9 + 7;
// Returns nCr % p using Fermat's
// little theorem.
static long fac[];
static long ncr(int n, int r, int p) {
if (n < r)
return 0;
// Base case
if (r == 0)
return 1;
// Fill factorial array so that we
// can find all factorial of r, n
// and n-r
return (fac[n] * modInverse(fac[r], p) % p * modInverse(fac[n - r], p) % p) % p;
}
private static long modInverse(long l, int p) {
return pow(l,p-2);
}
static void sort(long[] a) {
ArrayList<Long> aa = new ArrayList<>();
for (long i : a) {
aa.add(i);
}
Collections.sort(aa);
for (int i = 0; i < a.length; i++)
a[i] = aa.get(i);
}
static long pow(long x, long y) {
long res = 1l;
while (y != 0) {
if (y % 2 == 1) {
res = x * res % mod;
}
y /= 2;
x = (x * x) % mod;
}
return res;
}
//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Fast IO <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< //
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;
}
}
}
//use this for double quotes inside string
// " \"asdf\""
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
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
|
3e84dd4897e2ce5e7fc8e854a4d8108b
|
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.PrintStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.BufferedReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
C1GuessingTheGreatestEasyVersion solver = new C1GuessingTheGreatestEasyVersion();
solver.solve(1, in, out);
out.close();
}
static class C1GuessingTheGreatestEasyVersion {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.nextInt();
int ans = 1;
int lo = 1;
int hi = n;
while (lo + 1 < hi) {
int mid = (lo + hi) / 2;
System.out.println("? " + lo + " " + hi);
int q1 = in.nextInt();
if (q1 <= mid) {
System.out.println("? " + lo + " " + mid);
int q2 = in.nextInt();
if (q1 == q2) {
hi = mid;
} else
lo = mid + 1;
} else {
if (mid + 1 == hi) {
hi = mid;
continue;
}
System.out.println("? " + (mid + 1) + " " + hi);
int q2 = in.nextInt();
if (q2 == q1) {
lo = mid + 1;
} else {
hi = mid;
}
}
}
if (lo == hi) {
ans = lo;
} else {
System.out.println("? " + lo + " " + hi);
int q = in.nextInt();
if (q == lo) ans = hi;
else ans = lo;
}
System.out.println("! " + ans);
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void close() {
writer.close();
}
}
static class InputReader {
BufferedReader reader;
StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
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
|
b80952d1eb47fbac8b2abcc1ba04333a
|
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.lang.*;
import java.io.*;
public class GuessTheGreatest {
BufferedReader input;
BufferedWriter output;
StringTokenizer st;
int getElem(int start, int end) throws IOException {
output.write("? "+start+" "+end+"\n");
output.flush();
return Integer.parseInt(input.readLine());
}
int binarySearch(int start, int end, int last) throws IOException {
if(start==end){
return start;
}
if(last==-1)
last = getElem(start, end);
if(start+1==end){
if(last ==end)
return start;
else
return end;
}
int mid = (start+end)/2;
if(last <=mid){
int leftSecondPos = getElem(start, mid);
if(leftSecondPos== last)
return binarySearch(start, mid, leftSecondPos);
return binarySearch(mid+1, end, -1);
}else {
int rightSecondPos = getElem(mid, end);
if(rightSecondPos== last)
return binarySearch(mid, end, rightSecondPos);
return binarySearch(start, mid-1, -1);
}
}
// My Solution
void solve() throws IOException {
int n = Integer.parseInt(input.readLine());
int ans = binarySearch(1, n, -1);
output.write("! "+ans+"\n");
output.flush();
}
// Some basic functions
int min(int...i){
int min = Integer.MAX_VALUE;
for (int value : i) min = Math.min(min, value);
return min;
}
int max(int...i){
int max = Integer.MIN_VALUE;
for (int value : i) max = Math.max(max, value);
return max;
}
// Printing stuff
void print(int... i) throws IOException {
for (int value : i) output.write(value + " ");
}
void print(long... l) throws IOException {
for (long value : l) output.write(value + " ");
}
void print(String... s) throws IOException {
for (String value : s) output.write(value);
}
void nextLine() throws IOException {
output.write("\n");
}
// Taking Inputs
int[][] getIntMat(int n, int m) throws IOException {
int[][] mat = new int[n][m];
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
mat[i][j] = getInt();
return mat;
}
char[][] getCharMat(int n, int m) throws IOException {
char[][] mat = new char[n][m];
for (int i = 0; i < n; i++) {
String s = input.readLine();
for (int j = 0; j < m; j++)
mat[i][j] = s.charAt(j);
}
return mat;
}
int getInt() throws IOException {
if(st ==null || !st.hasMoreTokens())
st = new StringTokenizer(input.readLine());
return Integer.parseInt(st.nextToken());
}
int[] getInts(int n) throws IOException {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = getInt();
return a;
}
long getLong() throws IOException {
if(st==null || !st.hasMoreTokens())
st = new StringTokenizer(input.readLine());
return Long.parseLong(st.nextToken());
}
long[] getLongs(int n) throws IOException {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = getLong();
return a;
}
// Checks whether the code is running on OnlineJudge or LocalSystem
boolean isOnlineJudge() {
if (System.getProperty("ONLINE_JUDGE") != null)
return true;
try {
return System.getProperty("LOCAL")==null;
} catch (Exception e) {
return true;
}
}
// Handling CodeExecution
public static void main(String[] args) throws Exception {
new GuessTheGreatest().run();
}
void run() throws IOException {
// Defining Input Streams
if (isOnlineJudge()) {
input = new BufferedReader(new InputStreamReader(System.in));
output = new BufferedWriter(new OutputStreamWriter(System.out));
} else {
input = new BufferedReader(new FileReader("input.txt"));
output = new BufferedWriter(new FileWriter("output.txt"));
}
// Running Logic
solve();
output.flush();
// Run example test cases
if (!isOnlineJudge()) {
BufferedReader output = new BufferedReader(new FileReader("output.txt"));
BufferedReader answer = new BufferedReader(new FileReader("answer.txt"));
StringBuilder outFile = new StringBuilder();
StringBuilder ansFile = new StringBuilder();
String temp;
while ((temp = output.readLine()) != null)
outFile.append(temp.trim());
while ((temp = answer.readLine()) != null)
ansFile.append(temp.trim());
if (outFile.toString().equals(ansFile.toString()))
System.out.println("Test Cases Passed!!!");
else
System.out.println("Failed...");
}
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
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
|
7bce4c11301a816ff1c0a853ee3f9126
|
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.lang.*;
import java.io.*;
public class GuessTheGreatest {
BufferedReader input;
BufferedWriter output;
StringTokenizer st;
int getElem(int start, int end) throws IOException {
output.write("? "+start+" "+end+"\n");
output.flush();
return Integer.parseInt(input.readLine());
}
int binarySearch(int start, int end, int last) throws IOException {
if(start==end)
return start;
int secondPos = last;
if(last==-1)
secondPos = getElem(start, end);
if(start+1==end){
if(secondPos==end)
return start;
else
return end;
}
int mid = (start+end)/2;
if(secondPos<=mid){
int leftSecondPos = getElem(start, mid);
if(leftSecondPos==secondPos)
return binarySearch(start, mid, leftSecondPos);
return binarySearch(mid+1, end, -1);
}else {
int rightSecondPos = getElem(mid, end);
if(rightSecondPos==secondPos)
return binarySearch(mid, end, rightSecondPos);
return binarySearch(start, mid, -1);
}
}
// My Solution
void solve() throws IOException {
int n = Integer.parseInt(input.readLine());
int ans = binarySearch(1, n, -1);
output.write("! "+ans+"\n");
output.flush();
}
// Some basic functions
int min(int...i){
int min = Integer.MAX_VALUE;
for (int value : i) min = Math.min(min, value);
return min;
}
int max(int...i){
int max = Integer.MIN_VALUE;
for (int value : i) max = Math.max(max, value);
return max;
}
// Printing stuff
void print(int... i) throws IOException {
for (int value : i) output.write(value + " ");
}
void print(long... l) throws IOException {
for (long value : l) output.write(value + " ");
}
void print(String... s) throws IOException {
for (String value : s) output.write(value);
}
void nextLine() throws IOException {
output.write("\n");
}
// Taking Inputs
int[][] getIntMat(int n, int m) throws IOException {
int[][] mat = new int[n][m];
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
mat[i][j] = getInt();
return mat;
}
char[][] getCharMat(int n, int m) throws IOException {
char[][] mat = new char[n][m];
for (int i = 0; i < n; i++) {
String s = input.readLine();
for (int j = 0; j < m; j++)
mat[i][j] = s.charAt(j);
}
return mat;
}
int getInt() throws IOException {
if(st ==null || !st.hasMoreTokens())
st = new StringTokenizer(input.readLine());
return Integer.parseInt(st.nextToken());
}
int[] getInts(int n) throws IOException {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = getInt();
return a;
}
long getLong() throws IOException {
if(st==null || !st.hasMoreTokens())
st = new StringTokenizer(input.readLine());
return Long.parseLong(st.nextToken());
}
long[] getLongs(int n) throws IOException {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = getLong();
return a;
}
// Checks whether the code is running on OnlineJudge or LocalSystem
boolean isOnlineJudge() {
if (System.getProperty("ONLINE_JUDGE") != null)
return true;
try {
return System.getProperty("LOCAL")==null;
} catch (Exception e) {
return true;
}
}
// Handling CodeExecution
public static void main(String[] args) throws Exception {
new GuessTheGreatest().run();
}
void run() throws IOException {
// Defining Input Streams
if (isOnlineJudge()) {
input = new BufferedReader(new InputStreamReader(System.in));
output = new BufferedWriter(new OutputStreamWriter(System.out));
} else {
input = new BufferedReader(new FileReader("input.txt"));
output = new BufferedWriter(new FileWriter("output.txt"));
}
// Running Logic
solve();
output.flush();
// Run example test cases
if (!isOnlineJudge()) {
BufferedReader output = new BufferedReader(new FileReader("output.txt"));
BufferedReader answer = new BufferedReader(new FileReader("answer.txt"));
StringBuilder outFile = new StringBuilder();
StringBuilder ansFile = new StringBuilder();
String temp;
while ((temp = output.readLine()) != null)
outFile.append(temp.trim());
while ((temp = answer.readLine()) != null)
ansFile.append(temp.trim());
if (outFile.toString().equals(ansFile.toString()))
System.out.println("Test Cases Passed!!!");
else
System.out.println("Failed...");
}
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
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
|
8ba304a5a52617c3919a16eeb6c1128f
|
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
|
/*input
5
3
4
*/
import java.util.*;
import java.lang.*;
import java.io.*;
public class Main
{
static PrintWriter out;
static int MOD = 1000000007;
static FastReader scan;
/*-------- I/O using short named function ---------*/
public static String ns(){return scan.next();}
public static int ni(){return scan.nextInt();}
public static long nl(){return scan.nextLong();}
public static double nd(){return scan.nextDouble();}
public static String nln(){return scan.nextLine();}
public static void p(Object o){out.print(o);}
public static void ps(Object o){out.print(o + " ");}
public static void pn(Object o){out.println(o);}
/*-------- for output of an array ---------------------*/
static void iPA(int arr []){
StringBuilder output = new StringBuilder();
for(int i=0; i<arr.length; i++)output.append(arr[i] + " ");out.println(output);
}
static void lPA(long arr []){
StringBuilder output = new StringBuilder();
for(int i=0; i<arr.length; i++)output.append(arr[i] + " ");out.println(output);
}
static void sPA(String arr []){
StringBuilder output = new StringBuilder();
for(int i=0; i<arr.length; i++)output.append(arr[i] + " ");out.println(output);
}
static void dPA(double arr []){
StringBuilder output = new StringBuilder();
for(int i=0; i<arr.length; i++)output.append(arr[i] + " ");out.println(output);
}
/*-------------- for input in an array ---------------------*/
static void iIA(int arr[]){
for(int i=0; i<arr.length; i++)arr[i] = ni();
}
static void lIA(long arr[]){
for(int i=0; i<arr.length; i++)arr[i] = nl();
}
static void sIA(String arr[]){
for(int i=0; i<arr.length; i++)arr[i] = ns();
}
static void dIA(double arr[]){
for(int i=0; i<arr.length; i++)arr[i] = nd();
}
/*------------ for taking input faster ----------------*/
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
// Method to check if x is power of 2
static boolean isPowerOfTwo (int x) { return x!=0 && ((x&(x-1)) == 0);}
//Method to return lcm of two numbers
static int gcd(int a, int b){return a==0?b:gcd(b % a, a); }
//Method to count digit of a number
static int countDigit(long n){return (int)Math.floor(Math.log10(n) + 1);}
//Method for sorting
static void ruffle_sort(int[] a) {
//shandom_ruffle
Random r=new Random();
int n=a.length;
for (int i=0; i<n; i++) {
int oi=r.nextInt(n);
int temp=a[i];
a[i]=a[oi];
a[oi]=temp;
}
//sort
Arrays.sort(a);
}
//Method for checking if a number is prime or not
static boolean isPrime(int n) {
if (n <= 1) return false;
if (n <= 3) return true;
if (n % 2 == 0 || n % 3 == 0) return false;
for (int i = 5; i * i <= n; i = i + 6)
if (n % i == 0 || n % (i + 2) == 0)
return false;
return true;
}
public static void main (String[] args) throws java.lang.Exception
{
OutputStream outputStream =System.out;
out =new PrintWriter(outputStream);
scan =new FastReader();
//for fast output sometimes
StringBuilder sb = new StringBuilder();
int l=1, r= ni(), ans=0;
while (l<r) {
int mid = (l + r)/2;
if(r -l ==1){
int temp2 = askQuery(l, r);
if(temp2 == l)
ans = r;
else
ans = l;
break;
}
int smax = askQuery(l, r);
if(smax>=mid){
int temp = askQuery(mid, r);
if(temp == smax){
l = mid;
}else{
r = mid;
}
}else{
int temp = askQuery(l, mid);
if(temp == smax){
r = mid;
}else{
l = mid;
}
}
}
pn("! " + ans);
out.flush();
out.close();
}
static int askQuery(int l, int r){
pn("? " + l + " " + r);
out.flush();
int n = ni();
return 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 11
|
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
|
58fe4feb91a4f75e6b6a5512daa4b838
|
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
|
/*input
5
3
4
*/
import java.util.*;
import java.lang.*;
import java.io.*;
public class Main
{
static PrintWriter out;
static int MOD = 1000000007;
static FastReader scan;
/*-------- I/O using short named function ---------*/
public static String ns(){return scan.next();}
public static int ni(){return scan.nextInt();}
public static long nl(){return scan.nextLong();}
public static double nd(){return scan.nextDouble();}
public static String nln(){return scan.nextLine();}
public static void p(Object o){out.print(o);}
public static void ps(Object o){out.print(o + " ");}
public static void pn(Object o){out.println(o);}
/*-------- for output of an array ---------------------*/
static void iPA(int arr []){
StringBuilder output = new StringBuilder();
for(int i=0; i<arr.length; i++)output.append(arr[i] + " ");out.println(output);
}
static void lPA(long arr []){
StringBuilder output = new StringBuilder();
for(int i=0; i<arr.length; i++)output.append(arr[i] + " ");out.println(output);
}
static void sPA(String arr []){
StringBuilder output = new StringBuilder();
for(int i=0; i<arr.length; i++)output.append(arr[i] + " ");out.println(output);
}
static void dPA(double arr []){
StringBuilder output = new StringBuilder();
for(int i=0; i<arr.length; i++)output.append(arr[i] + " ");out.println(output);
}
/*-------------- for input in an array ---------------------*/
static void iIA(int arr[]){
for(int i=0; i<arr.length; i++)arr[i] = ni();
}
static void lIA(long arr[]){
for(int i=0; i<arr.length; i++)arr[i] = nl();
}
static void sIA(String arr[]){
for(int i=0; i<arr.length; i++)arr[i] = ns();
}
static void dIA(double arr[]){
for(int i=0; i<arr.length; i++)arr[i] = nd();
}
/*------------ for taking input faster ----------------*/
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
// Method to check if x is power of 2
static boolean isPowerOfTwo (int x) { return x!=0 && ((x&(x-1)) == 0);}
//Method to return lcm of two numbers
static int gcd(int a, int b){return a==0?b:gcd(b % a, a); }
//Method to count digit of a number
static int countDigit(long n){return (int)Math.floor(Math.log10(n) + 1);}
//Method for sorting
static void ruffle_sort(int[] a) {
//shandom_ruffle
Random r=new Random();
int n=a.length;
for (int i=0; i<n; i++) {
int oi=r.nextInt(n);
int temp=a[i];
a[i]=a[oi];
a[oi]=temp;
}
//sort
Arrays.sort(a);
}
//Method for checking if a number is prime or not
static boolean isPrime(int n) {
if (n <= 1) return false;
if (n <= 3) return true;
if (n % 2 == 0 || n % 3 == 0) return false;
for (int i = 5; i * i <= n; i = i + 6)
if (n % i == 0 || n % (i + 2) == 0)
return false;
return true;
}
public static void main (String[] args) throws java.lang.Exception
{
OutputStream outputStream =System.out;
out =new PrintWriter(outputStream);
scan =new FastReader();
//for fast output sometimes
StringBuilder sb = new StringBuilder();
int l=1, r= ni(), ans=0;
while (l<r) {
int mid = (l + r)/2;
if(r -l ==1){
int temp2 = askQuery(l, r);
if(temp2 == l)
ans = r;
else
ans = l;
break;
}
int smax = askQuery(l, r);
if(smax>=mid){
int temp = askQuery(mid, r);
if(temp == smax){
l = mid;
}else{
r = mid-1;
}
}else{
int temp = askQuery(l, mid);
if(temp == smax){
r = mid;
}else{
l = mid+1;
}
}
}
if(ans==0)
pn("! " + l);
else
pn("! " + ans);
out.flush();
out.close();
}
static int askQuery(int l, int r){
pn("? " + l + " " + r);
out.flush();
int n = ni();
return 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 11
|
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
|
ec56b7a08b823d88278aa757164d69e5
|
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 Solution{
public static void main(String[] args) {
TaskA solver = new TaskA();
// int t = in.nextInt();
// for (int i = 1; i <= t ; i++) {
// solver.solve(i, in, out);
// }
solver.solve(1, in, out);
out.flush();
out.close();
}
static class TaskA {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n= in.nextInt();
int l=1;int r=n;
while(l<r) {
int mid=(l+r)/2;
if(mid==l) {
int x=query(l,r);
if(x==l) {
System.out.println("! "+r);return;
}
else {
System.out.println("! "+l);return;
}
}
int x=query(l,r);
if(x<mid) {
if(mid==l+1){
l=mid;
continue;
}
int y=query(l,mid-1);
if(x==y) {
r=mid-1;
}
else {
l=mid;
}
}
else {
int y=query(mid,r);
if(x==y) {
l=mid;
}
else {
r=mid;
}
}
}
}
}
static int query(int l,int r) {
System.out.println("? "+l+" "+r);
System.out.print ("\n");
int x=in.nextInt();
return x;
}
static boolean check(Pair[]arr,int mid,int n) {
int c=0;
for(int i=0;i<n;i++) {
if(mid-1-arr[i].first<=c&&c<=arr[i].second) {
c++;
}
}
return c>=mid;
}
static long sum(int[]arr) {
long s=0;
for(int x:arr) {
s+=x;
}
return s;
}
static long sum(long[]arr) {
long s=0;
for(long x:arr) {
s+=x;
}
return s;
}
static int gcd(int a, int b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
static void sort(int[] a) {
ArrayList<Integer> q = new ArrayList<>();
for (int i : a) q.add(i);
Collections.sort(q);
for (int i = 0; i < a.length; i++) a[i] = q.get(i);
}
static void sort(long[] a) {
ArrayList<Long> q = new ArrayList<>();
for (long i : a) q.add(i);
Collections.sort(q);
for (int i = 0; i < a.length; i++) a[i] = q.get(i);
}
static void println(int[][]arr) {
for(int i=0;i<arr.length;i++) {
for(int j=0;j<arr[0].length;j++) {
print(arr[i][j]+" ");
}
print("\n");
}
}
static void println(long[][]arr) {
for(int i=0;i<arr.length;i++) {
for(int j=0;j<arr[0].length;j++) {
print(arr[i][j]+" ");
}
print("\n");
}
}
static void println(int[]arr){
for(int i=0;i<arr.length;i++) {
print(arr[i]+" ");
}
print("\n");
}
static void println(long[]arr){
for(int i=0;i<arr.length;i++) {
print(arr[i]+" ");
}
print("\n");
}
static long[]input(int n){
long[]arr=new long[n];
for(int i=0;i<n;i++) {
arr[i]=in.nextInt();
}
return arr;
}
static long[]input(){
long n= in.nextInt();
long[]arr=new long[(int)n];
for(int i=0;i<n;i++) {
arr[i]=in.nextLong();
}
return arr;
}
////////////////////////////////////////////////////////
static class Pair {
long first;
long second;
Pair(long x, long y)
{
this.first = x;
this.second = y;
}
}
static void sortS(Pair arr[])
{
Arrays.sort(arr, new Comparator<Pair>() {
@Override public int compare(Pair p1, Pair p2)
{
return (int)(p1.second - p2.second);
}
});
}
static void sortF(Pair arr[])
{
Arrays.sort(arr, new Comparator<Pair>() {
@Override public int compare(Pair p1, Pair p2)
{
return (int)(p1.first - p2.first);
}
});
}
/////////////////////////////////////////////////////////////
static InputStream inputStream = System.in;
static OutputStream outputStream = System.out;
static InputReader in = new InputReader(inputStream);
static PrintWriter out = new PrintWriter(outputStream);
static void println(long c) {
out.println(c);
}
static void print(long c) {
out.print(c);
}
static void print(int c) {
out.print(c);
}
static void println(int x) {
out.println(x);
}
static void print(String s) {
out.print(s);
}
static void println(String s) {
out.println(s);
}
static void println(boolean b) {
out.println(b);
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
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
|
fb515ec9cfe58323bf31268989b5385f
|
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 Solution{
public static void main(String[] args) {
TaskA solver = new TaskA();
// int t = in.nextInt();
// for (int i = 1; i <= t ; i++) {
// solver.solve(i, in, out);
// }
solver.solve(1, in, out);
out.flush();
out.close();
}
static class TaskA {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n= in.nextInt();
int l=0;int r=n;
while(r-l>1) {
int m=(l+r)/2;
int x=query(l,r-1);
if(x<m) {
if(query(l,m-1)==x) {
r=m;
}
else {
l=m;
}
}
else {
if(query(m,r-1)==x) {
l=m;
}
else {
r=m;
}
}
}
System.out.println("! "+r);
System.out.print("\n");
System.out.flush();
}
}
static int query(int l,int r) {
if(l>=r) {
return -1;
}
System.out.println("? "+(l+1)+" "+(r+1));
System.out.print ("\n");
int x=in.nextInt()-1;
return x;
}
static boolean check(Pair[]arr,int mid,int n) {
int c=0;
for(int i=0;i<n;i++) {
if(mid-1-arr[i].first<=c&&c<=arr[i].second) {
c++;
}
}
return c>=mid;
}
static long sum(int[]arr) {
long s=0;
for(int x:arr) {
s+=x;
}
return s;
}
static long sum(long[]arr) {
long s=0;
for(long x:arr) {
s+=x;
}
return s;
}
static int gcd(int a, int b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
static void sort(int[] a) {
ArrayList<Integer> q = new ArrayList<>();
for (int i : a) q.add(i);
Collections.sort(q);
for (int i = 0; i < a.length; i++) a[i] = q.get(i);
}
static void sort(long[] a) {
ArrayList<Long> q = new ArrayList<>();
for (long i : a) q.add(i);
Collections.sort(q);
for (int i = 0; i < a.length; i++) a[i] = q.get(i);
}
static void println(int[][]arr) {
for(int i=0;i<arr.length;i++) {
for(int j=0;j<arr[0].length;j++) {
print(arr[i][j]+" ");
}
print("\n");
}
}
static void println(long[][]arr) {
for(int i=0;i<arr.length;i++) {
for(int j=0;j<arr[0].length;j++) {
print(arr[i][j]+" ");
}
print("\n");
}
}
static void println(int[]arr){
for(int i=0;i<arr.length;i++) {
print(arr[i]+" ");
}
print("\n");
}
static void println(long[]arr){
for(int i=0;i<arr.length;i++) {
print(arr[i]+" ");
}
print("\n");
}
static long[]input(int n){
long[]arr=new long[n];
for(int i=0;i<n;i++) {
arr[i]=in.nextInt();
}
return arr;
}
static long[]input(){
long n= in.nextInt();
long[]arr=new long[(int)n];
for(int i=0;i<n;i++) {
arr[i]=in.nextLong();
}
return arr;
}
////////////////////////////////////////////////////////
static class Pair {
long first;
long second;
Pair(long x, long y)
{
this.first = x;
this.second = y;
}
}
static void sortS(Pair arr[])
{
Arrays.sort(arr, new Comparator<Pair>() {
@Override public int compare(Pair p1, Pair p2)
{
return (int)(p1.second - p2.second);
}
});
}
static void sortF(Pair arr[])
{
Arrays.sort(arr, new Comparator<Pair>() {
@Override public int compare(Pair p1, Pair p2)
{
return (int)(p1.first - p2.first);
}
});
}
/////////////////////////////////////////////////////////////
static InputStream inputStream = System.in;
static OutputStream outputStream = System.out;
static InputReader in = new InputReader(inputStream);
static PrintWriter out = new PrintWriter(outputStream);
static void println(long c) {
out.println(c);
}
static void print(long c) {
out.print(c);
}
static void print(int c) {
out.print(c);
}
static void println(int x) {
out.println(x);
}
static void print(String s) {
out.print(s);
}
static void println(String s) {
out.println(s);
}
static void println(boolean b) {
out.println(b);
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
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
|
5134e3ceef40eefdbad9a761c608ed10
|
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 rd = new BufferedReader(new InputStreamReader(System.in));
static BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(System.out));
static StringTokenizer tok;
public static void main(String[] args) throws Exception {
solution();
}
public static void solution() throws Exception {
// arr = new int[]{9,1,2,3,4,10,5,6,7,8};
// int n = arr.length;
int n = Integer.parseInt(rd.readLine());
int res = sol_rec(1,n);
System.out.println("! "+res);
}
public static int sol_rec(int left, int right) throws Exception {
int Mid = sol_query(left,right);
int fMid = -1, fLeft = left, fRight = Mid-1;
// 첫번째로 중간값을 찾는다.
if(Mid > left) fMid = sol_query(left,Mid);
// 찾은 중간값이 맨 왼쪽값이 아니라면, 왼쪽값중에 최댓값이 있는지 탐색한다.
while(fMid == Mid) {
// 최댓값이 있는경우 왼쪽값 내부로 탐색한다.
int gLeft = fLeft;
fLeft = (fLeft + fRight)/2;
// 이진탐색을 위하여 기준값을 절반으로 나눈다.
fMid = sol_query(fLeft, Mid);
// 해당 절반값에 최댓값이 존재하는지 확인한다.
if(fMid != Mid) {
// 절반값에 없다면 절반값 바깥쪽에 있는 것이므로 바깥쪽의 재차 절반체크를 위해 값을 조정한다.
fRight = fLeft-1;
fLeft = gLeft;
fMid = Mid;
}
if(fRight == fLeft) return fLeft;
else if (fRight - fLeft <= 1) return sol_res2(fLeft,fRight);
// 값이 줄어들어서 특정할 수 있게되면 출력한다.
}
fLeft = Mid+1;
fRight = right;
while(true) {
int gRight = fRight;
fRight = (fLeft+fRight)/2;
fMid = sol_query(Mid, fRight);
if(fMid != Mid) {
fLeft = fRight+1;
fRight = gRight;
fMid = Mid;
}
if(fRight == fLeft) return fLeft;
else if(fRight - fLeft <= 1) return sol_res2(fLeft,fRight);
}
}
public static int sol_query(int left, int right) throws Exception {
System.out.println("? "+left +" "+right);
System.out.flush();
return Integer.parseInt(rd.readLine());
// System.out.println(left+" "+right);
// int[] copy = new int[right-left+1];
// int copc = 0;
// for(int i=left-1;i<right;i++) copy[copc++] = arr[i];
// Arrays.sort(copy);
// int sec = copy[copy.length-2];
// for(int i=left-1;i<right;i++) {
// if( sec == arr[i]) return i+1;
// }
// return -1;
}
public static int sol_res2(int left, int right) throws Exception {
int q = sol_query(left,right);
return q == left ? right : left;
}
static int[] arr;
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
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
|
4c56b1974639a4d5450d24df748b88c7
|
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 cf {
static Reader sc = new Reader();
// static Scanner sc = new Scanner(System.in);
static PrintWriter out = new PrintWriter(System.out);
public static void main(String[] args) {
int n = sc.nextInt();
int ans = -1;
int index = query(1, n);
if (index == 1 || query(1, index) != index) {
ans = n;
// binary search
int l = index, r = n;
while (l < r) {
int mid = l + (r - l) / 2;
if (l + 1 == r) {
if (l > index && query(index, l) == index) {
ans = l;
} else {
ans = r;
}
break;
}
if (index == mid)
break;
if (query(index, mid) == index) {
ans = mid;
r = mid;
} else {
l = mid;
}
}
} else {
ans = 1;
// binary search
int l = 1, r = index;
while (l < r) {
int mid = l + (r - l) / 2;
if (l + 1 == r) {
if (r < index && query(r, index) == index) {
ans = r;
} else {
ans = l;
}
break;
}
if (index == mid)
break;
if (query(mid, index) == index) {
ans = mid;
l = mid;
} else {
r = mid;
}
}
}
out.println("! " + ans);
out.close();
}
private static int query(int x, int y) {
out.println("? " + x + " " + y);
out.flush();
return sc.nextInt();
}
static class Reader {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer("");
String next() {
while (!st.hasMoreTokens())
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
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
|
429cf79523e50fd099acfe7bb4771dec
|
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 cf {
static Reader sc = new Reader();
// static Scanner sc = new Scanner(System.in);
static PrintWriter out = new PrintWriter(System.out);
public static void main(String[] args) {
int n = sc.nextInt();
int ans = -1;
int index = query(1, n);
if (index == 1 || query(1, index) != index) {
ans = n;
// binary search
int l = index, r = n;
while (l <= r) {
int mid = l + (r - l) / 2;
if (l + 1 == r) {
if (l > index && query(index, l) == index) {
ans = l;
} else if (query(index, r) == index) {
ans = r;
}
break;
}
if (index == mid)
break;
if (query(index, mid) == index) {
ans = mid;
r = mid;
} else {
l = mid;
}
}
} else {
ans = 1;
// binary search
int l = 1, r = index;
while (l <= r) {
int mid = l + (r - l) / 2;
if (l + 1 == r) {
if (r < index && query(r, index) == index) {
ans = r;
} else if (query(l, index) == index) {
ans = l;
}
break;
}
if (index == mid)
break;
if (query(mid, index) == index) {
ans = mid;
l = mid;
} else {
r = mid;
}
}
}
out.println("! " + ans);
out.close();
}
private static int query(int x, int y) {
out.println("? " + x + " " + y);
out.flush();
return sc.nextInt();
}
static class Reader {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer("");
String next() {
while (!st.hasMoreTokens())
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
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
|
21865ac43cd3362032c5c86d51b123ac
|
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
{
BufferedReader Rb = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.valueOf(Rb.readLine());
int l = 1;
int r = n;
while(true)
{
System.out.println("? " + l + " " + r);
System.out.flush();
int pos = Integer.valueOf(Rb.readLine());
if(r - l == 1)
{
System.out.println("! " + (pos == l?r:l));
System.out.flush();
break;
}
int n_l = l, n_r = r;
if(pos > (l + r)/2)
{n_l = (l+r)/2;}
else
{n_r = (l+r)/2;}
System.out.println("? " + n_l + " " + n_r);
System.out.flush();
int n_pos = Integer.valueOf(Rb.readLine());
if(n_pos == pos)
{l = n_l; r = n_r;}
else
{
if(n_l == l)
{l = (l + r)/2;}
else
{r = (l + r)/2;}
}
}
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
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
|
8da0ccec0e71f495dc335ee3bbce7dc5
|
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.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.InputMismatchException;
import java.util.TreeMap;
import java.util.*;
import java.io.*;
public class Main {
static StringBuilder sb;
static dsu dsu;
static long fact[];
static long mod = (int) (1e9);
static void solve() {
int n = i();
int l = 1;
int r = n;
while(l<r){
int mid = l+((r-l)>>1);
System.out.println("? "+l+" "+r);
System.out.flush();
int pos1 = i();
if(pos1<=mid){
if(l==mid) l = mid+1;
else{
System.out.println("? "+l+" "+mid);
System.out.flush();
int pos2 = i();
if(pos1==pos2) r = mid;
else l = mid+1;
}
}else{
if(mid+1==r) r = mid;
else{
System.out.println("? "+(mid+1)+" "+r);
System.out.flush();
int pos2 = i();
if(pos1==pos2) l = mid+1;
else r = mid;
}
}
}
System.out.println("! "+l);
System.out.flush();
}
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 11
|
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
|
f439d0274e7d68a05a16c143afe41ae6
|
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.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.*;
public class Main {
static StringBuilder sb;
static dsu dsu;
static long fact[];
static long mod = (int) (1e9);
static void solve() {
int n = i();
int idx = search(1,n);
System.out.println("! "+idx);
System.out.flush();
}
private static int search(int low,int high){
while(low<high){
int mid = low + (high-low)/2;
System.out.println("? "+low+" "+high);
int secondMaxIdx = i();
System.out.flush();
if(secondMaxIdx>mid){
if(mid+1==high) high = mid;
else{
System.out.println("? "+(mid+1)+" "+high);
int temp = i();
System.out.flush();
if(temp==secondMaxIdx) low = mid+1;
else high = mid;
}
}else{
if(low==mid) low = mid+1;
else{
System.out.println("? "+low+" "+mid);
int temp = i();
System.out.flush();
if(temp==secondMaxIdx) high = mid;
else low = mid+1;
}
}
}
return low;
}
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 11
|
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
|
526d7d7a2c7c8a1a6bd17650b8d67c10
|
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
|
/*
Rating: 1461
Date: 11-04-2022
Time: 12-38-28
Author: Kartik Papney
Linkedin: https://www.linkedin.com/in/kartik-papney-4951161a6/
Leetcode: https://leetcode.com/kartikpapney/
Codechef: https://www.codechef.com/users/kartikpapney
*/
import java.util.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class C_1_Guessing_the_Greatest_easy_version {
public static boolean debug = false;
static void debug(String st) {
if(debug) p.writeln(st);
}
public static int ask(int left, int right) {
if(left >= right) return -1;
System.out.println("? " + left + " " + right);
System.out.println();
int pos = sc.nextInt();
sc.nextLine();
return pos;
}
// 1 2 3 4 5 6 7
//
public static void s() {
int n = sc.nextInt();
sc.nextLine();
int left = 1;
int right = n;
while(left < right) {
// [l, mid), [mid, r]
int mid = left+(right - left)/2;
int smax = ask(left, right);
if(smax <= mid) {
int npos = ask(left, mid);
if(npos == smax) {
right = mid;
} else {
left = mid+1;
}
} else {
int npos = ask(mid+1, right);
if(npos == smax) {
left = mid+1;
} else {
right = mid;
}
}
}
// int smax = ask(left, right);
// if(smax == left) {
// } else {
// System.out.println("! " + left);
// }
System.out.println("! " + right);
}
public static void main(String[] args) {
int t = 1;
// t = sc.nextInt();
while (t-- != 0) {
s();
}
p.print();
}
static final Integer MOD = (int) 1e9 + 7;
static final Scanner sc = new Scanner(System.in);
static final Print p = new Print();
static class Functions {
static void sort(int... a) {
ArrayList<Integer> l = new ArrayList<>();
for (int i : a) l.add(i);
Collections.sort(l);
for (int i = 0; i < a.length; i++) a[i] = l.get(i);
}
static void sort(long... a) {
ArrayList<Long> l = new ArrayList<>();
for (long i : a) l.add(i);
Collections.sort(l);
for (int i = 0; i < a.length; i++) a[i] = l.get(i);
}
static int max(int... a) {
int max = Integer.MIN_VALUE;
for (int val : a) max = Math.max(val, max);
return max;
}
static int min(int... a) {
int min = Integer.MAX_VALUE;
for (int val : a) min = Math.min(val, min);
return min;
}
static long min(long... a) {
long min = Long.MAX_VALUE;
for (long val : a) min = Math.min(val, min);
return min;
}
static long max(long... a) {
long max = Long.MIN_VALUE;
for (long val : a) max = Math.max(val, max);
return max;
}
static long sum(long... a) {
long sum = 0;
for (long val : a) sum += val;
return sum;
}
static int sum(int... a) {
int sum = 0;
for (int val : a) sum += val;
return sum;
}
public static long mod_add(long a, long b) {
return (a % MOD + b % MOD + MOD) % MOD;
}
public static long pow(long a, long b) {
long res = 1;
while (b > 0) {
if ((b & 1) != 0)
res = mod_mul(res, a);
a = mod_mul(a, a);
b >>= 1;
}
return res;
}
public static long mod_mul(long a, long b) {
long res = 0;
a %= MOD;
while (b > 0) {
if ((b & 1) > 0) {
res = mod_add(res, a);
}
a = (2 * a) % MOD;
b >>= 1;
}
return res;
}
public static long gcd(long a, long b) {
if (a == 0) return b;
return gcd(b % a, a);
}
public static long factorial(long n) {
long res = 1;
for (int i = 1; i <= n; i++) {
res = (i % MOD * res % MOD) % MOD;
}
return res;
}
public static int count(int[] arr, int x) {
int count = 0;
for (int val : arr) if (val == x) count++;
return count;
}
public static ArrayList<Integer> generatePrimes(int n) {
boolean[] primes = new boolean[n];
for (int i = 2; i < primes.length; i++) primes[i] = true;
for (int i = 2; i < primes.length; i++) {
if (primes[i]) {
for (int j = i * i; j < primes.length; j += i) {
primes[j] = false;
}
}
}
ArrayList<Integer> arr = new ArrayList<>();
for (int i = 0; i < primes.length; i++) {
if (primes[i]) arr.add(i);
}
return arr;
}
}
static class Print {
StringBuffer strb = new StringBuffer();
public void write(Object str) {
strb.append(str);
}
public void writes(Object str) {
char c = ' ';
strb.append(str).append(c);
}
public void writeln(Object str) {
char c = '\n';
strb.append(str).append(c);
}
public void yes() {
char c = '\n';
writeln("YES");
}
public void no() {
writeln("NO");
}
public void writeln() {
char c = '\n';
strb.append(c);
}
public void writes(int... arr) {
for (int val : arr) {
write(val);
write(' ');
}
}
public void writes(long... arr) {
for (long val : arr) {
write(val);
write(' ');
}
}
public void writeln(int... arr) {
for (int val : arr) {
writeln(val);
}
}
public void print() {
System.out.print(strb);
}
public void println() {
System.out.println(strb);
}
}
// 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());
// }
// 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;
// }
// double[] readArrayDouble(int n) {
// double[] a = new double[n];
// for (int i = 0; i < n; i++) a[i] = nextInt();
// return a;
// }
// String nextLine() {
// String str = new String();
// try {
// str = br.readLine();
// } catch (IOException e) {
// e.printStackTrace();
// }
// return str;
// }
// }
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
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
|
5d99a07d84653e735e08286412ab24d4
|
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.lang.*;
import java.io.*;
public class feb20 {
// *** ++
// +=-==+ +++=-
// +-:---==+ *+=----=
// +-:------==+ ++=------==
// =-----------=++=========================
// +--:::::---:-----============-=======+++====
// +---:..:----::-===============-======+++++++++
// =---:...---:-===================---===++++++++++
// +----:...:-=======================--==+++++++++++
// +-:------====================++===---==++++===+++++
// +=-----======================+++++==---==+==-::=++**+
// +=-----================---=======++=========::.:-+*****
// +==::-====================--: --:-====++=+===:..-=+*****
// +=---=====================-... :=..:-=+++++++++===++*****
// +=---=====+=++++++++++++++++=-:::::-====+++++++++++++*****+
// +=======++++++++++++=+++++++============++++++=======+******
// +=====+++++++++++++++++++++++++==++++==++++++=:... . .+****
// ++====++++++++++++++++++++++++++++++++++++++++-. ..-+****
// +======++++++++++++++++++++++++++++++++===+====:. ..:=++++
// +===--=====+++++++++++++++++++++++++++=========-::....::-=++*
// ====--==========+++++++==+++===++++===========--:::....:=++*
// ====---===++++=====++++++==+++=======-::--===-:. ....:-+++
// ==--=--====++++++++==+++++++++++======--::::...::::::-=+++
// ===----===++++++++++++++++++++============--=-==----==+++
// =--------====++++++++++++++++=====================+++++++
// =---------=======++++++++====+++=================++++++++
// -----------========+++++++++++++++=================+++++++
// =----------==========++++++++++=====================++++++++
// =====------==============+++++++===================+++==+++++
// =======------==========================================++++++
/*
* created by : Nitesh Gupta
*
*/
public static void main(String[] args) throws Exception {
first();
// sec();
// third();
// four();
// fif();
// six();
}
private static void first() throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] scn = (br.readLine()).trim().split(" ");
int n = Integer.parseInt(scn[0]);
int sm = ask(1, n);
int left = ask(1, sm);
int ans = 1;
if (left == sm) {
int st = 1, en = sm - 1;
while (st <= en) {
int mid = (st + en) / 2;
int pos = ask(mid, sm);
if (pos == sm) {
ans = mid;
st = mid + 1;
} else {
en = mid - 1;
}
}
} else {
int st = sm + 1, en = n;
while (st <= en) {
int mid = (st + en) / 2;
int pos = ask(sm, mid);
if (pos == sm) {
ans = mid;
en = mid - 1;
} else {
st = mid + 1;
}
}
}
System.out.println("! " + ans);
return;
}
public static int ask(int l, int r) throws Exception {
if(l==r)return -1;
System.out.println("? " + l + " " + r);
System.out.flush();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] scn = (br.readLine()).trim().split(" ");
int n = Integer.parseInt(scn[0]);
return n;
}
private static void sec() throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] scn = (br.readLine()).trim().split(" ");
int t = Integer.parseInt(scn[0]);
StringBuilder sb = new StringBuilder();
while (t-- > 0) {
scn = (br.readLine()).trim().split(" ");
int n = Integer.parseInt(scn[0]);
long[] arr = new long[n];
scn = (br.readLine()).trim().split(" ");
for (int i = 0; i < n; i++) {
arr[i] = Long.parseLong(scn[i]);
}
sb.append("\n");
}
System.out.println(sb);
return;
}
private static void third() throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] scn = (br.readLine()).trim().split(" ");
int t = Integer.parseInt(scn[0]);
StringBuilder sb = new StringBuilder();
while (t-- > 0) {
scn = (br.readLine()).trim().split(" ");
int n = Integer.parseInt(scn[0]);
long[] arr = new long[n];
scn = (br.readLine()).trim().split(" ");
for (int i = 0; i < n; i++) {
arr[i] = Long.parseLong(scn[i]);
}
sb.append("\n");
}
System.out.println(sb);
return;
}
private static void four() throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] scn = (br.readLine()).trim().split(" ");
int t = Integer.parseInt(scn[0]);
StringBuilder sb = new StringBuilder();
while (t-- > 0) {
scn = (br.readLine()).trim().split(" ");
int n = Integer.parseInt(scn[0]);
long[] arr = new long[n];
scn = (br.readLine()).trim().split(" ");
for (int i = 0; i < n; i++) {
arr[i] = Long.parseLong(scn[i]);
}
sb.append("\n");
}
System.out.println(sb);
return;
}
private static void fif() throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] scn = (br.readLine()).trim().split(" ");
int t = Integer.parseInt(scn[0]);
StringBuilder sb = new StringBuilder();
while (t-- > 0) {
scn = (br.readLine()).trim().split(" ");
int n = Integer.parseInt(scn[0]);
long[] arr = new long[n];
scn = (br.readLine()).trim().split(" ");
for (int i = 0; i < n; i++) {
arr[i] = Long.parseLong(scn[i]);
}
sb.append("\n");
}
System.out.println(sb);
return;
}
private static void six() throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] scn = (br.readLine()).trim().split(" ");
int t = Integer.parseInt(scn[0]);
StringBuilder sb = new StringBuilder();
while (t-- > 0) {
scn = (br.readLine()).trim().split(" ");
int n = Integer.parseInt(scn[0]);
long[] arr = new long[n];
scn = (br.readLine()).trim().split(" ");
for (int i = 0; i < n; i++) {
arr[i] = Long.parseLong(scn[i]);
}
sb.append("\n");
}
System.out.println(sb);
return;
}
public static void sort(long[] arr) {
int n = arr.length;
for (int i = 0; i < n; i++) {
int idx = (int) Math.random() * n;
long temp = arr[i];
arr[i] = arr[idx];
arr[idx] = temp;
}
Arrays.sort(arr);
}
public static void print(long[][] dp) {
for (long[] a : dp) {
for (long ele : a) {
System.out.print(ele + " ");
}
System.out.println();
}
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
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
|
c9fbffc3d82c157c7d964f381f604f95
|
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.util.Map.Entry;
import java.math.*;
public class Simple{
public static class Pair{
int x;
long y;
public Pair(int x,long y){
this.x = x;
this.y = y;
}
}
static int power(int x, int y, int p)
{
// Initialize result
int res = 1;
// Update x if it is more than or
// equal to p
x = x % p;
while (y > 0) {
// If y is odd, multiply x
// with result
if (y % 2 == 1)
res = (res * x) % p;
// y must be even now
y = y >> 1; // y = y/2
x = (x * x) % p;
}
return res;
}
// Returns n^(-1) mod p
static int modInverse(int n, int p)
{
return power(n, p - 2, p);
}
// Returns nCr % p using Fermat's
// little theorem.
static int nCrModPFermat(int n, int r,
int p)
{
if (n<r)
return 0;
// Base case
if (r == 0)
return 1;
// Fill factorial array so that we
// can find all factorial of r, n
// and n-r
int[] fac = new int[n + 1];
fac[0] = 1;
for (int i = 1; i <= n; i++)
fac[i] = fac[i - 1] * i % p;
return (fac[n] * modInverse(fac[r], p)
% p * modInverse(fac[n - r], p)
% p)
% p;
}
static int nCrModp(int n, int r, int p)
{
if (r > n - r)
r = n - r;
// The array C is going to store last
// row of pascal triangle at the end.
// And last entry of last row is nCr
int C[] = new int[r + 1];
C[0] = 1; // Top row of Pascal Triangle
// One by constructs remaining rows of Pascal
// Triangle from top to bottom
for (int i = 1; i <= n; i++) {
// Fill entries of current row using previous
// row values
for (int j = Math.min(i, r); j > 0; j--)
// nCj = (n-1)Cj + (n-1)C(j-1);
C[j] = (C[j] + C[j - 1]) % p;
}
return C[r];
}
// public static int helper(int mat[][],int n,int m,int i,int j,int min,int max){
// if(j==m){
// return max- min;
// }
// if(dp[i][j]){
// return dp[]
// }
// int ans1 = Integer.MAX_VALUE;
// int ans2 = Integer.MAX_VALUE;
// //we take that element
// for(int k = 0;k<n;k++){
// ans1 = Math.min(ans1,helper(mat, n, m, i+k, j+1, Math.min(min,mat[i+k][j+1]), Math.max(max,mat)));
// }
// //we do not take that element
// return dp[i][j] = Math.min(ans1,ans2);
// }
public static void main(String args[]){
//System.out.println("Hello Java");
Scanner s = new Scanner(System.in);
int t = 1;
for(int t1 = 1;t1<=t;t1++){
int n = s.nextInt();
// System.out.println(n);
long lo = 1;
long hi = n;
long ans = 0;
while(lo<=hi){
if(hi-lo+1<=3){
long m = hi - lo+ 1;
if(m==1){
ans= lo;
}
else if(m==2){
System.out.println("? "+lo+" "+hi);
System.out.flush();
long response = s.nextLong();
if(response==hi){
ans = lo;
}
else{
ans = hi;
}
}
else{
System.out.println("? "+lo+" "+hi);
System.out.flush();
long response = s.nextLong();
long mid = (lo+hi)/2;
if(mid==response){
System.out.println("? "+lo+" "+mid);
System.out.flush();
long r1 = s.nextLong();
if(r1==response){
ans = lo;
}
else{
ans = hi;
}
}
else{
if(response==hi)hi--;
else{
lo++;
}
System.out.println("? "+lo+" "+hi);
System.out.flush();
response = s.nextLong();
if(response==hi){
ans = lo;
}
else{
ans = hi;
}
}
}
break;
}
System.out.println("? "+lo+" "+hi);
System.out.flush();
long response = s.nextLong();
long mid = (lo+hi)/2;
if(response<=mid){
System.out.println("? "+lo+" "+mid);
System.out.flush();
long r1 = s.nextLong();
if(r1==response){
hi = mid;
}
else{
lo = mid+1;
}
}
else{
mid++;
System.out.println("? "+mid+" "+hi);
System.out.flush();
long r1 = s.nextLong();
if(r1==response){
lo = mid;
}
else{
hi = mid-1;
}
}
}
System.out.println("! "+ans);
System.out.flush();
}
}
}
/*
4 2 2 7
0 2 5
-2 3
5
0*x1 + 1*x2 + 2*x3 + 3*x4
*/
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
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
|
71a1e6d6729084134edced59f5916ca6
|
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.DecimalFormat;
import java.util.Arrays;
import java.util.Random;
import java.util.StringTokenizer;
public class Main {
static long mod = (long) 1e9 + 7;
static long mod1 = 998244353;
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
int n = in.nextInt();
int l = 0;
int r = n;
while (r-l>1) {
int mid = l + (r - l) / 2;
int smax = query(l,r-1,out,in);
if(smax<mid){
int m=query(l,mid-1,out,in);
if(m==smax)
r=mid;
else
l=mid;
}
else
{
int m=query(mid,r-1,out,in);
if (m==smax)
l=mid;
else
r=mid;
}
}
out.println("! " + r);
out.close();
}
static int query(int l,int r,PrintWriter out,InputReader in){
if(l>=r)
return -1;
out.println("? "+(l+1)+" "+(r+1));
out.flush();
return in.nextInt()-1;
}
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 long gcd(long x, long y) {
if (x == 0)
return y;
if (y == 0)
return x;
long r = 0, a, b;
a = Math.max(x, y);
b = Math.min(x, y);
r = b;
while (a % b != 0) {
r = a % b;
a = b;
b = r;
}
return r;
}
static long modulo(long a, long b, long c) {
long x = 1, y = a % c;
while (b > 0) {
if (b % 2 == 1)
x = (x * y) % c;
y = (y * y) % c;
b = b >> 1;
}
return x % c;
}
public static void debug(Object... o) {
System.err.println(Arrays.deepToString(o));
}
static String printPrecision(double d) {
DecimalFormat ft = new DecimalFormat("0.00000000000");
return String.valueOf(ft.format(d));
}
static int countBit(long mask) {
int ans = 0;
while (mask != 0) {
mask &= (mask - 1);
ans++;
}
return ans;
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public int[] readArray(int n) {
int[] arr = new int[n];
for (int i = 0; i < n; i++) arr[i] = nextInt();
return arr;
}
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
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
|
877486f50e9a763200354e03ab982d46
|
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 C {
InputStream is;
PrintWriter out;
String INPUT = "";
boolean bool= true;
void solve() throws IOException {
int start= 1, last= ni();
find(start, last, -1);
}
private void find(int start, int last, int pass)
{
if(start== last)
{
System.out.println("! "+start);
System.out.flush();
return;
}
else if(start+1== last)
{
if(pass== -1)
{
System.out.println("? "+start+" "+last);
System.out.flush();
pass= ni();
}
if(pass== start)
out.println("! "+last);
else
out.println("! "+start);
return;
}
int max2= pass;
if(pass== -1)
{
System.out.println("? "+start+" "+last);
System.out.flush();
max2= ni();
find(start, last, max2);
return;
}
int mid= start+ (last- start)/2;
if(max2>= start && max2<= mid)// first half
{
System.out.println("? "+start+" "+mid);
System.out.flush();
if(ni()== max2)
find(start, mid, max2);
else
find(mid, last, -1);
}
else
{
System.out.println("? "+mid+" "+last);
System.out.flush();
if(ni()== max2)
find(mid, last, max2);
else
find(start, mid, -1);
}
}
void run() throws Exception {
is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes());
out = new PrintWriter(System.out);
solve();
out.flush();
}
public static void main(String[] args) throws Exception {
new C().run();
}
private byte[] inbuf = new byte[1024];
public int lenbuf = 0, ptrbuf = 0;
private int readByte() {
if (lenbuf == -1) throw new InputMismatchException();
if (ptrbuf >= lenbuf) {
ptrbuf = 0;
try {
lenbuf = is.read(inbuf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (lenbuf <= 0) return -1;
}
return inbuf[ptrbuf++];
}
private boolean isSpaceChar(int c) {
return !(c >= 33 && c <= 126);
}
private int skip() {
int b;
while ((b = readByte()) != -1 && isSpaceChar(b)) ;
return b;
}
private double nd() {
return Double.parseDouble(ns());
}
private char nc() {
return (char) skip();
}
private String ns() {
int b = skip();
StringBuilder sb = new StringBuilder();
while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private char[] ns(int n) {
char[] buf = new char[n];
int b = skip(), p = 0;
while (p < n && !(isSpaceChar(b))) {
buf[p++] = (char) b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private char[][] nm(int n, int m) {
char[][] map = new char[n][];
for (int i = 0; i < n; i++) map[i] = ns(m);
return map;
}
private int[] na(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = ni();
return a;
}
private int ni() {
int num = 0, b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
private long nl() {
long num = 0;
int b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
private void tr(Object... o) {
if (INPUT.length() > 0) System.out.println(Arrays.deepToString(o));
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
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
|
836ca605ab506b43453756e6ffc0990c
|
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 C {
InputStream is;
PrintWriter out;
String INPUT = "";
boolean bool= true;
void solve() throws IOException {
int start= 1, last= ni();
find(start, last, -1);
}
private void find(int start, int last, int pass)
{
if(start== last)
{
System.out.println("! "+start);
System.out.flush();
return;
}
else if(start+1== last)
{
System.out.println("? "+start+" "+last);
System.out.flush();
if(ni()== start)
out.println("! "+last);
else
out.println("! "+start);
return;
}
int max2= pass;
if(pass== -1)
{
System.out.println("? "+start+" "+last);
System.out.flush();
max2= ni();
}
int mid= start+ (last- start)/2;
if(max2>= start && max2<= mid)// first half
{
System.out.println("? "+start+" "+mid);
System.out.flush();
if(ni()== max2)
find(start, mid, max2);
else
find(mid, last, -1);
}
else
{
System.out.println("? "+mid+" "+last);
System.out.flush();
if(ni()== max2)
find(mid, last, max2);
else
find(start, mid, -1);
}
}
void run() throws Exception {
is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes());
out = new PrintWriter(System.out);
solve();
out.flush();
}
public static void main(String[] args) throws Exception {
new C().run();
}
private byte[] inbuf = new byte[1024];
public int lenbuf = 0, ptrbuf = 0;
private int readByte() {
if (lenbuf == -1) throw new InputMismatchException();
if (ptrbuf >= lenbuf) {
ptrbuf = 0;
try {
lenbuf = is.read(inbuf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (lenbuf <= 0) return -1;
}
return inbuf[ptrbuf++];
}
private boolean isSpaceChar(int c) {
return !(c >= 33 && c <= 126);
}
private int skip() {
int b;
while ((b = readByte()) != -1 && isSpaceChar(b)) ;
return b;
}
private double nd() {
return Double.parseDouble(ns());
}
private char nc() {
return (char) skip();
}
private String ns() {
int b = skip();
StringBuilder sb = new StringBuilder();
while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private char[] ns(int n) {
char[] buf = new char[n];
int b = skip(), p = 0;
while (p < n && !(isSpaceChar(b))) {
buf[p++] = (char) b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private char[][] nm(int n, int m) {
char[][] map = new char[n][];
for (int i = 0; i < n; i++) map[i] = ns(m);
return map;
}
private int[] na(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = ni();
return a;
}
private int ni() {
int num = 0, b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
private long nl() {
long num = 0;
int b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
private void tr(Object... o) {
if (INPUT.length() > 0) System.out.println(Arrays.deepToString(o));
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
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
|
d18a116a529777545476d718c02e1fc8
|
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 C {
InputStream is;
PrintWriter out;
String INPUT = "";
boolean bool= true;
void solve() throws IOException {
int start= 1, last= ni();
find(start, last, -1);
}
private void find(int start, int last, int pass)
{
if(start== last)
{
System.out.println("! "+start);
System.out.flush();
return;
}
else if(start== last-1)
{
System.out.println("? "+start+" "+last);
System.out.flush();
if(ni()== start)
out.println("! "+last);
else
out.println("! "+start);
return;
}
int max2= pass;
if(pass== -1)
{
System.out.println("? "+start+" "+last);
System.out.flush();
max2= ni();
}
int mid= start+ (last- start)/2;
if(max2>= start && max2<= mid)// first half
{
System.out.println("? "+start+" "+mid);
System.out.flush();
if(ni()== max2)
find(start, mid, max2);
else
find(mid+1, last, -1);
}
else
{
if(mid+1== last)
{
mid-=1;
System.out.println("? "+(mid+1)+" "+last);
System.out.flush();
if(ni()== max2)
{
if(max2== mid+1)
out.println("! "+last);
else
out.println("! "+(mid+1));
return;
}
else
find(start, mid, -1);
}
else {
System.out.println("? " + (mid + 1) + " " + last);
System.out.flush();
if (ni() == max2)
find(mid + 1, last, max2);
else
find(start, mid, -1);
}
}
}
void run() throws Exception {
is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes());
out = new PrintWriter(System.out);
solve();
out.flush();
}
public static void main(String[] args) throws Exception {
new C().run();
}
private byte[] inbuf = new byte[1024];
public int lenbuf = 0, ptrbuf = 0;
private int readByte() {
if (lenbuf == -1) throw new InputMismatchException();
if (ptrbuf >= lenbuf) {
ptrbuf = 0;
try {
lenbuf = is.read(inbuf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (lenbuf <= 0) return -1;
}
return inbuf[ptrbuf++];
}
private boolean isSpaceChar(int c) {
return !(c >= 33 && c <= 126);
}
private int skip() {
int b;
while ((b = readByte()) != -1 && isSpaceChar(b)) ;
return b;
}
private double nd() {
return Double.parseDouble(ns());
}
private char nc() {
return (char) skip();
}
private String ns() {
int b = skip();
StringBuilder sb = new StringBuilder();
while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private char[] ns(int n) {
char[] buf = new char[n];
int b = skip(), p = 0;
while (p < n && !(isSpaceChar(b))) {
buf[p++] = (char) b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private char[][] nm(int n, int m) {
char[][] map = new char[n][];
for (int i = 0; i < n; i++) map[i] = ns(m);
return map;
}
private int[] na(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = ni();
return a;
}
private int ni() {
int num = 0, b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
private long nl() {
long num = 0;
int b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
private void tr(Object... o) {
if (INPUT.length() > 0) System.out.println(Arrays.deepToString(o));
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
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
|
7c4ab4c9c6361411c6d6c177ba0a9382
|
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.InputStreamReader;
import java.io.PrintWriter;
import java.sql.Array;
import java.sql.ResultSet;
import java.util.Map.Entry;
import java.util.*;
public class d{
static long mod = 1000000007L;
public static void main(String[] args) throws Exception {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
sc = new FastScanner(in);
HashMap<Integer , HashMap<Integer , ArrayList<Integer>>> map = new HashMap<>();
int t =1;
while(t-->0) {
int n = sc.nextInt();
int lo = 1 , hi = n ;
int ans = -1;
System.out.println("? "+lo+" "+hi);
System.out.flush();
int exp = sc.nextInt();
while(lo < hi) {
int mid = (lo+hi)/2 ;
if(lo == mid)break;
System.out.println("? "+lo+" "+mid);
System.out.flush();
int val1 = sc.nextInt();
int val2 = -1;
if(mid +1 < hi) {
System.out.println("? "+(mid+1)+" "+hi);
System.out.flush();
val2 = sc.nextInt();
}
if(val1 == exp) {
hi = mid;
}else if(val2 == exp){
lo = mid+1;
}else {
if(exp > mid) {
hi = mid;
exp = val1;
}else {
lo=mid+1;
exp =val2;
}
}
}
if(lo == hi) {
ans = lo;
}else {
System.out.println("? "+lo+" "+hi);
System.out.flush();
exp = sc.nextInt();
ans = lo ;
if(exp == lo )ans = hi;
}
System.out.println("! "+ans);
}
}
static long power(long x, long y, long p) {
long res = 1;
x = x % p;
while (y > 0) {
if (y % 2 == 1)
res = (res * x) % p;
y = y >> 1;
x = (x * x) % p;
}
return res;
}
static long modInverse(long n, long p) {
return power(n, p - 2, p);
}
static long nCr(int n, int r, long p) {
if (r == 0)
return 1;
long[] fac = new long[n + 1];
fac[0] = 1;
for (int i = 1; i <= n; i++)
fac[i] = fac[i - 1] * i % p;
return (fac[n] * modInverse(fac[r], p) % p * modInverse(fac[n - r], p) % p) % p;
}
static final int MAXN = 0;
static int spf[] = new int[MAXN];
static void sieve()
{
spf[1] = 1;
for (int i=2; i<MAXN; i++)
spf[i] = i;
for (int i=4; i<MAXN; i+=2)
spf[i] = 2;
for (int i=3; i*i<MAXN; i++)
{
if (spf[i] == i)
{
for (int j=i*i; j<MAXN; j+=i)
if (spf[j]==j)
spf[j] = i;
}
}
}
static ArrayList<Integer> getfactor(int x)
{
ArrayList<Integer> ret = new ArrayList<>();
while (x != 1)
{
ret.add(spf[x]);
x = x / spf[x];
}
return ret;
}
public static void dfs(int cur, TreeMap<Integer, ArrayList<Integer>> map, int par, boolean[] vis) {
if (vis[cur])
return;
vis[cur] = true;
for (int nbr : map.get(cur)) {
if (par != nbr && vis[cur]) {
dfs(nbr, map, cur, vis);
}
}
}
static int[] par;
static int[] rank;
static void build(int n) {
par = new int[n + 1];
rank = new int[n + 1];
for (int i = 0; i < n; i++)
par[i] = i;
}
static int find(int u) {
if (u == par[u])
return u;
int v = find(par[u]);
par[u] = v;
return v;
}
static void union(int u, int v) {
u = par[u];
v = par[v];
if (rank[u] > rank[v]) {
par[v] = u;
} else {
par[u] = v;
if (rank[u] == rank[v]) {
rank[v]++;
}
}
}
public static TreeMap<Integer, TreeSet<Integer>> directed(int n, int m) throws Exception {
TreeMap<Integer, TreeSet<Integer>> map = new TreeMap<>();
for (int i = 0; i < n; i++)
map.put(i, new TreeSet<Integer>());
for (int i = 0; i < m; i++) {
int a = sc.nextInt();
int b = sc.nextInt();
map.get(b).add(a);
}
return map;
}
public static TreeMap<Integer, TreeSet<Integer>> undirected(int n, int m) throws Exception {
TreeMap<Integer, TreeSet<Integer>> map = new TreeMap<>();
for (int i = 0; i < n; i++)
map.put(i, new TreeSet<Integer>());
for (int i = 0; i < m; i++) {
int a = sc.nextInt();
int b = sc.nextInt();
map.get(b).add(a);
map.get(a).add(b);
}
return map;
}
public static long[] inputl(int n) throws Exception {
long[] arr = new long[n];
for (int i = 0; i < n; i++) {
arr[i] = sc.nextLong();
}
return arr;
}
public static int[] input(int n) throws Exception {
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
return arr;
}
public static int[][] input(int n, int m) throws Exception {
int[][] arr = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
arr[i][j] = sc.nextInt();
}
}
return arr;
}
static BufferedReader in;
static FastScanner sc;
static PrintWriter out;
static class FastScanner {
BufferedReader in;
StringTokenizer st;
public FastScanner(BufferedReader in) {
this.in = in;
}
public String nextToken() throws Exception {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(in.readLine());
}
return st.nextToken();
}
public int nextInt() throws Exception {
return Integer.parseInt(nextToken());
}
public long nextLong() throws Exception {
return Long.parseLong(nextToken());
}
public double nextDouble() throws Exception {
return Double.parseDouble(nextToken());
}
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
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
|
54ab3e7aab737d7636a8797c4739e28d
|
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
|
//some updates in import stuff
import static java.lang.Math.max;
import static java.lang.Math.min;
import static java.lang.Math.abs;
import java.util.*;
import java.io.*;
import java.math.*;
//update this bad boi too
public class Main{
static int mod = (int) (Math.pow(10, 9)+7);
static final int dx[] = { -1, 0, 1, 0 }, dy[] = { 0, -1, 0, 1 };
static final int[] dx8 = { -1, -1, -1, 0, 0, 1, 1, 1 }, dy8 = { -1, 0, 1, -1, 1, -1, 0, 1 };
static final int[] dx9 = { -1, -1, -1, 0, 0, 0, 1, 1, 1 }, dy9 = { -1, 0, 1, -1, 0, 1, -1, 0, 1 };
static final double eps = 1e-10;
static List<Integer> primeNumbers = new ArrayList<>();
public static void main(String[] args) throws IOException{
MyScanner sc = new MyScanner();
//changes in this line of code
out = new PrintWriter(new BufferedOutputStream(System.out));
// out = new PrintWriter(new BufferedWriter(new FileWriter("output.out")));
//WRITE YOUR CODE IN HERE
int n = sc.nextInt();
int l = 1;
int r = n;
while(r-l > 1){
System.out.println("? " + l + " " + r);
int index = sc.nextInt();
//we have the index of second max element
int mid = l + (r-l)/2;
if(index < mid){
System.out.println("? " + l + " " + mid);
int get = sc.nextInt();
if(get == index){
r = mid;
}else{
l = mid;
}
}else{
System.out.println("? " + mid + " " + r);
int get = sc.nextInt();
if(get == index){
l = mid;
}else{
r = mid;
}
}
}
if(l == r){
System.out.println("! " + l);
}else{
System.out.println("? " + l + " " + r);
int index = sc.nextInt();
if(index == l){
System.out.println("! " + r);
}else{
System.out.println("! " + l);
}
}
out.close();
}
//-------------------------------------------------------------------
//-------------------------------------------------------------------
//-------------------------------------------------------------------
//-------------------------------------------------------------------
//-------------------------------------------------------------------
//Updation Required
//Fenwick Tree (customisable)
//Segment Tree (customisable)
//-----CURRENTLY PRESENT-------//
//Graph
//DSU
//powerMODe
//power
//Segment Tree (work on this one)
//Prime Sieve
//Count Divisors
//Next Permutation
//Get NCR
//isVowel
//Sort (int)
//Sort (long)
//Binomial Coefficient
//Pair
//Triplet
//lcm (int & long)
//gcd (int & long)
//gcd (for binomial coefficient)
//swap (int & char)
//reverse
//Fast input and output
//-------------------------------------------------------------------
//-------------------------------------------------------------------
//-------------------------------------------------------------------
//-------------------------------------------------------------------
//-------------------------------------------------------------------
//GRAPH (basic structure)
public static class Graph{
public int V;
public ArrayList<ArrayList<Integer>> edges;
//2 -> [0,1,2] (current)
Graph(int V){
this.V = V;
edges = new ArrayList<>(V+1);
for(int i= 0; i <= V; i++){
edges.add(new ArrayList<>());
}
}
public void addEdge(int from , int to){
edges.get(from).add(to);
}
}
//DSU (path and rank optimised)
public static class DisjointUnionSets {
int[] rank, parent;
int n;
public DisjointUnionSets(int n)
{
rank = new int[n];
parent = new int[n];
Arrays.fill(rank, 1);
Arrays.fill(parent,-1);
this.n = n;
}
public int find(int curr){
if(parent[curr] == -1)
return curr;
//path compression optimisation
return parent[curr] = find(parent[curr]);
}
public void union(int a, int b){
int s1 = find(a);
int s2 = find(b);
if(s1 != s2){
if(rank[s1] < rank[s2]){
parent[s1] = s2;
rank[s2] += rank[s1];
}else{
parent[s2] = s1;
rank[s1] += rank[s2];
}
}
}
}
//with mod
public static long powerMOD(long x, long y)
{
long res = 1L;
while (y > 0)
{
// If y is odd, multiply x with result
if ((y & 1) != 0){
x %= mod;
res %= mod;
res = (res * x)%mod;
}
// y must be even now
y = y >> 1; // y = y/2
x%= mod;
x = (x * x)%mod; // Change x to x^2
}
return res%mod;
}
//without mod
public static long power(long x, long y)
{
long res = 1L;
while (y > 0)
{
// If y is odd, multiply x with result
if ((y & 1) != 0){
res = (res * x);
}
// y must be even now
y = y >> 1; // y = y/
x = (x * x);
}
return res;
}
public static class segmentTree{
public long[] arr;
public long[] tree;
public long[] lazy;
segmentTree(long[] array){
int n = array.length;
arr = new long[n];
for(int i= 0; i < n; i++) arr[i] = array[i];
tree = new long[4*n + 1];
lazy = new long[4*n + 1];
}
public void build(int[]arr, int s, int e, int[] tree, int index){
if(s == e){
tree[index] = arr[s];
return;
}
//otherwise divide in two parts and fill both sides simply
int mid = (s+e)/2;
build(arr, s, mid, tree, 2*index);
build(arr, mid+1, e, tree, 2*index+1);
//who will build the current position dude
tree[index] = Math.min(tree[2*index], tree[2*index+1]);
}
public int query(int sr, int er, int sc, int ec, int index, int[] tree){
if(lazy[index] != 0){
tree[index] += lazy[index];
if(sc != ec){
lazy[2*index+1] += lazy[index];
lazy[2*index] += lazy[index];
}
lazy[index] = 0;
}
//no overlap
if(sr > ec || sc > er) return Integer.MAX_VALUE;
//found the index baby
if(sr <= sc && ec <= er) return tree[index];
//finding the index on both sides hehehehhe
int mid = (sc + ec)/2;
int left = query(sr, er, sc, mid, 2*index, tree);
int right = query(sr, er, mid+1, ec, 2*index + 1, tree);
return Integer.min(left, right);
}
//now we will do point update implementation
//it should be simple then we expected for sure
public void update(int index, int indexr, int increment, int[] tree, int s, int e){
if(lazy[index] != 0){
tree[index] += lazy[index];
if(s != e){
lazy[2*index+1] = lazy[index];
lazy[2*index] = lazy[index];
}
lazy[index] = 0;
}
//no overlap
if(indexr < s || indexr > e) return;
//found the required index
if(s == e){
tree[index] += increment;
return;
}
//search for the index on both sides
int mid = (s+e)/2;
update(2*index, indexr, increment, tree, s, mid);
update(2*index+1, indexr, increment, tree, mid+1, e);
//now update the current range simply
tree[index] = Math.min(tree[2*index+1], tree[2*index]);
}
public void rangeUpdate(int[] tree , int index, int s, int e, int sr, int er, int increment){
//if not at all in the same range
if(e < sr || er < s) return;
//complete then also move forward
if(s == e){
tree[index] += increment;
return;
}
//otherwise move in both subparts
int mid = (s+e)/2;
rangeUpdate(tree, 2*index, s, mid, sr, er, increment);
rangeUpdate(tree, 2*index + 1, mid+1, e, sr, er, increment);
//update current range too na
//i always forget this step for some reasons hehehe, idiot
tree[index] = Math.min(tree[2*index], tree[2*index + 1]);
}
public void rangeUpdateLazy(int[] tree, int index, int s, int e, int sr, int er, int increment){
//update lazy values
//resolve lazy value before going down
if(lazy[index] != 0){
tree[index] += lazy[index];
if(s != e){
lazy[2*index+1] += lazy[index];
lazy[2*index] += lazy[index];
}
lazy[index] = 0;
}
//no overlap case
if(sr > e || s > er) return;
//complete overlap
if(sr <= s && er >= e){
tree[index] += increment;
if(s != e){
lazy[2*index+1] += increment;
lazy[2*index] += increment;
}
return;
}
//otherwise go on both left and right side and do your shit
int mid = (s + e)/2;
rangeUpdateLazy(tree, 2*index, s, mid, sr, er, increment);
rangeUpdateLazy(tree, 2*index + 1, mid+1, e, sr, er, increment);
tree[index] = Math.min(tree[2*index+1], tree[2*index]);
return;
}
}
//prime sieve
public static void primeSieve(int n){
BitSet bitset = new BitSet(n+1);
for(long i = 0; i < n ; i++){
if (i == 0 || i == 1) {
bitset.set((int) i);
continue;
}
if(bitset.get((int) i)) continue;
primeNumbers.add((int)i);
for(long j = i; j <= n ; j+= i)
bitset.set((int)j);
}
}
//number of divisors
public static int countDivisors(long number){
if(number == 1) return 1;
List<Integer> primeFactors = new ArrayList<>();
int index = 0;
long curr = primeNumbers.get(index);
while(curr * curr <= number){
while(number % curr == 0){
number = number/curr;
primeFactors.add((int) curr);
}
index++;
curr = primeNumbers.get(index);
}
if(number != 1) primeFactors.add((int) number);
int current = primeFactors.get(0);
int totalDivisors = 1;
int currentCount = 2;
for (int i = 1; i < primeFactors.size(); i++) {
if (primeFactors.get(i) == current) {
currentCount++;
} else {
totalDivisors *= currentCount;
currentCount = 2;
current = primeFactors.get(i);
}
}
totalDivisors *= currentCount;
return totalDivisors;
}
//now adding next permutation function to java hehe
public static boolean next_permutation(int[] p) {
for (int a = p.length - 2; a >= 0; --a)
if (p[a] < p[a + 1])
for (int b = p.length - 1;; --b)
if (p[b] > p[a]) {
int t = p[a];
p[a] = p[b];
p[b] = t;
for (++a, b = p.length - 1; a < b; ++a, --b) {
t = p[a];
p[a] = p[b];
p[b] = t;
}
return true;
}
return false;
}
//finding the value of NCR in O(RlogN) time and O(1) space
public static long getNcR(int n, int r)
{
long p = 1, k = 1;
if (n - r < r) r = n - r;
if (r != 0) {
while (r > 0) {
p *= n;
k *= r;
long m = __gcd(p, k);
p /= m;
k /= m;
n--;
r--;
}
}
else {
p = 1;
}
return p;
}
//is vowel function
public static boolean isVowel(char c)
{
return (c=='a' || c=='A' || c=='e' || c=='E' || c=='i' || c=='I' || c=='o' || c=='O' || c=='u' || c=='U');
}
//to sort the array with better method
public static void sort(int[] a) {
ArrayList<Integer> l=new ArrayList<>();
for (int i:a) l.add(i);
Collections.sort(l);
for (int i=0; i<a.length; i++) a[i]=l.get(i);
}
//sort long
public static void sort(long[] a) {
ArrayList<Long> l=new ArrayList<>();
for (long i:a) l.add(i);
Collections.sort(l);
for (int i=0; i<a.length; i++) a[i]=l.get(i);
}
//for calculating binomialCoeff
public static int binomialCoeff(int n, int k)
{
int C[] = new int[k + 1];
// nC0 is 1
C[0] = 1;
for (int i = 1; i <= n; i++) {
// Compute next row of pascal
// triangle using the previous row
for (int j = Math.min(i, k); j > 0; j--)
C[j] = C[j] + C[j - 1];
}
return C[k];
}
//Pair with int int
public static class Pair{
public int a;
public int b;
Pair(int a , int b){
this.a = a;
this.b = b;
}
@Override
public String toString(){
return a + " -> " + b;
}
}
//Triplet with int int int
public static class Triplet{
public int a;
public int b;
public int c;
Triplet(int a , int b, int c){
this.a = a;
this.b = b;
this.c = c;
}
@Override
public String toString(){
return a + " -> " + b;
}
}
//Shortcut function
public static long lcm(long a , long b){
return a * (b/gcd(a,b));
}
//let's make one for calculating lcm basically
public static int lcm(int a , int b){
return (a * b)/gcd(a,b);
}
//int version for gcd
public static int gcd(int a, int b){
if(b == 0)
return a;
return gcd(b , a%b);
}
//long version for gcd
public static long gcd(long a, long b){
if(b == 0)
return a;
return gcd(b , a%b);
}
//for ncr calculator(ignore this code)
public static long __gcd(long n1, long n2)
{
long gcd = 1;
for (int i = 1; i <= n1 && i <= n2; ++i) {
// Checks if i is factor of both integers
if (n1 % i == 0 && n2 % i == 0) {
gcd = i;
}
}
return gcd;
}
//swapping two elements in an array
public static void swap(int[] arr, int left , int right){
int temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
}
//for char array
public static void swap(char[] arr, int left , int right){
char temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
}
//reversing an array
public static void reverse(int[] arr){
int left = 0;
int right = arr.length-1;
while(left <= right){
swap(arr, left,right);
left++;
right--;
}
}
//-----------PrintWriter for faster output---------------------------------
public static PrintWriter out;
//-----------MyScanner class for faster input----------
public static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
// public MyScanner() throws FileNotFoundException {
// br = new BufferedReader(new FileReader("input.in"));
// }
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine(){
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
//--------------------------------------------------------
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
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
|
3e1856facabb28b40252d6851212c0d5
|
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 D{
private static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
private static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
public static void main (String[] args) throws IOException{
int n = Integer.parseInt(br.readLine());
int l = 1, r = n;
while(l!=r) {
int mid = (int)Math.ceil((l+r)/2);
bw.write("? " + l + " " + r + "\n");
bw.flush();
int prev = Integer.parseInt(br.readLine());
if(r-l==1) {
if(prev==r)
r = l;
break;
}
if(prev<=mid) {
bw.write("? " + l + " " + mid + "\n");
bw.flush();
int left = Integer.parseInt(br.readLine());
if(left == prev) {
r = mid;
continue;
}else {
l = mid;
}
}else {
bw.write("? " + mid + " " + r + "\n");
bw.flush();
int right = Integer.parseInt(br.readLine());
if(right == prev) {
l = mid;
continue;
}else {
r = mid;
}
}
}
bw.write("! " + r + "\n");
bw.flush();
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
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
|
1354d93c8dafc4966aca86e883a2da4e
|
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 static java.lang.Math.max;
import static java.lang.Math.min;
import static java.lang.Math.abs;
import java.util.*;
import java.io.*;
import java.math.*;
public class Template {
public static void main(String[] args) throws Exception{
BufferedReader infile = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(infile.readLine());
int N = Integer.parseInt(st.nextToken());
System.out.println("? 1 " + N);
System.out.flush();
int secondLarge = Integer.parseInt(infile.readLine());
int ans = 0;
if(secondLarge > 1) {
// check left then
System.out.println("? 1 " + secondLarge);
System.out.flush();
int index = Integer.parseInt(infile.readLine());
if(index == secondLarge) {
// definitely we check left one
int start = 1;
int end = secondLarge-1;
while(start < end) {
int mid = (start+end+1)/2;
System.out.println("? " + mid + " " + secondLarge);
System.out.flush();
index = Integer.parseInt(infile.readLine());
if(index == secondLarge) {
start = mid;
}
else {
end = mid-1;
}
}
ans = start;
}
}
if(ans == 0 && secondLarge < N) {
// then go for right
int start = secondLarge+1;
int end = N;
while(start < end) {
int mid = (start+end)/2;
System.out.println("? " + secondLarge + " " + mid);
System.out.flush();
int index = Integer.parseInt(infile.readLine());
if(index == secondLarge) {
end = mid;
}
else {
start = mid+1;
}
}
ans = start;
}
System.out.println("! " + ans);
System.out.flush();
}
public static int[] readArr(int N, BufferedReader infile, StringTokenizer st) throws Exception
{
int[] arr = new int[N];
st = new StringTokenizer(infile.readLine());
for(int i=0; i < N; i++)
arr[i] = Integer.parseInt(st.nextToken());
return arr;
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
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
|
31af4d3a9c8baa22bcde938a9dbf7134
|
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 static java.lang.Math.max;
import static java.lang.Math.min;
import static java.lang.Math.abs;
import java.util.*;
import java.io.*;
import java.math.*;
public class Template {
public static void main(String[] args) throws Exception{
BufferedReader infile = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(infile.readLine());
int N = Integer.parseInt(st.nextToken());
System.out.println("? 1 " + N);
System.out.flush();
int middle = Integer.parseInt(infile.readLine());
int res = 0;
// check on left
if(middle > 1) {
System.out.println("? 1 " + middle);
System.out.flush();
int index = Integer.parseInt(infile.readLine());
if(index == middle) {
int start = 1;
int end = middle-1;
while(start != end) {
int mid = (start+end+1)/2;
System.out.println("? " + mid + " " + middle);
System.out.flush();
index = Integer.parseInt(infile.readLine());
if(index == middle) {
start = mid;
}
else {
end = mid-1;
}
}
res = start;
}
}
// otherwise check on right
if(res == 0 && middle < N) {
int start = middle+1;
int end = N;
while(start != end) {
int mid = (start+end)/2;
System.out.println("? " + middle + " " + mid);
System.out.flush();
int index = Integer.parseInt(infile.readLine());
if(index == middle) {
end = mid;
}
else {
start = mid+1;
}
}
res = start;
}
System.out.println("! " + res);
System.out.flush();
}
public static int[] readArr(int N, BufferedReader infile, StringTokenizer st) throws Exception
{
int[] arr = new int[N];
st = new StringTokenizer(infile.readLine());
for(int i=0; i < N; i++)
arr[i] = Integer.parseInt(st.nextToken());
return arr;
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
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
|
10efcaab03ac836e6fb8f5c09e4e9229
|
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 codechef; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
public class Codechef
{static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
public static void main (String[] args) throws java.lang.Exception
{
FastReader scan = new FastReader();
PrintWriter pw = new PrintWriter(System.out);
int n = scan.nextInt();
int l=1;
int r=n;
while(l<r){
pw.println("? "+l+" "+r);
pw.flush();
int smax = scan.nextInt();
int mid = (l+r)/2;
if(smax<=mid){
if(l<mid){
pw.println("? "+l+" "+mid);
pw.flush();
int check = scan.nextInt();
if(check==smax){
r = mid;
}
else
l = mid+1;
}
else
l = mid+1;}
else{
if(mid+1<r){
pw.println("? "+(mid+1)+" "+r);
pw.flush();
int check = scan.nextInt();
if(check==smax){
l = mid+1;
}
else
r = mid;}
else
r = mid;
}
}
pw.println("! "+l);
pw.flush();
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
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
|
158bef7a0353aae1ea0a2ae376ddba0f
|
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.util.ArrayList;
import java.util.StringTokenizer;
public class GuessingTheGreatest {
static class FastScanner
{
BufferedReader br;
StringTokenizer st;
public FastScanner()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
public static void main(String[] args) {
FastScanner f=new FastScanner();
int n=f.nextInt();
int smax=secmax(0,n-1);
int l=0;
int r=n-1;
if(smax==0||secmax(0, smax)!=smax) {
l=smax;
r=n-1;
while(r-l>1) {
int mid=(l+r)/2;
if(secmax(smax,mid)==smax) {
r=mid;
}else l=mid;
}
System.out.println("!"+" "+(r+1));
System.out.flush();
}else {
l=0;
r=smax;
while(r-l>1) {
int mid=(l+r)/2;
if(secmax(mid,smax)==smax) {
l=mid;
}else r=mid;
}
System.out.println("!"+" "+(l+1));
System.out.flush();
}
}
static int secmax(int l,int r) {
FastScanner f=new FastScanner();
if(l<r) {
System.out.println("?"+" "+(l+1)+" "+(r+1));
System.out.flush();
int q=f.nextInt();
return (q-1);
}else return -1;
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
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
|
eabfbd7963ca084a020f970cec38316f
|
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 a2oj {
static FastReader sc;
static PrintWriter out;
static int mod = 1000000007;
public static void main(String[] args) throws IOException {
if (System.getProperty("ONLINE_JUDGE") == null) {
File f1 = new File("input.txt");
File f2 = new File("output.txt");
Reader r = new FileReader(f1);
sc = new FastReader(r);
out = new PrintWriter(f2);
double prev = System.currentTimeMillis();
solve();
out.println("\n\nExecuted in : " + ((System.currentTimeMillis() - prev) / 1e3) + " sec");
} else {
sc = new FastReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
solve();
}
out.flush();
out.close();
}
static void solve() {
// int t = sc.nextInt();
// StringBuilder ans = new StringBuilder("");
// while (t-- > 0) {
// }
// out.println(ans);
int n = sc.nextInt();
int l = 1, r = n;
while (l + 1 < r) {
int smp = query(l, r);
int mid = (l + r) / 2;
if (smp <= mid) {
int nsmp = query(l, mid);
if (nsmp == smp) {
r = mid;
} else {
l = mid;
}
} else {
int nsmp = query(mid, r);
if (nsmp == smp) {
l = mid;
} else {
r = mid;
}
}
}
int smp = query(l, r);
printAns(smp == l ? r : l);
}
static int query(int l, int r) {
// if (l == r)
// return l;
out.println("? " + l + " " + r);
out.flush();
int n = sc.nextInt();
return n;
}
static void printAns(int ans) {
out.println("! " + ans);
out.flush();
System.exit(0);
}
public static int digitsCount(long x) {
return (int) Math.floor(Math.log10(x)) + 1;
}
public static boolean isPowerTwo(long n) {
return (n & n - 1) == 0;
}
static void sieve(boolean[] prime, int n) { // Sieve Of Eratosthenes
for (int i = 1; i <= n; i++) {
prime[i] = true;
}
for (int i = 2; i * i <= n; i++) {
if (prime[i]) {
for (int j = 2; i * j <= n; j++) {
prime[i * j] = false;
}
}
}
}
static void fillGraph(ArrayList<ArrayList<Integer>> adj, FastReader sc) {
int n = sc.nextInt(), m = sc.nextInt();
for (int i = 0; i < n + 1; i++) {
adj.add(new ArrayList<Integer>());
}
for (int i = 1; i <= m; i++) {
int x = sc.nextInt(), y = sc.nextInt();
adj.get(x).add(y);
adj.get(y).add(x);
}
}
static void dfs(ArrayList<ArrayList<Integer>> adj, boolean[] visited, int v, PrintWriter out) {
visited[v] = true;
out.print(v + " ");
for (Integer i : adj.get(v)) {
if (!visited[i])
dfs(adj, visited, i, out);
}
}
static void bfs(ArrayList<ArrayList<Integer>> adj, int V, int s, PrintWriter out) {
boolean[] visited = new boolean[V];
Queue<Integer> q = new LinkedList<>();
visited[s] = true;
q.add(s);
while (!q.isEmpty()) {
s = q.poll();
out.print(s + " ");
for (Integer i : adj.get(s)) {
if (!visited[i]) {
visited[i] = true;
q.add(i);
}
}
}
}
int fib(int n) { // n-th Fibonacci Number
int a = 0, b = 1, c, i;
if (n == 0)
return a;
for (i = 2; i <= n; i++) {
c = a + b;
a = b;
b = c;
}
return b;
}
static long nCr(int n, int r) { // Combinations
if (n < r)
return 0;
if (r > n - r) { // because nCr(n, r) == nCr(n, n - r)
r = n - r;
}
long ans = 1L;
for (int i = 0; i < r; i++) {
ans *= (n - i);
ans /= (i + 1);
}
return ans;
}
static long catalan(int n) { // n-th Catalan Number
long c = nCr(2 * n, n);
return c / (n + 1);
}
static class Pair implements Comparable<Pair> { // Pair Class
int x;
int y;
public Pair(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof Pair)) {
return false;
}
Pair pair = (Pair) o;
if (x != pair.x) {
return false;
}
if (y != pair.y) {
return false;
}
return true;
}
@Override
public int hashCode() {
long result = x;
result = 31 * result + y;
return (int) result;
}
@Override
public int compareTo(Pair o) {
return (int) (this.x - o.x);
}
}
static class Trip<E, T, Z> { // Triplet Class
E x;
T y;
Z z;
Trip(E x, T y, Z z) {
this.x = x;
this.y = y;
this.z = z;
}
public boolean equals(Trip<E, T, Z> o) {
if (o instanceof Trip) {
Trip<E, T, Z> t = o;
return t.x == x && t.y == y && t.z == z;
}
return false;
}
public int hashCode() {
return Integer.valueOf((int) x).hashCode() * 62 + Integer.valueOf((int) y).hashCode() * 31
+ Integer.valueOf((int) z).hashCode();
}
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader(Reader r) {
br = new BufferedReader(r);
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
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
|
cea18cb4f9b5073a3efcaf96d2afbb6f
|
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.util.StringTokenizer;
public class Solution {
static Reader input;
public static void main(String[] args) throws IOException {
input = new Reader();
int n = input.nextInt();
int secondMax = ask(1, n), temp;
int max;
if(secondMax == n) {
max = leftBinarySearch(1, n-1, secondMax);
} else if(secondMax == 1) {
max = rightBinarySearch(2, n, secondMax);
} else {
temp = ask(secondMax, n);
if(temp != secondMax) {
max = leftBinarySearch(1, secondMax-1, secondMax);
} else {
max = rightBinarySearch(secondMax+1, n, secondMax);
}
}
System.out.println("! " + max);
}
static int leftBinarySearch(int l, int r, int secondMax) throws IOException {
int temp, middle, left = l, right = r, answer = l;
while(left <= right) {
middle = left+right>>1;
temp = ask(middle, secondMax);
if(temp == secondMax) {
answer = middle;
left = middle+1;
} else {
right = middle-1;
}
}
return answer;
}
static int rightBinarySearch(int l, int r, int secondMax) throws IOException {
int temp, middle, left = l, right = r, answer = r;
while(left <= right) {
middle = left+right>>1;
temp = ask(secondMax, middle);
if(temp == secondMax) {
answer = middle;
right = middle-1;
} else {
left = middle+1;
}
}
return answer;
}
static int ask(int l, int r) throws IOException {
System.out.println("? " + l + " " + r);
System.out.flush();
return input.nextInt();
}
static class Reader {
BufferedReader bufferedReader;
StringTokenizer string;
public Reader() {
InputStreamReader inr = new InputStreamReader(System.in);
bufferedReader = new BufferedReader(inr);
}
public String next() throws IOException {
while(string == null || ! string.hasMoreElements()) {
string = new StringTokenizer(bufferedReader.readLine());
}
return string.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public String nextLine() throws IOException {
return bufferedReader.readLine();
}
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
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
|
977243cfb9cbc0f340e1b1ce9f753706
|
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.util.concurrent.CompletableFuture;
import javax.swing.text.Segment;
import java.io.*;
import java.math.*;
import java.sql.Array;
public class Main {
static class Reader{
BufferedReader br;
StringTokenizer st;
public Reader() {
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 long mod = (long)(1e9 + 7);
static void sort(long[] arr ) {
ArrayList<Long> al = new ArrayList<>();
for(long e:arr) al.add(e);
Collections.sort(al);
for(int i = 0 ; i<al.size(); i++) arr[i] = al.get(i);
}
static void sort(int[] arr ) {
ArrayList<Integer> al = new ArrayList<>();
for(int e:arr) al.add(e);
Collections.sort(al);
for(int i = 0 ; i<al.size(); i++) arr[i] = al.get(i);
}
static void sort(char[] arr) {
ArrayList<Character> al = new ArrayList<Character>();
for(char cc:arr) al.add(cc);
Collections.sort(al);
for(int i = 0 ;i<arr.length ;i++) arr[i] = al.get(i);
}
static void rvrs(int[] arr) {
int i =0 , j = arr.length-1;
while(i>=j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
i++;
j--;
}
}
static void rvrs(long[] arr) {
int i =0 , j = arr.length-1;
while(i>=j) {
long temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
i++;
j--;
}
}
static long mod_mul(long a , long b ,long mod) {
return ((a%mod)*(b%mod))%mod;
}
static long gcd(long a, long b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
static boolean[] prime(int num) {
boolean[] bool = new boolean[num];
for (int i = 0; i< bool.length; i++) {
bool[i] = true;
}
for (int i = 2; i< Math.sqrt(num); i++) {
if(bool[i] == true) {
for(int j = (i*i); j<num; j = j+i) {
bool[j] = false;
}
}
}
if(num >= 0) {
bool[0] = false;
bool[1] = false;
}
return bool;
}
static long modInverse(long a, long m)
{
long g = gcd(a, m);
return power(a, m - 2, m);
}
static long power(long x, long y, long m){
if (y == 0) return 1; long p = power(x, y / 2, m) % m; p = (int)((p * (long)p) % m);
if (y % 2 == 0) return p; else return (int)((x * (long)p) % m); }
static class Combinations{
private long[] z;
private long[] z1;
private long[] z2;
public Combinations(long N , long mod) {
z = new long[(int)N+1];
z1 = new long[(int)N+1];
z[0] = 1;
for(int i =1 ; i<=N ; i++) z[i] = (z[i-1]*i)%mod;
z2 = new long[(int)N+1];
z2[0] = z2[1] = 1;
for (int i = 2; i <= N; i++)
z2[i] = z2[(int)(mod % i)] * (mod - mod / i) % mod;
z1[0] = z1[1] = 1;
for (int i = 2; i <= N; i++)
z1[i] = (z2[i] * z1[i - 1]) % mod;
}
long fac(long n) {
return z[(int)n];
}
long invrsNum(long n) {
return z2[(int)n];
}
long invrsFac(long n) {
return invrsFac((int)n);
}
long ncr(long N, long R, long mod)
{ if(R<0 || R>N ) return 0;
long ans = ((z[(int)N] * z1[(int)R])
% mod * z1[(int)(N - R)])
% mod;
return ans;
}
}
static class DisjointUnionSets {
int[] rank, parent;
int n;
public DisjointUnionSets(int n)
{
rank = new int[n];
parent = new int[n];
this.n = n;
makeSet();
}
void makeSet()
{
for (int i = 0; i < n; i++) {
parent[i] = i;
}
}
int find(int x)
{
if (parent[x] != x) {
parent[x] = find(parent[x]);
}
return parent[x];
}
void union(int x, int y)
{
int xRoot = find(x), yRoot = find(y);
if (xRoot == yRoot)
return;
if (rank[xRoot] < rank[yRoot])
parent[xRoot] = yRoot;
else if (rank[yRoot] < rank[xRoot])
parent[yRoot] = xRoot;
else
{
parent[yRoot] = xRoot;
rank[xRoot] = rank[xRoot] + 1;
}
}
}
static int[] KMP(String str) {
int n = str.length();
int[] kmp = new int[n];
for(int i = 1 ; i<n ; i++) {
int j = kmp[i-1];
while(j>0 && str.charAt(i) != str.charAt(j)) {
j = kmp[j-1];
}
if(str.charAt(i) == str.charAt(j)) j++;
kmp[i] = j;
}
return kmp;
}
/************************************************ Query **************************************************************************************/
/***************************************** Sparse Table ********************************************************/
static class SparseTable{
private long[][] st;
SparseTable(long[] arr){
int n = arr.length;
st = new long[n][25];
log = new int[n+2];
build_log(n+1);
build(arr);
}
private void build(long[] arr) {
int n = arr.length;
for(int i = n-1 ; i>=0 ; i--) {
for(int j = 0 ; j<25 ; j++) {
int r = i + (1<<j)-1;
if(r>=n) break;
if(j == 0 ) st[i][j] = arr[i];
else st[i][j] = Math.min(st[i][j-1] , st[ i + ( 1 << (j-1) ) ][ j-1 ] );
}
}
}
public long gcd(long a ,long b) {
if(a == 0) return b;
return gcd(b%a , a);
}
public long query(int l ,int r) {
int w = r-l+1;
int power = log[w];
return Math.min(st[l][power],st[r - (1<<power) + 1][power]);
}
private int[] log;
void build_log(int n) {
log[1] = 0;
for(int i = 2 ; i<=n ; i++) {
log[i] = 1 + log[i/2];
}
}
}
/******************************************************** Segement Tree *****************************************************/
/**
static class SegmentTree{
long[] tree;
long[] arr;
int n;
SegmentTree(long[] arr){
this.n = arr.length;
tree = new long[4*n+1];
this.arr = arr;
buildTree(0, n-1, 1);
}
void buildTree(int s ,int e ,int index ) {
if(s == e) {
tree[index] = arr[s];
return;
}
int mid = (s+e)/2;
buildTree( s, mid, 2*index);
buildTree( mid+1, e, 2*index+1);
tree[index] = Math.min(tree[2*index] , tree[2*index+1]);
}
long query(int si ,int ei) {
return query(0 ,n-1 , si ,ei , 1 );
}
private long query( int ss ,int se ,int qs , int qe,int index) {
if(ss>=qs && se<=qe) return tree[index];
if(qe<ss || se<qs) return (long)(1e17);
int mid = (ss + se)/2;
long left = query( ss , mid , qs ,qe , 2*index);
long right= query(mid + 1 , se , qs ,qe , 2*index+1);
return Math.min(left, right);
}
public void update(int index , int val) {
arr[index] = val;
for(long e:arr) System.out.print(e+" ");
update(index , 0 , n-1 , 1);
}
private void update(int id ,int si , int ei , int index) {
if(id < si || id>ei) return;
if(si == ei ) {
tree[index] = arr[id];
return;
}
if(si > ei) return;
int mid = (ei + si)/2;
update( id, si, mid , 2*index);
update( id , mid+1, ei , 2*index+1);
tree[index] = Math.min(tree[2*index] ,tree[2*index+1]);
}
}
*/
/* ***************************************************************************************************************************************************/
static Reader sc = new Reader();
static StringBuilder sb = new StringBuilder();
public static void main(String args[]) throws IOException {
int tc = 1;
// tc = sc.nextInt();
for(int i = 1 ; i<=tc ; i++) {
// sb.append("Case #" + i + ": " ); // During KickStart && HackerCup
TEST_CASE();
}
System.out.println(sb);
// System.out.println();
}
static void TEST_CASE() {
int l = 1, r = sc.nextInt(), mid, x;
int second_max = query(l, r);
while (l < r) {
mid = (l + r) / 2;
if (second_max <= mid) {
x = query(Math.min(l, second_max), mid);
if (x == second_max)
r = mid;
else
l = mid + 1;
} else {
x = query(mid + 1, Math.max(second_max, r));
if (x == second_max)
l = mid + 1;
else
r = mid;
}
}
System.out.printf("! %d\n", l);
}
static int query(int a, int b) {
if(a>=b) return 0;
System.out.println("? "+a+" "+b);
System.out.flush();
return sc.nextInt();
}
}
/*******************************************************************************************************************************************************/
/**
*/
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
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
|
c5ea1d1ffd6aff748fab8b3bfe516ed5
|
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 three {
public static void main(String[] args) throws IOException, FileNotFoundException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
//BufferedReader in = new BufferedReader(new FileReader("three"));
int n = Integer.parseInt(in.readLine());
int left = 0;
int right = n-1;
while (left < right) {
System.out.println("? " + (left+1) + " " + (1+right));
System.out.flush();
int lastmin = Integer.parseInt(in.readLine())-1;
int mid = (left + right)/2;
if (mid == left && mid >= lastmin) {
left = mid+1;
break;
}
if (mid >= lastmin) {
System.out.println("? " + (left+1) + " " + (1+mid));
System.out.flush();
int curmin = Integer.parseInt(in.readLine())-1;
if (lastmin == curmin) {
right = mid;
}
else {
left = mid + 1;
}
// lastmin = curmin;
}
else {
System.out.println("? " + (mid+1) + " " + (1+right));
System.out.flush();
int curmin = Integer.parseInt(in.readLine())-1;
if (lastmin == curmin) {
left = mid;
}
else {
right = mid-1;
}
// lastmin = curmin;
}
if (left < right) {
if (lastmin == left) left++;
if (lastmin == right) right--;
}
}
System.out.println("! " + (left+1));
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
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
|
d657410fc1b2be5057f2804e1d651647
|
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.*;
@SuppressWarnings("unchecked")
public class GuessingtheGreatest implements Runnable {
void solve() throws IOException {
int l = 1, h = read.intNext();
while (h - l > 1) {
int mid = (h + l) / 2;
int curr = ask(l, h);
if (curr < mid) {
if (ask(l, mid) == curr) {
h = mid;
} else {
l = mid;
}
} else {
if( ask(mid, h) == curr){
l = mid;
}else{
h = mid;
}
}
}
int q = ask(l, h);
if( q == h ){
println("! " + l);
}else{
println("! " + h);
}
}
int ask(int l, int h) throws IOException {
if (l >= h) return -1;
System.out.println("? " + l + " " + h);
return read.intNext();
}
/************************************************************************************************************************************************/
public static void main(String[] args) throws IOException {
new Thread(null, new GuessingtheGreatest(), "1").start();
}
static PrintWriter out = new PrintWriter(System.out);
static Reader read = new Reader();
static StringBuilder sbr = new StringBuilder();
static int mod = (int) 1e9 + 7;
static int dmax = Integer.MAX_VALUE;
static long lmax = Long.MAX_VALUE;
static int dmin = Integer.MIN_VALUE;
static long lmin = Long.MIN_VALUE;
@Override
public void run() {
try {
solve();
out.close();
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
}
static class Reader {
private byte[] buf = new byte[1024];
private int index;
private InputStream in;
private int total;
public Reader() {
in = System.in;
}
public int scan() throws IOException {
if (total < 0)
throw new InputMismatchException();
if (index >= total) {
index = 0;
total = in.read(buf);
if (total <= 0)
return -1;
}
return buf[index++];
}
public int intNext() throws IOException {
int integer = 0;
int n = scan();
while (isWhiteSpace(n))
n = scan();
int neg = 1;
if (n == '-') {
neg = -1;
n = scan();
}
while (!isWhiteSpace(n)) {
if (n >= '0' && n <= '9') {
integer *= 10;
integer += n - '0';
n = scan();
} else throw new InputMismatchException();
}
return neg * integer;
}
public double doubleNext() throws IOException {
double doub = 0;
int n = scan();
while (isWhiteSpace(n))
n = scan();
int neg = 1;
if (n == '-') {
neg = -1;
n = scan();
}
while (!isWhiteSpace(n) && n != '.') {
if (n >= '0' && n <= '9') {
doub *= 10;
doub += n - '0';
n = scan();
} else throw new InputMismatchException();
}
if (n == '.') {
n = scan();
double temp = 1;
while (!isWhiteSpace(n)) {
if (n >= '0' && n <= '9') {
temp /= 10;
doub += (n - '0') * temp;
n = scan();
} else throw new InputMismatchException();
}
}
return doub * neg;
}
public String read() throws IOException {
StringBuilder sb = new StringBuilder();
int n = scan();
while (isWhiteSpace(n))
n = scan();
while (!isWhiteSpace(n)) {
sb.append((char) n);
n = scan();
}
return sb.toString();
}
private boolean isWhiteSpace(int n) {
if (n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1)
return true;
return false;
}
}
static void shuffle(int[] aa, int n) {
Random rand = new Random();
for (int i = 1; i < n; i++) {
int j = rand.nextInt(i + 1);
int tmp = aa[i];
aa[i] = aa[j];
aa[j] = tmp;
}
}
static void shuffle(int[][] aa, int n) {
Random rand = new Random();
for (int i = 1; i < n; i++) {
int j = rand.nextInt(i + 1);
int first = aa[i][0];
int second = aa[i][1];
aa[i][0] = aa[j][0];
aa[i][1] = aa[j][1];
aa[j][0] = first;
aa[j][1] = second;
}
}
static final class Comparators {
public static final Comparator<int[]> pairIntArr =
(x, y) -> x[0] == y[0] ? compare(x[1], y[1]) : compare(x[0], y[0]);
private static final int compare(final int x, final int y) {
return Integer.compare(x, y);
}
}
static void print(Object object) {
out.print(object);
}
static void println(Object object) {
out.println(object);
}
static int[] iArr(int len) {
return new int[len];
}
static long[] lArr(int len) {
return new long[len];
}
static long min(long a, long b) {
return Math.min(a, b);
}
static int min(int a, int b) {
return Math.min(a, b);
}
static long max(Long a, Long b) {
return Math.max(a, b);
}
static int max(int a, int b) {
return Math.max(a, b);
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
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
|
f1e08dc5b9dd8cff1f239372a58c5902
|
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.*;
@SuppressWarnings("unchecked")
public class GuessingtheGreatest implements Runnable {
void solve() throws IOException {
int l = 0, h = read.intNext();
while (h - l > 1) {
int mid = (h + l) / 2;
int curr = ask(l, h - 1);
if (curr < mid) {
if (ask(l, mid - 1) == curr) {
h = mid;
} else {
l = mid;
}
} else {
if( ask(mid, h - 1) == curr){
l = mid;
}else{
h = mid;
}
}
}
println("! " + h);
}
int ask(int l, int h) throws IOException {
if (l >= h) return -1;
System.out.println("? " + (l + 1) + " " + (h + 1));
return read.intNext() - 1;
}
/************************************************************************************************************************************************/
public static void main(String[] args) throws IOException {
new Thread(null, new GuessingtheGreatest(), "1").start();
}
static PrintWriter out = new PrintWriter(System.out);
static Reader read = new Reader();
static StringBuilder sbr = new StringBuilder();
static int mod = (int) 1e9 + 7;
static int dmax = Integer.MAX_VALUE;
static long lmax = Long.MAX_VALUE;
static int dmin = Integer.MIN_VALUE;
static long lmin = Long.MIN_VALUE;
@Override
public void run() {
try {
solve();
out.close();
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
}
static class Reader {
private byte[] buf = new byte[1024];
private int index;
private InputStream in;
private int total;
public Reader() {
in = System.in;
}
public int scan() throws IOException {
if (total < 0)
throw new InputMismatchException();
if (index >= total) {
index = 0;
total = in.read(buf);
if (total <= 0)
return -1;
}
return buf[index++];
}
public int intNext() throws IOException {
int integer = 0;
int n = scan();
while (isWhiteSpace(n))
n = scan();
int neg = 1;
if (n == '-') {
neg = -1;
n = scan();
}
while (!isWhiteSpace(n)) {
if (n >= '0' && n <= '9') {
integer *= 10;
integer += n - '0';
n = scan();
} else throw new InputMismatchException();
}
return neg * integer;
}
public double doubleNext() throws IOException {
double doub = 0;
int n = scan();
while (isWhiteSpace(n))
n = scan();
int neg = 1;
if (n == '-') {
neg = -1;
n = scan();
}
while (!isWhiteSpace(n) && n != '.') {
if (n >= '0' && n <= '9') {
doub *= 10;
doub += n - '0';
n = scan();
} else throw new InputMismatchException();
}
if (n == '.') {
n = scan();
double temp = 1;
while (!isWhiteSpace(n)) {
if (n >= '0' && n <= '9') {
temp /= 10;
doub += (n - '0') * temp;
n = scan();
} else throw new InputMismatchException();
}
}
return doub * neg;
}
public String read() throws IOException {
StringBuilder sb = new StringBuilder();
int n = scan();
while (isWhiteSpace(n))
n = scan();
while (!isWhiteSpace(n)) {
sb.append((char) n);
n = scan();
}
return sb.toString();
}
private boolean isWhiteSpace(int n) {
if (n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1)
return true;
return false;
}
}
static void shuffle(int[] aa, int n) {
Random rand = new Random();
for (int i = 1; i < n; i++) {
int j = rand.nextInt(i + 1);
int tmp = aa[i];
aa[i] = aa[j];
aa[j] = tmp;
}
}
static void shuffle(int[][] aa, int n) {
Random rand = new Random();
for (int i = 1; i < n; i++) {
int j = rand.nextInt(i + 1);
int first = aa[i][0];
int second = aa[i][1];
aa[i][0] = aa[j][0];
aa[i][1] = aa[j][1];
aa[j][0] = first;
aa[j][1] = second;
}
}
static final class Comparators {
public static final Comparator<int[]> pairIntArr =
(x, y) -> x[0] == y[0] ? compare(x[1], y[1]) : compare(x[0], y[0]);
private static final int compare(final int x, final int y) {
return Integer.compare(x, y);
}
}
static void print(Object object) {
out.print(object);
}
static void println(Object object) {
out.println(object);
}
static int[] iArr(int len) {
return new int[len];
}
static long[] lArr(int len) {
return new long[len];
}
static long min(long a, long b) {
return Math.min(a, b);
}
static int min(int a, int b) {
return Math.min(a, b);
}
static long max(Long a, Long b) {
return Math.max(a, b);
}
static int max(int a, int b) {
return Math.max(a, b);
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
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
|
0bcbb9a351353af00eb8c5b5c486afec
|
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[]){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int l = 1;
int r = n;
boolean done = false;
while(!done){
if(l==r-1){
System.out.println("? "+l+" "+r);
int z = sc.nextInt();
int ans = z==l? r:l;
System.out.println("! "+ans);
System.out.flush();
done = true;
break;
}
if(l==r){
int ans = l;
System.out.println("! "+ans);
System.out.flush();
done = true;
break;
}
System.out.println("? "+l+" "+r);
int x = sc.nextInt();
int mid = (r+l)/2;
if(x<=mid){
System.out.println("? "+l+" "+mid);
int y = sc.nextInt();
if(x==y){
r = mid;
}
else{
l = mid+1;
}
}
else{
if(mid==r-1){
System.out.println("? "+(mid)+" "+r);
int y = sc.nextInt();
if(x==y){
l = mid;
}
else{
r = mid;
}
}
else{
System.out.println("? "+(mid+1)+" "+r);
int y = sc.nextInt();
if(x==y){
l = mid+1;
}
else{
r = mid;
}
}
}
}
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
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
|
257b36778e8ac509102eda7b34d2815c
|
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 guessingTheGreatest {
static MyScanner sc = new MyScanner();
public static void main(String[] args) {
int n = sc.nextInt();
int l = 1;
int r = n;
int res = -1;
while(l<r) {
int mid = l + (r-l)/2;
int x = ask(l,r);
if(r==l+1) {
if(x==l) {
res = r;
}
else {
res = l;
}
break;
}
else {
if(x>=mid) {
int x2 = ask(mid,r);
if(x2==x) {
l = mid;
}
else {
r = mid-1;
}
}
else {
int x2 = ask(l,mid);
if(x2==x) {
r = mid;
}
else {
l = mid+1;
}
}
}
res = l;
}
System.out.println("! "+res);
System.out.flush();
}
static int ask(int a, int b) {
System.out.println("? "+a+" "+b);
System.out.flush();
int x = sc.nextInt();
return x;
}
public static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
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
|
58b1019cdb8e383b86a3a33bfe3b7b45
|
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;
//Some of the methods are copied from GeeksforGeeks Website
import java.util.*;
import java.lang.*;
import java.io.*;
public class Main
{
//static Scanner sc=new Scanner(System.in)
static Reader sc=new Reader();
// static FastReader sc=new FastReader(System.in);
static long mod = (long)(1e9)+ 7;
static int max_num=(int)1e5+5;
static int query(int l,int r) throws java.lang.Exception
{
if(l>=r) return -1;
out.println("? "+(l+1)+" "+(r+1));
out.flush();
int x=sc.nextInt();
return x-1;
}
static int solve(int n) throws java.lang.Exception
{
int l=0,r=n;
while(l+1<r)
{
int m = (l + r) / 2;
int smax = query(l, r - 1);
if (smax < m)
{
if (query(l, m - 1) == smax)
r = m;
else
l = m;
}
else
{
if (query(m, r - 1) == smax)
l = m;
else
r = m;
}
}
return r;
}
public static void main (String[] args) throws java.lang.Exception
{
try{
/*
int n=sc.nextInt();
Collections.sort(al,Collections.reverseOrder());
long n=sc.nextLong();
String s=sc.next();
StringBuilder sb=new StringBuilder();
*/
int t = 1;//sc.nextInt();
while(t-->0)
{
int n=sc.nextInt();
int ans=solve(n);
out.println("! "+ans);
}
out.flush();
out.close();
}
catch(Exception e)
{}
}
/*
...SOLUTION ENDS HERE...........SOLUTION ENDS HERE...
*/
static void flag(boolean flag)
{
out.println(flag ? "YES" : "NO");
out.flush();
}
/*
Map<Long,Long> map=new HashMap<>();
for(int i=0;i<n;i++)
{
if(!map.containsKey(a[i]))
map.put(a[i],1);
else
map.replace(a[i],map.get(a[i])+1);
}
Set<Map.Entry<Long,Long>> hmap=map.entrySet();
for(Map.Entry<Long,Long> data : hmap)
{
}
*/
// static class Pair
// {
// int x,y;
// Pair(int x,int y)
// {
// this.x=x;
// this.y=y;
// }
// }
// Arrays.sort(p, new Comparator<Pair>()
// {
// @Override
// public int compare(Pair o1,Pair o2)
// {
// if(o1.x>o2.x) return 1;
// else if(o1.x==o2.x)
// {
// if(o1.y>o2.y) return 1;
// else return -1;
// }
// else return -1;
// }});
static void print(int a[])
{
int n=a.length;
for(int i=0;i<n;i++)
{
out.print(a[i]+" ");
}
out.println();
out.flush();
}
static void print(long a[])
{
int n=a.length;
for(int i=0;i<n;i++)
{
out.print(a[i]+" ");
}
out.println();
out.flush();
}
static void print_int(ArrayList<Integer> al)
{
int si=al.size();
for(int i=0;i<si;i++)
{
out.print(al.get(i)+" ");
}
out.println();
out.flush();
}
static void print_long(ArrayList<Long> al)
{
int si=al.size();
for(int i=0;i<si;i++)
{
out.print(al.get(i)+" ");
}
out.println();
out.flush();
}
static int LowerBound(int a[], int x)
{ // x is the target value or key
int l=-1,r=a.length;
while(l+1<r) {
int m=(l+r)>>>1;
if(a[m]>=x) r=m;
else l=m;
}
return r;
}
static int UpperBound(int a[], int x)
{// x is the key or target value
int l=-1,r=a.length;
while(l+1<r) {
int m=(l+r)>>>1;
if(a[m]<=x) l=m;
else r=m;
}
return l+1;
}
static void DFS(ArrayList<Integer> graph[],boolean[] visited, int u)
{
visited[u]=true;
int v=0;
for(int i=0;i<graph[u].size();i++)
{
v=graph[u].get(i);
if(!visited[v])
DFS(graph,visited,v);
}
}
static boolean[] prime(int num)
{
boolean[] bool = new boolean[num];
for (int i = 0; i< bool.length; i++) {
bool[i] = true;
}
for (int i = 2; i< Math.sqrt(num); i++) {
if(bool[i] == true) {
for(int j = (i*i); j<num; j = j+i) {
bool[j] = false;
}
}
}
if(num >= 0) {
bool[0] = false;
bool[1] = false;
}
return bool;
}
static long nCr(long a,long b,long mod)
{
return (((fact[(int)a] * modInverse(fact[(int)b],mod))%mod * modInverse(fact[(int)(a - b)],mod))%mod + mod)%mod;
}
static long fact[]=new long[max_num];
static void fact_fill()
{
long fact[]=new long[max_num];
fact[0]=1l;
for(int i=1;i<max_num;i++)
{
fact[i]=(fact[i-1]*(long)i);
if(fact[i]>=mod)
fact[i]%=mod;
}
}
static long modInverse(long a, long m)
{
return power(a, m - 2, m);
}
static long power(long x, long y, long m)
{
if (y == 0)
return 1;
long p = power(x, y / 2, m) % m;
p = (long)((p * (long)p) % m);
if (y % 2 == 0)
return p;
else
return (long)((x * (long)p) % m);
}
static long sum_array(int a[])
{
int n=a.length;
long sum=0;
for(int i=0;i<n;i++)
sum+=a[i];
return sum;
}
static long sum_array(long a[])
{
int n=a.length;
long sum=0;
for(int i=0;i<n;i++)
sum+=a[i];
return sum;
}
static void sort(int[] a)
{
ArrayList<Integer> l=new ArrayList<>();
for (int i:a) l.add(i);
Collections.sort(l);
for (int i=0; i<a.length; i++) a[i]=l.get(i);
}
static void sort(long[] a)
{
ArrayList<Long> l=new ArrayList<>();
for (long i:a) l.add(i);
Collections.sort(l);
for (int i=0; i<a.length; i++) a[i]=l.get(i);
}
static void reverse_array(int a[])
{
int n=a.length;
int i,t;
for (i = 0; i < n / 2; i++) {
t = a[i];
a[i] = a[n - i - 1];
a[n - i - 1] = t;
}
}
static void reverse_array(long a[])
{
int n=a.length;
int i; long t;
for (i = 0; i < n / 2; i++) {
t = a[i];
a[i] = a[n - i - 1];
a[n - i - 1] = t;
}
}
static long gcd(long a, long b)
{
if (a == 0)
return b;
return gcd(b%a, a);
}
static int gcd(int a, int b)
{
if (a == 0)
return b;
return gcd(b%a, a);
}
static class FastReader{
byte[] buf = new byte[2048];
int index, total;
InputStream in;
FastReader(InputStream is) {
in = is;
}
int scan() throws IOException {
if (index >= total) {
index = 0;
total = in.read(buf);
if (total <= 0) {
return -1;
}
}
return buf[index++];
}
String next() throws IOException {
int c;
for (c = scan(); c <= 32; c = scan());
StringBuilder sb = new StringBuilder();
for (; c > 32; c = scan()) {
sb.append((char) c);
}
return sb.toString();
}
int nextInt() throws IOException {
int c, val = 0;
for (c = scan(); c <= 32; c = scan());
boolean neg = c == '-';
if (c == '-' || c == '+') {
c = scan();
}
for (; c >= '0' && c <= '9'; c = scan()) {
val = (val << 3) + (val << 1) + (c & 15);
}
return neg ? -val : val;
}
long nextLong() throws IOException {
int c;
long val = 0;
for (c = scan(); c <= 32; c = scan());
boolean neg = c == '-';
if (c == '-' || c == '+') {
c = scan();
}
for (; c >= '0' && c <= '9'; c = scan()) {
val = (val << 3) + (val << 1) + (c & 15);
}
return neg ? -val : val;
}
}
static class Reader
{
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader()
{
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Reader(String file_name) throws IOException
{
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException
{
byte[] buf = new byte[64]; // line length
int cnt = 0, c;
while ((c = read()) != -1)
{
if (c == '\n')
break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException
{
int ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do
{
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException
{
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException
{
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (c == '.')
{
while ((c = read()) >= '0' && c <= '9')
{
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException
{
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException
{
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException
{
if (din == null)
return;
din.close();
}
}
static PrintWriter out=new PrintWriter(System.out);
static int int_max=Integer.MAX_VALUE;
static int int_min=Integer.MIN_VALUE;
static long long_max=Long.MAX_VALUE;
static long long_min=Long.MIN_VALUE;
}
// Thank You !
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
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
|
f5a449544a0ad74c3800baa427958489
|
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.util.*;
public class CodeForces {
public static void main(String[] args) {
// TODO Auto-generated method stub
FastScanner fs=new FastScanner();
int n=fs.nextInt();
int pos=solve(0,n);
System.out.println("! "+pos);
// System.out.println("No of queery = "+count);
}
private static int solve(int l,int r) {
while (r - l > 1) {
int m = (l + r) / 2;
int smax = query(l, r - 1);
if (smax < m) {
if (query(l, m - 1) == smax) {
r = m;
} else {
l = m;
}
} else {
if (query(m, r - 1) == smax) {
l = m;
} else {
r = m;
}
}
}
return r;
}
private static int query(int l,int r) {
if(l>=r)
return -1;
System.out.println("? "+(l+1)+" "+(r+1));
FastScanner fs=new FastScanner();
int pos=fs.nextInt();
return pos-1;
}
static void mysort(int[] a) {
//ruffle
int n=a.length;
Random r=new Random();
for (int i=0; i<a.length; i++) {
int oi=r.nextInt(n), temp=a[i];
a[i]=a[oi];
a[oi]=temp;
}
//then sort
Arrays.sort(a);
}
// Use this to input code since it is faster than a Scanner
static class FastScanner {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st=new StringTokenizer("");
String next() {
while (!st.hasMoreTokens())
try {
st=new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
int[] readArray(int n) {
int[] a=new int[n];
for (int i=0; i<n; i++) a[i]=nextInt();
return a;
}
long nextLong() {
return Long.parseLong(next());
}
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
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
|
123279d12cf12c72f1d3672263bf63a7
|
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 GuessingTheGreatest {
public static void main(String[] args) {
FastScanner fs = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
int n = fs.nextInt();
int left = 1, right = n;
while(left + 1 < right) {
int mid = (left + right) / 2;
System.out.println("? " + left + " " + right);
int second = fs.nextInt();
if(mid <= second) {
System.out.println("? " + mid + " " + right);
int midsecond = fs.nextInt();
if(midsecond == second)
left = mid;
else
right = mid;
} else {
System.out.println("? " + left + " " + mid);
int midsecond = fs.nextInt();
if(midsecond == second)
right = mid;
else
left = mid;
}
}
System.out.println("? " + left + " " + right);
int v = fs.nextInt();
int myans = (v == left) ? right : left;
System.out.println("! " + myans);
}
static void ruffleSort(int[] a) {
int n = a.length;
Random r = new Random();
for(int i = 0; i < a.length; ++i) {
int oi = r.nextInt(n), t = a[i];
a[i] = a[oi];
a[oi] = t;
}
Arrays.sort(a);
}
static void sort(int[] a) {
ArrayList<Integer> l = new ArrayList<>();
for(int i : a) l.add(i);
Collections.sort(l);
for(int i = 0; i < a.length; ++i) a[i] = l.get(i);
}
static class FastScanner {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer("");
String next() {
while(!st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
int[] readArray(int n) {
int[] a = new int[n];
for(int i = 0; i < n; ++i)
a[i] = nextInt();
return a;
}
long nextLong() {
return Long.parseLong(next());
}
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
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
|
83465bf876487b0b58d89929862273b4
|
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.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class C {
static Scanner sc;
public static void main(String[] args) throws Exception{
sc = new Scanner(System.in);
int n = sc.nextInt();
int left = 1;
int right = n;
int oldPos = -1;
boolean checked = false;
while(true)
{
if(right-left == 1)
{
System.out.println("? "+left+" "+right);
System.out.flush();
int pos = sc.nextInt();
if(pos!=left)
{
System.out.println("! "+left);
System.out.flush();
}
else
{
System.out.println("! "+right);
System.out.flush();
}
break;
}
if(right == left)
{
System.out.println("! "+left);
System.out.flush();
break;
}
if(!checked)
{
// all the range check
System.out.println("? "+left+" "+right);
System.out.flush();
oldPos = sc.nextInt();
}
int mid = (left+right) / 2;
boolean posIsLeft = (oldPos <= mid);
if(posIsLeft)
{
System.out.println("? "+left+" "+mid);
System.out.flush();
}
else
{
System.out.println("? "+(mid)+" "+right);
System.out.flush();
}
int newPos = sc.nextInt();
if(oldPos == newPos)
{
checked = true;
// discard the other half
if(posIsLeft)
{
right = mid;
}
else
{
left = mid;
}
}
else
{
checked = false;
// discard this half
if(posIsLeft)
{
left = mid;
}
else
{
right = mid;
}
}
}
}
static class Scanner{
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream system) {
br = new BufferedReader(new InputStreamReader(system));
}
public Scanner(FileReader file) {
br = new BufferedReader(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 boolean ready() throws IOException {
return br.ready();
}
public void waitForInput() throws InterruptedException {
Thread.sleep(5000);
}
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
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
|
58cb42e8f3fbf17ac6fb01073f753d0a
|
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
|
// c1
import java.util.*;
// import java.lang.*;
import java.io.*;
// THIS TEMPLATE MADE BY AKSH BANSAL.
public class Solution {
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
public static void main(String[] args) throws IOException {
FastReader sc = new FastReader();
PrintWriter out = new PrintWriter(System.out);
// ________________________________
int n= sc.nextInt();
if(n==1){
out.println("! 1");
out.flush();
return;
}
int start = 1, end = n;
while(start<end){
int pos = query(start, end, out, sc);
int mid = start+(end-start)/2;
if(start+1==end){
if(pos==start){
start = end;
}
break;
}
// checking sub section
if(pos>mid){
if(mid+1==end){
end = mid;
continue;
}
int cur = query(mid+1, end, out, sc);
if(cur==pos){
start = mid+1;
}
else {
end = mid;
}
}
else{
int cur = query(start, mid, out, sc);
if(cur==pos){
end = mid;
}
else {
start = mid+1;
}
}
}
out.println("! "+start);
out.flush();
}
private static int query(int start, int end, PrintWriter out, FastReader sc) {
out.println("? "+start+" "+end);
out.flush();
int res= sc.nextInt();
return res;
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
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
|
e3a42d3fa6b6bbeed09cc7052eddcd6a
|
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 Main2 {
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 sc = new FastReader();
static int n;
public static void main (String[] args) {
PrintWriter out = new PrintWriter(System.out);
int t = 1;
// t = sc.nextInt();
while(t-->0) {
n = sc.nextInt();
int sm = ask(1,n);
int left = ask(1,sm);
int ans = -1;
if(left==sm) {
int l=1, h=sm-1;
while(l<=h) {
int mid = (l+h)/2;
left = ask(mid,sm);
if(left == sm) {
ans = mid;
l = mid+1;
}
else h = mid-1;
}
}
else {
int l=sm+1, h=n;
while(l<=h) {
int mid = (l+h)/2;
left = ask(sm,mid);
if(left == sm) {
ans = mid;
h = mid-1;
}
else l = mid+1;
}
}
System.out.println("! "+ans);
}
out.close();
}
private static int ask(int idx, int h) {
if(idx>n || h>n || idx == 0 || h == 0) return -1;
if(idx == h) return -1;
System.out.println("? "+idx+" "+h);
System.out.flush();
int ret = sc.nextInt();
return ret;
}
private static long pow(int i, int x) {
long ans = 1;
while(x>0) {
if(x%2==0) {
i*=i;
x/=2;
}
else {
ans*=i;
x--;
}
}
// System.out.println(ans+" ans");
return ans;
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
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
|
8f9e043570946d44b4dc250c004e69b1
|
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.ArrayList;
import java.util.Arrays.*;
import static java.util.Collections.*;
import static java.lang.Math.*;
import static java.util.Arrays.*;
public class cf {
static final int SCAN_LINE_LENGTH = 100002;
private static final boolean thread = false;
@SuppressWarnings("all")
static final boolean HAS_TEST_CASES = (1 == 0) ? true : false;
static int n, a[], e[][], vis[], m, b[];
@SuppressWarnings("all")
private static Vector<Integer> adj[], v = new Vector<>();
@SuppressWarnings("unchecked")
static void solve() throws Exception {
n = ni();
int l = 1, r = n, m;
pni("? " + l + " " + r);
m = ni();
while (r - l > 1) {
int mid = (l + r) / 2;
if (m <= mid) {
pni("? " + l + " " + (mid));
int i = ni();
if (i == m) {
r = mid;
} else {
l = mid + 1;
if (r - l >= 1) {
pni("? " + l + " " + r);
m = ni();
}
}
} else {
pni("? " + mid + " " + (r));
int i = ni();
if (i != m) {
r = mid - 1;
if (r - l >= 1) {
pni("? " + l + " " + r);
m = ni();
}
} else
l = mid;
}
}
l = (m == l) ? r : l;
pni("! " + l);
}
public static void main(final String[] args) throws Exception {
if (!thread) {
final int testcases = HAS_TEST_CASES ? ni() : 1;
for (int i = 1; i <= testcases; i++) {
// pni(i + " t");
// out.print("Case #" + (i + 1) + ": ");
try {
solve();
} catch (final Exception e) {
// pni("idk Exception");
// e.printStackTrace(System.err);
// System.exit(0);
pni(i);
throw e;
}
}
out.flush();
}
r.close();
out.close();
}
@SuppressWarnings("all")
private static final int MOD = (int) (1e9 + 7), MOD_FFT = 998244353;
private static final Reader r = new Reader();
private static final PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
public static long[] enumPows(int a, int n, int mod) {
a %= mod;
long[] pows = new long[n + 1];
pows[0] = 1;
for (int i = 1; i <= n; i++)
pows[i] = pows[i - 1] * a % mod;
return pows;
}
@SuppressWarnings("all")
private static boolean eq(long a, long b) {
return Long.compare(a, b) == 0;
}
@SuppressWarnings("all")
private static ArrayList<Integer> seive(int n) {
ArrayList<Integer> p = new ArrayList<>();
int[] f = new int[n + 1];
for (int i = 2; i <= n; i++) {
if (f[i] == 1)
continue;
for (int j = i * i; j <= n && j < f.length; j += i) {
f[j] = 1;
}
}
for (int i = 2; i < f.length; i++) {
if (f[i] == 0)
p.add(i);
}
return p;
}
@SuppressWarnings("all")
private static void s(int[] a) {
Integer[] t = new Integer[a.length];
for (int i = 0; i < t.length; i++) {
t[i] = a[i];
}
sort(t);
for (int i = 0; i < t.length; i++) {
a[i] = t[i];
}
}
int pow(int a, int b, int m) {
int ans = 1;
while (b != 0) {
if ((b & 1) != 0)
ans = (ans * a) % m;
b /= 2;
a = (a * a) % m;
}
return ans;
}
int modinv(int k) {
return pow(k, MOD - 2, MOD);
}
@SuppressWarnings("all")
private static void swap(final int i, final int j) {
final int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
@SuppressWarnings("all")
private static boolean isMulOverflow(final long A, final long B) {
if (A == 0 || B == 0)
return false;
final long result = A * B;
if (A == result / B)
return true;
return false;
}
@SuppressWarnings("all")
private static int gcd(final int a, final int b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
@SuppressWarnings("all")
private static long gcd(final long a, final long b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
@SuppressWarnings("all")
private static class Pair<T, E> implements Comparable<Pair<T, E>> {
T fir;
E snd;
Pair() {
}
Pair(final T x, final E y) {
this.fir = x;
this.snd = y;
}
// @Override
// @SuppressWarnings("unchecked")
// public int compareTo(final Pair<T, E> o) {
// final int c = ((Comparable<T>) fir).compareTo(o.fir);
// return c != 0 ? c : ((Comparable<E>) snd).compareTo(o.snd);
// }
@Override
@SuppressWarnings("unchecked")
public int compareTo(final Pair<T, E> o) {
final int c = ((Comparable<T>) fir).compareTo(o.fir);
return c;
}
}
@SuppressWarnings("all")
private static class pi implements Comparable<pi> {
int fir, snd;
pi() {
}
pi(final int a, final int b) {
fir = a;
snd = b;
}
public int compareTo(final pi o) {
return fir == o.fir ? snd - o.snd : fir - o.fir;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + fir;
result = prime * result + snd;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
pi other = (pi) obj;
if (fir != other.fir)
return false;
if (snd != other.snd)
return false;
return true;
}
}
@SuppressWarnings("all")
private static <T> void checkV(final Vector<T> adj[], final int i) {
adj[i] = adj[i] == null ? new Vector<>() : adj[i];
}
@SuppressWarnings("all")
private static int[] na(final int n) throws Exception {
final int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = ni();
}
return a;
}
@SuppressWarnings("all")
private static int[] na1(final int n) throws Exception {
final int[] a = new int[n + 1];
for (int i = 1; i < a.length; i++) {
a[i] = ni();
}
return a;
}
@SuppressWarnings("all")
private static String n() throws IOException {
return r.readToken();
}
@SuppressWarnings("all")
private static char[] ns() throws IOException {
return r.readToken().toCharArray();
}
@SuppressWarnings("all")
private static String nln() throws IOException {
return r.readLine();
}
private static int ni() throws IOException {
return r.nextInt();
}
@SuppressWarnings("all")
private static long nl() throws IOException {
return r.nextLong();
}
@SuppressWarnings("all")
private static double nd() throws IOException {
return r.nextDouble();
}
@SuppressWarnings("all")
private static void p(final Object o) {
out.print(o);
}
@SuppressWarnings("all")
private static void pn(final Object o) {
out.println(o);
}
@SuppressWarnings("all")
private static void pn() {
out.println("");
}
@SuppressWarnings("all")
private static void pi(final Object o) {
out.print(o);
out.flush();
}
@SuppressWarnings("all")
private static void pni() {
out.println("");
out.flush();
}
private static void pni(final Object o) {
out.println(o);
out.flush();
}
private static class Reader {
private final int BUFFER_SIZE = 1 << 17;
private final DataInputStream din;
private final byte[] buffer;
private int bufferPointer, bytesRead;
// private StringTokenizer st;
public Reader() {
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
@SuppressWarnings("all")
public Reader(final String file_name) throws IOException {
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
final byte[] buf = new byte[SCAN_LINE_LENGTH];
public String readLine() throws IOException {
int cnt = 0;
int c;
o: while ((c = read()) != -1) {
if (c == '\n')
if (cnt == 0)
continue o;
else
break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public String readToken() throws IOException {
int cnt = 0;
int c;
o: while ((c = read()) != -1) {
if (!(c >= 33 && c <= 126))
if (cnt == 0)
continue o;
else
break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException {
int ret = 0;
byte c = read();
while (c <= ' ')
c = read();
final boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException {
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
final boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException {
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
final boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (c == '.') {
while ((c = read()) >= '0' && c <= '9') {
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException {
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException {
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException {
if (din == null)
return;
din.close();
}
}
// static {
// if (thread)
// new Thread(null, new Runnable() {
// @Override
// public void run() {
// try {
// final int testcases = HAS_TEST_CASES ? ni() : 1;
// for (int i = 1; i <= testcases; i++) {
// // out.print("Case #" + (i + 1) + ": ");
// try {
// solve();
// } catch (final ArrayIndexOutOfBoundsException e) {
// e.printStackTrace(System.err);
// System.exit(-1);
// } catch (final Exception e) {
// pni("idk Exception in solve");
// e.printStackTrace(System.err);
// System.exit(-1);
// }
// }
// out.flush();
// } catch (final Throwable t) {
// t.printStackTrace(System.err);
// System.exit(-1);
// }
// }
// }, "rec", (1L << 28)).start();
// }
@SuppressWarnings({ "all", })
private static <T> T deepCopy(final T old) {
try {
return (T) deepCopyObject(old);
} catch (final IOException | ClassNotFoundException e) {
e.printStackTrace(System.err);
System.exit(-1);
}
return null;
}
private static Object deepCopyObject(final Object oldObj) throws IOException, ClassNotFoundException {
ObjectOutputStream oos = null;
ObjectInputStream ois = null;
try {
final ByteArrayOutputStream bos = new ByteArrayOutputStream(); // A
oos = new ObjectOutputStream(bos); // B
// serialize and pass the object
oos.writeObject(oldObj); // C
oos.flush(); // D
final ByteArrayInputStream bin = new ByteArrayInputStream(bos.toByteArray()); // E
ois = new ObjectInputStream(bin); // F
// return the new object
return ois.readObject(); // G
} catch (final ClassNotFoundException e) {
pni("Exception in ObjectCloner = " + e);
throw (e);
} finally {
oos.close();
ois.close();
}
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
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
|
0a01858506634f19e7b4cfab0e8ece23
|
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.util.*;
import java.io.*;
import java.lang.*;
public class Main{
/*
** || ॐ श्री गणेशाय नमः ||
** @𝙖𝙪𝙩𝙝𝙤𝙧 𝙅𝙞𝙜𝙖𝙧_𝙉𝙖𝙞𝙣𝙪𝙟𝙞
** 𝙎𝙑𝙉𝙄𝙏-𝙎𝙐𝙍𝘼𝙏
*/
public static void main(String args[]){
InputReader in=new InputReader(System.in);
TASK solver = new TASK();
int t=1;
// t = in.nextInt();
for(int i=1;i<=t;i++)
{
solver.solve(in,i);
}
}
static class TASK {
static int mod = 1000000000+7;
void solve(InputReader in, int testNumber) {
int n = in.nextInt();
int l=1,r=n;
Map<String,Integer> map = new HashMap<>();
while (l<r)
{
int mid = (l+r)/2;
int smaxid;
if(map.containsKey(l+" "+r))
{
smaxid=map.get(l+" "+r);
}
else {
System.out.println("? " + l + " " + r);
smaxid=in.nextInt();
map.put(l+" "+r,smaxid);
}
if(smaxid<=mid)
{
if(l==mid)
{
l=mid+1;
continue;
}
int l1;
if(map.containsKey(l+" "+mid))
{
l1=map.get(l+" "+mid);
}
else {
System.out.println("? " + l + " " + mid);
l1=in.nextInt();
map.put(l+" "+mid,l1);
}
if(l1==smaxid )
{
r=mid;
}
else
{
l=mid+1;
}
}
else
{
if(mid+1==r)
{
r=mid;
continue;
}
int l1;
if(map.containsKey((mid+1)+" "+r))
{
l1=map.get((mid+1)+" "+r);
}
else {
System.out.println("? " + (mid+1)+ " " + r);
l1=in.nextInt();
map.put((mid+1)+" "+r,l1);
}
if(l1==smaxid&& (mid+1)!=r)
{
l=mid+1;
}
else
{
r=mid;
}
}
}
System.out.println("! "+l);
System.out.flush();
}
}
static class pair{
long x;
int y;
pair(long x,int y) {
this.x = x;
this.y = y;
}
}
static class Maths {
static long gcd(long a, long b) {
if (a == 0)
return b;
return gcd(b % a, a);
}
public static long lcm(long a, long b) {
return (a * b) / gcd(a, b);
}
public static long factorial(int n) {
long fact = 1;
for (int i = 1; i <= n; i++) {
fact *= i;
}
return fact;
}
}
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 String nextLine() {
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
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);
}
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
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
|
68e2f34001e5f4ef6dc16787bad89bac
|
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.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.util.Arrays;
import java.util.Random;
import java.io.FileWriter;
import java.io.PrintWriter;
/*
Solution Created: 17:48:47 18/02/2021
Custom Competitive programming helper.
*/
public class Main {
static int qBound;
public static void solve() {
qBound = 0;
int n = in.nextInt();
int l = 1, r = n;
while(r-l>1){
int md = (r+l)/2;
int v2 = ask(l, r);
if(v2>=md) {
int v = ask(md,r);
if(v==v2) l = md;
else r = md;
}
else{
int v = ask(l,md);
if(v==v2) r = md;
else l = md;
}
}
if(l==r) found(l);
else{
if(ask(l, r)==l) found(r);
else found(l);
}
}
static int ask(int l, int r){
if(++qBound>40) throw new RuntimeException();
out.println("? "+l+" "+r);
out.flush();
return in.nextInt();
}
static void found(int i){
out.println("! "+i);
out.flush();
}
public static void main(String[] args) {
in = new Reader();
out = new Writer();
int t = 1;
while(t-->0) solve();
out.exit();
}
static Reader in; static Writer out;
static class Reader {
static BufferedReader br;
static StringTokenizer st;
public Reader() {
this.br = new BufferedReader(new InputStreamReader(System.in));
}
public Reader(String f){
try {
this.br = new BufferedReader(new FileReader(f));
} catch (IOException e) {
e.printStackTrace();
}
}
public int[] na(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = nextInt();
return a;
}
public double[] nd(int n) {
double[] a = new double[n];
for (int i = 0; i < n; i++) a[i] = nextDouble();
return a;
}
public long[] nl(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++) a[i] = nextLong();
return a;
}
public char[] nca() {
return next().toCharArray();
}
public String[] ns(int n) {
String[] a = new String[n];
for (int i = 0; i < n; i++) a[i] = next();
return a;
}
public int nextInt() {
ensureNext();
return Integer.parseInt(st.nextToken());
}
public double nextDouble() {
ensureNext();
return Double.parseDouble(st.nextToken());
}
public Long nextLong() {
ensureNext();
return Long.parseLong(st.nextToken());
}
public String next() {
ensureNext();
return st.nextToken();
}
public String nextLine() {
try {
return br.readLine();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
private void ensureNext() {
if (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
static class Util{
private static Random random = new Random();
static long[] fact;
public static void initFactorial(int n, long mod) {
fact = new long[n+1];
fact[0] = 1;
for (int i = 1; i < n+1; i++) fact[i] = (fact[i - 1] * i) % mod;
}
public static long modInverse(long a, long MOD) {
long[] gcdE = gcdExtended(a, MOD);
if (gcdE[0] != 1) return -1; // Inverted doesn't exist
long x = gcdE[1];
return (x % MOD + MOD) % MOD;
}
public static long[] gcdExtended(long p, long q) {
if (q == 0) return new long[] { p, 1, 0 };
long[] vals = gcdExtended(q, p % q);
long tmp = vals[2];
vals[2] = vals[1] - (p / q) * vals[2];
vals[1] = tmp;
return vals;
}
public static long nCr(int n, int r, long MOD) {
if (r == 0) return 1;
return (fact[n] * modInverse(fact[r], MOD) % MOD * modInverse(fact[n - r], MOD) % MOD) % MOD;
}
public static long nCr(int n, int r) {
return (fact[n]/fact[r])/fact[n-r];
}
public static long nPr(int n, int r, long MOD) {
if (r == 0) return 1;
return (fact[n] * modInverse(fact[n - r], MOD) % MOD) % MOD;
}
public static long nPr(int n, int r) {
return fact[n]/fact[n-r];
}
public static boolean isPrime(int n) {
if (n <= 1) return false;
if (n <= 3) return true;
if (n % 2 == 0 || n % 3 == 0) return false;
for (int i = 5; i * i <= n; i = i + 6)
if (n % i == 0 || n % (i + 2) == 0)
return false;
return true;
}
public static boolean[] getSieve(int n) {
boolean[] isPrime = new boolean[n+1];
for (int i = 2; i <= n; i++) isPrime[i] = true;
for (int i = 2; i*i <= n; i++) if (isPrime[i])
for (int j = i; i*j <= n; j++) isPrime[i*j] = false;
return isPrime;
}
public static int gcd(int a, int b) {
int tmp = 0;
while(b != 0) {
tmp = b;
b = a%b;
a = tmp;
}
return a;
}
public static long gcd(long a, long b) {
long tmp = 0;
while(b != 0) {
tmp = b;
b = a%b;
a = tmp;
}
return a;
}
public static int random(int min, int max) {
return random.nextInt(max-min+1)+min;
}
public static void dbg(Object... o) {
System.out.println(Arrays.deepToString(o));
}
public static void reverse(int[] s, int l , int r) {
for(int i = l; i<=(l+r)/2; i++) {
int tmp = s[i];
s[i] = s[r+l-i];
s[r+l-i] = tmp;
}
}
public static void reverse(int[] s) {
reverse(s, 0, s.length-1);
}
public static void reverse(long[] s, int l , int r) {
for(int i = l; i<=(l+r)/2; i++) {
long tmp = s[i];
s[i] = s[r+l-i];
s[r+l-i] = tmp;
}
}
public static void reverse(long[] s) {
reverse(s, 0, s.length-1);
}
public static void reverse(float[] s, int l , int r) {
for(int i = l; i<=(l+r)/2; i++) {
float tmp = s[i];
s[i] = s[r+l-i];
s[r+l-i] = tmp;
}
}
public static void reverse(float[] s) {
reverse(s, 0, s.length-1);
}
public static void reverse(double[] s, int l , int r) {
for(int i = l; i<=(l+r)/2; i++) {
double tmp = s[i];
s[i] = s[r+l-i];
s[r+l-i] = tmp;
}
}
public static void reverse(double[] s) {
reverse(s, 0, s.length-1);
}
public static void reverse(char[] s, int l , int r) {
for(int i = l; i<=(l+r)/2; i++) {
char tmp = s[i];
s[i] = s[r+l-i];
s[r+l-i] = tmp;
}
}
public static void reverse(char[] s) {
reverse(s, 0, s.length-1);
}
public static <T> void reverse(T[] s, int l , int r) {
for(int i = l; i<=(l+r)/2; i++) {
T tmp = s[i];
s[i] = s[r+l-i];
s[r+l-i] = tmp;
}
}
public static <T> void reverse(T[] s) {
reverse(s, 0, s.length-1);
}
public static void shuffle(int[] s) {
for (int i = 0; i < s.length; ++i) {
int j = random.nextInt(i + 1);
int t = s[i];
s[i] = s[j];
s[j] = t;
}
}
public static void shuffle(long[] s) {
for (int i = 0; i < s.length; ++i) {
int j = random.nextInt(i + 1);
long t = s[i];
s[i] = s[j];
s[j] = t;
}
}
public static void shuffle(float[] s) {
for (int i = 0; i < s.length; ++i) {
int j = random.nextInt(i + 1);
float t = s[i];
s[i] = s[j];
s[j] = t;
}
}
public static void shuffle(double[] s) {
for (int i = 0; i < s.length; ++i) {
int j = random.nextInt(i + 1);
double t = s[i];
s[i] = s[j];
s[j] = t;
}
}
public static void shuffle(char[] s) {
for (int i = 0; i < s.length; ++i) {
int j = random.nextInt(i + 1);
char t = s[i];
s[i] = s[j];
s[j] = t;
}
}
public static <T> void shuffle(T[] s) {
for (int i = 0; i < s.length; ++i) {
int j = random.nextInt(i + 1);
T t = s[i];
s[i] = s[j];
s[j] = t;
}
}
public static void sortArray(int[] a) {
shuffle(a);
Arrays.sort(a);
}
public static void sortArray(long[] a) {
shuffle(a);
Arrays.sort(a);
}
public static void sortArray(float[] a) {
shuffle(a);
Arrays.sort(a);
}
public static void sortArray(double[] a) {
shuffle(a);
Arrays.sort(a);
}
public static void sortArray(char[] a) {
shuffle(a);
Arrays.sort(a);
}
public static <T extends Comparable<T>> void sortArray(T[] a) {
Arrays.sort(a);
}
}
static class Writer {
private PrintWriter pw;
public Writer(){
pw = new PrintWriter(System.out);
}
public Writer(String f){
try {
pw = new PrintWriter(new FileWriter(f));
} catch (IOException e) {
e.printStackTrace();
}
}
public void printArray(int[] a) {
for(int i = 0; i<a.length; i++) print(a[i]+" ");
}
public void printlnArray(int[] a) {
for(int i = 0; i<a.length; i++) print(a[i]+" ");
pw.println();
}
public void printArray(long[] a) {
for(int i = 0; i<a.length; i++) print(a[i]+" ");
}
public void printlnArray(long[] a) {
for(int i = 0; i<a.length; i++) print(a[i]+" ");
pw.println();
}
public void print(Object o) {
pw.print(o.toString());
}
public void println(Object o) {
pw.println(o.toString());
}
public void println() {
pw.println();
}
public void flush() {
pw.flush();
}
public void exit() {
pw.close();
}
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
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
|
51a9bf7ac9a3da0e74ef3f228c0a7e46
|
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.InputStreamReader;
import java.util.*;
public class C7003 {
static BufferedReader br;
static long mod = 1000000000 + 7;
static HashSet<Integer> p = new HashSet<>();
public static void main(String[] args) throws Exception {
br = new BufferedReader(new InputStreamReader(System.in));
int tc = 1;
// tc = cinI();
while (tc-- > 0) {
int n =cinI();
// int l=1; int r =n;
// System.out.println("? "+l+" "+r);
// int x =cinI();
// int mid = (l+r)/2;
// System.out.println("? "+mid+" "+r);
// int y =cinI();
int ans = d2c(1,n);
System.out.println("! "+ans);
System.out.flush();
}
}
public static int d2c(int l,int r)throws Exception{
if(r-l==1){
System.out.println("? "+l +" "+r);
int sum=l+r;
int z = cinI();
return sum-z;
}
System.out.println("? "+l+" "+r);
System.out.flush();
int x =cinI();
int mid =(l+r)/2;
if(x>=mid) {
System.out.println("? " + mid + " " + r);
System.out.flush();
int y = cinI();
if(x==y){
return d2c(mid,r);
}
else {
return d2c(l,mid);
}
}
else{
System.out.println("? "+l+" "+mid);
System.out.flush();
int y = cinI();
if(x==y){
return d2c(l,mid);
}
else {
return d2c(mid,r);
}
}
// int y = cinI();
}
private static int dfs(TreeMap<Integer, HashSet<Integer>> graph, boolean[] vis, Integer key, Stack<Integer> st) {
if (st.size() == 0) {
return 0;
}
int par = st.pop();
HashSet<Integer> child = graph.get(par);
vis[par] = true;
int nodes = 1;
for (int c : child) {
if (vis[c] == false) {
st.add(c);
nodes += dfs(graph, vis, c, st);
}
}
return nodes;
}
public static boolean isSorted(int[] arr) {
for (int i = 0; i < arr.length - 1; i++) {
if (arr[i] > arr[i + 1]) {
return false;
}
}
return true;
}
private static long gcd(long a, long b) {
if (a == 0)
return b;
if (b == 0)
return a;
// base case
if (a == b)
return a;
// a is greater
if (a > b)
return gcd(a % b, b);
return gcd(a, b % a);
}
public static long min(long a, long b) {
return Math.min(a, b);
}
public static int min(int a, int b) {
return Math.min(a, b);
}
public static void sieve() {
int[] pf = new int[100000000 + 1];
//0 prime //1 not prime
pf[0] = 1;
pf[1] = 1;
for (int j = 2; j <= 10000; j++) {
if (pf[j] == 0) {
p.add(j);
for (int k = j * j; k < pf.length; k += j) {
pf[k] = 1;
}
}
}
}
public static int[] readArray(int n, int x, int z) throws Exception {
int[] arr = new int[n];
String[] ar = cinA();
for (int i = x; i < n + x; i++) {
arr[i] = getI(ar[i - x]);
}
return arr;
}
public static long[] readArray(int n, int x) throws Exception {
long[] arr = new long[n];
String[] ar = cinA();
for (int i = x; i < n + x; i++) {
arr[i] = getL(ar[i - x]);
}
return arr;
}
public static void arrinit(String[] a, long[] b) throws Exception {
for (int i = 0; i < a.length; i++) {
b[i] = Long.parseLong(a[i]);
}
}
public static HashSet<Integer>[] Graph(int n, int edge, int directed) throws Exception {
HashSet<Integer>[] tree = new HashSet[n];
for (int j = 0; j < edge; j++) {
String[] uv = cinA();
int u = getI(uv[0]);
int v = getI(uv[1]);
if (directed == 0) {
tree[v].add(u);
}
tree[u].add(v);
}
return tree;
}
public static void arrinit(String[] a, int[] b) throws Exception {
for (int i = 0; i < a.length; i++) {
b[i] = Integer.parseInt(a[i]);
}
}
static double findRoots(int a, int b, int c) {
// If a is 0, then equation is not
//quadratic, but linear
int d = b * b - 4 * a * c;
double sqrt_val = Math.sqrt(Math.abs(d));
// System.out.println("Roots are real and different \n");
return Math.max((double) (-b + sqrt_val) / (2 * a),
(double) (-b - sqrt_val) / (2 * a));
}
public static String cin() throws Exception {
return br.readLine();
}
public static String[] cinA() throws Exception {
return br.readLine().split(" ");
}
public static String[] cinA(int x) throws Exception {
return br.readLine().split("");
}
public static String ToString(Long x) {
return Long.toBinaryString(x);
}
public static void cout(String s) {
System.out.println(s);
}
public static Integer cinI() throws Exception {
return Integer.parseInt(br.readLine());
}
public static int getI(String s) throws Exception {
return Integer.parseInt(s);
}
public static long getL(String s) throws Exception {
return Long.parseLong(s);
}
public static long max(long a, long b) {
return Math.max(a, b);
}
public static int max(int a, int b) {
return Math.max(a, b);
}
public static void coutI(int x) {
System.out.println(String.valueOf(x));
}
public static void coutI(long x) {
System.out.println(String.valueOf(x));
}
public static Long cinL() throws Exception {
return Long.parseLong(br.readLine());
}
public static void arrInit(String[] arr, int[] arr1) throws Exception {
for (int i = 0; i < arr.length; i++) {
arr1[i] = getI(arr[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 11
|
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
|
490153050b4a0fcf5497658c6fa965a4
|
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.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.*;
public class weird_algrithm {
static BufferedWriter output = new BufferedWriter(
new OutputStreamWriter(System.out));
static BufferedReader sc = new BufferedReader(new InputStreamReader(System.in));
static int mod = 1000000007;
static String toReturn = "";
static int steps = Integer.MAX_VALUE;
static int maxlen = 1000005;
/*MATHEMATICS FUNCTIONS START HERE
MATHS
MATHS
MATHS
MATHS*/
static long gcd(long a, long b) {
if(b == 0) return a;
else return gcd(b, a % b);
}
static long powerMod(long x, long y, int mod) {
if(y == 0) return 1;
long temp = powerMod(x, y / 2, mod);
temp = ((temp % mod) * (temp % mod)) % mod;
if(y % 2 == 0) return temp;
else return ((x % mod) * (temp % mod)) % mod;
}
static long modInverse(long n, int p) {
return powerMod(n, p - 2, p);
}
static long nCr(int n, int r, int mod, long [] fact, long [] ifact) {
return ((fact[n] % mod) * ((ifact[r] * ifact[n - r]) % mod)) % mod;
}
static boolean isPrime(long a) {
if(a == 1) return false;
else if(a == 2 || a == 3 || a== 5) return true;
else if(a % 2 == 0 || a % 3 == 0) return false;
for(int i = 5; i * i <= a; i = i + 6) {
if(a % i == 0 || a % (i + 2) == 0) return false;
}
return true;
}
static int [] seive(int a) {
int [] toReturn = new int [a + 1];
for(int i = 0; i < a; i++) toReturn[i] = 1;
toReturn[0] = 0;
toReturn[1] = 0;
toReturn[2] = 1;
for(int i = 2; i * i <= a; i++) {
if(toReturn[i] == 0) continue;
for(int j = 2 * i; j <= a; j += i) toReturn[j] = 0;
}
return toReturn;
}
static long [] fact(int a) {
long [] arr = new long[a + 1];
arr[0] = 1;
for(int i = 1; i < a + 1; i++) {
arr[i] = (arr[i - 1] * i) % mod;
}
return arr;
}
static ArrayList<Long> divisors(long n) {
ArrayList<Long> arr = new ArrayList<Long>();
for(long i = 2; i * i <= n; i++) {
if(n % i == 0) {
while(n % i == 0) {
n /= i;
}
arr.add(i);
}
}
if(n > 1) arr.add(n);
return arr;
}
static int euler(int n) {
int ans = n;
for(int i = 2; i * i <= n; i++) {
if(n % i == 0) {
while(n % i == 0) {
n /= i;
}
ans -= ans / i;
}
}
if(n > 1) ans -= ans / n;
return ans;
}
static long extendedEuclid(long a, long b, long [] arr) {
if(b == 0) {
arr[0] = 1;
arr[1] = 0;
return a;
}
long [] arr1 = new long[2];
long d = extendedEuclid(b, a % b, arr1);
arr[0] = arr1[1];
arr[1] = arr1[0] - arr1[1] * (a / b);
return d;
}
/*MATHS
MATHS
MATHS
MATHS
MATHEMATICS FUNCTIONS END HERE */
/*SWAP FUNCTION START HERE
SWAP
SWAP
SWAP
SWAP
*/
static void swap(int i, int j, long[] arr) {
long temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
static void swap(int i, int j, int[] arr) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
static void swap(int i, int j, String [] arr) {
String temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
static void swap(int i, int j, char [] arr) {
char temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
/*SWAP
SWAP
SWAP
SWAP
SWAP FUNCTION END HERE*/
/*BINARY SEARCH METHODS START HERE
* BINARY SEARCH
* BINARY SEARCH
* BINARY SEARCH
* BINARY SEARCH
*/
static boolean BinaryCheck(long test, long [] arr, long health) {
for(int i = 0; i <= arr.length - 1; i++) {
if(i == arr.length - 1) health -= test;
else if(arr[i + 1] - arr[i] > test) {
health = health - test;
}else {
health = health - (arr[i + 1] - arr[i]);
}
if(health <= 0) return true;
}
return false;
}
static long binarySearchModified(long start1, long n, ArrayList<Integer> arr, int val) {
long start = start1, end = n, ans = -1;
while(start <= end) {
long mid = (start + end) / 2;
if(arr.get((int)mid) >= val) {
if(arr.get((int)mid) == val && mid + 1 < arr.size() && arr.get((int)mid + 1) == val) {
start = mid + 1;
}else if(arr.get((int)mid) == val) {
return mid;
}else end = mid - 1;
}else {
start = mid + 1;
}
}
//System.out.println();
return start;
}
static int upper(int start, int end, ArrayList<Integer> pairs, long val) {
while(start < end) {
int mid = (start + end) / 2;
if(pairs.get(mid) <= val) start = mid + 1;
else end = mid;
}
return start;
}
static int lower(int start, int end, ArrayList<Long> arr, long val) {
while(start < end) {
int mid = (start + end) / 2;
if(arr.get(mid) >= val) end = mid;
else start = mid + 1;
}
return start;
}
/*BINARY SEARCH
* BINARY SEARCH
* BINARY SEARCH
* BINARY SEARCH
* BINARY SEARCH
BINARY SEARCH METHODS END HERE*/
/*RECURSIVE FUNCTION START HERE
* RECURSIVE
* RECURSIVE
* RECURSIVE
* RECURSIVE
*/
static int recurse(int x, int y, int n, int steps1, Integer [][] dp) {
if(x > n || y > n) return 0;
if(dp[x][y] != null) {
return dp[x][y];
}
else if(x == n || y == n) {
return steps1;
}
return dp[x][y] = Math.max(recurse(x + y, y, n, steps1 + 1, dp), recurse(x, x + y, n, steps1 + 1, dp));
}
/*RECURSIVE
* RECURSIVE
* RECURSIVE
* RECURSIVE
* RECURSIVE
RECURSIVE FUNCTION END HERE*/
/*GRAPH FUNCTIONS START HERE
* GRAPH
* GRAPH
* GRAPH
* GRAPH
* */
static class edge{
int from, to;
long weight;
public edge(int x, int y, long weight2) {
this.from = x;
this.to = y;
this.weight = weight2;
}
}
static class sort implements Comparator<TreeNode>{
@Override
public int compare(TreeNode a, TreeNode b) {
// TODO Auto-generated method stub
return 0;
}
}
static void addEdge(ArrayList<ArrayList<edge>> graph, int from, int to, long weight) {
edge temp = new edge(from, to, weight);
edge temp1 = new edge(to, from, weight);
graph.get(from).add(temp);
//graph.get(to).add(temp1);
}
static int ans = 0;
static void topoSort(ArrayList<ArrayList<Integer>> graph, int vertex, boolean [] visited, ArrayList<Integer> toReturn) {
if(visited[vertex]) return;
visited[vertex] = true;
for(int i = 0; i < graph.get(vertex).size(); i++) {
if(!visited[graph.get(vertex).get(i)]) topoSort(graph, graph.get(vertex).get(i), visited, toReturn);
}
toReturn.add(vertex);
}
static boolean isCyclicDirected(ArrayList<ArrayList<Integer>> graph, int vertex, boolean [] visited, boolean [] reStack) {
if(reStack[vertex]) return true;
if(visited[vertex]) return false;
reStack[vertex] = true;
visited[vertex] = true;
for(int i = 0; i < graph.get(vertex).size(); i++) {
if(isCyclicDirected(graph, graph.get(vertex).get(i), visited, reStack)) return true;
}
reStack[vertex] = false;
return false;
}
static int e = 0;
static long mst(PriorityQueue<edge> pq, int nodes) {
long weight = 0;
int [] size = new int[nodes + 1];
Arrays.fill(size, 1);
while(!pq.isEmpty()) {
edge temp = pq.poll();
int x = parent(parent, temp.to);
int y = parent(parent, temp.from);
if(x != y) {
//System.out.println(temp.weight);
union(x, y, rank, parent, size);
weight += temp.weight;
e++;
}
}
return weight;
}
static void floyd(long [][] dist) { // to find min distance between two nodes
for(int k = 0; k < dist.length; k++) {
for(int i = 0; i < dist.length; i++) {
for(int j = 0; j < dist.length; j++) {
if(dist[i][j] > dist[i][k] + dist[k][j]) {
dist[i][j] = dist[i][k] + dist[k][j];
}
}
}
}
}
static void dijkstra(ArrayList<ArrayList<edge>> graph, long [] dist, int src) {
for(int i = 0; i < dist.length; i++) dist[i] = Long.MAX_VALUE / 2;
dist[src] = 0;
boolean visited[] = new boolean[dist.length];
PriorityQueue<pair> pq = new PriorityQueue<>();
pq.add(new pair(src, 0));
while(!pq.isEmpty()) {
pair temp = pq.poll();
int index = (int)temp.a;
for(int i = 0; i < graph.get(index).size(); i++) {
if(dist[graph.get(index).get(i).to] > dist[index] + graph.get(index).get(i).weight) {
dist[graph.get(index).get(i).to] = dist[index] + graph.get(index).get(i).weight;
pq.add(new pair(graph.get(index).get(i).to, graph.get(index).get(i).weight));
}
}
}
}
static int parent1 = -1;
static boolean ford(ArrayList<ArrayList<edge>> graph1, ArrayList<edge> graph, long [] dist, int src, int [] parent) {
for(int i = 0; i < dist.length; i++) dist[i] = Long.MIN_VALUE / 2;
dist[src] = 0;
boolean hasNeg = false;
for(int i = 0; i < dist.length - 1; i++) {
for(int j = 0; j < graph.size(); j++) {
int from = graph.get(j).from;
int to = graph.get(j).to;
long weight = graph.get(j).weight;
if(dist[to] < dist[from] + weight) {
dist[to] = dist[from] + weight;
parent[to] = from;
}
}
}
for(int i = 0; i < graph.size(); i++) {
int from = graph.get(i).from;
int to = graph.get(i).to;
long weight = graph.get(i).weight;
if(dist[to] < dist[from] + weight) {
parent1 = from;
hasNeg = true;
/*
* dfs(graph1, parent1, new boolean[dist.length], dist.length - 1);
* //System.out.println(ans); dfs(graph1, 0, new boolean[dist.length], parent1);
*/
//System.out.println(ans);
if(ans == 2) break;
else ans = 0;
}
}
return hasNeg;
}
/*GRAPH FUNCTIONS END HERE
* GRAPH
* GRAPH
* GRAPH
* GRAPH
*/
/*disjoint Set START HERE
* disjoint Set
* disjoint Set
* disjoint Set
* disjoint Set
*/
static int [] rank;
static int [] parent;
static int parent(int [] parent, int x) {
if(parent[x] == x) return x;
else return parent[x] = parent(parent, parent[x]);
}
static boolean union(int x, int y, int [] rank, int [] parent, int [] setSize) {
if(parent(parent, x) == parent(parent, y)) {
return true;
}
if (rank[x] > rank[y]) {
parent[y] = x;
setSize[x] += setSize[y];
} else {
parent[x] = y;
setSize[y] += setSize[x];
if (rank[x] == rank[y]) rank[y]++;
}
return false;
}
/*disjoint Set END HERE
* disjoint Set
* disjoint Set
* disjoint Set
* disjoint Set
*/
/*INPUT START HERE
* INPUT
* INPUT
* INPUT
* INPUT
* INPUT
*/
static int nextInt() throws NumberFormatException, IOException {
return Integer.parseInt(sc.readLine());
}
static long nextLong() throws NumberFormatException, IOException {
return Long.parseLong(sc.readLine());
}
static long [] inputLongArr() throws NumberFormatException, IOException{
String [] s = sc.readLine().split(" ");
long [] toReturn = new long[s.length];
for(int i = 0; i < s.length; i++) {
toReturn[i] = Long.parseLong(s[i]);
}
return toReturn;
}
static int max = 0;
static int [] inputIntArr() throws NumberFormatException, IOException{
String [] s = sc.readLine().split(" ");
//System.out.println(s.length);
int [] toReturn = new int[s.length];
for(int i = 0; i < s.length; i++) {
toReturn[i] = Integer.parseInt(s[i]);
}
return toReturn;
}
/*INPUT
* INPUT
* INPUT
* INPUT
* INPUT
* INPUT END HERE
*/
static long [] preCompute(int level) {
long [] toReturn = new long[level];
toReturn[0] = 1;
toReturn[1] = 16;
for(int i = 2; i < level; i++) {
toReturn[i] = ((toReturn[i - 1] % mod) * (toReturn[i - 1] % mod)) % mod;
}
return toReturn;
}
static class pair{
long a;
long b;
long d;
public pair(long in, long y) {
this.a = in;
this.b = y;
this.d = 0;
}
}
static int [] nextGreaterBack(char [] s) {
Stack<Integer> stack = new Stack<>();
int [] toReturn = new int[s.length];
for(int i = 0; i < s.length; i++) {
if(!stack.isEmpty() && s[stack.peek()] >= s[i]) {
stack.pop();
}
if(stack.isEmpty()) {
stack.push(i);
toReturn[i] = -1;
}else {
toReturn[i] = stack.peek();
stack.push(i);
}
}
return toReturn;
}
static int [] nextGreaterFront(char [] s) {
Stack<Integer> stack = new Stack<>();
int [] toReturn = new int[s.length];
for(int i = s.length - 1; i >= 0; i--) {
if(!stack.isEmpty() && s[stack.peek()] >= s[i]) {
stack.pop();
}
if(stack.isEmpty()) {
stack.push(i);
toReturn[i] = -1;
}else {
toReturn[i] = stack.peek();
stack.push(i);
}
}
return toReturn;
}
static int [] lps(String s) {
int [] lps = new int[s.length()];
lps[0] = 0;
int j = 0;
for(int i = 1; i < lps.length; i++) {
j = lps[i - 1];
while(j > 0 && s.charAt(i) != s.charAt(j)) j = lps[j - 1];
if(s.charAt(i) == s.charAt(j)) {
lps[i] = j + 1;
}
}
return lps;
}
static int [][] vectors = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};
static String dir = "DRUL";
static boolean check(int i, int j, boolean [][] visited) {
if(i >= visited.length || j >= visited[0].length) return false;
if(i < 0 || j < 0) return false;
return true;
}
static void selectionSort(long arr[], long [] arr1, ArrayList<ArrayList<Integer>> ans)
{
int n = arr.length;
for (int i = 0; i < n-1; i++)
{
int min_idx = i;
for (int j = i+1; j < n; j++)
if (arr[j] < arr[min_idx])
min_idx = j;
else if(arr[j] == arr[min_idx]) {
if(arr1[j] < arr1[min_idx]) min_idx = j;
}
if(i == min_idx) {
continue;
}
ArrayList<Integer> p = new ArrayList<Integer>();
p.add(min_idx + 1);
p.add(i + 1);
ans.add(new ArrayList<Integer>(p));
swap(i, min_idx, arr);
swap(i, min_idx, arr1);
}
}
static int saved = Integer.MAX_VALUE;
static String ans1 = "";
public static boolean isValid(int x, int y, String [] mat) {
if(x >= mat.length || x < 0) return false;
if(y >= mat[0].length() || y < 0) return false;
return true;
}
public static void recurse3(ArrayList<Character> arr, int index, String s, int max, ArrayList<String> toReturn) {
if(s.length() == max) {
toReturn.add(s);
return;
}
if(index == arr.size()) return;
recurse3(arr, index + 1, s + arr.get(index), max, toReturn);
recurse3(arr, index + 1, s, max, toReturn);
}
/*
if(arr[i] > q) return Math.max(f(i + 1, q - 1) + 1, f(i + 1, q);
else return f(i + 1, q) + 1
*/
static void dfsDP(ArrayList<ArrayList<Integer>> graph, int src, int [] dp1, int [] dp2, int parent) {
int sum1 = 0; int sum2 = 0;
for(int x : graph.get(src)) {
if(x == parent) continue;
dfsDP(graph, x, dp1, dp2, src);
sum1 += Math.min(dp1[x], dp2[x]);
sum2 += dp1[x];
}
dp1[src] = 1 + sum1;
dp2[src] = sum2;
System.out.println(src + " " + dp1[src] + " " + dp2[src]);
}
static int balanced = 0;
static void dfs(ArrayList<ArrayList<ArrayList<Long>>> graph, long src, int [] dist, long sum1, long sum2, long parent, ArrayList<Long> arr, int index) {
index = 0;//binarySearch(index, arr.size() - 1, arr, sum1);
if(index < arr.size() && arr.get(index) <= sum1) {
dist[(int)src] = index + 1;
}
else dist[(int)src] = index;
for(ArrayList<Long> x : graph.get((int)src)) {
if(x.get(0) == parent) continue;
if(arr.size() != 0) arr.add(arr.get(arr.size() - 1) + x.get(2));
else arr.add(x.get(2));
dfs(graph, x.get(0), dist, sum1 + x.get(1), sum2, src, arr, index);
arr.remove(arr.size() - 1);
}
}
static int compare(String s1, String s2) {
Queue<Character> q1 = new LinkedList<>();
Queue<Character> q2 = new LinkedList<Character>();
for(int i = 0; i < s1.length(); i++) {
q1.add(s1.charAt(i));
q2.add(s2.charAt(i));
}
int k = 0;
while(k < s1.length()) {
if(q1.equals(q2)) {
break;
}
q2.add(q2.poll());
k++;
}
return k;
}
static long pro = 0;
public static int len(ArrayList<ArrayList<Integer>> graph, int src, boolean [] visited
) {
visited[src] = true;
int max = 0;
for(int x : graph.get(src)) {
if(!visited[x]) {
visited[x] = true;
int len = len(graph, x, visited) + 1;
//System.out.println(len);
pro = Math.max(max * (len - 1), pro);
max = Math.max(len, max);
}
}
return max;
}
public static void recurse(int l, int [] ans) {
if(l < 0) return;
int r = (int)Math.sqrt(l * 2);
int s = r * r;
r = s - l;
recurse(r - 1, ans);
while(r <= l) {
ans[r] = l;
ans[l] = r;
r++;
l--;
}
}
static boolean isSmaller(String str1, String str2)
{
// Calculate lengths of both string
int n1 = str1.length(), n2 = str2.length();
if (n1 < n2)
return true;
if (n2 < n1)
return false;
for (int i = 0; i < n1; i++)
if (str1.charAt(i) < str2.charAt(i))
return true;
else if (str1.charAt(i) > str2.charAt(i))
return false;
return false;
}
// Function for find difference of larger numbers
static String findDiff(String str1, String str2)
{
// Before proceeding further, make sure str1
// is not smaller
if (isSmaller(str1, str2)) {
String t = str1;
str1 = str2;
str2 = t;
}
// Take an empty string for storing result
String str = "";
// Calculate length of both string
int n1 = str1.length(), n2 = str2.length();
// Reverse both of strings
str1 = new StringBuilder(str1).reverse().toString();
str2 = new StringBuilder(str2).reverse().toString();
int carry = 0;
// Run loop till small string length
// and subtract digit of str1 to str2
for (int i = 0; i < n2; i++) {
// Do school mathematics, compute difference of
// current digits
int sub
= ((int)(str1.charAt(i) - '0')
- (int)(str2.charAt(i) - '0') - carry);
// If subtraction is less than zero
// we add then we add 10 into sub and
// take carry as 1 for calculating next step
if (sub < 0) {
sub = sub + 10;
carry = 1;
}
else
carry = 0;
str += (char)(sub + '0');
}
// subtract remaining digits of larger number
for (int i = n2; i < n1; i++) {
int sub = ((int)(str1.charAt(i) - '0') - carry);
// if the sub value is -ve, then make it
// positive
if (sub < 0) {
sub = sub + 10;
carry = 1;
}
else
carry = 0;
str += (char)(sub + '0');
}
// reverse resultant string
return new StringBuilder(str).reverse().toString();
}
public static boolean check(String s, int k, int mid) {
int [] hash = new int[256];
for(int i = 0; i < s.length(); i++) {
hash[s.charAt(i)]++;
}
int len = 0; int count = 0;
for(int i = 0; i < hash.length; i++) {
if(hash[i] % 2 != 0 && len % 2 != 0) {
if(hash[i] > len) len = hash[i];
if(len >= mid) {
count++;
len = len - mid;
}
continue;
}
if(hash[i] % 2 == 0 && len % 2 != 0) {
if(len + hash[i] >= mid) {
count++;
len = len + hash[i] - mid;
}
continue;
}
if(len % 2 == 0 && hash[i] % 2 != 0) {
if(len + hash[i] >= mid) {
len = len + hash[i] - mid;
count++;
continue;
}
if(len == 0) {
len += hash[i];
if(len >= mid) {
count++;
len = len - mid;
}
continue;
}
}
if(hash[i] % 2 == 0 && len % 2 == 0) {
len += hash[i];
if(len >= mid) {
count++;
len = len - mid;
}
continue;
}
if(hash[i] >= mid) {
count++;
}
}
if(count >= k) return true;
return false;
}
/*
4, 8, 15, 16, 23, 42
*/
static interactor test;
static int query(int x, int y) throws NumberFormatException, IOException {
System.out.println("? " + x + " " + y);
int to = nextInt();
return to;
}
static void solve() throws IOException {
int min = 1; int max1 = 100000;
int n = nextInt();
//test = new interactor(n);
int start = 1; int end = n;
int sec = 0;
for(int i = 0; i < 20; i++) {
if(start >= end) break;
sec = query(start, end);
int mid = (start + end) / 2;
if(sec >= mid) {
int q = query(mid, end);
if(q == sec) start = mid;
else end = mid - 1;
}else {
int q = query(start, mid);
if(q == sec) {
end = mid;
}else start = mid + 1;
}
}
/*
int max = 0; int index = 0;
for(int i = 0; i < test.arr.length; i++) {
//System.out.print(test.arr[i] + " ");
if(max < test.arr[i]) {
max = test.arr[i];
index = i + 1;
}
}
*/
if(sec != start) {
output.write("! " + start + "\n");
}else {
output.write("! " + end + "\n");
}
}
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
//int t = Integer.parseInt(sc.readLine()); for(int i = 0; i < t; i++)
solve();
output.flush();
}
}
/* a + b = x, b + c = y, a + b + c = z;
*/
class interactor{
int [] arr;
int min = 1; int max = 100000;
public interactor(int n) {
arr = new int [n];
HashSet<Integer> set = new HashSet<Integer>();
for(int i = 0; i < arr.length; i++) {
int val = (int)(Math.random()*(max-min+1)+min);
while(set.contains(val)) val = (int)(Math.random()*(max-min+1)+min);
set.add(val);
arr[i] = val;
}
}
public int interact(int start, int end) {
if(start == end) return arr[start - 1];
PriorityQueue<ArrayList<Integer>> pq = new PriorityQueue<>((a, b) -> {
return b.get(0) - a.get(0);
});
for(int i = start - 1; i < end; i++) {
ArrayList<Integer> arr = new ArrayList<Integer>();
arr.add(this.arr[i]);
arr.add(i + 1);
pq.add(arr);
}
if(pq.size() == 1) return pq.poll().get(1);
pq.poll();
return pq.poll().get(1);
}
}
class TreeNode {
long a; long b;
public TreeNode(long x, long y) {
this.a = x;
this.b = y;
}
public String toString() {
return a + " " + b;
}
}
/*
1
10
6 10 7 9 11 99 45 20 88 31
*/
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
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
|
6261f11d5937c51a9020ac5608b1a11e
|
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 Interactive_2 {
public static void main(String[] args) {
FastReader sc = new FastReader();
StringBuilder sb = new StringBuilder();
int t = 1;
out:while(t-- >0) {
int n = sc.nextInt();
int l = 1;
int r = n;
System.out.println("? "+l+" "+r);
System.out.flush();
int second_max = sc.nextInt();
int x,y;
while(l<r) {
int mid = l + (r-l)/2;
if(r-l==1) {
if (second_max==l) {
l=r;
}
else r = l;
continue;
}
System.out.println("? "+l+" "+mid);
System.out.flush();
x = sc.nextInt();
if(mid+1==r) {
y=-1;
}
else {
System.out.println("? "+(mid+1)+" "+r);
System.out.flush();
y = sc.nextInt();
}
if(x==second_max) {
r = mid;
}
else if(y==second_max) {
l = mid+1;
}
else {
if(second_max>mid) {
r = mid;
second_max = x;
} else {
l = mid+1;
second_max = y;
}
}
}
System.out.println("! "+l);
}
// System.out.println(sb);
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
int[] readArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
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
|
2704a32f83f0d0d3ac2dce47d59198b5
|
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.*;
public class Main {
public static int[] a = new int[]{0, 4, 3, 2, 1, 5};
public static void main(String[] args) throws Exception{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int testCase = Integer.parseInt(in.readLine().trim());
int l = 1;
int r = testCase;
int result = 0;
while (l < r) {
int smax = seclarge(in, l, r);
if (l + 1 == r) {
result = smax == l ? r : l;
System.out.println("! " + result);
System.out.flush();
return;
}
int m = l + (r - l)/2;
if (smax <= m) {
int smax2 = seclarge(in, l, m);
if (smax2 == smax) {
r = m;
} else {
l = m + 1;
}
} else {
int smax2 = seclarge(in, m, r);
if (smax2 == smax) {
l = m;
} else {
r = m - 1;
}
}
}
System.out.println("! " + l);
System.out.flush();
}
public static int seclarge(BufferedReader in, int l, int r) throws Exception{
System.out.println("? " + l + " " + r);
System.out.flush();
int sec = Integer.parseInt(in.readLine().trim());
return sec;
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
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
|
cd18a627b2b6054b671690f1f82fbd0b
|
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.util.*;
public class Main {
static class DisjointUnionSets {
int[] rank, parent;
int n;
// Constructor
public DisjointUnionSets(int n)
{
rank = new int[n];
parent = new int[n];
this.n = n;
makeSet();
}
// Creates n sets with single item in each
void makeSet()
{
for (int i = 0; i < n; i++) {
// Initially, all elements are in
// their own set.
parent[i] = i;
}
}
// Returns representative of x's set
int find(int x)
{
// Finds the representative of the set
// that x is an element of
if (parent[x] != x) {
// if x is not the parent of itself
// Then x is not the representative of
// his set,
parent[x] = find(parent[x]);
// so we recursively call Find on its parent
// and move i's node directly under the
// representative of this set
}
return parent[x];
}
// Unites the set that includes x and the set
// that includes x
void union(int x, int y)
{
// Find representatives of two sets
int xRoot = find(x), yRoot = find(y);
// Elements are in the same set, no need
// to unite anything.
if (xRoot == yRoot)
return;
// If x's rank is less than y's rank
if (rank[xRoot] < rank[yRoot])
// Then move x under y so that depth
// of tree remains less
parent[xRoot] = yRoot;
// Else if y's rank is less than x's rank
else if (rank[yRoot] < rank[xRoot])
// Then move y under x so that depth of
// tree remains less
parent[yRoot] = xRoot;
else // if ranks are the same
{
// Then move y under x (doesn't matter
// which one goes where)
parent[yRoot] = xRoot;
// And increment the result tree's
// rank by 1
rank[xRoot] = rank[xRoot] + 1;
}
}
}
static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine(){
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
static class HashMultiSet<T> implements Iterable<T>
{ private final HashMap<T,Integer> map;
private int size;
public HashMultiSet(){map=new HashMap<>(); size=0;}
public void clear(){map.clear(); size=0;}
public int size(){return size;}
public int setSize(){return map.size();}
public boolean contains(T a){return map.containsKey(a);}
public boolean isEmpty(){return size==0;}
public Integer get(T a){return map.getOrDefault(a,0);}
public void add(T a, int count)
{
int cur=get(a);map.put(a,cur+count); size+=count;
if(cur+count==0) map.remove(a);
}
public void addOne(T a){add(a,1);}
public void remove(T a, int count){add(a,Math.max(-get(a),-count));}
public void removeOne(T a){remove(a,1);}
public void removeAll(T a){remove(a,Integer.MAX_VALUE-10);}
public Iterator<T> iterator()
{
return new Iterator<>()
{
private final Iterator<T> iter = map.keySet().iterator();
private int count = 0; private T curElement;
public boolean hasNext(){return iter.hasNext()||count>0;}
public T next()
{
if(count==0)
{
curElement=iter.next();
count=get(curElement);
}
count--; return curElement;
}
};
}
}
private static long abs(long x){ if(x < 0) x*=-1l;return x; }
private static int abs(int x){ if(x < 0) x*=-1;return x; }
// public static int get(HashMap<Integer, Deque<Integer> > a, int key ){
// return a.get(key).getLast();
// }
// public static void removeLast (HashMap<Integer,Deque<Integer> > a, int key){
// if(a.containsKey(key)){
// a.get(key).removeLast();
// if(a.get(key).size() == 0) a.remove(key);
// }
// }
// public static void add(HashMap<Integer,Deque<Integer>> a, int key, int val){
// if(a.containsKey(key)){
// a.get(key).addLast(val);
// }else{
// Deque<Integer> b = new LinkedList<>();
// b.addLast(val);
// a.put(key,b);
// }
// }
private static int askRange(int l ,int r){
if(l == r) return l;
MyScanner sc = new MyScanner();
System.out.println("? "+l+" "+r);
System.out.flush();
return sc.nextInt();
}
private static int bin(int l ,int r,int oo){
if(l == r){
return l;
}
if(r-l == 1){
// int v = askRange(l,r);
return (oo==l)? r:l;
}
if(r-l == 2){
int k = askRange(l,l+1);
int p = askRange(l+1,r);
if(k == oo) return bin(l,l+1,k);
if(p == oo) return bin(l+1,r,p);
if(oo == l) return r;
else return l;
}
int mid = (l+r)/2;
int mide = oo;
int right = askRange(mid+1,r);
int left = askRange(l,mid);
if(mide == left ) return bin(l,mid,left);
else if(mide == right){
return bin(mid+1,r,right);
}else if(mide >= mid+1 && mide <=r){
return bin(l,mid,left);
}else {
return bin(mid+1,r,right);
}
}
public static void main(String[] args) {
MyScanner sc = new MyScanner();
int n = sc.nextInt();
int v = askRange(1,n);
System.out.println("! "+bin(1,n,v));
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
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
|
36574ef3b5614f4ebf609382b24aa7ca
|
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.Arrays;
public class codeforces {
static int ask(int l,int r)throws IOException {
if(l==r) {
return -1;
}
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int out1;
System.out.println("? "+l+" "+r);
System.out.flush();
out1=Integer.parseInt(br.readLine());
return out1;
}
public static void main(String[] args)throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n=Integer.parseInt(br.readLine());
int l=1;
int r=n;
int pos=ask(1,n);
if(ask(1,pos)==pos) {
l=1;
r=pos;
while(l<r) {
int mid=(l+r+1)/2;
if(ask(mid,n)==pos) {
l=mid;
}
else {
r=mid-1;
}
}
System.out.println("! "+l);
}
else {
l=pos;
r=n;
while(l<r) {
int mid=(l+r)/2;
if(ask(pos,mid)==pos) {
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 11
|
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
|
6322dbe0be783fe777930e789b34a294
|
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.lang.*;
import java.io.*;
import java.math.BigInteger;
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 (Exception e){
e.printStackTrace();
}
return str;
}
int[] ra(int n){
int[] a = new int[n];
for(int i = 0; i < n; i++){
a[i] = nextInt();
}
return a;
}
long[] rla(int n){
long[] a = new long[n];
for(int i = 0; i < n; i++){
a[i] = nextLong();
}
return a;
}
double[] rda(int n){
double[] a = new double[n];
for(int i = 0; i < n; i++){
a[i] = nextDouble();
}
return a;
}
}
static int modPower(int x, int y, int mod){
int res = 1;
x %= mod;
if(x==0) return 0;
while(y>0){
if(y%2==1){
res = (res*x)%mod;
}
y = y>>1;
x = (x*x)%mod;
}
return res;
}
static class pair<T1, T2>{
T1 first;
T2 second;
pair(T1 first, T2 second){
this.first = first;
this.second = second;
}
}
static int gcd(int a, int b){
if(b == 0) return a;
return gcd(b, a%b);
}
static long sum(long n){
long s=0;
while(n>0){
s+=n%10;
n/=10;
}
return s;
}
static void query(int l,int r){
System.out.println("? "+l+" "+r);
}
public static void main (String[] args) throws java.lang.Exception
{
FastReader in = new FastReader();
int n = in.nextInt();
int l=1,r=n;
while((r-l)>1){
int mid=(l+r)/2;
query(l,r);
int x=in.nextInt();
if(x<=mid){
query(l,mid);
int y=in.nextInt();
if(x==y){
r=mid;
} else {
l=mid;
}
} else {
query(mid,r);
int y=in.nextInt();
if(x==y){
l=mid;
} else {
r=mid;
}
}
}
query(l,r);
int x=in.nextInt();
if(x==l){
l=r;
}
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 11
|
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
|
b5382150606ff3bffbcd4ab3e2bc8aee
|
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 credit;
import java.io.*;
import java.util.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Main{
static boolean v[];
static int ans[];
int size[];
static int count=0;
static int dsu=0;
static int c=0;
static int e9=1000000007;
int min=Integer.MAX_VALUE;
int max=Integer.MIN_VALUE;
long max1=Long.MIN_VALUE;
long min1=Long.MAX_VALUE;
boolean aBoolean=true;
boolean y=false;
long m=0;
static boolean t1=false;
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
int parent[];
int rank[];
int n=0;
ArrayList<ArrayList<Integer>> arrayLists;
boolean v1[];
static boolean t2=false;
boolean r=false;
int fib[];
int fib1[];
int ind[];
int min3=Integer.MAX_VALUE;
public static void main(String[] args) throws IOException {
Main g = new Main();
g.go();
}
public void go() throws IOException {
FastReader scanner = new FastReader();
// Scanner scanner = new Scanner(System.in);
// BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(System.in));
// String s;
PrintWriter printWriter = new PrintWriter(System.out);
int t =1;
for (int i = 0; i < t; i++) {
int n=scanner.nextInt();
int s=1;
int e=n;
int u=0;
int ans=0;
u = sm(s, e);
if(u==sm(s,u)){
s=1;
e=u-1;
while(s<=e){
int m=(s+e)/2;
if(sm(m,u)==u){
ans=m;
s=m+1;
}else{
e=m-1;
}
}
}else{
s=u+1;
e=n;
while(s<=e){
int m=(s+e)/2;
if(sm(u,m)==u){
ans=m;
e=m-1;
}else{
s=m+1;
}
}
}
printWriter.println("! "+(ans));
}
printWriter.flush();
}
public int sm(int l,int r){
FastReader scanner =new FastReader();
if(l==r){
return -1;
}
System.out.println("? "+(l)+" "+(r));
int h=scanner.nextInt();
System.out.flush();
return h;
}
static final int mod=1_000_000_007;
public long mul(long a, long b) {
return a*b;
}
public long fact(int x) {
long ans=1;
for (int i=2; i<=x; i++) ans=mul(ans, i);
return ans;
}
public long fastPow(long base, long exp) {
if (exp==0) return 1;
long half=fastPow(base, exp/2);
if (exp%2==0) return mul(half, half);
return mul(half, mul(half, base));
}
public long modInv(long x) {
return fastPow(x, mod-2);
}
public long nCk(int n, int k) {
return mul(fact(n), mul(modInv(fact(k)), modInv(fact(n-k))));
}
// public void sieve(int n){
// fib=new int[n+1];
// fib[1]=-1;
// fib[0]=-1;
// for (int i =2; i*i<=n; i++) {
// if(fib[i]==0)
// for (int j =i*i; j <=n; j+=i){
// fib[j]=-1;
//// System.out.println("l");
// }
// }
// }
public void parent(int n){
for (int i = 0; i < n; i++) {
parent[i]=i;
rank[i]=1;
size[i]=1;
}
}
public void union(int i,int j){
int root1=find(i);
int root2=find(j);
// if(root1 != root2) {
// parent[root2] = root1;
//// sz[a] += sz[b];
// }
if(root1==root2){
return;
}
if(rank[root1]>rank[root2]){
parent[root2]=root1;
size[root1]+=size[root2];
}
else if(rank[root1]<rank[root2]){
parent[root1]=root2;
size[root2]+=size[root1];
}
else{
parent[root2]=root1;
rank[root1]+=1;
size[root1]+=size[root2];
}
}
public int find(int p){
if(parent[p]!=p){
parent[p]=find(parent[p]);
}
return parent[p];
// if(parent[p]==-1){
// return -1;
// }
// else if(parent[p]==p){
// return p;
// }
// else {
// parent[p]=find(parent[p]);
// return parent[p];
// }
}
public double dist(double x1,double y1,double x2,double y2){
double e=(x2-x1)*(x2-x1)+(y2-y1)*(y2-y1);
double e1=Math.sqrt(e);
return e1;
}
public void make(int p){
parent[p]=p;
rank[p]=1;
}
Random rand = new Random();
public void sort(int[] a, int n) {
for (int i = 0; i < n; i++) {
int j = rand.nextInt(i + 1);
int tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
Arrays.sort(a, 0, n);
}
public long gcd(long a,long b){
if(b==0){
return a;
}
return gcd(b,a%b);
}
public void dfs(ArrayList<Integer> arrayLists1){
for (int i = 0; i < arrayLists1.size(); i++) {
if(v1[arrayLists1.get(i)]==false){
System.out.println(arrayLists1.get(i));
v1[arrayLists1.get(i)]=true;
count++;
dfs(arrayLists.get(arrayLists1.get(i)));
}
}
}
private void dfs2(ArrayList<Integer>[]arrayList,int j,int count){
ans[j]=count;
for(int i:arrayList[j]){
if(ans[i]==-1){
dfs2(arrayList,i,count);
}
}
}
private void dfs3(ArrayList<Integer>[] arrayList, int j) {
v[j]=true;
count++;
for(int i:arrayList[j]){
if(v[i]==false) {
dfs3(arrayList, i);
}
}
}
public double fact(double h){
double sum=1;
while(h>=1){
sum=(sum%e9)*(h%e9);
h--;
}
return sum%e9;
}
public long primef(double r){
long c=0;
long ans=1;
while(r%2==0){
c++;
r=r/2;
}
if(c>0){
ans*=2;
}
c=0;
// System.out.println(ans+" "+r);
for (int i = 3; i <=Math.sqrt(r) ;i+=2) {
while(r%i==0){
// System.out.println(i);
c++;
r=r/i;
}
if(c>0){
ans*=i;
}
c=0;
}
if(r>2){
ans*=r;
}
return ans;
}
public long divisor(double r){
long c=0;
for (int i = 1; i <=Math.sqrt(r); i++) {
if(r%i==0){
if(r/i==i){
c++;
}
else{
c+=2;
}
}
}
return c;
}
}
class Pair{
int x;
int y;
double z;
public Pair(int x,int y){
this.x=x;
this.y=y;
}
@Override
public int hashCode() {
int hash =37;
return this.x * hash + this.y;
}
@Override
public boolean equals(Object o1){
if(o1==null||o1.getClass()!=this.getClass()){
return false;
}
Pair o=(Pair)o1;
if(o.x==this.x&&o.y==this.y){
return true;
}
return false;
}
}
class Sorting implements Comparator<Pair> {
public int compare(Pair p1,Pair p2){
// if(p1.x==p2.x){
// return -1*Double.compare(p1.y,p2.y);
// }
// else {
return Double.compare(p1.x, p2.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 11
|
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
|
a74e6155d8b2672e50346dedd632db04
|
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.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.StringTokenizer;
public class problemC {
static class Solution {
HashMap<Point, Integer> map = new HashMap<>();
int query(int l, int r) {
Point p = new Point(l, r);
if (map.containsKey(p)) return map.get(p);
System.out.println("? " + l + " " + r);
System.out.flush();
int ans = fs.nextInt();
map.put(p, ans);
return ans;
}
void solve() {
int n = fs.nextInt();
int second = query(1, n);
int left = second == 1 ? -1 : query(1, second);
if (left == second) { // search left.
int ans = -1;
for (int low=1, high=second-1; low <= high; ) {
int mid = (low+high)/2;
int got = query(mid, second);
if (got == second) { // contains max.
ans = Math.max(ans, mid);
low = mid + 1;
} else { // does not contain max.
high = mid - 1;
}
}
print(ans);
return;
} else { // search right.
int ans = n+1;
for (int low=second+1, high=n; low <= high ; ) {
int mid = (low+high)/2;
int got = query(second, mid);
if (got == second) { // contains max.
high = mid - 1;
ans = Math.min(ans, mid);
} else { // does not contain max.
low = mid + 1;
}
}
print(ans);
return;
}
}
void print(int ans) {
System.out.println("! " + ans);
System.out.flush();
}
}
static class Point implements Comparable<Point> {
int x, y;
Point(int x, int y) {this.x = x; this.y = y;}
@Override
public int compareTo(Point other) {
if (this.x == other.x) return Integer.compare(this.y, other.y);
return Integer.compare(this.x, other.x);
}
@Override
public boolean equals(Object o) {
if (!(o instanceof Point)) return false;
Point other = (Point)o;
return this.x == other.x && this.y == other.y;
}
@Override
public int hashCode() {
return Arrays.hashCode(new int[]{this.x , this.y});
}
}
public static void main(String[] args) throws Exception {
Solution solution = new Solution();
solution.solve();
}
static void debug(Object... O) {
System.err.println("DEBUG: " + Arrays.deepToString(O));
}
private static FastScanner fs = new FastScanner();
static class FastScanner { // Thanks SecondThread.
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;
}
ArrayList<Integer> readArrayList(int n) {
ArrayList<Integer> a = new ArrayList<>(n);
for (int i = 0 ; i < n; i ++ ) a.add(fs.nextInt());
return a;
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextString() {
return next();
}
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
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
|
970748862630f55b3c83e31d56da1479
|
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.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.StringTokenizer;
public class problemC {
static class Solution {
HashMap<Integer, Integer>[] maps;
int query (int l, int r) {
if (maps[l].containsKey(r)) return maps[l].get(r);
System.out.println("? " + l + " " +r);
System.out.flush();
int ans = fs.nextInt();
maps[l].put(r, ans);
return ans;
}
int s, e;
void solve(int n) {
maps = new HashMap[n+1];
for (int i = 1; i <= n ; i ++ ) maps[i] = new HashMap<>();
for (s = 1, e = n ; e-s > 1 ; ) {
int second = query(s,e); // for sure s != e.
if (second == s) {
halfRight(second, e);
continue;
}
int left = query(s, second);
if (left == second) { // firstHalf.
halfLeft(s, second);
} else { // secondHalf.
halfRight(second, e);
}
}
int ans = 0;
if (e == s) ans = s;
else {
int mid = query(s, e);
ans = mid == s ? e : s;
}
System.out.println("! " +ans);
System.out.flush();
}
void halfLeft(int l, int h) {
if (h-l <= 1) {
s = l;
e = h;
return;
}
int mid = (l+h)/2;
int got = query(mid, h);
if (got == h) {
s = mid;
e = h-1;
return;
} else {
s = l;
e = mid-1;
return;
}
}
void halfRight(int l, int h) {
if (h-l <= 1) {
s = l; e = h;
return;
}
int mid = (l+h)/2;
int got = query(l ,mid);
debug(got, l, mid);
if (got == l) {
e = mid;
s = l+1;
return;
} else {
s = mid+1;
e = h;
}
}
}
public static void main(String[] args) throws Exception {
int T = 1;
Solution solution = new Solution();
int n = fs.nextInt();
solution.solve(n);
}
static void debug(Object... O) {
System.err.println("DEBUG: " + Arrays.deepToString(O));
}
private static FastScanner fs = new FastScanner();
static class FastScanner { // Thanks SecondThread.
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;
}
ArrayList<Integer> readArrayList(int n) {
ArrayList<Integer> a = new ArrayList<>(n);
for (int i = 0 ; i < n; i ++ ) a.add(fs.nextInt());
return a;
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextString() {
return next();
}
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
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
|
e7100cca39f876b8a3e446dc41443b4a
|
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 File {
public static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner() {
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());
}
}
public static void main(String[] args) {
FastScanner sc = new FastScanner();
PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
int n=sc.nextInt();
int l=0,r=n;
while(r-l>1)
{
int m=(l+r)/2;
int sm=ask(l,r-1);
if(sm<m)
{
if(ask(l,m-1)==sm)
{
r=m;
}
else l=m;
}
else
{
if(ask(m,r-1)==sm)
{
l=m;
}
else
{
r=m;
}
}
}
System.out.println("! "+r);
out.close();
}
static int ask(int l, int r) {
FastScanner sc = new FastScanner();
if (l >= r) return -1;
System.out.println("? "+(l+1)+" "+(r+1));
int ans=sc.nextInt();
return ans - 1;
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
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
|
1cf35e5e9960d351ea1166faef99681e
|
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.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.PriorityQueue;
import java.util.Scanner;
public class B {
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
int tt = 1;
// tt = sc.nextInt();
while (tt-- > 0) {
solve();
}
}
static int ans;
private static void solve() {
int n=sc.nextInt();
int low = 1, high = n, m;
callprint("? " + low + " " + high);
m = sc.nextInt();
while (high - low > 1) {
int mid = (low + high) / 2;
if (m <= mid) {
callprint("? " + low + " " + (mid));
int i =sc.nextInt();
// private static int recur(int a, int b) {
// if(a==0)
// return 0;
// int an1=Integer.MAX_VALUE;
// if(b!=1)
// an1=recur(a/b,b);
// b++;
// int an2= recur(a,b);
// return Math.min((an1==Integer.MAX_VALUE)?an1:(an1+1),(an2==Integer.MAX_VALUE)?an2:(an2+2));
// }
if (i == m) {
high = mid;
} else {
low = mid + 1;
if (high - low >= 1) {
callprint("? " + low + " " + high);
m = sc.nextInt();
}
}
// private static int recur(int a, int b) {
// if(a==0)
// return 0;
// int an1=Integer.MAX_VALUE;
// if(b!=1)
// an1=recur(a/b,b);
// b++;
// int an2= recur(a,b);
// return Math.min((an1==Integer.MAX_VALUE)?an1:(an1+1),(an2==Integer.MAX_VALUE)?an2:(an2+2));
// }
} else {
callprint("? " + mid + " " + (high));
int i = sc.nextInt();
if (i != m) {
high = mid - 1;
if (high - low >= 1) {
callprint("? " + low + " " + high);
m = sc.nextInt();
}
// private static int recur(int a, int b) {
// if(a==0)
// return 0;
// int an1=Integer.MAX_VALUE;
// if(b!=1)
// an1=recur(a/b,b);
// b++;
// int an2= recur(a,b);
// return Math.min((an1==Integer.MAX_VALUE)?an1:(an1+1),(an2==Integer.MAX_VALUE)?an2:(an2+2));
// }
} else
low = mid;
}
}
low = (m == low) ? high : low;
callprint("! " + low);
}
private static void callprint(String string) {
System.out.println(string);
//System.out.flush();
}
// private static int recur(int a, int b) {
// if(a==0)
// return 0;
// int an1=Integer.MAX_VALUE;
// if(b!=1)
// an1=recur(a/b,b);
// b++;
// int an2= recur(a,b);
// return Math.min((an1==Integer.MAX_VALUE)?an1:(an1+1),(an2==Integer.MAX_VALUE)?an2:(an2+2));
// }
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
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
|
319841f4e975b48d4296837aaac4be91
|
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 static java.lang.Math.*;
public class CP {
static int MAX = Integer.MAX_VALUE,MIN = Integer.MIN_VALUE,MOD = (int)1e9+7;
static long MAXL = (long)1e18,MINL = -(long)1e18;
static void solve() {
// 0 0 1
// x
// l x
// x r
int n = fs.nInt();
int l = 1, r = n;
while ( l < r ){
int ind = rangeQuery(l,r);
int mid = (l+r)/2;
if( ind <= mid ){
if( rangeQuery(l,mid) == ind )
r = mid;
else l = mid+1;
}else{
if( rangeQuery(mid+1,r) == ind )
l = mid + 1;
else r = mid;
}
}
out.println("! "+l);
}
static class Triplet<T,U,V>{
T a;
U b;
V c;
Triplet(T a,U b,V c){
this.a = a;
this.b = b;
this.c = c;
}
}
static class Pair<A, B>{
A fst;
B snd;
Pair(A fst,B snd){
this.fst = fst;
this.snd = snd;
}
}
static boolean multipleTestCase = false ;static FastScanner fs;static PrintWriter out;
public static void main(String[] args) {
try{
fs = new FastScanner();
out = new PrintWriter(System.out);
int tc = (multipleTestCase)?fs.nInt():1;
while (tc-->0)solve();
out.flush();
out.close();
}catch (Exception e){
e.printStackTrace();
}
}
static class FastScanner extends PrintWriter {
private InputStream stream;
private byte[] buf = new byte[1<<16];
private int curChar, numChars;
// standard input
public FastScanner() { this(System.in,System.out); }
public FastScanner(InputStream i, OutputStream o) {
super(o);
stream = i;
}
// file input
public FastScanner(String i, String o) throws IOException {
super(new FileWriter(o));
stream = new FileInputStream(i);
}
// throws InputMismatchException() if previously detected end of file
private int nextByte() {
if (numChars == -1) throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars == -1) return -1; // end of file
}
return buf[curChar++];
}
// to read in entire lines, replace c <= ' '
// with a function that checks whether c is a line break
public String next() {
int c; do { c = nextByte(); } while (c <= ' ');
StringBuilder res = new StringBuilder();
do { res.appendCodePoint(c); c = nextByte(); } while (c > ' ');
return res.toString();
}
public int nInt() { // nextLong() would be implemented similarly
int c; do { c = nextByte(); } while (c <= ' ');
int sgn = 1; if (c == '-') { sgn = -1; c = nextByte(); }
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res = 10*res+c-'0';
c = nextByte();
} while (c > ' ');
return res * sgn;
}
public long nLong(){return Long.parseLong(next());}
public double nextDouble() { return Double.parseDouble(next()); }
}
public static void sort(int[] arr){
ArrayList<Integer> ls = new ArrayList<Integer>();
for(int x: arr)
ls.add(x);
Collections.sort(ls);
for(int i=0; i < arr.length; i++)
arr[i] = ls.get(i);
}
public static void sort(long[] arr){
ArrayList<Long> ls = new ArrayList<>();
for(long x: arr)
ls.add(x);
Collections.sort(ls);
for(int i=0; i < arr.length; i++)
arr[i] = ls.get(i);
}
public static void sortR(int[] arr){
ArrayList<Integer> ls = new ArrayList<>();
for(int x: arr)
ls.add(x);
Collections.sort(ls,Collections.reverseOrder());
for(int i=0; i < arr.length; i++)
arr[i] = ls.get(i);
}
public static void sortR(long[] arr){
ArrayList<Long> ls = new ArrayList<>();
for(long x: arr)
ls.add(x);
Collections.sort(ls,Collections.reverseOrder());
for(int i=0; i < arr.length; i++)
arr[i] = ls.get(i);
}
public static int rangeQuery(int l,int r){
if( l == r )return -1;
out.println("? "+l+" "+r);
out.flush();
int x = fs.nInt();
return 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 11
|
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
|
5044422ad3746d63117fd029638bb4f5
|
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
|
// have faith in yourself!!!!!
/*
Naive mistakes in java :
--> Arrays.sort(primitive) is O(n^2)
--> Never use '=' to compare to Integer data types, instead use 'equals()'
--> -4 % 3 = -1, actually it should be 2, so add '+n' to modulo result
*/
import java.io.*;
import java.util.*;
public class CodeForces {
public static void main(String[] args) throws IOException {
openIO();
int testCase = 1;
// testCase = sc. nextInt();
for (int i = 1; i <= testCase; i++) solve(i);
closeIO();
}
/*-------------------------------------------EDITING CODE STARTS HERE-------------------------------------------*/
public static void solve(int tCase) throws IOException {
int n = sc.nextInt();
int l = 1;
int r = n;
while (l<r){
if(r==l+1){
int secInd = getQuery(l,r);
l = secInd==l?r:l;
break;
}
int mid = (l+r)/2;
int secInd = getQuery(l,r);
if(secInd <= mid){
int t = getQuery(l,mid);
if(t==secInd){
r = mid;
}else l = mid+1;
}else {
int t = getQuery(mid,r);
if(t == secInd){
l = mid;
}else r = mid-1;
}
}
System.out.println("! "+l);
System.out.flush();
}
private static int getQuery(int l, int r) throws IOException{
System.out.println("? "+l+" "+r);
System.out.flush();
return sc.nextInt();
}
/*-------------------------------------------EDITING CODE ENDS HERE-------------------------------------------*/
public static int mod = (int) 1e9 + 7;
// public static int mod = 998244353;
public static int inf_int = (int) 2e9;
public static long inf_long = (long) 2e18;
public static void _sort(int[] arr, boolean isAscending) {
int n = arr.length;
List<Integer> list = new ArrayList<>();
for (int ele : arr) list.add(ele);
Collections.sort(list);
if (!isAscending) Collections.reverse(list);
for (int i = 0; i < n; i++) arr[i] = list.get(i);
}
public static void _sort(long[] arr, boolean isAscending) {
int n = arr.length;
List<Long> list = new ArrayList<>();
for (long ele : arr) list.add(ele);
Collections.sort(list);
if (!isAscending) Collections.reverse(list);
for (int i = 0; i < n; i++) arr[i] = list.get(i);
}
// time : O(1), space : O(1)
public static int _digitCount(long num,int base){
// this will give the # of digits needed for a number num in format : base
return (int)(1 + Math.log(num)/Math.log(base));
}
// time : O(n), space: O(n)
public static long _fact(int n){
// simple factorial calculator
long ans = 1;
for(int i=2;i<=n;i++)
ans = ans * i % mod;
return ans;
}
// time for pre-computation of factorial and inverse-factorial table : O(nlog(mod))
public static long[] factorial , inverseFact;
public static void _ncr_precompute(int n){
factorial = new long[n+1];
inverseFact = new long[n+1];
factorial[0] = inverseFact[0] = 1;
for (int i = 1; i <=n; i++) {
factorial[i] = (factorial[i - 1] * i) % mod;
inverseFact[i] = _power(factorial[i], mod - 2);
}
}
// time of factorial calculation after pre-computation is O(1)
public static int _ncr(int n,int r){
if(r > n)return 0;
return (int)(factorial[n] * inverseFact[r] % mod * inverseFact[n - r] % mod);
}
public static int _npr(int n,int r){
if(r > n)return 0;
return (int)(factorial[n] * inverseFact[n - r] % mod);
}
// euclidean algorithm time O(max (loga ,logb))
public static long _gcd(long a, long b) {
if (a == 0)
return b;
return _gcd(b % a, a);
}
// lcm(a,b) * gcd(a,b) = a * b
public static long _lcm(long a, long b) {
return (a / _gcd(a, b)) * b;
}
// binary exponentiation time O(logn)
public static long _power(long x, long n) {
long ans = 1;
while (n > 0) {
if ((n & 1) == 1) {
ans *= x;
ans %= mod;
n--;
} else {
x *= x;
x %= mod;
n >>= 1;
}
}
return ans;
}
//sieve or first divisor time : O(mx * log ( log (mx) ) )
public static int[] _seive(int mx){
int[] firstDivisor = new int[mx+1];
for(int i=0;i<=mx;i++)firstDivisor[i] = i;
for(int i=2;i*i<=mx;i++)
if(firstDivisor[i] == i)
for(int j = i*i;j<=mx;j+=i)
firstDivisor[j] = i;
return firstDivisor;
}
// check if x is a prime # of not. time : O( n ^ 1/2 )
private static boolean _isPrime(long x){
for(long i=2;i*i<=x;i++)
if(x%i==0)return false;
return true;
}
static class Pair<K, V>{
K ff;
V ss;
public Pair(K ff, V ss) {
this.ff = ff;
this.ss = ss;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || this.getClass() != o.getClass()) return false;
Pair<?, ?> pair = (Pair<?, ?>) o;
return ff.equals(pair.ff) && ss.equals(pair.ss);
}
@Override
public int hashCode() {
return Objects.hash(ff, ss);
}
}
static FastestReader sc;
static PrintWriter out;
private static void openIO() throws IOException {
sc = new FastestReader();
out = new PrintWriter(System.out);
}
/*-------------------------------------------FAST INPUT STARTS HERE---------------------------------------------*/
public static void closeIO() throws IOException {
out.flush();
out.close();
sc.close();
}
private static final class FastestReader {
private static final int BUFFER_SIZE = 1 << 16;
private final DataInputStream din;
private final byte[] buffer;
private int bufferPointer, bytesRead;
public FastestReader() {
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public FastestReader(String file_name) throws IOException {
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
private static boolean isSpaceChar(int c) {
return !(c >= 33 && c <= 126);
}
private int skip() throws IOException {
int b;
//noinspection StatementWithEmptyBody
while ((b = read()) != -1 && isSpaceChar(b)) {
}
return b;
}
public String next() throws IOException {
int b = skip();
final StringBuilder sb = new StringBuilder();
while (!isSpaceChar(b)) { // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = read();
}
return sb.toString();
}
public int nextInt() throws IOException {
int ret = 0;
byte c = read();
while (c <= ' ') {
c = read();
}
final boolean neg = c == '-';
if (neg) {
c = read();
}
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg) {
return -ret;
}
return ret;
}
public long nextLong() throws IOException {
long ret = 0;
byte c = read();
while (c <= ' ') {
c = read();
}
final boolean neg = c == '-';
if (neg) {
c = read();
}
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg) {
return -ret;
}
return ret;
}
public double nextDouble() throws IOException {
double ret = 0, div = 1;
byte c = read();
while (c <= ' ') {
c = read();
}
final boolean neg = c == '-';
if (neg) {
c = read();
}
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (c == '.') {
while ((c = read()) >= '0' && c <= '9') {
ret += (c - '0') / (div *= 10);
}
}
if (neg) {
return -ret;
}
return ret;
}
private void fillBuffer() throws IOException {
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1) {
buffer[0] = -1;
}
}
private byte read() throws IOException {
if (bufferPointer == bytesRead) {
fillBuffer();
}
return buffer[bufferPointer++];
}
public void close() throws IOException {
din.close();
}
}
/*---------------------------------------------FAST INPUT ENDS HERE ---------------------------------------------*/
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
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
|
8e9c556f9e053f3d0ecbf997e86615bc
|
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) throws IOException {
Scanner scn = new Scanner(System.in);
// Always print a trailing "\n" and close the OutputWriter as shown at the end of your output
// example:
int n=scn.nextInt();
int l=1;int r=n;
System.out.print("? "+l+" "+r+"\n");System.out.flush();
int id=scn.nextInt();
while(r-l>1){
int m=(l+r)/2;
System.out.print("? "+l+" "+m+"\n");System.out.flush();
int id1=scn.nextInt();
System.out.print("? "+m+" "+r+"\n");System.out.flush();
int id2=scn.nextInt();
if(id<=m){
if(id==id1){
r=m;
}
else{
l=m;id=id2;
}
}
else if(id>=m){
if(id==id2){
l=m;
}
else{
r=m;id=id1;
}
}
}
if(id==r){
System.out.print("! "+l+"");System.out.flush();
}
else{
System.out.print("! "+r+"");System.out.flush();
}
}
// fast input
static class Scanner {
public BufferedReader reader;
public StringTokenizer tokenizer;
public Scanner(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream));
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
String line = reader.readLine();
if (line == null)
return null;
tokenizer = new StringTokenizer(line);
} catch (Exception e) {
throw(new RuntimeException());
}
}
return tokenizer.nextToken();
}
public int nextInt() { return Integer.parseInt(next()); }
public long nextLong() { return Long.parseLong(next()); }
public double nextDouble() { return Double.parseDouble(next()); }
}
// fast output
static class OutputWriter {
BufferedWriter writer;
public OutputWriter(OutputStream stream) {
writer = new BufferedWriter(new OutputStreamWriter(stream));
}
public void print(int i) throws IOException { writer.write(i); }
public void print(String s) throws IOException { writer.write(s); }
public void print(char[] c) throws IOException { writer.write(c); }
public void close() throws IOException { writer.close(); }
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
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
|
7764bba2707b30fecbf8112af53b6a14
|
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
|
//https://vjudge.net/contest/438472#problem/D
//D - Guess easy version
import java.util.*;
import java.io.*;
public class PBH_401_D{
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static PrintWriter pw = new PrintWriter(new OutputStreamWriter(System.out));
static int ask(int l, int h) throws Exception{
if(l==h)
return -1;
pw.print("? "+l+" "+h+"\n");
pw.flush();
return Integer.parseInt(br.readLine());
}
public static void main(String[] args) throws Exception{
int n = Integer.parseInt(br.readLine());
int l = 1, h = n;
while(h+1-l>1){
int sm = ask(l, h);
int mid = (l+h+1)/2;
if(sm<mid){
if(ask(l, mid-1)==sm)
h = mid-1;
else
l = mid;
}
else{
if(ask(mid, h)==sm)
l = mid;
else
h = mid-1;
}
}
pw.print("! "+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 11
|
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
|
46d53bb8dce07d9d5cd0303ed012b403
|
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
|
//https://vjudge.net/contest/438472#problem/D
//D - Guess easy version
import java.util.*;
import java.io.*;
public class PBH_401_D{
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static PrintWriter pw = new PrintWriter(new OutputStreamWriter(System.out));
static int ask(int l, int h) throws Exception{
if(l==h)
return -1;
pw.print("? "+l+" "+h+"\n");
pw.flush();
return Integer.parseInt(br.readLine());
}
public static void main(String[] args) throws Exception{
int n = Integer.parseInt(br.readLine());
int l = 1, h = n+1;
while(h-l>1){
int sm = ask(l, h-1);
int mid = (l+h)/2;
if(sm<mid){
if(ask(l, mid-1)==sm)
h = mid;
else
l = mid;
}
else{
if(ask(mid, h-1)==sm)
l = mid;
else
h = mid;
}
}
pw.print("! "+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 11
|
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
|
5b3869b4a0984240ea81be27e17dd3eb
|
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.*;
import java.lang.*;
public class cf719 {
public static int query(int l,int r) throws Exception{
if(l>=r)return -1;
InputStreamReader ip=new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(ip);
System.out.println("? "+(l+1)+" "+(r+1));
int ans=Integer.parseInt(br.readLine());
return ans-1;
}
//For HardVersion the resulting number of queries is 2+⌈𝑙𝑜𝑔(base2)10^5⌉=19.
//For EasyVersion the resulting number of queries is 2⋅⌈𝑙𝑜𝑔2105⌉=34.
public static void HardVersion() throws Exception{
InputStreamReader ip=new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(ip);
int n =Integer.parseInt(br.readLine());
// String[] strs=(br.readLine()).trim().split(" ");
int l=0,r=n; //so that segment divide equally by mid [l,mid) [mid,r)
int smax=query(l, r-1); //segment max
int ans=0;
if(smax==0 || query(0, smax)!=smax){
l=smax; r=n-1; //Max lie in right segment
while((r-l)>1){
int mid=l+(r-l)/2;
if(query(smax,mid)==smax){
r=mid;
}else{
l=mid;
}
}
System.out.println("! "+(r+1)); //+r+" "
}else{
l=0; r=smax; //Max lie in left segment
while((r-l)>1){
int mid=l+(r-l)/2;
if(query(mid,smax)==smax){
l=mid;
}else{
r=mid;
}
}
System.out.println("! "+(l+1));
}
}
public static void EasyVersion() throws Exception{
InputStreamReader ip=new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(ip);
int n =Integer.parseInt(br.readLine());
// String[] strs=(br.readLine()).trim().split(" ");
int l=0,r=n; //so that segment divide equally by mid [l,mid) [mid,r)
int ans=0;
while((r-l)>1){ // query possible for segment of size >1
int mid=l+(r-l)/2;
int smax=query(l, r-1); //segment max
if(smax<mid){
if(query(l, mid-1)==smax){
r=mid;
}else{ l=mid; }
}else{
if(query(mid, r-1)==smax){
l=mid;
}else{
r=mid;
}
}
// System.out.println(l+" "+r);
}
System.out.println("! "+r); //+r+" "
}
//******************************************************************************************************************** */
public static void main(String[] args) throws Exception{
HardVersion();
}
public static void solve3() throws Exception{
InputStreamReader ip=new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(ip);
int t = Integer.parseInt(br.readLine());
StringBuilder asb=new StringBuilder();
while(t-->0){
int n =Integer.parseInt(br.readLine());
String[] strs=(br.readLine()).trim().split(" ");
// int n=Integer.parseInt(strs[0]),k=Integer.parseInt(strs[1]),r=Integer.parseInt(strs[2]),s=Integer.parseInt(strs[3]);
// String str=(br.readLine()).trim();
//Rearrange Given Expression- a𝑗−a𝑖=𝑗−𝑖 => aj-j == ai-i
int[] arr=new int[n];
HashMap<Integer,Integer> hm=new HashMap<>();
for(int i=0;i<n;i++){ arr[i]=Integer.parseInt(strs[i]);
hm.put((arr[i]-i), hm.getOrDefault((arr[i]-i), 0)+1); }
long ans=0;
for(int key:hm.keySet()){
long ct=hm.get(key);
ans+=(ct*(ct-1))/2;
}
// System.out.println(ans+" ct "+ct);
System.out.println(ans);
}
}
//******************************************************************************************************************** */
public static long modInverse1(long a, long m){
// int g = gcd(a, m);
// if(g!=1) {System.out.println("Inverse Doesnot Exist");}
return binexp(a, m - 2, m);
}
public static long binexp(long a, long b, long m){
if (b == 0)return 1;
long res = binexp(a, b / 2, m);
if (b % 2 == 1) return (( (res*res)%m )*a) % m;
else return (res*res)%m;
}
//binexp
public static long binexp(long a,long b){
if(b==0)return 1;
long res=binexp(a, b/2);
if(b%2==1){
return (((res*res))*a);
}else return (res*res);
}
//Comparator Interface
public static class comp implements Comparator<int[]>{
public int compare(int[] a,int[] b){
return a[0]-b[0];
}
}
//gcd using Euclid's Division Algorithm
public static long gcd(long a,long b){
if(b==0)return a;
else return gcd(b, a%b);
}
//check prime in root(n)
public static int isprime(int n){
for(int i=2;i<=Math.sqrt(n);i++){
if(n%i==0)return i;
}
return -1; //means n is prime
}
//SOE
static int[] sieve;
public static void SOE(int n){
sieve=new int[n+1];
// System.out.println("All prime number from 1 to n:-");
for(int x=2;x<=n;x++){
if(sieve[x]!=0){ //Not prime number
continue;
}
// System.out.print(x+" ");
for(int u=2*x;u<=n;u+=x){
sieve[u]=x;
}
}
//If sieve[i]=0 means 'i' is primr else 'i' is not prime
}
//sort
public static void sort(long[] arr) {
int n = arr.length;
for (int i = 0; i < n; i++) {
int idx = (int) Math.random() * n;
long temp = arr[i]; arr[i] = arr[idx]; arr[idx] = temp; //swap
}
Arrays.sort(arr);
}
public static void sort(int[] arr) {
int n = arr.length;
for (int i = 0; i < n; i++) {
int idx = (int) Math.random() * n;
int temp = arr[i]; arr[i] = arr[idx]; arr[idx] = temp; //swap
}
Arrays.sort(arr);
}
//1d print
public static void print(int[] dp) {
for (int val : dp) {
System.out.print(val + " ");
}
System.out.println();
}
public static void print(long[] dp) {//Method Overloading
for (long val : dp) {
System.out.print(val + " ");
}
System.out.println();
}
//2d print
public static void print(long[][] dp) {//Method Overloading
for (long[] a : dp) {
for (long val : a) {
System.out.print(val + " ");
}
System.out.println();
}
}
public static void print(int[][] dp) {
for (int[] a : dp) {
for (int val : a) {
System.out.print(val + " ");
}
System.out.println();
}
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
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
|
4ad90bee19c239b36821c06aa0b2f755
|
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.*;
import java.lang.*;
public class cf719 {
public static void solve1() throws Exception{
InputStreamReader ip=new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(ip);
// int t = Integer.parseInt(br.readLine());
StringBuilder asb=new StringBuilder();
boolean fg=true;
while(fg){
int n =Integer.parseInt(br.readLine());
String[] strs=(br.readLine()).trim().split(" ");
// int n=Integer.parseInt(strs[0]),k=Integer.parseInt(strs[1]),r=Integer.parseInt(strs[2]),s=Integer.parseInt(strs[3]);
// String str=(br.readLine()).trim();
if(strs.length==2){
System.out.println(strs[0]+" "+strs[1]);
fg=false; break;
}else{
int lo=10 ,hi=60;
if(strs[0].equals(">=")){
}else if(strs[0].equals("<")){
lo++;
}
}
}
}
public static int query(int l,int r) throws Exception{
if(l>=r)return -1;
InputStreamReader ip=new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(ip);
System.out.println("? "+(l+1)+" "+(r+1));
int ans=Integer.parseInt(br.readLine());
return ans-1;
}
public static void solve() throws Exception{
InputStreamReader ip=new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(ip);
int n =Integer.parseInt(br.readLine());
// String[] strs=(br.readLine()).trim().split(" ");
int l=0,r=n; //so that segment divide equally by mid [l,mid) [mid,r)
int ans=0;
while((r-l)>1){ // query possible for segment of size >1
int mid=l+(r-l)/2;
// if(l==mid){ // last segment of size 2 This condition is mandatory otherwise loop goes in infinite loop
// if(query(l, r)==l){ ans=r;}
// else{ ans=l; } break;
// }
int smax=query(l, r-1); //segment max
if(smax<mid){
if(query(l, mid-1)==smax){
r=mid;
}else{ l=mid; }
}else{
if(query(mid, r-1)==smax){
l=mid;
}else{
r=mid;
}
}
// System.out.println(l+" "+r);
}
System.out.println("! "+r); //+r+" "
}
//******************************************************************************************************************** */
public static void main(String[] args) throws Exception{
solve();
}
public static void solve3() throws Exception{
InputStreamReader ip=new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(ip);
int t = Integer.parseInt(br.readLine());
StringBuilder asb=new StringBuilder();
while(t-->0){
int n =Integer.parseInt(br.readLine());
String[] strs=(br.readLine()).trim().split(" ");
// int n=Integer.parseInt(strs[0]),k=Integer.parseInt(strs[1]),r=Integer.parseInt(strs[2]),s=Integer.parseInt(strs[3]);
// String str=(br.readLine()).trim();
//Rearrange Given Expression- a𝑗−a𝑖=𝑗−𝑖 => aj-j == ai-i
int[] arr=new int[n];
HashMap<Integer,Integer> hm=new HashMap<>();
for(int i=0;i<n;i++){ arr[i]=Integer.parseInt(strs[i]);
hm.put((arr[i]-i), hm.getOrDefault((arr[i]-i), 0)+1); }
long ans=0;
for(int key:hm.keySet()){
long ct=hm.get(key);
ans+=(ct*(ct-1))/2;
}
// System.out.println(ans+" ct "+ct);
System.out.println(ans);
}
}
//******************************************************************************************************************** */
public static long modInverse1(long a, long m){
// int g = gcd(a, m);
// if(g!=1) {System.out.println("Inverse Doesnot Exist");}
return binexp(a, m - 2, m);
}
public static long binexp(long a, long b, long m){
if (b == 0)return 1;
long res = binexp(a, b / 2, m);
if (b % 2 == 1) return (( (res*res)%m )*a) % m;
else return (res*res)%m;
}
//binexp
public static long binexp(long a,long b){
if(b==0)return 1;
long res=binexp(a, b/2);
if(b%2==1){
return (((res*res))*a);
}else return (res*res);
}
//Comparator Interface
public static class comp implements Comparator<int[]>{
public int compare(int[] a,int[] b){
return a[0]-b[0];
}
}
//gcd using Euclid's Division Algorithm
public static long gcd(long a,long b){
if(b==0)return a;
else return gcd(b, a%b);
}
//check prime in root(n)
public static int isprime(int n){
for(int i=2;i<=Math.sqrt(n);i++){
if(n%i==0)return i;
}
return -1; //means n is prime
}
//SOE
static int[] sieve;
public static void SOE(int n){
sieve=new int[n+1];
// System.out.println("All prime number from 1 to n:-");
for(int x=2;x<=n;x++){
if(sieve[x]!=0){ //Not prime number
continue;
}
// System.out.print(x+" ");
for(int u=2*x;u<=n;u+=x){
sieve[u]=x;
}
}
//If sieve[i]=0 means 'i' is primr else 'i' is not prime
}
//sort
public static void sort(long[] arr) {
int n = arr.length;
for (int i = 0; i < n; i++) {
int idx = (int) Math.random() * n;
long temp = arr[i]; arr[i] = arr[idx]; arr[idx] = temp; //swap
}
Arrays.sort(arr);
}
public static void sort(int[] arr) {
int n = arr.length;
for (int i = 0; i < n; i++) {
int idx = (int) Math.random() * n;
int temp = arr[i]; arr[i] = arr[idx]; arr[idx] = temp; //swap
}
Arrays.sort(arr);
}
//1d print
public static void print(int[] dp) {
for (int val : dp) {
System.out.print(val + " ");
}
System.out.println();
}
public static void print(long[] dp) {//Method Overloading
for (long val : dp) {
System.out.print(val + " ");
}
System.out.println();
}
//2d print
public static void print(long[][] dp) {//Method Overloading
for (long[] a : dp) {
for (long val : a) {
System.out.print(val + " ");
}
System.out.println();
}
}
public static void print(int[][] dp) {
for (int[] a : dp) {
for (int val : a) {
System.out.print(val + " ");
}
System.out.println();
}
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
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
|
7f6335a79fb9fab06982598e08a3c8d6
|
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.Arrays;
public class codeforces {
static int ask(int l,int r)throws IOException {
if(l==r) {
return -1;
}
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int out1;
System.out.println("? "+l+" "+r);
System.out.flush();
out1=Integer.parseInt(br.readLine());
return out1;
}
public static void main(String[] args)throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n=Integer.parseInt(br.readLine());
int l=1;
int r=n;
int pos=ask(1,n);
if(ask(1,pos)==pos) {
l=1;
r=pos;
while(l<r) {
int mid=(l+r+1)/2;
if(ask(mid,n)==pos) {
l=mid;
}
else {
r=mid-1;
}
}
System.out.println("! "+l);
}
else {
l=pos;
r=n;
while(l<r) {
int mid=(l+r)/2;
if(ask(pos,mid)==pos) {
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 11
|
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
|
890342832c629e5562d5f90637afad19
|
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.Vector;
import java.util.*;
import java.lang.Math;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import javax.management.Query;
import java.io.*;
import java.math.BigInteger;
public class Main {
static int mod = 1000000007;
static class Edge {
int to;
long time, k;
public Edge(int to, long time, long k) {
this.to = to;
this.time = time;
this.k = k;
}
}
static class Pair implements Comparator<Pair> {
long x;
long y;
// Constructor
public Pair(long x, long y) {
this.x = x;
this.y = y;
}
public Pair() {
}
@Override
public int compare(Main.Pair o1, Main.Pair o2) {
if (o1.y < o2.y)
return -1;
if (o1.y > o2.y)
return 1;
if (o1.y == o2.y) {
if (o1.x <= o2.x) {
return -1;
} else {
return 1;
}
}
return 0;
}
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
int[] intArr(int n) {
int res[] = new int[n];
for (int i = 0; i < n; i++)
res[i] = nextInt();
return res;
}
long[] longArr(int n) {
long res[] = new long[n];
for (int i = 0; i < n; i++)
res[i] = nextLong();
return res;
}
}
static FastReader f = new FastReader();
static BufferedWriter w = new BufferedWriter(new OutputStreamWriter(System.out));
static boolean isPrime(long n) {
if (n <= 1)
return false;
if (n <= 3)
return true;
if (n % 2 == 0 || n % 3 == 0)
return false;
for (long i = 5; i * i <= n; i = i + 6)
if (n % i == 0 || n % (i + 2) == 0)
return false;
return true;
}
static int LowerBound(int a[], int x) { // smallest index having value >= x
int l = -1, r = a.length;
while (l + 1 < r) {
int m = (l + r) >>> 1;
if (a[m] >= x)
r = m;
else
l = m;
}
return r;
}
static int UpperBound(int a[], int x) {// biggest index having value <= x
int l = -1, r = a.length;
while (l + 1 < r) {
int m = (l + r) >>> 1;
if (a[m] <= x)
l = m;
else
r = m;
}
return l + 1;
}
static long gcd(long a, long b) {
if (a == 0)
return b;
return gcd(b % a, a);
}
static long lcm(long a, long b) {
return (a * b) / gcd(a, b);
}
static long power(long x, long y, long p) {
long res = 1;
x = x % p;
while (y > 0) {
if (y % 2 == 1)
res = (res * x) % p;
y = y >> 1; // y = y/2
x = (x * x) % p;
}
return res;
}
static long power(long x, long y) {
long res = 1;
while (y > 0) {
if (y % 2 == 1)
res = (res * x);
y >>= 1;
x = (x * x);
}
return res;
}
static int power(int x, int y) {
int res = 1;
while (y > 0) {
if (y % 2 == 1)
res = (res * x);
y >>= 1;
x = (x * x);
}
return res;
}
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));
}
/*
* ===========Modular Operations==================
*/
static long modInverse(long n, long p) {
return power(n, p - 2, p);
}
static long modAdd(long a, long b) {
return (a % mod + b % mod) % mod;
}
static long modMul(long a, long b) {
return ((a % mod) * (b % mod)) % mod;
}
static long nCrModPFermat(int n, int r) {
long p = 1000000007;
if (r == 0)
return 1;
long[] fac = new long[n + 1];
fac[0] = 1;
for (int i = 1; i <= n; i++)
fac[i] = fac[i - 1] * i % p;
return (fac[n] * modInverse(fac[r], p) % p * modInverse(fac[n - r], p) % p) % p;
}
/*
* ===============================================
*/
List<Integer> removeDup(ArrayList<Integer> list) {
List<Integer> newList = list.stream().distinct().collect(Collectors.toList());
return newList;
}
static void ruffleSort(long[] a) {
int n = a.length;
Random r = new Random();
for (int i = 0; i < a.length; i++) {
int oi = r.nextInt(n);
long temp = a[i];
a[i] = a[oi];
a[oi] = temp;
}
Arrays.sort(a);
}
static void ruffleSort(int[] a) {
int n = a.length;
Random r = new Random();
for (int i = 0; i < a.length; i++) {
int oi = r.nextInt(n);
int temp = a[i];
a[i] = a[oi];
a[oi] = temp;
}
Arrays.sort(a);
}
/*
* ===========Dynamic prog Recur Section===========
*/
static int DP[][];
static ArrayList<ArrayList<Integer>> g;
static int count = 0;
static ArrayList<Long> bitMask(ArrayList<Long> ar, int n) {
ArrayList<Long> ans = new ArrayList<>();
for (int mask = 0; mask <= Math.pow(2, n) - 1; mask++) {
long sum = 0;
for (int i = 0; i < n; i++) {
if (((1 << i) & mask) > 0) {
sum += ar.get(i);
}
}
ans.add(sum);
}
return ans;
}
/*
* ====================================Main=================================
*/
public static void main(String args[]) throws Exception {
File file = new File("D:\\VS Code\\Java\\Output.txt");
// FileWriter fw = new FileWriter("D:\\VS Code\\Java\\Output.txt");
Random rand = new Random();
int t = 1;
// t = f.nextInt();
while (t-- != 0) {
int n = f.nextInt();
int high = n, low = 1, mid = 0,flag=0;
while (high > low) {
int q=ask(low,high);
if(high-low==1){
print(q==low?high:low);
flag=1;
break;
}
mid=(high+low)/2;
if(q<=mid){
int x=ask(low,mid);
if(x==q){
high=mid;
}else{
low=mid;
}
}else{
int x=ask(mid,high);
if(x==q){
low=mid;
}else{
high=mid;
}
}
}
if(flag==0)print(low);
}
w.flush();
}
static int ask(int l, int r) throws IOException {
w.write("? "+l+" "+r+"\n");
w.flush();
int q=f.nextInt();
return q;
}
static void print(int p) throws IOException{
w.write("! "+p+"\n");
w.flush();
}
}
// 5 1 4 2 3
// 3 5 2 7 5 6 9
// 1 2 3 4 5 6 7
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
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
|
457f24a91094c0fc9aeb0b4bf8fc907d
|
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.Vector;
import java.util.*;
import java.lang.Math;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import javax.management.Query;
import java.io.*;
import java.math.BigInteger;
public class Main {
static int mod = 1000000007;
static class Edge {
int to;
long time, k;
public Edge(int to, long time, long k) {
this.to = to;
this.time = time;
this.k = k;
}
}
static class Pair implements Comparator<Pair> {
long x;
long y;
// Constructor
public Pair(long x, long y) {
this.x = x;
this.y = y;
}
public Pair() {
}
@Override
public int compare(Main.Pair o1, Main.Pair o2) {
if (o1.y < o2.y)
return -1;
if (o1.y > o2.y)
return 1;
if (o1.y == o2.y) {
if (o1.x <= o2.x) {
return -1;
} else {
return 1;
}
}
return 0;
}
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
int[] intArr(int n) {
int res[] = new int[n];
for (int i = 0; i < n; i++)
res[i] = nextInt();
return res;
}
long[] longArr(int n) {
long res[] = new long[n];
for (int i = 0; i < n; i++)
res[i] = nextLong();
return res;
}
}
static FastReader f = new FastReader();
static BufferedWriter w = new BufferedWriter(new OutputStreamWriter(System.out));
static boolean isPrime(long n) {
if (n <= 1)
return false;
if (n <= 3)
return true;
if (n % 2 == 0 || n % 3 == 0)
return false;
for (long i = 5; i * i <= n; i = i + 6)
if (n % i == 0 || n % (i + 2) == 0)
return false;
return true;
}
static int LowerBound(int a[], int x) { // smallest index having value >= x
int l = -1, r = a.length;
while (l + 1 < r) {
int m = (l + r) >>> 1;
if (a[m] >= x)
r = m;
else
l = m;
}
return r;
}
static int UpperBound(int a[], int x) {// biggest index having value <= x
int l = -1, r = a.length;
while (l + 1 < r) {
int m = (l + r) >>> 1;
if (a[m] <= x)
l = m;
else
r = m;
}
return l + 1;
}
static long gcd(long a, long b) {
if (a == 0)
return b;
return gcd(b % a, a);
}
static long lcm(long a, long b) {
return (a * b) / gcd(a, b);
}
static long power(long x, long y, long p) {
long res = 1;
x = x % p;
while (y > 0) {
if (y % 2 == 1)
res = (res * x) % p;
y = y >> 1; // y = y/2
x = (x * x) % p;
}
return res;
}
static long power(long x, long y) {
long res = 1;
while (y > 0) {
if (y % 2 == 1)
res = (res * x);
y >>= 1;
x = (x * x);
}
return res;
}
static int power(int x, int y) {
int res = 1;
while (y > 0) {
if (y % 2 == 1)
res = (res * x);
y >>= 1;
x = (x * x);
}
return res;
}
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));
}
/*
* ===========Modular Operations==================
*/
static long modInverse(long n, long p) {
return power(n, p - 2, p);
}
static long modAdd(long a, long b) {
return (a % mod + b % mod) % mod;
}
static long modMul(long a, long b) {
return ((a % mod) * (b % mod)) % mod;
}
static long nCrModPFermat(int n, int r) {
long p = 1000000007;
if (r == 0)
return 1;
long[] fac = new long[n + 1];
fac[0] = 1;
for (int i = 1; i <= n; i++)
fac[i] = fac[i - 1] * i % p;
return (fac[n] * modInverse(fac[r], p) % p * modInverse(fac[n - r], p) % p) % p;
}
/*
* ===============================================
*/
List<Integer> removeDup(ArrayList<Integer> list) {
List<Integer> newList = list.stream().distinct().collect(Collectors.toList());
return newList;
}
static void ruffleSort(long[] a) {
int n = a.length;
Random r = new Random();
for (int i = 0; i < a.length; i++) {
int oi = r.nextInt(n);
long temp = a[i];
a[i] = a[oi];
a[oi] = temp;
}
Arrays.sort(a);
}
static void ruffleSort(int[] a) {
int n = a.length;
Random r = new Random();
for (int i = 0; i < a.length; i++) {
int oi = r.nextInt(n);
int temp = a[i];
a[i] = a[oi];
a[oi] = temp;
}
Arrays.sort(a);
}
/*
* ===========Dynamic prog Recur Section===========
*/
static int DP[][];
static ArrayList<ArrayList<Integer>> g;
static int count = 0;
static ArrayList<Long> bitMask(ArrayList<Long> ar, int n) {
ArrayList<Long> ans = new ArrayList<>();
for (int mask = 0; mask <= Math.pow(2, n) - 1; mask++) {
long sum = 0;
for (int i = 0; i < n; i++) {
if (((1 << i) & mask) > 0) {
sum += ar.get(i);
}
}
ans.add(sum);
}
return ans;
}
/*
* ====================================Main=================================
*/
public static void main(String args[]) throws Exception {
File file = new File("D:\\VS Code\\Java\\Output.txt");
// FileWriter fw = new FileWriter("D:\\VS Code\\Java\\Output.txt");
Random rand = new Random();
int t = 1;
// t = f.nextInt();
while (t-- != 0) {
int n = f.nextInt();
int high = n, low = 1, mid = 0,flag=0;
while (high > low) {
int q=ask(low,high);
if(high-low==1){
print(q==low?high:low);
flag=1;
break;
}
mid=(high+low)/2;
if(q<=mid){
int x=ask(low,mid);
if(x==q){
high=mid;
}else{
low=mid+1;
}
}else{
int x=ask(mid,high);
if(x==q){
low=mid;
}else{
high=mid-1;
}
}
}
if(flag==0)print(low);
}
w.flush();
}
static int ask(int l, int r) throws IOException {
w.write("? "+l+" "+r+"\n");
w.flush();
int q=f.nextInt();
return q;
}
static void print(int p) throws IOException{
w.write("! "+p+"\n");
w.flush();
}
}
// 5 1 4 2 3
// 3 5 2 7 5 6 9
// 1 2 3 4 5 6 7
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
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
|
f19b754dd0e105fb2706f697642760fe
|
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.Vector;
import java.util.*;
import java.lang.Math;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import javax.management.Query;
import java.io.*;
import java.math.BigInteger;
public class Main {
static int mod = 1000000007;
static class Edge {
int to;
long time, k;
public Edge(int to, long time, long k) {
this.to = to;
this.time = time;
this.k = k;
}
}
static class Pair implements Comparator<Pair> {
long x;
long y;
// Constructor
public Pair(long x, long y) {
this.x = x;
this.y = y;
}
public Pair() {
}
@Override
public int compare(Main.Pair o1, Main.Pair o2) {
if (o1.y < o2.y)
return -1;
if (o1.y > o2.y)
return 1;
if (o1.y == o2.y) {
if (o1.x <= o2.x) {
return -1;
} else {
return 1;
}
}
return 0;
}
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
int[] intArr(int n) {
int res[] = new int[n];
for (int i = 0; i < n; i++)
res[i] = nextInt();
return res;
}
long[] longArr(int n) {
long res[] = new long[n];
for (int i = 0; i < n; i++)
res[i] = nextLong();
return res;
}
}
static FastReader f = new FastReader();
static BufferedWriter w = new BufferedWriter(new OutputStreamWriter(System.out));
static boolean isPrime(long n) {
if (n <= 1)
return false;
if (n <= 3)
return true;
if (n % 2 == 0 || n % 3 == 0)
return false;
for (long i = 5; i * i <= n; i = i + 6)
if (n % i == 0 || n % (i + 2) == 0)
return false;
return true;
}
static int LowerBound(int a[], int x) { // smallest index having value >= x
int l = -1, r = a.length;
while (l + 1 < r) {
int m = (l + r) >>> 1;
if (a[m] >= x)
r = m;
else
l = m;
}
return r;
}
static int UpperBound(int a[], int x) {// biggest index having value <= x
int l = -1, r = a.length;
while (l + 1 < r) {
int m = (l + r) >>> 1;
if (a[m] <= x)
l = m;
else
r = m;
}
return l + 1;
}
static long gcd(long a, long b) {
if (a == 0)
return b;
return gcd(b % a, a);
}
static long lcm(long a, long b) {
return (a * b) / gcd(a, b);
}
static long power(long x, long y, long p) {
long res = 1;
x = x % p;
while (y > 0) {
if (y % 2 == 1)
res = (res * x) % p;
y = y >> 1; // y = y/2
x = (x * x) % p;
}
return res;
}
static long power(long x, long y) {
long res = 1;
while (y > 0) {
if (y % 2 == 1)
res = (res * x);
y >>= 1;
x = (x * x);
}
return res;
}
static int power(int x, int y) {
int res = 1;
while (y > 0) {
if (y % 2 == 1)
res = (res * x);
y >>= 1;
x = (x * x);
}
return res;
}
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));
}
/*
* ===========Modular Operations==================
*/
static long modInverse(long n, long p) {
return power(n, p - 2, p);
}
static long modAdd(long a, long b) {
return (a % mod + b % mod) % mod;
}
static long modMul(long a, long b) {
return ((a % mod) * (b % mod)) % mod;
}
static long nCrModPFermat(int n, int r) {
long p = 1000000007;
if (r == 0)
return 1;
long[] fac = new long[n + 1];
fac[0] = 1;
for (int i = 1; i <= n; i++)
fac[i] = fac[i - 1] * i % p;
return (fac[n] * modInverse(fac[r], p) % p * modInverse(fac[n - r], p) % p) % p;
}
/*
* ===============================================
*/
List<Integer> removeDup(ArrayList<Integer> list) {
List<Integer> newList = list.stream().distinct().collect(Collectors.toList());
return newList;
}
static void ruffleSort(long[] a) {
int n = a.length;
Random r = new Random();
for (int i = 0; i < a.length; i++) {
int oi = r.nextInt(n);
long temp = a[i];
a[i] = a[oi];
a[oi] = temp;
}
Arrays.sort(a);
}
static void ruffleSort(int[] a) {
int n = a.length;
Random r = new Random();
for (int i = 0; i < a.length; i++) {
int oi = r.nextInt(n);
int temp = a[i];
a[i] = a[oi];
a[oi] = temp;
}
Arrays.sort(a);
}
/*
* ===========Dynamic prog Recur Section===========
*/
static int DP[][];
static ArrayList<ArrayList<Integer>> g;
static int count = 0;
static ArrayList<Long> bitMask(ArrayList<Long> ar, int n) {
ArrayList<Long> ans = new ArrayList<>();
for (int mask = 0; mask <= Math.pow(2, n) - 1; mask++) {
long sum = 0;
for (int i = 0; i < n; i++) {
if (((1 << i) & mask) > 0) {
sum += ar.get(i);
}
}
ans.add(sum);
}
return ans;
}
/*
* ====================================Main=================================
*/
public static void main(String args[]) throws Exception {
File file = new File("D:\\VS Code\\Java\\Output.txt");
// FileWriter fw = new FileWriter("D:\\VS Code\\Java\\Output.txt");
Random rand = new Random();
int t = 1;
// t = f.nextInt();
while (t-- != 0) {
int n = f.nextInt();
int high = n, low = 1, mid = 0,flag=0;
while (high > low) {
int q=ask(low,high);
if(high-low==1){
print(q==low?high:low);
flag=1;
break;
}
mid=(high+low)/2;
if(q<=mid){
int x=ask(low,mid);
if(x==q){
high=mid;
}else{
low=mid+1;
}
}else{
int x=ask(mid,high);
if(x==q){
low=mid;
}else{
high=mid-1;
}
}
}
if(flag==0)print(high);
}
w.flush();
}
static int ask(int l, int r) throws IOException {
w.write("? "+l+" "+r+"\n");
w.flush();
int q=f.nextInt();
return q;
}
static void print(int p) throws IOException{
w.write("! "+p+"\n");
w.flush();
}
}
// 5 1 4 2 3
// 3 5 2 7 5 6 9
// 1 2 3 4 5 6 7
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
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
|
3d4ae3776103111c5ddb68fb8b5adfcd
|
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.lang.*;
import java.io.*;
import java.awt.*;
public class Main
{
static Scanner scn = new Scanner(System.in) ;
public static int query(int l , int r)
{
System.out.println("? " + l +" " + r ) ;
int q = scn.nextInt() ;
return q ;
}
public static int getLeft(int l , int k)
{
int r = k-1 ;int ans = k-1 ;
while(l <= r)
{
int mid = (l+r)/2 ;
int q = query(mid, k) ;
if(q == k)
{
l =mid+1 ;
ans = mid ;
}
else{
r=mid-1 ;
}
}
return ans ;
}
public static int getRight(int k , int r)
{
int l = k+1 ;int ans = k+1 ;
while( l <= r )
{
int mid = ( l+r)/2 ;
int q = query(k , mid ) ;
if(q== k)
{
r=mid-1 ;
ans = mid ;
}
else{
l =mid+1 ;
}
}
return ans ;
}
public static void solve()
{
int n = scn.nextInt() ;
int q = query(1,n) ;
if(n ==2)
{
System.out.println("! " + (3-q)) ;
}
else{
int ans = 0 ;
if(q ==1)
{
ans = getRight(1,n) ;
}
else if(q== n)
{
ans = getLeft(1,n) ;
}
else{
int temp = query(1,q) ;
if(temp == q)
{
ans = getLeft(1,q) ;
}
else{
ans = getRight(q,n) ;
}
}
System.out.println("! " + (ans)) ;
}
}
public static void main (String[] args) throws java.lang.Exception
{
solve() ;
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
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
|
543d9aedfeef533138d31aa5e940d736
|
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 {
private static final boolean N_CASE = false;
private int query(int l, int r) {
out.println(String.format("? %d %d", l, r));
out.flush();
return sc.nextInt();
}
private void answer(int value) {
out.println(String.format("! %d", value));
out.flush();
}
private void solve() {
int n = sc.nextInt();
int secIdx = query(1, n);
int l, r;
if (secIdx != n && query(secIdx, n) == secIdx) {
l = secIdx + 1; r = n;
if (l == r) { answer(l); return; }
while (l + 1 < r) {
int mid = (l + r) / 2;
if (query(secIdx, mid) == secIdx) {
r = mid;
} else {
l = mid + 1;
}
}
if (l == r) { answer(l); return; }
answer(query(l, r) == l ? r : l);
} else {
l = 1; r = secIdx - 1;
if (l == r) { answer(l); return; }
while (l + 1 < r) {
int mid = (l + r) / 2;
if (query(mid, secIdx) == secIdx) {
l = mid;
} else {
r = mid - 1;
}
}
if (l == r) { answer(l); return; }
answer(query(l, r) == l ? r : l);
}
}
private void run() {
int T = N_CASE ? sc.nextInt() : 1;
for (int t = 0; t < T; ++t) {
solve();
}
}
private static MyWriter out;
private static MyScanner sc;
private static CommonUtils cu;
public static void main(String[] args) {
out = new MyWriter(new BufferedOutputStream(System.out));
sc = new MyScanner();
new Main().run();
out.close();
}
}
class CommonUtils {
private <T> List<List<T>> createGraph(int n) {
List<List<T>> g = new ArrayList<>();
for (int i = 0; i < n; ++i) {
g.add(new ArrayList<>());
}
return g;
}
private void fill(int[][] a, int value) {
for (int[] row : a) {
fill(row, value);
}
}
private void fill(int[] a, int value) {
Arrays.fill(a, value);
}
}
class MyScanner {
private BufferedReader br;
private StringTokenizer st;
public MyScanner() {
br = new BufferedReader(new InputStreamReader(System.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());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public int[] nextIntArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = nextInt();
}
return a;
}
public int[][] nextIntArray(int n, int m) {
int[][] a = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
a[i][j] = nextInt();
}
}
return a;
}
public long[] nextLongArray(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++) {
a[i] = nextLong();
}
return a;
}
public long[][] nextLongArray(int n, int m) {
long[][] a = new long[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
a[i][j] = nextLong();
}
}
return a;
}
public List<Integer> nextList(int n) {
List<Integer> list = new ArrayList<>();
for (int i = 0; i < n; i++) {
list.add(nextInt());
}
return list;
}
public List<Long> nextLongList(int n) {
List<Long> list = new ArrayList<>();
for (int i = 0; i < n; i++) {
list.add(nextLong());
}
return list;
}
public char[] nextCharArray(int n) {
return next().toCharArray();
}
public char[][] nextCharArray(int n, int m) {
char[][] c = new char[n][m];
for (int i = 0; i < n; i++) {
String s = next();
for (int j = 0; j < m; j++) {
c[i][j] = s.charAt(j);
}
}
return c;
}
}
class MyWriter extends PrintWriter {
public MyWriter(OutputStream outputStream) {
super(outputStream);
}
public void printArray(int[] a) {
for (int i = 0; i < a.length; ++i) {
print(a[i]);
print(i == a.length - 1 ? '\n' : ' ');
}
}
public void printArray(long[] a) {
for (int i = 0; i < a.length; ++i) {
print(a[i]);
print(i == a.length - 1 ? '\n' : ' ');
}
}
public void println(int[] a) {
for (int v : a) {
println(v);
}
}
public void print(List<Integer> list) {
for (int i = 0; i < list.size(); ++i) {
print(list.get(i));
print(i == list.size() - 1 ? '\n' : ' ');
}
}
public void println(List<Integer> list) {
list.forEach(this::println);
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
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
|
0a438db99b2463c5704c21f58219ac52
|
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 Cf {
public static void main(String [] args){
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();int a=1;int b=n;
System.out.println("? "+a+" "+b );
System.out.flush();
int t=sc.nextInt();
int q=0;
if(t==1){}
else{
System.out.println("? "+a+" "+t);
System.out.flush();
q=sc.nextInt();
}
int ans=0;int l=0;int r=0;
if(q==t){
l=1;r=t;
while(l<=r){
if(l==r){ans=l;break;}
if(r==l+1){
if(r==t){ans=l;break;}
System.out.println("? "+r+" "+t);
System.out.flush();
int check=sc.nextInt();
if(check==t){ans=r;break;}
ans=l;break;
}
int m=(l+r)/2;
System.out.println("? "+m+" "+t);
System.out.flush();
int res=sc.nextInt();
if(res==t){l=m;}
else{
r=m-1;
}
}
}
else{
l=t;r=n;
while(r>=l){
if(l==r){ans=l;break;}
if(r==l+1){
if(l==t){ans=r;break;}
System.out.println("? "+t+" "+l);
System.out.flush();
int check=sc.nextInt();
if(check==t){ans=l;break;}
ans=r;break;
}
int m=(l+r)/2;
System.out.println("? "+t+" "+m);
System.out.flush();
int res=sc.nextInt();
if(res==t){r=m;}
else{
l=m+1;
}
}
}
System.out.println("! "+ans);
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
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
|
4af7808947c1128d921c81cd683bf114
|
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.StringTokenizer;
public class C {
void solve() throws IOException {
int n = nextInt();
int begin = 1;
int end = n;
/*
5 1 3 4 2
1 2 3 4 5
2 1 3
5 1 4 2 3
5 4 3 2 1
*/
writer.println("? " + begin + " " + end);
writer.flush();
int secMax = nextInt();
boolean beginChanging = true;
if (secMax == 1) {
begin = 2;
end = n;
beginChanging = false;
} else if (secMax == n) {
begin = 1;
end = secMax - 1;
} else {
writer.println("? " + 1 + " " + secMax);
writer.flush();
int leftSecMax = nextInt();
if (leftSecMax == secMax) {
begin = 1;
end = secMax - 1;
} else {
beginChanging = false;
begin = secMax + 1;
end = n;
}
}
if (beginChanging) {
int lastGood = 0;
while (begin <= end) {
int mid = begin + (end - begin) / 2;
writer.println("? " + mid + " " + secMax);
writer.flush();
int newSecMax = nextInt();
if (secMax == newSecMax) {
lastGood = mid;
begin = mid + 1;
} else {
end = mid - 1;
}
}
writer.println("! " + lastGood);
} else {
int lastGood = 0;
while (begin <= end) {
int mid = begin + (end - begin) / 2;
writer.println("? " + secMax + " " + mid);
writer.flush();
int newSecMax = nextInt();
if (newSecMax == secMax) {
lastGood = mid;
end = mid - 1;
} else {
begin = mid + 1;
}
}
writer.println("! " + lastGood);
}
}
String nextToken() throws IOException {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
return tokenizer.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
StringTokenizer tokenizer;
PrintWriter writer;
BufferedReader reader;
public void run() {
try {
writer = new PrintWriter(System.out);
reader = new BufferedReader(new InputStreamReader(System.in));
solve();
reader.close();
writer.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new C().run();
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
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
|
b026d3e59aaa11d66d0a6bec26c71694
|
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.StringTokenizer;
public class C {
void solve() throws IOException {
int n = nextInt();
int begin = 1;
int end = n;
/*
5 1 3 4 2
1 2 3 4 5
2 1 3
5 1 4 2 3
5 4 3 2 1
*/
int prev = -1;
while (begin < end) {
int secMax = 0;
if (prev == -1) {
writer.println("? " + begin + " " + end);
writer.flush();
secMax = nextInt();
} else {
secMax = prev;
}
if (end - begin == 1) {
if (secMax == begin) {
writer.println("! " + end);
writer.flush();
return;
} else {
writer.println("! " + begin);
writer.flush();
return;
}
}
int mid = begin + (end - begin) / 2;
// if (secMax > mid && rightSecMax != secMax) {
// end = mid;
// prev = leftSecMax;
// } else if (secMax < mid && leftSecMax != secMax) {
// begin = mid;
// prev = rightSecMax;
// } else if (secMax == leftSecMax) {
// end = mid;
// prev = leftSecMax;
// } else {
// begin = mid;
// prev = rightSecMax;
// }
if (secMax >= mid) {
writer.println("? " + mid + " " + end);
writer.flush();
int rightSecMax = nextInt();
if (rightSecMax == secMax) {
begin = mid;
prev = rightSecMax;
} else {
// writer.println("? " + begin + " " + (mid - 1));
// writer.flush();
// int leftSecMax = nextInt();
end = mid - 1;
prev = -1;
// prev = leftSecMax;
}
} else {
writer.println("? " + begin + " " + mid);
writer.flush();
int leftSecMax = nextInt();
if (leftSecMax == secMax) {
end = mid;
prev = leftSecMax;
} else {
// writer.println("? " + (mid + 1) + " " + end);
// writer.flush();
// int rightSecMax = nextInt();
begin = mid + 1;
prev = -1;
// prev = rightSecMax;
}
}
}
writer.println("! " + begin);
}
String nextToken() throws IOException {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
return tokenizer.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
StringTokenizer tokenizer;
PrintWriter writer;
BufferedReader reader;
public void run() {
try {
writer = new PrintWriter(System.out);
reader = new BufferedReader(new InputStreamReader(System.in));
solve();
reader.close();
writer.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new C().run();
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
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
|
0df2ed14973adf60fd32104c227913f6
|
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.StringTokenizer;
public class C {
void solve() throws IOException {
int n = nextInt();
int begin = 1;
int end = n;
/*
5 1 3 4 2
1 2 3 4 5
2 1 3
5 1 4 2 3
5 4 3 2 1
*/
int prev = -1;
while (begin < end) {
int secMax = 0;
if (prev == -1) {
writer.println("? " + begin + " " + end);
writer.flush();
secMax = nextInt();
} else {
secMax = prev;
}
if (end - begin == 1) {
if (secMax == begin) {
writer.println("! " + end);
writer.flush();
return;
} else {
writer.println("! " + begin);
writer.flush();
return;
}
}
int mid = begin + (end - begin) / 2;
// if (secMax > mid && rightSecMax != secMax) {
// end = mid;
// prev = leftSecMax;
// } else if (secMax < mid && leftSecMax != secMax) {
// begin = mid;
// prev = rightSecMax;
// } else if (secMax == leftSecMax) {
// end = mid;
// prev = leftSecMax;
// } else {
// begin = mid;
// prev = rightSecMax;
// }
if (secMax >= mid) {
writer.println("? " + mid + " " + end);
writer.flush();
int rightSecMax = nextInt();
if (rightSecMax == secMax) {
begin = mid;
prev = rightSecMax;
} else {
writer.println("? " + begin + " " + mid);
writer.flush();
int leftSecMax = nextInt();
end = mid;
prev = leftSecMax;
}
} else {
writer.println("? " + begin + " " + mid);
writer.flush();
int leftSecMax = nextInt();
if (leftSecMax == secMax) {
end = mid;
prev = leftSecMax;
} else {
writer.println("? " + mid + " " + end);
writer.flush();
int rightSecMax = nextInt();
begin = mid;
prev = rightSecMax;
}
}
}
writer.println("! " + begin);
}
String nextToken() throws IOException {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
return tokenizer.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
StringTokenizer tokenizer;
PrintWriter writer;
BufferedReader reader;
public void run() {
try {
writer = new PrintWriter(System.out);
reader = new BufferedReader(new InputStreamReader(System.in));
solve();
reader.close();
writer.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new C().run();
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
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
|
f071225b287d7ddccfa7bdf206de4d90
|
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.StringTokenizer;
public class C {
void solve() throws IOException {
int n = nextInt();
int begin = 1;
int end = n;
/*
5 1 3 4 2
1 2 3 4 5
2 1 3
5 1 4 2 3
*/
int prev = -1;
while (begin < end) {
int secMax = 0;
if (prev == -1) {
writer.println("? " + begin + " " + end);
writer.flush();
secMax = nextInt();
} else {
secMax = prev;
}
if (end - begin == 1) {
if (secMax == begin) {
writer.println("! " + end);
writer.flush();
return;
} else {
writer.println("! " + begin);
writer.flush();
return;
}
}
int mid = begin + (end - begin) / 2;
writer.println("? " + begin + " " + mid);
writer.flush();
int leftSecMax = nextInt();
writer.println("? " + mid + " " + end);
writer.flush();
int rightSecMax = nextInt();
if (secMax > mid && rightSecMax != secMax) {
end = mid;
prev = leftSecMax;
} else if (secMax < mid && leftSecMax != secMax) {
begin = mid;
prev = rightSecMax;
} else if (secMax == leftSecMax) {
end = mid;
prev = leftSecMax;
} else {
begin = mid;
prev = rightSecMax;
}
}
writer.println("! " + begin);
}
String nextToken() throws IOException {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
return tokenizer.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
StringTokenizer tokenizer;
PrintWriter writer;
BufferedReader reader;
public void run() {
try {
writer = new PrintWriter(System.out);
reader = new BufferedReader(new InputStreamReader(System.in));
solve();
reader.close();
writer.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new C().run();
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
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
|
4bf95191da8f8fddf42f2b0a388c698b
|
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
|
//Implemented By Aman Kotiyal Date:-19-Feb-2021 Time:-1:07:15 am
import java.io.*;
import java.util.*;
public class ques1
{
public static void main(String[] args)throws Exception{ new ques1().run();}
long mod=1000000000+7;
void solve() throws Exception
{
int n=ni();
int l=1,r=n;
out.println("? "+l+" "+r);
out.flush();
int ind=ni();
int sec = ind;
int cnt=1;
if(sec!=1&&sec!=n)
{
out.println("? "+l+" "+sec);
out.flush();
ind=ni();
if(ind==sec) // left side
r=sec;
else// right side
l=sec;
cnt++;
}
int ans=1;
if(sec==n-1)
ans=n;
while(l<=r)
{
int mid=(l+r)/2;
if(sec<mid)
{
cnt++;
out.println("? "+sec+" "+mid);
out.flush();
ind=ni();
if(ind==sec)
{
r=mid-1;
ans=mid;
}
else
{
l=mid+1;
ans=mid+1;
}
}
else if(sec>mid)
{
cnt++;
out.println("? "+mid+" "+sec);
out.flush();
ind=ni();
if(ind==sec)
{
l=mid+1;
ans=mid;
}
else
{
r=mid-1;
ans=mid-1;
}
}
else
{
if(l+1==r)
{
out.println("? "+l+" "+r);
out.flush();
ind=ni();
if(sec==ind)
{
if(sec==l)
ans=r;
if(sec==r)
ans=l;
}
break;
}
break;
}
}
out.println("! "+ans);
out.flush();
}
/*FAST INPUT OUTPUT & METHODS BELOW*/
private byte[] buf=new byte[1024];
private int index;
private InputStream in;
private int total;
private SpaceCharFilter filter;
PrintWriter out;
int min(int... ar){int min=Integer.MAX_VALUE;for(int i:ar)min=Math.min(min, i);return min;}
long min(long... ar){long min=Long.MAX_VALUE;for(long i:ar)min=Math.min(min, i);return min;}
int max(int... ar) {int max=Integer.MIN_VALUE;for(int i:ar)max=Math.max(max, i);return max;}
long max(long... ar) {long max=Long.MIN_VALUE;for(long i:ar)max=Math.max(max, i);return max;}
void reverse(int a[]){for(int i=0;i<a.length>>1;i++){int tem=a[i];a[i]=a[a.length-1-i];a[a.length-1-i]=tem;}}
void reverse(long a[]){for(int i=0;i<a.length>>1;i++){long tem=a[i];a[i]=a[a.length-1-i];a[a.length-1-i]=tem;}}
String reverse(String s){StringBuilder sb=new StringBuilder(s);sb.reverse();return sb.toString();}
void shuffle(int a[]) {
ArrayList<Integer> al = new ArrayList<>();
for(int i=0;i<a.length;i++)
al.add(a[i]);
Collections.sort(al);
for(int i=0;i<a.length;i++)
a[i]=al.get(i);
}
long lcm(long a,long b)
{
return (a*b)/(gcd(a,b));
}
int gcd(int a, int b)
{
if (a == 0)
return b;
return gcd(b%a, a);
}
long gcd(long a, long b)
{
if (a == 0)
return b;
return gcd(b%a, a);
}
/* for (1/a)%mod = ( a^(mod-2) )%mod ----> use expo to calc -->(a^(mod-2)) */
long expo(long p,long q) /* (p^q)%mod */
{
long z = 1;
while (q>0) {
if (q%2 == 1) {
z = (z * p)%mod;
}
p = (p*p)%mod;
q >>= 1;
}
return z;
}
void run()throws Exception
{
in=System.in; out = new PrintWriter(System.out);
solve();
out.flush();
}
private int scan()throws IOException
{
if(total<0)
throw new InputMismatchException();
if(index>=total)
{
index=0;
total=in.read(buf);
if(total<=0)
return -1;
}
return buf[index++];
}
private int ni() throws IOException
{
int c = scan();
while (isSpaceChar(c))
c = scan();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = scan();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = scan();
} while (!isSpaceChar(c));
return res * sgn;
}
private long nl() throws IOException
{
long num = 0;
int b;
boolean minus = false;
while ((b = scan()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
;
if (b == '-') {
minus = true;
b = scan();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = scan();
}
}
private double nd() throws IOException{
return Double.parseDouble(ns());
}
private String ns() throws IOException {
int c = scan();
while (isSpaceChar(c))
c = scan();
StringBuilder res = new StringBuilder();
do {
if (Character.isValidCodePoint(c))
res.appendCodePoint(c);
c = scan();
} while (!isSpaceChar(c));
return res.toString();
}
private String nss() throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
return br.readLine();
}
private char nc() throws IOException
{
int c = scan();
while (isSpaceChar(c))
c = scan();
return (char) c;
}
private boolean isWhiteSpace(int n)
{
if(n==' '||n=='\n'||n=='\r'||n=='\t'||n==-1)
return true;
return false;
}
private boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return isWhiteSpace(c);
}
private interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
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
|
a67e31603595d4420ba7e8d96c884e24
|
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
|
/**
* Created by Himanshu
**/
import java.util.*;
import java.io.*;
import java.math.*;
public class C1486 {
static Reader s = new Reader();
public static void main(String[] args) throws IOException {
int n = s.i();
if (n == 1) {
System.out.println("! "+1);
System.out.flush();
return;
}
int start = 1, end = n;
while (start <= end) {
if (start == end) {
System.out.println("! " + start);
System.out.flush();
return;
}
if (end-start == 1) {
int x = query(start,end);
if (x == start) System.out.println("! " + end);
else System.out.println("! " + start);
System.out.flush();
break;
}
int x = query(start,end);
int mid = (start+end)/2;
if (x > mid) {
if (mid+1 == end) {
int y = query(mid,end);
if (x == y) {
System.out.println("! "+mid);
} else {
System.out.println("! "+start);
}
System.out.flush();
break;
}
int y = query(mid+1,end);
if (x == y) start = mid+1;
else end = mid;
} else {
int y = query(start,mid);
if (x == y) {
if (x == mid) end = mid-1;
else end = mid;
}
else start = mid+1;
}
// if (x > start && x < end) {
// int y = query(start,x);
// if (x == y) end = x-1;
// else start = x+1;
// } else if (x == start) {
// start = x+1;
// } else end = x-1;
}
}
private static int query(int l , int r) {
System.out.println("? " + l + " " + r);
System.out.flush();
return s.i();
}
public static void shuffle(long[] arr) {
int n = arr.length;
Random rand = new Random();
for (int i = 0; i < n; i++) {
long temp = arr[i];
int randomPos = i + rand.nextInt(n - i);
arr[i] = arr[randomPos];
arr[randomPos] = temp;
}
}
private static int gcd(int a, int b) {
if(b == 0) return a;
return gcd(b,a%b);
}
public static long nCr(long[] fact, long[] inv, int n, int r, long mod) {
if (n < r)
return 0;
return ((fact[n] * inv[n - r]) % mod * inv[r]) % mod;
}
private static void factorials(long[] fact, long[] inv, long mod, int n) {
fact[0] = 1;
inv[0] = 1;
for (int i = 1; i <= n; ++i) {
fact[i] = (fact[i - 1] * i) % mod;
inv[i] = power(fact[i], mod - 2, mod);
}
}
private static long power(long a, long n, long p) {
long result = 1;
while (n > 0) {
if (n % 2 == 0) {
a = (a * a) % p;
n /= 2;
} else {
result = (result * a) % p;
n--;
}
}
return result;
}
private static long power(long a, long n) {
long result = 1;
while (n > 0) {
if (n % 2 == 0) {
a = (a * a);
n /= 2;
} else {
result = (result * a);
n--;
}
}
return result;
}
private static long query(long[] tree, int in, int start, int end, int l, int r) {
if (start >= l && r >= end) return tree[in];
if (end < l || start > r) return 0;
int mid = (start + end) / 2;
long x = query(tree, 2 * in, start, mid, l, r);
long y = query(tree, 2 * in + 1, mid + 1, end, l, r);
return x + y;
}
private static void update(int[] arr, long[] tree, int in, int start, int end, int idx, int val) {
if (start == end) {
tree[in] = val;
arr[idx] = val;
return;
}
int mid = (start + end) / 2;
if (idx > mid) update(arr, tree, 2 * in + 1, mid + 1, end, idx, val);
else update(arr, tree, 2 * in, start, mid, idx, val);
tree[in] = tree[2 * in] + tree[2 * in + 1];
}
private static void build(int[] arr, long[] tree, int in, int start, int end) {
if (start == end) {
tree[in] = arr[start];
return;
}
int mid = (start + end) / 2;
build(arr, tree, 2 * in, start, mid);
build(arr, tree, 2 * in + 1, mid + 1, end);
tree[in] = (tree[2 * in + 1] + tree[2 * in]);
}
static class Reader {
private InputStream mIs;
private byte[] buf = new byte[1024];
private int curChar, numChars;
public Reader() {
this(System.in);
}
public Reader(InputStream is) {
mIs = is;
}
public int read() {
if (numChars == -1) throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = mIs.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) return -1;
}
return buf[curChar++];
}
public String nextLine() {
int c = read();
while (isSpaceChar(c)) c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public String s() {
int c = read();
while (isSpaceChar(c)) c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public long l() {
int c = read();
while (isSpaceChar(c)) c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9') throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int i() {
int c = read();
while (isSpaceChar(c)) c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public double d() throws IOException {
return Double.parseDouble(s());
}
public boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
public int[] arr(int n) {
int[] ret = new int[n];
for (int i = 0; i < n; i++) {
ret[i] = i();
}
return ret;
}
public long[] arrLong(int n) {
long[] ret = new long[n];
for (int i = 0; i < n; i++) {
ret[i] = l();
}
return ret;
}
}
// static class pairLong implements Comparator<pairLong> {
// long first, second;
//
// pairLong() {
// }
//
// pairLong(long first, long second) {
// this.first = first;
// this.second = second;
// }
//
// @Override
// public int compare(pairLong p1, pairLong p2) {
// if (p1.first == p2.first) {
// if(p1.second > p2.second) return 1;
// else return -1;
// }
// if(p1.first > p2.first) return 1;
// else return -1;
// }
// }
// static class pair implements Comparator<pair> {
// int first, second;
//
// pair() {
// }
//
// pair(int first, int second) {
// this.first = first;
// this.second = second;
// }
//
// @Override
// public int compare(pair p1, pair p2) {
// if (p1.first == p2.first) return p1.second - p2.second;
// return p1.first - p2.first;
// }
// }
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
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
|
10eb22f5347214256f5fee203f7431e3
|
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 TEST
{
static class Reader
{
final private int BUFFER_SIZE = 1 << 16;
Scanner scan = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
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 nextString() throws IOException
{
String str00 = scan.next();
return str00;
}
public String readLine() throws IOException
{
byte[] buf = new byte[64];
int cnt = 0, c;
while ((c = read()) != -1)
{
if (c == '\n')
break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
String next() throws IOException
{
int c;
for (c = read(); c <= 32; c = read());
StringBuilder sb = new StringBuilder();
for (; c > 32; c = read())
{
sb.append((char) c);
}
return sb.toString();
}
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();
}
public int[] nextArray(int n) throws IOException
{
int[] a=new int[n];
for (int i=0;i<n;i++)
{
a[i]=nextInt();
}
return a;
}
public long[] nextArrayl(int n) throws IOException
{
long[] a = new long[n];
for (int i=0;i<n;i++)
{
a[i]=nextLong();
}
return a;
}
}
public static void sort(long a[])
{
int n=a.length;
Long d[]=new Long[n];
for(int i=0;i<n;i++)
{
d[i]=a[i];
}
Arrays.sort(d);
for(int i=0;i<n;i++)
{
a[i]=d[i];
}
}
public static void sort(int a[])
{
int n=a.length;
Integer d[]=new Integer[n];
for(int i=0;i<n;i++)
{
d[i]=a[i];
}
Arrays.sort(d);
for(int i=0;i<n;i++)
{
a[i]=d[i];
}
}
public static void main(String args[])throws IOException
{
Reader re=new Reader();
int n=re.nextInt();
int l=1,r=n;
while(l<r-1)
{
System.out.println("? "+l+" "+r);
System.out.flush();
int p=re.nextInt();
int m=(l+r)/2;
int i,j;
if(p>=l && p<=m)
{
System.out.println("? "+l+" "+m);
System.out.flush();
i=re.nextInt();
if(p==i)
{
r=m;
}
else
{
l=m;
}
}
else
{
System.out.println("? "+m+" "+r);
System.out.flush();
i=re.nextInt();
if(p==i)
{
l=m;
}
else
{
r=m;
}
}
}
System.out.println("? "+l+" "+r);
System.out.flush();
int i=re.nextInt();
int ans=l^r^i;
System.out.println("! "+ans);
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
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
|
fcc1c6d13ff236fcf2eb0522c83554d6
|
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.lang.Math;
import java.util.*;
import javax.management.ValueExp;
public final class Codechef {
static BufferedReader br = new BufferedReader(
new InputStreamReader(System.in)
);
static BufferedWriter bw = new BufferedWriter(
new OutputStreamWriter(System.out)
);
static StringTokenizer st;
static int mod = 1000000007;
/*write your constructor and global variables here*/
static class sortCond implements Comparator<Pair<Integer, Integer>> {
@Override
public int compare(Pair<Integer, Integer> p1, Pair<Integer, Integer> p2) {
if (p1.a <= p2.a) {
return -1;
} else {
return 1;
}
}
}
static class sortCond1 implements Comparator<Integer> {
@Override
public int compare(Integer p1, Integer p2) {
if (p1 <= p2) {
return 1;
} else {
return -1;
}
}
}
static class Rec {
int a;
int b;
long c;
Rec(int a, int b, long c) {
this.a = a;
this.b = b;
this.c = c;
}
}
static class Pair<f, s> {
f a;
s b;
Pair(f a, s b) {
this.a = a;
this.b = b;
}
}
interface modOperations {
int mod(int a, int b, int mod);
}
static int findBinaryExponentian(int a, int pow, int mod) {
if (pow == 1) {
return a;
} else if (pow == 0) {
return 1;
} else {
int retVal = findBinaryExponentian(a, (int) pow / 2, mod);
int val = (pow % 2 == 0) ? 1 : a;
return modMul.mod(modMul.mod(retVal, retVal, mod), val, mod);
}
}
static int findPow(int a, int b, int mod) {
if (b == 1) {
return a % mod;
} else if (b == 0) {
return 1;
} else {
int res = findPow(a, (int) b / 2, mod);
return modMul.mod(res, modMul.mod(res, (b % 2 == 1 ? a : 1), mod), mod);
}
}
static int bleft(int ele, int[] arr) {
int l = 0;
int h = arr.length - 1;
int ans = -1;
while (l <= h) {
int mid = l + (int) (h - l) / 2;
int val = arr[mid];
if (ele > val) {
l = mid + 1;
} else if (ele < val) {
h = mid - 1;
} else {
ans = mid;
h = mid - 1;
}
}
return ans;
}
static int gcd(int a, int b) {
int div = b;
int rem = a % b;
while (rem != 0) {
int temp = rem;
rem = div % rem;
div = temp;
}
return div;
}
static long[] log(long no, long n) {
long i = 1;
int cnt = 0;
long sum = 0l;
long arr[] = new long[2];
while (i < no) {
sum += i;
cnt++;
if (sum == n) {
arr[0] = 1l * cnt;
arr[1] = sum;
break;
}
i *= 2l;
}
if (arr[0] == 0) {
arr[0] = cnt;
arr[1] = sum;
}
return arr;
}
static modOperations modAdd = (int a, int b, int mod) -> {
return (a % mod + b % mod) % mod;
};
static modOperations modSub = (int a, int b, int mod) -> {
return (int) ((1l * a % mod - 1l * b % mod + 1l * mod) % mod);
};
static modOperations modMul = (int a, int b, int mod) -> {
return (int) ((1l * (a % mod) * 1l * (b % mod)) % (1l * mod));
};
static modOperations modDiv = (int a, int b, int mod) -> {
return modMul.mod(a, findBinaryExponentian(b, mod - 1, mod), mod);
};
static HashSet<Integer> primeList(int MAXI) {
int[] prime = new int[MAXI + 1];
HashSet<Integer> obj = new HashSet<>();
for (int i = 2; i <= (int) Math.sqrt(MAXI) + 1; i++) {
if (prime[i] == 0) {
obj.add(i);
for (int j = i * i; j <= MAXI; j += i) {
prime[j] = 1;
}
}
}
for (int i = (int) Math.sqrt(MAXI) + 1; i <= MAXI; i++) {
if (prime[i] == 0) {
obj.add(i);
}
}
return obj;
}
static int[] factorialList(int MAXI, int mod) {
int[] factorial = new int[MAXI + 1];
factorial[0] = factorial[1] = 1;
factorial[2] = 2;
for (int i = 3; i < MAXI + 1; i++) {
factorial[i] = modMul.mod(factorial[i - 1], i, mod);
}
return factorial;
}
static void put(HashMap<Integer, Integer> cnt, int key) {
if (cnt.containsKey(key)) {
cnt.replace(key, cnt.get(key) + 1);
} else {
cnt.put(key, 1);
}
}
static long arrSum(ArrayList<Long> arr) {
long tot = 0;
for (int i = 0; i < arr.size(); i++) {
tot += arr.get(i);
}
return tot;
}
static int ord(char b) {
return (int) b - (int) 'a';
}
static int optimSearch(int[] cnt, int lower_bound, int pow, int n) {
int l = lower_bound + 1;
int h = n;
int ans = 0;
while (l <= h) {
int mid = l + (h - l) / 2;
if (cnt[mid] - cnt[lower_bound] == pow) {
return mid;
} else if (cnt[mid] - cnt[lower_bound] < pow) {
ans = mid;
l = mid + 1;
} else {
h = mid - 1;
}
}
return ans;
}
static Pair<Long, Integer> ret_ans(ArrayList<Integer> ans) {
int size = ans.size();
int mini = 1000000000 + 1;
long tit = 0l;
for (int i = 0; i < size; i++) {
tit += 1l * ans.get(i);
mini = Math.min(mini, ans.get(i));
}
return new Pair<>(tit - mini, mini);
}
static int factorList(
HashMap<Integer, Integer> maps,
int no,
int maxK,
int req
) {
int i = 1;
while (i * i <= no) {
if (no % i == 0) {
if (i != no / i) {
put(maps, no / i);
}
put(maps, i);
if (maps.get(i) == req) {
maxK = Math.max(maxK, i);
}
if (maps.get(no / i) == req) {
maxK = Math.max(maxK, no / i);
}
}
i++;
}
return maxK;
}
static ArrayList<Integer> getKeys(HashMap<Integer, Integer> maps) {
ArrayList<Integer> vals = new ArrayList<>();
for (Map.Entry<Integer, Integer> map : maps.entrySet()) {
vals.add(map.getKey());
}
return vals;
}
static ArrayList<Integer> getValues(HashMap<Integer, Integer> maps) {
ArrayList<Integer> vals = new ArrayList<>();
for (Map.Entry<Integer, Integer> map : maps.entrySet()) {
vals.add(map.getValue());
}
return vals;
}
static int getMax(ArrayList<Integer> arr) {
int max = arr.get(0);
for (int i = 1; i < arr.size(); i++) {
if (arr.get(i) > max) {
max = arr.get(i);
}
}
return max;
}
static int getMin(ArrayList<Integer> arr) {
int max = arr.get(0);
for (int i = 1; i < arr.size(); i++) {
if (arr.get(i) < max) {
max = arr.get(i);
}
}
return max;
}
static void bitRep(int n, int no) throws IOException {
int curr = (int) Math.pow(2, n - 1);
for (int i = n - 1; i >= 0; i--) {
if ((curr & no) != 0) {
bw.write("1");
} else {
bw.write("0");
}
curr /= 2;
}
bw.write("\n");
}
static ArrayList<Integer> retPow(int MAXI) {
long curr = 1l;
ArrayList<Integer> arr = new ArrayList<>();
for (int i = 1; i <= MAXI; i++) {
curr *= 2l;
curr = curr % mod;
arr.add((int) curr);
}
return arr;
}
static String is(int no) {
return Integer.toString(no);
}
static String ls(long no) {
return Long.toString(no);
}
static int pi(String s) {
return Integer.parseInt(s);
}
static long pl(String s) {
return Long.parseLong(s);
}
/*write your methods and classes here*/
public static void main(String[] args) throws IOException {
int n = pi(br.readLine());
int l = 1;
int h = n;
while (l < h) {
bw.write("? " + is(l) + " " + is(h) + "\n");
bw.flush();
int temp = -1;
int pos = pi(br.readLine());
if (h - l == 1) {
if (pos == l) {
l++;
} else {
h--;
}
continue;
}
int mid = l + (h - l) / 2;
if (pos <= mid) {
if (l == mid) {
l = mid + 1;
} else {
bw.write("? " + is(l) + " " + is(mid) + "\n");
bw.flush();
temp = pi(br.readLine());
if (pos == temp) {
h = mid;
} else {
l = mid + 1;
}
}
} else {
if (h == mid + 1) {
h = mid;
} else {
bw.write("? " + is(mid + 1) + " " + is(h) + "\n");
bw.flush();
temp = pi(br.readLine());
if (pos == temp) {
l = mid + 1;
} else {
h = mid;
}
}
}
}
bw.write("! " + is(l) + "\n");
bw.flush();
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
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
|
6bd552f59353f620afd8f3ac9d1aaeda
|
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 GuessingTheGreatest {
static FastScanner fs;
static FastWriter fw;
static boolean checkOnlineJudge = System.getProperty("ONLINE_JUDGE") == null;
private static final int iMax = (int) (1e9), iMin = (int) (-1e9);
private static final long lMax = (int) (1e15), lMin = (int) (-1e15);
private static final int mod = (int) (1e9 + 7);
public static void main(String[] args) throws IOException {
fs = new FastScanner();
fw = new FastWriter();
int t = 1;
//t = fs.nextInt();
while (t-- > 0) {
solve();
}
fw.out.close();
}
private static void solve() {
int l = 1, r = fs.nextInt();
while (r - l > 1) {
int mid = l + ((r - l) / 2);
int idx = ask(l, r);
if (idx >= l && idx <= mid) {
int temp = ask(l, mid);
if (temp == idx) {
r = mid;
} else {
l = mid;
}
} else {
int temp = ask(mid, r);
if (temp == idx) {
l = mid;
} else {
r = mid;
}
}
}
int idx = ask(l, r);
if (idx == l) {
fw.out.println("! " + r);
} else {
fw.out.println("! " + l);
}
}
private static int ask(int l, int r) {
fw.out.println("? " + l + " " + r);
fw.out.flush();
return fs.nextInt();
}
private static class UnionFind {
private final int[] parent;
UnionFind(int n) {
parent = new int[n];
for (int i = 0; i < n; i++)
parent[i] = i;
}
private int getParent(int i) {
if (parent[i] == i)
return i;
return parent[i] = getParent(parent[i]);
}
private void unify(int i, int j) {
int p1 = getParent(i);
int p2 = getParent(j);
if (p1 != p2)
parent[p1] = p2;
}
}
private static int gcd(int a, int b) {
return (b == 0 ? a : gcd(b, a % b));
}
private static long pow(long a, long b) {
long result = 1;
while (b > 0) {
if ((b & 1L) == 1) {
result = (result * a) % mod;
}
a = (a * a) % mod;
b >>= 1;
}
return result;
}
private static int ceilDiv(int a, int b) {
return ((a + b - 1) / b);
}
private static List<Integer> primes(int n) {
boolean[] primeArr = new boolean[n + 5];
Arrays.fill(primeArr, true);
for (int i = 2; (i * i) <= n; i++) {
if (primeArr[i]) {
for (int j = i * i; j <= n; j += i) {
primeArr[j] = false;
}
}
}
List<Integer> primeList = new ArrayList<>();
for (int i = 2; i <= n; i++) {
if (primeArr[i])
primeList.add(i);
}
return primeList;
}
private static class Pair<U, V> {
private final U first;
private final V second;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Pair<?, ?> pair = (Pair<?, ?>) o;
return first.equals(pair.first) && second.equals(pair.second);
}
@Override
public int hashCode() {
return Objects.hash(first, second);
}
@Override
public String toString() {
return "(" + first + ", " + second + ")";
}
private Pair(U ff, V ss) {
this.first = ff;
this.second = ss;
}
}
private static <T> void randomizeArr(T[] arr, int n) {
Random r = new Random();
for (int i = (n - 1); i > 0; i--) {
int j = r.nextInt(i + 1);
swap(arr, i, j);
}
}
private static Integer[] readIntArray(int n) {
Integer[] arr = new Integer[n];
for (int i = 0; i < n; i++)
arr[i] = fs.nextInt();
return arr;
}
private static List<Integer> readIntList(int n) {
List<Integer> list = new ArrayList<>();
for (int i = 0; i < n; i++)
list.add(fs.nextInt());
return list;
}
private static <T> void swap(T[] arr, int i, int j) {
T temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
private static <T> void displayArr(T[] arr) {
for (T x : arr)
fw.out.print(x + " ");
fw.out.println();
}
private static <T> void displayList(List<T> list) {
for (T x : list)
fw.out.print(x + " ");
fw.out.println();
}
private static class FastScanner {
BufferedReader br;
StringTokenizer st;
FastScanner() throws IOException {
if (checkOnlineJudge)
this.br = new BufferedReader(new FileReader("src/input.txt"));
else
this.br = new BufferedReader(new InputStreamReader(System.in));
this.st = new StringTokenizer("");
}
public String next() {
while (!st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException err) {
err.printStackTrace();
}
}
return st.nextToken();
}
public String nextLine() {
if (st.hasMoreTokens()) {
return st.nextToken("").trim();
}
try {
return br.readLine().trim();
} catch (IOException err) {
err.printStackTrace();
}
return "";
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
private static class FastWriter {
PrintWriter out;
FastWriter() throws IOException {
if (checkOnlineJudge)
out = new PrintWriter(new FileWriter("src/output.txt"));
else
out = new PrintWriter(System.out);
}
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
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
|
5c4d9ddb4bb0aca696d2d1bfc0e408ed
|
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.util.StringTokenizer;
import static java.lang.System.in;
import static java.lang.System.out;
public class Main {
public static void main(String[] args){
FastReader fr=new FastReader();
int tc=1;
while(tc-->0){
int n=fr.nextInt();
int sm=query(1,n,fr);
if(sm!=1 && query(1,sm,fr)==sm){
int l=1,r=sm-1;
while(l<=r){
int mid=(l+r)/2;
if(query(mid,sm,fr)==sm){
l=mid+1;
}else{
r=mid-1;
}
}
out.println("! "+r);
}else{
int l=sm+1,r=n;
while(l<=r){
int mid=(l+r)/2;
if(query(sm,mid,fr)==sm){
r=mid-1;
}else{
l=mid+1;
}
}
out.println("! "+l);
}
out.flush();
}
}
static int query(int l,int r,FastReader fr){
out.println("? "+l+" "+r);
out.flush();
return fr.nextInt();
}
static class FastReader{
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(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());
}
byte nextByte(){
return Byte.parseByte(next());
}
Float nextFloat(){
return Float.parseFloat(next());
}
long nextLong(){
return Long.parseLong(next());
}
double nextDouble(){
return Double.parseDouble(next());
}
short nextShort(){
return Short.parseShort(next());
}
Boolean nextbol(){
return Boolean.parseBoolean(next());
}
String nextLine(){
String str = "";
try{
str = br.readLine();
}
catch (IOException e){
e.printStackTrace();
}
return str;
}
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
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
|
7c013589617b3754a45bc31b942911c0
|
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 tank {
//static StringBuilder IO = new StringBuilder();
//static final Scanner scan = new Scanner(System.in);
static final FastScanner fs = new FastScanner();
public static void main(String[] args) {
// int t = fs.nextInt();
// while(t-->0){
// SLV();
// }
SLV();
//System.out.println(IO);
}
static void SLV(){
int n = fs.nextInt();
int smax = ask(1, n);
System.out.println("! " + fn(1, n, smax));
}
static int fn(int l ,int r, int smax){
int mid = (l + r)/2;
if(r == l) return l;
if(l == r - 1){
if(smax == l) return r;
else return l;
}
if(smax <= mid){
int tmp = ask(l , mid);
if(tmp == smax) return fn(l, mid, tmp);
else return fn(mid + 1, r, ask(mid+1, r));
}else{
if(mid == r - 1) return fn(l, mid, ask(l, mid));
int tmp = ask(mid + 1, r);
if(tmp == smax) return fn(mid + 1, r, tmp);
else return fn(l, mid, ask(l, mid));
}
}
static int ask(int l, int r){
if(l == r) return l;
System.out.println("? " + l + " " + r);
int num = fs.nextInt();
System.out.flush();
return num;
}
static class FastScanner {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st=new StringTokenizer("");
String next() {
while (!st.hasMoreTokens())
try {
st=new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
int[] readArray(int n) {
int[] a=new int[n];
for (int i=0; i<n; i++) a[i]=nextInt();
return a;
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
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
|
6e65de34611d6ddbd96fa0d07dd0842e
|
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 Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int l = 1, r = n;
System.out.flush();
while (l < r) {
int m = (l + r) / 2;
System.out.println("?" + " " + l + " " + r);
int x = sc.nextInt();
if (r - l == 1) {
if (x == l) {
System.out.println("! " + r);
return;
} else {
System.out.println("! " + l);
return;
}
}
if (r - l == 2) {
if (x <= m) {
System.out.println("?" + " " + l + " " + (l + 1));
int temp = sc.nextInt();
if (temp == x) {
if (l == x) {
System.out.println("! " + (l + 1));
return;
} else {
System.out.println("! " + l);
return;
}
} else {
System.out.println("! " + r);
return;
}
} else {
r = l + 1;
continue;
}
}
if (x <= m) {
System.out.println("?" + " " + l + " " + m);
int temp = sc.nextInt();
if (temp == x) {
r = m;
} else {
l = m + 1;
}
continue;
} else {
System.out.println("?" + " " + (m + 1) + " " + r);
int temp = sc.nextInt();
if (temp == x) {
l = m + 1;
} else {
r = m;
}
continue;
}
}
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
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
|
66fbc3e220dc86f602eba576b0997b95
|
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.io.PrintStream;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Jaynil
*/
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);
C1GuessingTheGreatestEasyVersion solver = new C1GuessingTheGreatestEasyVersion();
solver.solve(1, in, out);
out.close();
}
static class C1GuessingTheGreatestEasyVersion {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
int l = 1;
int r = n;
while (l < r) {
int m = (l + r) / 2;
System.out.println("?" + " " + l + " " + r);
int pos = in.nextInt();
if (r - l == 1) {
if (pos == l) {
System.out.println("! " + r);
return;
} else {
System.out.println("! " + l);
return;
}
}
if (r - l == 2) {
if (pos <= m) {
System.out.println("?" + " " + l + " " + (l + 1));
int temp = in.nextInt();
if (temp == pos) {
if (l == pos) {
System.out.println("! " + (l + 1));
return;
} else {
System.out.println("! " + l);
return;
}
} else {
System.out.println("! " + r);
return;
}
} else {
r = l + 1;
continue;
}
}
if (pos <= m) {
System.out.println("?" + " " + l + " " + m);
int temp = in.nextInt();
if (temp == pos) {
r = m;
} else {
l = m + 1;
}
continue;
} else {
System.out.println("?" + " " + (m + 1) + " " + r);
int temp = in.nextInt();
if (temp == pos) {
l = m + 1;
} else {
r = m;
}
continue;
}
}
}
}
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 11
|
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
|
d1281fa97679ec49a7a1ce53c457d150
|
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 void bs(int start,int end,int ind) {
if((end-start)==1) {
if(start==ind) {
System.out.println("! "+(end+1));
}
else {
System.out.println("! "+(start+1));
}
return;
}
FastScanner f = new FastScanner();
int mid=(start+end)/2;
if(ind<=mid) {
System.out.println("? "+(start+1)+" "+(mid+1));
int place=f.nextInt()-1;
if(place==ind) {
bs(start,mid,place);
}
else {
System.out.println("? "+(mid+1)+" "+(end+1));
place=f.nextInt()-1;
bs(mid,end,place);
}
}
else {
System.out.println("? "+(mid+1)+" "+(end+1));
int place=f.nextInt()-1;
if(place==ind) {
bs(mid,end,place);
}
else {
System.out.println("? "+(start+1)+" "+(mid+1));
place=f.nextInt()-1;
bs(start,mid,place);
}
}
}
public static void main(String[] args) throws IOException
{
FastScanner f = new FastScanner();
int t=1;
// t=f.nextInt();
PrintWriter out=new PrintWriter(System.out);
int mod=1000000007;
while(t>0) {
t--;
int n=f.nextInt();
System.out.println("? "+1+" "+(n));
int ind=f.nextInt()-1;
bs(0,n-1,ind);
}
out.close();
}
static void sort(int [] a) {
ArrayList<Integer> q = new ArrayList<>();
for (int i: a) q.add(i);
Collections.sort(q);
for (int i = 0; i < a.length; i++) a[i] = q.get(i);
}
static class FastScanner {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st=new StringTokenizer("");
String next() {
while (!st.hasMoreTokens())
try {
st=new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
int[] readArray(int n) {
int[] a=new int[n];
for (int i=0; i<n; i++) a[i]=nextInt();
return a;
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
long[] readLongArray(int n) {
long[] a=new long[n];
for (int i=0; i<n; i++) a[i]=nextLong();
return a;
}
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
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
|
4e3250dcc0b2bd8e565d66347c29bbf5
|
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;
import static java.lang.System.out;
public class C1_GuessingTheGreatest_EasyVersion {
private static final BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
private static StringTokenizer st;
private static int readInt() throws IOException {
while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine());
return Integer.parseInt(st.nextToken());
}
public static void main(String[] args) throws IOException {
int n = readInt();
int low = 1;
int high = n;
while (low + 1 < high) {
int secondMaxPos = query(low, high);
int mid = low + high >> 1;
if (secondMaxPos <= mid) {
int newSecondMaxPos = query(low, mid);
if (newSecondMaxPos == secondMaxPos) {
high = mid;
} else {
low = mid;
}
} else {
int newSecondMaxPos = query(mid, high);
if (newSecondMaxPos == secondMaxPos) {
low = mid;
} else {
high = mid;
}
}
}
// low + 1 == high
int secondMaxPos = query(low, high);
answer(secondMaxPos == low ? high : low);
}
private static int query(int l, int r) throws IOException {
out.println("? " + l + " " + r);
out.flush();
return readInt();
}
private static void answer(int a) {
out.println("! " + a);
out.flush();
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
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
|
2cd9c3ffe664765faeae3f7bf761d8d9
|
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;
import static java.lang.System.getSecurityManager;
import static java.lang.System.out;
public class C1_ {
private static final BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
private static StringTokenizer st;
private static int readInt() throws IOException {
while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine());
return Integer.parseInt(st.nextToken());
}
public static void main(String[] args) throws IOException {
int n = readInt();
int low = 1;
int high = n;
while (low + 1 < high) {
int secondMaxPos = query(low, high);
int mid = Math.max(low + high >> 1, low + 1);
if (secondMaxPos <= mid) {
int newSecondMaxPos = query(low, mid);
if (newSecondMaxPos == secondMaxPos) {
high = mid;
} else {
low = mid + 1;
}
} else {
mid = Math.min(low + high >> 1, high - 1);
int newSecondMaxPos = query(mid, high);
if (newSecondMaxPos == secondMaxPos) {
low = mid;
} else {
high = mid - 1;
}
}
}
if (low == high) {
answer(low);
} else { // low + 1 == high
int secondMaxPos = query(low, high);
answer(secondMaxPos == low ? high : low);
}
}
private static int query(int l, int r) throws IOException {
out.println("? " + l + " " + r);
out.flush();
return readInt();
}
private static void answer(int a) {
out.println("! " + a);
out.flush();
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
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
|
81f6bbef5cc365f10db114db13cc5ae7
|
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.*;
/**
* Created on: Feb 18, 2021
* Questions: https://codeforces.com/contest/1486/problem/C1#
*/
public class GuessingTheGreatest {
public static void main(String[] args) {
Scanner sc = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
int s = 1, e = sc.nextInt(), ans = -1;
while (s < e) {
int idx = query(sc, s, e);
if (e - s + 1 <= 2) {
// If there are only two numbers between start and end.
if (idx == s) ans = s + 1;
else ans = s;
break;
}
int mid = (s + e) / 2;
if (idx <= mid) {
// If the second highest is on the left side, then make a call from start to mid
// If the call still returns the same idx then the highest is on the left side.
int idx2 = query(sc, s, mid);
if (idx2 == idx) e = mid;
else s = mid;
} else {
// If the call still returns the same idx then the highest is on the right side.
int idx2 = query(sc, mid, e);
if (idx2 == idx) s = mid;
else e = mid;
}
}
System.out.println("! " + ans);
}
private static int query(Scanner sc, int s, int e) {
if (s == e) return s;
System.out.println("? " + s + " " + e);
System.out.flush();
return sc.nextInt();
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
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
|
2511f865eb4873ada3db6ef1515cb3c1
|
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.lang.*;
public class C {
public static PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
static long MOD = (long) (1e9 + 7);
//static int MOD = 998244353;
static long MOD2 = MOD * MOD;
static FastReader sc = new FastReader();
static int pInf = Integer.MAX_VALUE;
static int nInf = Integer.MIN_VALUE;
public static void main(String[] args) {
int test = 1;
//test = sc.nextInt();
for (int i = 1; i <= test; i++){
//out.print("Case #"+i+": ");
solve();
}
out.flush();
out.close();
}
static long oo = (long) (1e16);
static void solve(){
int n = sc.nextInt();
int l = 1;
int r = n;
int ele = query(1,n);
int lele = -1;
int rele = -1;
if(ele>l){
lele = query(l,ele);
}
if(r>ele){
rele = query(ele,r);
}
if(lele==ele){
r = ele;
l--;
while(r-l>1){
int m = l+(r-l)/2;
int idx = query(m,ele);
if(idx==ele){
l = m;
}else{
r = m;
}
}
out.println("! "+l);
out.flush();
}else if(rele==ele){
l = ele;
r++;
while(r-l>1){
int m = l+(r-l)/2;
int idx = query(ele,m);
if(idx==ele){
r = m;
}else{
l = m;
}
}
out.println("! "+r);
out.flush();
}
}
static int query(int l,int r){
out.println("? "+l+" "+r);
out.flush();
return sc.nextInt();
}
static long nC2(long n) {
return add((n * (n + 1)) / 2, 0);
}
public static long mul(long a, long b) {
return ((a % MOD) * (b % MOD)) % MOD;
}
public static long add(long a, long b) {
return ((a % MOD) + (b % MOD)) % MOD;
}
public static long c2(long n) {
if ((n & 1) == 0) {
return mul(n / 2, n - 1);
} else {
return mul(n, (n - 1) / 2);
}
}
//Pair Class
static class Pair implements Comparable<Pair> {
int x;
int y;
public Pair(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public int compareTo(Pair o) {
if ((this.x == o.x)) {
return (this.y - o.y);
}
return (this.x - o.x);
}
}
//Shuffle Sort
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);
}
//Brian Kernighans Algorithm
static long countSetBits(long n) {
if (n == 0) return 0;
return 1 + countSetBits(n & (n - 1));
}
//Euclidean Algorithm
static long gcd(long A, long B) {
if (B == 0) return A;
return gcd(B, A % B);
}
//Modular Exponentiation
static long fastExpo(long x, long n) {
if (n == 0) return 1;
if ((n & 1) == 0) return fastExpo((x * x) % MOD, n / 2) % MOD;
return ((x % MOD) * fastExpo((x * x) % MOD, (n - 1) / 2)) % MOD;
}
//AKS Algorithm
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 <= Math.sqrt(n); i += 6)
if (n % i == 0 || n % (i + 2) == 0) return false;
return true;
}
public static long modinv(long x) {
return modpow(x, MOD - 2);
}
public static long modpow(long a, long b) {
if (b == 0) {
return 1;
}
long x = modpow(a, b / 2);
x = (x * x) % MOD;
if (b % 2 == 1) {
return (x * a) % MOD;
}
return x;
}
public static class FastReader {
BufferedReader br;
StringTokenizer st;
//it reads the data about the specified point and divide the data about it ,it is quite fast
//than using direct
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception r) {
r.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());//converts string to integer
}
double nextDouble() {
return Double.parseDouble(next());
}
long nextLong() {
return Long.parseLong(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (Exception r) {
r.printStackTrace();
}
return str;
}
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
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
|
acf99f9385d2befceb338deaad1f6b54
|
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.*;
import java.math.*;
import java.awt.geom.*;
import static java.lang.Math.*;
public class Solution implements Runnable {
long mod1 = (long) 1e9 + 7;
int mod2 = 998244353;
public void solve() throws Exception {
int n=sc.nextInt();
int start=1;
int end=n;
boolean flag=false;
while(start<end) {
if(end-start==1) {
int take=query(start,end);
if(start==take) {
print(end);
}
else {
print(start);
}
flag=true;
break;
}
int mid=(start+end)/2;
int get = query(start,end);
if(get<=mid) {
int get1 = query(start,mid);
if(get==get1) {
end=mid;
}
else {
start=mid+1;
}
}
else {
int get1 = query(mid,end);
if(get==get1) {
start=mid;
}
else {
end=mid-1;
}
}
}
if(!flag)
print(start);
}
public void print(int x) {
System.out.println("! "+x);
System.out.flush();
}
public int query(int l,int r) throws Exception{
System.out.print("? "+l+" "+r);
System.out.println();
System.out.flush();
int x=sc.nextInt();
return x;
}
static long gcd(long a, long b) {
if (a == 0)
return b;
return gcd(b % a, a);
}
static void sort(int[] a) {
ArrayList<Integer> l = new ArrayList<>();
for (int i : a)
l.add(i);
Collections.sort(l);
for (int i = 0; i < a.length; i++)
a[i] = l.get(i);
}
static long ncr(int n, int r, long p) {
if (r > n)
return 0l;
if (r > n - r)
r = n - r;
long C[] = new long[r + 1];
C[0] = 1;
for (int i = 1; i <= n; i++) {
for (int j = Math.min(i, r); j > 0; j--)
C[j] = (C[j] + C[j - 1]) % p;
}
return C[r] % p;
}
void sieveOfEratosthenes(boolean prime[], int size) {
for (int i = 0; i < size; i++)
prime[i] = true;
for (int p = 2; p * p < size; p++) {
if (prime[p] == true) {
for (int i = p * p; i < size; i += p)
prime[i] = false;
}
}
}
static int LowerBound(int a[], int x) { // smallest index having value >= x
int l = -1, r = a.length;
while (l + 1 < r) {
int m = (l + r) >>> 1;
if (a[m] >= x)
r = m;
else
l = m;
}
return r;
}
static int UpperBound(int a[], int x) {// biggest index having value <= x
int l = -1, r = a.length;
while (l + 1 < r) {
int m = (l + r) >>> 1;
if (a[m] <= x)
l = m;
else
r = m;
}
return l + 1;
}
public long power(long x, long y, long p) {
long res = 1;
// out.println(x+" "+y);
x = x % p;
if (x == 0)
return 0;
while (y > 0) {
if ((y & 1) == 1)
res = (res * x) % p;
y = y >> 1;
x = (x * x) % p;
}
return res;
}
static Throwable uncaught;
BufferedReader in;
FastScanner sc;
PrintWriter out;
@Override
public void run() {
try {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
sc = new FastScanner(in);
solve();
} catch (Throwable uncaught) {
Solution.uncaught = uncaught;
} finally {
out.close();
}
}
public static void main(String[] args) throws Throwable {
Thread thread = new Thread(null, new Solution(), "", (1 << 26));
thread.start();
thread.join();
if (Solution.uncaught != null) {
throw Solution.uncaught;
}
}
}
class FastScanner {
BufferedReader in;
StringTokenizer st;
public FastScanner(BufferedReader in) {
this.in = in;
}
public String nextToken() throws Exception {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(in.readLine());
}
return st.nextToken();
}
public int nextInt() throws Exception {
return Integer.parseInt(nextToken());
}
public int[] readArray(int n) throws Exception {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
public long nextLong() throws Exception {
return Long.parseLong(nextToken());
}
public double nextDouble() throws Exception {
return Double.parseDouble(nextToken());
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
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
|
a8c033b227dfe5e46a26cb5346b28f9f
|
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
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
/**
*
* @author is2ac
*/
public class C_CF {
public static void main(String[] args) {
FastScanner57 fs = new FastScanner57();
PrintWriter pw = new PrintWriter(System.out);
for (int tc = 0; tc < 1; tc++) {
int n = fs.ni();
System.out.flush();
int m = recur(1,n,fs);
System.out.println("! " + m);
}
pw.close();
}
public static int recur(int l, int r, FastScanner57 fs) {
if (l==r) return l;
if (l+1==r) {
System.out.println("? " + l + " " + r);
System.out.flush();
int p = fs.ni();
if (l==p) return r;
return l;
}
System.out.println("? " + l + " " + r);
System.out.flush();
int s = fs.ni();
int m = (l + r)/2;
if (s<=m) {
System.out.println("? " + l + " " + m);
System.out.flush();
int lq = fs.ni();
if (lq==s) {
return recur(l,m,fs);
} else {
return recur(m+1,r,fs);
}
} else {
if (m+1==r) {
return recur(l,m,fs);
}
System.out.println("? " + (m+1) + " " + r);
System.out.flush();
int rq = fs.ni();
if (rq==s) {
return recur(m+1,r,fs);
} else {
return recur(l,m,fs);
}
}
}
}
class FastScanner57 {
BufferedReader br;
StringTokenizer st;
public FastScanner57() {
br = new BufferedReader(new InputStreamReader(System.in), 32768);
st = null;
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int ni() {
return Integer.parseInt(next());
}
int[] intArray(int N) {
int[] ret = new int[N];
for (int i = 0; i < N; i++) {
ret[i] = ni();
}
return ret;
}
long nl() {
return Long.parseLong(next());
}
long[] longArray(int N) {
long[] ret = new long[N];
for (int i = 0; i < N; i++) {
ret[i] = nl();
}
return ret;
}
double nd() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
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
|
af094ef0e30373ed7419a9940cabd4e3
|
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.lang.*;
import java.io.*;
public class Main
{
public static void main (String[] args) throws java.lang.Exception
{
Scanner sc=new Scanner(System.in);
// BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int t=1;
/// t=sc.nextInt();
//int t=Integer.parseInt(br.readLine());
while(--t>=0){
int n=sc.nextInt();
int l=1;
int r=n;
int ans=1;
while(l<=r){
System.out.println("? "+l+" "+(r));
System.out.flush();
int f=sc.nextInt();
if((r-l)<=1){
if(f==l){
ans=l+1;
break;
}
else{
ans=l;
break;
}
}
int mid=(l+r)/2;
if(f<=mid){
System.out.println("? "+(l)+" "+(mid));
System.out.flush();
int fh=sc.nextInt();
if(fh==f)
r=mid;
else
l=mid;
}
else{
System.out.println("? "+(mid)+" "+(r));
System.out.flush();
int sh=sc.nextInt();
if(sh==f)
l=mid;
else
r=mid;
}
}
System.out.println("! "+ans);
System.out.flush();
}
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
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
|
9a9db21379c0a1dee69a93af7ccdc87a
|
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 class FastIO
{
BufferedReader br;
BufferedWriter bw, be;
StringTokenizer st;
public FastIO()
{
br = new BufferedReader(new InputStreamReader(System.in));
bw = new BufferedWriter(new OutputStreamWriter(System.out));
be = new BufferedWriter(new OutputStreamWriter(System.err));
st = new StringTokenizer("");
}
private void read() throws IOException
{
st = new StringTokenizer(br.readLine());
}
public String ns() throws IOException
{
while(!st.hasMoreTokens())
read();
return st.nextToken();
}
public int ni() throws IOException
{
return Integer.parseInt(ns());
}
public long nl() throws IOException
{
return Long.parseLong(ns());
}
public float nf() throws IOException
{
return Float.parseFloat(ns());
}
public double nd() throws IOException
{
return Double.parseDouble(ns());
}
public char nc() throws IOException
{
return ns().charAt(0);
}
public int[] nia(int n) throws IOException
{
int[] a = new int[n];
for(int i = 0; i < n; i++)
a[i] = ni();
return a;
}
public long[] nla(int n) throws IOException
{
long[] a = new long[n];
for(int i = 0; i < n; i++)
a[i] = nl();
return a;
}
public char[] nca() throws IOException
{
return f.ns().toCharArray();
}
public void out(String s) throws IOException
{
bw.write(s);
bw.flush();
}
public void flush() throws IOException
{
bw.flush();
be.flush();
}
public void err(String s) throws IOException
{
be.write(s);
be.flush();
}
}
static class Pair
{
int a, b;
Pair(int x, int y)
{
a = x;
b = y;
}
public int hashCode()
{
return a^b;
}
public boolean equals(Object obj)
{
Pair that = (Pair)obj;
return a == that.a && b == that.b;
}
}
static FastIO f;
static HashMap<Pair, Integer> h;
public static void main(String args[]) throws IOException
{
f = new FastIO();
int n, ans;
h = new HashMap<>();
n = f.ni();
if(n == 1)
{
f.out("! 1\n");
return;
}
f.out("? 1 " + n + "\n");
ans = getMax(1, n, f.ni());
f.out("! " + ans + "\n");
}
public static int getMax(int l, int r, int sm) throws IOException
{
if(r == l+1)
return (sm == l) ? r : l;
if(r == l+2)
{
int a = getMax(l, l+1, getSMax(l, l+1)), b = getMax(l+1, r, getSMax(l+1, r));
return (a == b || b == sm) ? a : b;
}
int mid = l + (r-l)/2;
int sm1 = getSMax(l, mid), sm2 = getSMax(mid+1, r);
if(sm1 == sm)
return getMax(l, mid, sm1);
else if(sm2 == sm || sm <= mid)
return getMax(mid+1, r, sm2);
else
return getMax(l, mid, sm1);
}
public static int getSMax(int l, int r) throws IOException
{
Pair p = new Pair(l, r);
if(h.containsKey(p))
return h.get(p);
f.out("? " + l + " " + r + "\n");
int ans = f.ni();
h.put(p, ans);
return ans;
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
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
|
ca5041c3c98361cb166798c609001ab4
|
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 Solution{
public static void main(String[] args) {
TaskA solver = new TaskA();
// int t = in.nextInt();
// for (int i = 1; i <= t ; i++) {
// solver.solve(i, in, out);
// }
solver.solve(1, in, out);
out.flush();
out.close();
}
static class TaskA {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n= in.nextInt();
int l=0;int r=n;
while(r-l>1) {
int m=(l+r)/2;
int x=query(l,r-1);
if(x<m) {
if(query(l,m-1)==x) {
r=m;
}
else {
l=m;
}
}
else {
if(query(m,r-1)==x) {
l=m;
}
else {
r=m;
}
}
}
System.out.println("! "+r);
System.out.print("\n");
System.out.flush();
}
}
static int query(int l,int r) {
if(l>=r) {
return -1;
}
System.out.println("? "+(l+1)+" "+(r+1));
System.out.print ("\n");
int x=in.nextInt()-1;
return x;
}
static boolean check(Pair[]arr,int mid,int n) {
int c=0;
for(int i=0;i<n;i++) {
if(mid-1-arr[i].first<=c&&c<=arr[i].second) {
c++;
}
}
return c>=mid;
}
static long sum(int[]arr) {
long s=0;
for(int x:arr) {
s+=x;
}
return s;
}
static long sum(long[]arr) {
long s=0;
for(long x:arr) {
s+=x;
}
return s;
}
static int gcd(int a, int b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
static void sort(int[] a) {
ArrayList<Integer> q = new ArrayList<>();
for (int i : a) q.add(i);
Collections.sort(q);
for (int i = 0; i < a.length; i++) a[i] = q.get(i);
}
static void sort(long[] a) {
ArrayList<Long> q = new ArrayList<>();
for (long i : a) q.add(i);
Collections.sort(q);
for (int i = 0; i < a.length; i++) a[i] = q.get(i);
}
static void println(int[][]arr) {
for(int i=0;i<arr.length;i++) {
for(int j=0;j<arr[0].length;j++) {
print(arr[i][j]+" ");
}
print("\n");
}
}
static void println(long[][]arr) {
for(int i=0;i<arr.length;i++) {
for(int j=0;j<arr[0].length;j++) {
print(arr[i][j]+" ");
}
print("\n");
}
}
static void println(int[]arr){
for(int i=0;i<arr.length;i++) {
print(arr[i]+" ");
}
print("\n");
}
static void println(long[]arr){
for(int i=0;i<arr.length;i++) {
print(arr[i]+" ");
}
print("\n");
}
static long[]input(int n){
long[]arr=new long[n];
for(int i=0;i<n;i++) {
arr[i]=in.nextInt();
}
return arr;
}
static long[]input(){
long n= in.nextInt();
long[]arr=new long[(int)n];
for(int i=0;i<n;i++) {
arr[i]=in.nextLong();
}
return arr;
}
////////////////////////////////////////////////////////
static class Pair {
long first;
long second;
Pair(long x, long y)
{
this.first = x;
this.second = y;
}
}
static void sortS(Pair arr[])
{
Arrays.sort(arr, new Comparator<Pair>() {
@Override public int compare(Pair p1, Pair p2)
{
return (int)(p1.second - p2.second);
}
});
}
static void sortF(Pair arr[])
{
Arrays.sort(arr, new Comparator<Pair>() {
@Override public int compare(Pair p1, Pair p2)
{
return (int)(p1.first - p2.first);
}
});
}
/////////////////////////////////////////////////////////////
static InputStream inputStream = System.in;
static OutputStream outputStream = System.out;
static InputReader in = new InputReader(inputStream);
static PrintWriter out = new PrintWriter(outputStream);
static void println(long c) {
out.println(c);
}
static void print(long c) {
out.print(c);
}
static void print(int c) {
out.print(c);
}
static void println(int x) {
out.println(x);
}
static void print(String s) {
out.print(s);
}
static void println(String s) {
out.println(s);
}
static void println(boolean b) {
out.println(b);
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
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
|
8a8cd461b2ac8b70932ffac7cac5b41f
|
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.lang.*;
import java.io.*;
public class Main {
void solve() {
int n = in.nextInt();
int low = 1;
int high = n;
int secondLast = query(1, n);
if (secondLast == 1) {
low = 2;
} else if (secondLast == n) {
high = n - 1;
} else {
int onLeft = query(1, secondLast);
if (onLeft == secondLast) {
high = secondLast - 1;
} else {
low = secondLast + 1;
}
}
int res = 0;
while (low <= high) {
int mid = (low + high) / 2;
int l = secondLast;
int r = mid;
if (mid < secondLast) {
l = mid;
r = secondLast;
}
int val = query(l, r);
if (val != secondLast) {
if (r == secondLast) {
high = mid - 1;
} else {
low = mid + 1;
}
} else {
res = mid;
if (r == secondLast) {
low = mid + 1;
} else {
high = mid - 1;
}
}
}
System.out.println("! " + res);
}
int query(int l, int r) {
System.out.println("? " + l + " " + r);
int val = in.nextInt();
System.out.flush();
return val;
}
public static void main (String[] args) {
// It happens - Syed Mizbahuddin
Main sol = new Main();
int t = 1;
// t = in.nextInt();
while (t-- != 0) {
sol.solve();
}
System.out.print(out);
}
<T> void println(T[] s) {
if (err == null)return;
err.println(Arrays.toString(s));
}
<T> void println(T s) {
if (err == null)return;
err.println(s);
}
void println(int s) {
if (err == null)return;
err.println(s);
}
void println(int[] a) {
if (err == null)return;
println(Arrays.toString(a));
}
int[] array(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = in.nextInt();
}
return a;
}
int[] array1(int n) {
int[] a = new int[n + 1];
for (int i = 1; i <= n; i++) {
a[i] = in.nextInt();
}
return a;
}
int max(int[] a) {
int max = a[0];
for (int i = 0; i < a.length; i++)max = Math.max(max, a[i]);
return max;
}
int min(int[] a) {
int min = a[0];
for (int i = 0; i < a.length; i++)min = Math.min(min, a[i]);
return min;
}
int count(int[] a, int x) {
int count = 0;
for (int i = 0; i < a.length; i++)if (x == a[i])count++;
return count;
}
void printArray(int[] a) {
for (int ele : a)out.append(ele + " ");
out.append("\n");
}
static {
try {
// System.setIn(new FileInputStream("input.txt"));
// System.setOut(new PrintStream(new FileOutputStream("output.txt")));
// err = new PrintStream(new FileOutputStream("error.txt"));
} catch (Exception e) {}
}
static FastReader in;
static StringBuilder out;
static PrintStream err;
static String yes , no , endl;
final int MAX;
final int MIN;
int mod ;
Main() {
in = new FastReader();
out = new StringBuilder();
MAX = Integer.MAX_VALUE;
MIN = Integer.MIN_VALUE;
mod = (int)1e9 + 7;
yes = "YES\n";
no = "NO\n";
endl = "\n";
}
class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(
new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() { return Integer.parseInt(next()); }
long nextLong() { return Long.parseLong(next()); }
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
class Pair implements Comparable<Pair> {
int first , second;
Pair(int first, int second) {
this.first = first;
this.second = second;
}
public int compareTo(Pair b) {
return this.first - b.first;
}
public String toString() {
String s = "{ " + Integer.toString(first) + " , " + Integer.toString(second) + " }";
return s;
}
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
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
|
87c7461aa6ece7a15c38465d84cfc30b
|
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
|
/*
_oo0oo_
o8888888o
88" . "88
(| -_- |)
0\ = /0
___/`---'\___
.' \\| |// '.
/ \\||| : |||// \
/ _||||| -:- |||||- \
| | \\\ - /// | |
| \_| ''\---/'' |_/ |
\ .-\__ '-' ___/-. /
___'. .' /--.--\ `. .'___
."" '< `.___\_<|>_/___.' >' "".
| | : `- \`.;`\ _ /`;.`/ - ` : | |
\ \ `_. \_ __\ /__ _/ .-` / /
=====`-.____`.___ \_____/___.-`___.-'=====
`=---='
*/
import java.util.*;
import java.math.*;
import java.io.*;
import java.lang.Math.*;
public class KickStart2020 {
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
float nextFloat() {
return Float.parseFloat(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
static long gcd(long a, long b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
static long lcm(long a, long b) {
return a / gcd(a, b) * b;
}
public static class Pair implements Comparable<Pair> {
public long index;
public long value;
public Pair(long index, long value) {
this.index = index;
this.value = value;
}
@Override
public int compareTo(Pair other) {
// multiplied to -1 as the author need descending sort order
if(other.index < this.index) return 1;
if(other.index > this.index) return -1;
if(other.value < this.value) return -1;
if(other.value > this.value) return 1;
else return 0;
}
@Override
public String toString() {
return this.index + " " + this.value;
}
}
static boolean isPrime(long d) {
if (d == 1)
return false;
for (int i = 2; i <= (long) Math.sqrt(d); i++) {
if (d % i == 0)
return false;
}
return true;
}
static void decimalTob(int n, int k, Stack<Integer> ss) {
int x = n % k;
int y = n / k;
ss.push(x);
if(y > 0) {
decimalTob(y, k, ss);
}
}
static long powermod(long x, long y, long mod) {
long ans = 1;
x = x % mod;
if (x == 0)
return 0;
int i = 1;
while (y > 0) {
if ((y & 1) != 0)
ans = (ans * x) % mod;
y = y >> 1;
x = (x * x) % mod;
}
return ans;
}
static int findPos(int l, int r, FastReader sc) {
if(l == r) return l;
if(r - l == 1) {
System.out.println("? " + l + " " + r);
System.out.flush();
int temp = sc.nextInt();
if(l == temp) return r;
else return l;
}
int mid = (l + r) / 2;
System.out.println("? " + l + " " + r);
System.out.flush();
int pos = sc.nextInt();
if(pos >= mid) {
System.out.println("? " + mid + " " + r);
System.out.flush();
int ans = sc.nextInt();
if(ans == pos) return findPos(mid, r, sc);
else return findPos(l, mid, sc);
}
else {System.out.println("? " + l + " " + mid);
System.out.flush();
int ans = sc.nextInt();
if(ans == pos) return findPos(l, mid, sc);
else return findPos(mid, r, sc);}
}
public static void main(String[] args) throws Exception {
FastReader sc = new FastReader();
PrintWriter out = new PrintWriter(System.out);
int t = 1;
outerloop:
while(t-- > 0) {
int n = sc.nextInt();
out.println("! " + findPos(1, n, sc));
}
out.close();
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
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
|
1c12dbc9aa1273f43355b716ec58b7e8
|
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.util.Map.Entry;
import java.lang.*;
import java.io.*;
import java.math.BigInteger;
public class CF {
private static FS sc = new FS();
private static class FS {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer("");
String next() {
while (!st.hasMoreTokens())
try {
st=new StringTokenizer(br.readLine());
} catch (IOException e) {}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
}
private static class extra {
static int[] intArr(int size) {
int[] a = new int[size];
for(int i = 0; i < size; i++) a[i] = sc.nextInt();
return a;
}
static long[] longArr(int size) {
long[] a = new long[size];
for(int i = 0; i < size; i++) a[i] = sc.nextLong();
return a;
}
static long intSum(int[] a) {
long sum = 0;
for(int i = 0; i < a.length; i++) {
sum += a[i];
}
return sum;
}
static long longSum(long[] a) {
long sum = 0;
for(int i = 0; i < a.length; i++) {
sum += a[i];
}
return sum;
}
static LinkedList[] graphD(int vertices, int edges) {
LinkedList<Integer>[] temp = new LinkedList[vertices+1];
for(int i = 0; i <= vertices; i++) temp[i] = new LinkedList<>();
for(int i = 0; i < edges; i++) {
int x = sc.nextInt();
int y = sc.nextInt();
temp[x].add(y);
}
return temp;
}
static LinkedList[] graphUD(int vertices, int edges) {
LinkedList<Integer>[] temp = new LinkedList[vertices+1];
for(int i = 0; i <= vertices; i++) temp[i] = new LinkedList<>();
for(int i = 0; i < edges; i++) {
int x = sc.nextInt();
int y = sc.nextInt();
temp[x].add(y);
temp[y].add(x);
}
return temp;
}
static void printG(LinkedList[] temp) {
for(LinkedList<Integer> aa:temp) System.out.println(aa);
}
static long cal(long val, long pow) {
if(pow == 0) return 1;
long res = cal(val, pow/2);
// long ret = (res*res)%mod;
// if(pow%2 == 0) return ret;
// return (val*ret)%mod;
long ret = res*res;
if(pow%2 == 0) return ret;
return val*ret;
}
static long gcd(long a, long b) { return b == 0 ? a:gcd(b, a%b); }
}
static int mod = (int) 1e9 + 9;
// static int mod = (int) 998244353;
static int max = (int) 1e6, sq = 316;
static LinkedList<Integer>[] temp;
// static int[] par, rank;
public static void main(String[] args) {
// int t = sc.nextInt();
int t = 1;
StringBuilder ret = new StringBuilder();
while(t-- > 0) {
int n = sc.nextInt();
int l = 0, 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);
}
System.out.println(ret);
}
static int ask(int l, int r) {
if (l >= r) return -1;
System.out.println("? " + (l + 1) + " " + (r + 1));
int ans = sc.nextInt();
return ans - 1;
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
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
|
e661a48ab6f27949a3f2e16aab3f3af2
|
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.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.StringTokenizer;
public class Hello1 {
static FastReader s = new FastReader();
public static int ask(int l, int r) {
System.out.println("? " + (l + 1) + " " + (r + 1));
System.out.flush();
return (s.nextInt() - 1);
}
public static int result(int n, int l, int r) {
//System.out.pintln(n);
if(r - l == 0) return r;
if(r - l == 1) {
int second = ask(l, r);
if(second == l) return r;
else return l;
}
int second = ask(l, r);
int ans = -1;
int mid = (l + r) / 2;
if(second <= mid) {
int sec = ask(l, mid);
if(sec == second) {
ans = result(n, l, mid);
return ans;
}
else {
ans = result(n, mid + 1, r);
return ans;
}
}
else {
int sec = ask(mid, r);
if(sec == second) {
ans = result(n, mid, r);
return ans;
}
else {
ans = result(n, l, mid - 1);
return ans;
}
}
}
public static void main(String[] args) throws IOException{
// BufferedWriter output = new BufferedWriter(
// new OutputStreamWriter(System.out));
long t = 1;//s.nextInt();
for(int i = 0; i < t; i++) {
int n = s.nextInt();
int ans = result(n, 0, n - 1);
System.out.println("! " + (ans + 1));
System.out.flush();
}
//output.flush();
}
}
class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
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
|
bdb29715a04c7f3c5f3bfcfc2abf405d
|
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.DataInputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Map;
import java.util.TreeMap;
public class Main {
private static void run() throws IOException {
int n = in.nextInt();
// TreeMap<Double, Integer> map = new TreeMap<>();
// for (int i = 1; i <= n; i++) {
// map.put(Math.random(), i);
// }
// a = new int[n];
// int index = 0;
// for (Map.Entry<Double, Integer> now : map.entrySet()) {
// a[index++] = now.getValue();
// }
// print_array(a);
// System.err.flush();
query_with_second(1, n, query(1, n));
}
private static void query_with_second(int left, int right, int current_second) throws IOException {
if (current_second < left || current_second > right) {
current_second = query(left, right);
}
if (left + 1 == right) {
if (current_second == right) {
out.printf("! %d \n", left);
// check(left);
} else {
out.printf("! %d \n", right);
// check(right);
}
return;
}
int mid = (left + right) >> 1;
boolean is_left = current_second <= mid ? query(left, mid) == current_second : query(mid, right) != current_second;
if (is_left) {
query_with_second(left, mid, current_second);
} else {
query_with_second(mid, right, current_second);
}
}
static int[] a;
static int count = 0;
private static void check(int ans) {
int[] tmp = new int[a.length];
System.arraycopy(a, 0, tmp, 0, a.length);
Arrays.sort(tmp);
System.err.println(tmp[a.length - 1] + " " + a[ans - 1] + " " + (tmp[a.length - 1] == a[ans - 1]));
System.err.println("count: " + count);
System.err.flush();
}
private static int query(int left, int right) throws IOException {
out.printf("? %d %d\n", left, right);
out.flush();
return in.nextInt();
// count++;
//
// int[] tmp = new int[right - left + 1];
// for (int i = 0; i < right - left + 1; i++) {
// tmp[i] = a[left + i - 1];
// }
// Arrays.sort(tmp);
// for (int i = left; i <= right; i++) {
// if (a[i - 1] == tmp[right - left - 1]) {
// System.err.println("input: " + i);
// System.err.flush();
// return i;
// }
// }
// System.err.println("input: ");
// System.err.flush();
// return -1;
}
public static void main(String[] args) throws IOException {
in = new Reader();
out = new PrintWriter(new OutputStreamWriter(System.out));
// int t = in.nextInt();
// for (int i = 0; i < t; i++) {
// }
run();
out.flush();
in.close();
out.close();
}
private static int gcd(int a, int b) {
if (a == 0 || b == 0)
return 0;
while (b != 0) {
int tmp;
tmp = a % b;
a = b;
b = tmp;
}
return a;
}
static final long mod = 1000000007;
static long pow_mod(long a, long b) {
long result = 1;
while (b != 0) {
if ((b & 1) != 0) result = (result * a) % mod;
a = (a * a) % mod;
b >>= 1;
}
return result;
}
private static long multiplied_mod(long... longs) {
long ans = 1;
for (long now : longs) {
ans = (ans * now) % mod;
}
return ans;
}
@SuppressWarnings("FieldCanBeLocal")
private static Reader in;
private static PrintWriter out;
private static void print_array(int[] array) {
for (int now : array) {
System.err.print(now);
System.err.print(' ');
}
System.err.println();
}
private static void print_array(long[] array) {
for (long now : array) {
out.print(now);
out.print(' ');
}
out.println();
}
static class Reader {
private static final int BUFFER_SIZE = 1 << 16;
private final DataInputStream din;
private final byte[] buffer;
private int bufferPointer, bytesRead;
Reader() {
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException {
final byte[] buf = new byte[1024]; // line length
int cnt = 0, c;
while ((c = read()) != -1) {
if (c == '\n') {
break;
}
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int nextSign() throws IOException {
byte c = read();
while ('+' != c && '-' != c) {
c = read();
}
return '+' == c ? 0 : 1;
}
private static boolean isSpaceChar(int c) {
return !(c >= 33 && c <= 126);
}
public int skip() throws IOException {
int b;
// noinspection ALL
while ((b = read()) != -1 && isSpaceChar(b)) {
;
}
return b;
}
public char nc() throws IOException {
return (char) skip();
}
public String next() throws IOException {
int b = skip();
final StringBuilder sb = new StringBuilder();
while (!isSpaceChar(b)) { // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = read();
}
return sb.toString();
}
public int nextInt() throws IOException {
int ret = 0;
byte c = read();
while (c <= ' ') {
c = read();
}
final boolean neg = c == '-';
if (neg) {
c = read();
}
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg) {
return -ret;
}
return ret;
}
public long nextLong() throws IOException {
long ret = 0;
byte c = read();
while (c <= ' ') {
c = read();
}
final boolean neg = c == '-';
if (neg) {
c = read();
}
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (neg) {
return -ret;
}
return ret;
}
public double nextDouble() throws IOException {
double ret = 0, div = 1;
byte c = read();
while (c <= ' ') {
c = read();
}
final boolean neg = c == '-';
if (neg) {
c = read();
}
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (c == '.') {
while ((c = read()) >= '0' && c <= '9') {
ret += (c - '0') / (div *= 10);
}
}
if (neg) {
return -ret;
}
return ret;
}
private void fillBuffer() throws IOException {
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1) {
buffer[0] = -1;
}
}
private byte read() throws IOException {
if (bufferPointer == bytesRead) {
fillBuffer();
}
return buffer[bufferPointer++];
}
public void close() throws IOException {
din.close();
}
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
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
|
d3c677a5d14d1a7f442e035b0fce868c
|
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 codechef; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
import static java.lang.Math.*;
/* Name of the class has to be "Main" only if the class is public. */
// class Codechef
public class C1GuessingtheGreatest
{
static InputReader in = new InputReader(System.in);
public static int query(int l, int r) throws java.lang.Exception {
StringBuilder sb = new StringBuilder(15);
sb.append("? ");
sb.append(l);
sb.append(" ");
sb.append(r);
System.out.println(sb);
System.out.flush();
return in.nextInt();
}
public static void main(String[] args) throws java.lang.Exception {
int n = in.nextInt();
int l = 1;
int r = n;
int ans=-1;
while(l<r){
int mid = (l+r)/2;
int smax = ans;
if(ans==-1){
smax = query(l,r);
}
if(l+1==r){
if(l==smax){
l=r;
break;
}else{
r=l;
break;
}
}
if(smax<=mid){
int lsmax = query(l, mid);
if(lsmax == smax){
r=mid;
ans = lsmax;
}else{
l=mid+1;
ans=-1;
}
}else{
if(mid+1==r){
r=mid;
ans=-1;
continue;
}
int rsmax = query(mid+1, r);
if(rsmax == smax){
l = mid+1;
ans=rsmax;
}else{
r=mid;
ans=-1;
}
}
}
System.out.println("! " + l);
System.out.flush();
// in.close();
}
private static class InputReader implements AutoCloseable {
/**
* The default size of the InputReader's buffer is 2<sup>16</sup>.
*/
private static final int DEFAULT_BUFFER_SIZE = 1 << 16;
/**
* The default stream for the InputReader is standard input.
*/
private static final InputStream DEFAULT_STREAM = System.in;
/**
* The maximum number of accurate decimal digits the method
* {@link #nextDoubleFast() nextDoubleFast()} can read. Currently this value is
* set to 21 because it is the maximum number of digits a double precision float
* can have at the moment.
*/
private static final int MAX_DECIMAL_PRECISION = 21;
// 'c' is used to refer to the current character in the stream
private int c;
// Variables associated with the byte buffer.
private final byte[] buf;
private final int bufferSize;
private int bufIndex;
private int numBytesRead;
private final InputStream stream;
// End Of File (EOF) character
private static final byte EOF = -1;
// New line character: '\n'
private static final byte NEW_LINE = 10;
// Space character: ' '
private static final byte SPACE = 32;
// Dash character: '-'
private static final byte DASH = 45;
// Dot character: '.'
private static final byte DOT = 46;
// A reusable character buffer when reading string data.
private char[] charBuffer;
// Primitive data type lookup tables used for optimizations
private static final byte[] bytes = new byte[58];
private static final int[] ints = new int[58];
private static final char[] chars = new char[128];
static {
char ch = ' ';
int value = 0;
byte _byte = 0;
for (int i = 48; i < 58; i++)
bytes[i] = _byte++;
for (int i = 48; i < 58; i++)
ints[i] = value++;
for (int i = 32; i < 128; i++)
chars[i] = ch++;
}
// Primitive double lookup table used for optimizations.
private static final double[][] doubles = {
{ 0.0d, 0.00d, 0.000d, 0.0000d, 0.00000d, 0.000000d, 0.0000000d, 0.00000000d, 0.000000000d,
0.0000000000d, 0.00000000000d, 0.000000000000d, 0.0000000000000d, 0.00000000000000d,
0.000000000000000d, 0.0000000000000000d, 0.00000000000000000d, 0.000000000000000000d,
0.0000000000000000000d, 0.00000000000000000000d, 0.000000000000000000000d },
{ 0.1d, 0.01d, 0.001d, 0.0001d, 0.00001d, 0.000001d, 0.0000001d, 0.00000001d, 0.000000001d,
0.0000000001d, 0.00000000001d, 0.000000000001d, 0.0000000000001d, 0.00000000000001d,
0.000000000000001d, 0.0000000000000001d, 0.00000000000000001d, 0.000000000000000001d,
0.0000000000000000001d, 0.00000000000000000001d, 0.000000000000000000001d },
{ 0.2d, 0.02d, 0.002d, 0.0002d, 0.00002d, 0.000002d, 0.0000002d, 0.00000002d, 0.000000002d,
0.0000000002d, 0.00000000002d, 0.000000000002d, 0.0000000000002d, 0.00000000000002d,
0.000000000000002d, 0.0000000000000002d, 0.00000000000000002d, 0.000000000000000002d,
0.0000000000000000002d, 0.00000000000000000002d, 0.000000000000000000002d },
{ 0.3d, 0.03d, 0.003d, 0.0003d, 0.00003d, 0.000003d, 0.0000003d, 0.00000003d, 0.000000003d,
0.0000000003d, 0.00000000003d, 0.000000000003d, 0.0000000000003d, 0.00000000000003d,
0.000000000000003d, 0.0000000000000003d, 0.00000000000000003d, 0.000000000000000003d,
0.0000000000000000003d, 0.00000000000000000003d, 0.000000000000000000003d },
{ 0.4d, 0.04d, 0.004d, 0.0004d, 0.00004d, 0.000004d, 0.0000004d, 0.00000004d, 0.000000004d,
0.0000000004d, 0.00000000004d, 0.000000000004d, 0.0000000000004d, 0.00000000000004d,
0.000000000000004d, 0.0000000000000004d, 0.00000000000000004d, 0.000000000000000004d,
0.0000000000000000004d, 0.00000000000000000004d, 0.000000000000000000004d },
{ 0.5d, 0.05d, 0.005d, 0.0005d, 0.00005d, 0.000005d, 0.0000005d, 0.00000005d, 0.000000005d,
0.0000000005d, 0.00000000005d, 0.000000000005d, 0.0000000000005d, 0.00000000000005d,
0.000000000000005d, 0.0000000000000005d, 0.00000000000000005d, 0.000000000000000005d,
0.0000000000000000005d, 0.00000000000000000005d, 0.000000000000000000005d },
{ 0.6d, 0.06d, 0.006d, 0.0006d, 0.00006d, 0.000006d, 0.0000006d, 0.00000006d, 0.000000006d,
0.0000000006d, 0.00000000006d, 0.000000000006d, 0.0000000000006d, 0.00000000000006d,
0.000000000000006d, 0.0000000000000006d, 0.00000000000000006d, 0.000000000000000006d,
0.0000000000000000006d, 0.00000000000000000006d, 0.000000000000000000006d },
{ 0.7d, 0.07d, 0.007d, 0.0007d, 0.00007d, 0.000007d, 0.0000007d, 0.00000007d, 0.000000007d,
0.0000000007d, 0.00000000007d, 0.000000000007d, 0.0000000000007d, 0.00000000000007d,
0.000000000000007d, 0.0000000000000007d, 0.00000000000000007d, 0.000000000000000007d,
0.0000000000000000007d, 0.00000000000000000007d, 0.000000000000000000007d },
{ 0.8d, 0.08d, 0.008d, 0.0008d, 0.00008d, 0.000008d, 0.0000008d, 0.00000008d, 0.000000008d,
0.0000000008d, 0.00000000008d, 0.000000000008d, 0.0000000000008d, 0.00000000000008d,
0.000000000000008d, 0.0000000000000008d, 0.00000000000000008d, 0.000000000000000008d,
0.0000000000000000008d, 0.00000000000000000008d, 0.000000000000000000008d },
{ 0.9d, 0.09d, 0.009d, 0.0009d, 0.00009d, 0.000009d, 0.0000009d, 0.00000009d, 0.000000009d,
0.0000000009d, 0.00000000009d, 0.000000000009d, 0.0000000000009d, 0.00000000000009d,
0.000000000000009d, 0.0000000000000009d, 0.00000000000000009d, 0.000000000000000009d,
0.0000000000000000009d, 0.00000000000000000009d, 0.000000000000000000009d } };
/**
* Create an InputReader that reads from standard input.
*/
public InputReader() {
this(DEFAULT_STREAM, DEFAULT_BUFFER_SIZE);
}
/**
* Create an InputReader that reads from standard input.
*
* @param bufferSize The buffer size for this input reader.
*/
public InputReader(int bufferSize) {
this(DEFAULT_STREAM, bufferSize);
}
/**
* Create an InputReader that reads from standard input.
*
* @param stream Takes an InputStream as a parameter to read from.
*/
public InputReader(InputStream stream) {
this(stream, DEFAULT_BUFFER_SIZE);
}
/**
* Create an InputReader that reads from standard input.
*
* @param stream Takes an {@link java.io.InputStream#InputStream()
* InputStream} as a parameter to read from.
* @param bufferSize The size of the buffer to use.
*/
public InputReader(InputStream stream, int bufferSize) {
if (stream == null || bufferSize <= 0)
throw new IllegalArgumentException();
buf = new byte[bufferSize];
charBuffer = new char[128];
this.bufferSize = bufferSize;
this.stream = stream;
}
/**
* Reads a single character from the input stream.
*
* @return Returns the byte value of the next character in the buffer and EOF at
* the end of the stream.
* @throws IOException throws exception if there is no more data to read
*/
private byte read() throws IOException {
if (numBytesRead == EOF)
throw new IOException();
if (bufIndex >= numBytesRead) {
bufIndex = 0;
numBytesRead = stream.read(buf);
if (numBytesRead == EOF)
return EOF;
}
return buf[bufIndex++];
}
/**
* Read values from the input stream until you reach a character with a higher
* ASCII value than 'token'.
*
* @param token The token is a value which we use to stop reading junk out of
* the stream.
* @return Returns 0 if a value greater than the token was reached or -1 if the
* end of the stream was reached.
* @throws IOException Throws exception at end of stream.
*/
private int readJunk(int token) throws IOException {
if (numBytesRead == EOF)
return EOF;
// Seek to the first valid position index
do {
while (bufIndex < numBytesRead) {
if (buf[bufIndex] > token)
return 0;
bufIndex++;
}
// reload buffer
numBytesRead = stream.read(buf);
if (numBytesRead == EOF)
return EOF;
bufIndex = 0;
} while (true);
}
/**
* Reads a single byte from the input stream.
*
* @return The next byte in the input stream
* @throws IOException Throws exception at end of stream.
*/
public byte nextByte() throws IOException {
return (byte) nextInt();
}
/**
* Reads a 32 bit signed integer from input stream.
*
* @return The next integer value in the stream.
* @throws IOException Throws exception at end of stream.
*/
public int nextInt() throws IOException {
if (readJunk(DASH - 1) == EOF)
throw new IOException();
int sgn = 1, res = 0;
c = buf[bufIndex];
if (c == DASH) {
sgn = -1;
bufIndex++;
}
do {
while (bufIndex < numBytesRead) {
if (buf[bufIndex] > SPACE) {
res = (res << 3) + (res << 1);
res += ints[buf[bufIndex++]];
} else {
bufIndex++;
return res * sgn;
}
}
// Reload buffer
numBytesRead = stream.read(buf);
if (numBytesRead == EOF)
return res * sgn;
bufIndex = 0;
} while (true);
}
/**
* Reads a 64 bit signed long from input stream.
*
* @return The next long value in the stream.
* @throws IOException Throws exception at end of stream.
*/
public long nextLong() throws IOException {
if (readJunk(DASH - 1) == EOF)
throw new IOException();
int sgn = 1;
long res = 0L;
c = buf[bufIndex];
if (c == DASH) {
sgn = -1;
bufIndex++;
}
do {
while (bufIndex < numBytesRead) {
if (buf[bufIndex] > SPACE) {
res = (res << 3) + (res << 1);
res += ints[buf[bufIndex++]];
} else {
bufIndex++;
return res * sgn;
}
}
// Reload buffer
numBytesRead = stream.read(buf);
if (numBytesRead == EOF)
return res * sgn;
bufIndex = 0;
} while (true);
}
/**
* Doubles the size of the internal char buffer for strings
*/
private void doubleCharBufferSize() {
char[] newBuffer = new char[charBuffer.length << 1];
for (int i = 0; i < charBuffer.length; i++)
newBuffer[i] = charBuffer[i];
charBuffer = newBuffer;
}
/**
* Reads a line from the input stream.
*
* @return Returns a line from the input stream in the form a String not
* including the new line character. Returns <code>null</code> when
* there are no more lines.
* @throws IOException Throws IOException when something terrible happens.
*/
public String nextLine() throws IOException {
try {
c = read();
} catch (IOException e) {
return null;
}
if (c == NEW_LINE)
return ""; // Empty line
if (c == EOF)
return null; // EOF
int i = 0;
charBuffer[i++] = (char) c;
do {
while (bufIndex < numBytesRead) {
if (buf[bufIndex] != NEW_LINE) {
if (i == charBuffer.length)
doubleCharBufferSize();
charBuffer[i++] = (char) buf[bufIndex++];
} else {
bufIndex++;
return new String(charBuffer, 0, i);
}
}
// Reload buffer
numBytesRead = stream.read(buf);
if (numBytesRead == EOF)
return new String(charBuffer, 0, i);
bufIndex = 0;
} while (true);
}
// Reads a string of characters from the input stream.
// The delimiter separating a string of characters is set to be:
// any ASCII value <= 32 meaning any spaces, new lines, EOF, tabs...
public String nextString() throws IOException {
if (numBytesRead == EOF)
return null;
if (readJunk(SPACE) == EOF)
return null;
for (int i = 0;;) {
while (bufIndex < numBytesRead) {
if (buf[bufIndex] > SPACE) {
if (i == charBuffer.length)
doubleCharBufferSize();
charBuffer[i++] = (char) buf[bufIndex++];
} else {
bufIndex++;
return new String(charBuffer, 0, i);
}
}
// Reload buffer
numBytesRead = stream.read(buf);
if (numBytesRead == EOF)
return new String(charBuffer, 0, i);
bufIndex = 0;
}
}
// Returns an exact value a double value from the input stream.
public double nextDouble() throws IOException {
String doubleVal = nextString();
if (doubleVal == null)
throw new IOException();
return Double.valueOf(doubleVal);
}
// Very quickly reads a double value from the input stream (~3x faster than
// nextDouble()). However,
// this method may provide a slightly less accurate reading than .nextDouble()
// if there are a lot
// of digits (~16+). In particular, it will only read double values with at most
// 21 digits after
// the decimal point and the reading my be as inaccurate as ~5*10^-16 from the
// true value.
public double nextDoubleFast() throws IOException {
c = read();
int sgn = 1;
while (c <= SPACE)
c = read(); // while c is either: ' ', '\n', EOF
if (c == DASH) {
sgn = -1;
c = read();
}
double res = 0.0;
// while c is not: ' ', '\n', '.' or -1
while (c > DOT) {
res *= 10.0;
res += ints[c];
c = read();
}
if (c == DOT) {
int i = 0;
c = read();
// while c is digit and we are less than the maximum decimal precision
while (c > SPACE && i < MAX_DECIMAL_PRECISION) {
res += doubles[ints[c]][i++];
c = read();
}
}
return res * sgn;
}
// Read an array of n byte values
public byte[] nextByteArray(int n) throws IOException {
byte[] ar = new byte[n];
for (int i = 0; i < n; i++)
ar[i] = nextByte();
return ar;
}
// Read an integer array of size n
public int[] nextIntArray(int n) throws IOException {
int[] ar = new int[n];
for (int i = 0; i < n; i++)
ar[i] = nextInt();
return ar;
}
// Read a long array of size n
public long[] nextLongArray(int n) throws IOException {
long[] ar = new long[n];
for (int i = 0; i < n; i++)
ar[i] = nextLong();
return ar;
}
// read an of doubles of size n
public double[] nextDoubleArray(int n) throws IOException {
double[] ar = new double[n];
for (int i = 0; i < n; i++)
ar[i] = nextDouble();
return ar;
}
// Quickly read an array of doubles
public double[] nextDoubleArrayFast(int n) throws IOException {
double[] ar = new double[n];
for (int i = 0; i < n; i++)
ar[i] = nextDoubleFast();
return ar;
}
// Read a string array of size n
public String[] nextStringArray(int n) throws IOException {
String[] ar = new String[n];
for (int i = 0; i < n; i++) {
String str = nextString();
if (str == null)
throw new IOException();
ar[i] = str;
}
return ar;
}
// Read a 1-based byte array of size n+1
public byte[] nextByteArray1(int n) throws IOException {
byte[] ar = new byte[n + 1];
for (int i = 1; i <= n; i++)
ar[i] = nextByte();
return ar;
}
// Read a 1-based integer array of size n+1
public int[] nextIntArray1(int n) throws IOException {
int[] ar = new int[n + 1];
for (int i = 1; i <= n; i++)
ar[i] = nextInt();
return ar;
}
// Read a 1-based long array of size n+1
public long[] nextLongArray1(int n) throws IOException {
long[] ar = new long[n + 1];
for (int i = 1; i <= n; i++)
ar[i] = nextLong();
return ar;
}
// Read a 1-based double array of size n+1
public double[] nextDoubleArray1(int n) throws IOException {
double[] ar = new double[n + 1];
for (int i = 1; i <= n; i++)
ar[i] = nextDouble();
return ar;
}
// Quickly read a 1-based double array of size n+1
public double[] nextDoubleArrayFast1(int n) throws IOException {
double[] ar = new double[n + 1];
for (int i = 1; i <= n; i++)
ar[i] = nextDoubleFast();
return ar;
}
// Read a 1-based string array of size n+1
public String[] nextStringArray1(int n) throws IOException {
String[] ar = new String[n + 1];
for (int i = 1; i <= n; i++)
ar[i] = nextString();
return ar;
}
// Read a two dimensional matrix of bytes of size rows x cols
public byte[][] nextByteMatrix(int rows, int cols) throws IOException {
byte[][] matrix = new byte[rows][cols];
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
matrix[i][j] = nextByte();
return matrix;
}
// Read a two dimensional matrix of ints of size rows x cols
public int[][] nextIntMatrix(int rows, int cols) throws IOException {
int[][] matrix = new int[rows][cols];
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
matrix[i][j] = nextInt();
return matrix;
}
// Read a two dimensional matrix of longs of size rows x cols
public long[][] nextLongMatrix(int rows, int cols) throws IOException {
long[][] matrix = new long[rows][cols];
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
matrix[i][j] = nextLong();
return matrix;
}
// Read a two dimensional matrix of doubles of size rows x cols
public double[][] nextDoubleMatrix(int rows, int cols) throws IOException {
double[][] matrix = new double[rows][cols];
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
matrix[i][j] = nextDouble();
return matrix;
}
// Quickly read a two dimensional matrix of doubles of size rows x cols
public double[][] nextDoubleMatrixFast(int rows, int cols) throws IOException {
double[][] matrix = new double[rows][cols];
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
matrix[i][j] = nextDoubleFast();
return matrix;
}
// Read a two dimensional matrix of Strings of size rows x cols
public String[][] nextStringMatrix(int rows, int cols) throws IOException {
String[][] matrix = new String[rows][cols];
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
matrix[i][j] = nextString();
return matrix;
}
// Read a 1-based two dimensional matrix of bytes of size rows x cols
public byte[][] nextByteMatrix1(int rows, int cols) throws IOException {
byte[][] matrix = new byte[rows + 1][cols + 1];
for (int i = 1; i <= rows; i++)
for (int j = 1; j <= cols; j++)
matrix[i][j] = nextByte();
return matrix;
}
// Read a 1-based two dimensional matrix of ints of size rows x cols
public int[][] nextIntMatrix1(int rows, int cols) throws IOException {
int[][] matrix = new int[rows + 1][cols + 1];
for (int i = 1; i <= rows; i++)
for (int j = 1; j <= cols; j++)
matrix[i][j] = nextInt();
return matrix;
}
// Read a 1-based two dimensional matrix of longs of size rows x cols
public long[][] nextLongMatrix1(int rows, int cols) throws IOException {
long[][] matrix = new long[rows + 1][cols + 1];
for (int i = 1; i <= rows; i++)
for (int j = 1; j <= cols; j++)
matrix[i][j] = nextLong();
return matrix;
}
// Read a 1-based two dimensional matrix of doubles of size rows x cols
public double[][] nextDoubleMatrix1(int rows, int cols) throws IOException {
double[][] matrix = new double[rows + 1][cols + 1];
for (int i = 1; i <= rows; i++)
for (int j = 1; j <= cols; j++)
matrix[i][j] = nextDouble();
return matrix;
}
// Quickly read a 1-based two dimensional matrix of doubles of size rows x cols
public double[][] nextDoubleMatrixFast1(int rows, int cols) throws IOException {
double[][] matrix = new double[rows + 1][cols + 1];
for (int i = 1; i <= rows; i++)
for (int j = 1; j <= cols; j++)
matrix[i][j] = nextDoubleFast();
return matrix;
}
// Read a 1-based two dimensional matrix of Strings of size rows x cols
public String[][] nextStringMatrix1(int rows, int cols) throws IOException {
String[][] matrix = new String[rows + 1][cols + 1];
for (int i = 1; i <= rows; i++)
for (int j = 1; j <= cols; j++)
matrix[i][j] = nextString();
return matrix;
}
// Closes the input stream
public void close() throws IOException {
stream.close();
}
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
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
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.