杭电ACM计算机学院大学生程序设计竞赛(2015’12)1004(最大生成树)

题目:

Happy Value

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


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 Hij(0<=Hij<=10000) in ith row and jth column indicates that ith resident have a “Happy Value” Hij with jth resident. And Hij(i!=j) is equal to Hji. Hij(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
题目大意:给出一个矩阵,矩阵上的值hij代表i和j之间的happy值,要求将所有点连起来,并且使happy值最大。

解题思路:最小生成树的变形:最大生成树。

AC代码:

#include <iostream>
#include <cstring>
using namespace std;
#define inf -2000000;
int matrix[105][105];
int n;
int prim()
{
	bool visit[105];
	int result=0;
	int p[105];
	for(int i=1;i<=n;i++)
		p[i] = matrix[1][i];
	memset(visit,0,sizeof(visit));
	visit[1] = 1;
	for(int i=1;i<n;i++)
	{
		int max = inf;
		int index = 0;
		for(int j=1;j<=n;j++)
		{
			if(p[j]>max&&visit[j]==0)
			{
//				cout<<"p[j]"<<p[j]<<" "<<"max"<<" "<<max<<endl;
				max = p[j];
				index = j;		
			}
		}
		result+=p[index];
//		matrix[i][index] = matrix[index][i] = 0;
//		cout<<p[index]<<endl;
		visit[index] = 1;
		for(int j=1;j<=n;j++)
		{
			if(!visit[j])
			p[j] = matrix[index][j]>p[j]?matrix[index][j]:p[j];
		}
	}
	return result;
}
int main()
{
	while(cin>>n)
	{
		for(int i=1;i<=n;i++)
		{
			for(int j=1;j<=n;j++)
			{
				cin>>matrix[i][j];
			}
		}
		cout<<prim()<<endl;		
	}
	return 0;
}
有两个要点:第一是在外层循环中只能循环n-1次,第二是要在进循环之前使visit数组的第一个元素为true,开始没注意到,在这里卡了很久…………

你可能感兴趣的:(算法,ACM,杭电)