dijkstra模板

来源:互联网 发布:都市星际淘宝交易商 编辑:程序博客网 时间:2024/06/05 07:31
const int MAXN = 5 + 1e3;const int MAXE = 5 + 1e5;typedef int ElementType;struct Edge{ int to, next; ElementType w; Edge() {}; Edge(int to, ElementType w, int next): to(to), w(w), next(next) {};}edge[MAXE];int head[MAXN], no;void init(){ memset(head, -1, sizeof(head)); no = 0;}void add(int from, int to, ElementType w){ edge[no] = Edge(to, w, head[from]); head[from] = no++;}ElementType dist[MAXN];int pre[MAXN]; //用于输出路径typedef pair PEI;void dijkstra(int start){ for(int i=0;i<MAXN;i++) dist[i] = INF; dist[start] = 0; priority_queue<PEI, vector, greater > pq; pq.push(PEI(0, start)); while(!pq.empty()) { PEI tmp = pq.top(); pq.pop(); int u = tmp.second; if(dist[u] < tmp.first) continue; for(int i = head[u]; i!=-1; i=edge[i].next) { Edge &e=edge[i]; if(dist[u] + e.w < dist[e.to]) { dist[e.to] = dist[u] + e.w; pre[e.to] = u;//用于输出路径 pq.push(PEI(dist[e.to],e.to)); } } }}void path(int from, int to)//用于输出路径{ if (from == to) { printf("%d", to); return; } path(from, pre[to]); printf(" %d", to);}//how to useint main(){//1.建图:输入节点数n,边数mint n, m;scanf("%d%d", &n, &m);init(); //初始化图while (m--){int u, v, w;scanf("%d%d%d", &u, &v, &w);add(u, v, w);}//2.调用dijkstra(1);//3.查询路径int v;scanf("%d", &v);path(1, v);printf("\n");return 0;}
0 0
原创粉丝点击