CCF 201709-02公共钥匙盒

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.结构体数组要熟悉构造函数,用来传参数。

  • 8
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 6
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值