1.你需要知道可以用快速排序函数结合排序规则函数来给取放排序。
2.还要知道vector数组的强大功能。
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
struct Action {
int room;
int time;
int operators; // 0:放回, 1:取
Action(int room1,int time1,int operators1){//构造函数
room = room1;
time = time1;
operators = operators1;
}
};
bool cmp(Action a,Action b) {
if(a.time < b.time) return true;
else if(a.time == b.time && a.operators < b.operators)return true;
else if(a.time == b.time && a.operators == b.operators && a.room < b.room)return true;
return false;//首先根据时间的先后排序。时间相同,根据取放排序,先放后取。时间相同,是相同的操作,先房间号低的操作。
}
int main() {
int N, K;
cin >> N >> K;
vector<Action> actions;
vector<int> states(N+1);//比N大一防止向量数组溢出,N+1个参数
for(int n=1; n<=N; n++) states[n] = n;
for(int k=0; k<K; k++) {
int room, begin, length;
cin >> room >> begin >> length;
actions.push_back(Action(room, begin, 1));//取钥匙输入开始时间
actions.push_back(Action(room, begin+length, 0));//放回钥匙输入结束时间(开始时间+持续时间)
}
sort(actions.begin(), actions.end(),cmp);//调用cmp函数,给sort()排序加上具体的规则
for(int i=0; i<actions.size(); i++) {
Action act = actions[i];//定义一个Action结构体变量,act前面加不加&都可以成功赋值
if(act.operators == 0) { // 放回
for(int n=1; n<=N; n++) {
if(states[n] == -1) {
states[n] = act.room;
break;
}
}
}
else { // 取钥匙
for(int n=1; n<=N; n++) {
if(states[n] == act.room) {
states[n] = -1;//-1是对拿走钥匙后对空位置的标记
break;
}
}
}
}
for(int n=1; n<=N; n++) {
cout<< states[n] << " ";
}
cout<<endl;
return 0;
}
3.结构体数组要熟悉构造函数,用来传参数。