您的位置:首页 > 其它

POJ 3648 Wedding 2-SAT

2016-03-26 19:26 423 查看
一对夫妻不能对着坐,一些人不能对着坐,求可行方案。

显然夫妻可以算作一个状态,于是2-SAT。。

#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;
#define sqr(i) ((i)*(i))
#define ms(i) memset(i,0,sizeof(i))
const int N = 20005, M = 600000;
int a
, b
;
struct TwoSAT {
int h
, p[M], v[M], vis
, stk
, top, cnt;

void add(int a, int x, int b, int y) {
a = 2 * a + x; b = 2 * b + y;
if (a == (b ^ 1)) return;
p[++cnt] = h[a ^ 1]; v[cnt] = b; h[a ^ 1] = cnt;
p[++cnt] = h[b ^ 1]; v[cnt] = a; h[b ^ 1] = cnt;
}

void init() {
cnt = 0; ms(vis); ms(h);
}

bool solve(int n) {
for (int i = 0;i < 2 * n; i += 2) if (!vis[i] && !vis[i ^ 1]) {
top = 0;
if (!dfs(i)) {
while (top) vis[stk[--top]] = 0;
if (!dfs(i + 1)) return 0;
}
}
return 1;
}

bool dfs(int x) {
if (vis[x ^ 1]) return 0;
if (vis[x]) return 1;
vis[x] = 1; stk[top++] = x;
for (int i = h[x]; i; i = p[i])
if (!dfs(v[i])) return 0;
return 1;
}
} g;

int main() {
#define id(i,j) ((i)*2+(j))
int n, m, i, u, v, kase = 0;
char x, y;
while (scanf("%d%d", &n, &m) != EOF && (n || m)) {
g.init();
while (m--) {
scanf("%d%c%d%c", &u, &x, &v, &y);
g.add(--u, x == 'w', --v, y == 'w');
}
if (!g.solve(n)) puts("bad luck");
else {
for (int i = 0; i < n - 1; ++i)
printf("%d%c ", i + 1, g.vis[i * 2] ? 'h' : 'w');
putchar('\n');
}
}
return 0;
}


Wedding

Time Limit: 1000MS Memory Limit: 65536K

Total Submissions: 9393 Accepted: 2846 Special Judge

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: