1. 程式人生 > >New Year Snowmen(貪心)

New Year Snowmen(貪心)

As meticulous Gerald sets the table and caring Alexander sends the postcards, Sergey makes snowmen. Each showman should consist of three snowballs: a big one, a medium one and a small one. Sergey’s twins help him: they’ve already made n snowballs with radii equal to r1, r2, …, rn. To make a snowman, one needs any three snowballs whose radii are pairwise different. For example, the balls with radii 1, 2 and 3 can be used to make a snowman but 2, 2, 3 or 2, 2, 2 cannot. Help Sergey and his twins to determine what maximum number of snowmen they can make from those snowballs.

Input
The first line contains integer n (1 ≤ n ≤ 105) — the number of snowballs. The next line contains n integers — the balls’ radii r1, r2, …, rn (1 ≤ ri ≤ 109). The balls’ radii can coincide.

Output
Print on the first line a single number k — the maximum number of the snowmen. Next k lines should contain the snowmen’s descriptions. The description of each snowman should consist of three space-separated numbers — the big ball’s radius, the medium ball’s radius and the small ball’s radius. It is allowed to print the snowmen in any order. If there are several solutions, print any of them.

Examples
Input
7
1 2 3 4 5 6 7
Output
2
3 2 1
6 5 4
Input
3
2 2 3
Output
0

整理部落格才發現,這一週的題目和c++ stl函式庫關聯很大,說實在的,好好利用真的很節省時間。
題目大意就是給你一串數然後找能夠找出多少個由大到小的三個數。(好繞口)
本意上就是一個貪心了。出現次數多的就要多次利用,利用優先佇列先進先出的特性。把出現次數多的數字排在前面。首先還應該對資料離散化。用到map函式,好懵逼。
程式碼如下:

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

map<int,int>::iterator it;//map函式it指標
const int maxx=1e5+10;
struct node{
	int k,v;
	node(int _v, int _k):v(_v),k(_k){}
    bool operator <(const node &r)const {
        return k < r.k;
    }
};

map<int, int> mp;
priority_queue<node> que;//優先佇列和結構體的結合。
int a[maxx];
int b[maxx];
int c[maxx];
int n;

int main()
{
	cin>>n;
	for(int i=0;i<n;i++)
	{
		int x;
		cin>>x;
		mp[x]++;
	}
	for(it=mp.begin();it!=mp.end();it++)
	{
		que.push(node(it->first,it->second));
	}
	if(que.size()<3) cout<<0<<endl;
	else
	{
		int k=0;
		while(que.size()>=3)
		{
			node xx=que.top();que.pop();
			node yy=que.top();que.pop();
			node zz=que.top();que.pop();
			a[k]=xx.v;b[k]=yy.v;c[k++]=zz.v;
			xx.k--;yy.k--;zz.k--;
			if(xx.k) que.push(xx);
			if(yy.k) que.push(yy);
			if(zz.k) que.push(zz);
		}
		cout<<k<<endl;
		for(int i=0;i<k;i++)
		{
			if(a[i]<b[i]) swap(a[i],b[i]);
			if(a[i]<c[i]) swap(a[i],c[i]);
			if(b[i]<c[i]) swap(b[i],c[i]);
			cout<<a[i]<<" "<<b[i]<<" "<<c[i]<<endl;
 		}
	}
}

努力加油a啊,(o)/~