这道题是月赛题,有解题报告的。
用的是分治的做法。
当时想到了,但总感觉有点不够完美,所以没做,原来是没有正确估算时间复杂度……
#include <iostream>
#include <algorithm>
#define N 50001
using namespace std;
int n;
int a[N];
int b[N];
int bst;
void getLong(int low,int up)
{
if (low>=up || up - low +1 <=bst) return;
int i;
int minV=1000000000,minP,maxV=-1,maxP;
for (i=low; i<=up; ++i)
{
if (a[i]> maxV)
{
maxV = a[i];
maxP = i;
}
if (a[i] < minV)
{
minV = a[i];
minP = i;
}
}
if (minP < maxP)
{
bst = max(bst,maxP-minP);
getLong(low,minP);
getLong(maxP+1,up);
}
else
{
getLong(low,maxP);
getLong(maxP+1,minP-1);
getLong(minP,up);
}
}
int main()
{
while (scanf("%d",&n)!=EOF)
{
for (int I=0; I<n; ++I)
{
scanf("%d",&a[I]);
}
memcpy(b,a,sizeof(a));
if (next_permutation(b,b+n) == false)
{
cout<<-1<<endl;
continue;
}
bst = 0;
getLong(0,n-1);
cout<<bst<<endl;
}
}