You are given an undirected graph consisting of $n$ vertices and $m$ edges. Your task is to find the number of connected components which are cycles.

Here are some definitions of graph theory.

An undirected graph consists of two sets: set of nodes (called vertices) and set of edges. Each edge connects a pair of vertices. All edges are bidirectional (i.e. if a vertex $a$ is connected with a vertex $b$, a vertex $b$ is also connected with a vertex $a$). An edge can't connect vertex with itself, there is at most one edge between a pair of vertices.

Two vertices $u$ and $v$ belong to the same connected component if and only if there is at least one path along edges connecting $u$ and $v$.

A connected component is a cycle if and only if its vertices can be reordered in such a way that:  the first vertex is connected with the second vertex by an edge,  the second vertex is connected with the third vertex by an edge,  ...  the last vertex is connected with the first vertex by an edge,  all the described edges of a cycle are distinct. 

A cycle doesn't contain any other edges except described above. By definition any cycle contains three or more vertices. [Image] There are $6$ connected components, $2$ of them are cycles: $[7, 10, 16]$ and $[5, 11, 9, 15]$. 


-----Input-----

The first line contains two integer numbers $n$ and $m$ ($1 \le n \le 2 \cdot 10^5$, $0 \le m \le 2 \cdot 10^5$) — number of vertices and edges.

The following $m$ lines contains edges: edge $i$ is given as a pair of vertices $v_i$, $u_i$ ($1 \le v_i, u_i \le n$, $u_i \ne v_i$). There is no multiple edges in the given graph, i.e. for each pair ($v_i, u_i$) there no other pairs ($v_i, u_i$) and ($u_i, v_i$) in the list of edges.


-----Output-----

Print one integer — the number of connected components which are also cycles.


-----Examples-----
Input
5 4
1 2
3 4
5 4
3 5

Output
1

Input
17 15
1 8
1 12
5 11
11 9
9 15
15 5
4 13
3 13
4 3
10 16
7 10
16 7
14 3
14 4
17 6

Output
2



-----Note-----

In the first example only component $[3, 4, 5]$ is also a cycle.

The illustration above corresponds to the second example.

Difficulty: introductory

Starter code:

Solutions:
def connected_components(neighbors):
    seen = set()
    def component(node):
        nodes = set([node])
        while nodes:
            node = nodes.pop()
            seen.add(node)
            nodes |= neighbors[node] - seen
            yield node
    for node in neighbors:
        if node not in seen:
            yield component(node)
from collections import defaultdict
graph = defaultdict(set)
n,m = map(int,input().split())
for _ in range(m):
    u,v = map(int,input().split())
    graph[u].add(v)
    graph[v].add(u)

total = 0
for component in connected_components(graph):
    nodes = list(component)
    size = len(nodes)
    seen = set()
    current = nodes[0]
    while len(seen) < size:
        choice = list(graph[current])
        if len(choice) != 2:break
        seen.add(current)
        possible = [c for c in choice if c not in seen]
        if not possible: break
        current = possible[0]
    if len(seen) == size:
        total+=1
print (total)

from collections import deque

n, m = list(map(int, input().split()))
deg = [0] * (n + 1)
G = [[] for _ in range(n + 1)]
for _ in range(m):
    u, v = list(map(int, input().split()))
    deg[u] += 1
    deg[v] += 1
    G[u].append(v)
    G[v].append(u)

C = [0] * (n + 1)
def dfs(v, cc):
    ok = True
    q = [v]
    C[v] = cc
    sz = 1
    while q:
        v = q.pop()
        if len(G[v]) != 2:
            ok = False
        for w in G[v]:
            if C[w] == 0:
                C[w] = cc
                sz += 1
                q.append(w)
    return sz, ok


cc = 0
cycles = 0
for v in range(1, n + 1):
    if C[v] == 0:
        cc += 1
        sz, ok = dfs(v, cc)
        if ok and sz > 2:
            cycles += 1

print(cycles)

# print(C)


T = input().split(' ')
n = int(T[0])
m = int(T[1])
B = [0] * (n+1)
S1 = [0] * (n+1)
S2 = [0] * (n+1)
for i in range(m):
    S = input().split(' ')
    a = int(S[0])
    b = int(S[1])
    if S1[a]==0:
        S1[a] = b
    elif S2[a]==0:
        S2[a] = b
    else:
        B[a] = 1
        B[b] = 1
    if S1[b]==0:
        S1[b] = a
    elif S2[b]==0:
        S2[b] = a
    else:
        B[a] = 1
        B[b] = 1
