Advertisement
mickypinata

PROG-T1133: Subway

Jun 29th, 2021
582
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.57 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. const int N = 1e6;
  5. const int M = 500;
  6.  
  7. vector<int> line[N + 1];
  8. int dist[M + 1][M + 1];
  9.  
  10. int main(){
  11.  
  12.     int nStation, nLine;
  13.     scanf("%d%d", &nStation, &nLine);
  14.  
  15.     // APSP Setup
  16.     for(int u = 1; u <= nLine; ++u){
  17.         for(int v = 1; v <= nLine; ++v){
  18.             if(u == v){
  19.                 dist[u][v] = 0;
  20.             } else {
  21.                 dist[u][v] = 1e9;
  22.             }
  23.         }
  24.     }
  25.     for(int u = 1; u <= nLine; ++u){
  26.         int nPass;
  27.         scanf("%d", &nPass);
  28.         for(int j = 1; j <= nPass; ++j){
  29.             int station;
  30.             scanf("%d", &station);
  31.             for(int v : line[station]){
  32.                 if(u == v){
  33.                     continue;
  34.                 }
  35.                 dist[u][v] = 1;
  36.                 dist[v][u] = 1;
  37.             }
  38.             line[station].push_back(u);
  39.         }
  40.     }
  41.  
  42.     // Floyd-Warshall Algorithm
  43.     for(int k = 1; k <= nLine; ++k){
  44.         for(int u = 1; u <= nLine; ++u){
  45.             for(int v = 1; v <= nLine; ++v){
  46.                 dist[u][v] = min(dist[u][v], dist[u][k] + dist[k][v]);
  47.             }
  48.         }
  49.     }
  50.  
  51.     int Q;
  52.     scanf("%d", &Q);
  53.     while(Q--){
  54.         int st, ed;
  55.         scanf("%d%d", &st, &ed);
  56.         int mn = 1e9;
  57.         for(int u : line[st]){
  58.             for(int v : line[ed]){
  59.                 mn = min(mn, dist[u][v]);
  60.             }
  61.         }
  62.         if(mn == 1e9){
  63.             cout << "impossible\n";
  64.         } else {
  65.             cout << mn << '\n';
  66.         }
  67.     }
  68.  
  69.     return 0;
  70. }
  71.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement