Educational Codeforces Round 4 D. The Union of k-Segments 排序,思维

本文提供了一道来自 CodeForces 平台的问题 D 的解题思路及代码实现。该问题涉及多个区间,需要计算至少被覆盖 k 次的区间数量及其范围。采用排序和统计的方法解决此问题。

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

题目链接:http://codeforces.com/contest/612/problem/D
题意:给定n个区间,问你被覆盖至少k次的区间(两端连续区间可以合并)最少有多少个,并输出
解法:某个区间被覆盖至少k次,意味着在它前面的区间起点至少有k个且这些区间的终点不能出现在它前面。这样sort下,直接统计,遇到起点加一,终点减一,每k个一记录就行了

//CF 612D

#include <bits/stdc++.h>
using namespace std;
const int maxn = 2000010;

struct node{
    int x, op;
    node(){}
    node(int x, int op) : x(x), op(op){}
}s[maxn];

bool cmp(node a, node b){
    if(a.x == b.x) return a.op > b.op;
    return a.x < b.x;
}

int ans[maxn];

int main()
{
    int n, k;
    scanf("%d%d", &n, &k);
    int cnt = 0;
    for(int i = 0; i < n; i++){
        int u, v;
        scanf("%d%d", &u, &v);
        s[cnt].x = u;
        s[cnt++].op = 1;
        s[cnt].x = v;
        s[cnt++].op = 0;
    }
    sort(s, s+cnt, cmp);
    int tot = 0;
    int temp = 0;
    for(int i = 0; i < cnt; i++){
        if(s[i].op){
            temp++;
            if(temp == k) ans[tot++] = s[i].x;
        }
        else{
            if(temp == k) ans[tot++] = s[i].x;
            temp--;
        }
    }
    printf("%d\n", tot/2);
    for(int i = 0; i < tot; i += 2){
        printf("%d %d\n", ans[i], ans[i+1]);
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值