• hiho_1081_最短路径1


    题目

        最短路模板题目,纯练习手速。

    实现

    #include<iostream>
    #include<string.h>
    #include<iostream>
    #include<queue>
    #include<cmath>
    #include<unordered_map>
    #include<unordered_set>
    #include<string>
    #include<vector>
    #include<algorithm>
    using namespace std;
    const int inf = 1 << 29;
    const int kEdgeMax = 20005;
    const int kNodeMax = 1005;
    struct Edge{
    	int to;
    	int dist;
    	int next;
    	Edge(int t=0, int d=0, int n=0) :to(t), dist(d), next(n){};
    };
    Edge gEdges[kEdgeMax];
    int gEdgesIndex;
    int gHead[kNodeMax];
    int gDist[kNodeMax];
    bool gVisited[kNodeMax];
    
    struct Cmp{
    	bool operator()(const Edge& e1, const Edge& e2){
    		return e1.dist > e2.dist;
    	}
    };
    
    void InsertEdge(int u, int v, int d){
    	int e = gEdgesIndex++;
    	gEdges[e].to = v;
    	gEdges[e].dist = d;
    	gEdges[e].next = gHead[u];
    	gHead[u] = e;
    }
    //dijkstra 算法求最短路
    int Dijkstra(int s, int t){
    	priority_queue<Edge, vector<Edge>, Cmp> pq;
    	gDist[s] = 0;
    	Edge e = Edge(s, 0, 0);
    	pq.push(e);
    	while (!pq.empty()){
    		e = pq.top();
    		pq.pop();
    		int cur_v = e.to;
    		if (gVisited[cur_v]){
    			continue;
    		}
    		if (cur_v == t){
    			break;
    		}
    		gVisited[cur_v] = true;
    		for (int eid = gHead[cur_v]; eid != -1; eid = gEdges[eid].next){
    			int next_v = gEdges[eid].to;
    			if (!gVisited[next_v] && gDist[next_v] > gDist[cur_v] + gEdges[eid].dist){
    				gDist[next_v] = gDist[cur_v] + gEdges[eid].dist;
    				pq.push(Edge(next_v, gDist[next_v], 0));
    			}
    		}
    	}
    	return gDist[t];
    }
    
    void Init(){
    	memset(gHead, -1, sizeof(gHead));
    	memset(gVisited, false, sizeof(gVisited));
    	memset(gDist, 0x7F, sizeof(gDist));
    	gEdgesIndex = 0;
    }
    
    int main(){
    	int n, m, s, t, u, v, d;
    	Init();
    	scanf("%d %d %d %d", &n, &m, &s, &t);
    	for (int i = 0; i < m; i++){
    		scanf("%d %d %d", &u, &v, &d);
    		InsertEdge(u, v, d);
    		InsertEdge(v, u, d);
    	}
    	int min_dist = Dijkstra(s, t);
    	printf("%d
    ", min_dist);
    	return 0;
    }
    
  • 相关阅读:
    jQuery.hover() 函数详解
    深入了解css的行高Line Height属性
    yii2 restfulapi QueryParamAuth验证
    yii2 restfulapi 的配置和访问
    yii2 urlmanager的配置
    xubuntu install nodejs
    使用Putty连接VirtualBox的Ubuntu
    mvc与mvvm
    对二叉树进行广度优先遍历
    JavaScript 中的 FileReader
  • 原文地址:https://www.cnblogs.com/gtarcoder/p/5547707.html
Copyright © 2020-2023  润新知