for i in range(1, n+1):
    if S1[i] == 0 or S2[i] == 0:
        B[i] = 1
sol = 0
for ind in range(1, n+1):
    if B[ind] == 0:
        v = ind
        w = S2[ind]
        c = True
        while w!=ind:
            B[v] = 1
            if B[w] == 0:
                u = w
                if S1[w]==v:
                    w = S2[w]
                else:
                    w = S1[w]
            else:
                B[ind] = 0
                c = False
                break
            v = u
        if c:
            B[v] = 1
            sol+=1
print(sol)
        


import collections;
n, m = map(int, input().split());
rs=[];
for i in range(m):
    u, v = map(int, input().split());
    rs.append((u-1, v-1));
d = dict();
for v in range(n):
    d[v]=set();
for r in rs:
    u=r[0];
    v=r[1];
    setU=d.get(u, set());
    setV=d.get(v, set());
    setU.add(v);
    setV.add(u);
    d[u]=setU;
    d[v]=setV;
seen=[False]*n;
result=0;
for v in range(n):
    if seen[v]:
        continue;
    good=True;
    deq=collections.deque([v]);
    while len(deq)>0:
        currV=deq.pop();
        seen[currV]=True;
        if len(d[currV])!=2:
            good=False;
        for u in d[currV]:
            if seen[u]:
                continue;
            seen[u]=True;
            deq.append(u);
    if good:
        result+=1;
print(result);

n,m = [int(s) for s in input().split()]
g = [[] for x in range(n)]
for i in range(m):
    a,b = [int(s) for s in input().split()]
    g[a-1].append(b-1)
    g[b-1].append(a-1)
seen = [False for x in range(n)]
q = []
ans = 0
for i in range(len(g)):
    if not seen[i]:
        q.append(i)
        seen[i] = True
    is_cycle = True
    first = i
    cycle_len = 0
    while len(q) > 0:
        v = q.pop()
        cycle_len += 1
        if len(g[v]) != 2:
            is_cycle = False
        if len(g[v]) == 2 and (g[v][0] == first or g[v][1] == first) and cycle_len > 2 and is_cycle:
            ans += 1
            break
        for vv in g[v]:
            if not seen[vv]:
                q.append(vv)
                seen[vv] = True

print(ans)



n,m=map(int,input().split())
friend=[[] for i in range(n)]
for i in range(m):
    u,v=map(int,input().split())
    friend[u-1].append(v-1)
    friend[v-1].append(u-1)
step=[len(friend[i]) for i in range(n)]
s=set()
ans=0
ass=s.add
for i in range(n):
    if i in s:
        continue
    #print()
    Q=i
    k=1
    ass(Q)
    while True:
        #print(Q,s,i)
        if step[Q]!=2:
            ass(Q)
            break
        elif friend[Q][0] not in s:
            Q=friend[Q][0]
            ass(Q)
            k += 1
        elif friend[Q][1] not in s:
            Q=friend[Q][1]
            ass(Q)
            k += 1
        elif friend[Q][0]==i or friend[Q][1]==i:
            if k>2:
                ans+=1

            break
        else:
            ass(Q)
            break

print(ans)

v,e = list(map(int, input().strip().split()))

edges = [[] for _ in range(v)]
for i in range(e):
	x,y = input().strip().split()
	x = int(x) - 1
	y = int(y) - 1
	edges[x].append(y)
	edges[y].append(x)


degreeTwo = [i for i in range(v) if len(edges[i]) == 2]

components = [-1] * v
numComp = 0

ans = 0

for x in degreeTwo:
	if components[x] == -1:
		flag = True
		queue = [x]
		while queue:
			curr = queue.pop(0)
			flag = flag and len(edges[curr]) == 2
			components[curr] = numComp
			for neigh in edges[curr]:
				if components[neigh] == -1:
					queue.append(neigh)
					components[neigh] = numComp
		numComp += 1
		ans += int(flag)

print(ans)

# components = [-1] * v

# numComp = 0

# for i in range(v):
# 	if components[i] == -1:
# 		queue = [i]
# 		while queue:
# 			curr = queue.pop(0)
# 			components[curr] = numComp
# 			for neigh in edges[curr]:
# 				if components[neigh] == -1:
# 					queue.append(neigh)
# 		numComp += 1

# c = [[] for _ in range(numComp)]

# for i in range(numComp):
# 	for j in range(v):
# 		if components[j] == i:
# 			c[i].append(j)

# ans = 0
# for comp in c:
# 	if len(comp) >= 3:
# 		flag = True
# 		for vertex in comp:
# 			if len(edges[vertex]) != 2:
# 				flag = False
# 				break
# 		if flag:
# 			ans += 1

# print(ans)
	


import sys
#sys.stdin = open("e.txt")
input = sys.stdin.readline
N,M = map(int,input().split())
G = {}
for _ in range(M):
	a,b = map(int,input().split())
	if a not in G:
		G[a] = set()
	if b not in G:
		G[b] = set()
	G[a].add(b)
	G[b].add(a)

seen = set()
def dfs(graph, start):
	visited = set()
	stack = [start]
	while stack:
		node = stack.pop()
		if node not in visited:
			visited.add(node)
			stack.extend(graph[node])
	return visited

def dfs_paths(graph, start, goal):
	stack = [(start, [start])]
	while stack:
		(node, path) = stack.pop()
		for next in graph[node] - set(path):
			if next == goal:
				yield path + [next]
			else:
				stack.append((next, path + [next]))

CC = []
for x in G:
	if x not in seen:
		P = dfs(G,x)
		seen |= P
		CC.append((list(P)[0],P))
cnt = 0
for x in CC:
	if x[0] in x[1] and all([len(G[y]) == 2 for y in x[1]]):
		cnt += 1
print(cnt)

import sys
sys.setrecursionlimit(10 ** 9)  
import threading
threading.stack_size(67108864)
def main():
    n, m = [int(x) for x in input().split()]

    graph = []

    for i in range(n):
        graph.append([])

    deg = [0] * n

    for i in range(m):
        a, b = [int(x) - 1 for x in input().split()]
        deg[a] += 1
        deg[b] += 1
        graph[a].append(b)
        graph[b].append(a)

    used = [0] * n

    # print()
    def dfs(v):
        is_cir = 1
        if deg[v] != 2:
            is_cir = 0
        for child in graph[v]:
            if not used[child]:
                used[child] = 1
                is_cir = min(dfs(child), is_cir)
        return is_cir


    head = 0
    count = 0
    while 1:
        #print(used, head)
        used[head] = 1
        is_cir = dfs(head)
        count += is_cir
        f = 0
        for i in range(head, n):
            if not used[i]:
                head = i
                f = 1
                break
                
        if not f:
            print(count)
            return



thread = threading.Thread(target=main)
thread.start()
thread.join()

n,m = map(int, input().split())
G = [0]*n
parent = list(range(n))

def FindAncester(i):
    if i == parent[i]:
        pass
    else:
        parent[i] = FindAncester(parent[i])
    return parent[i]
def MergeTwo(i,j):
    A = FindAncester(i)
    B = FindAncester(j)
    parent[B] = parent[A]

for i in range(m):
    a,b = map(int, input().split())
    a,b = a-1,b-1
    if a>b:
        a,b = b,a
    G[a]+=1
    G[b]+=1
    MergeTwo(a,b)

R = {}
count = 0
for i in range(n):
    a = FindAncester(i)
    if a in R:
        R[a].append(i)
    else:
        R[a] = [i]
#print(parent)
#print(G)
for i in R:
    if len(R[i])>2:
        x = 1
        for j in R[i]:
            if G[j]!=2:
                x = 0
                break
        if x == 1:
            count+=1
print(count)

#!/usr/bin/env python3

[n, m] = list(map(int, input().strip().split()))
bis = [tuple(map(int, input().strip().split())) for _ in range(m)]

tos = [[] for _ in range(n)]
for u, v in bis:
	tos[u - 1].append(v - 1)
	tos[v - 1].append(u - 1)

cands = set(i for i in range(n) if len(tos[i]) == 2)
res = 0
while cands:
	v = cands.pop()
	R, L = tos[v]
	while L in cands:
		cands.remove(L)
		V1, V2 = tos[L]
		if V1 in cands:
			L = V1
		elif V2 in cands:
			L = V2
		else:
			break
		if L == R:
			res += 1

print (res)


def bfs(a,i,visited,connected):
	visited[i] = True
	q = list(a[i])
	j = 0
	while (j < len(q)):
		cur = q[j]
		if (not visited[cur]):
			connected.append(cur)
			visited[cur] = True
			for k in range(len(a[cur])):
				q.append(a[cur][k])
		j += 1


	return connected



def check(connected,a,n):
	if (len(connected) < 3):
		return False
	for i in range(1,len(connected)):
		node = connected[i]
		if (len(a[node]) != 2):
			return False
	return True

