树是一种特殊的图,一般用链式前向星存储。
456不打acm遇不到,先不加以说明
做题步骤:
洛谷P1352
#include<iostream>
#include<vector>
using namespace std;
#define maxn 6005
int n, l, k;
int r[maxn];
bool v[maxn];//找父亲v[i]==0无父亲
int f[maxn][2];
vector<int>tree[maxn];
void dfs(int x) {//以x为根的子树的最大快乐值int y;f[x][1] = r[x];//只有x去f[x][0] = 0;//x不去for (int i = 0; i < tree[x].size(); i++) {y = tree[x][i];dfs(y);//求出f[y][0]和f[y][1]f[x][1] += f[y][0];f[x][0] += max(f[y][1], f[y][0]);}
}
int main() {scanf("%d", &n);for (int i = 1; i <= n; i++) {scanf("%d", &r[i]);}for (int i = 1; i < n; i++) {scanf("%d %d", &l, &k);v[l] = 1;tree[k].push_back(l);}int root;for (int i = 1; i <= n; i++) {if (v[i] == 0) {root = i;break;}}dfs(root);printf("%d", max(f[root][1], f[root][0]));return 0;
}