Fish Graph (Codeforces 1817B)
Tags: Others, dfs and similar

You are given a simple undirected graph with $$$n$$$ nodes and $$$m$$$ edges. Note that the graph is not necessarily connected. The nodes are labeled from $$$1$$$ to $$$n$$$.We define a graph to be a Fish Graph if it contains a simple cycle with a special node $$$u$$$ belonging to the cycle. Apart from the edges in the cycle, the graph should have exactly $$$2$$$ extra edges. Both edges should connect to node $$$u$$$, but they should not be connected to any other node of the cycle. Determine if the graph contains a subgraph that is a Fish Graph, and if so, find any such subgraph.In this problem, we define a subgraph as a graph obtained by taking any subset of the edges of the original graph.  Visualization of example 1. The red edges form one possible subgraph that is a Fish Graph. 

Input: The first line of input contains the integer $$$t$$$ ($$$1 \leq t \leq 1000$$$), the number of test cases. The description of test cases follows.The first line of each test case contains two integers, $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 2\,000$$$) — the number of nodes and the number of edges.Each of the next $$$m$$$ lines contains the description of an edge. Each line contains two integers $$$u_i$$$ and $$$v_i$$$ ($$$1 \leq u_i, v_i \leq n$$$, $$$u_i\neq v_i$$$) — an edge connects node $$$u_i$$$ to node $$$v_i$$$.It is guaranteed that no two edges connect the same unordered pair of nodes.Furthermore, it is guaranteed that the sum of $$$n$$$ and the sum of $$$m$$$ over all test cases both do not exceed $$$2\,000$$$.

Output: For each testcase, output "YES" if the graph contains a subgraph that is a Fish Graph, otherwise print "NO". If the answer is "YES", on the following lines output a description of the subgraph.The first line of the description contains one integer $$$k$$$ — the number of edges of the subgraph. On the next $$$k$$$ lines, output the edges of the chosen subgraph. Each of the $$$k$$$ lines should contains two integers $$$u$$$ and $$$v$$$ ($$$1\le u, v\le n$$$, $$$u\neq v$$$) — the edge between $$$u$$$ and $$$v$$$ belongs to the subgraph. The order in which $$$u$$$ and $$$v$$$ are printed does not matter, as long as the two nodes are connected by an edge in the original graph. The order in which you print the edges does not matter, as long as the resulting subgraph is a fish graph.If there are multiple solutions, print any.

Note: In the first example, a possible valid subgraph contains the cycle $$$1 \rightarrow 2 \rightarrow 3 \rightarrow 4 \rightarrow 1$$$. The special node of this cycle is node $$$4$$$. The two extra edges $$$4 - 5$$$ and $$$4 - 6$$$ are both connected to $$$4$$$, completing the Fish Graph.In the second example, a possible valid subgraph contains the cycle $$$1 \rightarrow 3 \rightarrow 4 \rightarrow 1$$$. The special node of this cycle is node $$$3$$$. The two extra edges $$$3 - 2$$$ and $$$3 - 5$$$ are both connected to $$$3$$$, completing the Fish Graph.In the last example, it can be proven that there is no valid subgraph. 

Sample Inputs:
3
7 8
1 2
2 3
3 4
4 1
4 5
4 6
4 2
6 7
7 7
6 7
1 2
2 3
3 4
4 1
1 3
3 5
4 4
1 3
3 4
4 1
1 2

Sample Outputs:
YES
6
5 4
6 4
4 3
1 4
2 1
3 2
YES
5
5 3
2 3
3 1
4 3
1 4
NO

Solution (Python):
for _ in range(int(input())):
    (N, M) = map(int, input().split())
    ed = [set() for _ in range(N)]
    for _ in range(M):
        (u, v) = map(lambda x: int(x) - 1, input().split())
        ed[u].add(v)
        ed[v].add(u)
    fo = False
    for u in range(N):
        ta = ed[u].copy()
        if len(ta) < 4:
            continue
        while len(ta) >= 2:
            st = ta.pop()
            ex = [False for _ in range(N)]
            ex[u] = True
            ex[st] = True
            pi = [st]
            pr = [-1 for _ in range(N)]
            pr[st] = u
            while pi:
                cn = pi.pop()
                for nn in ed[cn]:
                    if ex[nn]:
                        continue
                    pr[nn] = cn
                    if nn in ta:
                        end = nn
                        fo = True
                        break
                    ex[nn] = True
                    pi.append(nn)
                if fo:
                    break
            if fo:
                break
        if fo:
            break
    if not fo:
        print('NO')
        continue
    print('YES')
    ta = ed[u].difference({st, end})
    fe = [(ta.pop(), u), (ta.pop(), u), (u, st), (end, u)]
    cn = end
    pn = pr[end]
    while pn != u:
        fe.append((cn, pn))
        cn = pn
        pn = pr[cn]
    print(len(fe))
    for edge in fe:
        (u, v) = edge
        print(u + 1, v + 1)

Solution (Python):
import sys
input = sys.stdin.buffer.readline

def check(n, g, root):
    parent = [None for i in range(n + 1)]
    first_parent = [None for i in range(n + 1)]
    start = [root]
    parent[root] = -1
    while len(start) > 0:
        next_s = []
        for x in start:
            for y in g[x]:
                if parent[y] is None:
                    parent[y] = x
                    if x == root:
                        first_parent[y] = y
                    else:
                        first_parent[y] = first_parent[x]
                    next_s.append(y)
        start = next_s
    for i in range(1, n + 1):
        i_p = first_parent[i]
        for j in g[i]:
            j_p = first_parent[j]
            if i != root and j != root:
                if i_p != j_p:
                    answer = [(i, j)]
                    p1 = i
                    while p1 != root:
                        x = p1
                        x_p = parent[x]
                        answer.append((x, x_p))
                        p1 = x_p
                    p2 = j
                    while p2 != root:
                        x = p2
                        x_p = parent[x]
                        answer.append((x, x_p))
                        p2 = x_p
                    other = [x for x in g[root] if x != i_p and x != j_p]
                    (a, b) = other[:2]
                    answer.append((root, a))
                    answer.append((root, b))
                    return answer
    return None

def process(n, G):
    g = [[] for i in range(n + 1)]
    for (u, v) in G:
        g[u].append(v)
        g[v].append(u)
    for i in range(1, n + 1):
        if len(g[i]) >= 4:
            answer = check(n, g, i)
            if answer is not None:
                sys.stdout.write('YES\n')
                sys.stdout.write(f'{len(answer)}\n')
                for (a, b) in answer:
                    sys.stdout.write(f'{a} {b}\n')
                return
    sys.stdout.write('NO\n')
    return
t = int(input())
for i in range(t):
    (n, m) = [int(x) for x in input().split()]
    G = []
    for j in range(m):
        (u, v) = [int(x) for x in input().split()]
        G.append([u, v])
    process(n, G)

Solution (Python):
import io, os
from collections import deque
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline

def unionfind(group, root):
    son = root
    while root != group[root]:
        root = group[root]
    while son != root:
        temp = group[son]
        group[son] = root
        son = group[temp]
    return root

def bfs(start, end, neigh):
    n = len(neigh)
    queue = deque()
    queue.append(start)
    pre = [-2] * n
    pre[start] = -1
    while queue:
        index = queue.popleft()
        for nextindex in neigh[index]:
            if pre[nextindex] > -2:
                continue
            if index == start and nextindex == end:
                continue
            pre[nextindex] = index
            queue.append(nextindex)
        if pre[end] > -2:
            break
    path = [end]
    curr = end
    while curr != start:
        curr = pre[curr]
        path.append(curr)
    return path

def main(t):
    (n, m) = map(int, input().split())
    degree = [0] * n
    edges = []
    wholeneigh = [[] for _ in range(n)]
    for _ in range(m):
        (u, v) = map(int, input().split())
        u -= 1
        v -= 1
        edges.append((u, v))
        wholeneigh[u].append(v)
        wholeneigh[v].append(u)
    neigh = [[] for _ in range(n)]
    group = [i for i in range(n)]
    node = -1
    for (u, v) in edges:
        rootu = unionfind(group, u)
        rootv = unionfind(group, v)
        neigh[u].append(v)
        neigh[v].append(u)
        if rootu != rootv:
            group[max(rootu, rootv)] = min(rootu, rootv)
            continue
        else:
            degree = [0] * n
            path = bfs(u, v, neigh)
            setpath = set(path)
            node = -1
            for i in range(len(path)):
                temp = []
                for nexti in wholeneigh[path[i]]:
                    if nexti in setpath:
                        continue
                    temp.append(nexti)
                if len(temp) > 1:
                    node = i
                    break
            if node < 0:
                continue
            m = len(path)
            print('YES')
            print(m + 2)
            for i in range(m):
                print(path[i] + 1, path[(i + 1) % m] + 1)
            print(path[node] + 1, temp[0] + 1)
            print(path[node] + 1, temp[1] + 1)
            return
    print('NO')
T = int(input())
t = 1
while t <= T:
    main(t)
    t += 1