省流:WA 了四发。
思路
这种联通性的题就很并查集。具体地,如果一条边连接的两端已经在这之前联通,那这条边就可以拿去和其它未联通的点连接。碰到这种情况就直接记边的编号即可。
需要变动的边数就是联通块个数减一。难点在于如何输出变动边的重连方案。对于点 ,我们需要快速找到点 , 满足不与 在同一个连通块中。如果直接枚举每个点去尝试合并的话时间复杂度一定不妙,所以考虑在每次合并的过程中去记录当前阶段每个连通块的祖先节点编号,这样至多枚举两个点就可以找到和当前点不联通的点。set 维护即可。
代码
赛时代码比较抽象,凑合看吧。
#include<set>
#include<vector>
#include<iostream>
#include<algorithm>
using namespace std;
const int N=3e5+5;
int n,m,fas[N];
vector<pair<int,pair<int,int> > > anu;
set<int> so;
int Findfa(int x){
if(fas[x]!=x) fas[x]=Findfa(fas[x]);
return fas[x];
}
bool HB(int x,int y){
int fx=Findfa(x),fy=Findfa(y);
if(fx==fy) return 0;
fas[fx]=fy;
so.erase(fx);//fx不再是祖先节点,将其从桶中删去
return 1;
}
signed main(){
cin>>n>>m;int f,l,rt,siz=n-1;
for(int i=1;i<=n;i++) fas[i]=i,so.insert(i);
for(int i=1;i<=m;i++){
cin>>f>>l;
if(!HB(f,l))
anu.push_back({i,{f,l}});
else siz--;
}
cout<<siz<<endl;int tot=0,id=1;
while(siz--){
cout<<anu[tot].first<<" "<<anu[tot].second.second<<" ";
int an=0;
for(auto a:so){
if(Findfa(a)!=Findfa(anu[tot].second.first)){
HB(a,anu[tot].second.first);
an=a;break;
}
}
cout<<an<<endl;tot++;
}
return 0;
}