标签:
struct Edge
{
int from;
int to;
int w;
};
Edge Edges[200200];
int father[200200],N,M;
int find(int x)
{
if(x != father[x])
father[x] = find(father[x]);
return father[x];
}
int cmp(Edge a,Edge b)
{
return a.w < b.w;
}
int Kruskal()
{
int a,b,ans = 0,k = 0;
for(int i = 0; i < M; i++)
{
a = find(Edges[i].from);
b = find(Edges[i].to);
if(a != b)
{
ans += Edges[i].w;
father[b] = a;
k++;
if(k == N-1)
break;
}
}
return ans;
}
//初始化
for(int i = 0; i < N; i++)
father[i] = i;
Sum = 0;
for(int i = 0; i < M; i++)
{
scanf("%d%d%d",&x,&y,&w);
Edges[i].from = x;
Edges[i].to = y;
Edges[i].w = w;
Sum += w;
}
sort(Edges,Edges+M,cmp);
int ans = Kruskal();
int G[110][110],vis[110],low[110];
void Prim(int N)
{
memset(vis,0,sizeof(vis));
int ans = 0;
vis[1] = 1;
int pos = 1;
for(int i = 1; i <= N; i++)
{
if(i != pos)
low[i] = G[pos][i];
}
for(int i = 1; i < N; i++)
{
int Min = 0xffffff0;
for(int j = 1; j <= N; j++)
{
if(!vis[j] && low[j] < Min)
{
Min = low[j];
pos = j;
}
}
ans += Min;
vis[pos] = 1;
for(int j = 1; j <= N; j++)
{
if(!vis[j] && low[j] > G[pos][j])
low[j] = G[pos][j];
}
}
printf("%d\n",ans);
}
//初始化调用
for(int i = 1; i <= N; i++)
for(int j = 1; j <= N; j++)
G[i][j] = 0xffffff0;
for(int i = 1; i <= n*(n-1)/2; i++)
{
scanf("%d%d%d",&x,&y,&d);
map[x][y] = map[y][x] = d;
}
标签:
原文地址:http://blog.csdn.net/lianai911/article/details/45445659