結果

問題 No.416 旅行会社
ユーザー rsk0315rsk0315
提出日時 2019-03-17 20:10:09
言語 C++17
(gcc 13.2.0 + boost 1.83.0)
結果
WA  
実行時間 -
コード長 1,940 bytes
コンパイル時間 1,210 ms
コンパイル使用メモリ 78,900 KB
実行使用メモリ 30,976 KB
最終ジャッジ日時 2023-09-22 00:27:33
合計ジャッジ時間 13,943 ms
ジャッジサーバーID
(参考情報)
judge15 / judge11
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 104 ms
20,488 KB
testcase_01 AC 1 ms
4,380 KB
testcase_02 AC 1 ms
4,376 KB
testcase_03 AC 2 ms
4,380 KB
testcase_04 WA -
testcase_05 WA -
testcase_06 WA -
testcase_07 WA -
testcase_08 WA -
testcase_09 WA -
testcase_10 AC 147 ms
20,492 KB
testcase_11 AC 152 ms
20,384 KB
testcase_12 AC 152 ms
20,492 KB
testcase_13 AC 3,923 ms
20,504 KB
testcase_14 AC 385 ms
30,872 KB
testcase_15 AC 1,028 ms
30,904 KB
testcase_16 AC 1,782 ms
30,932 KB
testcase_17 AC 812 ms
30,864 KB
testcase_18 AC 639 ms
30,976 KB
testcase_19 WA -
testcase_20 WA -
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <cstdio>
#include <cstdint>
#include <cassert>
#include <vector>
#include <utility>
#include <algorithm>
#include <set>
#include <tuple>
#include <numeric>

class quick_find {
  std::vector<std::vector<size_t>> groups;
  std::vector<size_t> index;

public:
  quick_find(size_t n): index(n) {
    std::iota(index.begin(), index.end(), 0);
    for (size_t i = 0; i < n; ++i)
      groups.emplace_back(1, i);
  }

  bool unite(size_t u, size_t v) {
    if (index[u] == index[v]) return false;

    if (groups[index[u]].size() > groups[index[v]].size())
      std::swap(u, v);

    size_t pi = index[u];
    for (size_t i: groups[index[u]]) {
      index[i] = index[v];
      groups[index[v]].push_back(i);
    }
    groups[pi].clear();

    return true;
  }

  const std::vector<size_t>& components(size_t v) const {
    return groups[index[v]];
  }

  bool connected(size_t u, size_t v) const {
    return index[u] == index[v];
  }
};

int main() {
  size_t N, M, Q;
  scanf("%zu %zu %zu", &N, &M, &Q);

  using edge = std::pair<size_t, size_t>;

  std::vector<edge> ab(M);
  for (auto& p: ab) {
    scanf("%zu %zu", &p.first, &p.second);
    --p.first;
    --p.second;
  }

  std::vector<edge> cd(Q);
  std::set<edge> es;
  for (auto& p: cd) {
    scanf("%zu %zu", &p.first, &p.second);
    --p.first;
    --p.second;
    es.emplace(p.first, p.second);
  }

  quick_find qf(N);
  for (const auto& p: ab) {
    size_t a, b;
    std::tie(a, b) = p;
    if (es.count({a, b})) continue;
    qf.unite(a, b);
  }

  std::vector<int> res(N, 0);
  for (size_t u: qf.components(0))
    res[u] = -1;

  for (size_t i = Q; i--;) {
    size_t c, d;
    std::tie(c, d) = cd[i];

    if (qf.connected(c, d)) continue;

    size_t u = c;
    if (qf.connected(0, u)) u = d;

    const auto& cmp = qf.components(u);
    for (size_t v: cmp) res[v] = i+1;

    qf.unite(c, d);
  }

  res.erase(res.begin());
  for (auto ri: res) printf("%d\n", ri);
}
0