hdu 计算机学院大学生程序设计竞赛(2015’12)Happy Value(最大生成树)

Happy Value

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 1286    Accepted Submission(s): 380


Problem Description
In an apartment, there are N residents. The Internet Service Provider (ISP) wants to connect these residents with N – 1 cables. 
However, the friendships of the residents are different. There is a “Happy Value” indicating the degrees of a pair of residents. The higher “Happy Value” is, the friendlier a pair of residents is. So the ISP wants to choose a connecting plan to make the highest sum of “Happy Values”.
 

Input
There are multiple test cases. Please process to end of file.
For each case, the first line contains only one integer N (2<=N<=100), indicating the number of the residents.
Then N lines follow. Each line contains N integers. Each integer H ij(0<=H ij<=10000) in i th row and j th column indicates that i th resident have a “Happy Value” H ijwith j th resident. And H ij(i!=j) is equal to H ji. H ij(i=j) is always 0.
 

Output
For each case, please output the answer in one line.
 

Sample Input
   
   
   
   
2 0 1 1 0 3 0 1 5 1 0 3 5 3 0
 

Sample Output
   
   
   
   
1 8


思路:最小生成树,用负权值求最小生成树,最后再对结果取负值即可得到最大生成树。

#include <iostream>
#include<cstring>
#include <stdio.h>
using namespace std;
#define INF 65537
#define MAXN 105

int a[MAXN][MAXN];
int prim(int n){
    int ans=0,lowc[MAXN],vis[MAXN];
    memset(vis,0,sizeof(vis));
    vis[0]=1;
    for(int i=1;i<n;i++)
        lowc[i]=a[0][i];
    for(int i=1;i<n;i++){
        int minc=INF;
        int p=-1;
        for(int j=0;j<n;j++)
            if(!vis[j]&&minc>lowc[j]){
                minc=lowc[j];
                p=j;
            }
        if(minc==INF)return -1;
        ans+=minc;
        vis[p]=true;
        for(int j=0;j<n;j++)
            if(!vis[j]&&lowc[j]>a[p][j])
                lowc[j]=a[p][j];
    }
    return (-1*ans);
}
int main()
{
    int n;
    while(cin>>n)
    {
        for(int i=0;i<n;i++)
          for(int j=0;j<n;j++)
             {
                 cin>>a[i][j];
                 a[i][j]=-a[i][j];
             }
        cout<<prim(n)<<endl;
    }
}


你可能感兴趣的:(hdu 计算机学院大学生程序设计竞赛(2015’12)Happy Value(最大生成树))