/ SeriousOJ /

Record Detail

Accepted


  
# Status Time Cost Memory Cost
#1 Accepted 1ms 532.0 KiB
#2 Accepted 1ms 320.0 KiB
#3 Accepted 2ms 532.0 KiB
#4 Accepted 5ms 616.0 KiB
#5 Accepted 115ms 4.105 MiB
#6 Accepted 236ms 4.332 MiB
#7 Accepted 180ms 4.391 MiB
#8 Accepted 44ms 580.0 KiB
#9 Accepted 138ms 972.0 KiB
#10 Accepted 312ms 4.328 MiB
#11 Accepted 221ms 4.68 MiB
#12 Accepted 253ms 4.273 MiB
#13 Accepted 97ms 4.688 MiB
#14 Accepted 310ms 4.605 MiB
#15 Accepted 88ms 1.062 MiB
#16 Accepted 65ms 4.465 MiB
#17 Accepted 72ms 4.484 MiB
#18 Accepted 67ms 4.438 MiB
#19 Accepted 207ms 27.301 MiB
#20 Accepted 220ms 27.301 MiB
#21 Accepted 220ms 27.293 MiB
#22 Accepted 269ms 49.035 MiB
#23 Accepted 617ms 26.75 MiB
#24 Accepted 626ms 26.547 MiB
#25 Accepted 259ms 26.527 MiB
#26 Accepted 11ms 2.395 MiB

Code

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

typedef long long ll;
const ll md = 1e9+7;
map<int,vector<int>>tree;
void fnd(int i,int vis[],int lv1[],int par[],int dp[],int ara[]){
vis[i]++;
if(ara[i])dp[i]=1;
for(auto it:tree[i]){
    if(!vis[it]){
            par[it]=i;
        lv1[it]=lv1[i]+1;
        fnd(it,vis,lv1,par,dp,ara);
        if(dp[it])dp[i]=1;
    }
}

}
void dfs(int i,int vis[],int tmp,int &ans,int dp[]){

vis[i]++;
for(auto it:tree[i]){
    if(!vis[it]&&it!=tmp&&dp[it]){
        ans+=2;
        dfs(it,vis,tmp,ans,dp);
    }
}
}
void solve() {
    tree.clear();
  int n;
  cin>>n;
  int ara[n+1];
  for(int i=1;i<=n;i++)cin>>ara[i];
  int dp[n+1]={0};
  int lv1[n+1]={0};
  for(int i=1;i<n;i++){
    int x,y;
    cin>>x>>y;
    tree[x].push_back(y);
    tree[y].push_back(x);
  }
  int vis[n+1]={0};
  int par[n+1]={0};
  fnd(1,vis,lv1,par,dp,ara);
  int mx=0;
  int j=1;
  for(int i=1;i<=n;i++){
        vis[i]=0;
        dp[i]=0;
    if(lv1[i]>=mx&&ara[i]){
        j=i;
        mx=lv1[i];
    }
  }
  int lv2[n+1]={0};
  par[j]=0;
  fnd(j,vis,lv2,par,dp,ara);
  mx=0;
  for(int i=1;i<=n;i++){
        vis[i]=0;
      if(lv2[i]>=mx&&ara[i]){
        j=i;
        mx=lv2[i];
    }
  }
  int x=j;
  vector<int>v;
  while(x!=0){
    v.push_back(x);
    x=par[x];
  }
  int ans=0;
  for(int i=v.size()-1;i>0;i--){
    dfs(v[i],vis,v[i-1],ans,dp);
  }
  if(v.size())
  ans+=v.size()-1;
  cout<<ans<<endl;
}

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

    int T;
     cin >> T;
    while (T--) {
        solve();
    }

    return 0;
}

Information

Submit By
Type
Submission
Problem
P1078 Apple on Tree
Contest
Bangladesh 2.0
Language
C++20 (G++ 13.2.0)
Submit At
2024-08-16 16:09:42
Judged At
2024-10-03 13:28:25
Judged By
Score
100
Total Time
626ms
Peak Memory
49.035 MiB