HDU 1233 还是畅通工程 (自己种的第一棵最小生成树)

还是畅通工程

Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 11558    Accepted Submission(s): 5293


Problem Description
某省调查乡村交通状况,得到的统计表中列出了任意两村庄间的距离。省政府“畅通工程”的目标是使全省任何两个村庄间都可以实现公路交通(但不一定有直接的公路相连,只要能间接通过公路可达即可),并要求铺设的公路总长度为最小。请计算最小的公路总长度。
 
Input
测试输入包含若干测试用例。每个测试用例的第1行给出村庄数目N ( < 100 );随后的N(N-1)/2行对应村庄间的距离,每行给出一对正整数,分别是两个村庄的编号,以及此两村庄间的距离。为简单起见,村庄从1到N编号。
当N为0时,输入结束,该用例不被处理。
 
Output
对每个测试用例,在1行里输出最小的公路总长度。
 
Sample Input
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
 
Sample Output
3
5
Hint
Hint
Huge input, scanf is recommended.
 
 
 
View Code
#include <set>
#include <map>
#include <list>
#include <cmath>
#include <ctime>
#include <deque>
#include <queue>
#include <stack>
#include <cstdio>
#include <string>
#include <vector>
#include <cctype>
#include <cstring>
#include <sstream>
#include <fstream>
#include <cstdlib>
#include <cassert>
#include <iostream>
#include <algorithm>

using namespace std;
//Constant Declaration
/*
--------------------------*/
//#define LL long long
#define LL __int64
const int M=110;
const int INF=1<<30;
const double EPS = 1e-11;
const double PI = acos(-1.0);
/*--------------------------*/
// some essential funtion
/*
----------------------------------*/
void Swap(int &a,int &b){ int t=a;a=b;b=t; }
int Max(int a,int b){ return a>b?a:b; }
int Min(int a,int b){ return a<b?a:b; }
int Gcd(int a,int b){ while(b){b ^= a ^=b ^= a %= b;} return a; }
/*----------------------------------*/
//for (i = 0; i < n; i++)
/*
----------------------------------*/


int d[M];
int g[M][M];
int used[M];

void Init(int n)//初始化。
{
int i, j;
for (i = 1; i <= n; i++)
{
d[i] = INF;
}

for (i = 1; i <= n; i++)
{
for (j = 1; j <= n; j++)
{
g[i][j] = INF;
}
}

memset(used, 0, sizeof(used));
}


int Prim(int n)
{
d[1] = 0;//默认d[1]为起点v1
int cnt, i, j;
int min, min_num;
int sum = 0;
for (cnt = 1; cnt <= n; cnt++)
{
min = INF;
min_num = 0;//防止非连通
for (i = 1; i <= n; i++)//生仔。
{
if (!used[i] && min > d[i])
{
min = d[i];
min_num = i;
}
}
if (min_num == 0)//非连通
{
return -1;
}

used[min_num] = 1;//别写成used[i]
sum += min;

for (i = 1; i <= n; i++)//松弛,更新。
{
if (!used[i] && d[i] > g[min_num][i])
{
d[i] = g[min_num][i];
}
}
}
return sum;
}


int main()
{
//freopen("in.txt","r",stdin);
//freopen("out.txt","w",stdout);
//int t, case1 = 0;
//scanf("%d", &t);
int n, m;
int i, j;
//scanf("%d%d", &n, &m);
while (scanf("%d", &n), n)
{
Init(n);
for (i = 0; i < n*(n-1)>>1; i++)
{
int a, b, c;
scanf("%d%d%d", &a, &b, &c);
if (g[a][b] > c)
{
g[a][b] = g[b][a] = c;
}

}
cout << Prim(n) << endl;
}

return 0;
}
原文地址:https://www.cnblogs.com/qiufeihai/p/2390661.html