C - sui题/经典问题 hihocoder-1305 ——mystical_curve

本文介绍了一种区间集合减法的问题及其实现方法。首先对输入的区间进行排序与合并操作,然后计算并输出两个区间集合相减后的长度。通过具体示例展示了算法流程,并附带源代码供读者参考。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

C - sui题/经典问题
You are given two interval collections A and B. Collection A has N intervals [ A1, A2 ], [ A3, A4 ], …, [ A2N-1, A2N ] and collection B has M intervals [ B1, B2 ], [ B3, B4 ], …, [ B2M-1, B2M ]. Your task is to calculate the length of A - B.

For example if A = {[2, 5], [4, 10], [14, 18]} and B = {[1, 3], [8, 15]}, the length of A - B ({(3, 8), (15, 18]}) is 8.

Input
Line 1: Two integers N and M (1 ≤ N, M ≤ 100000).

Line 2: 2*N integers, A1, A2, …, A2N (1 ≤ Ai ≤ 100000000).

Line 3: 2*M integers, B1, B2, …, B2M (1 ≤= Bi ≤ 100000000).

Output
The length of A - B.

Sample Input
3 2
2 5 4 10 14 18
1 3 8 15
Sample Output
8
我又写了一份毒代码,能够感觉感觉思路是对,但就是wa,调试了好久才发现最后区间减的时候有两种情况没考虑进去,哎,水平没达到,希望自己和别人少犯这种错误。

思路:先对区间排序,之后对区间合并,最后相减。

#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
const int N = 100050;
int n,m;
struct node
{
    int a, b;
}s1[N],s2[N];
bool cmp(node a,node b)
{
    return a.a<b.a||a.a==b.a&&a.b<b.b;
}
int flow(node *p,int h,int g)
{
    int a=1,c=g;
    for(int i=2;i<=g;i++)
    {
        if(p[a].b>=p[i].a){
            c--;
            p[a].b=max(p[i].b,p[a].b);
        }
        else
        {
            a++;
            p[a].a=p[i].a;p[a].b=p[i].b;
        }

    }
    return c;
}
int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    cin>>n>>m;int a,b;
    int ans=0;

    for(int i=1;i<=n;i++)
    {
        cin>>a>>b;s1[i].a=a,s1[i].b=b;
    }
    for(int i=1;i<=m;i++)
    {
        cin>>a>>b;s2[i].a=a;s2[i].b=b;
    }

    sort(s1+1,s1+n+1,cmp);
    sort(s2+1,s2+m+1,cmp);
    n=flow(s1,1,n);
    m=flow(s2,1,m);
    int f,g=1;int k=1;
    for(int i=1;i<=n;i++)
    {
        int f=s1[i].a;
        while(g<=m)
        {
            if(s2[g].b>=f)
                break;
            g++;
        }
        if(g>m){
            while(i<=n)
            {
                ans+=s1[i].b-s1[i].a;
                i++;
            }
            break;
        }
          a=s2[g].a;
        ans+=min(max(0,a-f),s1[i].b-f);
          b=s1[i].b;
        while(g+1<=m&&s2[g+1].a<b)
        {
            ans+=s2[g+1].a-s2[g].b;
            g++;
        }
        if(s2[g].b<b)
            ans+=b-s2[g].b;
    }
    cout<<ans<<endl;
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值