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