Pagini recente » Cod sursa (job #821240) | Cod sursa (job #2951826) | Cod sursa (job #2191716) | Cod sursa (job #1285823) | Cod sursa (job #1545216)
#include <fstream>
#include <iostream>
#include <vector>
using namespace std;
int nodes, edges, t;
int Lista[200010], C[200010], v[200010], _count, v_final[200010];
vector<int> graph[200010], graphT[200010], v2[200010];
void dfs1(int i)
{
v[i] = 1;
for (int j = 0; j<graph[i].size(); j++)
{
if (!v[graph[i][j]])
{
dfs1(graph[i][j]);
}
}
Lista[_count--] = i;
//for (int i = 1; i <= 2 * nodes; i++)
//cout << Lista[i] << " ";
//cout << endl;
}
void dfs2(int i)
{
C[i] = t;
for (int j = 0; j<graphT[j].size(); j++)
{
if (!C[graphT[i][j]])
{
dfs2(graphT[i][j]);
}
}
}
void initialize()
{
ifstream f("2sat.in");
f >> nodes >> edges;
int val1, val2, c1, c2;
t = 1;
_count = nodes * 2;
for (int i = 1; i <= edges; i++)
{
f >> val1 >> val2;
if (val1 > 0 && val2 > 0)
{
graph[val1+nodes].push_back(val2);
graph[val2+nodes].push_back(val1);
graphT[val2].push_back(val1+nodes);
graphT[val1].push_back(val2+nodes);
}
else if (val1 > 0 && val2 < 0)
{
graph[val1 + nodes].push_back(-val2 + nodes);
graph[-val2].push_back(val1);
graphT[-val2 + nodes].push_back(val1 + nodes);
graphT[val1].push_back(-val2);
}
else if (val1 < 0 && val2>0)
{
graph[-val1].push_back(val2);
graph[val2+nodes].push_back(val1);
graphT[val2].push_back(-val1);
graphT[val1].push_back(val2+nodes);
}
else
{
graph[-val1].push_back(-val2 + nodes);
graph[-val2].push_back(-val1 + nodes);
graphT[-val2 + nodes].push_back(-val1);
graphT[-val1 + nodes].push_back(-val2);
}
}
}
void solve()
{
for (int i = 1; i <= nodes * 2; i++)
if (!v[i])
dfs1(i);
t = 1;
for (int i = 1; i <= nodes * 2; i++)
{
if (!C[Lista[i]])
{
dfs2(Lista[i]);
t++;
}
}
for (int i = 1; i <= nodes << 2; i++)
{
v2[C[i]].push_back(i);
}
////
for (int i = 1; i < t; i++)
{
if (!v_final[v2[i][0]])
{
int j = 0;
while (j < v2[i].size())
{
{
v_final[v2[i][j]] = 1;
if (v2[i][j]>nodes)
v_final[v2[i][j] - nodes] = 2;
else
v_final[v2[i][j] + nodes] = 2;
}
j++;
}
}
}
}
void print(char path[])
{
ofstream fout(path);
for (int i = 1; i <= nodes; i++)
if (C[i] == C[i + nodes])
{
fout << -1;
//return 0;
break;
}
for (int i = 1; i <= nodes; i++)
fout << v_final[i] - 1 << " ";
}
int main()
{
initialize();
solve();
print("2sat.out");
//cin.get();
}