#define _crt_secure_no_warnings#include<iostream> #include <string> #include <iomanip> #include <cstdlib> #include <cstdio> #include <vector> #include <algorithm> #include <cmath># include<map>using namespace Std;const int INF = 10001;struct Edge {int from;int to;int wgt; Edge (int f =-1, int t =-1, int w = INF): from (f), to (t), WGT (w) {}};bool Bellmanford (vector<edge> &g, int num, int src) {vector<int> dist (num+1, INF);d ist[src] = 0;int st;for (st = 0; St < num; ++st) {bool Chg = false;for (i NT i = 0; I < g.size (); ++i) {if (dist[g[i].to] > Dist[g[i].from] + g[i].wgt) {dist[g[i].to] = Dist[g[i].from] + G[i].wgt;chg = true;}} if (!CHG) break;} if (st = = num) return true;else return false;} int main (void) {int f;cin >> f;while (f--) {int N, m, w;cin >> n >> M >> w;vector<edge> g;for (int i = 0; i < M; ++i) {int S, E, t;scanf ("%d%d%d", &s, &e, &t); G.push_back (Edge (S, E, t)); G.push_back(Edge (E, S, T));} for (int i = 0; i < W; ++i) {int S, E, t;scanf ("%d%d%d", &s, &e, &t); G.push_back (Edge (S, E,-T));} if (Bellmanford (G, N, 1)) cout << "YES" << endl;elsecout << "NO" << Endl;} System ("pause"); return 0;}
If you use STL to make adjacency matrix, it will time out, the memory request release cost is too large. and the title <span style= "font-family: ' Times New Roman ', times, serif; font-size:16px; " >n</span><span style= "font-family: ' Times New Roman ', times, serif; font-size:16px; " > (1≤ </span><span style= "font-family: ' Times New Roman ', times, serif; font-size:16px;" >n</span><span style= "font-family: ' Times New Roman ', times, serif; font-size:16px; " > ≤500), <span style= "font-family: ' Times New Roman ', times, serif; font-size:16px; " >m</span><span style= "font-family: ' Times New Roman ', times, serif; font-size:16px; " > (1≤ </span><span style= "font-family: ' Times New Roman ', times, serif; font-size:16px;" >m</span><span style= "font-family: ' Times New Roman ', times, serif; font-size:16px; " > ≤2500), <span style= "font-family: ' Times New Roman ', times, serif; font-size:16px; " >w</span><span style= "font-family: ' Times New Roman ', times, serif; Font-size:16px; " > (1≤ </span><span style= "font-family: ' Times New Roman ', times, serif; font-size:16px;" >w</span><span style= "font-family: ' Times New Roman ', times, serif; font-size:16px; " >&NBSP;≤200) is obviously sparse, and if it is represented by an adjacency matrix, the cost of the search will be significant. So consider the storage edge information .</span></span></span>
POJ 3259 wormholes AC code (negative weight ring judgment, Bellmanford)