Advertisement
Guest User

Untitled

a guest
Apr 22nd, 2018
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.28 KB | None | 0 0
  1. #include <iostream>
  2. #include <map>
  3. #include <vector>
  4. #include <queue>
  5. #include <functional>
  6.  
  7. using namespace std;
  8.  
  9. typedef vector<string> vs;
  10. typedef tuple<int, string, char> path;
  11.  
  12. map<string, map<string, vs> > G;
  13. map<string, int> D;
  14. string s, e;
  15. int n, m;
  16.  
  17. string dijkstra()
  18. {
  19. D.clear();
  20. priority_queue<path, vector<path>, greater<path> > PQ;
  21. PQ.emplace(0, s, '0');
  22. D[s] = 0;
  23. while (!PQ.empty())
  24. {
  25. string u;
  26. char c;
  27. int d;
  28. tie(d, u, c) = PQ.top(); PQ.pop();
  29.  
  30. if (u == e)
  31. return to_string(d);
  32.  
  33. if (D[s] && D[s] < d)
  34. continue;
  35.  
  36. for (auto it : G[u])
  37. {
  38. string v = it.first;
  39. for (string a : it.second)
  40. if (D.find(v) == D.end() || (a[0] != c && D[v] > D[u] + a.size()))
  41. D[v] = d + a.size(), PQ.emplace(d + a.size(), v, a[0]);
  42. }
  43. }
  44.  
  45. return "impossivel";
  46. }
  47.  
  48. int main()
  49. {
  50. while (cin >> m, m)
  51. {
  52. string a, b, d;
  53. cin >> s >> e;
  54. for (int i = 0; i < m; ++i)
  55. {
  56. cin >> a >> b >> d;
  57. G[a][b].push_back(d);
  58. G[b][a].push_back(d);
  59. }
  60.  
  61. cout << dijkstra() << '\n';
  62. }
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement