hdu1814 Peaceful Commission 2-SAT建图入门

题面

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.

题解

基础2-SAT建图,二者取其一,对每个点建两个分点分别代表取这个点/不取这个点,dfs染色取得字典序最小解

代码

#include
#include
#include
#include
using namespace std;

const int maxn = 20020;
const int maxm = 100010;

struct Edge {
    int v, next;
}e[maxm];

int fi[maxn], ecnt;

void init() {
    ecnt = 0;
    memset(fi, -1, sizeof(fi));
}

void add_edge(int u, int v) {
    e[ecnt] = (Edge) {v, fi[u]};
    fi[u] = ecnt++;
}

bool vis[maxn];
int st[maxn], top;

bool dfs(int u) {
    if(vis[u^1])    return false;
    if(vis[u])      return true;
    vis[u] = true;
    st[top++] = u;
    for(int i = fi[u]; i != -1; i = e[i].next)
        if(!dfs(e[i].v))    return false;
    return true;
}

bool T_SAT(int n) {
    memset(vis, 0, sizeof(vis));
    for(int i = 0; i < n; i += 2) {
        if(vis[i] || vis[i^1])  continue;
        top = 0;
        if(!dfs(i)) {
            while(top)  vis[st[--top]] = false;
            if(!dfs(i^1))   return false;
        }  
    }
    return true;
}

int main() {
    int n, m;
    int u, v;
    while(scanf("%d%d", &n, &m) == 2) {
        init();
        for(int i = 1; i <= m; i++) {
            scanf("%d%d", &u, &v);
            u--;    v--;
            add_edge(u, v^1);
            add_edge(v, u^1);
        }
        if(T_SAT(n*2)) {
            for(int i = 0; i < n*2; i++)
                if(vis[i]) {
                    printf("%d\n", i+1);
                }
        } else  printf("NIE\n");
    }
    return 0;
}

你可能感兴趣的:(图论)