Test instructions: The topic gives a tree, each node has its weight. If you select a node, you cannot select its parent node and ask the maximum value that can be obtained.
Analysis: A simple tree-shaped dp,dp[i][0] denotes node i is not selected, Dp[i][1] represents the node I select, the last selection of the maximum is good.
The code is as follows:
#pragma COMMENT (linker, "/stack:1024000000,1024000000") #include <cstdio> #include <string> #include < cstdlib> #include <cmath> #include <iostream> #include <cstring> #include <set> #include < queue> #include <algorithm> #include <vector> #include <map> #include <cctype> #include < cmath> #include <stack>//#include <tr1/unordered_map> #define FREOPENR freopen ("In.txt", "R", stdin) # Define FREOPENW freopen ("OUT.txt", "w", stdout) using namespace std;//using namespace std:: tr1;typedef Long Long ll;typed EF pair<int, int> p;const int inf = 0x3f3f3f3f;const double INF = 0x3f3f3f3f3f3f;const LL LNF = 0x3f3f3f3f3f3f;const Double PI = ACOs ( -1.0); const double EPS = 1e-8;const int maxn = 6e3 + 5;const LL mod = 1e9 + 7;const int N = 1e6 + 5;cons t int dr[] = {-1, 0, 1, 0, 1, 1,-1, -1};const int dc[] = {0, 1, 0,-1, 1,-1, 1, -1};const char *hex[] = {"0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111", "1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111"};inline ll gcd (ll A, ll b) {return b = = 0? a:gcd (b, a%b);} inline int gcd (int a, int b) {return b = = 0? a:gcd (b, a%b);} int n, m;const int mon[] = {0, 31, 29, 31, 30, 31, 0, +, +,, +, +, +,, N, H, H, C, h, 31};inline int Min (int a, int b) {return a < b? A:b;} inline int Max (int a, int b) {return a > b a:b;} inline ll Min (ll A, ll b) {return a < b a:b;} inline ll Max (ll A, ll b) {return a > b a:b;} inline bool Is_in (int r, int c) {return R >= 0 && r < n && C >= 0 && C < m;} vector<int> g[maxn];bool in[maxn];int dp[maxn][2];void dfs (int u) {for (int i = 0; i < g[u].size (); ++i) { int v = g[u][i]; DFS (v); Dp[u][0] + = Max (dp[v][1], dp[v][0]); DP[U][1] + = dp[v][0]; } return; int main () {while (scanf ("%d", &n) = = 1) {memset (DP, 0, sizeof DP); for (int i = 1; I <= n; ++i) {scanf ("%d", &dp[i][1]); G[i].clear (); } int u, v; Memset (in, false, sizeof in); while (scanf ("%d%d", &u, &v) = = 2 && u+v) {g[v].push_back (U); In[u] = true; } int ans; for (int i = 1; I <= n; ++i) if (!in[i]) {DFS (i); Ans = Max (dp[i][0], dp[i][1]); Break } printf ("%d\n", ans); } return 0;}
HDU 1520 Anniversary Party (tree-shaped DP)