HDU 1005 Number Sequence
生活随笔
收集整理的這篇文章主要介紹了
HDU 1005 Number Sequence
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
【題目】??????????????????????????????????????????????????
?
Number Sequence
Time Limit: 2000/1000 MS (Java/Others)??? Memory Limit: 65536/32768 K (Java/Others) Total Submission(s): 75924??? Accepted Submission(s): 17659
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 Author CHEN, Shunbao Source ZJCPC2004 Recommend JGShining
【分析】????????????????????????????????????????????????????? 一看到這個題,就直接用遞歸做了: /*============================================================================*\* HDU 1005 Number Sequence 直接遞歸 很明顯不可行 * 2013/04/04 * @CocoonFan \*============================================================================*/ #include<iostream>using namespace std;int a, b,n; int f(int n) {if(n <3) return 1;return (a*f(n - 1) + b*f(n - 2))%7; }int main() {while(true){cin >> a >> b >> n;if(!(a||b||n)) break;cout << f(n) << endl;}return 0; }
一提交。。。。。。。。很明顯直接暴力是行不通的。
于是我就思考能不能用循環的方法來做,嗯。。。。。應該可行:
于是:
/*============================================================================*\* HDU 1005 Number Sequence 非遞歸方法 超時 * 2013/04/04 * @CocoonFan \*============================================================================*/ #include<iostream> using namespace std;int main() {int a, b, n, t1, t2, t3;while(true){cin >> a >> b >> n;if(!(a||b||n)) break;t1 = t2 = t3 = 1;for(int i = 3; i <= n; ++i){t3 = (a*t2 + b*t1)%7;t1 = t2;t2 = t3;}cout << t3 << endl;}return 0; }很遺憾最后還是超時了。。。。。。。
于是我就跪了。
后來在網上查資料看了看,原來有個規律:
?因為這是一個遞歸,結果%7之后余數只有0,1,2,3,4,5,6七種情況,由于后一項是由前兩項推出來的所以最終的結果最多只有7*7=49中可能。
有了這個規律一切就好辦了:
/*============================================================================*\* HDU 1005 Number Sequence 非遞歸方法 * 2013/04/04 * @CocoonFan \*============================================================================*/ #include<iostream> using namespace std;int main() {int a, b, n, t1, t2, t3;while(true){cin >> a >> b >> n;if(!(a||b||n)) break;n %= 49;/只需要加上這句話就夠了 t1 = t2 = t3 = 1;for(int i = 3; i <= n; ++i){t3 = (a*t2 + b*t1)%7;t1 = t2;t2 = t3;}cout << t3 << endl;}return 0; }O了終于AC了。。。。。。。。。
?
轉載于:https://www.cnblogs.com/CocoonFan/archive/2013/04/04/2999785.html
總結
以上是生活随笔為你收集整理的HDU 1005 Number Sequence的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: hdu 1054(最小顶点覆盖)
- 下一篇: 读书笔记2013第6本:《棋与人生》(二