Cod sursa(job #2730139)

Utilizator stefanpiturStefan Alexandru Pitur stefanpitur Data 25 martie 2021 20:13:05
Problema 2SAT Scor 80
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.22 kb
#include <iostream>
#include <cstdio>
#include <fstream>
#include <vector>
using namespace std;

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

const int N = 100000;
const int M = 200000;

vector <int> graph[2*N + 1];
vector <int> graph_inv[2*N + 1];
vector <int> top;

int sol[2*N + 1];
bool completed[2*N + 1];
bool visited[2*N + 1];
bool visited_inv[2*N + 1];

int get_node(int nodeValue, int n){
    return nodeValue + n;
}

int inv(int nodeValue, int n){
    return get_node(-nodeValue, n);
}

void add_edge(int x, int y, int n){
    graph[inv(x, n)].push_back(get_node(y, n));
    graph[inv(y, n)].push_back(get_node(x, n));

    graph_inv[get_node(y, n)].push_back(inv(x, n));
    graph_inv[get_node(x, n)].push_back(inv(y, n));
}

void dfs(int node, int n){
    int nodeValue = get_node(node, n);
    visited[nodeValue] = true;
    for(int p = 0; p < (int)graph[nodeValue].size(); p++){
        int nextValue = graph[nodeValue][p];
        if(!visited[nextValue])
            dfs(nextValue - n, n);
    }
    top.push_back(node);
}

void dfs_inv(int node, int n){
    int nodeValue = get_node(node, n);
    int invValue = inv(node, n);

    if(!completed[nodeValue]){
        completed[nodeValue] = completed[invValue] = true;
        sol[nodeValue] = 0, sol[invValue] = 1;
    }

    visited_inv[nodeValue] = true;
    for(int p = 0; p < (int)graph_inv[nodeValue].size(); p++){
        int nextValue = graph_inv[nodeValue][p];
        if(!visited_inv[nextValue])
            dfs_inv(nextValue - n, n);
    }
}

int main()
{
    int n, m, i, j, x, y;
    fin >> n >> m;
    for(i = 0; i < m; i++){
        fin >> x >> y;
        add_edge(x, y, n);
    }
    // for(i = -n; i <= n; i++){
    //     printf("de la nodul %d : ", i);
    //     for(j = 0; j < (int)graph[get_node(i, n)].size(); j++)
    //         printf("%d ", graph[get_node(i, n)][j] - n);
    //     printf("\n");
    // }
    for(i = -n; i <= n; i++)
        if(!visited[get_node(i, n)] && i)
            dfs(i, n);

    for(i = -n; i <= n; i++)
        sol[get_node(i, n)] = -1;
    
    for(i = (int)top.size() - 1; i >= 0; i--)
        if(!visited_inv[get_node(top[i], n)])
            dfs_inv(top[i], n);
    for(i = 1; i <= n; i++)
        fout << sol[get_node(i, n)] << ' ';
    return 0;
}