codeforces 899 E - Segments Removal(链表模拟)

题意:给你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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值