Source of title: https://vjudge.net/problem/POJ-2387
[title]
The shortest path required from point n to point 1.
Single source shortest path problem.
[thinking]
The unknown edges are updated with known edges, and the relaxation operation is carried out continuously until the unknown edges can not be relaxed any more.
So what is relaxation?
Assuming a single source path problem, assume that point 1 is the starting point, and use d array to store the direct distance between point 1 and other points, then update it in turn, and use w [][] two-dimensional array to express the relationship between points and points. For example, d[2]=20,w[2][3]=10, and d[3]=40. This means that the distance from point 1 to point 2 is 20, and the distance from point 1 to point 3 is 40. But, the distance from point 2 to point 3 is 10. So from 1 to 3, which path should I choose? So compare:
D [3] > D [2] + W [2] [3], if established, is to update the shortest path. By the way, the above is the relaxation operation. It is similar to the prim algorithm in the minimum spanning tree.
[Code 1]
//Ordinary djs using adjacency matrix
//High time complexity
#include<cstdio>
#include<cstring>
#include<iostream>
#include<string>
#include<algorithm>
#include<cmath>
using namespace std;
const int INF=1e9;
int n,m;
int w[1004][1004];
int d[1005];
bool vis[1004];
void init()
{
for(int i=1; i<=n; i++)
{
for(int j=1; j<=n; j++)
{
w[i][j]=i==j?0:INF;
}
}
memset(vis,0,sizeof(vis));
}
void djs()
{
d[n]=0;
for(int i=1; i<=n-1; i++)
{
d[i]=w[n][i];
}//d array initialization
for(int i=n; i>=1; i--)//Every point has to be traversed.
{
int m=INF,x=-1;
for(int j=n-1; j>=1; j--)//Select a nearest unmarked point to 1
{
if(!vis[j]&&d[j]<m)
{
m=d[x=j];
}
}
if(x!=-1)
{
vis[x]=1;//sign
for(int j=n; j>=1; j--)//Relaxation operation using selected points (i.e. point 2 in the train of thought)
{
if(d[j]>d[x]+w[x][j])
{
// printf("d[%d]=%d d[%d]+d[%d][%d]=%d\n",j,d[j],x,x,j,d[x]+w[x][j]);
d[j]=d[x]+w[x][j];
// printf("***********\n");
}
}
}
}
// for(int i=1; i<=n; i++)
// printf("%d ",d[i]);
// printf("\n");
printf("%d\n",d[1]);
}
int main()
{
while(~scanf("%d%d",&m,&n))
{
init();
while(m--)
{
int x,y,z;
scanf("%d%d%d",&x,&y,&z);
if(w[x][y]>z) w[x][y]=w[y][x]=z;
}
djs();
}
}