使用DFS对一半
查看原帖
使用DFS对一半
753280
10chen01楼主2022/12/10 10:34

用DFS+邻接表做,无MLE和TLE对一半:

#include<bits/stdc++.h>

using namespace std;

vector<short> g[6005];
short f[6005];
short r[6005];
short n;

const short inf = 0x6fff;

short dfs(short idx){
    if(g[idx].empty()) return r[idx];
    int _this = r[idx];
    int _child_sum = 0;
    for(auto i : g[idx]){
        _child_sum += dfs(i);
    }
    return _this>_child_sum?_this:_child_sum;
}

int find_root(int start){
    if(f[start] == inf){
        return start;
    }else{
        return find_root(f[start]);
    }
}

int main(){
    cin>>n;
    for(int i=1;i<=n;i++){
        cin>>r[i];
        f[i] = inf;
    }
    for(int i=1;i<=n-1;i++){
        int l, k;
        cin>>l>>k;
        g[k].push_back(l);
        f[l] = k;
    }
    cout<<dfs(find_root(1))<<endl;
    return 0;
}
2022/12/10 10:34
加载中...