Codeforces Round #703 (Div. 2)C1&C2 Guessing the Greatest(二分)

题意:
交互题。
query l,r区间内第二大的数,要求得到整个数组最大的数。
思路:首先我们对整体数组进行query
找到第二大的数所在的位置,设这个位置为p。
然后分别对[1,p]和[p,n]进行query,看最大的数是在p的左端还是右端。
如果在左端,那我们二分左端的区间左端点,找到最右的左端点a满足[a,p]的query和[1,p]一致,此时得出答案是a。
在右端同理。
PS:这题二分细节有点多,有点坑。

#include<bits/stdc++.h>
using namespace std;
#define ll long long
int n;
int l ,r;
int ans = 0,ans1=0,ans2=0;
bool check(int x)
{
	cout<<"? "<<ans<<" "<<x<<endl;
	cout.flush();
	int res = 0;
	cin>>res;
	if(res == ans)return 1;
	else return 0;
}
bool check2(int x)
{
	cout<<"? "<<x<<" "<<ans<<endl;
	cout.flush();
	int res = 0;
	cin>>res;
	if(res == ans)return 1;
	else return 0;
}
int main()
{
	 
	cin>>n;
	l = 1,r = n;
	cout<<"? "<<l<<" "<<r<<endl;
	cout.flush();
 
	cin>>ans;
	if(r-l<=1)
	{
		if(l==ans)
		cout<<"! "<<r<<endl;
		else cout<<"! "<<l<<endl;
		return 0;
	}	
	if(l==ans)goto ok1;
	cout<<"? "<<l<<" "<<ans<<endl;
	cout.flush();
	cin>>ans1;
	ok1:;
	if(ans==r)goto ok2;
	cout<<"? "<<ans<<" "<<r<<endl;
	cout.flush();
	cin>>ans2;
	ok2:;
	if(ans1==ans){
		r = ans;
		int ok = l;
		while(l<r)
		{
			int mid = (l+r)/2;
 
 			if(mid==ans)break;
			if(check2(mid))
			{
				ok = mid;
				
				l = mid+1;				
			}
			else{
				
				r = mid;
			}
 
		}
		cout<<"! "<<ok<<endl;
	}
	else
	{
		l = ans;
		int ok = r;
		while(l<r)
		{
			int mid = (l+r)/2;
 
 			if(mid==ans)break;
			if(check(mid))
			{
				ok = mid;
				r = mid;
				
			}
			else{
				l = mid+1;
			}
			
		}
		cout<<"! "<<ok<<endl;
	}
	 
} 
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值