题目
代码
有错误,暂搁浅
#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;
}