已知两个由正整数组成的无序序列A、B,每个序列的元素个数未知,但至少有一个元素。你的任务是判断序列B是否是序列A的连续子序列。假设B是“1 9 2 4 18”,A是“33 64 1 9 2 4 18 7”,B是A的连续子序列;假设B是“1 9 2 4 18”,A是“33 1 9 64 2 4 18 7”,B不是A的连续子序列。
输入格式:
依次输入两个乱序的正整数序列A、B,序列中元素个数未知,但每个序列至少有一个元素,并以输入“-1”结束(-1不算序列中元素),每个序列占一行。两个数列的长度均不超过1000。
输入保证合法,且所有整数均可用int存储。
输出格式:
如果序列B是序列A的连续子序列,则输出“ListB is the sub sequence of ListA.”,否则输出“ListB is not the sub sequence of ListA.”。
输入样例:
5 4 3 2 1 -1
3 2 1 -1
输出样例:
ListB is the sub sequence of ListA.
#include<stdio.h>
int main() {
int i, j, i0, f = 1, a[1000], b[1000];
for (i = 0;; i++) {
scanf_s("%d", &a[i]);
if (a[i] == -1) break;
}
for (i = 0;; i++) {
scanf_s("%d", &b[i]);
if (b[i] == -1) break;
}
for (i = 0, j = 0;; i++) {
if (a[i] == -1) break;
f = 1;//初始化步骤易漏
if (a[i] == b[j]) {
i0 = i;
for (; a[i]!=-1&&b[j] != -1; i++, j++) {
if (a[i] != b[j]) f = 0;
}
}
else if (a[i] != b[j]) {
f = 0;
i0 = i;
}
if (f == 1&&b[j]==-1) {/*b[j]==-1易漏*/
printf("ListB is the sub sequence of ListA.\n");
break;
}
j = 0;//初始化步骤易漏
i = i0;//初始化步骤易漏
f = 0;//初始化步骤易漏
}
学一学其他的思路:
#include <stdio.h>
int main(){
int a[1000]={0};
int b[1000]={0};
int n1=0,n2=0;
int i=0;
int n;
scanf("%d",&n);
while(n!=-1){
a[n1++]=n;
scanf("%d",&n);
}
scanf("%d",&n);
while(n!=-1){
b[n2++]=n;
scanf("%d",&n);
}
int isprime1;
for(i=0;i<=n1-n2;i++){
isprime1=1;
for(int k=0;k<n2;k++) {
if(b[k]!=a[k+i]) isprime1=0;
}
if(isprime1==1) break;
}
if(isprime1==1) printf("ListB is the sub sequence of ListA.");
else printf("ListB is not the sub sequence of ListA.");
return 0;
}