Pagini recente » Cod sursa (job #901185) | Cod sursa (job #2574423) | Cod sursa (job #158716) | Cod sursa (job #955370) | Cod sursa (job #2472635)
#include<iostream>
#include<stack>
#include<vector>
#include<fstream>
using namespace std;
const int MAX_N = 1e5 + 9;
int n, m, a, b;
vector<int> sys[MAX_N*2];
int br, broi;
int index[MAX_N*2];
int lowLink[MAX_N*2];
int ans[MAX_N*2];
int comp[MAX_N*2];
stack<int> st;
bool onStack[MAX_N*2];
int compCount;
vector<int> output;
void dfs(int currV)
{
index[currV] = br;
lowLink[currV] = br;
br++;
st.push(currV);
onStack[currV] = true;
for(int i = 0; i < sys[currV].size(); i++){
int nextV = sys[currV][i];
if(index[nextV] == -1){
dfs(nextV);
lowLink[currV] = min(lowLink[currV], lowLink[nextV]);
}else if(onStack[nextV]){
lowLink[currV] = min(lowLink[currV], index[nextV]);
}
}
if(index[currV] == lowLink[currV]){
while(st.top() != currV){
int c = st.top();
st.pop();
onStack[c] = false;
comp[c] = compCount;
output.push_back(c);
}
output.push_back(currV);
st.pop();
onStack[currV] = false;
comp[currV] = compCount;
//output.push_back(-1);
compCount++;
}
}
int main(){
ofstream myfileout;
myfileout.open ("2sat.out");
ifstream myfilein;
myfilein.open("2sat.in");
myfilein >> n >> m;
for(int i = 0; i < m; i++){
myfilein >> a >> b;
int ca = a;
int cb = b;
a = -a;
if(a < 0){
a = -a;
a--;
a = a*2 + 1;
}else{
a--;
a = a*2;
}
if(b < 0){
b = -b;
b--;
b = b*2 + 1;
}else{
b--;
b = b*2;
}
//cout << a << " " << b << endl;
sys[a].push_back(b);
a = ca;
b = cb;
b = -b;
if(a < 0){
a = -a;
a--;
a = a*2 + 1;
}else{
a--;
a = a*2;
}
if(b < 0){
b = -b;
b--;
b = b*2 + 1;
}else{
b--;
b = b*2;
}
//cout << b << " " << a << endl << endl;
sys[b].push_back(a);
}
for(int i = 0; i < MAX_N*2; i++){
lowLink[i] = -1;
index[i] = -1;
ans[i] = -1;
}
for(int i = 0; i < n; i++){
if(index[i] == -1){
dfs(i);
}
}
//cout << compCount << endl;
for(int i = 0; i < output.size(); i++){
//if(ans[comp[output[i]]] == -1){
//broi++;
if(output[i]%2 == 0){
if(comp[output[i]] == comp[output[i]+1]){
myfileout << "-1\n";
return 0;
}
if(ans[comp[output[i]]] == -1){
ans[comp[output[i]]] = 1;
ans[comp[output[i]+1]] = 0;
}
}else{
if(comp[output[i]] == comp[output[i]-1]){
myfileout << "-1\n";
return 0;
}
if(ans[comp[output[i]]] == -1){
ans[comp[output[i]]] = 1;
ans[comp[output[i]-1]] = 0;
}
}
//}
}
for(int i = 0; i < n; i++){
myfileout << ans[comp[i*2]] << " ";
}
myfileout << endl;
return 0;
}
/*
*/