/ SeriousOJ /

Record Detail

Wrong Answer


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

Code

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

vector<vector<int>> adj;  // Adjacency list
vector<int> values;       // Node values
vector<bool> visited;     // Track visited nodes
int N, K;

// Function to find all paths of length K and return maximum weight
int findMaxPathWeight(int node, int pathLength, vector<int>& currentPath) {
    // If path length equals K, calculate weight
    if (pathLength == K) {
        int weight = 0;
        for (int n : currentPath) {
            weight += values[n - 1];
        }
        return weight;
    }
    
    if (pathLength > K) return 0;
    
    int maxWeight = 0;
    visited[node] = true;
    
    // Try all neighbors
    for (int next : adj[node]) {
        if (!visited[next]) {
            currentPath.push_back(next);
            maxWeight = max(maxWeight, findMaxPathWeight(next, pathLength + 1, currentPath));
            currentPath.pop_back();
        }
    }
    
    visited[node] = false;
    return maxWeight;
}

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    
    // Read input
    cin >> N >> K;
    
    // Initialize data structures
    adj.resize(N + 1);
    values.resize(N);
    visited.resize(N + 1, false);
    
    // 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 from root (node 1)
    vector<int> currentPath = {1};  // Start with root node
    int result = findMaxPathWeight(1, 1, currentPath);
    
    cout << result << 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:08:55
Judged At
2025-01-18 10:08:55
Judged By
Score
1
Total Time
1ms
Peak Memory
540.0 KiB