单点时限: 2.0 sec
内存限制: 256 MB
Partychen is working as system administrator and is planning to establish a new network in his company. There will be N hubs in the company, they can be connected to each other using cables. Since each worker of the company must have access to the whole network, each hub must be accessible by cables from any other hub (with possibly some intermediate hubs).
Since cables of different types are available and shorter ones are cheaper, it is necessary to make such a plan of hub connection, that the cost is minimal. partychen will provide you all necessary information about possible hub connections. You are to help partychen to find the way to connect hubs so that all above conditions are satisfied.
输入格式
The first line of the input contains two integer numbers: N - the number of hubs in the network (2 <= N <= 1000) and M - the number of possible hub connections (1 <= M <= 15000). All hubs are numbered from 1 to N. The following M lines contain information about possible connections - the numbers of two hubs, which can be connected and the cable cost required to connect them. cost is a positive integer number that does not exceed 106. There will always be at least one way to connect all hubs.
输出格式
Output the minimize cost of your hub connection plan.
样例
input
4 6 1 2 1 1 3 1 1 4 2 2 3 1 3 4 1 2 4 1
output
3 Hint We can build net from 1 to 2 to 3 to 4,then we get the cost is 3.Of course you can get 3 by other way.
注意!!!Hint后面的那两行只是题目的提示,而不需要我们输出,不要像我一样天真地把它输出了然后百思不得其解一直过不了。。。
代码如下:
#include<iostream>
#include<vector>
using namespace std;
#define INF 0x3f3f3f3f
const int MAXINT = 1010;
void Prim(int n, int c[][1010])
{
int cost = 0;
vector<int> route;
int lowcost[MAXINT];//i与它的邻接节点的边权
int closest[MAXINT];//i在S集合中的邻接节点
bool s[MAXINT];
s[1] = true;//是否被放入了S集
route.push_back(1);
for (int i = 2; i <= n; i++)
{
lowcost[i] = c[1][i];//其余节点与节点1之间的权
closest[i] = 1;//邻近节点,一开始S中只有节点1
s[i] = false;
}
for (int i = 1; i < n; i++)
{
int min = INF;
int j = 1;
for (int k = 2; k <= n; k++)
{
if ((lowcost[k] < min) && !s[k])
{
min = lowcost[k];
j = k;
}
}
s[j] = true;//放入集合S中
route.push_back(j);
//更新邻接节点和最小权
for (int k = 2; k <= n; k++)
{
if ((c[j][k] < lowcost[k]) && (!s[k])) {
lowcost[k] = c[j][k];
closest[k] = j;
}
}
cost += lowcost[j];
}
cout << cost << endl;
}
int main()
{
int c[MAXINT][MAXINT];
int N, M;
cin >> N >> M;
//初始化
for (int i = 1; i <= N; i++)
for (int j = 1; j <= N; j++)
c[i][j] = INF;
//更新权重
for (int i = 1; i <= M; i++)
{
int a, b, quan;
cin >> a >> b >> quan;
c[a][b] = c[b][a] = quan;
}
Prim(N, c);
return 0;
}