题解 T353591 孤独摇滚

· · 个人记录

思路 1:

单调栈模拟弦,每次将一个值压入栈,若栈顶的值比他大,则弹出栈顶(模拟松开手指),再把值压入栈(模拟按下手指)。
时间复杂度为 O(n)。

思路 2:

优先队列模拟弦,每次将一个值加入优先队列,若队首的值比他大,则弹出队头,再把值加入队列。
时间复杂度为 O(n\log n)。

因为不同的弦互不影响,因此对于不同的弦,分开模拟。先将操作按弦大小、输入的顺序排序一遍,最后按上述思路即可。

代码

#include<bits/stdc++.h>
using namespace std;
struct node{
    int x,d,id;//弦和段 
    bool operator <(const node &p)const{
        return d < p.d;
    }
};
node ta[500005];
priority_queue<node> q;
int n,p;
bool cmp(node u,node v){
    if(u.x!=v.x)return u.x<v.x;
    return u.id<v.id;
}
int main(){
    scanf("%d%d",&n,&p);
    for(int i=1;i<=n;i++){
        scanf("%d%d",&ta[i].x,&ta[i].d);
        ta[i].id=i;
    }
    sort(ta+1,ta+1+n,cmp);
    int cnt=1;
    q.push(ta[1]);
//  cout<<"&&&";
    for(int i=2;i<=n;i++){

        if(ta[i].x!=q.top().x){
            while(!q.empty()){
                q.pop();
            }
            q.push(ta[i]);
//          cout<<"按"<<ta[i].d<<endl;
        }
        else{
            if(q.top().d==ta[i].d)continue;
            while(q.top().d>ta[i].d&&q.size()>0){
//              cout<<"松"<<q.top().d<<endl;
                q.pop();
                cnt++;
            }
            if(q.top().d==ta[i].d) continue;
//          cout<<"按"<<ta[i].d<<endl;
            q.push(ta[i]);
        }
        cnt++;
    }
    printf("%d",cnt);
    return 0;
}