link
题意:交互题,每次可以询问一个区间的次大值,保证所有值都不相同,求最大值位置。easy是询问最多40次,hard最多20次。
交互题大部分都是二分,可以向二分考虑。
easy比较好想,假设当前区间为[l,r][l,r][l,r],中点midmidmid,先查询[l,r][l,r][l,r],得到次大值的位置pos1pos_1pos1,假设pos1<=midpos_1<=midpos1<=mid,那么就查询[l,mid][l,mid][l,mid]的次大值得到pos2pos_2pos2,如果pos1==pos2pos_1==pos_2pos1==pos2,那么最大值一定在[l,mid][l,mid][l,mid],否则在[mid+1,r][mid+1,r][mid+1,r]。这样每次操作两次,一共lognlognlogn次。
hard怎么做呢?显然是不能由easy优化过来,需要另外思考二分的方式。
考虑如果[l,r][l,r][l,r]的区间,且次大值在边界lll或者rrr上,这里假设次大值在lll处,我们是否可以通过二分找到最大值的位置呢?通过观察我们可以发现rrr的位置具有单调性,假设最大值在pospospos的位置,那么[l,r](r>=pos)[l,r](r>=pos)[l,r](r>=pos)的区间,他们查询结果都是lll即[l,r][l,r][l,r]的次大值位置,对于[l,r](r<pos)[l,r](r<pos)[l,r](r<pos)的区间,他们查询结果一定不是lll,因为在这些区间lll位置是最大值。所以可以根据这个性质进行二分。
#include<cstdio>
#include<iostream>
#include<string>
#include<cstring>
#include<map>
#include<cmath>
#include<cctype>
#include<vector>
#include<set>
#include<queue>
#include<algorithm>
#include<sstream>
#include<ctime>
#include<cstdlib>
#define X first
#define Y second
#define L (u<<1)
#define R (u<<1|1)
#define pb push_back
#define mk make_pair
#define Mid (tr[u].l+tr[u].r>>1)
#define Len(u) (tr[u].r-tr[u].l+1)
#define random(a,b) ((a)+rand()%((b)-(a)+1))
#define db puts("---")
using namespace std
;
typedef long long LL
;
typedef unsigned long long ULL
;
typedef pair
<int,int> PII
;const int N
=1000010,mod
=1e9+7,INF
=0x3f3f3f3f;
const double eps
=1e-6;int n
;int query(int l
,int r
)
{if(r
-l
+1<2) return -1;printf("? %d %d\n",l
,r
); fflush(stdout);int x
; scanf("%d",&x
);return x
;
}int main()
{
scanf("%d",&n
);int pos
=query(1,n
);int l
=1,r
=n
,mid
,ans
;if(query(1,pos
)==pos
){l
=1,r
=pos
;while(l
<r
){mid
=l
+r
+1>>1;if(query(mid
,pos
)==pos
) l
=mid
,ans
=mid
;else r
=mid
-1;}printf("! %d\n",l
); fflush(stdout);}else{l
=pos
,r
=n
;while(l
<r
){mid
=l
+r
>>1;if(query(pos
,mid
)==pos
) r
=mid
,ans
=mid
;else l
=mid
+1;}printf("! %d\n",r
); fflush(stdout);}return 0;
}
总结
以上是生活随笔为你收集整理的Codeforces Round #703 (Div. 2) Guessing the Greatest C1 C2 二分的全部内容,希望文章能够帮你解决所遇到的问题。
如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。