codeforces1452E Two Editorials (Educational Codeforces Round 98)

题意

给定m个长度不定的区间,取两个长度为k的区间,m个区间中每个区间的贡献为与两个长度为k的区间的交的较大值。求最大贡献。

思路

可以看到对于两个区间来说,当区间中心越靠近时区间交越大。所以我们把m个区间按区间中心排序,然后对于两个长度为k的区间一个取前一部分进行相交,一个取后一部分取交。预处理出前缀(后缀)最大值,复杂度为(O(n^2))

代码

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn=2000+5;
int l[maxn],r[maxn],order[maxn];
int pre[maxn],sub[maxn];
int main()
{
    ios::sync_with_stdio(false);
    int n,m,k;
    cin>>n>>m>>k;
    for(int i=1;i<=m;i++)
        cin>>l[i]>>r[i];
    for(int i=1;i<=m;i++)
        order[i]=i;
    sort(order+1,order+m+1,[&](int i,int j){
        return l[i]+r[i]<l[j]+r[j];
    });

    for(int L=1;L<=n-k+1;L++)
    {
        int ans=0,R=L+k-1;
        for(int j=1;j<=m;j++)
        {
            ans+=max(0,min(R,r[order[j]])-max(L,l[order[j]])+1);
            pre[j]=max(pre[j],ans);
        }
    }
    for(int L=1;L<=n-k+1;L++)
    {
        int ans=0,R=L+k-1;
        for(int j=m;j>=1;j--)
        {
            ans+=max(0,min(R,r[order[j]])-max(L,l[order[j]])+1);
            sub[j]=max(sub[j],ans);
        }
    }

    int Ans=0;
    for(int i=0;i<=m;i++)
        Ans=max(Ans,pre[i]+sub[i+1]);
    cout<<Ans<<endl;
    return 0;
}
原文地址:https://www.cnblogs.com/intmian/p/14059910.html