#include <iostream>
#include <string>
#define maxnum 1000
#define edgemax 2000;
using namespace std;
int edges;
int node[maxnum];
int nodenum;
struct edge
{
int value;
int a;
int b;
//a to b is edge
};
edge e[maxnum];
struct path
{
void append(int nodeid)
{
p=p+" "+(char)('0'+nodeid);
}
void clear()
{
p="";
}
void append(path & temp,int nodeid)
{
p=temp.p+" "+(char)('0'+nodeid);
}
string p;
};
path paths[maxnum];
void relax(int dst,edge e )
{
if(e.b==dst)
{
if(node[e.a]!=99999)
if(node[dst]>(node[e.a]+e.value))
{
paths[dst].clear();
paths[dst].append(paths[e.a],dst);
node[dst]=node[e.a]+e.value;
}
}
}
void bellmanford()
{
int i=0;
for(i=0;i<nodenum-1;i++)
{
int j=0;
for(j=0;j<edges;j++)
{
relax(e[j].b,e[j]);
}
}
}
int main()
{
cout<<"输入节点个数和边数"<<endl;
cin>>nodenum;
cin>>edges;
cout<<"输入起点"<<endl;
int s;
cin>>s;
int i=0;
for(i=0;i<edges;i++)
{
int a,b,value;
cin>>a;
cin>>b;
cin>>value;
e[i].a =a;
node[i]=99999;
e[i].b =b;
e[i].value=value;
}
node[s]=0;
bellmanford();
for(i=0;i<nodenum;i++)
{
cout<<node[i]<<" ";
cout<<paths[i].p<<endl;
}
}
BellFord单元最短路径算法
最新推荐文章于 2022-09-01 21:47:52 发布