2-SAT原来很有趣!

文章目录

  • 推荐阅读资料
  • A.HDU 3062 Party
    • title
    • analysis[^1]
    • code
  • B.POJ 3678 Katu Puzzle
    • title
    • analysis
    • code
  • C.HDU 3715 Go Deeper
    • title
    • analysis
    • code
  • D.POJ 3207 Ikki's Story IV - Panda's Trick
    • title
    • analysis
    • code
  • E.POJ 2723 Get Luffy Out
    • title
    • analysis
    • code
  • F.POJ 3648 Wedding
    • title
    • analysis
    • code
  • G.POJ 2749 Building roads
    • title
    • analysis
    • warning
    • code
  • H.POJ 3683 Priest John's Busiest Day
    • title
    • analysis
    • code

推荐阅读资料

唐浩 《2-SAT问题》
伍昱 《由对称性解2-sat问题》
赵爽 《2-sat解法浅析》

A.HDU 3062 Party

title

HDU 3062
Problem Description

有n对夫妻被邀请参加一个聚会,因为场地的问题,每对夫妻中只有1人可以列席。在2n 个人中,某些人之间有着很大的矛盾(当然夫妻之间是没有矛盾的),有矛盾的2个人是不会同时出现在聚会上的。有没有可能会有n 个人同时列席?

Input

n: 表示有n对夫妻被邀请 (n<= 1000)
m: 表示有m 对矛盾关系 ( m < (n - 1) * (n -1))
在接下来的m行中,每行会有4个数字,分别是 A1,A2,C1,C2
A1,A2分别表示是夫妻的编号
C1,C2 表示是妻子还是丈夫 ,0表示妻子 ,1是丈夫
夫妻编号从 0 到 n -1

Output

如果存在一种情况 则输出YES
否则输出 NO

Sample Input

2
1
0 1 1 1

Sample Output

YES

Source

2009 Multi-University Training Contest 16 - Host by NIT

Recommend

lcy | We have carefully selected several similar problems for you: 3060 3068 3063 3064 3065

analysis1

裸2-SAT模型,图基本上给好了,判断一下就好。
用 tarjan 算法求强连通,然后判断 i i i i ′ i' i 是否在同一个连通分量里面就好。

code

#include
using namespace std;
const int maxn=2e3+10,maxm=5e5+10;
template<typename T>inline void read(T &x)
{
	x=0;
	T f=1, ch=getchar();
	while (!isdigit(ch) && ch^'-') ch=getchar();
	if (ch=='-') f=-1, ch=getchar();
	while (isdigit(ch)) x=(x<<1)+(x<<3)+(ch^48), ch=getchar();
	x*=f;
}
int ver[maxm<<1],Next[maxm<<1],head[maxn],len;
inline void add(int x,int y)
{
	ver[++len]=y,Next[len]=head[x],head[x]=len;
}
int dfn[maxn],low[maxn],id;
int Stack[maxn],top;
int belong[maxn],tot;
bool instack[maxn];
inline void tarjan(int x)
{
	dfn[x]=low[x]=++id;
	Stack[++top]=x;
	instack[x]=1;
	for (int i=head[x];i;i=Next[i])
	{
		int y=ver[i];
		if (!dfn[y])
		{
			tarjan(y);
			low[x]=min(low[x],low[y]);
		}
		else if (instack[y])
			low[x]=min(low[x],dfn[y]);
	}
	if (low[x]==dfn[x])
	{
		int k;
		++tot;
		do
		{
			k=Stack[top--];
			belong[k]=tot;
			instack[k]=0;
		} while (k!=x);
	}
}
inline void Clear()
{
	memset(dfn,0,sizeof(dfn));
	memset(low,0,sizeof(low));
	memset(belong,0,sizeof(belong));
	memset(instack,0,sizeof(instack));
	id=top=tot=0;
}
int main()
{
	int n;
	while (~scanf("%d",&n))
	{
		int m;read(m);
		memset(head,0,sizeof(head));
		len=0;
		while (m--)
		{
			int a1,a2,c1,c2;
			read(a1);read(a2);read(c1);read(c2);
			if (c1==1&&c2==1) add(a1+n,a2),add(a2+n,a1);
			if (c1==1&&c2==0) add(a1+n,a2+n),add(a2,a1);
			if (c1==0&&c2==1) add(a1,a2),add(a2+n,a1+n);
			if (c1==0&&c2==0) add(a1,a2+n),add(a2,a1+n);
		}
		Clear();
		for (int i=1;i<=(n<<1);++i)
			if (!dfn[i]) tarjan(i);
		bool flag=1;
		for (int i=1;i<=n;++i)
			if (belong[i]==belong[i+n])
			{
				flag=0;
				break;
			}
		printf(flag?"YES\n":"NO\n");
	}
	return 0;
}

B.POJ 3678 Katu Puzzle

title

POJ 3648
Description

Katu Puzzle is presented as a directed graph G(V, E) with each edge e(a, b) labeled by a boolean operator op (one of AND, OR, XOR) and an integer c (0 ≤ c ≤ 1). One Katu is solvable if one can find each vertex Vi a value Xi (0 ≤ Xi ≤ 1) such that for each edge e(a, b) labeled by op and c, the following formula holds:
Xa op Xb = c
The calculating rules are:

AND 0 1 OR 0 1 XOR 0 1
0 0 0 0 0 1 0 0 1
1 0 1 1 1 1 1 1 0

Given a Katu Puzzle, your task is to determine whether it is solvable.

Input

The first line contains two integers N (1 ≤ N ≤ 1000) and M,(0 ≤ M ≤ 1,000,000) indicating the number of vertices and edges.
The following M lines contain three integers a (0 ≤ a < N), b(0 ≤ b < N), c and an operator op each, describing the edges.

Output

Output a line containing “YES” or “NO”.

Sample Input

