Ikki's Story IV - Panda's Trick POJ - 3207_dfs跑2-SAT
Code:
#include<cstdio>
#include<algorithm>
#include<vector>
using namespace std;
const int maxn=3000;
int c=0;
int mark[maxn],S[maxn],from[maxn],to[maxn];
vector<int>G[maxn];
void add_edge(int x,int y){
x=(x*2)+1,y=(y*2)+1;
G[x-1].push_back(y); //里->外
G[y-1].push_back(x); //里->外
G[x].push_back(y-1); //外->里
G[y].push_back(x-1); //外->里
}
void build(int m){
for(int i=0;i<m-1;++i)
for(int j=i+1;j<m;++j)
if((from[j]<from[i]&&to[j]<to[i]&&to[j]>from[i])||(from[i]<from[j]&&to[i]<to[j]&&to[i]>from[j]))
add_edge(i,j);
}
int dfs(int x)
{
if(mark[x^1])return 0;
if(mark[x])return 1;
mark[x]=1;
++c;
S[c]=x;
int siz=G[x].size();
for(int i=0;i<siz;++i)
if(!dfs(G[x][i]))return 0;
return 1;
}
int solve(int m)
{
for(int i=0;i<m*2;i+=2){
if(!mark[i]&&!mark[i+1])
{
c=0;
if(!dfs(i))
{
while(c>0)
{
mark[S[c]]=0;
c-=1;
}
if(!dfs(i+1))return 0;
}
}
}
return 1;
}
int main(){
int n,m;
scanf("%d %d",&n,&m);
for(int i=0;i<m;++i){
int a,b;
scanf("%d%d",&a,&b);
from[i]=min(a,b);
to[i]=max(a,b);
}
build(m);
if(solve(m))printf("panda is telling the truth...");
else printf("the evil panda is lying again");
return 0;
}