1769. Way to Escape

单点时限: 2.0 sec

内存限制: 256 MB

Kid has got the diamond ring after he got the password. After that he tried to escape as quickly as possible. Now give you the map, point 0 stands for Kid, point 1 stands for the exit.

输入格式
There are n (2<=n<=100) points (from 0 to n-1), r roads, given in a line. Different distances between points are given, one line for each road with three integers s, e, l(0<=s, e<=n-1, 0<l<=1000), stands for the road between the point s and e, length l.

输出格式
Please find out the shortest way for Kid to escape. Just output the length of the way you’ve found.

样例
input
5 6
0 2 2
0 3 2
2 3 3
0 4 12
3 1 34
4 1 24
output
36
思路:Dijkstra单元最短路径

#include<iostream>
#include<queue>
#include<vector>
#include<algorithm>
using namespace std;
struct g {
	int x;
	int cost;
	friend bool operator < (g a,g b) {
		return a.cost>b.cost;
	}
};
const int inf=100000;
bool visit[100]= {false};//是否访问
bool visit1[100]= {false};//判断是否入队
int d[100];
int n;
vector<g>v[100];
void Dijkstra_1(int s) {
	fill(d,d+100,inf);
	d[s]=0;
	for(int i = 0; i < n; i++) {
		int u=-1,Min=inf;
		for(int j = 0; j < n; j++) {
			if(visit[j]==false&&Min>d[j]) {
				u=j;
				Min=d[j];
			}
		}
		if(u==-1)
			return ;
		visit[u]=true;
		for(int i = 0; i < v[u].size(); i++) {
			int w=v[u][i].x;
			int cost=v[u][i].cost;
			if(visit[w]==false&&d[u]+cost<d[w]) {
				d[w]=d[u]+cost;
			}
		}
	}
}
void Dijkstra_2(int s) {//优先队列实现
	fill(d,d+100,inf);
	d[s]=0;
	priority_queue<g>q;
	g G;
	G.x=s;
	G.cost=0;
	q.push(G);
	visit1[s]=true;//入队
	while(!q.empty()) {
		g f=q.top();
		q.pop();
		visit1[f.x]=false;//不在队列
		for(int i = 0; i < v[f.x].size(); i++) {
			int u=v[f.x][i].x;
			int cost=v[f.x][i].cost;
			if(visit[u]==false&&d[f.x]+cost<d[u]) {
				d[u]=d[f.x]+cost;
				if(visit1[u]==false) {//为入队
					g m;
					m.x=u;
					m.cost=v[f.x][i].cost;
					q.push(m);
					visit1[u]=true;
				}
			}
		}
	}
}
int main() {
	int m;
	cin>>n>>m;
	for(int i = 0; i < m; i++) {
		int a,b,cost;
		cin>>a>>b>>cost;
		g G;
		G.x=b;
		G.cost=cost;
		v[a].push_back(G);
		G.x=a;
		v[b].push_back(G);
	}
	Dijkstra_2(0);
	cout<<d[1];
//	for(int i = 0; i < n; i++)
//		cout<<d[i]<<" ";
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_40394960/article/details/105988652
way