求助2-sat,悬赏关注
查看原帖
求助2-sat,悬赏关注
711584
Lienqwq楼主2022/10/12 19:29

一直RE+TLE

#include<bits/stdc++.h>
using namespace std;

const int _ = 4e6 + 5; 
int n ,m ,head[_] ,ts ,dfn[_] ,low[_] ,scc_cnt ,stk[_] ,all[_] ,id[_] ,top ,ans ,cnt;
struct Edge
{
	int to ,nxt;
}e[_];

inline void add(int from ,int to)
{
	e[++cnt] = {to ,head[from]};
	head[from] = cnt;
}

inline int tarjan(int u)
{
	dfn[u] = low[u] = ++ts;
	stk[++top] = u;
	for(int i = head[u];i != -1;i = e[i].nxt)
	{
		int to = e[i].to;
		if(!dfn[to])
		{
			tarjan(to);
			low[u] = min(low[u] ,low[to]);
		}
		else if(!id[to])
			low[u] = min(low[u] ,dfn[to]);
	}
	if(dfn[u] == low[u])
	{
		id[u] = ++scc_cnt;
		++all[scc_cnt];
		while(stk[top] != u)
		{
			id[stk[top--]] = scc_cnt;
			++all[scc_cnt];
		}
		top--;
	}
}

int main()
{
	memset(head ,-1 ,sizeof(head));
	scanf("%d%d" ,&n ,&m);
	for(int i = 1;i <= m;++i)
	{
		int x ,y ,vx ,vy;
		scanf("%d%d%d%d" ,&x ,&vx ,&y ,&vy);
		//以i为false ,i + n为true 
		if(vx && vy) add(x ,y + n) ,add(y ,x + n);
		if(!vx && vy) add(y ,x) ,add(x + n ,y + n);
		if(vx && !vy) add(x ,y) ,add(y + n ,x + n);
		if(!vx && !vy) add(x + n ,y) ,add(y + n ,x);
	}
	for(int i = 1;i <= n << 1;++i)
		//tarjan也要把所有编号遍历一遍 
		if(!dfn[i]) tarjan(i);
	for(int i = 1;i <= n;++i)
		if(id[i] == id[i + n])
		{ //在同一个强连通分量内,不可能满足
			printf("IMPOSSIBLE	");
			return 0;
		}
	printf("POSSIBLE\n");
	for(int i = 1;i <= n;++i)
	{ //强联通分量编号越小 -> 拓扑序越大 -> 越优
		if(id[i] > id[i + n]) printf("1 ");
        else printf("0 ");
	}
	return 0; 
}
2022/10/12 19:29
加载中...