poj2891 Strange Way to Express Integers【解一元线性同余方程组模板】
来源:互联网 发布:程序员用机械键盘推荐 编辑:程序博客网 时间:2024/05/24 06:31
题目大意:
求解一元线性同余方程组:
……
若无解输出-1,否则输出最小正整数解。
解题思路:
考虑只有两个方程:
设
可以转化为:
联立移项得
这时我们就可以用拓展欧几里得把最小的
我们取特解
这时假设有第三个方程:
那么同理:
移项得:
可以发现这与
由
#include<cstdio>#include<iostream>#include<cstring>#include<string>#include<algorithm>#include<cmath>#include<ctime>#include<vector>#include<set>#define ll long longusing namespace std;int n;ll b1,b2,m1,m2,d;ll gcd(ll a,ll b){ return b?gcd(b,a%b):a;}void exgcd(ll a,ll b,ll &x,ll &y){ b?(exgcd(b,a%b,y,x),y-=a/b*x):(x=1,y=0);}ll solve(){ ll x,y,a=m2,b=m1,c=b1-b2; d=gcd(a,b); if(c%d!=0)return -1; a/=d,b/=d,c/=d; exgcd(a,b,x,y); x*=c;x=(x%b+b)%b; return x;}int main(){ //freopen("lx.in","r",stdin); //freopen("lx.out","w",stdout); ll y2; while(scanf("%d",&n)!=EOF) { y2=0; scanf("%lld%lld",&m1,&b1); for(int i=2;i<=n;i++) { scanf("%lld%lld",&m2,&b2); if(y2==-1)continue; y2=solve(); m1=m1*(m2/d);b1=(b2+m2*y2)%m1; } if(y2==-1)puts("-1"); else cout<<b1<<'\n'; } return 0;}
阅读全文
0 0
- poj2891 Strange Way to Express Integers【解一元线性同余方程组模板】
- 【POJ2891】Strange Way to Express Integers-解一元线性同余方程组
- Strange Way to Express Integers(poj2891线性同余方程组)
- POJ2891 Strange Way to Express Integers 线性同余方程组
- POJ2891——Strange Way to Express Integers(一元线性同余方程组)
- POJ2891 Strange Way to Express Integers【一元线性同余方程组】
- POJ2891 Strange Way to Express Integers 一元线性同余方程组
- poj2891 Strange Way to Express Integers 同余方程组
- [数论] 同余方程组 poj2891 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(exgcd—解一元线性同余方程组)
- 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(一元线性同余方程组)
- poj2891 Strange Way to Express Integers 解线性同余方程的应用
- POJ2891 Strange Way to Express Integers(解多元线性同余方程)
- eclipse开发birt报表时预览数据错误修改方案
- Hive编程(九)【模式设计】
- PostgreSQL Serial类型和序列及子查询(五)
- Unity2017 UnityAds 问题
- 编译错误"/usr/bin/ld: cannot find -lz"
- poj2891 Strange Way to Express Integers【解一元线性同余方程组模板】
- java中的泛型
- vuex入门教程
- 【云星数据---Scala实战系列(精品版)】:Scala入门教程061-Scala实战源码-Scala包引用的语法
- python全局变量小心得
- Linux下php安装Redis扩展
- scala ide 报错:错误: 找不到或无法加载主类
- LINUX设置固定IP上网方法
- 算法训练 连续正整数的和