/*
Independent set on trees, which could be solved by greedy algorithm.
Key observation: if node v is a leaf, there exists a max cardinality independent
set containing v.
http://www.cs.princeton.edu/~wayne/kleinberg-tardos/pdf/IntractabilityIII-2x2.pdf
The sample in this program is from wikipedia
https://en.wikipedia.org/wiki/Tree_traversal
*/
#include <iostream>
#include <vector>
#include <stack>
#include <Windows.h>
using namespace std;
struct node
{
char data;
struct node *left = nullptr;
struct node *right = nullptr;
bool visited = false;
node() = default;
node(char d) : data(d) {}
node(char d, node *l, node *r) : data(d), left(l), right(r) {}
};
void independentSet(node *root, vector<char> &set)
{
stack<node*> s;
node *lst = nullptr; // last visited node
node *cur = root; // current visit node
node *top = nullptr; // top node on stack
while (!s.empty() || cur) // postorder traverse
{
if (cur)
{
s.push(cur);
cur = cur->left;
}
else
{
top = s.top();
if (top->right && lst != top->right)
cur = top->right;
else
{
lst = top;
if ((top->left == nullptr || top->left->visited == false) &&
(top->right == nullptr || top->right->visited == false))
{
set.push_back(top->data);
top->visited = true;
}
s.pop();
}
}
}
}
int main()
{
node *root = new node('F');
root->left = new node('B');
root->right = new node('G');
root->left->left = new node('A');
root->left->right = new node('D');
root->left->right->left = new node('C');
root->left->right->right = new node('E');
root->right->right = new node('I');
root->right->right->left = new node('H');
/*
node *root = new node('A');
root->left = new node('B');
root->right = new node('C');
root->left->left = new node('D');
root->left->left->left = new node('F');
root->left->left->right = new node('G');
root->left->left->right->left = new node('I');
root->left->left->right->right = new node('J');
root->right = new node('C');
root->right->right = new node('E');
root->right->right->left = new node('H');
*/
vector<char> set;
independentSet(root, set);
for (auto a : set)
cout << a << " ";
cout << endl;
system("PAUSE");
return 0;
}
Independent set of tree with greedy algorithm
最新推荐文章于 2020-05-06 21:22:34 发布