https://codeforces.com/contest/1106/problem/D

C++版本一

题解:

每次都走曾经和现在可以选择的最小节点

/*
*@Author:   STZG
*@Language: C++
*/
#include <bits/stdc++.h>
#include<iostream>
#include<algorithm>
#include<cstdlib>
#include<cstring>
#include<cstdio>
#include<string>
#include<vector>
#include<bitset>
#include<queue>
#include<deque>
#include<stack>
#include<cmath>
#include<list>
#include<map>
#include<set>
//#define DEBUG
#define RI register int
using namespace std;
typedef long long ll;
//typedef __int128 lll;
const int N=100000+10;
const int MOD=1e9+7;
const double PI = acos(-1.0);
const double EXP = 1E-8;
const int INF = 0x3f3f3f3f;
int t,n,m,k,q;
int cnt,flag,temp;
vector<int>v[N];
vector<int>ans;
int vis[N];
priority_queue<int,vector<int>,greater<int> >Q;
void dfs(int x){
    //cout<<x<<endl;
    ans.push_back(x);
    for(int i=0,j=v[x].size();i<j;i++){
        if(vis[v[x][i]]==0){
            Q.push(v[x][i]);
            //vis[v[x][i]]=0;
        }
    }
    if(Q.empty())
        return;
    int d=Q.top();
    Q.pop();
    while(vis[d]&&!Q.empty()){
        d=Q.top();
        Q.pop();
    }
    if(vis[d])
        return;
    vis[d]=1;
    dfs(d);
}
int main()
{
#ifdef DEBUG
	freopen("input.in", "r", stdin);
	//freopen("output.out", "w", stdout);
#endif
    scanf("%d%d",&n,&m);
    while(m--){
        int a,b;
        scanf("%d %d",&a,&b);
        v[a].push_back(b);
        v[b].push_back(a);
    }
    for(int i=1;i<=n;i++)
        sort(v[i].begin(),v[i].end());
    vis[1]=1;
    dfs(1);
    //vis[1]=0;
    for(int i=0,j=ans.size();i<j;i++)
        printf("%d ",ans[i]);
    //cout << "Hello world!" << endl;
    return 0;
}

C++版本二

#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
#include<math.h>
#include<string.h>
#include<queue>
#include<algorithm>
#include<vector>
#define ll long long
#define pb push_back
#define INF 0x3f3f3f3f;
#define test printf("here!!!")
using namespace std;
const int mx=1e5+10;
const int mod=998244353;
int vis[mx];
priority_queue<int,vector<int>,greater<int> >q;
vector<int>vec[mx];
void dfs(int st)
{
    printf("1 ");
    while (!q.empty())
    {
        int nx=q.top();
        q.pop();
        if (!vis[nx])
        {
            printf("%d ",nx);
            vis[nx]=1;
            for (int i=vec[nx].size()-1;i>=0;--i)
            {
                if (!vis[vec[nx][i]]) q.push(vec[nx][i]);
            }

        }
    }
}
int main()
{
    int n,m,u,v;
    scanf("%d%d",&n,&m);
    for (int i=1;i<=m;++i)
    {
        scanf("%d%d",&u,&v);
        vec[u].pb(v);
        vec[v].pb(u);
        if (u==1)
        {
            q.push(v);
        }
        else if (v==1)
        {
            q.push(u);
        }
    }
    vis[1]=1;
    dfs(1);
}