1 条题解

  • 0
    @ 2026-1-29 23:13:45

    D37 2-SAT P3007 [USACO11JAN] The Continental Cowngress G

    // O(n*n)
    #include<bits/stdc++.h>
    using namespace std;
    
    const int N=2005;
    int n,m;
    char s1[10],s2[10];
    int dfn[N],low[N],stk[N],scc[N],tim,top,cnt;
    int head[N],idx,vis[N];
    struct Edge{int to,ne;}e[8005];
    
    void add(int x,int y){
      e[++idx].to=y;e[idx].ne=head[x];head[x]=idx;
    }
    void tarjan(int x){
      dfn[x]=low[x]=++tim;
      stk[++top]=x;
      for(int i=head[x];i;i=e[i].ne){
        int y=e[i].to;
        if(!dfn[y]){ //若y尚未访问
          tarjan(y);
          low[x]=min(low[x],low[y]);
        }
        else if(!scc[y]) //若y已访问且未处理
          low[x]=min(low[x],dfn[y]);
      }
      
      if(low[x]==dfn[x]){ //若x是SCC的根
        ++cnt;
        for(int y=-1;y!=x;) scc[y=stk[top--]]=cnt;
      }
    }
    void dfs(int x){
      vis[x]=1;
      for(int i=head[x];i;i=e[i].ne)
        if(!vis[e[i].to]) dfs(e[i].to);
    }
    int check(int x){
      memset(vis,0,sizeof(vis));
      dfs(x); //找出以x为起点的链上的点
      // 如果能从x走到x+n或x-n,则返回 true
      if(vis[x]&&vis[x<=n?x+n:x-n]) return 1;
      return 0;
    }
    int main(){
      scanf("%d %d",&n,&m);
      for(int i,j,a,b;m--;){
        scanf("%d %s %d %s",&i,s1,&j,s2);
        a=(s1[0]=='Y'); //N:0,i和Y:1,i+n
        b=(s2[0]=='Y');
        add(i+!a*n,j+b*n),
        add(j+!b*n,i+a*n);
      }
      for(int i=1;i<=2*n;++i) if(!dfn[i]) tarjan(i);
      for(int i=1;i<=n;++i)
        if(scc[i]==scc[i+n]){
          puts("IMPOSSIBLE"); return 0;
        }
      for(int i=1,x,y;i<=n;++i){
        x=check(i);   //若i→i+n,则取Y
        y=check(i+n); //若i+n→i,则取N
        if(x&&!y) putchar('Y');
        else if(!x&&y) putchar('N');
        else if(!x&&!y) putchar('?');
      }
    }
    
    • 1

    D37【2-sat】[USACO11JAN] The Continental Cowngress G

    信息

    ID
    1569
    时间
    1000ms
    内存
    128MiB
    难度
    10
    标签
    递交数
    5
    已通过
    3
    上传者