trickyPriorityQueue

来源:互联网 发布:e63诺基亚软件下载网址 编辑:程序博客网 时间:2024/06/16 17:55

利用stl中的容器vector实现队列中元素较大的优先出队的问题
例如: 输入 6 0
1 1 9 1 1 1
output: 5

That is, there are six members in the queue, and you position is in 0, you have to calculate the order you can dequeue.

// 排队问题#include<iostream>#include<vector>using namespace std;//  善于使用struct存储数据,然后再使用vector和queue等容器,而不是盲目地使用map//  vector用的是最频繁的也非常好用struct node{  int index;  int pri;  node(int i = 0, int p = 0):index(i), pri(p) {}};int main() {  vector<node> que;  int alljobs, myjob;  cin >> alljobs >> myjob;  int temp;  for (int i = 0; i < alljobs; ++i) {    cin >> temp;    que.push_back(node(i, temp));  }  int result = 0;  while (!que.empty()) {    node top = que.front();    bool flag = false;    //  例: 1 3 7 5 2要找到3在第几个    //  变为: 3 7 5 2 1    // 再变为: 7 5 2 1 3    // 此时在que的后面找不到比7大的数,所以7出队列(此处其实是从vector中erase掉)    // sum++;    // 依次循环下去    for (int i = 1; i < que.size(); ++i) {      if (que[i].pri > que[0].pri) {        que.push_back(top);        flag = true;        break;      }    }    que.erase(que.begin());    if (flag == false) result++;    if (flag == false && top.index == myjob) break;  }  cout << result << endl;  return 0;}

此处用的是vector实现而不是queue

0 0
原创粉丝点击