Sending email - dijkstra无向图 + 优先队列

学知识学的太死了,书上的模板是个有向图,而这题是一道无向图的题,所以需要加边,也就是原来有m条边,我们给他加成2 * m条

    for(int i = 0;i < m;i++){
        scanf("%d%d%d",&u[i],&v[i],&w[i]);
        next[i] = head[u[i]];
        head[u[i]] = i;
        i ++;
        u[i] = v[i -1]; v[i] = u[i -1]; w[i] = w[i - 1];
        next[i] = head[u[i]];
        head[u[i]] = i;
    }

以每个点为单位储存与他相连的所有的边,之后利用优先队列,每次取出离除法点最近的点,以这个点拓展到其他点,进行松弛

#include
#include
#include
#include
#include
using namespace std;
int n,m,S,T;
#define MAXD 500000 + 100
#define LEN  500000 + 10
#define Inf  1<<30
typedef pairpill;
priority_queue,greater >q;
int head[LEN],next[LEN];
int u[LEN],v[LEN];
int w[MAXD];
int d[LEN];
bool vis[LEN];
inline void Get_line(){
    scanf("%d%d%d%d",&n,&m,&S,&T);
    for(int i = 0;i < n;i++) head[i] = -1;
    m *= 2;
    for(int i = 0;i < m;i++){
        scanf("%d%d%d",&u[i],&v[i],&w[i]);
        next[i] = head[u[i]];
        head[u[i]] = i;
        i ++;
        u[i] = v[i -1]; v[i] = u[i -1]; w[i] = w[i - 1];
        next[i] = head[u[i]];
        head[u[i]] = i;
    }
    /*这里的话是Dijkstra的有向图转无向图
    多添加一条边,将这条边的2个端点互换*/
}
inline void solve(){
    for(int  i= 0;i < n;i++) d[i] = Inf;
    memset(vis,0,sizeof(vis));
    d[S] = 0;
    q.push(make_pair(d[S],S));
    while(!q.empty()){
        pill t = q.top();
        q.pop();
        int x = t.second;
        if(vis[x]) continue;
        vis[x] = 1;
        for(int i = head[x]; i != -1; i = next[i]){
            if(d[v[i]] >  d[x] + w[i]){
                d[v[i]] = d[x] + w[i];
                q.push(make_pair(d[v[i]],v[i]));
            }
        }
    }
}
int main(){
    int N,Case = 1;
    scanf("%d",&N);
    while(N--){
        Get_line();
        solve();
        if(d[T] < Inf)
        printf("Case #%d: %d\n",Case ++,d[T]);
        else
        printf("Case #%d: unreachable\n",Case ++);
    }
    return 0;
}


你可能感兴趣的:(图论,STL函数)