题目来源
题目描述
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/bc02b73da64748279650cb4c361edc2e.png)
题目解析
- 这是一道模拟题,入队出队。关键点有两个:
- 判断当前出队的值,是否在剩下的里面优先级最优,这个可以用优先队列实现
- 相同元素时,要保证原顺序,原顺序在前的优先级更高,这个就需要优先队列里存储原顺序
#include <utility>
#include <vector>
#include <map>
#include <set>
#include <iostream>
#include <queue>
#include <algorithm>
using namespace std;
struct Info{
int prio;
int id;
Info(int prio, int id) : prio(prio), id(id){
}
};
struct cmp{
bool operator()(Info &a, Info &b){
return (a.prio < b.prio) || ( a.prio == b.prio && a.id < b.id) ;
}
};
std::vector<int> solitInt(std::string str, char ch){
str += ch;
int i = 0;
std::vector<int> ans;
for (int j = 0; j < str.size(); ++j) {
if(str[j] == ch){
ans.push_back(stoi(str.substr(i, j - i)));
i = j + 1;
}
}
return ans;
}
int main()
{
std::string str = "9,3,5,5,9,4";
auto nums = solitInt(str, ',');
std::queue<Info> queue;
std::priority_queue<Info, std::vector<Info>, cmp> pQ;
for (int i = 0; i < nums.size(); ++i) {
queue.push({nums[i], i});
pQ.push({nums[i], i});
}
std::vector<int> res(nums.size());
int idx = 0;
while (!queue.empty()){
auto p1 = queue.front(); queue.pop();
auto prio = pQ.top(); pQ.pop();
if (p1.prio == prio.prio){
res[idx++] = p1.id;
}else{
queue.push(p1);
pQ.push(prio);
}
}
std::string ansStr;
for (int i = 0; i < res.size(); ++i) {
ansStr += std::to_string(res[i]);
if(i != res.size() - 1){
ansStr += ",";
}
}
std::cout << ansStr <<"\n";
}