题解 | #相遇#

相遇

https://www.nowcoder.com/practice/5dc1ccabaa0442d8b83f00ec74b225fa

import sys
from collections import deque

# Constants
MAXN = 1e6+10
P = 100007

# Read input from stdin
n, m, t = map(int, sys.stdin.readline().split())

# Graph data structures
e = [[] for _ in range(int(MAXN))]
f = [0] * int(MAXN)
ind = [0] * int(MAXN)
dfn = [0] * int(MAXN)

# Reading graph edges
for _ in range(m):
    u, v = map(int, sys.stdin.readline().split())
    e[u].append(v)
    ind[v] += 1

# Topological sort algorithm using queue
q = deque()
for i in range(1, n+1):
    if ind[i] == 0:
        q.append(i)

cnt = 0
while q:
    u = q.popleft()
    cnt += 1
    dfn[cnt] = u
    for nx in e[u]:
        ind[nx] -= 1
        if ind[nx] == 0:
            q.append(nx)

# Calculating f values
f[t] = 1
for i in range(n, 0, -1):
    u = dfn[i]
    for nx in e[u]:
        f[u] = (f[u] + f[nx]) % P

# Output result
Q = int(sys.stdin.readline())
for _ in range(Q):
    s = int(sys.stdin.readline())
    print(f[s])

全部评论

相关推荐

06-23 11:43
门头沟学院 Java
allin校招的烤冷...:我靠,今天中午我也是这个hr隔一个星期发消息给我。问的问题还是一模一样的😅
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务