CodeForces - 1486C2 Guessing the Greatest (hard version)(二分+交互)
生活随笔
收集整理的這篇文章主要介紹了
CodeForces - 1486C2 Guessing the Greatest (hard version)(二分+交互)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目鏈接:點擊查看
題目分析:給出一個長度為 nnn 的序列,現在可以進行最多 202020 次查詢,每次查詢可以詢問區間 [l,r][l,r][l,r] 中次大值的位置,現在要求在查詢后輸出最大值的位置
題目分析:C1C1C1 的 404040 次查詢是比較簡單的二分,就不多說了,關于本題,個人感覺更像是一道思維偏重的構造題,直接說做法吧
可以先利用一次查詢,詢問 [1,n][1,n][1,n] 的次大值位置,記為 ppp
再用一次查詢,詢問最大值是在 [1,p?1][1,p-1][1,p?1] 還是 [p+1,n][p+1,n][p+1,n] 之中
這里假設最大值在 [p+1,n][p+1,n][p+1,n] 之中,那么我們發現,假設最大值的位置為 ttt,我們對于下面三種詢問討論:
似乎滿足了二分的性質?這樣我們就可以二分去尋找最大值的位置了,詢問復雜度為 O(logn)+2=19O(logn)+2=19O(logn)+2=19
代碼:
// Problem: C2. Guessing the Greatest (hard version) // Contest: Codeforces - Codeforces Round #703 (Div. 2) // URL: https://codeforces.com/contest/1486/problem/C2 // Memory Limit: 256 MB // Time Limit: 1000 ms // // Powered by CP Editor (https://cpeditor.org)// #pragma GCC optimize(2) // #pragma GCC optimize("Ofast","inline","-ffast-math") // #pragma GCC target("avx,sse2,sse3,sse4,mmx") #include<iostream> #include<cstdio> #include<string> #include<ctime> #include<cmath> #include<cstring> #include<algorithm> #include<stack> #include<climits> #include<queue> #include<map> #include<set> #include<sstream> #include<cassert> #include<bitset> #include<list> #include<unordered_map> #define lowbit(x) x&-x using namespace std; typedef long long LL; typedef unsigned long long ull; template<typename T> inline void read(T &x) {T f=1;x=0;char ch=getchar();while(0==isdigit(ch)){if(ch=='-')f=-1;ch=getchar();}while(0!=isdigit(ch)) x=(x<<1)+(x<<3)+ch-'0',ch=getchar();x*=f; } template<typename T> inline void write(T x) {if(x<0){x=~(x-1);putchar('-');}if(x>9)write(x/10);putchar(x%10+'0'); } const int inf=0x3f3f3f3f; const int N=1e6+100; int query(int l,int r) {if(l>=r) {return -1;}printf("? %d %d\n",l,r);fflush(stdout);int x;scanf("%d",&x);return x; } int main() { #ifndef ONLINE_JUDGE // freopen("data.in.txt","r",stdin); // freopen("data.out.txt","w",stdout); #endif // ios::sync_with_stdio(false);int n;scanf("%d",&n);int pos=query(1,n),ans=-1;if(pos==query(1,pos)) {//[1,pos]int l=1,r=pos;while(l<=r) {int mid=(l+r)>>1;if(query(mid,pos)==pos) {l=mid+1;ans=mid;} else {r=mid-1;}}} else {//[pos,n]int l=pos,r=n;while(l<=r) {int mid=(l+r)>>1;if(query(pos,mid)==pos) {r=mid-1;ans=mid;} else {l=mid+1;}}}printf("! %d\n",ans);return 0; }總結
以上是生活随笔為你收集整理的CodeForces - 1486C2 Guessing the Greatest (hard version)(二分+交互)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: CodeForces - 1486B E
- 下一篇: CodeForces - 1486D M