给关注,求改样例都过不掉的奶牛议会(2-SAT)
查看原帖
给关注,求改样例都过不掉的奶牛议会(2-SAT)
97737
Wsyflying2022楼主2022/2/11 22:19
#include <bits/stdc++.h>
using namespace std;
const int maxn=5e4+10;
int n,m;
int Index,top;
int dfn[maxn],low[maxn],st[maxn],instack[maxn];
int sc,scc[maxn];
int from[maxn],to[maxn];
int vis[maxn];
bool flag;
struct Edge{
	int next;
	int to;
} e[maxn];
int head[maxn],tot;
inline void add_edge(int u,int v){
	e[++tot].next=head[u];
	e[tot].to=v;
}
int neg(int x){
	if (x>n) return x-n;
	return x+n;
}
inline void target(int x){
	dfn[x]=low[x]=++Index;
	instack[x]=1,st[++top]=x;
	for (int i=head[x];i;i=e[i].next) {
		int y=e[i].to;
		if (!dfn[y]) {
			target(y);
			low[x]=min(low[x],low[y]);
		}
		else if (instack[y]) {
			low[x]=min(low[x],dfn[y]);
		}
	}
	if (low[x]==dfn[x]) {
		sc++;
		scc[x]=sc;
		instack[x]=0;
		while (st[top]!=x) {
			scc[st[top]]=sc;
			instack[st[top]]=0;
			top--;
		}
		top--;
	}
}
bool dfs(int x,int ans) {
	if (flag) return false;
	if (x==ans) return false;
	for (int i=head[x];i;i=e[i].next) {
		int y=e[i].to;
		if (vis[y]!=Index) {
			vis[y]=Index;
			if (dfs(y,ans)){
				flag=true;
				return false;
			}
		}
	}
	return true;
}
int main(){
	scanf("%d%d",&n,&m);
	for (int i=1;i<=m;i++) {
		int x,y;
		char opt1,opt2;
		scanf("%d",&x);
		cin>>opt1;
		scanf("%d",&y);
		cin>>opt2;
		if (opt1=='Y') x+=n;
		if (opt2=='Y') y+=n;
		add_edge(neg(x),y);
		add_edge(neg(y),x);
		from[(i-1<<1)+1]=neg(x),to[(i-1<<1)+1]=y;
		from[i<<1]=neg(y),to[i<<1]=x;
	}
	for (int i=1;i<=2*n;i++)
	  if (!dfn[i]) target(i);
	for (int i=1;i<=n;i++)
	  if (scc[i]==scc[i+n]) flag=true;
	if (flag) {
		printf("IMPOSSIBLE");
		return 0;
	}
	tot=0;
	memset(e,0,sizeof(e));
	for (int i=1;i<=(m<<1);i++) {
		if (scc[from[i]]==scc[to[i]]) continue;
		add_edge(scc[from[i]],scc[to[i]]);
	}
	Index=0;
	for (int i=1;i<=n;i++){
		int x;
		Index++;
		x=(scc[n+i]>scc[i]) ? n+i : i;
		vis[scc[x]]=Index;
		flag=false;
		if (!dfs(scc[x],scc[neg(x)])) {
			printf("?");
		} 
		else if (x<n) printf("N");
		else printf("Y");
	}
	return 0;
}

2022/2/11 22:19
加载中...