题目链接:http://poj.org/problem?id=2342
题意:一家公司有1 <= N <= 6 000个职工,现要组织一些职工参加晚会,要求每个职工和其顶头上司不能同时参加晚会,并且每个职工有一个enjoy值,问选取的职工的最大enjoy总和为多少?
输入N个职工各种的enjoy值,和L K表示K是L的顶头上司;
思路:建图之后DFS,dp[u][1] :u去时,以u为根的子树最大enjoy值,dp[u][0]:u不去时,以u为子树的enjoy值;
则dp[u][1] += dp[v][0]; u去则孩子节点一定不能去,
dp[u][0] += max(dp[v][0],dp[v][1]); u不去,v可去可不去。因为可能v的孩子节点的值很大,导致v不能去。
#include<iostream> #include<cstdio> #include<cstring> #include<string.h> #include<algorithm> #include<vector> #include<cmath> #include<stdlib.h> #include<time.h> #include<stack> #include<set> #include<map> #include<queue> using namespace std; #define rep0(i,l,r) for(int i = (l);i < (r);i++) #define rep1(i,l,r) for(int i = (l);i <= (r);i++) #define rep_0(i,r,l) for(int i = (r);i > (l);i--) #define rep_1(i,r,l) for(int i = (r);i >= (l);i--) #define MS0(a) memset(a,0,sizeof(a)) #define MS1(a) memset(a,-1,sizeof(a)) #define MSi(a) memset(a,0x3f,sizeof(a)) #define inf 0x3f3f3f3f #define lson l, m, rt << 1 #define rson m+1, r, rt << 1|1 typedef pair<int,int> PII; #define A first #define B second #define MK make_pair typedef __int64 ll; template<typename T> void read1(T &m) { T x=0,f=1;char ch=getchar(); while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();} while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();} m = x*f; } template<typename T> void read2(T &a,T &b){read1(a);read1(b);} template<typename T> void read3(T &a,T &b,T &c){read1(a);read1(b);read1(c);} template<typename T> void out(T a) { if(a>9) out(a/10); putchar(a%10+'0'); } #define N 6066 int dp[N][2],vis[N]; int head[N],tot; struct Edge{ int to,w,Next; Edge(){} Edge(int to,int w,int Next):to(to),w(w),Next(Next){} }e[N<<1]; inline void ins(int u,int v,int w) { e[++tot] = Edge{v,w,head[u]}; head[u] = tot; } void dfs(int u) { vis[u] = 1; for(int d = head[u];d;d = e[d].Next){ int v = e[d].to; if(vis[v]) continue; dfs(v); dp[u][0] += max(dp[v][1],dp[v][0]); dp[u][1] += dp[v][0]; } } int main() { int n; read1(n); rep1(i,1,n) read1(dp[i][1]); int a,b; while(read2(a,b),a+b){ ins(a,b,0);ins(b,a,0); } dfs(1); printf("%d\n",max(dp[1][0],dp[1][1])); return 0; }