hdu 3579 (同余方程组,逐一合并大法)

来源:互联网 发布:c语言简单的图形编程 编辑:程序博客网 时间:2024/05/16 18:57

Problem Description
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
2214 575 56519 54 40 24 8011 2 36 20 76
 

Sample Output
Case 1: 341Case 2: 5996
这是一个同余方程组;对于同余方程组可以采用逐一合并大法来做;通过合并之后可以得到一个同余方程;可以通过欧几里德的拓展来解决;得到最后的答案,建议将逐一合并大法来存为模板;

代码如下:

#include<iostream>using namespace std;typedef long long ll;ll ext_gcd(ll a, ll b,ll& x, ll&y)///欧几里得拓展{    if (b == 0) { x = 1; y = 0; return a; }    ll d = ext_gcd(b, a % b, y, x);    y = y - a / b * x;    return d;}inline ll mod(ll a,ll b){ return a % b+( a % b > 0 ? 0 : b );}///逐一合并大法 参数n为同余方程组的个数;ll ext_crt(int n,int *a,int *m)///x=ai(mod mi){    if(n==1&&a[0]==0) return m[0];    ll ans=a[0],lcm=m[0];    bool legal=true;    for( int i = 1; i < n; i++)    {        ll x, y, gcd;        gcd = ext_gcd(lcm,m[i],x,y);        if((a[i]-ans)%gcd)///判断有无解;            { legal = false;break;}        ll tmp=lcm * mod((a[i]-ans)/gcd*x/**求解u m1 + v m2 = (a1 – a2)的解,(a[i]-ans)/gcd 是倍数*/,m[i]/gcd);///求解同余方程;        lcm=lcm/gcd*m[i];///lcm 等于两个系数的最小公倍数;        ans=mod(ans+tmp,lcm);    }    return legal?ans:-1;}int a[200],m[200];int main(){    int t;    cin>>t;    for(int cas=1;cas<=t;cas++)    {        int n;        cin>>n;        for(int i=0;i<n;i++) cin>>m[i];        for(int i=0;i<n;i++) cin>>a[i];        cout<<"Case "<<cas<<": "<<ext_crt(n,a,m)<<endl;    }    return 0;}






0 0
原创粉丝点击