zoukankan      html  css  js  c++  java
  • 洛谷 P4782 【模板】2SAT 问题

    传送门


    解题思路

    思想:将问题转化为图论问题。

    因为一个点只有两个状态,所以每个点可以拆成 i 和 i+n 两个点,u 连向 v 表示选择 u 就必须选择 v。

    根据条件建图(注意一定要建对应的反向边(例如建立 u->v+n,就必须再连 v->u+n))后,跑一遍Tarjan求强连通分量。若发现存在一个 i 和 i+n 在同一个SCC里,则无解。

    否则就比较i和i+n所在scc的编号大小,一定是选择编号小的更优(scc编号小相当于拓扑序编号大)。

    tyy告诉我:

    建立反边是Tarjan算法正确性的保证。

    AC代码

    #include<iostream>
    #include<cstdio>
    #include<cstring>
    #include<cmath>
    #include<algorithm>
    #include<vector>
    #include<queue>
    #include<map>
    #include<bitset>
    #include<stack>
    using namespace std;
    template<class T>inline void read(T &x)
    {
        x=0;register char c=getchar();register bool f=0;
        while(!isdigit(c))f^=c=='-',c=getchar();
        while(isdigit(c))x=(x<<3)+(x<<1)+(c^48),c=getchar();
        if(f)x=-x;
    }
    template<class T>inline void print(T x)
    {
        if(x<0)putchar('-'),x=-x;
        if(x>9)print(x/10);
        putchar('0'+x%10);
    }
    const int maxn=2e6+5;
    int n,m,dfn[maxn],p[maxn],low[maxn],times,scc_cnt,in[maxn],cnt;
    struct node{
    	int v,next;
    }e[maxn];
    stack<int> s;
    void insert(int u,int v){
    	cnt++;
    	e[cnt].v=v;
    	e[cnt].next=p[u];
    	p[u]=cnt;
    }
    void dfs(int u){
    	dfn[u]=low[u]=++times;
    	s.push(u);
    	for(int i=p[u];i!=-1;i=e[i].next){
    		int v=e[i].v;
    		if(dfn[v]==0){
    			dfs(v);
    			low[u]=min(low[u],low[v]); 
    		}
    		else{
    			if(!in[v]) low[u]=min(low[u],dfn[v]);
    		}
    	}
    	if(low[u]==dfn[u]){
    		scc_cnt++;
    		while(!s.empty()){
    			int x=s.top();s.pop();
    			in[x]=scc_cnt;
    			if(x==u) break;
    		}
    	}
    }
    int main(){
    	ios::sync_with_stdio(false);
    	memset(p,-1,sizeof(p));
    	read(n);read(m);
    	for(int i=1;i<=m;i++){
    		int x,a,y,b;
    		read(x);read(a);read(y);read(b);
    		if(a==1&&b==1){
    			insert(x+n,y);
    			insert(y+n,x);
    		}
    		if(a==1&&b==0){
    			insert(x+n,y+n);
    			insert(y,x);
    		}
    		if(a==0&&b==1){
    			insert(x,y);
    			insert(y+n,x+n);
    		}
    		if(a==0&&b==0){
    			insert(x,y+n);
    			insert(y,x+n);
    		}
    	}
    	for(int i=1;i<=2*n;i++) if(!in[i]) dfs(i);
    	for(int i=1;i<=n;i++){
    		if(in[i]&&in[i+n]&&(in[i]==in[i+n])){
    			puts("IMPOSSIBLE");
    			return 0;
    		}
    	}
    	puts("POSSIBLE");
    	for(int i=1;i<=n;i++){
    		print(in[i]>in[i+n]?0:1);
    		putchar(' ');
    	}
    	return 0;
    }
    
  • 相关阅读:
    sql count中加条件
    zero-copy总结
    问题诊断神器arthas
    rabbitmq 消息确认
    HttpRunner安装笔记(1)安装环境准备:pyenv安装
    centos7 安装rabbitmq3.4.1-1
    centos7 python2.7.5 升级python3.6.4
    测试面试必会sql(1)
    mysql5.6 无法远程连接问题解决
    Katalon 学习笔记(一)
  • 原文地址:https://www.cnblogs.com/yinyuqin/p/15424302.html
Copyright © 2011-2022 走看看