Problem:


Score : 600 points

Problem Statement

We have a tree with N vertices, whose i-th edge connects Vertex u_i and Vertex v_i.
Vertex i has an integer a_i written on it.
For every integer k from 1 through N, solve the following problem:

We will make a sequence by lining up the integers written on the vertices along the shortest path from Vertex 1 to Vertex k, in the order they appear. Find the length of the longest increasing subsequence of this sequence.

Here, the longest increasing subsequence of a sequence A of length L is the subsequence A_{i_1} , A_{i_2} , ... , A_{i_M} with the greatest possible value of M such that 1 \leq i_1 < i_2 < ... < i_M \leq L and A_{i_1} < A_{i_2} < ... < A_{i_M}.

Constraints

2 \leq N \leq 2 \times 10^5

1 \leq a_i \leq 10^9

1 \leq u_i , v_i \leq N

u_i \neq v_i

The given graph is a tree.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 ... a_N
u_1 v_1
u_2 v_2
:
u_{N-1} v_{N-1}

Output

Print N lines. The k-th line, print the length of the longest increasing subsequence of the sequence obtained from the shortest path from Vertex 1 to Vertex k.

Sample Input 1

10
1 2 5 3 4 6 7 3 2 4
1 2
2 3
3 4
4 5
3 6
6 7
1 8
8 9
9 10

Sample Output 1

1
2
3
3
4
4
5
2
2
3

For example, the sequence A obtained from the shortest path from Vertex 1 to Vertex 5 is 1,2,5,3,4. Its longest increasing subsequence is A_1, A_2, A_4, A_5, with the length of 4.



Sample input:
10
1 2 5 3 4 6 7 3 2 4
1 2
2 3
3 4
4 5
3 6
6 7
1 8
8 9
9 10


Sample output:
1
2
3
3
4
4
5
2
2
3

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
#F

import sys
import math
from bisect import bisect_right as br
from bisect import bisect_left as bl
sys.setrecursionlimit(2147483647)
from heapq import heappush, heappop,heappushpop
from collections import defaultdict
from itertools import accumulate
from collections import Counter
from collections import deque
from operator import itemgetter
from itertools import permutations
mod = 10**9 + 7
inf = float('inf')
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))

n = I()
a = LI()
edges = [[] for _ in range(n)]
for _ in range(n-1):
    u, v = LI()
    edges[u-1].append(v-1)
    edges[v-1].append(u-1)

dp = [inf]*n
ans = [None]*n
ans[0] = 1
dp[0] = a[0]
def dfs(s, p, dp, num):
    for u in edges[s]:
        flag = False
        if u == p:
            continue
        if ans[u] != None:
            return
        r = br(dp, a[u])
        tmp = dp[r]
        if dp[r] == inf:
            num += 1
            flag = True
        ans[u] = num
        dp[r] = min(dp[r], a[u])
        dfs(u, s, dp, num)
        dp[r] = tmp
        if flag:
            num -= 1
    return
dfs(0, -1, dp, 1)

for i in ans:
    print(i)

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
#F

import sys
import math
from bisect import bisect_right as br
from bisect import bisect_left as bl
sys.setrecursionlimit(2147483647)
from heapq import heappush, heappop,heappushpop
from collections import defaultdict
from itertools import accumulate
from collections import Counter
from collections import deque
from operator import itemgetter
from itertools import permutations
mod = 10**9 + 7
inf = float('inf')
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))

n = I()
a = LI()
edges = [[] for _ in range(n)]
for _ in range(n-1):
    u, v = LI()
    edges[u-1].append(v-1)
    edges[v-1].append(u-1)

dp = [inf]*n
ans = [None]*n
ans[0] = 1
dp[0] = a[0]
def dfs(s, p, dp, num):
    for u in edges[s]:
        flag = False
        if u == p:
            continue
        if ans[u] != None:
            return
        r = br(dp, a[u])
        tmp = dp[r]
        if dp[r] == inf:
            num += 1
            flag = True
        ans[u] = num
        dp[r] = min(dp[r], a[u])
        dfs(u, s, dp, num)
        dp[r] = tmp
        if flag:
            num -= 1
    return
dfs(0, -1, dp, 1)
print(ans)

Submission status: Wrong Answer

Solution code:
import sys
readline = sys.stdin.readline

sys.setrecursionlimit(10**6)


