5
2
2015
0

CODEVS 1003 电话连线

//使用prim算法即可
#include <iostream>
#include <climits>
using namespace std;

int n,a[101][101],f[101],pre[101],s[101],t[101];
bool b[101];
int main()
{
	cin>>n;
	for (int i=1;i<=n;++i)
		for (int j=1;j<=n;++j) {
			cin>>a[i][j];
			a[j][i]=a[i][j];
		}
	for (int i=1;i<=n;++i) f[i]=INT_MAX/3;
	f[1]=0; int cnt=n,ans=0,m=0;
	while (cnt--) {
		int p,v=INT_MAX/3;
		for (int i=1;i<=n;++i)
			if (f[i]<v && !b[i]) {
				p=i;
				v=f[i];
			}
		ans+=v; f[p]=0; b[p]=1;
		if (v!=0 && p!=1) { //如果是非0边,则记录下来
			++m;
			s[m]=pre[p];
			t[m]=p;
		}
		for (int i=1;i<=n;++i)
			if (f[p]+a[p][i]<f[i]) {
				f[i]=f[p]+a[p][i];
				pre[i]=p; //更新pre[i]
			}
	}
	cout<<m<<endl;
	for (int i=1;i<=m;++i)
		if (s[i]<t[i]) cout<<s[i]<<' '<<t[i]<<endl;
		else cout<<t[i]<<' '<<s[i]<<endl;
	cout<<ans;
	return 0;
}
Category: 题解 | Tags: CODEVS 数据结构 MST

Host by is-Programmer.com | Power by Chito 1.3.3 beta | Theme: Aeros 2.0 by TheBuckmaker.com