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

题目链接:https://codeforces.com/contest/1486/problem/C1

There is an array a of n different numbers. In one query you can ask the position of the second maximum element in a subsegment a[l…r]. Find the position of the maximum element in the array in no more than 40 queries.

A subsegment a[l…r] is all the elements al,al+1,…,ar. After asking this subsegment you will be given the position of the second maximum from this subsegment in the whole array.

Input
The first line contains a single integer n (2≤n≤105) — the number of elements in the array.

Interaction
You can ask queries by printing “? l r” (1≤l<r≤n). The answer is the index of the second maximum of all elements al,al+1,…,ar. Array a is fixed beforehand and can’t be changed in time of interaction.

You can output the answer by printing “! p”, where p is the index of the maximum element in the array.

You can ask no more than 40 queries. Printing the answer doesn’t count as a query.

After printing a query do not forget to output end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use:

fflush(stdout) or cout.flush() in C++;
System.out.flush() in Java;
flush(output) in Pascal;
stdout.flush() in Python;
see documentation for other languages
Hacks

To make a hack, use the following test format.

In the first line output a single integer n (2≤n≤105). In the second line output a permutation of n integers 1 to n. The position of n in the permutation is the position of the maximum


分析

第一次找 1 到 n 的区间找到第二大的位置 x ,然后即可判断出最大值的位置:如果 1 到 x 区间第二小还是位置 x ,那么最大值的位置就在 1 到 x-1 中。
知道最大值的位置区间,再二分即可。

代码
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;

int er1(int l,int r,int x)
{
	if(l == r) return l;
	int y,ans = 1e9;
	while(l <= r)
	{
		int mid = (l + r) >> 1;
		cout<<"? "<<x<<" "<<mid<<endl;
		cin>>y;
		if(x == y) r = mid - 1, ans = min(ans, mid);
		else l = mid + 1;
	}
	return ans;
}

int er2(int l,int r,int x)
{
	if(l == r) return l;
	int y,ans = 0;
	while(l <= r)
	{
		int mid = (l + r) >> 1;
		cout<<"? "<<mid<<" "<<x<<endl;
		cin>>y;
		if(x == y) l = mid + 1, ans = max(ans, mid);
		else r = mid - 1;
	}
	return ans;
}

void ask(int l,int r)
{
	int x,y,ans;
	cout<<"? "<<l<<" "<<r<<endl;
	cin>>x;
	if(x > l)
	{
		cout<<"? "<<l<<" "<<x<<endl;
		cin>>y;
		if(x == y) ans = er2(l, x - 1, x);
		else ans = er1(x + 1, r, x);
	}
	else
	{
		ans = er1(x + 1, r, x);
	}
	cout<<"! "<<ans<<endl;
}

int main() {
	int n;
	cin>>n;
	ask(1, n);
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值