Cod sursa(job #2948801)

Utilizator Giulian617Buzatu Giulian Giulian617 Data 28 noiembrie 2022 13:04:52
Problema 2SAT Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.11 kb
#include <bits/stdc++.h>
using namespace std;
ifstream f("2sat.in");
ofstream g("2sat.out");
const int NMAX=200005;///we keep double the number of nodes because we have x and !x
int n,m,x,y,negation_x,negation_y,no_scc;
vector<int>order,component,graph[NMAX],GT[NMAX];
bitset<NMAX>used;
bitset<NMAX/2>value;
void dfs(int node)
{
    used[node]=1;
    for(int next:graph[node])
        if(!used[next])
            dfs(next);
    order.push_back(node);
}
void dfsGT(int node)
{
    used[node]=1;
    component[node]=no_scc;///we know that this will be in topological order
    for(int next:GT[node])
        if(!used[next])
            dfsGT(next);
}
bool satisfiability()
{
    for(int i=1; i<=n; i++)
        if(component[i]==component[i+n])
            return 0;
        else if(component[i]>component[i+n])
            value[i]=1;
    return 1;
}
int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    f>>n>>m;
    component.resize(2*n+1,0);
    for(int i=1; i<=m; i++)
    {
        f>>x>>y;
        x=(x<0)?n-x:x;///n-x goes to n+(abs(x))
        y=(y<0)?n-y:y;
        negation_x=(x>n)?x-n:x+n;///x-n if x is already negated, x+n otherwise
        negation_y=(y>n)?y-n:y+n;
        graph[negation_x].push_back(y);
        graph[negation_y].push_back(x);
        GT[y].push_back(negation_x);
        GT[x].push_back(negation_y);
    }
    n*=2;///because we now have x and the negation of x as variables;
    for(int i=1; i<=n; i++)
        if(!used[i])
            dfs(i);
    used.reset();
    reverse(order.begin(),order.end());///because from the first dfs with get the in the non-decreasing order and we want them in the non-increasing order
    for(int i=0; i<(int)order.size(); i++)
        if(!used[order[i]])
        {
            no_scc++;
            dfsGT(order[i]);
        }
    n/=2;///because we will check the variables related to their negations, which start from n+1(where n is the one from the input)
    if(satisfiability())
    {
        for(int i=1; i<=n; i++)
            g<<value[i]<<' ';
    }
    else
        g<<-1;
    return 0;
}