题解:P13849 [CERC 2023] Equal Schedules

· · 题解

通过阅读此题可以得知写这个题目的方法有几种,比如: 1.结构化方法 2.函数式方法 3.面向对象方法 4.高效的单次遍历方法 5.现代C++方法(注:使用C++20的ranges特性,代码简洁现代) 以下代码是第一种方法(简单一点):

#include<bits/stdc++.h>
using namespace std;

map<string, int> processSchedule(const vector<string>& lines) {
    map<string, int> result;
    for (const auto& line : lines) {
        if (line.empty()) continue;
        istringstream iss(line);
        int start, end;
        string name;
        iss >> start >> end >> name;
        result[name] += end - start;
    }
    return result;
}

int main() {
    vector<string> inputLines;
    string line;
    while (getline(cin, line) && line != "======") {
        inputLines.push_back(line);
    }
    auto separator = find(inputLines.begin(), inputLines.end(), "------");
    vector<string> firstLines(inputLines.begin(), separator);
    vector<string> secondLines(next(separator), inputLines.end());
    auto first = processSchedule(firstLines);
    auto second = processSchedule(secondLines);
    map<string, int> differences;
    for (const auto& [name, time] : second) {
        int diff = time - first[name];
        if (diff != 0) differences[name] = diff;
    }
    for (const auto& [name, time] : first) {
        if (!second.count(name)) differences[name] = -time;
    }
    if (differences.empty()) {
        cout << "No differences found." << endl;
    } else {
        for (const auto& [name, diff] : differences) {
            cout << name << (diff >= 0 ? " +" : " ") << diff << endl;
        }
    }

    return 0;
}

结束!