hdu1316 How Many Fibs?

#include <stdio.h>  
#include <stdlib.h>  
#include <string.h>  

struct node  
{  
	int len;  
	char c[200];  
}Fib[502];  

int cmp(int len,int indx,char *ch)
{
	int i,j;
	for (i=0,j=len-1;i<len;i++,j--)
	{
		if(Fib[indx].c[j]>ch[i])
			return 1;
		else if(Fib[indx].c[j]<ch[i])
			return -1;
	}
	return 0;
}

void add(int x,int y)  
{  
	int len1,len2,i,j,k;  
	len1=Fib[x].len;  
	len2=Fib[y].len;  
	for (i=0,j=0,k=0;i<len1;i++,j++)  
	{  
		Fib[x+1].c[k]=(Fib[x].c[i]-'0'+(j<len2?(Fib[y].c[j]-'0'):0))+'0';  
		k++;  //和的结果低位保存在低位
	}  
	for(i=0;i<k;i++)  
		if((Fib[x+1].c[i]-'0')>9)  
		{  
			if(Fib[x+1].c[i+1]==0)  
				Fib[x+1].c[i+1]=((Fib[x+1].c[i]-'0')/10)+'0';  
			else  
				Fib[x+1].c[i+1]=((Fib[x+1].c[i+1]-'0')+(Fib[x+1].c[i]-'0')/10)+'0';  
			Fib[x+1].c[i]=((Fib[x+1].c[i]-'0')%10)+'0';  
		}  
		if(Fib[x+1].c[len1]!=0)//两数相加最多进一位  
			Fib[x+1].len=len1+1;  
		else  
			Fib[x+1].len=len1;  
}  

int main()  
{  
	int x,y,i; 
	char s1[120],s2[120];
	strcpy(Fib[1].c,"1");  
	Fib[1].len=1;  
	strcpy(Fib[2].c,"2");  
	Fib[2].len=1;  
	for(i=3;i<=500;i++)  
		add(i-1,i-2);  
	while(scanf("%s %s",s1,s2))
	{
		int len1,len2,len;
		if(s1[0]=='0'&&s2[0]=='0')
			break;
		len1=strlen(s1);
		len2=strlen(s2);
		for (i=1;i<=500;i++)
		{
			len=Fib[i].len;
			if(len<len1)
				continue;
			else if(len1<len)
			{
				x=i;
				break;
			}
			else if(len==len1&&(cmp(len,i,s1)>=0))
			{
				x=i;
				break;
			}
		}
		for(i=500;;i--)
		{
			len=Fib[i].len;
			if(len>len2)
				continue;
			else if(len2>len)
			{
				y=i;
				break;
			}
			else if(len==len2&&(cmp(len,i,s2)<=0))
			{
				y=i;
				break;
			}
		}
		printf("%d\n",y-x+1);
	}
	return 0;  
} 

你可能感兴趣的:(hdu1316 How Many Fibs?)