CodeForces - 1025B Weakened Common Divisor

http://codeforces.com/problemset/problem/1025/B

大意:n对数对(ai,bi),求任意一个数满足是所有数对中至少一个数的因子(大于1)

分析:

  1. 首先求所有数对的lcm,把所有数的素因子提出来
  2. 求所有lcm的gcd,这样做求出数对之间的公共素因子gcd
  3. 注意,公共素因子可能在某一组数对中状态为某一部分是ai的素因子而剩下的一部分是bi的素因子,这种情况导致gcd既不是ai的因子又不是bi的因子,因此必须只保留下aibi公共的素因子,剔除非公共素因子,故只需执行gcd=__gcd(ai,gcd),gcd=__gcd(bi,gcd)(注意,需先判断__gcd(xi,gcd)>1)
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int MAXN=150000+100;
ll a[MAXN],b[MAXN];

int main()
{
    int n;
    scanf("%d",&n);
    for(int i=0;i<n;i++)
        scanf("%lld %lld",&a[i],&b[i]);
    ll gcd=a[0]*b[0]/__gcd(a[0],b[0]);
    for(int i=1;i<n;i++)
        gcd=__gcd(gcd,a[i]*b[i]/__gcd(a[i],b[i]));
    if(gcd==1)
    {
        printf("-1\n");
        return 0;
    }
    ll temp;
    for(int i=0;i<n;i++)
    {
        temp=__gcd(gcd,a[i]);
        if(temp>1){
            gcd=temp;
            continue;
        }
        temp=__gcd(gcd,b[i]);
        if(temp>1)
            gcd=temp;
    }
    printf("%lld\n",gcd);
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/spzeno/p/10467084.html
今日推荐