4 4
0 1 1 AND
1 2 1 OR
3 2 0 AND
3 0 0 XOR

Sample Output

YES

Hint

X0 = 1, X1 = 1, X2 = 0, X3 = 1.

Source

POJ Founder Monthly Contest – 2008.07.27, Dagger

analysis

题意是说给出一些变量,他们可以取 0 或 1 ,然后给出一组他们的由 与,或,异或 三种运算组成的式子,问是否有一组可行解,满足这些式子,也是很裸的2-SAT模型。

code

#include
using namespace std;
const int maxn=2e3+10;
template<typename T>inline void read(T &x)
{
	x=0;
	T f=1, ch=getchar();
	while (!isdigit(ch) && ch^'-') ch=getchar();
	if (ch=='-') f=-1, ch=getchar();
	while (isdigit(ch)) x=(x<<1)+(x<<3)+(ch^48), ch=getchar();
	x*=f;
}
int ver[maxn*maxn],Next[maxn*maxn],head[maxn],len;
inline void add(int x,int y)
{
	ver[++len]=y,Next[len]=head[x],head[x]=len;
}
int dfn[maxn],low[maxn],id;
int Stack[maxn],top;
int belong[maxn],tot;
bool instack[maxn];
inline void tarjan(int x)
{
	dfn[x]=low[x]=++id;
	Stack[++top]=x;
	instack[x]=1;
	for (int i=head[x];i;i=Next[i])
	{
		int y=ver[i];
		if (!dfn[y])
		{
			tarjan(y);
			low[x]=min(low[x],low[y]);
		}
		else if (instack[y])
			low[x]=min(low[x],dfn[y]);
	}
	if (low[x]==dfn[x])
	{
		int k;
		++tot;
		do
		{
			k=Stack[top--];
			belong[k]=tot;
			instack[k]=0;
		} while (k!=x);
	}
}
int main()
{
	int n,m;
	read(n);read(m);
	for (int i=1;i<=m;++i)
	{
		int a,b,c;
		char ch[5];
		read(a);read(b);read(c);scanf("%s",ch);
		if (ch[0]=='A')
		{
			if (c==1)
			{
				add(a,b+n),add(a,b),add(a+n,b+n);
				add(b,a+n),add(b,a),add(b+n,a+n);
			}
			else
				add(a+n,b),add(b+n,a);
		}
		else if (ch[0]=='O')
		{
			if (c==1)
				add(a,b+n),add(b,a+n);
			else
			{
				add(a,b),add(a+n,b+n),add(a+n,b);
				add(b,a),add(b+n,a+n),add(b+n,a);
			}
		}
		else
		{
			if (c==1)
			{
				add(a,b+n),add(a+n,b);
				add(b,a+n),add(b+n,a);
			}
			else
			{
				add(a,b),add(a+n,b+n);
				add(b,a),add(b+n,a+n);
			}
		}
	}
	for (int i=1;i<=(n<<1);++i)
		if (!dfn[i]) tarjan(i);
	bool flag=1;
	for (int i=1;i<=n;++i)
		if (belong[i]==belong[i+n])
		{
			flag=0;
			break;
		}
	printf(flag?"YES\n":"NO\n");
	return 0;
}

C.HDU 3715 Go Deeper

title

HDU 3715
Problem Description

Here is a procedure’s pseudocode:

go(int dep, int n, int m)
begin
output the value of dep.
if dep < m and x[a[dep]] + x[b[dep]] != c[dep] then go(dep + 1, n, m)
end

In this code n is an integer. a, b, c and x are 4 arrays of integers. The index of array always starts from 0. Array a and b consist of non-negative integers smaller than n. Array x consists of only 0 and 1. Array c consists of only 0, 1 and 2. The lengths of array a, b and c are m while the length of array x is n. Given the elements of array a, b, and c, when we call the procedure go(0, n, m) what is the maximal possible value the procedure may output?

Input

There are multiple test cases. The first line of input is an integer T (0 < T ≤ 100), indicating the number of test cases. Then T test cases follow. Each case starts with a line of 2 integers n and m (0 < n ≤ 200, 0 < m ≤ 10000). Then m lines of 3 integers follow. The i-th(1 ≤ i ≤ m) line of them are ai-1 ,bi-1 and ci-1 (0 ≤ ai-1, bi-1 < n, 0 ≤ ci-1 ≤ 2).

Output

For each test case, output the result in a single line.

Sample Input

3
2 1
0 1 0
2 1
0 0 0
2 2
0 1 0
1 1 2

Sample Output

1
1
2

Author

CAO, Peng

Source

2010 Asia Chengdu Regional Contest

Recommend

zhouzeyong | We have carefully selected several similar problems for you: 3718 3711 3713 3714 3717

analysis

也是很裸的模型,不过由于解未知,要求找到最大的可行解,所以需要在解的可行区间里面二分查找答案,直到找到最大的可行解。

if dep < m and x[a[dep]] + x[b[dep]] != c[dep] then go(dep + 1, n, m)

我们在 0 到 m 上查找最大可行解时,要想让 dep 值尽量大,就要尽量满足不等式 ( x [ a [ d e p ] ] + x [ b [ d e p ] ] ! = c [ d e p ] ) (x[ a[ dep ] ] + x[ b[ dep ] ] != c[ dep ]) x[a[dep]]+x[b[dep]]!=c[dep] c [ d e p ] c[ dep ] c[dep]值有三种情况,如下:

if (!c[i]) //x[ a[i] ],x[ b[i] ]不能同时为0
else if (c[i]==1) //x[ a[i] ],x[ b[i] ]不能不同,二者要么同时为0,要么同时为1
else if (c[i]==2) //x[ a[i] ],x[ b[i] ]不能同时为1

根据这个关系建图,就好了。

code

