UVA 208 Firetruck
https://vjudge.net/problem/UVA-208
题意:
按字典序输出1到k的所有路径
先从k bfs一遍,判断有哪些点能到k
枚举的时候只枚举能到k的点
#include<queue> #include<cstdio> #include<cstring> using namespace std; int k,sum; bool e[21][21]; bool ok[21]; bool vis[21]; int road[21]; bool have[21]; bool maybe() { memset(vis,false,sizeof(vis)); queue<int>q; q.push(k); vis[k]=true; int now; while(!q.empty()) { now=q.front(); q.pop(); for(int i=1;i<=20;i++) if(e[now][i] && !vis[i]) vis[i]=true,q.push(i); } return vis[1]; } void dfs(int now,int cnt) { have[now]=true; road[cnt]=now; if(now==k) { for(int i=1;i<cnt;i++) printf("%d ",road[i]); printf("%d\n",k); sum++; } for(int i=1;i<=20;i++) if(!have[i] && vis[i] && e[now][i]) dfs(i,cnt+1); have[now]=false; } int main() { int T=0; int u,v; while(scanf("%d",&k)!=EOF) { printf("CASE %d:\n",++T); memset(e,false,sizeof(e)); memset(ok,false,sizeof(ok)); while(1) { scanf("%d%d",&u,&v); if(!u) break; e[u][v]=e[v][u]=true; } sum=0; memset(have,false,sizeof(have)); if(maybe()) dfs(1,1); printf("There are %d routes from the firestation to streetcorner %d.\n",sum,k); } }