結果

問題 No.994 ばらばらコイン
ユーザー KoseTKoseT
提出日時 2020-02-21 22:21:41
言語 C++14
(gcc 13.2.0 + boost 1.83.0)
結果
AC  
実行時間 60 ms / 2,000 ms
コード長 1,311 bytes
コンパイル時間 619 ms
コンパイル使用メモリ 73,108 KB
実行使用メモリ 5,376 KB
最終ジャッジ日時 2024-04-17 07:42:05
合計ジャッジ時間 2,127 ms
ジャッジサーバーID
(参考情報)
judge4 / judge1
このコードへのチャレンジ(β)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 2 ms
5,248 KB
testcase_01 AC 2 ms
5,376 KB
testcase_02 AC 60 ms
5,376 KB
testcase_03 AC 60 ms
5,376 KB
testcase_04 AC 60 ms
5,376 KB
testcase_05 AC 30 ms
5,376 KB
testcase_06 AC 60 ms
5,376 KB
testcase_07 AC 60 ms
5,376 KB
testcase_08 AC 42 ms
5,376 KB
testcase_09 AC 55 ms
5,376 KB
testcase_10 AC 41 ms
5,376 KB
testcase_11 AC 47 ms
5,376 KB
testcase_12 AC 50 ms
5,376 KB
testcase_13 AC 2 ms
5,376 KB
testcase_14 AC 2 ms
5,376 KB
testcase_15 AC 2 ms
5,376 KB
testcase_16 AC 2 ms
5,376 KB
testcase_17 AC 2 ms
5,376 KB
testcase_18 AC 2 ms
5,376 KB
testcase_19 AC 2 ms
5,376 KB
testcase_20 AC 2 ms
5,376 KB
testcase_21 AC 2 ms
5,376 KB
testcase_22 AC 2 ms
5,376 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <iostream>
#include <vector>

using ll = long long;
#define rep(i,n) for(int i = 0;i < (n);++i)
#include <utility>
using P = std::pair<int, int>;

class UnionFind{
  private:
    std::vector<int> parent; // if (parent[i] == i) ==> parent[i] is root
    std::vector<int> rank;
  public:
    UnionFind(const int& N) :parent(N), rank(N, 0) {
      for (auto i = 0;i < N;++i) {
        parent[i] = i;
      }
    }
    int find(const int& x) { // find tree root
      if (parent[x] == x) return x;
      else return parent[x] = find(parent[x]);
    }
    void unite(int x, int y) { // x-tree add y-tree
      x = find(x);
      y = find(y);
      if (x == y) return;

      if (rank[x] < rank[y]) {
        parent[x] = y;
      } else {
        parent[y] = x;
        if (rank[x] == rank[y]) ++rank[x];
      }
    }
    bool same(const int& x, const int& y) {
      return find(x) == find(y);
    }
};

int main(int argc, char** argv) {
  ll N, K;
  std::cin >> N >> K;
  std::vector<P> tree(N);
  rep(i, N-1) std::cin >> tree[i].first >> tree[i].second;
  UnionFind f(N+1);
  rep(i, N-1) f.unite(tree[i].first, tree[i].second);

  ll sum {};
  for(auto i = 1;i <= N;++i) {
    if (f.same(1, i)) ++sum;
  }
  if (sum < K || N < K) {
    std::cout << "-1\n";
  } else {
    std::cout << K-1 << '\n';
  }
}
0