forked from matthewsamuel95/ACM-ICPC-Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 1
/
sack.cpp
68 lines (59 loc) · 1.3 KB
/
sack.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#include <bits/stdc++.h>
using namespace std;
#define max 100007
vector<int> tree[max];
int weight[max];
vector<int> *nos[max];
void dfs(int u, int p){
weight[u] = 1;
for(auto v: tree[u]){
if(v != p){
dfs(v, u);
weight[u] += weight[v];
}
}
}
void sack(int u, int p, bool keep){
int heavy_child = -1;
for(auto son: tree[u]){
if(son != p){
if(heavy_child == -1 || weight[son] > weight[heavy_child]) heavy_child = son;
}
}
for(auto son: tree[u]){
if(son != p && son != heavy_child) sack(son, u, false);
}
if(heavy_child == -1) nos[u] = new vector<int> ();
else{
sack(heavy_child, u, true);
nos[u] = nos[heavy_child];
}
nos[u]->push_back(u);
//Operation
for(auto son: tree[u]){
if(son != p && son != heavy_child){
for(auto x: *nos[son]){
nos[u]->push_back(x);
}
}
}
// Output of sub tree u is ok
/* Operation
if(!keep){
for(auto x: *nos[u]){
}
}
*/
}
int main(){
int n;
scanf("%d", &n);
for(int i=1; i<n; i++){
int u, v;
scanf("%d%d", &u, &v);
tree[u].push_back(v);
tree[v].push_back(u);
}
dfs(1,1);
sack(1,1,true);
}