#训练5# 4-特殊堆栈

题目

在这里插入图片描述

代码

#include <iostream>
#include <iostream>
#include <cstring>
#include <stack>
#include <algorithm>
#include <queue>
#include <vector>
#include <string>

#define MAXX 10010
using namespace std;

vector<int> v;
vector<int> tt;
vector<int>::iterator it;
int main()
{
    int n;
    cin >> n;
    string s;
    //getchar();
    while (n--)
    {
        cin >> s;
        if (s == "Pop")
        {
            if (v.empty())
                cout<<"Invalid"<<endl;
            else
            {
                cout<<v.back()<<endl;
                it = lower_bound(tt.begin(),tt.end(),v.back());
                tt.erase(it);
                v.pop_back();
            }
        }
        else if (s == "Push")
        {
            int x;
            cin >> x;
            v.push_back(x);
            it = lower_bound(tt.begin(),tt.end(),x);
            tt.insert(it,x);
        }
        else
        {
            if (v.empty())
                cout<<"Invalid"<<endl;
            else
            {
                int tmp = tt.size();
                if (tmp%2==0)
                    tmp/=2;
                else
                    tmp = (tmp+1)/2;
                cout<<tt[tmp-1]<<endl;
            }
        }
    }
    return 0;
}

总结:

1. low_bound()的使用方法

在这里插入图片描述

#include<bits/stdc++.h>
using namespace std;
int main() {
  int a[] = {1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4};
 
  cout << (lower_bound(a, a + 12, 4) - a) << endl; //输出 9:4的第一次出现
  cout << (upper_bound(a, a + 12, 4) - a) << endl; //输出 12:4的最后一次出现位置的后一位
  cout << (lower_bound(a, a + 12, 5) - a) << endl; //输出 12:不存在,最后一位的后一位
  cout << (upper_bound(a, a + 12, 5) - a) << endl; //输出 12
  cout << (lower_bound(a, a + 12, 0) - a) << endl; //输出 0:不存在,0 
  cout << (upper_bound(a, a + 12, 0) - a) << endl; //输出 0
 
  return 0;
}
  • 在升序序列中 lower_bound 进行二分查找,返回第一个大于等于 参数val 的序列值的迭代器,然后减去首迭代器 a,就是两个迭代器的距离了(在这里也就是数组中下标)
  • 在升序序列中 upper_bound 进行二分查找,返回第一个大于 参数val 的 序列值的迭代器,如果找不到,返回一个尾迭代器(在这里是数组越界后的那一个元素的指针),它在数组中下标为 12

vector使用方法

//尾部插入数字
v.push_back(a); 

//使用迭代器访问,这个一直没用过
vector<int>::iterator it;
for(it=vec.begin();it!=vec.end();it++)
    cout<<*it<<endl;
    
//插入元素:在第i+1个元素之前插入x
v.insert(v.begin()+i,x);

//删除元素:某个元素
v.erase(v.begin()+i);
//删除元素:某个区间[i,j]
v.erase(v.begin()+i,v.begin()+j);

//sort排序
bool cmp(const int &a,const int &b)
{
    return a>b;
}
sort(vec.begin(),vec.end(),cmp);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值