#分支限界---单源最短路径
#include<iostream>
#include<bits/stdc++.h>
using namespace std;
#define inf 0x3f3f3f
int c[100][100];
int dist[100];
int prev[100];
int n;
struct Vex
{
int i;
int length;
bool operator < (const Vex & v) const
{
return length>v.length;
}
Vex() {};
Vex(int v,int l)
{
i=v;
length=l;
}
};
void shortest(int v0)
{
priority_queue<Vex>Q;
Vex E;
E.i=v0;
E.length=0;
Q.push(E);
dist[v0]=0;
while(!Q.empty())
{
E=Q.top();
for(int j=1; j<=n; j++)
{
if((c[E.i][j]<inf)&&(c[E.i][j]+E.length<dist[j]))
{
dist[j]=E.length+c[E.i][j];
prev[j]=E.i;
Q.push(Vex(j,dist[j]));
}
}
Q.pop();
}
}
void trace(int prev[], int n,int v)
{
if (n == v)
{
cout<<n<<" ";
return;
}
trace(prev, prev[n],v);
cout<<n<<" ";
}
int main()
{
memset(c,inf,sizeof(c));
memset(dist,inf,sizeof(dist));
int e;
cout<<"请输入顶点的数目和边数"<<endl;
cin>>n>>e;
cout<<"输入各顶点之间的通路"<<endl;
for(int i=1; i<=e; i++)
{
int t1,t2,t3;
cin>>t1>>t2>>t3;
c[t1][t2]=t3;
}
cout<<"输出邻接矩阵"<<endl;
for(int i=1; i<=n; i++)
{
for(int j=1; j<=n; j++)
{
cout<<c[i][j]<<'\t';
}
cout<<endl;
}
cout<<endl;
int v0;
cout<<"输入初始顶点v0"<<endl;
cin>>v0;
shortest(v0);
for(int i=1; i<=n; i++)
{
cout<<v0<<" "<<i<<"的最短距离"<<dist[i]<<endl;
}
for(int j=1; j<=n; j++)
{
if(j!=v0)
trace(prev,j,v0);
cout<<endl;
}
return 0;
}
测试数据
5 7
1 2 10
1 4 30
1 5 100
2 3 50
3 5 10
4 3 20
4 5 60
来源:CSDN
作者:啦啦啦mmm
链接:https://blog.csdn.net/qq_45593796/article/details/103582913