UVA - 10986 Sending email

题意:使用优先队列的Dijkstra算法的模板题,注意数组的大小,要开两倍的M,因为我们存的是两次

#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
#include <algorithm>
using namespace std;
const int MAXN = 21004;
const int MAXM = 110004;
const int INF = 0x3f3f3f3f;
int n,m;
int d[MAXM],vis[MAXM];
int u[MAXM],v[MAXM],w[MAXM],first[MAXM],next[MAXM];

struct node{
    int w,id;
    friend bool operator<(node a,node b){
        return a.w > b.w;
    }
};

void dijkstra(int s,int t){
    int e,x;
    node p;
    priority_queue<node> q;
    memset(vis,0,sizeof(vis));
    memset(d,INF,sizeof(d));
    d[s] = 0;
    p.w = 0,p.id = s;
    q.push(p);
    while (!q.empty()){
        p = q.top(),q.pop();
        x = p.id;
        d[x] = p.w;
        if (x == t)
            return;
        if (vis[x])
            continue;
        vis[x] = 1;
        for (e = first[x]; e != -1; e = next[e])
            if (!vis[v[e]] && d[v[e]]>d[x]+w[e]){
                d[v[e]] = d[x] + w[e];
                p.w = d[v[e]];
                p.id = v[e];
                q.push(p);
            }
    }
}

int main(){
    int T,e,s,t,cas=0;
    int x,y,z;
    scanf("%d",&T);
    while (T--){
        scanf("%d%d%d%d",&n,&m,&s,&t);
        memset(first,-1,sizeof(first));
        e = 0;
        for (int i = 0; i < m; i++){
            scanf("%d%d%d",&x,&y,&z);
            u[e] = x,v[e] = y,w[e] = z;
            next[e] = first[u[e]];
            first[u[e]] = e;
            e++;
            u[e] = y,v[e] = x,w[e] = z;
            next[e] = first[u[e]];
            first[u[e]] = e;
            e++;
        }
        dijkstra(s,t);
        if (d[t] == INF)
            printf("Case #%d: unreachable\n",++cas);
        else printf("Case #%d: %d\n",++cas,d[t]);
    }
    return 0;
}


你可能感兴趣的:(UVA - 10986 Sending email)