Codeforce - 1106：Lunar New Year and a Wander（BFS-优先队列 + 图 + STL）

Lunar New Year is approaching, and Bob decides to take a wander in a nearby park.

The park can be represented as a connected graph with n nodes and m bidirectional edges. Initially Bob is at the node 1 and he records 1 on his notebook. He can wander from one node to another through those bidirectional edges. Whenever he visits a node not recorded on his notebook, he records it. After he visits all nodes at least once, he stops wandering, thus finally a permutation of nodes a1,a2,…,an is recorded.

Wandering is a boring thing, but solving problems is fascinating. Bob wants to know the lexicographically smallest sequence of nodes he can record while wandering. Bob thinks this problem is trivial, and he wants you to solve it.

A sequence x is lexicographically smaller than a sequence y if and only if one of the following holds:

x is a prefix of y, but x≠y (this is impossible in this problem as all considered sequences have the same length);
in the first position where x and y differ, the sequence x has a smaller element than the corresponding element in y.
Input
The first line contains two positive integers n and m (1≤n,m≤105), denoting the number of nodes and edges, respectively.

The following m lines describe the bidirectional edges in the graph. The i-th of these lines contains two integers ui and vi (1≤ui,vi≤n), representing the nodes the i-th edge connects.

Note that the graph can have multiple edges connecting the same two nodes and self-loops. It is guaranteed that the graph is connected.

Output
Output a line containing the lexicographically smallest sequence a1,a2,…,an Bob can record.

Examples
Input
3 2
1 2
1 3
Output
1 2 3
Input
5 5
1 4
3 4
5 4
3 2
1 5
Output
1 4 3 2 5
Input
10 10
1 4
6 8
2 5
3 7
9 4
5 6
3 4
8 10
8 9
1 10
Output
1 4 3 7 9 8 6 5 2 10
Note
In the first sample, Bob’s optimal wandering path could be 1→2→1→3. Therefore, Bob will obtain the sequence {1,2,3}, which is the lexicographically smallest one.

In the second sample, Bob’s optimal wandering path could be 1→4→3→2→3→4→1→5. Therefore, Bob will obtain the sequence {1,4,3,2,5}, which is the lexicographically smallest one.

题目描述

``````#include <stdio.h>
#include <iostream>
#include <algorithm>
#include <queue>
#include <vector>
#define MAX_SIZE 100005

using namespace std;

int n,m,book[MAX_SIZE];		//用来记录该结点是否输出
vector<int> a[MAX_SIZE];	//用来存图
priority_queue<int,vector<int>,greater<int> >q;	//最小堆

int main()
{
int i;
scanf("%d %d",&n,&m);
for(i = 0;i < m;i++)
{
int u,v;
scanf("%d %d",&u,&v);
//因为是无向图，所以两边都要存储
a[u].push_back(v);
a[v].push_back(u);
}
q.push(1);
while(!q.empty())
{
int now = q.top();
q.pop();
if(book[now])	//如果该结点已经输出，那么就continue
continue;
book[now] = 1;	//该结点没有输出就标记并输出
printf("%d ",now);
//将当前遍历结点的所有连接的结点都入队，并且在队列中自动进行排序，可以保证每次队首元素都是最小的
for(i = 0;i < a[now].size();i++)
{
if(!book[a[now][i]])
{
q.push(a[now][i]);
}
}
}
return 0;
}
``````

0条评论