Cod sursa(job #520825)

Utilizator ciprianfFarcasanu Alexandru Ciprian ciprianf Data 10 ianuarie 2011 16:12:40
Problema Andrei Scor 20
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.51 kb
#include <stdio.h>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
#define FOR(i, v) for(vector<int>::iterator i = v.begin(); i != v.end(); ++i)
#define NMAX 200010
vector <int> G[NMAX];
queue <int> q, q2;
int SOL[NMAX], viz[NMAX];
int n, m;
int OK;
inline int real(int x){
	if(x < 0) return n-x;
	return x;
}
inline int other(int x){
	if(x > n) return x-n;
	return x+n;
}
void relax(int x){
	FOR(i, G[x])
		if(!viz[*i]){
			SOL[*i] = 1;
			viz[*i] = viz[other(*i)] = 1;
			q2.push(other(*i));
			q.push(other(*i));
		}
		else if(SOL[*i] == 0) OK = 1;
}
void sterge(int x){
	SOL[x] = SOL[other(x)] = viz[x] = viz[other(x)] = 0;
}
int check(int y, int val){
	while(!q.empty()) q.pop();
	SOL[y] = val;
	if(val == 1) y = other(y);
	OK = 0;
	q2.push(y);
	q.push(y);
	while(!q.empty()){
		if(OK) return 0;
		int x = q.front();
		q.pop();
		relax(x);
	}
	return 1;
}
void add(int x, int y){
	G[real(x)].push_back(real(y));
	G[real(y)].push_back(real(x));
}
int main(){
	freopen("andrei.in", "r", stdin);
	freopen("andrei.out", "w", stdout);
	scanf("%d%d", &n, &m);
	for(int i = 1; i <= m; ++i){
		int x, y, c;
		scanf("%d%d%d", &x, &y, &c);
		if(c == 0)add(x,y);
		else if(c == 1) add(-x,-y);
		else add(x,-y),add(-x,y);
	}
	for(int i = 1; i <= n; ++i)
		if(!viz[i]) {
			if(!check(i, 0)){
				while(!q2.empty()) sterge(q2.front()), q2.pop();
				if(!check(i, 0)){
					printf("-1\n");
					return 0;
				}
			}
			while(!q2.empty()) q2.pop();
		}
	for(int i = 1; i <= n; ++i)
		printf("%d ", SOL[i]);
	return 0;
}