#include
using namespace std;
const int maxn=2e4+10;
template<typename T>inline void read(T &x)
{
	x=0;
	T f=1, ch=getchar();
	while (!isdigit(ch) && ch^'-') ch=getchar();
	if (ch=='-') f=-1, ch=getchar();
	while (isdigit(ch)) x=(x<<1)+(x<<3)+(ch^48), ch=getchar();
	x*=f;
}
int ver[maxn*3],Next[maxn*3],head[maxn],len;
inline void add(int x,int y)
{
	ver[++len]=y,Next[len]=head[x],head[x]=len;
}
int dfn[maxn],low[maxn],id;
int Stack[maxn],top;
int belong[maxn],tot;
bool instack[maxn];
inline void tarjan(int x)
{
	dfn[x]=low[x]=++id;
	Stack[++top]=x;
	instack[x]=1;
	for (int i=head[x];i;i=Next[i])
	{
		int y=ver[i];
		if (!dfn[y])
		{
			tarjan(y);
			low[x]=min(low[x],low[y]);
		}
		else if (instack[y])
			low[x]=min(low[x],dfn[y]);
	}
	if (low[x]==dfn[x])
	{
		int k;
		++tot;
		do
		{
			k=Stack[top--];
			belong[k]=tot;
			instack[k]=0;
		} while (k!=x);
	}
}
inline void Clear()
{
	memset(dfn,0,sizeof(dfn));
	memset(low,0,sizeof(low));
	memset(instack,0,sizeof(instack));
	id=top=0;
}
int a[maxn],b[maxn],c[maxn];
int main()
{
	int t,n,m,ans=0;read(t);
	while (t--)
	{
		read(n);read(m);
		for (int i=1;i<=m;++i)
			read(a[i]),read(b[i]),read(c[i]);
		int l=0,r=m;
		while (l<=r)
		{
			int mid=(l+r)>>1;
			memset(head,0,sizeof(head));
			len=0;
			for (int i=1;i<=mid;++i)
			{
//    			if (!c[i])
//					add(a[i]<<1,b[i]<<1|1),
//					add(b[i]<<1,a[i]<<1|1);
//				else if (c[i]==1)
//					add(a[i]<<1,b[i]<<1),
//					add(a[i]<<1|1,b[i]<<1|1),
//					add(b[i]<<1,a[i]<<1),
//					add(b[i]<<1|1,a[i]<<1|1);
//				else
//					add(a[i]<<1|1,b[i]<<1),
//					add(b[i]<<1|1,a[i]<<1);
				if (!c[i])
					add(a[i],b[i]+n),
					add(b[i],a[i]+n);
				else if (c[i]==1)
					add(a[i],b[i]),
					add(a[i]+n,b[i]+n),
					add(b[i],a[i]),
					add(b[i]+n,a[i]+n);
				else
					add(a[i]+n,b[i]),
					add(b[i]+n,a[i]);
			}
			Clear();
			for (int i=1;i<=(mid<<1);++i)
				if (!dfn[i]) tarjan(i);
			bool flag=0;
			for (int i=1;i<=mid;++i)
//				if (belong[i<<1]==belong[i<<1|1])
				if (belong[i]==belong[i+n])
				{
					flag=1;
					break;
				}
			if (!flag) ans=mid,l=mid+1;
			else r=mid-1;
		}
		printf("%d\n",ans);
	}
	return 0;
}

D.POJ 3207 Ikki’s Story IV - Panda’s Trick

title

POJ 3207
Description

liympanda, one of Ikki’s friend, likes playing games with Ikki. Today after minesweeping with Ikki and winning so many times, he is tired of such easy games and wants to play another game with Ikki.
liympanda has a magic circle and he puts it on a plane, there are n points on its boundary in circular border: 0, 1, 2, …, n − 1. Evil panda claims that he is connecting m pairs of points. To connect two points, liympanda either places the link entirely inside the circle or entirely outside the circle. Now liympanda tells Ikki no two links touch inside/outside the circle, except on the boundary. He wants Ikki to figure out whether this is possible…
Despaired at the minesweeping game just played, Ikki is totally at a loss, so he decides to write a program to help him.

Input

The input contains exactly one test case.
In the test case there will be a line consisting of of two integers: n and m (n ≤ 1,000, m ≤ 500). The following m lines each contain two integers ai and bi, which denote the endpoints of the ith wire. Every point will have at most one link.

Output

Output a line, either “panda is telling the truth…” or “the evil panda is lying again”.

Sample Input

4 2
0 1
3 2

Sample Output

panda is telling the truth…

Source

POJ Monthly–2007.03.04, Ikki

analysis

如果两个线段是相交的,那么两个线段同时在圆内或者圆外都是相交的。
这样就得到了约束关系,套用2-SAT的模板就行了。

code

#include
using namespace std;
const int maxn=1e3+10,maxm=5e5+10;
template<typename T>inline void read(T &x)
{
	x=0;
	T f=1, ch=getchar();
	while (!isdigit(ch) && ch^'-') ch=getchar();
	if (ch=='-') f=-1, ch=getchar();
	while (isdigit(ch)) x=(x<<1)+(x<<3)+(ch^48), ch=getchar();
	x*=f;
}
int ver[maxm<<1],Next[maxm<<1],head[maxn],len;
inline void add(int x,int y)
{
	ver[++len]=y,Next[len]=head[x],head[x]=len;
}
int dfn[maxn],low[maxn],id;
int Stack[maxn],top;
int belong[maxn],tot;
bool instack[maxn];
inline void tarjan(int x)
{
	dfn[x]=low[x]=++id;
	Stack[++top]=x;
	instack[x]=1;
	for (int i=head[x];i;i=Next[i])
	{
		int y=ver[i];
		if (!dfn[y])
		{
			tarjan(y);
			low[x]=min(low[x],low[y]);
		}
		else if (instack[y])
			low[x]=min(low[x],dfn[y]);
	}
	if (low[x]==dfn[x])
	{
		int k;
		++tot;
		do
		{
			k=Stack[top--];
			belong[k]=tot;
			instack[k]=0;
		} while (k!=x);
	}
}
inline void Clear()
{
	memset(dfn,0,sizeof(dfn));
	memset(low,0,sizeof(low));
	memset(belong,0,sizeof(belong));
	memset(instack,0,sizeof(instack));
	id=tot=top=0;
}
int st[maxn],ed[maxn];
int main()
{
	int n,m;
	while (~scanf("%d %d",&n,&m))
	{
		for (int i=1;i<=m;++i)
		{
			int x,y;
			read(x);read(y);
			st[i]=min(x,y);
			ed[i]=max(x,y);
		}
		for (int i=1;i<=m;++i)
			for (int j=i+1;j<=m;++j)
				if ((st[i]>st[j] && st[i]<ed[j] && ed[i]>ed[j]) || (st[j]>st[i] && st[j]<ed[i] && ed[j]>ed[i]))
					add(i,j+m),add(j+m,i),add(j,i+m),add(i+m,j);
		Clear();
		for (int i=1;i<=(m<<1);++i)
			if (!dfn[i]) tarjan(i);
		bool flag=1;
		for (int i=1;i<=m;++i)
			if (belong[i]==belong[i+m])
			{
				flag=0;
				break;
			}
		printf(flag?"panda is telling the truth...":"the evil panda is lying again");
	}
	return 0;
}

E.POJ 2723 Get Luffy Out

title

POJ 2723
Description

Ratish is a young man who always dreams of being a hero. One day his friend Luffy was caught by Pirate Arlong. Ratish set off at once to Arlong’s island. When he got there, he found the secret place where his friend was kept, but he could not go straight in. He saw a large door in front of him and two locks in the door. Beside the large door, he found a strange rock, on which there were some odd words. The sentences were encrypted. But that was easy for Ratish, an amateur cryptographer. After decrypting all the sentences, Ratish knew the following facts:
Behind the large door, there is a nesting prison, which consists of M floors. Each floor except the deepest one has a door leading to the next floor, and there are two locks in each of these doors. Ratish can pass through a door if he opens either of the two locks in it. There are 2N different types of locks in all. The same type of locks may appear in different doors, and a door may have two locks of the same type. There is only one key that can unlock one type of lock, so there are 2N keys for all the 2N types of locks. These 2N keys were divided into N pairs, and once one key in a pair is used, the other key will disappear and never show up again.
Later, Ratish found N pairs of keys under the rock and a piece of paper recording exactly what kinds of locks are in the M doors. But Ratish doesn’t know which floor Luffy is held, so he has to open as many doors as possible. Can you help him to choose N keys to open the maximum number of doors?

Input

There are several test cases. Every test case starts with a line containing two positive integers N (1 <= N <= 210) and M (1 <= M <= 211) separated by a space, the first integer represents the number of types of keys and the second integer represents the number of doors. The 2N keys are numbered 0, 1, 2, …, 2N - 1. Each of the following N lines contains two different integers, which are the numbers of two keys in a pair. After that, each of the following M lines contains two integers, which are the numbers of two keys corresponding to the two locks in a door. You should note that the doors are given in the same order that Ratish will meet. A test case with N = M = 0 ends the input, and should not be processed.
Output
For each test case, output one line containing an integer, which is the maximum number of doors Ratish can open.

Sample Input

3 6
0 3
1 2
4 5
0 1
0 2
4 1
4 2
3 5
2 2
0 0

Sample Output

4

Source

Beijing 2005

analysis

题意:给出 n 对钥匙,每对只能挑一把使用,每把只能用一次,当一对钥匙中的一把被使用后,另一把也就不能再用了;然后给出 m 道门,每个门都有两把钥匙可以打开,问最多能开几道门(按给出的顺序开)。

矛盾关系:
1:n 对钥匙中,A 和 B 只能选择一把,用点 A 表示选择钥匙 A ,用 A’ 表示不选择(同理用点 B 和 B‘ 表示钥匙 B 的选择关系),建边(A -> B‘)表示用钥匙 A 就不能用钥匙 B ;还有(B -> A’ )表示用 B 就不能用 A。

2:m 道门,每对门都有两把钥匙可以开(假设是 C 和 D ),可能的选择是(用 C 不用 D)或者(用 D 不用 C),根据这个关系建边(D’ -> C),(C’ -> D)。

code

这道题见图时用 + n +n +n竟然过不了,很不解。。。  ̄ へ  ̄   < (  ̄ ﹌  ̄ ) >  ̄へ ̄ \text{ }<( ̄ ﹌  ̄)>  <()>

