【数据结构】BOJ-848最小生成树
Prim算法
#include <stdio.h>
#define N 1000
int main() {
int G[10][10] = {
{N,3,N,4,4,N,N,N,N,N},//A
{3,N,10,N,2,3,N,N,N,N},//B
{N,10,N,N,N,6,1,N,N,N},//C
{4,N,N,N,5,N,N,6,N,N},//D
{4,2,N,5,N,11,N,2,1,N},//E
{N,3,6,N,11,N,2,N,3,11},//F
{N,N,1,N,N,2,N,N,N,8},//G
{N,N,N,6,2,N,N,N,4,N},//H
{N,N,N,N,1,3,N,4,N,7},//I
{N,N,N,N,N,11,8,N,7,N},};
char a,b;
int i =0,j=0,k=0;
scanf("%c,%c,%d",&a,&b,&k);
G[a-65][b-65] = k;
G[b-65][a-65] = k;
int arr[10];
int path[10];
for (i = 1; i < 10; ++i)
path[i] = G[0][i];
int min,minid = 0;
for (i = 1; i < 10; ++i)
{
min = N;
for (j = 1; j < 10; ++j)
if(path[j] < min && path[j] != 0)
{
min = path[j];
minid = j;
}
arr[i-1] = min;
path[minid] = 0;
for (j = 1; j < 10; ++j)
if(G[minid][j] < path[j])
path[j] = G[minid][j];
}
for(i=0;i<8;++i)
for(j=0;j<8-i;++j)
if(arr[j]>arr[j+1])
{
k=arr[j];
arr[j]=arr[j+1];
arr[j+1]=k;
}
for(j=0;j<9;++j)
printf("%d,",arr[j]);
return 0;
}
Kruskal 算法
#include <stdio.h>
#define N 1000
typedef struct node
{
int a,b,data;
}Node;
int fa[10];
int find(int x)
{
if(fa[x]==x)
return x;
else
return fa[x] = find(fa[x]);
}
int Kruskal(Node *arr) {
int count = 0, sum = 0;
Node temp;
for (int i = 0; i < 10; ++i)
fa[i] = i;
//排序
for (int m = 0; m < 19; ++m) {
for (int n = 0; n < 18 - m; ++n) {
if (arr[n].data > arr[n + 1].data) {
temp = arr[n];
arr[n] = arr[n + 1];
arr[n + 1] = temp;
}
}
}
for (int l = 0; l < 19 && count != 9; ++l) {
int u = find(arr[l].a);
int v = find(arr[l].b);
if (u!= v) {
fa[u] = v;
sum += arr[l].data;
count++;
printf("%d,",arr[l].data);
}
//判断非联通
if(l>=19&&count!=9)
return -1;
}
return sum;
}
int main() {
int G[10][10] = {
{N,3,N,4,4,N,N,N,N,N},//A
{3,N,10,N,2,3,N,N,N,N},//B
{N,10,N,N,N,6,1,N,N,N},//C
{4,N,N,N,5,N,N,6,N,N},//D
{4,2,N,5,N,11,N,2,1,N},//E
{N,3,6,N,11,N,2,N,3,11},//F
{N,N,1,N,N,2,N,N,N,8},//G
{N,N,N,6,2,N,N,N,4,N},//H
{N,N,N,N,1,3,N,4,N,7},//I
{N,N,N,N,N,11,8,N,7,N},};
char a,b;
int v;
scanf("%c,%c,%d",&a,&b,&v);
G[a-65][b-65] = v;
G[b-65][a-65] = v;
int num = 0;
Node ar[20];
for (int i = 0; i < 10; ++i) {
for (int j = 0; j < i; ++j) {
if(G[i][j] != N){
ar[num].data = G[i][j];
ar[num].a = i;
ar[num].b = j;
num++;
}
}
}
Kruskal(ar);
}