Advertisement
Alex_tz307

146. graph

Apr 19th, 2021
674
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.67 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. ifstream fin("graph.in");
  6. ofstream fout("graph.out");
  7.  
  8. const int INF = 2e9L;
  9. const int NMAX = 1500;
  10. int N, M, dp[NMAX + 1][NMAX + 1], deg[NMAX + 1];
  11. vector<pair<int,int>> G[NMAX + 1];
  12. vector<int> top_order;
  13.  
  14. void init() {
  15.     for(int i = 0; i <= N; ++i)
  16.         for(int j = 0; j <= N; ++j)
  17.             dp[i][j] = INF;
  18. }
  19.  
  20. void read() {
  21.     fin >> N >> M;
  22.     while(M--) {
  23.         int u, v, w;
  24.         fin >> u >> v >> w;
  25.         G[u].emplace_back(v, w);
  26.         ++deg[v];
  27.     }
  28. }
  29.  
  30. void topological_sort() {
  31.     queue<int> Q;
  32.     for(int u = 1; u <= N; ++u)
  33.         if(deg[u] == 0)
  34.             Q.emplace(u);
  35.     while(!Q.empty()) {
  36.         int u = Q.front();
  37.         Q.pop();
  38.         top_order.emplace_back(u);
  39.         for(const pair<int,int> &v : G[u]) {
  40.             --deg[v.first];
  41.             if(deg[v.first] == 0)
  42.                 Q.emplace(v.first);
  43.         }
  44.     }
  45. }
  46.  
  47. void solve() {
  48.     for(int source = 1; source <= N; ++source) {
  49.         dp[source][source] = 0;
  50.         for(const int &u : top_order) {
  51.             if(dp[source][u] == INF)
  52.                 continue;
  53.             for(const pair<int,int> &v : G[u])
  54.                 if(dp[source][v.first] > dp[source][u] + v.second)
  55.                     dp[source][v.first] = dp[source][u] + v.second;
  56.         }
  57.     }
  58. }
  59.  
  60. void print() {
  61.     for(int i = 1; i <= N; ++i, fout << '\n')
  62.         for(int j = 1; j <= N; ++j, fout << ' ')
  63.             if(dp[i][j] == INF)
  64.                 fout << 'x';
  65.             else
  66.                 fout << dp[i][j];
  67. }
  68.  
  69. int main() {
  70.     read();
  71.     init();
  72.     topological_sort();
  73.     solve();
  74.     print();
  75. }
  76.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement