/ SeriousOJ /

Record Detail

Accepted


  
# Status Time Cost Memory Cost
#1 Accepted 6ms 8.027 MiB
#2 Accepted 6ms 8.195 MiB
#3 Accepted 7ms 8.277 MiB
#4 Accepted 8ms 8.277 MiB
#5 Accepted 50ms 8.875 MiB
#6 Accepted 88ms 9.117 MiB
#7 Accepted 68ms 9.02 MiB
#8 Accepted 41ms 8.074 MiB
#9 Accepted 91ms 8.527 MiB
#10 Accepted 109ms 8.996 MiB
#11 Accepted 82ms 9.27 MiB
#12 Accepted 88ms 9.242 MiB
#13 Accepted 38ms 9.164 MiB
#14 Accepted 120ms 9.113 MiB
#15 Accepted 61ms 8.32 MiB
#16 Accepted 33ms 8.926 MiB
#17 Accepted 33ms 9.086 MiB
#18 Accepted 33ms 9.086 MiB
#19 Accepted 138ms 14.883 MiB
#20 Accepted 138ms 14.863 MiB
#21 Accepted 138ms 14.914 MiB
#22 Accepted 194ms 32.449 MiB
#23 Accepted 234ms 14.504 MiB
#24 Accepted 212ms 14.359 MiB
#25 Accepted 177ms 14.055 MiB
#26 Accepted 17ms 8.879 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-08-17 08:37:29
Judged By
Score
100
Total Time
234ms
Peak Memory
32.449 MiB