poj 2413 How many Fibs? 打表+二分查找+大数加和模板

点击打开链接

#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
const int maxv=600+5;
string sum[maxv];
//大数加和模板
string bigsum(string s1,string s2)
{
     if(s1.length()<s2.length())
     {
          string temp=s1;
          s1=s2;
          s2=temp;
     }
     for(int i=s1.length()-1,j=s2.length ()-1;i>=0;i--,j--)
     {
          s1[i]=char(s1[i]+(j>=0?s2[j]-'0':0));
          if(s1[i]-'0'>=10)
          {
              s1[i]=char((s1[i]-'0')%10+'0');
              if(i)
                   s1[i-1]++;
              else
                   s1='1'+s1;
          }
     }
     return s1;
}
bool judge(string s1,string s2)
{
    if(s2.size()==s1.size()) {
        if(s2>s1) return true;
    }
    else {
        if(s2.size()>s1.size()) return true;
    }
    return false;
}
//二分查找
int search(string s)
{
    int left=0,right=maxv;              // 左闭右开
    while(left<right)
    {
        int mid=(left+right)>>1;
        if(sum[mid]==s) return mid;
        else {
            if(judge(sum[mid],s)) left=mid+1;           //返回true 在靠右区间继续搜索
            else right=mid;
        }
    }
    return left;
}
int main()
{
    std::ios::sync_with_stdio(false);
    cin.tie(0);
    sum[0]="1";
    sum[1]="2";
    for(int i=2;i<maxv;i++)
        sum[i]=bigsum(sum[i-1],sum[i-2]);
    string a,b;
    while(cin>>a>>b)
    {
        if(a=="0"&&b=="0") break;
        int p1=search(a);
        int p2=search(b);
        if(sum[p2]==b) p2++;
        cout<<p2-p1<<endl;
        a.clear();
        b.clear();
    }
}

猜你喜欢

转载自blog.csdn.net/m0_37428263/article/details/79979236