poj 2891Strange Way to Express Integers
来源:互联网 发布:mac win10自动更新 编辑:程序博客网 时间:2024/06/05 11:23
题目链接:点击打开链接;
题意:给出n个(a,r)组合问是否有值m可以使所有m mod a=r;
分析:本题重点在于对于这些对数进行分析,m%a1=r1;m%a2=r2;即m=a1*x+r1,m=a2*y+r2;所以a1*x+a2*y=r2-r1;通过扩展欧几里得算法即可解出x的值,以此类推,解得一次同余方程组的解。本题的几大点在于对于无解的数据,要及时的退出,不要进行无用的计算,其次,总要保证x>0。本题重点在于扩展欧几里得算法的实现,扩展欧几里得算法内部推理好麻烦,就不赘述了;
代码:
#include <set>#include <map>#include <stack>#include <queue>#include <math.h>#include <vector>#include <utility>#include <string>#include <stdio.h>#include <stdlib.h>#include <string.h>#include <iostream>#include <algorithm>#include <functional>using namespace std;long long gcd(long long a,long long b){ if(b==0)return a; return gcd(b,a%b);}void _gcd(long long a,long long b,long long &x,long long &y){ if(b==1){ x=1; y=1-a; return; } else{ long long x1,y1; _gcd(b,a%b,x1,y1); x=y1;//假设 y=x1-(a/b)*x; }}int main(){ int n; while(cin>>n){ long long x,y,a1,r1,a2,r2; cin>>a1>>r1; int flag=1; for(int i=1;i<n;i++){ scanf("%I64d%I64d",&a2,&r2); if(flag==0)continue;//及时退出 long long a,b,c; a=a1,b=a2; c=r2-r1; long long g=gcd(a,b); a/=g,b/=g; _gcd(a,b,x,y); if(c%g!=0){ flag=0; continue; } c/=g; x=((x*c)%b+b)%b;//保证x>0; x=x*a1+r1; r1=x;//手动推一下就出来了 a1=b*a1; } if(flag==0){ puts("-1"); } else cout<<r1<<endl;//第一次写成x了错了好多回 } return 0;}
0 0
- 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
- 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
- poj 2891Strange 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
- POJ 2891 Strange Way to Express Integers
- POJ 2891 Strange Way to Express Integers
- POJ 2891 Strange Way to Express Integers
- note
- NYOJ-673悟空的难题~~水题~~
- centos6.7 安装 keepalived
- JVM性能调优
- 2.window安装Jenkins和tomcat
- poj 2891Strange Way to Express Integers
- uva111 - History Grading(最长公共子序列LCS)
- 前端开发静态文件自动添加版本号解决方案
- 数据结构与算法javascript描述(六)集合
- HDU 1250 Hat's Fibonacci (JAVA大数)
- 跨服务器查询sql
- LeapMotion+Processing+Arduino 控制LED灯的亮与灭
- 欢迎使用CSDN-markdown编辑器
- TREE KERNELS IN SVM-LIGHT---在svm-light中树核的使用(翻译)