/ SeriousOJ /

Record Detail

Accepted


  
# Status Time Cost Memory Cost
#1 Accepted 8ms 6.43 MiB
#2 Accepted 8ms 6.664 MiB
#3 Accepted 10ms 6.48 MiB
#4 Accepted 11ms 6.707 MiB
#5 Accepted 36ms 7.371 MiB
#6 Accepted 58ms 7.648 MiB
#7 Accepted 45ms 7.469 MiB
#8 Accepted 307ms 6.691 MiB
#9 Accepted 98ms 6.844 MiB
#10 Accepted 74ms 7.566 MiB
#11 Accepted 54ms 7.582 MiB
#12 Accepted 62ms 7.621 MiB
#13 Accepted 28ms 7.676 MiB
#14 Accepted 79ms 7.672 MiB
#15 Accepted 52ms 6.887 MiB
#16 Accepted 26ms 7.613 MiB
#17 Accepted 24ms 7.582 MiB
#18 Accepted 24ms 7.379 MiB
#19 Accepted 69ms 13.352 MiB
#20 Accepted 71ms 13.531 MiB
#21 Accepted 69ms 13.414 MiB
#22 Accepted 93ms 25.008 MiB
#23 Accepted 156ms 13.0 MiB
#24 Accepted 158ms 13.0 MiB
#25 Accepted 82ms 12.562 MiB
#26 Accepted 12ms 7.07 MiB

Code

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll N = 2e5 + 10;
const ll MOD = 1e9 + 7;

int root, cnt, mxlen;

vector<int> v(N), dist(N), g[N];

void dfs(int vertex, int par){
  for (auto child : g[vertex]){
    if (child == par) continue;
    dfs(child, vertex);
    v[vertex] = max(v[vertex], v[child]);
  }
}
void dfs2(int vertex, int par, int cur) {
  mxlen = max(mxlen, cur);
  cnt++;
  dist[vertex] = cur;
  for(auto child : g[vertex]) {
    if (child == par) continue;
    if(v[child]) {
      dfs2(child, vertex, cur + 1);
    }
  }
}

void solve()
{
  for(int i = 0; i < N; i++) {
    g[i].clear();
    dist[i] = 0;
    v[i] = 0;
    root = mxlen = cnt = 0;
  }
  int n;
  cin >> n;
  int root = 0;
  for(int i = 1; i <= n; i++) {
    cin >> v[i];
    if(v[i] == 1) {
      root = i;
    }
  }
  for(int i = 1; i < n; i++) {
    int u, v;
    cin >> u >> v;
    g[u].push_back(v);
    g[v].push_back(u);
  }

  dfs(root, 0);
  dfs2(root, 0, 0);

  int ans = (cnt - 1) * 2, mx = 0;
  for(int i = 1; i <= n; i++) {
    if(dist[i] > mx) {
      root = i;
      mx = dist[i];
    }
  }
  dfs2(root, 0, 0);
  ans -= mxlen;

  cout << ans << endl;
}

int main()
{
  ios::sync_with_stdio(false),cin.tie(0),cout.tie(0);

  int t;
  cin >> t;
  while(t--){
    solve();
  }
}

Information

Submit By
Type
Submission
Problem
P1078 Apple on Tree
Language
C++17 (G++ 13.2.0)
Submit At
2024-08-17 20:09:03
Judged At
2024-11-11 03:07:59
Judged By
Score
100
Total Time
307ms
Peak Memory
25.008 MiB