hdu 6109 数据分割

条件分组算法解析
本文介绍了一种用于处理条件分组的问题解决算法。该算法利用并查集维护相等关系的传递性,并通过集合记录不等关系。面对一组可能相互冲突的条件(如 xi = xj 或 xi ≠ xj),算法采用贪心策略来划分这些条件,确保每组内的条件在去掉最后一个时能够成立。

Problem

acm.hdu.edu.cn/showproblem.php?pid=6109

Meaning

给出若干个条件: xi=xj xixj ,它们分属若干组,但组与组之间的分隔符没了,要重新分隔这几组条件。
每一组条件的特点是:不可能成立,但去掉最后一个条件后,就可以成立。

Analysis

每次都贪心地常试将尽量多的条件放进当前这组,遇到第一个与已有条件冲突时,就是分隔的时候。
相等有传递性,用并查集维护;不等没有传递性,用 set 维护。
注意到:若 x1=x2x1x3x2x4 ,那么有: x1x4x2x3 。所以在用并查集将 x1x2 合并时(比如将 x1 合并到 x2 ),就要将 x1 的不相等的信息合并到 x2

Code

#include <cstdio>
#include <set>
using namespace std;
const int N = 100000;

set<int> st[N+1];
int fa[N+1], rk[N+1];

void clear(int n)
{
    for(int i = 1; i <= n; ++i)
    {
        rk[i] = 1;
        fa[i] = i;
        st[i].clear();
    }
}

void pushup(int x, int y)
{
    for(set<int>::iterator it = st[x].begin(); it != st[x].end(); ++it)
        st[y].insert(*it);
}

int root(int x)
{
    if(x == fa[x])
        return x;
    pushup(x, fa[x]); // 儿子信息合并到父亲
    return fa[x] = root(fa[x]);
}

void unite(int x, int y)
{
    int rx = root(x), ry = root(y);
    if(rk[rx] < rk[ry])
        fa[rx] = ry;
    else
    {
        fa[ry] = rx;
        if(rk[rx] == rk[ry])
            ++rk[rx];
    }
}

int ans[N];

int main()
{
    int L;
    scanf("%d", &L);
    clear(L);
    int top = 0;
    for(int i = 0, x, y, e, cnt = 0; i < L; ++i)
    {
        scanf("%d%d%d", &x, &y, &e);
        ++cnt;
        x = root(x);
        y = root(y);
        if(e)
        {
            if(x == y)
                continue;
            if(st[x].count(y) || st[y].count(x))
            {
                ans[top++] = cnt;
                cnt = 0;
                clear(L);
            }
            else
                unite(x, y);
        }
        else
        {
            if(x == y)
            {
                ans[top++] = cnt;
                cnt = 0;
                clear(L);
            }
            else
            {
                st[x].insert(y);
                st[y].insert(x);
            }
        }
    }
    printf("%d\n", top);
    for(int i = 0; i < top; ++i)
        printf("%d\n", ans[i]);
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值