HDU 5087 Revenge of LIS II(BestCoder Round #16)(次长上升子序列)

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
 
Hint:
For 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.
 
题意:给出一个序列,输出次长递增子序列的长度。次长递增子序列的定义是:长度小于最长递增子序列,或者长度相等,但在原序列中起始和终止位置不一样。
#include<stdio.h>
#include<string.h>
#include<queue>
#include<math.h>
#include<stdlib.h>
#include<algorithm>
using namespace std;

const int N=1e3+10;
const int INF=0x3f3f3f3f;
const int MOD=1e9+7;

typedef long long LL;

LL a[N];
int dp[N][2], b[2*N]; ///dp[i][0]保存以a[i]结尾的最长递增子序列的长度,dp[i][1]保存以a[i]结尾的次长递增子序列的长度
        
int main ()
{
    int T, n, i, j, k, x, y;

    scanf("%d", &T);

    while (T--)
    {
        scanf("%d", &n);
        for (i = 0; i < n; i++)
            scanf("%lld", &a[i]);

        memset(dp, 0, sizeof(dp));
        for (i = 0; i < n; i++) 
            dp[i][0] = 1; ///将最长递增子序列的长度初始化为1(大于次长递增子序列)
        memset(b, 0, sizeof(b));
        k = 0;

        for (i = 0; i < n; i++)
        {
            for (j = 0; j < i; j++)
            {
                if (a[j] < a[i])
                {
                    x = dp[j][0]+1; ///如果前面比后面小,说明递增序列+1
                    y = dp[j][1]+1;

                    if (x > dp[i][0]) swap(x, dp[i][0]); ///因为次长递增子序列<=最长递增子序列,所以dp[i][1]更新的值<=dp[i][0]
                    dp[i][1] = max(dp[i][1], x);
                    dp[i][1] = max(dp[i][1], y);
                }
            }

            b[k++] = dp[i][0];
            b[k++] = dp[i][1];
        }

        sort(b, b+k);

        printf("%d
", b[k-2]);
    }

    return 0;
}
原文地址:https://www.cnblogs.com/syhandll/p/4935469.html