hiho_1081_最短路径1

Posted 农民伯伯-Coding

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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\n", min_dist);
	return 0;
}

 

以上是关于hiho_1081_最短路径1的主要内容,如果未能解决你的问题,请参考以下文章

Hihocoder1081 最短路径 继续结构题

hiho_1089_floyd最短路

算法笔记_006:全源最短路径问题动态规划法

ybtoj最短路Dijkstra堆例题1单源最短路径

[平面几何]轴对称与最短路径问题

BZOJ_4016_[FJOI2014]最短路径树问题_最短路+点分治