Salvens

Untitled

Aug 1st, 2023
896
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.21 KB | None | 0 0
  1. #include <iostream>
  2. #include <iomanip>
  3. #include <vector>
  4. #include <array>
  5. #include <set>
  6.  
  7. using namespace std;
  8.  
  9. #define int long long
  10.  
  11. const long long INF = 1e18 + 7;
  12. const int MAXN = 1e5 + 100;
  13. const int N = 1e5 + 10;
  14. const int MOD = 1e9 + 7;
  15.  
  16. int dp[MAXN][2];
  17. vector<vector<int>> g;
  18.  
  19. void dfs(int v, int p) {
  20.     dp[v][0] = dp[v][1] = 0;
  21.     for (auto to: g[v]) {
  22.         if (to == p) continue;
  23.         dfs(to, v);
  24.         dp[v][0] = max({dp[v][0], dp[to][0], dp[to][1]});
  25.         dp[v][1] = max(dp[v][1], dp[to][0]);
  26.     }
  27.     dp[v][1] += 1;
  28. }
  29.  
  30. void get_ans(int u, int p = -1) {
  31.     for (auto v: g[u]) {
  32.         if (v == p) {
  33.             continue;
  34.         }
  35.         if (dp[v][1] > dp[v][0]) {
  36.             cout << u + 1 << ' ' << v + 1 << '\n';
  37.         }
  38.         get_ans(v, u);
  39.     }
  40. }
  41.  
  42. signed main() {
  43.     ios_base::sync_with_stdio(false);
  44.     cin.tie(nullptr);
  45.     cout.tie(nullptr);
  46.     int n, m;
  47.     cin >> n >> m;
  48.     g.resize(n);
  49.     for (int i = 0; i < m; ++i) {
  50.         int u, v;
  51.         cin >> u >> v;
  52.         --u, --v;
  53.         g[u].emplace_back(v);
  54.         g[v].emplace_back(u);
  55.     }
  56.  
  57.     dfs(0, -1);
  58.  
  59.     cout << max(dp[0][0], dp[0][1]) << '\n';
  60.     get_ans(0);
  61. }
Advertisement
Add Comment
Please, Sign In to add comment