C. Painting the Fence(暴力)

22 篇文章 0 订阅

You have a long fence which consists of ? sections. Unfortunately, it is not painted, so you decided to hire ? painters to paint it. ?-th painter will paint all sections ? such that ??≤?≤??.

Unfortunately, you are on a tight budget, so you may hire only ?−2

painters. Obviously, only painters you hire will do their work.

You want to maximize the number of painted sections if you choose ?−2

painters optimally. A section is considered painted if at least one painter paints it.

Input

The first line contains two integers ?

and ? (3≤?,?≤5000) — the number of sections and the number of painters availible for hire, respectively.

Then ?

lines follow, each describing one of the painters: ?-th line contains two integers ?? and ?? (1≤??≤??≤?).

Output

Print one integer — maximum number of painted sections if you hire ?−2

painters.

Examples

Input

Copy

7 5
1 4
4 5
5 6
6 7
3 5

Output

Copy

7

Input

Copy

4 3
1 1
2 2
3 4

Output

Copy

2

Input

Copy

4 4
1 1
2 2
2 3
3 4

Output

Copy

3

题意:n个点,q条线段。我们要删除2条线段使得q-2条线段能覆盖的点的个数最多。

题解:可暴力:记录左端点、右端点、点的覆盖次数、覆盖次数为1的前缀和。也可用dp来做,不过如此菜鸟的我不会~~

q次循环,首先去掉该线段,最后回复该线段;去掉该线段后我们想要再去掉一条线段取得最大值,先用sum记录去掉一条线段后的可覆盖的点的个数,则我们需要用到覆盖次数为1的前缀和了,因为覆盖次数再多一点的话,去不去掉没影响;看L到R区间内有几个覆盖次数为1的,如果为0,则sum不需要变,否则sum需要减去该值,运用前缀和可以O(1)查找。之后更新最优值即可。

#include<bits/stdc++.h>
using namespace std;
const int maxn=5050;
int l[maxn],r[maxn],cnt[maxn],pre[maxn];//线段左右端点,每个点的覆盖次数。只出现一次的前缀和
int sum,ans,n,q;    //sum为去掉一条线段可覆盖的最多的点的个数,再减去一条线段与最优值ans比较
int main()
{
    cin>>n>>q;
    for(int i=1;i<=q;i++)
    {
        cin>>l[i]>>r[i];
        for(int j=l[i];j<=r[i];j++)//记录每个点的出现次数
            cnt[j]++;
    }
    for(int i=1;i<=q;i++)
    {
        for(int j=l[i];j<=r[i];j++) //暴力枚举减去该条线段
            cnt[j]--;
        sum=0;      //注意每次循环sum都从0开始
        for(int j=1;j<=n;j++)
        {
            if(cnt[j]==1)       //这里就是只覆盖一次的前缀和了
                pre[j]=pre[j-1]+1;
            else
                pre[j]=pre[j-1];
            if(cnt[j])          //去掉1条线段后可覆盖的最多点的个数
                sum++;
        }
        for(int j=i+1;j<=q;j++)//从i+1开始枚举去掉该条线段,取最优值即可,因为前i个的情况已经考虑过了
            ans=max(ans,sum-pre[r[j]]+pre[l[j]-1]);
        for(int j=l[i];j<=r[i];j++) //暴力枚举恢复该条线段
            cnt[j]++;
    }
    cout<<ans<<endl;
    return 0;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值