CCF(公共钥匙盒):思维+模拟

公共钥匙盒

201709-2

这题的思路一开始不是很清晰,一开始想用贪心去做。但是发现按照题目的思路不对。所以这里采用的是类似于多项式的加减的处理。

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<string>
#include<vector>
#include<map>
using namespace std;
const int maxn=1003;
int n,k;
int locate[maxn];//第i个空放的钥匙编号
struct node{
    int w;
    int time;
    bool operator<(const node& t)const{
        if(time==t.time)
            return w<t.w;
        return time<t.time;
    }
};
node barr[maxn];
node retu[maxn];
map<int,int> lock;//第i把钥匙在第j个孔
int main(){
    // ios::sync_with_stdio(false);
    // cin.tie(0);
    cin>>n>>k;
    for(int i=0;i<n;i++){
        locate[i]=i;
        lock[i]=i;
    }
    for(int i=0;i<k;i++){
        int w,st,dur;//编号,开始时间,上课时间
        cin>>w>>st>>dur;
        w--;
        barr[i]=node{w,st};
        retu[i]=node{w,dur+st};
    }
    sort(barr,barr+k);//-------------排序
    sort(retu,retu+k);
    int i,j;
    for(i=0,j=0;i<k&&j<k;){
        if(barr[i].time<retu[j].time){
            int lo=lock[barr[i].w];//取出钥匙放的空
            lock[barr[i].w]=-1;//钥匙放在的空为-1
            locate[lo]=-1;//这个空放的钥匙编号为-1,已经取出来了
            i++;//先借
        }else{//归还时间小于等于借的时间的时候
            for(int k1=0;k1<n;k1++){
                if(locate[k1]==-1){
                    locate[k1]=retu[j].w;//第k个空放钥匙编号
                    lock[retu[j].w]=k1;//钥匙放在第k个空
                    break;
                }
            }
            j++;//先还
        }
    }
    //cout<<j<<endl;
    if(j<k){
        for(;j<k;j++){
            for(int k1=0;k1<n;k1++){
                if(locate[k1]==-1){
                    locate[k1]=retu[j].w;//第k个空放钥匙编号
                    lock[retu[j].w]=k1;//钥匙放在第k个空
                    break;
                }
            }
        }
    }
    for(int i=0;i<n-1;i++){
        //cout<<i<<endl;
        cout<<locate[i]+1<<" ";
    }
    cout<<locate[n-1]+1<<endl;
    //system("pause");
    return 0;
}
posted @ 2019-09-03 16:21  Garrett_Wale  阅读(285)  评论(0编辑  收藏  举报