Road work and the distance to the capital
InterviewTime limit2sMemory limit512 MB
After each of q edge insertions and deletions, output the shortest-path distance from every city to city 1, or -1 if unreachable.
- Level
Medium4 of 10
- Topics
- BFS, Graph, Implementation, Brute force
- Solved
- No attempts yet
Problem
A country announced a road work plan. The plan contains jobs that build a new road between two cities and jobs that tear down a road that already exists. The jobs run one at a time, in the order given. A road built by an earlier job can be torn down by a later one.
The capital is city 1. After each job the country wants to know, for every city, the smallest number of roads you have to travel to reach the capital. Roads are two way, and the capital itself travels no road at all, so its answer is always 0.
Given the initial roads and the plan, print the answer for every city after each job.
Input
The first line contains the number of cities and the number of roads that exist at the start . (, )
Each of the next lines contains the two cities joined by one road.
The next line contains the number of jobs in the plan . ()
Each of the next lines contains three integers , , . If is 1, a new road between city and city is built. If is 2, the road between those two cities is torn down. (, , )
At most one road joins any pair of cities. The input never builds a road that already exists and never tears down a road that is not there.
Output
Print lines. Line holds the answers after job , for city 1 to city in that order, separated by single spaces.
The answer for a city is the smallest number of roads on a route from that city to the capital. Print -1 for a city that cannot reach the capital.