Problem:


Score : 500 points

Problem Statement

You are given a tree with N vertices 1,2,\ldots,N, and positive integers c_1,c_2,\ldots,c_N.
The i-th edge in the tree (1 \leq i \leq N-1) connects Vertex a_i and Vertex b_i.

We will write a positive integer on each vertex in T and calculate our score as follows:

On each edge, write the smaller of the integers written on the two endpoints.

Let our score be the sum of the integers written on all the edges.

Find the maximum possible score when we write each of c_1,c_2,\ldots,c_N on one vertex in T, and show one way to achieve it. If an integer occurs multiple times in c_1,c_2,\ldots,c_N, we must use it that number of times.

Constraints

1 \leq N \leq 10000

1 \leq a_i,b_i \leq N

1 \leq c_i \leq 10^5

The given graph is a tree.

Input

Input is given from Standard Input in the following format:

N
a_1 b_1
:
a_{N-1} b_{N-1}
c_1 \ldots c_N

Output

Use the following format:

M
d_1 \ldots d_N

where M is the maximum possible score, and d_i is the integer to write on Vertex i.
d_1,d_2,\ldots,d_N must be a permutation of c_1,c_2,\ldots,c_N.
If there are multiple ways to achieve the maximum score, any of them will be accepted.

Sample Input 1

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

Sample Output 1

10
1 2 3 4 5

If we write 1,2,3,4,5 on Vertex 1,2,3,4,5, respectively, the integers written on the four edges will be 1,2,3,4, for the score of 10. This is the maximum possible score.

Sample Input 2

5
1 2
1 3
1 4
1 5
3141 59 26 53 59

Sample Output 2

197
59 26 3141 59 53

c_1,c_2,\ldots,c_N may not be pairwise distinct.



Sample input:
5
1 2
2 3
3 4
4 5
1 2 3 4 5


Sample output:
10
1 2 3 4 5

Submission status: Wrong Answer

Solution code:
import sys
def input(): return sys.stdin.readline().rstrip()
from collections import deque
def main():
    n=int(input())
    graph=[[]for _ in range(n)]
    for i in range(n-1):
        a,b=map(int,input().split())
        graph[a-1].append(b-1)
        graph[b-1].append(a-1)
    C=list(map(int,input().split()))
    C.sort(reverse=True)#頂点の値が大きい順に
    node_c=[0]*n #各頂点の値 0なら初めて
    node_c[0]=C[0]
    queue=deque([0])
    i=1
    while queue:
        node=queue.popleft()
        for xnode in graph[node]:
            if node_c[xnode]>0:continue
            node_c[xnode]=C[i]
            i+=1
            queue.append(xnode)
            print(i)
    print(sum(C[1:]))
    print(' '.join(map(str,node_c)))

if __name__=='__main__':
    main()

Submission status: Wrong Answer

Solution code:
import sys
def input(): return sys.stdin.readline().rstrip()
from collections import deque
def main():
    n=int(input())
    graph=[[]for _ in range(n)]
    for i in range(n-1):
        a,b=map(int,input().split())
        graph[a-1].append(b-1)
        graph[b-1].append(a-1)
    C=list(map(int,input().split()))
    C.sort(reverse=True)#頂点の値が大きい順に
    node_c=[0]*n #各頂点の値 0なら初めて
    node_c[0]=C[0]
    queue=deque([0])
    i=1
    while queue:
        node=queue.popleft()
        for xnode in graph[node]:
            if node_c[xnode]>0:continue
            node_c[xnode]=C[i]
            i+=1
            queue.append(xnode)
    print(sum(C[1:]))
    print(' '.join(map(str,C)))





if __name__=='__main__':
    main()

Submission status: Wrong Answer

Solution code:
import sys
def input(): return sys.stdin.readline().rstrip()
from operator import itemgetter
def main():
    n=int(input())
    graph=[[]for _ in range(n)]
    AB=[tuple(map(int,input().split())) for i in range(n-1)]
    for a,b in AB:
        graph[a-1].append(b-1)
        graph[b-1].append(a-1)
    C=list(map(int,input().split()))
    C.sort(reverse=True)
    node=[[i,0,0]for i in range(n)]#インデックス，隣接頂点数，c
    for i,g in enumerate(graph):
        node[i][1]=len(g)
    node.sort(key=itemgetter(1),reverse=True)
    for i in range(n):
        node[i][2]=C[i]
    node.sort()
    ans=0
    for i in range(n-1):
        a,b=AB[i]
        ans+=min(node[a-1][2],node[b-1][2])
    print(ans)
    print(' '.join(map(str,[x[2] for x in node])))





if __name__=='__main__':
    main()

Submission status: Wrong Answer

