有 N 個星系 (節點),M 個蟲洞 (有向邊),每條邊有權重 (時間)。教授想利用蟲洞回到過去,即尋找是否存在負權環 (總權重 < 0 的環)。輸出 "possible" 或 "not possible"。
#includeusing namespace std; struct Edge { int u, v, w; }; const int INF = 0x3f3f3f3f; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int T; cin >> T; while (T--) { int N, M; cin >> N >> M; vector edges; edges.reserve(M + N); for (int i=0;i >u>>v>>w; edges.push_back({u, v, w}); } // 超級源點 0 -> 所有節點 (1~N),權重 0 for (int i=1;i<=N;++i) edges.push_back({0, i, 0}); vector dist(N+1, INF); dist[0] = 0; bool hasNegCycle = false; // N 輪鬆弛 (含超級源點共 N+1 個節點,需 N 輪) for (int i=0;i dist[e.u] + e.w) { dist[e.v] = dist[e.u] + e.w; updated = true; if (i == N-1) hasNegCycle = true; // 第 N 輪仍更新 } } if (!updated) break; // 提前收斂 } cout << (hasNegCycle ? "possible" : "not possible") << '\n'; } return 0; }
int,建議用 long long。隊列優化 Bellman-Ford (SPFA) 平均更快,但最壞仍 O(NM) 且有 Hack 數據導致 TLE。競程建議用標準 Bellman-Ford 或 SLF/LLL 優化版 SPFA。