hdu 1025 Constructing Roads In JGShining's Kingdom 最长上升子序列(nlogn)

题意:有n个富国和n个穷国,他们分别该在两条直线上,从编号从小到大,线上位置从左到右排列。每个穷国当且仅当有一个富国与之相连,且富国当且仅当有一个穷国与之相连。现在删除部分线,使得所有连线不相交,问最大剩余连线数是多少?

题解:

对输入,先根据穷国编号从小到大排序,得到一个富国的序列。我们发现对于任意富国ai和aj(i<j),只有ai<aj时才不相交,从而将题目转换为,求最长上升子序列。

这题的n可以达到500000,所以必须用nlogn的算法。

dp[i]=max(dp[k])+1;(0<=k<i,a[i]>a[k])

多加一个数组c[i],用于记录最长上升子序列长为i的序列中,最小的最后一个数字。这样查找max(dp[k])时只用找c[i]数组了,而c[i]数组递增,可以用二分查找查询,找到最接近且比a[i]小的值。若k为这个值,那么c[k+1]=min(c[k+1],a[i]);

由于c数组的长度t相当于记录了最长上升子序列,所以可以省略掉dp数组。


注意:输出的时候只有一条线时是road,多条线时是roads,被坑了。。



#include <iostream>
#include <cstdio>
#include <cstring>
#include <ctime>
#include <algorithm>
#include <cmath>
#include <queue>
#include <vector>
using namespace std;

const int maxn=5e5+10;
struct node{
    int x,y;
}e[maxn];
int c[maxn],dp[maxn],t;
int cmp(node a,node b)
{
    return a.x<b.x;
}
void LongestIncreasingSubsequence(int n,int tt)
{
    int i,j,k;
    c[1]=e[0].y;
    t=1;
    for(i=1;i<n;i++)
    {
        if(e[i].y<c[1])c[1]=e[i].y;
        else if(e[i].y>c[t])c[++t]=e[i].y;
        else
        {
            k=lower_bound(c+1,c+t+1,e[i].y)-c;
            c[k]=min(c[k],e[i].y);
        }
    }
    if(t==1)printf("Case %d:\nMy king, at most %d road can be built.\n\n",tt,t);
    else printf("Case %d:\nMy king, at most %d roads can be built.\n\n",tt,t);
}
int main()
{
    int n,tt=0;
    while(scanf("%d",&n)!=EOF)
    {
        int i,j,k;
        for(i=0;i<n;i++)
            scanf("%d%d",&e[i].x,&e[i].y);
        sort(e,e+n,cmp);
        LongestIncreasingSubsequence(n,++tt);
    }
    return 0;
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值