fzu 1402(数论:中国剩余定理)

典型的中国剩余定理题,我用自己写的剩余定理跪掉了

原因是我在套用expand_gcd(a,b,d,x,y)时总是傻乎乎地令d=gcd(a,b)尴尬

值得一说的是fzu oj的注册相当的不友好!!!,鼠标要移动到导航栏member上但不要点击才会出现register选项!!!安静


代码如下:

#include <cmath>
#include <cstdio>
#include <iostream>
#include <algorithm>
#define MAXN 110
#define LL long long
using namespace std;

LL a[MAXN], m[MAXN], n[MAXN];

LL gcd(LL a, LL b) {
    return b==0 ? a : gcd(b, a%b);
}

void expand_gcd(LL a, LL b, LL d, LL &x, LL &y) {
    if(b == 0) {
        d = a;
        x = 1;
        y = 0;
    } else {
        expand_gcd(b, a%b, d, y, x);
        y -= x*(a/b);
    }
}

LL chinese_remainder(LL a[], LL n[], LL num) {
    LL M = 1;
    LL d, x, y;
    LL sum = 0;
    for(int i=0; i<num; ++i)
        M *= n[i];
    for(int i=0; i<num; ++i) {
        m[i] = M/n[i];
        expand_gcd(m[i], n[i], d, x, y);
  //      cout << "x = " << x << endl;
        x = (x%n[i]+n[i])%n[i];//这里的处理很重要,保证x取得的是最小非负整数
  //      cout << "d = " << d << " x = " << x << endl;
        sum = (sum+x*m[i]*a[i]%M)%M;
    }
    return sum%M;
}

int main(void) {
    int T;
    while(cin >> T) {
        for(int i=0; i<T; ++i) {
            cin >> n[i] >> a[i];
        }
        cout << chinese_remainder(a, n, T) << endl;
    }
    return 0;
}

发现了一个很有趣的写法,可以依次读入数据,判断当前的ans%a[i]是否等于b[i]

若等于则继续,不等于则一直加前(i-1)个a[i]的乘积直至满足条件,这种贪心的策略也是可行的

代码相当简洁:

#include <cstdio>
#include <iostream>
#include <algorithm>
#define MAXN 11
#define LL long long
using namespace std;

LL a, b, ans, m, n;

int main(void) {
    while(cin >> n) {
        cin >> a >> b;
        m = a;
        ans = b;
        for(int i=1; i<n; ++i) {
            cin >> a >> b;
            while(ans%a != b)
                ans += m;
            m *= a;
        }
        cout << ans << endl;
    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值