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

【链接】 我是链接,点我呀:)
【题意】


给你n个数对(ai,bi)。
让你求一个大于1的数字x
使得对于任意的i
x|a[i] 或者 x|b[i]

【题解】


求出第一个数对的两个数他们有哪些质因子。

显然用这些质因子去试2..n就可以了。
看哪个可以满足 就输出对应的就可以了。

(一开始我求出这个数的所有因子(TLE了)。。其实没有必要。。。因为假设y是x的倍数。。然后y满足的话,显然x也能满足要求。。所以只要用质因子搞就行了。

【代码】

#include <bits/stdc++.h>
#define LL long long
#define rep1(i,a,b) for (int i = a;i <= b;i++)
#define rep2(i,a,b) for (int i = a;i >= b;i--)
#define all(x) x.begin(),x.end()
#define pb push_back
#define lson l,mid,rt<<1
#define ri(x) scanf("%d",&x)
#define rl(x) scanf("%lld",&x)
#define rs(x) scanf("%s",x)
#define rson mid+1,r,rt<<1|1
using namespace std;

const double pi = acos(-1);
const int dx[4] = {0,0,1,-1};
const int dy[4] = {1,-1,0,0};

const int N = 15e4;

int n,m;
int a[N+10][2];
set<int> myset;
vector<int> v;

void get_yinzi(int x){
    int len = sqrt(x);
    for (int i = 1;i <= len;i++){
        if (x%i==0) {
            myset.insert(i);
            while (x%i==0 && i!=1 ) x/=i;
        }
    }
    if (x>1) myset.insert(x);
}

int main(){
    #ifdef LOCAL_DEFINE
        freopen("rush_in.txt", "r", stdin);
    #endif
    scanf("%d",&n);
    for (int i = 1;i <= n;i++) scanf("%d%d",&a[i][0],&a[i][1]);
    for (int i = 0;i <=1;i++) get_yinzi(a[1][i]);
    for (int x:myset) v.push_back(x);
    m=v.size();
    for (int i = 0;i < m;i++){
        int x = v[i];
        if (x<=1) continue;
        bool ok = true;
        for (int j = 2;j <= n;j++){
            if ((a[j][0]%x==0) || (a[j][1]%x==0)){
                continue;
            }else {
                ok = false;
                break;
            }
        }
        if (ok){
            printf("%d\n",x);
            return 0;
        }
    }
    puts("-1");
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/AWCXV/p/9504006.html