Codeforces Round #358 (Div. 2) C. Alyona and the Tree DFS

C. Alyona and the Tree

链接:

http://www.codeforces.com/contest/682/problem/C

题意

给你一棵树,有点权有边权。

如果存在两个点,u,v。满足u存在v的子树中,(u,v)的之间的边权和大于a[u]的话,那么u点是不开心的。

你只能从叶子节点开始删除点,问你最少删除多少个点,可以使得这个树里面没有不开心的点。

题解:

题目中的树是有顺序的,所以直接从1号节点dfs就好了

如果要删除u点的话,那么显然u子树也得全部删去,所以直接dfs一波就完了。

代码:

 1 #include<iostream>
 2 #include<vector>
 3 #include<algorithm>
 4 using namespace std;
 5 
 6 const int maxn = 1e5 + 7;
 7 int a[maxn];
 8 vector<pair<int, int>> E[maxn];
 9 
10 int dfs(int x,int fa,long long dis)
11 {
12     if(dis > a[x])return 0;
13     int ans = 1;
14     for (int i = 0; i < E[x].size(); i++) {
15         if (E[x][i].first == fa)
16             continue;
17         ans += dfs(E[x][i].first, x, max(dis + E[x][i].second, 0LL));
18     }
19     return ans;
20 }
21 
22 int main()
23 {
24     int n;
25     cin >> n;
26     for (int i = 1; i <= n; i++)
27         cin >> a[i];
28     int p, c;
29     for (int i = 2; i <= n; i++) {
30         cin >> p >> c;
31         E[i].push_back(make_pair(p, c));
32         E[p].push_back(make_pair(i, c));
33     }
34     int ans = dfs(1, 0, 0);
35     cout << n - ans << endl;
36     return 0;
37 }
原文地址:https://www.cnblogs.com/baocong/p/5913359.html