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;
}

 

posted @ 2016-05-31 21:53  农民伯伯-Coding  阅读(223)  评论(0编辑  收藏  举报