Hello Kiki(中国剩余定理不互质情况)

Hello Kiki

 One day I was shopping in the supermarket. There was a cashier counting coins seriously when a little kid running and singing "门前大桥下游过一群鸭,快来快来 数一数,二四六七八". And then the cashier put the counted coins back morosely and count again...
Hello Kiki is such a lovely girl that she loves doing counting in a different way. For example, when she is counting X coins, she count them N times. Each time she divide the coins into several same sized groups and write down the group size Mi and the number of the remaining coins Ai on her note.
One day Kiki's father found her note and he wanted to know how much coins Kiki was counting. 

Input
The first line is T indicating the number of test cases.
Each case contains N on the first line, Mi(1 <= i <= N) on the second line, and corresponding Ai(1 <= i <= N) on the third line.
All numbers in the input and output are integers.
1 <= T <= 100, 1 <= N <= 6, 1 <= Mi <= 50, 0 <= Ai < Mi
Output
For each case output the least positive integer X which Kiki was counting in the sample output format. If there is no solution then output -1.
Sample Input

2
2
14 57
5 56
5
19 54 40 24 80
11 2 36 20 76

Sample Output

Case 1: 341
Case 2: 5996

同样是中国剩余定理不互质情况的模板套用

注意这里要求最小正整数解,所以如果结果求出来是0,需要加上一个lcm

我在这里wa了好几发。。。

code:

#include 
#include 
#include 
using namespace std;
bool flag;
int m[100],a[100],lcm;
int gcd(int a,int b){
    return b ? gcd(b,a%b) : a;
}
int ex_gcd(int a,int b,int &x,int &y){
    if(!b){
        x = 1;
        y = 0;
        return a;
    }
    int g = ex_gcd(b,a%b,y,x);
    y -= a / b * x;
    return g;
}
int China(int n){
    int m1 = m[0],a1 = a[0];
    int m2,a2,k1,k2,x0,g,c;
    lcm = m[0];
    for(int i = 1; i < n; i++){
        m2 = m[i];
        a2 = a[i];
        c = a2 - a1;
        g = ex_gcd(m1,m2,k1,k2);
        lcm = lcm * m[i] / gcd(lcm,m[i]);
        if(c % g){
            flag = false;
            return 0;
        }
        x0 = k1 * c / g;
        int t = m2 / g;
        x0 = (x0 % t + t) % t;
        a1 += m1 * x0;
        m1 = m2 / g * m1;
    }
    return a1;
}
int main(){
    int T,cas = 0;
    scanf("%d",&T);
    while(T--){
        int n;
        scanf("%d",&n);
        for(int i = 0; i < n; i++) scanf("%d",&m[i]);
        for(int i = 0; i < n; i++) scanf("%d",&a[i]);
        flag = true;
        int ans = China(n);
        if(flag && ans <= 0) ans += lcm;
        if(!flag) printf("Case %d: -1\n",++cas);
        else printf("Case %d: %d\n",++cas,ans);
    }
    return 0;
}

你可能感兴趣的:(数论)