(两元序列)试求一个整数序列中,最长的仅包含两个不同整数的连续子序列。如有多个子序列并列最长,输出任意一个即可。例如,序列“1 1 2 3 2 3 2 3 3 1 1 1 3 1”中,有两段满足条件的最长子序列,长度均为7,分别用下划线和上划线标出。
#include
using namespace std;
int main()
{
\tconst int SIZE = 100;
\tint n, i, j, a[SIZE], cur1, cur2, count1, count2,
\tans_length, ans_start, ans_end;
\t//cur1, cur2 分别表示当前子序列中的两个不同整数
\t//count1, count2 分别表示 cur1, cur2 在当前子序列中出现的次数
\tcin>>n;
\tfor (i = 1; i <= n; i )
\t\tcin>>a[i];
\t\ti = 1;
\t\tj = 1;
\t\t//i, j 分别表示当前子序列的首尾,并保证其中至多有两个不同整数
\twhile ((j <= n) && (a[j] == a[i]))
\t\tj ;
\t\tcur1 = a[i];
\t\tcur2 = a[j];
\t\tcount1 = (1) //(3 分)
\t\tcount2 = 1;
\t\tans_length = j - i 1;
\twhile (j < n) {
\t\tj ;
\t\tif (a[j] == cur1)
\t\t\tcount1 ;
\t\telse if (a[j] == cur2)
\t\t\tcount2 ;
\t\telse {
\t\t\tif (a[j - 1] == (2) ) { //(3 分)
\t\t\t\twhile (count2 > 0) {
\t\t\t\t\tif (a[i] == cur1)
\t\t\t\t\t\tcount1--;
\t\t\t\t\telse
\t\t\t\t\t\tount2--;
\t\t\t\t\t\ti ;
\t\t\t}
\t\t\t\tcur2 = a[j];
\t\t\t\tcount2 = 1;
\t\t}
\t\telse {
\t\t\twhile (count1 > 0) {
\t\t\t\tif (a[i] == cur1)
(3) //(2 分)
\t\t\t\telse
(4) //(2 分)
\t\t\t\ti ;
\t\t}
(5) //(3 分)
\t\tcount1 = 1;
\t}
\t}
\tif (ans_length < j - i 1) {
\t\tans_length = j - i 1;
\t\tans_start = i;
\t\tans_end = j;
\t}
\t}
\tfor (i = ans_start; i <= ans_end; i )
\tcout< \treturn 0; }
发表评论 取消回复