Problem:
Cycle Detection for a Directed Graph

Find a cycle in a directed graph G(V, E).

Input

A directed graph G is given in the following format:

|V| |E|
s0 t0
s1 t1
:
s|E|-1 t|E|-1

|V| is the number of nodes and |E| is the number of edges in the graph. The graph nodes are named with the numbers 0, 1,..., |V|-1 respectively.

si and ti represent source and target nodes of i-th edge (directed).

Output

Print 1 if G has cycle(s), 0 otherwise.

Constraints

1 ≤ |V| ≤ 100

0 ≤ |E| ≤ 1,000

si ≠ ti

Sample Input 1

3 3
0 1
0 2
1 2

Sample Output 1

0

Sample Input 2

3 3
0 1
1 2
2 0

Sample Output 2

1

Solution in C++14 (judge verdict: Time Limit Exceeded)

#include <iostream>
#include <vector>
#include <stack>

#define FOR(i,n) for(int i=0;i<n;i++)
#define FORI(i,z,n) for(int i=z;i<n;i++)

using namespace std;

vector<vector<int> > graph;
vector<bool> seen;
vector<bool> localSeen;

bool hasLoop(int i) {
    stack<pair<int, bool> > Q;
    Q.push(make_pair(i, true));
    while (! Q.empty()) {
        auto x = Q.top();
        Q.pop();
        int u = x.first;
        bool goingDown = x.second;

        if (goingDown) {
            Q.push(make_pair(u, false));
            seen[u] = true;
            localSeen[u] = true;
            for(int v: graph[u])
                if (localSeen[v])
                    return true;
                else
                    Q.push(make_pair(v, true));
        } else {
            localSeen[u] = false;
        }

    }
    return false;
}

int main () {
    int V, E;
    cin >> V >> E;

    graph.resize(V);
    seen.resize(V, false);
    localSeen.resize(V, false);

    FOR(i, E) {
        int f, t;
        cin >> f >> t;
        graph[f].push_back(t);
    }

    FOR(i, V)
        if (! seen[i])
            if (hasLoop(i)) {
                cout << 1 << endl;
                return 0;
            }

    cout << 0 << endl;
}