当前位置: 代码迷 >> 综合 >> POJ 2342 最大利润
  详细解决方案

POJ 2342 最大利润

热度:37   发布时间:2024-02-10 15:16:16.0

POJ 2342 最大利润

POJ 2342

题目

There is going to be a party to celebrate the 80-th Anniversary of the Ural State University. The University has a hierarchical structure of employees. It means that the supervisor relation forms a tree rooted at the rector V. E. Tretyakov. In order to make the party funny for every one, the rector does not want both an employee and his or her immediate supervisor to be present. The personnel office has evaluated conviviality of each employee, so everyone has some number (rating) attached to him or her. Your task is to make a list of guests with the maximal possible sum of guests’ conviviality ratings.


输入

Employees are numbered from 1 to N. A first line of input contains a number N. 1 <= N <= 6 000. Each of the subsequent N lines contains the conviviality rating of the corresponding employee. Conviviality rating is an integer number in a range from -128 to 127. After that go N – 1 lines that describe a supervisor relation tree. Each line of the tree specification has the form:
L K
It means that the K-th employee is an immediate supervisor of the L-th employee. Input is ended with the line
0 0


输出

Output should contain the maximal sum of guests’ ratings.


样例

input
7
1
1
1
1
1
1
1
1 3
2 3
6 4
7 4
4 5
3 5
0 0

output
5


题意

政府邀请了你在火车站开饭店,但不允许同时在两个相连接的火车站开。任意两个火车站有且只有一条路径,每个火车站最多有50个和它相连接的火车站。
告诉你每个火车站的利润,问你可以获得的最大利润为多少。


解题思路

由题意得
有n-1对相连的点
相连的点二选一
求最大的权值和
所以
它类似于没有上司的晚会

父节点去则父节点去的当前最大值+子节点不去的最大值
父节点不去则父节点不去的当前最大值+子节点去或不去的最大值中的较大值


代码

#include<iostream>
#include<cstdio>
#include<cmath> 
using namespace std;
struct hhx{int to,next;
}m[13000];
int a[6010],t,n,x,y,p[6010],f[6010][6010],head[6010],ans;
void dp(int d)
{p[d]=1;f[d][1]=a[d];for (int i=head[d];i;i=m[i].next){ if (p[m[i].to]==1) continue;dp(m[i].to);f[d][0]+=max(f[m[i].to][0],f[m[i].to][1]);  //不去,选子节点去或不去的最大值相加f[d][1]+=f[m[i].to][0];  //去,加子节点不去的最大值}
}
void add(int x,int y)  //建树
{m[++t].to=y;m[t].next=head[x];head[x]=t; 
}
int main()
{scanf("%d",&n);for (int i=1;i<=n;i++)scanf("%d",&a[i]);for (int i=1;i<=n;i++){scanf("%d%d",&x,&y);add(x,y);add(y,x);} dp(1);cout<<max(f[1][1],f[1][0])<<endl;return 0;
}