题意:
略复杂不会概括。
题解:
每次都将一个点能连出的点并在一起,然后再让他们bfs,一直缩,直到缩不动。
code:
#include<iostream>
#include<cstdio>
#include<cstring>
#define N 100005
using namespace std;
int n,m,tot,fa[N],sz[N],pnt[N<<2],nxt[N<<2],h[N],od[N]; bool bo[N];
int read(){
int x=0; char ch=getchar();
while (ch<'0' || ch>'9') ch=getchar();
while (ch>='0' && ch<='9'){ x=x*10+ch-'0'; ch=getchar(); }
return x;
}
struct graph{
int fst[N];
void add(int x,int y){
pnt[++tot]=y; nxt[tot]=fst[x]; fst[x]=tot;
}
}g1,g2;
int getfa(int x){
return (x==fa[x])?x:fa[x]=getfa(fa[x]);
}
void merge(int x,int y){
int u=getfa(x),v=getfa(y); if (sz[u]>sz[v]) swap(u,v);
if (u!=v){ fa[u]=v; sz[v]+=sz[u]; }
}
int main(){
n=read(); m=read(); int i,x,y;
for (i=1; i<=m; i++){
x=read(); y=read(); od[x]++;
g1.add(x,y); g2.add(y,x);
}
for (i=1; i<=n; i++){ sz[i]=1; fa[i]=i; }
for (i=1; i<=n; i++){
for (x=g1.fst[i]; x; x=nxt[x]) bo[pnt[x]]=1;
for (x=g2.fst[i]; x; x=nxt[x])
if (bo[pnt[x]]) merge(i,pnt[x]);
for (x=g1.fst[i]; x; x=nxt[x]) bo[pnt[x]]=0;
}
for (i=1; i<=n; i++){
for (x=g1.fst[i],y=0; x; x=nxt[x])
if (y) merge(pnt[x],y); else y=pnt[x];
}
int head=0,tail=0; memset(bo,1,sizeof(bo));
for (i=1; i<=n; i++)
if (sz[getfa(i)]>1){ bo[i]=0; h[++tail]=i; }
while (head<tail){
x=h[++head];
for (i=g1.fst[x]; i; i=nxt[i]){
y=pnt[i]; merge(x,y);
if (bo[y]){ bo[y]=0; h[++tail]=y; }
}
}
long long ans=0;
for (i=1; i<=n; i++)
if (getfa(i)==i)
if (sz[i]>1) ans+=(long long)sz[i]*(sz[i]-1);
else ans+=od[i];
printf("%lld\n",ans);
return 0;
}