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 hzoi_hexing at 2014-01-18 21:26:24 on Problem 1258
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<iostream>
#include<algorithm>
#include<cmath>
using namespace std;
#define N 150
#define M 21000
int n;
struct arr{
	int ff,tt,ww;
}c[M];
int r[M];
int f[N];
int tot = 0;
inline void add(int x,int y,int z){
	c[++tot].ff = x;
	c[tot].tt = y;
	c[tot].ww = z;
	return;
}

bool comp(const int a,const int b){
	return c[a].ww < c[b].ww;
}

int find(int x){
	return f[x] == x ? x:f[x] = find(f[x]);
}

int kruscal(){
	int ans = 0;
	for (int i = 1; i<=n; i++) f[i] = i;
	for (int i = 1; i<=tot; i++) r[i] = i;
	sort(r + 1,r + 1 + tot,comp);
	for (int i = 1; i<=tot; i++){
		int y = r[i];
		int fx = find(c[y].ff);
		int fy = find(c[y].tt);
		if (fx != fy){
			ans += c[y].ww;
			f[fx] = fy;
		}
	}
	return ans;
}

int main(){
	while (scanf("%d",&n) != EOF){
		int w;
		memset(c,0,sizeof(c));
		for (int i = 1; i<=n; i++){
			for (int j = 1; j<=n; j++){
				scanf("%d",&w);
				if (i < j) add(i,j,w);
			}
		}
		printf("%d\n",kruscal());
	}
	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