转载自:http://blog.csdn.net/qq_34374664/article/details/72377345
题意:
给出n条线段和k,然后输出被这些线段经过了至少k次的点形成的线段。
思路:
一个计数变量cnt,遇到一个起点就cnt++,终点就cnt--,如果遇到起点cnt变成了k,说明他是所求线段的一个起点,把他扔进答案,如果遇到了一个终点,原来是k,说明他要结束了,把他扔进答案。
Code:
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn = 1e6 + 10;
typedef pair<int,int> P;
int n,k;
vector<P>v,ans;
int main()
{
while( ~ scanf("%d%d",&n,&k))
{
v.clear();
ans.clear();
for(int i = 1; i <= n; i ++)
{
int l,r;
scanf("%d%d",&l,&r);
v.push_back(make_pair(l,-1));
v.push_back(make_pair(r,1));
}
sort(v.begin(),v.end());
int cnt = 0;
int x,y;
for(int i = 0; i < v.size(); i ++)
{
P t = v[i];
if(t.second == -1)
{
cnt ++;
if(cnt == k)
x = t.first;
}
else
{
if(cnt == k)
ans.push_back(make_pair(x,t.first));
cnt --;
}
}
cout << ans.size() << endl;
for(int i = 0; i < ans.size(); i ++)
cout << ans[i].first << " " << ans[i].second << endl;
}
return 0;
}