[HDU] 1025 Constructing Roads In JGShining's Kingdom 二分的求最大递增非连续子序列

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1025

方法:求最大递增非连续子序列朴素的方法是o(n^2)的时间复杂度,而该题要超时,所以用二分的,具体实现参见链接http://www.programfan.com/blog/article.asp?id=13086

感想:熟悉上述链接的定理证明。

代码:

View Code
#include<iostream>
#include<math.h>
#include<algorithm>
#include<stack>
using namespace std;
int const MAX =0x3f3f3f3f;
struct Road
{
    int p;
    int r;
};
bool cmp(Road x,Road y)
{
    if(x.p < y.p )
        return true;
    return false;
}
Road roads[500001];
int counts[500001];
int main()
{
    int n=0,tc=1;
    while(scanf("%d",&n)!=EOF)
    {
        memset(counts,0,sizeof(counts));
        for(int i=0;i<n;i++)
            scanf("%d %d",&roads[i].p,&roads[i].r);
        sort(roads,roads+n,cmp);
        counts[1] = roads[0].r;
        counts[0] = 0;
        int len=1;
        for(int i=1;i<n;i++)
        {
            int p = 0,ed = len,mid;
            while(p<=ed)
            {
                mid = (p+ed)/2;
                if(counts[mid]>=roads[i].r)
                    ed = mid-1;
                else
                    p=mid+1;
            }
            counts[p]=roads[i].r;
            if(p>len)len++;
        }
        cout<<"Case "<<tc<<":"<<endl;
        if(len>1)
            cout<<"My king, at most "<<len<<" roads can be built."<<endl;
        else
            cout<<"My king, at most "<<len<<" road can be built."<<endl;
        cout<<endl;
        tc++;
    }
    return 0;
} 
原文地址:https://www.cnblogs.com/kbyd/p/3054336.html