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

本文详细介绍了最大生成树的概念及其求解方法,通过最小生成树的变形思想,使用Prim算法实现最大生成树的计算过程。具体展示了算法实现细节及输入输出样例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:

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,开始没注意到,在这里卡了很久…………

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值