def main():
    N = int(input())
    As = list(map(int, input().split()))

    query = (map(int, readline().strip().split()) for _ in range(N-1))

    tree = [[] for _ in range(N)]
    for u, v in query:
        tree[u-1].append(v-1)
        tree[v-1].append(u-1)

    inf = 10 ** 9 + 7
    dp = [inf] * N
    ans = [0] * N

    def dfs(node, parent):
        v = As[node]
        lb = binary_search(dp, v)
        old = dp[lb]
        dp[lb] = v
        ans[node] = lb + 1
        for child in tree[node]:
            if child == parent:
                continue
            dfs(child, node)
        dp[lb] = old

    dfs(0, 0)

    for k in range(N):
        print(ans[k])


def binary_search(seq, v):
    left = 0
    right = len(seq) - 1
    center = right // 2

    while center != right:
        if v <= seq[center]:
            right = center
        else:
            left = center+1
        center = (right + left) // 2

    return center


if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
import sys
readline = sys.stdin.readline

sys.setrecursionlimit(10**6)


def main():
    N = int(input())
    As = list(map(int, input().split()))

    query = (map(int, readline().strip().split()) for _ in range(N-1))

    tree = [[] for _ in range(N)]
    for u, v in query:
        tree[u-1].append(v-1)
        tree[v-1].append(u-1)

    inf = 10 ** 9 + 7
    dp = [inf] * N
    ans = [0] * N

    def dfs(node, parent):
        v = As[node]
        lb = binary_search(dp, v)
        old = dp[lb]
        dp[lb] = v
        ans[node] = lb + 1
        for child in tree[node]:
            if child == parent:
                continue
            dfs(child, node)
        dp[lb] = old

    dfs(0, 0)

    for k in range(N):
        print(ans[k])


def binary_search(seq, v):
    left = 0
    right = len(seq) - 1
    center = right // 2

    while center != right:
        if v < seq[center]:
            right = center
        else:
            left = center+1
        center = (right + left) // 2

    return center


if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
import sys,bisect,string,math,time,functools,random,fractions
from heapq import heappush,heappop,heapify
from collections import deque,defaultdict,Counter
from itertools import permutations,combinations,groupby
def Golf():*a,=map(int,open(0))
def I():return int(input())
def S_():return input()
def IS():return input().split()
def LS():return [i for i in input().split()]
def LI():return [int(i) for i in input().split()]
def LI_():return [int(i)-1 for i in input().split()]
def NI(n):return [int(input()) for i in range(n)]
def NI_(n):return [int(input())-1 for i in range(n)]
def StoLI():return [ord(i)-97 for i in input()]
def ItoS(n):return chr(n+97)
def LtoS(ls):return ''.join([chr(i+97) for i in ls])
def GI(V,E,ls=None,Directed=False,index=1):
    org_inp=[];g=[[] for i in range(V)]
    FromStdin=True if ls==None else False
    for i in range(E):
        if FromStdin:
            inp=LI()
            org_inp.append(inp)
        else:
            inp=ls[i]
        if len(inp)==2:
            a,b=inp;c=1
        else:
            a,b,c=inp
        if index==1:a-=1;b-=1
        aa=(a,c);bb=(b,c);g[a].append(bb)
        if not Directed:g[b].append(aa)
    return g,org_inp
def GGI(h,w,search=None,replacement_of_found='.',mp_def={'#':1,'.':0},boundary=1):
#h,w,g,sg=GGI(h,w,search=['S','G'],replacement_of_found='.',mp_def={'#':1,'.':0},boundary=1) # sample usage
    mp=[boundary]*(w+2);found={}
    for i in range(h):
        s=input()
        for char in search:
            if char in s:
                found[char]=((i+1)*(w+2)+s.index(char)+1)
                mp_def[char]=mp_def[replacement_of_found]
        mp+=[boundary]+[mp_def[j] for j in s]+[boundary]
    mp+=[boundary]*(w+2)
    return h+2,w+2,mp,found
