Baltic OI 2017 - Toll
Author: Andi Qu
Solution
Split the graph into "layers" with nodes each. Notice how this graph somewhat resembles a neural network.
Let denote the minimum cost of a path between nodes to .
For any triple , the following recurrence holds:
This is known as the product.
To finish, we can use any algorithm that allows us to quickly answer static range queries (ex. divide & conquer). Another approach is to use a sparse table. Instead of storing each DP state, we can store only for each , , , and . Then we can find the value of in time per query with binary jumping. This gives a time complexity of .
Implementation
per query. We can reduce this to
per query by only storing the a % k
-th row of ans
.
C++
#include <bits/stdc++.h>using namespace std;int k, n, m, o;int dp[50000][17][5][5], ans[5][5], tmp[5][5];void combine(int target[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++) {
Python
MAX_K = 5MAX_J = 17def combine(target: list[list[int]], a: list[list[int]], b: list[list[int]]):for x in range(k):for y in range(k):for z in range(k):target[x][y] = min(target[x][y], a[x][z] + b[z][y])
Join the USACO Forum!
Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!