2011.2.26 14:50
这道题目想了很久,还是没做出来。。。现在想起来,有的道路已经修好了,虽然他本来可能不是最优二叉树的一条边,但是他修好了,他的权值就成为0了,你不必为他付出代价,所以他理想当然的成了最小生成树的一条边。。。
所以在存在已经建好的公路上,求解最小生成树和以前其实上一样的,对于这个我确实想太多了,哎。。脑袋不好。。。
下面是代码。。。
#include <stdio.h>
#include<iostream>
using namespace std;
#define MAX_Point 100
struct Edge {
int point;
int lowcost;
} closedge[MAX_Point];
int map[MAX_Point][MAX_Point];
int Prim(int n)
{
int i, j, k, min, sum = 0;
closedge[0].lowcost = -1;
for (i = 1; i < n; ++i)
{
closedge[i].point =0;
closedge[i].lowcost = map[0][i];
}
for (i = 1; i < n; ++i)
{
min = INT_MAX;
for (j = 0; j < n; ++j)
{
if(closedge[j].lowcost != -1 && closedge[j].lowcost < min)
{
k = j;
min = closedge[j].lowcost;
}
}
sum += closedge[k].lowcost;
closedge[k].lowcost = -1;
for (j = 0; j < n; ++j)
{
if(map[k][j] < closedge[j].lowcost)
{
closedge[j].point = k;
closedge[j].lowcost = map[k][j];
}
}
}
return sum;
}
int main()
{
int n, a, b, c, d;
while (scanf("%d", &n), n)
{
int m = n * (n - 1) / 2;
for (int i = 0; i < m; i++)
{
scanf("%d%d%d%d", &a, &b, &c, &d);
map[a - 1][b - 1] = map[b - 1][a - 1] = (d == 1 ? 0 : c);
}
printf("%d\n", Prim(n));
}
return 0;
}