【PTA Data Structures and Algorithms (English)】7-3 Pop Sequence

给定一个栈,最大容量为M,按照1到N的顺序入栈,然后进行K次询问,每次询问给出一个出栈序列,判断是否可能。正解是通过模拟栈操作检查序列,而复杂度较高的解法使用树状数组检查每个元素后面小于它的元素数量。
摘要由CSDN通过智能技术生成

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.

Input Specification:
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.

Output Specification:
For each pop sequence, print in one line “YES” if it is indeed a possible pop sequence of the stack, or “NO” if not.

题意:

有一个栈,按照1到n的顺序来入栈,给你一个M,N,K,M表示的是栈的大小,N表示的是序列的长度,K是询问次数,每次询问给你一个出栈序列,来问你这个序列是否是正确的

思路:

先说一下在网上学到的正解吧,就是模拟过程,如果第一个数是5,那么代表在5出栈的时候前面4个数还在栈中,然后就看这个时候栈里面元素的个数是否大于K,按照这个思路来遍历完所有序列即可。
下面来看正解思路的代码:

#include<bits/stdc++.h>
using namespace std;
const int N = 1010;
int n,m,k,a[N];
void solve(){
	int tt = 0,cnt = 0;
	for(int i=1;i<=n;i++) scanf("%d",&a[i]);
	stack<int> stk;
	stk.push(0);
	for(int i=1;i<=n;i++){
		while(a[i] > stk.top()){
			stk.push(++cnt);
		}
		if(stk.size() > k + 1 || stk.top() != a[i]){
			puts("NO");
			return;
		}
		stk.pop();
	}
	puts("YES");
}
int main(){
	scanf("%d%d%d",&k,&n,&m);
	while(m--) solve();
	return 0;
}

我当时做的时候,选择了一种复杂度够不到的方法,但是数据比较水,给我过了哈哈哈哈,思路就是看这个元素的后面的比他小的元素有多少个,如果大于等于K,那就false,这个可以用树状数组来解决,这个就是O(n^2logn)的复杂度了,刚刚够得上,但是还有一种特殊情况,就是它后面的可能比它小,但是顺序是乱的,就不是降序的,这个就是不对的,但是还是过了,下面附上代码:

#include<bits/stdc++.h>
using namespace std;
const int N = 1010;
int tr[N],n,m,k,a[N],tr1[N];
inline int lowbit(int x){
	return x & -x;
} 
void add(int pos,int val){
	for(int i=pos;i<=n;i+=lowbit(i)){
		tr[i] += val;
	}
}
int sum(int x){
	int ans = 0;
	for(int i=x;i>0;i-=lowbit(i)) ans += tr[i];
	return ans;
}
bool check(int pos){
	int re = a[pos];
	for(int i=pos+1;i<=n;i++){
		if(a[i] < a[pos]){
			if(a[i] > re) return true;
			re = a[i];
		}
	}
	return false;
}
void solve(){
	for(int i=1;i<=n;i++) tr[i] = tr1[i] = 0;
	for(int i=1;i<=n;i++) scanf("%d",&a[i]);
	for(int i=n;i>=1;i--){
		if(sum(a[i]) >= k || check(i)){
			puts("NO");
			return;
		}
		add(a[i],1);
	}
	puts("YES");
}
int main(){
	scanf("%d%d%d",&k,&n,&m);
	while(m--) solve();
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

宇智波一打七~

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值