[Aizu] ITP2_6_B Includes

Problem

Description

For given two sequneces \(A=\{a_{0}, a_{1},...,a_{n−1}\} and B=\{b_{0}, b_{1}, ...,b_{m−1}\}\), determine whether all elements of \(B\) are included in \(A\). Note that, elements of \(A\) and \(B\) are sorted by ascending order respectively.

Input

The input is given in the following format.

\(n\)
\(a_{0} a_{1} , ..., a_{n-1}\)
\(m\)
\(b_{0} b_{1} , ..., b_{m-1}\)

The number of elements in \(A\) and its elements \(a_{i}\) are given in the first and second lines respectively. The number of elements in \(B\) and its elements \(b_{i}\) are given in the third and fourth lines respectively.

Output

Print 1, if A contains all elements of B, otherwise 0.

Constrain

1≤n,m≤200,000
−1,000,000,000≤a0<a1<...<an−1≤1,000,000,000
−1,000,000,000≤b0<b1<...<bm−1≤1,000,000,000

Sample

Sample Input1

4
1 2 3 4
2
2 4

Sample Output1

1

Sample Input2

4
1 2 3 4
3
1 2 5

Sample Output 2

0

Solution

Analyse

已知条件有: 两个序列的所有元素都是整数, 并且它们都是按照升序排列的, 没有重复的元素
所以就可以通过两个指针(数组下标)来遍历, 如果B中的元素全部可以在A中找到, 那么就输出1, 否则输出0

Design

由于数据范围为-1000000000 ~ 1000000000, int满足条件(-2147483648 ~ 2147483647), 所以可以使用int数组来存储两个序列, 数组的长度可以预定义, 也可以动态分配
设计一个includes函数, 用来处理判断, 参数中包含数组的地址和长度等信息
p1指向A数组元素, p2指向B数组元素, 如果p1小于p2, 那么A数组后面可能还有相等的, 所以p1后移; 如果p1 大于 p2 , 由于是升序, 所以后面的值肯定没有等于p2的, 直接返回false, 如果p1等于*p2, 那么同时后移, 最终的终止条件为两个指针任何一个指出范围都结束循环, 最后判断p2是否指出, 如果是的话, 证明B数组的所有元素都在A数组中找到了, 返回true, 否则返回false

code

#include <cstdio>
using namespace std;
 
bool includes(int* A, int* A_end, int* B, int* B_end) {
    int *p1 = A, *p2 = B;
    while (p1 != A_end && p2 != B_end) {
        if (*p1 == *p2) {
            p1++;
            p2++;
        } else if (*p1 < *p2)
            p1++;
        else if (*p1 > *p2)
            return false;
    }
    if (p2 == B_end) 
        return true;
    else
        return false;
}
 
int main(void) {
    int n, m;
    scanf("%d", &n);
    int* A = new int[n];
    for (int i = 0; i < n; i++) {
        scanf("%d", &A[i]);
    }
    scanf("%d", &m);
    int* B = new int[m];
    for (int i = 0; i < m; i++) {
        scanf("%d", &B[i]);
    }
 
    if (includes(A, A + n, B, B + m))
        printf("1\n");
    else
        printf("0\n");
 
    delete[] A;
    delete[] B;
}

result

猜你喜欢

转载自www.cnblogs.com/by-sknight/p/10879252.html