图的最短路径

1000. 畅通工程
Total:159Accepted:26
   
Time Limit: 1sec    Memory Limit:256MB
Description

 

本周练习是最后一次练习...前面每一周的练习都已经重新开放...不管你是之前没做还是本着为机试做准备的态度...我建议做一下前面的每个题...之前没做的同学请抓紧时间补做...我不希望这些作业拖到你的期末备考进度...如果有题目需要讲解,请发邮件告诉我...
 
某省自从实行了很多年的畅通工程计划后,终于修建了很多路。不过路多了也不好,每次要从一个城镇到另一个城镇时,都有许多种道路方案可以选择,而某些方案要比另一些方案行走的距离要短很多。这让行人很困扰。
现在,已知起点和终点,请你计算出要从起点到终点,最短需要行走多少距离。

 

Input

注意:两个城镇之间可能有多条路径 

 

本题目包含多组数据,请处理到文件结束。
每组数据第一行包含两个正整数N和M(0<N<200,0<M<1000),分别代表现有城镇的数目和已修建的道路的数目。城镇分别以0,1,...,N-1编号。
接下来是M行道路信息。每一行有三个整数A,B,X(0<A,B<N,A!=B,0<X<10000),表示城镇A和城镇B之间有一条长度为X的双向道路。
再接下一行有两个整数S,T(0<=S,T<N),分别代表起点和终点。

 

Output

 

对于每组数据,请在一行里输出最短需要行走的距离。如果不存在从ST的路线,就输出-1

 

Sample Input
Copy sample input to clipboard
3 30 1 10 2 31 2 10 23 10 1 11 2
Sample Output
2
-1

#include <iostream>
#include <cstring>
#define INF 100000
#define SIZE 205
using namespace std;
bool visited[SIZE] = {false};
int dist[SIZE];
int graph[SIZE][SIZE];
int Dijkstra(int begin, int end, int v)
{
	int min_, s, ans; // s record the min vertex
	graph[begin][begin] = 0;
	visited[begin] = true;
	for (int i = 0; i < v; i++)
		dist[i] = graph[begin][i];
	while (true)
	{
		/*for (int i = 0; i < v; i++)
			cout << dist[i] << " ";
		cout << endl;*/
		min_ = INF, s = -1;
		for (int i = 0; i < v; i++)
			if (!visited[i])
				if (dist[i] < min_)
					min_ = dist[i], s = i;
		
		if (s == -1) // s == -1 mean has found all vertex which can find
			break;
		visited[s] = true;
		for (int i = 0; i < v; i++)
		{
			if (graph[s][i] != INF && (graph[s][i] + dist[s] < dist[i]))
			{
				dist[i] = graph[s][i] + dist[s];
				visited[i] = false;
			}
		}
	}
	ans = dist[end];
	return ans;
}

int main()
{
	int vertexs, sides;
	while (cin >> vertexs >> sides)
	{
		
		int v1, v2, w;
		memset(graph, INF, sizeof(graph));
		memset(visited, false, sizeof(visited));
		for (int i = 0; i < SIZE; i++)
			dist[i] = INF;
		for (int i = 0; i < SIZE; i++)
			for (int j = 0; j < SIZE; j++)
				graph[i][j] = INF;
		//cout << "顶点数: "; cin >> vertexs;
		//cout << "边数: "; cin >> sides;
		
		for (int i = 0; i < sides; i++)
		{
			cin >> v1 >> v2 >> w;
			if (graph[v1][v2] > w) {
				graph[v1][v2] = w;
				graph[v2][v1] = w;
			}
		}
		int begin, end;
		cin >> begin >> end;
		int road = Dijkstra(begin, end, vertexs);
		if (road != INF)
			cout << road << endl;
		else
			cout << "-1" << endl;
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值