結果

問題 No.2756 GCD Teleporter
ユーザー MZKi
提出日時 2023-03-13 18:55:15
言語 C++17
(gcc 13.3.0 + boost 1.87.0)
結果
AC  
実行時間 160 ms / 2,000 ms
コード長 1,809 bytes
コンパイル時間 4,164 ms
コンパイル使用メモリ 258,116 KB
最終ジャッジ日時 2025-02-11 10:58:46
ジャッジサーバーID
(参考情報)
judge2 / judge1
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 4
other AC * 36
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <bits/stdc++.h>
#include<atcoder/all>
using namespace std;

using ll = long long;

struct smart_sieve{
	int n;
	vector<int> f;
	// 初期構築 : (nloglog(n))
	smart_sieve(int x = 1) :n(x), f(x+1, -1){
        for(ll i = 2; i <= n; i++){
            if(f[i] != -1)continue;
            for(ll j = i*i; j <= n; j += i){
                f[j] = (f[j] == -1 ? i : f[j]);
            }
            f[i] = i;
        }
	}
	// 素数判定 : O(1)
	bool isPrime(int x){return f[x] == x;}
	// 素因数分解 : O(log(n))
	vector<pair<ll,ll>> prime_factor(int x){
        if(x == 1)return {};
        vector<pair<ll, ll>> ret;
        ret.emplace_back(f[x], 1); x /= f[x];
		while(x != 1){
            if(f[x] == ret.back().first){
                ret.back().second++;
            }else{
                ret.emplace_back(f[x], 1);
            }
            x /= f[x];
        }
        return ret;
	}
};

int main(){
    int n;
    cin >> n;
    vector<int> a(n);
    for(int i = 0; i < n; i++)cin >> a[i];

    set<int> pf;
    smart_sieve ss(200000);
    for(int i = 0; i < n; i++){
        vector<pair<ll, ll>> p;
        p = ss.prime_factor(a[i]);
        for(auto x : p)pf.insert(x.first);
    }
    
    int cnt = 0, mn = 1e9+7;
    vector<int> pos(200000, -1);
    for(auto it = pf.begin(); it != pf.end(); it++){
        mn = (mn == 1e9+7 ? (*it) : mn); pos[*it] = cnt++;
    }

    atcoder::dsu uf(n+cnt);
    for(int i = 0; i < n; i++){
        vector<pair<ll, ll>> p;
        p = ss.prime_factor(a[i]);
        for(auto x : p)uf.merge(i, n+pos[x.first]);
    }

    set<int> st;
    for(int i = 0; i < n; i++)st.insert(uf.leader(i));
    int ans = 1e9+7, S = st.size();
    if(pos[2] == -1){
        ans = min(2*S, mn * (S-1));
    }else{
        ans = 2 * (S-1);
    }
	
    cout << ans << endl;
}
0