>  기사  >  백엔드 개발  >  C++를 사용하여 시퀀스에 대한 특정 작업 수행

C++를 사용하여 시퀀스에 대한 특정 작업 수행

WBOY
WBOY앞으로
2023-09-03 11:49:06943검색

C++를 사용하여 시퀀스에 대한 특정 작업 수행

빈 시퀀스와 처리해야 할 n개의 쿼리가 있다고 가정해 보겠습니다. 쿼리는 {쿼리, 데이터} 형식의 배열 쿼리 형태로 제공됩니다. 쿼리는 다음 세 가지 유형이 될 수 있습니다.

  • query = 1: 제공된 데이터를 시퀀스 끝에 추가합니다.

  • query = 2: 시퀀스 시작 부분에 요소를 인쇄합니다. 그런 다음 요소를 삭제하십시오.

  • query = 3: 순서를 오름차순으로 정렬합니다.

쿼리 유형 2와 3의 데이터는 항상 0이라는 점에 유의하세요.

따라서 입력이 n = 9이면 쿼리 = {{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
  • 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
  • output
#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;
}

위 내용은 C++를 사용하여 시퀀스에 대한 특정 작업 수행의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 tutorialspoint.com에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제