Jzoj3899 逻辑的连通性

题意:给你一个图,求出每个节点所在的联通快的大小总和

显然就是tarjan找强连通分量了,没啥好说

//#pragma GCC optimize("O3")
//#pragma G++ optimize("O3")
#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<stack>
using namespace std;
struct Edge{ int v,nt; } G[600010];
int h[50010]={0},C=0;
int dfn[50010],low[50010],clk=0;
int n,m,col[50010],cnt=0,b[50010];
bool in[50010]; stack<int> st;
inline void adj(int x,int y){
	G[++C]=(Edge){y,h[x]}; h[x]=C;
}
void dfs(int u){
	dfn[u]=low[u]=++clk;
	st.push(u); in[u]=1;
	for(int v,i=h[u];i;i=G[i].nt)
		if(!dfn[v=G[i].v]){
			dfs(v);
			low[u]=min(low[u],low[v]);
		} else if(in[v]) low[u]=min(low[u],dfn[v]);
	if(low[u]==dfn[u]){
		++cnt; 
		for(int v;(v=st.top())!=u;){
			col[v]=cnt; b[cnt]++;
			in[v]=0; st.pop();
		}
		col[u]=cnt; b[cnt]++; 
		in[u]=0; st.pop();
	}
}
int main(){
	long long ans=0;
	scanf("%d%d",&n,&m);
	for(int x,y,i=0;i<m;++i){
		scanf("%d%d",&x,&y);
		adj(x,y);
	}
	for(int i=1;i<=n;++i) if(!dfn[i]) dfs(i);
	for(int i=1;i<=cnt;++i) ans+=(long long)b[i]*(b[i]-1)>>1;
	printf("%lld\n",ans);
}

posted @ 2017-10-03 19:44  扩展的灰(Extended_Ash)  阅读(104)  评论(0编辑  收藏  举报