SPOJ Problem: GHOSTS

I am trying to solve this problem GHOSTS.
if question is not clear to you then “all edges are directed from a to b, and we have to build edges according to the order they appear in input. If the current edge does not form a cycle with edges already built, we build this edge; otherwise, we report the current edge and ignore it.”
What I am doing is checking DAG (directed acyclic graph) at every step but this approach (My solution) is not enough for given time limit. How can I optimize?