POJ2891 Strange Way to Express Integers 扩展欧几里德 中国剩余定理

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

去博客园看该题解


题目传送门 - POJ2891


题意概括

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


题解

  UPD(2018-08-07):

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

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

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


代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#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;
}

  

 

posted @   zzd233  阅读(446)  评论(0编辑  收藏  举报
编辑推荐:
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构

点击右上角即可分享
微信分享提示