Solution code:
import sys
def input(): return sys.stdin.readline().rstrip()
from operator import itemgetter
def main():
    n=int(input())
    graph=[[]for _ in range(n)]
    AB=[tuple(map(int,input().split())) for i in range(n-1)]
    for a,b in AB:
        graph[a-1].append(b-1)
        graph[b-1].append(a-1)
    C=list(map(int,input().split()))
    C.sort()
    node=[[i,0,0]for i in range(n)]#インデックス，隣接頂点数，c
    for i,g in enumerate(graph):
        node[i][1]=len(g)
    node.sort(key=itemgetter(1))
    for i in range(n):
        node[i][2]=C[i]
    node.sort()
    ans=0
    for i in range(n-1):
        a,b=AB[i]
        ans+=min(node[a-1][2],node[b-1][2])
    print(ans)
    print(' '.join(map(str,[x[2] for x in node])))





if __name__=='__main__':
    main()

Submission status: Wrong Answer

Solution code:
N = int(input())
G = [[] for i in range(N)]
B = [[0, i] for i in range(N)]
c = [0 for i in range(N)]
d = [10** 5 for i in range(N)]
for i in range(N-1):
    a, b = map(int, input().split())
    a -= 1
    b -= 1
    G[a].append(b)
    B[a][0] += 1
    B[b][0] += 1
C = list(map(int, input().split()))
C = sorted(C, reverse=True)
B = sorted(B, reverse=True)
for i in range(N):
    d[B[i][1]] = C[i]
ans = 0
for i in range(N):
    for j in range(len(G[i])):
        ans += min(d[i], d[G[i][j]])

print(ans)
print(" ".join([str(i) for i in d]))

Submission status: Wrong Answer

Solution code:
# 16:37 - 
N = int(input())
D = [0]*N
T = [[] for i in range(N)]
for i in range(N-1):
    a,b = map(lambda x:int(x)-1,input().split())
    D[a]+=1
    D[b]+=1
    T[a].append(b)
    T[b].append(a)
C = list(map(int,input().split()))
C.sort()

D = [[D[i],i] for i in range(N)]
D.sort()
A = [0]*N
for i in range(N):
    A[D[i][1]] = C[i]
M = 0
Q = [[0,-1]]
while Q:
    v,p = Q.pop()
    for c in T[v]:
        if c!=p:
            M += min(A[v],A[c])
            Q.append([c,v])
print(M)
print(*A)

Submission status: Wrong Answer

Solution code:
n = int(input())
ab = [list(map(int,input().split())) for _ in range(n-1)]
c = list(map(int,input().split()))

c.sort(reverse = True)
edges = [[] for _ in range(n)]
ans = [-1]*n
ans[0] = c[0]
count = 1

for a,b in ab:
    edges[a-1].append(b-1)
    edges[b-1].append(b-1)

q = [0]

while q:
    l = q.pop(-1)
    for l1 in edges[l]:
        if ans[l1] == -1:
            q.append(l1)
            ans[l1] = c[count]
            count += 1

print(sum(c[1:]))
for i in ans:
    print(i, end = ' ')

Submission status: Wrong Answer

Solution code:
n = int(input())
ab = [list(map(int,input().split())) for _ in range(n-1)]
c = list(map(int,input().split()))

c.sort()
count = [0]*n
count2 = []

for a,b in ab:
    count[a-1] += 1
    count[b-1] += 1

for i in range(n):
    count2.append((count[i], i))

count2.sort()
ans = [-1]*n
tmp = 0

for i,j in count2:
    ans[j] = c[tmp]
    tmp += 1

ans_num = 0

for a,b in ab:
    ans_num += min(ans[a-1], ans[b-1])

print(ans_num)
for i in ans:
    print(i, end = ' ')

Submission status: Wrong Answer

Solution code:
from collections import Counter
from collections import deque
n = int(input())

counter = [0]*n
G = [[] for _ in range(n)]
for i in range(n-1):
  a,b = map(int,input().split())  
  G[a-1].append(b-1)
  G[b-1].append(a-1)
  counter[a-1] += 1
  counter[b-1] += 1
  
C = sorted(list(map(int,input().split())))[::-1]


root = 0
v = 0
for i in range(n):
  if v > counter[i]:
    root = i
    v = counter[i]


def bfs(s):
  que = deque()
  que.append(s)
  nodes = [-1]*n
  k = 0
  ans = 0
  while len(que)>0:    
    q = que.pop()    
    nodes[q] = C[k]
    if k!=0:
      ans += C[k]
    k += 1
    
    for v in G[q]:
      if nodes[v]<0:
        que.append(v)
        
  return ans
              
print(bfs(root))

Submission status: Wrong Answer

Solution code:
N = int(input())
cnt = dict()

nodes = [set() for _ in range(N+1)]

for _ in range(N-1):
    a, b = [int(x) for x in input().split()]
    cnt[a-1] = cnt.get(a-1,0) + 1
    cnt[b-1] = cnt.get(b-1,0) + 1
    nodes[a-1].add(b-1)
    nodes[b-1].add(a-1)


C = [int(x) for x in input().split()]
C = sorted(C, reverse=True)

Z = cnt.items()
Z = sorted(Z, key=lambda x:x[1], reverse=True)
# print(Z)

opennodes = {Z[0][0]}
closednodes = set()

ans = [-1] * N


for i in range(N):
    n = opennodes.pop()
    closednodes.add(n)
    ans[Z[i][0]] = C[i]

    for nn in nodes[n]:
        if not nn in closednodes:
            opennodes.add(nn)

print(sum(C) - max(C))
print(" ".join([str(x) for x in ans]))

Submission status: Wrong Answer

Solution code:
N = int(input())
cnt = dict()
for _ in range(N-1):
    a, b = [int(x) for x in input().split()]
    cnt[a] = cnt.get(a,0) + 1
    cnt[b] = cnt.get(b,0) + 1

C = [int(x) for x in input().split()]
C = sorted(C, reverse=True)

Z = cnt.items()
Z = sorted(Z, key=lambda x:x[1], reverse=True)
# print(Z)

ans = [-1] * N
for i in range(N):
    ans[Z[i][0]-1] = C[i]

print(sum(C) - max(C))
print(" ".join([str(x) for x in ans]))

Submission status: Wrong Answer

Solution code:
N = int(input())
# cnt = dict()
for _ in range(N-1):
    a, b = [int(x) for x in input().split()]
    # cnt[a] = cnt.get(a,0) + 1
    # cnt[b] = cnt.get(b,0) + 1

C = [int(x) for x in input().split()]
# C = sorted(C, reverse=True)

print(sum(C) - max(C))

# Z = cnt.items()
# Z = sorted(Z, key=lambda x:x[1], reverse=True)
# print(Z)

Submission status: Wrong Answer

Solution code:
n = int(input())

deg = [[0, i] for i in range(n)]

abl = []
for _ in range(n-1):
    a,b = map(int,input().split())
    deg[a-1][0] += 1
    deg[b-1][0] += 1
    abl.append((a-1, b-1))
deg = sorted(deg, key=lambda x:x[1])

cl = list(map(int,input().split()))
cl = sorted(cl, reverse=True)
ansl = [0 for _ in range(n)]
for d, c in zip(deg, cl):
    ansl[d[1]] = c

ans = 0
for a,b in abl:
    ans += min(ansl[a], ansl[b])


print(ans)
print(*ansl)

Submission status: Wrong Answer

Solution code:
n = int(input())

deg = [[0, i] for i in range(n)]

abl = []
for _ in range(n-1):
    a,b = map(int,input().split())
    deg[a-1][0] += 1
    deg[b-1][0] += 1
    abl.append((a-1, b-1))
deg = sorted(deg, reverse=False, key=lambda x:x[1])

cl = list(map(int,input().split()))

ansl = [0 for _ in range(n)]
for d, c in zip(deg, cl):
    ansl[d[1]] = c

ans = 0
for a,b in abl:
    ans += min(ansl[a], ansl[b])


print(ans)
print(*ansl)

Submission status: Wrong Answer

Solution code:
n = int(input())

deg = [[0, i] for i in range(n)]

abl = []
for _ in range(n-1):
    a,b = map(int,input().split())
    deg[a-1][0] += 1
    deg[b-1][0] += 1
    abl.append((a-1, b-1))
deg = sorted(deg, reverse=False)

cl = list(map(int,input().split()))

ansl = [0 for _ in range(n)]
for d, c in zip(deg, cl):
    ansl[d[1]] = c

ans = 0
for a,b in abl:
    ans += min(ansl[a], ansl[b])


print(ans)
print(*ansl)

Submission status: Wrong Answer

Solution code:
N = int(input())
V = [[] for _ in range(N)]
VC = [-1] * N
E = []

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

C = list(map(int, input().split()))
C.sort(reverse = True)
lst = []

for i in range(N):
    lst.append([i, len(V[i])])

lst.sort(key = lambda x : x[1], reverse = True)

for i in range(N):
    v = lst[i][0]
    VC[v] = C[i]

ans = 0

for a, b in E:
    ans += min(VC[a], VC[b])

print(ans)
print(*VC)

Submission status: Wrong Answer

Solution code:
import sys
from collections import deque

