結果

問題 No.1293 2種類の道路
ユーザー ninoinuininoinui
提出日時 2020-11-20 23:42:46
言語 C++17
(gcc 12.3.0 + boost 1.83.0)
結果
AC  
実行時間 59 ms / 2,000 ms
コード長 1,854 bytes
コンパイル時間 2,374 ms
コンパイル使用メモリ 213,584 KB
実行使用メモリ 8,792 KB
最終ジャッジ日時 2023-09-30 20:10:32
合計ジャッジ時間 4,268 ms
ジャッジサーバーID
(参考情報)
judge13 / judge15
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 2 ms
4,384 KB
testcase_01 AC 1 ms
4,376 KB
testcase_02 AC 1 ms
4,376 KB
testcase_03 AC 1 ms
4,380 KB
testcase_04 AC 1 ms
4,380 KB
testcase_05 AC 2 ms
4,380 KB
testcase_06 AC 1 ms
4,380 KB
testcase_07 AC 1 ms
4,376 KB
testcase_08 AC 1 ms
4,376 KB
testcase_09 AC 56 ms
5,468 KB
testcase_10 AC 56 ms
5,128 KB
testcase_11 AC 56 ms
5,512 KB
testcase_12 AC 57 ms
5,548 KB
testcase_13 AC 56 ms
5,180 KB
testcase_14 AC 49 ms
8,792 KB
testcase_15 AC 49 ms
8,556 KB
testcase_16 AC 51 ms
6,716 KB
testcase_17 AC 54 ms
7,248 KB
testcase_18 AC 41 ms
7,820 KB
testcase_19 AC 58 ms
8,592 KB
testcase_20 AC 59 ms
8,536 KB
testcase_21 AC 30 ms
4,380 KB
testcase_22 AC 29 ms
4,380 KB
testcase_23 AC 29 ms
4,380 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

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

template <typename T, typename U> bool cmin(T &a, U b) { return a > b && (a = b, true); }
template <typename T, typename U> bool cmax(T &a, U b) { return a < b && (a = b, true); }

class UnionFind {
private:
  int N;
  vector<int> PS;

public:
  UnionFind() : N(0) {}
  UnionFind(int n) : N(n), PS(n, -1) {}
  bool unite(int a, int b) {
    int x = root(a), y = root(b);
    if (x == y) return false;
    if (-PS.at(x) < -PS.at(y)) swap(x, y);
    PS.at(x) += PS.at(y);
    PS.at(y) = x;
    return true;
  }
  bool same(int a, int b) { return root(a) == root(b); }
  int root(int a) {
    if (PS.at(a) < 0) return a;
    return PS.at(a) = root(PS.at(a));
  }
  int size(int a) { return -PS.at(root(a)); }
  vector<vector<int>> groups() {
    vector<int> B(N), S(N);
    for (int i = 0; i < N; i++) {
      B.at(i) = root(i);
      S.at(B.at(i))++;
    }
    vector<vector<int>> ret(N);
    for (int i = 0; i < N; i++) {
      ret.at(i).reserve(S.at(i));
    }
    for (int i = 0; i < N; i++) {
      ret.at(B.at(i)).push_back(i);
    }
    auto f = [&](const vector<int> &v) { return v.empty(); };
    ret.erase(remove_if(ret.begin(), ret.end(), f), ret.end());
    return ret;
  }
};

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

  int N, D, W;
  cin >> N >> D >> W;

  UnionFind UF(N);
  UnionFind UF2(N);

  for (int i = 0; i < D; i++) {
    int a, b;
    cin >> a >> b, a--, b--;
    UF.unite(a, b);
  }

  for (int i = 0; i < W; i++) {
    int a, b;
    cin >> a >> b, a--, b--;
    UF2.unite(a, b);
  }

  long ans = 0;
  set<pair<int, int>> tmp;
  for (int i = 0; i < N; i++) {
    if (tmp.count({UF.root(i), UF2.root(i)})) continue;
    tmp.insert({UF.root(i), UF2.root(i)});
    ans += (long)UF.size(UF.root(i)) * UF2.size(UF2.root(i));
  }
  cout << ans - N << "\n";
}
0