hdu 4115 Eliminate the Conflict(2SAT)

本文提供了一种解决HDU4115EliminatetheConflict问题的方法,利用TwoSAT算法来处理冲突情况。代码实现包括了结构化问题定义、约束条件添加及求解过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接:hdu 4115 Eliminate the Conflict

代码

#include <cstdio>
#include <cstring>
#include <vector>
#include <algorithm>

using namespace std;
const int maxn = 10005;

struct TwoSAT {
    int n, s[maxn<<1], c;
    bool mark[maxn<<1];
    vector<int> g[maxn<<1];

    void init (int n) {
        this->n = n;
        memset(mark, false, sizeof(mark));
        for (int i = 0; i < n*2; i++) g[i].clear();
    }

    void addClause(int x, int xval, int y, int yval) { // (sx || sy)
        x = x * 2 + xval;
        y = y * 2 + yval;
        g[x^1].push_back(y);
        g[y^1].push_back(x);
    }

    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;
    }

    bool solve () {
        for (int i = 0; i < n*2; i += 2) {
            if (!mark[i] && !mark[i+1]) {
                c = 0;
                if (!dfs(i)) {
                    while (c) mark[s[--c]] = false;
                    if (!dfs(i+1)) return false;
                }
            }
        }
        return true;
    }
}solver;

int N, M, A[maxn];

int main () {
    int cas;
    scanf("%d", &cas);
    for (int kcas = 1; kcas <= cas; kcas++) {
        scanf("%d%d", &N, &M);
        for (int i = 1; i <= N; i++) { scanf("%d", &A[i]); A[i]--; }
        solver.init(N);

        int a, b, k;
        while (M--) {
            scanf("%d%d%d", &a, &b, &k);
            for (int i = 0; i < 2; i++) {
                for (int j = 0; j < 2; j++) {
                    int u = (A[a] + i) % 3, v = (A[b] + j) % 3;

                    if (u != v && k == 0) solver.addClause(a-1, i^1, b-1, j^1);
                    if (u == v && k) solver.addClause(a-1, i^1, b-1, j^1);
                }
            }
        }
        printf("Case #%d: %s\n", kcas, solver.solve() ? "yes" : "no");
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值