我有一个Bellman's Ford算法的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();
}
Thanks in advance
如果你想修改你的输入以从输入格式2中读取,那么只需对你的输入函数做以下更改:
void input(){
int i, u, v, w;
ifstream fin("net30.txt");
fin >> n >> m ;
for (i = 1; i <= n; i++)
adj[i].clear();
for (i = 1; i <= m; i++){
fin >> u >> v >> w;
adj[u].push_back(make_pair(v, w));
adj[v].push_back(make_pair(u, w));
}
fin >> s >> f;
fin.close();
}
然而,要转换文件的内容,您需要编写一个单独的函数来读取文件内容,然后将其重新写入同一个文件。这个函数将执行以下操作:
void changeInputFileFormat(){
int i, u, v, w;
ifstream fin("net30.txt");
fin >> n >> m >> s >> f;
vector<pair<int,pair<int,int> > > edges;
for (i = 1; i <= m; i++){
fin >> u >> v >> w;
edges.push_back(make_pair(u, make_pair(v, w)));
}
fin.close();
ofstream fout("net30.txt");
//for converting to format 2
fout<<n<<" "<<m<<endl;
for( int i=0; i<edges.size(); i++ ){
fout<<edges[i].first<<" "<<edges[i].second.first<<" "<<edges[i].second.second<<endl;
}
fout<<s<<" "<<f<<endl;
fout.close();
}