• UVA208 消防车 Firetruck


    知识点:图的遍历,回溯

    这个题其实就是图的遍历然后加上回溯,但是有点坑的是,我们在找路径之前,要先判断1是不是能到k点,否则会超时,这个要不是看提示,还真想不到,因为如果不用别的函数来判断是不是连通的话,用求解的dfs函数,是自带回溯的,如果找不到,那么会比较费时间,会把所有的路径都走一遍,总之做这种图论的题总是会有很多这种考虑不周到,最后导致错误的地方,

    这里存图没用邻接矩阵,用的是董晓讲的链式邻接表,因为我们每个节点要从小到大遍历它连着的节点,所有搜索之前对每个点连着的点排序,如果是采用链式前向星的话,我想不到该怎么写程序,就没有使用那种存图方式,

    还有一点需要注意的是,题目输出,一个空格就够了,不需要样例里面长度为3的空格

    1. #include
    2. using namespace std;
    3. const int N = 25;
    4. int n, k, vis[N], cnt;
    5. vector<int> h[N], chosen;
    6. vectorint, int>> e;
    7. void add(int a, int b) {
    8. e.push_back(make_pair(a, b));
    9. h[a].push_back((int) e.size() - 1);
    10. }
    11. bool cmp(int a, int b) {
    12. return e[a].second < e[b].second;
    13. }
    14. bool bfs() {
    15. queue<int> q;
    16. q.push(1);
    17. int dist[N] = {};
    18. dist[1] = 1;
    19. while (!q.empty()) {
    20. int now = q.front(); q.pop();
    21. if (now == k) return true;
    22. for (int i = 0; i < (int) h[now].size(); i++) {
    23. int ind = h[now][i];
    24. int y = e[ind].second;
    25. if (dist[y]) continue;
    26. q.push(y);
    27. dist[y] = 1;
    28. }
    29. }
    30. return false;
    31. }
    32. void dfs(int x) {
    33. if (x == k) {
    34. for (int i = 0; i < (int) chosen.size(); i++) {
    35. cout << chosen[i] << (i < (int) chosen.size() - 1 ? " " : "\n");
    36. }
    37. cnt++;
    38. return;
    39. }
    40. for (int i = 0; i < (int) h[x].size(); i++) {
    41. int ind = h[x][i];
    42. int y = e[ind].second;
    43. if (vis[y]) continue;
    44. vis[y] = 1;
    45. chosen.push_back(y);
    46. dfs(y);
    47. chosen.pop_back();
    48. vis[y] = 0;
    49. }
    50. }
    51. int main() {
    52. int tt = 1;
    53. while (cin >> k) {
    54. n = 0; cnt = 0;
    55. e.clear();
    56. for (int i = 0; i < N; i++) h[i].clear();
    57. cout << "CASE " << tt++ << ":\n";
    58. int a, b;
    59. while (cin >> a >> b && a) {
    60. add(a, b);
    61. add(b, a);
    62. n = max(n, max(a, b));
    63. }
    64. for (int i = 1; i <= n; i++) {
    65. sort(h[i].begin(), h[i].end(), cmp);
    66. }
    67. if (bfs()) {
    68. vis[1] = 1;
    69. chosen.push_back(1);
    70. dfs(1);
    71. vis[1] = 0;
    72. chosen.pop_back();
    73. }
    74. printf("There are %d routes from the firestation to streetcorner %d.\n", cnt, k);
    75. }
    76. return 0;
    77. }

  • 相关阅读:
    PostgreSQL中实现数学中的组合问题
    Java技能树-RE-元字符-贪婪模式/非贪婪模式
    uniapp 分享到朋友圈
    【从零开始学习 SystemVerilog】8.3、SystemVerilog 约束—— Constraint Blocks(约束块)
    C++入门5 名字空间|new|虚拟地址
    合成孔径雷达地面运动目标检测技术研究——基于概率图(Matlab代码实现)
    Ubuntu18.04 ROS-Melodic安装Moveit
    微信如何设置自动回复消息,提升沟通效率的?
    HCIP实验2-1:IS-IS 配置实验
    QTableView对自定义的Model排序
  • 原文地址:https://blog.csdn.net/m0_73035684/article/details/127659586