DIJ最短路

#include<bits/stdc++.h>
using namespace std;
int n,m;
struct node{//结构体
    int v,w;
    node(){ };
    node(int _v,int _w){
        v=_v;
        w=_w;
    }
};

vector <node> g[10100];

bool vis[10100];
int dst[10100];

void add(int u,int v,int w){//建图
    g[u].push_back(node(v,w));
    g[v].push_back(node(u,w));
}


void dij(int s){
    memset(dst,0x3f,sizeof dst);

    int u = s;
    dst[u]=0;
    vis[u]=1;
    int nn=n;
    while(nn--){
        for(int j=0;j<g[u].size();j++){

            int v = g[u][j].v;
            int w = g[u][j].w;
            dst[v] = min(dst[v],dst[u]+w);

        }

        int mi=0x3f3f3f3f;//无穷大
        for(int j=1;j<=n;j++){
            if(!vis[j]&&mi>dst[j]){
                mi = dst[j];
                u = j;  
            }
        }
        vis[u] = 1; 
    }
}
int main(){
    cin >> n >>m;
    int u,v,w;
    while (m--){
        cin >> u >> v >> w;
        add(u,v,w);
    }

    dij(1);
    cout << dst[n];

    return 0;
}

猜你喜欢

转载自www.cnblogs.com/LH2000/p/12404288.html