强连通分量+缩点(记录所缩点的个数)

#include <stdio.h>
#include <algorithm>
#include <string.h>
#include <iostream>
#include <stack>
using namespace std;
#define M 10005
#define N 105
struct note
{
    int v,next;
}edge[M];

int head[N],dfn[N],low[N],belong[N],index,ip,cnt_tar,cont[N],instack[N*2];

void init()
{
    memset(head,-1,sizeof(head));
    ip=0;
}

stack <int> q;
int n;
void addedge(int u,int v)//新增一条边的操作
{
    edge[ip].v=v,edge[ip].next=head[u],head[u]=ip++;
}
void tarjan(int u)
{
    dfn[u]=low[u]=++index;//为节点u设定次序编号和low初值
    q.push(u);//将节点u压入栈中
    instack[u]=1;//点u在栈内
    for(int i=head[u];i!=-1;i=edge[i].next)//枚举每一条边
    {
        int v=edge[i].v;
        if(!dfn[v])//如果节点v未被访问过
        {
            tarjan(v);//继续向下找
            low[u]=min(low[u],low[v]);
        }
        else if(instack[v])//如果节点还在栈内
            low[u]=min(low[u],dfn[v]);
    }
    if(dfn[u]==low[u])//如果节点u是强连通分量的根
    {
        cnt_tar++;//计数加一
        int j;
        do
        {
            j=q.top();//将v退栈
            q.pop();
            belong[j]=cnt_tar;//该强连通分量的最后一个出栈的点作为一个缩点出现在新的待建的图中作为该强连通分量的代表
            instack[j]=0;//点u出栈
            cont[cnt_tar]++;//记录这一强连通分量中所包含的点的个数;
        }while(j!=u);
    }
}
void solve()
{
    index=0,cnt_tar=0;
    memset(dfn,0,sizeof(dfn));
    memset(low,0,sizeof(low));
    memset(instack,0,sizeof(instack));
    memset(cont,0,sizeof(cont));
    for(int i=1;i<=n;i++)
    {
        if(!dfn[i])
           tarjan(i);
    }
}
//主函数里面调用init,solve函数就可以了

你可能感兴趣的:(强连通分量+缩点(记录所缩点的个数))