hdu1874畅通工程续

#include
#define INF 0x3f3f3f3f
#define ll long long
#define mem(ar,num) memset(ar,num,sizeof(ar))
#define me(ar) memset(ar,0,sizeof(ar))
#define lowbit(x) (x&(-x))
#define IOS ios::sync_with_stdio(false)
#define DEBUG cout<
using namespace std;
struct Edge {
    int v, w, next;
} edge[N * 2];
int n, m, num, s, e;
int dis[N], use[N], head[N];
priority_queue, greater>que;
void addedge(int u, int v, int w) {
    edge[num].v = v;
    edge[num].next = head[u];
    edge[num].w = w;
    head[u] = num++;
}
void dijkstra(int s) {
    int v, w, j;
    for(int i = 0; i <= n; i++)
        dis[i] = INF;
    dis[s] = 0;
    que.push(MP(0, s));
    while(!que.empty()) {
        w = que.top().first;
        v = que.top().second;
        que.pop();
        use[v] = 1;
        for(int i = head[v]; i != -1; i = edge[i].next) {
            j = edge[i].v;
            if(!use[j] && dis[j] > w + edge[i].w) {
                dis[j] = w + edge[i].w;
                que.push(MP(dis[j], j));
            }
        }
    }
    if(dis[e] == INF)
        printf("-1\n");
    else
        printf("%d\n", dis[e]);
}
int main() {
    while(cin >> n >> m) {
        mem(head, -1),me(use);
        num = 0;
        while(!que.empty())
            que.pop();
        for(int i = 1; i <= m; i++) {
            int x, y, w;
            scanf("%d%d%d", &x, &y, &w);
            addedge(x, y, w);
            addedge(y, x, w);
        }
        cin >> s >> e;
        dijkstra(s);
    }
    return 0;
}

 

你可能感兴趣的:(最短路)