其他分享
首页 > 其他分享> > 【模板】dijsktra

【模板】dijsktra

作者:互联网

#include<bits/stdc++.h>
using namespace std;
const int z = 1024;
int dis[z], head[z], in[z], cnt, ans = 0x7f7f7f, n, m;
int pre[z], start, end;
bool visit[z];
struct node{
    int id, data;
    bool operator < (const node x) const{
        return x.data < data;
    }
} hp;
priority_queue<node> q;
struct edge{
    int f, t, w;
    int next;
} line[z*4];
void adline(int f,int t,int w) {
    line[++cnt].f = f;
    line[cnt].t = t;
    line[cnt].w = w;
    line[cnt].next = head[f];
    head[f] = cnt;
    return;
}
void print(int r) {
    if(!pre[r]) {
        printf("%d",r);
        return;
    }
    print(pre[r]);
    printf(" > %d",r);
}
void dijsktra(int f) {
    hp.id = f;
    hp.data = 0;
    q.push(hp);
    memset(dis,50,sizeof(dis));
    memset(visit,false,sizeof(visit));
    dis[f] = 0;
    while(!q.empty()) {
        int x = q.top().id;
        int y = q.top().data;
        q.pop();
        if(!visit[x]) {
            visit[x] = true;
            for(int i = head[x];i;i = line[i].next) {
                hp.id = line[i].t;
                if(dis[hp.id] > y+line[i].w) {
                    dis[hp.id] = y+line[i].w;
                    hp.data = dis[hp.id];
                    q.push(hp);
                    pre[hp.id] = x;
                }
            }
        }
    }
    return;
}
int main() {
    scanf("%d %d",&n,&m);
    for(int i = 1;i <= m;++i) {
        int a, b, w;
        scanf("%d %d %d",&a,&b,&w);
        adline(a,b,w);
    }
    scanf("%d %d",&start,&end);
    dijsktra(start);
    printf("dis = %d\n",dis[end]);
    print(end);
    return 0;
}

  

标签:cnt,int,hp,dijsktra,line,id,模板,dis
来源: https://www.cnblogs.com/bikuhiku/p/Map-dijsktra.html