poj又很英勇的挂掉了,无奈。。再挂上几次我就转战zoj!
今天刷了几道最小生成树, 都是用prim写的
#include<cstdio>
#include<cstring>
#define amin(a,b) a<b?a:b
#define MAX 99999999
using namespace std ;
int map[105][105] ;
int i, j, k ;
int prim(int n){
int dis[105] ;
int x = 1 ;
int sum = 0 ;
memset(dis, 127, sizeof(dis)) ;
dis[1] = 0 ;
for(i=2; i<=n; i++)
if(map[x][i]!=0)
dis[i] = map[x][i] ;
for(i=2; i<=n; i++){
int min = MAX ;
for(j=1; j<=n; j++)
if(dis[j]!=0&&min>dis[j]){
min = dis[j] ;
x = j ;
}
dis[x] = 0 ;
sum += min ;
//printf(" %d ", sum) ;
for(k=1; k<=n; k++){
if(map[x][k]!=0&&(map[x][k]<dis[k])&&dis[k]!=0)
dis[k] = map[x][k] ;
}
}
return sum ;
}
int main(){
int n, m, value, a, b, sum ;
while(true){
memset(map, 0, sizeof(map)) ;
scanf("%d", &n) ;
if(!n) break ;
scanf("%d", &m) ;
while(m--){
scanf("%d%d%d", &a, &b, &value) ;
if(map[a][b]==0)
map[a][b] = map[b][a] = value ;
else
map[a][b]=map[b][a]=amin(value, map[a][b]) ;
//printf("%d ", map[a][b]) ;
}
sum = prim(n) ;
printf("%d\n", sum) ;
}
return 0 ;
#include<cstring>
#define amin(a,b) a<b?a:b
#define MAX 99999999
using namespace std ;
int map[105][105] ;
int i, j, k ;
int prim(int n){
int dis[105] ;
int x = 1 ;
int sum = 0 ;
memset(dis, 127, sizeof(dis)) ;
dis[1] = 0 ;
for(i=2; i<=n; i++)
if(map[x][i]!=0)
dis[i] = map[x][i] ;
for(i=2; i<=n; i++){
int min = MAX ;
for(j=1; j<=n; j++)
if(dis[j]!=0&&min>dis[j]){
min = dis[j] ;
x = j ;
}
dis[x] = 0 ;
sum += min ;
//printf(" %d ", sum) ;
for(k=1; k<=n; k++){
if(map[x][k]!=0&&(map[x][k]<dis[k])&&dis[k]!=0)
dis[k] = map[x][k] ;
}
}
return sum ;
}
int main(){
int n, m, value, a, b, sum ;
while(true){
memset(map, 0, sizeof(map)) ;
scanf("%d", &n) ;
if(!n) break ;
scanf("%d", &m) ;
while(m--){
scanf("%d%d%d", &a, &b, &value) ;
if(map[a][b]==0)
map[a][b] = map[b][a] = value ;
else
map[a][b]=map[b][a]=amin(value, map[a][b]) ;
//printf("%d ", map[a][b]) ;
}
sum = prim(n) ;
printf("%d\n", sum) ;
}
return 0 ;
}