Codeforces Round #505 (rated, Div. 1 + Div. 2, based on VK Cup 2018 Final) B. Weakened Common Diviso

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Light2Chasers/article/details/81865041
  1. problem link:http://codeforces.com/contest/1025/problem/B
  2. 题意:给你又一个n和n对数,找到每对数乘积的都含有的一个因数,如果没有输出-1,如果有输出任意的一个。
  3. 解题思路:先找到每对数的最大公倍数,然后再与每对数进行gcd,过滤得到最终结果。
  4. AC code:
#include<iostream>
using namespace std;
typedef long long ll;
const int N=15e4+6;
pair<ll,ll>itv[N];
ll gcd(ll a,ll b){if(!b)return a;return gcd(b,a%b);}
int main(){
    ios::sync_with_stdio(false);cin.tie(0);
    int n;cin>>n;
    for(int i=1;i<=n;i++)cin>>itv[i].first>>itv[i].second;
    ll res=itv[1].first*itv[1].second;
    for(int i=2;i<=n;i++)res=gcd(res,itv[i].first*itv[i].second);
    for(int i=1;i<=n;i++){
        int x=gcd(res,itv[i].first),y=gcd(res,itv[i].second);
        if(x==1)res=y;else res=x;
    }
    res=res==1?-1:res;cout<<res<<endl;
}

猜你喜欢

转载自blog.csdn.net/Light2Chasers/article/details/81865041