/ SeriousOJ /

Record Detail

Wrong Answer


  
# Status Time Cost Memory Cost
#1 Accepted 7ms 7.309 MiB
#2 Accepted 7ms 7.297 MiB
#3 Wrong Answer 7ms 7.277 MiB
#4 Wrong Answer 10ms 7.309 MiB

Code

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

vector<int> a(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){
  a[u] = 0;
  dis1[u] = cur;
  for (auto v : g[u]){
    if (a[v]){
      dfs3(v, cur + 1);
      dis2[u] = max(dis2[u], dis2[v] + 1);
    }
  }
}

int main(){
  int t;
  cin >> t;
  while (t--){
    int n, u, v, mxLength = 0, cnt = 0;
    cin >> n;
    for (int i = 1; i <= n; i++){
      cin >> a[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;
    for (int i = 1; i <= n; i++){
      if (a[i]) cnt++; //cout<<a[i]<<" ";
    } //cout<<endl;
    dfs3(root, 0);
    for (int i = 1; i <= n; i++){
      mxLength = max(mxLength, dis1[i] + dis2[i]);
    }
    cout << (cnt - 1) * 2 - mxLength << endl;
    root = 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 07:37:51
Judged At
2024-11-11 03:09:20
Judged By
Score
4
Total Time
10ms
Peak Memory
7.309 MiB