Wedding
题目背景:
分析:2-SAT裸题,直接将与新郎同侧设置为true,然后跑tarjan即可。
如果不太清楚2-SAT的同学,请去看我的另一篇文章,详解了2-SAT
Source:
#include
#include
#include
#include
#include
#include
#include
#include
using namespace std; inline void R(int &v) { char c = 0; bool p = true; v = 0; while(!isdigit(c)) { if(c == '-') p = false; c = getchar(); } while(isdigit(c)) { v = (v << 3) + (v << 1) + (c ^ '0'); c = getchar(); } if(!p) v = -v; } const int MAXN = 30 + 10; const int MAXM = 1000; struct node { int next, to; } edge[MAXM << 1]; stack
s; int first[MAXN << 1], low[MAXN << 1], num[MAXN << 1], scc[MAXN << 1]; int n, m, x, y, cnt, ind, tot; char c1, c2; bool exist[MAXN << 1]; inline void create(int x, int y) { tot++, edge[tot].next = first[x], first[x] = tot, edge[tot].to = y; } inline int rev(int x) { return (x <= n) ? x + n : x - n; } void read() { for(int i = 1; i <= m; ++i) { cin >> x >> c1 >> y >> c2; x++, y++; if(c1 == 'h') x += n; if(c2 == 'h') y += n; create(x, rev(y)); create(y, rev(x)); } create(1, n + 1);/*强制新郎与新郎同侧*/ } void dfs(int cur) { num[cur] = low[cur] = ++ind; s.push(cur); exist[cur] = true; for(int p = first[cur]; p; p = edge[p].next) { if(!num[edge[p].to]) dfs(edge[p].to), low[cur] = min(low[edge[p].to], low[cur]); else if(exist[edge[p].to]) low[cur] = min(low[cur], num[edge[p].to]); } if(num[cur] == low[cur]) { int o = s.top(); cnt++; while(o != cur) scc[o] = cnt, s.pop(), exist[o] = false, o = s.top(); scc[o] = cnt, s.pop(), exist[o] = false; } } void work() { for(int i = 1; i <= (n << 1); ++i) if(!num[i]) dfs(i); for(int i = 1; i <= n; ++i) if(scc[i] == scc[i + n]) { cout << "bad luck" << '\n'; return ; } for(int i = 2; i <= n; ++i) /*scc[i] > scc[i + n] <=> top[i] < top[i + n]*/ cout << i - 1 << (scc[i] > scc[i + n] ? 'w' : 'h') << " "; cout << '\n'; } void clear() { memset(exist, false, sizeof(exist)); memset(num, 0 ,sizeof(num)); memset(first, 0, sizeof(first)); while(!s.empty()) s.pop(); tot = cnt = ind = 0; } int main() { while(cin >> n >> m) { if(n == 0 && m == 0) break; read(); work(); clear(); } return 0; }
本文介绍如何使用2-SAT算法解决POJ3648婚礼问题,通过设置新郎一侧为真,运用Tarjan算法进行求解。文章提供了完整的源代码实现,并解释了关键步骤。
814

被折叠的 条评论
为什么被折叠?



