1131 Subway Map (30分)/最短路径问题

题目描述

In the big cities, the subway systems always look so complex to the visitors. To give you some sense, the following figure shows the map of Beijing subway. Now you are supposed to help people with your computer skills! Given the starting position of your user, your task is to find the quickest way to his/her destination.

subwaymap.jpg

Input Specification:

Each input file contains one test case. For each case, the first line contains a positive integer NNN (≤\le 100), the number of subway lines. Then NNN lines follow, with the iii-th (i=1,⋯,Ni=1, \cdots , Ni=1,,N) line describes the iii-th subway line in the format:

MMM S[1] S[2] ... S[MMM]

where MMM (≤\le 100) is the number of stops, and S[iii]'s (i=1,⋯,Mi=1, \cdots , Mi=1,,M) are the indices of the stations (the indices are 4-digit numbers from 0000 to 9999) along the line. It is guaranteed that the stations are given in the correct order -- that is, the train travels between S[iii] and S[i+1i+1i+1] (i=1,⋯,M−1i=1, \cdots , M-1i=1,,M1) without any stop.

Note: It is possible to have loops, but not self-loop (no train starts from S and stops at S without passing through another station). Each station interval belongs to a unique subway line. Although the lines may cross each other at some stations (so called "transfer stations"), no station can be the conjunction of more than 5 lines.

After the description of the subway, another positive integer KKK (≤\le 10) is given. Then KKK lines follow, each gives a query from your user: the two indices as the starting station and the destination, respectively.

The following figure shows the sample map.

samplemap.jpg

Note: It is guaranteed that all the stations are reachable, and all the queries consist of legal station numbers.

Output Specification:

For each query, first print in a line the minimum number of stops. Then you are supposed to show the optimal path in a friendly format as the following:

Take Line#X1 from S1 to S2.
Take Line#X2 from S2 to S3.

where Xiii’s are the line numbers and Siii’s are the station indices. Note: Besides the starting and ending stations, only the transfer stations shall be printed.

If the quickest path is not unique, output the one with the minimum number of transfers, which is guaranteed to be unique.

Sample Input:

4
7 1001 3212 1003 1204 1005 1306 7797
9 9988 2333 1204 2006 2005 2004 2003 2302 2001
13 3011 3812 3013 3001 1306 3003 2333 3066 3212 3008 2302 3010 3011
4 6666 8432 4011 1306
3
3011 3013
6666 2001
2004 3001

Sample Output:

2
Take Line#3 from 3011 to 3013.
10
Take Line#4 from 6666 to 1306.
Take Line#3 from 1306 to 2302.
Take Line#2 from 2302 to 2001.
6
Take Line#2 from 2004 to 1204.
Take Line#1 from 1204 to 1306.
Take Line#3 from 1306 to 3001.

解析

通过这道题让我学到了很多东西,知道原来DFS、BFS算法也是可以求解最短路径问题的,但只是对于顶点之间没有距离可言的时候DFS、BFS才会比较容易
一开始是想用BFS算法求解这道题,后来发现,由于题目要求维护换乘数这个量,那么这时候BFS好像并不是很方便。反而DFS更容易维护,只是需要求出所有能到达终点的路径,再从中选择最优路径。(有种Dijkstra+DFS的感觉)。

BFS错误代码

#include<iostream>
#include<cstring>
#include<string>
#include<vector>
#include<map>
#include<set>
#include<unordered_map>
#include<unordered_set>
#include<stack>
#include<queue>
#include<cmath>
#include<algorithm>
using namespace std;
const int maxn = 10000;
int pre[maxn];
bool inq[maxn];
vector<int> adj[maxn];
unordered_map<int, int> line;
void bfs(int s, int des) {
	queue<int> q;
	q.push(s);
	inq[s] = 1;
	while (!q.empty()) {
		int now = q.front(); q.pop();
		if (now == des) return;
		for (int i = 0; i < adj[now].size(); i++) {
			if (inq[adj[now][i]] == 0) {
				q.push(adj[now][i]);
				pre[adj[now][i]] = now;
				inq[adj[now][i]] = 1;
			}
		}
	}
}
int main() {
#ifdef ONLINE_JUDGE
#else
	freopen("1.txt", "r", stdin);
#endif
	int n; cin >> n;
	for(int i=1;i<=n;i++) {
		int m, pre=0, temp; cin >> m;
		for (int j = 0; j < m; j++) {
			scanf("%d", &temp);
			line[pre * 10000 + temp] = line[temp * 10000 + pre] = i;
			if (j != 0) {
				adj[pre].push_back(temp);
				adj[temp].push_back(pre);
			}
			pre = temp;
		}
	}
	int k, s, des; cin >> k;
	while (k--) {
		scanf("%d%d", &s, &des);
		memset(pre, 0, sizeof(pre));
		memset(inq, 0, sizeof(inq));
		bfs(s, des);
		vector<int> path;
		int u=des;
		while (1) {
			path.push_back(u);
			if (u == s) break;
			u = pre[u];
		}
		int len = path.size();
		printf("%d\n", len-1);
		int nowline = line[path[len - 1] * 10000 + path[len - 2]];
		for (int i = path.size() - 3; i >= 0; i--) {
			int templine = line[path[i + 1] * 10000 + path[i]];
			if (templine != nowline) {
				printf("Take Line#%d from %04d to %04d.\n", nowline, s, path[i+1]);
				s = path[i+1];
				nowline = templine;
			}
		}
		printf("Take Line#%d from %04d to %04d.\n", nowline, s, des);
	}
	return 0;
}

