B. Restaurant
time limit per test
4 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output
A restaurant received n orders for the rental. Each rental order reserve the restaurant for a continuous period of time, the i-th order is characterized by two time values — the start time li and the finish time ri (li ≤ ri).
Restaurant management can accept and reject orders. What is the maximal number of orders the restaurant can accept?
No two accepted orders can intersect, i.e. they can't share even a moment of time. If one order ends in the moment other starts, they can't be accepted both.
Input
The first line contains integer number n (1 ≤ n ≤ 5·105) — number of orders. The following n lines contain integer values li and ri each (1 ≤ li ≤ ri ≤ 109).
Output
Print the maximal number of orders that can be accepted.
Examples
input
2 7 11 4 7
output
1
input
5 1 2 2 3 3 4 4 5 5 6
output
3
input
6 4 8 1 5 4 7 2 5 1 3 6 8
output
2
题目大意:饭店收到了n条租房子的命令,这n条命令以时间区间的形式给出,问饭店最多能接收多少条命令(即时间不能交叉,重合也不行,如3-4 、4-5就不行,4重合了)
解题思路:贪心。比如你正在出租某时间段的房子,如果向尽快给下一家租的话,那么当前这家的租期得尽早结束,于是将所有租贡的结束时间有小到大排序,cnt计数,且下一家开始时间要与本次的结束时间不冲突。
代码如下:
#include <stdio.h> #include <algorithm> using namespace std; struct node { int start; int end; }per[500010]; bool cmp(struct node a,struct node b) { if(a.end==b.end) { return a.start>b.start; } return a.end<b.end; } int main() { int n; scanf("%d",&n); for(int i=0;i<n;i++) { scanf("%d%d",&per[i].start,&per[i].end); } sort(per,per+n,cmp); int time=0;//初始化本次租贡的结束时间 int cnt=0; for(int i=0;i<n;i++) { if(per[i].start>time)//时间不交叉 { time=per[i].end; cnt++; } } printf("%d\n",cnt); return 0; }