POJ 1182食物链

代码1.

#include <stdio.h>

#define N    50000

struct item
{
    int p;
    int rank;
};

struct item items[3*N + 3];
int count;
int ret;
void init(void)
{
    int i;
    for(i = 1; i <= 3*count; i++)
    {
        items[i].p = i;
        items[i].rank = 0;
    }
}

int find_set(int x)
{
    if(items[x].p != x)
    {
        items[x].p = find_set(items[x].p);
    }

    return items[x].p;
}

void combine(int x, int y)
{
    if(items[x].rank > items[y].rank)
    {
        items[y].p = x;
    }
    else
    {
        items[x].p = y;
        if(items[x].rank == items[y].rank)
        {
            items[y].rank++;
        }
    }
}

void solve(int x, int y, int action)
{
    if( x > count || y > count)
    {
        ret++;
        return;
    }

    if( action == 2 && x == y)
    {
        ret++;
        return;
    }


    if(action == 1)
    {
        if(find_set(x) == find_set(y+count)  || find_set(x) == find_set(y + 2 * count))
        {
            printf("%d %d %d\n", action, x, y);
            ret++;
            return;
        }    

        combine(find_set(x), find_set(y));
        combine(find_set(x+count), find_set(y+count));
        combine(find_set(x+ 2 * count), find_set(y+2 * count));
    }
    else if(action == 2)
    {
        if(find_set(x) == find_set(y) || find_set(x) == find_set(y+2*count))
        {
            printf("%d %d %d\n", action, x, y);
            ret++;
            return;
        }

        combine(find_set(x),  find_set(y + count));
        combine(find_set(x + count), find_set(y+2*count));
        combine(find_set(x + 2 *count), find_set(y));
    }
}


int main(void)
{
    freopen("foodchain.txt", "r", stdin);
    int K;
    scanf("%d %d", &count, &K);

    init();
    int i;
    for(i = 0; i < K; i++)
    {
        int action, x, y;
        scanf("%d %d %d", &action, &x, &y);
        solve(x, y, action);
    }

    printf("%d\n", ret);
    return 0;
}

 

代码2:利用类似连通图的概念。

修改函数combine:

void combine(int x, int y)
{

    if( x != y)
    {
        items[x].p = y;
    }
}

 

参考:

https://blog.csdn.net/backforward/article/details/51892505

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值