欢迎访问~原文出处——博客园-zhouzhendong

去博客园看该题解


题目传送门 - POJ2891


题意概括

  给出k个同余方程组:x mod ai = ri。求x的最小正值。如果不存在这样的x,那么输出-1.不满足所有的ai互质。


题解

  UPD(2018-08-07):

  本题做法为扩展中国剩余定理。

  我写了一篇证明:链接:https://www.cnblogs.com/zhouzhendong/p/exCRT.html

  代码就不要看了,很久之前写的,太丑了。


代码

#include <cstring>
#include <cstdio>
#include <algorithm>
#include <cstdlib>
#include <cmath>
using namespace std;
typedef long long LL;
const int N=100005;
LL ex_gcd(LL a,LL b,LL &x,LL &y){
if (!b){
x=1,y=0;
return a;
}
LL ans=ex_gcd(b,a%b,y,x);
y-=(a/b)*x;
return ans;
}
LL m,a[N],n[N];
LL solve(){
LL a1,a2,n1,n2,c,d,k1,k2,K,t;
a1=a[1],n1=n[1];
for (int i=2;i<=m;i++){
a2=a[i],n2=n[i],d=ex_gcd(n1,n2,k1,k2),c=a2-a1;
if (c%d)
return -1;
K=c/d*k1,t=n2/d,K=(K%t+t)%t,a1+=n1*K,n1=n1/d*n2;
}
return a1;
}
int main(){
while (~scanf("%lld",&m)){
for (int i=1;i<=m;i++)
scanf("%lld%lld",&n[i],&a[i]);
printf("%lld\n",solve());
}
return 0;
}

  

最新文章

  1. 【初窥javascript奥秘之事件机制】论“点透”与“鬼点击”
  2. iOS五种本地缓存数据方式
  3. sql 数据库 初级 个人学习总结(一)
  4. KTV点歌系统
  5. POJ3185(简单BFS,主要做测试使用)
  6. android内核读取file文件
  7. KeyEvent
  8. Java面向对象面试案例
  9. C语言之ASCII码
  10. hdu 1007 最近点对问题(Splay解法)
  11. (三)Harbor使用OpenLDAP认证登陆
  12. (HTTPS)web 项目如何实现https
  13. LeetCode 543. Diameter of Binary Tree (二叉树的直径)
  14. python3.6 urllib.request库实现简单的网络爬虫、下载图片
  15. 什么是HTTP Referer?
  16. Mac Node.js 配置
  17. Redis 为什么使用单进程单线程方式也这么快(转载)
  18. [React] 09 - Tutorial: components
  19. MySQL LIMIT的使用
  20. eclipse 关于*.properties 文件 中文显示为Unicode,无法显示中文的问题(Properties Editor)

热门文章

  1. SQL——Hibernate SQL增删改查
  2. android contentprovider内容提供者
  3. TCP 链接 存在大量 close_wait 等待
  4. [JXOI2018]游戏 (线性筛,数论)
  5. D - Laying Cables Gym - 100971D (单调栈)
  6. saltstack系列~第一篇
  7. LOJ 2567: 洛谷 P3643: bzoj 4584: 「APIO2016」划艇
  8. Dubbo重试次数
  9. Pytorch 资料汇总(持续更新)
  10. How to Repair GRUB2 When Ubuntu Won’t Boot