Pagini recente » Cod sursa (job #2111501) | Cod sursa (job #1408982) | Cod sursa (job #546382) | Cod sursa (job #139125) | Cod sursa (job #2973961)
#include <bits/stdc++.h>
#define N 200007
using namespace std;
ifstream fin("2sat.in");
ofstream fout("2sat.out");
int n,ncomp,m,nn;
vector<int> g[N];
vector<int> gt[N];
vector<int> comp[N];
vector <bool>viz(N,0);
vector <int>st(N,0);
/// not(x) = x + TX
int negat(int x)
{
if( x<0 )
{
return -x;
}
if( x>n )
return x-n;
return x+n;
}
int adevarat(int x)
{
if( x<0 )
{
return -x+n;
}
if( x>n )
return -(x-n);
return x;
}
void Citire()
{
fin >> n >> m;nn=2*n;
for(int i=1;i<=m;i++)
{
int x,y;
fin >> x >> y;
//cout << i << "\n";
g[ negat(x) ].push_back(adevarat(y));
//cout << negat(x) << " " << adevarat(y) << "\n";
g[ negat(y) ].push_back(adevarat(x));
//cout << negat(y) << " " << adevarat(x) << "\n";
gt[ adevarat(y) ].push_back(negat(x));
gt[ adevarat(x) ].push_back(negat(y));
}
fin.close();
}
void dfs1(int x)
{
viz[x]=1;
for(auto y:g[x])
if( !viz[y] )
dfs1(y);
st[nn--]=x;
}
void dfs2(int x)
{
viz[x]=0;
for(auto y:gt[x])
if( viz[y] )
dfs2(y);
comp[ncomp].push_back(x);
}
void Kosaraju()
{
for(int i=1;i<=2*n;i++)
if( !viz[i] )
dfs1(i);
for(int i=1;i<=2*n;i++)
if( viz[ st[i] ] )
{
ncomp++;
dfs2( st[i] );
}
// das good
}
bool Exista()
{
for(int i=1;i<=ncomp;i++)
{
set<int> bucket;
int sz=comp[i].size();
for(int j=0;j<sz;j++)
{
if( bucket.count( adevarat(comp[i][j]) ) )return 0;
bucket.insert( adevarat(comp[i][j]) ) ;
}
}
return 1;
}
int main()
{
Citire();
Kosaraju();
if( !Exista() )fout << "-1\n";
/// ... .. .. ... . .. etc
fout.close();
return 0;
}