51nod:1079 中国剩余定理
原创
©著作权归作者所有:来自51CTO博客作者im0qianqian的原创作品,请联系作者获取转载授权,否则将追究法律责任
Input
第1行:1个数N表示后面输入的质数及模的数量。(2 <= N <= 10)
第2 - N + 1行,每行2个数P和M,中间用空格分隔,P是质数,M是K % P的结果。(2 <= P <= 100, 0 <= K < P)
Output
输出符合条件的最小的K。数据中所有K均小于10^9。
Input示例
3
2 1
3 2
5 3
Output示例
23
下面的AC代码看起来比较暴力的啦!我的思想是
比如K % 2 = 1, K % 3 = 2, K % 5 = 3
首先给2 3 5排序,然后让K从2+1=3开始,步长为2,因为这样刚好满足第一个条件,然后找到了5满足第二个条件,然后以2和3的最小公倍数为步长继续枚举,直到满足第三个条件,当然条件如果较多也可以使用这种办法。
没有TLE真的好幸运呀!
AC代码:
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>
#include <iostream>
#include<algorithm>
#include <queue>
using namespace std;
struct po
{
int num;
int last;
} a[105];
bool cmp(po a,po b)
{
return a.num<b.num;
}
int gcd(int a,int b)
{
if(a<b)swap(a,b);
if(b==0)return a;
return gcd(b,a%b);
}
int main()
{
int N;
cin>>N;
int i;
for(i=0; i<N; i++)
cin>>a[i].num>>a[i].last;
sort(a,a+i,cmp);
int fri=a[0].num+a[0].last;
for(int j=0; j<i; j++)
{
int s=1;
for(int k=0; k<j; k++)
s=s/gcd(a[k].num,s)*a[k].num;
//cout<<s<<endl;
for(; fri%a[j].num!=a[j].last; fri+=s);
// cout<<s<<" "<<fri<<endl;
}
cout<<fri<<endl;
return 0;
}