Codeforces 1106D(Lunar New Year and a Wander )

题目:
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.

题意:
给你一个n个顶点,m条边的无向图连通图,你现在在1这个点,请你遍历这张图,每个点必须经过( 同一个点可以经过多次),请你找出字典序最小的遍历方法。

思路:
图上的dfs吧,看了一篇学长的博客,收到了启发,用vector数组来存储邻接表,然后又用了一个set有序地存储了当前这个点所连通的其他点。

#include<bits/stdc++.h>
using namespace std;
const int maxn = 3e5 + 15;
vector<int>v[maxn];
set<int>st;
int vis[maxn];
int n, m;
void dfs(int a, int cnt){
    vis[a] = 1;
    cnt++;
    cout << a << " ";
    st.erase(a);
    if(cnt == n)
        return;
    for(int i = 0; i < v[a].size(); i++){
        if(vis[v[a][i]] == 0)
            st.insert(v[a][i]);
    }
    dfs(*st.begin(), cnt);
}
int main()
{
    cin >> n >> m;
    for(int i = 0; i < m; i++){
        int x, y;
        cin >> x >> y;
        v[x].push_back(y);
        v[y].push_back(x);
    }
    st.insert(1);
    dfs(1, 0);
    return 0;
}
发布了40 篇原创文章 · 获赞 6 · 访问量 1413

猜你喜欢

转载自blog.csdn.net/qq_43321732/article/details/103949059