题目大意
个人排成一排参加舞蹈课,每个人有性别和舞蹈技术值。每次选出相邻异性且技术值差最小的一对出列跳舞(差相同选最左的),出列后队伍合并,重复这个过程直到没有相邻异性,要求输出出列顺序。
思路分析
- 数据结构选择:使用双向链表维护相邻关系,优先队列处理最小差值对。
- 关键操作:
- 预处理所有相邻异性对存入优先队列
- 每次取出差值最小的对,标记已出列
- 更新相邻关系,将新形成的相邻异性对加入队列
优先队列
默认声明(大根堆)
priority_queue<int> pq; // 默认大顶堆,从大到小出队小根堆声明
priority_queue<int, vector<int>, greater<int>>min_pq; // 小根堆常用操作
| 操作 | 说明 |
|---|---|
| pq.push(x) | 插入元素x |
| pq.pop() | 弹出堆顶元素 |
| pq.top() | 访问堆顶元素 |
| pq.empty() | 判断是否为空 |
| pq.size() | 返回元素个数 |
重载运算符
基本语法
struct Node {
int x, y;
// 重载<运算符
bool operator < (const Node& other) const {
return ...; // 自定义比较规则
}
};在优先队列中的应用
struct Node {
int val, idx;
// 小根堆比较规则(val小的优先)
bool operator < (const Node& other) const {
return val > other.val; // 注意是>号
}
};
priority_queue<Node> pq; // 此时会按照我们定义的规则排序多级比较规则
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; // 学号小的在前
}
};样例模拟
输入:
4
BGBG
4 2 4 3处理过程:
初始相邻对: 差 , 差 , 差 → 队列
取出 出列 → 队伍变为 ,新相邻 差
取出 出列 → 无新相邻对
队列空,结束。
代码要点
-
和 数组维护双向链表
-
标记已出列人员
-
每次处理时检查两端是否未被访问
-
合并后检查新形成的相邻对是否为异性
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;
}