此题应使用模拟的思路。
首先记录机器当前的开关状态 (开启为 ,关闭为 )以及最近一次被启用的时间 。
初始时 (即机器开启)且 。
用优先队列按时间从小到大存储所有青木经过的事件和机器重新开启的事件(在输入时,并不存在机器重新开启的事件)。
具体地,可以使用 pair,第一项记录事件时间,第二项记录事件类型。
然后遍历优先队列,取出时间最靠前的事件,其发生时间定义为 。分情况讨论:
1. 当事件类型为青木经过时
- 如果此时 (即机器开启),那么 (关闭机器);向优先队列中添加一次机器重新开启的事件,时间为 ;记录机器开启至今的时长。
- 如果此时 (即机器已被关闭),则不用处理。
2. 当事件类型为机器重新开启时
- (开启机器);
- (保存事件发生时间)。
最后统计所有机器开启的时长总和。别忘了时间为 时也要进行统计。
AC Code
#include<bits/stdc++.h>
using namespace std;
typedef pair<int, int> PIR;//PIR.second=0表示关闭,1表示开启
priority_queue<PIR, vector<PIR>, greater<PIR> > todo;
int main()
{
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
bool opening = 1;
int N, T;
int t = 0, tt = 0;
cin>>N>>T;
for(int i = 1; i <= N; i++){
int x;
cin>>x;
todo.push({x, 0});
}
while(!todo.empty()){
PIR task = todo.top();
todo.pop();
if(task.first > T) break;
if(!task.second){
if(opening){
//关闭
opening = 0;
tt += (task.first - t);//添加时间段
todo.push({task.first + 100, 1});//100秒后开启
}
}else{
if(!opening){
//开启
opening = 1;
t = task.first;
}
}
}
if(opening){
//别忘了最后一段
tt += (T - t);
}
cout<<tt;
}