def solve():
    input = sys.stdin.readline
    N = int(input())
    Edge = [[] for _ in range(N)]
    for _ in range(N-1):
        a, b = map(int, input().split())
        Edge[a-1].append(b-1)
        Edge[b-1].append(a-1)
    C = [int(c) for c in input().split()]
    C.sort(reverse  = True)
    Color = [None] * N
    Color[0] = C[0]
    q = deque()
    for e in Edge[0]:
        q.append((e, 0))
    ans = 0
    for i in range(1, N):
        nowN, preN = q.popleft()
        ans += C[i]
        Color[i] = C[i]
        for e in Edge[nowN]:
            if e != preN: q.append((e, nowN))
    print(ans)
    print(" ".join(map(str, Color)))

    return 0

if __name__ == "__main__":
    solve()

Submission status: Wrong Answer

Solution code:
n = int(input())
link = [[] for _ in range(n)]
for i in range(n-1):
    a,b = list(map(int,input().split()))
    link[a-1].append(b-1)
    link[b-1].append(a-1)
c=list(map(int, input().split()))
c.sort(reverse=True)
print(sum(c)-c[-1])

from collections import deque
Q = deque()
Q.append(0)
visited=[-1]*n
visited[0]=0

ind=1
while Q:
    now = Q.popleft()
    for nxt in link[now]:
        if visited[nxt]!=-1:
            continue
        visited[nxt]=ind
        ind+=1
        Q.append(nxt)
for i in visited:
    print(c[i],end=" ")

Submission status: Wrong Answer

Solution code:
import sys
import math
import fractions
from collections import deque
from collections import defaultdict
sys.setrecursionlimit(10**7)

N = int(input())
graph = [[] for _ in range(N)]
for _ in range(N - 1):
    a, b = map(int, input().split())
    a -= 1
    b -= 1
    graph[a].append(b)
    graph[b].append(a)

c = list(map(int, input().split()))
c.sort(reverse=True)
sum_val = sum(c) - max(c)

assign = [0] * N
index = 0

q = deque()
q.append(0)
visited = []

while len(q) != 0:
    cur = q.popleft()
    print(cur, index)
    assign[cur] = c[index]
    index += 1
    for n in graph[cur]:
        if n not in visited:
            q.append(n)
    visited.append(cur)

print(sum_val)
print(" ".join(map(str, assign)))

Submission status: Wrong Answer

Solution code:
# 解説AC
from collections import deque

N = int(input())
edge = [[] for _ in range(N)]
for _ in range(N - 1):
    a,b = map(int, input().split())
    edge[a-1].append(b-1)
    edge[b-1].append(a-1)
C = [int(i) for i in input().split()]

C.sort()

M = sum(C) - C[0]
d = [-1] * N

que = deque([0])
while que:
    v = que.popleft()
    d[v] = C.pop()
    for w in edge[v]:
        if d[w] < 0:
            que.append(w)

print(M)
print(*d)

Submission status: Wrong Answer

Solution code:
# 解説AC
from collections import deque

N = int(input())
edge = [[] for _ in range(N)]
for _ in range(N - 1):
    a,b = map(int, input().split())
    edge[a-1].append(b-1)
    edge[b-1].append(a-1)
C = [int(i) for i in input().split()]

C.sort()

M = sum(C) - C[0]
d = [-1] * N

que = deque([0])
d[0] = C.pop()
while que:
    v = que.popleft()
    for w in edge[v]:
        if d[w] < 0:
            d[w] = C.pop()
            que.append(w)

print(M)
print(*d)

Submission status: Wrong Answer

Solution code:
N=int(input())
A=[[]for i in range(N)]
X=[list(map(int, input().split())) for _ in range(N-1)]
for i in range(N-1):
  a=X[i][0]
  b=X[i][1]
  a-=1
  b-=1
  A[a].append(b)
  A[b].append(a)
D=list(map(int, input().split()))
D=sorted(D)
B=[]
for i in range(N):
  B.append((len(A[i]),i))
B=sorted(B)
E=[0]*N
for i in range(N):
  E[B[i][1]]=D[i]
cnt=0
for i,j in X:
  cnt+=min(E[i-1],E[j-1])
print(cnt)
print(*E)

Submission status: Wrong Answer

Solution code:
#
# 　　  ⋀_⋀　 
#　　  (･ω･)  
# .／ Ｕ ∽ Ｕ＼
#  │＊　合　＊│
#  │＊　格　＊│ 
#  │＊　祈　＊│ 
#  │＊　願　＊│ 
#  │＊　　　＊│ 
#      ￣
#
import sys
sys.setrecursionlimit(10**6)
input=sys.stdin.readline
from math import floor,sqrt,factorial,hypot,log #log2ないｙｐ
from heapq import heappop, heappush, heappushpop
from collections import Counter,defaultdict,deque
from itertools import accumulate,permutations,combinations,product,combinations_with_replacement
from bisect import bisect_left,bisect_right
from copy import deepcopy
from fractions import gcd
from random import randint
def ceil(a,b): return (a+b-1)//b
inf=float('inf')
mod = 10**9+7
def pprint(*A): 
    for a in A:     print(*a,sep='\n')
def INT_(n): return int(n)-1
def MI(): return map(int,input().split())
def MF(): return map(float, input().split())
def MI_(): return map(INT_,input().split())
def LI(): return list(MI())
def LI_(): return [int(x) - 1 for x in input().split()]
def LF(): return list(MF())
def LIN(n:int): return [I() for _ in range(n)]
def LLIN(n: int): return [LI() for _ in range(n)]
def LLIN_(n: int): return [LI_() for _ in range(n)]
def LLI(): return [list(map(int, l.split() )) for l in input()]
def I(): return int(input())
def F(): return float(input())
def ST(): return input().replace('\n', '')
def main():
    N=I()
    indegree = [0]*N
    for _ in range(N-1):
        a,b = MI_()
        indegree[a] += 1
        indegree[b] += 1
    C=sorted(LI())
    index_ = sorted(range(N), key=lambda x: indegree[x])
    ans = [-1]*N
    for i,idx in enumerate(index_):
        ans[idx] = C[i]

    print(sum(C)-C[-1])
    print(*ans)
if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
from collections import Counter
import sys
sys.setrecursionlimit(10 ** 7)

N = int(input())
edges = [[] for _ in range(N)]

for _ in range(N - 1):
    fr, to = map(int, input().split())
    fr -= 1
    to -= 1
    edges[fr].append(to)
    edges[to].append(fr)

C = Counter(map(int, input().split()))

def dfs(now, pr, prev):
    ret = 0
    for to in edges:
        if to == pr:
            continue
        for c, n in C.items():
            if n == 0:
                continue
            C[c] -= 1
            ret = max(ret, dfs(to, now, c) + min(prev, c))
            C[c] += 1
    return ret

print(dfs(0, -1, 0))

Submission status: Wrong Answer

Solution code:
from operator import itemgetter
n=int(input())
d=dict()
edge=[[] for _ in range(n)]
for _ in range(n-1):
  a,b=map(int,input().split())
  a-=1
  b-=1
  edge[a].append(b)
  edge[b].append(a)
  if a not in d:
    d[a]=1
  else:
    d[a]+=1
  if b not in d:
    d[b]=1
  else:
    d[b]+=1
c=list(map(int,input().split()))
c.sort(reverse=True)
d=list(d.items())
d.sort(reverse=True,key=itemgetter(1))
ans=[-1]*n
i,s=0,0
for pa,cnt in d:
  if ans[pa]==-1:
    ans[pa]=c[i]
    i+=1
  for ch in edge[pa]:
    if ans[ch]==-1:
      ans[ch]=c[i]
      s+=c[i]
      i+=1
print(s)
print(*ans)
#print(d)

Submission status: Wrong Answer

Solution code:
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians
from itertools import accumulate, permutations, combinations, product
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left
from fractions import gcd
from heapq import heappush, heappop
from functools import reduce
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def ZIP(n): return zip(*(MAP() for _ in range(n)))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7

N = INT()
ab = [LIST() for _ in range(N-1)]
c = LIST()
c.sort()
tree = [[] for _ in range(N)]
for a, b in ab:
	tree[a-1].append(b-1)
	tree[b-1].append(a-1)

start=None
for i in range(N):
	if len(tree[i]) == 1:
		start = i
		break

ans = [0]*N
q = deque()
q.append(start)
ans[start] = c[0]
cnt = 1
while q:
	n = q.popleft()
	for node in tree[n]:
		if ans[node]:
			continue
		ans[node] = c[cnt]
		cnt += 1
		q.append(node)
print(sum(c)-max(c))
print(*ans)

Submission status: Wrong Answer

Solution code:
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians
from itertools import accumulate, permutations, combinations, product
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left
from fractions import gcd
from heapq import heappush, heappop
from functools import reduce
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def ZIP(n): return zip(*(MAP() for _ in range(n)))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7

N = INT()
ab = [LIST() for _ in range(N-1)]
c = LIST()
c.sort(reverse=True)
dim = [0]*N
for a, b in ab:
	dim[a-1] += 1
	dim[b-1] += 1
d = sorted([(i, x) for i, x in enumerate(dim)], key=lambda x:x[1], reverse=True)
ans = [0]*N
print(sum(c)-max(c))
for i in range(N):
	ans[d[i][0]] = c[i]
print(*ans)

Submission status: Wrong Answer

Solution code:
# G[v]: 頂点vに隣接する頂点list
# N: 頂点数

N = int(input())
from collections import defaultdict
G = defaultdict(list)

for _ in range(N-1):
    a,b = map(int,input().split())
    G[a-1].append(b-1)
    G[b-1].append(a-1)
cl = list(map(int,input().split()))
cl = sorted(cl, reverse=True)
for i in G:
    if len(G[i]) == 1:
        p = i
        break


from collections import deque
dist = [-1]*N
que = deque([p])
dist[p] = 0
while que:
    v = que.popleft()
    d = dist[v]
    for w in G[v]:
        if dist[w] > -1:
            continue
        dist[w] = d + 1
        que.append(w)


ansl = []
for idx, d in enumerate(dist):
    ansl.append((d, idx))
ansl = sorted(ansl)
ansl2 = [-1 for i in range(N)]
for k, (d, idx) in enumerate(ansl):
    ansl2[idx] = cl[k]
print(sum(cl[:-1]))
for i in ansl2:
    print(i)

Submission status: Wrong Answer

Solution code:
# G[v]: 頂点vに隣接する頂点list
# N: 頂点数

N = int(input())
from collections import defaultdict
G = defaultdict(list)

for _ in range(N-1):
    a,b = map(int,input().split())
    G[a-1].append(b-1)
    G[b-1].append(a-1)
cl = list(map(int,input().split()))
cl = sorted(cl)
for i in G:
    if len(G[i]) == 1:
        p = i
        break


from collections import deque
dist = [-1]*N
que = deque([p])
dist[p] = 0
while que:
    v = que.popleft()
    d = dist[v]
    for w in G[v]:
        if dist[w] > -1:
            continue
        dist[w] = d + 1
        que.append(w)

ansl = []
for idx, d in enumerate(dist):
    ansl.append((d, idx))
ansl = sorted(ansl)
ansl2 = [-1 for i in range(N)]
for k, (d, idx) in enumerate(ansl):
    ansl2[idx] = cl[k]
print(sum(cl[:-1]))
for i in ansl2:
    print(i)

Submission status: Wrong Answer

Solution code:
# G[v]: 頂点vに隣接する頂点list
# N: 頂点数

N = int(input())
from collections import defaultdict
G = defaultdict(list)

for _ in range(N-1):
    a,b = map(int,input().split())
    G[a-1].append(b-1)
    G[b-1].append(a-1)
cl = list(map(int,input().split()))
cl = sorted(cl)


from collections import deque
dist = [-1]*N
que = deque([0])
dist[0] = 0
while que:
    v = que.popleft()
    d = dist[v]
    for w in G[v]:
        if dist[w] > -1:
            continue
        dist[w] = d + 1
        que.append(w)

ansl = []
for idx, d in enumerate(dist):
    ansl.append((d, idx))
ansl = sorted(ansl)
ansl2 = [-1 for i in range(N)]
for k, (d, idx) in enumerate(ansl):
    ansl2[idx] = cl[k]
print(sum(cl[:-1]))
for i in ansl2:
    print(i)

Submission status: Wrong Answer

Solution code:
import queue
def main():
    n = int(input())
    g = [[] for _ in range(n)]
    for _ in range(n-1):
        a, b = map(int, input().split())
        g[a-1].append(b-1)
        g[b-1].append(a-1)
    c = list(map(int, input().split()))
    c.sort()
    ans = [None]*n
    a = [i for i in range(n)]
    a.sort(key=lambda x: len(g[x]))
    for i in range(n):
        ans[a[i]] = c[i]
    score = 0
    f = [True]*n
    f[0] = False
    q = queue.Queue()
    q.put(0)
    while not q.empty():
        target = q.get()
        for v in g[target]:
            if f[v]:
                f[v] = False
                score += min(ans[target], ans[v])
                q.put(v)
    print(score)
    for i in range(n):
        print(ans[i], end="")
        if i < n-1:
            print(" ",end="")
        else:
            print("")

if __name__ == "__main__":
    main()

Submission status: Wrong Answer

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

N = int(input())
edges = []
degree = [0] * (N+1)
for _ in range(N-1):
    a, b = map(int, input().split())
    edges.append((a, b))
    degree[a] += 1
    degree[b] += 1
c = [0] + list(map(int, input().split()))
c.sort()
degree = [(degree[i], i) for i in range(N+1)]
degree.sort()
num = [0] * (N+1)
for i in range(1, N+1):
    num[degree[i][1]] = c[i]