n, m = map(int, input().split())

a = []
visited = []

for i in range(n):
	a.append([])
	visited.append(False)

for i in range(m):
	u, v = map(int, input().split())
	a[u-1].append(v-1)
	a[v-1].append(u-1)

res = 0

for i in range(n):
	if (not visited[i]):
		connected = bfs(a,i,visited,[i])
		if (check(connected,a,n)):
			res += 1

print(res)

[n, m] = map(int, input().strip().split())
bis = [tuple(map(int, input().strip().split())) for _ in range(m)]

tos = [[] for _ in range(n)]
for u, v in bis:
	tos[u - 1].append(v - 1)
	tos[v - 1].append(u - 1)

cands = set(i for i in range(n) if len(tos[i]) == 2)
res = 0
while cands:
	v = cands.pop()
	R, L = tos[v]
	while L in cands:
		cands.remove(L)
		V1, V2 = tos[L]
		if V1 in cands:
			L = V1
		elif V2 in cands:
			L = V2
		else:
			break
		if L == R:
			res += 1

print (res)

# coding=utf-8

n, m = list(map(int, input().split()))
a = [[] for _ in range(n+1)]
for i in range(m):
    a1, a2 = list(map(int, input().split()))
    a[a2].append(a1)
    a[a1].append(a2)
ans, f, flag = 0, [0]*(n+1), 1

def dfs(x):
    f[x] = 1
    mid = []
    mid.append(x)
    while mid:
        v = mid.pop()
        if len(a[v]) != 2: nonlocal flag;flag = 0
        for i in a[v]:
            if not f[i]: f[i] = 1;mid.append(i)

for i in range(1, n+1):
    if not f[i]:
        flag = 1
        dfs(i)
        ans += flag
print(ans)



from collections import defaultdict

V, E = input().split()
V, E = int(V), int(E)
G = defaultdict(set)
for _ in range(E):
    v1, v2 = input().split()
    v1, v2 = int(v1), int(v2)
    G[v1].add(v2)
    G[v2].add(v1)

cycle_cnt = 0
visited = set()
for v in G:
    if v in visited:
        continue
    stack = [v]
    path = []
    while stack:
        node = stack.pop()
        if node in visited:
            continue
        visited.add(node)
        path.append(node)
        stack.extend(G[node])
    ok = True
    for node in path:
        if len(G[node]) != 2:
            ok = False
            break
    cycle_cnt += ok
print(cycle_cnt)





def go():
    n, m = (int(i) for i in input().split(' '))
    graph = {}
    for _ in range(m):
        a, b = (int(i) for i in input().split(' '))
        graph.setdefault(a, [])
        graph.setdefault(b, [])
        graph[a].append(b)
        graph[b].append(a)
    output = 0
    cands = set(i for i in graph if len(graph[i]) == 2)
    while cands:
        c = cands.pop()
        r, l = graph[c]
        while l in cands:
            cands.remove(l)
            c1, c2 = graph[l]
            if c1 in cands:
                l = c1
            elif c2 in cands:
                l = c2
            else:
                break
            if l == r:
                output += 1
    return output

print(go())


N,M = map(int,input().split())
G = {}
for i in range(M):
	a,b = map(int,input().split())
	if a not in G:
		G[a] = set()
	if b not in G:
		G[b] = set()
	G[a].add(b)
	G[b].add(a)

def dfs(graph, start):
	visited = set()
	stack = [start]
	while stack:
		node = stack.pop()
		if node not in visited:
			visited.add(node)
			for i in graph[node]:
				stack.append(i)
	return visited

arr = []
seen = set()
for x in G:
	if x not in seen:
		P = dfs(G,x)
		seen |= P
		arr.append((list(P)[0],P))
cnt = 0
for x in arr:
	if x[0] in x[1] and all([len(G[y]) == 2 for y in x[1]]):
		cnt += 1
print(cnt)

n,m=list(map(int,input().split()))
par=[-1]*n

def find(x):
    if par[x]!=-1:
        x=find(par[x])
        
    return x

def union(x,y):
    a=find(x)
    b=find(y)
    b,a=sorted([a,b])
    if a==b:
        return
    par[a]=b

deg=[0]*n

for i in range(m):
    u,v=list(map(int,input().split()))
    deg[u-1]+=1
    deg[v-1]+=1
    union(u-1,v-1)

R=dict()
out=0
for i in range(n):
    if par[i]==-1:
        R[i]=[]
for i in range(n):
    a=find(i)
    R[a].append(i)
    
