/ SeriousOJ /

Record Detail

Accepted


  
# Status Time Cost Memory Cost
#1 Accepted 1ms 532.0 KiB
#2 Accepted 1ms 532.0 KiB
#3 Accepted 1ms 532.0 KiB
#4 Accepted 5ms 532.0 KiB
#5 Accepted 99ms 4.125 MiB
#6 Accepted 224ms 4.422 MiB
#7 Accepted 166ms 4.27 MiB
#8 Accepted 45ms 536.0 KiB
#9 Accepted 140ms 976.0 KiB
#10 Accepted 304ms 4.223 MiB
#11 Accepted 228ms 4.699 MiB
#12 Accepted 250ms 4.277 MiB
#13 Accepted 98ms 4.82 MiB
#14 Accepted 365ms 4.598 MiB
#15 Accepted 90ms 1.066 MiB
#16 Accepted 77ms 4.488 MiB
#17 Accepted 71ms 4.391 MiB
#18 Accepted 76ms 4.488 MiB
#19 Accepted 215ms 27.305 MiB
#20 Accepted 218ms 27.301 MiB
#21 Accepted 222ms 27.156 MiB
#22 Accepted 266ms 48.891 MiB
#23 Accepted 570ms 26.754 MiB
#24 Accepted 610ms 26.754 MiB
#25 Accepted 257ms 26.539 MiB
#26 Accepted 11ms 2.285 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-11-11 03:15:51
Judged By
Score
100
Total Time
610ms
Peak Memory
48.891 MiB