UVA - 208 Firetruck
2014-10-22 16:06
447 查看
题目大意:给一个点,然后给一系列相连的线段,要求按字典序输出从1到该点所经过的点
解题思路:这个如果直接回溯的话,会出现TLE,因为有做无用功,如果是稠密图的话,就会出错了,先把和终点有联系的点找出来,然后将其放在一个数组中,排序一下,再用该数组进行判断,判断点是否符合要求
解题思路:这个如果直接回溯的话,会出现TLE,因为有做无用功,如果是稠密图的话,就会出错了,先把和终点有联系的点找出来,然后将其放在一个数组中,排序一下,再用该数组进行判断,判断点是否符合要求
#include<cstdio> #include<cstring> #include<algorithm> using namespace std; #define maxn 30 int g[maxn][maxn], res[maxn], vis[maxn], link[maxn], judge[maxn]; int _max,num,_count,number; void dfs_1(int cur) { judge[cur] = 1; link[_count++] = cur; for(int i = 1; i <= _max; i++) if(!judge[i] && g[cur][i]) dfs_1(i); } void dfs_2(int cur, int n) { if(cur == num) { for(int i = 0 ; i < n - 1; i++) printf("%d ",res[i]); printf("%d\n",res[n-1]); number++; } else for(int i = 1; i < _count; i++) if(vis[link[i]] && g[cur][link[i]]) { vis[link[i]] = 0; res = link[i]; dfs_2(link[i],n+1); vis[link[i]] = 1; } } int main() { int mark = 1; int n1, n2; while(scanf("%d", &num) != EOF) { memset(g,0,sizeof(g)); memset(judge,0,sizeof(judge)); memset(link,0,sizeof(link)); _max = 0; _count = 1; number = 0; for(int i = 0; ;i++) { scanf("%d%d", &n1,&n2); if(!n1 && !n2) break; g[n1][n2]++; g[n2][n1]++; if(n1 > _max) _max = n2; if(n2 > _max) _max = n2; } printf("CASE %d:\n",mark++); for(int i = 1; i <= _max ; i++) vis[i] = 1; res[0] = 1; vis[1] = 0; dfs_1(num); sort(link,link+_count); dfs_2(1,1); printf("There are %d routes from the firestation to streetcorner %d.\n",number,num); } return 0; }
相关文章推荐
- uva 208 - Firetruck
- uva 208 - Firetruck
- uva 208 Firetruck (需要预先处理 再dfs,TLE是此题AC常规步骤……)
- UVA 208 Firetruck
- uva208 - Firetruck
- UVa 208 - Firetruck(DFS判连通+回溯)
- UVa 208 - Firetruck
- UVa #208 Firetruck (习题7-1)
- uva208 - Firetruck
- UVA 208 Firetruck
- uva 208 - Firetruck
- UVA 208 - Firetruck
- UVa 208 - Firetruck
- UVa 208:Firetruck(DFS)
- UVA - 208 Firetruck(回溯)
- UVA 208 Firetruck
- UVA208-Firetruck
- UVa 208 - Firetruck,双向搜索进行剪枝
- 双向搜索(UVA 208 Firetruck)
- Uva208 Firetruck【dfs】【习题7-1】