[Trie树优化建图 2-SAT] Codeforces Gym101190B. Binary Code

把所有串建成一棵Trie树,相当于任意一条从根到叶子的链上都至多有一个点,用类似于前缀优化建图的方法建图

#include 
#include 
#include 
#include 
#include 

using namespace std;

const int N=5000010;

int n,lst,cnt,tot,cc,len[N],imark[N],pos[N],G[N],fa[N],nxt[N][2];
char a[N],*S[N];
struct edge{
    int t,nx;
}E[N<<1];

inline void addedge(int x,int y){
    //cout<
    E[++cnt].t=y; E[cnt].nx=G[x]; G[x]=cnt;
}

inline void instrie(char *a,int len,int flg){
    int cur=0;
    for(int i=0;iif(!nxt[cur][a[i]-'0']) nxt[cur][a[i]-'0']=++cc,fa[cc]=cur;
        cur=nxt[cur][a[i]-'0'];
    }
    pos[flg]=cur;
}

vector<int> loc[N];

int vis[N],dfn[N],low[N],s[N],tp,g[N],ig,it;

void tarjan(int x){
    dfn[x]=low[x]=++it; vis[x]=1; s[++tp]=x;
    for(int i=G[x];i;i=E[i].nx){
        if(!vis[E[i].t]) tarjan(E[i].t);
        if(vis[E[i].t]!=2) low[x]=min(low[x],low[E[i].t]);
    }
    if(dfn[x]==low[x]){
        int k; ++ig;
        do{ k=s[tp--]; vis[k]=2; g[k]=ig; }while(tp && k!=x);
    }
}

int main(){
    freopen("binary.in","r",stdin);
    freopen("binary.out","w",stdout);
    scanf("%d",&n);
    for(int i=1;i<=n;i++){
        scanf("%s",S[i]=a+lst);
        lst+=(len[i]=strlen(S[i]))+1;
        S[i][len[i]]='\n';
        imark[i]=-1;
        for(int j=0;jif(S[i][j]=='?') imark[i]=j;
        if(!~imark[i]){
            addedge(i<<1,i<<1|1);
            instrie(S[i],len[i],i<<1|1);
            pos[i<<1]=pos[i<<1|1];
        }
        else{
            S[i][imark[i]]='0';
            instrie(S[i],len[i],i<<1);
            S[i][imark[i]]='1';
            instrie(S[i],len[i],i<<1|1);
        }
    }
    tot=(n<<1|1)+2;
    for(int i=1;i<=cc;i++)
        addedge(tot+(fa[i]<<1),tot+(i<<1)),addedge(tot+((i<<1)|1),tot+((fa[i]<<1)|1));
    for(int i=2;i<=(n<<1|1);i++){
        loc[pos[i]].push_back(i);
        if(nxt[pos[i]][0])
            addedge(i,tot+(nxt[pos[i]][0]<<1));
        if(nxt[pos[i]][1])
            addedge(i,tot+(nxt[pos[i]][1]<<1));
        addedge(i,tot+(fa[pos[i]]<<1|1));
        addedge(tot+(pos[i]<<1),i^1);
        addedge(tot+(pos[i]<<1|1),i^1);
    }
    tot+=(cc<<1|1)+2;
    for(int i=1;i<=cc;i++){
        if(!loc[i].size()) continue;
        addedge(loc[i][0],tot); addedge(tot+1,loc[i][0]^1);
        for(int j=1;j1|1),tot+((j-1<<1)|1));
            addedge(tot+(j-1<<1),tot+(j<<1));
            addedge(loc[i][j],tot+(j<<1)); addedge(tot+(j<<1|1),loc[i][j]^1);
            addedge(loc[i][j],tot+((j-1<<1)|1)); addedge(tot+(j-1<<1),loc[i][j]^1);
        }
        tot+=(loc[i].size()<<1|1)+2;
    }
    for(int i=1;i<=tot;i++)
        if(!vis[i]) tarjan(i);
    for(int i=1;i<=n;i++)
        if(g[i<<1]==g[i<<1|1]) return puts("NO"),0;
    for(int i=1;i<=n;i++)
        if(!~imark[i]);else S[i][imark[i]]=g[i<<1|1]1]?'1':'0';
    printf("YES\n%s",a);
    return 0;
}

你可能感兴趣的:(字典树,2-SAT)