/ SeriousOJ /

Record Detail

Accepted


  
# Status Time Cost Memory Cost
#1 Accepted 7ms 8.062 MiB
#2 Accepted 8ms 8.062 MiB
#3 Accepted 8ms 7.961 MiB
#4 Accepted 14ms 8.188 MiB
#5 Accepted 96ms 9.066 MiB
#6 Accepted 177ms 9.176 MiB
#7 Accepted 146ms 9.113 MiB
#8 Accepted 75ms 8.062 MiB
#9 Accepted 180ms 8.359 MiB
#10 Accepted 276ms 9.16 MiB
#11 Accepted 192ms 9.301 MiB
#12 Accepted 173ms 9.148 MiB
#13 Accepted 96ms 9.215 MiB
#14 Accepted 319ms 9.25 MiB
#15 Accepted 135ms 8.461 MiB
#16 Accepted 81ms 9.113 MiB
#17 Accepted 80ms 9.133 MiB
#18 Accepted 79ms 9.125 MiB
#19 Accepted 293ms 15.062 MiB
#20 Accepted 317ms 15.066 MiB
#21 Accepted 332ms 14.961 MiB
#22 Accepted 371ms 32.648 MiB
#23 Accepted 453ms 14.508 MiB
#24 Accepted 542ms 14.516 MiB
#25 Accepted 387ms 14.293 MiB
#26 Accepted 26ms 8.941 MiB

Code

#include<bits/stdc++.h>
#define ll long long
using namespace std;
 
const int N = 2e5 + 7;
int root, cnt, mxLength;

vector<int> a(N), ok(N), dis1(N), dis2(N), g[N];

void dfs(int u, int p){
  for (auto v : g[u]){
    if (v == p) continue;
    dfs(v, u);
    if (!root && a[v]) root = v;
  }
}

void dfs2(int u, int p){
  for (auto v : g[u]){
    if (v == p) continue;
    dfs2(v, u);
    a[u] = max(a[u], a[v]);
  }
}

void dfs3(int u, int cur){
  cnt++;
  a[u] = 0;
  dis1[u] = cur;
  for (auto v : g[u]){
    if (a[v]){
      dfs3(v, cur + 1);
      ok[u]++;
      if (u > 0 && ok[u] > 1) mxLength = max(mxLength, dis2[u] + dis2[v] + 1);
      mxLength = max(mxLength, dis1[v] + dis2[v]);
      dis2[u] = max(dis2[u], dis2[v] + 1);
    }
  }
}

int main(){
  int t;
  cin >> t;
  while (t--){
    int n, u, v;
    cin >> n;
    for (int i = 1; i <= n; i++){
      cin >> a[i];
      ok[i] = dis1[i] = dis2[i] = 0;
      g[i].clear();
    }
    for (int i = 1; i < n; i++){
      cin >> u >> v;
      g[u].push_back(v);
      g[v].push_back(u);
    }
    dfs(1, 0);
    dfs2(root, 0); //cout<<root<<endl;
    dfs3(root, 0);
    cout << (cnt - 1) * 2 - mxLength << endl;
    root = mxLength = cnt = ok[0] = 0;
    // for (int i = 1; i <= n; i++) cout<<dis1[i]<<" ";cout<<endl;
    // for(int i=1;i<=n; i++)cout<<dis2[i]<<" ";cout<<endl;
  }
}

Information

Submit By
Type
Submission
Problem
P1078 Apple on Tree
Language
C++17 (G++ 13.2.0)
Submit At
2024-08-17 08:37:29
Judged At
2024-11-11 03:09:03
Judged By
Score
100
Total Time
542ms
Peak Memory
32.648 MiB