POJ 3905 Perfect Election

2-SAT 裸题,搞之

#include<cstdio>
#include<cstring>
#include<cmath>
#include<stack>
#include<vector>
#include<algorithm>
using namespace std;

const int maxn=2000+10;
int N,M;
char s1[100],s2[100];

stack<int>S;
vector<int>G[maxn];
vector<int>FG[maxn];
int Belong[maxn];
int flag[maxn];
int Block;

void init()
{
    for(int i=0; i<maxn; i++) G[i].clear();
    for(int i=0; i<maxn; i++) FG[i].clear();
    memset(Belong,0,sizeof Belong);
    memset(flag,0,sizeof flag);
    while(!S.empty()) S.pop();
    Block=0;
}

void addEgde(int x,int y)
{
    G[x].push_back(y);
    FG[y].push_back(x);
}

void dfs1(int now)
{
    flag[now]=1;
    for(int i=0; i<G[now].size(); i++)
        if(!flag[G[now][i]])
            dfs1(G[now][i]);
    S.push(now);
}

void dfs2(int now)
{
    Belong[now]=Block;
    for(int i=0; i<FG[now].size(); i++)
        if(!Belong[FG[now][i]])
            dfs2(FG[now][i]);
}

bool judge()
{
    for(int i=0; i<2*N; i++) if(!flag[i]) dfs1(i);
    while(!S.empty())
    {
        int Top=S.top();
        S.pop();
        if(!Belong[Top])
        {
            Block++;
            dfs2(Top);
        }
    }
    for(int i=0; i<N; i++)
        if(Belong[2*i]==Belong[2*i+1])
            return 0;
    return 1;
}

int main()
{
    while(~scanf("%d%d",&N,&M))
    {
        init();
        for(int i=1;i<=M;i++)
        {
            scanf("%s%s",s1,s2);
            int num1=0,num2=0;
            for(int i=1;i<strlen(s1);i++) num1=num1*10+s1[i]-'0';
            for(int i=1;i<strlen(s2);i++) num2=num2*10+s2[i]-'0';
            
            num1--;num2--;
            
            if(s1[0]=='+'&&s2[0]=='+')
            {
                addEgde(2*num1,2*num2+1);
                addEgde(2*num2,2*num1+1);
            }
            if(s1[0]=='-'&&s2[0]=='-')
            {
                addEgde(2*num1+1,2*num2);
                addEgde(2*num2+1,2*num1);
            }
            if(s1[0]=='+'&&s2[0]=='-')
            {
                addEgde(2*num1,2*num2);
                addEgde(2*num2+1,2*num1+1);
            }
            if(s1[0]=='-'&&s2[0]=='+')
            {
                addEgde(2*num1+1,2*num2+1);
                addEgde(2*num2,2*num1);
            }
        }
        if(judge()) printf("1\n");
        else printf("0\n");
    }
    return 0;
}

 

posted @ 2015-10-28 14:45  Fighting_Heart  阅读(150)  评论(0编辑  收藏  举报