您的位置:首页 > 其它

HDOJ 5087 Revenge of LIS II (次大递增子序列)

2017-04-05 19:49 696 查看

Revenge of LIS II

[b]Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)

Total Submission(s): 1624    Accepted Submission(s): 551
[/b]

Problem Description

In computer science, the longest increasing subsequence problem is to find a subsequence of a given sequence in which the subsequence's elements are in sorted order, lowest to highest, and in which the subsequence
is as long as possible. This subsequence is not necessarily contiguous, or unique.

---Wikipedia

Today, LIS takes revenge on you, again. You mission is not calculating the length of longest increasing subsequence, but the length of the second longest increasing subsequence.

Two subsequence is different if and only they have different length, or have at least one different element index in the same place. And second longest increasing subsequence of sequence S indicates the second largest one while sorting all the increasing subsequences
of S by its length.
 

Input

The first line contains a single integer T, indicating the number of test cases.

Each test case begins with an integer N, indicating the length of the sequence. Then N integer Ai follows, indicating the sequence.

[Technical Specification]

1. 1 <= T <= 100

2. 2 <= N <= 1000

3. 1 <= Ai <= 1 000 000 000
 

Output

For each test case, output the length of the second longest increasing subsequence.
 

Sample Input

3
2
1 1
4
1 2 3 4
5
1 1 2 2 2

 


Sample Output

1
3
2
HintFor the first sequence, there are two increasing subsequence: [1], [1]. So the length of the second longest increasing subsequence is also 1, same with the length of LIS.

解法:记录每个位置LIS的个数,如果到最后一位LIS只有一种序列就输出LIS-1,否则输出LIS

经典hack数据(1,1,2)

#include <bits/stdc++.h>
using namespace std;
#define mst(a,b) memset((a),(b),sizeof(a))
#define f(i,a,b) for(int i=(a);i<(b);++i)
const int maxn = 500005;
const int mod = 1000000007;
const int INF = 1e9;
#define ll long long
#define rush() int T;scanf("%d",&T);while(T--)
int a[maxn],dp[maxn],sum[maxn];
int main()
{
int n;
rush()
{
scanf("%d",&n);
int Max=0;
f(i,0,n)
{
scanf("%d",&a[i]);
Max=max(a[i],Max); //Max的引入主要是为了解决如 1,1 的序列
}
a[n++]=Max+1;
mst(sum,0);
dp[0]=1;
sum[0]=1;
f(i,1,n)
{
int t=0;
for(int j=i-1;j>=0;j--)
{
if(a[i]>a[j]&&dp[j]>t)
t=dp[j];
}
for(int j=i-1;j>=0;j--)
{
if(dp[j]==t&&a[i]>a[j])
{
sum[i]+=sum[j];
}
}
if(sum[i]==0)
sum[i]=1;
dp[i]=t+1;
}
int ans=0;
f(i,0,n)
{
ans=max(ans,dp[i]);
}
if(sum[n-1]==1)
ans--;
printf("%d\n",ans-1);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: