Under construction

Still being built. Things may change

Cowherd and Weaver Girl

Interview

Time limit1sMemory limit1024 MB

Summary
Given two weighted trees, pick one vertex from each and join them with a unit edge to minimize the sum of distances over all cross pairs.
Level

Medium5 of 10

Topics
Tree, DFS, Math
Solved
No attempts yet

Problem

Cowherd lives in a weighted undirected tree EE with NN vertices, and Weaver Girl lives in a weighted undirected tree WW with MM vertices.

The two live in different trees, so they cannot meet. To help the two lovers, the Jade Emperor builds a magpie bridge every year on July 7 so they can meet.

The magpie bridge is an edge of length 11. The Jade Emperor connects it so that the sum of distances between all vertices of EE and all vertices of WW is minimized, which makes it easy for the two to meet.

Tell them which vertices the bridge connects on July 7.

Input

The first line contains NN, the number of vertices in EE (1≤N≤100 0001 \leq N \leq 100\,000). The next N−1N-1 lines each describe an edge of EE in the form a b c (1≤a,b≤N;1≤c≤104)(1 \leq a, b \leq N; 1 \leq c \leq 10^4). This means the distance between vertex aa and vertex bb of EE is cc. The next line contains MM, the number of vertices in WW (1≤M≤100 0001 \leq M \leq 100\,000). The next M−1M-1 lines each describe an edge of WW in the form a b c (1≤a,b≤M;1≤c≤104)(1 \leq a, b \leq M; 1 \leq c \leq 10^4). This means the distance between vertex aa and vertex bb of WW is cc. All input values are integers.

Output

The first line prints the vertex of EE and the vertex of WW that the bridge connects, separated by a space. If several answers exist, print any of them. The second line prints the sum of distances between all vertices of EE and all vertices of WW after the bridge is built.

Hint

The sum of distances between all vertices of EE and all vertices of WW is defined as follows. ∑u∈E∑v∈Wdist(u,v)\sum_{u \in E} \sum_{v \in W} dist(u, v)

Examples2

  1. Example 1

    Input
    3
    1 2 2
    2 3 3
    1
    
    Expected output
    2 1
    8
    
  2. Example 2

    Input
    5
    1 2 2
    2 4 1
    2 3 3
    3 5 1
    5
    1 3 2
    3 5 3
    2 3 1
    3 4 2
    
    Expected output
    2 3
    115