#BS0000475. Truy vấn đường mới (New Roads Queries)
Bài tập thuộc lộ trình
Mục lục đề ⌄
Truy vấn đường mới (New Roads Queries)
New Roads Queries
Source: CSES
Version: Phuoc Hung OJ Extended
Problem Statement
Byteland has cities numbered from to . Initially no roads connect the cities. Over the next days, one bidirectional road is constructed each day; previously built roads remain available.
You are given the construction order of all roads. Two cities can reach each other if a route exists through the roads already built. Each city can also reach itself without using a road. Some pairs may remain disconnected even after all roads are built.
For each of the queries , determine the earliest day on which it becomes possible to travel from city to city . Return -1 if no such day exists.
Input
- The first line contains three integers : the numbers of cities, roads and queries.
- Each of the next lines contains two integers; line specifies endpoints of the road built on day .
- Each of the final lines contains two integers; line specifies cities for query .
Output
Print lines in query order. Line contains the earliest day on which can reach , or -1 if they cannot reach each other even after day . If , print .
Subtasks
- Subtask 1 (20 points): ; ; ; for every ; for every . All roads are bidirectional; endpoints need not differ, endpoint pairs need not be distinct, and the final graph need not be connected.
- Subtask 2 (30 points): ; ; ; for every ; for every . All roads are bidirectional; endpoints need not differ, endpoint pairs need not be distinct, and the final graph need not be connected.
- Subtask 3 (50 points): ; ; ; for every ; for every . All roads are bidirectional; endpoints need not differ, endpoint pairs need not be distinct, and the final graph need not be connected.
Examples
Input 1
5 4 3
1 2
2 3
1 3
2 5
1 3
3 4
3 5
Output 1
2
-1
4
Explanation 1
There are cities. Day links and ; day adds the road between and , forming the route . City was not connected to before day , so the first answer is .
City remains isolated through all four days, giving -1 for the second query. Day adds road , making the route possible. City was isolated until then, so the final answer is .
Input 2
4 4 4
1 1
1 2
2 1
3 4
1 1
1 2
1 4
4 3
Output 2
0
2
-1
4
Explanation 2
City can reach itself on day . The first road does not link distinct cities. Day links and , giving for pair . Day repeats an existing connection. Day connects and , but the groups and remain separate. The last two answers are therefore -1 and .