【模板】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;
}

  

上一篇:idea中mvn的配置


下一篇:Unity判断敌方的方位