Pagini recente » Cod sursa (job #1999977) | Cod sursa (job #1862726) | Cod sursa (job #2338135) | Cod sursa (job #841286) | Cod sursa (job #2508315)
#include <bits/stdc++.h>
#define ll long long
#define all(a) (a).begin(), (a).end()
#pragma GCC optimize("O3")
#pragma GCC optimize("Ofast")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
#define sz() size()
#define fr first
#define sc second
#define pb push_back
#define er erase
#define in insert
#define pi pair<int,int>
#define pii pair<pair<int,int>,int>
#define mp make_pair
#define int long long
#define rc(s) return cout<<s,0
#define rcc(s) cout<<s,exit(0)
using namespace std;
const int mod=1e9+7;
const int modp=1999999973;
const int modx=998244353;
int n,m,sol[200005];
bitset<200005>viz;
vector<int>nod1[200005],nod2[200005],parc;
int non(int x){
return((x>n)? x-n:x+n);
}
void DFS1(int s){
viz[s]=1;
for(auto it:nod1[s]) if(!viz[it]) DFS1(it);
parc.push_back(s);
}
bool DFS2(int s){
if(sol[s]==1){
sol[0]=-1;
return 0;
}
sol[non(s)]=1;
viz[s]=1;
for(auto it:nod2[s]){
if(!viz[it]) if(DFS2(it)==0) return 0;
}
return 1;
}
int32_t main(){
ios_base::sync_with_stdio(false);cin.tie(0);cerr.tie(0);cout.tie(0);
srand(chrono::steady_clock::now().time_since_epoch().count());
ifstream fin("2sat.in");
ofstream fout("2sat.out");
fin >> n >> m;
for(int i=1;i<=m;i++){
int x,y;
fin >> x >> y;
if(x<0) x=non(x);
if(y<0) y=non(y);
int xx=non(x),yy=non(y);
nod1[xx].push_back(y);
nod1[yy].push_back(x);
nod2[x].push_back(yy);
nod2[y].push_back(xx);
}
for(int i=1;i<=2*n;i++) if(!viz[i]) DFS1(i);
for(int i=1;i<=2*n;i++) viz[i]=0;
while(parc.size()){
int curr=parc.back(); parc.pop_back();
if(!viz[curr] && !viz[non(curr)]){
if(DFS2(curr)==0) break;
}
}
if(sol[0]==-1){
fout << -1;
return 0;
}
else fout << -1;
return 0;
}