LibreOJ #10008. 「一本通 1.1 练习 4」家庭作业 题解

原题地址

定睛一看,!这和前面例题一样罢,然后反手敲了个 O ( n t ) O(nt) 的贪心,可惜没看数据范围… 80 p t s 80pts ,还以为是要卡常…
然后才发现需要用并查集优化。
首先是先把价值从大到小排序,然后瞎搞。
C o d e \color{blue}Code

# include <bits/stdc++.h>
using namespace std;
const int N=1e6+10;
int n;
struct node
{
	int t,fen;
}a[N];
int f[N];
int maxl=-1;
bool cmp(struct node x,struct node y) 
{
	return x.fen>y.fen;
}
int find(int x) 
{
	if(f[x]!=x) return f[x]=find(f[x]);
	return f[x];
}
inline int read(void) 
{
	int s=0,w=1;
	char ch=getchar();
	while(!isdigit(ch)) 
	{
		if(ch=='-') w=-1;
		ch=getchar();
	}
	while(isdigit(ch)) 
	{
		s=(s<<1)+(s<<3)+ch-'0';
		ch=getchar();
	}
	return s*w;
}
int main(void) 
{
	n=read();
	for(int i=1;i<=n;i++) 
	{
		a[i].t=read(),a[i].fen=read();
		maxl=max(maxl,a[i].t);
	}
	sort(a+1,a+n+1,cmp);
	for(int i=1;i<=maxl;i++) f[i]=i;
	int tot=0;
	for(int i=1;i<=n;i++)
	{
		int _find=find(a[i].t);
		if(_find) 
		{
			tot+=a[i].fen;
			f[_find]=_find-1;
		}
	}
	printf("%d\n",tot);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/woshidalaocxy/article/details/105621459