习题7-1 消防车 UVa208

来源:互联网 发布:淘宝的售后服务在哪里 编辑:程序博客网 时间:2024/04/30 14:48

1.题目描述:点击打开链接

2.解题思路:本题让按照字典序来枚举从1到k的所有路径,结点不能重复经过;类似于枚举全排列,不过事先要判断1到k是否联通,否则会TLE,判断连通的方法据说是Floyd算法(队友告诉我的,一种找两点间接有联系的有效算法),之前我试着用dfs找1到k能否连通,但我写的算法自身有致命缺陷,还是通过对拍才找到的。。。这道题不太难,但我在判断1到k是否连通这个地方花费了很多时间,频繁TLE,RE或WA==,还好又学会了一种新算法,也算小有收获~

3.代码:

#define _CRT_SECURE_NO_WARNINGS#include<iostream>#include<algorithm>#include<string>#include<sstream>#include<set>#include<vector>#include<stack>#include<map>#include<queue>#include<cstdlib>#include<cstdio>#include<cstring>#include<cmath>using namespace std;const int maxn = 20 + 10;int G[maxn][maxn];int rem[maxn][maxn];int k;int cnt;int arr[maxn];queue<int>q;void dfs(int n, int start, int cur){if (cur > n)return;if (start == k){cnt++;for (int i = 0; i<cur; i++)printf("%s%d", i == 0 ? "" : " ", arr[i]);printf("\n");return;}int num = G[start][0];for (int i = 1; i <= num; i++){int ok = 1;for (int j = 0; j < cur; j++)if (arr[j] == G[start][i])ok = 0;if (ok){arr[cur] = G[start][i];dfs(n, G[start][i], cur + 1);}}}int main(){//freopen("test.txt", "r", stdin);//freopen("RE.txt", "w", stdout);int a, b;int rnd = 0;while (scanf("%d", &k) != EOF){cnt = 0;while (!q.empty())q.pop();memset(G, 0, sizeof(G));memset(rem, 0, sizeof(rem));memset(arr, 0, sizeof(arr));int max_d = 1;while (scanf("%d%d", &a, &b), a || b){if (!rem[a][b]){ G[a][++G[a][0]] = b; rem[a][b] = 1; }if (!rem[b][a]){ G[b][++G[b][0]] = a; rem[b][a] = 1; }max_d = max(max_d, max(a, b));}for (int i = 1; i <= max_d; i++)sort(G[i] + 1, G[i] + G[i][0] + 1);for (int l = 1; l <= max_d; l++)//找间接相连的点,注意l要放在第一层循环for (int i = 1; i <= max_d; i++)for (int j = 1; j <= max_d; j++)rem[i][j] |= rem[i][l] & rem[l][j];arr[0] = 1;printf("CASE %d:\n", ++rnd);if (rem[1][k])//判断能否到达目标点dfs(max_d, 1, 1);printf("There are %d routes from the firestation to streetcorner %d.\n", cnt, k);}return 0;}


0 0