#54542: C++解答


kita197 (KK)


#include <iostream>
#include <vector>
#include <string>
#include <map>
#include <algorithm>

using namespace std;

typedef long long ll;

struct City {
    string name;
    ll income;
    int id;
};

struct Event {
    string type;
    string cityName;
};

bool cmp(const City& a, const City& b) {
    if (a.income != b.income) return a.income < b.income;
    return a.id < b.id; // 收入相同時,按輸入先後順序
}

int toM(string s) {
    return stoi(s.substr(0, 4)) * 12 + stoi(s.substr(5, 2));
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(NULL);

    string d0_s;
    ll M;
    while (cin >> d0_s >> M) {
        vector<City> cities;
        map<string, int> nameToIdx;
        string name;
        int count = 0;

        // 1. 讀取城市
        while (cin >> name && name != "----") {
            ll inc;
            cin >> inc;
            nameToIdx[name] = count;
            cities.push_back({name, inc, count});
            count++;
        }

        // 2. 讀取 X, Y
        ll X, Y;
        cin >> X >> Y;

        // 3. 讀取事件
        map<int, vector<Event>> events;
        string dateK, cName, typeH;
        while (cin >> dateK && dateK != "----") {
            cin >> cName >> typeH;
            events[toM(dateK)].push_back({typeH, cName});
        }

        // 4. 讀取終點日期
        string d1_s;
        cin >> d1_s;

        int startT = toM(d0_s);
        int endT = toM(d1_s);

        // 5. 模擬 (依照題目:月初算錢 -> 發生變化 -> 總結)
        // 題目說 D1 的日期一定在 D0 之後
        for (int t = startT + 1; t <= endT; ++t) {
            // A. 計算月收入
            for (int i = 0; i < (int)cities.size(); ++i) {
                M += cities[i].income;
            }

            // B. 城市變化
            if (events.count(t)) {
                for (auto& ev : events[t]) {
                    int idx = nameToIdx[ev.cityName];
                    if (ev.type == "BUILT") cities[idx].income += X;
                    else if (ev.type == "BOOST") cities[idx].income += X * X;
                    else if (ev.type == "DAMAGE") {
                        cities[idx].income -= Y;
                        if (cities[idx].income < 0) cities[idx].income = 0;
                    }
                    else if (ev.type == "RUIN") cities[idx].income = 0;
                }
            }
            // C. 帳冊總結 (如果是 D1 就跳出,但因為迴圈條件 t <= endT,自然會在此結束)
        }

        // 6. 排序與輸出
        sort(cities.begin(), cities.end(), cmp);

        cout << d1_s << " " << M << endl;
        for (const auto& c : cities) {
            cout << c.name << " " << c.income << endl;
        }
    }
    return 0;
}