POJ 2891 Strange Way to Express Integers 中国剩余定理 模板 数论
题目链接: http://poj.org/problem?id=2891
题目描述: m % p1 = q1, m % p2 = q1 ...... 给出N组p1, q1, p2, p2.... pn, qn 让你求满足条件的最小m, 如果m不存在, 输出-1
解题思路: 感觉这个才是裸的中国剩余定理........这个模板很不错
代码:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#include <cstdio> #include <cstring> #include <iostream> #include <stack> #include <queue> #include <map> #include <algorithm> #include <vector> using namespace std; typedef long long ll; ll ex_gcd(ll a,ll b,ll &x,ll &y) { if(b == 0){ x = 1; y = 0; return a; } ll r = ex_gcd(b,a%b,x,y); ll t = x; x = y; y = t - a/b*y; return r; } int main() { ll i,n,a1,r1,a2,r2,a,b,c,x0,y0; while(scanf("%lld",&n)!=EOF){ bool flag = 1; scanf("%lld%lld",&a1,&r1); for( i=1;i<n;i++){ scanf("%lld%lld",&a2,&r2); a = a1; b = a2; c = r2-r1; ll d = ex_gcd(a,b,x0,y0); if(c%d!=0){ flag = 0; } ll t = b/d; x0 = (x0*(c/d)%t+t)%t;//保证x0为正 r1 = a1*x0 + r1; a1 = a1*(a2/d); } if(!flag){ puts("-1"); continue; } printf("%lld\n",r1); } return 0; }
思考: 整理整理, 整理一堆模板.....
posted on 2017-09-01 16:17 FriskyPuppy 阅读(130) 评论(0) 编辑 收藏 举报