Pagini recente » Cod sursa (job #2621676) | Cod sursa (job #2623863) | Monitorul de evaluare | Cod sursa (job #1691546) | Cod sursa (job #3304964)
#include <unordered_map>
#include <fstream>
#include <vector>
#include <queue>
#include <stack>
using namespace std;
const string txt = "2sat";
const int nmax = 2e5 + 5;
ifstream f(txt + ".in");
ofstream g(txt + ".out");
int n, m, k, per[nmax], ans[nmax];
vector<int> comp[nmax], aux;
unordered_map< int, vector<int> > v[5], v2;
unordered_map<int, int> c, fr, nr;
queue<int> q;
static void dfs(int nod, int tip)
{
fr[nod] = tip + 1;
for (auto x : v[tip][nod])
if (fr[x] != tip + 1)
dfs(x, tip);
if (!tip) aux.push_back(nod);
else c[nod] = k, comp[k].push_back(nod);
}
int main()
{
f >> n >> m;
for (int i = 1; i <= m; i++)
{
int x, y; f >> x >> y;
v[0][-x].push_back(y);
v[0][-y].push_back(x);
v[1][x].push_back(-y);
v[1][y].push_back(-x);
}
for(int i = 1; i <= n; i ++)
if(!fr[i])
dfs(i, 0);
for (int i = aux.size() - 1; i >= 0; i--)
if (fr[aux[i]] != 2)
k++, dfs(aux[i], 1);
fr.clear();
for (int j = 1; j <= k; j ++)
for(auto nod : comp[j])
for (auto x : v[0][nod])
if (fr[c[x]] != c[nod] && c[x] != c[nod])
{
v2[c[nod]].push_back(c[x]);
nr[c[x]]++; fr[c[x]] = c[nod];
}
for (int i = 1; i <= n; i++)
per[c[i]] = c[-i], per[c[-i]] = c[i];
for (int i = 1; i <= k; i++)
if (!nr[i]) q.push(i);
fr.clear();
while (!q.empty())
{
while (!q.empty() && fr[q.front()]) q.pop();
if (q.empty()) break;
int nod = q.front(); fr[nod] = fr[per[nod]] = 1;
ans[nod] = 0; ans[per[nod]] = 1;
for (auto x : v2[nod])
{
nr[x]--;
if (!nr[x]) q.push(x);
}
for (auto x : v2[per[nod]])
{
nr[x]--;
if (!nr[x]) q.push(x);
}
}
g << -1;
//for (int i = 1; i <= n; i++)
// g << ans[c[i]] << " ";
return 0;
}