140C. New Year Snowmen - Codeforces Solution C++

  Problem Link : 140C. New Year Snowmen 


✅ C++ Solution :

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

#define ll long long int

#define pp pair<ll,ll>
#define mp make_pair
#define pb push_back
int main()
{
	int n;
	cin>>n;
	ll x;
	unordered_map<ll,ll> ms;
	for(int i=1;i<=n;i++)
	{
		cin>>x;
		ms[x]++;
	}
	priority_queue<pp> pq;
	for(auto p : ms)
		pq.push(mp(p.second,p.first));

	pp a,b,c;
	vector< pair<ll,pair<ll,ll> > > ans;
	while(pq.size()>=3)
	{
		a=pq.top();
		pq.pop();
		b=pq.top();
		pq.pop();
		c=pq.top();
		pq.pop();
		ans.pb(mp(a.second,mp(b.second,c.second)));
		a.first--;
		b.first--;
		c.first--;
		if(a.first>0)
			pq.push(a);
		if(b.first>0)
			pq.push(b);
		if(c.first>0)
			pq.push(c);
	}
	cout<<ans.size()<<"\n";
	ll mn,mx,mid;
	for(auto it : ans)
	{
		mn=min(it.first,min(it.second.first,it.second.second));
		mx=max(it.first,max(it.second.first,it.second.second));
		if(it.first!=mn && it.first!=mx)
			mid=it.first;
		else if(it.second.first!=mn && it.second.first!=mx)
			mid=it.second.first;
		else
			mid=it.second.second;
		cout<<mx<<" "<<mid<<" "<<mn<<"\n";
	}


}

 

Thank you for your patience reading. If you enjoyed this post, I’d be very grateful if you’d help it spread by emailing it to a friend, or sharing it on Whatsapp or Facebook. 

😇Happy Learning!!