hdu 5773 最長遞增子序列 (nlogn)+貪心

The All-purpose Zero

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 947    Accepted Submission(s): 453


php

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.
題意: 給你n個數字,你能夠將其中的0變成任意數字,求最終能獲得的最長嚴格遞增子序列,
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <string>
#include <cmath>
#include <stdlib.h>
using namespace std;
typedef long long LL;
const int inf=0x3f3f3f3f;
const int mod=1e9+7;
const int N=1e5+10;

int a[N],ans[N];
int main()
{
    int cas,n,x,kk=0;
    scanf("%d",&cas);
    while(cas--){
        scanf("%d",&n);
        int cnt=0,num=0;
        for(int i=1;i<=n;i++){
            scanf("%d",&x);
            if(!x) cnt++;
            else a[++num]=x-cnt;
        }
        if(!num) {
            printf("Case #%d: %d\n",++kk,cnt);
            continue;
        }
        int len=1;
        ans[1]=a[1];
        for(int i=2;i<=num;i++){
            if(a[i]>ans[len]) ans[++len]=a[i];
            else {
              int pos=lower_bound(ans+1,ans+len,a[i])-ans;
              ans[pos]=a[i];
            }
        }
        printf("Case #%d: %d\n",++kk,len+cnt);
    }
    return 0;
}

  0能夠轉化成任意整數,包括負數,顯然求LIS時儘可能把0都放進去一定是正確的。所以咱們能夠把0拿出來,對剩下的作O(nlogn)的LIS,統計結果的時候再算上0的數量。爲了保證嚴格遞增,咱們能夠將每一個權值S[i]減去i前面0的個數,再作LIS,就能保證結果是嚴格遞增的。ios

相關文章
相關標籤/搜索