题目如下:
给定一个输入受限的双端队列(即一个端点允许插入和删除,另一个端点只允许删除的双端队列)和一个长度为 N的插入序列。
插入序列中的元素两两不同。
你需要将插入序列中的元素按顺序依次插入到给定队列中。
在插入过程中和插入完成后的任意时刻,你可以随时删除队列中的现有元素(如果有的话)。
将所有元素按删除顺序进行排列可以得到删除序列。
现在,给定 K个删除序列,对于每个删除序列,请你判断其能否通过给定插入序列得到。
输入格式
第一行包含两个整数 N,K。
第二行包含 N个不同的整数,表示插入序列。
接下来 K行,每行包含一个删除序列,保证每个删除序列都是给定插入序列的一个排列。
输出格式
每个删除序列,输出一行答案,如果该删除序列可以通过给定插入序列得到,则输出 yes
,否则输出 no
。
数据范围
1≤N≤1e5
1≤K≤10
序列中元素的取值范围 [1,10][1,1e9]。
输入样例:
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
输出样例:
yes
no
yes
yes
解题代码如下:
#include<iostream>
#include<list>
using namespace std;
int N;
bool judge(int* in,int* out) {
list<int> q;
int i = 0, u = 0;
while(1) {
if (q.empty() || (q.front() != out[i] && q.back() != out[i])) {
if (u != N)
q.push_back(in[u++]);
else
break;
}
else {
if (q.front() == out[i])
q.pop_front();
else
q.pop_back();
i++;
}
}
return i == N ? true : false;
}
int main() {
std::ios::sync_with_stdio(false);
int K;
cin >> N >> K;
int* in = (int*)malloc(4 * N);
int* out = (int*)malloc(4 * N);
for (int i = 0; i < N; i++)
cin >> in[i];
while (K--) {
for (int i = 0; i < N; i++)
cin >> out[i];
if (judge(in, out))
cout << "yes" << endl;
else
cout << "no" << endl;
}
return 0;
}