#include
using namespace std;
const int maxn=4100;
template<typename T>inline void read(T &x)
{
	x=0;
	T f=1, ch=getchar();
	while (!isdigit(ch) && ch^'-') ch=getchar();
	if (ch=='-') f=-1, ch=getchar();
	while (isdigit(ch)) x=(x<<1)+(x<<3)+(ch^48), ch=getchar();
	x*=f;
}
int ver[maxn*3],Next[maxn*3],head[maxn],len;
inline void add(int x,int y)
{
	ver[++len]=y,Next[len]=head[x],head[x]=len;
}
int dfn[maxn],low[maxn],id;
int Stack[maxn],top;
int belong[maxn],tot;
bool instack[maxn];
inline void tarjan(int x)
{
	dfn[x]=low[x]=++id;
	Stack[++top]=x;
	instack[x]=1;
	for (int i=head[x];i;i=Next[i])
	{
		int y=ver[i];
		if (!dfn[y])
		{
			tarjan(y);
			low[x]=min(low[x],low[y]);
		}
		else if (instack[y])
			low[x]=min(low[x],dfn[y]);
	}
	if (low[x]==dfn[x])
	{
		int k;
		++tot;
		do
		{
			k=Stack[top--];
			belong[k]=tot;
			instack[k]=0;
		} while (k!=x);
	}
}
inline void Clear()
{
	memset(dfn,0,sizeof(dfn));
	memset(low,0,sizeof(low));
	memset(belong,0,sizeof(belong));
	memset(instack,0,sizeof(instack));
	id=tot=top=0;
}
int x[maxn],y[maxn],a[2][maxn];
int main()
{
	int n,m;
	while (~scanf("%d %d",&n,&m)&&(n+m))
	{
		for (int i=1;i<=n;++i)
			read(x[i]),read(y[i]);
		for (int i=1;i<=m;++i)
			read(a[0][i]),read(a[1][i]);
		int l=0,r=m,ans=0;
		while (l<=r)
		{
			memset(head,0,sizeof(head));
			len=0;
			for (int i=1;i<=n;++i)
				add(x[i]<<1,y[i]<<1|1),
				add(y[i]<<1,x[i]<<1|1);
			int mid=(l+r)>>1;
			for (int i=1;i<=mid;++i)
				add(a[0][i]<<1|1,a[1][i]<<1),
				add(a[1][i]<<1|1,a[0][i]<<1);
			Clear();
			for (int i=1;i<=(n<<2);++i)
				if (!dfn[i]) tarjan(i);
			bool flag=1;
			for (int i=1;i<=(n<<1);++i)
				if (belong[i<<1]==belong[i<<1|1])
				{
					flag=0;
					break;
				}
			if (flag) ans=mid,l=mid+1;
			else r=mid-1;
		}
		printf("%d\n",ans);
	}
	return 0;
}

F.POJ 3648 Wedding

title

POJ 3648
之所以没有像原来那样提供Ch的地址,是因为我不管怎么写,在Ch上都会WA。。。。
Description

Up to thirty couples will attend a wedding feast, at which they will be seated on either side of a long table. The bride and groom sit at one end, opposite each other, and the bride wears an elaborate headdress that keeps her from seeing people on the same side as her. It is considered bad luck to have a husband and wife seated on the same side of the table. Additionally, there are several pairs of people conducting adulterous relationships (both different-sex and same-sex relationships are possible), and it is bad luck for the bride to see both members of such a pair. Your job is to arrange people at the table so as to avoid any bad luck.

Input

The input consists of a number of test cases, followed by a line containing 0 0. Each test case gives n, the number of couples, followed by the number of adulterous pairs, followed by the pairs, in the form “4h 2w” (husband from couple 4, wife from couple 2), or “10w 4w”, or “3h 1h”. Couples are numbered from 0 to n - 1 with the bride and groom being 0w and 0h.

Output

For each case, output a single line containing a list of the people that should be seated on the same side as the bride. If there are several solutions, any one will do. If there is no solution, output a line containing “bad luck”.

Sample Input

10 6
3h 7h
5w 3w
7h 6w
8w 3w
7h 3w
2w 5h
0 0

Sample Output

1h 2h 3w 4h 5h 6h 7h 8h 9h

Source

Waterloo Local Contest, 2007.9.29

analysis

这道题的解决部分还必须写一个 w o r k ( ) work() work()函数,以此在判断结果为 “ b a d   l u c k ” “bad\text{ }luck” bad luck后,返回,否则,写在主函数里,不管是 c o n t i n u e continue continue还是 e x i t ( 0 ) exit(0) exit(0),都会 W A WA WA。哎,这是我提交了14遍得出的结论。
就是这个。

if (belong[i]==belong[i+n])
{
	puts("bad luck");
	exit(0); or continue;//都会WA。
}

所以还是这样写比较好。

inline void work()
{
.....................................//自己想想前面怎么写。
	if (belong[i]==belong[i+n])
	{
		puts("bad luck");
		return ;
	}
.....................................//还有后面怎么写
}

但是,这真的是一道比较板子性质的 2 − S A T 2-SAT 2SAT问题,只不过没想到这么坑!

code

#include
using namespace std;
const int maxn=62,maxm=3605;
template<typename T>inline void read(T &x)
{
	x=0;
	T f=1, ch=getchar();
	while (!isdigit(ch) && ch^'-') ch=getchar();
	if (ch=='-') f=-1, ch=getchar();
	while (isdigit(ch)) x=(x<<1)+(x<<3)+(ch^48), ch=getchar();
	x*=f;
}
int ver[maxm],Next[maxm],head[maxn],len;
inline void add(int x,int y)
{
	ver[++len]=y,Next[len]=head[x],head[x]=len;
}
int vc[maxm],Nc[maxm],hc[maxn],lc;
inline void addc(int x,int y)
{
	vc[++lc]=y,Nc[lc]=hc[x],hc[x]=lc;
}
int dfn[maxn],low[maxn],id;
int Stack[maxn],top;
int belong[maxn],tot;
bool instack[maxn];
inline void tarjan(int x)
{
	dfn[x]=low[x]=++id;
	Stack[++top]=x;
	instack[x]=1;
	for (int i=head[x];i;i=Next[i])
	{
		int y=ver[i];
		if (!dfn[y])
		{
			tarjan(y);
			low[x]=min(low[x],low[y]);
		}
		else if (instack[y])
			low[x]=min(low[x],dfn[y]);
	}
	if (low[x]==dfn[x])
	{
		int k;
		++tot;
		do
		{
			k=Stack[top--];
			belong[k]=tot;
			instack[k]=0;
		} while (k!=x);
	}
}
int val[maxn],deg[maxn],opp[maxn];
inline void topsort()
{
	queue<int>q;
	for (int i=1;i<=tot;++i)
		if (!deg[i]) q.push(i);
	while (!q.empty())
	{
		int x=q.front();
		q.pop();
		if (!val[x]) val[x]=1,val[opp[x]]=-1;
		for (int i=hc[x];i;i=Nc[i])
		{
			int y=vc[i];
			if (!--deg[y]) q.push(y);
		}
	}
}
int n,m;
inline void work()
{
	len=lc=id=top=tot=0;
	for (int i=1;i<=(n<<1);++i)
		head[i]=hc[i]=dfn[i]=instack[i]=deg[i]=val[i]=0;
	for (int i=1;i<=m;++i)
	{
		int a,c;char b,d;
		scanf("%d%c %d%c",&a,&b,&c,&d);
		if (!a) a=n;
		if (!c) c=n;
		if (b=='h'&&d=='h') add(a,c+n),add(c,a+n);
		if (b=='h'&&d=='w') add(a,c),add(c+n,a+n);
		if (b=='w'&&d=='h') add(a+n,c+n),add(c,a);
		if (b=='w'&&d=='w') add(a+n,c),add(c+n,a);
	}
	add(n<<1,n);
	for (int i=1;i<=(n<<1);++i)
		if (!dfn[i]) tarjan(i);
	for (int i=1;i<=n;++i)
	{
		if (belong[i]==belong[i+n])
		{
			puts("bad luck");
			return ;
		}
		opp[belong[i]]=belong[i+n];
		opp[belong[i+n]]=belong[i];
	}
	for (int x=1;x<=(n<<1);++x)
		for (int i=head[x];i;i=Next[i])
		{
			int y=ver[i];
			if (belong[y]!=belong[x])
				addc(belong[y],belong[x]),++deg[belong[x]];
		}
	topsort();
	for (int i=1;i<n;++i)
		if (val[belong[i]]==-1) printf("%dh ",i);
		else printf("%dw ",i);
	puts("");
}
int main()
{
	while (~scanf("%d %d",&n,&m)&&(n+m)) work();
	return 0;
}

