tien_noob

MulMatrix - shortest path after right k edges (what the fuck is this)

May 20th, 2021 (edited)
131
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.85 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. #define TASK "CROBOT"
  3. using namespace std;
  4. const long long oo = 1e18 + 100;
  5. const int N = 1e2;
  6. vector<vector< long long > > w, d;
  7. int n, m, k;
  8. void ResizeMatrix(vector<vector<long long> > & x)
  9. {
  10.     x.resize(n + 1);
  11.     for (int i = 1; i <= n; ++ i)
  12.     {
  13.         x[i].resize(n + 1, oo);
  14.     }
  15. }
  16. vector<vector<long long> > operator *= (vector<vector<long long> > & a, vector<vector<long long> > & b)
  17. {
  18.     vector<vector<long long> > c;
  19.     ResizeMatrix(c);
  20.     for (int i = 1; i <= n; ++ i)
  21.     {
  22.         for (int j = 1; j <= n; ++ j)
  23.         {
  24.             for (int k = 1; k <= n; ++ k)
  25.             {
  26.                 if (a[i][k] < oo && b[k][j] < oo)
  27.                 {
  28.                     c[i][j] = min(c[i][j], a[i][k] + b[k][j]);
  29.                 }
  30.             }
  31.         }
  32.     }
  33.     swap(a, c);
  34.     return a;
  35. }
  36. void read()
  37. {
  38.     cin >> n >> m >> k;
  39.     ResizeMatrix(w);
  40.     ResizeMatrix(d);
  41.     for (int i = 1; i <= n; ++ i)
  42.     {
  43.         d[i][i] = 0;
  44.     }
  45.     for (int i = 1; i <= m; ++ i)
  46.     {
  47.         int u, v;
  48.         long long weight;
  49.         cin >> u >> v >> weight;
  50.         w[u][v] = min(w[u][v], weight);
  51.     }
  52. }
  53. void solve()
  54. {
  55.     vector<vector<long long> > a = w;
  56.     for (; k > 0; k /= 2)
  57.     {
  58.         if (k & 1)
  59.             d *= a;
  60.         a *= a;
  61.     }
  62.     long long ans = oo;
  63.     for (int i = 1; i <= n; ++ i)
  64.     {
  65.         ans = min(ans, d[i][i]);
  66.     }
  67.     if (ans == oo)
  68.     {
  69.         cout << -1;
  70.         return ;
  71.     }
  72.     cout << ans;
  73. }
  74. int main()
  75. {
  76.     ios_base::sync_with_stdio(false);
  77.     cin.tie(nullptr);
  78.     freopen(TASK".INP", "r", stdin);
  79.     freopen(TASK".OUT", "w", stdout);
  80.     int t = 1;
  81.     bool typetest = false;
  82.     if (typetest)
  83.     {
  84.         cin >> t;
  85.     }
  86.     for (int __ = 1; __ <= t; ++ __)
  87.     {
  88.         read();
  89.         solve();
  90.     }
  91. }
  92.  
Add Comment
Please, Sign In to add comment