求最长等值序列 (100/100 分数)
题目描述
给定一个数列A,如果其中有一段(至少含有两个元素)序列里面的元素都相等,则称这段序列为等值序列。我们的任务是求最长的等值序列
输入描述
第一行是数列的长度n,n<=50
第二行是n个数字
输出描述
输出最长等值序列在原始数列中的起始位置和末位置,数列的起始下标为0;
若有多个最长等值序列,输出第一个最长等值序列的起始位置和末位置;
若没有等值序列,输出"No answer."
样例输入
2
1 2
5
1 1 3 1 1
样例输出
No answer.
0 1
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
int main()
{
int n;
cin >> n;
int* a = new int[n];//申请一个大小为n的数组,不要直接用int a[n];
//因为数组大小必须是常数,这样做编译器不报错是因为编译器扩展
for(int i=0; i<n; ++i){
cin >> a[i];
}
int start=0, end=0, max_num=1;//记录相等序列起始位置、末尾位置、最长序列长度
for(int i=0; i<n; ++i){
int cnt = 1;//记录相等序列长度
for(int j=i+1; j<n; ++j){
if(a[i]==a[j]){
++cnt;
}
else{
break;
}
if(cnt>max_num){
max_num = cnt;//更新最大序列长度
start = i;
end = j;
}
}
}
if(max_num==1){
cout << "No answer." << endl;
}
else{
cout << start << ' ' << end << endl;
}
return 0;
}