微軟程式設計一小時--Longest Repeated Sequence

jsjliuyun發表於2014-04-05

題目2 : Longest Repeated Sequence

時間限制:10000ms
單點時限:1000ms
記憶體限制:256MB

描述

You are given a sequence of integers, A = a1, a2, ... an. A consecutive subsequence of A (say ai, ai+1 ... aj) is called a "repeated sequence" if it appears more than once in A (there exists some positive k that ai+k = ai, ai+k+1 = ai+1, ... aj+k = aj) and its appearances are not intersected (i + k > j).

Can you find the longest repeated sequence in A?

輸入

Line 1: n (1 <= n <= 300), the length of A.
Line 2: the sequence, a1 a2 ... an (0 <= ai <= 100).

輸出

The length of the longest repeated sequence.

樣例輸入
5
2 3 2 3 2
樣例輸出
2
解析:該題的大致意思是找最長的連續數假如是ai, ai+1 ... aj,這些數滿足這樣的條件: ai+k = ai, ai+k+1 = ai+1, ... aj+k = aj,也就是每個
數隔k個數就相同,但是還有一個條件i+k>j,這個也應該考慮到,綜上我就直接模擬了一下,因為時間過了無法提交,如果有錯請大家糾正哈!
#include <iostream>
using std::endl;
using std::cin;
using std::cout;
int main(void)
{
	int N;
	int data[300];
	while(cin >> N)
	{
		int maxLength=0;
		//輸入資料
		for(int i=0; i<N; ++i)
		{
			cin >> data[i];
		}
		for(int i=0; i<N; ++i)
		{
			//如果沒有與當前相等data[i],則k為初值
			int k = 0;
			//每一次迴圈計算length都應該重置
			int length = 0;
			//計算k
			for(int j=i+1; j<N; ++j)
			{
				if(data[j] == data[i])
				{
					length++;
					k = j-i;
					break;
				}
			}
			//開始計算長度
			for(int j=i+1; j+k<N;++j)
			{//這裡還必須控制一個條件i + k > j
				if((data[j] == data[j+k]) && (i +k >j))
				{
					length++;
				}else{
					//如果不滿足上述任何一個條件,終止迴圈
					break;
				}
			}
			//判斷當前的計算的length與maxLength相比較
			if(length > maxLength)
			{
				maxLength = length;
			}
		}
		cout << maxLength << endl;
	}
	return 0;
}


相關文章