Online JudgeProblem SetAuthorsOnline ContestsUser
Web Board
Home Page
F.A.Qs
Statistical Charts
Problems
Submit Problem
Online Status
Prob.ID:
Register
Update your info
Authors ranklist
Current Contest
Past Contests
Scheduled Contests
Award Contest
User ID:
Password:
  Register

并查集+贪心水过……

Posted by YushengJiang at 2012-08-30 11:38:56 on Problem 1251
#include<iostream>
#include<algorithm>
using namespace std;
int father[28];
struct road{
	int from,to;
	int dist;
} roads[75];
int searchfather(int i){
	if (father[i]==i) return i;
	return father[i]=searchfather(father[i]);
}
bool cmp(road a,road b){
	return a.dist<b.dist;
}
int main (void){
	int n;
	cin>>n;
	while (n!=0){
		for (int i=0;i<n;++i) father[i]=i;
		int st,dis,m,rd=0;
		char a,b;
		for (int i=0;i<n-1;++i){
			cin>>a>>m;
			st=a-'A';
			for (int j=0;j<m;++j){
				cin>>b>>dis;
				roads[rd].from=st;
				roads[rd].to=b-'A';
				roads[rd].dist=dis;
				++rd;
			}
		}
		sort(&roads[0],&roads[rd],cmp);
		int pt=0,ct=0,tot=0;
		while (pt!=n-1){
			while (searchfather(roads[ct].from)==searchfather(roads[ct].to)) ++ct;
			father[searchfather(roads[ct].from)]=searchfather(roads[ct].to);
			tot+=roads[ct].dist;
			++pt;
			++ct;
		}
		cout<<tot<<endl;
		cin>>n;
	}
	return 0;
}

Followed by:

Post your reply here:
User ID:
Password:
Title:

Content:

Home Page   Go Back  To top


All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator