盒子
盒子
文章目录
  1. 题目
  2. 题意
  3. 思路
  4. 更新日志

hdu 5087 Revenge of LIS II (dp)

题目

源地址:http://acm.hdu.edu.cn/showproblem.php?pid=5087

题意

求序列第二长的上升子序列。

思路

LIS的$O(N^2)$做法是$dp[i]=max(dp[j]|a[j]<a[i])+1$。如果需要第二大的,额外开一维,记录到该位的最大长度能否由多个序列得到。
复杂度:$O(N^2)$

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
/*
ID: wuqi9395@126.com
PROG:
LANG: C++
*/
#include<map>
#include<set>
#include<queue>
#include<stack>
#include<cmath>
#include<cstdio>
#include<vector>
#include<string>
#include<fstream>
#include<cstring>
#include<ctype.h>
#include<iostream>
#include<algorithm>
using namespace std;
#define INF (1 << 30)
#define LINF (1LL << 60)
#define PI acos(-1.0)
#define mem(a, b) memset(a, b, sizeof(a))
#define rep(i, a, n) for (int i = a; i < n; i++)
#define per(i, a, n) for (int i = n - 1; i >= a; i--)
#define eps 1e-6
#define debug puts("===============")
#define pb push_back
#define mkp make_pair
#define all(x) (x).begin(),(x).end()
#define fi first
#define se second
#define SZ(x) ((int)(x).size())
#define POSIN(x,y) (0 <= (x) && (x) < n && 0 <= (y) && (y) < m)
typedef long long ll;
typedef unsigned long long ULL;
const int maxn = 1100;
int a[maxn], dp[maxn][2], mx, ok, n;
int main () {
int t;
scanf("%d", &t);
while(t--) {
scanf("%d", &n);
for (int i = 0; i < n; i++) scanf("%d", a + i);
mx = -1;
for (int i = 0; i < n; i++) {
dp[i][0] = 1, dp[i][1] = 0;
for (int j = 0; j < i; j++) if (a[i] > a[j]) {
if (dp[i][0] < dp[j][0] + 1) dp[i][0] = dp[j][0] + 1, dp[i][1] = dp[j][1];
else if (dp[i][0] == dp[j][0] + 1) dp[i][1] = 1;
}
//cout<<dp[i][0]<<" "<<dp[i][1]<<endl;
if (dp[i][0] > mx) mx = dp[i][0];
}
ok = 0;
int has = 0;
for (int i = 0; i < n; i++) if (dp[i][0] == mx) {
ok++;
if (dp[i][1]) has = 1;
}
if (ok > 1 || has) cout<<mx<<endl;
else cout<<mx - 1<<endl;
}
return 0;
}
/*
6
3 5 2 5 1 6
*/

更新日志

  • 2014-11-4 AC