CodeForces 45C Dancing Lessons 优先队列

CodeForces 45C Dancing Lessons

博客搬新家,以后就是基本只在自己的独立博客进行更新,欢迎访问。http://zihengoi.cn

题目描述:

  题目链接:CodeForces 45C Dancing Lessons

题目大意:

  有n 个人在上舞蹈课,每个人都有相应的舞蹈技能值。所有人从左到右排成一行。要求在所有人中男女两两一组,组成舞伴。详细要求如下:

  • 若要组为舞伴则两人必须相邻,且两人舞蹈技能值差小的,优先组合,出队。
  • 存在多个可选舞伴的话,那么就从队首起左边的优先出队。
  • 抽走一对后,队伍合并,补齐空位。

问:最多可以出队多少队,并且按顺序输出跳舞成员编号(初始队列的左起位置)。
 

解题思路:

  根据题目的描述可以很容易的将整个舞蹈队和出队要求构造成一个优先队列。队列的每一个结点包含信息有,左侧学员编号,右侧学员编号,技能值差。而出队的小于符号应以两个结点的技能值差为第一比较小的优先出队,若技能值差相同,则比较左侧学员的编号,编号小的优先出队。
  另外使用数组llrr 来标记每个学员左右的学员编号,每次有人出队则更新对应两人的左右人员编号,且若相邻两者为异性则入队。

复杂度分析:

时间复杂度 :O(N)
空间复杂度 :O(N)

AC代码:

#include <cstring>
#include <queue>
#include <iostream>
#include <cmath>
#include <cstdlib>
#include <cstdio>
using namespace std;

const int maxn = (100010 << 1);
int skill[maxn];
bool cp[maxn];
int r[maxn],l[maxn];
char que[maxn];
struct node{
    int b,g,c;
    bool operator < (const node& a) const{
        if(c == a.c)return b > a.b;
        else return c > a.c;
    }
};
priority_queue<node>Q;
int main()
{
    int n;
    while(cin>>n)
    {
        cin >> que+1;
        node tmp;
        int cup = 0;
        for(int i = 1; i <= n; i++){
            l[i] = i - 1;
            r[i] = i + 1;
            if(que[i] == 'B')cup++;
            cin >> skill[i];
        }
        cup = min(n - cup, cup);
        while(!Q.empty()) Q.pop();
        for(int i = 1; i < n; i++)
            if(que[i] != que[i+1]){
                tmp.b = i;
                tmp.g = i+1;
                tmp.c = abs(skill[i] - skill[i+1]);
                Q.push(tmp);
            }
        memset(cp,false,sizeof(cp));
        cout<< cup << endl;
        while(cup--)

        {
            while(!Q.empty())
            {
                tmp=Q.top();
                Q.pop();
                if(!cp[tmp.b]&&!cp[tmp.g])
                {
                    cout<< tmp.b << " " << tmp.g << endl;
                    cp[tmp.b] = cp[tmp.g] = true;
                    break;
                }
            }
       int lc=l[tmp.b],rc=r[tmp.g];
            r[lc] = rc;
            l[rc] = lc;
            tmp.b = lc;
            tmp.g = rc;
            tmp.c = abs(skill[lc]-skill[rc]);
            if(lc > 0 && rc <= n && que[lc] != que[rc]) Q.push(tmp);
        }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章