def TI(n):return GI(n,n-1)
def bit_combination(n,base=2):
    rt=[]
    for tb in range(base**n):s=[tb//(base**bt)%base for bt in range(n)];rt+=[s]
    return rt
def gcd(x,y):
    if x%y==0:return y
    while x%y!=0:x,y=y,x%y
    return y
def show(*inp,end='\n'):
    if show_flg:print(*inp,end=end)

YN=['YES','NO'];Yn=['Yes','No']
mo=10**9+7
inf=float('inf')
FourNb=[(1,0),(-1,0),(0,1),(0,-1)];EightNb=[(1,0),(-1,0),(0,1),(0,-1),(1,1),(-1,-1),(1,-1),(-1,1)];compas=dict(zip('EWNS',FourNb))
l_alp=string.ascii_lowercase
#sys.setrecursionlimit(10**7)
input=lambda: sys.stdin.readline().rstrip()

class Tree:
    def __init__(self,inp_size=None,ls=None,init=True,index=0):
        self.LCA_init_stat=False
        self.ETtable=[]
        if init:
            if ls==None:
                self.stdin(inp_size,index=index)
            else:
                self.size=len(ls)+1
                self.edges,_=GI(self.size,self.size-1,ls,index=index)
        return

    def stdin(self,inp_size=None,index=1):
        if inp_size==None:
            self.size=int(input())
        else:
            self.size=inp_size
        self.edges,_=GI(self.size,self.size-1,index=index)
        return
    
    def listin(self,ls,index=0):
        self.size=len(ls)+1
        self.edges,_=GI(self.size,self.size-1,ls,index=index)
        return

    def __str__(self):
        return  str(self.edges)

    def dfs(self,x,func=lambda prv,nx,dist:prv+dist,root_v=0):
        q=deque()
        q.append(x)
        v=[-1]*self.size
        v[x]=root_v
        while q:
            c=q.pop()
            for nb,d in self.edges[c]:
                if v[nb]==-1:
                    q.append(nb)
                    v[nb]=func(v[c],nb,d)
        return v

    def EulerTour(self,x):
        q=deque()
        q.append(x)
        self.depth=[None]*self.size
        self.depth[x]=0
        self.ETtable=[]
        self.ETdepth=[]
        self.ETin=[-1]*self.size
        self.ETout=[-1]*self.size
        cnt=0
        while q:
            c=q.pop()
            if c<0:
                ce=~c
            else:
                ce=c
                for nb,d in self.edges[ce]:
                    if self.depth[nb]==None:
                        q.append(~ce)
                        q.append(nb)
                        self.depth[nb]=self.depth[ce]+1
            self.ETtable.append(ce)
            self.ETdepth.append(self.depth[ce])
            if self.ETin[ce]==-1:
                self.ETin[ce]=cnt
            else:
                self.ETout[ce]=cnt
            cnt+=1
        return
    
    def LCA_init(self,root):
        self.EulerTour(root)
        self.st=SparseTable(self.ETdepth,init_func=min,init_idl=inf)
        self.LCA_init_stat=True
        return
    
    def LCA(self,root,x,y):
        if self.LCA_init_stat==False:
            self.LCA_init(root)
        xin,xout=self.ETin[x],self.ETout[x]
        yin,yout=self.ETin[y],self.ETout[y]
        a=min(xin,yin)
        b=max(xout,yout,xin,yin)
        id_of_min_dep_in_et=self.st.query_id(a,b+1)
        return self.ETtable[id_of_min_dep_in_et]

class SparseTable: # O(N log N) for init, O(1) for query(l,r)
    def __init__(self,ls,init_func=min,init_idl=float('inf')):
        self.func=init_func
        self.idl=init_idl
        self.size=len(ls)
        self.N0=self.size.bit_length()
        self.table=[ls[:]]
        self.index=[list(range(self.size))]
        self.lg=[0]*(self.size+1)
        
        for i in range(2,self.size+1):
            self.lg[i]=self.lg[i>>1]+1

        for i in range(self.N0):
            tmp=[self.func(self.table[i][j],self.table[i][min(j+(1<<i),self.size-1)]) for j in range(self.size)]
            tmp_id=[self.index[i][j] if self.table[i][j]==self.func(self.table[i][j],self.table[i][min(j+(1<<i),self.size-1)]) else self.index[i][min(j+(1<<i),self.size-1)] for j in range(self.size)]
            self.table+=[tmp]
            self.index+=[tmp_id]
    
    # return func of [l,r)
    def query(self,l,r):
        if r>self.size:r=self.size
        #N=(r-l).bit_length()-1
        N=self.lg[r-l]
        return self.func(self.table[N][l],self.table[N][r-(1<<N)])
    
    # return index of which val[i] = func of v among [l,r)
    def query_id(self,l,r):
        if r>self.size:r=self.size
        #N=(r-l).bit_length()-1
        N=self.lg[r-l]
        a,b=self.index[N][l],self.index[N][r-(1<<N)]
        if self.table[0][a]==self.func(self.table[N][l],self.table[N][r-(1<<N)]):
            b=a
        return b
    
    def __str__(self):
        return str(self.table[0])

    def print(self):
        for i in self.table:
            print(*i)

class Comb:
    def __init__(self,n,mo=10**9+7):
        self.fac=[0]*(n+1)
        self.inv=[1]*(n+1)
        self.fac[0]=1
        self.fact(n)
        for i in range(1,n+1):
            self.fac[i]=i*self.fac[i-1]%mo
            self.inv[n]*=i
            self.inv[n]%=mo
        self.inv[n]=pow(self.inv[n],mo-2,mo)
        for i in range(1,n):
            self.inv[n-i]=self.inv[n-i+1]*(n-i+1)%mo
        return
    
    def fact(self,n):
        return self.fac[n]
        
    def invf(self,n):
        return self.inv[n]

    def comb(self,x,y):
        if y<0 or y>x:
            return 0
        return self.fac[x]*self.inv[x-y]*self.inv[y]%mo

show_flg=False
show_flg=True
ans=0

n=I()
a=LI()
a=[2]*n
tr=Tree(n,index=1)

for i in range(n):
    0#print()
    


ET=tr.EulerTour(0)
dp=[inf]*n

def update(x):
    idx=bisect.bisect_left(dp,x)
    y=dp[idx]
    dp[idx]=x
    return idx,x,y
    
ans=[-1]*n
q=deque()
scnd=10**10
pre=-1
d=tr.ETdepth
for node,depth in zip(tr.ETtable,d):
    
    if depth>pre:
        idx,x,y=update(a[node])
        q.append((idx,x,y))
        if ans[node]==-1:
            ans[node]=bisect.bisect(dp,scnd)
    else:
        idx,x,y=q.pop()
        dp[idx]=y
    pre=depth

for i in ans:
    print(i)

Submission status: Wrong Answer

Solution code:
import sys,bisect,string,math,time,functools,random,fractions
from heapq import heappush,heappop,heapify
from collections import deque,defaultdict,Counter
from itertools import permutations,combinations,groupby
def Golf():*a,=map(int,open(0))
def I():return int(input())
def S_():return input()
def IS():return input().split()
def LS():return [i for i in input().split()]
def LI():return [int(i) for i in input().split()]
def LI_():return [int(i)-1 for i in input().split()]
def NI(n):return [int(input()) for i in range(n)]
def NI_(n):return [int(input())-1 for i in range(n)]
def StoLI():return [ord(i)-97 for i in input()]
def ItoS(n):return chr(n+97)
def LtoS(ls):return ''.join([chr(i+97) for i in ls])
def GI(V,E,ls=None,Directed=False,index=1):
    org_inp=[];g=[[] for i in range(V)]
    FromStdin=True if ls==None else False
    for i in range(E):
        if FromStdin:
            inp=LI()
            org_inp.append(inp)
        else:
            inp=ls[i]
        if len(inp)==2:
            a,b=inp;c=1
        else:
            a,b,c=inp
        if index==1:a-=1;b-=1
        aa=(a,c);bb=(b,c);g[a].append(bb)
        if not Directed:g[b].append(aa)
    return g,org_inp
def GGI(h,w,search=None,replacement_of_found='.',mp_def={'#':1,'.':0},boundary=1):
#h,w,g,sg=GGI(h,w,search=['S','G'],replacement_of_found='.',mp_def={'#':1,'.':0},boundary=1) # sample usage
    mp=[boundary]*(w+2);found={}
    for i in range(h):
        s=input()
        for char in search:
            if char in s:
                found[char]=((i+1)*(w+2)+s.index(char)+1)
                mp_def[char]=mp_def[replacement_of_found]
        mp+=[boundary]+[mp_def[j] for j in s]+[boundary]
    mp+=[boundary]*(w+2)
    return h+2,w+2,mp,found
def TI(n):return GI(n,n-1)
def bit_combination(n,base=2):
    rt=[]
    for tb in range(base**n):s=[tb//(base**bt)%base for bt in range(n)];rt+=[s]
    return rt
def gcd(x,y):
    if x%y==0:return y
    while x%y!=0:x,y=y,x%y
    return y
def show(*inp,end='\n'):
    if show_flg:print(*inp,end=end)

YN=['YES','NO'];Yn=['Yes','No']
mo=10**9+7
inf=float('inf')
FourNb=[(1,0),(-1,0),(0,1),(0,-1)];EightNb=[(1,0),(-1,0),(0,1),(0,-1),(1,1),(-1,-1),(1,-1),(-1,1)];compas=dict(zip('EWNS',FourNb))
l_alp=string.ascii_lowercase
#sys.setrecursionlimit(10**7)
input=lambda: sys.stdin.readline().rstrip()

class Tree:
    def __init__(self,inp_size=None,ls=None,init=True,index=0):
        self.LCA_init_stat=False
        self.ETtable=[]
        if init:
            if ls==None:
                self.stdin(inp_size,index=index)
            else:
                self.size=len(ls)+1
                self.edges,_=GI(self.size,self.size-1,ls,index=index)
        return

    def stdin(self,inp_size=None,index=1):
        if inp_size==None:
            self.size=int(input())
        else:
            self.size=inp_size
        self.edges,_=GI(self.size,self.size-1,index=index)
        return
    
    def listin(self,ls,index=0):
        self.size=len(ls)+1
        self.edges,_=GI(self.size,self.size-1,ls,index=index)
        return

    def __str__(self):
        return  str(self.edges)

    def dfs(self,x,func=lambda prv,nx,dist:prv+dist,root_v=0):
        q=deque()
        q.append(x)
        v=[-1]*self.size
        v[x]=root_v
        while q:
            c=q.pop()
            for nb,d in self.edges[c]:
                if v[nb]==-1:
                    q.append(nb)
                    v[nb]=func(v[c],nb,d)
        return v

    def EulerTour(self,x):
        q=deque()
        q.append(x)
        self.depth=[None]*self.size
        self.depth[x]=0
        self.ETtable=[]
        self.ETdepth=[]
        self.ETin=[-1]*self.size
        self.ETout=[-1]*self.size
        cnt=0
        while q:
            c=q.pop()
            if c<0:
                ce=~c
            else:
                ce=c
                for nb,d in self.edges[ce]:
                    if self.depth[nb]==None:
                        q.append(~ce)
                        q.append(nb)
                        self.depth[nb]=self.depth[ce]+1
            self.ETtable.append(ce)
            self.ETdepth.append(self.depth[ce])
            if self.ETin[ce]==-1:
                self.ETin[ce]=cnt
            else:
                self.ETout[ce]=cnt
            cnt+=1
        return
    
    def LCA_init(self,root):
        self.EulerTour(root)
        self.st=SparseTable(self.ETdepth,init_func=min,init_idl=inf)
        self.LCA_init_stat=True
        return
    
    def LCA(self,root,x,y):
        if self.LCA_init_stat==False:
            self.LCA_init(root)
        xin,xout=self.ETin[x],self.ETout[x]
        yin,yout=self.ETin[y],self.ETout[y]
        a=min(xin,yin)
        b=max(xout,yout,xin,yin)
        id_of_min_dep_in_et=self.st.query_id(a,b+1)
        return self.ETtable[id_of_min_dep_in_et]

class SparseTable: # O(N log N) for init, O(1) for query(l,r)
    def __init__(self,ls,init_func=min,init_idl=float('inf')):
        self.func=init_func
        self.idl=init_idl
        self.size=len(ls)
        self.N0=self.size.bit_length()
        self.table=[ls[:]]
        self.index=[list(range(self.size))]
        self.lg=[0]*(self.size+1)
        
        for i in range(2,self.size+1):
            self.lg[i]=self.lg[i>>1]+1

        for i in range(self.N0):
            tmp=[self.func(self.table[i][j],self.table[i][min(j+(1<<i),self.size-1)]) for j in range(self.size)]
            tmp_id=[self.index[i][j] if self.table[i][j]==self.func(self.table[i][j],self.table[i][min(j+(1<<i),self.size-1)]) else self.index[i][min(j+(1<<i),self.size-1)] for j in range(self.size)]
            self.table+=[tmp]
            self.index+=[tmp_id]
    
    # return func of [l,r)
    def query(self,l,r):
        if r>self.size:r=self.size
        #N=(r-l).bit_length()-1
        N=self.lg[r-l]
        return self.func(self.table[N][l],self.table[N][r-(1<<N)])
    
    # return index of which val[i] = func of v among [l,r)
    def query_id(self,l,r):
        if r>self.size:r=self.size
        #N=(r-l).bit_length()-1
        N=self.lg[r-l]
        a,b=self.index[N][l],self.index[N][r-(1<<N)]
        if self.table[0][a]==self.func(self.table[N][l],self.table[N][r-(1<<N)]):
            b=a
        return b
    
    def __str__(self):
        return str(self.table[0])

    def print(self):
        for i in self.table:
            print(*i)

class Comb:
    def __init__(self,n,mo=10**9+7):
        self.fac=[0]*(n+1)
        self.inv=[1]*(n+1)
        self.fac[0]=1
        self.fact(n)
        for i in range(1,n+1):
            self.fac[i]=i*self.fac[i-1]%mo
            self.inv[n]*=i
            self.inv[n]%=mo
        self.inv[n]=pow(self.inv[n],mo-2,mo)
        for i in range(1,n):
            self.inv[n-i]=self.inv[n-i+1]*(n-i+1)%mo
        return
    
    def fact(self,n):
        return self.fac[n]
        
    def invf(self,n):
        return self.inv[n]

    def comb(self,x,y):
        if y<0 or y>x:
            return 0
        return self.fac[x]*self.inv[x-y]*self.inv[y]%mo

show_flg=False
show_flg=True
ans=0

n=I()
a=LI()
tr=Tree(n,index=1)

for i in range(n):
    0#print()
    


ET=tr.EulerTour(0)
dp=[inf]*n

def update(x):
    idx=bisect.bisect(dp,x)
    y=dp[idx]
    dp[idx]=x
    return idx,x,y
    
ans=[-1]*n
q=deque()
scnd=10**10
pre=-1
d=tr.ETdepth
for node,depth in zip(tr.ETtable,d):
    
    if depth>pre:
        idx,x,y=update(a[node])
        q.append((idx,x,y))
        if ans[node]==-1:
            ans[node]=bisect.bisect(dp,scnd)
    else:
        idx,x,y=q.pop()
        dp[idx]=y
    pre=depth

for i in ans:
    print(i)

Submission status: Wrong Answer

Solution code:
def old_combine(s1, s2):
    '''
    combine two scores
    s1, s2: [(last_v, cnt, comment), ...]
    return: same format
    '''
    w_set = set([_[0] for _ in s1])
    w_set = w_set.union([_[0] for _ in s2])
    w_set = list(w_set)
    w_set.sort()
    i1 = 0
    i2 = 0
    ret = []
    for w in w_set:
        while i1 + 1 < len(s1) and s1[i1 + 1][0] <= w:
            i1 += 1
        while i2 + 1 < len(s2) and s2[i2 + 1][0] <= w:
            i2 += 1
        if s1[i1][1] >= s2[i2][1]:
            val = s1[i1][1]
            com = s1[i1][2]
        else:
            val = s2[i2][1]
            com = s2[i2][2]
        if len(ret) >= 1 and ret[-1][1] >= val:
            continue
        ret.append((w, val, com))
    return ret

def combine(s1, s2):
    '''
    combine two scores
    s1, s2: [(last_v, cnt, comment), ...]
    return: same format
    '''
    len_s1 = len(s1)
    len_s2 = len(s2)
    i1 = 0
    i2 = 0
    ret = []
    while i1 < len_s1 and i2 < len_s2:
        if ret:
            while s1[i1][1] <= ret[-1][1]:
                i1 += 1
                if i1 == len_s1:
                    break
            while s2[i2][1] <= ret[-1][1]:
                i2 += 1
                if i2 == len_s2:
                    break
        if s1[i1][0] < s2[i2][0]:
            ret.append(s1[i1])
            i1 += 1
        elif s1[i1][0] > s2[i2][0]:
            ret.append(s2[i2])
            i2 += 1
        else: # s1[i1][0] == s2[i2][0]
            if s1[i1][1] >= s2[i2][1]:
                ret.append(s1[i1])
            else:
                ret.append(s2[i2])
            i1 += 1
            i2 += 1
    while i1 < len_s1:
        if ret:
            if s1[i1][1] > ret[-1][1]:
                ret.append(s1[i1])
        else:
            ret.append(s1[i1])
        i1 += 1
    while i2 < len_s2:
        if ret:
            if s2[i2][1] > ret[-1][1]:
                ret.append(s2[i2])
        else:
            ret.append(s2[i2])
        i2 += 1
    return ret



N = int(input())
A = [int(_) for _ in input().split()]

connection = [[] for _ in range(N + 1)]
for n in range(N - 1):
    u, v = (int(_) for _ in input().split())
    connection[u].append(v)
    connection[v].append(u)

parent = [None] * (N + 1)
child = [[] for _ in range(N + 1)]
stack = [1]
parent[0] = 0
parent[1] = 0
while stack:
    u = stack.pop()
    for v in connection[u]:
        if parent[v] is not None:
            continue
        parent[v] = u
        child[u].append(v)
        stack.append(v)

ret = [(0, 0, None)] * (N + 1)
ret[0] = [(0, 0, None)]
stack = [1]
while stack:
    i = stack.pop()
    #print('== {:} =='.format(i))
    score = ret[parent[i]]
    value = 1
    for _ in score:
        if _[0] >= A[i - 1]:
            break
        value = max(value, _[1] + 1)
    score_ = [(0, 0, None), (A[i - 1], value, None)]
    #print(score)
    #print(score_)
    ret[i] = combine(score, score_)
    stack += child[i]
    #print(ret[i])
    #print(ret[i][-1][1])

#print(ret)
#for i in range(1, N + 1):
    #print(ret[i][-1][1])
print('ok')

Submission status: Wrong Answer

Solution code:
def combine(s1, s2):
    '''
    combine two scores
    s1, s2: [(last_v, cnt, comment), ...]
    return: same format
    '''
    w_set = set([_[0] for _ in s1])
    w_set = w_set.union([_[0] for _ in s2])
    w_set = list(w_set)
    w_set.sort()
    i1 = 0
    i2 = 0
    ret = []
    for w in w_set:
        while i1 + 1 < len(s1) and s1[i1 + 1][0] <= w:
            i1 += 1
        while i2 + 1 < len(s2) and s2[i2 + 1][0] <= w:
            i2 += 1
        if s1[i1][1] >= s2[i2][1]:
            val = s1[i1][1]
            com = s1[i1][2]
        else:
            val = s2[i2][1]
            com = s2[i2][2]
        if len(ret) >= 1 and ret[-1][1] >= val:
            continue
        ret.append((w, val, com))
    return ret



N = int(input())
A = [int(_) for _ in input().split()]

parent = [0] * (N + 1)
for n in range(N - 1):
    u, v = (int(_) for _ in input().split())
    if u > v:
        u, v = v, u
    parent[v] = u

#print(parent)

ret = [(0, 0, None)] * (N + 1)
ret[0] = [(0, 0, None)]
for i in range(1, N + 1):
    #print('== {:} =='.format(i))
    score = ret[parent[i]]
    value = 1
    for _ in score:
        if _[0] >= A[i - 1]:
            break
        value = max(value, _[1] + 1)
    score_ = [(0, 0, None), (A[i - 1], value, None)]
    #print(score)
    #print(score_)
    ret[i] = combine(score, score_)
    #print(ret[i])
    print(ret[i][-1][1])

#print(ret)

Submission status: Wrong Answer

Solution code:
import collections
import bisect
import sys

sys.setrecursionlimit(10 ** 8)

def f(v):
    state[v] = 1
    a=As[v]
    idx = bisect.bisect_left(D,a)
    stack.append( (idx,D[idx]) ) # push
    D[idx] = a
    
    ans[v] = bisect.bisect_left(D,float('inf'))

    for u in V[v]:
        if state[u] == 0:
            f(u)

    # 巻き戻し
    i_pre,d_pre=stack.pop()
    D[i_pre] = d_pre



N=int(input())
As=list(map(int,input().split()))

D=[float('inf')]*(N+1)
stack=collections.deque([])
ans=[0]*N
state=[0]*N

V=[[] for _ in range(N)]
for _ in range(N-1):
    u,v=map(int,input().split())
    V[u-1].append(v-1)

f(0)

print(*ans,sep='\n')

Submission status: Wrong Answer

Solution code:
import collections
import bisect
import sys

sys.setrecursionlimit(10 ** 8)

def f(v):
    state[v] = 1
    a=As[v]
    idx = bisect.bisect_left(D,a)
    stack.append( (idx,D[idx]) ) # push
    D[idx] = a
    
    ans[v] = bisect.bisect_left(D,float('inf'))

    for u in V[v]:
        if state[u] == 0:
            f(u)

    # 巻き戻し
    i_pre,d_pre=stack.pop()
    D[i_pre] = d_pre



N=int(input())
As=list(map(int,input().split()))

D=[float('inf')]*N
stack=collections.deque([])
ans=[0]*N
state=[0]*N

V=[[] for _ in range(N)]
for _ in range(N-1):
    u,v=map(int,input().split())
    V[u-1].append(v-1)

f(0)

print(*ans,sep='\n')

Submission status: Wrong Answer

Solution code:
import collections
import bisect
import sys

sys.setrecursionlimit(10 ** 6)

def f(v):
    state[v] = 1
    a=As[v]
    idx = bisect.bisect_left(D,a)
    stack.append( (idx,D[idx]) ) # push
    D[idx] = a
    
    ans[v] = bisect.bisect_left(D,float('inf'))

    for u in V[v]:
        if state[u] == 0:
            f(u)

    # 巻き戻し
    i_pre,d_pre=stack.pop()
    D[i_pre] = d_pre



N=int(input())
As=list(map(int,input().split()))

D=[float('inf')]*N
stack=collections.deque([])
ans=[0]*N
state=[0]*N

V=[[] for _ in range(N)]
for _ in range(N-1):
    u,v=map(int,input().split())
    V[u-1].append(v-1)

f(0)

print(*ans,sep='\n')

Submission status: Wrong Answer

Solution code:
from collections import deque
from bisect import bisect_left

INF = 10**9 + 1
N = int(input())
A = list(map(int, input().split()))
G = [[] for i in range(N)]
for i in range(N-1):
    u, v = list(map(int, input().split()))
    if u > v:
        u, v = v, u
    G[u-1].append(v-1)
LIS = [INF] * N
ans = [0] * N

stack = deque()
stack.append((0, None, None)) # (current_node, prev_node, old_val)
while stack:
    c_node, p_node, old_val = stack.pop()

    if c_node == -1:
        LIS[p_node] = old_val
        continue

    a = A[c_node]
    idx = bisect_left(LIS, a)
    old_val = LIS[idx]
    LIS[idx] = a 
    
    ans[c_node] = bisect_left(LIS, INF)

    stack.append((-1, idx, old_val))

    for next_node in G[c_node]:
        stack.append((next_node, c_node, old_val))

print(*ans, sep="\n")

Submission status: Wrong Answer

Solution code:
from collections import deque
from bisect import bisect_left

INF = 10**9 + 1
N = int(input())
A = list(map(int, input().split()))
G = [[] for i in range(N)]
for i in range(N-1):
    u, v = list(map(int, input().split()))
    G[u-1].append(v-1)
LIS = [INF] * N
ans = [0] * N

stack = deque()
stack.append((0, None, None)) # (current_node, prev_node, old_val)
while stack:
    c_node, p_node, old_val = stack.pop()

    if c_node == -1:
        LIS[p_node] = old_val
        continue

    a = A[c_node]
    idx = bisect_left(LIS, a)
    old_val = LIS[idx]
    LIS[idx] = a 
    
    ans[c_node] = bisect_left(LIS, INF)

    stack.append((-1, idx, old_val))

    for next_node in G[c_node]:
        stack.append((next_node, c_node, old_val))

print(*ans, sep="\n")

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(10**6)
sr = lambda: sys.stdin.readline().rstrip()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))
from bisect import bisect_left
def resolve():
    N = ir()
    a = lr()
    tr = [[] for _ in range(N)]
    for i in range(N-1):
        u, v = lr()
        tr[u-1].append(v-1)
        tr[v-1].append(u-1)
    lis = [pow(10, 9)+1]*N
    lis[0] = a[0]
    prev_lis = [pow(10, 9)+1]*N
    vis = [0]*N
    vis[0] = 1
    ans = [0]*N
    ans[0] = 1
    def dfs(v):
        for u in tr[v]:
            if vis[u] == 0:
                vis[u] = 1
                idx = bisect_left(lis, a[u])
                prev_lis[u] = lis[idx]
                lis[idx] = a[u]
                ans[u] = idx+1
                dfs(u)
                lis[idx] = prev_lis[u]
    dfs(0)
    print(*ans, sep='\n')
resolve()

Submission status: Wrong Answer

Solution code:
import sys
import time

readline = sys.stdin.readline
MOD = 10 ** 9 + 7
INF = float('INF')
sys.setrecursionlimit(10**5)


def main():
    n = int(input())
    a = list(map(int, readline().split()))
    node = {i: [] for i in range(n)}

    for _ in range(n - 1):
        u, v = map(int, readline().split())
        u, v = u - 1, v - 1
        node[u].append(v)

    ans = [0] * n
    dp = [INF] * n
    dp[0] = a[0]

    from collections import deque
    import bisect

    def dfs(cur):
        nv = a[cur]
        index = bisect.bisect_left(dp, nv)
        pv = dp[index]
        dp[index] = nv
        suc = node[cur]

        for nx in suc:
            dfs(nx)

        ans[cur] = bisect.bisect_left(dp, INF)
        dp[index] = pv

    dfs(0)
    print(*ans, sep="\n")


if __name__ == '__main__':
    main()