fork download
  1. /*
  2. * Author: Geeza
  3. */
  4.  
  5. #include <bits/stdc++.h>
  6.  
  7. #define ld long double
  8. #define ll long long
  9. #define pb push_back
  10. #define fin(a, n) for(int i = a; i < n; i++)
  11. #define fjn(a, n) for(int j = a; j < n; j++)
  12. #define all(a) a.begin(),a.end()
  13. #define allr(a) a.rbegin(),a.rend()
  14. #define FAST ios_base::sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr)
  15.  
  16. using namespace std;
  17.  
  18. const double PI = acos(-1);
  19. const int N = 1e5+20;
  20. const ll oo = 0x3f3f3f3f3f3f3f3f;
  21. const int MOD = 1000000007, inf = 1e6;
  22.  
  23. string di[] = {"D","L", "U", "R", "UL", "UR", "DL", "DR"};
  24. int dx[] = {+1, +0, +0, -1, -1, -1, +1, +1};
  25. int dy[] = {+0, -1, +1, +0, -1, +1, -1, +1};
  26. char dc[] = {'D', 'L', 'R', 'U'};
  27.  
  28. struct DSU {
  29. vector<int> parent, size;
  30. ll tot;
  31. DSU(int n) : parent(n + 1), size(n + 1, 1) {
  32. iota(parent.begin(), parent.end(), 0);
  33. tot = n;
  34. }
  35.  
  36. int find(int x) {
  37. if (x == parent[x]) return x;
  38. return parent[x] = find(parent[x]);
  39. }
  40.  
  41. bool unite(int x, int y) {
  42. x = find(x);
  43. y = find(y);
  44. if (x == y) return false;
  45. if (size[x] < size[y]) swap(x, y);
  46. tot--;
  47. parent[y] = x;
  48. size[x] += size[y];
  49. return true;
  50. }
  51. };
  52.  
  53. void solve() {
  54. ll n, m1, m2; cin >> n >> m1 >> m2;
  55. ll mx = max(m1, m2);
  56. if (mx == n-1) return void(cout << "0\n");
  57.  
  58. DSU dsu1(n), dsu2(n);
  59.  
  60. fin(0, m1) {
  61. ll u, v; cin >> u >> v;
  62. dsu1.unite(u, v);
  63. }
  64.  
  65. fin(0, m2) {
  66. ll u, v; cin >> u >> v;
  67. dsu2.unite(u, v);
  68. }
  69.  
  70. ll needed = n-1-mx;
  71. vector<pair<ll, ll>> ans;
  72. for (ll i = 2, x = 0; i <= n; i++) {
  73. if (needed == x) break;
  74. bool can1 = (dsu1.find(1) != dsu1.find(i));
  75. bool can2 = (dsu2.find(1) != dsu2.find(i));
  76. if (can1 && can2) {
  77. ans.push_back({1, i});
  78. x++;
  79. }
  80. }
  81. cout << needed << "\n";
  82. for (auto [u, v] : ans) {
  83. cout << u << " " << v << "\n";
  84. }
  85. }
  86.  
  87. int main() {
  88. FAST;
  89. #ifndef ONLINE_JUDGE
  90. freopen("input.txt","r",stdin);
  91. freopen("output.txt","w",stdout);
  92. #endif
  93. int tt = 1; //cin >> tt;
  94. while(tt--){
  95. solve();
  96. }
  97. return 0;
  98. }
Success #stdin #stdout 0s 5320KB
stdin
Standard input is empty
stdout
-1