Cod sursa(job #1907115)

Utilizator LucianTLucian Trepteanu LucianT Data 6 martie 2017 17:51:54
Problema 2SAT Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.68 kb
#include <bits/stdc++.h>
#define maxN 2*100005
using namespace std;
bool in_stk[maxN];
int stk[maxN],top;
int n,m,i,j,x,y,val[maxN],cntscc;
int low[maxN],idx[maxN],curr,scc[maxN];
vector<int> v[maxN],crt_scc;
inline int opposite(int x) /* node corresponding to negation of x */
{
    if(x>n)
        return x-n;
    return x+n;
}
void tarjan(int nod)
{
    low[nod]=idx[nod]=++curr;
    stk[++top]=nod;
    in_stk[nod]=true;

    for(auto it:v[nod]) /* updating lowlink */
        if(!idx[it]){
            tarjan(it);
            low[nod]=min(low[nod],low[it]);
        }
        else if(in_stk[it])
            low[nod]=min(low[nod],idx[it]);

    if(low[nod]==idx[nod]) /* new scc */
    {
        ++cntscc;
        int newn;
        do
        {
            newn=stk[top--];
            in_stk[newn]=false;
            scc[newn]=cntscc;
            if(!val[newn]) /* assigning values to nodes */
                val[newn]=1,val[opposite(newn)]=-1;
        }while(nod!=newn);
    }
}
int main()
{
    freopen("2sat.in","r",stdin);
    freopen("2sat.out","w",stdout);
    scanf("%d %d",&n,&m);
    for(i=1;i<=m;i++)
    {
        scanf("%d %d",&x,&y);
        if(x<0)
            x=n-x;
        if(y<0)
            y=n-y;
        v[opposite(x)].push_back(y); /* edges between negation of x and y */
        v[opposite(y)].push_back(x); /* and vice-versa */
    }
    for(i=1;i<=n;i++) /* finding scc */
        if(!idx[i])
            tarjan(i);
    for(i=1;i<=n;i++)
        if(scc[i]==scc[opposite(i)]){ /* impossible */
            printf("-1");
            return 0;
        }
    for(i=1;i<=n;i++)
        printf("%d ",val[i]>0);
    return 0;
}