Pagini recente » Cod sursa (job #1919122) | Cod sursa (job #2950515) | Cod sursa (job #47813) | Cod sursa (job #875950) | Cod sursa (job #1141114)
#include <fstream>
#include <iostream>
#include <iterator>
#include <stack>
#include <vector>
#include <algorithm>
using namespace std;
int N, M;
stack<int> st;
vector<int> ctcIndex;
vector<int> lowlink;
vector<int> idx;
vector<bool> uz;
int contor;
vector<vector<int> > ctc;
vector<int> values;
vector<vector<int> > G;
int Map(int x)
{
if (x > 0)
x--;
else
{
x = - x;
x --;
x += N;
}
return x;
}
int Non(int x)
{
if (x < N)
x += N;
else
x -= N;
return x;
}
void tarjan(int x)
{
idx[x] = lowlink[x] = ++ contor;
st.push(x);
for (vector<int>::iterator itr = G[x].begin();
itr != G[x].end();
itr++)
{
if (idx[*itr] == -1)
{
tarjan(*itr);
lowlink[x] = min(lowlink[x], lowlink[*itr]);
}
else if (uz[*itr] == false)
{
lowlink[x] = min(lowlink[x], lowlink[*itr]);
}
}
if (lowlink[x] == idx[x])
{
int n = -1;
vector<int> newCtc;
while (n != x)
{
n = st.top();
st.pop();
uz[n] = true;
ctcIndex[n] = ctc.size();
newCtc.push_back(n);
}
ctc.push_back(newCtc);
}
}
int main()
{
fstream fin("2sat.in", ios::in);
fstream fout("2sat.out", ios::out);
fin >> N >> M;
ctcIndex.resize(2 * N, -1);
idx.resize(2 * N, -1);
lowlink.resize(2 * N, -1);
uz.resize(2 * N, false);
G.resize(2 * N);
values.resize(N, -1);
for (int i = 0; i < M; i++)
{
int x, y;
fin >> x >> y;
x = Map(x);
y = Map(y);
G[Non(x)].push_back(y);
G[Non(y)].push_back(x);
}
for (int i = 0; i < 2 * N; i++)
{
if (idx[i] == -1)
{
tarjan(i);
}
}
bool ok = true;
for (int i = 0; i < N; i++)
{
if (ctcIndex[i] == ctcIndex[Non(i)])
{
ok = false;
break;
}
}
if (ok == false)
{
fout << -1 << "\n";
}
if (ok == true)
{
for (vector<vector<int> >::reverse_iterator itr = ctc.rbegin();
itr != ctc.rend();
itr++)
{
for (vector<int>::iterator jtr = itr->begin();
jtr != itr->end();
jtr++)
{
int newValue = 0;
int x = *jtr;
if (x >= N)
{
newValue = 1;
x -= N;
}
if (values[x] == -1)
{
values[x] = newValue;
}
else
{
break;
}
}
}
copy(values.begin(), values.end(), ostream_iterator<int>(fout, " "));
fout << "\n";
}
fout.close();
fin.close();
}