【hdoj1005】Number Sequence

Number Sequence
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 130189 Accepted Submission(s): 31676


Problem Description
A number sequence is defined as follows:

f(1) = 1, f(2) = 1, f(n) = (A * f(n - 1) + B * f(n - 2)) mod 7.

Given A, B, and n, you are to calculate the value of f(n).


Input
The input consists of multiple test cases. Each test case contains 3 integers A, B and n on a single line (1 <= A, B <= 1000, 1 <= n <= 100,000,000). Three zeros signal the end of input and this test case is not to be processed.


Output
For each test case, print the value of f(n) on a single line.


Sample Input
1 1 3
1 2 10
0 0 0

Sample Output 2
5

题意:Fibnacci数列的变形,每个结论要对7取余,所以满足所有情况的序列的最小周期为49,所以我就直接写了这个程序

code:

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <string>
using namespace std;
int num[50];
void solve(int a,int b)
{
    num[1]=1;
    num[2]=1;
    for(int i=3;i<51;i++)
        num[i]=(b*num[i-2]+a*num[i-1])%7;
}
int main()
{
    int a,b,n;
    while(scanf("%d%d%d",&a,&b,&n)!=EOF)
    {
        if(!a&&!b&&!n)
            break;
        if(n==1||n==2)
            printf("1\n");
        else{
            solve(a,b);
            printf("%d\n",num[n%49]);
        }

    }
    return 0;
}

在杭电上提交竟然过了,我发现一个问题,当n%49==0的时候,我的num【0】是没有赋值的,然而。。它过了。。。后来测了很多数据,num【49】都是1.于是我的代码改成了这样,还是过了:

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <string>
using namespace std;
int num[50];
void solve(int a,int b)
{
    num[1]=1;
    num[2]=1;
    for(int i=3;i<51;i++)
        num[i]=(b*num[i-2]+a*num[i-1])%7;
}
int main()
{
    int a,b,n;
    while(scanf("%d%d%d",&a,&b,&n)!=EOF)
    {
        if(!a&&!b&&!n)
            break;
        if(n==1||n==2)
            printf("1\n");
        else{
            solve(a,b);
            num[0]=1;
            printf("%d\n",num[n%49]);
        }

    }
    return 0;
}














猜你喜欢

转载自blog.csdn.net/nininicrystal/article/details/48344119
今日推荐