牛客网 Wannafly挑战赛9 C.列一列-sscanf()函数

 
C.列一列
 
时间限制:C/C++ 1秒,其他语言2秒
空间限制:C/C++ 262144K,其他语言524288K
64bit IO Format: %lld

题目描述

小W在计算一个数列{An},其中A1=1,A2=2,An+2=An+1+An。尽管他计算非常精准,但很快他就弄混了自己的草稿纸,他找出了一些他计算的结果,但他忘记了这些都是数列中的第几项。

输入描述:

每行包括数列中的一项Ak(k<=100000)。

总行数T<=30。

输出描述:

对于每一项Ak,输出一行包括一个正整数k表示输入中数是数列的第几项。

示例1

输入

2
3
5
8
13

输出

2
3
4
5
6




这个题真的是大数了,递推到后面的数就很大了,就超过int的范围了。
我感觉输入的时候要按字符数组输入(试了一下直接输大数ull的不行)
代码,直接unsigned long long的可以,取模的也可以。取模的话有可能模后的数相同,所以在判断的数上处理一下,因为只有很大的数才会取模之后发生变化,直接判断输入的字符串的长度就可以。
因为感觉sscanf函数有点意思,所以才想写题解。。。
这个题用java写大数也可以,但是我没写(;´д`)ゞ

代码1: 

 1 //C-ull版
 2 #include<iostream>
 3 #include<cstring>
 4 #include<cstdio>
 5 #include<algorithm>
 6 #include<cmath>
 7 #include<queue>
 8 #include<stack>
 9 #include<map>
10 using namespace std;
11 typedef unsigned long long ull;
12 const int maxn=1e5;
13 ull a[maxn];
14 void fun(){
15     a[0]=0;a[1]=1;a[2]=2;
16     for(int i=3;i<=maxn;i++)
17         a[i]=a[i-1]+a[i-2];
18 }
19 char s[maxn];
20 int main(){
21     ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
22     fun();
23     while(cin>>s){
24         int len=strlen(s);
25         ull n=0;
26         for(int i=0;i<len;i++)
27             n=n*10+s[i]-'0';
28         for(int i=1;i<=maxn;i++){
29             if(a[i]==n){
30                 cout<<i<<endl;
31                 break;
32             }
33         }
34     }
35     return 0;
36 }
37 */


代码2:

 1 //C-取模版
 2 #include<iostream>
 3 #include<cstring>
 4 #include<cstdio>
 5 #include<cmath>
 6 #include<algorithm>
 7 #include<queue>
 8 using namespace std;
 9 const int mod=1e9;
10 const int maxn=1e5+10;
11 int a[maxn];
12 void fun(){
13     a[1]=1;a[2]=2;
14     for(int i=3;i<=maxn;i++)
15         a[i]=(a[i-1]+a[i-2])%mod;
16 }
17 char s[maxn];
18 int main(){
19     int n;
20     fun();
21     ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
22     while(cin>>s){
23         int len=strlen(s);
24         if(len<10)sscanf(s,"%d",&n);
25         else sscanf(s+(len-9),"%d",&n);
26         for(int i=1;i<=maxn;i++){
27             if(a[i]==n){
28                 cout<<i<<endl;
29                 break;
30             }
31         }
32     }
33     return 0;
34 }

sscanf是个好东西。

溜了。

 
原文地址:https://www.cnblogs.com/ZERO-/p/9711181.html