题解 P4413 【[COCI2006-2007#2] R2】

这道题你当然可以一遍过

#include<iostream>
using namespace std;
int a,b;
int main()
{
    cin>>a>>b;
    cout<<b*2-a<<endl;
}

但是你真的这样写的话对你个人并没有任何作用
而且大佬会觉得你很无脑

那我们再来看一眼这白给的题面

除了直接输出$S*2-R1$外,我们还可以尝试用新的方法去做。

那就是:
#### 二分查找
(这道题用来练手真的很不错)

因为题目给了数据范围,那我们就可以在$[-1000,+1000]$这个区间去寻找答案。

bool check(int x) 
{
    return (r1+x)/2<s;
}

定义一个check函数,当当前答案可行,就返回true,否则返回False。

int so(int l,int r)
{
    if(l==r) return l+1;
    int mid=(l+r+1)/2;
    if(check(mid)) return so(mid,r);//mid可行的话就在右区间搜索
    else return so(l,mid-1); 
}

这是我们的搜索函数(也就是灵魂)当当前答案可行的话,就在右区间找更优解,否则就转向左区间。直到不能搜索为止。

附上完整代码

#include<bits/stdc++.h>
using namespace std;
int r1,r2,s;
bool check(int x) 
{
    return (r1+x)/2<s;
}
int so(int l,int r)
{
    if(l==r) return l+1;
    int mid=(l+r+1)/2;
    if(check(mid)) return so(mid,r);//mid可行的话就在右区间搜索
    else return so(l,mid-1); 
}
int main()
{
    cin>>r1>>s;
    cout<<so(-1000,1000)<<endl;
    return 0;
}

最后说一句

WRY is the loveliest person in the world!!!

猜你喜欢

转载自www.cnblogs.com/lizinuo/p/10089886.html