제출 #618095

#제출 시각아이디문제언어결과실행 시간메모리
618095narvaloUntitled (POI11_ins)C++17
0 / 100
1004 ms71188 KiB
#include <bits/stdc++.h>

using namespace std;

int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  int n;
  cin >> n;
  if (n == 1) {
    cout << 0 << '\n';
    return 0;
  }
  vector<vector<int>> adj(n);
  for (int i = 0 ; i < n - 1 ; i += 1) {
    int a , b;
    cin >> a >> b;
    a -= 1 , b -= 1;
    adj[a].push_back(b);
    adj[b].push_back(a);
  }
  vector<pair<int , int>> dp(n);
  function<pair<int , int>(int , int)> Dfs = [&](int node , int pre) {
    int ans = 1;
    for (auto x : adj[node]) {
      if (x == pre) continue;
      ans += Dfs(x , node).first;
    }
    return dp[node] = make_pair(ans , pre);
  };
  Dfs(0 , -1);
  long long ans = 0;
  int max_depth = 0;
  function<void(int , int , int)> Get = [&](int node , int pre , int depth) {
    max_depth = max(depth , max_depth);
    ans += 1LL * depth * 2;
    for (auto x : adj[node]) {
      if (x == pre) continue;
      Get(x , node , depth + 1);
    }
    return ;
  };
  auto Init = [&]() {
    max_depth = 0;
    ans = 0;
    return ;
  };
  vector<int> sum(n);
  for (int i = 0 ; i < n ; i++) {
    for (auto x : adj[i]) {
      if (x == dp[i].second) continue;
      sum[i] += dp[x].first;
    }
  }
  for (int node = 0 ; node < n ; node += 1) {
    vector<int> comps;
    for (auto x : adj[node]) {
      int sz = (x == dp[node].second ? n - 1 - sum[node] : dp[x].first);
      comps.emplace_back(sz);
    }
    int mx = *max_element(comps.begin() , comps.end());
    if (mx > n - mx - 1 && n > 2) {
      cout << -1 << '\n';
      continue;     
    }
    else {
      Get(node , -1 , 0);
      cout << ans - max_depth << '\n';      
      Init(); 
    }
  }
  return 0; 
}
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...