【2-sat】 HDOJ 1814 Peaceful Commission

暴力dfs染色求解字典序最小。。。

#include <iostream>  
#include <queue>  
#include <stack>  
#include <map>  
#include <set>  
#include <bitset>  
#include <cstdio>  
#include <algorithm>  
#include <cstring>  
#include <climits>  
#include <cstdlib>
#include <cmath>
#include <time.h>
#define maxn 20005
#define maxm 40005
#define eps 1e-10
#define mod 998244353
#define INF 999999999
#define lowbit(x) (x&(-x))
#define mp mark_pair
#define ls o<<1
#define rs o<<1 | 1
#define lson o<<1, L, mid  
#define rson o<<1 | 1, mid+1, R  
typedef long long LL;
//typedef int LL;
using namespace std;
LL powmod(LL a, LL b){LL res=1,base=a;while(b){if(b%2)res=res*base%mod;base=base*base%mod;b/=2;}return res;}
void scanf(int &__x){__x=0;char __ch=getchar();while(__ch==' '||__ch=='\n')__ch=getchar();while(__ch>='0'&&__ch<='9')__x=__x*10+__ch-'0',__ch = getchar();}
// head

int h[maxn], next[maxm], v[maxm];
int flag[maxn], reg[maxn];
int n, m, cnt, CNT, kk;

void init(void)
{
	cnt = 0;
	memset(h, -1, sizeof h);
	memset(flag, 0, sizeof flag);
}
void addedges(int u, int vv)
{
	next[cnt] = h[u], h[u] = cnt, v[cnt] = vv, cnt++;
}
void read(void)
{
	int a, b;
	while(m--) {
		//scanf("%d%d", &a, &b);
		scanf(a), scanf(b), a--, b--;
		addedges(a, b^1);
		addedges(b, a^1);
	}
}
bool dfs(int u)
{
	if(flag[u] == 1) return true;
	if(flag[u] == 2) return false;
	flag[u] = 1, flag[u^1] = 2;
	reg[kk++] = u;
	for(int e = h[u]; ~e; e = next[e])
		if(!dfs(v[e])) return false;
	return true;
}
void debug(void)
{
	for(int i = 0; i < n; i++) printf("%d\n", flag[i]);
}
bool work(void)
{
	n *= 2;
	for(int i = 0; i < n; i++) {
		if(flag[i]) continue;
		kk = 0;
		if(!dfs(i)) {
			for(int j = 0; j < kk; j++) flag[reg[j]] = flag[reg[j]^1] = 0;
			if(!dfs(i^1)) return false;
		}
	}
	return true;
}
int main(void)
{
	while(scanf("%d%d", &n, &m)!=EOF) {
		init();
		read();
		if(!work()) printf("NIE\n");
		else for(int i = 0; i < n; i++) if(flag[i] == 1) printf("%d\n", i+1);
	}
	return 0;
}


你可能感兴趣的:(HDU)