[C++]Stall ReservationsPOJ - 3190

Stall Reservations POJ - 3190

Stall Reservations:
Oh those picky N (1 <= N <= 50,000) cows! They are so picky that each one will only be milked over some precise time interval A…B (1 <= A <= B <= 1,000,000), which includes both times A and B. Obviously, FJ must create a reservation system to determine which stall each cow can be assigned for her milking time. Of course, no cow will share such a private moment with other cows.

Help FJ by determining:
The minimum number of stalls required in the barn so that each cow can have her private milking period
An assignment of cows to these stalls over time
Many answers are correct for each test dataset; a program will grade your answer.

輸入格式:
Line 1: A single integer, N

Lines 2…N+1: Line i+1 describes cow i’s milking interval with two space-separated integers.
輸出格式:
Line 1: The minimum number of stalls the barn must have.

Lines 2…N+1: Line i+1 describes the stall to which cow i will be assigned for her milking period.

輸入:
5
1 10
2 4
3 6
5 8
4 7
輸出:
4
1
2
3
2
4

題目大意:
這裏有N只 (1 <= N <= 50,000) 挑剔的奶牛! 他們如此挑剔以致於必須在[A,B]的時間內產奶(1 <= A <= B <= 1,000,000)當然, FJ必須爲他們創造一個決定擠奶時間的系統.當然,沒有牛想與其他奶牛分享這一時光

幫助FJ做以下事:
使每隻牛都有專屬時間的最小牛棚數
每隻牛在哪個牛棚
也許有很多可行解。輸出一種即可,採用SPJ

解題分析:
以最短結束時間排序優先隊列,每個元素有牛棚號與結束時間
如果該頭牛的開始時間小於隊頭的結束時間,則需要新增一個牛棚
反之,如果該頭牛的開始時間大於隊頭的結束時間,則表示可以與其共用一個牛棚,於是彈出,並將該頭牛與牛棚號加入隊列
過程中將結果存入pos數組中。pos[i]表示第i頭牛所在的牛棚號。

AC代碼:

#include<iostream>
#include<algorithm>
#include<vector>
#include<queue>
using namespace std;

int n;

struct ST{
	int l, r;
	int i;
};

struct node{
	int no;
	int end;
	
	// 以畜欄結束時間早排序 
	bool operator < (const node & c) const{
		return end > c.end;
	}
	
	// 構造函數
	node(int no, int end):no(no), end(end){}
};

int cmp(ST a, ST b){
	return a.l < b.l;
}

ST mp[50010];
int pos[1000010];

priority_queue<node> q;

int main(){
	cin>>n;
	
	for(int i = 0; i<n; i++){
		cin>>mp[i].l>>mp[i].r;
		mp[i].i = i;
	}
	sort(mp, mp+n, cmp);
	int res = 0;
	for(int i = 0; i<n; i++){
		if(q.empty()){
			++res;
			pos[ mp[i].i] = res;
			q.push(node(res, mp[i].r));
		}
		else {
			node nod = q.top();
			if(nod.end < mp[i].l){
				q.pop();
				pos[mp[i].i] = nod.no;
				q.push(node(nod.no, mp[i].r));
			}
			else {
				++res;
				pos[mp[i].i] = res;
				q.push(node(res, mp[i].r));
			}	
		}
	}
	
	cout<<res<<endl;
	for(int i = 0; i<n; i++){
		cout<<pos[i]<<endl;
	}
	return 0;
} 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章