换了三个做法调了一整天 /youl
并查集不知道能不能做,写了很久想不出来哪里挂了,看着题解好像也大差不差,红温了于是重构。
考虑启发式合并吧。
显然的一个点所有出边走到的点都需要合并出边。
用 set 存边集,然后跑 bfs 状物,每次解决后不断的把新出现的需要合并的点扔进队列,这个东西的次数应该是线性的。
每次缩点都至少会少一条边,所以缩点的次数严格不超过 。
然后启发式合并 set,那么时间复杂度就是 。
好的被卡常了。另外的我怎么还写挂了!!重构吧。
考虑不用 set,显然没有去重也可以做。
换用 vector 就好。
时间复杂度 。
警钟,最大值的初始化一定要小。
#include<bits/stdc++.h>
using namespace std;
vector<int>st[200005];
int fa[200005];
int find(int x){
return x==fa[x]?x:fa[x]=find(fa[x]);
}
int ans[200005],top;
int main(){
int n,m;
cin>>n>>m;
while(m--){
int u,v;
cin>>u>>v;
st[u].push_back(v);
}
queue<int>q;
for(int i=1;i<=n;i++){
fa[i]=i;
if(st[i].size()>1)
q.push(i);
}
while(!q.empty()){
int x=q.front();
q.pop();
int mx=-1,qwq=-1;
for(int i:st[x])
if((int)(st[find(i)].size())>mx){
mx=st[find(i)].size();
qwq=find(i);
}
if(qwq==-1)continue;
for(int i:st[x])
if(find(i)!=find(qwq)){
for(auto j:st[find(i)])
st[qwq].push_back(j);
st[find(i)].clear();
fa[find(i)]=find(qwq);
}
st[x].clear();
st[x].push_back(qwq);
if(st[qwq].size()>1)q.push(qwq);
}
for(int i=1;i<=n;i++){
if(ans[find(i)]==0)ans[find(i)]=++top;
cout<<ans[find(i)]<<'\n';
}
return 0;
}