#P1751. 贪吃虫

    ID: 711 远端评测题 1000ms 125MiB 尝试: 0 已通过: 0 难度: 7 上传者: 标签>模拟搜索图论深度优先搜索,DFS

贪吃虫

Description

There are kk worms on a tree with nn nodes, and each worm is on a different node. When the first food appears, all kk worms start from their current positions and move toward the food. Their movement follows these rules:

  • Between any two nodes on the tree there is exactly one path, and all worms move along the unique path toward the food.
  • As soon as a worm reaches the food’s node, the food is immediately eaten.
  • If there is another worm on a worm’s path to the food, the worm that is farther from the food stops moving and stays at its current node.
  • If multiple worms attempt to enter the same node at the same time, only the worm with the smallest index can enter; the others remain at their current nodes.
  • The worm that eats the food stays at the food’s node.
  • After the food is eaten, it will appear at another node on the tree. At that moment, all worms start again from their current positions and try to eat the food. To simplify, moving from a node to an adjacent node takes one unit of time.

Input Format

  • The first line contains an integer nn, the number of nodes in the tree.
  • The next n1n - 1 lines: line i+1i + 1 contains two integers Ai,BiA_i, B_i (1in11 \le i \le n - 1), indicating there is an edge between nodes AiA_i and BiB_i.
  • The next line contains an integer kk, the number of worms on the tree.
  • The next kk lines: line n+1+in + 1 + i contains an integer PiP_i, the initial position of the ii-th worm; no two worms share the same initial position.
  • The next line contains an integer hh, the number of times the food appears.
  • The next hh lines: each line contains one integer, the position where the food appears, in order.

Output Format

Output kk lines. On the ii-th line, print two integers CiC_i and DiD_i, denoting the final position of the ii-th worm and the number of times this worm eats the food, respectively.

4
1 2
1 3
2 4
2
1
2
2
2
4
1 0
4 2

Hint

Constraints

For all testdata: 1n50001 \le n \le 5000, 1k10001 \le k \le 1000, knk \le n, 1h5001 \le h \le 500.

Translated by ChatGPT 5