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: Accepted

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[:-1])
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: Accepted

Solution code:
from collections import deque
N=int(input())
tree=[[] for _ in range(N)]
tree2=[]
for i in range(N-1):
    a,b=map(int,input().split())
    tree[a-1].append(b-1)
    tree[b-1].append(a-1)
    tree2.append([a-1,b-1])
score=list(map(int,input().split()))
score.sort(reverse=True)
#print(tree,tree2,score)
v=0
d=deque()
seen=[0]*N
d.append(v)
ans=[]
l=[0]*N
s=0
while len(ans)!=N:
    v=d.popleft()
    seen[v]=1
    ans.append(v)
    for j in tree[v]:
        if seen[j]!=1:
            d.append(j)
    #print(ans,seen)
    #input()
for i in range(N):
    l[ans[i]]=score[i]
#print(l)
for i in range(N-1):
    s=s+min(l[tree2[i][0]],l[tree2[i][1]])
print(s)
print(*l,sep=" ")

Submission status: Accepted

Solution code:
import sys 
sys.setrecursionlimit(10**6)
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)[::-1]
from collections import deque
d=deque(D)
E=[-1]*N
def f(now,pre):
  for i in A[now]:
    if i!=pre and E[i]==-1:
      E[i]=d.popleft()
      f(i,now)
E[0]=d.popleft()
f(0,0)
print(sum(D[1:]))
print(*E)

Submission status: Accepted

Solution code:
from collections import deque
N = int(input())
es = [[] for i in range(N)]
for i in range(N-1):
    a, b = map(lambda x: int(x)-1, input().split())
    es[a].append(b)
    es[b].append(a)
c = list(map(int, input().split()))
c.sort(reverse=1)
q = deque()
q.append(0)
flg = [0]*N
num = [None]*N
i = 0
while len(q):
    v = q.popleft()
    flg[v] = 1
    num[v] = c[i]
    i += 1
    for u in es[v]:
        if flg[u]:
            continue
        q.append(u)
print(sum(c[1:]))
print(*num)

Submission status: Accepted

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()
    edge = [[] for _ in range(N)]
    indegree = [0]*N
    for _ in range(N-1):
        a,b = MI_()
        indegree[a] += 1
        indegree[b] += 1
        edge[a].append(b)
        edge[b].append(a)

    ans = [-1]*N
    s = []
    for i in range(N):
        if(indegree[i]==1):
            s.append(i)  
    C = sorted(LI(), reverse=True)
    ans_sum = sum(C)-C[0]
    while(s):
        v = s.pop()
        ans[v] = C.pop()
        for to in edge[v]:
            indegree[to]-=1
            if(indegree[to] == 1):
                s.append(to)

    print(ans_sum)
    print(*ans)
if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
import sys, math, itertools, collections, bisect
input = lambda: sys.stdin.buffer.readline().rstrip().decode('utf-8')
inf = float('inf') ;mod = 10**9+7
mans = inf ;ans = 0 ;count = 0 ;pro = 1

n = int(input())
G = [[] 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)
  G[b].append(a)
C = list(map(int,input().split()))
C.sort(reverse = True)
ans = [0]*n
ans[0] = C[0]
que = collections.deque([0])
i = 1
M = 0
while que:
  node = que.popleft()
  for vi in G[node]:
    if ans[vi] == 0:
      ans[vi] = C[i]
      i += 1
      que.append(vi)
      M += min(ans[vi],ans[node])
print(M)
print(*ans)

Submission status: Accepted

Solution code:
from collections import deque


n = int(input())
info = [list(map(int, input().split())) for i in range(n - 1)]
c = list(map(int, input().split()))
c = sorted(c, reverse=True)

tree = [[] for i in range(n)]
cnt = [0] * n
for i in range(n - 1):
    a, b = info[i]
    a -= 1
    b -= 1
    tree[a].append(b)
    tree[b].append(a)
    cnt[a] += 1
    cnt[b] += 1

for i in range(n):
    if len(tree[i]) == 1:
        root = i
        break
        
