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;
    }
    
    唯愿,青春不辜负梦想,未来星辰闪耀
  • 相关阅读:
    Yii2的View中JS代码添加
    Yii2命名规则
    Yii2 Redis的使用
    win7下php5.6安装redis扩展
    Ubuntu安装cuda
    Ubuntu 安装显卡驱动
    TensorFlow 图片resize方法
    anaconda的kernel对jupyter可见
    cuda和显卡驱动版本
    jupyter修改根目录
  • 原文地址:https://www.cnblogs.com/Benjamin-cpp/p/10995041.html
Copyright © 2011-2022 走看看