堆的应用
题目源于陈越、何钦铭-数据结构
Given a stack which can keep M numbers at most. Push N numbers in the order of 1, 2, 3, …, N and pop randomly. You are supposed to tell if a given sequence of numbers is a possible pop sequence of the stack. For example, if M is 5 and N is 7, we can obtain 1, 2, 3, 4, 5, 6, 7 from the stack, but not 3, 2, 1, 7, 5, 6, 4.
翻译:
给定一个可以保持的堆栈 最多M个数字。推N个数字,按1、2、3,…,N并随机弹出。您应该判断给定的数字序列是否是堆栈的可能弹出序列。例如,如果M是5并且N为7,我们可以从堆栈中获得1,2,3,4,4,5,6,7,而不是3,2,1,7,5,6,4。
输入规格:
Each input file contains one test case. For each case, the first line contains 3 numbers (all no more than 1000): M (the maximum capacity of the stack), N (the length of push sequence), and K (the number of pop sequences to be checked). Then K lines follow, each contains a pop sequence of N numbers. All the numbers in a line are separated by a space.
每个输入文件包含一个测试用例。对于每种情况,第一行包含3个数字(所有数字均不超过1000):M(堆栈的最大容量),N(推送序列的长度),和K(要检查的弹出序列数)。然后接下来是K行,每行包含一个弹出序列N个数字。一行中的所有数字都用空格分隔。
输出规格:
For each pop sequence, print in one line “YES” if it is indeed a possible pop sequence of the stack, or “NO” if not.
对于每个弹出序列,如果确实是堆栈中可能的弹出序列,则在一行中打印“是”,否则打印为“否”。
输入样例:
5 7 5
1 2 3 4 5 6 7
3 2 1 7 5 6 4
7 6 5 4 3 2 1
5 6 4 3 7 2 1
1 7 6 5 4 3 2
样本输出:
YES
NO
NO
YES
NO
暴力建堆,一次次比较
#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include "stack"
using namespace std;
#define MAXSIZE 1000
int data[MAXSIZE],capacity,num,count;;
int compare(int *data);
int main(int argc, char *argv[])
{
//1、读入数据
//capacity堆的容量
//num 数据量
//count 比较的次数
cin >> capacity >> num >> count;
for(int i = 0; i < count;i++){
for(int j = 0;j < num ; j++){
cin >> data[j];
}
//作比较
if(compare(data)){
cout << "YES" << endl;
}else{
cout << "NO" << endl;
}
}
return 0;
}
int compare(int *data ){
//1、暴力法,直接建堆比较
stack<int> stack;
int i = 0;
int j = 1;
stack.push(0);
while(i < num){
while(stack.top() < data[i] ){
stack.push(j);
j++;
if(stack.size()-1 > capacity){
return 0;
}
}
i++;
stack.pop();
}
if(stack.size() != 1){
return 0;
}
return 1;
}