zoukankan      html  css  js  c++  java
  • 一本通 1261:【例9.5】城市交通路网

    城市交通路网

    最短路 + 路径输出


    Code:

    #include <iostream>
    #include <cstdio>
    #include <cstring>
    #include <queue>
    using namespace std;
    //Mystery_Sky
    //
    #define M 1000100
    #define INF 0x3f3f3f3f
    struct Edge{
    	int to, next, w;
    }edge[M];
    
    int n, m;
    int map[5000][5000];
    int head[M], cnt, dis[M], vis[M];
    inline void add_edge(int u, int v, int w)
    {
    	edge[++cnt].to = v;
    	edge[cnt].next = head[u];
    	edge[cnt].w = w;
    	head[u] = cnt;
    }
    
    struct node {
    	int dis;
    	int pos;
    	inline bool operator <(const node &x) const{
    		return x.dis < dis;
    	}
    };
    priority_queue <node> q;
    inline void dijkstra()
    {
    	memset(dis, INF, sizeof(dis));
    	dis[1] = 0;
    	q.push((node){0, 1});
    	while(!q.empty()) {
    		node top = q.top();
    		q.pop();
    		int x = top.pos;
    		if(vis[x]) continue;
    		vis[x] = 1;
    		for(int i = head[x]; i; i = edge[i].next) {
    			int y = edge[i].to;
    			if(dis[y] > dis[x] + edge[i].w) {
    				dis[y] = dis[x] + edge[i].w;
    				if(!vis[y]) q.push((node){dis[y], y}); 
    			}
    		}
    	} 
    }
    
    void print(int i) {
    	if(i == 1) return;
    	for(int k = 1; k <= n; k++) {
    		if(dis[k] + map[k][i] == dis[i]) {
    			print(k);
    			printf("%d ", k);
    			return;
    		}
    	}
    }
    
    int main() {
    	scanf("%d", &n);
    	int a;
    	for(int i = 1; i <= n; i++)
    		for(int j = 1; j <= n; j++) {
    			scanf("%d", &map[i][j]);
    			if(map[i][j]) add_edge(i, j, map[i][j]);
    		}
    	dijkstra();
    	printf("minlong=%d
    ", dis[n]);
    	print(n);
    	printf("%d
    ", n);
    	return 0;
    }
    
    唯愿,青春不辜负梦想,未来星辰闪耀
  • 相关阅读:
    css3 animation 点亮灯光效果
    setTimeout和setInterval
    红绿灯 promise和原始方式实现
    思考3
    转载: 理解Javascript执行过程
    tapable
    SVG: 将 svg 导出成图片
    ES6: Module:
    d3 插值-实现一个简单的 animation
    three.js开发指南(第三版)_案例源码
  • 原文地址:https://www.cnblogs.com/Benjamin-cpp/p/10995041.html
Copyright © 2011-2022 走看看