a128困難公式解析・拓樸求值與循環依賴

TOI 2025/09 潛力組:試算表

讓可求值的儲存格逐步解鎖,並辨識受循環影響的全部 ERROR。

前往題目練習 →回報教學錯誤令 V=MN≤2600,每格最多兩條引用邊;時間 O(V+輸入字元數)、空間 O(V)。

解題思路

解析每格的兩個運算元:數字直接加到該格的暫存值,位址則建立『被引用格→公式格』的邊並增加待完成數。一般數字格沒有依賴。從待完成數為 0 的格子開始,將其值取模後傳給所有引用者;引用者收到全部運算元後才入隊。

每個出隊格都只依賴已完成格,因此值正確。若兩個運算元引用同一格,保留兩條邊與兩份待完成數,才能正確加兩次。最後沒有出隊的格子必在循環內或依賴未完成的循環:若剩餘圖沒有循環,它就會有待完成數 0 的節點,與演算法已停止矛盾。這些格子全部輸出 ERROR,包含循環下游。

Step-by-step animation

公開範例:A1=3,B1=A1+4,A2=B1+B1,B2=B2+1

回報動畫錯誤
步驟 1 / 3

初始可算格

A1 無依賴,B1 尚待 A1,A2 需要兩份 B1,B2 自我依賴。

A1:3
B1:待1
A2:待2
B2:待1
queue
A1

Reference solution

回報程式錯誤

完整程式

#include <iostream>
#include <vector>
#include <string>
#include <queue>
using namespace std;
const long long MOD = 1000000007;
int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int m, n;
    cin >> m >> n;
    int total = m * n;
    vector<long long> value(total, 0);
    vector<int> pending(total, 0);
    vector<vector<int>> users(total);
    auto addOperand = [&](int u, const string &operand) {
        if (operand[0] >= '0' && operand[0] <= '9')
            value[u] += stoi(operand);
        else {
            int col = operand[0] - 'A', row = stoi(operand.substr(1)) - 1;
            users[row * n + col].push_back(u);
            ++pending[u];
        }
    };
    for (int u = 0; u < total; ++u) {
        string token;
        cin >> token;
        if (token[0] != '=')
            addOperand(u, token);
        else {
            auto plus = token.find('+');
            addOperand(u, token.substr(1, plus - 1));
            addOperand(u, token.substr(plus + 1));
        }
    }
    queue<int> q;
    vector<bool> ready(total, false);
    for (int u = 0; u < total; ++u)
        if (!pending[u])
            q.push(u);
    while (!q.empty()) {
        int u = q.front();
        q.pop();
        ready[u] = true;
        value[u] %= MOD;
        for (int v : users[u]) {
            value[v] = (value[v] + value[u]) % MOD;
            if (--pending[v] == 0)
                q.push(v);
        }
    }
    for (int r = 0; r < m; ++r) {
        for (int c = 0; c < n; ++c) {
            if (c)
                cout << ' ';
            int u = r * n + c;
            if (ready[u])
                cout << value[u];
            else
                cout << "ERROR";
        }
        cout << '\n';
    }
}

先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。

更多