Pagini recente » Cod sursa (job #2565348) | Cod sursa (job #1040616) | Cod sursa (job #757170) | Cod sursa (job #2124686) | Cod sursa (job #2470215)
#define _CRT_SECURE_NO_WARNINGS
#include <cstdio>
#include <vector>
#include <algorithm>
int index = 1;
int n, m;
std::vector<bool> on_stack, value;
std::vector<unsigned> stack, v_index, parent, visited;
std::vector<std::vector<unsigned>> graph, components;
bool strong_connect_visit(int v)
{
v_index[v] = index;
parent[v] = index;
index += 1;
on_stack[v] = true;
stack.push_back(v);
for (unsigned i = 0; i < graph[v].size(); ++i)
{
if (v_index[graph[v][i]] == 0) // !visited
{
strong_connect_visit(graph[v][i]);
parent[v] = std::min(parent[v], parent[graph[v][i]]);
}
else if (on_stack[graph[v][i]])
{
parent[v] = std::min(parent[v], parent[graph[v][i]]);
}
}
if (parent[v] == v_index[v])
{
unsigned w;
// std::cout << "\n";
components.push_back(std::vector<unsigned>());
do {
w = stack.back();
stack.pop_back();
on_stack[w] = false;
// std::cout << w << " ";
components.back().push_back(w);
} while (w != v);
}
return true;
}
bool strong_connect()
{
for (int i = 1; i <= 2 * n; ++i)
{
if (!v_index[i])
{
if (strong_connect_visit(i))
return false;
}
}
return true;
}
void assign()
{
value.resize(n + 1);
visited.resize(2 * n + 1);
while (components.size())
{
for (int i = 0; i < components.back().size(); ++i)
{
if (visited[components.back()[i]]) break;
if (components.back()[i] > n)
{
value[components.back()[i] - n] = true;
visited[components.back()[i]] = true;
visited[components.back()[i] - n] = true;
}
else
{
value[components.back()[i]] = false;
visited[components.back()[i]] = true;
visited[components.back()[i] + n] = true;
}
}
components.pop_back();
}
for (int i = 1; i <= n; ++i)
printf("%d ", value[i] ? 1 : 0);
}
void read()
{
scanf("%d %d", &n, &m);
graph.resize(2 * n + 1);
on_stack.resize(2 * n + 1);
v_index.resize(2 * n + 1);
parent.resize(2 * n + 1);
for (int i = 0; i < m; ++i)
{
int src, dst;
int nsrc, ndst;
scanf("%d %d", &src, &dst);
if (src < 0) src = -src + n;
if (dst < 0) dst = -dst + n;
if (src > n) nsrc = src - n;
else nsrc = src + n;
if (dst > n) ndst = dst - n;
else ndst = dst + n;
graph[nsrc].push_back(dst);
graph[ndst].push_back(src);
}
}
int main()
{
freopen("2sat.in", "r", stdin);
freopen("2sat.out", "w", stdout);
read();
if (strong_connect())
{
printf("-1");
return 0;
}
assign();
return 0;
}