题目链接网站:http://codeforces.com/problemset/problem/962/D
优先队列暴力,每次从末尾取出两个数,看看这两个数是否相同,如果相同,合并之后再放进队列中,如果不同,把队尾的那个元素放进另外一个数组中,即答案
代码如下:
#include <bits/stdc++.h>
using namespace std;
const int Maxn = 1e5 + 5e4 + 2000;
struct node {
long long x;
int id ;
friend bool operator < (node a, node b) {
if(a.x == b.x ) return a.id > b.id;
return a.x > b.x;
}
};
priority_queue <node>q;
struct node1 {
long long x;
int id;
} G[Maxn];
bool cmp(struct node1 a,struct node1 b) {
return a.id < b.id;
}
int main() {
int n,cnt;
while(~scanf("%d",&n)) {
cnt = 0;
node s;
for(int i = 0; i < n; i++) {
cin >> s.x ;
s.id = i;
q.push(s);
}
while(!q.empty()) {
if(q.size() == 1) {
node d = q.top();
q.pop();
node1 dd;
dd.x = d.x;
dd.id = d.id;
G[cnt++] = dd;
} else {
node d = q.top();
q.pop();
node dd = q.top();
q.pop();
if(d.x == dd.x) {
dd.x *= 2;
q.push(dd);
} else {
node1 d1;
d1.x = d.x;
d1.id = d.id;
G[cnt++] = d1;
q.push(dd);
}
}
}
sort(G,G +cnt,cmp);
cout << cnt << endl;
for(int i = 0; i < cnt; i++) {
printf("%lld%c",G[i].x,i == cnt - 1?'\n':' ');
}
}
return 0;
}