-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathprufer_code.cpp
More file actions
83 lines (69 loc) · 2.33 KB
/
prufer_code.cpp
File metadata and controls
83 lines (69 loc) · 2.33 KB
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
/*
Tree to Prufer Code
Works for both 0 and 1 indexed node numbering
Complexity: O(VlogV)
*/
vector<int> treeToPruferCode (int nodes, vector<pair<int,int>> &edges) {
unordered_set<int> neighbors[nodes+1]; // For each node, who is it's neighbor?
for( int i = 0; i < edges.size(); i++ ) {
pair<int,int> edge = edges[i];
int u = edges[i].first; int v = edges[i].second;
neighbors[u].insert(v);
neighbors[v].insert(u);
}
priority_queue<int> leaves;
for ( int i = 0; i <= nodes; i++ ) {
if (neighbors[i].size() == 1 ) {
leaves.push(-i); // Negating since we need min heap
}
}
vector<int> pruferCode;
int need = nodes - 2;
while(need--) {
int leaf = -leaves.top(); leaves.pop();
int neighborOfLeaf = *(neighbors[leaf].begin());
pruferCode.push_back(neighborOfLeaf);
// Remove the leaf
neighbors[neighborOfLeaf].erase(leaf);
// The neighbor can become a new leaf
if(neighbors[neighborOfLeaf].size() == 1) {
leaves.push(-neighborOfLeaf);
}
}
return pruferCode;
}
/*
Prufer Code to Tree
Complexity: O(VlogV)
*/
vector<pair<int,int>> pruferCodeToTree(vector<int> &pruferCode) {
// Stores number count of nodes in the prufer code
unordered_map<int,int> nodeCount;
// Set of integers absent in prufer code. They are the leaves
set<int> leaves;
int len = pruferCode.size();
int node = len + 2;
// Count frequency of nodes
for ( int i = 0; i < len; i++ ) {
int t = pruferCode[i];
nodeCount[t]++;
}
// Find the absent nodes
for ( int i = 1; i <= node; i++ ) {
if ( nodeCount.find ( i ) == nodeCount.end() ) leaves.insert ( i );
}
vector<pair<int,int>> edges;
/*Connect Edges*/
for ( int i = 0; i < len; i++ ){
int a = prufer[i]; // First node
//Find the smallest number which is not present in prufer code now
int b = *leaves.begin(); // the leaf
edges.push_back({a,b}); // Edge of the tree
leaves.erase ( b ); // Remove from absent list
nodeCount[a]--; // Remove from prufer code
if ( nodeCount[a] == 0 ) leaves.insert ( a ); // If a becomes absent
}
// The final edge
edges.push_back({*leaves.begin(), *leaves.rbegin()});
return edges;
}