Explanation
We can use the games to construct a directed graph. If wins against then we can construct an edge from to . Since the bounds of and are small, we can start a DFS from every vertex. If we reach that vertex again, then we can mark that vertex as “cyclic” and count said vertex in the result.
Implementation
time
C++
#include <iostream>#include <vector>using namespace std;const int MAX_N = 20;vector<vector<int>> adj(MAX_N);bool vis[MAX_N], cyclic[MAX_N];int original_node;
Python
n, m = map(int, input().split())adj = [[] for _ in range(n)]vis, cyclic = [False for _ in range(n)], [False for _ in range(n)]original_node = -1def dfs(node):if vis[node]:return
Java
import java.io.*;import java.util.*;public class Rank {static Map<Integer, HashSet<Integer>> graph = new HashMap<>();static int ans = 0;static Set<Integer> visited = new HashSet<>();static boolean cyclic = false;public static void main(String[] args) throws IOException {
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!