我有一个用于贝尔曼福特算法的 C++ 源代码。它获取一个包含节点、边、源节点和目标节点的输入文件,并返回从一个节点到另一个节点的最短路径。文件类型为:
30 150 29 30 //Vertices,Nodes,SourceNode,DestinationNode
30 25 20 // Node30 , to Node 25 , Weight 20
1 2 29
1 3 68
24 22 8
1 5 61
24 23 76
5 4 62
所以,我想让它从如下文件中读取输入:
30 150 //Vertices,Nodes
30 25 20 // Node30 , to Node 25 , Weight 20
1 2 29
1 3 68
24 22 8
1 5 61
24 23 76
5 4 62
29 30 //SourceNode,DestinationNode
这是我的源代码:
#include <iostream>
#include <cstring>
#include <string>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <vector>
#include <set>
#include <map>
#include <iterator>
#include <algorithm>
#define MaxN 111111
#define INF 1000000000
using namespace std;
int n, m, s, f;
vector< pair<int, int> > adj[MaxN];
int d[MaxN];
int rear, front;
int queue[MaxN];
bool inqueue[MaxN];
void input(){
int i, u, v, w;
cin >> n >> m >> s >> f;
for (i = 1; i <= n; i++)
adj[i].clear();
for (i = 1; i <= m; i++){
cin >> u >> v >> w;
adj[u].push_back(make_pair(v, w));
adj[v].push_back(make_pair(u, w));
}
}
void push(int v){
if (inqueue[v]) return;
front = (front + 1) % n;
queue[front] = v;
inqueue[v] = true;
}
int pop(){
rear = (rear + 1) % n;
int v = queue[rear];
inqueue[v] = false;
return v;
}
void Bellman_Ford(){
int i, u, v, w;
memset(inqueue, false, sizeof(inqueue));
for (i = 1; i <= n; i++) d[i] = INF;
d[s] = 0;
rear = 0;
front = 0;
push(s);
while (rear != front){
u = pop();
for (i = 0; i < adj[u].size(); i++){
v = adj[u][i].first;
w = adj[u][i].second;
if (d[v] > d[u] + w){
d[v] = d[u] + w;
push(v);
}
}
}
if (d[f] == INF) cout << "-1" << endl; cout << d[f] << endl;
}
int main(){
freopen("net30.txt", "r", stdin);
freopen("output.txt", "w", stdout);
input();
Bellman_Ford();
}
提前致谢