poj2891

难得见中级中的水题。。

一开始做,想着存下来,如下:

#include <iostream>

using namespace std;

#define LL long long 
#define MAXN 100000000

LL ext_gcd(LL a, LL b, LL& x, LL& y)
{
    LL t, ret;
    if (!b)
    {
        x = 1, y = 0;
        return a;
    }
    ret = ext_gcd(b, a%b, x, y);
    t = x, x = y, y = t - a / b*y;
    return ret;
}

LL modular_linear_system(LL b [], LL w [], LL k)
{
    LL d, x, y, a = 0, m, n = 1, i;
    for (i = 0; i < k; i++)
        n *= w[i];
    for (i = 0; i < k; i++)
    {
        m = n / w[i];
        d = ext_gcd(w[i], m, x, y);
        a = (a + y*m*b[i])%n;
    }
    return (a + n)%n;
}

int main()
{
    int t;
    while (cin >> t)
    {
        LL * r = new LL[MAXN];
        LL * a = new LL[MAXN];
        for (int i = 0; i < t; i++)
        {
            cin >> r[i] >> a[i];
        }
        LL ans = modular_linear_system(a, r, t);
        cout << ans << endl;
    }
}

就和这个主题的名字一样。。too young too naive...各种RE,根本没有告诉k的范围,乱猜哪行哇~

然后改了改,不存,逐个算就是了

#include <iostream>
#include <algorithm>

using namespace std;

#define LL long long
#define MAXN 100000000

LL ext_gcd(LL a, LL b, LL& x, LL& y)
{
    LL t, ret;
    if (!b)
    {
        x = 1, y = 0;
        return a;
    }
    ret = ext_gcd(b, a%b, x, y);
    t = x, x = y, y = t - a / b*y;
    return ret;
}
LL modular_linear(LL a, LL b, LL m)
{
    LL d, x, y;
    d = ext_gcd(a, m, x, y);
    if (b % d != 0) return -1;
    return (x * (b / d) % m + m) % m;
}

int main()
{
    LL a1, a2, m1, m2, k, y;
    while (cin>>k)
    {
        bool flag = false;
        cin >> m1 >> a1;
        if (k == 1) y = a1;

        for (int i = 1; i < k; i++)
        {
            cin >> m2 >> a2;
            if (flag) continue;
            LL y = modular_linear(m2, a1 - a2, m1);
            if (y == -1) { flag = truecontinue; }
            a1 = a2 + m2 * y;
            m1 = m1*m2 / (__gcd(m1, m2));
            a1 = (a1 % m1 + m1) % m1;
        }
        if (flag) cout << -1 << endl;
        else cout << a1 << endl;
    }
    return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值