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

ac

Posted by 940111490 at 2015-09-14 23:04:11 on Problem 1679
//问最小生成树是否唯一 
#include<stdio.h>
#include<string.h>
#include<algorithm>
#define INF 0x3f3f3f3f 
using namespace std;
struct node 
{
	int x;
	int y;
	int len;
}num[100000];
bool cmp(node a,node b)
{
	return a.len<b.len;
}
int mincost=0;
int p;
int f[1000];
int r[1000];
int a[1000];
int find(int n)
{
    if(f[n]==n)
        return n;
    else
        f[n]=find(f[n]);
    return f[n];
}
int UU(int x,int y)
{
	int xa;
	int ya;
	xa=find(x);
	ya=find(y);
	if(xa==ya)
	{
		return 0;
	}
	else if(r[xa]<=r[ya])
	{
		f[xa]=ya;
		r[ya]+=r[xa];
	}
	else
	{
		f[ya]=xa;
		r[xa]+=r[ya];
	}
	return 1;
}
int ki(int n,int m)
{
	mincost=0;
	int temp=INF;
	p=0;
	int i,j;
	for(i=1;i<=n;i++)
	{
		f[i]=i;
		r[i]=1;
	}
	for(i=1;i<=m;i++)
	{
		scanf("%d%d%d",&num[i].x,&num[i].y,&num[i].len);
	}
	sort(num+1,num+1+m,cmp);
	int num1=0;
	for(i=1;i<=m;i++)
	{
		if(UU(num[i].x,num[i].y))
		{
			num1++;
			p++;
			a[p]=i;
			mincost+=num[i].len;
		}
		if(num1==n-1)
		break;
	}
	int scost;
	for(i=1;i<=n-1;i++)
	{
		scost=0;
		num1=0;
		for(j=1;j<=n;j++)
		{
			f[j]=j;
			r[j]=1;
		}
		for(j=1;j<=m;j++)
		{
			if(j==a[i])
			{
				continue;
			}
			if(UU(num[j].x,num[j].y))
			{
				scost+=num[j].len;
				num1++;
			}
			if(num1==n-1)
			{
				break;
			}
		}
		if(num1==n-1&&scost<temp)
		temp=scost;
	}
	if(temp==mincost)
	return 0;
	else
	return 1;
}
int main()
{
	int T;
	scanf("%d",&T);
	while(T--)
	{
		int i;
		int j;
		scanf("%d%d",&i,&j);
		if(ki(i,j))
		{
			printf("%d\n",mincost);
		}
		else
		{
			printf("Not Unique!\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