POJ1258 Agri-Net(Prim)

Agri-Net
Time Limit: 1000MS   Memory Limit: 10000K
Total Submissions: 51685   Accepted: 21558

Description

Farmer John has been elected mayor of his town! One of his campaign promises was to bring internet connectivity to all farms in the area. He needs your help, of course.
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

The input includes several cases. For each case, the first line contains the number of farms, N (3 <= N <= 100). The following lines contain the N x N conectivity matrix, where each element shows the distance from on farm to another. Logically, they are N lines of N space-separated integers. Physically, they are limited in length to 80 characters, so some lines continue onto others. Of course, the diagonal will be 0, since the distance from farm i to itself is not interesting for this problem.

Output

For each case, output a single integer length that is the sum of the minimum length of fiber required to connect the entire set of farms.

Sample Input

4
0 4 9 21
4 0 8 17
9 8 0 16
21 17 16 0

Sample Output

28
【题意】有n个农场,已知这n个农场都互相相通,有一定的距离,现在每个农场需要装光纤,问怎么安装光纤能将所有农场都连通起来,
并且要使光纤距离最小,输出安装光纤的总距离 【分析】又是一个最小生成树,因为给出了一个二维矩阵代表他们的距离,直接算prim就行了
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <algorithm>
#include <climits>
#include <cstring>
#include <string>
#include <set>
#include <map>
#include <queue>
#include <stack>
#include <vector>
#include <list>
#include<functional>
#define mod 1000000007
#define inf 0x3f3f3f3f
#define pi acos(-1.0)
using namespace std;
typedef long long ll;
const int N=105;
const int M=15005;
int n,m,k,edg[N][N],lowcost[N],pre[N];
void Prim() {
  for(int i=1;i<=n;i++){
    lowcost[i]=edg[1][i];
  }
  lowcost[1]=-1;
  int sum=0;
  for(int i=1;i<n;i++){
      int minn=inf;
      for(int j=1;j<=n;j++){
        if(lowcost[j]!=-1&&lowcost[j]<minn){
            minn=lowcost[j];
            k=j;
        }
      }sum+=minn;
      lowcost[k]=-1;
      for(int j=1;j<=n;j++){
        if(edg[j][k]<lowcost[j]){
            lowcost[j]=edg[j][k];
        }
      }
  }
  printf("%d
",sum);
}
int main() {
    while(~scanf("%d",&n)) {
            memset(edg,0,sizeof(edg));
    memset(lowcost,0,sizeof(lowcost));
        for(int i=1; i<=n; i++) {
          for(int j=1;j<=n;j++){
            scanf("%d",&edg[i][j]);
          }
        }
        Prim();
    }
    return 0;
}
View Code
原文地址:https://www.cnblogs.com/jianrenfang/p/5731895.html