Cod sursa(job #1196628)

Utilizator howsiweiHow Si Wei howsiwei Data 8 iunie 2014 15:41:22
Problema 2SAT Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.38 kb
#include <iostream>
#include <cstdio>
#include <vector>
#include <unordered_set>
#include <cstdio>
#include <ctime>
using namespace std;

int main()
{
	srand(time(NULL));
	ios::sync_with_stdio(false);
	freopen("2sat.in", "r", stdin);
	freopen("2sat.out", "w", stdout);
	int n, m;
	cin >> n >> m;
	vector<int> expr(2*m);
	vector<vector<int>> usein(n);
	vector<bool> ispos(2*m, true);
	for (int i = 0; i < 2*m; i++) {
		cin >> expr[i];
		if (expr[i] < 0) {
			expr[i] = -expr[i];
			ispos[i] = false;
		}
		expr[i]--;
		usein[expr[i]].push_back(i/2);
	}
	vector<bool> b(n);
	for (int i = 0; i < n; i++) {
		b[i] = rand()&1;
	}
	unordered_set<int> t;
	vector<bool> in_t(m);
	for (int i = 0; i < m; i++) {
		int j = 2*i;
		if (!(b[expr[j]] == ispos[j] || b[expr[j+1]] == ispos[j+1])) {
			t.insert(i);
			in_t[i] = true;
		}
	}

	int trial = 0;
	int maxtrial = 10*m;
	while (!t.empty()) {
		int r = 2*(*t.begin());
		if (rand()&1) {
			r += 1;
		}
		r = expr[r];
		b[r] = !b[r];
		for (auto i: usein[r]) {
			int j = 2*i;
			if (b[expr[j]] == ispos[j] || b[expr[j+1]] == ispos[j+1]) {
				if (in_t[i]) {
					t.erase(i);
					in_t[i] = false;
				}
			}
			else {
				if (!(in_t[i])) {
					t.insert(i);
					in_t[i] = true;
				}
			}
		}
		trial++;
		if (trial > maxtrial) {
			printf("-1\n");
			return 0;
		}
	}
	for (int i = 0; i < n; i++) {
		printf("%c ", b[i] ? '1' : '0');
	}
	printf("\n");
	return 0;
}