Ornaments on a Tree

시간 제한4초메모리 제한2048 MB

요약
루트 있는 트리에서 고정되지 않은 각 노드에 음이 아닌 정수 무게를 배정해 모든 노드와 그 자식들의 합이 K 이하가 되도록 하면서 전체 무게 합의 최댓값을 구한다.
난이도

어려움10점 중 8점

유형
트리, 그리디, 동적 계획법, DFS
정답자
아직 제출이 없습니다

문제

You're helping your friend decorate their Christmas tree! Funnily enough, the places to put your ornaments on their Christmas tree can be represented by a (graph-theoretic) tree with nodes labeled 11 to NN, with node 11 being the root of the tree and other nodes numbered arbitrarily. You have an infinite supply of ornaments of every non-negative integer weight (including 00), and you must place exactly one ornament on each node of the tree.

However, your friend has some restrictions on how they want their tree decorated. First, they have strong opinions about which ornament must go on some of the tree nodes; you are only allowed to choose decorations on the other nodes. Second, each region of their tree can support only so much weight: if the sum of the weights of the ornaments on a node and all of its immediate children exceeds a constant KK, the whole tree will come crashing down!

Your friend wants to know the largest possible total weight of ornaments on their tree, given the above restrictions. Can you help them find out?

입력

The first line of input has two space-separated integers NN and KK (1≤N≤2⋅105,0≤K≤1091 \leq N \leq 2 \cdot 10^5, 0 \leq K \leq 10^9), the number of nodes in the tree and the weight constant, respectively.

The next line contains NN space-separated integers. The ithi^\text{th} integer (starting at i=1i=1) is either −1-1 or a non-negative integer. If it is −1-1, you are free to choose any ornament for node ii. If it is a non-negative integer w_iw\_i (0≤w_i≤1090 \leq w\_i \leq 10^9), your friend insists you place an ornament with weight w_iw\_i on node ii.

The next N−1N-1 lines each contain two space-separated integers aa and bb (1≤a,b≤N1 \leq a, b \leq N), indicating that nodes aa and bb are connected by an edge. The input graph is guaranteed to be a tree: there is a unique path of edges between every pair of nodes in the graph.

출력

If it is impossible to place ornaments on the tree in a way that satisfies all of the constraints described above, print −1-1. Otherwise, print the maximum possible total weight of the ornaments on the tree, subject to the constraints.

예제3

  1. 예제 1

    입력
    5 10
    -1 2 3 -1 -1
    1 2
    1 3
    2 4
    2 5
    
    예상 출력
    18
    
  2. 예제 2

    입력
    1 5
    -1
    
    예상 출력
    5
    
  3. 예제 3

    입력
    2 5
    5 5
    1 2
    
    예상 출력
    -1