您的位置:首页 > 其它

[CodeForces - 140C New Year Snowmen] 贪心 + STL 优先队列

2016-08-03 22:27 465 查看

[CodeForces - 140C New Year Snowmen] 贪心 + STL 优先队列

题目链接[CodeForces - 140C New Year Snowmen]  
题意: 给定N个数(1 ≤ n ≤ 105),问最多能够选出多少个三元组满足(a,
b, c) 满足(a < b < c)。
分析:贪心。每次都是从N个数中选出出现次数最多三个不同的数,一定是最优的。因为这样最多的不先选取会可能取不完。比如下面的测试数据。当大小为 a 数选完了, 便将它从优先队列中删除。
测试数据
10

1 2 2 2 2 3 3 4 4 4

#include <set>
#include <cmath>
#include <queue>
#include <vector>
#include <cstdio>
#include <string>
#include <cstring>
#include <iomanip>
#include <iostream>
#include <algorithm>
using namespace std;

//#pragma comment(linker, "/STACK:1024000000,1024000000")

#define FIN             freopen("input.txt","r",stdin)
#define FOUT            freopen("output.txt","w",stdout)
#define fst             first
#define snd             second
#define lson            l, mid, rt << 1
#define rson            mid + 1, r, rt << 1 | 1

typedef __int64  LL;
//typedef long long LL;
typedef unsigned int uint;
typedef pair<int, int> PII;

const int MAXN = 1e5 + 5;

struct Node {
int a, b, c;
Node () {}
Node (int a, int b, int c) : a (a), b (b), c (c) {}
};
vector<Node> res;
int N;
int R[MAXN];
priority_queue<PII> Q;

int main() {
#ifndef ONLINE_JUDGE
FIN;
#endif // ONLINE_JUDGE
while (~scanf ("%d", &N) ) {
PII top;
res.clear();
for (int i = 0; i < N; i++) {
scanf ("%d", &R[i]);
}
sort (R, R + N);
for (int i = 0, cnt; i < N; i++) {
cnt = 1;
while (i + 1 < N && R[i + 1] == R[i]) cnt ++, i++;
Q.push (make_pair (cnt, R[i]) );
}
PII tp[3];
int x[3];
while (!Q.empty() ) {
bool finish = false;
for (int i = 0; i < 3; i++) {
if (Q.empty() ) {
finish = true;
break;
}
tp[i] = Q.top();
Q.pop();
}
if (finish) continue;
for (int i = 0; i < 3; i++) {
x[i] = tp[i].snd;
tp[i].fst --;
if (tp[i].fst) Q.push (tp[i]);
}
sort (x, x + 3);
res.push_back (Node (x[0], x[1], x[2]) );
}
int tot = res.size();
printf ("%d\n", tot);
for (int i = 0; i < tot; i++) {
printf ("%d %d %d\n", res[i].c, res[i].b, res[i].a);
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: