优先级队列 优化

公司食堂

https://www.nowcoder.com/questionTerminal/601815bea5544f389bcd20fb5ebca6a8

链接

using namespace std;
#include<vector>
#include<queue>
int main(){
    int T=0;cin>>T;
    for(int i=0;i<T;i++){
        int N=0;cin>>N;//N张餐桌
        vector<int>canzhuo;
        string s;cin>>s;
        //原:用数组存储
        for(int i=0;i<N;i++){
            canzhuo.push_back(s[i]-'0');
        }
        int M=0;cin>>M;//M 个 人
        string str;cin>>str;   // 男女序列
        bool flag1=false;bool flag2=false;
        // 改用优先级队列存储 保证桌子号顺序
        priority_queue<int, vector<int>, greater<int>> pq0, pq1;
        for(int i=0;i<N;i++){
            if(s[i]=='0') pq0.push(i+1);
            else if(s[i]=='1') pq1.push(i+1);
        }
        
        for(int j=0;j<M;j++){
            if(str[j]=='F'){    // 女性
                // 原  每次都要遍历   先找到 空的  不满足在找到 1 的。每次要全部遍历
                /*for(int i=0;i<N;i++){
                    if(canzhuo[i]==0){flag2=true;canzhuo[i]++;std::cout<<i+1<<'\n';break;}// 优先空桌子
                }
                 if(flag2) {
                    flag2=false;
                     continue;
                }
                for(int i=0;i<N;i++){
                    if(canzhuo[i]==1){canzhuo[i]++;std::cout<<i+1<<'\n';break;}// 优先一个人桌子
                }*/
                if(!pq0.empty()){   // 有 人数为 0 的桌子
                    int tmp = pq0.top();
                    pq0.pop();       
                    pq1.push(tmp);  // 坐下后 该桌号插入人数为1的桌子
                    cout<<tmp<<'\n';
                }
                else{        //  没有 人数为 0 的桌子
                    int tmp = pq1.top();
                    pq1.pop();  //坐下后 桌子变成两个人  直接出队
                    cout<<tmp<<'\n';
                }
                
            }
    
            if(str[j]=='M'){   //  男性
                // 原  每次都要遍历   先找到 1的  不满足在找到 0 的。每次要全部遍历
/*                 for(int i=0;i<N;i++){
                    if(canzhuo[i]==1){flag1=true;canzhuo[i]++;std::cout<<i+1<<'\n';break;}// 优先空桌子
                }
                if(flag1) {
                    flag1=false;continue;
                }
                for(int i=0;i<N;i++){
                    if(canzhuo[i]==0){canzhuo[i]++;std::cout<<i+1<<'\n';break;}// 优先一个人桌子
                }*/
                if(!pq1.empty()){
                    int tmp = pq1.top();
                    pq1.pop();
                    cout<<tmp<<'\n';
                }
                else{
                    int tmp = pq0.top();
                    pq0.pop();
                    pq1.push(tmp);
                    cout<<tmp<<'\n';
                }
            }
        
    }
        
}
    return 0;}
全部评论

相关推荐

头像
不愿透露姓名的神秘牛友
04-08 00:50
点赞 评论 收藏
转发
点赞 收藏 评论
分享
牛客网
牛客企业服务