PAT (Advanced Level) Practice 1057 Stack (30分)堆模拟

Practice 1057 Stack (30分)

Stack is one of the most fundamental data structures, which is based on the principle of Last In First Out (LIFO). The basic operations include Push (inserting an element onto the top position) and Pop (deleting the top element). Now you are supposed to implement a stack with an extra operation: PeekMedian – return the median value of all the elements in the stack. With N elements, the median value is defined to be the (N/2)-th smallest element if N is even, or ((N+1)/2)-th if N is odd.

Input Specification:

Each input file contains one test case. For each case, the first line contains a positive integer N (≤10^​5). Then N lines follow, each contains a command in one of the following 3 formats:

Push key
Pop
PeekMedian

where key is a positive integer no more than 10^5.

Output Specification:

For each Push command, insert key into the stack and output nothing. For each Pop or PeekMedian command, print in a line the corresponding returned value. If the command is invalid, print Invalid instead.

Sample Input:

17
Pop
PeekMedian
Push 3
PeekMedian
Push 2
PeekMedian
Push 1
PeekMedian
Pop
Pop
Push 5
Push 4
PeekMedian
Pop
Pop
Pop
Pop

Sample Output:

Invalid
Invalid
3
2
2
1
2
4
4
5
3
Invalid

题意:

要求提供一个栈,可以进栈出栈再加上一个输出中位数的功能接口。

题解:

进栈出栈就用 < s t a c k > <stack> <stack>,剩下就是得自己写个数据结构实现中位数功能,用空间换时间,1e5的数据量 O ( n 2 ) O(n^2) O(n2)不太行。

Code1:

第一次用vector二分插入和二分查找,但一想vector是数组实现,插入删除 O ( n ) O(n) O(n)的复杂度直接被拿下。(不过就少了8分)

#include <bits/stdc++.h>
#include <limits.h>
#include <math.h>
#include <memory.h>
#include <stdio.h>

#include <algorithm>
#include <iostream>
#include <map>
#include <queue>
#include <stack>
#include <string>
#include <vector>
using namespace std;
#define ms(x, n) memset(x, n, sizeof(x))
#define wht() \
    int _;    \
    for (scanf("%d", &_); _; _--)
#define For(i, a, b) for (int i = a; i <= (b); i++)
#define Rof(i, a, b) for (int i = a; i >= (b); i--)
#define ioss ios::sync_with_stdio(false)
#define all(a) a.begin(), a.end()
#define int long long
#define input(x) scanf("%lld", &x);
#define print(x) printf("%lld", x);
#define println(x) printf("%lld\n", x);
typedef vector<int> vi;
typedef pair<int, int> pii;

const int maxn = 2e6 + 7;
const int maxm = 5e3 + 7;
const int MOD = 1e9 + 7;
const int mod = 998244353;

int min(int a, int b) { return a < b ? a : b; }
int max(int a, int b) { return a > b ? a : b; }
int gcd(int a, int b) { return b ? gcd(b, a % b) : a; }
bool cmp(int a, int b) { return a > b; }

const int N = 1e5 + 5;
int n, m, k;
int a[N], b[N];
int f[N];

void work() {
	input(n);
	vi ve;
	stack<int> st;
	For(i,1,n){
		string s;
		cin>>s;
		if(s == "Pop"){
			if(st.size() == 0){
				puts("Invalid");
				continue;
			}
			int x = st.top();
			ve.erase(lower_bound(all(ve),x));
			st.pop();
			cout<<x<<"\n";
		}
		else if(s == "Push"){
			int x;
			cin>>x;
			st.push(x);
			auto it = lower_bound(all(ve), x);
			ve.insert(it, x);
		}
		else{
			if(st.size() == 0){
				puts("Invalid");
				continue;
			}
			if(ve.size()%2)
				cout<<ve[(ve.size()+1)/2-1]<<"\n";
			else
				cout<<ve[ve.size()/2-1]<<"\n";
		}
	}
}

signed main() {
#ifndef ONLINE_JUDGE
    freopen("test.in", "r", stdin);
    freopen("test.out", "w", stdout);
#endif
    work();
}

在这里插入图片描述

Code2:

怎么才能把插入删除的复杂度降下来呢,可以用 l i s t list list或手写链表,这样插入删除就是 O ( 1 ) O(1) O(1)的了,不过想找到插入或删除的位置就变成 O ( n ) O(n) O(n)了相当于没变。其实前辈早就发明了神奇的树状数组,把两种操作中和一下复杂度都为 O ( l o g n ) O(logn) O(logn)了,还可以用堆来优化,用堆实现的结构有优先队列和多重集,下面是用multiset的写法:

#include <bits/stdc++.h>
#include <limits.h>
#include <math.h>
#include <memory.h>
#include <stdio.h>

#include <algorithm>
#include <iostream>
#include <map>
#include <queue>
#include <stack>
#include <string>
#include <vector>
using namespace std;
#define ms(x, n) memset(x, n, sizeof(x))
#define wht() \
    int _;    \
    for (scanf("%d", &_); _; _--)
#define For(i, a, b) for (int i = a; i <= (b); i++)
#define Rof(i, a, b) for (int i = a; i >= (b); i--)
#define ioss ios::sync_with_stdio(false)
#define all(a) a.begin(), a.end()
#define int long long
#define input(x) scanf("%lld", &x);
#define print(x) printf("%lld", x);
#define println(x) printf("%lld\n", x);
typedef vector<int> vi;
typedef pair<int, int> pii;

const int maxn = 2e6 + 7;
const int maxm = 5e3 + 7;
const int MOD = 1e9 + 7;
const int mod = 998244353;

int min(int a, int b) { return a < b ? a : b; }
int max(int a, int b) { return a > b ? a : b; }
int gcd(int a, int b) { return b ? gcd(b, a % b) : a; }
bool cmp(int a, int b) { return a > b; }

const int N = 1e5 + 5;
int n, m, k;
int a[N], b[N];
int f[N];

void work() {
//	printf("%.100lf\n",0.1+0.2);
//	printf("%.100lf\n",1.1);
//	printf("%.100lf\n",0.2);
//	return;
	
	
	
    input(n);
    vi ve;
    stack<int> st;
    multiset<int> se1, se2;
    For(i, 1, n) {
        string s;
        cin >> s;
        if (s == "Pop") {
//        	cout<<"POP ";
            if (st.size() == 0) {
                puts("Invalid");
                continue;
            }
            int x = st.top();
            if (x <= *(--se1.end())) {
                se1.erase(se1.find(x));
            } else {
                se2.erase(se2.find(x));
            }
            st.pop();
			if (se1.size() > se2.size() + 1) {
                se2.insert(*(--se1.end()));
                se1.erase(--se1.end());
            } else if (se1.size() < se2.size()) {
                se1.insert(*se2.begin());
                se2.erase(se2.begin());
            }
            cout << x << "\n";
        } else if (s == "Push") {
            int x;
            cin >> x;
//            cout<<"PUSH "<<x<<"\n";
            st.push(x);
            if (se1.size() == 0) {
                se1.insert(x);
            } else {
                    int y = *(--se1.end());
                    if (x <= y) {
                        se1.insert(x);
                    } else {
                        se2.insert(x);
                    }
            }
            if (se1.size() > se2.size() + 1) {
                se2.insert(*(--se1.end()));
                se1.erase(--se1.end());
            } else if (se1.size() < se2.size()) {
                se1.insert(*se2.begin());
                se2.erase(se2.begin());
            }
        } else {
//        	cout<<"MEDIAN ";
            if (st.size() == 0) {
                puts("Invalid");
                continue;
            }
            cout << *(--se1.end()) << "\n";
        }
//        cout<<se1.size()<<" " <<se2.size()<<"\n";
    }
}

signed main() {
#ifndef ONLINE_JUDGE
    freopen("test.in", "r", stdin);
    freopen("test.out", "w", stdout);
#endif
    work();
}

-------------------------------------------------------------------------------------------

upd:

#include <bits/stdc++.h>
#include <limits.h>
#include <math.h>
#include <memory.h>
#include <stdio.h>

#include <algorithm>
#include <iostream>
#include <map>
#include <queue>
#include <stack>
#include <string>
#include <vector>
using namespace std;
#define ms(x, n) memset(x, n, sizeof(x))
#define wht() \
    int _;    \
    for (scanf("%d", &_); _; _--)
#define For(i, a, b) for (int i = a; i <= (b); i++)
#define Rof(i, a, b) for (int i = a; i >= (b); i--)
#define ioss ios::sync_with_stdio(false)
#define all(a) a.begin(), a.end()
// #define int long long
#define input(x) scanf("%lld", &x);
#define print(x) printf("%lld", x);
#define println(x) printf("%lld\n", x);
typedef vector<int> vi;
typedef pair<int, int> pii;

const int maxn = 2e6 + 7;
const int maxm = 5e3 + 7;
const int MOD = 1e9 + 7;
const int mod = 998244353;

int min(int a, int b) { return a < b ? a : b; }
int max(int a, int b) { return a > b ? a : b; }
int gcd(int a, int b) { return b ? gcd(b, a % b) : a; }
bool cmp(int a, int b) { return a > b; }

const int N = 1e5 + 5;
int n, m, k;
int a[N], b[N];
int f[N];

void work() {
    scanf("%d", &n);
    vector<int> ve, ve1;
    vector<int>::iterator it;
    For(i, 1, n) {
        char ch[15];
        scanf("%s", ch);
        string s = ch;
        if (s == "Pop") {
            if (ve1.size() == 0) {
                puts("Invalid");
                continue;
            }
            int x = ve1.back();
            ve.erase(lower_bound(all(ve), x));
            ve1.pop_back();
            printf("%d\n", x);
        } else if (s == "Push") {
            int x;
            scanf("%d", &x);
            ve1.push_back(x);
            it = lower_bound(all(ve), x);
            ve.insert(it, x);
        } else {
            if (ve1.size() == 0) {
                puts("Invalid");
                continue;
            }
            if (ve.size() % 2) {
                printf("%d\n", ve[(ve.size() + 1) / 2 - 1]);
            } else
                printf("%d\n", ve[ve.size() / 2 - 1]);
        }
    }
}

signed main() {
#ifndef ONLINE_JUDGE
    freopen("test.in", "r", stdin);
    freopen("test.out", "w", stdout);
#endif
    work();
}

突然发现用c语言标准输入输出和int类型之后,第一种方法直接就过了。。。应该是数据水了?还是vector优化太好了,不得而知。
vector的时间复杂
但是跟堆优化的还是没法比:
堆优化过得到时间复杂

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值