HDOJ 1041 笨...

第一种TLE 第二种AC,不过我感觉我的方法不太好。。去学习一下别人的- -
#include<stdio.h>
#include<string.h>
void PLUS (char *a,char *b,char *res);
int main()
{
	int n;
	while(scanf("%d",&n)!=EOF)
	{   int i;
	 char a[400]={'1'};
	 char b[400]={'1'};
	 char  res[400]={'\0'};
	 char  sum[400]={'\0'};
	 if(n==1) printf("%d\n",0);
	 else if(n==2||n==3)  printf("%d\n",1);
	 else
	 {
	 	for(i=4;i<=n;i++)
		{PLUS(a,a,res);
		PLUS(res,b,sum);
		strcpy(a,b);
		strcpy(b,sum);
		}
		printf("%s\n",sum);
	 }
	}
	return 1;
}

void PLUS (char *a,char *b,char *res)
{
	int La=strlen(a),Lb=strlen(b);
    char sum[400]={'\0'};
    int  cnt,k,i,j;
    for(i=0;i<La&&i<Lb;i++)
		sum[i]=a[La-1-i]+b[Lb-1-i]-'0'-'0';
	 if(i==La)
		while (i<Lb)  sum[i]=b[Lb-1-i]-'0',i++;
	 else
		while (i<La)  sum[i]=a[La-1-i]-'0',i++;
	 for(j=0;j<i;j++)
	 if(sum[j]>=10) sum[j]%=10,sum[j+1]+=1;
	 for(i=i+2;;i--)
	 if(sum[i]!=0)
		{cnt=i;break;}
	for(i=cnt,k=0;i>=0;k++,i--)
	   res[k]=sum[i]+48;
}

//修改:先计算出所有结果存储到字符串数组里面

<pre name="code" class="html">#include<stdio.h>
#include<string.h>
void PLUS (char *a,char *b,char *res);
int main()
{   int i;
	char a[400]={'1'};
	char b[400]={'1'};
	char  res[400]={'\0'};
	char  sum[400]={'\0'};
	char ans[1001][400]={"0","0","1","1"};
	for(i=4;i<=1000;i++)
		{
		PLUS(a,a,res);
		PLUS(res,b,sum);
		strcpy(a,b);
		strcpy(b,sum);
		strcpy(ans[i],sum);
		}
	int n;
	while(scanf("%d",&n)!=EOF)
	{
    printf("%s\n",ans[n]);

	}
	return 1;
}

void PLUS (char *a,char *b,char *res)
{
	int La=strlen(a),Lb=strlen(b);
    char sum[400]={'\0'};
    int  cnt,k,i,j;
    for(i=0;i<La&&i<Lb;i++)
		sum[i]=a[La-1-i]+b[Lb-1-i]-'0'-'0';
	 if(i==La)
		while (i<Lb)  sum[i]=b[Lb-1-i]-'0',i++;
	 else
		while (i<La)  sum[i]=a[La-1-i]-'0',i++;
	 for(j=0;j<i;j++)
	 if(sum[j]>=10) sum[j]%=10,sum[j+1]+=1;
	 for(i=i+2;;i--)
	 if(sum[i]!=0)
		{cnt=i;break;}
	for(i=cnt,k=0;i>=0;k++,i--)
	   res[k]=sum[i]+48;
}


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值