#include
#include
#include
struct road
{
int st;
int ed;
int w;
};
road all[900];
int A[30];
int cmp(const void *a,const void *b)
{
return (*(road *)a).w - (*(road *)b).w;
}
int find(int x)
{
if (x != A[x])
A[x] = find(A[x]);
return A[x];
}
int main()
{
int i,j,k,q,p,m,n,sum;
char s,e;
while (scanf("%d",&n) != EOF)
{
if (n == 0) break;
memset(A,0,sizeof(int));
for (i = 1;i <= n;i++)
A[i] = i;
m = 0;
for (i = 1;i < n;i++)
{
scanf(" %c%d",&s,&p);
while (p--)
{
scanf(" %c%d",&e,&q);
all[m].st = s - 'A';
all[m].ed = e - 'A';
all[m].w = q;
m++;
}
}
qsort(all,m,sizeof(all[0]),cmp);
k = 0;sum = 0;
while (k < m)
{
all[k].st = find(all[k].st);
all[k].ed = find(all[k].ed);
if (all[k].st != all[k].ed)
{
sum += all[k].w;
A[all[k].st] = all[k].ed;
}
k++;
}
printf("%d\n",sum);
}
system("pause");
return 0;
}
这是杭电上的jungle roads 的代码,,就用的是最小生成树,,你看看吧。。。
#include
#include
#include
#define MAXN 1000
int map[MAXN][MAXN];
int n;
void Prim()
{
int i, j, minV, sum;
int dis[n], pre[n];
bool vist[n] = {0};
vist[0] = 1;
for (i = 0; i < n; i++)
{
dis[i] = map[0][i];
pre[i] = 0;
}
sum = 0;
for (i = 1; i < n; i++)
{
minV = -1;
for (j = 0; j < n; j++)
if (!vist[j] && (minV < 0 || dis[j] < dis[minV]))
minV = j;
vist[minV] = 1;
sum += dis[minV];
for (j = 0; j < n; j++)
if (!vist[j] && dis[j] > map[minV][j])
{
dis[j] = map[minV][j];
pre[j] = minV;
}
}
printf("最小生成树的权为 = %d\n", sum);
for (i = 0; i < n; i++)
printf("边 %d - %d\n", i, pre[i]);
}
int main()
{
int i, j;
printf("请输入结点数n:\n");
scanf("%d", &n);
printf("请输入邻接矩阵:\n");
for (i = 0; i < n; i++)
for (j = 0; j < n; j++)
scanf("%d", &map[i][j]);
prim();
return 0;
}
//用prim写的,输入是邻接矩阵
你说明白点,我看能不能帮你写出来