Abrar_Al_Samit

Find The Length (FW TREE) (CF GYM 100917F)

Aug 4th, 2021 (edited)
143
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.24 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3.  
  4. const int MAXN = 301;
  5. const long long INF = 1e12 + 8;
  6. long long adj[MAXN][MAXN], par[MAXN][MAXN], dist[MAXN][MAXN], N, Timer;
  7. vector<int>T[MAXN], in(MAXN), out(MAXN);
  8.  
  9. void DFS(int node, int parent) {
  10.     in[node] = Timer++;
  11.     for(auto child : T[node]) if(child != parent) {
  12.         DFS(child, node);
  13.     }
  14.     out[node] = Timer++;
  15. }
  16. int Process(int r) {
  17.     Timer = 0;
  18.     vector<vector<bool>>TreeEdge(N+1, vector<bool>(N+1));
  19.     for(int i=1; i<=N; ++i) if(i!=r) {
  20.         if(dist[r][i]==INF) continue;
  21.         int p = par[r][i];
  22.         TreeEdge[i][p] = true;
  23.         TreeEdge[p][i] = true;
  24.  
  25.         // Re-build Tree in Adjacency List
  26.         T[p].push_back(i);
  27.     }
  28.     DFS(r, r);
  29.     long long ret = INF;
  30.     vector<int>token(N+1);
  31.     for(int i=1; i<=N; ++i) {
  32.         token[i] = i;
  33.         for(int anc=1; anc<=N; ++anc) if(anc!=r && in[anc]<in[token[i]] && out[anc]>out[token[i]]) {
  34.             token[i] = anc;
  35.         }
  36.     }
  37.     for(int i=1; i<=N; ++i) {
  38.         for(int j=1; j<=N; ++j) if(j!=r && j!=i) {
  39.             if(TreeEdge[i][j]==false && adj[i][j]!=-1) {
  40.                 if(token[i]!=token[j]) {
  41.                     ret = min(ret, dist[r][i] + dist[r][j] + adj[i][j]);
  42.                 }
  43.             }
  44.         }
  45.     }
  46.     if(ret==INF) ret = -1;
  47.  
  48.     // Clean up
  49.     for(int i=1; i<=N; ++i) {
  50.         T[i].clear();
  51.         in[i] = out[i] = 0;
  52.     }
  53.  
  54.     return ret;
  55.  
  56.  
  57. }
  58. void PlayGround() {
  59.     cin >> N;
  60.     for(int i=1; i<=N; ++i) {
  61.         for(int j=1; j<=N; ++j) {
  62.             cin >> adj[i][j];
  63.             if(adj[i][j]==-1) dist[i][j] = INF;
  64.             else dist[i][j] = adj[i][j], par[i][j] = i;
  65.         }
  66.     }
  67.     for(int k=1; k<=N; ++k) {
  68.         for(int i=1; i<=N; ++i) {
  69.             for(int j=1; j<=N; ++j) {
  70.                 long long x = dist[i][k] + dist[k][j];
  71.                 if(dist[i][j] > x) {
  72.                     dist[i][j] = x;
  73.                     par[i][j] = par[k][j];
  74.                 }
  75.             }
  76.         }
  77.     }
  78.     for(int r=1; r<=N; ++r) {
  79.         cout << Process(r) << '\n';
  80.     }
  81.  
  82.  
  83.     // cerr << "Time elapsed: " << 1.0 * clock() / CLOCKS_PER_SEC << " s.\n";
  84. }
  85. int main() {
  86.  
  87.     PlayGround();
  88.     return 0;
  89. }
Add Comment
Please, Sign In to add comment