您的位置:首页 > 其它

Monkey Tradition(中国剩余定理)

2014-09-26 13:57 162 查看
Time Limit:2000MS Memory Limit:32768KB 64bit IO Format:%lld
& %llu

Description

In 'MonkeyLand', there is a traditional game called "Bamboo Climbing". The rules of the game are as follows:

1) There are N monkeys who play this game and there are N bamboos of equal heights. Let the height be L meters.

2) Each monkey stands in front of a bamboo and every monkey is assigned a different bamboo.

3) When the whistle is blown, the monkeys start climbing the bamboos and they are not allowed to jump to a different bamboo throughout the game.

4) Since they are monkeys, they usually climb by jumping. And in each jump, the ith monkey can jump exactly pimeters (pi is a prime). After a while when a monkey finds
that he cannot jump because one more jump may get him out of the bamboo, he reports the remaining length ri that he is not able to cover.

5) And before the game, each monkey is assigned a distinct pi.

6) The monkey, who has the lowest ri, wins.

Now, the organizers have found all the information of the game last year, but unluckily they haven't found the height of the bamboo. To be more exact, they know N, all pi and corresponding ri,
but not L. So, you came forward and found the task challenging and so, you want to find L, from the given information.

Input

Input starts with an integer T (≤ 10000), denoting the number of test cases.

Each case starts with a line containing an integer n (1 ≤ n ≤ 12). Each of the next n lines contains two integerspi (1 < pi < 40, pi is a prime) and ri (0
< ri < pi)
. All pi will be distinct.

Output

For each case, print the case number and the minimum possible value of L that satisfies the above conditions. If there is no solution, print 'Impossible'.

Sample Input

2

3

5 4

7 6

11 3

4

2 1

3 2

5 3

7 1

Sample Output

Case 1: 69

Case 2: 113

中国剩余定理:

求 x = b1 (mod m1) , x = b2 (mode m2) , ... , x = bn (mod mn) 的解

令 m = m1*m2*...*mn Mi = m/mi (i = 1 ,2,3,...,n)

即 上述同余式组的解为 x = ( M1 * M1 ’ * b1 + M2 * M2 ’ * b2 + ...+ Mn * Mn ’ * bn ) % m;

其中 Mi * Mi ' = 1(mod mi) 即 Mi ' 是 Mi相对于 mi 的 逆元 (可用拓展欧几里得求出)。

#include <iostream>
#include <cstdio>
#define LL long long
using namespace std;
const int maxn=15;

int n,T;
LL M[maxn],b[maxn],m[maxn],mul;

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

void input()
{
mul=1;
scanf("%d",&n);
for(int i=0; i<n; i++)
{
scanf("%lld %lld",&m[i],&b[i]);
mul*=m[i];
}
}

void slove(int co)
{
LL x,y,ans=0;
for(int i=0; i<n; i++)  M[i]=mul/m[i];
for(int i=0; i<n; i++)
{
ext_gcd(M[i],m[i],x,y);
ans=(ans+M[i]*x*b[i])%mul;
}
if(ans<0)  ans=(ans+mul)%mul;
printf("Case %d: %lld\n",co,ans);
}

int main()
{
scanf("%d",&T);
for(int co=1; co<=T; co++)
{
input();
slove(co);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: