How Many Fibs?
题目来自杭电:http://acm.hdu.edu.cn/showproblem.php?pid=1316 Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others) Problem Description Given two numbers a and b,calculate how many Fibonacci numbers are in the range [a,b]. Input Output Sample Input Sample Output Source #include <iostream>
#include <cstring>
using namespace std;
const int MAX = 1000;
const int LEN = 100 + 10;
int aFib[MAX][LEN];
//相加
int add(int *x,int *y,int *z){
int i;
int temp;
int carry = 0;
for(i = 0;i < LEN;i++){
temp = x[i] + y[i] + carry;
z[i] = temp % 10;
carry = temp /10;
}
return 0;
}
//获得表
int Fib(){
int i;
memset(aFib,0,sizeof(aFib));
aFib[0][0] = 1;
aFib[1][0] = 2;
for(i = 2;i < MAX;i++)
add(aFib[i-1],aFib[i-2],aFib[i]);
return 0;
}
//比较
int compare(char *x,int *y){
int i,j;
int temp[LEN] = {0};
for(i = 0,j = strlen(x) - 1;j >= 0;i++,j--)
temp[i] = x[j] - '0';
for(i = LEN - 1;i >= 0;i--){
if(temp[i] > y[i])
return 0;
else if(temp[i] < y[i])
return 1;
}
return 2;
}
int main()
{
char a[LEN],b[LEN];
int head,tail;
int i,j;
int temp;
Fib();
while(cin >> a >> b){
if(strcmp(a,"0") == 0 && strcmp(b,"0") == 0)
break;
for(i = 0;i < MAX;i++){
temp = compare(a,aFib[i]);
if(temp){
head = i;
break;
}
}
for(;i < MAX;i++){
temp = compare(b,aFib[i]);
if(temp == 1){
tail = i;
break;
}
else if(temp == 2){
tail = i + 1;
break;
}
}
cout << tail - head << endl;
}
return 0;
}
小结:大数问题,思想是先建立斐波那契表,然后比对,通过数组下标计算个数,建立斐波那契数表的过程也就是大数相加的过程,这个不难,巧妙地是统计个数,原来我也用到了vector,一个一个比较,虽然AC了,但是效率很低,然后看了别人的代码,灵光一闪,只要比较首尾就可以了,然后通过下标技术就可以了,于是又重写了别人的代码,基本上没变;这种方法比我之前的效率高很多 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |