P1878 舞蹈课·题解

· · 题解

题目大意

## 思路分析 1. **数据结构选择**:使用双向链表维护相邻关系,优先队列处理最小差值对。 2. **关键操作**: - 预处理所有相邻异性对存入优先队列 - 每次取出差值最小的对,标记已出列 - 更新相邻关系,将新形成的相邻异性对加入队列 ## 优先队列 #### 默认声明(大根堆) ```cpp priority_queue<int> pq; // 默认大顶堆,从大到小出队 ``` #### 小根堆声明 ```cpp priority_queue<int, vector<int>, greater<int>>min_pq; // 小根堆 ``` #### 常用操作 |操作|说明| |:-:|:-:| |pq.push(x)|插入元素x| |pq.pop()|弹出堆顶元素| |pq.top()|访问堆顶元素| |pq.empty()|判断是否为空| |pq.size()|返回元素个数| ## 重载运算符 #### 基本语法 ```cpp struct Node { int x, y; // 重载<运算符 bool operator < (const Node& other) const { return ...; // 自定义比较规则 } }; ``` #### 在优先队列中的应用 ```cpp struct Node { int val, idx; // 小根堆比较规则(val小的优先) bool operator < (const Node& other) const { return val > other.val; // 注意是>号 } }; priority_queue<Node> pq; // 此时会按照我们定义的规则排序 ``` #### 多级比较规则 ```cpp struct Student { string name; int score, id; // 先按分数降序,分数相同按学号升序 bool operator < (const Student& other) const { if(score != other.score) return score < other.score; // 分数大的在前 return id > other.id; // 学号小的在前 } }; ``` ## 样例模拟 输入: ```cpp 4 BGBG 4 2 4 3 ``` 处理过程: 初始相邻对:$(1,2)$ 差 $2$,$(2,3)$ 差 $2$,$(3,4)$ 差 $1$ → 队列$[(3,4,1),(1,2,2),(2,3,2)]

取出 (3,4) 出列 → 队伍变为 B B G,新相邻 (1,2) 差 2

取出 (1,2) 出列 → 无新相邻对

队列空,结束。

代码要点

AC Code:

#include<bits/stdc++.h>
using namespace std;
int n,a[200005],l[200005],r[200005],ans[200005][2],cnt,vis[200005];
//l[i]表示第i个点的左端点,r[i]表示第i个点的右端点
//ans用于存储答案,vis用于标记是否已出队
char s[200005];
struct node{
    int l,r,v;
    bool operator <(const node &y)const{//重载运算符
        if(v==y.v) return l>y.l;
        return v>y.v;
    }
};
priority_queue<node>q;
int main() {
    cin>>n;
    for(int i=1;i<=n;i++){
        cin>>s[i];
    }
    for(int i=1;i<=n;i++){//初始化双向链表
        cin>>a[i];
        l[i]=i-1,r[i]=i+1;
    }
    for(int i=1;i<n;i++){//将异性入队
        if(s[i]!=s[i+1]) q.push(node{i,i+1,abs(a[i]-a[i+1])});
    }
    while(q.size()>0){
        node c=q.top();//存储头元素
        q.pop();//出队
        if(vis[c.l]==0&&vis[c.r]==0){//判断是否使用过
            vis[c.l]=1;
            vis[c.r]=1;//标记
            cnt++;
            ans[cnt][0]=c.l;
            ans[cnt][1]=c.r;//记录答案
            if(r[c.r]>n||l[c.l]<1) continue;//如果是头节点或是尾结点则跳过修改操作
            r[l[c.l]]=r[c.r];
            l[r[c.r]]=l[c.l];//更改左右关系
            if(s[l[c.l]]!=s[r[c.r]]) q.push(node{l[c.l],r[c.r],abs(a[l[c.l]]-a[r[c.r]])});
//将新的异性关系入队
        }
    }
    //答案输出
    cout<<cnt<<endl;
    for(int i=1;i<=cnt;i++){
        cout<<ans[i][0]<<" "<<ans[i][1]<<endl;
    }
    return 0;
}