Cod sursa(job #468797)

Utilizator ilincaSorescu Ilinca ilinca Data 5 iulie 2010 03:29:57
Problema Andrei Scor 0
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.03 kb
#include <cstdio>
#include <vector>
#include <queue>

#define pmax 200005
#define pb push_back

using namespace std;

typedef vector <int> VI;
int n, nc, grup [pmax], val [pmax], deg [pmax];
VI c, g [pmax], gt [pmax], ctc [pmax];
bool viz [pmax];

inline int neg (int x)
{return (x<=n)? x+n:x-n;}

void scan ()
{
	int m, a, b, s;
	scanf ("%d%d", &n, &m);
	for (; m; --m)
	{
		scanf ("%d%d%d", &a, &b, &s);
		if (s == 0)
		{
			g [a].pb (neg (b));
			g [b].pb (neg (a));
			gt [neg (b)].pb (a);
			gt [neg (a)].pb (b);
		}
		if (s == 1)
		{
			g [neg (a)].pb (b);
			g [neg (b)].pb (a);
			gt [b].pb (neg (a));
			gt [a].pb (neg (b));
		}
		if (s == 2)
		{
			g [a].pb (b);
			g [neg (a)].pb (neg (b));
			gt [b].pb (a);
			gt [neg (b)].pb (neg (a));
		}
	}
}

void dfs1 (int x)
{
	viz [x]=true;
	for (int i=0; i < g [x].size (); ++i)
		if (!viz [g [x] [i]]) dfs1 (g [x] [i]);
	c.pb (x);
}

void dfs2 (int x)
{
	grup [x]=nc;
	ctc [nc].pb (x);
	for (int i=0; i < gt [x].size (); ++i)
		if (!grup [gt [x] [i]]) dfs2 (gt [x] [i]);
}

void scc ()
{
	int i;
	for (i=1; i <= 2*n; ++i)
		if (!viz [i]) dfs1 (i);
	for (i=c.size ()-1; i >= 0; --i)
		if (!grup [c [i]]) {++nc; dfs2 (c [i]);}
}

void dsat ()
{
	queue<int> q;
	int i, j, k, gr, x;
	for (i=1; i <= nc; ++i)
		for (j=0; j < ctc [i].size (); ++j)
			for (k=0; k < g [ctc [i] [j]].size (); ++k)
			{
				gr=grup [g [ctc [i] [j]] [k]];
				if (gr != i) ++deg [gr];
			}	
	for (i=1; i <= nc; ++i) if (deg [i] == 0) q.push (i);
	while (!q.empty ())
	{
		x=q.front ();
		q.pop ();
		if (val [x] == 1) continue;
		val [x]=0;
		val [grup [neg (ctc [x] [0])]]=1;
		for (i=0; i < ctc [x].size (); ++i)
			for (j=0; j < g [ctc [x] [i]].size (); ++j)
			{
				gr=grup [g [ctc [x] [i]] [j]];
				if (gr != x) 
				{
					--deg [gr];
					if (deg [gr] == 0)
						q.push (gr);
				}
			}
	}
}

void print ()
{
	for (int i=1; i <= n; ++i) printf ("%d ", val [grup [i]]);
	printf ("\n");
}

int main ()
{
	freopen ("andrei.in", "r", stdin);
	freopen ("andrei.out", "w", stdout);
	scan ();
	scc ();
	dsat ();
     	print ();	
	return 0;
}