1. 程式人生 > >USACO06JAN The Cow Prom /// tarjan求強聯通分量 oj24219

USACO06JAN The Cow Prom /// tarjan求強聯通分量 oj24219

cow www pac ack void != gif 大小 htm

題目大意:

n個點 m條邊的圖 求大小大於1的強聯通分量的個數

https://www.cnblogs.com/stxy-ferryman/p/7779347.html

tarjan求完強聯通分量並染色後

計算一下每種顏色的個數 就是每個強聯通塊的大小

技術分享圖片
#include <stdio.h>
#include <cstring>
#include <algorithm>
#include <stack>
using namespace std;

const int N=10005;
struct EDGE { int to, nt; }e[5*N];
int
head[N], tot; int dfn[N], low[N], ind; int col[N], id; bool vis[N]; stack <int> s; int n, m, cnt[N]; void init() { while(!s.empty()) s.pop(); for(int i=0;i<=n;i++) { head[i]=dfn[i]=low[i]=col[i]=-1; vis[i]=cnt[i]=0; } tot=ind=id=0; } void addE(int u,int v) { e[tot].to
=v; e[tot].nt=head[u]; head[u]=tot++; } void tarjan(int u) { dfn[u]=low[u]=ind++; s.push(u); vis[u]=1; for(int i=head[u];i!=-1;i=e[i].nt) { int v=e[i].to; if(dfn[v]==-1) { tarjan(v); low[u]=min(low[u],low[v]); } else {
if(vis[v]) low[u]=min(low[u],low[v]); } } if(dfn[u]==low[u]) { col[u]=++id; vis[u]=0; while(s.top()!=u) { col[s.top()]=id; vis[s.top()]=0; s.pop(); } s.pop(); } } int main() { while(~scanf("%d%d",&n,&m)) { init(); for(int i=1;i<=m;i++) { int u,v; scanf("%d%d",&u,&v); addE(u,v); } for(int i=1;i<=n;i++) if(dfn[i]==-1) tarjan(i); for(int i=1;i<=n;i++) cnt[col[i]]++; int ans=0; for(int i=1;i<=id;i++) if(cnt[i]>1) ans++; printf("%d\n",ans); } return 0; }
View Code

USACO06JAN The Cow Prom /// tarjan求強聯通分量 oj24219