我们有 N 个工作,以及它们的开始和结束时间。我们可以在特定时刻同时做两份工作。如果一项工作在另一场演出开始的同一时刻结束,那么我们就做不到。我们需要检查是否有可能完成所有的工作。
例子:
Input : Start and End times of Jobs
1 2
2 3
4 5
Output : Yes
By the time third job starts, both jobs
are finished. So we can schedule third
job.
Input : Start and End times of Jobs
1 5
2 4
2 6
1 7
Output : No
All 4 jobs needs to be scheduled at time
3 which is not possible.
我们首先根据工作的开始时间对工作进行排序。然后我们同时启动两个作业,并检查第三个作业的开始时间等是否大于前两个作业的结束时间和结束时间。
下面给出上述想法的实现。
C++
// CPP program to check if all jobs can be scheduled
// if two jobs are allowed at a time.
#include
using namespace std;
bool checkJobs(int startin[], int endin[], int n)
{
// making a pair of starting and ending time of job
vector > a;
for (int i = 0; i < n; i++)
a.push_back(make_pair(startin[i], endin[i]));
// sorting according to starting time of job
sort(a.begin(), a.end());
// starting first and second job simultaneously
long long tv1 = a[0].second, tv2 = a[1].second;
for (int i = 2; i < n; i++) {
// Checking if starting time of next new job
// is greater than ending time of currently
// scheduled first job
if (a[i].first >= tv1)
{
tv1 = tv2;
tv2 = a[i].second;
}
// Checking if starting time of next new job
// is greater than ending time of ocurrently
// scheduled second job
else if (a[i].first >= tv2)
tv2 = a[i].second;
else
return false;
}
return true;
}
// Driver code
int main()
{
int startin[] = { 1, 2, 4 }; // starting time of jobs
int endin[] = { 2, 3, 5 }; // ending times of jobs
int n = sizeof(startin) / sizeof(startin[0]);
cout << checkJobs(startin, endin, n);
return 0;
}
Python3
# Python3 program to check if all
# jobs can be scheduled if two jobs
# are allowed at a time.
def checkJobs(startin, endin, n):
# making a pair of starting and
# ending time of job
a = []
for i in range(0, n):
a.append([startin[i], endin[i]])
# sorting according to starting
# time of job
a.sort()
# starting first and second job
# simultaneously
tv1 = a[0][1]
tv2 = a[1][1]
for i in range(2, n):
# Checking if starting time of next
# new job is greater than ending time
# of currently scheduled first job
if (a[i][0] >= tv1) :
tv1 = tv2
tv2 = a[i][1]
# Checking if starting time of next
# new job is greater than ending time
# of ocurrently scheduled second job
elif (a[i][0] >= tv2) :
tv2 = a[i][1]
else:
return 0
return 1
# Driver Code
if __name__ == '__main__':
startin = [1, 2, 4] # starting time of jobs
endin = [2, 3, 5] # ending times of jobs
n = 3
print(checkJobs(startin, endin, n))
# This code is contributed by
# Shubham Singh(SHUBHAMSINGH10)
输出:
1
另一种解决方案是找到需要随时安排的最大作业数。如果此计数大于 2,则返回 false。否则返回真。
如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程和学生竞争性编程现场课程。