Educational Codeforces Round 42D. Merge Equals(STL)

D. Merge Equals
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

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, 2x2⋅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 (2n1500002≤n≤150000) — the number of elements in the array.

The second line contains a sequence from nn elements a1,a2,,ana1,a2,…,an (1ai1091≤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
Copy
7
3 4 1 2 2 1 1
output
Copy
4
3 8 2 1
input
Copy
5
1 1 3 1 1
output
Copy
2
3 4
input
Copy
5
10 40 20 50 30
output
Copy
5
10 40 20 50 30
Note

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.

题意:给出n个数,接下来对这个数列进行一个操作,即从左往右找最小的两个相同的数,然后将左边那个删除,右边那个数的值乘以2。不断进行以上操作,直到无相同的数为止,输出最终那个数列。

思路:

map中套一个set的操作,mp[i]指的是值为i的数字的下标合集。从小到大的遍历mp,如果有两个,则将其合并为一个放到2*i的集合中去。如果仅含一个元素,记录其的位置即可。

代码:

 1 #include <bits/stdc++.h>
 2 
 3 using namespace std;
 4 typedef long long ll;
 5 const int maxn = 2e6+100;
 6 ll n;
 7 ll a[maxn];
 8 map<ll, set<ll> >mp;
 9 ll b[maxn];
10 int main()
11 {
12     scanf("%I64d",&n);
13     for(int i=1;i<=n;i++)
14     {
15         scanf("%I64d",&a[i]);
16         mp[a[i]].insert((ll)i);
17     }
18     ll ans=0;
19     for (auto it: mp)
20     {
21         while(it.second.size()>=2)
22         {
23             it.second.erase(it.second.begin());
24             mp[it.first*2].insert(*it.second.begin());
25             it.second.erase(it.second.begin());
26         }
27         if(it.second.size()==1)
28         {
29             int id=*it.second.begin();
30             b[id]=it.first;
31             ans++;
32         }
33     }
34     printf("%I64d\n",ans);
35     for(int i=1;i<=n;i++) if(b[i]>0) printf("%I64d ",b[i]);
36     return 0;
37 }

 

posted @ 2018-04-19 19:05  thges  阅读(156)  评论(0编辑  收藏  举报