Codeforces Round #323 (Div. 1) B. Once Again... (最长不下降序列_DP)

博客探讨了Codeforces Round #323的Div. 1 B问题,涉及寻找给定数组中最长非递减序列。问题描述包括数组特性,解题要求及样例。博主指出,尽管看似复杂,但实际上这个问题可以简化为一个经典算法,并提供了具有线性时间复杂度的解法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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: nT (1 ≤ n ≤ 1001 ≤ 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, 23, 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;
}





评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值