Advertisement
oleg_drawer

bfs but dfs

Apr 23rd, 2020
299
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.22 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. int n;
  4. vector<vector<int>>g(0);
  5. vector<bool>used(0);
  6. pair<int, string> dfs(int st, int nd){
  7.     used[st] = true;
  8.     if(st == nd){
  9.         used[st] = false;
  10.         return {0 , ""};
  11.     }
  12.     int c = g[st][nd];
  13.     char x = char('A'+st);
  14.     char y = char('A'+nd);
  15.     char z = char('0' + g[st][nd]);
  16.     string s = "";
  17.     s+=y;
  18.     s+=x;
  19.     s+=z;
  20.     for(int i = 0; i < n; i++){
  21.         if(used[i])
  22.             continue;
  23.         auto par = dfs(i, nd);
  24.         if( par.first + g[st][i] < c){
  25.             c = par.first + g[st][i];
  26.             s = par.second + "--" + char('A'+i) + x  + char('0' + g[st][i]);
  27.         }
  28.  
  29.     }
  30.     used[st] = false;
  31.     return {c, s};
  32. }
  33.  
  34. int main() {
  35.     cin >> n;
  36.     g.resize(n, vector<int>(n, 1000000));
  37.     used.resize(n, false);
  38.     for(int i = 0; i < n; i++){
  39.         for(int j = 0; j < n; j++){
  40.             int c;
  41.             cin >> c;
  42.             if(c > -1)
  43.                 g[i][j] = c;
  44.         }
  45.     }
  46.     int a,b, c;
  47.     cin >> a >> b >> c;
  48.     auto par1 = dfs(b, a);
  49.     auto par2 = dfs(c,b);
  50.     cout << par1.first + par2.first << endl;
  51.     cout << par1.second + "--" + par2.second << endl;
  52.  
  53.     return 0;
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement