poj2723 2-sat

当两个门锁相同时,这个钥匙必须用,不同时分开用

可以直接遍历门,当然二分更快

#include<map>
#include<set>
#include<cmath>
#include<queue>
#include<stack>
#include<vector>
#include<cstdio>
#include<cassert>
#include<iomanip>
#include<cstdlib>
#include<cstring>
#include<iostream>
#include<algorithm>
#define C 0.5772156649
#define pi acos(-1.0)
#define ll long long
#define mod 1000000007
#define ls l,m,rt<<1
#define rs m+1,r,rt<<1|1
#pragma comment(linker, "/STACK:1024000000,1024000000")

using namespace std;

const double g=10.0,eps=1e-7;
const int N=4000+10,maxn=1000+10,inf=0x3f3f3f;

int num,index;
int ins[N],inans[N];
int dfn[N],low[N];
int f1[N],f2[N];
vector<int>v[N];
stack<int>s;
int p[N];
int tarjan(int u)
{
    ins[u]=2;
    dfn[u]=low[u]=++index;
    s.push(u);
    for(int i=0; i<v[u].size(); i++)
    {
        int x=v[u][i];
        if(!dfn[x])
        {
            tarjan(x);
            low[u]=min(low[u],low[x]);
        }
        else if(ins[x]==2)low[u]=min(low[u],dfn[x]);
    }
    if(dfn[u]==low[u])
    {
        ++num;
        while(!s.empty())
        {
            int k=s.top();
            s.pop();
            ins[k]=1;
            inans[k]=num;
            if(k==u)break;
        }
    }
}
void  init(int n)
{
    memset(dfn,0,sizeof dfn);
    memset(low,0,sizeof low);
    memset(ins,0,sizeof ins);
    num=index=0;
}
bool ok(int n)
{
    for(int i=0;i<2*n;i++)
        if(!dfn[i])
           tarjan(i);
    for(int i=0;i<n*2;i+=2)
        if(inans[i]==inans[i^1])
        return 0;
    return 1;
}
int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    int n,m;
    while(cin>>n>>m)
    {
        if(!n&&!m)break;
        memset(inans,0,sizeof inans);
        while(!s.empty())s.pop();
        for(int i=0; i < 2*n; i++)v[i].clear();
        for(int i=0; i < n; i++)
        {
            int a,b;
            cin>>a>>b;
            p[a]=2*i;p[b]=2*i+1;
        }
        for(int i=0; i < m; i++)cin>>f1[i]>>f2[i];
        for(int i=0; i < m; i++)
        {
            int x=p[f1[i]],y=p[f2[i]];
            if(f1[i]==f2[i])v[x].push_back(x^1);
            else v[x^1].push_back(y),v[y^1].push_back(x);
            init(n);
            if(!ok(i))
            {
                cout<<i<<endl;
                break;
            }
            if(i==m-1)cout<<m<<endl;
        }
    }
    return 0;
}
/********************
3 6
0 3
1 2
4 5
0 1
0 2
4 1
4 2
3 5
2 2
0 0
********************/
View Code
原文地址:https://www.cnblogs.com/acjiumeng/p/7337541.html