hdu 1316

How Many Fibs?

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others) Total Submission(s): 2282    Accepted Submission(s): 926

Problem Description
Recall the definition of the Fibonacci numbers: f1 := 1 f2 := 2 fn := fn-1 + fn-2 (n >= 3)
Given two numbers a and b, calculate how many Fibonacci numbers are in the range [a, b].
 
Input
The input contains several test cases. Each test case consists of two non-negative integer numbers a and b. Input is terminated by a = b = 0. Otherwise, a <= b <= 10^100. The numbers a and b are given with no superfluous leading zeros.
 
Output
For each test case output on a single line the number of Fibonacci numbers fi with a <= fi <= b.
 
Sample Input
10 100 1234567890 9876543210 0 0
 
Sample Output
5 4
 
解题思路:大整数相加,存放到2维数组里,然后二分查找就可以了。本题对大整数是一个很好的练习。
 
#include <iostream>
#include <cstdlib>
#include <cstring>
#define M 105
using namespace std;
char
data[1000][M+2];
char
a[M+2],b[M+2];
int
cmp_ab(char *s1,char *s2)
{

    for
(int k=0;k<=105;k++)
      {

         if
(k==105)
             return
s1[k]-s2[k];
          if
(s1[k]!=s2[k])  return s1[k]-s2[k];

      }

}



int
find1(int i,char *x)
{

    int
low=0,high=i,mid;
    while
(low<=high)
    {

        mid=(low+high)/2;
        int
value=cmp_ab(x,data[mid]);
        if
(value>0)  low=mid+1;
        if
(value==0) return mid-1;
        if
(value<0)  high=mid-1;
    }

     return
high; //这时候high小于low
}

int
find2(int i,char *x)
{

    int
low=0,high=i,mid;
    while
(low<=high)
    {

        mid=(low+high)/2;
        int
value=cmp_ab(x,data[mid]);
        if
(value>0)  low=mid+1;
        if
(value==0) return mid+1;
        if
(value<0)  high=mid-1;
    }

     return
low; //这时候 low大于high
}



int
main()
{

  int
i,j,p;
  //memset(data,0,sizeof(data));
  data[0][105]=1;
  data[1][105]=2;
  i=2;p=105;
  while
(data[i-1][5]<=1)
  {

    for
(j=105;j>=p;j--)
    data[i][j]=data[i-1][j]+data[i-2][j];

    for
(j=105;j>=p;j--)
    {

         int
c=data[i][j]/10;
         if
(c>=1)
         {

             data[i][j]=data[i][j]%10;
             data[i][j-1]=data[i][j-1]+c;
         }

    }

     if
(data[i][p-1]>0) p--;
    i++;
  }


    while
(cin>>a>>b)
{

    if
(a[0]=='0'&&b[0]=='0') break;
     int
len1=strlen(a)-1;
     int
len2=strlen(b)-1;
     int
k;
     for
(int d=len1,k=105;d>=0;d--,k--)
        {

             a[k]=a[d]-'0';
             a[d]=0;
        }

      for
(int d=len2,k=105;d>=0;d--,k--)
        {

             b[k]=b[d]-'0';
             b[d]=0;
        }

    /*for(int i=0;i<=105;i++)
    cout<<(int)b[i];
    cout<<endl;
    */

    int
lt=find1(i-1,a);
    int
rt=find2(i-1,b);
    //cout<<"lt="<<lt<<endl;
    //cout<<"rt="<<rt<<endl;
   //cout<<lt<<endl;

    cout<<rt-lt-1<<endl;
    memset(a,0,sizeof(a));
    memset(b,0,sizeof(b));

}


    return
0;
}
posted @ 2012-09-19 21:05  兴安黑熊  阅读(189)  评论(0编辑  收藏  举报