hdu1788 Chinese remainder theorem again(Mi不互质解线性同余方程)

题意:
N M 1 ( M 1 a ) M 2 ( M 2 a ) , M 3 ( M 3 a ) , M I ( M I a ) , a < M i < 100 i = 1 , 2 , I , 现在有一个问题是这样的: 一个正整数N除以M1余(M1 - a),除以M2余(M2-a), 除以M3余(M3-a),总之, 除以MI余(MI-a),其中(a<Mi<100 i=1,2,…I),求满足条件的最小的数。
思路:模板题。
一开始题意介绍了中国剩余定理,然后我就认为它给的 M i Mi 是互质的。结果,并不是。注意这点就好了。
A C   C o d e : AC \ Code:

#include<iostream>
#include<cstring>
#include<queue>
#include<map>
#include<cmath>
#include<set>
#include<stack>
#include<cstdio>
#include<sstream>
#include<vector>
#include<bitset>
#include<algorithm>

using namespace std;
#define read(x) scanf("%d",&x)
#define Read(x,y) scanf("%d%d",&x,&y)
#define gc(x)  scanf(" %c",&x);
#define mmt(x,y)  memset(x,y,sizeof x)
#define write(x) printf("%d\n",x)
#define pii pair<int,int>
#define INF 0x3f3f3f3f
#define ll long long
const ll mod =   1000000007;
const int N = 100000 + 100;
const int M = 3e6 + 1005;
typedef long long LL;
typedef pair<LL, LL> PLL;
LL a[100000], b[100000], mo[100000];
LL gcd(LL a, LL b){
    return b ? gcd(b, a%b) : a;
}
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){//如果不存在,返回-1 
    LL d, x, y;
    ex_gcd(t, p, x, y, d);
    return d == 1 ? (x % p + p) % p : -1;
}
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, b = B[i] - A[i]*x, d = gcd(M[i], a);
        if(b % d != 0)  return PLL(0, -1);//答案,不存在,返回-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,m;
    while(scanf("%d%d",&n,&m) == 2&&n + m){
        for(int i = 0;i < n;++i){
            scanf("%lld",&mo[i]);
            a[i] = (mo[i] - m + mo[i])%mo[i];
            while(a[i] <0 ) a[i] += mo[i];
            b[i] = 1;
        }
        cout<<linear(b,a,mo,n).first<<endl;
    }
}
发布了632 篇原创文章 · 获赞 27 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/qq_43408238/article/details/103588828