【Codeforces Testing Round 12B】【貪心】Restaurant 選取數量最多的不覆蓋區間數
阿新 • • 發佈:2018-12-23
B. Restaurant
time limit per test
4 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output
A restaurant receivednorders for the rental. Each rental order reserve the restaurant for a continuous period of time, thei-th order is characterized by two time values — the start timeliand the finish timeri(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.
InputThe first line contains integer numbern(1 ≤ n ≤ 5·105)
— number of orders. The followingnlines contain integer valuesliandrieach
(1 ≤ l i ≤ ri ≤ 109).
Print the maximal number of orders that can be accepted.
Sample test(s) input2 7 11 4 7output
1input
5 1 2 2 3 3 4 4 5 5 6output
3input
6 4 8 1 5 4 7 2 5 1 3 6 8output
2
#include<stdio.h> #include<string.h> #include<ctype.h> #include<math.h> #include<iostream> #include<string> #include<set> #include<map> #include<vector> #include<queue> #include<bitset> #include<algorithm> #include<time.h> using namespace std; void fre(){freopen("c://test//input.in","r",stdin);freopen("c://test//output.out","w",stdout);} #define MS(x,y) memset(x,y,sizeof(x)) #define MC(x,y) memcpy(x,y,sizeof(x)) #define MP(x,y) make_pair(x,y) #define ls o<<1 #define rs o<<1|1 typedef long long LL; typedef unsigned long long UL; typedef unsigned int UI; template <class T> inline void gmax(T &a,T b){if(b>a)a=b;} template <class T> inline void gmin(T &a,T b){if(b<a)a=b;} const int N=5e5+10,M=0,Z=1e9+7,ms63=1061109567; int n,l,r; pair<int,int>a[N]; int main() { while(~scanf("%d",&n)) { for(int i=1;i<=n;++i)scanf("%d%d",&a[i].first,&a[i].second); sort(a+1,a+n+1); int ed=0;a[0].first=0; int ans=0; for(int i=1;i<=n;i++)if(a[i].first>a[i-1].first) { if(a[i].first>ed) { ++ans; ed=a[i].second; } else gmin(ed,a[i].second); } printf("%d\n",ans); } return 0; } /* 【trick&&吐槽】 不是所有的xe5都是1e5,這道題就是5e5.我的陣列卻開小了QwQ好難過! 【題意】 給你n(5e5)個區間, 希望選取最多個數的區間, 使得所有區間相互之間不覆蓋。 並輸出這個最多區間的區間數。 【型別】 貪心 【分析】 對於亂序的區間我們很難思考。 於是按照(first-左界升序,second-右界升序)的方式排序。 排序後我們順序掃描, 首先,如果左界相同,所有區間最多隻能選一個,我們肯定貪心選擇右區間最小的那個。 然後,如果這個區間的左界與上一個左界不相同,我們會先看上個區間是否已經end, 如果end了,那麼我們可以選擇這個區間。 如果沒end,那麼這兩個區間 構成衝突,它們的前效性是相同的,對之間的決策都不影響,都可以選取當前最多的區間數。 於是我們會貪心選擇右邊界小的那個。 於是,對於這道題,我們就可以用O(nlogn)的時間複雜度AC掉啦。 【時間複雜度&&優化】 O(nlogn) */