本文主要是介绍POJ2891【中国剩余定理】,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
原题:
Elina is reading a book written by Rujia Liu, which introduces a strange way to express non-negative integers. The way is described as following:
Choose k different positive integers a1, a2, …, ak. For some non-negative m, divide it by every ai (1 ≤ i ≤ k) to find the remainder ri. If a1, a2, …, ak are properly chosen, m can be determined, then the pairs (ai, ri) can be used to express m.
“It is easy to calculate the pairs from m, ” said Elina. “But how can I find m from the pairs?”
Since Elina is new to programming, this problem is too difficult for her. Can you help her?
Input
The input contains multiple test cases. Each test cases consists of some lines.
- Line 1: Contains the integer k.
- Lines 2 ~ k + 1: Each contains a pair of integers ai, ri (1 ≤ i ≤ k).
Output
Output the non-negative integer m on a separate line for each test case. If there are multiple possible values, output the smallest one. If there are no possible values, output -1.
Sample Input
2 8 7 11 9Sample Output
31Hint
All integers in the input and the output are non-negative and can be represented by 64-bit integral types.
题目大意:
找到一个数x,满足n组等式,x/第一个数,余数为第二个数。
即中国剩余定理的模板题,求解一元线性方程。
解题思路:
套模板
代码:
#include<iostream>
#include<stdio.h>
using namespace std;
long long exgcd(long long a,long long b,long long &x,long long &y){if(b==0){x=1,y=0;return a;}long long q=exgcd(b,a%b,y,x);y-=a/b*x;return q;
}
int main(){long long a1,c1,a2,c2,x,y,t;long long n;while(cin>>n){long long flag=1;cin>>a1>>c1;for(long long i=1;i<n;i++){cin>>a2>>c2;long long q=exgcd(a1,a2,x,y);if((c2-c1)%q!=0){flag=0;}t=a2/q;x=((x*(c2-c1)/q)%t+t)%t;//cout<<x;c1=c1+a1*x;a1=a1*(a2/q);}if(flag==0){cout<<"-1"<<endl;continue;}cout<<c1<<endl;}return 0;
}
这篇关于POJ2891【中国剩余定理】的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!