forked from AllAlgorithms/cpp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgrith.cpp
More file actions
64 lines (56 loc) · 886 Bytes
/
grith.cpp
File metadata and controls
64 lines (56 loc) · 886 Bytes
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
#include<bits/stdc++.h>
using namespace std;
typedef vector<int> vi;
typedef pair<int,int> pi;
#define int long long
#define F first
#define S second
#define PB push_back
#define MP make_pair
#define REP(i, a, b) for(int i =a;i < b; i++)
const int MX = 2e5 + 3;
vi adj[MX];
int mark[MX],dis[MX], ans;
void DFS(int u, int par, int k);
int32_t main()
{
ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
int n, m;
int u, v;
cin>>n>>m;
ans = m + 1;
REP(i, 0, m)
{
cin>>u>>v;
adj[v].PB(u);
adj[u].PB(v);
}
REP(i, 1, n+1)
{
dis[i]=0;
DFS(i, -1, mark[i]);
}
if(ans == m+1) cout<<-1;
else cout<<ans;
return 0;
}
void DFS(int u, int par, int k)
{
mark[u] ++;
if(u == par)
{
ans = min(ans, (int)1);
}
for(auto v: adj[u])
{
if(mark[v] == k)
{
dis[v] = dis[u]+1;
DFS(v, u, k);
}
else if(v != par)
{
ans = min(ans, dis[u]+dis[v]+1);
}
}
}