D. Merge Equals
You are given an array of positive integers. While there are at least two equal elements, we will perform the following operation. We choose the smallest value xx that occurs in the array 22 or more times. Take the first two occurrences of xx in this array (the two leftmost occurrences). Remove the left of these two occurrences, and the right one is replaced by the sum of this two values (that is, 2⋅x2⋅x).
Determine how the array will look after described operations are performed.
For example, consider the given array looks like [3,4,1,2,2,1,1][3,4,1,2,2,1,1]. It will be changed in the following way: [3,4,1,2,2,1,1] → [3,4,2,2,2,1] → [3,4,4,2,1] → [3,8,2,1][3,4,1,2,2,1,1] → [3,4,2,2,2,1] → [3,4,4,2,1] → [3,8,2,1].
If the given array is look like [1,1,3,1,1][1,1,3,1,1] it will be changed in the following way: [1,1,3,1,1] → [2,3,1,1] → [2,3,2] → [3,4][1,1,3,1,1] → [2,3,1,1] → [2,3,2] → [3,4].
Input
The first line contains a single integer nn (2≤n≤1500002≤n≤150000) — the number of elements in the array.
The second line contains a sequence from nn elements a1,a2,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109) — the elements of the array.
Output
In the first line print an integer kk — the number of elements in the array after all the performed operations. In the second line print kkintegers — the elements of the array after all the performed operations.
Examples
input
7 3 4 1 2 2 1 1
output
4 3 8 2 1
input
5 1 1 3 1 1
output
2 3 4
input
5 10 40 20 50 30
output
5 10 40 20 50 30
#include<cstdio>
#include<queue>
#include<algorithm>
using namespace std;
typedef long long ll;
const int maxn = 1e6;
struct node{
ll num;int weizhi;
friend bool operator < (const node &x,const node &y){
if(x.num==y.num) return x.weizhi>y.weizhi;
else return x.num>y.num;
}
}r,a,b,s[maxn];
priority_queue<node> que;
bool cmp(node x,node y){
return x.weizhi<y.weizhi;
}
int main(){
int n;
scanf("%d",&n);
for(int i = 1;i <= n;i++){
scanf("%lld",&r.num);
r.weizhi = i;
que.push(r);
}
int k = 0;
while(!que.empty()){
a = que.top();que.pop();
if(que.empty()) {s[k].num = a.num;s[k++].weizhi = a.weizhi;break;}
b = que.top();que.pop();
if(a.num==b.num) b.num *= 2;
else s[k].num = a.num,s[k++].weizhi = a.weizhi;
que.push(b);
}
sort(s,s+k,cmp);
printf("%d\n",k);
for(int i = 0;i < k;i++){
if(i == 0) printf("%lld",s[i].num);
else printf(" %lld",s[i].num);
}
return 0;
}
本文介绍了一种对包含正整数的数组进行特定操作的算法,该操作会将两个相等的最小元素合并成一个两倍于原数值的新元素,直至无法再进行合并。通过实例演示了操作流程,并提供了一个实现该算法的C++代码示例。
379

被折叠的 条评论
为什么被折叠?



