【2-sat】 HDOJ 1816 Get Luffy Out *

找出矛盾,建图就行了。。。

#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 5005
#define maxm 3000005
#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
//#pragma comment (linker,"/STACK:102400000,102400000")
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 h[maxn], next[maxm], v[maxm];
int flag[maxn], low[maxn], dfn[maxn], ins[maxn];
int CNT, cnt, color, dfs_clock;
stack<int> s;
struct node
{
	int a, b;
}po[maxn];
int n, m;

void addedges(int u, int vv)
{
	next[cnt] = h[u], h[u] = cnt, v[cnt] = vv, cnt++;
}
void Addedges(int U, int VV)
{
	NEXT[CNT] = H[U], H[U] = CNT, V[CNT] = VV, CNT++;
}
void read(void)
{
	int a, b;
	CNT = 0;
	memset(H, -1, sizeof H);
	for(int i = 0; i < n; i++) {
		scanf(a), scanf(b);//scanf("%d%d", &a, &b);
		Addedges(a*2, b*2+1);
		Addedges(b*2, a*2+1);
	}
	for(int i = 1; i <= m; i++) scanf(po[i].a), scanf(po[i].b);//scanf("%d%d", &po[i].a, &po[i].b);
}
void init(void)
{
	cnt = color = dfs_clock = 0;
	memset(h, -1, sizeof h);
	memset(low, 0, sizeof low);
	memset(dfn, 0, sizeof dfn);
}
void tarjan(int u)
{
	low[u] = dfn[u] = ++dfs_clock;
	s.push(u), ins[u] = 1;
	for(int e = H[u]; ~e; e = NEXT[e])
		if(!dfn[V[e]]) {
			tarjan(V[e]);
			low[u] = min(low[u], low[V[e]]);
		}
		else if(ins[V[e]]) low[u] = min(low[u], dfn[V[e]]);
	for(int e = h[u]; ~e; e = next[e])
		if(!dfn[v[e]]) {
			tarjan(v[e]);
			low[u] = min(low[u], low[v[e]]);
		}
		else if(ins[v[e]]) low[u] = min(low[u], dfn[v[e]]);
	if(low[u] == dfn[u]) {
		int tmp = s.top(); s.pop(), ins[tmp] = 0, ++color;
		while(tmp != u) {
			flag[tmp] = color;
			tmp = s.top(), s.pop(), ins[tmp] = 0;
		}
		flag[tmp] = color;
	}
}
bool check(int x)
{
	init();
	for(int i = 1; i <= x; i++) {
		addedges(2*po[i].a+1, 2*po[i].b);
		addedges(2*po[i].b+1, 2*po[i].a);
	}
	for(int i = 0; i < (n<<1); i++)
		if(!dfn[i]) tarjan(i);
	for(int i = 0; i < n; i++) if(flag[i*2] == flag[i*2+1]) return false;
	return true;
}
void work(void)
{
	int bot = 0, top = m, mid, res = 0;
	while(top >= bot) {
		mid = (top+bot)>>1;
		if(check(mid)) bot = mid+1, res = mid;
		else top = mid-1;
	}
	printf("%d\n", res);
}
int main(void)
{
	while(scanf("%d%d", &n, &m), n != 0 || m != 0) {
		read();
		work();
	}
	return 0;
}


你可能感兴趣的:(HDU)