Advertisement
a53

Distanta

a53
Mar 21st, 2022
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.98 KB | None | 0 0
  1. #include <fstream>
  2. #include <vector>
  3. #include <queue>
  4. #include <unordered_map>
  5. #include <string>
  6. #define INF 0x3F3F3F3F
  7. using namespace std;
  8. unordered_map<string,int>mp;
  9. unordered_map<int,string>mp1;
  10. ifstream in("distanta.in");
  11. ofstream out("distanta.out");
  12. string s;
  13. int n,m;
  14. vector<int>d,dist,t;
  15. vector<pair<int,int>>g[21];
  16. int p,q;
  17. int dp[21][21];
  18.  
  19. long long bfs(int node)
  20. {
  21. queue<int>coada;
  22. coada.push(node);
  23. d[node]=0;
  24. int ok=0;
  25. while(!coada.empty())
  26. {
  27. int node=coada.front();
  28. coada.pop();
  29. for(auto& i:g[node])
  30. {
  31. if(!ok&&i.first==q)
  32. continue;
  33. int tmp=i.second+d[node];
  34. if(d[i.first]>=tmp)
  35. d[i.first]=tmp,t[i.first]=node,coada.push(i.first);
  36. }
  37. ++ok;
  38. }
  39. return d[q];
  40. }
  41.  
  42. int main()
  43. {
  44. in>>n;
  45. d=t=vector<int>(n+1);
  46. dist=vector<int>(n+1);
  47. for(int i=1;i<=n;++i)
  48. t[i]=i,in>>s>>d[i],dist[i]=d[i],mp[s]=i,mp1[i]=s;
  49. in>>m;
  50. for(int i=0;i<m;++i)
  51. {
  52. string a,b;
  53. int c;
  54. in >>a>>b>>c;
  55. int cost=c+d[mp[a]]+d[mp[b]];
  56. dp[mp[a]][mp[b]]=cost;
  57. dp[mp[b]][mp[a]]=cost;
  58. g[mp[a]].push_back(make_pair(mp[b],cost));
  59. g[mp[b]].push_back(make_pair(mp[a],cost));
  60. }
  61. string a,b;
  62. in>>a>>b;
  63. p=mp[a];
  64. q=mp[b];
  65. d=vector<int>(n+1,INF);
  66. long long maxi=bfs(p);
  67. if(maxi==INF)
  68. out<<"NU EXISTA TRASEU";
  69. else
  70. {
  71. vector<int>ans;
  72. int aux=q;
  73. while(t[q]!=q)
  74. ans.push_back(q),q=t[q],maxi-=dist[q];
  75. q=aux;
  76. if(maxi+dist[p]>dp[p][q]&&dp[p][q])
  77. out<<dp[p][q]<<'\n'<<mp1[p]<<'\n'<<mp1[q]<<'\n';
  78. else
  79. {
  80. out<<maxi+dist[p]<<'\n';
  81. out<<a<<'\n';
  82. for(vector<int>::reverse_iterator it=ans.rbegin();it!=ans.rend();++it)
  83. out<<mp1[*it]<<'\n';
  84. }
  85. }
  86. return 0;
  87. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement