Hdu 1829 A Bug's Life && Poj 1182 食物链 (并查集偏移量的应用)

本文介绍了并查集偏移量的应用,包括ABug'sLife和食物链两个实例。通过对偏移量的维护,可以有效地解决同性交配检测和食物链关系确认等问题。

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

复习了一下并查集偏移量的应用,A Bug's Life比食物链简单些,偏移量只有0和1。
偏移量:维护所有集合的根的偏移量都为0。在集合合并时,若两集合对应偏移量不同,改变被合并集合根的偏移量,而集合内部的偏移量暂不改变,在以后查询某点偏移量时,先调用find函数,在find函数中递归更新偏移量值。

Hdu 1829 A Bug's Life

输入可交配的虫子,判断有没有同性交配

#include<iostream>
#include<algorithm>
#include<cmath>
#include<cstdio>
#include<cstring>
using namespace std;
int p[2005], g[2005], n, flag, root[2005];
void init(){
    memset(g, 0, sizeof(g));
    for(int i=0; i<=n; i++){
        p[i]=i;
        root[i]=0;
    }
    flag=0;
}
int find(int x){
    if(p[x]==x)
        return x;
    int t=find(p[x]);
    g[x]=(g[x]+g[p[x]])%2;
    p[x]=t;
    return p[x];
}
void union_set(int x, int y){
    int x1=find(x), y1=find(y);
    if(root[x1]<root[y1]){
        p[x1]=y1;
        if(g[x]==g[y])g[x1]=1;
    }
    else {
        p[y1]=x1;
        if(g[x]==g[y])g[y1]=1;
    }
    if(root[x1]==root[y1])root[x1]++;
}
int main(){
    //freopen("1.txt", "r", stdin);
    int T, i, x, y, m, cas=1, x1, y1;
    scanf("%d", &T);
    while(T--){
        scanf("%d%d", &n, &m);
        init();
        while(m--){
            scanf("%d%d", &x, &y);
            if(flag)continue;
            x1=find(x);y1=find(y);
            if(x1==y1){
                if(g[x]==g[y])
                flag=1;
            }
            else {
                union_set(x, y);
            }
        }
        if(flag)
        printf("Scenario #%d:\nSuspicious bugs found!\n\n", cas++);
        else printf("Scenario #%d:\nNo suspicious bugs found!\n\n", cas++);
    }
    return 0;
}


Poj 1182 食物链

#include<iostream>
#include<algorithm>
#include<cmath>
#include<cstdio>
#include<cstring>
#include<stack>
#include<queue>
using namespace std;
int p[50005], g[50005], n, k, ans;
void init(){
    memset(g, 0, sizeof(g));
    for(int i=0; i<=n; i++){
        p[i]=i;
    }
    ans=0;
}
int find(int x){
    if(p[x]==x)
        return x;
    int t=find(p[x]);
    g[x]=(g[x]+g[p[x]])%3;
    p[x]=t;
    return p[x];
}
void check(int d,int x,int y){
    int t1=find(x),t2=find(y);
    if(t1==t2){
        if(d==1){
            if(g[x]!=g[y])
            ans++;
        }
    else if((g[y]-g[x]+3)%3!=d)
        ans++;
    return;
    }
    p[t1]=t2;
    if(d==1)
    g[t1]=(g[y]-g[x]+6)%3;
    else g[t1]=(g[y]-g[x]+1+6)%3;
}

int main(){
    //freopen("1.txt", "r", stdin);
    int i, x, y, d;
    scanf("%d%d", &n, &k);
	init();
    while(k--){
        scanf("%d%d%d", &d, &x, &y);
        if(x>n||y>n||(d==2&&x==y)){
        ans++;continue;
        }
        check(d, x, y);
    }
    printf("%d\n", ans);
    return 0;
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值