Title Description
The Government has invited you to open restaurant in the train station, but not at the same time open two connecting train station. Any two of the train station and only one path, up to 50 and which is connected to each of the station railway station.
Tell your profits each station, ask the maximum profit you can get for how much.
Input Format
The first line of the input integer N (N≤100000), there are N represents station, respectively 1,2, ..., N numbered.
Next N lines, each an integer (not more than 10,000) represents the profits of each site.
The next line N-1 is described network station, each row of two integers, showing two connected sites.
Output Format
Output An integer representing the maximum profit that can be obtained.
Topic analysis:
Tree \ (dp \) Getting a lecture entitled yards
Set \ (dp [i] [0/1 ] \) represents \ (I \) nodes selected / not selected optimal solution
equation Obviously, lazy, see the code
Code:
#include<bits/stdc++.h>
#define N (300000 + 10)
using namespace std;
inline void read(int &cnt) {
cnt = 0;
int f = 1; char c = getchar();
while (!isdigit(c)) {if (c == '-') f = -f; c = getchar();}
while (isdigit(c)) {cnt = (cnt << 3) + (cnt << 1) + (c ^ 48); c = getchar();}
cnt *= f;
}
int n, first[N], to[N], nxt[N], tot, a, b;
int dp[N][2];
void add(int x, int y) {nxt[++tot] = first[x], first[x] = tot, to[tot] = y;}
void dfs_(int p, int fa) {
for (register int i = first[p]; i; i = nxt[i]) {
int v = to[i];
if (v == fa) continue;
dfs_(v, p);
dp[p][0] += max(dp[v][0], dp[v][1]);
dp[p][1] += dp[v][0];
}
}
int main() {
read(n);
for (register int i = 1; i <= n; ++i) read(dp[i][1]);
for (register int i = 1; i < n; ++i) read(a), read(b), add(a, b), add(b, a);
dfs_(1, 0);
printf("%d", max(dp[1][0], dp[1][1]));
return 0;
}