-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathl2b.cpp
105 lines (83 loc) · 1.95 KB
/
l2b.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
#include <cstdio>
#include <cstring>
#include <vector>
using namespace std;
#define rep(i, a, b) for (int i = (a); i <= (b); ++i)
#define pb push_back
const int MAX_N = 2100;
int n = 0;
int d[MAX_N];
int fa[MAX_N];
bool v[MAX_N];
vector<int> g_adj[MAX_N];
int read();
void write(int x);
void init();
int check_circle();
int main() {
int T = read();
while (T--) {
init();
write(check_circle());
putchar('\n');
}
return 0;
}
void init() {
rep(i, 1, n << 1) g_adj[i].clear();
n = read();
int m = read();
while (m--) {
int x = read(), y = read();
y += n;
g_adj[x].pb(y);
g_adj[y].pb(x);
}
}
int check_circle() {
int ans = MAX_N;
rep(i, 1, n) {
memset(v, false, sizeof v);
int q[MAX_N], front = 0, rear = 0;
q[++rear] = i;
d[i] = 0;
fa[i] = -1;
v[i] = true;
int p;
while (front != rear) {
p = q[++front];
for (int a: g_adj[p]) {
if (a != fa[p]) {
if (v[a]) {
int sum = d[p] + d[a] + 1;
if (sum < ans) {
if (sum == 4) return 4;
ans = sum;
}
} else {
d[a] = d[p] + 1;
fa[a] = p;
v[a] = true;
q[++rear] = a;
}
}
}
}
}
return ans == MAX_N ? -1 : ans;
}
int read() {
int s = 0, f = 1;
char ch = getchar();
while (ch < '0' || ch > '9') {
if (ch == '-') f = -f;
ch = getchar();
}
while (ch >= '0' && ch <= '9') s = (s << 1) + (s << 3) + (ch ^ '0'), ch = getchar();
return s * f;
}
void write(int x) {
if (x < 0) putchar('-'), x = -x;
if (x > 9) write(x / 10), putchar(x % 10 + '0');
else putchar(x + '0');
}