Given N tasks with starting time and end time ( S1, E1 ), ( S2, E2 ), ..., ( SN, EN), try to distribute and finish them with the minimum number of machines.
At the same time there is at most one running task on each machine and one task should keep running on one machine.
The first line contains 1 integer N (1 ≤ N ≤ 100000), the number of tasks.
The following N lines each contain 2 integers Si and Ei,(0 ≤ Si < Ei ≤ 1000000000), the starting and end time of i-th task.
The minimum number of machine needed.
5 1 10 2 7 6 9 3 4 7 10
3
题意:给n个的任务开始和结束时间,然后让你给这些任务分配执行任务的机器,每个机器在一段时间只能执行一个任务,问最少要分配多少机器。
思路:思路来源于挑战40页的区间问题,那个问题按照结束时间排序,求得是最多能接任务的数量,认真分析本题,可以想到:每个任务都会被分配机器去完成,所以可以按任务开始时间从小到大排序;用优先队列来维护当前机器正在做的任务;优先队列按照任务结束时间从小到大排序,结束最早就最早出队,队列最终尺寸就是答案。
#include<bits/stdc++.h> using namespace std; #define maxn 1000005 struct node { int s; int t; bool operator <(const node&a)const { return a.t<t; } }a[maxn]; bool cmp(node a,node b) { return a.s==b.s?a.t<b.t:a.s<b.s; } priority_queue <node> p; int main() { int n; cin>>n; for(int i=0;i<n;i++) cin>>a[i].s>>a[i].t; sort(a,a+n,cmp); p.push(a[0]); int sum=1; for(int i=1;i<n;i++) { if(p.top().t<=a[i].s) {p.pop();} p.push(a[i]); } cout<<p.size()<<endl; }