-
-
Notifications
You must be signed in to change notification settings - Fork 8
/
Prufer to Tree.cpp
45 lines (35 loc) · 1.24 KB
/
Prufer to Tree.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
/*
Prufer Code to Tree (or a Connected Graph :) )
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 = pruferCode[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;
}