Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ UVA 10077-为什么是二进制搜索?_C++_Algorithm_Binary Search - Fatal编程技术网

C++ UVA 10077-为什么是二进制搜索?

C++ UVA 10077-为什么是二进制搜索?,c++,algorithm,binary-search,C++,Algorithm,Binary Search,我正在努力提高CP。我遇到了这个问题-。虽然我头脑中有一个天真的BFS解决方案O(2^N),但它显然给了我一点启发 string bfs(int t1,int t2) { queue<pair<VII,string>> st; st.push({{0,1,1,2,1,1},"L"}); st.push({{1,1,2,1,1,0},"R"}); while(!st.empty()) { VII u=st.front(

我正在努力提高CP。我遇到了这个问题-。虽然我头脑中有一个天真的BFS解决方案O(2^N),但它显然给了我一点启发

string bfs(int t1,int t2)
{
    queue<pair<VII,string>> st;
    st.push({{0,1,1,2,1,1},"L"});
    st.push({{1,1,2,1,1,0},"R"});
    while(!st.empty())
    {
        VII u=st.front().first;
        string v=st.front().second;
        st.pop();
        //cout<<u[2]<<' '<<u[3]<<endl;
        if(u[2]==t1 && u[3]==t2)
        return v;
        st.push({{u[0],u[1],u[0]+u[2],u[1]+u[3],u[2],u[3]},v+"L"});
        st.push({{u[2],u[3],u[2]+u[4],u[3]+u[5],u[4],u[5]},v+"R"});
    }
    return "";
}
字符串bfs(int t1,int t2)
{
队列st;
圣普什({0,1,1,2,1,1},“L”});
st.push({1,1,2,1,1,0},“R”});
而(!st.empty())
{
VII u=第一个圣前();
字符串v=st.front().second;
圣普();

//cout您试图在无限区间内找到目标数
lo=(0,1)hi=(1,0)
。 正如PDF所说,您可以通过执行
mid=(lo[0]+hi[0])/(lo[1]+hi[1])
找到间隔的中点。 向左或向右的决定取决于
mid
与目标号码的比较。 如果向左,将发出一个
L
,并在间隔
lo=lo hi=mid
中开始搜索。 如果向右移动,将发出一个
R
,并在间隔
lo=mid hi=hi
中开始搜索。 重复此操作直到
mid==target

下面是Python中的一个快速解决方案:

from fractions import Fraction
def walk(lo, hi, tgt):
    mid = (lo[0] + hi[0], lo[1] + hi[1])
    fmid = Fraction(mid[0], mid[1])
    if tgt == fmid:
        return
    if tgt < fmid:
        yield 'L'
        yield from walk(lo, mid, tgt)
    else:
        yield 'R'
        yield from walk(mid, hi, tgt)

print(list(walk((0,1), (1,0), Fraction(878, 323))))
从分数导入分数
def步行(低、高、tgt):
mid=(低[0]+hi[0],低[1]+hi[1])
fmid=分数(中间[0],中间[1])
如果tgt==fmid:
回来
如果tgt
好的,所以只需看到它们的分数就足够了。现在理解了,因为我以前不确定。