Pagini recente » Cod sursa (job #989181) | Cod sursa (job #1261763) | Cod sursa (job #1306297) | Cod sursa (job #3209013) | Cod sursa (job #2948812)
#include <bits/stdc++.h>
using namespace std;
ifstream f("2sat.in");
ofstream g("2sat.out");
const int NMAX=200005;///we keep double the number of nodes because we have x and !x
int n,m,x,y,negation_x,negation_y,no_scc;
vector<int>order,component,graph[NMAX],GT[NMAX];
bitset<NMAX>used;
bitset<NMAX/2>value;
void create_graph()
{
f>>n>>m;
for(int i=1; i<=m; i++)
{
f>>x>>y;
x=(x<0)?n-x:x;///n-x goes to n+(abs(x))
y=(y<0)?n-y:y;
negation_x=(x>n)?x-n:x+n;///x-n if x is already negated, x+n otherwise
negation_y=(y>n)?y-n:y+n;
graph[negation_x].push_back(y);
graph[negation_y].push_back(x);
GT[y].push_back(negation_x);
GT[x].push_back(negation_y);
}
}
void dfs(int node)
{
used[node]=1;
for(int next:graph[node])
if(!used[next])
dfs(next);
order.push_back(node);
}
void dfsGT(int node)
{
component[node]=no_scc;///we know that this will be in topological order
for(int next:GT[node])
if(!component[next])
dfsGT(next);
}
void kosaraju()
{
n*=2;///because we now have x and the negation of x as variables;
for(int i=1; i<=n; i++)
if(!used[i])
dfs(i);
component.assign(n+1,0);
reverse(order.begin(),order.end());///because from the first dfs with get the in the non-decreasing order and we want them in the non-increasing order
for(int i=0; i<(int)order.size(); i++)
if(!component[order[i]])
{
no_scc++;
dfsGT(order[i]);
}
}
bool satisfiability()
{
kosaraju();
n/=2;///because we will check the variables related to their negations, which start from n+1(where n is the one from the input)
for(int i=1; i<=n; i++)
if(component[i]==component[i+n])
return 0;
else if(component[i]>component[i+n])
value[i]=1;
return 1;
}
void write()
{
if(satisfiability())
{
for(int i=1; i<=n; i++)
g<<value[i]<<' ';
}
else
g<<-1;
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
create_graph();
write();
return 0;
}