I was trying to solve this problem https://mirror.codeforces.com/contest/1472/problem/G, and i built a graph which basically adds a directed edge between two nodes u and v if and only if d[u] >d[v], you can consider that d[i] is a value associated with node i( it is actually the distance to node 1 in the input graph),so now it can easily be seen that the graph has no cycles and there cannot be two edges between any two nodes, so it is a tree and also during the dfs if u go down from the parent to child you cannot come back because in that were the case we would have two edges between two nodes which is obviously a contradiction, however when i submit this 313150168 , it gave me a TLE , so i figured it was infinite loop and when i added a visited array to keep count if a node has been visited before it works 313151392, can someone please help me figure out why doesn't the first one work and why do i need to keep track of visited nodes even if the graph is acyclic.








I guess the problem is that even though the graph is acyclic, dfs in the first version can still be not linear. Consider this case: 1 -> 2 -> 3 -> ... and 1 -> 4 -> 3 -> ...
dfs will first go through path 1->2->3 and explore all the graph from there, then through path 1->4->3 and explore all the graph again. which means if you have a lot of edges you can visit the same vertex quite a lot, leading to TL. in a sense having a cycle like in this example becomes a problem, even if its not a cycle considering orientation on edges
i see so the cause of the TLE isn't an infinite loop but rather visiting some edges many times thanks a lot
Wow, what an incredible achievement! Is this for real? Congratulations Milashka