Moment of Bloom (Codeforces 1586E)
Tags: Greedy, graph matchings

She does her utmost to flawlessly carry out a person's last rites and preserve the world's balance of yin and yang.Hu Tao, being the little prankster she is, has tried to scare you with this graph problem! You are given a connected undirected graph of $$$n$$$ nodes with $$$m$$$ edges. You also have $$$q$$$ queries. Each query consists of two nodes $$$a$$$ and $$$b$$$.Initially, all edges in the graph have a weight of $$$0$$$. For each query, you must choose a simple path starting from $$$a$$$ and ending at $$$b$$$. Then you add $$$1$$$ to every edge along this path. Determine if it's possible, after processing all $$$q$$$ queries, for all edges in this graph to have an even weight. If so, output the choice of paths for each query. If it is not possible, determine the smallest number of extra queries you could add to make it possible. It can be shown that this number will not exceed $$$10^{18}$$$ under the given constraints.A simple path is defined as any path that does not visit a node more than once.An edge is said to have an even weight if its value is divisible by $$$2$$$.

Input: The first line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 3 \cdot 10^5$$$, $$$n-1 \leq m \leq \min{\left(\frac{n(n-1)}{2}, 3 \cdot 10^5\right)}$$$).Each of the next $$$m$$$ lines contains two integers $$$x$$$ and $$$y$$$ ($$$1 \leq x, y \leq n$$$, $$$x\neq y$$$) indicating an undirected edge between node $$$x$$$ and $$$y$$$. The input will not contain self-loops or duplicate edges, and the provided graph will be connected.The next line contains a single integer $$$q$$$ ($$$1 \leq q \leq 3 \cdot 10^5$$$).Each of the next $$$q$$$ lines contains two integers $$$a$$$ and $$$b$$$ ($$$1 \leq a, b \leq n, a \neq b$$$), the description of each query.It is guaranteed that $$$nq \leq 3 \cdot 10^5$$$.

Output: If it is possible to force all edge weights to be even, print "YES" on the first line, followed by $$$2q$$$ lines indicating the choice of path for each query in the same order the queries are given. For each query, the first line should contain a single integer $$$x$$$: the number of nodes in the chosen path. The next line should then contain $$$x$$$ spaced separated integers $$$p_i$$$ indicating the path you take ($$$p_1 = a, p_x = b$$$ and all numbers should fall between $$$1$$$ and $$$n$$$). This path cannot contain duplicate nodes and must be a valid simple path in the graph.If it is impossible to force all edge weights to be even, print "NO" on the first line and the minimum number of added queries on the second line.

Note: Here is what the queries look like for the first test case (red corresponds to the 1st query, blue 2nd query, and green 3rd query):    Notice that every edge in the graph is part of either $$$0$$$ or $$$2$$$ colored query edges.The graph in the second test case looks like this:    There does not exist an assignment of paths that will force all edges to have even weights with the given queries. One must add at least $$$2$$$ new queries to obtain a set of queries that can satisfy the condition.

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

5 7
4 3
4 5
2 1
1 4
1 3
3 5
3 2
4
4 2
3 5
5 1
4 5

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

NO
2

Solution (Python):
import sys
import math
inpu = sys.stdin.readline
prin = sys.stdout.write
(n, m) = map(int, inpu().split())
neigh = {i: [] for i in range(1, n + 1)}
for i in range(m):
    (x, y) = map(int, inpu().split())
    neigh[x].append(y)
    neigh[y].append(x)
q = int(inpu())
queries = []
appearances = [0] * n
for i in range(q):
    (x, y) = map(int, inpu().split())
    appearances[x - 1] += 1
    appearances[y - 1] += 1
    queries.append((x, y))
odds = 0
for guy in appearances:
    if guy % 2 == 1:
        odds += 1
