这是一道原始的最小生成树问题。
http://acm.xmu.edu.cn/JudgeOnline/problem.php?cid=1023&pid=3
代码可以看做是模板代码:
#include <iostream>
#include <vector>
#include <stdlib.h>
#include <stdio.h>
#include <limits.h>
using namespace std;
int lingjie[101][101]; //邻接矩阵
int dist[1001];//
int parent[1001];//
int main(){
int N; //顶点个数
vector<int> MIT; //最小生成树,存储顶点序号
vector<int> LEFT;//剩余的点
int length = 0; //最小生成树
while (scanf("%d",&N),N!=0)
{
MIT.clear();
LEFT.clear();
length = 0;
//初始化lingjie[][]
for (int i = 1; i <= N; i++)
{
for (int j = 1; j <= N; j++)
{
lingjie[i][j] = INT_MAX;
}
}
//序号从1开始
int x, y, d,i,j;
for ( i = 1; i <= N*(N - 1)/2 ; i++)
{
scanf("%d %d %d", &x, &y, &d);
lingjie[x][y] = lingjie[y][x] = d;
}
for ( i = 1; i <= N; i++)
{
LEFT.insert(LEFT.end(), i);
}
int v = *LEFT.begin();
MIT.insert(MIT.end(), v);
LEFT.erase(LEFT.begin());
//初始化dist[][] , parent[]
for (i = 1; i <= N; i++)
{
dist[i] = lingjie[i][v];
parent[i] = v; //全部先设为v
}
//主循环
while (LEFT.size() != 0){
d = dist[*LEFT.begin()];
vector<int>::iterator mark = LEFT.begin();
for (vector<int>::iterator i = LEFT.begin() + 1; i != LEFT.end(); i++)//寻找到MIT最近的点
{
if (d > dist[*i])
{
d = dist[*i];
mark = i;
}
}
v = *mark;
MIT.insert(MIT.end(),*mark);
LEFT.erase(mark);
length += d;
//更新dist[]
for (vector<int>::iterator j = LEFT.begin(); j != LEFT.end(); j++)//更新当前剩余点到MIT的dist
{
if (lingjie[*j][v] < dist[*j])
{
dist[*j] = lingjie[*j][v];
parent[*j] = v; //预处理时: lingjie[i][i] = MAX ,否则parent[i] =i 恒成立
}
}
}
//end of 主循环
printf("%d\n", length);
}
return 0;
}
/*
3
1 2 1
1 3 2
2 3 4
4
1 2 1
1 3 4
1 4 1
2 3 3
2 4 2
3 4 5
0
*/
/**************************************************************
Problem: 1500
User: cld378632668
Language: C++
Result: Accepted
Time:3 ms
Memory:1560 kb
****************************************************************/
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。