HDOJ 1025 Constructing Roads In JGShining's Kingdom(LIS O(nlogn) )

26 篇文章 0 订阅

一看数据量就知道要 O(nlogn) 的 LIS

于是上网学了下。。

DP方程仍然是 dp[i] = max(dp[j]+1) (a[j] < a[i])

不过这次用 f[i] 表示所有长度为 i 的上升子序列中结尾最小的那个子序列的结尾。(有点绕嘴。。)

这样就免去了求 max 的过程。

维护 f 数组,每当读入一个 a[i] 时,如果它比 f 中最后一个元素还大,则将 f 数组的长度增加1,并把 a[i] 赋给 f 的结尾。

否则找到 f 中第一个比 a[i] 大的数,将其替换为 a[i] 。

很不严谨的证明:假设要找结尾最小的那个 LIS ,那么我们如果保证在遍历 a 数组时,遍历到该 LIS 的最后一项之前,我们已经得到了 a 数组在这一项之前的所有元素中长度为 LIS 长度减1的结尾最小的子序列,显然问题可解。同理,LIS 长度减1的子问题又可以由 LIS 长度减2的得出。故问题得解。

查找过程可以二分,故时间复杂度被优化到了 O(nlogn)。

#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;

const int maxn = 501000;
int p[maxn], r[maxn], r1[maxn], od[maxn];
int que[maxn], cnt;

bool cmp(int a, int b)
{
    return p[a] < p[b];
}

int findr(int x)
{
    int lf = 0, rt = cnt;
    while(lf <= rt) {
        int md = (lf + rt) / 2;
        if(que[md] <= x && que[md+1] > x)
            return md + 1;
        else if(que[md] > x)
            rt = md - 1;
        else
            lf = md + 1;
    }
}

int main()
{
    int n, ca = 1;

    while(~scanf("%d", &n)) {
        for(int i = 0; i < n; i++) {
            scanf("%d%d", &p[i], &r1[i]);
            od[i] = i;
        }
        sort(od, od+n, cmp);
        for(int i = 0; i < n; i++)
            r[i] = r1[od[i]];
        cnt = 0;
        que[0] = r[0];
        for(int i = 1; i < n; i++) {
            if(r[i] > que[cnt]) {
                cnt++;
                que[cnt] = r[i];
            }
            else que[findr(r[i])] = r[i];
        }
        printf("Case %d:\nMy king, at most %d ", ca++, cnt+1);
        if(cnt == 0) printf("road ");
        else printf("roads ");
        printf("can be built.\n\n");
    }

    return 0;
}


PS:此题有一坑,输出时要注意单复数。。。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值