首次练习面向对象的编程,原因是连续两道涉及时间的题了,想写个每次碰到时间稍微改改就能用的代码,当然这里为了图方便,变量都public了,方法的话只涉及了类的声明,构造函数,运算符重载,本来还想试试继承但是好像不太符合逻辑就没试,十分坎坷得写出了一坨能AC的💩。
#include <iostream>
#include <vector>
using namespace std;
class Time{//变量时、分、秒,方法包括时间相减,几分后的时间,时间相比,时间设定,转化为秒数。
public:
int hour, minute, second;
int toSecond(){
return this->hour * 3600 + this->minute * 60 + this->second;
}
void setTime(int a,int b,int c){
this->hour = a;
this->minute = b;
this->second = c;
}
bool operator<(Time time){
return this->toSecond() < time.toSecond();
}
Time operator+(int m){
Time time;
time.second = this->second;
time.hour = this->hour + (this->minute + m) / 60;
time.minute = (this->minute + m) % 60;
return time;
}
Time operator-(const Time &a){
Time time;
time.second = this->second - a.second;
time.minute = this->minute - a.minute;
time.hour = this->hour - a.hour;
if(time.second < 0){
time.second += 60;
time.minute--;
}
if(time.minute < 0){
time.minute += 60;
time.hour--;
}
return time;
}
};
class Custom{
public:
int use;
Time time;
Custom(int a, int b, int c, int d);
};
Custom::Custom(int a, int b, int c, int d){
time.setTime(a, b, c);
use = d;
}
int main(){
int n, k, h, m, s, use;
Time t0, tt;
t0.setTime(8, 0, 0);//上班时间
tt.setTime(17, 0, 0);//下班时间
cin >> n >> k;
vector<Custom> vc;
vector<Time> vw(k,t0);//各窗口当前时间
for(int i = 0; i < n; i++){
scanf("%d:%d:%d %d", &h, &m, &s, &use);
Custom c(h, m, s, use);
if(!(tt < c.time)){//5点以后来的不用算进去
int j = 0;
while(j!=vc.size() && vc[j].time<c.time)j++;
vc.insert(vc.begin()+j, c);//队头是来的最早的
}
}
int countTime = 0;
for(int i = 0; i < vc.size(); i++){//从来得最早的人开始
int minId = 0;
Time minTime = vw[0];
for(int j = 1; j < k; j++){//找到最早结束的窗口
if(vw[j] < minTime){
minTime = vw[j];
minId = j;
}
}
if(vc[i].time < vw[minId]){//如果客户来的早
countTime += (vw[minId] - vc[i].time).toSecond();
vw[minId] = vw[minId] + vc[i].use;
}
else vw[minId] = vc[i].time + vc[i].use;//如果窗口开得早
}
printf("%.1f", countTime / (60.0 * vc.size()));
}