Packet Routing
InterviewTime limit1sMemory limit128 MB
Given a tree with weighted edges connecting N computers, compute the travel time along the unique path between each query pair of computers.
- Level
Medium4 of 10
- Topics
- Tree, DFS, Graph, Implementation
- Solved
- No attempts yet
Problem
The date is October 29th, 1969. Today, scientists at UCLA made history by exchanging data between two computers over a network. The transmission wasn't very spectacular: only the first two letters of the word login were received before the system crashed. Nevertheless, the researchers are beginning to design larger computer networks, and they need your help.
A computer network is a collection of computers and wires. The computers are identified by the numbers . Each wire connects exactly two computers, allowing data packets to flow in both directions between them. The wires are placed so that a packet can be sent (directly or indirectly through other computers) between every pair of computers. In fact, the placement of the wires has been optimized so that there is exactly one path between every pair of computers. If a packet travels along several wires to get from the source computer to the destination computer, the time needed to travel this path is the sum of the times required to travel each individual wire. Write a program that, given a pair of distinct computers, computes the time needed for a packet to travel between them.
Input
The first line contains three positive integers , , and .
For each wire, a line follows giving the identification numbers of the two computers it connects, and an integer between and giving the time required for a packet to travel along that wire.
is the number of packets that must be sent. For each packet, a line follows giving the identification numbers of the packet's source and destination computers.
Output
For each packet, find the route through the network from the source computer to the destination computer, and output the travel time of that route on a single line.