q = deque([root])
visited = [False] * n
visited[root] = True
ind = 0
ans = 0
res = [0] * n
while q:
    v= q.pop()
    tmp_cnt = 0
    for nxt_v in tree[v]:
        if visited[nxt_v]:
            tmp_cnt += 1
    ans += c[ind] * tmp_cnt
    res[v] = c[ind]
    ind += 1
    for nxt_v in tree[v]:
        if visited[nxt_v]:
            continue
        visited[nxt_v] = True
        q.append(nxt_v)
    
print(ans)
print(*res)

Submission status: Accepted

Solution code:
n = int(input())
g = [[] for _ in range(n)]
for i in range(n-1):
    a, b = map(int, input().split())
    a, b = a-1, b-1
    g[a].append(b)
    g[b].append(a)

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

order = []
par = [-1]*n
s = []
visit = [-1]*n
s.append(0)
visit[0] = 0
while s:
    v = s.pop()
    order.append(v)
    for u in g[v]:
        if u == par[v]:
            continue
        par[u] = v
        s.append(u)

order.reverse()
ans = [0]*n
m = 0
for v in order:
    ans[v] = C.pop()
    if par[v] != -1:
        m += ans[v]
print(m)
print(*ans)

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10**8)
N = int(input())
AB = [tuple(map(int,input().split())) for i in range(N-1)]
C = list(map(int,input().split()))
C.sort()
es = [[] for i in range(N)]
for a,b in AB:
    a,b = a-1,b-1
    es[a].append(b)
    es[b].append(a)

score = 0
vscore = [-1]*N
vscore[0] = C.pop()

def dfs(v,p=-1):
    global score
    for to in es[v]:
        if to==p: continue
        vscore[to] = C.pop()
        score += min(vscore[v], vscore[to])
        dfs(to,v)
dfs(0)

print(score)
print(*vscore)

Submission status: Accepted

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)

A = list(map(int, input().split()))
A.sort()
S = sum(A) - A[-1]

print(S)

ans = [0] * N
st = [(0, -1)]
while st:
    now, pr = st.pop()
    ans[now] = A.pop()
    for to in edges[now]:
        if to == pr:
            continue
        st.append((to, now))
print(*ans)

Submission status: Accepted

Solution code:
import sys
from collections import defaultdict as dd
input = sys.stdin.readline
sys.setrecursionlimit(10 ** 6)
N = int(input())
e = dd(list)
for _ in range(N - 1):
  u, v = map(int, input().split())
  e[u].append(v)
  e[v].append(u)
c = list(map(int, input().split()))
c.sort()
sm = sum(c) - c[-1]
res = [0] * (N + 1)
def dfs(x):
  global res
  res[x] = c.pop()
  for y in e[x]:
    if res[y]: continue
    dfs(y)
dfs(1)
print(sm)
print(*res[1: ])

Submission status: Accepted

Solution code:
from collections import deque
class UnionFind:
    """
        n : 要素数
        root : 親ノード
        size : グループのサイズ
    """
    
    def __init__(self, n):
        self.n = n
        self.root = [-1]*(n+1)
        self.size = [1]*(n+1)
    
    """ノードxのrootノードを見つける"""
    def Find_Root(self, x):
        if self.root[x] < 0:
            return x
        else:
            self.root[x] = self.Find_Root(self.root[x])
            return self.root[x]
    
    """木の合併"""
    def Union(self, x, y):
        #入力ノードの親を探索
        x = self.Find_Root(x)
        y = self.Find_Root(y)
        
        #既に同じ木に所属する場合
        if x==y:
            return 
        
        #異なる木に所属する場合 -> sizeが小さい方から大きい方に合併する
        elif self.size[x] > self.size[y]:
            self.size[x] += self.size[y]
            self.root[y] = x
        
        else:
            self.size[y] += self.size[x]
            self.root[x] = y

n = int(input())
uf = UnionFind(n)
G = [[] for _ in range(n+1)]
for _ in range(n-1):
    a,b = map(int,input().split())
    uf.Union(a,b)
    G[a].append(b)
    G[b].append(a)
rt = uf.root.index(-1)
for idx in range(1, n+1):
    if uf.root[idx] == -1:
        rt = idx-1
        break

c = list(map(int,input().split()))
c.sort(reverse=True)
c = [0] + c
ans = [0]*(n+1)
que = deque([rt])
idx = 1

while que:
    node = que.popleft()
    if ans[node]!=0:
        continue
    else:
        ans[node] = c[idx]
        idx += 1
        for g in G[node]:
            que.append(g)
print(sum(c)-max(c))
print(*ans[1:])

Submission status: Accepted

Solution code:
from collections import deque

n = int(input())
g = [[] for _ in range(n)]
for _ in range(n-1):
    a, b = map(int, input().split())
    a -= 1; b -= 1
    g[a].append(b)
    g[b].append(a)
c = list(map(int, input().split()))
c.sort()
m = sum(c[:-1])
ans = [-1] * n

q = deque([(0, -1)])
while q:
    v, pv = q.popleft()
    ans[v] = c.pop()
    for nv in g[v]:
        if nv == pv: continue
        q.append((nv, v))

print(m)
print(*ans)

Submission status: Accepted

Solution code:
from collections import deque
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)
c=list(map(int,input().split()))
c.sort(reverse=True)
visited=[-1]*n
def bfs(s):
  i=0
  q=deque([s])
  visited[s]=c[i]
  while q:
    x=q.popleft()
    for nx in edge[x]:
      if visited[nx]==-1:
        i+=1
        visited[nx]=c[i]
        q.append(nx)
  return
bfs(0)
print(sum(c)-max(c))
print(*visited)

Submission status: Accepted

Solution code:
import heapq as h

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

c=list(map(int,input().split()))
c.sort(reverse=True)

ans=[-1 for i in range(0,N)]

q=[]
q.append(0)
h.heapify(q)
sub=[]
h.heapify(sub)
count=0
while q!=[]:
    while q!=[]:
        x=h.heappop(q)
        ans[x]=c[count]
        count+=1
        for p in hen[x]:
            if ans[p]==-1:
                h.heappush(sub,p)
        #何らかの操作
        #ここでsubキューに次に使うものを格納
        if q==[]:
            q=sub
            sub=[]
            h.heapify(sub)
            break

print(sum(c)-c[0])
print(*ans)

Submission status: Accepted

Solution code:
n = int(input())
graph = [[] for i 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)
L = list(map(int,input().split()))
L.sort()
used = [0]*n
ans = [0]*n
used[0] = 1
ans[0] = L[n-1]
next = graph[0]
cur = n-2
while len(next) > 0:
    t = next.pop()
    ans[t] = L[cur]
    cur -= 1
    used[t] = 1
    for i in range(len(graph[t])):
        if used[graph[t][i]] != 1:
            next.append(graph[t][i])
print(sum(L)-L[n-1])
print(' '.join(map(str,ans)))

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
import sys, math, itertools, collections, bisect
input = lambda: sys.stdin.buffer.readline().rstrip().decode('utf-8')
inf = float('inf') ;mod = 10**9+7
mans = inf ;ans = 0 ;count = 0 ;pro = 1

n = int(input())
G = [[] for i in range(n)]
F = [-1]*n
AB = []
for i in range(n-1):
  a,b = map(int,input().split())
  a-=1;b-=1
  G[a].append(b)
  G[b].append(a)
  AB.append((a,b))
C = sorted(map(int,input().split()),reverse = True)
for i in range(n):
  G[i].sort(key = lambda x:len(G[x]))
m = max(range(n),key = lambda x: len(G[x]))
count = 1
que = collections.deque()
que.append(m)
F[m] = C[0]
while que:
  node = que.popleft()
  for vi in G[node]:
    if F[vi] != -1: continue
    F[vi] = C[count]
    count += 1
    que.append(vi)

for a,b in AB:
  ans += min(F[a],F[b])
print(ans)
print(*F)
# print(C)

Submission status: Accepted

Solution code:
from collections import deque

n = int(input())
Adj_dict = {x:[] for x in range(1, n+1)}

for _ in range(n-1):
    a, b = map(int, input().split())
    Adj_dict[a].append(b)
    Adj_dict[b].append(a)
C = list(map(int, input().split()))
C = sorted(C, reverse=True)
dq_C = deque(C)

max_node = 0
max_edge_count = 0
for i in range(1,n+1):
    if len(Adj_dict[i]) >= max_edge_count:
        max_edge_count = len(Adj_dict[i])
        max_node = i

dq = deque()
dq.append(max_node)

Visited = [-1 for _ in range(n+1)]
Visited[max_node] = dq_C.popleft()
ans = 0

while dq:
    node = dq.popleft()
    Adjs = Adj_dict[node]
    for next_node in Adjs:
        if Visited[next_node] != -1:
            continue
        dq.append(next_node)
        Visited[next_node] = dq_C.popleft()
        ans += Visited[next_node]

print(ans)
print(' '.join(map(str, Visited[1:])))

Submission status: Accepted

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)
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(0)
ans[0] = 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: Accepted

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)
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: Accepted

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(reverse=True)
    ans = [None]*n
    a = [i for i in range(n)]
    a.sort(key=lambda x: len(g[x]), reverse=True)
    f = [True]*n
    f[a[0]] = False
    q = queue.Queue()
    q.put(a[0])
    ans[a[0]] = c[0]
    x = 1
    while not q.empty():
        target = q.get()
        for v in g[target]:
            if f[v]:
                f[v] = False
                ans[v] = c[x]
                q.put(v)
                x += 1
    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: Accepted

Solution code:
from heapq import heappush, heappop
import sys
input = sys.stdin.readline

N = int(input())
G = [[] for _ in range(N+1)]
degree = [0] * (N+1)
for _ in range(N-1):
    a, b = map(int, input().split())
    G[a].append(b)
    G[b].append(a)
    degree[a] += 1
    degree[b] += 1
c = list(map(int, input().split()))
c.sort(reverse=True)

heap = []
for i in range(1, N+1):
    heappush(heap, (degree[i], i))

M = 0
num = [0] * (N+1)
while heap:
    d, i = heappop(heap)
    if num[i] != 0:
        continue
    num[i] = c.pop()
    for j in G[i]:
        if num[j] == 0:
            M += num[i]
            degree[i] -= 1
            degree[j] -= 1
            heappush(heap, (degree[j], j))
print(M)
print(' '.join(map(str, num[1:])))

Submission status: Accepted

Solution code:
import sys

sys.setrecursionlimit(10 ** 9 + 7)

N = int(input())
visited = [False] * N
edges = [[] for _ in range(N)]
AB = []
for _ in range(N-1):
    a, b = map(int, input().split())
    a -= 1
    b -= 1
    AB.append((a, b))
    edges[a].append(b)
    edges[b].append(a)
C = list(map(int, input().split()))
C.sort(reverse=True)
scores = [-1] * N
i = 0

def dfs(v):
    if visited[v]:
        return

    visited[v] = True
    global i
    scores[v] = C[i]
    i += 1
    for e in edges[v]:
        if visited[e]:
            continue

        dfs(e)

dfs(0)

total = 0
for a, b in AB:
    total += min(scores[a], scores[b])
print(total)
print(*scores)

Submission status: Accepted

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(sum(c_ls[1:]))
print(" ".join([str(i) for i in costs]))

Submission status: Accepted

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

C.sort(reverse=True)
M = sum(C) - C[0]

from collections import deque
q = deque([0])
ans = [0]*N
ans[0] = C[0]
i = 1
while q:
    u = q.popleft()
    for v in E[u]:
        if ans[v] > 0:
            continue
        ans[v] = C[i]
        i += 1
        q.append(v)

print(M)
print(*ans)

Submission status: Accepted

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()))
print(sum(C[:-1]))
L = [-1]*n
stack = [0]
while stack:
  temp = stack.pop()
  L[temp] = C.pop()
  for v in T[temp]:
    if L[v] == -1:
      stack.append(v)
print(*L)

Submission status: Accepted

Solution code:
import sys

read = sys.stdin.read
readline = sys.stdin.readline

N, *abc = map(int, read().split())
c = abc[2 * (N - 1):]
c.sort()
graph = [[] for _ in range(N + 1)]
for a, b in zip(*[iter(abc[:2 * (N - 1)])] * 2):
    graph[a].append(b)
    graph[b].append(a)

nodes = [0] * (N + 1)
score = sum(c) - c[-1]
start = 1
nodes[start] = c.pop()
queue = [start]
while queue:
    V = queue.pop()
    for v in graph[V]:
        if nodes[v] == 0:
            nodes[v] = c.pop()
            queue.append(v)

print(score)
print(' '.join(map(str, nodes[1:])))

Submission status: Accepted

Solution code:
import sys
from collections import deque

read = sys.stdin.read
readline = sys.stdin.readline

N, *abc = map(int, read().split())
c = abc[2 * (N - 1):]
c.sort()
graph = [[] for _ in range(N + 1)]
cnt = [0] * (N + 1)
for a, b in zip(*[iter(abc[:2 * (N - 1)])] * 2):
    graph[a].append(b)
    graph[b].append(a)

m = max(cnt)
nodes = [0] * (N + 1)
score = sum(c) - c[-1]
start = 1
nodes[start] = c.pop()
queue = deque([start])
while queue:
    V = queue.popleft()
    for v in graph[V]:
        if nodes[v] == 0:
            nodes[v] = c.pop()
            queue.append(v)

print(score)
print(' '.join(map(str, nodes[1:])))

Submission status: Accepted

Solution code:
import sys
from collections import deque

read = sys.stdin.read
readline = sys.stdin.readline

N, *abc = map(int, read().split())
c = abc[2 * (N - 1):]
c.sort()
graph = [[] for _ in range(N + 1)]
cnt = [0] * (N + 1)
for a, b in zip(*[iter(abc[:2 * (N - 1)])] * 2):
    graph[a].append(b)
    graph[b].append(a)
    cnt[a] += 1
    cnt[b] += 1

m = max(cnt)
nodes = [0] * (N + 1)
score = sum(c) - c[-1]
start = cnt.index(max(cnt))
nodes[start] = c.pop()
queue = deque([start])
while queue:
    V = queue.popleft()
    for v in graph[V]:
        if nodes[v] == 0:
            nodes[v] = c.pop()
            queue.append(v)

print(score)
print(' '.join(map(str, nodes[1:])))

Submission status: Accepted

Solution code:
# coding: utf-8
# Your code here!
from collections import deque

def bfs(num):
    if visited[num]==0:
        visited[num]=C.pop(-1)
        for item in way[num]:
            d.append(item)
    return

N=int(input())

ans=[-1]*N
way=[[]for i in range(N)]
visited=[0]*N

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

C=list(map(int,input().split()))
C.sort()
#print(C)


d=deque([0])

while d:
    temp=d.popleft()
    if visited[temp]==0:
        bfs(temp)

ans=0
for i in range(N):
    for item in way[i]:
        ans+=min(visited[i],visited[item])

print(ans//2)
print(*visited)

Submission status: Accepted

Solution code:
import sys
from collections import defaultdict as dd
import heapq
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()))
c.sort()
ressum = sum(c[: -1])
vis = set()
res = [0] * (N + 1)
res[x] = c[-1]
def dfs(y):
  global vis
  global res
  global c
  res[y] = c.pop()
  for z in e[y]:
    if z in vis: continue
    vis.add(z)
    dfs(z)
vis.add(x)
dfs(x)
print(ressum)
print(*res[1: ])

Submission status: Accepted

Solution code:
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
sys.setrecursionlimit(10 ** 7)

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

for i, e in enumerate(edge[1:], start=1):
    if len(e) == 1:
        s = i
        break

node = [s]
memo = [-1] * (N + 1)
while node:
    s = node.pop()
    memo[s] = C.pop()
    for t in edge[s]:
        if memo[t] != -1:
            continue
        node.append(t)

ans = 0
for a, b in AB:
    ans += min(memo[a], memo[b])

print(ans)
print(*memo[1:])

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
from collections import deque

def main():
    N = int(input())
    edge = [[] for _ in range(N)]
    for _ in range(N-1):
        l,r = map(int,input().split())
        edge[l-1].append(r-1)
        edge[r-1].append(l-1)

    a = list(map(int,input().split()))
    a.sort(reverse = True)
    put = [-1 for _ in range(N)]
    put[0] = a[0]
    q = deque([0])
    i = 1
    while q:
        now = q.popleft()
        for fol in edge[now]:
            if put[fol] != -1:
                continue
            else:
                put[fol] = a[i]
                i += 1
                q.append(fol)
    
    print(sum(a)-a[0])
    print(*put)
    
if __name__ == "__main__":
    main()

Submission status: Accepted

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 = sorted(c)
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)
    edge[neigh].discard(tmp)
    if(edge_num[neigh] == 0):
        ans[neigh] = c[c_num]
        break

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

Submission status: Accepted

