1005 Number Sequence(HDU)

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1005

Number Sequence

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 85249    Accepted Submission(s): 20209

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

解析:

这是一道寻找循环点的问题,可能很多人在杭电上通过了这个题目,但是我建议大家将自己的代码再贴到另一个OJ上进行测试http://zju.acmclub.com/index.php?app=problem_title&id=1&problem_id=2603

很多人都认为周期是49,但是给出的解题报告都不是很有说服力。

所以,我们可以寻找循环的开头以及周期,然后输出,这样能够保证正确性,当然一开始的记录数组最好能够相对大一些,不然仍然不能通过测试。



代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#define min(a,b) (a<b?a:b)
#define max(a,b) (a>b?a:b)
#define swap(a,b) {(a)=(a)^(b); (b)=(a)^(b); (a)=(a)^(b);}
#define MAXN 65535
#define INF 1e9

int f[1200];
int main(){
    int a,b,n;
    int i, j;
    int flag, term, temp, begin;
    while(~scanf("%d%d%d", &a, &b, &n), (a||b||n)){
        memset(f, 0, sizeof(f));
        f[1]=1;
        f[2]=1;
        term = n;
        flag = 0;
        for(i=3; i<=n&&!flag; i++){
            f[i] = (a*f[i-1]+b*f[i-2])%7;
            for(j = 2; j<i; j++){
                if(f[i]==f[j]&&f[i-1]==f[j-1]){
                    term = i-j;
                    begin = j-2;
                    flag = 1;
                    break;
                }
            }
        }
        if(flag)
            printf("%d
", f[begin+(n-1-begin)%term+1]);
        else
            printf("%d
", f[n]);
    }
    return 0;
}
原文地址:https://www.cnblogs.com/suncoolcat/p/3331289.html