Cod sursa(job #3239479)

Utilizator butasebiButa Gabriel-Sebastian butasebi Data 5 august 2024 18:59:10
Problema 2SAT Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.64 kb
# include<bits/stdc++.h>
using namespace std;
int n, m, x, y;
vector<int> G[200005], GT[200005];
bool viz[200005], not_possible, tf[200005];
int neg(int x)
{
    if(x > n)
        return x - n;
    return x + n;
}
stack<int> s;
void DFS(int x)
{
    viz[x] = true;
    for(int i = 0; i < G[x].size(); i ++)
    {
        int aux = G[x][i];
        if(viz[aux] == false)
            DFS(aux);
    }
    s.push(x);
}

void DFS2(int x)
{
    viz[x] = true;
    if(tf[x] == true)
        not_possible = true;

    tf[neg(x)] = true;

    for(int i = 0; i < GT[x].size(); i ++)
    {
        int aux = GT[x][i];
        if(viz[aux] == false)
            DFS2(aux);
    }
}
int main()
{
    ifstream f("2sat.in");
    ofstream g("2sat.out");

    f >> n >> m;
    for(int i = 1; i <= m; i ++)
    {
        f >> x >> y;

        // negations converted to positive positions
        if(x < 0)
            x = -x + n;

        if(y < 0)
            y = -y + n;

        // x V y => !x -> y and !y -> x
        G[neg(x)].push_back(y);
        G[neg(y)].push_back(x);

        // as above but transposed
        GT[x].push_back(neg(y));
        GT[y].push_back(neg(x));
    }

    for(int i = 1; i <= n * 2; i ++)
        if(viz[i] == false)
            DFS(i);

    memset(viz, 0, sizeof(viz));

    while(! s.empty())
    {
        int aux = s.top();
        s.pop();

        if(viz[aux] == false && viz[neg(aux)] == false)
            DFS2(aux);
    }

    if(not_possible)
    {
        g << "-1\n";
        return 0;
    }

    for(int i = 1; i <= n; i ++)
        g << tf[i] << " ";
    return 0;
}