結果

問題 No.3093 Safe Infection
ユーザー miya145592
提出日時 2025-04-06 16:49:25
言語 C++23
(gcc 13.3.0 + boost 1.87.0)
結果
TLE  
実行時間 -
コード長 2,493 bytes
コンパイル時間 1,609 ms
コンパイル使用メモリ 123,164 KB
実行使用メモリ 11,908 KB
最終ジャッジ日時 2025-04-06 16:49:34
合計ジャッジ時間 8,711 ms
ジャッジサーバーID
(参考情報)
judge1 / judge3
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
other AC * 45 TLE * 1 -- * 24
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>

using namespace std;

class UnionFind {
public:
    vector<int> par, rank, siz;
    int cnt;

    UnionFind(int n) {
        par.assign(n, -1);
        rank.assign(n, 0);
        siz.assign(n, 1);
        cnt = n;
    }

    int root(int x) {
        if (par[x] == -1) return x;
        return par[x] = root(par[x]);
    }

    bool issame(int x, int y) {
        return root(x) == root(y);
    }

    bool unite(int x, int y) {
        int px = root(x);
        int py = root(y);
        if (px == py) return false;
        if (rank[px] < rank[py]) swap(px, py);
        par[py] = px;
        if (rank[px] == rank[py]) rank[px]++;
        siz[px] += siz[py];
        cnt--;
        return true;
    }

    int count() {
        return cnt;
    }

    int size(int x) {
        return siz[root(x)];
    }
};

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

    int N, M, K;
    cin >> N >> M >> K;
    vector<int> A(N);
    for (int i = 0; i < N; ++i) {
        cin >> A[i];
    }

    vector<vector<pair<int, int>>> G(N);
    for (int i = 0; i < M; ++i) {
        int u, v;
        cin >> u >> v;
        u--; v--;
        G[u].emplace_back(A[v], v);
        G[v].emplace_back(A[u], u);
    }

    UnionFind UF(N);
    priority_queue<pair<int, int>, vector<pair<int, int>>, greater<>> dp;
    for (int i = 0; i < N; ++i) {
        dp.emplace(A[i], i);
    }

    while (dp.size() > 1) {
        auto [a, i] = dp.top(); dp.pop();
        int ri = UF.root(i);
        priority_queue<pair<int, int>, vector<pair<int, int>>, greater<>> pq(G[ri].begin(), G[ri].end());
        if (pq.empty()) continue;
        auto [s, j] = pq.top(); pq.pop();
        int rj = UF.root(j);
        if (s - a > K) {
            cout << "No\n";
            return 0;
        }
        UF.unite(i, j);
        int r = UF.root(i);
        if (G[ri].size() < G[rj].size()) {
            // discard one edge to avoid duplicate
            G[rj].erase(remove_if(G[rj].begin(), G[rj].end(), [&](auto& p) { return p.second == ri; }), G[rj].end());
            G[rj].insert(G[rj].end(), G[ri].begin(), G[ri].end());
            G[ri].clear();
            G[r] = G[rj];
        } else {
            for (auto& g : G[rj]) {
                if (g.second == ri) continue;
                G[ri].push_back(g);
            }
            G[rj].clear();
            G[r] = G[ri];
        }
    }

    cout << "Yes\n";
    return 0;
}
0