Submission #1309106

#TimeUsernameProblemLanguageResultExecution timeMemory
1309106saken03Toll (BOI17_toll)C++20
100 / 100
89 ms83748 KiB
#include <algorithm>
#include <iostream>
#include <cstring>

#define pb push_back

#define fi first
#define se second

typedef long long ll;

using namespace std;

const int N = 50005;
const int INF = 1e9;

int k, n, m, o;
int dp[N][17][5][5]; // kA + x -> (kA + 2^i) + y
int ans[5][5], tmp[5][5];


void combine(int tar[5][5], int a[5][5], int b[5][5]) {
    for (int x = 0; x < k; x++) {
        for (int y = 0; y < k; y++) {
            for (int z = 0; z < k; z++) {
                tar[x][y] = min(tar[x][y], a[x][z] + b[z][y]);
            //  dp[i][j][x][y] = min dp[i][j - 1][x][z] + dp[i + (1 << j - 1)][j - 1][z][y])
//  min cost (ki + x) -> (ki+2^j + y) = min (ki + x) -> (ki+2^j-1 + z) + (ki+2^j-1 + z) -> (ki+2j + y)
            }
        }
    }
}

void solve() {
    cin >> k >> n >> m >> o;

    memset(dp, 0x3f, sizeof dp);
    for (int i = 0; i < m; i++) {
        int a, b, c;
        cin >> a >> b >> c;
        dp[a / k][0][a % k][b % k] = c;
    }

    for (int j = 1; j < 17; j++) {
        for (int i = 0; i + (1 << j) < (n + k - 1) / k; i++) {
            combine(dp[i][j], dp[i][j - 1], dp[i + (1 << (j - 1))][j - 1]);
        }
    }

    while (o--) {
        int a, b;
        cin >> a >> b;

        memset(ans, 0x3f, sizeof ans);
		for (int i = 0; i < 5; i++) ans[i][i] = 0;

        for (int cur = a / k, dest = b / k, i = 16; i >= 0; i--) {
            if (cur + (1 << i) <= dest) {

                for (int x = 0; x < 5; x++) {
                    for (int y = 0; y < 5; y++) {
                        tmp[x][y] = INF;
                    }
                }

                combine(tmp, ans, dp[cur][i]);

                for (int x = 0; x < 5; x++) {
                    for (int y = 0; y < 5; y++) {
                        ans[x][y] = tmp[x][y];
                    }
                }

                cur += (1 << i);
            }
        }

        cout << (ans[a % k][b % k] >= 1e9 ? -1 : ans[a % k][b % k]) << '\n';
    }
}

int main() {
    ios::sync_with_stdio(0);
    cin.tie(0);

    solve();

    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...