제출 #530006

#제출 시각아이디문제언어결과실행 시간메모리
530006Alex_tz307Toll (BOI17_toll)C++17
100 / 100
103 ms79540 KiB
#include <bits/stdc++.h>
#define INF 0x3f3f3f3f

using namespace std;

const int kN = 5e4;
const int kLog = 15;
const int kK = 5;
int res[kK][kK], ret[kK][kK], dp[kN][1 + kLog][kK][kK];

void minSelf(int &x, int y) {
  if (y < x) {
    x = y;
  }
}

void combine(int n, int a[kK][kK], int b[kK][kK], int c[kK][kK]) {
  for (int i = 0; i < n; ++i) {
    for (int j = 0; j < n; ++j) {
      for (int k = 0; k < n; ++k) {
        minSelf(a[i][j], b[i][k] + c[k][j]);
      }
    }
  }
}

void testCase() {
  int k, n, m, q;
  cin >> k >> n >> m >> q;
  for (int i = 0; i <= (n - 1) / k; ++i) {
    for (int j = 0; (1 << j) <= (n - 1) / k; ++j) {
      for (int a = 0; a < k; ++a) {
        for (int b = 0; b < k; ++b) {
          dp[i][j][a][b] = INF;
        }
      }
    }
  }
  for (int i = 0; i < m; ++i) {
    int a, b, t;
    cin >> a >> b >> t;
    dp[a / k][0][a % k][b % k] = t;
  }
  for (int j = 1; (1 << j) <= (n - 1) / k; ++j) {
    for (int i = 0; i + (1 << j) - 1 <= (n - 1) / k; ++i) {
      combine(k, dp[i][j], dp[i][j - 1], dp[i + (1 << (j - 1))][j - 1]);
    }
  }
  for (int qq = 0; qq < q; ++qq) {
    int a, b;
    cin >> a >> b;
    if (a / k == b / k) {
      cout << "-1\n";
      continue;
    }
    for (int i = 0; i < k; ++i) {
      for (int j = 0; j < k; ++j) {
        if (i == j) {
          res[i][i] = 0;
        } else {
          res[i][j] = INF;
        }
      }
    }
    int s = a / k, t = b / k;
    for (int i = kLog; i >= 0; --i) {
      if (s + (1 << i) <= t) {
        for (int l = 0; l < k; ++l) {
          for (int c = 0; c < k; ++c) {
            ret[l][c] = res[l][c];
            res[l][c] = INF;
          }
        }
        combine(k, res, ret, dp[s][i]);
        s += (1 << i);
      }
    }
    if (res[a % k][b % k] == INF) {
      cout << "-1\n";
    } else {
      cout << res[a % k][b % k] << '\n';
    }
  }
}

int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(nullptr);
  int tests = 1;
  for (int tc = 0; tc < tests; ++tc) {
    testCase();
  }
  return 0;
}
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...