地址:http://codeforces.com/contest/1025/problem/B
做的时候还把a,b进行分解质因素,不需要,a*b后的值两个数的质因子均包括了,直接求gcd即可。。。。
先判断最后是否存在一个WCD数,利用(a[i] * b[i])之间求gcd,当最后得数为1时,说明不存在;否则,因为可能存在g还是a[i] * b[i]的情况,所以再和每个单独的a[i]或b[i]取个gcd
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
const int inf = 0x3f3f3f3f;
const int N = 150005;
#define fi first
#define se second
LL gcd(LL a,LL b)
{
return (b == 0) ? a : gcd(b,a % b);
}
LL a[N],b[N];
int main()
{
int n;
scanf("%d",&n);
scanf("%lld %lld",&a[0],&b[0]);
LL g = a[0] * b[0];
for(int i = 1;i < n;++i)
{
scanf("%lld %lld",&a[i],&b[i]);
g = gcd(g,a[i] * b[i]);
}
if(g == 1){
cout << "-1" << endl;
return 0;
}
for(int i = 0;i < n;++i)
{
if(gcd(g,a[i]) != 1){
g = gcd(g,a[i]);
}
else{
g = gcd(g,b[i]);
}
}
cout << g << endl;
return 0;
}
第二种方法:
先得到第一个数的质因子
然后再依次判断该质因子是否可以成为WCD数,我也是这样想的,但是用了map写,超时了
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
const int inf = 0x3f3f3f3f;
const int N = 150005;
#define fi first
#define se second
LL a[N],b[N];
LL cnt[N];
int main()
{
int n;
scanf("%d",&n);
for(int i = 0;i < n;++i)
{
scanf("%d %d",&a[i],&b[i]);
}
int tot = 0;
LL x = a[0],y = b[0];
for(int i = 2;i <= sqrt(x);++i)
{
if(x % i == 0) cnt[tot++] = i;
while(x % i == 0) x /= i;
}
if(x > 1) cnt[tot++] = x;
for(int i = 2;i <= sqrt(y);++i)
{
if(y % i == 0) cnt[tot++] = i;
while(y % i == 0) y /= i;
}
if(y > 1) cnt[tot++] = y;
for(int i = 0;i < tot;++i)
{
bool flag = false;
for(int j = 1;j < n;++j){
if(a[j] % cnt[i] != 0 && b[j] % cnt[i] != 0)
{
flag = true;
break;
}
}
if(!flag){
printf("%lld\n",cnt[i]);
return 0;
}
}
printf("-1\n");
return 0;
}