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;
}