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 that ai = ai - n. Find the length of the longest non-decreasing sequence of the given array.
The first line contains two space-separated integers: n, T (1 ≤ n ≤ 100, 1 ≤ T ≤ 107). The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 300).
Print a single number — the length of a sought sequence.
4 3 3 1 4 2
5
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.
题目大意:
给你一个长度为N的序列,其循环延伸T次,问此时的最长上升子序列的长度(非递减即可)。
思路:
1、首先肯定的是我们暴力延伸10^7次的话,无论是空间还是时间都是不够的。那么我们考虑如何优化这个问题:
①首先我们设定dp【i】,表示以第i个数作为结尾的最长上升子序列的长度.
②那么我们如果想要对一个循环序列的终点进行枚举的话,假设我们每段循环的子序列只取了一个数,那么我们需要将这段序列延伸N次才行。
③那么我们最初的时候,t不满100的,我们延展N次,t满100的,我们延展100次。
2、接下来我们继续思考:
①对于延展了T次的序列,其最长上升子序列的递增过程我们可以YY出来,其一定是先递增再保持不变,最后再递增的过程。
②那么我们再设定dp2【i】,表示以第i个数作为起点的最长上升子序列的长度。
③此时我们已经有了dp【i】,dp2【i】两个数组的结果。那么此时答案:如果t<100,我们直接维护最大的dp【i】即可。否则我们维护最大的dp【i】+dp2【i】-1+(t-100)*这个数出现的次数。因为重复统计了第i个数,那么我们需要-1.先递增的一部分就是dp【i】,保持不变的过程就是(t-100)*这个数出现的次数.那么最后再递增的过程就是dp2【i】;
Ac代码:
#include<stdio.h>
#include<string.h>
#include<iostream>
using namespace std;
int a[100005];
int dp[100005];
int dp2[100005];
int have[100005];
int main()
{
int n,t;
while(~scanf("%d%d",&n,&t))
{
for(int i=1;i<=n;i++)
{
scanf("%d",&a[i]);
have[a[i]]++;
}
int tmp=t;
if(tmp>100)tmp=100;
int now=n+1;
for(int i=1;i<=tmp;i++)
{
for(int i=1;i<=n;i++)
{
a[now]=a[i];
now++;
}
}
for(int i=1;i<=n*tmp;i++)
{
dp[i]=1;
for(int j=1;j<i;j++)
{
if(a[i]>=a[j])dp[i]=max(dp[i],dp[j]+1);
}
}
for(int i=n*tmp;i>=1;i--)
{
dp2[i]=1;
for(int j=n*tmp;j>i;j--)
{
if(a[j]>=a[i])dp2[i]=max(dp2[i],dp2[j]+1);
}
}
if(t<=100)
{
int output=0;
for(int i=1;i<=n*tmp;i++)
{
output=max(output,dp[i]);
}
printf("%d\n",output);
}
else
{
int output=0;
for(int i=1;i<=n*tmp;i++)
{
output=max(output,dp[i]+dp2[i]-1+have[a[i]]*(t-100));
}
printf("%d\n",output);
}
}
}