結果

問題 No.2756 GCD Teleporter
ユーザー GOTKAKO
提出日時 2024-05-10 22:37:41
言語 C++17
(gcc 13.3.0 + boost 1.87.0)
結果
AC  
実行時間 224 ms / 2,000 ms
コード長 2,467 bytes
コンパイル時間 2,997 ms
コンパイル使用メモリ 219,548 KB
最終ジャッジ日時 2025-02-21 13:01:19
ジャッジサーバーID
(参考情報)
judge2 / judge2
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 4
other AC * 36
権限があれば一括ダウンロードができます

ソースコード

diff #

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

class UnionFind{
    public:
    vector<int> par,siz;
    vector<bool> have2,have3;
 
    void make(int N){
        par.resize(N,-1);
        siz.resize(N,1);
        have2.resize(N); have3.resize(N);
    }
 
    int root(int x){
        if(par.at(x) == -1) return x;
        else return par.at(x) = root(par.at(x));
    }
 
    void unite(int u, int v){
        u = root(u),v = root(v);
        if(u == v) return;
        if(siz.at(u) < siz.at(v)) swap(u,v);
 
        par.at(v) = u; 
        siz.at(u) += siz.at(v);
        have2.at(u) = (have2.at(u)||have2.at(v)); 
        have3.at(u) = (have3.at(u)||have3.at(v));
    }
 
    bool issame(int u, int v){
        if(root(u) == root(v)) return true;
        else return false;
    }
};

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);

    int Need = 200000;
    vector<vector<pair<int,int>>> Pf(Need+1);
    vector<bool> prime(Need+1,true);
    prime.at(0) = false; prime.at(1) = false;
    for(int i=2; i<=Need; i++){
        if(!prime.at(i)) continue;
        Pf.at(i) = {{i,1}};
        for(int k=i+i; k<=Need; k+=i){
            prime.at(k) = false;
            int f = 0,k2 = k;
            while(k2%i == 0) f++,k2 /= i;
            Pf.at(k).push_back({i,f});
        }
    }

    int N; cin >> N;
    UnionFind Z; Z.make(N);
    vector<vector<int>> fac(Need);
    for(int i=0; i<N; i++){
        int a; cin >> a;
        for(auto[p,e] : Pf.at(a)) fac.at(p).push_back(i);
        if(a%2 == 0) Z.have2.at(i) = true;
        if(a%3 == 0) Z.have3.at(i) = true;
    }

    int group = N;
    for(int i=0; i<Need; i++){
        int siz=fac.at(i).size();
        for(int k=0; k<siz-1; k++){
            int pos1 = fac.at(i).at(k),pos2 = fac.at(i).at(k+1);
            if(Z.issame(pos1,pos2)) continue;
            group--; Z.unite(pos1,pos2);
        }
    }
    int answer = 0;
    set<int> leader;
    for(int i=0; i<N; i++) leader.insert(Z.root(i));
    if(group == 2){
        bool two = false,three = false;
        for(auto pos : leader){
            if(Z.have2.at(pos)) two = true;
            if(Z.have3.at(pos)) three = true;
        }
        if(two) answer = 2;
        else if(three) answer = 3;
        else answer = 4;
    }
    else if(group >= 3){
        bool two = false;
        for(auto pos : leader) if(Z.have2.at(pos)) two = true;
        answer = 2*group;
        if(two) answer -= 2;
    }
    cout << answer << endl;
}
0