vertex cover problem with dynamic programming

来源:互联网 发布:知乎城市冷漠 编辑:程序博客网 时间:2024/06/01 11:02
#include <iostream>#include <Windows.h>#include <vector>#include <algorithm>#include <numeric>using namespace std;struct node{int data;node *left, *right;int vc; // vc is the vertex cover count for the subtree.node(int d) : data(d), left(nullptr), right(nullptr), vc(0) {};};// recursive methodint vCover(node *root){if (root == nullptr)return 0;if (root->left == nullptr && root->right == nullptr)return 0;if (root->vc)return root->vc;// root is included in vertex coverint root_inc = 1 + vCover(root->left) + vCover(root->right);// root is excludedint root_exc = 0;if (root->left != nullptr)root_exc += 1 + vCover(root->left->left) + vCover(root->left->right);if (root->right != nullptr)root_exc += 1 + vCover(root->right->left) + vCover(root->right->right);root->vc = min(root_inc, root_exc);return root->vc;}int main(){node *root = new node(20);root->left = new node(8);root->left->left = new node(4);root->left->right = new node(12);root->left->right->left = new node(10);root->left->right->right = new node(14);root->right = new node(22);root->right->right = new node(25);cout << vCover(root) << endl;system("PAUSE");return 0;}

0 0
原创粉丝点击