G.POJ 2749 Building roads

title

POJ 2749
Description

Farmer John’s farm has N barns, and there are some cows that live in each barn. The cows like to drop around, so John wants to build some roads to connect these barns. If he builds roads for every pair of different barns, then he must build N * (N - 1) / 2 roads, which is so costly that cheapskate John will never do that, though that’s the best choice for the cows.
Clever John just had another good idea. He first builds two transferring point S1 and S2, and then builds a road connecting S1 and S2 and N roads connecting each barn with S1 or S2, namely every barn will connect with S1 or S2, but not both. So that every pair of barns will be connected by the roads. To make the cows don’t spend too much time while dropping around, John wants to minimize the maximum of distances between every pair of barns.
That’s not the whole story because there is another troublesome problem. The cows of some barns hate each other, and John can’t connect their barns to the same transferring point. The cows of some barns are friends with each other, and John must connect their barns to the same transferring point. What a headache! Now John turns to you for help. Your task is to find a feasible optimal road-building scheme to make the maximum of distances between every pair of barns as short as possible, which means that you must decide which transferring point each barn should connect to.
We have known the coordinates of S1, S2 and the N barns, the pairs of barns in which the cows hate each other, and the pairs of barns in which the cows are friends with each other.
Note that John always builds roads vertically and horizontally, so the length of road between two places is their Manhattan distance. For example, saying two points with coordinates (x1, y1) and (x2, y2), the Manhattan distance between them is |x1 - x2| + |y1 - y2|.

Input

The first line of input consists of 3 integers N, A and B (2 <= N <= 500, 0 <= A <= 1000, 0 <= B <= 1000), which are the number of barns, the number of pairs of barns in which the cows hate each other and the number of pairs of barns in which the cows are friends with each other.
Next line contains 4 integer sx1, sy1, sx2, sy2, which are the coordinates of two different transferring point S1 and S2 respectively.
Each of the following N line contains two integer x and y. They are coordinates of the barns from the first barn to the last one.
Each of the following A lines contains two different integers i and j(1 <= i < j <= N), which represent the i-th and j-th barns in which the cows hate each other.
The same pair of barns never appears more than once.
Each of the following B lines contains two different integers i and j(1 <= i < j <= N), which represent the i-th and j-th barns in which the cows are friends with each other. The same pair of barns never appears more than once.
You should note that all the coordinates are in the range [-1000000, 1000000].

Output

You just need output a line containing a single integer, which represents the maximum of the distances between every pair of barns, if John selects the optimal road-building scheme. Note if there is no feasible solution, just output -1.

Sample Input

4 1 1
12750 28546 15361 32055
6706 3887
10754 8166
12668 19380
15788 16059
3 4
2 3

Sample Output

53246
Source
POJ Monthly–2006.01.22,zhucheng

analysis

题意是说有 N 个牛栏,现在通过一条通道(s1,s2)把他们连起来,他们之间有一些约束关系,一些牛栏不能连在同一个点,一些牛栏必须连在同一个点,现在问有没有可能把他们都连好,而且满足所有的约束关系,如果可以,输出两个牛栏之间距离最大值的最小情况。

比如牛栏 A 连在 s1 点,牛栏 B 连在 s2 点,那么AB之间的距离为(As1 + s1s2 + s2B);也可以两个牛栏连在同一个点上,比如 A 连在 s1 ,B 也连在 s1 ,那么AB的距离是(As1 + Bs1)。

A 表示连在s1,A‘ 表示连在 s2 ,按照给出的约束关系建边,然后在区间内2分枚举所有可能的解 ans,如果当前解满足条件,那么就意味着 ans 还可以更小,如果不满足,说明当前的 ans 值过大。

warning

在这里插入图片描述

code