Solution code:
from collections import deque
N=int(input())
AB=[tuple(map(int, input().split())) for _ in range(N-1)]
C=sorted(map(int, input().split()))
G=[[] for _ in range(N)]
for a,b in AB:
    a-=1
    b-=1
    G[a].append(b)
    G[b].append(a)
deq=deque(i for i in range(N) if len(G[i])==1)
D=[len(G[i]) for i in range(N)]
X=[0]*N
for c in C:
    i=deq.popleft()
    X[i]=c
    for j in G[i]:
        D[j]-=1
        if D[j]==1:
            deq.append(j)
ans=0
for a,b in AB:
    ans+=min(X[a-1],X[b-1])
print(ans)
print(*X)

Submission status: Accepted

Solution code:
from heapq import heappush, heappop
N, *L = map(int, open(0).read().split())
dic = [[] for i in range(N)]
ans = [-1]*N
cnt = [0]*N
hq = []
for a,b in zip(*[iter(L[:2*(N-1)])]*2):
  a -= 1
  b -= 1
  dic[a] += [b]
  dic[b] += [a]
  cnt[a] += 1
  cnt[b] += 1
C = L[2*(N-1):]
C.sort()
for i in range(N):
  heappush(hq,(cnt[i],i))
arg = 0
m = sum(C)-C[-1]
while True:
  c, i = heappop(hq)
  if ans[i]!=-1:
    continue
  ans[i] = C[arg]
  arg += 1
  if arg==N:
    break
  for v in dic[i]:
    cnt[v] -= 1
    heappush(hq,(cnt[v],v))
print(m)
print(*ans)

Submission status: Accepted

Solution code:
from heapq import heappush, heappop
N, *L = map(int, open(0).read().split())
dic = [[] for i in range(N)]
ans = [-1]*N
cnt = [0]*N
hq = []
for a,b in zip(*[iter(L[:2*(N-1)])]*2):
  a -= 1
  b -= 1
  dic[a] += [b]
  dic[b] += [a]
  cnt[a] += 1
  cnt[b] += 1
C = L[2*(N-1):]
C.sort()
for i in range(N):
  heappush(hq,(cnt[i],i))
arg = 0
m = 0
while True:
  c, i = heappop(hq)
  if ans[i]!=-1:
    continue
  m += C[arg]*cnt[i]
  ans[i] = C[arg]
  arg += 1
  if arg==N:
    break
  for v in dic[i]:
    cnt[v] -= 1
    heappush(hq,(cnt[v],v))
print(m)
print(*ans)

Submission status: Accepted

Solution code:
import sys
from collections import deque
input = sys.stdin.readline
n = int(input())
T = [[] for _ in range(n)]
for i in range(n-1):
    ai,bi = map(int, input().split( ))
    ai-=1;bi-=1
    T[ai].append(bi)
    T[bi].append(ai)

c = list(map(int, input().split( )))
c.sort()


#最小の数字は葉に書き込む
#次点は葉あるいは最小頂点除いたら葉な点
#r = 0
Q = deque()
Q.append(0)
P = [-1 for i in range(n)]
P[0] = 0
D = [0]*n
L=[]
while Q:
    v = Q.popleft()
    leaf = True
    for u in T[v]:
        if P[u]<0:
            D[v]+=1
            P[u]=v
            leaf = False
            Q.append(u)
    if leaf:
        L.append(v)

Q =deque(L)

j = 0
A = [0]*n
m = 0
while Q:
    v = Q.popleft()
    A[v] = c[j]
    if v:
        m+=c[j]
    j+=1
    D[P[v]]-=1
    if not D[P[v]] and v:
        Q.append(P[v])
print(m)
print(*A)

Submission status: Accepted

Solution code:
from collections import deque

N = int(input())
tree = [set() for _ in range(N)]
for _ in range(N - 1):
    a, b = map(int, input().split())
    tree[a - 1].add(b - 1)
    tree[b - 1].add(a - 1)
C = sorted(list(map(int, input().split())))

ans = [0] * N

print(sum(C[:-1]))

ans[0] = C.pop()
n = min(tree[0])
ans[n] = C.pop()

d = deque([0, n])
visited = set(d)
while d:
    x = d.pop()
    for new_x in tree[x]:
        if new_x not in visited:
            ans[new_x] = C.pop()
            d.append(new_x)
            visited.add(new_x)

print(*ans)