M = 0
for a, b in edges:
    M += min(num[a], num[b])
print(M)
print(' '.join(map(str, num[1:])))

Submission status: Wrong Answer

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

N = int(input())
edges = []
degree = [0] * (N+1)
for _ in range(N-1):
    a, b = map(int, input().split())
    edges.append((a, b))
    degree[a] += 1
    degree[b] += 1
c = [0] + list(map(int, input().split()))
degree = [(degree[i], i) for i in range(N+1)]
degree.sort()
num = [0] * (N+1)
for i in range(1, N+1):
    num[degree[i][1]] = c[i]
M = 0
for a, b in edges:
    M += min(num[a], num[b])
print(M)
print(' '.join(map(str, num[1:])))

Submission status: Wrong Answer

Solution code:
n=int(input())
d=[[0,i]for i in range(n)]
e=[]
for i in range(n-1):
  a,b=map(int,input().split())
  a-=1
  b-=1
  e.append([a,b])
  d[a][0]+=1
  d[b][0]+=1
c=list(map(int,input().split()))
c.sort()
d.sort()
ans=[0]*n
for i in range(n):
  ans[d[i][1]]=c[i]
m=0
for a,b in e:
  m+=min(ans[a],ans[b])
print(m)
print(*ans)

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(10**5)
n = int(input())
adjacent_list = [[i] for i in range(n+1)]
for i in range(n-1):
    a,b = map(int ,input().split())
    adjacent_list[a].append(b)
    adjacent_list[b].append(a)
c = list(map(int, input().split()))
c.sort(reverse=True)
k = sorted(adjacent_list,key = lambda x:len(x),reverse=True)
ans = 0
node_num = [-1 for i in range(n+1)]
index = 0
for i in range(n):
    node_num[k[i][0]] = c[i]
#print(node_num)
#現在、出次数が多い順にnodeに数字を振り分けた
finished = set()
def dfs(node):
    global ans
    finished.add(node)
    #print(node)
    for i in adjacent_list[node][1:]:
        #print("node:{} ad:{}".format(node, adjacent_list[node][1:]))
        if i not in finished:
            ans += min(node_num[i], node_num[node])
            dfs(i)
dfs(1)
print(ans)
for i in range(1,n+1):
    print(node_num[i], end=" ")

Submission status: Wrong Answer

Solution code:
N = int(input())
cnt = [0] * N
for _ in range(N-1):
    a, b = map(int, input().split())
    a -= 1
    b -= 1
    cnt[a] += 1
    cnt[b] += 1
C = list(map(int, input().split()))
C.sort()
indices = []
for i, c in enumerate(cnt):
    indices.append((c, i))
indices.sort()
ans = [0] * N
for i, c in zip(indices, C):
    ans[i[1]] = c
print(*ans)

Submission status: Wrong Answer

Solution code:
import sys
from collections import deque
n = int(input())
graph = {i : [] for i in range(n)}
for i in range(n-1):
    a, b = [int(i) for i in sys.stdin.readline().split()]
    a -= 1
    b -= 1
    graph[a].append(b)
    graph[b].append(a)
c_ls = [int(i) for i in sys.stdin.readline().split()]
c_ls.sort(reverse=True)
costs = [0 for i in range(n)]
que = deque([0])
already = {0}
i = 0
while len(que) > 0:
    cur = que.popleft()
    costs[cur] = c_ls[i]
    i += 1
    for _next in graph[cur]:
        if _next not in already:
            que.append(_next)
            already.add(_next)
print(" ".join([str(i) for i in costs]))

Submission status: Wrong Answer

Solution code:
N = int(input())
T = [[] for _ in range(N)]
E = []
for i in range(N-1):
    a, b = map(int, input().split())
    T[a-1].append([i, b-1])
    T[b-1].append([i, a-1])
    E.append([a-1, b-1])
C = list(map(int, input().split()))
C.sort()
J = [[i] for i in range(N)]
for i in range(N):
    J[i].append(len(T[i]))
J.sort(key=lambda x: x[1])
res = [-1 for _ in range(N)]
tc = 0
for i in range(N):
    v = J[i][0]
    res[v] = C[i]
M = 0
for i in range(N-1):
    M += min(res[E[i][0]], res[E[i][1]])
print(M)
print(" ".join(map(str, res)))

Submission status: Wrong Answer

Solution code:
n = int(input())
T = [[] for _ in range(n)]
for _ in range(n-1):
  a, b = map(int, input().split())
  a -= 1
  b -= 1
  T[a].append(b)
  T[b].append(a)
