#include<stdio.h>
#include<string.h>
#include<queue>
#define INF 1000
#define MAXN 20
using namespace std;
struct ArcNode
{
int to;
int weight;
struct ArcNode * next;
};
queue<int> Q;
int n,m;
struct ArcNode * List[MAXN];
int inq[MAXN]; //表示顶点是否在队列中的标志
int dist[MAXN]; //表示当前最短路径的距离
int path[MAXN];//最短路径的上一个顶点
void SPFA(int src)
{
int i,u;
struct ArcNode *temp;
for(i=0;i<n;i++)
{
dist[i]=INF;
path[i]=src;
inq[i]=0;
}
dist[src]=0;
path[src]=src;
inq[src]++;
Q.push(src);
while(!Q.empty())
{
u=Q.front();
Q.pop();
inq[u]=0;
temp=List[u];
while(temp!=NULL)
{
int v=temp->to;
if(dist[v]>dist[u]+temp->weight)
{
dist[v]=dist[u]+temp->weight;
path[v]=u;
if(!inq[v])
{
Q.push(v);
inq[v]=1;
}
}
temp=temp->next;
}
}
}
int main()
{
int i,j,k;
int u,v,w;
int shortest[MAXN];
struct ArcNode *temp;
scanf("%d %d",&n,&m);
memset(List,NULL,sizeof(List));
for(j=0;j<m;j++)
{
scanf("%d%d%d",&u,&v,&w);
temp=new ArcNode;
temp->to=v;
temp->weight=w;
if(List[u]==NULL)
{
List[u]=temp;
temp->next=NULL;
}
else
{
temp->next=List[u];
List[u]=temp;
}
}
SPFA(0);
for(j=0;j<n;j++)
{
temp=List[j];
while(temp!=NULL)
{
List[j]=temp->next;
delete temp;
temp=List[j];
}
}
for(i=1;i<n;i++)
{
printf("%d\t",dist[i]);
memset(shortest,0,sizeof(shortest));
k=0;
shortest[k]=i;
while(path[shortest[k]]!=0)
{
k++;
shortest[k]=path[shortest[k-1]];
}
k++;
shortest[k]=0;
for(j=k;j>0;j--)
printf("%d->",shortest[j]);
printf("%d\n",shortest[0]);
}
system("PAUSE");
return 0;
}
SPFA算法 快速Bellaman-ford算法 源点最短路径
最新推荐文章于 2023-01-17 20:00:00 发布