原题:
A. Best Subsegment
time limit per test1 second
memory limit per test256 megabytes
inputstandard input
outputstandard output
You are given array a1,a2,…,an. Find the subsegment al,al+1,…,ar (1≤l≤r≤n) with maximum arithmetic mean
1
r
−
l
+
1
∑
i
=
l
r
a
i
\frac{1}{r-l+1}\sum\limits_{i=l}^ra_i
r−l+11i=l∑rai
(in floating-point numbers, i.e. without any rounding).
If there are many such subsegments find the longest one.
Input
The first line contains single integer n (1≤n≤10^5) — length of the array a.
The second line contains n integers a1,a2,…,an (0≤ai≤10^9) — the array a.
Output
Print the single integer — the length of the longest subsegment with maximum possible arithmetic mean.
Example
input
5
6 1 6 6 0
output
2
Note
The subsegment [3,4] is the longest among all subsegments with maximum arithmetic mean.
中文:
给你一个序列,让你找出这个序列当中的一个连续的子序列,使得这个连续的子序列的平均值最大的情况下该子序列长度最长。
代码:
#include<bits/stdc++.h>
using namespace std;
const int maxn = 100005;
int a[maxn];
int n;
int main()
{
ios::sync_with_stdio(false);
while (cin >> n)
{
for (int i = 1; i <= n; ++i)
cin >> a[i];
int ans=1,tmp=a[1];
for(int i=1;i<=n;)
{
int j=i+1;
while(a[j]==a[i]&&j<=n)
j++;
if(a[i]==tmp)
{
if(j-i>ans)
ans=j-i;
i=j;
continue;
}
if(a[i]>tmp)
{
tmp=a[i];
ans=j-i;
i=j;
continue;
}
if(a[i]<tmp)
{
i=j;
continue;
}
}
cout<<ans<<endl;
}
return 0;
}
思路:
A题还有点做头
要找到某一个序列的子序列的平均值最大且子序列长度最长,那么肯定是这个序列中最大值连续出现的次数,所以可以先遍历一遍序列,找到最大值,然后再遍历一遍序列,把最大值连续出现的长度找出来即可。也可以在一次循环中完成。