GUPTA MECHANICAL

IN THIS WEBSITE I CAN TELL ALL ABOUT TECH. TIPS AND TRICKS APP REVIEWS AND UNBOXINGS ALSO TECH. NEWS .............

Thursday 5 May 2022

Vertical Paths Codeforces Solution | Codeforces Problem Solution 2022

D. Vertical Paths
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

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.

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: pi 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.

Solution Click Below:- CLICK HERE

The root has no parent, so for it, the value of pi is i (the root is the only vertex for which pi=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);
  • amount 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:

  1. 315 (path of 3 vertices),
  2. 4 (path of 1 vertices).
  3. 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 (1t104) — the number of test cases in the test.

Each test case consists of two lines.

The first of them contains an integer n (1n2105). It is the number of vertices in the tree.

The second line contains n integers p1,p2,,pn (1pin). 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 2105.

Output

For each test case on the first line, output an integer m — the minimum amount 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. 

Join Now for Solution:- 

No comments:

Post a Comment