Strange Way to Express Integers
Time Limit: 1000MS | Memory Limit: 131072K | |
Total Submissions: 20640 | Accepted: 6946 |
Description
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 9
Sample Output
31
Hint
All integers in the input and the output are non-negative and can be represented by 64-bit integral types.
题意 给出k个同余方程组:x mod ai = ri。求x的最小正值。如果不存在这样的x,那么输出-1.不满足所有的ai互质。
解析 https://blog.csdn.net/litble/article/details/75807726 中国扩展剩余定理
1 #include<stdio.h> 2 #define pb push_back 3 #define mp make_pair 4 #define fi first 5 #define se second 6 #define all(a) (a).begin(), (a).end() 7 #define fillchar(a, x) memset(a, x, sizeof(a)) 8 #define huan printf("\n"); 9 #define debug(a,b) cout<<a<<" "<<b<<" "<<endl; 10 using namespace std; 11 const int maxn=1e5+10,inf=0x3f3f3f3f; 12 typedef long long ll; 13 ll chu[maxn],yu[maxn]; 14 ll exgcd(ll a,ll b,ll &x,ll &y) //&引用符号,修改x,y,函数返回的是a,b的最大公约数 15 { 16 if(b==0) 17 { 18 x=1;y=0; 19 return a; 20 } 21 ll gcd=exgcd(b,a%b,x,y); //递归下去 22 ll temp=x; 23 x=y;y=temp-a/b*y; 24 return gcd; 25 } 26 ll CRT(int n)//中国剩余定理 除数互质 27 { 28 ll lcm=1,x,y,ans=0; 29 for(int i=0;i<n;i++) 30 lcm*=chu[i]; //除数互质 31 for(int i=0;i<n;i++) 32 { 33 ll temp=lcm/chu[i]; 34 ll gcd=exgcd(temp,chu[i],x,y); //互质所以gcd肯定是1 x*temp%chu[i]=1 <=>x*temp+y*chu[i]=1 35 x=(x%chu[i]+chu[i])%chu[i]; //最小正整数解 36 ans=(ans+yu[i]*x*temp)%lcm; 37 } 38 return ans; 39 } 40 ll EXCRT(int n)//扩展中国剩余定理除数互不互质都可以 41 { 42 ll temp=chu[0],k=yu[0],x,y,t; 43 for(int i=1;i<n;i++) 44 { 45 ll gcd=exgcd(temp,chu[i],x,y); 46 if((yu[i]-k)%gcd)return -1;//无解 47 x*=(yu[i]-k)/gcd,t=chu[i]/gcd,x=(x%t+t)%t; 48 k=temp*x+k,temp=temp/gcd*chu[i],k%=temp; 49 } 50 k=(k%temp+temp)%temp; 51 return k; 52 } 53 int main() 54 { 55 int n; 56 while(scanf("%d",&n)!=EOF) 57 { 58 for(int i=0;i<n;i++) 59 scanf("%lld%lld",&chu[i],&yu[i]); 60 printf("%lld\n",CRT(n)); 61 } 62 return 0; 63 }
原文地址:https://www.cnblogs.com/stranger-/p/9688516.html