zoukankan      html  css  js  c++  java
  • 洛谷 [P1352] 没有上司的舞会

    树型DP

    一个人不能和他的直接上司一起去,那么就分别保存这个人去和不去的最大值
    注意转移方程

    #include <iostream>
    #include <cstring>
    #include <cstdio>
    #include <algorithm>
    using namespace std;
    const int MAXN = 7005;
    int n, num[MAXN], dp[MAXN][2], fa[MAXN], head[MAXN], nume, rot;
    struct edge{
    	int to, nxt;
    }e[MAXN<<1];
    void adde(int from, int to) {
    	e[++nume].to = to;
    	e[nume].nxt = head[from];
    	head[from] = nume;
    }
    void dfs(int rt) {
    	dp[rt][1] = num[rt];
    	for(int i = head[rt]; i; i = e[i].nxt) {
    		int v = e[i].to;
    		if(v == fa[rt]) continue;
    		dfs(v);
    		if(dp[v][1] > dp[v][0]) dp[rt][0] = max(dp[rt][0], dp[rt][0] + dp[v][1]);
    		else dp[rt][0] = max(dp[rt][0], dp[rt][0] + dp[v][0]);
    		dp[rt][1] = max(dp[rt][1], dp[rt][1] + dp[v][0]);
    	}
    }
    int main() {
    	cin >> n;
    	for(int i = 1; i <= n; i++) cin >> num[i];
    	for(int i = 1; i< n; i++) {
    		int u, v;
    		cin >> u >> v;
    		fa[u] = v;
    		adde(u, v); adde(v, u);
    	}
    	for(int i = 1; i <= n; i++) if(!fa[i]) rot = i;
    	dfs(rot);
    	cout << max(dp[rot][0], dp[rot][1]) << endl;
    	return 0;
    }
    
  • 相关阅读:
    铁轨
    POJ 2385 -- Apple Catching
    POJ 3258 -- River Hopscotch
    POJ 1469 -- COURSES (二分匹配)
    POJ 2349 -- Arctic Network
    最小生成树
    NOIP200703守望者的逃离
    NOIP200706字符串的展开
    POJ 1036 -- Gangsters
    POJ 1952 -- BUY LOW, BUY LOWER
  • 原文地址:https://www.cnblogs.com/Mr-WolframsMgcBox/p/8607449.html
Copyright © 2011-2022 走看看