UVA11294-Wedding(2-SAT)

來源:互聯網
上載者:User

標籤:

option=com_onlinejudge&Itemid=8&page=show_problem&problem=2269">題目連結


題意:有n對夫妻參加一個婚宴。

全部人都坐在一個長長的餐桌的左邊或者右邊。全部夫妻都僅僅能面對面坐,包含新娘和新郎。新娘僅僅能看到坐在她不同側的人。有m對人超過架,新娘不希望看到他們坐在同一側。

問有沒有分配方案滿足新娘的要求。

思路:2-SAT問題。如果每對夫婦為一個變數xi。如果xi為true時,妻子與新娘坐同一側;xi為false時,丈夫與新娘坐同一側。當xi和xj同為丈夫時,則需滿足~xi V ~xj,表示兩個丈夫最多僅僅有一個坐在與新娘不同側;當xi和xj同為妻子時。則需滿足xi V xj。表示兩個妻子最多僅僅有一個坐在與新娘不同側。當xi和xj為異性時,則需滿足~xi V xj或者xi V ~xj當中一個。表示兩個最多就一個坐在與新娘不同側。

綜上所述。就是要滿足丈夫~xi,妻子xi。最後要注意初始化mark[1] = 1。

代碼:

#include <iostream>#include <cstdio>#include <cstring>#include <vector>#include <algorithm>using namespace std;const int MAXN = 1005;struct TwoSAT{    int n;    vector<int> g[MAXN * 2];    bool mark[MAXN * 2];    int s[MAXN * 2], c;    bool 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;    }    void init(int n) {        this->n = n;        for (int i = 0; i < n * 2; i++)             g[i].clear();        memset(mark, 0, sizeof(mark));        mark[1] = 1;    }    void add_clause(int x, int xval, int y, int yval) {        x = x * 2 + xval;        y = y * 2 + yval;        g[x^1].push_back(y);        g[y^1].push_back(x);    }    bool solve() {        for (int i = 0; i < n * 2; 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;    }};TwoSAT solver;int n, m;int main() {    while (scanf("%d%d", &n, &m)) {        if (n == 0 && m == 0)            break;        solver.init(n);                 char a, b;        int xval, yval, u, v;        while (m--) {            scanf("%d%c%d%c", &u, &a, &v, &b);             xval = (a == 'h') ?

0 : 1; yval = (b == 'h') ? 0 : 1; solver.add_clause(u, xval, v, yval); } if (!solver.solve()) printf("bad luck\n"); else { for (int i = 1; i < n; i++) { printf("%d%c", i, solver.mark[2*i] ? 'h' : 'w'); if (i == n - 1) printf("\n"); else printf(" "); } } } return 0;}



著作權聲明:本文部落格原創文章,部落格,未經同意,不得轉載。

UVA11294-Wedding(2-SAT)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.