强联通

#include<bits/stdc++.h>
using namespace std;
const int maxn=1e6+10;
vector<int> g[maxn];
vector<int> rg[maxn];
vector<int> vs;
bool vis[maxn];
int camp[maxn];
void add_edge(int x,int y) { g[x].push_back(y);   rg[y].push_back(x); }
void dfs(int x)
{
    vis[x]=1;
    for(int i=0;i<g[x].size();i++)   if(!vis[g[x][i]]) dfs(g[x][i]);
    vs.push_back(x);
}
void rdfs(int x,int k)
{
    vis[x]=1;
    camp[k]=k;
    for(int i=0;i<rg[x].size();i++)   if(!vis[rg[x][i]]) rdfs(rg[x][i],k++);
}
int main()
{
    int n,m; cin>>n>>m;
    for(int i=1;i<=m;i++)   {  int x,y; add_edge(x,y);  }
    for(int i=1;i<=n;i++)   {  if(!vis[i]) dfs(i);      }
    memset(vis,0,sizeof(vis));   int k=0;
    for(int i=vs.size();i>=0;i--) {   if(!vis[vs[i]]) rdfs(vs[i],k++);  }
}
#include<bits/stdc++.h>
using namespace std;
const int maxn=1e6+10;
vector<int> g[maxn];
int st[maxn];
int dfn[maxn];
int low[maxn];
int cmp[maxn];
bool vis[maxn];
int number=0,top=0,tot=0;
void tarjan(int x)// x-v;
{
    dfn[x]=++number;
    low[x]=number;
    vis[x]=1;
    st[++top]=x;
    for(int i=0;i<g[x].size();i++)
    {
        int v=g[x][i];
        if(!dfn[v])     { tarjan(v); low[x]=min(low[v],low[x]);}
        else if(vis[v]) { low[x]= min(low[x],dfn[v])          ;}
    }
    if(low[x]==dfn[x])  // lian tong
    {
        cmp[x]=++tot;  // ran se
        vis[x]=0;
        while(st[top]!=x) { cmp[st[top]]=tot; vis[st[top--]]=0; }
        top--;
    }
}
int main()
{
    int n,m; cin>>n>>m;
    for(int i=1;i<=m;i++) {     int x,y;  cin>>x>>y; g[x].push_back(y);    }
    for(int i=1;i<=n;i++) {     if(!dfn[i]) tarjan(i);                      }
    for(int i=1;i<=n;i++) cout<<cmp[i]<<endl;
}
原文地址:https://www.cnblogs.com/Andromeda-Galaxy/p/10425355.html