最大利润
没有上司的舞会的翻版
没有上司的舞会是有向图,而这一题是无向图(没有上司)
样例输入
6
10
20
25
40
30
30
4 5
1 3
3 4
2 3
6 4
样例输出
90
思路
DP
没有上司的舞会
#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
struct whw
{
int w,h;
}wh[200015];
int a[100005],h[100005],f[2][100005];
int n,m,x,y,t,ans,maxx;
bool b[100005];
void dp(int k)
{
b[k]=1;//防止无限循环
f[1][k]=a[k];
for(int i=h[k];i;i=wh[i].h)
if(!b[wh[i].w])//这里判断一下是否走过
{
dp(wh[i].w);
f[1][k]=f[1][k]+f[0][wh[i].w];
f[0][k]=max(f[1][wh[i].w],f[0][wh[i].w])+f[0][k];
}
}
int main()
{
freopen("profit.in","r",stdin);
freopen("profit.out","w",stdout);
scanf("%d",&n);
for(int i=1;i<=n;++i)
scanf("%d",&a[i]);
for(int i=1;i<=n-1;++i)
{
scanf("%d%d",&x,&y);
wh[++t]=(whw){x,h[y]};h[y]=t;//因为是无向图
wh[++t]=(whw){y,h[x]};h[x]=t;//所以两边都要赋值
}
memset(f,0,sizeof(f));
dp(1);
printf("%d",max(f[1][1],f[0][1]));
fclose(stdin);
fclose(stdout);
return 0;
}