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 ; iQ;
    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);
        }
    }
}

 

你可能感兴趣的:(图论模板)