/ SeriousOJ /

Record Detail

Compile Error

foo.cc:13:3: error: invalid preprocessing directive #dp
   13 | # dp[node][k] = max path sum of length k ending at node
      |   ^~
foo.cc:17:3: error: invalid preprocessing directive #Initialize
   17 | # Initialize dp for path length 1 (just the node itself)
      |   ^~~~~~~~~~
foo.cc:31:15: error: invalid preprocessing directive #Update
   31 |             # Update dp[node] with child's dp
      |               ^~~~~~
foo.cc:35:7: error: invalid preprocessing directive #Update
   35 |     # Update with parent's dp
      |       ^~~~~~
foo.cc:42:3: error: invalid preprocessing directive #Run
   42 | # Run DFS from root (node 1)
      |   ^~~
foo.cc:45:3: error: invalid preprocessing directive #Print
   45 | # Print the result (if no valid path found, dp will remain -inf)
      |   ^~~~~
foo.cc:1:1: error: 'import' does not name a type
    1 | import sys
      | ^~~~~~
foo.cc:1:1: note: C++20 'import' only available with '-fmodules-ts'

Code

import sys
sys.setrecursionlimit(10**7)

n, K = map(int, input().split())
values = list(map(int, input().split()))

graph = [[] for _ in range(n+1)]
for _ in range(n-1):
    u, v = map(int, input().split())
    graph[u].append(v)
    graph[v].append(u)

# dp[node][k] = max path sum of length k ending at node
dp = [[float('-inf')] * (K+1) for _ in range(n+1)]
visited = [False] * (n+1)

# Initialize dp for path length 1 (just the node itself)
for i in range(1, n+1):
    dp[i][1] = values[i-1]

ans = 0

def dfs(node, parent):
    global ans
    visited[node] = True
    
    for child in graph[node]:
        if child != parent:
            dfs(child, node)
            
            # Update dp[node] with child's dp
            for k_len in range(2, K+1):
                dp[node][k_len] = max(dp[node][k_len], dp[child][k_len-1] + values[node-1])

    # Update with parent's dp
    if parent != -1:
        for k_len in range(2, K+1):
            dp[node][k_len] = max(dp[node][k_len], dp[parent][k_len-1] + values[node-1])

    ans = max(ans, max(dp[node]))

# Run DFS from root (node 1)
dfs(1, -1)

# Print the result (if no valid path found, dp will remain -inf)
print(ans if ans != float('-inf') else 0)

Information

Submit By
Type
Submission
Problem
P1161 Max path sum (Hard Version)
Contest
Brain Booster #8
Language
C++17 (G++ 13.2.0)
Submit At
2025-02-17 16:43:01
Judged At
2025-02-17 16:43:01
Judged By
Score
0
Total Time
0ms
Peak Memory
0 Bytes