Each query gives two factory sets on a weighted tree and asks for the minimum distance between any factory in one set and any in the other.
Hard9Divide and conquerTreeShortest pathNo attempts yetTime limit6sMemory limit512 MBThe kingdom of IOI has N cities numbered 0 through N−1. The cities are joined by N−1 two-way roads, and you can travel from any city to any other city along a few of these roads.
Many companies in the kingdom make special products. Each company makes exactly one kind of product, and no two companies make the same kind. Every company owns one or more factories, and each factory is built in one of the cities. Several companies may own factories in the same city.
Sometimes a company CA needs the product of another company CB (CA=CB). The product is then carried from one factory of CB to one factory of CA. The two companies choose the pair of factories that makes the distance between them as small as possible.
You are first given the number of cities and the roads of the kingdom, then Q queries. Query j reads as follows. Company Uj, which owns factories in cities Xj,0,…,Xj,Sj−1, needs the product of company Vj, which owns factories in cities Yj,0,…,Yj,Tj−1. For each query, report the smallest distance needed to carry the product.
The first line contains two integers N and Q separated by a space. The kingdom has N cities and your program is given Q queries.
Line i+1 of the next N−1 lines (0≤i≤N−2) contains three integers Ai, Bi, Di separated by spaces. There is a road of length Di between city Ai and city Bi.
The next 3Q lines hold the queries. The information of query j (0≤j≤Q−1) occupies lines 3j+1 through 3j+3.
Line 3j+1 contains two integers Sj and Tj separated by a space. Company Uj owns factories in Sj cities and company Vj owns factories in Tj cities.
Line 3j+2 contains the Sj integers Xj,0,…,Xj,Sj−1 separated by spaces. Company Uj owns factories in these cities.
Line 3j+3 contains the Tj integers Yj,0,…,Yj,Tj−1 separated by spaces. Company Vj owns factories in these cities.
Every input satisfies the following conditions.
Print the answer to each query on its own line, in the order the queries are given.
The three queries of the example are answered as follows.