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

被折叠的 条评论
为什么被折叠?



