题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1520
Anniversary party
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 8233 Accepted Submission(s): 3574
Problem Description
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.
Input
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 T 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
Output should contain the maximal sum of guests‘ ratings.
Sample Input
7
1
1
1
1
1
1
1
1 3
2 3
6 4
7 4
4 5
3 5
0 0
Sample Output
5
Source
Ural State University Internal Contest October‘2000 Students Session
看题解说是树型dp,就学习了一下。
状态转移:
上司去,下级不去:
dp[node][1]+=dp[u][0]; //node去,则u必不能去
上司不去,下级去或者不去:
dp[node][0]+=max(dp[u][0],dp[u][1]); //node不去,取u去或不去的最大值
和深搜很像,也就是用的深搜。
hdu上的数据更加刁钻,poj上能过的代码,在hdu上又是wa又是TLE。
开始模仿别人的代码用数组存上司和下级的关系,一直超时,最后改为用vector做.有的题解说可能不只一棵树,但是题目上说了是一棵树。
用了二维的vector,注意,每一组样例,都要清空vector,二维的需要每一维clear。用vector来搜索非常方便,节约时间和空间。
本题中vis数组没用。
注意理解树型dp思想。
#include <stdio.h> #include <string.h> #include <algorithm> #include<vector> #include<iostream> using namespace std; int father[6005],vis[6005],dp[6005][2],t; vector<int> v[6005]; void dfs(int node) { int i,j; vis[node] = 1; for(i = 0; i<v[node].size(); i++) { int u=v[node][i]; //if(!vis[u]) //{ dfs(u); dp[node][1]+=dp[u][0];//node去,则i必不能去 dp[node][0]+=max(dp[u][0],dp[u][1]);//node不去,取i去或不去的最大值 //} } } int main() { int i,j,l,k,root; while(~scanf("%d",&t)) { //memset(father,0,sizeof(father)); for(i = 1; i<=t; i++) { v[i].clear(); scanf("%d",&dp[i][1]); dp[i][0]=0; father[i]=0; } while(scanf("%d%d",&l,&k),l+k>0) { v[k].push_back(l); father[l]++; } //father[l] = k;//记录上司 int ans=0; for(int i=1; i<=t; i++) if(father[i]==0) { memset(vis,0,sizeof(vis)); dfs(i); ans+=max(dp[i][1],dp[i][0]); } printf("%d\n",ans); } return 0; }