Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 56603 | Accepted: 23473 |
Description
Farmer John ordered a high speed connection for his farm and is going to share his connectivity with the other farmers. To minimize cost, he wants to lay the minimum amount of optical fiber to connect his farm to all the other farms.
Given a list of how much fiber it takes to connect each pair of farms, you must find the minimum amount of fiber needed to connect them all together. Each farm must connect to some other farm such that a packet can flow from any one farm to any other farm.
The distance between any two farms will not exceed 100,000.
Input
Output
Sample Input
4 0 4 9 21 4 0 8 17 9 8 0 16 21 17 16 0
Sample Output
28
解题思路:很简单的一道模板题用prime和kruskal应该都可以这个题是prime
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int MAXN = 105;
const int INF = 0x3f3f3f3f;
int cost[MAXN][MAXN];
int minCost[MAXN];
bool used[MAXN];
int N;
int prime()
{
memset(minCost, INF, sizeof(minCost));
memset(used, false, sizeof(used));
for(int i = 0; i < N; i++){
minCost[i] = cost[0][i];
}
used[0] = true;
minCost[0] = 0;
int ret = 0;
while(true){
int v = -1;
for(int i = 0; i < N; i++){
if(!used[i] && (v == -1 || minCost[v] > minCost[i])){
v = i;
}
}
if(v == -1)
break;
used[v] = 1;
ret += minCost[v];
for(int i = 0; i < N; i++){
// if(!used[i])
{
minCost[i] = min(minCost[i], cost[v][i]);
}
}
}
return ret;
}
int main()
{
while(~scanf("%d", &N))
{
for(int i = 0; i < N; i++){
for(int j = 0; j < N; j++){
scanf("%d", &cost[i][j]);
}
}
int d = prime();
cout << d << endl;
}
return 0;
}