跳到正文

题解

题解:P6968 [NEERC 2016] Expect to Wait

#SUSPENDED#约 5 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2026年4月26日
篇幅
约 5 分钟
题目
P6968

版本

  1. v1当前

题目传送门 [NEERC 2016] Expect to Wait

题目分析

1.系统状态由可用车辆数和排队队列组成

2.每个”-tk”操作代表k人排队取车,每个”+tk”操作代表增加k辆车

3.等待时间计算需要考虑先到先服务原则

算法内容

  • 使用优先队列(最小堆)管理排队请求
  • 维护当前可用车辆数和待处理的请求队列

Solution

C++
#include<bits/stdc++.h>
using namespace std;
struct Operation {
    char type; // '+'表示停车,'-'表示取车
    int time;  // 操作时间
    int count; // 车辆数量
};
int main() {
    ios::sync_with_stdio(false);
    int n, q;
    cin >> n >> q;
    vector<Operation> operations(n);
    long long total_park = 0, total_take = 0;
    // 读取操作并统计总停车数和总取车数
    for (int i = 0; i < n; i++) {
        char type;
        int t, k;
        cin >> type >> t >> k;
        operations[i] = {type, t, k};
        if (type == '+') {
            total_park += k;
        } else {
            total_take += k;
        }
    }
    // 处理每个查询
    for (int i = 0; i < q; i++) {
        long long b;
        cin >> b;
        // 判断是否会出现无限等待
        if (total_take > total_park + b) {
            cout << "INFINITY\n";
            continue;
        }
        long long current_bikes = b;
        long long total_wait_time = 0;
        queue<pair<int, int>> waiting; // 等待队列:(开始等待时间, 等待人数)

        for (const Operation& op : operations) {
            if (op.type == '+') {
                // 停车操作:增加车辆并尝试满足等待队列
                current_bikes += op.count;

                while (current_bikes > 0 && !waiting.empty()) {
                    auto front = waiting.front();
                    int start_time = front.first;
                    int wait_count = front.second;

                    if (current_bikes >= wait_count) {
                        // 可以满足当前所有等待的人
                        total_wait_time += (long long)(op.time - start_time) * wait_count;
                        current_bikes -= wait_count;
                        waiting.pop();
                    } else {
                        // 只能满足部分等待的人
                        total_wait_time += (long long)(op.time - start_time) * current_bikes;
                        waiting.front().second -= current_bikes;
                        current_bikes = 0;
                        break;
                    }
                }
            } else {
                // 取车操作:先使用现有车辆,不足则加入等待队列
                if (current_bikes >= op.count) {
                    current_bikes -= op.count;
                } else {
                    int take_now = current_bikes;
                    int wait_count = op.count - take_now;
                    current_bikes = 0;
                    waiting.push({op.time, wait_count});
                }
            }
        }//有点长
        cout << total_wait_time << endl;
    }
    return 0;
}
原文