#include<iostream>
#include<queue>
#define MaxSize 501//最大顶点数
#define ElemVex int//顶点编号的表示类型
#define INF 0x7fffffff
#include<string>
using namespace std;
int vex,arc;
bool vis[MaxSize];//记录队列中是否存在该节点
int in_queue[MaxSize];
//表结构
struct ArcNode {
int adjvex; //边的另外一边的顶点下标
ArcNode * next; //下一条边的表结点
int weight;
};
struct Vnode {
string data; //顶点信息
ArcNode * firstarc; //第一条依附在该顶点的边
Vnode(){firstarc=NULL;data="";}
};
Vnode vnode[MaxSize];
//记录结果的结构体
struct Dis {
string path; //从顶点到该该顶点最短路径
int weight; //最短路径的权重
Dis(){path="";weight=0;}
};
Dis dis[MaxSize];
void CreatGraph(){
cin>>vex>>arc;
for(int i=0;i<arc;i++){
int x,y,value;cin>>x>>y>>value;
//可以加一个check判断输入是否合法
ArcNode* temp_1=new ArcNode;
temp_1->adjvex=y;
temp_1->next=NULL;
temp_1->weight=value;
if(!vnode[x].firstarc){vnode[x].firstarc=temp_1;}//初始化代码
else{
ArcNode* now=vnode[x].firstarc;
while(now->next){now=now->next;}
now->next=temp_1;
}
//该图为无向图
ArcNode* temp_2=new ArcNode;
temp_2->adjvex=x;
temp_2->next=NULL;
temp_2->weight=value;
if(!vnode[y].firstarc){vnode[y].firstarc=temp_2;}//初始化代码
else{
ArcNode* now=vnode[y].firstarc;
while(now->next){now=now->next;}
now->next=temp_2;
}
}
}
void SPFA(int begin){
for(int i=1;i<=vex;i++){
vnode[i].data="v"+to_string(i);
}
for(int i=1;i<=vex;i++){
vis[i]=false;
dis[i].path=vnode[begin].data+"---"+vnode[i].data;
dis[i].weight=INF;
}
queue<ElemVex> s;
s.push(begin);vis[begin]=true;++in_queue[begin];dis[begin].weight=0;dis[begin].path=vnode[begin].data;
//初始化让下面的队列能正常跑起来
ElemVex temp; ArcNode* temp_child;
while(!s.empty()){
temp=s.front();s.pop();
temp_child=vnode[temp].firstarc;
while(temp_child){
if(dis[temp_child->adjvex].weight>dis[temp].weight+temp_child->weight)//利用temp_child进行松弛
{
dis[temp_child->adjvex].weight=dis[temp].weight+temp_child->weight;
dis[temp_child->adjvex].path=dis[temp].path+"---"+vnode[temp_child->adjvex].data;//类似于动态规划的展现(这里的解释比较意识流啦,只是我的一种感觉~~
if(!vis[temp_child->adjvex]){
vis[temp_child->adjvex]=true;
++in_queue[temp_child->adjvex];
s.push(temp_child->adjvex);
if(in_queue[temp_child->adjvex]>vex){cout<<"图中有环"<<endl;exit(-1);}///!!!!!!!!!!
}
}
temp_child=temp_child->next;
}
}
}
void print(int begin){
cout<<"以顶点"<<vnode[begin].data<<"为顶点的各个最短路径信息:"<<endl;
for(int i=1;i<=vex;i++){
if(i==begin) continue;
else if(dis[i].weight==INF) cout<<vnode[begin].data<<"---"<<vnode[i].data<<"无最短路径;"<<endl;
else{cout<<vnode[begin].data<<"---"<<vnode[i].data<<" weight:"<<dis[i].weight<<" path:"<<dis[i].path<<";"<<endl;}
}
}
int main(void){
CreatGraph();
SPFA(1);
print(1);
return 0;
}
SPFA.
最新推荐文章于 2024-10-10 22:04:37 发布