思路:DFS遍历
#include <iostream>
#include <map>
#include <vector>
#include <cstdio>
using namespace std; const int INF = 0x7fffffff;
const int maxn = ; struct Node{
int line, s, e;
Node(int xl, int xs, int xe) :line(xl), s(xs), e(xe) {}
}; struct WhichLine {
int u, v;
WhichLine(int _u, int _v) :u(_u), v(_v) {}
friend bool operator <(WhichLine a,WhichLine b) {//const whichLine &a, const whichLine &b
//如果只是whichLine &a, whichLine &b报错
if (a.u != b.u) return a.u < b.u;
else return a.v < b.v;
}
};
map<WhichLine, int> searchLine;//判断两个站点在哪条线上
vector<int> G[maxn];//图的邻接表
bool visit[maxn];//判断是否已经访问数组
int minStation, minTransfer;//最少的站点,最少的换乘
vector<Node> ans, temp;//最终结果路径和中间记录路径
int st, ed; void DFS(int head, int now, int stationCnt, int pre) {
if (now == ed) {
if (stationCnt < minStation || stationCnt == minStation && temp.size() < minTransfer) {
minStation = stationCnt;
minTransfer = temp.size();
ans = temp;
ans.push_back(Node(searchLine[WhichLine(pre, now)], head, now));
return;
}
} visit[now] = true;
for (auto next : G[now]) {
if (visit[next]) continue;
if (pre != now && searchLine[WhichLine(pre, now)] != searchLine[WhichLine(now, next)]) { temp.push_back(Node(searchLine[WhichLine(pre, now)], head, now));
DFS(now, next, stationCnt + , now);
temp.pop_back();
}
else DFS(head, next, stationCnt + , now);
} visit[now] = false;
} int main(){
int n;
scanf("%d", &n);
for (int i = ; i <= n; ++i){
int k, u, v;
scanf("%d", &k);
for (int j = ; j < k; j++) {
scanf("%d", &v);
if (j > ) {
searchLine[WhichLine(u, v)] = i;//两个相邻节点的线路
searchLine[WhichLine(v, u)] = i;
G[u].push_back(v);
G[v].push_back(u);
}
u = v;
}
}
int q;
scanf("%d", &q);
while (q--){
scanf("%d %d", &st, &ed);
minStation = minTransfer = INF;
DFS(st, st, , st);
printf("%d\n", minStation);
for (auto x : ans) printf("Take Line#%d from %04d to %04d.\n", x.line, x.s, x.e);
}
return ;
}