BZOJ1997 2-sat

1 篇文章 0 订阅

题目:http://www.lydsy.com/JudgeOnline/problem.php?id=1997

大意:给一个哈密顿回路以及其他边,问是否图中任意两条无重合顶点的边不相交。

对于两条边,要么连外面要么连里面。然后就可以2-sat啦。(当边数大于点数*3时肯定不合法)

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
struct sef { int ne,en; }h[1000050];
int tot,first[2030];
int T,n,m,ex[10020],ey[10050],pos[2004];
int sum,Be[2030];
int stk[2030],top,low[2030],dfn[2030],tim;
bool vis[2030];
inline bool Judge(int x,int y)
{
    return (y-x==1||y-x==n-1);
}
inline bool Cr(int i,int j)
{
    return (ex[i]<ex[j]&&ex[j]<ey[i]&&ey[i]<ey[j]);
}
inline void setl(int x,int y)
{
    h[++tot].ne=first[x]; h[tot].en=y;
    first[x]=tot;

    h[++tot].ne=first[y]; h[tot].en=x;
    first[y]=tot;
}
void Dfs(int x)
{
    vis[x]=1;
    stk[++top]=x;
    low[x]=dfn[x]=++tim;
    int y;
    for (int i=first[x];y=h[i].en,i;i=h[i].ne) 
        if (!dfn[y]) {
            Dfs(y);
            low[x]=min(low[x],low[y]);
        } else if (vis[y]) low[x]=min(low[x],dfn[y]);
    if (low[x]==dfn[x]) {
        ++sum;  
        while (stk[top]!=x) {
            Be[stk[top]]=sum;
            vis[stk[top]]=0;
            --top;
        }
        Be[x]=sum; vis[x]=0;
        --top;
    }
}
int main()
{
    scanf("%d",&T);
    while (T--) {
        scanf("%d%d",&n,&m);
        for (int i=1;i<=m;++i) scanf("%d%d",&ex[i],&ey[i]);
        int x;
        for (int i=1;i<=n;++i) {
            scanf("%d",&x); pos[x]=i;
        }
        if (m>n*3) { printf("NO\n"); continue; }
        tot=0;  memset(first,0,sizeof(first));
        for (int i=1;i<=m;++i) {
            ex[i]=pos[ex[i]]; ey[i]=pos[ey[i]];
            if (ex[i]>ey[i]) swap(ex[i],ey[i]); 
            if (!Judge(ex[i],ey[i])) {
                for (int j=1;j<i;++j) 
                    if (!Judge(ex[j],ey[j])) {
                        if (Cr(i,j)||Cr(j,i)) {
                            setl(i*2-1,j*2);
                            setl(i*2,j*2-1);
                        }
                    }
            }
        }
        tim=top=sum=0; memset(dfn,0,sizeof(dfn));
        for (int i=1;i<=m*2;++i)
            if (!dfn[i]) Dfs(i);
        bool boo=false;
        for (int i=1;i<=m;++i)
            if (Be[i*2-1]==Be[i*2]) { boo=true; break; }
        if (boo) printf("NO\n");
        else printf("YES\n");
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值