CSES - Game Routes

Author: Andrew Wang

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

This problem is very similar to the "Longest Flight Route" problem discussed earlier in this module. Let dp[v]dp[v] denote the number of paths reaching vv. We can see,

dp[v]=edge uv existsdp[u],dp[v]= \sum_{\text{edge } u\to v \text{ exists}}dp[u],

with an exception of dp[1]dp[1], or the starting node, having a value of 1. We process the nodes topologically so dp[u]dp[u] will already have been computed before dp[v]dp[v].

#include <iostream>
#include <vector>
#include <queue>
using namespace std;
int n;
vector<int> edge[100001];
vector<int> backedge[100001];
int main(){
ios_base::sync_with_stdio(0); cin.tie(0);

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!