bhupixb

Generating a tree

Aug 15th, 2019
122
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.13 KB | None | 0 0
  1. #include "bits/stdc++.h"
  2. using namespace std;
  3.  
  4. #define int long long
  5.  
  6. inline int rand(int l, int r){
  7. static std::mt19937 rng(std::chrono::steady_clock::now().time_since_epoch().count());
  8. std::uniform_int_distribution<int> uid(l, r); return uid(rng);
  9. }
  10. const int N = 1e5+4;
  11. #define rep(i,a,n) for (int i = a; i <= n; ++i)
  12.  
  13. int parent[N];
  14.  
  15. int find(int x) {
  16. if (x == parent[x]) {
  17. return x;
  18. }
  19. return parent[x] = find(parent[parent[x]]);
  20. }
  21.  
  22. void join(int x, int y) {
  23. int px = find(x);
  24. int py = find(y);
  25. parent[px] = py;
  26. }
  27.  
  28. signed main() {
  29. int n = rand(1, 10);
  30. rep(i,1,n)
  31. parent[i] = i;
  32. cout << "1\n" << n << '\n';
  33. vector < pair < int, int > > v;
  34. rep(i,1,n)
  35. rep(j,i+1,n)
  36. v.push_back({i, j});
  37. random_shuffle(v.begin(), v.end());
  38. int cnt = 0;
  39. for (auto i : v) {
  40. if (find(i.first) != find(i.second)) {
  41. join(i.first, i.second);
  42. ++cnt;
  43. cout << i.first << ' ' << i.second << ' ' << rand(1, n) << '\n';
  44. }
  45. if (cnt == n-1)
  46. break;
  47. }
  48. }
Add Comment
Please, Sign In to add comment