CodeForces - 612D The Union of k-Segments 扫描线基础

题目传送门:点击打开链接
D. The Union of k-Segments
time limit per test
4 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

You are given n segments on the coordinate axis Ox and the number k. The point is satisfied if it belongs to at least k segments. Find the smallest (by the number of segments) set of segments on the coordinate axis Ox which contains all satisfied points and no others.

Input

The first line contains two integers n and k (1 ≤ k ≤ n ≤ 106) — the number of segments and the value of k.

The next n lines contain two integers li, ri ( - 109 ≤ li ≤ ri ≤ 109) each — the endpoints of the i-th segment. The segments can degenerate and intersect each other. The segments are given in arbitrary order.

Output

First line contains integer m — the smallest number of segments.

Next m lines contain two integers aj, bj (aj ≤ bj) — the ends of j-th segment in the answer. The segments should be listed in the order from left to right.

Examples
input
Copy
3 2
0 5
-3 2
3 8
output
2
0 2
3 5
input
Copy
3 2
0 5
-3 3
3 8
output
1
0 5

题意很好理解:给定一些线段的左右端点,问至少被覆盖了k次的线段有几个,并从左到右一一列出

其实就是一个扫描线,从最左边的端点开始扫描,每遇到线段的左端点就+1,每遇到线段的右端点就-1.只是有一处需要注意,那就是一个点可能既是左端点又是右端点,此时需要先将其设为左端点,每次+1都记录,直到它不是左端点之后再视为右端点-1

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int, int>P;
const int N = 1e6 + 5;
int po[2*N];
map<int ,int>mp1, mp2;
vector<P>rec;
int main()
{
    int n, k, x, y;
    scanf("%d%d", &n, &k);
    int cnt = 0;
    for(int i = 0; i < n; i++)
    {
        scanf("%d%d", &x, &y);
        po[cnt++] = x;
        po[cnt++] = y;
        if(!mp1.count(x))
            mp1.insert(P(x, 1));
        else mp1[x]++;
        if(!mp2.count(y))
            mp2.insert(P(y, 1));
        else mp2[y]++;
    }
    sort(po, po + cnt);
    int ans = 0, beg, cnt1 = 0;
    bool ju = false;
    for(int i = 0; i < cnt; i++)
    {
        int tp = po[i];
        if(mp1.count(tp) && !mp2.count(tp))
            ans++;
        else if(!mp1.count(tp) && mp2.count(tp))
            ans--;
        else if(mp1.count(tp) && mp2.count(tp))
        {
            if(mp1[tp] != 0)
            {
                ans++;
                mp1[tp]--;
            }
            else
            {
                ans--;
            }
        }
        if(!ju && ans == k)
        {
            beg = tp;
            ju = true;
        }
        else if(ju && ans < k)
        {
            rec.push_back(P(beg, tp));
            ju = false;
            cnt1++;
        }
    }
    printf("%d\n", cnt1);
    int siz = rec.size();
    for(int i = 0; i < siz; i++)
    {
        printf("%d %d\n", rec[i].first, rec[i].second);
    }
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值