Nastya and Potions (Codeforces 1851E)
Tags: DP, dfs and similar

Alchemist Nastya loves mixing potions. There are a total of $$$n$$$ types of potions, and one potion of type $$$i$$$ can be bought for $$$c_i$$$ coins.Any kind of potions can be obtained in no more than one way, by mixing from several others. The potions used in the mixing process will be consumed. Moreover, no potion can be obtained from itself through one or more mixing processes.As an experienced alchemist, Nastya has an unlimited supply of $$$k$$$ types of potions $$$p_1, p_2, \dots, p_k$$$, but she doesn't know which one she wants to obtain next. To decide, she asks you to find, for each $$$1 \le i \le n$$$, the minimum number of coins she needs to spend to obtain a potion of type $$$i$$$ next.

Input: The first line of each test contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases.Each test case is described as follows:The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k < n \le 2 \cdot 10^5$$$) — the total number of potion types and the number of potion types Nastya already has.The second line contains $$$n$$$ integers $$$c_1, c_2, \dots, c_n$$$ ($$$1 \le c_i \le 10^9$$$) — the costs of buying the potions.The third line contains $$$k$$$ distinct integers $$$p_1, p_2, \dots, p_k$$$ ($$$1 \le p_i \le n$$$) — the indices of potions Nastya already has an unlimited supply of.This is followed by $$$n$$$ lines describing ways to obtain potions by mixing.Each line starts with the integer $$$m_i$$$ ($$$0 \le m_i < n$$$) — the number of potions required to mix a potion of the type $$$i$$$ ($$$1 \le i \le n$$$).Then line contains $$$m_i$$$ distinct integers $$$e_1, e_2, \dots, e_{m_i}$$$ ($$$1 \le e_j \le n$$$, $$$e_j \ne i$$$) — the indices of potions needed to mix a potion of the type $$$i$$$. If this list is empty, then a potion of the type $$$i$$$ can only be bought.It is guaranteed that no potion can be obtained from itself through one or more mixing processes.It is guaranteed that the sum of all $$$n$$$ values across all test cases does not exceed $$$2 \cdot 10^5$$$. Similarly, it is guaranteed that the sum of all $$$m_i$$$ values across all test cases does not exceed $$$2 \cdot 10^5$$$.

Output: For each test case, output $$$n$$$ integers — the minimum number of coins Nastya needs to spend to obtain a potion of each type.

Note: In the first test case of the first sample, it is optimal:  Get a potion of the first type by buying and mixing $$$2$$$, $$$4$$$ and $$$5$$$;  a potion of the second type can only be obtained by purchasing it;  Nastya already has an unlimited number of potions of the third type;  a potion of the fourth type is more profitable to buy than to buy and mix other potions;  a potion of the fifth type can only be obtained by purchasing it. 

Sample Inputs:
4
5 1
30 8 3 5 10
3
3 2 4 5
0
0
2 3 5
0
3 2
5 143 3
1 3
1 2
0
2 1 2
5 1
5 4 1 3 4
2
2 4 5
3 3 5 4
2 1 4
1 5
0
4 2
1 1 5 4
2 4
3 2 4 3
0
2 2 4
1 2

3
6 3
5 5 4 5 2 2
3 4 5
2 2 5
1 5
3 4 1 6
4 2 6 1 5
0
0
6 2
1 4 4 1 5 2
3 6
4 6 3 4 5
4 6 5 3 4
0
1 5
1 6
0
2 1
4 3
1
0
1 1

Sample Outputs:
23 8 0 5 10 
0 143 0 
5 0 1 3 4 
0 0 0 0

0 0 0 0 0 2 
0 0 0 0 0 0 
0 0

Solution (Python):
import bisect
import collections
import heapq
import io
import math
import os
import random
import re
import sys
LO = 'abcdefghijklmnopqrstuvwxyz'
Mod = 998244353

def gcd(x, y):
    while y:
        (x, y) = (y, x % y)
    return x

def euk(x, y):
    if y:
        (p, q, g) = euk(y, x % y)
        return (q, p - x // y * q, g)
    return (1, 0, x)
_input = lambda : sys.stdin.buffer.readline().strip().decode()
T = 1
T = int(_input())
for _ in range(T):
    (n, m) = map(int, _input().split())
    c = list(map(int, _input().split()))
    f = [None] * n
    for x in map(int, _input().split()):
        f[x - 1] = 1
    g = [[] for _ in range(n)]
    d = [0] * n
    for i in range(n):
        p = map(int, _input().split())
        d[i] = next(p)
        for x in p:
            g[x - 1].append(i)
    a = [0] * n
    q = []
    for x in range(n):
        if d[x] == 0:
            q.append(x)
            a[x] = 0 if f[x] else c[x]
    for x in q:
        if f[x]:
            a[x] = 0
        else:
            a[x] = min(a[x], c[x])
        for y in g[x]:
            a[y] += a[x]
            d[y] -= 1
            if d[y] < 1:
                q.append(y)
    print(*a)

Solution (Python):
import sys
from collections import deque
input = sys.stdin.readline
for _ in range(int(input())):
    (n, k) = map(int, input().split())
    dp = [0 for _ in range(n + 1)]
    graph = [[] for _ in range(n + 1)]
    indeg = [0 for _ in range(n + 1)]
    price = [0] + list(map(int, input().split()))
    mixed = [0 for _ in range(n + 1)]
    for i in range(1, n + 1):
        dp[i] = price[i]
    for i in list(map(int, input().split())):
        dp[i] = 0
    for i in range(1, n + 1):
        arr = list(map(int, input().split()))
        for j in arr[1:]:
            indeg[i] += 1
            graph[j].append(i)
    q = deque()
    for i in range(1, n + 1):
        if indeg[i] == 0:
            q.append((i, 0))
    while q:
        (x, d) = q.popleft()
        if d:
            dp[x] = min(dp[x], mixed[x])
        for nxt in graph[x]:
            mixed[nxt] += dp[x]
            indeg[nxt] -= 1
            if indeg[nxt] == 0:
                q.append((nxt, d + 1))
    print(*dp[1:])

Solution (Python):
import sys
import sys
input = sys.stdin.readline
for _ in range(int(input())):
    (n, k) = map(int, input().split())
    c = list(map(int, input().split()))
    p = list(map(int, input().split()))
    visit = [0] * (n + 1)
    for i in p:
        c[i - 1] = 0
        visit[i] = 1
    graf = [[] for _ in range(n + 1)]
    for i in range(n):
        m = list(map(int, input().split()))
        for j in range(1, len(m)):
            graf[i + 1].append(m[j])
        if m[0] == 0:
            visit[i + 1] = 1
    ans = []
    for i in range(n):
        if visit[i + 1] == 0:
            tmp = [i + 1]
            while tmp:
                v = tmp.pop()
                if visit[v] == 0:
                    e = []
                    co = 0
                    for r in graf[v]:
                        if visit[r] == 0:
                            e.append(r)
                        co += c[r - 1]
                    if e == []:
                        c[v - 1] = min(co, c[v - 1])
                        visit[v] = 1
                    else:
                        tmp.append(v)
                        tmp += e
    print(*c)