Cod sursa(job #3380037)

Utilizator ItsHezovPahonie George Alessio ItsHezov Data 1 decembrie 2026 19:27:49
Problema 2SAT Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.78 kb
#include <fstream>
#include <algorithm>
#include <vector>
using namespace std;
ifstream cin("2sat.in");
ofstream cout("2sat.out");
const int mxN = 2e5 + 10;
vector<int> adj[mxN+1], rev[mxN+1], order;
int visited[mxN+1], compID[mxN+1], sol[mxN+1], nrComp, n , m ;
int literal(int x, bool value)
{
    return 2 * x + value;
}
int positive(int x)
{
    return literal(x,true);
}
int negative(int x)
{
    return literal(x,false);
}
int opposite(int x)
{
    return x ^ 1;
}
void addOr(int a, int b)
{
    adj[opposite(a)].push_back(b);
    adj[opposite(b)].push_back(a);

    rev[a].push_back(opposite(b));
    rev[b].push_back(opposite(a));
}
void DFS1(int node)
{
    visited[node] = true;
    for(auto it : adj[node])
        if(!visited[it])
            DFS1(it);
    order.push_back(node);
}
void DFS2(int node)
{
    compID[node] = nrComp;
    visited[node] = true;
    for(auto it : rev[node])
        if(!visited[it])
            DFS2(it);
}
bool hasSolution()
{
    for(int i = 1;i<=n;i++)
        if(compID[positive(i)] == compID[negative(i)])
            return false;
    return true;
}
int main()
{
    cin >> n >> m;
    for(int i = 1;i<=m;i++)
    {
        int a, b;
        cin >> a >> b;
        int A = literal(abs(a), a > 0);
        int B = literal(abs(b), b > 0);
        addOr(A,B);
    }

    for(int i = 1;i<=2*n+1;i++)
        if(!visited[i])
            DFS1(i);
    fill(visited+1,visited+2*n+2,0);
    reverse(order.begin(),order.end());
    for(auto it : order)
        if(!visited[it])
            nrComp++, DFS2(it);
    if(!hasSolution())
    {
        cout << -1 << '\n';
        return 0;
    }
    for(int i = 1;i<=n;i++)
        cout << (compID[positive(i)] > compID[negative(i)]) << ' ';
    return 0;
}