首页 > 学院 > 开发设计 > 正文

1005.Number Sequence

2019-11-06 07:01:18
字体:
来源:转载
供稿:网友

寻找循坏周期,由于只有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; } }}
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表