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

PE的不行了,咋回事》?

Posted by dynamic_study at 2009-07-16 17:06:09 on Problem 2377 and last updated at 2009-07-16 17:07:00
#include<iostream>
using namespace std;
#define maxn 3000
struct node
{
       int beg, end, weight;
} edge[maxn];
int cmp(const void *a,const void *b)
{
     struct node *aa=(node *)a;
     struct node *bb=(node *)b;
     return(((aa->weight)<(bb->weight))?1:-1);
}

int uset[maxn];
int root(int v)
{
    if(uset[v]==v)
		return v;
    else
    {
        uset[v]=root(uset[v]);
        return uset[v];
    }
}
bool same(int a, int b)
{
    return root(a)==root(b);
}
void unite(int a,int b)
{
    if(same(a,b)) return;
    uset[uset[b]]=uset[a];
}

void kruskal(int N,int E)
{
    qsort(edge, E,sizeof(edge[0]), cmp);
    int i, ct(0);
    for(i=0; i<=N;i++)
       uset[i] = i;
    int ans=0;
    for(i=0;i<E;i++)
    {
        if(same(edge[i].beg, edge[i].end) )
			continue;
        ct++;
        if(ct==N) break;
        unite(edge[i].beg, edge[i].end);
        ans+=edge[i].weight;
    }   
    cout<<ans<<endl;
}
int main()
{
	int node[maxn];
	int m,n,i,a,b;
	int c;
	cin>>m>>n;
	memset(node,0,sizeof(node));
	for(i=0;i<n;i++)
	{
		cin>>a>>b>>c;
        node[a]++;
		node[b]++;
		edge[i].beg=a;
		edge[i].end=b;
		edge[i].weight=c;
		
	}
    for(i=1;i<=m;i++)
	{
		if(node[i]==0)
		{
			cout<<"-1"<<endl;
		    return 0;
		}
	}
	kruskal(m,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