UVA208 Firetruck 消防车(并查集,dfs)
2024-09-08 08:18:11
要输出所有路径,又要字典序,dfs最适合了,用并查集判断1和目的地是否连通即可
#include<bits/stdc++.h>
using namespace std;
const int maxn = ; int p[maxn],cnt[maxn];
void init(int n) {
for(int i = ;i <= n; i++) p[i] = i,cnt[i] = ;
}
int Find(int x) { return p[x] == x ? x : p[x] = Find(p[x]); } bool G0[maxn][maxn];
int G[maxn][maxn],deg[maxn]; int maxd;
int path[maxn];
bool vis[maxn];
int k,Count;
void dfs(int d,int cur)
{
if(cur == k){
printf("");
for(int i = ; i < d; i++)
printf(" %d",path[i]);
puts("");
Count++;
return;
}
if(d == maxd) return;
for(int i = ; i < deg[cur]; i++){
int v = G[cur][i];
if(vis[v]) continue;
vis[v] = ;
path[d] = v;
dfs(d+,v);
vis[v] = ;
}
} int main()
{
//freopen("in.txt","r",stdin);
int cas = ;
while(~scanf("%d",&k)){
printf("CASE %d:\n",++cas);
int u,v,n = ;
init();
memset(G0,,sizeof(G0));
memset(deg,,sizeof(deg));
while(scanf("%d%d",&u,&v),u){
G0[u][v] = G0[v][u] = ;
n = max(n,v);
n = max(n,u);
int s1 = Find(u), s2 = Find(v);
if(s1 != s2) {p[s1] = s2; cnt[s2] += cnt[s1];}
}
if(Find(k) != Find()) {printf("There are 0 routes from the firestation to streetcorner %d.\n",k); continue;}
for(int i = ; i <= n; i++)
for(int j = ; j <= n; j++) if(G0[i][j]){
G[i][deg[i]++] = j;
}
maxd = cnt[Find()] ;
memset(vis,,sizeof(vis));
vis[] = ;
Count = ;
dfs(,);
printf("There are %d routes from the firestation to streetcorner %d.\n",Count,k);
}
return ;
}
最新文章
- 【JS基础】
- 北京54全国80及WGS84坐标系的相互转换
- java 线程安全 synchronized
- ndk学习10: linux文件系统
- 创建Struct2的web应用(一)
- 快速安装 GitLab 并汉化
- 【IOS笔记】Resource Management in View Controllers
- C语言开源项目
- html中调用silverlight中的方法
- C++ (P103—P154)
- 武汉科技大学ACM:1010: 零起点学算法89——母牛的故事
- iOS手机号正则表达式并实现344格式 (正则的另一种实现方式)
- poj 1715 Hexadecimal Numbers 排列组合
- jQuery从入门到忘记
- 如何用while循环输出十行十列变色★☆
- 细数本地连阿里云上mysql8遇到的坑
- no-sql数据库之redis
- python操作excel的读、计算、写----xlrd、copy
- Java JDBC基本用法
- 7z压缩与解压命令