/ SeriousOJ /

Record Detail

Accepted


  
# Status Time Cost Memory Cost
#1 Accepted 5ms 5.02 MiB
#2 Accepted 14ms 5.066 MiB
#3 Accepted 14ms 5.066 MiB
#4 Accepted 18ms 5.02 MiB
#5 Accepted 43ms 6.02 MiB
#6 Accepted 41ms 6.27 MiB
#7 Accepted 31ms 6.328 MiB
#8 Accepted 24ms 5.02 MiB
#9 Accepted 41ms 5.266 MiB
#10 Accepted 56ms 6.273 MiB
#11 Accepted 38ms 6.27 MiB
#12 Accepted 44ms 6.27 MiB
#13 Accepted 21ms 6.316 MiB
#14 Accepted 54ms 6.27 MiB
#15 Accepted 27ms 5.32 MiB
#16 Accepted 18ms 6.316 MiB
#17 Accepted 17ms 6.316 MiB
#18 Accepted 18ms 6.062 MiB
#19 Accepted 61ms 13.383 MiB
#20 Accepted 62ms 13.5 MiB
#21 Accepted 66ms 13.438 MiB
#22 Accepted 78ms 21.723 MiB
#23 Accepted 140ms 12.848 MiB
#24 Accepted 116ms 12.988 MiB
#25 Accepted 76ms 12.562 MiB
#26 Accepted 8ms 5.715 MiB

Code

#include <bits/stdc++.h>
using namespace std;

#define all(v) v.begin(), v.end()

using LL = long long;

const int N = 2e5 + 69;

vector <int> adj[N];
int n, active_node, isApple[N], dist[N];

int dfs (int cur, int par) {
  int ret = isApple[cur];    
  if (par != -1) dist[cur] = dist[par] + 1;
  for (auto next : adj[cur]) {
    if (next != par) ret += dfs (next, cur);
  }
  if (ret == 0) active_node--;
  return ret;
}

int main() {
  cin.tie (nullptr) -> ios_base :: sync_with_stdio (false);

  int tests;
  cin >> tests;
  while (tests--) {
    cin >> n;
    for (int i = 1; i <= n; i++) cin >> isApple[i], adj[i].clear (), dist[i] = 0;
    for (int i = 1; i < n; i++) {
      int a, b;
      cin >> a >> b;
      adj[a].push_back (b);
      adj[b].push_back (a);
    }
    if (accumulate (isApple + 1, isApple + n + 1, 0) < 2) {
      cout << 0 << '\n';
      continue;
    }
    active_node = n;
    int src = find (isApple + 1, isApple + n + 1, 1) - isApple;
    dfs (src, -1);
    int mx = 0;
    for (int i = 1; i <= n; i++) {
      if (isApple[i] and dist[i] > mx) {
        mx = dist[i];
        src = i;
      }
    }
    fill (dist + 1, dist + n + 1, 0);
    int ans = 2 * (active_node - 1);
    dfs (src, -1);
    mx = 0;
    for (int i = 1; i <= n; i++) {
      if (isApple[i]) mx = max (mx, dist[i]);
    }
    cout << ans - mx << '\n';
  }

  return 0;
}

Information

Submit By
Type
Submission
Problem
P1078 Apple on Tree
Language
C++20 (G++ 13.2.0)
Submit At
2024-08-16 19:25:09
Judged At
2024-08-16 19:25:09
Judged By
Score
100
Total Time
140ms
Peak Memory
21.723 MiB