LightOJ - 1319
Monkey Tradition
Time Limit: 2000MS    Memory Limit: 32768KB    64bit IO Format: %lld & %llu
Submit Status


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 pi meters (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 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 integers pi (1 < pi < 40, pi is a prime) and ri (0 < ri < pi). All pi will be distinct.


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



5 4

7 6

11 3


2 1

3 2

5 3

7 1

Sample Output

Case 1: 69

Case 2: 113

题意:有 n 个猴子,n 棵树,树的高度为 L ,每个猴子刚开始的时候都在树的底部,后来往上跳,每次跳的距离是pi,最后不能跳到树上面所以最后会有个到顶端的距离ri,求L的最小值;


using namespace std;
typedef long long ll;
void extend_Euclid(ll a, ll b, ll &x, ll &y)
if(b == 0)
x = 1;
y = 0;
extend_Euclid(b, a % b, x, y);
ll tmp = x;
x = y;
y = tmp - (a / b) * y;

ll CRT(ll a[],ll m[],ll n) //xi≡a[i]( mod m[i])
ll M = 1;
ll ans = 0;
for(int i=1; i<=n; i++)
M *= m[i];
for(int i=1; i<=n; i++)
ll x, y;
ll Mi = M / m[i];
extend_Euclid(Mi, m[i], x, y);
ans = (ans + Mi * x * a[i]) % M;
if(ans < 0) ans += M;
return ans;
ll p[200],r[200];
int main(){
int T;
int cas=0;
ll n,m;
for(int i=1;i<=n;i++)


printf("Case %d: %lld\n",++cas,CRT(r,p,n));