组合题5 个小题
已作答 0 / 5
(两元序列)试求一个整数序列中,最长的仅包含两个不同整数的连续子序列。如有多 个子序列并列最长,输出任意一个即可。例如,序列 1 1 2 3 2 3 2 3 3 1 1 1 3 1 中, 有两段满足条件的最长子序列,长度均为 7,分别用下划线和上划线标出。
1#include <stdio.h>2int main()3{4 const int SIZE = 100;5 int n, i, j, a[SIZE], cur1, cur2, count1, count2,6 ans_length, ans_start, ans_end; //cur1, cur2 分别表示当前子序列中的两个不同整数 //count1, count2 分别表示 cur1, cur2 在当前子序列中出现的次数7 scanf("%d", &n);8 for (i = 1; i <= n; i++)9 scanf("%d", &a[i]);10 i = 1;11 j = 1; //i, j 分别表示当前子序列的首尾,并保证其中至多有两个不同整数12 while ((j <= n) && (a[j] == a[i]))13 j++;14 cur1 = a[i];15 cur2 = a[j]; count1 = (1) ; //(3 分)16 count2 = 1;17 ans_length = j - i + 1;18 while (j < n) {19 j++;20 if (a[j] == cur1)21 count1++;22 else if (a[j] == cur2)23 count2++;24 else { if (a[j - 1] == (2) ) { //(3 分)25 while (count2 > 0) {26 if (a[i] == cur1)27 count1--;28 else29 count2--;30 i++;31 }32 cur2 = a[j];33 count2 = 1;34 }35 else {36 while (count1 > 0) {37 if (a[i] == cur1) (3) ; //(2 分)38 else (4) ; //(2 分)39 i++;40 } (5) ; //(3 分)41 count1 = 1;42 }43 }44 if (ans_length < j - i + 1) {45 ans_length = j - i + 1;46 ans_start = i;47 ans_end = j;48 }49 }50 for (i = ans_start; i <= ans_end; i++)51 printf("%d ", a[i]);52 return 0;53}第 3 空应填( )