if odds > 0:
    prin('NO\n')
    prin(str(odds // 2))
else:
    prin('YES\n')
    ancestors = {1: None}
    layer = [1]
    while layer != []:
        newlayer = []
        for v in layer:
            for n in neigh[v]:
                if n not in ancestors:
                    ancestors[n] = v
                    newlayer.append(n)
        layer = newlayer
    for (a, b) in queries:
        to = [a]
        curr = a
        while ancestors[curr] is not None:
            curr = ancestors[curr]
            to.append(curr)
        fro = [b]
        curr = b
        while ancestors[curr] is not None:
            curr = ancestors[curr]
            fro.append(curr)
        i = -1
        while i + len(to) >= 0 and i + len(fro) >= 0 and (to[i] == fro[i]):
            i -= 1
        useto = to[:i + 1]
        usefro = fro[:i + 1]
        path = useto + [to[i + 1]] + usefro[::-1]
        prin(str(len(path)))
        prin('\n')
        prin(' '.join([str(v) for v in path]))
        prin('\n')

Solution (Python):
import io, os, sys
import threading
threading.stack_size(32 * 2048 * 2048)
sys.setrecursionlimit(350000)
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 getpath(index, end, neigh, pre, ans):
    if index == end:
        pre.append(end)
        ans.append(list(pre))
        pre.pop()
        return
    pre.append(index)
    for nextindex in neigh[index]:
        if len(pre) > 1 and nextindex == pre[-2]:
            continue
        getpath(nextindex, end, neigh, pre, ans)
    pre.pop()

def printarr(arr):
    for i in range(len(arr)):
        arr[i] += 1
    print(len(arr))
    print(' '.join(map(str, arr)))
    return

def main():
    (n, m) = map(int, input().split())
    neigh = [[] for i in range(n)]
    group = [i for i in range(n)]
    for _ in range(m):
        (u, v) = map(int, input().split())
        u -= 1
        v -= 1
        root1 = unionfind(group, u)
        root2 = unionfind(group, v)
        if root1 == root2:
            continue
        group[max(root1, root2)] = min(root1, root2)
        neigh[u].append(v)
        neigh[v].append(u)
    queries = []
    dic = {}
    q = int(input())
    for _ in range(q):
        (u, v) = map(int, input().split())
        u -= 1
        v -= 1
        queries.append([u, v])
        if u in dic:
            del dic[u]
        else:
            dic[u] = 1
        if v in dic:
            del dic[v]
        else:
            dic[v] = 1
    if len(dic) > 0:
        print('NO')
        print(len(dic) // 2)
    else:
        print('YES')
        for i in range(q):
            ans = []
            getpath(queries[i][0], queries[i][1], neigh, [], ans)
            printarr(ans[0])
threading.Thread(target=main).start()

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

class DSU:

    def __init__(self, n):
        self.p = [i for i in range(n)]
        self.size = [1] * n

    def find(self, x):
        root = x
        while root != self.p[root]:
            root = self.p[root]
        while x != root:
            tmp = x
            x = self.p[x]
            self.p[tmp] = root
        return root

    def union(self, x, y):
        (pa, pb) = (self.find(x), self.find(y))
        if pa == pb:
            return True
        if self.size[pa] < self.size[pb]:
            (pa, pb) = (pb, pa)
        self.p[pb] = pa
        self.size[pa] += self.size[pb]
        return False

def readList():
    return list(map(int, input().split()))

def readInt():
    return int(input())

def readInts():
    return map(int, input().split())

def readStr():
    return input().strip()

def solve():
    (n, m) = readInts()
    graph = [[] for _ in range(n)]
    dsu = DSU(n)
    for i in range(m):
        (u, v) = readInts()
        u -= 1
        v -= 1
        if dsu.find(u) != dsu.find(v):
            dsu.union(u, v)
            graph[u].append(v)
            graph[v].append(u)
    (q, cnt, Q) = (readInt(), [0] * n, [])
    for _ in range(q):
        (a, b) = readInts()
        cnt[a - 1] += 1
        cnt[b - 1] += 1
        Q.append([a - 1, b - 1])
    v = 0
    for i in range(n):
        v += cnt[i] % 2
    if v:
        print('NO')
        print(v // 2)
    else:
        print('YES')
        for (s, t) in Q:
            st = [s]
            pred = [-1] * n
            pred[s] = -2
            while st:
                node = st.pop()
                if node == t:
                    break
                for nei in graph[node]:
                    if pred[nei] == -1:
                        pred[nei] = node
                        st.append(nei)
            path = []
            curr = t
            while curr != -2:
                path.append(curr + 1)
                curr = pred[curr]
            print(len(path))
            print(*path[::-1])
    return
solve()