题目链接
题解
先按照 d e a d l i n e deadline deadline 排序,然后贪心即可,可抽象为事件都紧凑在 e n d end end 附近。
- 当当前任务的起始时间大于 e n d end end,时,更新 e n d end end为当前的 d e a d l i n e deadline deadline, 且 a n s ans ans 加一;
- 否则
e
n
d
end
end 的更新规则是:
- 当当前的 d e a d l i n e deadline deadline 大于 e n d end end, e n d end end才加1;
- 否则直接将任务添加到 e n d end end 之前,无需担心溢出,因为起始时间在排序时也是升序,一定放得下。
代码
/*
* @Date: 2021-12-09 15:53:49
* @LastEditors: fuchaoxin
* @LastEditTime: 2021-12-09 17:19:58
* @FilePath: \Visual Studio\UVA\Laptop.cpp
*/
#include <bits/stdc++.h>
#include <algorithm>
#include <cmath>
using namespace std;
int compare(const void *a, const void *b)
{
int *m = (int *)a, *n = (int *)b;
if (m[1] != n[1])
{
return m[1] - n[1]; // ascent
}
else
{
return m[0] - n[0]; // ascent
}
}
int main(void)
{
int T;
scanf("%d", &T);
while (T-- > 0)
{
int n;
scanf("%d", &n);
int intervals[n][2];
// initialize the intervals
for (int i = 0; i < n; i++)
{
scanf("%d%d", &intervals[i][0], &intervals[i][1]);
}
qsort(intervals, n, sizeof(intervals) / n, compare);
// // display
// for (int i = 0; i < n; i++)
// {
// printf("[%d, %d]\n", intervals[i][0], intervals[i][1]);
// }
int end = intervals[0][1];
int ans = 0; // num of the idle periods
// solve
for (int i = 1; i < n; i++)
{
if (intervals[i][0] > end) // the start time is bigger than current end time
{
end = intervals[i][1];
ans++; // idle++
}
else // update the end time
{
if(intervals[i][1] > end){ // add after the endtime, the end time only plus one
end++;
}
// else if(intervals[i][1] == end) { // just add infront of the endtime, do worry about overflow
// continue;
// }
}
}
cout << ans << endl;
}
return 0;
}