D. The Union of k-Segments(扫描线)

来源:互联网 发布:js 强制转换字符串 编辑:程序博客网 时间:2024/06/04 19:02

题目链接:http://codeforces.com/contest/612/problem/D

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
3 20 5-3 23 8
output
20 23 5
input
3 20 5-3 33 8
output
10 5


解析:每条线段加个编号,开始为0,结束为1,把所有端点存起来,然后从小到大排序,ans存覆盖k次的,最后输出

代码:

#include<bits/stdc++.h>using namespace std;typedef pair<int, int> P;vector<P> mp;vector<int> ans;int main(){    int n, k;    int l, r;    scanf("%d%d", &n, &k);    for(int i = 1; i <= n; i++)    {        scanf("%d%d", &l, &r);        mp.push_back(make_pair(l, 0));        mp.push_back(make_pair(r, 1));    }    sort(mp.begin(), mp.end());    int cnt = 0;    for(int i = 0; i < mp.size(); i++)    {        if(mp[i].second == 0)        {            cnt++;            if(cnt == k) ans.push_back(mp[i].first);        }        else        {            if(cnt == k) ans.push_back(mp[i].first);            cnt--;        }    }    printf("%d\n", ans.size()/2);    for(int i = 0; i < ans.size(); i += 2) printf("%d %d\n", ans[i], ans[i+1]);    return 0;}


阅读全文
0 0