您的位置:首页 > 其它

fzu 1402 猪的安家

2013-12-08 23:27 302 查看
[align=center]Problem 1402 猪的安家[/align]

Accept: 839 Submit: 5341

Time Limit: 1000 mSec Memory Limit : 32768 KB



Problem Description

Andy和Mary养了很多猪。他们想要给猪安家。但是Andy没有足够的猪圈,很多猪只能够在一个猪圈安家。举个例子,假如有16头猪,Andy建了3个猪圈,为了保证公平,剩下1头猪就没有地方安家了。Mary生气了,骂Andy没有脑子,并让他重新建立猪圈。这回Andy建造了5个猪圈,但是仍然有1头猪没有地方去,然后Andy又建造了7个猪圈,但是还有2头没有地方去。Andy都快疯了。你对这个事情感兴趣起来,你想通过Andy建造猪圈的过程,知道Andy家至少养了多少头猪。



Input

输入包含多组测试数据。每组数据第一行包含一个整数n (n <= 10) – Andy建立猪圈的次数,解下来n行,每行两个整数ai, bi( bi <= ai <= 1000), 表示Andy建立了ai个猪圈,有bi头猪没有去处。你可以假定(ai, aj) = 1.



Output

输出包含一个正整数,即为Andy家至少养猪的数目。



Sample Input

33 15 17 2



Sample Output

16

中国剩余定理

中国剩余定理是中国古代求解一次同余方程组的方法,是数论中的一个重要定理。

设n1,n2,n3,...,nk是两两互素的正整数,即gcd(ni,nj)=1,i!=j,i,j=1,2,3,...,k.

则同余方程组:

x = a1 (mod n1)
x = a2 (mod n2)
...
x = ak (mod nk)
模[n1,n2,...nk]有唯一解,即在[n1,n2,...,nk]的意义下,存在唯一的x,满足:

x = ai mod [n1,n2,...,nk], i=1,2,3,...,k。

解可以写为这种形式:

x = sigma(ai* mi*mi') mod(N)
其中N=n1*n2*...*nk,mi=N/ni,mi'为mi在模ni乘法下的逆元。

AC代码:

#include <iostream>
#include <cmath>
#include <cstdlib>
#include <cstring>
#include <cstdio>
#include <queue>
#include <ctime>
#include <algorithm>

#define ll long long

using namespace std;

ll a[15], b[15];
ll x, y, n;
ll ex_gcd(ll a, ll b)
{
if(!b)
{
x = 1;
y = 0;
return a;
}
ll d = ex_gcd(b, a % b);
ll t = x;
x = y;
y = t - a / b * y;
return d;
}
ll China_Reminder()
{
ll ret = 0, M = 1;
for(int i = 0; i < n; i++)
M *= a[i];
for(int i = 0; i < n; i++)
{
ll m = M / a[i];
ex_gcd(m, a[i]);
x = (x % a[i] + a[i]) % a[i];
ret += b[i] * m * x;
ret = (ret % M + M) % M;
}
return ret;
}
int main()
{
while(cin>>n)
{
for(int i = 0; i < n; i++)
cin>>a[i]>>b[i];
cout<<China_Reminder()<<endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: