PATA1057题解

本文介绍了一个使用分块思想和栈数据结构解决特定问题的C++程序实例。该程序处理一系列指令,包括压栈、弹栈及查找中间元素等操作,并通过分块优化查找效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

分块思想

//
//  main.cpp
//  PATA1057
//
//  Created by Phoenix on 2018/2/14.
//  Copyright © 2018年 Phoenix. All rights reserved.
//

#include <iostream>
#include <cstdio>
#include <stack>
using namespace std;
const int maxn = 317;
int a[maxn] = {0}, b[maxn * maxn] = {0}, num = 0;
stack<int> s;

int main(int argc, const char * argv[]) {
    int n;
    scanf("%d", &n);
    for(int i = 0; i < n; i++) {
        char str[12];
        scanf("%s", str);
        if(str[1] == 'u') {
            int t;
            scanf("%d", &t);
            s.push(t);
            a[t / maxn]++;
            b[t]++;
        }else if (str[1] == 'o') {
            if(!s.empty()) {
                int top = s.top();
                printf("%d\n", top);
                s.pop();
                a[top / maxn]--;
                b[top]--;
            } else {
                printf("Invalid\n");
            }
        } else if(str[1] == 'e') {
            if(!s.empty()) {
                int mid = (s.size() + 1) / 2;
                int k = 0, ans = 0;
                while(a[k] + ans < mid) {
                    ans += a[k];
                    k++;
                }
                k = k * maxn;
                while(b[k] + ans < mid) {
                    ans += b[k];
                    k++;
                }
                printf("%d\n", k);
            } else {
                printf("Invalid\n");
            }
        }
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值