bzoj 4243: 交朋友

题意:

略复杂不会概括。

题解:

每次都将一个点能连出的点并在一起,然后再让他们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;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值