Codeforces1486 C2.Guessing the Greatest (hard version) (interactive questions + strange dichotomy)

The original link
idea: It's
starting to become strange.
First of all, let pos be the second largest value position in the interval [1,n].
Then query the second largest value position of [1,pos]. If it is equal to pos, it means that the maximum value is at [1,pos], otherwise it means that the maximum value is at [pos,n].
Then perform a binary search on these two parts, and the check is very clever.
Assuming that the maximum value is at [1,pos], then mark mid as the midpoint of the interval [l,r]. What is queried is the second largest value position of [mid, pos] , which is recorded as t. If t==pos, it means that the maximum position is in [mid,r], otherwise, it is in [l,mid].
Number of inquiries: 2+log (1e5)
code:

#pragma GCC optimize(2)
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;typedef unsigned long long ull;
typedef pair<ll,ll>PLL;typedef pair<int,int>PII;typedef pair<double,double>PDD;
#define I_int ll
inline ll read(){
    
    ll x=0,f=1;char ch=getchar();while(ch<'0'||ch>'9'){
    
    if(ch=='-')f=-1;ch=getchar();}while(ch>='0'&&ch<='9'){
    
    x=x*10+ch-'0';ch=getchar();}return x*f;}
#define read read()
#define closeSync ios::sync_with_stdio(0);cin.tie(0);cout.tie(0)
#define multiCase int T;cin>>T;for(int t=1;t<=T;t++)
#define rep(i,a,b) for(int i=(a);i<=(b);i++)
#define repp(i,a,b) for(int i=(a);i<(b);i++)
#define per(i,a,b) for(int i=(a);i>=(b);i--)
#define perr(i,a,b) for(int i=(a);i>(b);i--)
ll ksm(ll a,ll b,ll p){
    
    ll res=1;while(b){
    
    if(b&1)res=res*a%p;a=a*a%p;b>>=1;}return res;}
const int maxn=1e6+7;
int n;
int ask(int l,int r){
    
    
    if(l>=r) return -1;
    cout<<"? "<<l<<" "<<r<<endl;
    fflush(stdout);
    int pos;cin>>pos;
    return pos;
}
void solve(){
    
    
    n=read;
    int pos=ask(1,n);//区间[1,n]的次大值
    if(pos!=ask(1,pos)){
    
    ///查询[1,pos]的次大值位置,不相等说明最大值在[pos,n]
        int l=pos,r=n,res;
        while(r-l>1){
    
    
            int mid=(l+r)/2;
            if(pos==ask(pos,mid)) r=mid;
            else l=mid;
        }
        cout<<"! "<<r<<endl;
    }
    else{
    
    
        int l=1,r=pos,res;
        while(r-l>1){
    
    
            int mid=(l+r)/2;
            if(pos==ask(mid,pos)) l=mid;
            else r=mid;
        }
        cout<<"! "<<l<<endl;
    }
}

int main(){
    
    
	int T=1;
	while(T--) solve();
	return 0;
}

Guess you like

Origin blog.csdn.net/weixin_45675097/article/details/113859813