algoblazerEarly Access
LearnProblemsStudy GroupsMock InterviewLeaderboard
Log inSign up

All problems

‹ Back to map
1 shown · 0/288 solved

Tree Path Distance Sum With Edge Updates

GoldCommunity Beta
Asked atJuspay
Solve problem →
3000ms256MBAdded Sep 25, 2026

You are given an integer n, a list edges, and a list queries. There are n nodes labeled from 0 to n - 1. Each element in edges contains [u, v, w] meaning there is an edge between node u and node v whose weight is w. The n - 1 edges form a tree, so exactly one path joins any two nodes.

The distance between two nodes is the sum of the weights of the edges on the path between them. The distance from a node to itself is 0.

Each element in queries contains [type, x, y, w], and the queries are processed in the order given:

  • [1, x, y, w] sets the weight of the edge between x and y to w. You can assume that edge is in the tree. The two endpoints may be listed in either order.
  • [2, x, y, 0] asks for the distance between x and y right now. The fourth value is always 0.

Return the sum of the answers to all queries of the second type.

If there are no queries of the second type, return 0.

Note that the answer can exceed the 32-bit integer range.

Examples

Read full statement →

Constraints

  • 2≤n≤1052 \leq n \leq 10^52≤n≤105
  • edges.length =n−1= n - 1=n−1 and the edges form a tree
  • 0≤u,v<n0 \leq u, v < n0≤u,v<n and u≠vu \neq vu=v for each [u, v, w] in edges
  • 1≤w≤1041 \leq w \leq 10^41≤w≤104 for every weight in edges and in queries
  • 1≤1 \leq1≤ queries.length ≤105\leq 10^5≤105
  • queries[i][0] is 1 or 2
  • 0≤x,y<n0 \leq x, y < n0≤x,y<n in every query

Details

Solved by0 people
Time limit3000ms
Memory256MB
AddedSep 25, 20264 hours ago