贪心算法解决最小集合覆盖问题

AVL自平衡树

关键就是对于递归的每一步插入都要进行判断,而不是对于root节点进行判断。
ac代码

#include 
#include 
#include 
#include 
using namespace std;

struct node {
	int val;
	struct node* left, * right;
};
int getHeight(node* root) {
	if (root == nullptr) return 0;
	return max(getHeight(root->left), getHeight(root->right)) + 1;
}
node* rotateRight(node* root) {
	node* t = root->left;
	root->left = t->right;
	t->right = root;
	return t;
}
node* rotateLeft(node* root) {
	node* t = root->right;
	root->right = t->left;
	t->left = root;
	return t;
}
node* rotateRightLeft(node* root) {
	root->right = rotateRight(root->right);
	return rotateLeft(root);
}
node* rotateLeftRight(node* root) {
	root->left = rotateLeft(root->left);
	return rotateRight(root);
}
node* insert(node* root, int val) {
	if (root == nullptr) {
		root = new node();
		root->val = val;
		root->left = root->right = nullptr;
	}
	else if (val < root->val) {
		root->left = insert(root->left, val);
		if (getHeight(root->left) - getHeight(root->right) == 2)
			root = val < root->left->val ? rotateRight(root) : rotateLeftRight(root);
	}
	else {
		root->right = insert(root->right, val);
		if (getHeight(root->right) - getHeight(root->left) == 2)
			root = val > root->right->val ? rotateLeft(root) : rotateRightLeft(root);
	}
	return root;
}

int main() {
	int n, val;
	cin >> n;
	node* root = nullptr;
	for (int i = 0; i < n; i++) {
		scanf("%d", &val);
		root = insert(root, val);
	}
	cout << root->val << endl;
	return 0;
}

你可能感兴趣的:(贪心算法解决最小集合覆盖问题)