1
0

undirected-tree-validator.cpp 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. #include "testlib.h"
  2. #include <vector>
  3. #include <set>
  4. using namespace std;
  5. int leader(vector<int> &dsu, int idx) {
  6. return dsu[idx] == idx ? dsu[idx] : (dsu[idx] = leader(dsu, dsu[idx]));
  7. }
  8. bool merge(vector<int> &dsu, int a, int b) {
  9. a = leader(dsu, a);
  10. b = leader(dsu, b);
  11. if (a == b)
  12. return false;
  13. else {
  14. if (rnd.next(2) == 0)
  15. dsu[a] = b;
  16. else
  17. dsu[b] = a;
  18. return true;
  19. }
  20. }
  21. int main(int argc, char *argv[]) {
  22. registerValidation(argc, argv);
  23. int n = inf.readInt(2, 100'000, "n");
  24. inf.readEoln();
  25. vector<int> dsu(n);
  26. for (int i = 0; i < n; i++)
  27. dsu[i] = i;
  28. set<pair<int, int>> edges;
  29. for (int i = 0; i < n - 1; i++) {
  30. int x = inf.readInt(1, n, "x_i");
  31. inf.readSpace();
  32. int y = inf.readInt(1, n, "y_i");
  33. inf.readEoln();
  34. ensuref(x != y, "Tree can't contain loops");
  35. ensuref(edges.count(make_pair(x, y)) == 0, "Tree can't contain multiple edges between a pair of vertices");
  36. edges.insert(make_pair(x, y));
  37. edges.insert(make_pair(y, x));
  38. ensuref(merge(dsu, x - 1, y - 1), "Tree can't contain cycles");
  39. }
  40. inf.readEof();
  41. }