/ SeriousOJ /

Record Detail

Wrong Answer


  
# Status Time Cost Memory Cost
#1 Accepted 3ms 532.0 KiB
#2 Wrong Answer 3ms 532.0 KiB
#3 Wrong Answer 3ms 532.0 KiB

Code

#include <bits/stdc++.h>
using namespace std;

vector<vector<int>> adj;  // Adjacency list to store the tree
vector<int> values;       // Store node values
int N, K;
int maxWeight = 0;

void dfs(int node, int parent, int length, int weight) {
    // If we've reached length K, update maxWeight if current path is heavier
    if (length == K) {
        maxWeight = max(maxWeight, weight);
        return;
    }
    
    // If we've exceeded K, return as this path is not valid
    if (length > K) return;
    
    // Try all possible neighbors
    for (int neighbor : adj[node]) {
        // Skip parent to avoid going backwards
        if (neighbor == parent) continue;
        
        // Recursively explore path, incrementing length and adding weight
        dfs(neighbor, node, length + 1, weight + values[neighbor - 1]);
    }
}

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    
    // Read N and K
    cin >> N >> K;
    
    // Initialize adjacency list and values vector
    adj.resize(N + 1);
    values.resize(N);
    
    // Read node values
    for (int i = 0; i < N; i++) {
        cin >> values[i];
    }
    
    // Read edges
    for (int i = 0; i < N - 1; i++) {
        int u, v;
        cin >> u >> v;
        adj[u].push_back(v);
        adj[v].push_back(u);
    }
    
    // Start DFS from root (node 1), with initial weight as value of root
    dfs(1, 0, 1, values[0]);
    
    // If maxWeight is still 0, it means no path of length K was found
    cout << (maxWeight == 0 ? 0 : maxWeight) << endl;
    
    return 0;
}

Information

Submit By
Type
Submission
Problem
P1160 Max path sum (Easy Version)
Language
C++17 (G++ 13.2.0)
Submit At
2025-01-18 10:07:32
Judged At
2025-01-18 10:07:32
Judged By
Score
1
Total Time
3ms
Peak Memory
532.0 KiB