POJ 3903 Testingthe CATCHER ( LIS )

来源:互联网 发布:剑三捏脸数据不合法 编辑:程序博客网 时间:2024/06/08 18:53

题意:

       给你一个长度为n (n<=200000) 的数字序列, 要你求该序列中的最长(严格)下降子序列的长度.

分析:

       读取所有输入将原始数组逆向然后求最长严格上升子序列即可.

       由于n的规模达到20W, 所以只能用O(nlogn)的算法求.

       令g[i]==x表示当前遍历到的长度为i的所有最长上升子序列中的最小序列末尾值为x.(如果到目前为止根本不存在长i的上升序列那么x==INF无穷大)

       假设当前遍历到了第j个值即a[j], 那么先找到g[n]数组的值a[j]的下确界(即第一个>=a[j]值的g[k]k). 那么此时表明存在长度为k-1的最长上升子序列且该序列末尾的位置<j且该序列末尾值<a[j].

       那么我们可以令g[k]=a[j] 且 dp[i]=k (dp含义如解法1).

       (上面一段花时间仔细理解)

       最终我们可以找出下标最大的i使得: g[i]<INF 中i下标最大. 这个i就是LIS的长.

AC代码: O(n*logn)复杂度

关于LIS参考之前整理博客:here

参考网址:here

#include<cstdio>#include<cstring>#include<algorithm>using namespace std;const int maxn=200000+5;const int INF=1e8;int n;int a[maxn];int g[maxn];int main(){    int kase=0;    while(scanf("%d",&a[1])==1 && a[1]!=-1)    {        if(kase>0) printf("\n");        n=2;        while(scanf("%d",&a[n])==1 && a[n]!=-1)        {            n++;        }        n--;        reverse(a+1,a+n+1);        for(int i=1;i<=n;i++)            g[i]=INF;        int ans=0;        for(int i=1;i<=n;i++)        {            int k=lower_bound(g+1,g+n+1,a[i])-g;            g[k]=a[i];            ans=max(ans,k);        }        printf("Test #%d:\n  maximum possible interceptions: %d\n",++kase,ans);    }    return 0;}



0 0
原创粉丝点击