Cod sursa(job #3320318)

Utilizator Ruxandra009Ruxandra Vasilescu Ruxandra009 Data 4 noiembrie 2025 21:56:44
Problema 2SAT Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.3 kb
#include <fstream>
#include <vector>
#include <stack>

using namespace std;

const string txt = "2sat";
const int nmax = 2e5 + 5;

ifstream f(txt + ".in");
ofstream g(txt + ".out");

int n, m, scc[nmax], fr[nmax];
vector<int> v[nmax], v2[nmax], aux;

static void dfs(int node, vector<int> v[], int tip = 0)
{
    fr[node] = 1;
    for (auto x : v[node])
        if (!fr[x]) dfs(x, v, tip);

    if (!tip) aux.push_back(node);
    else scc[node] = tip;
}

int main()
{
    f >> n >> m;
    for (int i = 1; i <= m; i++)
    {
        int x, y; f >> x >> y;
        
        v[-x + n].push_back(y + n);
        v[-y + n].push_back(x + n);

        v2[y + n].push_back(-x + n);
        v2[x + n].push_back(-y + n);
    }

    for (int i = 0; i < n; i++)
        if (!fr[i]) dfs(i, v);

    for (int i = n + 1; i <= 2 * n; i++)
        if (!fr[i]) dfs(i, v);

    for (int i = 0; i <= 2 * n; i++) fr[i] = 0;

    int ind = 1;
    for (int i = aux.size() - 1; i >= 0; i--)
        if (!fr[aux[i]]) dfs(aux[i], v2, ind), ind++;

    int oki = 1;
    for (int i = 1; i <= n; i++)
        if (scc[i + n] == scc[-i + n]) oki = 0;
    
    if (!oki) g << -1;
    else 
        for (int i = 1; i <= n; i++)
            g << (scc[-i + n] > scc[i + n] ? 0 : 1) << " ";
    
    return 0;
}