程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> 關於C++ >> POJ_2376_Cleaning Shifts(貪心)

POJ_2376_Cleaning Shifts(貪心)

編輯:關於C++
Cleaning Shifts Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 12788   Accepted: 3312

Description

Farmer John is assigning some of his N (1 <= N <= 25,000) cows to do some cleaning chores around the barn. He always wants to have one cow working on cleaning things up and has divided the day into T shifts (1 <= T <= 1,000,000), the first being shift 1 and the last being shift T.

Each cow is only available at some interval of times during the day for work on cleaning. Any cow that is selected for cleaning duty will work for the entirety of her interval.

Your job is to help Farmer John assign some cows to shifts so that (i) every shift has at least one cow assigned to it, and (ii) as few cows as possible are involved in cleaning. If it is not possible to assign a cow to each shift, print -1.

Input

* Line 1: Two space-separated integers: N and T

* Lines 2..N+1: Each line contains the start and end times of the interval during which a cow can work. A cow starts work at the start time and finishes after the end time.

Output

* Line 1: The minimum number of cows Farmer John needs to hire or -1 if it is not possible to assign a cow to each shift.

Sample Input

3 10
1 7
3 6
6 10

Sample Output

2

Hint

This problem has huge input data,use scanf() instead of cin to read data to avoid time limit exceed.

INPUT DETAILS:

There are 3 cows and 10 shifts. Cow #1 can work shifts 1..7, cow #2 can work shifts 3..6, and cow #3 can work shifts 6..10.

OUTPUT DETAILS:

By selecting cows #1 and #3, all shifts are covered. There is no way to cover all the shifts using fewer than 2 cows.


題意:農夫有N頭牛。現在他想讓一些牛去做家務。然後他把一天分成T個時間點,也就是一天的時間點是區間[1,T]。他想要任何一個時間點都有牛在做家務。現在給出每頭牛的工作時間,問你能否用最少的牛滿足他的要求,即用最少的時間段覆蓋掉這一天([1,T])。如果不能滿足則輸出-1,否則輸出最少的牛數量。

分析:貪心題。題目意思很明顯是求最少的區間覆蓋掉大區間。先對這些時間段排好序(見代碼),這個排序應該是沒什麼問題的。然後呢,第一頭牛肯定要選,就從這頭牛開始,選取下一頭牛。下一頭牛怎麼選取呢?即在滿足條件的牛裡面(注意:滿足條件的牛是只要開始工作時間 start>=cow[0].y+1 即可),選取右邊界值最大的那個,因為這樣子能夠覆蓋掉最多的時間段。以此類推,故貪心法求之。


代碼清單:
#include
#include #include #include #include #include #include #include #include #include #include #include #include using namespace std; typedef long long ll; const int maxn = 25000 + 5; const int maxd = 1000000 + 5; struct Edge{ int x; int y; }cow[maxn]; int N,T; int X,Y; bool cmp(Edge a,Edge b){ if(a.x==b.x) return a.y>b.y; return a.xmaxy){ maxy=cow[End].y; } } if(maxy!=Start){ ans++; Start=maxy; } else{ if(End==N-1){ //已覆蓋掉區間 break; } else{ //說明中間有的時間點覆蓋不到 printf("-1\n"); return ; } } } printf("%d\n",ans); return ; } int main(){ input(); solve(); return 0; }


  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved