Advertisement
glerium

abc394_f

Feb 22nd, 2025
328
0
29 days
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.49 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. #define endl '\n'
  3. #define rep(i,x,y) for(int i=x;i<=y;i++)
  4. using namespace std;
  5. typedef long long ll;
  6. constexpr int maxn = 2e5+10;
  7. constexpr ll mod = 998244353;
  8. void solve() {
  9.     int n; cin >> n;
  10.     int a[n+5] = {}, b[n+5] = {};
  11.     int de[n+5] = {};
  12.     bool ok[n+5] = {};
  13.     rep(i,1,n-1) {
  14.         cin >> a[i] >> b[i];
  15.         de[a[i]]++; de[b[i]]++;
  16.     }
  17.     rep(i,1,n) {
  18.         ok[i] = (de[i] >= 4);
  19.     }
  20.     vector<vector<int>> p(n+5);
  21.     rep(i,1,n-1) {
  22.         if(ok[a[i]] && ok[b[i]]) {
  23.             p[a[i]].push_back(b[i]);
  24.             p[b[i]].push_back(a[i]);
  25.         }
  26.     }
  27.     vector<bool> vis(n+5, false);
  28.     function<int(int, int)> dfs = [&](int x, int fa) -> int {
  29.         int sz = 1;
  30.         vector<int> vret;
  31.         for(auto i : p[x]) {
  32.             if(!vis[i]) {
  33.                 vis[i] = true;
  34.                 vret.push_back(dfs(i, x));
  35.             }
  36.         }
  37.         if(!vret.empty())
  38.             sort(vret.begin(), vret.end(), greater<int>());
  39.  
  40.         rep(i,0,min(3 - (fa != -1), int(vret.size())-1))
  41.             sz += vret[i];
  42.         return sz;
  43.     };
  44.     int ans = -1;
  45.     rep(i,1,n) {
  46.         if(!vis[i] && ok[i]) {
  47.             vis[i] = true;
  48.             ans = max(ans, dfs(i, -1));
  49.         }
  50.     }
  51.     if(ans == -1)
  52.         cout << -1 << endl;
  53.     else cout << 3 * ans + 2 << endl;
  54. }
  55. int main() {
  56.     ios::sync_with_stdio(false);
  57.     cin.tie(nullptr);
  58.     int t = 1;
  59.     while(t--) solve();
  60.     return 0;
  61. }
  62.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement