Problem:
Revenge of the Endless BFS
Mr. Endo wanted to write the code that performs breadth-first search (BFS), which is a search algorithm to explore all vertices on a
directed
graph. An example of pseudo code of BFS is as follows:
1: $current \leftarrow \{start\_vertex\}$
2: $visited \leftarrow current$
3: while $visited \ne$ the set of all the vertices
4:   $found \leftarrow \{\}$
5:   for $u$ in $current$
6:     for each $v$ such that there is an edge from $u$ to $v$
7:       $found \leftarrow found \cup \{v\}$
8:   $current \leftarrow found \setminus visited$
9:   $visited \leftarrow visited \cup found$
However, Mr. Endo apparently forgot to manage visited vertices in his code. More precisely, he wrote the following code:
1: $current \leftarrow \{start\_vertex\}$
2: while $current \ne$ the set of all the vertices
3:   $found \leftarrow \{\}$
4:   for $u$ in $current$
5:     for each $v$ such that there is an edge from $u$ to $v$
6:       $found \leftarrow found \cup \{v\}$
7:   $current \leftarrow found$
You may notice that for some graphs, Mr. Endo's program will not stop because it keeps running infinitely. Notice that it does not necessarily mean the program cannot explore all the vertices within finite steps. Your task here is to make a program that determines whether Mr. Endo's program will stop within finite steps for a given directed graph in order to point out the bug to him. Also, calculate the minimum number of loop iterations required for the program to stop if it is finite. Since the answer might be huge, thus print the answer modulo $10^9 +7$, which is a prime number.
Input
The input consists of a single test case formatted as follows.
$N$ $M$
$u_1$ $v_1$
:
$u_M$ $v_M$
The first line consists of two integers $N$ ($2 \leq N \leq 500$) and $M$ ($1 \leq M \leq 200,000$), where $N$ is the number of vertices and $M$ is the number of edges in a given directed graph, respectively. The $i$-th line of the following $M$ lines consists of two integers $u_i$ and $v_i$ ($1 \leq u_i, v_i \leq N$), which means there is an edge from $u_i$ to $v_i$ in the given graph. The vertex $1$ is the start vertex, i.e. $start\_vertex$ in the pseudo codes. You can assume that the given graph also meets the following conditions.
The graph has no self-loop, i.e., $u_i \ne v_i$ for all $1 \leq i \leq M$.
The graph has no multi-edge, i.e., $(u_i, v_i) \le (u_j, v_j)$ for all $1 \leq i < j \leq M$.
For each vertex $v$, there is at least one path from the start vertex $1$ to $v$.
Output
If Mr. Endo's wrong BFS code cannot stop within finite steps for the given input directed graph, print '-1' in a line. Otherwise, print the minimum number of loop iterations required to stop modulo $10^9+7$.
Sample Input 1
4 4
1 2
2 3
3 4
4 1
Output for Sample Input 1
-1
Sample Input 2
4 5
1 2
2 3
3 4
4 1
1 3
Output for Sample Input 2
7
Sample Input 3
5 13
4 2
2 4
1 2
5 4
5 1
2 1
5 3
4 3
1 5
4 5
2 3
5 2
1 3
Output for Sample Input 3
3

Submitted solutions:

code_snippet: #include<bits/stdc++.h>
using namespace std;
typedef long long ll;
ll in()
{
    ll re=0,f=1;char x=getchar();
    while(x<'0'||x>'9'){if(x=='-')f=-1;x=getchar();}
    while(x>='0'&&x<='9')re=re*10+x-48,x=getchar();
    return re*f;
}
void out(ll x)
{
    if(x<0)putchar('-'),x=-x;
    if(!x){putchar('0');return;}
    char z[21],ct=0;
    while(x){z[++ct]=x%10+48,x/=10;}
    while(ct){putchar(z[ct]);--ct;}
}
const int M=24;
int n,m;
bitset<501>st[M][501],tmp,tmp2;
int main()
{
    n=in();m=in();
    for(int x,y,i=1;i<=m;++i)
    {
        x=in();y=in();
        st[0][x][y]=1;
    }
    for(int i=1;i<M;++i)
    for(int j=1;j<=n;++j)
    {
        tmp.reset();
        for(int k=1;k<=n;++k)
        if(st[i-1][j][k])
        {
            tmp|=st[i-1][k];
        }
        st[i][j]=tmp;
    }
    if(st[M-1][1].count()<n)
    {
        puts("-1");
        return 0;
    }
    int ans=0,cur=0;
    for(int i=M-1;~i;--i)
    {
        if(st[i][1].count()<n)
        {
            ans=1<<i;
            tmp=st[i][1];
            cur=i;
            break;
        }
    }
    for(int ii=1;ii<=M;++ii)
    for(int i=cur;~i;--i)
    {
        tmp2.reset();
        for(int j=1;j<=n;++j)
        if(tmp[j])
        {
            tmp2|=st[i][j];
        }
        if(tmp2.count()<n)
        {
            tmp=tmp2;
            ans=ans+(1<<i);
            cur=i;
            break;
        }
    }
    ++ans;
    printf("%d\n",ans);
}
accuracy: 1
time_ms: 20
memory_kb: 4320
final_rank: 3

code_snippet: #include <bits/stdc++.h>
using namespace std;
#pragma GCC target("avx2")
#pragma GCC optimize("O3")
#pragma GCC optimize("unroll-loops")

long long N;
long long M, U[1 << 19], V[1 << 19];
bitset<509> edge[509];
bitset<509> dp1, dp2;
bitset<509> all_ok, all_clear;

int main() {
    // Step 1. Input
    cin >> N >> M;
    for (int i = 1; i <= M; i++) scanf("%lld%lld", &U[i], &V[i]);
    for (int i = 1; i <= M; i++) {
        U[i] -= 1; V[i] -= 1;
        edge[V[i]].set(U[i]);
    }
    for (int i = 0; i < N; i++) all_ok.set(i);
    dp1.set(0);

    // Step 2. Solve
    for (int loops = 0; loops < N * N; loops++) {
        if (loops % 2 == 0) {
            for (int i = 0; i < N; i++) {
                int val = ((edge[i] & dp1) == all_clear ? 0 : 1);
                if (val == 0) dp2.reset(i);
                else dp2.set(i);
            }
            if (dp2 == all_ok) { cout << loops + 1 << endl; return 0; }
        }
        else {
            for (int i = 0; i < N; i++) {
                int val = ((edge[i] & dp2) == all_clear ? 0 : 1);
                if (val == 0) dp1.reset(i);
                else dp1.set(i);
            }
            if (dp1 == all_ok) { cout << loops + 1 << endl; return 0; }
        }
    }

    // Step 3. Output
    cout << "-1" << endl;
    return 0;
}
accuracy: 1
time_ms: 400
memory_kb: 7068
final_rank: 8

code_snippet: #include <bits/stdc++.h>

using namespace std;

#define rep(i, a, b) for (int i = (int)(a); i < (int)(b); i++)
#define rrep(i, a, b) for (int i = (int)(b)-1; i >= (int)(a); i--)
#define ALL(v) (v).begin(), (v).end()
#define UNIQUE(v) sort(ALL(v)), (v).erase(unique(ALL(v)), (v).end())
#define SZ(v) (int)v.size()
#define MIN(v) *min_element(ALL(v))
#define MAX(v) *max_element(ALL(v))
#define LB(v, x) int(lower_bound(ALL(v), (x)) - (v).begin())
#define UB(v, x) int(upper_bound(ALL(v), (x)) - (v).begin())

using uint = unsigned int;
using ll = long long int;
using ull = unsigned long long;
using i128 = __int128_t;
using u128 = __uint128_t;
const int inf = 0x3fffffff;
const ll INF = 0x1fffffffffffffff;

template <typename T> inline bool chmax(T &a, T b) {
    if (a < b) {
        a = b;
        return 1;
    }
    return 0;
}
template <typename T> inline bool chmin(T &a, T b) {
    if (a > b) {
        a = b;
        return 1;
    }
    return 0;
}
template <typename T, typename U> T ceil(T x, U y) {
    assert(y != 0);
    if (y < 0)
        x = -x, y = -y;
    return (x > 0 ? (x + y - 1) / y : x / y);
}
template <typename T, typename U> T floor(T x, U y) {
    assert(y != 0);
    if (y < 0)
        x = -x, y = -y;
    return (x > 0 ? x / y : (x - y + 1) / y);
}
template <typename T> int popcnt(T x) {
    return __builtin_popcountll(x);
}
template <typename T> int topbit(T x) {
    return (x == 0 ? -1 : 63 - __builtin_clzll(x));
}
template <typename T> int lowbit(T x) {
    return (x == 0 ? -1 : __builtin_ctzll(x));
}

template <class T, class U>
ostream &operator<<(ostream &os, const pair<T, U> &p) {
    os << "P(" << p.first << ", " << p.second << ")";
    return os;
}
template <typename T> ostream &operator<<(ostream &os, const vector<T> &vec) {
    os << "{";
    for (int i = 0; i < vec.size(); i++) {
        os << vec[i] << (i + 1 == vec.size() ? "" : ", ");
    }
    os << "}";
    return os;
}
template <typename T, typename U>
ostream &operator<<(ostream &os, const map<T, U> &map_var) {
    os << "{";
    for (auto itr = map_var.begin(); itr != map_var.end(); itr++) {
        os << "(" << itr->first << ", " << itr->second << ")";
        itr++;
        if (itr != map_var.end())
            os << ", ";
        itr--;
    }
    os << "}";
    return os;
}
template <typename T> ostream &operator<<(ostream &os, const set<T> &set_var) {
    os << "{";
    for (auto itr = set_var.begin(); itr != set_var.end(); itr++) {
        os << *itr;
        ++itr;
        if (itr != set_var.end())
            os << ", ";
        itr--;
    }
    os << "}";
    return os;
}
#ifdef LOCAL
#define show(...) _show(0, #__VA_ARGS__, __VA_ARGS__)
#else
#define show(...) true
#endif
template <typename T> void _show(int i, T name) {
    cerr << '\n';
}
template <typename T1, typename T2, typename... T3>
void _show(int i, const T1 &a, const T2 &b, const T3 &...c) {
    for (; a[i] != ',' && a[i] != '\0'; i++)
        cerr << a[i];
    cerr << ":" << b << " ";
    _show(i + 1, a, c...);
}

/**
 * @brief template
 */

int main() {
    cin.tie(0);
    ios_base::sync_with_stdio(false);
    int N, M;
    cin >> N >> M;
    bitset<500> DB[20][500];
    rep(i,0,M) {
        int a, b;
        cin >> a >> b;
        a--, b--;
        DB[0][a][b] = true;
    }
    rep(i,0,19) {
        rep(j,0,500) rep(k,0,500) if (DB[i][j][k]) DB[i+1][j] |= DB[i][k];
    }
    bitset<500> Cur;
    Cur[0] = true;
    int ANS = 0;
    rrep(i,0,20) {
        bitset<500> Next;
        rep(j,0,500) if (Cur[j]) Next |= DB[i][j];
        if (Next.count() == N) continue;
        ANS += (1<<i);
        Cur = Next;
    }
    ANS++;
    cout << (ANS > N*N ? -1 : ANS) << '\n';
}
accuracy: 1
time_ms: 30
memory_kb: 4084
final_rank: 1

code_snippet: #include <bits/stdc++.h>
using namespace std;
using BI=bitset<503>;
BI G[503];

int main(){
    
    int N,M;cin>>N>>M;
    for(int i=0;i<M;i++){
        int a,b;cin>>a>>b;a--;b--;
        G[a][b]=true;
    }
    
    BI now;now[0]=true;
    for(int q=0;q<N*N;q++){
        if(now.count()==N){
            cout<<q<<endl;
            return 0;
        }
        BI nex;
        for(int i=0;i<N;i++) if(now[i]) nex|=G[i];
        now=nex;
    }
    cout<<-1<<endl;
}
accuracy: 1
time_ms: 440
memory_kb: 3456
final_rank: 5

code_snippet: // AOJ 2864 Revenge of the Endless BFS
// 2024.1.27

#include "bits/stdc++.h"
using namespace std;

#define gc() getchar_unlocked()

int in() {
    int n = 0, c = gc();
    do n = 10 * n + (c & 0xf), c = gc(); while (c >= '0');
    return n;
}

#define MAX 505
#define K 19
int  N, M;
bitset<MAX> to[K+5][MAX];

int main() {
    int i, j, k;

    N = in(), M = in();
    for (i = 0; i < M; ++i) {
        int u = in()-1, v = in()-1;
        to[0][u].set(v);
    }

    for (k = 0; k < K; ++k) {
        for (i = 0; i < N; ++i) {
            for (j = 0; j < N; ++j){
                if (to[k][i][j]) to[k+1][i] |= to[k][j];
            }
        }
    }

    bitset<MAX> b;
    b[0] = 1;
    int ans = 0;
    int ok = 0;
    for (k = K; k >= 0; --k) {
        bitset<MAX> b2;
        for (i = 0; i < N; ++i) if (b[i]) b2 |= to[k][i];
        if ((int)b2.count() < N) swap(b, b2), ans += 1 << k;
        else ok = 1;
    }
    printf("%d\n", ok? ans+1: -1);
    return 0;
}
accuracy: 1
time_ms: 20
memory_kb: 4188
final_rank: 2

code_snippet: // AOJ 2864 Revenge of the Endless BFS
// 2024.1.27

#include "bits/stdc++.h"
using namespace std;

#define gc() getchar_unlocked()

int in() {
    int n = 0, c = gc();
    do n = 10 * n + (c & 0xf), c = gc(); while (c >= '0');
    return n;
}

#define MAX 505
#define K 19
int  N, M;
bitset<MAX> to[MAX][K+5];

int main() {
    int i, j, k;
    N = in(), M = in();
    for (i = 0; i < M; ++i) {
        int u = in()-1, v = in()-1;
        to[0][u].set(v);
    }

    for (k = 0; k < K; ++k) {
        for (i = 0; i < N; ++i) {
            for (j = 0; j < N; ++j){
                if (to[k][i][j]) to[k+1][i] |= to[k][j];
            }
        }
    }

    bitset<MAX> b;
    b[0] = 1;
    int ans = 0;
    int ok = 0;
    for (k = K; k >= 0; --k) {
        bitset<MAX> b2;
        for (i = 0; i < N; ++i) if (b[i]) b2 |= to[k][i];

        if ((int)b2.count() < N) swap(b, b2), ans += 1 << k;
        else ok = 1;
    }
    printf("%d\n", ok? ans+1: -1);
    return 0;
}
accuracy: 0.42857142857142855
time_ms: 20
memory_kb: 3612
final_rank: 11

code_snippet: #include <vector>
#include <iostream>
using namespace std;

uint64_t G[512][8], cur[8], tar[8], nxt[8];

int main() {
	// step #1. read input
	cin.tie(0);
	ios_base::sync_with_stdio(false);
	int N, M;
	cin >> N >> M;
	vector<int> A(M), B(M);
	for (int i = 0; i < M; i++) {
		cin >> A[i] >> B[i];
		A[i] -= 1;
		B[i] -= 1;
	}
	
	// step #2. make adjacency list
	int L = (N + 63) / 64;
	for (int i = 0; i < N; i++) {
		for (int j = 0; j < L; j++) {
			G[i][j] = 0ULL;
		}
	}
	for (int i = 0; i < M; i++) {
		G[A[i]][B[i] >> 6] |= 1ULL << (B[i] & 63);
	}
	
	// step #3. simulation with bitset
	for (int i = 0; i < L; i++) {
		cur[i] = 0ULL;
		tar[i] = 0ULL;
	}
	for (int i = 0; i < N; i++) {
		tar[i >> 6] |= 1ULL << (i & 63);
	}
	cur[0] = 1ULL;
	int loops = 0;
	while (loops < N * N) {
		bool ok = true;
		for (int i = 0; i < L; i++) {
			if (cur[i] != tar[i]) {
				ok = false;
			}
		}
		if (ok) {
			break;
		}
		loops += 1;
		for (int i = 0; i < L; i++) {
			nxt[i] = 0ULL;
		}
		for (int i = 0; i < L; i++) {
			uint64_t bit = cur[i];
			while (bit != 0ULL) {
				int idx = __builtin_ctzll(bit);
				bit ^= (1ULL << idx);
				for (int j = 0; j < L; j++) {
					nxt[j] |= G[(i << 6) | idx][j];
				}
			}
		}
		for (int i = 0; i < L; i++) {
			cur[i] = nxt[i];
		}
	}
	
	// step #4. output
	cout << (loops != N * N ? loops : -1) << endl;
	
	return 0;
}
accuracy: 1
time_ms: 610
memory_kb: 4540
final_rank: 6

code_snippet: #include <vector>
#include <iostream>
using namespace std;

uint64_t G[512][8], cur[8], tar[8], nxt[8];

int main() {
	// step #1. read input
	cin.tie(0);
	ios_base::sync_with_stdio(false);
	int N, M;
	cin >> N >> M;
	vector<int> A(M), B(M);
	for (int i = 0; i < M; i++) {
		cin >> A[i] >> B[i];
		A[i] -= 1;
		B[i] -= 1;
	}
	
	// step #2. make adjacency list
	int L = (N + 63) / 64;
	for (int i = 0; i < N; i++) {
		for (int j = 0; j < L; j++) {
			G[i][j] = 0ULL;
		}
	}
	for (int i = 0; i < M; i++) {
		G[A[i]][B[i] / 64] |= 1ULL << (B[i] % 64);
	}
	
	// step #3. simulation with bitset
	for (int i = 0; i < L; i++) {
		cur[i] = 0ULL;
		tar[i] = 0ULL;
	}
	for (int i = 0; i < N; i++) {
		tar[i / 64] |= 1ULL << (i % 64);
	}
	cur[0] = 1ULL;
	int loops = 0;
	while (loops < N * N) {
		bool ok = true;
		for (int i = 0; i < L; i++) {
			if (cur[i] != tar[i]) {
				ok = false;
			}
		}
		if (ok) {
			break;
		}
		loops += 1;
		for (int i = 0; i < L; i++) {
			nxt[i] = 0ULL;
		}
		for (int i = 0; i < L; i++) {
			uint64_t bit = cur[i];
			while (bit != 0ULL) {
				int idx = __builtin_ctzll(bit);
				bit ^= (1ULL << idx);
				for (int j = 0; j < L; j++) {
					nxt[j] |= G[idx][j];
				}
			}
		}
		for (int i = 0; i < L; i++) {
			cur[i] = nxt[i];
		}
	}
	
	// step #4. output
	cout << (loops != N * N ? loops : -1) << endl;
	
	return 0;
}
accuracy: 0.21428571428571427
time_ms: 20
memory_kb: 3440
final_rank: 12

code_snippet: #include<bits/stdc++.h>
typedef long long int ll;
typedef unsigned long long int ull;
#define BIG_NUM 2000000000
#define HUGE_NUM 99999999999999999
#define MOD 1000000007
#define EPS 0.000000001
using namespace std;



#define SIZE 505

int V,E;
int root = 0;
int POW[20],pow_max = 0;
bool can_visit[20][SIZE][SIZE],check[2][SIZE];


bool isOK(int count){

	int CURRENT = 0,NEXT = 1;
	for(int i = 0; i < V; i++){
		check[CURRENT][i] = false;
		check[NEXT][i] = false;
	}

	bool FLG;

	check[CURRENT][root] = true;

	for(int i = pow_max; i >= 0; i--){
		if(POW[i] > count)continue;
		count -= POW[i];

		for(int k = 0; k < V; k++){
			if(!check[CURRENT][k])continue;


			for(int p = 0; p < V; p++){
				if(can_visit[i][k][p]){

					check[NEXT][p] = true;
				}
			}
		}

		FLG = true;
		for(int k = 0; k < V; k++){
			if(!check[NEXT][k]){
				FLG = false;
				break;
			}
		}

		if(FLG)return true;

		swap(CURRENT,NEXT);
		for(int k = 0; k < V; k++){

			check[NEXT][k] = false;
		}
	}

	return false;
}


int main(){

	scanf("%d %d",&V,&E);

	POW[0] = 1;
	for(int i = 1; i <= 19; i++){

		POW[i] = POW[i-1]*2;
	}

	for(int i = 0; i <= 19; i++){
		if(POW[i] > V*V+(V+5)){
			pow_max = i;
			break;
		}
	}

	for(int i = 0; i <= pow_max; i++){
		for(int from = 0; from < V; from++){
			for(int to = 0; to < V; to++){

				can_visit[i][from][to] = false;
			}
		}
	}

	int from,to;
	for(int loop = 0; loop < E; loop++){

		scanf("%d %d",&from,&to);
		from--;
		to--;
		can_visit[0][from][to] = true;
	}

	for(int i = 1; i <= pow_max; i++){
		for(int a = 0; a < V; a++){
			for(int b = 0; b < V; b++){
				if(!can_visit[i-1][a][b])continue;
				for(int c = 0; c < V; c++){
					if(!can_visit[i-1][b][c])continue;
					can_visit[i][a][c] = true;
				}
			}
		}
	}

	int left = 0,right = V*V+V+5,mid = (left+right)/2;
	int ans = BIG_NUM;

	while(left <= right){

		if(isOK(mid)){

			ans = mid;
			right = mid-1;
		}else{

			left = mid+1;
		}
		mid = (left+right)/2;
	}

	if(ans == BIG_NUM){

		printf("-1\n");
	}else{

		printf("%d\n",ans);
	}

	return 0;
}
accuracy: 1
time_ms: 1270
memory_kb: 7908
final_rank: 9

code_snippet: #include <algorithm>
#include <iostream>
#include <climits>
#include <cstdio>
#include <queue>

using namespace std;

typedef unsigned int uint;

const int INF = INT_MAX >> 1;
const int N = 505;
const int W = 32;
const int B = N / W + 2;
const int M = 200005;

typedef pair<int , int> data;

#define mkp(a , b) make_pair(a , b)
#define ft first
#define sd second

queue<data> q;

uint done[N][B] , graph[N][B];
int tov[M] , nxt[M];
bool vis[N];
int f[N][N];
int last[N];
int n , m , tot , cirlen , ans;

inline void set(uint *bits , int x){bits[x / W] |= 1 << x % W;}

inline void insert(int x , int y){tov[++ tot] = y , nxt[tot] = last[x] , last[x] = tot;}

int dfs(int x , int dep = 0)
{
	vis[x] = 1;
	for (int i = last[x] , y , ret;i;i = nxt[i])
	{
		if ((y = tov[i]) == 1) return dep + 1;
		if (!vis[y])
		{
			ret = dfs(y , dep + 1);
			if (ret) return ret;
		}
	}
	return 0;
}

void bfs()
{
	ans = INF;
	if (!cirlen) return;
	for (int i = 0;i < cirlen;++ i)
		for (int x = 1;x <= n;++ x)
			f[i][x] = INF;
	f[0][1] = 0 , q.push(mkp(0 , 1)) , set(done[0] , 0);
	for (data cur;!q.empty();)
	{
		cur = q.front() , q.pop();
		for (int i = 0 , nxti = cur.ft == cirlen - 1 ? 0 : cur.ft + 1;i <= (n - 1) / W;++ i)
		{
			uint state = ~done[nxti][i] & graph[cur.sd][i];
			if (state)
				for (int j = 0 , y = i * W + 1;j < W;++ j , ++ y)
					if ((state >> j) & 1)
					{
						f[nxti][y] = f[cur.ft][cur.sd] + 1;
						q.push(mkp(nxti , y)) , set(done[nxti], y - 1);
					}
		}
	}
	for (int i = 0 , ret;i < cirlen;++ i)
	{
		ret = 0;
		for (int x = 1;x <= n;++ x) ret = max(ret , f[i][x]);
		ans = min(ans , ret);
	}
}

int main()
{
	//freopen("f.in" , "r" , stdin) , freopen("f.out" , "w" , stdout);
	scanf("%d%d" , &n , &m);
	for (int i = 1 , x , y;i <= m;++ i) scanf("%d%d" , &x , &y) , insert(x , y) , set(graph[x] , y - 1);
	cirlen = dfs(1) , bfs() , printf("%d\n" , ans == INF ? -1 : ans);
	//fclose(stdin) , fclose(stdout);
	return 0;
}
accuracy: 1
time_ms: 20
memory_kb: 4876
final_rank: 4

code_snippet: #include <bits/stdc++.h>
#define ll long long
#define INF 1000000005
#define MOD 1000000007
#define EPS 1e-10
#define rep(i,n) for(int i=0;i<(int)(n);++i)
#define rrep(i,n) for(int i=(int)(n)-1;i>=0;--i)
#define srep(i,s,t) for(int i=(int)(s);i<(int)(t);++i)
#define each(a,b) for(auto& (a): (b))
#define len(v) (int)(v).size()
#define zip(v) sort(all(v)),v.erase(unique(all(v)),v.end())
#define cmx(x,y) x=max(x,y)
#define cmn(x,y) x=min(x,y)
#define fi first
#define se second
#define pb push_back
#define show(x) cout<<#x<<" = "<<(x)<<endl
#define spair(p) cout<<#p<<": "<<p.fi<<" "<<p.se<<endl
#define sar(a,n) cout<<#a<<":";rep(pachico,n)cout<<" "<<a[pachico];cout<<endl
#define svec(v) cout<<#v<<":";rep(pachico,v.size())cout<<" "<<v[pachico];cout<<endl
#define svecp(v) cout<<#v<<":";each(pachico,v)cout<<" {"<<pachico.first<<":"<<pachico.second<<"}";cout<<endl
#define sset(s) cout<<#s<<":";each(pachico,s)cout<<" "<<pachico;cout<<endl
#define smap(m) cout<<#m<<":";each(pachico,m)cout<<" {"<<pachico.first<<":"<<pachico.second<<"}";cout<<endl

using namespace std;

typedef pair<int,int> P;
typedef pair<ll,ll> pll;
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef vector<ll> vl;
typedef vector<vl> vvl;
typedef vector<double> vd;
typedef vector<P> vp;
typedef vector<string> vs;

const int MAX_N = 500;

int n,m;

struct mat
{
    bitset<MAX_N> a[MAX_N];
};

mat operator*(const mat& m1,const mat& m2){
    mat ans;
    rep(i,MAX_N){
        rep(j,MAX_N){
            if(m1.a[i][j] == 0) continue;
            ans.a[i] |= m2.a[j];
        }
    }
    return ans;
}

bool possible(mat m, ll cnt)
{
    mat res;
    rep(i,n){
        res.a[i].set(i);
    }
    while(cnt){
        if(cnt & 1){
            res = res*m;
        }
        cnt >>= 1;
        m = m*m;
    }
    return ((int)res.a[0].count() == n);
}

int main()
{
    cin.tie(0);
    ios::sync_with_stdio(false);
    cin >> n >> m;
    mat A;
    rep(i,m){
        int x,y;
        cin >> x >> y;
        A.a[x-1].set(y-1);
    }
    ll l = 0, r = 50000000000LL;
    if(!possible(A,r)){
        cout << "-1\n";
        return 0;
    }
    while(r-l>1){
        ll mid = (l+r)/2;
        if(possible(A,mid)){
            r = mid;
        }else{
            l = mid;
        }
    }
    cout << r%MOD << "\n";
    return 0;
}
accuracy: 1
time_ms: 1160
memory_kb: 3364
final_rank: 7

code_snippet: #include<bits/stdc++.h>
#define MOD 1000000007LL
using namespace std;

typedef long long ll;
typedef pair<int,int> P;

int n,m;
vector<int> G[501];
bool path[21][501][501];
bool now[505];
bool tmp[505];

bool C(int v){
	memset(now,false,sizeof(now));
	now[0]=true;
	for(int i=0;i<20;i++){
		if((v>>i) & 1){
			memset(tmp,false,sizeof(tmp));
			for(int j=0;j<n;j++){
				if(now[j]){
					for(int k=0;k<n;k++){
						if(path[i][j][k]){
							tmp[k]=true;
						}
					}
				}
			}
			for(int j=0;j<n;j++){
				now[j]=tmp[j];
			}
		}
	}
	for(int i=0;i<n;i++){
		if(!now[i])return false;
	}
	return true;
}

int main(void){
	scanf("%d%d",&n,&m);
	memset(path,false,sizeof(path));
	for(int i=0;i<m;i++){
		int u,v;
		scanf("%d%d",&u,&v);
		u--;
		v--;
		path[0][u][v]=true;
	}
	for(int i=0;i<20;i++){
		for(int j=0;j<n;j++){
			for(int k=0;k<n;k++){
				if(path[i][j][k]){
					for(int l=0;l<n;l++){
						if(path[i][k][l]){
							path[i+1][j][l]=true;
						}
					}
				}
			}
		}
	}
	int l=0,r=1000000;
	while(l+1<r){
		int mid=(l+r)/2;
		if(C(mid))r=mid;
		else l=mid;
	}
	if(r==1000000){
		printf("-1\n");
	}else{
		printf("%d\n",r);
	}
	return 0;
}
accuracy: 1
time_ms: 1410
memory_kb: 8368
final_rank: 10