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<cstdio>
#include<algorithm>
#include<cstring>
#include<cstdlib>
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;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值