首页 > 其他分享 >D37 2-SAT P3007 [USACO11JAN] The Continental Cowngress G

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

时间:2024-08-04 11:27:35浏览次数:12  
标签:Continental head P3007 int D37 Cowngress vis dfn low

视频链接:D37 2-SAT P3007 [USACO11JAN] The Continental Cowngress G_哔哩哔哩_bilibili

 

 

P3007 [USACO11JAN] The Continental Cowngress G - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)

// O(n*n)
#include <iostream>
#include <cstring>
#include <algorithm>
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('?');
  }
}

 

标签:Continental,head,P3007,int,D37,Cowngress,vis,dfn,low
From: https://www.cnblogs.com/dx123/p/18340851

相关文章

  • P3007 [USACO11JAN] The Continental Cowngress G
    P3007[USACO11JAN]TheContinentalCowngressG题目链接思路:2-SAT模板,经典的或条件,那么直接建图即可,对于可行解,我们直接枚举每个方案支持和反对,然后染色判断即可。代码:#include<bits/stdc++.h>usingnamespacestd;#definefffirst#definesssecond#definepbpush_......
  • 牛客周赛ROUND37--C题解
    C-红魔馆的馆主(495倍数)题意:做法:dfs搜索后面添加的数字。stringans="1000000000000000000";voiddfs(intcur,stringaddnum){//用数字写的话会无限dfs,因为addnum永远等于0。if(cur==0){if(addnum.size()<ans.size())ans=addnum;return;......