DFS AC代码

#include<iostream>
#include<cstring>
#include<string>
#include<vector>
#include<map>
#include<set>
#include<unordered_map>
#include<unordered_set>
#include<stack>
#include<queue>
#include<cmath>
#include<algorithm>
using namespace std;
const int maxn = 10000;
bool vis[maxn];
vector<int> adj[maxn], temppath, path;
int line[maxn][maxn], minStation, minLineNum; //line相当于邻接矩阵
//minStation、minLineNum分别是最小站点数,最小换乘数
int lineNum(vector<int> path) {
	int preLine=0, cnt=0;
	for (int i = 1; i < path.size(); i++) {
		if (line[path[i - 1]][path[i]] != preLine) cnt++;
		preLine = line[path[i - 1]][path[i]];
	}
	return cnt;
}
void dfs(int u, int &des, int cnt) {
	vis[u] = 1; temppath.push_back(u);
	if (u == des && (cnt < minStation || cnt == minStation && lineNum(temppath) < minLineNum)) {
		path = temppath;
		minStation = cnt;
		minLineNum = lineNum(temppath);
		return;
	}	
	for (int i = 0; i < adj[u].size(); i++) {		
		int v = adj[u][i];
		if (vis[v] == 0) {			
			dfs(v, des, cnt+1);
			vis[v] = 0;   //由于已访问过的也可能构成最优路径,需要恢复vis[v]为0
			temppath.pop_back();
		}
	}
}
int main() {
#ifdef ONLINE_JUDGE
#else
	freopen("1.txt", "r", stdin);
#endif
	int n; cin >> n;
	for(int i=1;i<=n;i++) {
		int m, pre=0, temp; cin >> m;
		for (int j = 0; j < m; j++) {
			scanf("%d", &temp);
			if (j != 0) {
				line[pre][temp] = line[temp][pre] = i;
				adj[pre].push_back(temp);
				adj[temp].push_back(pre);
			}
			pre = temp;
		}
	}
	int k, s, des; cin >> k;
	while (k--) {
		scanf("%d%d", &s, &des);
		memset(vis, 0, sizeof(vis));
		minStation = maxn; minLineNum = maxn;
		temppath.clear();
		dfs(s, des, 0);
		printf("%d\n", minStation);
		int preLine = 0, nowLine=0;
		for (int i = 1; i < path.size(); i++) {
			nowLine = line[path[i - 1]][path[i]];
			if (nowLine != preLine) {
				if(i!=1) printf("Take Line#%d from %04d to %04d.\n", preLine, s, path[i - 1]);
				s = path[i - 1];
				preLine = nowLine;
			}
		}
		printf("Take Line#%d from %04d to %04d.\n", nowLine, s, des);
	}
	return 0;
}
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
地铁线路最短路径可以使用Dijkstra算法来解决。以下是Java实现的示例代码: ```java import java.util.*; public class Subway { private static final int INF = Integer.MAX_VALUE; // 代表正无穷 private int[][] graph; // 地铁图的邻接矩阵表示 private int[] dist; // 起点到各个站点的最短距离 private boolean[] visited; // 标记站点是否已经访问过 private int start; // 起点站 public Subway(int[][] graph, int start) { this.graph = graph; this.start = start; this.dist = new int[graph.length]; this.visited = new boolean[graph.length]; } public void shortestPath() { Arrays.fill(dist, INF); dist[start] = 0; for (int i = 0; i < graph.length; i++) { // 找到未访问过的距离起点最近的站点 int u = -1; int minDist = INF; for (int j = 0; j < graph.length; j++) { if (!visited[j] && dist[j] < minDist) { u = j; minDist = dist[j]; } } if (u == -1) break; // 如果找不到未访问过的站点,则退出循环 visited[u] = true; // 更新与u相邻的站点到起点的最短距离 for (int v = 0; v < graph.length; v++) { if (!visited[v] && graph[u][v] != INF) { dist[v] = Math.min(dist[v], dist[u] + graph[u][v]); } } } } public int getShortestDist(int end) { return dist[end]; } public static void main(String[] args) { int[][] graph = new int[][]{ {0, 3, 1, 2, INF}, {3, 0, INF, INF, 4}, {1, INF, 0, INF, INF}, {2, INF, INF, 0, 5}, {INF, 4, INF, 5, 0} }; Subway subway = new Subway(graph, 0); subway.shortestPath(); System.out.println(subway.getShortestDist(4)); // 输出起点到终点的最短距离 } } ``` 在这个示例代码中,我们用邻接矩阵表示地铁图,用Dijkstra算法求出起点到各个站点的最短距离。可以通过调用`getShortestDist`方法来获取起点到某个站点的最短距离。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值