Cod sursa(job #3361902)

Utilizator brianabucur11Briana Bucur brianabucur11 Data 29 iulie 2026 18:52:23
Problema 2SAT Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.96 kb
#include <bits/stdc++.h>

using namespace std;

ifstream fin ("2sat.in");
ofstream fout ("2sat.out");

const int nmax = 2e5 + 5;

int n, m, fr[nmax], ap[nmax];

vector <int> g[nmax], gt[nmax], scc[nmax];

stack <int> st;

void dfs (int node)
{
    fr[node] = 1;
    for (auto it : g[node])
    {
        if (!fr[it])
            dfs (it);
    }
    st.push (node);
}

void dfst (int node, int k)
{
    scc[k].push_back (node);
    fr[node] = 0;
    for (auto it : gt[node])
    {
        if (fr[it])
            dfst (it, k);
    }
}

void kosaraju ()
{
    int cnt = 0;
    for (int i = 1; i <= 2 * n; i++)
    {
        if (!fr[i])
            dfs (i);
    }
    while (!st.empty ())
    {
        int x = st.top ();
        st.pop ();
        if (fr[x])
        {
            cnt++;
            dfst (x, cnt);
        }
    }
    for (int i = 1; i <= cnt; i++)
    {
        for (auto it : scc[i])
        {
            ap[it] = i;
            if (it >= n + 1 && ap[it - n] == i)
            {
                fout << -1;
                return;
            }
            if (it <= n && ap[it + n] == i)
            {
                fout << -1;
                return;
            }
        }
    }
}

signed main ()
{
    fin >> n >> m;
    for (int i = 1; i <= m; i++)
    {
        int x, y;
        fin >> x >> y;
        if (x < 0)
            x = -x + n;
        if (y < 0)
            y = -y + n;
        if (x >= n + 1)
        {
            g[x - n].push_back (y);
            gt[y].push_back (x - n);
        }
        else
        {
            g[x + n].push_back (y);
            gt[y].push_back (x + n);
        }
        if (y >= n + 1)
        {
            g[y - n].push_back (x);
            gt[x].push_back (y - n);
        }
        else
        {
            g[y + n].push_back (x);
            gt[x].push_back (y + n);
        }
    }
    kosaraju ();
    return 0;
}