题意大致就是连通所有点的需要的最小代价,典型的最小生成树。本人用了Prim来算。
#include <iostream>
#include <cmath>
#include <algorithm>
#include <string.h>
#include <stdio.h>
#define MAXN 1000
#define INF 1<<30
using namespace std;
int closest[MAXN],lowcost[MAXN],m;// m为节点的个数
int G[MAXN][MAXN];//邻接矩阵
void prim()
{
for(int i=0;i<m;i++)
{
lowcost[i]=INF;
}
for(int i=0;i<m;i++)
{
closest[i]=0;
}
closest[0]=-1;//加入第一个点,-1表示该点在集合U中,否则在集合V中
int num=0,ans=0,e=0;//e为最新加入集合的点
while(num<m-1)//加入m-1条边
{
int micost=INF,miedge=-1;
for(int i=0;i<m;i++)
if(closest[i]!=-1)
{
int temp=G[e][i];
if(temp<lowcost[i])
{
lowcost[i]=temp;
closest[i]=e;
}
if(lowcost[i]<micost)
micost=lowcost[miedge=i];
}
ans+=micost;
closest[e=miedge]=-1;
num++;
}
printf("%d\n",ans);
}
int main()
{
int cas;
int n;
int u, v, w;
scanf("%d", &cas);
while(cas--)
{
scanf("%d%d", &m, &n);
for(int i = 0; i <= m; i ++)
for(int j = 0; j <= m; j ++)
G[i][j] = INF;
while(n--)
{
scanf("%d%d%d", &u, &v, &w);
G[u][v] = G[v][u] = w;
}
prim();
}
return 0;
}
下面是kruskal算法提交的代码:
#include <iostream>
#include <math.h>
#include <algorithm>
#include <string.h>
#include <stdio.h>
#define Maxn 10000
using namespace std;
struct x
{
int f, t, w;
} xx[20000];
bool cmp(x a, x b)
{
return a.w < b.w;
}
int fa[1000];
int mincost, point_number, edge_number;
int fi(int x)
{
if(x != fa[x])
fa[x] = fi(fa[x]);
return fa[x];
}
void kruskal()
{
for(int i = 0; i <= point_number; i++)
fa[i] = i;
mincost = 0;
for(int i = 0; i < edge_number; i ++)
{
int a = xx[i].f, b = xx[i].t;
a = fi(a), b = fi(b);
if(a != b)
{
fa[a] = b;
mincost += xx[i].w;
}
}
printf("%d\n", mincost);
}
int find(int x, int y)
{
for(int i = 0; i < edge_number; i ++)
{
if(xx[i].f == x && xx[i].t == y)
return i;
if(xx[i].f == y && xx[i].t == x)
return i;
}
return -1;
}
int main()
{
int T;
scanf("%d", &T);
while(T--)
{
int m;
edge_number = 0;
scanf("%d%d", &point_number, &m);
for(int i = 0; i < m; i++)
{
int a, b, c;
scanf("%d%d%d", &a, &b, &c);
int h = find(a,b);
if(h != -1)
xx[h].w = max(xx[h].w, c);
else
{
xx[edge_number].f = a;
xx[edge_number].t = b;
xx[edge_number++].w = c;
}
}
sort(xx, xx + edge_number, cmp);
kruskal();
}
return 0;
}