UVA - 208 Firetruck

来源:互联网 发布:彩票的算法 编辑:程序博客网 时间:2024/04/29 03:42

题目大意:给一个点,然后给一系列相连的线段,要求按字典序输出从1到该点所经过的点

解题思路:这个如果直接回溯的话,会出现TLE,因为有做无用功,如果是稠密图的话,就会出错了,先把和终点有联系的点找出来,然后将其放在一个数组中,排序一下,再用该数组进行判断,判断点是否符合要求

#include<cstdio>#include<cstring>#include<algorithm>using namespace std;#define maxn 30int 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[n] = 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;}


0 0
原创粉丝点击