思路:
不必每次都找最小的值进行合并,从前往后扫一遍的过程中能合并就一直合并。
实现:
1 #include <bits/stdc++.h> 2 using namespace std; 3 typedef long long ll; 4 const int MAXN = 150005; 5 ll a[MAXN]; 6 int main() 7 { 8 int n; 9 while (cin >> n) 10 { 11 map<ll, int> mp; 12 for (int i = 0; i < n; i++) 13 { 14 cin >> a[i]; 15 if (mp.count(a[i])) 16 { 17 while (mp.count(a[i])) 18 { 19 a[mp[a[i]]] = -1; 20 mp.erase(a[i]); 21 a[i] <<= 1; 22 } 23 } 24 mp[a[i]] = i; 25 } 26 vector<ll> v; 27 for (int i = 0; i < n; i++) 28 { 29 if (a[i] != -1) v.push_back(a[i]); 30 } 31 cout << v.size() << endl; 32 for (int i = 0; i < v.size(); i++) cout << v[i] << " "; 33 cout << endl; 34 } 35 return 0; 36 }