竟然没有使用树形dp就过了,难道是数据弱了?
查看原帖
竟然没有使用树形dp就过了,难道是数据弱了?
1104073
zhangyc666楼主2024/7/22 21:19

#include <bits/stdc++.h>
using namespace std;
#define int long long
#define INF 0x3f3f3f3f

const int N = 6e3+9;
int w[N] , fa[N];
int n , s;
vector<int>g[N];
int ans1 , ans2;

void dfs(int u , int t){
    if(t == 1)if(w[u] >0)ans1 += w[u];
    for(auto to :g[u]){
        if(to == fa[u])continue;
        if(t == 0)dfs(to , 1);
        else if(t == 1)dfs(to , 0);
    }
}


void solve(){
   cin>>n;
   for(int i =1;i<=n;++i)cin>>w[i];

   for(int i  =1 ;i<n;++i){
    int u ,v;
    cin>>u>>v;
    fa[u]=  v;
    g[u].push_back(v);
    g[v].push_back(u);
   }
   for(int i =1;i<=n;++i)if(fa[i] == 0)s = i;

   dfs(s , 1);
   
   ans2 = ans1;
   ans1 = 0;
   dfs(s , 0);
    int ans = max(ans1 , ans2);
    cout<<ans<<endl;




}



signed main(){
    ios::sync_with_stdio(false);
    cout.tie(0);
    cin.tie(0);
    int _ = 1;
    //cin>>_;
    while(_--)solve();

    return 0;
}
2024/7/22 21:19
加载中...