?(2015-3)优先队列的实现

题目描述:

ADD N P:往队列里加入id为N的优先级为P的任务

NEXT:输出下一个最高优先级的任务的id,如果优先级相同输出id小的任务,若队列中没有任务输出-1

REMOVE N:移除id为N的任务

COUNT:输出队列中的任务数量

思路1:

采用set实现,但是不行...不会

#include <cstdio>
#include <string>
#include <set>
#include <iostream>
using namespace std;

struct node{
    int id;
    int p;
};
struct cmp{
    bool operator () (node a, node b){
        if(a.p == b.p){
            return a.id > b.id;         //优先级相同则id小的在前
        }
        return a.p < b.p;               //优先级大的在前
    }
};

set<node> s;

void Add(int id, int p){
    node a;
    a.id = id;
    a.p = p;
    s.insert(a);
    printf("添加成功\n");
}

void Next(){
    if(!s.empty()){
        set<node>::iterator it = s.begin();
        printf("下一个元素id为:%d\n", *it);
    }
    else{
        printf("-1\n");
    }
}

void Remove(int id){

}

void Count(){
    printf("%d", s.size());
}

int main(){
    string str;
    int id, p;
    cin >> str;
    while(1){
        if(str == "ADD"){
            scanf("%d%d", &id, &p);
            Add(id, p);
        }
        else if(str == "NEXT"){
            Next();
        }
        else if(str == "REMOVE"){
            scanf("%d", &id);
            Remove(id);
        }
        else if(str == "COUNT"){
            Count();
        }
        else{
            break;
        }
    }

}

思路2:

采用优先队列,发现remove难以实现

#include <queue>
#include <iostream>
using namespace std;

struct node{
    int id;
    int p;
};
struct cmp{
    bool operator () (node a, node b){
        if(a.p == b.p){
            return a.id > b.id;         //优先级相同则id小的在前
        }
        return a.p < b.p;               //优先级大的在前
    }
};

priority_queue<node, vector<node>, cmp> q;
priority_queue<node, vector<node>, cmp> temp;

void add(int id, int p){
    node a;
    a.id = id;
    a.p = p;
    q.push(a);
}

void next(){
    node a = q.top();
    printf("%d %d", a.id, a.p);
}

void Remove(int id){
    node a = q.top();
    while(a.id != id){
        node b = a;
        q.pop();
        temp.push(b);
    }
}

int main(){
    string str;
    int id, p;
    cin >> str;
    while(1){
        if(str == 'ADD'){
            scanf("%d%d", &id, &p);
            add(id, p);
        }
        else if(str == 'NEXT'){
            next();
        }
        else if(str == 'REMOVE'){
            scanf("%d", &id);
            Remove(id);
        }
        else{
            break;
        }
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_35093872/article/details/88065887
今日推荐