#include
using namespace std;
const int maxn=5010,maxm=8e5+10;
template<typename T>inline void read(T &x)
{
	x=0;
	T f=1, ch=getchar();
	while (!isdigit(ch) && ch^'-') ch=getchar();
	if (ch=='-') f=-1, ch=getchar();
	while (isdigit(ch)) x=(x<<1)+(x<<3)+(ch^48), ch=getchar();
	x*=f;
}
struct point
{
	int x,y;
}p[maxn],s1,s2;
inline int dist(point a,point b)
{
	return abs(a.x-b.x)+abs(a.y-b.y);
}
int ver[maxm],Next[maxm],head[maxn],len;
inline void add(int x,int y)
{
	ver[++len]=y,Next[len]=head[x],head[x]=len;
}
int dfn[maxn],low[maxn],id;
int Stack[maxn],top;
int belong[maxn],tot;
bool instack[maxn];
inline void tarjan(int x)
{
	dfn[x]=low[x]=++id;
	Stack[++top]=x;
	instack[x]=1;
	for (int i=head[x];i;i=Next[i])
	{
		int y=ver[i];
		if (!dfn[y])
		{
			tarjan(y);
			low[x]=min(low[x],low[y]);
		}
		else if (instack[y])
			low[x]=min(low[x],dfn[y]);
	}
	if (low[x]==dfn[x])
	{
		int k;
		++tot;
		do
		{
			k=Stack[top--];
			belong[k]=tot;
			instack[k]=0;
		} while (k!=x);
	}
}
inline void Clear()
{
	memset(dfn,0,sizeof(dfn));
	memset(low,0,sizeof(low));
	memset(belong,0,sizeof(belong));
	memset(instack,0,sizeof(instack));
	id=tot=top=0;
}
int hate[maxn][2],like[maxn][2];
int main()
{
	int n,A,B;
	while (~scanf("%d %d %d",&n,&A,&B))
	{
		read(s1.x),read(s1.y),read(s2.x),read(s2.y);
		int length=dist(s1,s2);
		int maxum=INT_MIN,minum=INT_MAX;
		for (int i=1;i<=n;++i)
		{
			read(p[i].x),read(p[i].y);
			minum=min(minum,min(dist(p[i],s1),dist(p[i],s2)));
			maxum=max(maxum,max(dist(p[i],s1),dist(p[i],s2)));
		}
		for (int i=1;i<=A;++i)
			read(hate[i][0]),read(hate[i][1]);
		for (int i=1;i<=B;++i)
			read(like[i][0]),read(like[i][1]);
		int l=minum<<1,r=(maxum<<1)+length,ans=INT_MAX;
		while (l<=r)
		{
			memset(head,0,sizeof(head));
			len=0;
			for (int i=1;i<=A;++i)
			{
				add(hate[i][0],hate[i][1]+n),add(hate[i][1],hate[i][0]+n);
				add(hate[i][0]+n,hate[i][1]),add(hate[i][1]+n,hate[i][0]);
			}
			for (int i=1;i<=B;++i)
			{
				add(like[i][0],like[i][1]),add(like[i][0]+n,like[i][1]+n);
				add(like[i][1],like[i][0]),add(like[i][1]+n,like[i][0]+n);
			}
			int mid=(l+r)>>1;
			for (int i=1;i<=n;++i)
				for (int j=i+1;j<=n;++j)
					if (i!=j)
					{
						if (dist(p[i],s1)+dist(s1,p[j])>mid) add(i,j+n),add(j,i+n);
						if (dist(p[i],s2)+dist(s2,p[j])>mid) add(i+n,j),add(j+n,i);
						if (dist(p[i],s1)+length+dist(s2,p[j])>mid) add(i,j),add(j+n,i+n);
						if (dist(p[i],s2)+length+dist(s1,p[j])>mid) add(j,i),add(i+n,j+n);
					}
			Clear();
			for (int i=1;i<=(n<<1);++i)
				if (!dfn[i]) tarjan(i);
			bool flag=1;
			for (int i=1;i<=n;++i)
				if (belong[i]==belong[i+n])
				{
					flag=0;
					break;
				}
			if (flag) ans=min(ans,mid),r=mid-1;
			else l=mid+1;
		}
		printf("%d\n",ans<INT_MAX?ans:-1);
	}
	return 0;
}

H.POJ 3683 Priest John’s Busiest Day

title

POJ 3683
CH POJ3683
Description

John is the only priest in his town. September 1st is the John’s busiest day in a year because there is an old legend in the town that the couple who get married on that day will be forever blessed by the God of Love. This year N couples plan to get married on the blessed day. The i-th couple plan to hold their wedding from time Si to time Ti. According to the traditions in the town, there must be a special ceremony on which the couple stand before the priest and accept blessings. The i-th couple need Di minutes to finish this ceremony. Moreover, this ceremony must be either at the beginning or the ending of the wedding (i.e. it must be either from Si to Si + Di, or from Ti - Di to Ti). Could you tell John how to arrange his schedule so that he can present at every special ceremonies of the weddings.
Note that John can not be present at two weddings simultaneously.

Input

The first line contains a integer N ( 1 ≤ N ≤ 1000).
The next N lines contain the Si, Ti and Di. Si and Ti are in the format of hh:mm.

Output

The first line of output contains “YES” or “NO” indicating whether John can be present at every special ceremony. If it is “YES”, output another N lines describing the staring time and finishing time of all the ceremonies.

Sample Input

2
08:00 09:00 30
08:15 09:00 20

Sample Output

YES
08:00 08:30
08:40 09:00

Source

POJ Founder Monthly Contest – 2008.08.31, Dagger and Facer

analysis

x i 为 真 < = > 在 开 始 时 举 行 仪 式 , x_{i}为真 <=> 在开始时举行仪式, xi<=>
x j 为 假 < = > 在 结 束 时 举 行 仪 式 。 x_{j}为假 <=> 在结束时举行仪式。 xj<=>
设 x ′ 为 非 x 。 ( 若 x 为 真 , 则 x ′ 为 假 ) 设x' 为 非x。(若 x 为真,则 x' 为假) xxxx
x i − > x j 表 示 x i 为 真 则 x j 为 真 。 ( x i x j 连 边 ) x_{i} -> xj 表示 xi 为真则 xj 为真。(xi xj 连边) xi>xjxixj(xixj)

