zoukankan      html  css  js  c++  java
  • 1131(★、※)Subway Map

    思路:DFS遍历

     1 #include <iostream>
     2 #include <map>
     3 #include <vector>
     4 #include <cstdio>
     5 using namespace std;
     6 
     7 const int INF = 0x7fffffff;
     8 const int maxn = 10010;
     9 
    10 struct Node{
    11     int line, s, e;
    12     Node(int xl, int xs, int xe) :line(xl), s(xs), e(xe) {}
    13 };
    14 
    15 struct WhichLine {
    16     int u, v;
    17     WhichLine(int _u, int _v) :u(_u), v(_v) {}
    18     friend bool operator <(WhichLine a,WhichLine b) {//const whichLine &a, const whichLine &b
                                     //如果只是whichLine &a, whichLine &b报错
    19 if (a.u != b.u) return a.u < b.u; 20 else return a.v < b.v; 21 } 22 }; 23 map<WhichLine, int> searchLine;//判断两个站点在哪条线上 24 vector<int> G[maxn];//图的邻接表 25 bool visit[maxn];//判断是否已经访问数组 26 int minStation, minTransfer;//最少的站点,最少的换乘 27 vector<Node> ans, temp;//最终结果路径和中间记录路径 28 int st, ed; 29 30 31 void DFS(int head, int now, int stationCnt, int pre) { 32 if (now == ed) { 33 if (stationCnt < minStation || stationCnt == minStation && temp.size() < minTransfer) { 34 minStation = stationCnt; 35 minTransfer = temp.size(); 36 ans = temp; 37 ans.push_back(Node(searchLine[WhichLine(pre, now)], head, now)); 38 return; 39 } 40 } 41 42 visit[now] = true; 43 for (auto next : G[now]) { 44 if (visit[next]) continue; 45 if (pre != now && searchLine[WhichLine(pre, now)] != searchLine[WhichLine(now, next)]) { 46 47 temp.push_back(Node(searchLine[WhichLine(pre, now)], head, now)); 48 DFS(now, next, stationCnt + 1, now); 49 temp.pop_back(); 50 } 51 else DFS(head, next, stationCnt + 1, now); 52 } 53 54 visit[now] = false; 55 } 56 57 58 59 60 int main(){ 61 int n; 62 scanf("%d", &n); 63 for (int i = 1; i <= n; ++i){ 64 int k, u, v; 65 scanf("%d", &k); 66 for (int j = 0; j < k; j++) { 67 scanf("%d", &v); 68 if (j > 0) { 69 searchLine[WhichLine(u, v)] = i;//两个相邻节点的线路 70 searchLine[WhichLine(v, u)] = i; 71 G[u].push_back(v); 72 G[v].push_back(u); 73 } 74 u = v; 75 } 76 } 77 int q; 78 scanf("%d", &q); 79 while (q--){ 80 scanf("%d %d", &st, &ed); 81 minStation = minTransfer = INF; 82 DFS(st, st, 0, st); 83 printf("%d ", minStation); 84 for (auto x : ans) printf("Take Line#%d from %04d to %04d. ", x.line, x.s, x.e); 85 } 86 return 0; 87 }
  • 相关阅读:
    使用GitHub建立自己的个人主页
    学习Linux第二天
    学习Linux第一天
    网页布局基础
    HTML弹出窗口
    CSS进阶
    HTML+CSS入门
    廖老师JavaScript教程高阶函数-sort用法
    获取页面的title值
    if...else...这段代码打印结果,并简述其理由
  • 原文地址:https://www.cnblogs.com/fuqia/p/9590738.html
Copyright © 2011-2022 走看看