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].
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.
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.
7 3 4 1 2 2 1 1
4 3 8 2 1
5 1 1 3 1 1
2 3 4
5 10 40 20 50 30
5 10 40 20 50 30
The first two examples were considered in the statement.
In the third example all integers in the given array are distinct, so it will not change.
题意:给一串数字,如果有两个数字相同,将前一个数字乘二,并删除后一个数字。要求输出最后状态的时候有多少个数字,并依次输出这些数字。
思路:使用两个优先队列,优先队列一按照序号从小到大排列,优先队列二存储初始状态的数字串,按照数字从小到大排列,数字相同的按照序号从小到大排列。每次取出队列中两个元素,比较大小,如果不相等的话把第一个元素放进优先队列一,第二个元素重新放进优先队列二。如果相等的话,把第一个元素乘2重新放入优先队列二,第二个元素弃掉。
最后把优先队列一中的元素全部输出即可。
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<queue>
using namespace std;
struct node1
{
long long num,id;
bool operator<(const node1 &a)const
{
if(a.num==num)
return a.id<id;
return a.num<num;
}
};
struct node2
{
long long num,id;
bool operator<(const node2 &a)const
{
return a.id<id;
}
};
priority_queue<node1> Q1;
priority_queue<node2> Q2;
int main()
{
int n,i;
while(scanf("%d",&n)!=EOF)
{
node1 p,q;
node2 t;
for(i=1;i<=n;i++)
{
scanf("%I64d",&p.num);
p.id=i;
Q1.push(p);
}
while(!Q1.empty())
{
if(Q1.size()==1)
{
p=Q1.top();
Q1.pop();
t.num=p.num;
t.id=p.id;
Q2.push(t);
break;
}
p=Q1.top();
Q1.pop();
q=Q1.top();
Q1.pop();
if(p.num==q.num)
{
if(q.id>p.id)
{
q.num*=2;
Q1.push(q);
}
else
{
p.num*=2;
Q1.push(p);
}
}
else
{
t.num=p.num;
t.id=p.id;
Q2.push(t);
Q1.push(q);
}
}
printf("%d\n",Q2.size());
while(!Q2.empty())
{
t=Q2.top();
Q2.pop();
printf("%I64d ",t.num);
}
printf("\n");
}
return 0;
}