1005.Number Sequence

来源:互联网 发布:好的数据分析报告 编辑:程序博客网 时间:2024/04/29 08:35

寻找循坏周期,由于只有7*7=49种情况,而且只要相邻位置的数组出现重复就是循环,故再49以内必定会找到循环,然后根据循环来求解(注意未找到循环就结束的情况要额外考虑)

#include<iostream>#include<climits>using namespace std;int main(){    int A, B, N;    int x[50];    while (cin >>A>>B>>N&&!(A==0&&B==0&&N==0))    {        int visited[7][7] = {0};        x[1] = 1;x[2] = 1;        visited[1][1] = 1;        int cnt = INT32_MAX;//循环周期        int F=0;        int flag = 0;        for (int t = 3;t <=N;t++)        {            x[t] = (x[t - 1] * A + x[t - 2] * B) % 7;            if (visited[x[t - 1]][x[t]] != 0) { cnt = t - 2 - visited[x[t - 1]][x[t]] + 1;F = visited[x[t - 1]][x[t]];flag = 1; break;}            visited[x[t - 1]][x[t]] = t - 1;        }        if (!flag) cout << x[N] << endl;        else {            int pos = (N - F +1) % cnt == 0 ? cnt : (N - F + 1) % cnt;            pos = pos + F - 1;            cout << x[pos] << endl;        }    }}
0 0
原创粉丝点击