ZOJ 4028 LIS(贪心)

题目链接:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=4028

借鉴了一位大佬的博客:https://blog.csdn.net/V5ZSQ/article/details/80205592

Description

有一个长度为n的序列a1,…,an,以fi表示以ai结尾的最长严格上升子序列长度,先给出fi和ai的取值范围[li,ri],给出满足条件的序列a1,…,an,保证有解

Input

第一行一整数T表示用例组数,每组用例首先输入一整数n表示序列长度,之后输入n个整数f1,…,fn,最后n行每行输入两个整数li,ri表示ai的取值范围

(1≤n≤105,1≤fi≤n,0≤li≤ri≤2⋅109)
Output

输出满足条件的a序列

Sample Input

4
6
1 2 3 2 4 3
0 5
2 4
3 3
1 2
3 5
1 5
5
1 2 1 3 1
100 200
200 300
200 400
400 500
100 500
7
1 2 3 1 1 4 2
0 3
0 3
0 3
0 3
0 3
0 3
0 3
2
1 1
1 2
2 3

Sample Output

1 2 3 2 5 3
200 300 200 500 200
0 1 2 0 0 3 1
2 2

Solution 1(贪心)

若fi=1,说明a1,…,ai−1均不小于ai,那么所有fi=1的位置的取值应该是一个不增的序列,贪心的让最后一个fi=1的位置取最小值li,之后从后往前把所有fi=1的位置都取最小值(两个限制:所给取值限制以及保证前面的fi=1的值要大于等于后面的fi=1的值),这样一定对其他位置取值影响最小且合法

若fi=x>1,说明存在1≤j

#include <iostream>
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>
#include <algorithm>
#include <vector>
#include <map>
#include <queue>

using namespace std;

const int maxn = 100000+5;
int next[maxn],pos[maxn],ans[maxn];

struct point
{
    int f,l,r,id;
    bool operator <(const point &rhs) const
    {
        if(f==rhs.f)
            return id >rhs.id;
        return f <rhs.f;
    }
} p[maxn];

int main()
{
    int T,n;
    scanf("%d",&T);
    while(T--)
    {
        memset(next,0,sizeof(next));
        scanf("%d",&n);

        for(int i=1; i<=n; i++)
        {
            scanf("%d",&p[i].f);
            p[i].id=i;
        }

        for(int i=1; i<=n; i++)
            scanf("%d %d",&p[i].l,&p[i].r);

        for(int i=1; i<=n; i++)
        {
            pos[i]=next[p[i].f-1];
            next[p[i].f]=i;
        }
        sort(p+1,p+n+1);
        int L;

        for(int i=1; i<=n; i++)
        {
            if(pos[p[i].id])p[i].l=max(p[i].l,ans[pos[p[i].id]]+1);
            if(i==1||p[i].f!=p[i-1].f)
            {
                L=p[i].l;
                ans[p[i].id]=L;
                continue;
            }
            ans[p[i].id]=max(L,p[i].l);
            L=ans[p[i].id];
        }

        for(int i=1; i<=n; i++)
        {
            if(i!=n)
                printf("%d ",ans[i]);
            else
                printf("%d\n",ans[i]);
        }
    }
    return 0;
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值