PAT A1057

题目
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.

输入:
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

输出:
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.

分析:
分块思想的简单应用,即使用两种结构存储数据,一个为栈,另一个是两个数组,前者主要用于栈入栈出操作,后者可按分块思想作为快速查询到中位数的查询表。
后者两个数组一个命名为table,设置容量为10^5(题目key的最大值),小标 i 用于表示 i 这个数有table[i]个;另一个数组命名为block,其大小定义为316(为sqrt(105)的向下取整),代表将table划分为了sqrt(105)个块,每块有sqrt(105)个数字,下标block_index表示第block_index块,block[block_index]表示该块有多少个数。
栈和table、block的数据要同步,每栈入一个数字x,table[x]应加一,block[x/316]应加一;同理每栈出一个数字x,两个数组也应对应减一;
中位数的获得按照题目的意思获得索引K,先根据block数组获取块的索引block_index,再从block_index*316开始遍历table,即可快速定位到该数字。

超时代码,Java真是慢

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Scanner;
import java.util.Stack;

public class A1057 {
    static LinkedList<Integer> stack = new LinkedList<>();
    static int N;
    static int maxN = 100010;
    static int sqrN = 316;  // (int) Math.sqrt(maxN)
    static int[] block = new int[sqrN];
    static int[] table = new int[maxN];

    public static void main(String[] args) {
        Scanner scanner = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
        N = scanner.nextInt();
        while (N-->0){
            String op = scanner.next();
            if (op.equals("Pop")){
                int x = pop();
                System.out.printf(x==-1? "Invalid\n": "%d\n", x);
            }else if (op.equals("PeekMedian")){
                int x = peekMedian();
                System.out.printf(x==-1? "Invalid\n": "%d\n", x);
            }else if (op.equals("Push")){
                push(scanner.nextInt());
            }else{
                throw new RuntimeException("No this Operation: " + op);
            }
        }
    }

    static int peekMedian(){
        int size = stack.size();
        if (size == 0){
            return -1;
        }
        int k = size%2==1? (size+1)/2: size/2;
        int block_index = 0;
        int sum = 0;
        while (sum + block[block_index] < k)
            sum += block[block_index++];
        int number = block_index*sqrN;
        while (sum + table[number] < k)
            sum += table[number++];
        return number;
    }

    static int pop() {
        if (stack.peekFirst() == null){
            return -1;
        }
        int x = stack.poll();
        table[x] = table[x]==0? 0: --table[x];
        block[x/sqrN] = block[x/sqrN]==0? 0: --block[x/sqrN];
        return x;
    }

    static void push(int x){
        stack.push(x);
        table[x]++;
        block[x/sqrN]++;
    }
}

AC代码

#include<cstdio>
#include<cstring>
#include<stack>
using namespace std;
#pragma warning(disable : 4996)

const int maxN = 100010;
const int sqrN = 316;
stack<int> st;
int block[sqrN];
int table[maxN];

void peekMedian() {
	int size = st.size();
	if (st.empty() == true) {
		printf("Invalid\n");
		return;
	}
	int k = size % 2 == 1 ? (size + 1) / 2 : size / 2;
	int block_index = 0;
	int sum = 0;
	while (sum + block[block_index] < k)
		sum += block[block_index++];
	int number = block_index * sqrN;
	while (sum + table[number] < k)
		sum += table[number++];
	printf("%d\n", number);
}

void pop() {
	if (st.empty()) {
		printf("Invalid\n");
		return;
	}
	int x = st.top();
	st.pop();
	table[x] = table[x] == 0 ? 0 : --table[x];
	block[x / sqrN] = block[x / sqrN] == 0 ? 0 : --block[x / sqrN];
	printf("%d\n", x);
}

void push(int x) {
	st.push(x);
	table[x]++;
	block[x / sqrN]++;
}
int main() {
	int x, query;
	memset(block, 0, sizeof(block));
	memset(table, 0, sizeof(table));
	char cmd[20];   //命令
	scanf("%d", &query);
	for (int i = 0; i < query; i++) {
		scanf("%s", cmd);
		if (strcmp(cmd, "Push") == 0) {
			scanf("%d", &x);
			push(x);
		}
		else if (strcmp(cmd, "Pop") == 0) {
			pop();
		}
		else {
			peekMedian();
		}
	}
	return 0;
}

参考《算法笔记》

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值