PTA甲级考试真题练习131——1131 Subway Map

题目

在这里插入图片描述

代码

有错误,暂搁浅

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
const int nmax = 10000;
const int inf = 2147483647;
vector<int> graph[nmax];
int min_dst = inf, src;
vector<int> path;
struct info {
	int station,cur;
};
vector<pair<int,vector<info>>> path_vec;
vector<int> cnt[nmax];
int visited[nmax] = { 0 };

bool cmp(const pair<int, vector<info>>& a, const pair<int, vector<info>>& b) {
	return a.first != b.first ? a.first < b.first : a.second.size() < b.second.size();
}

int find(int num1, int num2) {
	for (auto& p : cnt[num1]) {
		if (find(cnt[num2].begin(), cnt[num2].end(), p) != cnt[num2].end())
			return p;
	}
}

void DFS(int cur,int dst) {
	if (dst > min_dst) return;
	if (cur == src) {
		if (dst <= min_dst) {
			min_dst = dst;
			vector<info> v;
			for (int i = 0; i < path.size()-1;++i) {
				int num = find(path[i], path[i + 1]);
				if (i == 0) {
					v.emplace_back(info{ num,path[i] });
				}
				else {
					if (num != v.rbegin()->station)
						v.emplace_back(info{ num,path[i] });
				}
			}
			v.emplace_back(info{ 0,path[path.size() - 1] });
			path_vec.emplace_back(pair<int, vector<info>>(dst,v));
		}
	}
	for (auto& p : graph[cur]) {
		if (!visited[p]) {
			if (cnt[p].size() > 1 || p == src)
				path.emplace_back(p);
			visited[p] = 1;
			DFS(p, dst + 1);
			visited[p] = 0;
			if (cnt[p].size() > 1 || p == src)
				path.pop_back();
		}
	}
}

void deal() {
	sort(path_vec.begin(), path_vec.end(), cmp);
	vector<info> tmp = path_vec.begin()->second;
	cout << path_vec.begin()->first << endl;
	for (int i = 0; i < tmp.size()-1; ++i) {
		cout << "Take Line#" << tmp[i].station << " from " << tmp[i].cur << " to " << tmp[i + 1].cur << "." <<endl;
	}
	path_vec.clear();
	min_dst = inf;
}

int main()
{
	int n;
	cin >> n;
	for (int i = 1; i <= n; ++i) {
		int num;
		cin >> num;
		vector<int> tmp;
		tmp.resize(num);
		for (int j = 0; j < num; ++j) {
			cin >> tmp[j];
			if(find(cnt[tmp[j]].begin(),cnt[tmp[j]].end(),i) == cnt[tmp[j]].end())
				cnt[tmp[j]].emplace_back(i);
			if (j != 0) {
				graph[tmp[j]].emplace_back(tmp[j - 1]);
				graph[tmp[j - 1]].emplace_back(tmp[j]);
			}
		}
	}
	int qn;
	cin >> qn;
	for (int i = 0; i < qn; ++i) {
		int start;
		cin >> start >> src;
		visited[start] = 1;
		path.emplace_back(start);
		DFS(start,0);
		visited[start] = 0;
		path.pop_back();
		deal();
	}
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值