今天学完B树之后想顺手做一道poj,依次下来今天轮到1006,但是读完题目发现这道题目似乎是个数论题目,没有思路。于是上网搜,发现这道题目是个中国余数定理的题目,没办法,研究了一晚上的中国余数定理,感觉算法导论中这部分的内容好像将不是很清楚,于是参考了http://blog.csdn.net/jiaobuchong/article/details/40585575这篇文章,终于把中国余数定理弄明白了,理论上逆元应该用扩展欧几里得算法算一下,但今天实在没时间看他了,于是手工算了一下逆元,就是代码中的a1,a2,a3,一开始是WA,后来下了测试数据发现,我的结果里面有两组数据出现了负值,果断修改了代码,顺利通过。
特别注意逆元的求解方法。
Source Code
Problem: 1006 | User: zhyh2010 | |
Memory: 240K | Time: 79MS | |
Language: C++ | Result: Accepted |
#include <iostream> using namespace std; const int period1 = 23; const int period2 = 28; const int period3 = 33; int main(int argc, char ** argv) { unsigned int m1 = period3*period2; unsigned int m2 = period3*period1; unsigned int m3 = period1*period2; unsigned int total = period1*period2*period3; unsigned int a1 = 6; unsigned int a2 = 19; unsigned int a3 = 2; int a, b, c, d; int count = 0; while (cin >> a >> b >> c >> d) { if (a == -1 && b == -1 && c == -1 && d == -1) { break; } int res; res = (m1*a1*a + m2*a2*b + m3*a3*c) % total; /*if (res == 0) { res += total; } res -= d;*/ res -= d; res <= 0 ? res += total : res; // output cout << "Case " << ++count << ": the next triple peak occurs in " << res << " days." << endl; } return 0; }