PKU 1258 Agri-Net
文章作者:ktyanny 文章来源:ktyanny 转载请注明,谢谢合作。
话说N久没做题了,手生……今天拿一道很水的最小生成树来做,很水的。理解题意后一看就是赤裸裸的最小生成树算法题。好吧,二话不多说,贴上我的代码:
/*
by ktyanny
2010.01.26
C++ 47MS
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <iostream>
using namespace std;
const int MAX = 105;
typedef struct
{
int a, b;
}point;
point v[MAX];
typedef struct
{
int x, y;
int w;
}edge;
const int MAXN = 50005;
edge e[MAXN];
int ans;
int rank[MAXN];
int pa[MAXN];
void make_set(int x)
{
pa[x] = x;
rank[x] = 0;
}
int find_set(int x)
{
if(x != pa[x])
pa[x] = find_set(pa[x]);
return pa[x];
}
/*按秩合并x,y所在的集合*/
void union_set(int x, int y, int w)
{
x = find_set(x);
y = find_set(y);
if(x == y)return ;
ans += w;
if(rank[x] > rank[y])/*让rank比较高的作为父结点*/
{
pa[y] = x;
}
else
{
pa[x] = y;
if(rank[x] == rank[y])
rank[y]++;
}
}
int cmp(const void *a, const void *b)
{
return ( (*(edge *)a).w > (*(edge *)b).w ) ? 1 : -1;
}
int main()
{
int n, i, j, jj, x, y, k, t;
while(cin >> n)
{
k = 0;
ans = 0;
for(i = 0; i < n; i++){
for(j = 0; j < n; j++)
{
scanf("%d", &t);
if(i < j){
e[k].w = t;
e[k].x = i;
e[k].y = j;
k++;
}
}
}
n = n * n;
for(i = 0; i <= n; i++)
make_set(i);
qsort(e, k, sizeof(e[0]), cmp);
/*Kruscal过程求最小生成树*/
ans = 0;
for(i = 0; i < k; i++)
{
x = find_set(e[i].x);
y = find_set(e[i].y);
if(x != y)
union_set(x, y, e[i].w);
}
printf("%d\n", ans);
}
return 0;
}
posted on 2010-01-26 13:36 Ktyanny Home 阅读(285) 评论(0) 编辑 收藏 举报