Dijkstra

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include <bits/stdc++.h>
#define INF 0x3f3f3f3f
typedef long long ll;
using namespace std;
int cost[120][120],d[120],V,M;
bool vis[120];
void dijkstra(int s)
{
    fill(d,d+120,INF);
    fill(vis,vis+120,false);
    d[s]=0;
    while(true)
    {
        int v=-1;
        for(int u=1;u<=V;u++)
            if(!vis[u]&&(v==-1||d[u]<d[v]))v=u;
        if(v==-1)break;
        vis[v]=true;
        for(int u=1;u<=V;u++)
            if(!vis[u])
            d[u]=min(d[u],d[v]+cost[v][u]);
    }
}
int main()
{
    while(cin>>V>>M)
    {
        if(!V&&!M)break;
        memset(cost,INF,sizeof(cost));
        int a,b,c;
        for(int i=0;i<M;i++)
        {
            cin>>a>>b>>c;
            cost[a][b]=c;
            cost[b][a]=c;
        }
        dijkstra(1);
        cout<<d[V]<<endl;
    }
    return 0;
}