#include<cstdio>
#include<iostream>
#include<cstring>
#include<vector>
#include<map>
#include<set>
#include<sstream>
#include<algorithm>//find()
using namespace std;
const int maxn=20+5;
int N,pa[maxn];
set<int> G[maxn];
int find_pa(int x){
return x==pa[x]?x:(pa[x]=find_pa(pa[x]));
}
ostream& operator<<(ostream& os,const vector<int>& s){
bool first=true;
for(int i=0;i<s.size();i++){
if(first) first=false;
else os<<" ";
os<<s[i];
}
return os;
}
vector<int> path;
vector<string> paths;
int vis[maxn];
void dfs(int src,int dest){
path.push_back(src);
vis[src]=1;
int v;
if(src==dest){
stringstream os; os<<path;
paths.push_back(os.str());
}
else {
for(set<int>::iterator it=G[src].begin();it!=G[src].end();it++){
v=*it;
if(vis[v])//
continue;
dfs(v,dest);
//vis[v]=0; ①
//path.pop_back(); ② (删除v)
}
}
vis[src]=0;// ③ 可删除③④语句换成①② 两个方法完全等价
path.pop_back();// ④ (删除src )
}
int main(){
for(int kase=1,from,to;scanf("%d",&N)==1;kase++){
for(int i=0;i<maxn;i++) G[i].clear(),pa[i]=i;//
paths.clear(),path.clear();
memset(vis,0,sizeof(vis));
while(true){
cin>>from>>to;
if(from==0||to==0)
break;
G[from].insert(to),G[to].insert(from);
int pf=find_pa(from),pt=find_pa(to);
if(pf!=pt)
pa[pt]=pf;
}
if(find_pa(1)==find_pa(N)) dfs(1,N);//先判断连通 连通再dfs
printf("CASE %d:\n",kase);
for(int i=0;i<paths.size();i++){
cout<<paths[i]<<endl;
}
printf("There are %lu routes from the firestation to streetcorner %d.\n",paths.size(),N);
}
return 0;
}
入门经典-习题7-1,109-uva208消防车-DFS,并查集,打印路径,利用set保存边,字典序,STL⭐⭐⭐⭐⭐复杂度:3
猜你喜欢
转载自blog.csdn.net/qq_41093189/article/details/79602163
今日推荐
周排行