hduThe All-purpose Zero+LIS

来源:互联网 发布:南风知我意txt下载西州 编辑:程序博客网 时间:2024/06/10 10:42

啊啊喔。啊啊哦。好久没DP,没DP,不会了啊,不会了啊。orz(以防万一,膜拜边上的两位菊苣)。。

LIS:以前写的都是O(n2)的复杂度。今弃嫌。换一nlog(n) 的写法。调试几小时,O啦。
严格递增/非严格递增

int LIS(int A[],int n){    memset(d,0,sizeof(d));    memset(g,INF,sizeof(g));    for(int i=0;i<n;i++){        int k=lower_bound(g+1,g+n+1,A[i])-g;  //非严格递增用upper_bound        cout<<k<<endl;        d[i]=k;        g[k]=A[i];    }    int ans=0;    for(int i=0;i<n;i++) ans=max(ans,d[i]);    return ans;}

将A[i]换成负数就变递减了。。
严格递减/非严格递减

int LIS(int A[],int n){    memset(d,0,sizeof(d));    memset(g,INF,sizeof(g));    for(int i=0;i<n;i++){        int k=lower_bound(g+1,g+n+1,-A[i])-g; //非严格递减用upper_bound       // cout<<k<<endl;        d[i]=k;        g[k]=-A[i];//减用负    }    int ans=0;    for(int i=0;i<n;i++) ans=max(ans,d[i]);    return ans;}

再来说说这个题目。
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.

Author
FZU

Source
2016 Multi-University Training Contest 4
我们可以讲0变成任意数,问最大上升子序列。
解法:最优策略是讲0全部放进去。所以先把所有非零数取出来。每个减去这个数之前有多少个0,再做LIS。得到的LIS+零的个数。
(为什么这么就是最大的呢?窝不造啊,题解是这么说的,问问神奇的海螺吧)。

#include<cstdio>#include<algorithm>#include<cstring>#include<iostream>#include<cmath>using namespace std;#define LL long long#define INF 0x3f3f3f3f#define MOD 10000007int g[100005],d[100005];int a[100005],a2[100005];int LIS(int A[],int n){    memset(d,0,sizeof(d));    memset(g,INF,sizeof(g));    for(int i=0;i<n;i++){        int k=lower_bound(g+1,g+n+1,A[i])-g;        //cout<<k<<endl;        d[i]=k;        g[k]=A[i];    }    int ans=0;    for(int i=0;i<n;i++) ans=max(ans,d[i]);    return ans;}int main(){    int n,t;    scanf("%d",&t);    for(int fo=1;fo<=t;fo++)    {        scanf("%d",&n);        int cnt=0;        int op=0;        for(int i=0;i<n;i++){           scanf("%d",&a[i]);           if(a[i]==0) cnt++;           else a2[op++]=a[i]-cnt;        }        cout<<"Case #"<<fo<<": "<<LIS(a2,op)+cnt<<endl;    }    return 0;}
0 0
原创粉丝点击