Cod sursa(job #1545196)

Utilizator BrokePetronel Catalin Joldescu Broke Data 6 decembrie 2015 15:45:10
Problema 2SAT Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 2.45 kb
#include <fstream>
#include <vector>
using namespace std;
int nodes, edges, t;
int Lista[200005], C[200005], v[200005], _count, v_final[200005];
vector<int> graph[200005], graphT[200005], v2[200005];

void dfs1(int i)
{
	v[i] = 1;
	for (int j = 0; j<graph[i].size(); j++)
	{
		if (!v[graph[i][j]])
		{
			dfs1(graph[i][j]);
		}
	}
	Lista[_count--] = i; 
	//for (int i = 1; i <= 2 * nodes; i++)
		//cout << Lista[i] << " ";
	//cout << endl;
}
void dfs2(int i)
{
	C[i] = t;
	for (int j = 0; j<graphT[j].size(); j++)
	{
		if (!C[graphT[i][j]])
		{
			dfs2(graphT[i][j]);
		}
	}
}


void initialize()
{
	ifstream f("2sat.in");
	f >> nodes >> edges;
	int val1, val2, c1, c2;
	t = 1;
	_count = nodes * 2;
	for (int i = 1; i <= edges; i++)
	{
		f >> val1 >> val2;
		if (val1 > 0 && val2 > 0)
		{
			graph[val1+nodes].push_back(val2);
			graph[val2+nodes].push_back(val1);
			graphT[val2].push_back(val1+nodes);
			graphT[val1].push_back(val2+nodes);
		}
		else if (val1 > 0 && val2 < 0)
		{
			graph[val1 + nodes].push_back(-val2 + nodes);
			graph[-val2].push_back(val1);
			graphT[-val2 + nodes].push_back(val1 + nodes);
			graphT[val1].push_back(-val2);
		}
		else if (val1 < 0 && val2>0)
		{
			graph[-val1].push_back(val2);
			graph[val2+nodes].push_back(val1);
			graphT[val2].push_back(-val1);
			graphT[val1].push_back(val2+nodes);
		}
		else
		{
			graph[-val1].push_back(-val2 + nodes);
			graph[-val2].push_back(-val1 + nodes);
			graphT[-val2 + nodes].push_back(-val1);
			graphT[-val1 + nodes].push_back(-val2);
		}
	}
}

void solve()
{
	for (int i = 1; i <= nodes * 2; i++)
		if (!v[i])
			dfs1(i);

	t = 0;
	for (int i = 0; i < nodes * 2; i++)
	{
		if (!C[Lista[i]])
		{
			dfs2(Lista[i]);
			t++;
		}
	}
	for (int i = 1; i <= nodes << 2; i++)
	{
		v2[C[i]].push_back(i);
	}
	////
	for (int i = 1; i < t; i++)
	{
		if (!v_final[v2[i][0]])
		{
			int j = 0;
			while (j < v2[i].size())
			{
				{
					v_final[v2[i][j]] = 1;
					if (v2[i][j]>nodes)
						v_final[v2[i][j] - nodes] = 2;
					else
						v_final[v2[i][j] + nodes] = 2;
				}
				j++;
			}
		}
	}
}

void print(char path[])
{
	ofstream fout(path);
	for (int i = 1; i <= nodes; i++)
		if (C[i] == C[i + nodes])
		{
			fout << -1;
			//return 0;
			break;
		}

	for (int i = 1; i <= nodes; i++)
		fout << v_final[i] - 1 << " ";
}

int main()
{
	initialize();
	solve();
	print("2sat.out");

	//cin.get();
}