Problem:


  MathJax.Hub.Config({ tex2jax: { inlineMath: [["$","$"], ["\\(","\\)"]], processEscapes: true }});

A - Breadth-First Search by Foxpower

Problem Statement

Fox Ciel went to JAG Kingdom by bicycle, but she forgot a place where she parked her bicycle. So she needs to search it from a bicycle-parking area before returning home.

The parking area is formed as a unweighted rooted tree $T$ with $n$ vertices, numbered $1$ through $n$. Each vertex has a space for parking one or more bicycles. Ciel thought that she parked her bicycle near the vertex $1$, so she decided to search it from there by the breadth-first search. That is, she searches it at the vertices in the increasing order of their distances from the vertex $1$. If multiple vertices have the same distance, she gives priority to the vertices in the order of searching at their parents. If multiple vertices have the same parent, she searches at the vertex with minimum number at first.

Unlike a computer, she can't go to a next vertex by random access. Thus, if she goes to the vertex $j$ after the vertex $i$, she needs to walk the distance between the vertices $i$ and $j$. BFS by fox power perhaps takes a long time, so she asks you to calculate the total moving distance in the worst case starting from the vertex $1$.

Input

The input is formatted as follows.

$n$
$p_2$ $p_3$ $p_4$ $\cdots$ $p_n$

The first line contains an integer $n$ ($1 \le n \le 10^5$), which is the number of vertices on the unweighted rooted tree $T$.
The second line contains $n-1$ integers $p_i$ ($1 \le p_i < i$), which are the parent of the vertex $i$.
The vertex $1$ is a root node, so $p_1$ does not exist.

Output

Print the total moving distance in the worst case in one line.

Sample Input 1

4
1 1 2

Output for the Sample Input 1

6

Sample Input 2

4
1 1 3

Output for the Sample Input 2

4

Sample Input 3

11
1 1 3 3 2 4 1 3 2 9

Output for the Sample Input 3

25


Sample input:
4
1 1 2


Sample output:
6

Submission status: Wrong Answer

Solution code:
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools

sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**13
mod = 10**9+7
dd = [(-1,0),(0,1),(1,0),(0,-1)]
ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]

def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)


def main():
    n = I()
    a = LI_()
    b = [0]
    c = [[None] * 18]
    for i in range(n-1):
        t = a[i]
        b.append(b[t] + 1)
        d = [None] * 18
        d[0] = t
        for j in range(1,18):
            if c[d[j-1]][j-1] is None:
                break
            d[j] = c[d[j-1]][j-1]
        c.append(d)

    ii = [2**i for i in range(19)]
    def f(i,j):
        if i == j:
            return 0
        if b[i] > b[j]:
            sa = b[i] - b[j]
            for k in range(1,18):
                if sa < ii[k]:
                    return ii[k-1] + f(c[i][k-1], j)
        if b[i] < b[j]:
            sa = b[j] - b[i]
            for k in range(1,18):
                if sa < ii[k]:
                    return ii[k-1] + f(c[j][k-1], i)
        for k in range(1,18):
            if c[i][k] == c[j][k]:
                return ii[k] + f(c[i][k-1], c[j][k-1])

    ba = sorted(zip(b, range(n)))
    aa = [0]
    aai = {}
    aai[0] = 0
    i = 1
    while i < n:
        j = i + 1
        bi = ba[i][0]
        while j < n and bi == ba[j][0]:
            j += 1
        aa.extend(list(map(lambda x: x[1], sorted([[aai[c[_][0]], _] for k,_ in ba[i:j]]))))
        for k in range(i,j):
            aai[aa[k]] = k
        i = j
    r = 1
    for i in range(1,n-1):
        r += f(aa[i],aa[i+1])

    return r


print(main())

Submission status: Time Limit Exceeded

Solution code:
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools

sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**13
mod = 10**9+7
dd = [(-1,0),(0,1),(1,0),(0,-1)]
ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]

def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)


def main():
    n = I()
    a = LI_()
    b = [0]
    c = [[None] * 18]
    for i in range(n-1):
        t = a[i]
        b.append(b[t] + 1)
        d = [None] * 18
        d[0] = t
        for j in range(1,18):
            if c[d[j-1]][j-1] is None:
                break
            d[j] = c[d[j-1]][j-1]
        c.append(d)

    ii = [2**i for i in range(19)]
    def f(i,j):
        if i == j:
            return 0
        if b[i] > b[j]:
            sa = b[i] - b[j]
            for k in range(1,18):
                if sa < ii[k]:
                    return ii[k-1] + f(c[i][k-1], j)
        if b[i] < b[j]:
            sa = b[j] - b[i]
            for k in range(1,18):
                if sa < ii[k]:
                    return ii[k-1] + f(c[j][k-1], i)
        for k in range(1,18):
            if c[i][k] == c[j][k]:
                return ii[k] + f(c[i][k-1], c[j][k-1])

    ba = sorted(zip(b, range(n)))
    aa = [0]
    i = 1
    while i < n:
        j = i + 1
        bi = ba[i][0]
        while j < n and bi == ba[j][0]:
            j += 1
        aa.extend(list(map(lambda x: x[1], sorted([[aa.index(c[_][0]), _] for k,_ in ba[i:j]]))))
        i = j
    r = 1
    for i in range(1,n-1):
        r += f(aa[i],aa[i+1])

    return r


print(main())

Submission status: Accepted

Solution code:
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools

sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**13
mod = 10**9+7
dd = [(-1,0),(0,1),(1,0),(0,-1)]
ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]

def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)


def main():
    n = I()
    if n == 1:
        return 0
    a = LI_()
    b = [0]
    c = [[None] * 18]
    for i in range(n-1):
        t = a[i]
        b.append(b[t] + 1)
        d = [None] * 18
        d[0] = t
        for j in range(1,18):
            if c[d[j-1]][j-1] is None:
                break
            d[j] = c[d[j-1]][j-1]
        c.append(d)

    ii = [2**i for i in range(19)]
    def f(i,j):
        if i == j:
            return 0
        if b[i] > b[j]:
            sa = b[i] - b[j]
            for k in range(1,18):
                if sa < ii[k]:
                    return ii[k-1] + f(c[i][k-1], j)
        if b[i] < b[j]:
            sa = b[j] - b[i]
            for k in range(1,18):
                if sa < ii[k]:
                    return ii[k-1] + f(c[j][k-1], i)
        for k in range(1,18):
            if c[i][k] == c[j][k]:
                return ii[k] + f(c[i][k-1], c[j][k-1])

    ba = sorted(zip(b, range(n)))
    aa = [0]
    aai = {}
    aai[0] = 0
    i = 1
    while i < n:
        j = i + 1
        bi = ba[i][0]
        while j < n and bi == ba[j][0]:
            j += 1
        aa.extend(list(map(lambda x: x[1], sorted([[aai[c[_][0]], _] for k,_ in ba[i:j]]))))
        for k in range(i,j):
            aai[aa[k]] = k
        i = j
    r = 1
    for i in range(1,n-1):
        r += f(aa[i],aa[i+1])

    return r


print(main())