SPFA Summary _ Shortest Path

Source: Internet
Author: User

Dynamic approximation method: Set up an advanced first out queue to save the node to be optimized, when optimized, the first node of the team is removed each time, and the current shortest path estimate of the U point is used to relax the node v pointing to the left U point, if the shortest path estimate of the V point is adjusted and the V point is not in the current queue, Put the V-point at the end of the line. This keeps the nodes out of the queue for relaxation until the queue is empty.

#include <iostream>
#include <queue>
#include <cstring>
#define INF 1<<29
using namespace Std;
int map[105][105];
int dict[105];
Queue <int> Q;
BOOL vis[105];
int c[105];




void Build_map (int n,int m)
{
for (int i=0;i<=n;i++)
for (int j=0;j<=n;j++)
if (I==J)
map[i][j]=0;
else Map[i][j]=inf;
for (int i=0;i<m;i++)
{
int b,e,v;
cin>>b>>e>>v;
Map[b][e]=map[e][b]=v;
}
}


BOOL SPFA (int n,int x)
{
for (int i=1;i<=n;i++)
Dict[i]=inf;
dict[x]=0;
memset (Vis) (vis,false,sizeof);
Memset (C,0,sizeof (c));
Q.push (x);
Vis[x]=true;
while (! Q.empty ())
{
int Q=q.front ();
Q.pop ();
Vis[q]=false;
c[q]++;
if (c[q]>n)
return false;
for (int i=1;i<=n;i++)
{
if (Dict[i]>dict[q]+map[q][i])
{
Dict[i]=dict[q]+map[q][i];
if (!vis[i])
{
Q.push (i);
Vis[i]=true;
}
}
}
}
return true;
}


int main ()
{
int n,m;
while (cin>>n>>m&&n!=0&&m!=0)
{
Build_map (N,M);
if (SPFA (n,1))
cout<<dict[n]<<endl;
Else
cout<< "with negative ring" <<endl;
}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.