hihocoder-任务分配

Description

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.
Input

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.
Output

The minimum number of machine needed.

题解
题目大意是给定n个任务的起始时间,求问最少需要多少台机器。
这里写图片描述
首先我们对几个随意的任务进行画图分析,可以分为两种情况—>1.两个任务开始时间一样,但是两者任务时间长度不同;2.两个任务开始时间不同,两者任务时间长度相同或不同。
采用贪心的策略解决,我们对于情况一选择时间长度小的。情况二选择时间长度早的。这样可以得到当前机器应该运行的任务单。这里就不详细举例了,请自己脑补。
至于重开机器的情况,我们的操作的效果是等价的,假设当前执行任务为S,任务池中存在一个可以连接S的任务P,那么一个可以连接S的先任务必然可以连接P(S的开始时间早于P).
最后我们可以容易得到对所有任务按照开始时间排序,候选结束时间排序。然后采用优先队列对任务的序列进行维护即可。

数据结构分析

采用一个类T来存放任务的开始start和结束end信息

这里写图片描述

任务池

实现池
这里写图片描述


运行过程

输入
这里写图片描述

  • q容器内(输入初始)
    这里写图片描述

    细心的童鞋会发现2,3位置反了,那是因为我重写了运算符

  • que容器内变化(优先队列)

[ ] 初始状态
这里写图片描述
[ ] q[0]
这里写图片描述
[ ] q[1]
这里写图片描述
[ ] q[2]
这里写图片描述

[ ] q[3]

这里写图片描述
[ ] End.

———–在AC之路上一路向东


附上源代码

#include <iostream>
#include <queue>

using namespace std;

class T {

public:
    int s,e;
    T(int a, int b):s(a), e(b){

    }
};

bool operator < (const T &t1,const T &t2)
{
    if(t1.s != t2.s)    return t1.s >
        t2.s;
    else    return t1.e > t2.e;
}

priority_queue<T> q;


void slove(){
    priority_queue<int,vector<int>, greater<int>> que;
    que.push(0);
    int tmp;
    while (!q.empty()){
        T t = q.top();
        q.pop();
        tmp = que.top();
        que.pop();
        if (tmp <= t.s) {
            que.push(t.e);
        }else{
            que.push(t.e),que.push(tmp);
        }

    }
    cout<<que.size()<<endl;
}


int main(){
    int n,v1,v2;
    //while(){
    cin >> n;
        //
        for (int i = 0; i < n; i++) {
            cin>>v1>>v2;
            q.push(T(v1,v2));
        }
        slove();
    //}
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_31979619/article/details/73505941