题解 CF962D 【Merge Equals】

· · 题解

用map记录每个数值出现的上一次下标 在枚举到a_i时,看一下map以前有没有a_i这个值,没有就把下标存进去 有的话就取出以前的那个下标,抹掉,自己翻倍,然后重复这个过程

可能你会疑惑,这里不是按照从小到大消除的,是一旦出现就消除,为什么对了呢?

因为这两个相同的数在最左边,迟早要消掉,与顺序无关
#include <bits/stdc++.h>
using namespace std;
#define int long long
const int maxn=2e5+10;
int n,a[maxn],s;
map<int,int>m;
signed main()
{
    cin >> n;
    int s=n;
    for(int i=1;i<=n;i++)
    {
        cin >> a[i];
        if( m[ a[i] ] )
        {
            while( m[ a[i] ])
            {
                int index = m[ a[i] ];
                a[index]=0,s--,m[ a[i] ] =0;//清空
                a[i] = 2*a[i];
            }
            m[ a[i] ]=i;
        }   
        else    m[ a[i] ]=i;
    }
    cout<<s<<endl;
    for(int i=1;i<=n;i++)
        if( a[i] )  cout<<a[i]<<" ";
}