Bonus-1 One Way In, Two Ways Out (20 分)
题干
Consider a special queue which is a linear structure that allows insertions at one end, yet deletions at both ends. Your job is to check, for a given insertion sequence, if a deletion sequence is possible. For example, if we insert 1, 2, 3, 4, and 5 in order, then it is possible to obtain 1, 3, 2, 5, and 4 as an output, but impossible to obtain 5, 1, 3, 2, and 4.
Input Specification:
Each input file contains one test case. For each case, the first line gives 2 positive integers N and K (≤10), which are the number of insertions and the number of queries, respectively. Then N distinct numbers are given in the next line, as the insertion sequence. Finally K lines follow, each contains N inserted numbers as the deletion sequence to be checked.
All the numbers in a line are separated by spaces.
Output Specification:
For each deletion sequence, print in a line yes if it is indeed possible to be obtained, or no otherwise.
Sample Input:
5 4
10 2 3 4 5
10 3 2 5 4
5 10 3 2 4
2 3 10 4 5
3 5 10 4 2
Sample Output:
yes
no
yes
yes
分析
不理解题意的可以参照另一篇文章,Pop Sequence
这个比那个稍微复杂一点点,其实也就一点点,代码基本一样。
一是这个的入栈的不是默认1->N,而是给的第一行,然后我就加了个origin[];其实多了个索引而已。
原来是b[pb] =tmp; 这里是b[pb] = origin[tmp]
二是这个的出口是有俩个的,于是这里用pbf指向b[]这个栈的栈底,然后判断的时候加一个a[pa] == b[pbf]的情况的考虑(具体见下),以及结尾原来的pb<=0变成了pb-pbf(还是栈长)<=0;
CODE
/*
Bonus-1 One Way In, Two Ways Out (20 分)
* Version 1.2
* Latest Update 2021.10.8
* Platform Recomended: Visual Studio 2017
*/
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#define maxN 11
void judge();
int main()
{
int N, K;
int i, j;
scanf("%d%d", &N, &K);
int a[maxN];
int origin[maxN];
//输入第一行
for (j = 0; j < N; j++) {
scanf("%d", &origin[j]);
}
//输入第i行
for (i = 0; i < K; i++) {
//先读入第i行到a[]中
for (j = 0; j < N; j++) {
scanf("%d", &a[j]);
}
judge(&a, &origin,N);
if (i < K - 1) printf("\n");
}
return 0;
}
void judge(int* a,int *origin,int N)
{
int b[maxN];
int pa = 0;//指向a中元素
int pb = -1;//指向b中元素 尾部
int pbf = 0;//指向b中元素 头部
int tmp = 0;//表示现在排到的要入栈的数
int fact = 1;//默认可以 如果矛盾 fact=0
while (tmp <= N) {
//先把tmp入栈
pb++;
b[pb] = origin[tmp];
//出栈到无法出
while ((a[pa] == b[pb]||a[pa]==b[pbf]) && pa < N && pb >= 0) {
if (a[pa] == b[pb]) {
pa++;
b[pb] = 0;
pb--;
}
else if(a[pa] == b[pbf]) {
pa++;
b[pbf] = 0;
pbf++;
}
}
//tmp继续插入
tmp++;
}
if (fact == 0) return;
if (tmp > N && pb-pbf <= 0 && pa >= N) printf("yes");
else printf("no");
}