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);
        }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章