7-7 One Way In, Two Ways Out (25 分)

题目

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

思路

/*
使用数组模拟双端队列,在数组尾端插入,两端皆可输出
注意点:
1.对于front,rear指针位置初始化的设定
2.模拟元素进入队列时,要着重注意何时退出循环
*/

代码 (存在问题,测试点见评论区)

#include 
#define maxsize 10000
int queue[maxsize];
int save[maxsize];
int main()
{
    int n, k;
    scanf("%d %d", &n, &k);
    for(int i=0; i<n; i++)
        scanf("%d", &save[i]);

    while(k--)
    {
        int flag = 0, index = 0;
        int front = 1, rear = 0;
        for(int i=0; i<n; i++)
        {
            int tmp;
            scanf("%d", &tmp);
            for(; index<n; index++)
            {
                queue[++rear] = save[index];
                if(save[index] == tmp) break;
            }
            if(tmp == queue[rear]) rear--;
            else if(tmp == queue[front]) front++;
            else flag = 1;
            index += 1;
        }
        if(flag) printf("no\n");
        else printf("yes\n");
    }
    return 0;
}

你可能感兴趣的:(题目,数据结构,c语言)