您的位置:首页 > 其它

poj 1456 supermarket

2011-11-29 16:32 225 查看
贪心+并查集

#include<stdio.h>
#include<stdlib.h> 
struct Product {
	int p, t;
}pro[10005];
int f[10005],n;
int compare(const void *m,const void *n)
{
	return (*(Product *)n).p-(*(Product *)m).p;
}
void init()
{
	for (int i = 0; i <10005; i++)
		f[i] = i;
}
int find(int i)
{
	if(f[i]!=i)
		f[i]=find(f[i]);
	return f[i];
}
void unionSet(int m,int n)
{
	int i=find(m);
	int j=find(n);
	f[i]=j;
}
int main() 
{
	while (scanf("%d",&n)!=EOF)
	{
		for (int i = 0; i < n; i++)
			scanf("%d%d",&pro[i].p,&pro[i].t);
		qsort(pro,n,sizeof(Product),compare);
		init();
		int sum=0;
		for(int i=0;i<n;i++)
		{
			int temp=find(pro[i].t);
			if(temp!=0)
			{
				sum+=pro[i].p;
				unionSet(temp,temp-1);
			}
		}
		printf("%d\n",sum);

	}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: