Table of Contents

ExplanationImplementation

Explanation

First, instead of trying to tackle the problem for arbitrary values of kk, let's try calculating the number of steps it takes for each node to reach node pp.

When at a fountain, we will only ever take the two most beautiful outgoing trails. Let's consider a graph, where we draw edges between states. Each state is represented as a pair (u,f)(u, f), where:

  • uu is our current node
  • ff represents whether we are taking the most beautiful trail
    • f=0f=0 means we can take the most beautiful trail
    • f=1f=1 means we can only take the second most beautiful trail

Now, we want to find the distance from every other state to (p,0)(p, 0). Finding the distances to (p,1)(p, 1) can be handled in a similar fashion.

We can use our graph traversal method of choice to traverse from (p,0)(p, 0) out to all of our other states. To handle this, we construct a reversed graph, and traverse out from (p,0)(p, 0) to other states. After calculating the distances, we know that the distance from any node ii to our state (p,0)(p, 0) is the distance from (i,0)(i, 0) to (p,0)(p, 0). We handle (p,1)(p, 1) similarly.

Alright, so now we know how to calculate the distance from every node to pp. How do we handle large values of kk?

Consider the fact that each state will directly map to another state, forming a successor graph. Thus, if we arrive at (p,0)(p, 0) or (p,1)(p, 1) at any point, one of the following must happen:

  • We arrive at pp, and end up in a cycle where pp is not present
  • We arrive at (p,f)(p, f), and cycle back to (p,f)(p, f)
  • We arrive at (p,f)(p, f), encounter (p,1f)(p, 1-f), and loop back to (p,f)(p, f)

Say our state (p,f)(p, f) falls under the second scenario, where it ends up in a cycle of length nn. Then, for a node ii to be able to reach (p,f)(p, f) after kk trails, the following must be true for some non-negative integer cc:

k=dist((p,f),(i,0))+cn.k = \text{dist}((p, f), (i, 0)) + c \cdot n.

Scenarios 1 and 3 can be handled in a similar fashion. For scenario 3, we have to store the time that we visit the state (p,1f)(p, 1 - f) in our cycle.

With this, we can solve each query in O(N)\mathcal{O}(N) by checking each node and seeing if it ends up at pp, using the three cases outlined above.

Implementation

Time Complexity: O(M+NQ)\mathcal{O}(M + NQ)

C++

#include "garden.h"
#include "gardenlib.h"
#include <bits/stdc++.h>
using ll = long long;
constexpr int INF = 1e9;
void count_routes(int n, int m, int p, int r[][2], int q, int g[]) {
std::vector<std::vector<std::array<int, 2>>> adj(n);

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!