CSES - Planets Cycles
Authors: Maggie Liu (C++), Qi Wang (Java), George Pong
Define the number of teleportations starting from a planet as the of that planet. For each planet that hasn't been visited, we want to find its . Call the planet we are performing from the . As we perform from the , keep track of the planets seen, in order, in the queue and keep track of , the length of the path (which is also the of the ). When we reach a planet that has already been visited (call this planet the ), add the of the to the current count because we would continue to visit all of the planets that would go on to visit.
Once we have and we can calculate the of all the planets in this . We know the will always be the planet at the end of the , but it may appear elsewhere as well. We can break this down into two cases:
- The was visited twice in the current . The planets in the between the two occurrences of the form a .
- The only appears at the end of the current . All of the planets in the are not part of a .
For planets inside a , the repeating planet when starting from that planet is itself. For all the planets in the but outside the , the planet that repeats when starting from each planet will still be the .
Since the planets outside the all have paths ending at the , each one's is less than the previous'. So, as we iterate through the planets along the that are outside the , the will decrease by each time, starting from the with a of . Once we get to the , the of the planets will all be equal to the of the , which is the length of the .
C++
Implementation
#include <iostream>#include <queue>using namespace std;void dfs(int planet);bool visited[200000]{};int destinations[200000];int pathlength[200000]{};queue<int> path;int steps = 0;
Java
Implementation
import java.io.*;import java.util.*;public class PlanetCycles {static int N, steps;static int[] destinations, pathlength;static boolean[] visited;static LinkedList<Integer> path = new LinkedList<>();public static void main(String[] args) {Kattio io = new Kattio();
Python
n = int(input())planets = list(map(lambda i: int(i) - 1, input().split()))path_length = [0] * nvisited = [False] * nfor i in range(len(planets)):"""We dfs from the current planet until we end up at a planet we have alreadyvisited. Note that the visited planet is not added to the path array.
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!