首页 > 试题广场 >

(两元序列)试求一个整数序列中,最长的仅包含两个不同整数的连

[填空题]
(两元序列)试求一个整数序列中,最长的仅包含两个不同整数的连续子序列。如有多 个子序列并列最长,输出任意一个即可。例如,序列“1 1 2 3 2 3 2 3 3 1 1 1 3 1”中, 有两段满足条件的最长子序列,长度均为 7,分别用下划线和上划线标出。

program two;
const
  SIZE = 100;
var
  n, i, j, cur1, cur2, count1, count2, ans_length, ans_start, ans_end : longint;
//cur1, cur2 分别表示当前子序列中的两个不同整数
//count1, count2 分别表示 cur1, cur2 在当前子序列中出现的次数
  a : array[1..SIZE] of longint;
begin
  readln(n);
  for i := 1 to n do read(a[i]);
  i := 1;
  j := 1;
//i, j 分别表示当前子序列的首尾,并保证其中至多有两个不同整数
  while (j <= n) and (a[j] = a[i]) do inc(j);
  cur1 := a[i];
  cur2 := a[j];
  count1 := 1; //(3 分)
  count2 := 1;
  ans_length := j - i + 1;
  while j < n do
  begin
    inc(j);
    if a[j] = cur1 then inc(count1)
    else if a[j] = cur2 then inc(count2)
    else begin
      if a[j - 1] = 2 then  //(3 分)
      begin
        while count2 > 0 do
        begin
          if a[i] = cur1 then dec(count1)
          else
            dec(count2);
          inc(i);
        end;
        cur2 := a[j];
        count2 := 1;
      end
      else begin
        while count1 > 0 do
        begin
          if a[i] = cur1 then
            3  //(2 分)
          else
            4; //(2 分)
          inc(i);
        end;
        5; //(3 分)
        count1 := 1;
      end;
    end;
    if (ans_length < j - i + 1) then
    begin
      ans_length := j - i + 1;
      ans_start := i;
      ans_end := j;
    end;
  end;
  for i := ans_start to ans_end do write(a[i], ' ');
end.

这道题你会答吗?花几分钟告诉大家答案吧!