Vertical Paths (Codeforces 1675D)
Tags: Implement, trees

You are given a rooted tree consisting of $$$n$$$ vertices. Vertices are numbered from $$$1$$$ to $$$n$$$. Any vertex can be the root of a tree.A tree is a connected undirected graph without cycles. A rooted tree is a tree with a selected vertex, which is called the root.The tree is specified by an array of parents $$$p$$$ containing $$$n$$$ numbers: $$$p_i$$$ is a parent of the vertex with the index $$$i$$$. The parent of a vertex $$$u$$$ is a vertex that is the next vertex on the shortest path from $$$u$$$ to the root. For example, on the simple path from $$$5$$$ to $$$3$$$ (the root), the next vertex would be $$$1$$$, so the parent of $$$5$$$ is $$$1$$$.The root has no parent, so for it, the value of $$$p_i$$$ is $$$i$$$ (the root is the only vertex for which $$$p_i=i$$$).Find such a set of paths that:  each vertex belongs to exactly one path, each path can contain one or more vertices;  in each path each next vertex — is a son of the current vertex (that is, paths always lead down — from parent to son);  number of paths is minimal. For example, if $$$n=5$$$ and $$$p=[3, 1, 3, 3, 1]$$$, then the tree can be divided into three paths:   $$$3 \rightarrow 1 \rightarrow 5$$$ (path of $$$3$$$ vertices),  $$$4$$$ (path of $$$1$$$ vertices).  $$$2$$$ (path of $$$1$$$ vertices).   Example of splitting a root tree into three paths for $$$n=5$$$, the root of the tree — node $$$3$$$. 

Input: The first line of input data contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test.Each test case consists of two lines.The first of them contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$). It is the number of vertices in the tree.The second line contains $$$n$$$ integers $$$p_1, p_2, \dots, p_n$$$ ($$$1 \le p_i \le n$$$). It is guaranteed that the $$$p$$$ array encodes some rooted tree.It is guaranteed that the sum of the values $$$n$$$ over all test cases in the test does not exceed $$$2 \cdot 10^5$$$.

Output: For each test case on the first line, output an integer $$$m$$$ — the minimum number of non-intersecting leading down paths that can cover all vertices of the tree.Then print $$$m$$$ pairs of lines containing path descriptions. In the first of them print the length of the path, in the second — the sequence of vertices specifying that path in the order from top to bottom. You can output the paths in any order.If there are several answers, output any of them.


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

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

2
2
1 2
2
4 3

1
7
1 2 3 4 5 6 7

1
1
1

3
3
4 1 5
2
2 6
1
3

3
2
2 1
1
3
1
4

Solution (Python):
def f():
    n = int(input())
    a = list(map(int, input().split()))
    if n == 1:
        print('1' + '\n' + '1' + '\n' + '1' + '\n')
        return
    visited = [False] * n
    branch = [True] * n
    for i in a:
        branch[i - 1] = False
    print(branch.count(True))
    for i in range(n):
        if branch[i]:
            t = i
            path = [i + 1]
            while not visited[a[t] - 1]:
                visited[a[t] - 1] = True
                path.append(a[t])
                t = a[t] - 1
            print(len(path))
            print(' '.join((str(x) for x in path[::-1])))
    print()
for _ in range(int(input())):
    f()

Solution (Python):
import bisect
import collections
import math
import random
import sys
p2D = lambda x: print(*x, sep='\n')

def II():
    return int(sys.stdin.buffer.readline())

def MI():
    return map(int, sys.stdin.buffer.readline().split())

def LI():
    return list(map(int, sys.stdin.buffer.readline().split()))

def LLI(rows_number):
    return [LI() for _ in range(rows_number)]

def BI():
    return sys.stdin.buffer.readline().rstrip()

def SI():
    return sys.stdin.buffer.readline().rstrip().decode()

def li():
    return [int(i) for i in input().split()]

def lli(rows):
    return [li() for _ in range(rows)]

def si():
    return input()

def ii():
    return int(input())

def ins():
    return input().split()

def drank(d, processing, da, rank):
    tmp = 10 ** 9
    if len(d[da]) == 1:
        return 1
    for di in d[da]:
        if processing[di - 1] == 0:
            processing[di - 1] = 1
            tmp = min(tmp, drank(d, processing, di, rank))
            processing[di - 1] = 0
    rank[da - 1] = tmp + 1
    return tmp + 1

def binary_search(n, a):
    l = len(a)
    low = 0
    high = l - 1
    while high >= low:
        mid = (high + low) // 2
        if a[mid] == n:
            return mid
        elif a[mid] > n:
            high = mid - 1
        else:
            low = mid + 1
    return -1

def gcd(a, b):
    if b == 0:
        x = 1
        y = 0
        return (x, y, a)
    (x, y, g) = gcd(b, a % b)
    return (y, x - a // b * y, g)

def solve():
    n = II()
    p = LI()
    taken = [0] * (n + 1)
    d = collections.defaultdict(list)
    for i in range(n):
        d[p[i]].append(i + 1)
    ans = ''
    snt = 0
    for i in range(1, n + 1):
        z = i
        de = []
        if taken[i] == 0:
            while taken[i] != 1:
                de.append(i)
                taken[i] = 1
                i = p[i - 1]
            de = de[::-1]
            while d[z] != []:
                x = d[z].pop()
                while d[z] != [] and taken[x] == 1:
                    x = d[z].pop()
                if taken[x] == 0:
                    de.append(x)
                    taken[x] = 1
                z = x
            ans += str(len(de)) + '\n' + ' '.join(map(str, de)) + '\n'
            snt += 1
    return str(snt) + '\n' + ans

def main():
    for _ in range(II()):
        sys.stdout.write(str(solve()) + '\n')
if __name__ == '__main__':
    main()

Solution (Python):
def read_input():
    t = int(input())
    for _ in range(t):
        n = int(input())
        ps = [int(i) for i in input().split(' ')]
        out = path(ps)
        print(out)

def path(ps):
    paths = []
    nexter = {}
    starters = set()
    for (index, parent) in enumerate(ps):
        node = index + 1
        if parent in nexter:
            starters.add(node)
        else:
            if node == parent:
                starters.add(node)
                continue
            nexter[parent] = node
    for s in starters:
        path = [s]
        current = s
        while current in nexter and current != nexter[current]:
            current = nexter[current]
            path.append(current)
        paths.append(path)
    out_text = f'{len(paths)}'
    for path in paths:
        out_text += f'\n{len(path)}'
        out_text += f"\n{' '.join((str(i) for i in path))}"
    return out_text
read_input()