PAT Advanced 1131 Subway Map (30 )

题目描述

在这里插入图片描述

Input Specification:

在这里插入图片描述

Output Specification:

在这里插入图片描述

Sample Input:

在这里插入图片描述

Sample Output:

在这里插入图片描述

解题思路

暴力Dfs,注意输出%04d,因为这个有3个测试点没过,还以为是算法问题。。

Code

  • AC代码
#include<bits/stdc++.h>
using namespace std;
const int maxn = 1e4+10;
int station[maxn], vis[maxn];
unordered_map<int, int> line;
vector<int> nextStation[maxn], res, resLine;
int minStop, st, ed;
void dfs(int preLine, int cur, int cntStop, vector<int> &path, vector<int> &transferLine) {
	if(minStop != -1 && cntStop > minStop) return;
	if(cur == ed) {
		if(minStop == -1 || cntStop < minStop) {
			minStop = cntStop;
			res = path;
			resLine = transferLine;
		} else if(cntStop == minStop && resLine.size() > transferLine.size()) {
			res = path;
			resLine = transferLine;
		}
		return ;
	}
	for(int i = 0; i<nextStation[cur].size(); i++) {
		int tempNext = nextStation[cur][i];
		if(!vis[tempNext]) {
			vis[tempNext] = 1;
			int flag = 0, curLine = preLine;
			if((!station[cur] && preLine != line[cur*10000+tempNext]) || (cur == st)) {
				path.push_back(cur);
				curLine = line[cur*10000+tempNext];
				transferLine.push_back(curLine);
				flag = 1;
			}
			dfs(curLine, tempNext, cntStop+1, path, transferLine);
			if(flag) {
				path.pop_back();
				transferLine.pop_back();
			}
			vis[tempNext] = 0;
		}
	}
}
int main() {
	freopen("in.txt", "r", stdin);
	int N, M, K;
	cin >> N;
	memset(station, -1, sizeof(station));
	for(int i = 1; i<=N; i++) {
		cin >> M;
		int pre = -1, cur = -1;
		for(int j = 0; j<M; j++) {
			pre = cur;
			cin >> cur;
			if(j != 0) {
				nextStation[cur].push_back(pre);
				nextStation[pre].push_back(cur);
				line[pre*10000+cur] = line[cur*10000+pre] = i;
			}
			if(station[cur] == -1) {
				station[cur] = i;
			} else {
				station[cur] = 0;
			}
		}
	}
	cin >> K;
	for(int i = 0; i<K; i++) {
		cin >> st >> ed;
		memset(vis, 0, sizeof(vis));
		minStop = -1;
		vis[st] = 1;
		vector<int> path, transferLine;
		dfs(-1, st, 0, path, transferLine);
		res.push_back(ed);
		printf("%d\n", minStop);
		for(int j = 1; j<res.size(); j++) {
			int pre = res[j-1], cur = res[j];
			printf("Take Line#%d from %04d to %04d.\n", resLine[j-1], pre, cur);
			//cout << "Take Line#" << resLine[j-1] << " from " << pre << " to "<< cur << ".\n";
		}
	}
	return 0;
} 

总结

  • 输出数字时一定要注意格式要求
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值