Author : Dipu Kumar Mohanto
CSE, Batch - 6
BRUR.
Problem Statement : D. Book of Evil
Source : Codeforces
Category : Graph Theory, Dynamic Programing
Algorithm : DP on Tree, In Out DP
Verdict : Accepted
- #include "bits/stdc++.h"
-
- using namespace std;
-
- signed main()
- {
- ios_base::sync_with_stdio(false);
- cin.tie(nullptr);
-
- #ifndef ONLINE_JUDGE
- freopen("in.txt", "r", stdin);
- #endif // ONLINE_JUDGE
-
- int n, m, d;
- cin >> n >> m >> d;
- vector <int> evil(n + 1);
- int root = -1;
- for (int i = 1; i <= m; i++)
- {
- int x;
- cin >> x;
- evil[x] = 1;
- if (root == -1) root = x;
- }
- vector < vector <int> > graph(n + 1);
- for (int e = 1; e < n; e++)
- {
- int u, v;
- cin >> u >> v;
- graph[u].push_back(v);
- graph[v].push_back(u);
- }
- vector <int> in(n + 1, 0);
- vector <int> useful(n + 1);
- function <void(int, int)> dfs = [&](int u, int p)
- {
- useful[u] = evil[u];
- in[u] = evil[u] ? 1 : 0;
- for (int v : graph[u])
- {
- if (v == p) continue;
- dfs(v, u);
- if (useful[v] == 1)
- {
- in[u] = max(in[u], 1 + in[v]);
- useful[u] = 1;
- }
- }
- };
- vector <int> out(n + 1);
- out[root] = 1;
- function <void(int, int)> solve = [&](int u, int p)
- {
- int max1 = 0;
- int max2 = 0;
- for (int v : graph[u])
- {
- if (v == p) continue;
- if (in[v] >= max1) max2 = max1, max1 = in[v];
- else if (in[v] > max2) max2 = in[v];
- }
- for (int v : graph[u])
- {
- if (v == p) continue;
- int use = max1;
- if (in[v] == use) use = max2;
- if (out[u]) out[v] = 1 + out[u];
- if (use) out[v] = max(out[v], 2 + use);
- solve(v, u);
- }
- };
- dfs(root, 0);
- solve(root, 0);
- int ans = 0;
- for (int i = 1; i <= n; i++)
- {
- int maxi = max(in[i], out[i]);
- if (maxi > 0 and maxi - 1 <= d) ++ans;
- }
- cout << ans;
- }
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.