首页 > 后端开发 > C++ > 正文

使用C++对序列执行特定操作

WBOY
发布: 2023-09-03 11:49:06
转载
1063人浏览过

使用c++对序列执行特定操作

假设我们有一个空序列和n个需要处理的查询。查询以数组queries的格式给出,格式为{query,data}。查询可以有以下三种类型:

  • query = 1:将提供的数据添加到序列的末尾。

  • query = 2:打印序列开头的元素。然后删除该元素。

  • query = 3:按升序对序列进行排序。

    立即学习C++免费学习笔记(深入)”;

注意,查询类型2和3的data始终为0。

序列猴子开放平台
序列猴子开放平台

具有长序列、多模态、单模型、大数据等特点的超大规模语言模型

序列猴子开放平台 0
查看详情 序列猴子开放平台

因此,如果输入是n = 9,queries = {{1, 5},{1, 4},{1, 3},{1, 2},{1, 1},{2, 0},{3, 0},{2, 0},{3, 0}},那么输出将是5和1。

每个查询后的序列如下所示:

  • 1:{5}
  • 2:{5, 4}
  • 3:{5, 4, 3}
  • 4:{5, 4, 3, 2}
  • 5:{5, 4, 3, 2, 1}
  • 6:{4, 3, 2, 1},打印5。
  • 7:{1, 2, 3, 4}
  • 8:{2, 3, 4},打印1。
  • 9:{2, 3, 4}

要解决这个问题,我们将按照以下步骤进行:

priority_queue<int> priq
Define one queue q
for initialize i := 0, when i < n, update (increase i by 1), do:
   operation := first value of queries[i]
   if operation is same as 1, then:
      x := second value of queries[i]
      insert x into q
   otherwise when operation is same as 2, then:
      if priq is empty, then:
         print first element of q
         delete first element from q
      else:
         print -(top element of priq)
         delete top element from priq
    otherwise when operation is same as 3, then:
       while (not q is empty), do:
          insert (-first element of q) into priq and sort
          delete element from q
登录后复制

Example

让我们来看下面的实现,以便更好地理解 −

#include <bits/stdc++.h>
using namespace std;

void solve(int n, vector<pair<int, int>> queries){
   priority_queue<int> priq;
   queue<int> q;
   for(int i = 0; i < n; i++) {
      int operation = queries[i].first;
      if(operation == 1) {
         int x;
         x = queries[i].second;
         q.push(x);
      } else if(operation == 2) {
         if(priq.empty()) {
             cout << q.front() << endl;
             q.pop();
         } else {
            cout << -priq.top() << endl;
            priq.pop();
         }
      } else if(operation == 3) {
         while(!q.empty()) {
            priq.push(-q.front());
            q.pop();
         }
      }
   }
}
int main() {
   int n = 9; vector<pair<int, int>> queries = {{1, 5}, {1, 4}, {1, 3}, {1, 2}, {1, 1}, {2, 0},  {3, 0}, {2, 0}, {3, 0}};
   solve(n, queries);
   return 0;
}
登录后复制

输入

9, {{1, 5}, {1, 4}, {1, 3}, {1, 2}, {1, 1}, {2, 0}, {3, 0}, {2, 0}, {3, 0}}
登录后复制

输出

5
1
登录后复制

以上就是使用C++对序列执行特定操作的详细内容,更多请关注php中文网其它相关文章!

相关标签:
c++速学教程(入门到精通)
c++速学教程(入门到精通)

c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载
来源:tutorialspoint网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号