Cod sursa(job #2967724)

Utilizator vmnechitaNechita Vlad-Mihai vmnechita Data 19 ianuarie 2023 23:54:22
Problema 2SAT Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.33 kb
#include <bits/stdc++.h>
#define ll long long
#define pb push_back
#define pf push_front
#define MOD 1000000007
#define MAX 100005

using namespace std;

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

vector < int > a, v[2*MAX], cv[2*MAX];
int nr, componenta[2*MAX];
bool viz[2*MAX];

void dfs1(int nod);
void dfs2(int nod);

int main()
{
    int n, m, x, y, i;

    fin >> n >> m;
    for(i = 1; i <= m; i++)
    {
        fin >> x >> y;
        if(x < 0) x = -x + n;
        if(y < 0) y = -y + n;

        if(x > n) v[x-n].pb(y), cv[y].pb(x - n);
        else v[x+n].pb(y), cv[y].pb(x + n);

        if(y > n) v[y-n].pb(x), cv[x].pb(y - n);
        else v[y+n].pb(x), cv[x].pb(y + n);
    }
    for(i = 1; i <= 2 * n; i++) if(viz[i] == 0) dfs1(i);
    reverse(a.begin(), a.end());


    for(int it:a) if(componenta[it] == 0) nr++, dfs2(it);

    bool ok = 1;
    for(i = 1; i <= n && ok == 1; i++) if(componenta[i] == componenta[i+n]) ok = 0;

    if(ok == 0) fout << -1;
    else for(i = 1; i <= n; i++) fout << (componenta[i] > componenta[i+n]) << ' ';


    return 0;
}

void dfs1(int nod)
{
    viz[nod] = 1;
    for(int it:v[nod]) if(viz[it] == 0) dfs1(it);
    a.pb(nod);
}

void dfs2(int nod)
{
    componenta[nod] = nr;
    for(int it:cv[nod]) if(componenta[it] == 0) dfs2(it);
}