Cod sursa(job #2669268)

Utilizator Mihai145Oprea Mihai Adrian Mihai145 Data 6 noiembrie 2020 17:18:08
Problema 2SAT Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.55 kb
#include <fstream>
#include <vector>
#include <stack>

using namespace std;

ifstream cin("2sat.in");
ofstream cout("2sat.out");

const int NMAX = 1e5;

int N, M;
vector <int> g[2 * NMAX + 5], r[2 * NMAX + 5];
bool vis[2 * NMAX + 5];

int Val(int x)
{
    if(x < 0) return -x;
    return x + N;
}

int Not(int x)
{
    if(x < 0) return -x + N;
    return x;
}

stack <int> st;
void dfs(int node)
{
    vis[node] = true;

    for(auto it : g[node])
        if(!vis[it]) dfs(it);

    st.push(node);
}

int scc, comp[2 * NMAX + 2];
void dfs2(int node)
{
    comp[node] = scc;
    vis[node] = true;

    for(auto it : r[node])
        if(!vis[it]) dfs2(it);
}

int main()
{
    cin >> N >> M;

    for(int i = 1; i <= M; i++)
    {
        int x, y;
        cin >> x >> y;

        g[Not(x)].push_back(Val(y));
        g[Not(y)].push_back(Val(x));

        r[Val(y)].push_back(Not(x));
        r[Val(x)].push_back(Not(y));
    }

    for(int i = 1; i <= 2 * N; i++)
        if(!vis[i]) dfs(i);

    for(int i = 1; i <= 2 * N; i++)
        vis[i] = false;

    while(!st.empty())
    {
        int node = st.top();
        st.pop();

        if(!vis[node])
        {
            ++scc;
            dfs2(node);
        }
    }

    for(int i = 1; i <= N; i++)
        if(comp[i] == comp[i + N])
        {
            cout << -1 << '\n';
            return 0;
        }

    for(int i = 1; i <= N; i++)
        if(comp[i + N] > comp[i]) cout << 1 << ' ';
        else cout << 0 << ' ';

    return 0;
}