Pagini recente » Cod sursa (job #2478520) | Cod sursa (job #195279) | Cod sursa (job #1492500) | Cod sursa (job #54677) | Cod sursa (job #2593494)
#include <bits/stdc++.h>
using namespace std;
ifstream fin("andrei.in");
ofstream fout("andrei.out");
class TwoSat {
private:
int n;
vector<vector<int>> adG, adT;
inline int non(int x) {
return (x > n ? x - n : x + n);
}
void addEdge(int x, int y) {
adG[x].push_back(y);
adT[y].push_back(x);
}
void dfsG(int node, vector<bool>& vis, vector<int>& topo) {
vis[node] = true;
for (int nghb : adG[node])
if (!vis[nghb])
dfsG(nghb, vis, topo);
topo.push_back(node);
}
void dfsT(int node, vector<bool>& vis, vector<bool>& ans) {
vis[node] = false;
ans[non(node)] = true;
for (int nghb : adT[node])
if (vis[nghb])
dfsT(nghb, vis, ans);
}
public:
TwoSat(int n) :
n(n), adG(2 * n + 1), adT(2 * n + 1) { }
void addProp(int x, int y) {
if (x < 0) x = n - x;
if (y < 0) y = n - y;
addEdge(non(x), y);
addEdge(non(y), x);
}
vector<bool> solve() {
vector<bool> vis(2 * n + 1);
vector<int> topo;
for (int i = 1; i <= 2 * n; i++)
if (!vis[i])
dfsG(i, vis, topo);
reverse(topo.begin(), topo.end());
vector<bool> ans(2 * n + 1);
for (int node : topo)
if (vis[node] && vis[non(node)])
dfsT(node, vis, ans);
ans.resize(n + 1);
return ans;
}
};
int main() {
int n, m; fin >> n >> m;
TwoSat graph(n);
for (int i = 0; i < m; i++) {
int x, y, t; fin >> x >> y >> t;
if (t == 0)
graph.addProp(+x, +y);
else if (t == 1)
graph.addProp(-x, -y);
else {
graph.addProp(-x, +y);
graph.addProp(+x, -y);
}
}
auto ans = graph.solve();
for (int i = 1; i <= n; i++)
fout << ans[i] << ' ';
fout << '\n';
fout.close();
return 0;
}