Pagini recente » Cod sursa (job #1981215) | Cod sursa (job #1794565) | Cod sursa (job #1908248) | Cod sursa (job #242295) | Cod sursa (job #1598257)
//============================================================================
// Name : 2SAT.cpp
// Author : Teodor Cotet
// Version :
// Copyright : Your copyright notice
// Description : SAT in O in O(N + M) C++, Ansi-style
//============================================================================
#include <fstream>
#include <vector>
#include <iostream>
#include <cstring>
#include <stack>
#include <set>
using namespace std;
const int NMAX = 100000;
const int MMAX = 200000;
ifstream fin("2sat.in");
ofstream fout("2sat.out");
int n; int m;
/*
* constructors for vector:
* v(int size)
* v(int size, TYPE value)
*/
vector< vector<int> > g(NMAX * 2 + 1, vector<int>(0));
vector< vector<int> > gTranspose(NMAX * 2 + 1, vector<int>(0));
int st[NMAX * 2 + 1];
bool visited[NMAX * 2 + 1];
int solution[NMAX * 2 + 1];
vector< vector<int> > strongComp;
bool existSolution = true;
int negateNode(int x) {
return (x == n) ? (2 * n) : (x + n) % (2 * n);
}
void read() {
fin >> n >> m;
for(int i = 0 ; i < m ; ++i) {
int x; int y;
fin >> x >> y;
if(x < 0) x = -x + n;
if(y < 0) y = -y + n;
/* p v q <=> !p -> q sau !q ->p */
g[negateNode(x)].push_back(y);
g[negateNode(y)].push_back(x);
gTranspose[y].push_back(negateNode(x));
gTranspose[x].push_back(negateNode(y));
}
}
void dfs(int curent, vector< vector<int> >& g, bool visited[]) {
visited[curent] = 1;
for(vector<int>::iterator it = g[curent].begin(); it != g[curent].end(); ++it) {
if(visited[*it] == 0)
dfs(*it, g, visited);
}
st[++st[0]] = curent;
}
void topologicalSort(vector< vector<int> >& g, vector< vector<int> >& gTranspose) {
/* do a topological sort first */
memset(visited, 0, 2 * n + 1);
for(int i = 1; i <= 2 * n ; ++i) {
if(visited[i] == 0)
dfs(i, g, visited);
}
/* if there is a node which "enters" in the first node from the topological sort, it
* means they are in the same strong connected component, so we make a dfs in the transpose graph
*/
}
void dfsOnTranspose(int curent, vector< vector<int> >& gT, bool visited[]) {
if(solution[curent] == 1)//oppose are the same, wrong
existSolution = false;
solution[negateNode(curent)] = 1;
visited[curent] = 1;
for(unsigned i = 0 ; i < gT[curent].size(); ++i)
if(visited[ gT[curent][i] ] == 0)
dfsOnTranspose(gT[curent][i], gT, visited);
}
void solveSat() {
memset(visited, 0, 2 * n + 1);
for(int i = st[0] ; i > 0 ; --i) {
int node = st[i];
if(visited[node] == 0 && visited[negateNode(node)] == 0)
dfsOnTranspose(node, gTranspose, visited);
}
}
void printSolution() {
if(existSolution == false)
fout << -1 ;
else {
for(int i = 1; i <= n; ++i)
fout << solution[i] << " ";
}
}
void solve() {
topologicalSort(g, gTranspose);
solveSat();
printSolution();
}
int main() {
read();
solve();
return 0;
}