You are given an array of positive integers a1, a2, ..., an × T of length n × T. We know that for any i > n it is true thatai = ai - n. Find the length of the longest non-decreasing sequence of the given array.
Input
The first line contains two space-separated integers: n, T (1 ≤ n ≤ 100, 1 ≤ T ≤ 107). The second line contains nspace-separated integers a1, a2, ..., an (1 ≤ ai ≤ 300).
Output
Print a single number — the length of a sought sequence.
Sample test(s)
input
4 3 3 1 4 2
output
5
Note
The array given in the sample looks like that: 3, 1, 4, 2, 3, 1, 4, 2, 3, 1, 4, 2. The elements in bold form the largest non-decreasing subsequence.
仔细思考,其实只是一道水题哎。 (多出来的部分可以直接插进来,不影响求最长子序列!!!)
做法一:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int a[20000],num[20000];
int dp[400];
int main()
{
int n,m,i,j,t,k,tt,ans,mmax;
cin>>n>>m;
mmax=0;
ans=0;
for(i=1;i<=n;i++) {
cin>>a[i];
num[a[i]]++;
mmax=max(mmax,num[a[i]]);
}
t=min(n,m);
k=t;
tt=0;
while(--k) {
tt+=n;
for(i=1;i<=n;i++) a[i+tt]=a[i];
}
for(i=1;i<=n*t;i++) {
dp[a[i]]++;
for(j=a[i]-1;j>=0;j--)
dp[a[i]]=max(dp[a[i]],dp[j]+1);
ans=max(dp[a[i]],ans);
}
ans+=mmax*(m-t);
cout<<ans<<endl;
return 0;
}
复杂度是上一个的一倍!
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int a[20000],num[20000];
int dp[20000];
int main()
{
int n,m,i,j,t,k,tt,ans,mmax;
cin>>n>>m;
mmax=0;
ans=0;
for(i=1;i<=n;i++) {
cin>>a[i];
num[a[i]]++;
mmax=max(mmax,num[a[i]]);
}
t=min(n,m);
k=t;
tt=0;
while(--k) {
tt+=n;
for(i=1;i<=n;i++) a[i+tt]=a[i];
}
for(i=1;i<=n*t;i++) {
dp[i]=1;
for(j=1;j<i;j++) {
if(a[j]<=a[i]) dp[i]=max(dp[i],dp[j]+1);
}
ans=max(dp[i],ans);
}
ans+=mmax*(m-t);
cout<<ans<<endl;
return 0;
}