L3-014 周游世界
高难度dfs,解析看subway map那篇博客
#include<cstdio> #include<algorithm> #include<cstring> #include<map> #include<vector> using namespace std; const int maxn=10014; map<int,int> line; vector<int> g[maxn]; vector<int> path,tmp; int transferCnt (vector<int> vi) { int cnt=0; int pre=vi[0]; for (int i=1;i<vi.size()-1;i++) { if (line[pre*10000+vi[i]]!=line[vi[i]*10000+vi[i+1]]) cnt++; pre=vi[i]; } return cnt; } int minTransferCnt=1e9; int minCnt=1e9; int st,ed; bool visit[maxn]; void dfs (int st) { tmp.push_back(st); visit[st]=true; if (st==ed) { if (tmp.size()<minCnt) { path=tmp; minCnt=tmp.size(); minTransferCnt=transferCnt(tmp); } else if (tmp.size()==minCnt&&transferCnt(tmp)<minTransferCnt) { path=tmp; minTransferCnt=transferCnt(tmp); } tmp.pop_back(); return; } for (int i=0;i<g[st].size();i++) { if (visit[g[st][i]]==false) { dfs (g[st][i]); visit[g[st][i]]=false; //tmp.pop_back(); } } tmp.pop_back(); } int main () { int n,k,pre,x; scanf ("%d",&n); for (int i=1;i<=n;i++) { scanf ("%d %d",&k,&pre); for (int j=1;j<k;j++) { scanf ("%d",&x); g[x].push_back(pre); g[pre].push_back(x); line[pre*10000+x]=i; line[x*10000+pre]=i; pre=x; } } int q; scanf ("%d",&q); for (int i=0;i<q;i++) { scanf ("%d %d",&st,&ed); fill (visit,visit+maxn,false); minCnt=1e9; minTransferCnt=1e9; tmp.clear (); dfs (st); visit[st]=false; if (minCnt==1e9) { printf ("Sorry, no line is available.\n"); continue; } printf ("%d\n",minCnt-1); int preL=0; for (int i=1;i<path.size();i++) { if (line[path[i-1]*10000+path[i]]!=line[path[i]*10000+path[i+1]]) { printf ("Go by the line of company #%d from %04d to %04d.\n",line[path[i-1]*10000+path[i]],path[preL],path[i]); preL=i; } } } return 0; }