for i in R:
    if len(R[i])>2:
        x=1
        for j in R[i]:
            if deg[j]!=2:
                x=0
                break
        if x==1:
            out+=1
print(out)


n,m = list(map(int, input().split()))
g = [[] for i in range(n)]
dg = [0 for i in range(n)]
for i in range(m):
    u,v = list(map(int, input().split()))
    g[u-1].append(v-1)
    g[v-1].append(u-1)
    dg[u-1] +=1
    dg[v-1]+=1
vis = [0 for i in range(n)]
ans = 0
for i in range(n):
    if vis[i] != 0:
        continue
    q = [i]
    if dg[i] == 2:
        ans1 = 1
    else:
        ans1 = 0
    while len(q) > 0:
        v = q[0]
        for u in g[v]:
            if vis[u] == 0:
                vis[u] = 1
                q.append(u)
                if dg[u] != 2:
                    ans1 = 0
        del q[0]
    ans += ans1
print(ans)


rd = lambda: list(map(int, input().split()))
n, m = rd()
d = {}
def f(x):
    d[x] = d.get(x, 0) + 1
uf = [i for i in range(n)]
def find(i):
    p = uf[i]
    if i == p:
        return p
    else:
        uf[i] = find(p)
        return uf[i]
for _ in range(m):
    u, v = sorted(rd())
    u -= 1
    v -= 1
    f(u)
    f(v)
    uf[find(v)] = find(u)
r = [1] * n
for i in range(n):
    r[find(i)] &= d.get(i, 0) == 2
print(sum(i == uf[i] for i in range(n)) + sum(r) - n)


from collections import deque


def bfs(v):
    q = deque()
    q.append(v)
    w = []
    while len(q):
        cur = q.popleft()
        w.append(cur)
        p[cur] = c
        for i in g[cur]:
            if p[i] == 0:
                q.append(i)
                p[i] = c
    k.append(w)

n, m = list(map(int, input().split()))

g = [[] for i in range(n + 1)]
p = [0] * (n + 1)
k = [[]]

for i in range(m):
    a, b = list(map(int, input().split()))
    g[a].append(b)
    g[b].append(a)


c = 0
for v in range(1, n + 1):
    if p[v] == 0:
        c += 1
        bfs(v)


ans = 0
for i in range(1, len(k)):
    fl = True
    for j in range(len(k[i])):
        if len(g[k[i][j]]) != 2:
            fl = False
    if fl:
        ans += 1

print(ans)


def dfs(v, g, vis):
    count = 1
    first = v
    st = [v]
    vis[v] = True
    while st:
        v = st[-1]
        st.pop()
        if len(g[v]) != 2 or vis[g[v][0]] and vis[g[v][1]] and g[v][0] != first and g[v][1] != first:
            count = 0
        for i in range(len(g[v])):
            if not vis[g[v][i]]:
                vis[g[v][i]] = True
                st.append(g[v][i])
                if v == first and count:
                    break
    if len(g[first]) == 2 and not vis[g[first][1]]:
        st.append(g[first][1])
        while st:
            v = st[-1]
            st.pop()
            for i in range(len(g[v])):
                if not vis[g[v][i]]:
                    vis[g[v][i]] = True
                    st.append(g[v][i])            
    return count

v, e = list(map(int, input().split()))
g = [[] for i in range(v)]
for i in range(e):
    f, to = list(map(int, input().split()))
    g[f-1].append(to-1)
    g[to-1].append(f-1)
vis = [False] * v
ans = 0
for i in range(v):
    if not vis[i]:
        ans += dfs(i, g, vis)
print(ans)


import operator
data = list( map (int, input().split(' ')) )
n = data[0]
m = data[1]
edge = {}
for i in range(n):
    edge[i+1] = []
for _ in range(m):
    data = list( map (int, input().split(' ')) )
    i = data[0]
    j = data[1]
    edge[i].append(j)
    edge[j].append(i)
candidate = [k for k,v in list(edge.items()) if len(v) == 2]
result = 0
used = {}
def _iscircle(c, result):
    n = edge[c][0]
    used[c] = 1
    last = c
    while n not in used:
        used[n] = 1
        if len(edge[n]) != 2:
            return result
        t = edge[n][0]
        if t != last:
            last = n
            if t == c:
                return result + 1
            n = t
            continue
        last = n

        t = edge[n][1]
        if t == c:
            return result + 1
        n = t
    return result


for i in candidate:
    result = _iscircle(i, result)
print (result)