| :
include "pch.h" #include #include #include #include #include #include #include #include #include using namespace std; struct Edge { int from; int to; int weight; }; struct Node { int id; int distance; int parent; }; struct Graph { vector nodes; vector edges; }; Graph ReadGraph(string filename) { Graph g; ifstream input(filename); string line; while (getline(input, line)) { istringstream iss(line); int from, to, weight; iss >> from >> to >> weight; g.edges.push_back({ from, to, weight }); } input.close(); set nodes; for (auto edge : g.edges) { nodes.insert(edge.from); nodes.insert(edge.to); } for (auto node : nodes) { g.nodes.push_back({ node, INT_MAX, -1 }); } return g; } void PrintGraph(Graph g) { for (auto edge : g.edges) { cout << edge.from << " " << edge.to << " " << edge.weight << endl; } } void PrintNodes(Graph g) { for (auto node : g.nodes) { cout << node.id << " " << node.distance << " " << node.parent << endl; } } bool Relax(Edge edge, Graph& g) { if (g.nodes[edge.to].distance > g.nodes[edge.from].distance + edge.weight) { g.nodes[edge.to].distance = g.nodes[edge.from].distance + edge.weight; g.nodes[edge.to].parent = edge.from; return true; } return false; } bool BellmanFord(Graph& g) { g.nodes[0].distance = 0; for (int i = 0; i < g.nodes.size() - 1; i++) { for (auto edge : g.edges) { Relax(edge, g); } } for (auto edge : g.edges) { if (Relax(edge, g)) { return false; } } return true; } int main() { Graph g = ReadGraph("graph.txt"); PrintGraph(g); cout << endl; if (BellmanFord(g)) { cout << "No negative cycles" << endl; PrintNodes(g); } else { cout << "Negative cycle" << endl; } return 0; }
ǸҳܰȨ۳ʱ踶ѹ
˴
ɨ븶Ѽɸ
Live CD ISO | 导频 | 频分多址 | 单载波 | 空口 | earth station | 空间站 | NAS层 | 回环地址 | Qemu-Guest-Agent | QGA | unix socket |