Guessing the Greatest (easy version) -(交互+二分)

博客围绕询问区间 [ l, r ] 内求最大值位置的问题展开。已知需根据区间内第二大值的位置来求解,简单版本最多询问40次。解题思路是对区间进行二分,每次询问两次第二大值,借此确定最大值所在区间并缩小区间,还给出了对应代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接:点击进入
题目

在这里插入图片描述

题意

询问区间 [ l , r ] ,给你区间内的第二大的值的位置,让你求最大值的位置( 简单版本,最多询问40次 )

思路

二分区间都询问 两次 第二大的值,借用第二大值确定最大值所在区间,然后缩小区间。

代码
#include<iostream>
#include<string>
#include<map>
#include<set>
//#include<unordered_map>
#include<queue>
#include<cstdio>
#include<vector>
#include<cstring>
#include<algorithm>
#include<iomanip>
#include<cmath>
#include<fstream>
#define X first
#define Y second
#define best 131 
#define INF 0x3f3f3f3f3f3f3f3f
#define pii pair<int,int>
#define lowbit(x) x & -x
#define inf 0x3f3f3f3f
//#define int long long
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const double eps=1e-7;
const double pai=acos(-1.0);
const int N=2e4+10;
const int maxn=1e6+10;
const int mod=1e9+7;
int t,n,m,k;
int check(int l,int r)
{
	int x;
	cout<<"? "<<l<<' '<<r<<endl;
	cout.flush();
	cin>>x;
	return x;
}
int main() 
{
//	ios::sync_with_stdio(false);
//	cin.tie(0);cout.tie(0);
	cin>>n;
	int l=1,r=n;
	while(l<r)
	{
		int mid=(l+r)>>1;
		int pos=check(l,r);
		if(r-l==1)
		{
			if(l!=pos) break;
			else l=r; break;
		}
		if(pos<=mid)
		{
			int tmp=check(l,mid);
			if(tmp!=pos)
				l=mid+1;
			else
				r=mid;
		}
		else
		{
			if(mid+1<r)
			{
				int tmp=check(mid+1,r);
				if(tmp!=pos)
					r=mid;
				else
					l=mid+1;
			}
			else r=mid;
		}
	}
	cout<<"! "<<l<<endl;
	cout.flush();
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值