【CCF】高速公路 tarjan强连通缩点

【题意】

给定一个有向图,问图中互相可达(强连通)的点有多少对

【AC】

强连通缩点,缩点后是一个DAG,所以互相可达的点只在强连通块里。

#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
#include<algorithm>

using namespace std;
int n,m;
const int maxn=1e4+2;
const int maxm=1e5+2;
struct edge{
    int to;
    int nxt;
}e[maxm];
int head[maxn];
int tot;
int S[maxn],top;
int dfn[maxn],low[maxn],id;
int belong[maxn],num;
bool vis[maxn];
int circle[maxn];
void init(){
    memset(head,-1,sizeof(head));
    tot=0;
    id=top=num=0;
    memset(dfn,0,sizeof(dfn));
    memset(low,0,sizeof(low));
    memset(vis,false,sizeof(vis));
    memset(circle,0,sizeof(circle));
}
void add(int u,int v){
    e[tot].to=v;
    e[tot].nxt=head[u];
    head[u]=tot++;
}
void tarjan(int u)
{
    dfn[u]=low[u]=++id;
    S[++top]=u;
    vis[u]=true;
    for(int i=head[u];i!=-1;i=e[i].nxt)
    {
        int v=e[i].to;
        if(!dfn[v])
        {
            tarjan(v);
            low[u]=min(low[u],low[v]);
        }
        else if(vis[v]) low[u]=min(low[u],dfn[v]);
    }
    if(dfn[u]==low[u])
    {
        num++;
        while(1)
        {
            belong[S[top]]=num;
            vis[S[top]]=false;
            if(S[top--]==u) break;
        }
    }
}

int main(){
    while(~scanf("%d%d",&n,&m)){
        init();
        int u,v;
        for(int i=1;i<=m;i++){
            scanf("%d%d",&u,&v);
            add(u,v);    
        }
        for(int i=1;i<=n;i++){
            if(!dfn[i]) tarjan(i);
        }
        for(int i=1;i<=n;i++){
            circle[belong[i]]++; 
        }
        int ans=0;
        for(int i=1;i<=num;i++){
            ans+=circle[i]*(circle[i]-1)/2;
        }
        printf("%d\n",ans);
    }
    return 0;
} 

 

转载于:https://www.cnblogs.com/itcsl/p/9192589.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值