源代码

class Patient {
    constructor(id, priority) {
        this.id = id;
        this.priority = priority;
    }
}

class Doctor {
    constructor() {
        this.queue = [];
    }

    enqueue(patient) {
        const index = this.queue.findIndex(p => p.priority < patient.priority);
        if (index !== -1) {
            this.queue.splice(index, 0, patient);
        } else {
            this.queue.push(patient);
        }
    }

    dequeue() {
        if (this.queue.length === 0) {
            return null;
        }
        return this.queue.shift();
    }

    isEmpty() {
        return this.queue.length === 0;
    }
}

class Hospital {
    constructor() {
        this.doctors = new Map();
        this.patientId = 1;
    }

    handleIN(doctorId, priority) {
        if (!this.doctors.has(doctorId)) {
            this.doctors.set(doctorId, new Doctor());
        }
        const patient = new Patient(this.patientId++, priority);
        this.doctors.get(doctorId).enqueue(patient);
    }

    handleOUT(doctorId) {
        if (!this.doctors.has(doctorId) || this.doctors.get(doctorId).isEmpty()) {
            return "EMPTY";
        }
        const patient = this.doctors.get(doctorId).dequeue();
        return patient.id.toString();
    }

    simulate(events) {
        const results = [];
        for (const event of events) {
            const [type, doctorId, ...priorityParts] = event.split(' ');
            const doctorIdNum = parseInt(doctorId);
            if (type === 'IN') {
                const priority = parseInt(priorityParts.join(' '));
                this.handleIN(doctorIdNum, priority);
            } else if (type === 'OUT') {
                const result = this.handleOUT(doctorIdNum);
                results.push(result);
            }
        }
        return results;
    }
}

// 输入样例
const events = [
    "IN 1 1",
    "OUT 1",
    "IN 1 1",
    "IN 2 1",
    "OUT 1",
    "OUT 2",
    "OUT 1"
];

// 创建医院实例并模拟事件
const hospital = new Hospital();
const results = hospital.simulate(events);

// 输出结果
console.log(results.join('\n'));

运行结果

1 2 3 EMPTY