結果

問題 No.583 鉄道同好会
ユーザー kokatsukokatsu
提出日時 2023-01-09 21:58:43
言語 D
(dmd 2.106.1)
結果
AC  
実行時間 54 ms / 2,000 ms
コード長 1,722 bytes
コンパイル時間 2,376 ms
コンパイル使用メモリ 201,952 KB
実行使用メモリ 4,380 KB
最終ジャッジ日時 2023-09-04 19:36:28
合計ジャッジ時間 3,922 ms
ジャッジサーバーID
(参考情報)
judge11 / judge15
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 1 ms
4,380 KB
testcase_01 AC 2 ms
4,376 KB
testcase_02 AC 1 ms
4,376 KB
testcase_03 AC 2 ms
4,376 KB
testcase_04 AC 1 ms
4,376 KB
testcase_05 AC 2 ms
4,376 KB
testcase_06 AC 2 ms
4,376 KB
testcase_07 AC 1 ms
4,380 KB
testcase_08 AC 1 ms
4,380 KB
testcase_09 AC 2 ms
4,380 KB
testcase_10 AC 1 ms
4,376 KB
testcase_11 AC 13 ms
4,380 KB
testcase_12 AC 19 ms
4,380 KB
testcase_13 AC 19 ms
4,380 KB
testcase_14 AC 19 ms
4,376 KB
testcase_15 AC 24 ms
4,380 KB
testcase_16 AC 44 ms
4,380 KB
testcase_17 AC 54 ms
4,376 KB
testcase_18 AC 53 ms
4,376 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

import std;

void main() {
    int N, M;
    readf("%d %d\n", N, M);

    auto uf = new UnionFind!int(N);
    auto cnts = new int[](N);
    foreach (_; 0 .. M) {
        int S, T;
        readf("%d %d\n", S, T);

        uf.unite(S, T);
        ++cnts[S], ++cnts[T];
    }

    int pos = -1, cnt1, cnt2;
    foreach (i; 0 .. N) {
        if (cnts[i] == 0) continue;

        if (uf.root(i) == i) pos = i, ++cnt1;
        if (cnts[i] % 2 == 1) ++cnt2;
    }

    writeln(cnt1 == 1 && cnt2 <= 2 ? "YES" : "NO");
}

/// Union-Find
struct UnionFind(T)
if (isIntegral!T) {

    /// Constructor
    this(T n) nothrow @safe {
        len = n;
        par.length = len;
        cnt.length = len;
        foreach (i; 0 .. len) {
            par[i] = i;
        }
        cnt[] = 1;
    }

    /// Returns the root of x.
    T root(T x) nothrow @nogc @safe
    in (0 <= x && x < len) {
        if (par[x] == x) {
            return x;
        }
        else {
            return par[x] = root(par[x]);
        }
    }

    /// Returns whether x and y have the same root.
    bool isSame(T x, T y) nothrow @nogc @safe
    in (0 <= x && x < len && 0 <= y && y < len) {
        return root(x) == root(y);
    }

    /// Unites x tree and y tree.
    void unite(T x, T y) nothrow @nogc @safe
    in (0 <= x && x < len && 0 <= y && y < len) {
        x = root(x), y = root(y);
        if (x == y) {
            return;
        }

        if (cnt[x] > cnt[y]) {
            swap(x, y);
        }

        cnt[y] += cnt[x];
        par[x] = y;
    }

    /// Returns the size of the x tree.
    T size(T x) nothrow @nogc @safe
    in (0 <= x && x < len) {
        return cnt[root(x)];
    }

private:
    T len;
    T[] par;
    T[] cnt;
}
0