PAT A1131 Subway Map
Posted zhanglichen
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了PAT A1131 Subway Map相关的知识,希望对你有一定的参考价值。
dfs,选择最优路径并输出~
#include<bits/stdc++.h> using namespace std; const int maxn=10010; unordered_map<int,int> line; vector<int> g[maxn]; vector<int> path,tmp; bool visit[maxn]={false}; int minCnt=1e9; int minTransferCnt=1e9; int st,ed; int transfer (vector<int> v) { int cnt=0,preLine=0; for (int i=1;i<v.size();i++) if (line[v[i-1]*10000+v[i]]!=preLine) { cnt++; preLine=line[v[i-1]*10000+v[i]]; } return cnt; } void dfs (int v) { visit[v]=true; tmp.push_back(v); if (v==ed) { int transferCnt=transfer(tmp); if (tmp.size()<minCnt) { minCnt=tmp.size(); minTransferCnt=transferCnt; path=tmp; } else if (tmp.size()==minCnt&&transferCnt<minTransferCnt) { minTransferCnt=transferCnt; path=tmp; } visit[v]=false; tmp.pop_back(); return; } for (int i=0;i<g[v].size();i++) { if (visit[g[v][i]]==false) { dfs (g[v][i]); } } visit[v]=false; tmp.pop_back(); } int main () { int N; scanf ("%d",&N); int k,pre,x; for (int i=1;i<=N;i++) { scanf ("%d %d",&k,&pre); for (int j=1;j<k;j++) { scanf ("%d",&x); g[pre].push_back(x); g[x].push_back(pre); line[pre*10000+x]=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); minTransferCnt=1e9; minCnt=1e9; tmp.clear(); dfs (st); printf ("%d ",path.size()-1); int preLine=line[path[0]*10000+path[1]]; int pre=0; for (int j=0;j<path.size();j++) { if (line[path[j]*10000+path[j+1]]!=preLine) { printf ("Take Line#%d from %04d to %04d. ",preLine,path[pre],path[j]); pre=j; preLine=line[path[j]*10000+path[j+1]]; } } } return 0; }
以上是关于PAT A1131 Subway Map的主要内容,如果未能解决你的问题,请参考以下文章
PAT甲级1131 Subway Map (30分)(DFS)