4 6 1 2 1 1 3 1 1 4 2 2 3 1 3 4 1 2 4 1
4个城市,6条道路,求最小生成树
套用kruskal算法过
#include<cstdio>
#include<algorithm>
#include<vector>
using namespace std;
class cable
{
public:
int x;
int y;
int L;//x-y
int id;
bool flag;//初始为false,代表未选择
};
class T
{
public:
int parent[1010];
int root(int x)
{
if(parent[x]==x)
{
return x;
}
return parent[x]=root(parent[x]);
}
void Merge(int a,int b)
{
int ra=root(a);
int rb=root(b);
parent[ra]=rb;
}
void init(int n)
{
for(int i=1;i<=n;i++)
{
parent[i]=i;
}
}
}disjiontset;//并查集
vector<cable>edge;
bool cmp(cable a,cable b)
{
return a.L<b.L;
}
bool cmp2(cable a,cable b)
{
return a.id<b.id;
}
int main()
{
int n,m;
scanf("%d%d",&n,&m);
disjiontset.init(n);
for(int i=0;i<m;i++)
{
cable tt;
tt.id=i;
tt.flag=false;
scanf("%d%d%d",&tt.x,&tt.y,&tt.L);
edge.push_back(tt);
}
sort(edge.begin(),edge.end(),cmp);
int MAX=-1;
int counter=0;
for(vector<cable>::iterator i=edge.begin();i!=edge.end();i++)
{
if(disjiontset.root(i->x)!=disjiontset.root(i->y))
{
disjiontset.Merge(i->x,i->y);
i->flag=true;
counter++;
if(MAX<i->L)
{
MAX=i->L;
}
}
}
printf("%d\n",MAX);
printf("%d\n",counter);
sort(edge.begin(),edge.end(),cmp2);
for(vector<cable>::iterator i=edge.begin();i!=edge.end();i++)
{
if(i->flag)
{
printf("%d %d\n",i->x,i->y);
}
}
return 0;
}