Cod sursa(job #2927707)

Utilizator cristia_razvanCristia Razvan cristia_razvan Data 21 octombrie 2022 09:42:06
Problema 2SAT Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.65 kb
#include <bits/stdc++.h>
using namespace std;

#define pb push_back
#define mp make_pair
#define dbg(x) cout << #x <<": " << x << "\n";
#define sz(x) ((int)x.size())

using ll = long long;

const string fn = "2sat";
ifstream fin(fn + ".in");
ofstream fout(fn + ".out");

const int mxn = 100005;


int n, m;
bool bad = false;
vector<int> g[200005], revg[200005];
bitset<200005> viz;
vector<int> topo;
bool ans[200005];

int neg(int x){
    if(x < n)
        return x + n;
    return x - n;
}

void adde(int x, int y){

    if(x < 0)
        x = -x + n;
    if(y < 0)
        y = -y + n;
    --x; --y;
    int nx = neg(x), ny = neg(y);
    g[nx].pb(y);
    g[ny].pb(x);
    revg[y].pb(nx);
    revg[x].pb(ny);

}

void dfs(int nod){

    viz[nod] = 1;
    for(auto i : g[nod])
        if(viz[i] == 0)
            dfs(i);
    topo.pb(nod);

}

void dfsR(int nod){

    if(bad)
        return;
    if(ans[nod])
        bad = true;
    viz[nod] = false;
    ans[neg(nod)] = true;
    for(auto i : revg[nod])
        if(viz[i])
            dfsR(i);

}


int main() {

	ios_base::sync_with_stdio(false);
	cin.tie();

    fin >> n >> m;
    for(int i = 0; i < m; ++i){
        int x, y;
        fin >> x >> y;
        adde(x, y);
    }
    for(int i = 0; i < 2 * n; ++i)
        if(!viz[i])
            dfs(i);
    reverse(topo.begin(), topo.end());
    for(auto i : topo){
        if(viz[i] == 1 && viz[neg(i)] == 1)
            dfsR(i);
    }
    if(bad)
        fout << "-1\n";
    else{
        for(int i = 0; i < n; ++i)
            fout << ans[i] << " ";
        fout << '\n';
    }

	return 0;
}