对 于 结 婚 仪 式 i 和 j , 如 果 S i   S i + D i 和 S j   S j + D j 冲 突 , 就 有 x i ′ o r x j ′ , 这 种 情 况 即 x i − > x j ′ , x j − > x i ′ 。 ( x i 和 x j 不 能 同 时 选 , 即 选 择 一 个 , 那 么 选 了 x i 后 就 会 选 择 到 x j ′ , 表 示 不 选 x j 。 ) 对于结婚仪式 i 和 j ,如果 Si ~ Si+Di 和 Sj ~ Sj+Dj 冲突,就有 x_{i}' or xj' ,这种情况即 x_{i} -> xj' ,xj -> x_{i}' 。(x_{i} 和 xj 不能同时选,即选择一个,那么选了 x_{i} 后 就会选择到 xj' ,表示不选 xj。) ijSi Si+DiSj Sj+Djxiorxjxi>xjxj>xixixjxixjxj
如 果 S i ∼ S i + D i 和 T j − D j ∼ D j 冲 突 , 有 x i ′ o r x j , 即 x i − > x j , x j ′ − > x i ′ 。 如果 Si \sim Si+Di 和 Tj-Dj \sim Dj 冲突,有 xi' or xj ,即 x_{i} -> xj,xj' -> x_{i}' 。 SiSi+DiTjDjDjxiorxjxi>xjxj>xi
如 果 T i − D i ∼ T i 和 S j ∼ S j + D j 冲 突 , 有 x i o r x j ′ , 即 x i ′ − > x j ′ , x j − > x i 。 如果 Ti-Di \sim Ti 和 Sj \sim Sj+Dj 冲突,有 xi or xj' ,即 x_{i}' -> xj',xj -> x_{i} 。 TiDiTiSjSj+Djxiorxjxi>xjxj>xi
如 果 T i − D i ∼ T i 和 T j − D j ∼ D j 冲 突 , 有 x i o r x j , 即 x i ′ − > x j , x j ′ − > x i 。 如果 Ti-Di \sim Ti 和 Tj-Dj \sim Dj 冲突 ,有 xi or xj ,即 x_{i}' -> xj ,xj' -> x_{i} 。 TiDiTiTjDjDjxiorxjxi>xjxj>xi

code

#include
using namespace std;
const int maxn=2e3+10,maxm=3e6+10;
template<typename T>inline void read(T &x)
{
	x=0;
	T f=1,ch=getchar();
	while (!isdigit(ch) && ch^'-') ch=getchar();
	if (ch=='-') f=-1, ch=getchar();
	while (isdigit(ch)) x=(x<<1)+(x<<3)+(ch^48), ch=getchar();
	x*=f;
}
int ver[maxm],Next[maxm],head[maxn],len;
inline void add(int x,int y)
{
	ver[++len]=y,Next[len]=head[x],head[x]=len;
}
inline bool Wrong(int a,int b,int c,int d)
{
	if (a>=c&&a<d || b>c&&b<=d || a<=c&&b>=d)//
		return true;
	else
		return false;
}
int dfn[maxn],low[maxn],id;
int Stack[maxn],top;
bool instack[maxn];
int belong[maxn],tot;
inline void tarjan(int x)
{
	dfn[x]=low[x]=++id;
	Stack[++top]=x;
	instack[x]=1;
	for (int i=head[x];i;i=Next[i])
	{
		int y=ver[i];
		if (!dfn[y])
		{
			tarjan(y);
			low[x]=min(low[x],low[y]);
		}
		else if (instack[y])
			low[x]=min(low[x],dfn[y]);
	}
	if (low[x]==dfn[x])
	{
		int k;
		++tot;
		do
		{
			k=Stack[top--];
			belong[k]=tot;
			instack[k]=0;
		} while (k!=x);
	}
}
int opp[maxn];
bool val[maxn];
int S[maxn],T[maxn],D[maxn];
int main()
{
	int n;read(n);
	for (int i=1;i<=n;++i)
    {
        int a,b,c,d;
        scanf("%d:%d %d:%d %d",&a,&b,&c,&d,&D[i]);//这里都把时间转化为分钟来计算
        S[i]=a*60+b;//计算开头的时间
        T[i]=c*60+d;//计算结尾的时间
    }
    for (int i=1;i<n;++i)
		for (int j=i+1;j<=n;++j)
		{
			if (Wrong(S[i],S[i]+D[i],S[j],S[j]+D[j])) add(i,j+n),add(j,i+n);
			if (Wrong(S[i],S[i]+D[i],T[j]-D[j],T[j])) add(i,j),add(j+n,i+n);
			if (Wrong(T[i]-D[i],T[i],S[j],S[j]+D[j])) add(i+n,j+n),add(j,i);
			if (Wrong(T[i]-D[i],T[i],T[j]-D[j],T[j])) add(i+n,j),add(j+n,i);
		}
	for (int i=1;i<=(n<<1);++i)
		if (!dfn[i]) tarjan(i);
	for (int i=1;i<=n;++i)
	{
		if (belong[i]==belong[i+n])
		{
			puts("NO");
			exit(0);
		}
		opp[i]=i+n,opp[i+n]=i;
	}
	puts("YES");
	for (int i=1;i<=(n<<1);++i)
		val[i]=belong[i]>belong[opp[i]];//
	for (int i=1;i<=n;++i)
		if (!val[i])
			printf("%02d:%02d %02d:%02d\n",S[i]/60,S[i]%60,(S[i]+D[i])/60,(S[i]+D[i])%60);
		else
			printf("%02d:%02d %02d:%02d\n",(T[i]-D[i])/60,(T[i]-D[i])%60,T[i]/60,T[i]%60);
	return 0;
}

  1. 有些analysis来自laoda扯一扯 ↩︎

你可能感兴趣的:(模板,强连通分量,======图论=======,HDU,POJ,2-SAT)