J - Welcome Party
#include<bits/stdc++.h> using namespace std; const int maxn=1e6+10; int f[maxn]; int visf[maxn]; int vis[maxn]; int as[maxn]; vector<int> v[maxn]; priority_queue<int,vector<int>,greater<int> > q; int getf(int a) { if(f[a]==a) return a; else return f[a]=getf(f[a]); } int main() { int t; scanf("%d",&t); while(t--) { int n,m; scanf("%d%d",&n,&m); while(q.size()) q.pop(); for(int i=1; i<=n; i++) { f[i]=i; vis[i]=0; visf[i]=0; v[i].clear(); } for(int i=1; i<=m; i++) { int a,b; scanf("%d%d",&a,&b); f[getf(b)]=getf(a); v[a].push_back(b); v[b].push_back(a); } int ans=0; for(int i=1; i<=n; i++) { if(getf(i)==i) ans++; if(visf[getf(i)]==0) { q.push(i); visf[getf(i)]=1; vis[i]=1; } } int len=0; while(!q.empty()) { int t1=q.top(); q.pop(); as[++len]=t1; for(int i=0; i<v[t1].size(); i++) { int y=v[t1][i]; if(vis[y]) continue; q.push(y); vis[y]=1; } } printf("%d\n",ans); for(int i=1; i<=len; i++) { if(i!=len) printf("%d ",as[i]); else printf("%d\n",as[i]); } } }
原文地址:https://www.cnblogs.com/dongdong25800/p/10801223.html
时间: 2024-10-31 21:08:19