• CF-1055E:Segments on the Line (二分&背包&DP优化)(nice problem)


    You are a given a list of integers

    You need to select exactly

    The

    Input

    The first line contains four integers

    The second line contains

    Each of the next

    It is possible that some segments coincide.

    Output

    Print exactly one integer — the smallest possible

    Examples
    Input
    4 3 2 2
    3 1 3 2
    1 2
    2 3
    4 4
    Output
    2
    Input
    5 2 1 1
    1 2 3 4 5
    2 4
    1 5
    Output
    1
    Input
    5 3 3 5
    5 5 2 1 1
    1 2
    2 3
    3 4
    Output
    -1

    题意:给定给N个点,以及M个线段,让你选择S个线段,使得至少被一个线段覆盖的点排序后,第K大最小,没有则输出-1。

    思路:求第K大最小,显然需要二分,每次验证看当前的mid是否有大于等于K个数小于mid。验证我们用dp来验证,复杂度是O(NMS*lgN);

    需要优化掉一个。这里用背包把M优化掉了,我们找到每个点的Next,Next代表包含这个点的最右端。就不难得到dp方程,这个时候M已经没用了。

    #include<bits/stdc++.h>
    #define rep(i,a,b) for(int i=a;i<=b;i++)
    using namespace std;
    const int maxn=1510;
    struct in{ int L,R;}s[maxn];
    int a[maxn],b[maxn],N,S,M,K,sum[maxn];
    int dp[maxn][maxn],Next[maxn];
    bool check(int Mid) //M个选最多S个的第K大
    {
        rep(i,1,N) sum[i]=sum[i-1]+(a[i]<=Mid);
        rep(i,0,S) rep(j,0,N) dp[i][j]=0;
        rep(i,1,S){
            rep(j,1,N) dp[i][j]=max(dp[i][j],dp[i-1][j]); //不选j位置。
            rep(j,1,N) if(Next[j]) dp[i][Next[j]]=max(dp[i][Next[j]],dp[i-1][j-1]+sum[Next[j]]-sum[j-1]); //选j
            rep(j,1,N) dp[i][j]=max(dp[i][j],dp[i][j-1]);
        }
        return dp[S][N]>=K;
    }
    int main()
    {
        scanf("%d%d%d%d",&N,&M,&S,&K);
        rep(i,1,N) scanf("%d",&a[i]),b[i]=a[i];
        rep(i,1,M) scanf("%d%d",&s[i].L,&s[i].R);
        rep(i,1,M) rep(j,s[i].L,s[i].R) Next[j]=max(Next[j],s[i].R);
        sort(b+1,b+N+1); int L=1,R=N,Mid,ans=-1;
        while(L<=R){
            Mid=(L+R)>>1;
            if(check(b[Mid])) ans=b[Mid],R=Mid-1;
            else L=Mid+1;
        }
        printf("%d
    ",ans);
        return 0;
    }
  • 相关阅读:
    Windows环境下OpenLDAP安装配置
    jobcenter在Windows下连携LDAP
    OpenLDAP搭建
    Go 函数 #3
    Go 数组/多维数组/切片/map #2
    Go内置类型/变量/常量 #1
    git常用命令
    makefile基础_1
    kubernete的service
    配置开发环境
  • 原文地址:https://www.cnblogs.com/hua-dong/p/10046059.html
Copyright © 2020-2023  润新知