POJ 2891 Strange Way to Express Integers 中国剩余定理 模板 数论

本文介绍了一道经典的中国剩余定理题目,并提供了一个清晰的解题思路和完整的代码实现。通过对题目的解析,读者可以了解如何利用中国剩余定理解决特定类型的数学问题。

  题目链接: http://poj.org/problem?id=2891

  题目描述: m % p1 = q1, m % p2 = q1 ...... 给出N组p1, q1, p2, p2.... pn, qn 让你求满足条件的最小m, 如果m不存在, 输出-1

  解题思路: 感觉这个才是裸的中国剩余定理........这个模板很不错

  代码: 

#include <cstdio>
#include <cstring>
#include <iostream>
#include <stack>
#include <queue>
#include <map>
#include <algorithm>
#include <vector>

using namespace std;

typedef long long ll;

ll ex_gcd(ll a,ll b,ll &x,ll &y)
{
    if(b == 0){
        x = 1;
        y = 0;
        return a;
    }
    ll r = ex_gcd(b,a%b,x,y);
    ll t = x;
    x = y;
    y = t - a/b*y;
    return r;
}
int main()
{
    ll i,n,a1,r1,a2,r2,a,b,c,x0,y0;
    while(scanf("%lld",&n)!=EOF){
        bool flag = 1;
        scanf("%lld%lld",&a1,&r1);
        for( i=1;i<n;i++){
            scanf("%lld%lld",&a2,&r2);
            a = a1;
            b = a2;
            c = r2-r1;
            ll d = ex_gcd(a,b,x0,y0);
            if(c%d!=0){
                flag = 0;
            }
            ll t = b/d;
            x0 = (x0*(c/d)%t+t)%t;//保证x0为正
            r1 = a1*x0 + r1;
            a1 = a1*(a2/d);
        }
        if(!flag){
            puts("-1");
            continue;
        }
        printf("%lld\n",r1);
    }
    return 0;
}
View Code

  思考: 整理整理, 整理一堆模板.....

转载于:https://www.cnblogs.com/FriskyPuppy/p/7463753.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值