Codeforce962D(暴力优先队列)

本文介绍了一个名为MergeEquals的算法实现过程,该算法针对一个正整数数组进行操作,当数组中存在至少两个相等元素时,选取最小重复值x,移除左起第一个x,并将相邻的另一个x替换成两者的和,直至无法再执行此操作。文章通过C++代码展示了具体的实现细节。

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 x that occurs in the array 2or more times. Take the first two occurrences of x 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
Determine how the array will look after described operations are performed.

#include <iostream>
#include <fstream>
#include <cstdio>
#include <cstring>
#include <queue>
#include <stack>
#include <vector>
#include <map>
#include <set>
#include <cmath>
#include <algorithm>
#include <functional>
#define inf 1000000000
using namespace std;
typedef long long ll;
const int MAXN=1e9+10;
const int MAX=2e5+10;
const double eps=1e-6;

int n;
struct NODE{
    ll data,id;
    NODE(ll a,ll b):data(a),id(b){};
    NODE(){};
    friend operator<(NODE a,NODE b){
        if(a.data==b.data)
            return a.id>b.id;
        else
            return a.data>b.data;
    }
};

priority_queue<NODE>q;

int cmp(NODE a,NODE b){
    return a.id<b.id;
}

int main(){
    #ifdef ONLINE_JUDGE
    #else
    freopen("in.txt","r",stdin);
    //freopen("output.txt","w",stdout);
    #endif
//cout<<"*"<<endl;

    cin>>n;
    ll t;
    for(ll i=1;i<=n;i++){
        scanf("%lld",&t);
        NODE temp(t,i);
        q.push(temp);
    }

    int cnt=0;
    NODE ans[MAX];
    while(q.size()){
        NODE a=q.top();q.pop();
        if(q.size()==0||a.data!=(q.top()).data){
            ans[cnt++]=a;
            continue;
        }
        NODE b=q.top();q.pop();
        //cout<<2*a.data<<endl;
        NODE temp(2*a.data,b.id);
        q.push(temp);
    }
    sort(ans,ans+cnt,cmp);
    cout<<cnt<<endl;
    for(int i=0;i<cnt;i++){
        cout<<ans[i].data<<" ";
    }cout<<endl;


    return 0;
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值