C = sorted(map(int, input().split()), reverse=True)
print(sum(C[1:]))
L = [-1]*n
L[0] = C[0]
L[T[0][0]] = C[1]
used = [0, T[0][0]]
for i in range(2, n):
  for v in used:
    for nv in T[v]:
      if L[nv] == -1:
        L[nv] = C[i]
        break
    else:
      continue
    break
print(*L)

Submission status: Wrong Answer

Solution code:
n = int(input())
T = [[] for _ in range(n)]
C = [0]*n
for _ in range(n-1):
  a, b = map(int, input().split())
  a -= 1
  b -= 1
  T[a].append(b)
  T[b].append(a)
  C[a] += 1
  C[b] += 1
L = sorted([(j, i) for i, j in enumerate(C)], reverse=True)
B = sorted(map(int, input().split()))
K = [0]*n
ans = 0
for s, edge in L:
  K[edge] = B.pop()
  for v in T[edge]:
    if K[v]:
      ans += min(K[edge], K[v])
print(ans)
print(*K)

Submission status: Wrong Answer

Solution code:
import sys
from collections import defaultdict as dd
from collections import deque as dq
input = sys.stdin.readline
N = int(input())
e = dd(list)
inc = [0] * (N + 1)
for _ in range(N - 1):
  u, v = map(int, input().split())
  e[u].append(v)
  e[v].append(u)
  inc[u] += 1
  inc[v] += 1
x = 0
for i in range(1, N + 1):
  if inc[x] < inc[i]: x = i

c = list(map(int, input().split()))
vis = set()
vis.add(x)
t = [x]
Q = dq([x])
while len(Q):
  y = Q.popleft()
  for z in e[y]:
    if z in vis: continue
    t.append(z)
    vis.add(z)
    Q.append(z)

res = [0] * N
c.sort(reverse = True)
for i in range(N): res[i] = c[i]
print(sum(c[1: ]))
print(*res)

Submission status: Wrong Answer

Solution code:
import sys
from collections import defaultdict as dd
input = sys.stdin.readline
sys.setrecursionlimit(10 ** 6)
N = int(input())
e = dd(list)
inc = [0] * (N + 1)
for _ in range(N - 1):
  u, v = map(int, input().split())
  e[u].append(v)
  e[v].append(u)
  inc[u] += 1
  inc[v] += 1
x = 0
for i in range(1, N + 1):
  if inc[x] < inc[i]: x = i

c = list(map(int, input().split()))
vis = set()
t = [x]
def dfs(y):
  global vis
  global t
  for z in e[y]:
    if z in vis: continue
    t.append(z)
    vis.add(z)
    dfs(z)
vis.add(x)
dfs(x)
res = [0] * N
c.sort(reverse = True)
for i in range(N): res[i] = c[i]
print(sum(c[1: ]))
print(*res)

Submission status: Wrong Answer

Solution code:
n = int(input())
ab = [list(map(int, input().split())) for _ in range(n-1)]
c = list(map(int,input().split()))

edge_num = [0] * (n+1)
edge = {}
for i in range(1,n+1):
    edge[i] = set()

for a,b in ab:
    edge_num[a] += 1
    edge_num[b] += 1
    edge[a].add(b)
    edge[b].add(a)

edge_num2 = {}
for i in range(max(edge_num) + 1):
    edge_num2[i] = set()

for i in range(1,n+1):
    edge_num2[edge_num[i]].add(i)

c.sort()
c_num = 0
ans = [0] * (n+1)
while(len(edge_num2[1]) > 0):
    tmp = edge_num2[1].pop()
    ans[tmp] = c[c_num]
    c_num += 1

    neigh = edge[tmp].pop()
    edge_num2[edge_num[neigh]].discard(neigh)
    edge_num[neigh] -= 1
    edge_num2[edge_num[neigh]].add(neigh)
    if(edge_num[neigh] == 0):
        ans[neigh] = c[c_num]
        break

print(sum(c) - max(c))
print(' '.join(map(str, ans[1:])))

Submission status: Wrong Answer

Solution code:
n = int(input())
ab = [list(map(int,input().split())) for _ in range(n-1)]
c = list(map(int, input().split()))

edge_num = [ [0,0] for _ in range(n)]

for i in range(n):
    edge_num[i][1] = i

for a,b in ab:
    edge_num[a-1][0] += 1
    edge_num[b-1][0] += 1

edge_num = sorted(edge_num)
c = sorted(c)

ans = [ [0,0] for _ in range(n)]
for i in range(n):
    ans[i][0] = edge_num[i][1]
    ans[i][1] = c[i]
    
ans = sorted(ans)
    
ans_sum = 0
for a,b in ab:
    ans_sum += min(ans[a-1][1], ans[b-1][1])
    
print(ans_sum)
print(' '.join(map(lambda x : str(x[1]), ans)))