Codeforces1486 C2.Guessing the Greatest (hard version)(交互题+奇怪的二分)

简介: Codeforces1486 C2.Guessing the Greatest (hard version)(交互题+奇怪的二分)

原题链接

思路:

开始变得奇怪了。

首先还是记pos为区间[1,n]的次大值位置。

然后再查询[1,pos]的次大值位置,如果等于pos的话,说明最大值在[1,pos],否则说明最大值在[pos,n]。

然后再对这两部分进行二分查找,check的很巧妙。

假设最大值在[1,pos],那么记mid为区间[l,r]的中点。查询的是 [mid,pos]的次大值位置,记作t。如果t==pos的话,说明最大值位置在[mid,r]里,反之,在[l,mid]里。

询问次数:2+log(1e5)

代码:

#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;
}
目录
相关文章
|
8月前
|
机器学习/深度学习 人工智能 BI
The Great Hero(Codeforces Round #700 (Div. 2))模拟+贪心思想和排序
The Great Hero(Codeforces Round #700 (Div. 2))模拟+贪心思想和排序
35 0
|
8月前
|
Go
Shortest Path with Obstacle( CodeForces - 1547A )(模拟)
Shortest Path with Obstacle( CodeForces - 1547A )(模拟)
28 0
|
9月前
|
算法
LeetCode 热题 HOT 100题解 (easy级别)(一)
LeetCode 热题 HOT 100题解 (easy级别)
84 0
|
9月前
|
机器学习/深度学习
LeetCode 热题 HOT 100题解 (easy级别)(二)
LeetCode 热题 HOT 100题解 (easy级别)
74 0
|
10月前
|
文件存储
Easy Number Challenge(埃式筛思想+优雅暴力)
Easy Number Challenge(埃式筛思想+优雅暴力)
59 0
【每日一题Day19】LC1678设计Goal解析器 | 简单模拟
给你字符串 command ,返回 Goal 解析器 对 command 的解释结果。
61 0
Codeforces1486 C1.Guessing the Greatest (easy version)(交互题+二分)
Codeforces1486 C1.Guessing the Greatest (easy version)(交互题+二分)
73 0
|
Java Shell
Codeforces Round #746 (Div. 2) D - Hemose in ICPC ?(交互 二分 欧拉序)
Codeforces Round #746 (Div. 2) D - Hemose in ICPC ?(交互 二分 欧拉序)
135 0
|
机器学习/深度学习 存储 算法
算法系统学习-牛刀小试几个小Case(非递归算法)
该系列是基于有一定语言基础(C,C++,Java等等)和基本的数据结构基础进行的算法学习专栏,如果觉得有点吃力 😥 ,建议先了解前提知识再学习喔!本个专栏会将用更容易理解的表达去学习算法,如果在一些表述上存在问题还请各位多多指点
102 0