HDU 1814 – Peaceful Commission [2-SAT]

Link

传送门

Problem

The Public Peace Commission should be legislated in Parliament of The Democratic Republic of Byteland according to The Very Important Law. Unfortunately one of the obstacles is the fact that some deputies do not get on with some others.

The Commission has to fulfill the following conditions:
1.Each party has exactly one representative in the Commission,
2.If two deputies do not like each other, they cannot both belong to the Commission.

Each party has exactly two deputies in the Parliament. All of them are numbered from 1 to 2n. Deputies with numbers 2i-1 and 2i belong to the i-th party .

Task
Write a program, which:
1.reads from the text file SPO.IN the number of parties and the pairs of deputies that are not on friendly terms,
2.decides whether it is possible to establish the Commission, and if so, proposes the list of members,
3.writes the result in the text file SPO.OUT.

Mean

根据宪法,Byteland民主共和国的公众和平委员会应该在国会中通过立法程序来创立。 不幸的是,由于某些党派代表之间的不和睦而使得这件事存在障碍。

此委员会必须满足下列条件:

  • 每个党派都在委员会中恰有1个代表,
  • 如果2个代表彼此厌恶,则他们不能都属于委员会。

每个党在议会中有2个代表。代表从1编号到2n。 编号为2i-1和2i的代表属于第I个党派。

任务

写一程序:

  • 从文本文件读入党派的数量和关系不友好的代表对,
  • 计算决定建立和平委员会是否可能,若行,则列出委员会的成员表,
  • 结果写入文本文件。

Analysis

典型的2-SAT,跟2-SAT模型一样,直接套即可。注意加边时怎么加。

Code

#include <bits/stdc++.h>
using namespace std;

const int maxn = 8888;

struct TwoSAT {
    int n, c, S[maxn*2];
    vector<int> G[maxn*2];
    bool mark[maxn*2];

    void init(int n) {
        this->n = n;
        for(int i = 0; i < n * 2; ++i)
            G[i].clear();
        memset(mark, 0, sizeof(mark));
    }
    bool dfs(int u) {
        if(mark[u ^ 1]) return false;
        if(mark[u]) return true;
        mark[u] = true;
        S[c++] = u;
        for(int v : G[u])
            if(!dfs(v)) return false;
        return true;
    }
    void addClause(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;
    }
}sat;


int main() {
    int N, M;
    while(~scanf("%d%d", &N, &M)) {
        sat.init(N);
        while(M--) {
            int a, b; scanf("%d%d", &a, &b); --a, --b;
            int xval = a % 2, yval = b % 2;
            sat.addClause(a/2, 1-xval, b/2, 1-yval);
        }
        if(!sat.solve()) {
            puts("NIE");
            continue;
        }
        for(int i = 0; i < 2 * N; i += 2) {
            if(sat.mark[i]) printf("%d\n", i + 1);
            else printf("%d\n", i + 2);
        }
    }
    return 0;
}

PS:我会变得更好,我会让你后悔的,走着瞧!

欢迎留言