Cod sursa(job #826664)

Utilizator mihai995mihai995 mihai995 Data 1 decembrie 2012 00:06:01
Problema 2SAT Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.28 kb
#include <fstream>
#include <iostream>
#include <vector>
#include <stack>
#include <cstring>
#include <algorithm>
using namespace std;

const int N = 100005;

class Sat{
    vector<int> etc1[2 * N], *graph;
    vector<int> etc2[2 * N], *trans;
    int etc3[2 * N], *ctc, size;
    bool etc4[2 * N], *use;
    stack<int> S;

    void reset(){
        memset(etc4, false, sizeof(etc4));
    }

    void unalloc(vector<int>& v){
        vector<int> a;
        a.swap(v);
    }

    void dfs(int x){
        use[x] = true;

        for (vector<int> :: iterator it = trans[x].begin() ; it != trans[x].end() ; it++)
            if (!use[*it])
                dfs(*it);

        S.push(x);
    }

    void dfs(int x, int C){
        ctc[x] = C;
        use[x] = true;

        for (vector<int> :: iterator it = graph[x].begin() ; it != graph[x].end() ; it++)
            if (!use[*it])
                dfs(*it, C);
    }

    void get_ctc(){
        int nr = 0;

        reset();

        for (int i = -size ; i <= size ; i++)
            if (!use[i])
                dfs(i);

        reset();

        while (!S.empty()){
            if (!use[S.top()])
                dfs(S.top(), ++nr);

            S.pop();
        }
    }
public:
    Sat(){
        graph = etc1 + N;
        trans = etc2 + N;
        ctc = etc3 + N;
        use = etc4 + N;
    }

    void push(int x, int y){
        graph[-x].push_back(y);
        graph[-y].push_back(x);

        trans[x].push_back(-y);
        trans[y].push_back(-x);
    }

    vector<int> get_sat(int n){
        size = n;

        get_ctc();

        vector<int> v;

        for (int i = 1 ; i <= size ; i++)
            if (ctc[i] == ctc[-i]){
                v.clear();
                v.push_back(-1);
                return v;
            } else
                v.push_back(ctc[i] < ctc[-i]);
        return v;
    }
};
Sat S;

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

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

    in >> n >> m;

    while (m--){
        in >> x >> y;

        S.push(x, y);
    }

    vector<int> v = S.get_sat(n);

    for (vector<int> :: iterator it = v.begin() ; it != v.end() ; it++)
        out << (*it) << " ";

    out << "\n";

    return 0;
}