【CF140C】New Year Snowmen

题目

题目链接:https://codeforces.com/problemset/problem/140/C
现在来做雪人,每个雪人由三个不同大小的雪球构成:一个大的,一个中等的,一个小的。现在有(n)个雪球半径分别为(r_1, r_2, ..., r_n)为了做雪人,三个雪球的大小必须两两不同。例如,半径分别为 (1,2,3) 的雪球可以做成雪人,但(2,2,3)(2,2,2)不行。现在需要尽可能做更多雪人。

思路

容易发现每次肯定是将最多的三个雪球拿出来。因为如果此时不拿最多的雪球,要么最后会剩余很多这种雪球,要么最终依然会使用这些雪球,所以可以先使用最多的。
优先队列维护即可。时间复杂度 (O(nlog n))

代码

#include <bits/stdc++.h>
#define mp make_pair
using namespace std;

const int N=100010;
int n,m,ans[N][3];
map<int,int> cnt;
priority_queue<pair<int,int> > q;

int main()
{
	scanf("%d",&n);
	for (int i=1,x;i<=n;i++)
	{
		scanf("%d",&x);
		cnt[x]++;
	}
	for (map<int,int>::iterator it=cnt.begin();it!=cnt.end();it++)
		q.push(mp((*it).second,(*it).first));
	while (q.size()>=3)
	{
		m++;
		pair<int,int> a=q.top(); q.pop();
		pair<int,int> b=q.top(); q.pop();
		pair<int,int> c=q.top(); q.pop();
		ans[m][0]=a.second; a.first--;
		ans[m][1]=b.second; b.first--;
		ans[m][2]=c.second; c.first--;
		if (a.first) q.push(a);
		if (b.first) q.push(b);
		if (c.first) q.push(c);
	}
	printf("%d
",m);
	for (int i=1;i<=m;i++)
	{
		sort(ans[i],ans[i]+3);
		printf("%d %d %d
",ans[i][2],ans[i][1],ans[i][0]);
	}
	return 0;
}
原文地址:https://www.cnblogs.com/stoorz/p/13865573.html