giabinh

762_WeShipCheap

Sep 8th, 2015
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.07 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. int trace[1002];
  6. vector <int> adj[1002];
  7.  
  8. void BFS(int s, int t) {
  9.     queue <int> q;
  10.     q.push(s);
  11.     trace[s] = -1;
  12.  
  13.     while (!q.empty())
  14.     {
  15.         int u = q.front(); q.pop();
  16.         if (u == t) break;
  17.  
  18.         for (int i=0; i<adj[u].size(); ++i)
  19.         {
  20.             int v = adj[u][i]; //cout << v << endl;
  21.             if (!trace[v])
  22.             {
  23.                 q.push(v);
  24.                 trace[v] = u;
  25.             }
  26.         }
  27.     }
  28. }
  29.  
  30. int main() {
  31.     #ifndef ONLINE_JUDGE
  32.         freopen("uva762.inp", "r", stdin);
  33.     #endif // ONLINE_JUDGE
  34.  
  35.     bool blank = true;
  36.     int E;
  37.     while (scanf("%d", &E) != EOF)
  38.     {
  39.         if (!blank) printf("\n"); else blank = false;
  40.  
  41.         int n = 0; //m.clear(); rm.clear();
  42.         string u, v;
  43.         map <string, int> m;
  44.         map <int, string> rm;
  45.  
  46.         for (int i=0; i<E; ++i)
  47.         {
  48.             cin >> u >> v;
  49.             //cout << u << " " << v << " " << m[u] << " " << m[v] << endl;
  50.             if (!m[u])
  51.             {
  52.                 m[u] = ++n;
  53.                 rm[n] = u;
  54.                 adj[m[u]].clear();
  55.             }
  56.             if (!m[v])
  57.             {
  58.                 m[v] = ++n;
  59.                 rm[n] = v;
  60.                 adj[m[v]].clear();
  61.             }
  62.  
  63.             adj[m[u]].push_back(m[v]);
  64.             adj[m[v]].push_back(m[u]);
  65.         }
  66.  
  67.         cin >> u >> v;
  68.         if (!m[u] || !m[v]) printf("No route\n");
  69.         else
  70.         {
  71.             for(int i=1; i<=n; ++i) trace[i] = 0;
  72.             BFS(m[u], m[v]);
  73.  
  74.             int s = m[u], f = m[v];
  75.             if (!trace[f]) printf("No route\n");
  76.             else
  77.             {
  78.                 vector <string> ans;
  79.                 while (s != f)
  80.                 {
  81.                     ans.push_back(rm[f]);
  82.                     f = trace[f];
  83.                 }
  84.  
  85.                 ans.push_back(rm[s]);
  86.                 for (int i=ans.size()-1; i>0; i--) cout << ans[i] << " " << ans[i-1] << endl;
  87.             }
  88.         }
  89.     }
  90.  
  91.     return 0;
  92. }
Advertisement
Add Comment
Please, Sign In to add comment