此题题干略
Sample Input:
4
7 1001 3212 1003 1204 1005 1306 7797
9 9988 2333 1204 2006 2005 2004 2003 2302 2001
13 3011 3812 3013 3001 1306 3003 2333 3066 3212 3008 2302 3010 3011
4 6666 8432 4011 1306
3
3011 3013
6666 2001
2004 3001
Sample Output:
2
Take Line#3 from 3011 to 3013.
10
Take Line#4 from 6666 to 1306.
Take Line#3 from 1306 to 2302.
Take Line#2 from 2302 to 2001.
6
Take Line#2 from 2004 to 1204.
Take Line#1 from 1204 to 1306.
Take Line#3 from 1306 to 3001.
#include<stdio.h>
#include<vector>
#include<algorithm>
using namespace std;
int start;
int final;
int countmax=9999999;
struct Station
{
int line;
int id;
}station[10005];
vector<Station> seq[10005];
vector<Station> result;
vector<Station> stops;
bool flag[10005];
int submin;
void dfs(int s,int count)
{
if(s==final)
{
int sub=0;
if(countmax>count)
{
result=stops;
countmax=count;
for(int i=1;i<stops.size();i++)
{
if(stops[i].line!=stops[i-1].line)
{
sub++;
}
}
submin=sub;
}
if(countmax==count)
{
for(int i=1;i<stops.size();i++)
{
if(stops[i].line!=stops[i-1].line)
{
sub++;
}
}
if(sub<submin)
{
result=stops;
submin=sub;
}
}
return;
}
for(int i=0;i<seq[s].size();i++)
{
if(flag[seq[s][i].id]==false)
{
flag[seq[s][i].id]=true;
stops.push_back(seq[s][i]);
dfs(seq[s][i].id,count+1);
stops.pop_back();
flag[seq[s][i].id]=false;
}
}
}
int main()
{
int linenum;
scanf("%d",&linenum);
for(int i=1;i<=linenum;i++)
{
int potnum;
scanf("%d",&potnum);
for(int j=0;j<potnum;j++)
{
int temp;
scanf("%d",&temp);
station[j].id=temp;
station[j].line=i;
if(j!=0)
{
seq[station[j].id].push_back(station[j-1]);
seq[station[j-1].id].push_back(station[j]);
}
}
}
int cxnum;
scanf("%d",&cxnum);
for(int i=0;i<cxnum;i++)
{
scanf("%d %d",&start,&final);
countmax=9999999;
dfs(start,0);
printf("%d\n",countmax);
int lineout=result[0].line;
int id=start;
for(int i=0;i<result.size();i++)
{
if(lineout!=result[i].line)
{
printf("Take Line#%d from %04d to %04d.\n",lineout,id,result[i-1].id);
lineout=result[i].line;
id=result[i-1].id;
}
}
printf("Take Line#%d from %04d to %04d.\n",lineout,id,final);
}
}