Skip to content

Commit 911004a

Browse files
Merge pull request matthewsamuel95#271 from ThiagoWhispher/patch-4
Created Sack
2 parents 8d7a168 + 0388496 commit 911004a

File tree

2 files changed

+78
-0
lines changed

2 files changed

+78
-0
lines changed

Graph/Sack/README.md

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
# Sack' Algorihm
2+
The Sack algorithm allows responding offline queries related to node subtree information in a tree.
3+
A concept introduced in the algorithm is that of heavy son, in which the heavier nodes inherit their information to the parent (causing the heavy part of the processing to be discarded) and the lighter ones are processed normally.
4+
Some problems that can be solved with the Sack algorithm:
5+
* [Lomsat gelral - Codeforces](https://codeforces.com/problemset/problem/600/E)
6+
* [Tree Requests - Codeforces](https://codeforces.com/problemset/problem/570/D)
7+
8+
Troubleshooting the above using sack:
9+
* [Lomsat Gelral Solution](https://notepad.pw/code/ghp6r2r2i)
10+
* [Tree Requests Solution](https://notepad.pw/code/vf1qu7y8)

Graph/Sack/sack.cpp

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

0 commit comments

Comments
 (0)