poj 3648(2-SAT)

poj 3648
1、注意2-SAT的定义(例如此题定义坐不坐新郎这边比坐不坐新娘这边更好解题)
2、取了和题目不同定义时,记得反一下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<vector>
using namespace std;
#define ms(i,j) memset(i, j, sizeof i);
const int MAXN = 200 + 5;
struct TwoSAT
{
vector<int> G[MAXN*2];
int S[MAXN*2];
bool mark[MAXN*2];
int n, c;
void init(int n)
{
this->n = n;
for (int i=0;i<=2*n;i++)
{
G[i].clear();
mark[i] = false;
}
}
void ins(int u, int v)
{
G[u].push_back(v);
}
int dfs(int x)
{
if (mark[x^1]) return false;
if (mark[x]) return true;
mark[x] = true;
S[++c] = x;
for (int i=0;i<G[x].size();i++)
{
if (!dfs(G[x][i])) return false;
}
return true;
}
int solve()
{
for (int i=0;i<2*n;i+=2)
if (!mark[i]&&!mark[i+1])
{
c = 0;
if (!dfs(i))
{
while (c>0) mark[S[c--]] = false;
if (!dfs(i+1)) return false;
}
}
return true;
}
}ts;
int n, m;
void init()//2*x is h, 2*x+1 is w
{
ts.init(n);
ts.ins(1, 0);//the groom must be in the line
for (int i=1;i<=m;i++)
{
int a,b;
char as, bs;
scanf("%d%c%d%c", &a, &as, &b, &bs);
if (as=='h'&&bs=='w')
{
ts.ins(2*a, 2*b);//ha->hb
ts.ins(2*b+1, 2*a+1);//wb->wa
}
if (as=='w'&&bs=='h')
{
ts.ins(2*b, 2*a);//hb->ha
ts.ins(2*a+1, 2*b+1);//wa->wb
}
if (as=='h'&&bs=='h')
{
ts.ins(2*a, 2*b+1);//ha->wb
ts.ins(2*b, 2*a+1);//hb->wa
}
if (as=='w'&&bs=='w')
{
ts.ins(2*a+1, 2*b);//wa->hb
ts.ins(2*b+1, 2*a);//wb->ha
}
}
}
void solve()
{
bool flag = false;
if (ts.solve())
{
for (int i=1;i<ts.n;i++)
{
if (ts.mark[i*2])
{
if (flag) printf(" ");
printf("%dw", i), flag = true;
}
if (ts.mark[i*2+1])
{
if (flag) printf(" ");
printf("%dh", i), flag = true;
}
}
printf("\n");
} else printf("bad luck\n");
}
int main()
{
while (scanf("%d%d", &n, &m)==2&&n&&m)
{
init();
solve();
}
return 0;
}

------ 本文结束 ------