HDU 5773 The All-purpose Zero【LIS变形】

来源:互联网 发布:正交矩阵的行列式 编辑:程序博客网 时间:2024/06/05 01:04

Problem Description
?? gets an sequence S with n intergers(0 < n <= 100000,0<= S[i] <= 1000000).?? has a magic so that he can change 0 to any interger(He does not need to change all 0 to the same interger).?? wants you to help him to find out the length of the longest increasing (strictly) subsequence he can get.

Input
The first line contains an interger T,denoting the number of the test cases.(T <= 10)
For each case,the first line contains an interger n,which is the length of the array s.
The next line contains n intergers separated by a single space, denote each number in S.

Output
For each test case, output one line containing “Case #x: y”(without quotes), where x is the test case number(starting from 1) and y is the length of the longest increasing subsequence he can get.

Sample Input
2
7
2 0 2 1 2 0 5
6
1 2 3 3 0 0

Sample Output
Case #1: 5
Case #2: 5

Hint
In the first case,you can change the second 0 to 3.So the longest increasing subsequence is 0 1 2 3 5.
题意:
将0替换成任意整数(可以为负数),在此基础上求最长递增子序列。
思路:
把A序列所有的0提出来,并把这个数之后的所有数字全部减一(换位思考,就是把每位非0的数字减去它前面0的个数),再对变形后的B序列进行nlogn求LIS,算出的结果直接加上A序列0的总数,就是结果。
分析:
有0的位置分成各个段,比如:(1 2 3) 0 (2 3 5) 0 (3 6 9),各个位减去0的个数,其实每个段的LIS没有改变,改变的是每个段的首和尾之间的差,假设没改变之前的差为a,当a为1时变之后才会有影响(其余无影响),但是这个影响会被这个0覆盖,用这个0的话,之间差为1,这个0没有用处。比较与nlogn思想求LIS,这个分析也可以用。
例如:1,3,0,4,6。在提取出0后序列其实为1,3,3,6,LIS的长度为3,加上0的个数则为答案。

#include <cstdio>#include <cstring>#include <algorithm>#include <cmath>#define max_n 100100#define INF 0x3f3f3f3fusing namespace std;typedef long long LL;int a[max_n], dp[max_n], b[max_n];int main() {    int T, n;    scanf("%d", &T);    while(T--) {        scanf("%d", &n);        for(int i = 0; i < n; i++) {            scanf("%d", &a[i]);        }        int p = 0, ans = 0, j = 0;        for(int i = 0; i < n; i++) {            if(!a[i]) ans++;            else b[j++] = a[i] - ans;        }        if(j > 0) dp[++p] = b[0];        for(int i = 1; i < j; i++) {            if(b[i] > dp[p]) {                dp[++p] = b[i];            }            else {                int cnt = lower_bound(dp + 1, dp + p + 1, b[i]) - dp;                dp[cnt] = b[i];            }        }        static int cas = 1;        printf("Case #%d: %d\n", cas++, p + ans);    }    return 0;}