POJ 2891-Strange Way to Express Integers

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

题意比较简单,就是给出k个a, r. 求出满足 x mod ai = ri 的x的最小正值,若不存在这样的x,就输出-1.

这个题一开始看感觉是在考察中国剩余定理(其实也算是了)。

但是,如果我们直接套用中国剩余定理的模板后,就会发现,wa了,为什么呢?这里我们就需要搞清楚中国剩余定理

的适用条件,即对于所有的 x ≡ ai mod mi,有m1,m2,...mi须互质。但是在这个题中,貌似没有这个条件的说~。

所以,我们就需要对中国剩余定理进行变形,即一般模线性方程组(少年,你该换一个模板了)

代码如下:

#include<cstdio>
#include<iostream>
#include<cstring>
using namespace std;

typedef long long LL;
typedef pair<LL, LL> PLL;
LL a[100000], b[100000], m[100000];

int gcd(int x, int y)
{
	if(y == 0)
		return x;
	else 
		return gcd(y, x%y);
}
void ex_gcd(LL a, LL b, LL &x, LL &y, LL &d)
{  
    if (!b){
		d = a;
		x = 1;
		y = 0;
	}  
    else{  
        ex_gcd(b, a % b, y, x, d);  
        y -= x * (a / b);  
    }  
}  
LL inv(LL t, LL p)
{   
    LL d, x, y;  
    ex_gcd(t, p, x, y, d);  
    return d == 1 ? (x % p + p) % p : -1;  
}  

typedef pair<LL, LL> PLL;
PLL linear(LL A[], LL B[], LL M[], int n)    //求解A[i]x = B[i] (mod M[i]),总共n个线性方程组 
{
    LL x = 0, m = 1;
    for(int i = 0; i < n; i ++) {
        LL a = A[i] * m;
		LL b = B[i] - A[i]*x;
		LL d = gcd(M[i], a);
        if(b % d != 0)  
			return PLL(0, -1);
        LL t = b/d * inv(a/d, M[i]/d)%(M[i]/d);
        x = x + m*t;
        m *= M[i]/d;
    }
    x = (x % m + m ) % m;
    return PLL(x, m);    //返回的x就是最后的答案,m是最后的lcm值
}

int main()
{
	int n;
	while(~scanf("%d", &n)){
		for(int i = 0; i < n; i++){
			a[i] = 1;
			scanf("%d %d", &m[i], &b[i]);
		}
		PLL ans = linear(a, b, m, n);
		if(ans.second == -1)
			cout << "-1" << endl;
		else
			cout << ans.first << endl;
	}
	return 0;
}

所以,这道题就这么愉快的AC了,至于这个模板的证明,暂时我还不会,逃~。

网上又找到了一个新的模板,算法用时比上面的短,但所用空间要高(难道这就是传说中的以空间换时间大法?)

#include<iostream>
#include<cstdio>
#include<cstring>

using namespace std;

#define LL long long
const int inf = 0x3f3f3f3f;
const int maxn = 1e5 + 5;
int n;
void ex_gcd(LL a, LL b, LL &d, LL &x, LL &y)
{
    if (!b) {d = a, x = 1, y = 0;}
    else
    {
        ex_gcd(b, a % b, d, y, x);
        y -= x * (a / b);
    }
}
LL ex_crt(LL *m, LL *r, int n)
{
    LL M = m[1], R = r[1], x, y, d;
    for (int i = 2; i <= n; ++i)
    {
        ex_gcd(M, m[i], d, x, y);
        if ((r[i] - R) % d) return -1;
        x = (r[i] - R) / d * x % (m[i] / d);
        R += x * M;
        M = M / d * m[i];
        R %= M;
    }
    return R > 0 ? R : R + M;
}
int main()
{
    while (~scanf("%d",&n))
    {
        LL m[maxn], r[maxn];
        for (int i = 1; i <= n; ++i)
            scanf("%lld%lld", &m[i], & r[i]);
        printf("%lld\n",ex_crt(m,r,n));
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值