原理图
#图片来源http://blog.csdn.net/luoshixian099/article/details/51908175
代码
基于小根堆和并查集。测试是根据图中来的。
代码中含有将有向图化为无向图的部分。
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
int set[100];
int find(int x) {
if (set[x] == x)
{
return x;
} else {
int root = find(set[x]);
set[x] = root;
return root;
}
}
void unin(int root1 , int root2) {
set[root1] = root2;//root2作为根
}
struct Node
{
int x, y;
int e;
Node(int a, int b , int w) {
x = a;
y = b;
e = w;
}
};
struct cmp
{
bool operator()(Node& a, Node& b) {
return a.e > b.e;
}
};
int main(int argc, char const *argv[])
{
priority_queue<Node, vector<Node>, cmp> a, con;
Node x1 = Node(1, 2, 6);
Node x2 = Node(2, 3, 5);
Node x3 = Node(1, 3, 1);
Node x4 = Node(1, 4, 5);
Node x5 = Node(3, 4, 5);
Node x6 = Node(2, 5, 3);
Node x7 = Node(3, 5, 6);
Node x8 = Node(5, 6, 6);
Node x9 = Node(3, 6, 4);
Node x10 = Node(4, 6, 2);
a.push(x1);
a.push(x2);
a.push(x3);
a.push(x4);
a.push(x5);
a.push(x6);
a.push(x7);
a.push(x8);
a.push(x9);
a.push(x10);
for (int i = 1; i <= 10; ++i)//有向图变为无向图
{
con.push(Node(a.top().x, a.top().y, a.top().e));
con.push(Node(a.top().y, a.top().x, a.top().e));
a.pop();
}
for (int i = 0; i <= 9; ++i)
{
set[i] = i;
}
vector<Node> res;
while (!con.empty() && res.size() <=5) {
Node a = con.top();
con.pop();
int x = find(a.x);
int y = find(a.y);
if (x != y)
{
unin(x, y);
res.push_back(a);
} else {
continue;
}
}
if (res.size() != 5)
{
for (int i = 0; i < res.size(); ++i)
{
cout << res[i].x << "--" << res[i].y << "--"
<< res[i].e<<endl;
}
cout << "false" << endl;
} else {
cout << "res:"<<endl;
for (int i = 0; i < res.size(); ++i)
{
cout << res[i].x << "--" << res[i].y << "--"
<< res[i].e<<endl;
}
}
return 0;
}