Author : Dipu Kumar Mohanto
CSE, Batch - 6
BRUR.
Problem Statement : 13274 - Christmas Tree
Source : UVA Online Judge
Category : Graph Theory, Dynamic Programing
Algorithm : DP on Tree
Verdict : Accepted
- #include <bits/stdc++.h>
-
- using namespace std;
-
- static const int maxn = 1e3 + 5;
- static const int logn = 15;
-
- struct node
- {
- int name, totalNode;
- node() {}
- node(int _name, int _totalNode)
- {
- name = _name;
- totalNode = _totalNode;
- }
- inline friend bool operator<(node A, node B)
- {
- return A.totalNode > B.totalNode;
- }
- };
-
- vector <int> graph[maxn];
- int total_node[maxn], ok[maxn], discover[maxn], dfsTime,
- tnode, k, tnode_beautiful_tree;
-
- inline void initialize()
- {
- dfsTime = 0;
- for (int i = 0; i < maxn; i++)
- {
- graph[i].clear();
- total_node[i] = 0;
- ok[i] = 0;
- discover[i] = 0;
- tnode_beautiful_tree = 0;
- }
- }
-
- inline void dfs(int u = 1, int p = -1)
- {
- discover[u] = dfsTime++;
- for (int v : graph[u])
- {
- if (v == p) continue;
- dfs(v, u);
- }
- }
-
- inline void dfs2(int u = 1, int p = -1)
- {
- vector <int> vec;
- for (int v : graph[u])
- {
- if (v == p) continue;
- vec.push_back(v);
- dfs2(v, u);
- }
- int sz = vec.size();
- if (sz == 0)
- {
- ok[u] = 1;
- total_node[u] = 1;
- }
- else
- {
- vector <node> vec2;
- ok[u] = 1;
- for (int w : graph[u])
- {
- if (ok[w] && discover[u] < discover[w])
- {
- vec2.push_back({w, total_node[w]});
- }
- }
- sort(vec2.begin(), vec2.end());
- int len = vec2.size();
- if (len < k)
- {
- for (node it : vec2)
- {
- ok[it.name] = 0;
- }
- }
- else if (len >= k)
- {
- int tNum = 0;
- for (int i = 0; i < k; i++)
- {
- tNum += vec2[i].totalNode;
- }
- for (int i = k; i < len; i++)
- {
- ok[vec2[i].name] = 0;
- }
- total_node[u] = tNum + 1;
- }
- vec2.clear();
- }
- }
-
- inline void dfs3(int u = 1, int p = -1)
- {
- tnode_beautiful_tree++;
- for (int v : graph[u])
- {
- if (!ok[v] || v == p) continue;
- dfs3(v, u);
- }
- }
-
- int main()
- {
- int tc;
- cin >> tc;
- for (int tcase = 1; tcase <= tc; tcase++)
- {
- initialize();
- cin >> tnode >> k;
- for (int i = 1; i < tnode; i++)
- {
- int u, v;
- cin >> u >> v;
- graph[u].push_back(v);
- graph[v].push_back(u);
- }
- dfs();
- dfs2();
- dfs3();
- cout << "Case " << tcase << ": " << tnode_beautiful_tree << endl;
- }
- }
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.