复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
微软招聘信息(主要针对已经有工作经验的)Number Sequence
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others) Total Submission(s): 68329 Accepted Submission(s): 15854Problem DescriptionA 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).InputThe 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.OutputFor 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
AuthorCHEN, Shunbao
SourceZJCPC2004
RecommendJGShining
这个题关键就是思路的问题,我刚开始也没有搞懂该怎样算,最后也是看了别人的思路才明白,其实就是一个循环数,可以看得出来f(n)是对7取的模就可得肯定是0-6之间的数,而f(n) = (a *f(n - 1) + b* f(n - 2))%7,所以从当有两个数和前面两个数一样的时候,f(n)的值就开始了循环了,从0-6中任取两个数可以有7*7= 49种组合,所以在第51个之内一定一定会有两个连续的数和前面的某两个连续的数相等,此时循环就开始了,后面的f(n)的值就不用算了,只需要根据循环开始位置和周期就可得出了。
复制代码
这是别人的代码,C++的,
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24#include <iostream> using namespace std; int main() { int A,B; int N; int f[50]; while(cin>>A>>B>>N) { if(A==0&&B==0&&N==0)break; int n=3; f[1]=f[2]=1; for(n=3;n!=50;++n) { f[n]=(A*f[n-1]+B*f[n-2])%7; if(f[n]==1&&f[n-1]==1)break; } N=N%(n-2); if(N==0)cout<<f[(n-2)]<<endl; else cout<<f[N]<<endl; } return 0; }
我的源代码:
复制代码
虽然没有他的代码简洁,但是好在跑的比他的快乐,0ms过的
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36#include<stdio.h> int main(void) { int i, j, a, b, f[51], k, m; long n; while(1) { f[1] = 1; f[2] = 1; m = 0; scanf("%d%d%ld", &a, &b, &n); getchar(); if(a == 0 && b == 0 && n == 0) break; for(i = 3;i < 51;i++) { f[i] = (a * f[i - 1] + b * f[i - 2]) % 7; for(j = 2;j < i;j++) { if(f[j - 1]==f[i - 1] && f[j]==f[i]) { m = j - 1; k = i - j; break; } } if(m != 0) break; } if(n < m) printf("%dn", f[n]); else printf("%dn", f[(n - m) % k + m]); } return 0; }
最后
以上就是高贵砖头最近收集整理的关于杭电 ACM 1004Number Sequence的全部内容,更多相关杭电内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复