思路:
首先找到所有集合中的最小值,可以用并查集,也可以用广搜,深搜就超时了,
然后把所有最小的值先存入有限队列,依次遍历队列就好了,但是要用邻接表,vector数组就超时╮(╯▽╰)╭。
#include<iostream>
#include<cstdio>
#include<cstring>
#include<vector>
#include<queue>
using namespace std;
const int maxn = 2e6+10;
int vis[maxn],bj[maxn],head[maxn],tot;
vector <int> vd,vv;
priority_queue <int,vector <int>,greater <int> > q;
struct Node{
int v,nxt;
}cur[maxn];
void add(int x,int y){
cur[tot].nxt = head[x];
cur[tot].v = y;
head[x] = tot++;
}
void bfs(int x){
queue <int> p;
vis[x] = 1;
p.push(x);
while(!p.empty()){
x = p.front();p.pop();
for(int i=head[x];i!=-1;i=cur[i].nxt)
if(vis[cur[i].v]==0){
vis[cur[i].v] = 1;
p.push(cur[i].v);
}
}
}
int main(void)
{
int n,m,i,j,x,y,T;
scanf("%d",&T);
while(T--){
scanf("%d%d",&n,&m);
vd.clear();vv.clear();
tot = 1;
for(i=1;i<=n;i++){
vis[i] = bj[i] = 0;
head[i] = -1;
}
while(!q.empty()) q.pop();
for(i=1;i<=m;i++){
scanf("%d%d",&x,&y);
add(x,y);
add(y,x);
}
int num = 0;
for(i=1;i<=n;i++)
if(vis[i]==0){
bfs(i);
vd.push_back(i);
q.push(i);
bj[i] = 1;num++;
}
while(!q.empty()){
x = q.top();q.pop();
vv.push_back(x);
for(i=head[x];i!=-1;i=cur[i].nxt){
y = cur[i].v;
if(!bj[y]){
bj[y] = 1;
q.push(y);
}
}
}
printf("%d\n",num);
y = vv.size();
for(i=0;i<y;i++){
if(i) printf(" ");
printf("%d",vv[i]);
}
printf("\n");
}
return 0;
}