HDU1233

Prim算法:
#include
#include
#include
#include
#include
#include
#include
using namespace std;
#define min(a,b) ((a)>(b)?(b):(a))
#define inf 1000000
int mat[101][101],n;
void Prim()
{
int i,j,min_i,Min,sum=0;
int dis[501];
int flag[501];
for( i=1 ; i <= n ; i++ )
dis[i] = mat[i][1];
memset( flag, 0, sizeof(flag));
flag[1] = 1;
for( i=2 ; i <= n ; i++ )
{
Min = inf;min_i=i;
for( j=2 ; j <= n ; j++ )
if(flag[j]==0 && dis[j]
{
Min = dis[j];
min_i = j;
}
if(Min == inf) break;
sum += Min;
flag[min_i] = 1;
for( j=2 ; j <= n ; j++ )
{
if(flag[j]==0 && dis[j]>mat[min_i][j])
dis[j] = mat[min_i][j];
}
}
printf("%d\n", sum);
}
int main()
{
while(scanf("%d",&n)&&n)
{
int a,b,d;
 for(int i=0;i
 {
 scanf("%d%d%d",&a,&b,&d);
 mat[a][b]=mat[b][a]=d;
 }
 Prim();
}
return 0;
}
Kruskal算法:
#include
#include
#include
#include
#include
#include
#include
using namespace std;
#define min(a,b) ((a)>(b)?(b):(a))
#define N 101
int fa[N],n;
struct edge
{
int x,y,value;
}e[10001];
bool cmp(edge a,edge b)
{
return a.value < b.value;
}
int find(int x)
{
if(x==fa[x]) return x;
return fa[x]=find(fa[x]);
}
void Kruskal()
{
int ans = 0;
for(int i=1 ; i <= n ; ++i)
fa[i] = i;
sort(e,e+(n-1)*n/2,cmp);
for(int i=0 ; i < n*(n-1)/2 ; ++i)
{
int x = find(e[i].x);
int y = find(e[i].y);
if(x != y)
{
ans += e[i].value;
fa[x] = y;
}
}
printf("%d\n",ans);
}
int main()
{
while(scanf("%d",&n)&&n)
{
 for(int i=0;i
 scanf("%d%d%d",&e[i].x ,&e[i].y,&e[i].value );
 //sort(e,e+(n-1)*n/2,cmp);
 Kruskal();
}
return 0;
}

你可能感兴趣的:(HDU1233)