/ SeriousOJ /

Record Detail

Accepted


  
# Status Time Cost Memory Cost
#1 Accepted 6ms 2.09 MiB
#2 Accepted 6ms 2.027 MiB
#3 Accepted 8ms 2.082 MiB
#4 Accepted 9ms 2.145 MiB
#5 Accepted 42ms 3.637 MiB
#6 Accepted 73ms 3.586 MiB
#7 Accepted 53ms 3.707 MiB
#8 Accepted 286ms 2.117 MiB
#9 Accepted 112ms 2.328 MiB
#10 Accepted 106ms 3.742 MiB
#11 Accepted 66ms 3.781 MiB
#12 Accepted 72ms 3.484 MiB
#13 Accepted 34ms 3.848 MiB
#14 Accepted 102ms 3.832 MiB
#15 Accepted 60ms 2.316 MiB
#16 Accepted 28ms 3.723 MiB
#17 Accepted 29ms 3.719 MiB
#18 Accepted 29ms 3.723 MiB
#19 Accepted 119ms 13.312 MiB
#20 Accepted 133ms 13.352 MiB
#21 Accepted 131ms 13.559 MiB
#22 Accepted 158ms 28.066 MiB
#23 Accepted 288ms 13.004 MiB
#24 Accepted 253ms 12.988 MiB
#25 Accepted 153ms 12.758 MiB
#26 Accepted 12ms 3.0 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, int cur){
  dist[vertex] = cur;
  for (auto child : g[vertex]){
    if (child == par) continue;
    dfs(child, vertex, cur + 1);
    v[vertex] = max(v[vertex], v[child]);
  }
}

void dfs2(int vertex, int par, int cur) {
  mxlen = max(mxlen, cur);
  cnt++;
  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, 0);

  int mx = 0;
  for(int i = 1; i <= n; i++) {
    if(v[i] and dist[i] > mx) {
      root = i;
      mx = dist[i];
    }
  }
  
  dfs2(root, 0, 0);
  int ans = (cnt - 1) * 2 - 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++20 (G++ 13.2.0)
Submit At
2024-08-17 20:21:08
Judged At
2024-11-11 03:07:59
Judged By
Score
100
Total Time
288ms
Peak Memory
28.066 MiB