题意:Andrew 打算建一个 a new network in his company. 要求所用电缆最短,给出n个hubs m条能够相连的边,求出最小生成树中最大的边,且输出所有相连的边
思路:典型的kruskal;
#include "stdio.h"
#include <algorithm>
#include <string.h>
#define M 15005
using namespace std;
struct data
{
int v1,v2,w;
}edge[M];
bool cmp (const data &a,const data &b)
//比较函数必须为 const 防止数据改变 且最好用&(引用而不用指针)
{
return a.w < b.w;
}
int find (int father[],int v)
{
int t;
t = v;
while (father[t] >= 0)
t = father[t];
return t;
}
void kruskal (int n,int m)
{
int father[M],vf1,vf2,i,j;
data T[M];
memset (father,-1,sizeof(father));
i = 0;
j = 0;
while (i < m&&j < n-1)
{
vf1 = find (father,edge[i].v1);
vf2 = find (father,edge[i].v2);
if (vf1 != vf2)
{
father[vf2] = vf1;
T[j++] = edge[i];
//把边加入T中
}
i ++;
}
int max = 0;
for (i = 0;i < n-1;i ++)
if (max < T[i].w)
max = T[i].w;
printf ("%d\n%d\n",max,n-1);
for (i = 0;i < n-1;i ++)
printf ("%d %d\n",T[i].v1,T[i].v2);
}
int main ()
{
int n,m,i,x,y,cost;
scanf ("%d %d",&n,&m);
for (i = 0;i < m;i ++)
{
scanf ("%d %d %d",&x,&y,&cost);
edge[i].v1 = x;
edge[i].v2 = y;
edge[i].w = cost;
}
sort (edge,edge+m,cmp);
kruskal(n,m);
return 0;
}
思路:典型的kruskal;
#include "stdio.h"
#include <algorithm>
#include <string.h>
#define M 15005
using namespace std;
struct data
{
}edge[M];
bool cmp (const data &a,const data &b)
{
}
int find (int father[],int v)
{
}
void kruskal (int n,int m)
{
}
int main ()
{
}