H - H (CodeForces-612D)(排序+區間計數)

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 l i, r i ( - 109 ≤ l i ≤ r i ≤ 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 a j, b j ( a j ≤ b j) — the ends of j-th segment in the answer. The segments should be listed in the order from left to right.

Examples

Input

3 2
0 5
-3 2
3 8

Output

2
0 2
3 5

Input

3 2
0 5
-3 3
3 8

Output

1
0 5

 

題意:給出n條線段,讓你算這些線段重合次數大於等於k次的部分。

思路:這道題的話,是一道區間覆蓋的問題,我們可以在存數時把左端點記做1,右端點記做-1,代表在這個線段內是被覆蓋一次的,這樣處理後共有2*n個點。當第一次到k次時,就記錄下左端點,同理,第一次小於k就是答案的右端,還有就是一個點被覆蓋k次時也算是一個答案。

AC代碼:

#include <stdio.h>
#include <string>
#include <string.h>
#include <iostream>
#include <algorithm>
#include <math.h>
#include <queue>
#include <stack>
#include <map>
#include <set>
typedef long long ll;
const int maxx=2000010;
const int mod=1000000007;
const int inf=0x3f3f3f3f;
const double eps=1e-8;
using namespace std;
struct node1
{
    int x,y;
} edge[maxx];
bool cmp(node1 a,node1 b)
{
    if(a.x==b.x)
        return a.y>b.y;
    return a.x<b.x;
}
struct node2
{
    int x1,y1;
} edge1[maxx];
int main()
{
    int n,k;
    while(~scanf("%d%d",&n,&k))
    {
        memset(edge,0,sizeof(edge));
        memset(edge1,0,sizeof(edge1));
        for(int i=0; i<2*n; i+=2)
        {
            scanf("%d%d",&edge[i].x,&edge[i+1].x);
            edge[i].y=1;
            edge[i+1].y=-1;
        }
        sort(edge,edge+2*n,cmp);
        int ans=0,cnt=0;
        int flag=0;
        for(int i=0; i<2*n; i++)
        {
            ans+=edge[i].y;
            if(ans>=k && flag==0)
            {
                edge1[cnt].x1=edge[i].x;
                flag=1;
            }
            else if(ans<k && flag==1)
            {
                edge1[cnt++].y1=edge[i].x;
                flag=0;
            }
        }
        printf("%d\n",cnt);
        for(int i=0; i<cnt; i++)
            printf("%d %d\n",edge1[i].x1,edge1[i].y1);
    }
    return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章