hdu 4115 2-sat

本文介绍了一种使用C++实现的Tarjan算法来解决并查集问题,详细阐述了算法原理、代码实现及应用实例。

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

#include <iostream>
#include <cstdio>
#include <cstring>
#include <stack>
#include <vector>

using namespace std;

const int M = 20005;
int dfn[M];
int low[M];
int ins[M];
int sccf[M];
struct node {
    int x;
    int y;
}p[M*10];
vector<int>que[M];
stack<int>s;
int n, m;
int index, scc;

void init() {

    index = 1;
    scc = 0;
    memset(dfn, 0, sizeof(dfn));
    memset(low, 0, sizeof(low));
    memset(ins, 0, sizeof(ins));
    memset(sccf, 0, sizeof(sccf));
    for(int i = 0; i <= n*2; i++)
        que[i].clear();
    while(!s.empty())
        s.pop();
}

void Tarjan(int u) {

    int v;
    dfn[u] = low[u] = index++;
    ins[u] = 1;
    s.push(u);
    for(int i = 0; i < (int)que[u].size(); i++) {

        v = que[u][i];
        if(!dfn[v]) {

         Tarjan(v);
         low[u] = min(low[u], low[v]);
        }else if(ins[v]) {

            low[u] = min(low[u], low[v]);
        }
    }
    if(dfn[u] == low[u]) {

        scc++;
        do{

            v = s.top();
            s.pop();
            ins[v] = 0;
            sccf[v] = scc;
        }while(u != v);
    }
}

bool work() {

    int a, b, k;
    init();
    for(int i = 0; i < m; i++) {

        scanf("%d%d%d", &a, &b, &k);
        if(k == 0) {

            if(p[a].x != p[b].x) que[a].push_back(b+n), que[b].push_back(a+n);
            if(p[a].x != p[b].y) que[a].push_back(b), que[b+n].push_back(a+n);
            if(p[a].y != p[b].x) que[a+n].push_back(b+n), que[b].push_back(a);
            if(p[a].y != p[b].y) que[a+n].push_back(b), que[b+n].push_back(a);
        }else {

            if(p[a].x == p[b].x) que[a].push_back(b+n), que[b].push_back(a+n);
            if(p[a].x == p[b].y) que[a].push_back(b), que[b+n].push_back(a+n);
            if(p[a].y == p[b].x) que[a+n].push_back(b+n), que[b].push_back(a);
            if(p[a].y == p[b].y) que[a+n].push_back(b), que[b+n].push_back(a);
        }
    }
    for(int i = 1; i <= n*2; i++)
        if(!dfn[i])
        Tarjan(i);
    for(int i = 1; i <= n; i++)
        if(sccf[i] == sccf[i + n])
        return false;
    return true;
}

int main()
{
    int a, t;
    int q = 1;
    scanf("%d", &t);
   while(t--) {
        scanf("%d%d", &n, &m);
        for(int i = 1; i <= n; i++) {

            scanf("%d", &a);
            if(a == 3) {

                p[i].x = 3;
                p[i].y = 1;
                continue;
            }
            p[i].x = a;
            p[i].y = a+1;
        }
        if(work())
            printf("Case #%d: yes\n", q++);
        else
            printf("Case #%d: no\n", q++);
   }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值