杭電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;
}
には2つのポイントがあります.1つ目は外層サイクルでn-1回しかサイクルできないこと、2つ目はサイクルに入る前にvisit配列の最初の要素をtrueにすることです.最初は気づかなかったのですが、ここで長い間詰まっていました.......