Strange Way to Express Integers 扩展欧几里得
来源:互联网 发布:fs2you mac 编辑:程序博客网 时间:2024/06/08 15:35
题意:
给定数组数据a1,r1,a2,r2,使得存在x,x%a1=r1,x%a2=r2,求出最小的x,没有输出-1;
扩展欧几里得的定义自己去网上搜搜,我这讲一些公式的推导。
#include<cstdio>#include<cstring>#include<algorithm>using namespace std;typedef long long ll;ll egcd(ll a,ll b,ll &x,ll &y){ if(b == 0) { x = 1 ;y = 0 ; return a; } ll d=egcd(b,a%b,y,x); y -= (a/b)*x ; return d;}int main(){ ll k,a1,a2,r1,r2,d,x,y; while(~scanf("%lld",&k)) { bool flag=true; scanf("%lld%lld",&a1,&r1); k--; while(k--) { scanf("%lld%lld",&a2,&r2); d=egcd(a1,a2,x,y); if( (r2-r1)%d ) flag = false ; if( flag ) { x = (r2-r1)/d*x ; y = a2/d ; x = ( x%y +y)%y ; r1 = x*a1 + r1 ; a1 = a1*y ; } } if(flag) printf("%lld\n",r1); else printf("-1\n"); } return 0;}
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 mfrom the pairs?”
Since Elina is new to programming, this problem is too difficult for her. Can you help her?
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 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.
28 711 9
31
All integers in the input and the output are non-negative and can be represented by 64-bit integral types.
- Strange Way to Express Integers 扩展欧几里得
- poj 2891 Strange Way to Express Integers 扩展欧几里得运用
- 【POJ 2891】Strange Way to Express Integers(扩展欧几里得)
- POJ Strange Way to Express Integers 2891(扩展欧几里得)
- POJ-----2891---Strange Way to Express Integers扩展欧几里得
- POJ 2891 Strange Way to Express Integers (扩展欧几里得)
- POJ 2891 Strange Way to Express Integers(扩展欧几里得)
- poj 2891 Strange Way to Express Integers(扩展欧几里得,中国剩余定理)
- poj-2891(Strange Way to Express Integers)--中国剩余定理&&扩展欧几里得
- Strange Way to Express Integers--扩展欧几里得和中国剩余定理
- poj2891——Strange Way to Express Integers(扩展欧几里得解中国剩余定理)
- Strange Way to Express Integers (模线性方程组(扩展欧几里得))
- poj2891 Strange Way to Express Integers 扩展欧几里德的应用
- POJ 2891 Strange Way to Express Integers(扩展GCD)
- POJ 2891-Strange Way to Express Integers(扩展欧几里德)
- POJ 2891 Strange Way to Express Integers 扩展gcd
- 【POJ 2891 Strange Way to Express Integers】+ 扩展欧几里德
- [POJ2891] Strange Way to Express Integers (扩展欧几里德)
- Excel 中连续生成开始日期和结束日期之间的日期
- The C Programming Language的小代码
- 机器学习之监督学习-回归
- hdu1579(记忆深搜)
- Codeforces 840D:Destiny
- Strange Way to Express Integers 扩展欧几里得
- Spring Boot+log4j2+yml配置
- java 图形用户界面编程 之 事件处理
- JavaScript实现rgb转为16进制
- HDU 2813 One fihgt one(KM算法解决最小权值匹配)
- 感触
- VxWorks讨论群 166692882
- poj 3190
- epoll源码分析(转)