题意:给你n个数,每次删除一段相同的数量最多的数,若有多个,则删除最左边。
题解:看了一下别人的代码发现可以用链表模拟一下,然后放进优先队列里跑一跑。
对于每一个删除了的就vis[true],有一种删除以后需要合并的情况,在队列里不是很好找左右两个区间,那么我们把右边的加到左边上去,右边的加一个使用过的标记,然后再扔进去新合成的左边,这样可以保证此时左边的一定是覆盖之前的(因为有一个vis标记并且数量多的在前面)
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <string>
#include <map>
#include <cmath>
#include <queue>
#include <set>
#define INF 0x3f3f3f3f
using namespace std;
const int maxn = 2e5 + 5;
typedef long long LL;
struct node{
int n;
int id;
node(){}
node(int nn, int idd):n(nn),id(idd){}
bool operator < (const node &p ) const{
if(n == p.n) return id > p.id;
return n < p.n;
}
};
int cost[maxn];
int num[maxn];
int PRE[maxn];
int NEXT[maxn];
bool vis[maxn];
priority_queue<node> P;
void init(){
memset(cost, 0, sizeof(cost));
memset(num, 0, sizeof(num));
memset(PRE, 0, sizeof(PRE));
memset(NEXT, 0, sizeof(NEXT));
memset(vis, false, sizeof(vis));
}
int main(){
init();
int n;
cin >> n;
int cnt = 0;
for(int i=1; i<=n; i++){
int x;
cin >> x;
if(x == cost[cnt]) num[cnt]++;
else{
cost[++cnt] = x;
num[cnt]++;
}
}
for(int i=1; i<=cnt; i++){
node temp(num[i],i);
P.push(temp);
PRE[i] = i-1;
NEXT[i] = i+1;
}
int ans = 0;
while(cnt > 0){
node temp;
while(true){
node temp2 = P.top();
P.pop();
if(!vis[temp2.id]){
temp = temp2;
break;
}
}
cnt--;
ans++;
int id = temp.id;
vis[id] = true;
int ppid = PRE[id];
int nnid = NEXT[id];
if(cost[ppid] == cost[nnid]){
vis[nnid] = true;
num[ppid] += num[nnid];
NEXT[ppid] = NEXT[nnid];
PRE[NEXT[nnid]] = ppid;
P.push(node(num[ppid],ppid));
cnt--;
}
else{
NEXT[ppid] = nnid;
PRE[nnid] = ppid;
}
}
cout << ans << endl;
}