2-SAT(强连通缩点,拓扑排序求任意解)

int tol,head[maxn];
int dol,dead[maxn];
struct edge
{
    int to,next;
}es[maxm],dag[maxm];
void addedge( int u , int v )
{
    es[tol].to = v;
    es[tol].next = head[u];
    head[u] = tol++;
}
void add( int u , int v )
{
    dag[dol].to = v;
    dag[dol].next = dead[u];
    dead[u] = dol++;
}
int Low[maxn],Dfn[maxn],Stack[maxn],Belong[maxn];
int Index,Top,scc,num[maxn];
bool Instack[maxn];
void dfs( int u )
{
    int v;
    Low[u] = Dfn[u] = ++Index;
    Stack[Top++] = u;
    Instack[u] = true;
    for ( int i=head[u] ; i!=-1 ; i=es[i].next )
    {
        v = es[i].to;
        if ( !Dfn[v] )
        {
            dfs( v );
            if ( Low[u]>Low[v] ) Low[u] = Low[v];
        }
        else if ( Instack[v]&&Low[u]>Dfn[v] )
            Low[u] = Dfn[v];
    }
    if ( Low[u]==Dfn[u] )
    {
        scc++;
        do
        {
            v = Stack[--Top];
            Instack[v] = false;
            Belong[v] = scc;
            num[scc]++;
        }while( v!=u );
    }
}
bool solvable( int n )
{
    memset( Dfn , 0 , sizeof(Dfn) );
    memset( Instack , false , sizeof(Instack) );
    memset( num , 0 , sizeof(num) );
    Index = scc = Top = 0;
    for ( int i=0 ; i<n ; i++ )
        if ( !Dfn[i] ) dfs( i );
    for ( int i=0 ; i<n ; i+=2 )
        if ( Belong[i]==Belong[i^1] ) return false;
    return true;
}
char color[maxn]; int indeg[maxn],cf[maxn];
void solve( int n )
{
    dol = 0; memset ( dead , -1 , sizeof(dead) );
    memset ( indeg , 0 , sizeof(indeg) );
    memset ( color , 0 , sizeof(color) );
    for ( int u=0 ; u<n ; u++ )
        for ( int i=head[u] ; i!=-1 ; i=es[i].next )
        {
            int v = es[i].to;
            if ( Belong[u]!=Belong[v] )
            {
                add( Belong[v] , Belong[u] );
                indeg[Belong[u]]++;
            }
        }
    for ( int i=0 ; i<n ; i+=2 )
    {
        cf[Belong[i]] = Belong[i^1];
        cf[Belong[i^1]] = Belong[i];
    }
    queue<int>Q;
    for ( int i=1 ; i<=scc ; i++ )
        if ( indeg[i]==0 ) Q.push(i);
    while( !Q.empty() )
    {
        int u = Q.front(); Q.pop();
        if ( color[u]==0 )
        {
            color[u] = 'R';
            color[cf[u]] = 'B';
        }
        for ( int i=dead[u] ; i!=-1 ; i=dag[i].next )
        {
            int v = dag[i].to;
            indeg[v]--;
            if ( indeg[v]==0 )
                Q.push(v);
        }
    }
}

 

    原文作者:拓扑排序
    原文地址: https://blog.csdn.net/Game_Acm/article/details/82459436
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