1 以边为主,速度更快一些
#include <iostream>
#include <stdio.h>
#include <algorithm>
#include <string.h>
#include <vector>
using namespace std;
const int maxn=6010;
int head[maxn];
int visted[maxn];
int dp[maxn][2];
int cnt=0;
struct Edge{
int u;//出发点
int v;//到达点
int last;//上一条边的序号,-1为该点初始边
}edge[maxn];
void Add_edge(int u,int v){
edge[cnt].u=u;
edge[cnt].v=v;
edge[cnt].last=head[u];
head[u]=cnt++;
}
void Dfs(int x){//dfs的结束条件,一定拿在循环外面写,会更简洁
if(head[x]==-1){
return ;
}
for(int i=head[x];i!=-1;i=edge[i].last){
int v=edge[i].v;
//cout<<x<<"-"<<v<<endl;
Dfs(v);
dp[x][0]+=max(dp[v][0],dp[v][1]);
dp[x][1]+=dp[v][0];
}
//cout<<"dp["<<x<<"][0]:"<<dp[x][0]<<" dpx["<<x<<"][1]"<<dp[x][1]<<endl;
}
int main()
{
int n;
while(~scanf("%d",&n)){
memset(visted,0,sizeof(visted));//寻找根节点
memset(head,-1,sizeof(head));//存储各个点的初始边序号
memset(dp,0,sizeof(dp));
for(int i=1;i<=n;i++){
scanf("%d",&dp[i][1]);
dp[i][0]=0;
}
int v,u;
while(~scanf("%d%d",&v,&u)&&(u+v)){
Add_edge(u,v);
visted[v]++;
}
int root=-1;
for(int i=1;i<=n;i++){
if(visted[i]==0){
root=i;
break;
}
}
//cout<<"root: "<<root<<endl;
Dfs(root);
//cout<<dp[root][0]<<" "<<dp[root][1]<<endl;
cout<<max(dp[root][0],dp[root][1])<<endl;
}
}
2 以点为主的二维数组,速度相对慢一点点
#include <iostream>
#include <stdio.h>
#include <algorithm>
#include <string.h>
#include <vector>
using namespace std;
const int maxn=6010;
int visted[maxn];
int dp[maxn][2];
vector<int > father_sons[maxn];
void Dfs(int x){
/*
if(!father_sons[x].size()){
return;
}
*/
for(int i=0;i<father_sons[x].size();i++){
int v=father_sons[x][i];
Dfs(v);
dp[x][0]+=max(dp[v][0],dp[v][1]);
dp[x][1]+=dp[v][0];
}
}
int main()
{
int n;
while(~scanf("%d",&n)){
memset(visted,0,sizeof(visted));
memset(dp,0,sizeof(dp));
for(int i=1;i<=n;i++){
father_sons[i].clear();
}
for(int i=1;i<=n;i++){
scanf("%d",&dp[i][1]);
dp[i][0]=0;
}
int v,u;
while(~scanf("%d%d",&v,&u)&&(u+v)){
father_sons[u].push_back(v);
visted[v]++;
}
int root=-1;
for(int i=1;i<=n;i++){
if(visted[i]==0){
root=i;
break;
}
}
//cout<<"root: "<<root<<endl;
Dfs(root);
//cout<<dp[root][0]<<" "<<dp[root][1]<<endl;
cout<<max(dp[root][0],dp[root][1])<<endl;
}
}