Description
Given a weighted undirected graph, the shortest path node 1 to node n.
Input
Comprising a plurality of sets of input data format.
The first line includes two integer number representative of the number of nodes and edges nm. (n <= 100)
remaining between the m lines each have three ABC positive integer, and a representative node of a node b side, a weight of c.
Output
Each group of outputs per line, only the output from the shortest path weight 1 to n. (To ensure the presence of the shortest path)
Sample
Input
3 2
1 2 1
1 3 1
1 0
Output
1
0
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<malloc.h>
#include<queue>
#define INF 0x3f3f3f3f
using namespace std;
int n,m;
int dis[110],vis[110],Map[110][110];
void dijstra()
{
for(int i=1;i<=n;i++)
{
dis[i] = Map[1][i];
}
vis[1] = 1;
for(int i=2;i<=n;i++)
{
int Min = INF;
int flag;
for(int j=1;j<=n;j++)
{
if(!vis[j]&&dis[j]<Min)
{
Min = dis[j];
flag = j;
}
}
vis[flag] = 1;
for(int j=1;j<=n;j++)
{
if(dis[j]>Map[flag][j]+dis[flag])
dis[j] = Map[flag][j]+dis[flag];
}
}
printf("%d\n",dis[n]);
}
int main()
{
int u,v,w;
while(~scanf("%d %d",&n,&m))
{
memset(Map,INF,sizeof(Map));
memset(dis,INF,sizeof(dis));
memset(vis,0,sizeof(vis));
if(m==0)
printf("0\n");
else
{
for(int i=0; i<m; i++)
{
scanf("%d %d %d",&u,&v,&w);
if(Map[u][v]>w)
{
Map[u][v]=Map[v][u]=w;
}
}
dijstra();
}
}
return 0;
}