首页 > 代码库 > HDU-1025 Constructing Roads In JGShining's Kingdom O(nlogn)的最长上升子序列

HDU-1025 Constructing Roads In JGShining's Kingdom O(nlogn)的最长上升子序列

模板题,唯一问题是当长度为1是,road是单数,不然road是复数roads。

#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <queue>
#include <vector>
#include <cstdlib>
#include <algorithm>
using namespace std;
const int maxn=1021000;
struct node
{
    int r;
    int b;
    int k;
}a[maxn];
int n;
int len;
int visit[maxn];
int dp[maxn];
bool cmp(node a,node b)
{
    if(a.r==b.r)
    {
        return a.b>b.b;
    }
    return a.r<b.r;
}
int find(int i)
{
    int low,high,mid;
    low=1;
    high=len;
    while(low<=high)
    {
        int mid=(low+high)/2;
        if(a[i].b==dp[mid])
        {
            return mid;
        }
        if(a[i].b<dp[mid])
        {
            high=mid-1;
        }
        else
        {
            low=mid+1;
        }
    }
    return low;
}
int main()
{
    int cas=1;
    while(scanf("%d",&n)!=EOF)
    {
        memset(visit,0,sizeof(visit));
        for(int i=1;i<=n;i++)
        {
            scanf("%d%d",&a[i].r,&a[i].b);
            a[i].k=i;
        }
        sort(a+1,a+n+1,cmp);
        dp[1]=a[1].b;
        visit[1]=1;
        len=1;
        for(int i=2;i<=n;i++)
        {
            if(a[i].b>dp[len])
            {
                dp[++len]=a[i].b;
                visit[i]=len;
            }
            else
            {
                int pos=find(i);
                dp[pos]=a[i].b;
                visit[i]=pos;
            }
        }
        printf("Case %d:\n",cas++);
        if(len==1)
        {
        	printf("My king, at most %d road can be built.\n\n",len);
        }
        
		else
		{
			printf("My king, at most %d roads can be built.\n\n",len);
		}
    }
    return 0;
}


HDU-1025 Constructing Roads In JGShining's Kingdom O(nlogn)的最长上升子序列