The 2023 ICPC Asia Regionals Online Contest (2) --E Another Bus Route Problem(BFS)

Pik's village comprises of n residential buildings (labeled from 1 to n) connected by n−1 bidirectional roads. The village forms a tree structure, where each building is interpreted as a tree vertex, and each road is interpreted as a tree edge. Within the village, there are a total of m bus routes. The i-th bus route (1≤i≤m) originates from building ui​ and follows the shortest path on the tree to building vi​, and then it reverses its path to return to building ui​. When villagers wish to use the i-th bus route, they can board the bus only from either building ui​ or building vi​. They are free to disembark at any building along the shortest path between ui​ and vi​.

Pik, as the village chief, is curious about the minimum number of bus routes needed to reach any building within the village, starting from building 1 where he resides; print −1 if there is a building that cannot be reached.

Input

The first line contains two integers, n and m (1

Then m lines are provided, where the i-th line consists of two integers, ui​ and vi​ (ui​=vi​), indicating a bus route.

Output

One line with n−1 integers, where the i-th integer represents the minimum number of buses required to reach building i+1 from building 1. Print −1 if i+1 cannot be reached.

Sample Input

10 6
1 2 1 4 4 6 7 2 9
1 4
3 6
3 7
9 4
5 10
3 4

Sample Output

2 2 1 -1 3 3 -1 2 -1 

题意:一个树形结构的图,有n个点,m个公交路线,每个路线从x到y,限制是,你只能从起点或者终点上车,但是你可以中途下车,问你从1到2~n点的最少需要经历多少公交路线,如果到达不了输出-1。

解析:从1开始BFS,其中途径的点X,他如果包含其他公交路线Y,那么可以多乘坐1次到达那些点,如何确定途径的点?其实就是从Y向上跑,如果没有遍历过,那么赋值即可,因为BFS总是当前最短,因此每个点只用跑一次。

#include 
using namespace std;
const int N=1e6+5;
int n,m,f[N];//记录每个点的父节点
vector v[N];
int dist[N];
void bfs()
{
	queue q;
	q.push(1);
	dist[1]=0;
	while(q.size())
	{
		int u=q.front();
		q.pop();
		for(int i=0;i

你可能感兴趣的:(宽度优先,算法)