/ SeriousOJ /

Record Detail

Time Exceeded


  
# Status Time Cost Memory Cost
#1 Accepted 3ms 2.77 MiB
#2 Accepted 3ms 2.812 MiB
#3 Accepted 5ms 2.77 MiB
#4 Accepted 4ms 2.77 MiB
#5 Accepted 5ms 2.676 MiB
#6 Accepted 5ms 2.75 MiB
#7 Accepted 6ms 2.77 MiB
#8 Accepted 6ms 2.77 MiB
#9 Accepted 6ms 2.816 MiB
#10 Accepted 6ms 2.773 MiB
#11 Accepted 6ms 2.77 MiB
#12 Wrong Answer 239ms 6.191 MiB
#13 Time Exceeded ≥3095ms ≥6.539 MiB

Code

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

const int MAXN = 1e5 + 5;

int N, K;
vector<int> adj[MAXN]; // Adjacency list
vector<int> values;    // Node values

int findMaxWeightPath() {
    int maxWeight = 0;

    // Perform BFS from each node
    for (int start = 1; start <= N; ++start) {
        queue<pair<int, pair<int, int>>> q; // {current node, {current depth, weight sum}}
        q.push({start, {1, values[start - 1]}});
        vector<bool> visited(N + 1, false);
        visited[start] = true;

        while (!q.empty()) {
            auto [node, data] = q.front();
            int depth = data.first;
            int sumWeight = data.second;
            q.pop();

            // If path of exact length K is reached, update maxWeight
            if (depth == K) {
                maxWeight = max(maxWeight, sumWeight);
                continue;
            }

            // Traverse adjacent nodes
            for (int neighbor : adj[node]) {
                if (!visited[neighbor]) {
                    visited[neighbor] = true;
                    q.push({neighbor, {depth + 1, sumWeight + values[neighbor - 1]}});
                }
            }
        }
    }

    return maxWeight;
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    cin >> N >> K;
    values.resize(N);
    for (int i = 0; i < N; ++i) cin >> values[i];

    for (int i = 0; i < N - 1; ++i) {
        int u, v;
        cin >> u >> v;
        adj[u].push_back(v);
        adj[v].push_back(u);
    }

    cout << findMaxWeightPath() << "\n";
    return 0;
}

Information

Submit By
Type
Submission
Problem
P1160 Max path sum (Easy Version)
Contest
Brain Booster #8
Language
C++17 (G++ 13.2.0)
Submit At
2025-02-17 14:42:07
Judged At
2025-02-17 14:42:07
Judged By
Score
22
Total Time
≥3095ms
Peak Memory
≥6.539 MiB