解題思路
直接刪除一座塔後重新求最短路徑會花 O(n⁴)。改把拆除順序倒過來:初始沒有塔,每次加回一座 k,使用 Floyd 轉移 d[i][j]=min(d[i][j],d[i][k]+d[k][j])。距離矩陣對全部端點都更新,只有允許的中繼點逐步增加。
加回 k 後,活躍塔恰好對應正向拆除 k 之前的狀態。此時將所有活躍有序點對的距離相加,再加到總能量;對角為 0 不影響。不要先把原圖完整 Floyd 化,否則會允許已拆除的塔當中繼。n=500 時總和需要 64 位元,塔編號直接用本地的 0..n−1。
Step-by-step animation
示意:兩塔距離 0→1=4、1→0=7,拆除順序0、1
步驟 1 / 3
反向起點
沒有活躍塔,總能量 0。
活躍數0
- 總能量
- 0
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <algorithm>
#include <numeric>
#include <cmath>
#include <iomanip>
#include <queue>
#include <deque>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <array>
#include <tuple>
#include <functional>
#include <limits>
#include <cstdint>
#include <cctype>
#include <utility>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
vector<vector<long long>> d(n, vector<long long>(n));
for (auto &row : d)
for (auto &x : row)
cin >> x;
vector<int> order(n), active;
for (int &x : order)
cin >> x;
long long ans = 0;
for (int pos = n - 1; pos >= 0; --pos) {
int k = order[pos];
active.push_back(k);
for (int i = 0; i < n; ++i)
for (int j = 0; j < n; ++j)
d[i][j] = min(d[i][j], d[i][k] + d[k][j]);
for (int i : active)
for (int j : active)
ans += d[i][j];
}
cout << ans << '\n';
}
}
先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。