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

TLE求救啊 各位大侠留步啊。。。。

Posted by 1106100214 at 2012-04-03 22:06:52 on Problem 3723
#include<iostream>
#include<algorithm>
struct relation //所谓"relationship"
{
	int x,y,d;
};
struct set  //查并集节点的类
{
	set *root;
	int rank;
	set();
	set* find();
	void operator>>(set&);
};
set::set() //构造函数
{
	root=this;
	rank=0;
}
set* set::find()  //查找根
{
	set *p,*i,*j;
	
	for(p=this;p->root!=p;p=p->root);
	for(i=this;i!=p;i=j)
	{
		j=i->root;
		i->root=p;
	}
	return p;
}
void set::operator>>(set &a)  //合并
{
	if(find()->rank==a.find()->rank)
	{
		find()->root=a.find();
		a.find()->rank++;
	}
	else if(find()->rank>a.find()->rank)
	{
		a.find()->root=find();
	}
	else
	{
		find()->root=a.find();
	}
	return;
}
bool comp(relation &a,relation &b)  //排序比较
{
	return a.d>b.d;
}
int main()
{
	int cases,N,M,R,i,total,rn;  //rn用来标记已经使用的"关系"的个数
	set *sets;        //查并集节点数组,数量不定
	relation *rs;
	std::cin>>cases;
	while(cases--)
	{
		
		//初始化
		std::cin>>N>>M>>R;
		sets=new set[N+M];
		rs=new relation[R];
		for(i=0;i<R;i++)
		{
			std::cin>>rs[i].y>>rs[i].x>>rs[i].d;
			rs[i].x+=N;
		}
		std::sort(rs,rs+R,comp);//排序

		//计算
		total=10000*(M+N);
		rn=0;
		for(i=0;(rn<M+N)&&(i<R);i++)//或已使用足够数量的"关系"或没有"关系"可用
		{
			//根节点不同,合并起来,贪污掉俩人"关系"
			if(sets[rs[i].x].find()!=sets[rs[i].y].find())
			{
				sets[rs[i].x]>>sets[rs[i].y];
				total-=rs[i].d;
				rn++;
			}
		}

		//输出并为下一个case做准备
		std::cout<<total<<std::endl;
		delete sets;
		delete rs;
	}
	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