我也不想当 Btd ……
来了的人数
题目 具体思路不过多阐述,详见代码。
#include<bits/stdc++.h>
using namespace std;
vector<int> G[6010];
int n,r[6010],fa[6010],f[6010][2];
void dfs(int u){
for(int v:G[u]){
dfs(v);
f[u][1]=f[v][0]+f[u][1];
f[u][0]=max(f[v][0],f[v][1]);
}
}
signed main(){
cin>>n;
for(int i=1;i<=n;i++){
cin>>r[i];
f[i][1]=r[i];
}
for(int i=2;i<=n;i++){
int l,k;
cin>>l>>k;
fa[l]=k;
G[k].push_back(l);
}
int root=1;
while(fa[root]!=0){
root++;
}
dfs(root);
cout<<max(f[root][0],f[root][1]);
return 0;
}
#include <bits/stdc++.h>
using namespace std;
int n,root,fa[6010],r[6010],f[6010][2];
int head[6010],cnt=0;
struct edge{
int to,nxt;
}e[6010];
void add_edge(int u,int v){
cnt++;
e[cnt].to=v;
e[cnt].nxt=head[u];
head[u]=cnt;
}
void dfs(int u,int fa){
for(int i=head[u];i;i=e[i].nxt){
int v=e[i].to;
if(v==fa) continue;
dfs(v,u);
f[u][1]+=f[v][0];
f[u][0]+=max(f[v][0],f[v][1]);
}
}
int main(){
cin>>n;
for(int i=1;i<=n;i++){
cin>>r[i];
f[i][1]=r[i];
}
for(int i=2;i<=n;i++){
int k,l;
cin>>l>>k;
add_edge(k,l);
fa[l]=k;
}
root=1;
while(fa[root]!=0){
root++;
}
dfs(root,0);
cout<<max(f[root][0],f[root][1]);
return 0;
}
区别仅在于一份使用了 Vector 储存节点的子节点,而另一份使用了链式前向星的方式。
求条,玄关