#include <bits/stdc++.h>
using namespace std;
#define inf 100000000
#define maxn 10000
struct node{
int id,l;
};
int n,m,k,s,e,mins,mint;
bool vis[maxn]={0};
vector<node> g[maxn],temp,path;
void dfs(int st,int cnt1,int cnt2)
{
if(st==e&&(cnt1<mins||(cnt1==mins&&cnt2<mint)))
{
mins=cnt1;
mint=cnt2;
path=temp;
}
if(st==e)
{ return; }
for(int i=0;i<g[st].size();i++)
{
if(vis[g[st][i].id]==0)
{
if(st==s)
{ temp[0].l=g[st][i].l; }
if(g[st][i].l!=temp[temp.size()-1].l)//注意顺序
{ cnt2++; }
temp.push_back(g[st][i]);
vis[g[st][i].id]=1;
dfs(g[st][i].id,cnt1+1,cnt2);
vis[g[st][i].id]=0;
temp.pop_back();
if(g[st][i].l!=temp[temp.size()-1].l)
{ cnt2--; }
}
}
}
int main() {
scanf("%d",&n);
for(int i=1;i<=n;i++)
{
scanf("%d %d",&m,&s);
for(int j=1;j<m;j++)
{
scanf("%d",&e);
node a,b;
a.id=s;
a.l=b.l=i;
b.id=e;
g[s].push_back(b);
g[e].push_back(a);
s=e;
}
}
scanf("%d",&k);
while(k--)
{
scanf("%d %d",&s,&e);
mins=mint=inf;
temp.clear();
node a;
a.id=s;
temp.push_back(a);
vis[s]=1;
dfs(s,0,0);
vis[s]=0;
printf("%d\nTake Line#%d from %04d to ",mins,path[0].l,s);
for(int i=1;i<path.size();i++)
{
if(i<path.size()-1&&path[i].l!=path[i+1].l)
{ printf("%04d.\nTake Line#%d from %04d to ",path[i].id,path[i+1].l,path[i].id); }
if(i==path.size()-1)
{ printf("%04d.\n",e); }
}
}
return 0;
}
PAT A1131 Subway Map (30分)
最新推荐文章于 2021-05-22 19:35:56 发布